hexsha stringlengths 40 40 | size int64 3 1.05M | ext stringclasses 1
value | lang stringclasses 1
value | max_stars_repo_path stringlengths 5 1.02k | max_stars_repo_name stringlengths 4 126 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses list | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 5 1.02k | max_issues_repo_name stringlengths 4 114 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses list | max_issues_count float64 1 92.2k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 5 1.02k | max_forks_repo_name stringlengths 4 136 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses list | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | avg_line_length float64 2.55 99.9 | max_line_length int64 3 1k | alphanum_fraction float64 0.25 1 | index int64 0 1M | content stringlengths 3 1.05M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e1ee2731854dcdbbf1823b759fe38174686d4c8 | 303 | java | Java | src/main/java/com/ana/service/MsgService.java | braverokmc79/HanOkay | 8d1b364dc9904beedf8e552533fff1f475d643e4 | [
"MIT"
] | 7 | 2020-09-24T00:18:21.000Z | 2022-01-20T11:56:35.000Z | src/main/java/com/ana/service/MsgService.java | braverokmc79/HanOkay | 8d1b364dc9904beedf8e552533fff1f475d643e4 | [
"MIT"
] | 7 | 2020-06-24T11:35:54.000Z | 2020-08-08T03:54:18.000Z | src/main/java/com/ana/service/MsgService.java | braverokmc79/HanOkay | 8d1b364dc9904beedf8e552533fff1f475d643e4 | [
"MIT"
] | 7 | 2021-01-11T08:49:28.000Z | 2022-02-28T04:56:08.000Z | 17.823529 | 73 | 0.759076 | 13,053 | package com.ana.service;
import java.util.List;
import com.ana.domain.MsgVO;
public interface MsgService {
public List<MsgVO> readConversation( String userNum1, String userNum2);
public int marksRead(String MsgNum);
public int unreadMsg(String userNum);
public void sendMsg(MsgVO vo);
}
|
3e1ee3819a5dfa3eec857176f9f94c6d351dd467 | 1,952 | java | Java | core/src/main/java/com/softavail/commsrouter/domain/Skill.java | brendahon/comms-router | baaf7735da4c25425d785ed789dbb8d6d1bc1490 | [
"Apache-2.0"
] | 15 | 2017-12-12T07:23:20.000Z | 2021-03-24T16:21:29.000Z | core/src/main/java/com/softavail/commsrouter/domain/Skill.java | brendahon/comms-router | baaf7735da4c25425d785ed789dbb8d6d1bc1490 | [
"Apache-2.0"
] | 25 | 2017-12-18T00:53:27.000Z | 2019-10-04T18:21:15.000Z | core/src/main/java/com/softavail/commsrouter/domain/Skill.java | brendahon/comms-router | baaf7735da4c25425d785ed789dbb8d6d1bc1490 | [
"Apache-2.0"
] | 12 | 2017-12-14T14:44:00.000Z | 2022-03-29T00:28:59.000Z | 25.025641 | 75 | 0.73668 | 13,054 | /*
* Copyright 2017 - 2018 SoftAvail Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.softavail.commsrouter.domain;
import com.softavail.commsrouter.api.dto.model.RouterObjectRef;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.validation.constraints.Size;
/**
* @author ikrustev
*/
@Entity
@Table(name = "skill")
public class Skill extends RouterObject {
@Column(name = "description")
@Size(max = 255, message = "{domain.Skill.description.size}")
private String description;
@Column(name = "multivalue")
private Boolean multivalue;
@OneToOne(cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "attribute_domain_id")
private AttributeDomain domain;
public Skill() {}
public Skill(RouterObjectRef objectRef) {
super(objectRef.getRef());
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Boolean getMultivalue() {
return multivalue;
}
public void setMultivalue(Boolean multivalue) {
this.multivalue = multivalue;
}
public AttributeDomain getDomain() {
return domain;
}
public void setDomain(AttributeDomain domain) {
this.domain = domain;
}
}
|
3e1ee476a3313d689df720018d9b0269a28d5e18 | 4,327 | java | Java | Chinese Checkers/src/Test.java | Hazarrrd/TP-Project | 956ee82ee74aa9feb98494189752cab63780533f | [
"Unlicense"
] | 1 | 2019-11-11T14:26:38.000Z | 2019-11-11T14:26:38.000Z | Chinese Checkers/src/Test.java | Hazarrrd/TP-Project | 956ee82ee74aa9feb98494189752cab63780533f | [
"Unlicense"
] | null | null | null | Chinese Checkers/src/Test.java | Hazarrrd/TP-Project | 956ee82ee74aa9feb98494189752cab63780533f | [
"Unlicense"
] | null | null | null | 25.304094 | 117 | 0.516062 | 13,055 |
import board.Board;
import fields.Checker;
import fields.EmptyField;
import fields.Field;
import game.Colors;
import junit.framework.Assert;
import junit.framework.TestCase;
/**
* Created by lenovo on 01.01.2018.
*/
public class Test extends TestCase {
int side = 5;
int width = (side-2)+2*side;
int height = 4*side-3;
Board board1 = null;
public void setUp() {
board1 = new Board(5, 6, 10);
}
public void testMoveIsLegal() {
board1.isMoveLegal(1, 7, 2, 7, Colors.GREEN);
Assert.assertEquals(false, board1.isMoveLegal(1, 7, 2, 7, Colors.GREEN));
Assert.assertEquals(false, board1.isMoveLegal(1, 7, 1, 1, Colors.GREEN));
}
public void testDidPlayerWin() {
board1.didPlayerWin(Colors.GREEN);
Assert.assertSame(false, board1.didPlayerWin(Colors.GREEN));
}
public void testGiveNeighbourToArray() {
assertNotNull("nie", board1.board);
}
public void testDoMove(){
Field[][] b1 = new Field[width][height];
for(int i=0;i<side;i++) {
for (int j = 0; j < width; j++) {
b1[i][j] = new EmptyField(i,j);
}
}
boolean move = false;
board1.board[4][7] = new Checker(Colors.GREEN, 4, 7, 1);
b1[4][7]=board1.board[4][7];
if(b1[4][7].kindOfField == 2) {
board1.doMove(4,7,5,7);
move = true;
}
Assert.assertTrue("false", move);
}
public void testFillerFirst(){
Field[][] b1 = new Field[width][height];
for(int i=0;i<side;i++) {
for (int j = 0; j < width; j++) {
b1[i][j] = new EmptyField(i,j);
}
}
boolean fill = false;
for(int i=0;i<side;i++) {
for (int j = 0; j < width; j++) {
if (b1[i][j].kindOfField == 1) {
board1.fillerFirst(0);
fill = true;
}
}
}
Assert.assertTrue("false", fill);
}
public void testArrayFirst() {
assertNotNull("null", board1.arrayFirst());
}
public void testArraySecond() {assertNotNull("null", board1.arraySecond());}
public void testArrayThird() {
assertNotNull("null", board1.arrayThird());
}
public void testArrayFourth() {
assertNotNull("null", board1.arrayFourth());
}
public void testArrayFifth() {
assertNotNull("null", board1.arrayFifth());
}
public void testArraySixth() {
assertNotNull("null", board1.arraySixth());
}
public void testCheckIfInTarget() {
Field[][] b1 = new Field[width][height];
for(int i=0;i<side;i++) {
for (int j = 0; j < width; j++) {
b1[i][j] = new EmptyField(i, j);
}
}
board1.board[1][7]= new Checker(Colors.GREEN, 4, 7, 1);
Field c1 = board1.board[1][7];
//board1.checkIfInTarget(board1.board[1][7]);
Assert.assertEquals(board1.checkIfInTriangle(c1,c1.target), board1.checkIfInTarget(c1));
}
public void testCheckIfInTriangle() {
Field[][] b1 = new Field[width][height];
for(int i=0;i<side;i++) {
for (int j = 0; j < width; j++) {
b1[i][j] = new EmptyField(i, j);
}
}
Field c1 = b1[5][1];
board1.checkIfInTriangle(c1, 1);
Assert.assertEquals(board1.checkIfInTargetHelper(c1, board1.arrayFirst()), board1.checkIfInTriangle(c1, 1));
}
public void testCheckIfInTargetHelper() {
boolean is = false;
board1.board[3][7] = new Checker(Colors.GREEN, 3, 7, 1);
board1.checkIfInTarget(board1.board[3][7]);
if(board1.board[3][7].reachedTarget == true)
is = true;
Assert.assertTrue("m", is);
}
public void testMakeEmptyBoard() {
boolean empty = false;
board1.makeEmptyBoard(6);
if(board1.board != null)
empty = true;
Assert.assertTrue("false", empty);
}
public void tearDown() {
board1 = null;
}
}
|
3e1ee4f9cf132da800d3571829c0ff99dd060b2c | 681 | java | Java | phoenix-console/src/main/java/com/dianping/phoenix/utils/StringUtils.java | unidal/phoenix | 05c48fc75591114403ba2cb0552ef4b66b1442ad | [
"Apache-2.0"
] | 6 | 2015-12-04T08:52:34.000Z | 2021-07-29T09:49:11.000Z | phoenix-console/src/main/java/com/dianping/phoenix/utils/StringUtils.java | unidal/phoenix | 05c48fc75591114403ba2cb0552ef4b66b1442ad | [
"Apache-2.0"
] | null | null | null | phoenix-console/src/main/java/com/dianping/phoenix/utils/StringUtils.java | unidal/phoenix | 05c48fc75591114403ba2cb0552ef4b66b1442ad | [
"Apache-2.0"
] | 8 | 2015-08-19T00:13:01.000Z | 2020-12-01T01:58:46.000Z | 24.321429 | 79 | 0.706314 | 13,056 | package com.dianping.phoenix.utils;
import java.util.ArrayList;
import java.util.List;
import org.unidal.webres.json.JsonSerializer;
public class StringUtils {
public static boolean isBlank(String str) {
if (str == null || str.trim().length() == 0) {
return true;
}
return false;
}
public static String getDefaultValueIfBlank(String str, String defaultValue) {
return isBlank(str) ? defaultValue : str;
}
public static void main(String[] args) throws Exception {
List<String> list = new ArrayList<String>();
for (int idx = 0; idx < 10; idx++) {
list.add(String.valueOf(idx));
}
System.out.println(JsonSerializer.getInstance().serialize(list));
}
}
|
3e1ee521d0c28539a0ba139887c168b917722ee3 | 3,232 | java | Java | src/eu/artemis/demanes/lib/services/RESTService.java | DEMANES/demanes-api | 0e102b93f5eec499565d409c331ad90d577cb68d | [
"Apache-2.0"
] | null | null | null | src/eu/artemis/demanes/lib/services/RESTService.java | DEMANES/demanes-api | 0e102b93f5eec499565d409c331ad90d577cb68d | [
"Apache-2.0"
] | null | null | null | src/eu/artemis/demanes/lib/services/RESTService.java | DEMANES/demanes-api | 0e102b93f5eec499565d409c331ad90d577cb68d | [
"Apache-2.0"
] | null | null | null | 31.686275 | 81 | 0.700186 | 13,057 | /**
* File RESTService.java
*
* This file is part of the eu.artemis.demanes project.
*
* Copyright 2014 TNO
*
* 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 eu.artemis.demanes.lib.services;
import java.nio.ByteBuffer;
import eu.artemis.demanes.datatypes.ANES_URN;
/**
* <h1>RESTService</h1>
*
* <p>
* A RESTService is any object that provides a particular service in a REST way.
* This means we provide four operations for GET, PUT, POST or DELETE
* information to a service. This is exactly what the interface provides. The
* usage of the service is entirely up the implementing service, but this
* interface makes sure all services can be addressed in a universal way.
* </p>
*
* </p> A nice video explaining the REST architectural style can be found in <a
* href=http://www.restapitutorial.com/lessons/whatisrest.html>this video</a>
* </p>
*
* @author leeuwencjv
* @version 0.1
* @since 15 okt. 2014
*
*/
public interface RESTService {
/**
* Get information from the service. This usually means the data requested
* comes via the return value, but this is in no way guaranteed. The
* function returns either the data that was requested or null otherwise.
*
* @param input
* @return
* @throws ServiceException
*/
public ByteBuffer get(ByteBuffer input) throws ServiceException;
/**
* Put information in to the service. This usually means the creation of new
* resources in the service, but this is up to the design of the service.
* The return value may be null, or some kind of confirmation of the action.
*
* @param input
* @return
* @throws ServiceException
*/
public ByteBuffer put(ByteBuffer input) throws ServiceException;
/**
* Post information to the service. This usually means the update of
* existing resources in the service, but this is up to the design of the
* service. The return value may be null, or some kind of confirmation of
* the action.
*
* @param input
* @return
* @throws ServiceException
*/
public ByteBuffer post(ByteBuffer input) throws ServiceException;
/**
* Request deletion of information from the service. The return value may be
* null, or some kind of confirmation of the deletion.
*
* @param input
* @return
* @throws ServiceException
*/
public ByteBuffer delete(ByteBuffer input) throws ServiceException;
/**
* Every service must be identifier by an (ideally unique) ANES_URN. Calling
* this function on any particular service should always return the same URN
* that will identify this service.
*
* @return
*/
public ANES_URN identifier();
}
|
3e1ee558d17dfe9e34f91b027f38692cb9f5d4d3 | 3,589 | java | Java | opensearch/src/main/java/org/opensearch/sql/opensearch/data/utils/ObjectContent.java | zhongnansu/opensearch-sql | 6b651c13a1a6baa084ff1e279d19d100a2945b12 | [
"Apache-2.0"
] | 1 | 2022-03-09T10:27:19.000Z | 2022-03-09T10:27:19.000Z | opensearch/src/main/java/org/opensearch/sql/opensearch/data/utils/ObjectContent.java | zhongnansu/opensearch-sql | 6b651c13a1a6baa084ff1e279d19d100a2945b12 | [
"Apache-2.0"
] | null | null | null | opensearch/src/main/java/org/opensearch/sql/opensearch/data/utils/ObjectContent.java | zhongnansu/opensearch-sql | 6b651c13a1a6baa084ff1e279d19d100a2945b12 | [
"Apache-2.0"
] | null | null | null | 26.19708 | 96 | 0.688771 | 13,058 | /*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
/*
* Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.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 org.opensearch.sql.opensearch.data.utils;
import java.util.AbstractMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.tuple.Pair;
/**
* The Implementation of Content to represent {@link Object}.
*/
@RequiredArgsConstructor
public class ObjectContent implements Content {
private final Object value;
@Override
public Integer intValue() {
return parseNumberValue(value, Integer::valueOf, Number::intValue);
}
@Override
public Long longValue() {
return parseNumberValue(value, Long::valueOf, Number::longValue);
}
@Override
public Short shortValue() {
return parseNumberValue(value, Short::valueOf, Number::shortValue);
}
@Override
public Byte byteValue() {
return parseNumberValue(value, Byte::valueOf, Number::byteValue);
}
@Override
public Float floatValue() {
return parseNumberValue(value, Float::valueOf, Number::floatValue);
}
@Override
public Double doubleValue() {
return parseNumberValue(value, Double::valueOf, Number::doubleValue);
}
@Override
public String stringValue() {
return (String) value;
}
@Override
public Boolean booleanValue() {
return (Boolean) value;
}
@Override
public Object objectValue() {
return value;
}
@SuppressWarnings("unchecked")
@Override
public Iterator<Map.Entry<String, Content>> map() {
return ((Map<String, Object>) value).entrySet().stream()
.map(entry -> (Map.Entry<String, Content>) new AbstractMap.SimpleEntry<String, Content>(
entry.getKey(),
new ObjectContent(entry.getValue())))
.iterator();
}
@SuppressWarnings("unchecked")
@Override
public Iterator<? extends Content> array() {
return ((List<Object>) value).stream().map(ObjectContent::new).iterator();
}
@Override
public boolean isNull() {
return value == null;
}
@Override
public boolean isNumber() {
return value instanceof Number;
}
@Override
public boolean isString() {
return value instanceof String;
}
@Override
public Pair<Double, Double> geoValue() {
final String[] split = ((String) value).split(",");
return Pair.of(Double.valueOf(split[0]), Double.valueOf(split[1]));
}
private <T> T parseNumberValue(Object value, Function<String, T> stringTFunction,
Function<Number, T> numberTFunction) {
if (value instanceof String) {
return stringTFunction.apply((String) value);
} else {
return numberTFunction.apply((Number) value);
}
}
}
|
3e1ee5cac7d550844a4e2da8ff17687ac1427907 | 682 | java | Java | bassy-common/src/main/java/com/dianwoda/test/bassy/common/enums/AssetTypeEn.java | DianwodaCompany/bassy | 03746d0fa347c05c1398d0c7468e38e8949574b9 | [
"Apache-2.0"
] | 8 | 2019-12-27T08:53:27.000Z | 2019-12-31T06:44:59.000Z | bassy-common/src/main/java/com/dianwoda/test/bassy/common/enums/AssetTypeEn.java | DianwodaCompany/bassy | 03746d0fa347c05c1398d0c7468e38e8949574b9 | [
"Apache-2.0"
] | 10 | 2019-12-27T01:28:22.000Z | 2022-03-08T23:06:16.000Z | bassy-common/src/main/java/com/dianwoda/test/bassy/common/enums/AssetTypeEn.java | DianwodaCompany/bassy | 03746d0fa347c05c1398d0c7468e38e8949574b9 | [
"Apache-2.0"
] | 1 | 2021-01-18T13:15:22.000Z | 2021-01-18T13:15:22.000Z | 17.947368 | 48 | 0.52346 | 13,059 | package com.dianwoda.test.bassy.common.enums;
import lombok.Getter;
/**
* Created by gaoh on 2019/1/29.
*/
public enum AssetTypeEn {
PHONE(10, "手机"),
COMPUTER(20, "电脑"),
FITTINGS(30, "配件"),
BOOK(40, "图书");
@Getter
private int code;
@Getter
private String mean;
AssetTypeEn(int code, String mean) {
this.code = code;
this.mean = mean;
}
public static AssetTypeEn toEnum(int code) {
AssetTypeEn[] var = values();
for(int i=0; i<var.length; i++) {
AssetTypeEn en = var[i];
if(en.code == code) {
return en;
}
}
return null;
}
}
|
3e1ee643cd4bd31983161bd59ea9c8370cbe3550 | 53 | java | Java | springdemo/src/main/java/com/xuan/dao/HelloDao.java | heropopcorn/spring | fbb09d14aef0545a39b651409a677cf8a84171de | [
"Apache-2.0"
] | null | null | null | springdemo/src/main/java/com/xuan/dao/HelloDao.java | heropopcorn/spring | fbb09d14aef0545a39b651409a677cf8a84171de | [
"Apache-2.0"
] | null | null | null | springdemo/src/main/java/com/xuan/dao/HelloDao.java | heropopcorn/spring | fbb09d14aef0545a39b651409a677cf8a84171de | [
"Apache-2.0"
] | null | null | null | 10.6 | 27 | 0.754717 | 13,060 | package com.xuan.dao;
public interface HelloDao {
}
|
3e1ee69c5bde559eb6b0d54b401ceae4241dc749 | 233 | java | Java | src/main/java/com/example/modelmapper/repository/ClienteRepository.java | BCaldas/poc-modelmapper | bb40eda391b8507eca4213816d029abfa3894289 | [
"MIT"
] | null | null | null | src/main/java/com/example/modelmapper/repository/ClienteRepository.java | BCaldas/poc-modelmapper | bb40eda391b8507eca4213816d029abfa3894289 | [
"MIT"
] | null | null | null | src/main/java/com/example/modelmapper/repository/ClienteRepository.java | BCaldas/poc-modelmapper | bb40eda391b8507eca4213816d029abfa3894289 | [
"MIT"
] | null | null | null | 29.125 | 76 | 0.845494 | 13,061 | package com.example.modelmapper.repository;
import com.example.modelmapper.model.Cliente;
import org.springframework.data.jpa.repository.JpaRepository;
public interface ClienteRepository extends JpaRepository<Cliente, Integer> {
}
|
3e1ee6a7e146ee511e5cf2fcbc8efc35a9854888 | 299 | java | Java | rcpt/src/main/java/jp/chang/myclinic/rcpt/check/CheckNaifuku.java | hangilc/myclinic-spring | 5d2befd7901439d8e8c0102e0c81cf356b5b38ba | [
"MIT"
] | null | null | null | rcpt/src/main/java/jp/chang/myclinic/rcpt/check/CheckNaifuku.java | hangilc/myclinic-spring | 5d2befd7901439d8e8c0102e0c81cf356b5b38ba | [
"MIT"
] | 2 | 2020-03-04T22:17:34.000Z | 2020-03-21T05:58:49.000Z | rcpt/src/main/java/jp/chang/myclinic/rcpt/check/CheckNaifuku.java | hangilc/myclinic-spring | 5d2befd7901439d8e8c0102e0c81cf356b5b38ba | [
"MIT"
] | null | null | null | 23 | 56 | 0.662207 | 13,062 | package jp.chang.myclinic.rcpt.check;
class CheckNaifuku extends CheckBaseDrugShinryou {
CheckNaifuku(Scope scope) {
super(scope);
setPredicate(d -> isNaifuku(d) || isTonpuku(d));
setShinryoucode(getShinryouMaster().内服調剤);
setShinryouName("調剤料(内服薬)");
}
}
|
3e1ee6ff261219a4853e8ea95de4292ec451db61 | 4,292 | java | Java | src/main/java/com/github/gilbertotcc/lifx/models/Selectors.java | iamleot/lifx-client | 82215425ce6530b9cd3a7a54f9195bac88fa912d | [
"BSD-2-Clause"
] | 3 | 2018-10-15T09:04:03.000Z | 2019-10-26T10:28:33.000Z | src/main/java/com/github/gilbertotcc/lifx/models/Selectors.java | iamleot/lifx-client | 82215425ce6530b9cd3a7a54f9195bac88fa912d | [
"BSD-2-Clause"
] | 9 | 2019-05-05T10:40:37.000Z | 2020-07-05T09:21:59.000Z | src/main/java/com/github/gilbertotcc/lifx/models/Selectors.java | iamleot/lifx-client | 82215425ce6530b9cd3a7a54f9195bac88fa912d | [
"BSD-2-Clause"
] | 2 | 2020-04-13T04:43:39.000Z | 2020-12-17T17:04:44.000Z | 23.977654 | 113 | 0.738583 | 13,063 | // CHECKSTYLE:OFF
package com.github.gilbertotcc.lifx.models;
import static java.lang.String.format;
import lombok.AllArgsConstructor;
import lombok.experimental.UtilityClass;
@UtilityClass
public class Selectors {
public static AllSelector all() {
return new AllSelector();
}
public static LabelSelector byLabel(String label) {
return new LabelSelector(label);
}
public static IdSelector byId(String id) {
return new IdSelector(id);
}
public static GroupIdSelector byGroupId(String groupId) {
return new GroupIdSelector(groupId);
}
public static GroupSelector byGroup(String group) {
return new GroupSelector(group);
}
public static LocationIdSelector byLocationId(String locationId) {
return new LocationIdSelector(locationId);
}
public static LocationSelector byLocation(String location) {
return new LocationSelector(location);
}
public static SceneIdSelector bySceneId(String sceneId) {
return new SceneIdSelector(sceneId);
}
@Deprecated
public static AllSelector All() { //NOSONAR
return all();
}
@Deprecated
public static LabelSelector LabelSelector(String label) { //NOSONAR
return byLabel(label);
}
@Deprecated
public static IdSelector IdSelector(String id) { //NOSONAR
return byId(id);
}
@Deprecated
public static GroupIdSelector GroupIdSelector(String groupId) { //NOSONAR
return byGroupId(groupId);
}
@Deprecated
public static GroupSelector GroupSelector(String group) { //NOSONAR
return byGroup(group);
}
@Deprecated
public static LocationIdSelector LocationIdSelector(String locationId) { //NOSONAR
return byLocationId(locationId);
}
@Deprecated
public static LocationSelector LocationSelector(String location) { //NOSONAR
return byLocation(location);
}
@Deprecated
public static SceneIdSelector SceneIdSelector(String sceneId) { //NOSONAR
return bySceneId(sceneId);
}
@AllArgsConstructor
public static final class AllSelector
implements LightSelector, RandomizableLightSelector, MultiZoneEnabledLightSelector {
@Override
public String identifier() {
return "all";
}
}
@AllArgsConstructor
public static final class LabelSelector
implements LightSelector, CombinableLightSelector, MultiZoneEnabledLightSelector {
private String label;
@Override
public String identifier() {
return format("label:%s", label);
}
}
@AllArgsConstructor
public static final class IdSelector
implements LightSelector, CombinableLightSelector, MultiZoneEnabledLightSelector {
private String id;
@Override
public String identifier() {
return format("id:%s", id);
}
}
@AllArgsConstructor
public static final class GroupIdSelector
implements LightSelector, RandomizableLightSelector, CombinableLightSelector, MultiZoneEnabledLightSelector {
private String groupId;
@Override
public String identifier() {
return format("group_id:%s", groupId);
}
}
@AllArgsConstructor
public static final class GroupSelector
implements LightSelector, RandomizableLightSelector, CombinableLightSelector, MultiZoneEnabledLightSelector {
private String group;
@Override
public String identifier() {
return format("group:%s", group);
}
}
@AllArgsConstructor
public static final class LocationIdSelector
implements LightSelector, RandomizableLightSelector, CombinableLightSelector, MultiZoneEnabledLightSelector {
private String locationId;
@Override
public String identifier() {
return format("location_id:%s", locationId);
}
}
@AllArgsConstructor
public static final class LocationSelector
implements LightSelector, RandomizableLightSelector, CombinableLightSelector, MultiZoneEnabledLightSelector {
private String location;
@Override
public String identifier() {
return format("location:%s", location);
}
}
@AllArgsConstructor
public static final class SceneIdSelector
implements LightSelector, RandomizableLightSelector, CombinableLightSelector, MultiZoneEnabledLightSelector {
private String sceneId;
@Override
public String identifier() {
return format("scene_id:%s", sceneId);
}
}
}
|
3e1ee86b1375b0c38bddd898c09ee100a744d9e2 | 3,632 | java | Java | spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapping/Encrypted.java | divyajnu08/spring-data-mongodb | ba8a37d37705896858cf6280555024698bef3d08 | [
"Apache-2.0"
] | 1,264 | 2015-01-02T12:33:41.000Z | 2022-03-29T23:23:26.000Z | spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapping/Encrypted.java | divyajnu08/spring-data-mongodb | ba8a37d37705896858cf6280555024698bef3d08 | [
"Apache-2.0"
] | 1,012 | 2015-01-06T12:30:30.000Z | 2022-03-31T15:44:26.000Z | spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapping/Encrypted.java | divyajnu08/spring-data-mongodb | ba8a37d37705896858cf6280555024698bef3d08 | [
"Apache-2.0"
] | 972 | 2015-01-03T06:58:31.000Z | 2022-03-29T07:08:07.000Z | 32.141593 | 120 | 0.660242 | 13,064 | /*
* Copyright 2021 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.mongodb.core.mapping;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* {@link Encrypted} provides data required for MongoDB Client Side Field Level Encryption that is applied during schema
* resolution. It can be applied on top level (typically those types annotated with {@link Document} to provide the
* {@literal encryptMetadata}.
*
* <pre class="code">
* @Document
* @Encrypted(keyId = "4fPYFM9qSgyRAjgQ2u+IMQ==")
* public class Patient {
* private ObjectId id;
* private String name;
*
* @Field("publisher_ac")
* @DocumentReference(lookup = "{ 'acronym' : ?#{#target} }") private Publisher publisher;
* }
*
* "encryptMetadata": {
* "keyId": [
* {
* "$binary": {
* "base64": "4fPYFM9qSgyRAjgQ2u+IMQ==",
* "subType": "04"
* }
* }
* ]
* }
* </pre>
*
* <br />
* On property level it is used for deriving field specific {@literal encrypt} settings.
*
* <pre class="code">
* public class Patient {
* private ObjectId id;
* private String name;
*
* @Encrypted(keyId = "4fPYFM9qSgyRAjgQ2u+IMQ==", algorithm = "AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic")
* private String ssn;
* }
*
* "ssn" : {
* "encrypt": {
* "keyId": [
* {
* "$binary": {
* "base64": "4fPYFM9qSgyRAjgQ2u+IMQ==",
* "subType": "04"
* }
* }
* ],
* "algorithm" : "AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic",
* "bsonType" : "string"
* }
* }
* </pre>
*
* @author Christoph Strobl
* @since 3.3
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.FIELD })
public @interface Encrypted {
/**
* Get the {@code keyId} to use. The value must resolve to either the UUID representation of the key or a base64
* encoded value representing the UUID value.
* <br />
* On {@link ElementType#TYPE} level the {@link #keyId()} can be left empty if explicitly set for fields. <br />
* On {@link ElementType#FIELD} level the {@link #keyId()} can be left empty if inherited from
* {@literal encryptMetadata}.
*
* @return the key id to use. May contain a parsable {@link org.springframework.expression.Expression expression}. In
* this case the {@code #target} variable will hold the target element name.
*/
String[] keyId() default {};
/**
* Set the algorithm to use.
* <br />
* On {@link ElementType#TYPE} level the {@link #algorithm()} can be left empty if explicitly set for fields. <br />
* On {@link ElementType#FIELD} level the {@link #algorithm()} can be left empty if inherited from
* {@literal encryptMetadata}.
*
* @return the encryption algorithm.
* @see org.springframework.data.mongodb.core.EncryptionAlgorithms
*/
String algorithm() default "";
}
|
3e1ee9a21cf02c6d22768131e542a9029a0ee4e9 | 2,995 | java | Java | src/main/java/org/giwi/geotracker/routes/priv/UsersRoute.java | Giwi/geoTraker | 5a09299ea6598bd34810ffc6e7e786c74cda3f20 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/giwi/geotracker/routes/priv/UsersRoute.java | Giwi/geoTraker | 5a09299ea6598bd34810ffc6e7e786c74cda3f20 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/giwi/geotracker/routes/priv/UsersRoute.java | Giwi/geoTraker | 5a09299ea6598bd34810ffc6e7e786c74cda3f20 | [
"Apache-2.0"
] | null | null | null | 31.526316 | 87 | 0.605008 | 13,065 | package org.giwi.geotracker.routes.priv;
import io.vertx.core.Vertx;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.AuthHandler;
import io.vertx.ext.web.handler.JWTAuthHandler;
import org.giwi.geotracker.annotation.VertxRoute;
import org.giwi.geotracker.beans.AuthUtils;
import org.giwi.geotracker.services.UserService;
import javax.inject.Inject;
/**
* The type Users route.
*/
@VertxRoute(rootPath = "/api/1/private/user")
public class UsersRoute implements VertxRoute.Route {
@Inject
private AuthUtils authUtils;
@Inject
private UserService userService;
@Override
public Router init(Vertx vertx) {
AuthHandler adminHandler = JWTAuthHandler.create(authUtils.getAuthProvider());
adminHandler.addAuthority("admin");
Router router = Router.router(vertx);
router.route("/*").handler(JWTAuthHandler.create(authUtils.getAuthProvider()));
router.get("/logout").handler(this::logout);
router.get("/").handler(this::getCurrentUser);
router.get("/all").handler(adminHandler);
router.get("/all").handler(this::getUserList);
return router;
}
/**
* @api {get} /api/1/private/user/all Get User list
* @apiName getUserList
* @apiGroup Users
* @apiDescription Get User list
* @apiSuccess {Array} user User[]
*/
private void getUserList(RoutingContext context) {
userService.getUserList(new JsonObject(), res -> {
if (res.succeeded()) {
JsonArray jar = new JsonArray();
res.result().forEach(u -> {
u.remove("password");
u.remove("salt");
jar.add(u);
});
context.response().end(jar.encode());
} else {
context.fail(res.cause());
}
});
}
/**
* @api {get} /api/1/private/user Get Current User
* @apiName getCurrentUser
* @apiGroup Users
* @apiDescription Get the current logged user
* @apiSuccess {Object} user User
*/
private void getCurrentUser(RoutingContext context) {
String uid = context.user().principal().getString("uid");
authUtils.getClientFromToken(uid, res -> {
if (res.succeeded()) {
res.result().remove("salt");
res.result().remove("password");
context.response().end(res.result().encode());
} else {
context.fail(res.cause());
}
});
}
/**
* @api {get} /api/1/private/user/logout Logout
* @apiName logout
* @apiGroup Users
* @apiDescription Logout the user
* @apiSuccess {Boolean} status Status
*/
private void logout(RoutingContext context) {
String uid = context.user().principal().getString("uid");
}
}
|
3e1ee9dcb5ad0aeef7ed792d4efd09520935c900 | 3,280 | java | Java | app/src/main/java/com/lt/hm/wovideo/model/BannerList.java | smellHui/WoVideo | c677e5a1aca74d9aacea0bb7d3d083a534b887fa | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/lt/hm/wovideo/model/BannerList.java | smellHui/WoVideo | c677e5a1aca74d9aacea0bb7d3d083a534b887fa | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/lt/hm/wovideo/model/BannerList.java | smellHui/WoVideo | c677e5a1aca74d9aacea0bb7d3d083a534b887fa | [
"Apache-2.0"
] | null | null | null | 20 | 61 | 0.479573 | 13,066 | package com.lt.hm.wovideo.model;
import java.util.List;
/**
* @author leonardo
* @version 1.0
* @create_date 16/6/13
*/
public class BannerList {
private List<Banner> bannerList;
public List<Banner> getBannerList() {
return bannerList;
}
public void setBannerList(List<Banner> bannerList) {
this.bannerList = bannerList;
}
@Override
public String toString() {
return "BannerList{" +
"bannerList=" + bannerList +
'}';
}
public class Banner{
/**
* typeName : 电影
* id : 13
* utime : 1465904126000
* cb :
* hit : null
* img : /banner/0bce60b57d824908968d88d078783a85.jpg
* vfType : 1
* type : 0
* ctime : 1465724716000
* url :
* outid : 3
* isvip : 0
*/
private String typeName;
private int id;
private long utime;
private String cb;
private String hit;
private String img;
private String vfType;
private String type;
private long ctime;
private String url;
private String outid;
private String isvip;
private String vfName;
public String getVfName() {
return vfName;
}
public void setVfName(String vfName) {
this.vfName = vfName;
}
public String getTypeName() {
return typeName;
}
public void setTypeName(String typeName) {
this.typeName = typeName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public long getUtime() {
return utime;
}
public void setUtime(long utime) {
this.utime = utime;
}
public String getCb() {
return cb;
}
public void setCb(String cb) {
this.cb = cb;
}
public String getHit() {
return hit;
}
public void setHit(String hit) {
this.hit = hit;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public String getVfType() {
return vfType;
}
public void setVfType(String vfType) {
this.vfType = vfType;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public long getCtime() {
return ctime;
}
public void setCtime(long ctime) {
this.ctime = ctime;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getOutid() {
return outid;
}
public void setOutid(String outid) {
this.outid = outid;
}
public String getIsvip() {
return isvip;
}
public void setIsvip(String isvip) {
this.isvip = isvip;
}
}
}
|
3e1eeab02f220bd44d177ef737def72b3c23370e | 733 | java | Java | utilities/src/main/java/io/syndesis/qe/bdd/entities/SeparatorType.java | mmajerni/syndesis-qe | 60d6b8e3e7dc6fa9065df6a951a291ae7d38a9c2 | [
"Apache-2.0"
] | 1 | 2019-04-04T05:20:37.000Z | 2019-04-04T05:20:37.000Z | utilities/src/main/java/io/syndesis/qe/bdd/entities/SeparatorType.java | mmajerni/syndesis-qe | 60d6b8e3e7dc6fa9065df6a951a291ae7d38a9c2 | [
"Apache-2.0"
] | 1 | 2019-12-16T13:45:44.000Z | 2019-12-17T16:29:22.000Z | utilities/src/main/java/io/syndesis/qe/bdd/entities/SeparatorType.java | mmajerni/syndesis-qe | 60d6b8e3e7dc6fa9065df6a951a291ae7d38a9c2 | [
"Apache-2.0"
] | null | null | null | 29.32 | 75 | 0.72442 | 13,067 | /*
* Copyright 2018 tplevko.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.syndesis.qe.bdd.entities;
/**
*
* @author tplevko
*/
public enum SeparatorType {
Colon, Comma, Dash, Multispace, Space
}
|
3e1eed0b6f236dd027d9f3a59b37d461f645e97d | 11,291 | java | Java | src/main/java/com/github/jbox/h2/TinyHelpers.java | feiqing/jbox | bcc8ce320e8b201ed9a4d517694e751777b0e7ab | [
"Apache-2.0"
] | 9 | 2017-11-21T06:18:25.000Z | 2021-12-31T03:30:47.000Z | src/main/java/com/github/jbox/h2/TinyHelpers.java | feiqing/jbox | bcc8ce320e8b201ed9a4d517694e751777b0e7ab | [
"Apache-2.0"
] | 3 | 2017-11-15T08:19:48.000Z | 2022-01-21T23:49:01.000Z | src/main/java/com/github/jbox/h2/TinyHelpers.java | feiqing/jbox | bcc8ce320e8b201ed9a4d517694e751777b0e7ab | [
"Apache-2.0"
] | 13 | 2017-11-25T15:11:43.000Z | 2021-12-23T09:22:22.000Z | 40.647482 | 140 | 0.612389 | 13,068 | package com.github.jbox.h2;
import com.alibaba.druid.pool.DruidDataSource;
import com.github.jbox.serializer.ISerializer;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import org.apache.commons.lang3.StringUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import static java.sql.Types.*;
/**
* @author kenaa@example.com (FeiQing)
* @version 1.0
* @since 2020/9/24 10:44 AM.
*/
class TinyHelpers {
private static final ConcurrentMap<Class<? extends ISerializer>, ISerializer> serializers = new ConcurrentHashMap<>();
private static final ConcurrentMap<String, JdbcTemplate> templates = new ConcurrentHashMap<>();
static JdbcTemplate getTemplate(String h2path) {
return templates.computeIfAbsent(h2path, path -> {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName("org.h2.Driver");
dataSource.setUrl(String.format("jdbc:h2:%s;AUTO_RECONNECT=TRUE;AUTO_SERVER=TRUE", path));
dataSource.setUsername("jbox");
dataSource.setPassword("jbox");
JdbcTemplate template = new JdbcTemplate(dataSource);
template.afterPropertiesSet();
return template;
});
}
@SuppressWarnings("unchecked")
static <T> Class<T> getModelType(Object obj) {
Type superclass = obj.getClass().getGenericSuperclass();
while (!superclass.equals(Object.class) && !(superclass instanceof ParameterizedType)) {
superclass = ((Class) superclass).getGenericSuperclass();
}
if (!(superclass instanceof ParameterizedType)) {
throw new RuntimeException(String.format("class:%s extends H2Batis<T> not replace generic type <T>", obj.getClass().getName()));
}
return (Class<T>) ((ParameterizedType) superclass).getActualTypeArguments()[0];
}
private static final ConcurrentMap<Class<?>, List<Field>> fields = new ConcurrentHashMap<>();
static List<Field> getFields(final Class<?> clazz) {
return fields.computeIfAbsent(clazz, _cls -> {
List<Field> fields = new ArrayList<>();
Class<?> tmp = clazz;
while (tmp != Object.class) {
for (Field field : tmp.getDeclaredFields()) {
if (!Modifier.isStatic(field.getModifiers())) {
field.setAccessible(true);
fields.add(field);
}
}
tmp = tmp.getSuperclass();
}
return fields;
});
}
/* Java -> SQL */
private static final ConcurrentMap<Class<?>, String> tableNames = new ConcurrentHashMap<>();
static String getTableName(Class<?> type) {
return tableNames.computeIfAbsent(type, _type -> "T_" + type.getName().toUpperCase().replace(".", "_"));
}
// 对象属性名 -> 表字段名
private static final ConcurrentMap<Field, String> field2columnNames = new ConcurrentHashMap<>();
static String getColumnName(Class<?> type, Field field) {
String columnName = field2columnNames.computeIfAbsent(field, _field -> _field.getName().toUpperCase());
columnName2fields.computeIfAbsent(type, _k -> new ConcurrentHashMap<>()).put(columnName, field);
return columnName;
}
// 对象属性名(s) -> 表字段名(s)
private static final ConcurrentMap<Class<?>, ConcurrentMap<String, Map<String, String>>> columnsNames = new ConcurrentHashMap<>();
static Map<String, String> getColumnsNames(Class<?> type, Collection<String> fieldNames) {
return getColumnsNames(type, fieldNames.toArray(new String[0]));
}
static Map<String, String> getColumnsNames(Class<?> type, String[] fieldNames) {
return columnsNames
.computeIfAbsent(type, _type -> new ConcurrentHashMap<>())
.computeIfAbsent(Joiner.on("@").join(fieldNames), _k -> {
Map<String, String> columnNames = new LinkedHashMap<>(fieldNames.length);
for (String fieldName : fieldNames) {
for (Field field : getFields(type)) {
if (StringUtils.equals(fieldName, field.getName())) {
columnNames.put(fieldName, getColumnName(type, field));
}
}
}
Preconditions.checkState(fieldNames.length == columnNames.size());
return columnNames;
});
}
// 对象属性类型 -> 表字段类型
private static final ConcurrentMap<Class<?>, String> java2sqlTypes = new ConcurrentHashMap<>();
static {
java2sqlTypes.put(byte.class, "TINYINT");
java2sqlTypes.put(Byte.class, "TINYINT");
java2sqlTypes.put(short.class, "SMALLINT");
java2sqlTypes.put(Short.class, "SMALLINT");
java2sqlTypes.put(int.class, "INT");
java2sqlTypes.put(Integer.class, "INT");
java2sqlTypes.put(long.class, "BIGINT");
java2sqlTypes.put(Long.class, "BIGINT");
java2sqlTypes.put(float.class, "REAL");
java2sqlTypes.put(Float.class, "REAL");
java2sqlTypes.put(double.class, "DOUBLE");
java2sqlTypes.put(Double.class, "DOUBLE");
java2sqlTypes.put(boolean.class, "BOOLEAN");
java2sqlTypes.put(Boolean.class, "BOOLEAN");
java2sqlTypes.put(char.class, "CHAR(10)");
java2sqlTypes.put(Character.class, "CHAR(10)");
java2sqlTypes.put(String.class, "VARCHAR(255)");
java2sqlTypes.put(BigDecimal.class, "DECIMAL");
java2sqlTypes.put(LocalTime.class, "TIME");
java2sqlTypes.put(LocalDate.class, "DATE");
java2sqlTypes.put(Date.class, "TIMESTAMP");
java2sqlTypes.put(Object.class, "BINARY(1000)");
}
private static final ConcurrentMap<Field, String> columnTypes = new ConcurrentHashMap<>();
static String getColumnType(Field field) {
return columnTypes.computeIfAbsent(field, _field -> {
Column column;
if ((column = field.getAnnotation(Column.class)) != null && !Strings.isNullOrEmpty(column.type())) {
return column.type().toUpperCase();
}
String type = java2sqlTypes.get(field.getType());
if (type == null) {
if (column == null || column.serializer() == ISerializer.class)
throw new RuntimeException("not support type:[" + field.getType().getName() + "] default, need specified 'serializer'");
else
type = java2sqlTypes.get(Object.class);
}
return type;
});
}
// 判定属性是否可以为Null
private static final ConcurrentMap<Field, String> columnNulls = new ConcurrentHashMap<>();
static String getColumnNull(Field field) {
return columnNulls.computeIfAbsent(field, _field -> {
if (field.isAnnotationPresent(Column.class)) {
return field.getAnnotation(Column.class).nullable() ? "" : "NOT NULL";
}
return "";
});
}
// 对象属性值 -> 表字段值
static Object getColumnValue(Field field, Object model) {
try {
Object value = field.get(model);
if (value == null) {
return null;
}
Column column;
if ((column = field.getAnnotation(Column.class)) != null && column.serializer() != ISerializer.class) {
ISerializer serializer = serializers.computeIfAbsent(column.serializer(), _k -> {
try {
return column.serializer().newInstance();
} catch (InstantiationException | IllegalAccessException e) {
throw new RuntimeException(e);
}
});
value = serializer.serialize(value);
}
return value;
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
/* SQL -> Java */
// 表字段 -> 对象属性
private static final ConcurrentMap<Class<?>, ConcurrentMap<String, Field>> columnName2fields = new ConcurrentHashMap<>();
// 在启动时会自动扫描model并建表, 此时columnName2fields内容就已经构建好了, 直接使用即可
static Field getColumnField(Class<?> type, String columnName) {
return columnName2fields.get(type).get(columnName);
}
// SqlResult -> 对象属性值
private interface Function {
Object apply(ResultSet rs, int columnIdx, Field field) throws SQLException;
}
private static final ConcurrentMap<Integer, Function> extractor = new ConcurrentHashMap<>();
static {
Function binary = (rs, idx, field) -> {
Column column;
Preconditions.checkState((column = field.getAnnotation(Column.class)) != null && column.serializer() != ISerializer.class);
ISerializer serializer = serializers.computeIfAbsent(column.serializer(), _k -> {
try {
return column.serializer().newInstance();
} catch (InstantiationException | IllegalAccessException e) {
throw new RuntimeException(e);
}
});
return serializer.deserialize(rs.getBytes(idx));
};
extractor.put(NULL, (rs, idx, field) -> null);
extractor.put(BIT, (rs, idx, field) -> rs.getByte(idx));
extractor.put(TINYINT, (rs, idx, field) -> rs.getByte(idx));
extractor.put(SMALLINT, (rs, idx, field) -> rs.getShort(idx));
extractor.put(INTEGER, (rs, idx, field) -> rs.getInt(idx));
extractor.put(BIGINT, (rs, idx, field) -> rs.getLong(idx));
extractor.put(FLOAT, (rs, idx, field) -> rs.getFloat(idx));
extractor.put(REAL, (rs, idx, field) -> rs.getFloat(idx));
extractor.put(DOUBLE, (rs, idx, field) -> rs.getDouble(idx));
extractor.put(BOOLEAN, (rs, idx, field) -> rs.getBoolean(idx));
extractor.put(CHAR, (rs, idx, field) -> rs.getString(idx).charAt(0));
extractor.put(VARCHAR, (rs, idx, field) -> rs.getString(idx));
extractor.put(DECIMAL, (rs, idx, field) -> rs.getBigDecimal(idx));
extractor.put(TIME, (rs, idx, field) -> rs.getTime(idx).toLocalTime());
extractor.put(DATE, (rs, idx, field) -> rs.getDate(idx).toLocalDate());
extractor.put(TIMESTAMP, (rs, idx, field) -> rs.getTimestamp(idx));
extractor.put(BINARY, binary);
extractor.put(VARBINARY, binary);
}
static Object getColumnValue(ResultSet rs, int idx, int columnType, Field field) {
try {
return extractor.get(columnType).apply(rs, idx, field);
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
|
3e1eed5b4331b1e00c47d783bbe56e597d482847 | 3,355 | java | Java | src/gwt/client/mail/FriendInviteDisplay.java | VirtueDev/synced_repo | adc1b61ad68402492386fa011e4c628d6588c800 | [
"BSD-3-Clause"
] | 21 | 2015-04-30T10:28:47.000Z | 2021-06-23T23:00:45.000Z | src/gwt/client/mail/FriendInviteDisplay.java | VirtueDev/synced_repo | adc1b61ad68402492386fa011e4c628d6588c800 | [
"BSD-3-Clause"
] | 36 | 2015-07-29T20:50:57.000Z | 2021-09-18T22:37:25.000Z | src/gwt/client/mail/FriendInviteDisplay.java | VirtueDev/synced_repo | adc1b61ad68402492386fa011e4c628d6588c800 | [
"BSD-3-Clause"
] | 35 | 2015-04-30T10:29:41.000Z | 2022-02-15T21:17:01.000Z | 33.217822 | 97 | 0.594337 | 13,069 | //
// $Id$
package client.mail;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Widget;
import com.threerings.gwt.ui.SmartTable;
import com.threerings.msoy.data.all.Friendship;
import com.threerings.msoy.mail.gwt.ConvMessage;
import com.threerings.msoy.mail.gwt.MailService;
import com.threerings.msoy.mail.gwt.MailServiceAsync;
import com.threerings.msoy.web.gwt.WebMemberService;
import com.threerings.msoy.web.gwt.WebMemberServiceAsync;
import client.util.ClickCallback;
import client.util.InfoCallback;
/**
* Displays a friend invitation.
*/
public class FriendInviteDisplay extends MailPayloadDisplay
{
@Override // from MailPayloadDisplay
public Widget widgetForRecipient ()
{
return new InvitationWidget();
}
protected class InvitationWidget extends SmartTable
{
protected InvitationWidget ()
{
super(0, 0);
refreshUI(false);
}
protected void refreshUI (final boolean roundtrip)
{
int friendId = _message.author.name.getId();
_membersvc.getFriendship(friendId, new InfoCallback<Friendship>() {
public void onSuccess (Friendship result) {
buildUI(result, roundtrip);
}
});
}
protected void buildUI (Friendship friendship, boolean roundtrip)
{
if (friendship == Friendship.INVITEE) { // normal case
setText(0, 0, _msgs.friendInvitation(), 0, "rowPanelCell");
Button ayeButton = new Button(_msgs.friendBtnAccept());
new ClickCallback<Void>(ayeButton) {
@Override protected boolean callService () {
_membersvc.addFriend(_message.author.name.getId(), this);
return true;
}
@Override protected boolean gotResult (Void result) {
mailResponse();
refreshUI(true);
return false;
}
};
setWidget(0, 1, ayeButton);
return;
}
String otherName = _message.author.name.toString();
String text;
if (friendship == Friendship.FRIENDS) { // success case
text = roundtrip ? _msgs.friendAccepted(otherName)
: _msgs.friendAlreadyFriend(otherName);
} else if (friendship == Friendship.INVITED) { // weird, but ok
text = _msgs.friendInvited(otherName);
} else { // retracted
text = _msgs.friendRetracted(otherName);
}
setText(0, 0, text);
setText(0, 1, "");
}
protected void mailResponse ()
{
_mailsvc.continueConversation(
_convoId, _msgs.friendReplyBody(), null, new InfoCallback.NOOP<ConvMessage>());
}
protected boolean _thirdPerson;
}
protected static final MailMessages _msgs = GWT.create(MailMessages.class);
protected static final WebMemberServiceAsync _membersvc = GWT.create(WebMemberService.class);
protected static final MailServiceAsync _mailsvc = GWT.create(MailService.class);
}
|
3e1eed66e4688356a78db361f4627f11b948574a | 28,540 | java | Java | ImageSocketClient/ClassQueryMakers.java | jtmedley/Electronic-Medical-Record | bbaa8260f32f5fdfcb3518a9194cf471bd3d490e | [
"Apache-2.0"
] | null | null | null | ImageSocketClient/ClassQueryMakers.java | jtmedley/Electronic-Medical-Record | bbaa8260f32f5fdfcb3518a9194cf471bd3d490e | [
"Apache-2.0"
] | null | null | null | ImageSocketClient/ClassQueryMakers.java | jtmedley/Electronic-Medical-Record | bbaa8260f32f5fdfcb3518a9194cf471bd3d490e | [
"Apache-2.0"
] | null | null | null | 39.14952 | 157 | 0.620357 | 13,070 | /*
*
* * Copyright (c) 2019. Tabitha Huff & Hyunji Kim & Jonathan Medley & Jack O'Connor
* *
* * 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.example.medley.medicalrecord;
import org.threeten.bp.DateTimeUtils;
import org.threeten.bp.LocalDate;
import java.sql.Types;
import java.text.NumberFormat;
import java.util.ArrayList;
/**
* Implements methods to create a query object to be used for database communications, containing
* an array of parameters for the query, and an array of the parameter types to be applied to
* a prepared SQL statement.
* <p>
* Adapted from https://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html
* and from http://www.java2s.com/Code/Java/Database-SQL-JDBC/InsertpicturetoMySQL.htm
* and from https://stackoverflow.com/questions/10618325/how-to-create-a-blob-from-bitmap-in-android-activity/10618678
*/
class ClassQueryMakers {
/**
*
*/
final ArrayList<Object> parameterArray;
/**
*
*/
final ArrayList<Integer> paramTypeArray;
/**
*
*/
private final String locationRecord;
/**
* Constructor
* Assigns parameter and parameter type fields to given inputs.
* Receives location string from current application settings.
*/
ClassQueryMakers() {
parameterArray = new ArrayList<>();
paramTypeArray = new ArrayList<>();
locationRecord = "Haiti";
}
/**
* Select basic patient information that matches input data
*
* @param newPatientFirstName The current patient's first name input by the
* user.
* @param newPatientLastName The current patient's last name input by the user.
* @param newPatientSex The current patient's sex input by the user.
* @param newPatientDOB The current patient's date of birth input by the
* user.
*/
void selectBasicQuery(String newPatientFirstName, String newPatientLastName, LocalDate newPatientDOB,
String newPatientSex) {
java.sql.Date newPatientDOBSql = null;
String newPatientDOBString = null;
if (newPatientFirstName == null) {
newPatientFirstName = "%";
} else {
if (newPatientFirstName.isEmpty()) {
newPatientFirstName = "%";
} else {
newPatientFirstName = "%" + newPatientFirstName + "%";
}
}
if (newPatientLastName == null) {
newPatientLastName = "%";
} else {
if (newPatientLastName.isEmpty()) {
newPatientLastName = "%";
} else {
newPatientLastName = "%" + newPatientLastName + "%";
}
}
if (newPatientDOB == null) {
newPatientDOBString = "%";
} else {
newPatientDOBSql = DateTimeUtils.toSqlDate(newPatientDOB);
}
if (newPatientSex == null) {
newPatientSex = "%";
} else {
if (newPatientSex.isEmpty()) {
newPatientSex = "%";
}
}
parameterArray.add(locationRecord);
paramTypeArray.add(Types.VARCHAR);
parameterArray.add(newPatientFirstName);
paramTypeArray.add(Types.VARCHAR);
parameterArray.add(newPatientLastName);
paramTypeArray.add(Types.VARCHAR);
if (newPatientDOB != null) {
parameterArray.add(newPatientDOBSql);
paramTypeArray.add(Types.VARCHAR);
} else {
parameterArray.add(newPatientDOBString);
paramTypeArray.add(Types.VARCHAR);
}
parameterArray.add(newPatientSex);
paramTypeArray.add(Types.VARCHAR);
}
/**
* Select basic or static patient information that matches input data or the patient ids
* received from image recognition
*
* @param newPatientFirstName The current patient's first name input by the
* user.
* @param newPatientLastName The current patient's last name input by the user.
* @param newPatientSex The current patient's sex input by the user.
* @param newPatientDOB The current patient's date of birth input by the
* user.
* @param personIds A list of possible matching patient ids from facial recognition
*/
void selectWithFaceQuery(String newPatientFirstName, String newPatientLastName, LocalDate newPatientDOB,
String newPatientSex, ArrayList<Integer> personIds) {
java.sql.Date newPatientDOBSql = null;
String newPatientDOBString = null;
if (newPatientFirstName == null) {
newPatientFirstName = "%";
} else {
if (newPatientFirstName.isEmpty()) {
newPatientFirstName = "%";
} else {
newPatientFirstName = "%" + newPatientFirstName + "%";
}
}
if (newPatientLastName == null) {
newPatientLastName = "%";
} else {
if (newPatientLastName.isEmpty()) {
newPatientLastName = "%";
} else {
newPatientLastName = "%" + newPatientLastName + "%";
}
}
if (newPatientDOB == null) {
newPatientDOBString = "%";
} else {
newPatientDOBSql = DateTimeUtils.toSqlDate(newPatientDOB);
}
if (newPatientSex == null) {
newPatientSex = "%";
} else {
if (newPatientSex.isEmpty()) {
newPatientSex = "%";
}
}
parameterArray.add(locationRecord);
paramTypeArray.add(Types.VARCHAR);
parameterArray.add(newPatientFirstName);
paramTypeArray.add(Types.VARCHAR);
parameterArray.add(newPatientLastName);
paramTypeArray.add(Types.VARCHAR);
if (newPatientDOB != null) {
parameterArray.add(newPatientDOBSql);
paramTypeArray.add(Types.VARCHAR);
} else {
parameterArray.add(newPatientDOBString);
paramTypeArray.add(Types.VARCHAR);
}
parameterArray.add(newPatientSex);
paramTypeArray.add(Types.VARCHAR);
if (personIds != null) {
if (!personIds.isEmpty()) {
for (Object next : personIds) {
parameterArray.add(next);
paramTypeArray.add(Types.INTEGER);
}
} else {
parameterArray.add(0);
paramTypeArray.add(Types.INTEGER);
}
} else {
parameterArray.add(0);
paramTypeArray.add(Types.INTEGER);
}
}
/**
* @param personIds
*/
void selectOnlyFaceQuery(ArrayList<Integer> personIds) {
parameterArray.add(locationRecord);
paramTypeArray.add(Types.VARCHAR);
if (personIds != null) {
if (!personIds.isEmpty()) {
for (Object next : personIds) {
parameterArray.add(next);
paramTypeArray.add(Types.INTEGER);
}
} else {
parameterArray.add(0);
paramTypeArray.add(Types.INTEGER);
}
} else {
parameterArray.add(0);
paramTypeArray.add(Types.INTEGER);
}
}
/**
* @param currentPersonId
*/
void selectPatientRecordsQuery(int currentPersonId) {
parameterArray.add(locationRecord);
paramTypeArray.add(Types.VARCHAR);
parameterArray.add(currentPersonId);
paramTypeArray.add(Types.INTEGER);
}
/**
* Select the general exam record data and the Haiti exam record data for the selected record
* ID
*
* @param examRecordId the record ID for the current exam record
*/
void selectHaitiExamRecordQuery(int examRecordId) {
parameterArray.add(examRecordId);
paramTypeArray.add(Types.INTEGER);
}
/**
* Select the general exam record data and the default location exam record data for the
* selected record ID
*
* @param examRecordId the record ID for the current exam record
*/
void selectExamRecordQuery(int examRecordId) {
parameterArray.add(examRecordId);
paramTypeArray.add(Types.INTEGER);
}
/**
* @param examFirstName
* @param examLastName
* @param examDOB
* @param examSex
* @param examDischarged
* @param currentTriage
* @param examPersonId
*/
void updateBasicQuery(
String examFirstName, String examLastName, LocalDate examDOB, String examSex,
boolean examDischarged, String currentTriage, int examPersonId) {
parameterArray.add(examFirstName);
paramTypeArray.add(Types.VARCHAR);
parameterArray.add(examLastName);
paramTypeArray.add(Types.VARCHAR);
java.sql.Date examDOBSql = DateTimeUtils.toSqlDate(examDOB);
parameterArray.add(examDOBSql);
paramTypeArray.add(Types.DATE);
parameterArray.add(examSex);
paramTypeArray.add(Types.VARCHAR);
parameterArray.add(examDischarged);
paramTypeArray.add(Types.BIT);
parameterArray.add(currentTriage);
paramTypeArray.add(Types.VARCHAR);
parameterArray.add(examPersonId);
paramTypeArray.add(Types.INTEGER);
}
/**
* @param examTriage
* @param examDateOfVisit
* @param examChartNumber
* @param examBodyTemperature
* @param examDiastolicBP
* @param examSystolicBP
* @param examHeight
* @param examWeight
* @param examBMI
* @param examOtherHistory
* @param examDiet
* @param examChiefComplaint
* @param examHistPresentIll
* @param examAssessment
* @param examPhysicalExam
* @param examTreatmentPlan
* @param examClinicianFirst
* @param examClinicianLast
* @param examPrescription
* @param examSignature
* @param examRecordId
*/
void updateExamRecordQuery(
String examTriage, LocalDate examDateOfVisit, Integer examChartNumber,
Float examBodyTemperature, Integer examDiastolicBP, Integer examSystolicBP, Integer examHeight, Integer examWeight,
Float examBMI, String examOtherHistory, String examDiet, String examChiefComplaint,
String examHistPresentIll, String examAssessment, String examPhysicalExam, String examTreatmentPlan, String examClinicianFirst,
String examClinicianLast, String examPrescription, String examSignature, String examLocationRecord,
int examRecordId) {
parameterArray.add(examTriage);
paramTypeArray.add(Types.VARCHAR);
java.sql.Date examDateOfVisitSql = DateTimeUtils.toSqlDate(examDateOfVisit);
parameterArray.add(examDateOfVisitSql);
paramTypeArray.add(Types.DATE);
parameterArray.add(examChartNumber);
paramTypeArray.add(Types.INTEGER);
parameterArray.add(examBodyTemperature);
paramTypeArray.add(Types.DECIMAL);
parameterArray.add(examDiastolicBP);
paramTypeArray.add(Types.INTEGER);
parameterArray.add(examSystolicBP);
paramTypeArray.add(Types.INTEGER);
parameterArray.add(examHeight);
paramTypeArray.add(Types.INTEGER);
parameterArray.add(examWeight);
paramTypeArray.add(Types.INTEGER);
parameterArray.add(examBMI);
paramTypeArray.add(Types.DECIMAL);
parameterArray.add(examOtherHistory);
paramTypeArray.add(Types.VARCHAR);
parameterArray.add(examDiet);
paramTypeArray.add(Types.VARCHAR);
parameterArray.add(examChiefComplaint);
paramTypeArray.add(Types.VARCHAR);
parameterArray.add(examHistPresentIll);
paramTypeArray.add(Types.VARCHAR);
parameterArray.add(examAssessment);
paramTypeArray.add(Types.VARCHAR);
parameterArray.add(examPhysicalExam);
paramTypeArray.add(Types.VARCHAR);
parameterArray.add(examTreatmentPlan);
paramTypeArray.add(Types.VARCHAR);
parameterArray.add(examClinicianFirst);
paramTypeArray.add(Types.VARCHAR);
parameterArray.add(examClinicianLast);
paramTypeArray.add(Types.VARCHAR);
parameterArray.add(examPrescription);
paramTypeArray.add(Types.VARCHAR);
parameterArray.add(examSignature);
paramTypeArray.add(Types.VARCHAR);
parameterArray.add(examLocationRecord);
paramTypeArray.add(Types.VARCHAR);
parameterArray.add(examRecordId);
paramTypeArray.add(Types.INTEGER);
}
/**
* @param examVillage
* @param examHemoglobin
* @param examDmDx
* @param examETOH
* @param examHTNDx
* @param examFamilyHxDm
* @param examFamilyHxHTN
* @param examFamilyHxStroke
* @param examPolydipsia
* @param examPolyphagia
* @param examPolyuria
* @param examSmoker
* @param examStroke
* @param examAmountOfMaggi
* @param examRecordId
*/
void updateHaitiExamRecordQuery(String examVillage, Integer examHemoglobin, Boolean examDmDx, Boolean examETOH,
Boolean examFamilyHxDm, Boolean examFamilyHxHTN, Boolean examFamilyHxStroke, Boolean examHTNDx,
Boolean examPolydipsia, Boolean examPolyphagia, Boolean examPolyuria, Boolean examSmoker,
Boolean examStroke, Integer examAmountOfMaggi, int examRecordId) {
parameterArray.add(examVillage);
paramTypeArray.add(Types.VARCHAR);
parameterArray.add(examHemoglobin);
paramTypeArray.add(Types.INTEGER);
parameterArray.add(examDmDx);
paramTypeArray.add(Types.BIT);
parameterArray.add(examETOH);
paramTypeArray.add(Types.BIT);
parameterArray.add(examFamilyHxDm);
paramTypeArray.add(Types.BIT);
parameterArray.add(examFamilyHxHTN);
paramTypeArray.add(Types.BIT);
parameterArray.add(examFamilyHxStroke);
paramTypeArray.add(Types.BIT);
parameterArray.add(examHTNDx);
paramTypeArray.add(Types.BIT);
parameterArray.add(examPolydipsia);
paramTypeArray.add(Types.BIT);
parameterArray.add(examPolyphagia);
paramTypeArray.add(Types.BIT);
parameterArray.add(examPolyuria);
paramTypeArray.add(Types.BIT);
parameterArray.add(examSmoker);
paramTypeArray.add(Types.BIT);
parameterArray.add(examStroke);
paramTypeArray.add(Types.BIT);
parameterArray.add(examAmountOfMaggi);
paramTypeArray.add(Types.INTEGER);
parameterArray.add(examRecordId);
paramTypeArray.add(Types.INTEGER);
}
/**
* Written so that makeHaitiRecord and makeDefaultRecord can be called to add to
* the queryString, parameterArray, and paramTypeArray variables.
*
* @param examPersonID
* @param examTriage
* @param examDateOfVisit
* @param examChartNumber
* @param examBodyTemperature
* @param examDiastolicBP
* @param examSystolicBP
* @param examHeight
* @param examWeight
* @param examBMI
* @param examOtherHistory
* @param examDiet
* @param examChiefComplaint
* @param examHistPresentIll
* @param examAssessment
* @param examPhysicalExam
* @param examTreatmentPlan
* @param examClinicianFirst
* @param examClinicianLast
* @param examPrescription
* @param examSignature
* @param examLocationRecord
*/
void makeExamRecordQuery(Integer examPersonID, String examTriage, LocalDate examDateOfVisit, Integer examChartNumber,
Float examBodyTemperature, Integer examDiastolicBP, Integer examSystolicBP, Integer examHeight, Integer examWeight,
Float examBMI, String examOtherHistory, String examDiet, String examChiefComplaint,
String examHistPresentIll, String examAssessment, String examPhysicalExam, String examTreatmentPlan, String examClinicianFirst,
String examClinicianLast, String examPrescription, String examSignature, String examLocationRecord) {
parameterArray.add(examPersonID);
paramTypeArray.add(Types.INTEGER);
parameterArray.add(examPersonID);
paramTypeArray.add(Types.INTEGER);
parameterArray.add(examTriage);
paramTypeArray.add(Types.VARCHAR);
java.sql.Date examDateOfVisitSql = DateTimeUtils.toSqlDate(examDateOfVisit);
parameterArray.add(examDateOfVisitSql);
paramTypeArray.add(Types.DATE);
parameterArray.add(examChartNumber);
paramTypeArray.add(Types.INTEGER);
parameterArray.add(examBodyTemperature);
paramTypeArray.add(Types.DECIMAL);
parameterArray.add(examDiastolicBP);
paramTypeArray.add(Types.INTEGER);
parameterArray.add(examSystolicBP);
paramTypeArray.add(Types.INTEGER);
parameterArray.add(examHeight);
paramTypeArray.add(Types.INTEGER);
parameterArray.add(examWeight);
paramTypeArray.add(Types.INTEGER);
parameterArray.add(examBMI);
paramTypeArray.add(Types.DECIMAL);
parameterArray.add(examOtherHistory);
paramTypeArray.add(Types.VARCHAR);
parameterArray.add(examDiet);
paramTypeArray.add(Types.VARCHAR);
parameterArray.add(examChiefComplaint);
paramTypeArray.add(Types.VARCHAR);
parameterArray.add(examHistPresentIll);
paramTypeArray.add(Types.VARCHAR);
parameterArray.add(examAssessment);
paramTypeArray.add(Types.VARCHAR);
parameterArray.add(examPhysicalExam);
paramTypeArray.add(Types.VARCHAR);
parameterArray.add(examTreatmentPlan);
paramTypeArray.add(Types.VARCHAR);
parameterArray.add(examClinicianFirst);
paramTypeArray.add(Types.VARCHAR);
parameterArray.add(examClinicianLast);
paramTypeArray.add(Types.VARCHAR);
parameterArray.add(examPrescription);
paramTypeArray.add(Types.VARCHAR);
parameterArray.add(examSignature);
paramTypeArray.add(Types.VARCHAR);
parameterArray.add(examLocationRecord);
paramTypeArray.add(Types.VARCHAR);
}
/**
* Written to be called after makeExamRecordQuery or makeBothRecords to add
* specific record location query information to the queryString,
* parameterArray, and paramTypeArray variables.
*
* @param examVillage
* @param examHemoglobin
* @param examHTNDx
* @param examDmDx
* @param examStroke
* @param examFamilyHxHTN
* @param examFamilyHxDm
* @param examFamilyHxStroke
* @param examPolyphagia
* @param examPolydipsia
* @param examPolyuria
* @param examSmoker
* @param examETOH
* @param examAmountOfMaggi
*/
void makeHaitiRecordQuery(String examVillage, Integer examHemoglobin, Boolean examDmDx, Boolean examETOH,
Boolean examFamilyHxDm, Boolean examFamilyHxHTN, Boolean examFamilyHxStroke, Boolean examHTNDx,
Boolean examPolydipsia, Boolean examPolyphagia, Boolean examPolyuria, Boolean examSmoker,
Boolean examStroke, Integer examAmountOfMaggi) {
parameterArray.add(examVillage);
paramTypeArray.add(Types.VARCHAR);
parameterArray.add(examHemoglobin);
paramTypeArray.add(Types.INTEGER);
parameterArray.add(examDmDx);
paramTypeArray.add(Types.BIT);
parameterArray.add(examETOH);
paramTypeArray.add(Types.BIT);
parameterArray.add(examFamilyHxDm);
paramTypeArray.add(Types.BIT);
parameterArray.add(examFamilyHxHTN);
paramTypeArray.add(Types.BIT);
parameterArray.add(examFamilyHxStroke);
paramTypeArray.add(Types.BIT);
parameterArray.add(examHTNDx);
paramTypeArray.add(Types.BIT);
parameterArray.add(examPolydipsia);
paramTypeArray.add(Types.BIT);
parameterArray.add(examPolyphagia);
paramTypeArray.add(Types.BIT);
parameterArray.add(examPolyuria);
paramTypeArray.add(Types.BIT);
parameterArray.add(examSmoker);
paramTypeArray.add(Types.BIT);
parameterArray.add(examStroke);
paramTypeArray.add(Types.BIT);
parameterArray.add(examAmountOfMaggi);
paramTypeArray.add(Types.INTEGER);
}
/**
* @param examFirstName
* @param examLastName
* @param examDOB
* @param examSex
* @param examTriage
* @param examDateOfVisit
* @param examChartNumber
* @param examBodyTemperature
* @param examDiastolicBP
* @param examSystolicBP
* @param examHeight
* @param examWeight
* @param examBMI
* @param examOtherHistory
* @param examDiet
* @param examChiefComplaint
* @param examHistPresentIll
* @param examAssessment
* @param examPhysicalExam
* @param examTreatmentPlan
* @param examClinicianFirst
* @param examClinicianLast
* @param examPrescription
* @param examSignature
* @param examLocationRecord
*/
void makeBothRecordsQuery(String examFirstName, String examLastName, LocalDate examDOB, String examSex, Boolean examDischarged,
String examCurrentTriage, String examTriage, LocalDate examDateOfVisit, Integer examChartNumber, Float examBodyTemperature,
Integer examDiastolicBP, Integer examSystolicBP, Integer examHeight, Integer examWeight, Float examBMI,
String examOtherHistory, String examDiet, String examChiefComplaint, String examHistPresentIll,
String examAssessment, String examPhysicalExam, String examTreatmentPlan, String examClinicianFirst, String examClinicianLast,
String examPrescription, String examSignature, String examLocationRecord) {
parameterArray.add(examFirstName);
paramTypeArray.add(Types.VARCHAR);
parameterArray.add(examLastName);
paramTypeArray.add(Types.VARCHAR);
java.sql.Date examDOBSql = DateTimeUtils.toSqlDate(examDOB);
parameterArray.add(examDOBSql);
paramTypeArray.add(Types.DATE);
parameterArray.add(examSex);
paramTypeArray.add(Types.VARCHAR);
parameterArray.add(examDischarged);
paramTypeArray.add(Types.BIT);
parameterArray.add(examCurrentTriage);
paramTypeArray.add(Types.VARCHAR);
parameterArray.add(examTriage);
paramTypeArray.add(Types.VARCHAR);
java.sql.Date examDateOfVisitSql = DateTimeUtils.toSqlDate(examDateOfVisit);
parameterArray.add(examDateOfVisitSql);
paramTypeArray.add(Types.DATE);
parameterArray.add(examChartNumber);
paramTypeArray.add(Types.INTEGER);
parameterArray.add(examBodyTemperature);
paramTypeArray.add(Types.DECIMAL);
parameterArray.add(examDiastolicBP);
paramTypeArray.add(Types.INTEGER);
parameterArray.add(examSystolicBP);
paramTypeArray.add(Types.INTEGER);
parameterArray.add(examHeight);
paramTypeArray.add(Types.INTEGER);
parameterArray.add(examWeight);
paramTypeArray.add(Types.INTEGER);
parameterArray.add(examBMI);
paramTypeArray.add(Types.DECIMAL);
parameterArray.add(examOtherHistory);
paramTypeArray.add(Types.VARCHAR);
parameterArray.add(examDiet);
paramTypeArray.add(Types.VARCHAR);
parameterArray.add(examChiefComplaint);
paramTypeArray.add(Types.VARCHAR);
parameterArray.add(examHistPresentIll);
paramTypeArray.add(Types.VARCHAR);
parameterArray.add(examAssessment);
paramTypeArray.add(Types.VARCHAR);
parameterArray.add(examPhysicalExam);
paramTypeArray.add(Types.VARCHAR);
parameterArray.add(examTreatmentPlan);
paramTypeArray.add(Types.VARCHAR);
parameterArray.add(examClinicianFirst);
paramTypeArray.add(Types.VARCHAR);
parameterArray.add(examClinicianLast);
paramTypeArray.add(Types.VARCHAR);
parameterArray.add(examPrescription);
paramTypeArray.add(Types.VARCHAR);
parameterArray.add(examSignature);
paramTypeArray.add(Types.VARCHAR);
parameterArray.add(examLocationRecord);
paramTypeArray.add(Types.VARCHAR);
}
/**
* <p>
* Inserts a thumbnail and an encoding of an image received from facial recognition into a
* newly created record
*
* @param bitmap an image stored as a byte array containing a thumbnail bitmap of the patient
* @param currentEncoding the image encoding array received from facial recognition
*/
void makeImageRecordQuery(byte[] bitmap, ArrayList<Double> currentEncoding) {
parameterArray.add(bitmap);
paramTypeArray.add(Types.VARBINARY);
if(currentEncoding!=null) {
if(!currentEncoding.isEmpty()) {
for (int count = 0; count < 128; count++) {
parameterArray.add(currentEncoding.get(count));
paramTypeArray.add(Types.DOUBLE);
}
}else{
for (int count = 0; count < 128; count++) {
parameterArray.add(null);
paramTypeArray.add(Types.DOUBLE);
}
}
}else{
for (int count = 0; count < 128; count++) {
parameterArray.add(null);
paramTypeArray.add(Types.DOUBLE);
}
}
}
/**
* @param username
* @param password
*/
void getLogin(String username, String password) {
parameterArray.add(username);
paramTypeArray.add(Types.VARCHAR);
parameterArray.add(password);
paramTypeArray.add(Types.VARCHAR);
}
/**
* @param firstName
* @param lastName
* @param username
* @param password
* @param location
* @param privileges
*/
void setLogin(String firstName, String lastName, String username, String password, String location, boolean privileges) {
parameterArray.add(firstName);
paramTypeArray.add(Types.VARCHAR);
parameterArray.add(lastName);
paramTypeArray.add(Types.VARCHAR);
parameterArray.add(username);
paramTypeArray.add(Types.VARCHAR);
parameterArray.add(password);
paramTypeArray.add(Types.VARCHAR);
parameterArray.add(location);
paramTypeArray.add(Types.VARCHAR);
parameterArray.add(privileges);
paramTypeArray.add(Types.BIT);
}
}
|
3e1eed748894c8e0d0f24bcb0aff3ccdb2520e8b | 2,363 | java | Java | Gangbb-SpringBoot-Swagger/src/main/java/com/gangbb/gangbbspringbootswagger/config/SwaggerConfig.java | Gang-bb/Gangbb-SpringBoot | a0964364defce0723daa288f4b4b8704576fbe57 | [
"MIT"
] | 190 | 2021-01-24T13:23:28.000Z | 2021-07-09T03:53:38.000Z | Gangbb-SpringBoot-Swagger/src/main/java/com/gangbb/gangbbspringbootswagger/config/SwaggerConfig.java | Gang-bb/Gangbb-SpringBoot | a0964364defce0723daa288f4b4b8704576fbe57 | [
"MIT"
] | null | null | null | Gangbb-SpringBoot-Swagger/src/main/java/com/gangbb/gangbbspringbootswagger/config/SwaggerConfig.java | Gang-bb/Gangbb-SpringBoot | a0964364defce0723daa288f4b4b8704576fbe57 | [
"MIT"
] | 4 | 2021-02-03T03:32:22.000Z | 2022-01-15T01:05:29.000Z | 36.338462 | 97 | 0.682472 | 13,071 | package com.gangbb.gangbbspringbootswagger.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* @author : Gangbb
* @ClassName : SwaggerConfig
* @Description :
* @Date : 2021/1/24 9:47
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket docket1() {
return new Docket(DocumentationType.SWAGGER_2).groupName("group1");
}
@Bean
public Docket docket2() {
return new Docket(DocumentationType.SWAGGER_2).groupName("group2");
}
@Bean
public Docket docket3() {
return new Docket(DocumentationType.SWAGGER_2).groupName("group3");
}
@Bean
public Docket api(Environment environment) {
//设置要显示的Swagger环境
Profiles profiles = Profiles.of("dev", "test");
//获取项目环境:是生产环境还是发布环境
boolean flag = environment.acceptsProfiles(profiles);
return new Docket(DocumentationType.SWAGGER_2) // 指定api类型为swagger2
.apiInfo(apiInfo()) // 用于定义api文档汇总信息
.groupName("api")
.enable(flag)//是否启用swagger,如果为false则swagger不能再浏览器中访问
.select() //通过select()方法配置扫描接口,RequestHandlerSelectors配置如何扫描接口
.apis(RequestHandlerSelectors.any()) // 指定扫描的controller包
.paths(PathSelectors.any()) //通过paths()方法配置扫描接口,PathSelectors配置如何扫描接口
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Gangbb Swagger API")
.description("Gangbb 的 Swagger UI")
.contact(new Contact("Gangbb", "http://xxx.xxx.com/联系人访问链接", "dycjh@example.com"))
.version("1.0.0")
.termsOfServiceUrl("") // 网站地址
.build();
}
}
|
3e1eee2f96280f1d3e8ce5b1d91ee9a0f4fae99a | 1,252 | java | Java | src/main/lee/code/code_300__Longest_Increasing_Subsequence/C300_MainClass.java | code543/leetcodequestions | 44cbfe6718ada04807b6600a5d62b9f0016d4ab2 | [
"MIT"
] | 1 | 2019-02-23T06:47:17.000Z | 2019-02-23T06:47:17.000Z | src/main/lee/code/code_300__Longest_Increasing_Subsequence/C300_MainClass.java | code543/leetcodequestions | 44cbfe6718ada04807b6600a5d62b9f0016d4ab2 | [
"MIT"
] | null | null | null | src/main/lee/code/code_300__Longest_Increasing_Subsequence/C300_MainClass.java | code543/leetcodequestions | 44cbfe6718ada04807b6600a5d62b9f0016d4ab2 | [
"MIT"
] | null | null | null | 28.454545 | 75 | 0.56869 | 13,072 | package lee.code.code_300__Longest_Increasing_Subsequence;
import java.util.*;
import lee.util.*;
import java.io.*;
import com.eclipsesource.json.*;
import java.text.*;
public class C300_MainClass {
public static String testCase = "[10,9,2,5,3,7,101,18]";
/*
public static int[] Utils.stringToIntegerArray(String input) {
input = input.trim();
input = input.substring(1, input.length() - 1);
if (input.length() == 0) {
return new int[0];
}
String[] parts = input.split(",");
int[] output = new int[parts.length];
for(int index = 0; index < parts.length; index++) {
String part = parts[index].trim();
output[index] = Integer.parseInt(part);
}
return output;
}
*/
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new StringReader(testCase));
String line;
while ((line = in.readLine()) != null) {
int[] nums = Utils.stringToIntegerArray(line);
int ret = new Solution().lengthOfLIS(nums);
String out = String.valueOf(ret);
System.out.print(out);
}
}
}
|
3e1eeeb2d4d8167312b79755fe4d064bde7bff47 | 263 | java | Java | src/main/java/io/github/panxiaochao/App.java | panxiaochao/pxc-jwt-commons-spring-boot-starter | c5224ac6e1e612616752957aa3251269e1188f16 | [
"MIT"
] | null | null | null | src/main/java/io/github/panxiaochao/App.java | panxiaochao/pxc-jwt-commons-spring-boot-starter | c5224ac6e1e612616752957aa3251269e1188f16 | [
"MIT"
] | null | null | null | src/main/java/io/github/panxiaochao/App.java | panxiaochao/pxc-jwt-commons-spring-boot-starter | c5224ac6e1e612616752957aa3251269e1188f16 | [
"MIT"
] | null | null | null | 20.230769 | 68 | 0.642586 | 13,073 | package io.github.panxiaochao;
/**
* @author Mr_LyPxc
* @title: App
* @description: TODO
* @date 2021/12/17 21:42
*/
public class App {
public static void main(String[] args) {
System.out.println("pxc-jwt-commons-spring-boot-starter !");
}
} |
3e1eefc9a0ff8b4845d2e633ba8acebbb573ada5 | 4,989 | java | Java | src/extends-parent/jetty-all/src/main/java/org/apache/jasper/compiler/JspProperty.java | ivanDannels/hasor | 3b9f4ae6355c6dad2ea8818750b3e04e90cc3e39 | [
"Apache-2.0"
] | 1 | 2018-12-03T09:07:44.000Z | 2018-12-03T09:07:44.000Z | src/extends-parent/jetty-all/src/main/java/org/apache/jasper/compiler/JspProperty.java | ivanDannels/hasor | 3b9f4ae6355c6dad2ea8818750b3e04e90cc3e39 | [
"Apache-2.0"
] | null | null | null | src/extends-parent/jetty-all/src/main/java/org/apache/jasper/compiler/JspProperty.java | ivanDannels/hasor | 3b9f4ae6355c6dad2ea8818750b3e04e90cc3e39 | [
"Apache-2.0"
] | null | null | null | 33.938776 | 78 | 0.690319 | 13,074 | /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can
* obtain a copy of the License at
* https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html
* or packager/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at packager/legal/LICENSE.txt.
*
* GPL Classpath Exception:
* Oracle designates this particular file as subject to the "Classpath"
* exception as provided by Oracle in the GPL Version 2 section of the License
* file that accompanied this code.
*
* Modifications:
* If applicable, add the following below the License Header, with the fields
* enclosed by brackets [] replaced by your own identifying information:
* "Portions Copyright [year] [name of copyright owner]"
*
* Contributor(s):
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*
*
* This file incorporates work covered by the following copyright and
* permission notice:
*
* Copyright 2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.jasper.compiler;
import java.util.List;
public class JspProperty {
private String isXml;
private String elIgnored;
private String scriptingInvalid;
private String pageEncoding;
private String trimSpaces;
private String poundAllowed;
private List<String> includePrelude;
private List<String> includeCoda;
private String buffer;
private String defaultContentType;
private String errorOnUndeclaredNamespace;
public JspProperty(String isXml,
String elIgnored,
String scriptingInvalid,
String trimSpaces,
String poundAllowed,
String pageEncoding,
List<String> includePrelude,
List<String> includeCoda,
String defaultContentType,
String buffer,
String errorOnUndeclaredNamespace) {
this.isXml = isXml;
this.elIgnored = elIgnored;
this.scriptingInvalid = scriptingInvalid;
this.trimSpaces = trimSpaces;
this.poundAllowed = poundAllowed;
this.pageEncoding = pageEncoding;
this.includePrelude = includePrelude;
this.includeCoda = includeCoda;
this.defaultContentType = defaultContentType;
this.buffer = buffer;
this.errorOnUndeclaredNamespace = errorOnUndeclaredNamespace;
}
public String isXml() {
return isXml;
}
public String isELIgnored() {
return elIgnored;
}
public String isScriptingInvalid() {
return scriptingInvalid;
}
public String getPageEncoding() {
return pageEncoding;
}
public String getTrimSpaces() {
return trimSpaces;
}
public String getPoundAllowed() {
return poundAllowed;
}
public List<String> getIncludePrelude() {
return includePrelude;
}
public List<String> getIncludeCoda() {
return includeCoda;
}
public String getBuffer() {
return buffer;
}
public String getDefaultContentType() {
return defaultContentType;
}
public String errorOnUndeclaredNamespace() {
return errorOnUndeclaredNamespace;
}
}
|
3e1ef01d282ed2b88e44067177e80ac49ae5b8d4 | 3,956 | java | Java | spring-cloud-framework/common-util/src/main/java/com/markyang/framework/util/ValidationUtils.java | markyangchangliang/framework | 273232608f2589ec7e1650063366647e715bfa35 | [
"Apache-2.0"
] | 9 | 2020-12-24T14:38:06.000Z | 2021-04-14T06:55:29.000Z | spring-cloud-framework/common-util/src/main/java/com/markyang/framework/util/ValidationUtils.java | markyangchangliang/framework | 273232608f2589ec7e1650063366647e715bfa35 | [
"Apache-2.0"
] | 1 | 2021-03-26T06:42:51.000Z | 2021-03-26T06:42:51.000Z | spring-cloud-framework/common-util/src/main/java/com/markyang/framework/util/ValidationUtils.java | markyangchangliang/framework | 273232608f2589ec7e1650063366647e715bfa35 | [
"Apache-2.0"
] | null | null | null | 30.198473 | 115 | 0.617543 | 13,075 | package com.markyang.framework.util;
import com.baomidou.mybatisplus.annotation.TableId;
import com.markyang.framework.util.exception.UtilException;
import com.markyang.framework.pojo.common.support.FrameworkEnum;
import com.markyang.framework.pojo.entity.BaseEntity;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.ConcurrentReferenceHashMap;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Supplier;
/**
* 验证工具类
* @author yangchangliang
*/
public final class ValidationUtils {
/**
* 缓存表单类主键字段
*/
private static final Map<Class<?>, Field> CLASS_ID_FIELD_CACHE = new ConcurrentReferenceHashMap<>(128);
/**
* 判断对象是否为零(无意义)
* @param object 对象
* @return bool
*/
public static boolean isNil(Object object) {
// 如果是bool
if (object instanceof Boolean) {
return BooleanUtils.isFalse((Boolean) object);
}
// 如果是字符序列
if (object instanceof CharSequence) {
return StringUtils.isBlank((CharSequence) object);
}
// 如果是集合
if (object instanceof Collection) {
return CollectionUtils.isEmpty((Collection<?>) object);
}
// 如果是对象
return Objects.isNull(object);
}
/**
* 判断两个值是否相等
* @param object 对象
* @param value 值
* @return bool
*/
public static boolean equals(Object object, String value) {
if (object instanceof FrameworkEnum) {
return Objects.equals(((FrameworkEnum) object).getValue(), value);
} else if (object instanceof Number) {
Double a = ((Number) object).doubleValue();
try {
Double b = Double.parseDouble(value);
return Objects.equals(a, b);
} catch (NumberFormatException e) {
return false;
}
} else if (object instanceof Boolean) {
return StringUtils.equalsIgnoreCase(((Boolean) object).toString(), value);
}
return Objects.equals(object, value);
}
/**
* 判断是否是合法的手机号
* @param phone 手机号码
* @return bool
*/
public static boolean isValidPhone(String phone) {
if (phone == null) {
return true;
}
return phone.matches("^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|19[0-9]|14[57])[0-9]{8}$");
}
/**
* 验证一个数据是否存在
* @param supplier 实体提供器
* @param tip 提示信息
* @param <E> 实体类泛型
* @param <ID> 实体类主键泛型
* @return 实体对象
*/
public static <E extends BaseEntity, ID> E exists(Supplier<Optional<E>> supplier, String tip) {
Optional<E> optional = supplier.get();
if (!optional.isPresent()) {
throw new UtilException(tip);
}
return optional.get();
}
/**
* 获取一个类中的主键字段
* @param clazz 类
* @return 主键字段
*/
public static Optional<Field> getIdField(Class<?> clazz) {
if (CLASS_ID_FIELD_CACHE.containsKey(clazz)) {
return Optional.of(CLASS_ID_FIELD_CACHE.get(clazz));
} else {
Optional<Field> idFieldOptional = ReflectionOperationUtils.getAnnotatedField(clazz, TableId.class);
idFieldOptional.ifPresent(field -> CLASS_ID_FIELD_CACHE.put(clazz, field));
return idFieldOptional;
}
}
/**
* 获取ID值
* @param target 目标对象
* @return optional结果
*/
public static Optional<Object> getIdValue(Object target) {
Optional<Field> idFieldOptional = getIdField(target.getClass());
if (!idFieldOptional.isPresent()) {
return Optional.empty();
}
return ReflectionOperationUtils.getFieldValue(idFieldOptional.get(), target);
}
}
|
3e1ef0beb05c001f029945bc07094950b1d212e3 | 5,843 | java | Java | tony-azkaban/src/test/java/com/linkedin/tony/azkaban/TestTonyJob.java | nevesnunes/TonY | c2b67f76765458ad570c2f7616a2df2b8e140ba5 | [
"BSD-2-Clause"
] | 645 | 2018-09-13T03:51:08.000Z | 2021-07-28T14:46:38.000Z | tony-azkaban/src/test/java/com/linkedin/tony/azkaban/TestTonyJob.java | nevesnunes/TonY | c2b67f76765458ad570c2f7616a2df2b8e140ba5 | [
"BSD-2-Clause"
] | 365 | 2018-09-17T19:58:03.000Z | 2021-08-13T06:02:12.000Z | tony-azkaban/src/test/java/com/linkedin/tony/azkaban/TestTonyJob.java | nevesnunes/TonY | c2b67f76765458ad570c2f7616a2df2b8e140ba5 | [
"BSD-2-Clause"
] | 166 | 2018-09-13T14:51:13.000Z | 2021-08-12T13:25:19.000Z | 38.189542 | 114 | 0.721205 | 13,076 | /**
* Copyright 2018 LinkedIn Corporation. All rights reserved. Licensed under the BSD-2 Clause license.
* See LICENSE in the project root for license information.
*/
package com.linkedin.tony.azkaban;
import azkaban.flow.CommonJobProperties;
import azkaban.utils.FileIOUtils;
import azkaban.utils.Props;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import java.io.File;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.io.FilenameUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.log4j.Logger;
import org.testng.Assert;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import static azkaban.ServiceProvider.SERVICE_PROVIDER;
public class TestTonyJob {
private final Logger log = Logger.getLogger(TestTonyJob.class);
// Taken from azkaban.test.Utils in azkaban-common.
private static void initServiceProvider() {
final Injector injector = Guice.createInjector(new AbstractModule() {
@Override
protected void configure() { }
});
// Because SERVICE_PROVIDER is a singleton and it is shared among many tests,
// need to reset the state to avoid assertion failures.
SERVICE_PROVIDER.unsetInjector();
SERVICE_PROVIDER.setInjector(injector);
}
@BeforeTest
public void setup() {
initServiceProvider();
}
@Test
public void testMainArguments() {
final String azkabanInputDatasetJobProp = "azkaban.input.dataset";
final String azkabanOutputDatasetJobProp = "azkaban.output.dataset";
final String azkabanInputDatasetEnvVarKey = "AZKABAN_INPUT_DATASET";
final String azkabanOutputDatasetEnvVarKey = "AZKABAN_OUTPUT_DATASET";
final Props jobProps = new Props();
jobProps.put(TonyJobArg.HDFS_CLASSPATH.azPropName, "hdfs://nn:8020");
jobProps.put(azkabanInputDatasetJobProp,
"HDFS_DYNAMIC_PATH:input_ds:/jobs/azktest/gsalia_tony/192/input_ds_job1");
jobProps.put(azkabanOutputDatasetJobProp,
"HDFS_DYNAMIC_PATH:output_ds:/jobs/azktest/gsalia_tony/192/output_ds_job1");
jobProps.put(TonyJob.WORKER_ENV_PREFIX + "E1", "e1");
jobProps.put(TonyJob.WORKER_ENV_PREFIX + "E2", "e2");
final TonyJob tonyJob = new TonyJob("test_tony_job", new Props(), jobProps, log) {
@Override
public String getWorkingDirectory() {
return System.getProperty("java.io.tmpdir");
}
};
String args = tonyJob.getMainArguments();
Assert.assertTrue(args.contains(TonyJobArg.HDFS_CLASSPATH.tonyParamName + " hdfs://nn:8020"));
Assert.assertTrue(args.contains(TonyJobArg.SHELL_ENV.tonyParamName
+ " " + azkabanInputDatasetEnvVarKey
+ "='HDFS_DYNAMIC_PATH:input_ds:/jobs/azktest/gsalia_tony/192/input_ds_job1'"));
Assert.assertTrue(args.contains(TonyJobArg.SHELL_ENV.tonyParamName
+ " " + azkabanOutputDatasetEnvVarKey
+ "='HDFS_DYNAMIC_PATH:output_ds:/jobs/azktest/gsalia_tony/192/output_ds_job1'"));
Assert.assertTrue(args.contains(TonyJobArg.SHELL_ENV.tonyParamName + " E2=e2"));
Assert.assertTrue(args.contains(TonyJobArg.SHELL_ENV.tonyParamName + " E1=e1"));
}
/**
* Check if the flow level information is passed to the tony job through configuration.
*/
@Test
public void testFlowInfoPropagation() {
final Props jobProps = new Props();
jobProps.put(TonyJobArg.HDFS_CLASSPATH.azPropName, "hdfs://nn:8020");
jobProps.put(CommonJobProperties.PROJECT_NAME, "unit_test");
jobProps.put(CommonJobProperties.FLOW_ID, "1");
jobProps.put(CommonJobProperties.EXEC_ID, "0");
jobProps.put(TonyJob.AZKABAN_WEB_HOST, "localhost");
final TonyJob tonyJob = new TonyJob("test_tony_job", new Props(), jobProps, log) {
@Override
public String getWorkingDirectory() {
return System.getProperty("java.io.tmpdir");
}
};
Configuration conf = tonyJob.getTonyJobConf();
Set<String> values = new HashSet<>(
conf.getStringCollection(TonyJob.TONY_APPLICATION_TAGS));
values.remove("");
Map<String, String> parsedTags = new HashMap<>();
for (String value : values) {
String[] pair = value.split(":");
Assert.assertTrue(pair.length == 2);
parsedTags.put(pair[0], pair[1]);
}
Assert.assertEquals(parsedTags.get(CommonJobProperties.EXEC_ID), "0");
Assert.assertEquals(parsedTags.get(CommonJobProperties.FLOW_ID), "1");
Assert.assertEquals(parsedTags.get(CommonJobProperties.PROJECT_NAME), "unit_test");
Assert.assertEquals(parsedTags.get(TonyJob.AZKABAN_WEB_HOST), "localhost");
}
@Test
public void testClassPaths() {
final Props sysProps = new Props();
final Props jobProps = new Props();
jobProps.put(TonyJob.WORKING_DIR, FilenameUtils.getFullPath(FileIOUtils.getSourcePathFromClass(Props.class)));
sysProps.put("jobtype.classpath", "123,456,789");
sysProps.put("plugin.dir", "Plugins");
final TonyJob tonyJob = new TonyJob("test_tony_job_class_path", sysProps, jobProps, log) {
@Override
public String getWorkingDirectory() {
return System.getProperty("java.io.tmpdir");
}
};
List<String> paths = tonyJob.getClassPaths();
int counter = 0;
String tonyConfigPath = new File(tonyJob.getWorkingDirectory(), "_tony-conf"
+ "-test_tony_job_class_path").toString();
boolean hasTonYConfigInClassPath = false;
for (String path : paths) {
if (path.contains("Plugins/123") || path.contains("Plugins/456") || path.contains("Plugins/789")) {
counter += 1;
} else if (path.startsWith(tonyConfigPath)) {
hasTonYConfigInClassPath = true;
}
}
Assert.assertTrue(counter == 3);
Assert.assertTrue(hasTonYConfigInClassPath);
}
}
|
3e1ef10f0360f18f47736db4c162b6a353e0c345 | 7,716 | java | Java | app/src/main/java/com/haoyue/app/happyreader/bean/ImagesListEntity.java | xukg/HappyReader-master | 8de2e146ef922da2b3786cae7f8f59f09ebbbb1c | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/haoyue/app/happyreader/bean/ImagesListEntity.java | xukg/HappyReader-master | 8de2e146ef922da2b3786cae7f8f59f09ebbbb1c | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/haoyue/app/happyreader/bean/ImagesListEntity.java | xukg/HappyReader-master | 8de2e146ef922da2b3786cae7f8f59f09ebbbb1c | [
"Apache-2.0"
] | null | null | null | 24.651757 | 72 | 0.592146 | 13,077 | package com.haoyue.app.happyreader.bean;
import java.util.List;
public class ImagesListEntity {
private String id;
private String desc;
private List<String> tags;
private String fromPageTitle;
private String column;
private String date;
private String downloadUrl;
private String imageUrl;
private int imageWidth;
private int imageHeight;
private String thumbnailUrl;
private int thumbnailWidth;
private int thumbnailHeight;
private String thumbnailLargeUrl;
private int thumbnailLargeWidth;
private int thumbnailLargeHeight;
private String thumbnailLargeTnUrl;
private int thumbnailLargeTnWidth;
private int thumbnailLargeTnHeight;
private String siteName;
private String siteLogo;
private String siteUrl;
private String fromUrl;
private String objUrl;
private String shareUrl;
private String albumId;
private int isAlbum;
private String albumName;
private int albumNum;
private String title;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public List<String> getTags() {
return tags;
}
public void setTags(List<String> tags) {
this.tags = tags;
}
public String getFromPageTitle() {
return fromPageTitle;
}
public void setFromPageTitle(String fromPageTitle) {
this.fromPageTitle = fromPageTitle;
}
public String getColumn() {
return column;
}
public void setColumn(String column) {
this.column = column;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getDownloadUrl() {
return downloadUrl;
}
public void setDownloadUrl(String downloadUrl) {
this.downloadUrl = downloadUrl;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public int getImageWidth() {
return imageWidth;
}
public void setImageWidth(int imageWidth) {
this.imageWidth = imageWidth;
}
public int getImageHeight() {
return imageHeight;
}
public void setImageHeight(int imageHeight) {
this.imageHeight = imageHeight;
}
public String getThumbnailUrl() {
return thumbnailUrl;
}
public void setThumbnailUrl(String thumbnailUrl) {
this.thumbnailUrl = thumbnailUrl;
}
public int getThumbnailWidth() {
return thumbnailWidth;
}
public void setThumbnailWidth(int thumbnailWidth) {
this.thumbnailWidth = thumbnailWidth;
}
public int getThumbnailHeight() {
return thumbnailHeight;
}
public void setThumbnailHeight(int thumbnailHeight) {
this.thumbnailHeight = thumbnailHeight;
}
public String getThumbnailLargeUrl() {
return thumbnailLargeUrl;
}
public void setThumbnailLargeUrl(String thumbnailLargeUrl) {
this.thumbnailLargeUrl = thumbnailLargeUrl;
}
public int getThumbnailLargeWidth() {
return thumbnailLargeWidth;
}
public void setThumbnailLargeWidth(int thumbnailLargeWidth) {
this.thumbnailLargeWidth = thumbnailLargeWidth;
}
public int getThumbnailLargeHeight() {
return thumbnailLargeHeight;
}
public void setThumbnailLargeHeight(int thumbnailLargeHeight) {
this.thumbnailLargeHeight = thumbnailLargeHeight;
}
public String getThumbnailLargeTnUrl() {
return thumbnailLargeTnUrl;
}
public void setThumbnailLargeTnUrl(String thumbnailLargeTnUrl) {
this.thumbnailLargeTnUrl = thumbnailLargeTnUrl;
}
public int getThumbnailLargeTnWidth() {
return thumbnailLargeTnWidth;
}
public void setThumbnailLargeTnWidth(int thumbnailLargeTnWidth) {
this.thumbnailLargeTnWidth = thumbnailLargeTnWidth;
}
public int getThumbnailLargeTnHeight() {
return thumbnailLargeTnHeight;
}
public void setThumbnailLargeTnHeight(int thumbnailLargeTnHeight) {
this.thumbnailLargeTnHeight = thumbnailLargeTnHeight;
}
public String getSiteName() {
return siteName;
}
public void setSiteName(String siteName) {
this.siteName = siteName;
}
public String getSiteLogo() {
return siteLogo;
}
public void setSiteLogo(String siteLogo) {
this.siteLogo = siteLogo;
}
public String getSiteUrl() {
return siteUrl;
}
public void setSiteUrl(String siteUrl) {
this.siteUrl = siteUrl;
}
public String getFromUrl() {
return fromUrl;
}
public void setFromUrl(String fromUrl) {
this.fromUrl = fromUrl;
}
public String getObjUrl() {
return objUrl;
}
public void setObjUrl(String objUrl) {
this.objUrl = objUrl;
}
public String getShareUrl() {
return shareUrl;
}
public void setShareUrl(String shareUrl) {
this.shareUrl = shareUrl;
}
public String getAlbumId() {
return albumId;
}
public void setAlbumId(String albumId) {
this.albumId = albumId;
}
public int getIsAlbum() {
return isAlbum;
}
public void setIsAlbum(int isAlbum) {
this.isAlbum = isAlbum;
}
public String getAlbumName() {
return albumName;
}
public void setAlbumName(String albumName) {
this.albumName = albumName;
}
public int getAlbumNum() {
return albumNum;
}
public void setAlbumNum(int albumNum) {
this.albumNum = albumNum;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Override
public String toString() {
return "ImagesListEntity{" +
"id='" + id + '\'' +
", desc='" + desc + '\'' +
", tags=" + tags +
", fromPageTitle='" + fromPageTitle + '\'' +
", column='" + column + '\'' +
", date='" + date + '\'' +
", downloadUrl='" + downloadUrl + '\'' +
", imageUrl='" + imageUrl + '\'' +
", imageWidth=" + imageWidth +
", imageHeight=" + imageHeight +
", thumbnailUrl='" + thumbnailUrl + '\'' +
", thumbnailWidth=" + thumbnailWidth +
", thumbnailHeight=" + thumbnailHeight +
", thumbnailLargeUrl='" + thumbnailLargeUrl + '\'' +
", thumbnailLargeWidth=" + thumbnailLargeWidth +
", thumbnailLargeHeight=" + thumbnailLargeHeight +
", thumbnailLargeTnUrl='" + thumbnailLargeTnUrl + '\'' +
", thumbnailLargeTnWidth=" + thumbnailLargeTnWidth +
", thumbnailLargeTnHeight=" + thumbnailLargeTnHeight +
", siteName='" + siteName + '\'' +
", siteLogo='" + siteLogo + '\'' +
", siteUrl='" + siteUrl + '\'' +
", fromUrl='" + fromUrl + '\'' +
", objUrl='" + objUrl + '\'' +
", shareUrl='" + shareUrl + '\'' +
", albumId='" + albumId + '\'' +
", isAlbum=" + isAlbum +
", albumName='" + albumName + '\'' +
", albumNum=" + albumNum +
", title='" + title + '\'' +
'}';
}
}
|
3e1ef18c4e247e625652861b9289a5723a79c314 | 3,788 | java | Java | typesystem/src/main/java/org/apache/atlas/typesystem/types/AttributeInfo.java | SarahMehddi/HelloWorld | 800df29a9f6b87784c2ef412bb476b6ae21ddab2 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | typesystem/src/main/java/org/apache/atlas/typesystem/types/AttributeInfo.java | SarahMehddi/HelloWorld | 800df29a9f6b87784c2ef412bb476b6ae21ddab2 | [
"Apache-2.0",
"BSD-3-Clause"
] | 2 | 2020-02-12T19:39:35.000Z | 2020-07-15T21:31:24.000Z | typesystem/src/main/java/org/apache/atlas/typesystem/types/AttributeInfo.java | SarahMehddi/HelloWorld | 800df29a9f6b87784c2ef412bb476b6ae21ddab2 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | 39.051546 | 114 | 0.662355 | 13,078 | /**
* 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.atlas.typesystem.types;
import org.apache.atlas.AtlasException;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import java.util.Map;
public class AttributeInfo {
public final String name;
public final Multiplicity multiplicity;
//A composite is the one whose lifecycle is dependent on the enclosing type and is not just a reference
public final boolean isComposite;
public final boolean isUnique;
public final boolean isIndexable;
/**
* If this is a reference attribute, then the name of the attribute on the Class
* that this refers to.
*/
public final String reverseAttributeName;
private IDataType dataType;
AttributeInfo(TypeSystem t, AttributeDefinition def, Map<String, IDataType> tempTypes) throws AtlasException {
this.name = def.name;
this.dataType =
(tempTypes != null && tempTypes.containsKey(def.dataTypeName)) ? tempTypes.get(def.dataTypeName) :
t.getDataType(IDataType.class, def.dataTypeName);
this.multiplicity = def.multiplicity;
this.isComposite = def.isComposite;
this.isUnique = def.isUnique;
this.isIndexable = def.isIndexable;
this.reverseAttributeName = def.reverseAttributeName;
}
public IDataType dataType() {
return dataType;
}
void setDataType(IDataType dT) {
dataType = dT;
}
@Override
public String toString() {
return "AttributeInfo{" +
"name='" + name + '\'' +
", dataType=" + dataType +
", multiplicity=" + multiplicity +
", isComposite=" + isComposite +
", isUnique=" + isUnique +
", isIndexable=" + isIndexable +
", reverseAttributeName='" + reverseAttributeName + '\'' +
'}';
}
public String toJson() throws JSONException {
JSONObject json = new JSONObject();
json.put("name", name);
json.put("multiplicity", multiplicity.toJson());
json.put("isComposite", isComposite);
json.put("isUnique", isUnique);
json.put("isIndexable", isIndexable);
json.put("dataType", dataType.getName());
json.put("reverseAttributeName", reverseAttributeName);
return json.toString();
}
public static AttributeDefinition fromJson(String jsonStr) throws JSONException {
JSONObject json = new JSONObject(jsonStr);
String reverseAttr = null;
if (json.has("reverseAttributeName")) {
reverseAttr = json.getString("reverseAttributeName");
}
return new AttributeDefinition(json.getString("name"), json.getString("dataType"),
Multiplicity.fromJson(json.getString("multiplicity")), json.getBoolean("isComposite"),
json.getBoolean("isUnique"), json.getBoolean("isIndexable"), reverseAttr);
}
}
|
3e1ef1a571088e13fe684fef2a653c499890316c | 2,036 | java | Java | simple/src/main/java/org/lightfw/supervisor/SuperVisor.java | bjo2008cnx/example-akka-java | d5fe122dbee5020cfdddfad862fb3d2240509daf | [
"Apache-2.0"
] | null | null | null | simple/src/main/java/org/lightfw/supervisor/SuperVisor.java | bjo2008cnx/example-akka-java | d5fe122dbee5020cfdddfad862fb3d2240509daf | [
"Apache-2.0"
] | null | null | null | simple/src/main/java/org/lightfw/supervisor/SuperVisor.java | bjo2008cnx/example-akka-java | d5fe122dbee5020cfdddfad862fb3d2240509daf | [
"Apache-2.0"
] | null | null | null | 38.415094 | 134 | 0.578585 | 13,079 | package org.lightfw.supervisor;
import akka.actor.OneForOneStrategy;
import akka.actor.Props;
import akka.actor.SupervisorStrategy;
import akka.actor.UntypedActor;
import akka.japi.Function;
import scala.concurrent.duration.Duration;
import java.util.concurrent.TimeUnit;
/**
* 监督者,监督策略
*/
public class SuperVisor extends UntypedActor {
/**
* 配置自己的strategy
*
* @return
*/
@Override
public SupervisorStrategy supervisorStrategy() {
return new OneForOneStrategy(3, Duration.create(1, TimeUnit.MINUTES),//一分钟内重试3次,超过则kill掉actor
new Function<Throwable, SupervisorStrategy.Directive>() {
@Override
public SupervisorStrategy.Directive apply(Throwable throwable) throws Exception {
if (throwable instanceof ArithmeticException) {//ArithmeticException是出现异常的运算条件时,抛出此异常。例如,一个整数“除以零”时,抛出此类的一个实例。
System.out.println("meet ArithmeticException ,just resume.");
return SupervisorStrategy.resume();//继续; 重新开始; 恢复职位;
} else if (throwable instanceof NullPointerException) {
System.out.println("meet NullPointerException , restart.");
return SupervisorStrategy.restart();
} else if (throwable instanceof IllegalArgumentException) {
System.out.println("meet IllegalArgumentException ,stop.");
return SupervisorStrategy.stop();
} else {
System.out.println("escalate.");
return SupervisorStrategy.escalate();//使逐步升级; 使逐步上升; 乘自动梯上升;也就是交给更上层的actor处理。抛出异常
}
}
});
}
@Override
public void onReceive(Object o) {
if (o instanceof Props) {
getContext().actorOf((Props) o, "restartActor");
} else {
unhandled(o);
}
}
} |
3e1ef2512ba12004d321c2b4bd830e7a86c592f6 | 18,860 | java | Java | core/src/main/java/org/neo4j/ogm/metadata/FieldInfo.java | mattharr/neo4j-ogm | 35f23127eca0f7e1ad0a2effe6271024613be6d8 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2019-07-16T09:35:15.000Z | 2019-07-16T09:35:17.000Z | core/src/main/java/org/neo4j/ogm/metadata/FieldInfo.java | TJ1451862/neo4j-ogm | e0f82f05c7072ce2b1564475f3b7eee916dee0d4 | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2021-02-24T03:43:12.000Z | 2021-02-24T03:43:12.000Z | core/src/main/java/org/neo4j/ogm/metadata/FieldInfo.java | TJ1451862/neo4j-ogm | e0f82f05c7072ce2b1564475f3b7eee916dee0d4 | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2021-01-22T11:13:41.000Z | 2021-01-22T11:13:41.000Z | 36.130268 | 157 | 0.624549 | 13,080 | /*
* Copyright (c) 2002-2019 "Neo4j,"
* Neo4j Sweden AB [http://neo4j.com]
*
* This file is part of Neo4j.
*
* 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.neo4j.ogm.metadata;
import static org.neo4j.ogm.metadata.reflect.GenericUtils.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Map;
import java.util.Optional;
import java.util.function.Predicate;
import org.apache.commons.lang3.StringUtils;
import org.neo4j.ogm.annotation.GeneratedValue;
import org.neo4j.ogm.annotation.Id;
import org.neo4j.ogm.annotation.Index;
import org.neo4j.ogm.annotation.Labels;
import org.neo4j.ogm.annotation.Properties;
import org.neo4j.ogm.annotation.Property;
import org.neo4j.ogm.annotation.Relationship;
import org.neo4j.ogm.annotation.Version;
import org.neo4j.ogm.exception.core.MappingException;
import org.neo4j.ogm.id.InternalIdStrategy;
import org.neo4j.ogm.session.Utils;
import org.neo4j.ogm.typeconversion.AttributeConverter;
import org.neo4j.ogm.typeconversion.CompositeAttributeConverter;
import org.neo4j.ogm.typeconversion.MapCompositeConverter;
import org.neo4j.ogm.utils.RelationshipUtils;
/**
* @author Vince Bickers
* @author Luanne Misquitta
* @author Mark Angrish
* @author Michael J. Simons
*/
public class FieldInfo {
private final String name;
private final String descriptor;
private final String typeParameterDescriptor;
private final ObjectAnnotations annotations;
private final boolean isArray;
private final boolean isSupportedNativeType;
private final ClassInfo containingClassInfo;
private final Field field;
private final Class<?> fieldType;
/**
* The associated attribute converter for this field, if applicable, otherwise null.
*/
private AttributeConverter<?, ?> propertyConverter;
/**
* The associated composite attribute converter for this field, if applicable, otherwise null.
*/
private CompositeAttributeConverter<?> compositeConverter;
/**
* Constructs a new {@link FieldInfo} based on the given arguments.
*
* @param typeParameterDescriptor The descriptor that expresses the generic type parameter, which may be <code>null</code>
* if that's not appropriate
* @param annotations The {@link ObjectAnnotations} applied to the field
*/
public FieldInfo(ClassInfo classInfo, Field field, String typeParameterDescriptor, ObjectAnnotations annotations,
Predicate<Class<?>> isSupportedNativeType) {
this.containingClassInfo = classInfo;
this.field = field;
this.fieldType = isGenericField(field) ? findFieldType(field, classInfo.getUnderlyingClass()) : field.getType();
this.isArray = fieldType.isArray();
this.name = field.getName();
this.descriptor = field.getType().getTypeName();
this.typeParameterDescriptor = typeParameterDescriptor;
this.annotations = annotations;
this.isSupportedNativeType = isSupportedNativeType.test(DescriptorMappings.getType(getTypeDescriptor()));
if (!this.annotations.isEmpty()) {
Object converter = getAnnotations().getConverter(this.fieldType);
if (converter instanceof AttributeConverter) {
setPropertyConverter((AttributeConverter<?, ?>) converter);
} else if (converter instanceof CompositeAttributeConverter) {
setCompositeConverter((CompositeAttributeConverter<?>) converter);
} else if (converter != null) {
throw new IllegalStateException(String.format(
"The converter for field %s is neither an instance of AttributeConverter or CompositeAttributeConverter",
this.name));
} else if (hasAnnotation(Properties.class)) {
if (fieldType.equals(Map.class)) {
Properties propertiesAnnotation = (Properties) getAnnotations().get(Properties.class).getAnnotation();
Type fieldGenericType = field.getGenericType();
MapCompositeConverter mapCompositeConverter = new MapCompositeConverter(
Optional.ofNullable(propertiesAnnotation.prefix()).filter(StringUtils::isNotBlank).orElseGet(field::getName),
propertiesAnnotation.delimiter(),
propertiesAnnotation.allowCast(),
(ParameterizedType) fieldGenericType, isSupportedNativeType);
try {
mapCompositeConverter.setEnumKeysTransformation(propertiesAnnotation.transformEnumKeysWith().getDeclaredConstructor().newInstance());
} catch (Exception e) {
throw new IllegalArgumentException("Unsupported property key filter: " + propertiesAnnotation.transformEnumKeysWith(), e);
}
setCompositeConverter(mapCompositeConverter);
} else {
throw new MappingException("@Properties annotation is allowed only on fields of type java.util.Map");
}
}
}
}
public String getName() {
return name;
}
// should these two methods be on PropertyReader, RelationshipReader respectively?
public String property() {
if (persistableAsProperty()) {
if (annotations != null) {
AnnotationInfo propertyAnnotation = annotations.get(Property.class);
if (propertyAnnotation != null) {
return propertyAnnotation.get(Property.NAME, getName());
}
}
return getName();
}
return null;
}
public String relationship() {
if (!persistableAsProperty()) {
if (annotations != null) {
AnnotationInfo relationshipAnnotation = annotations.get(Relationship.class);
if (relationshipAnnotation != null) {
return relationshipAnnotation
.get(Relationship.TYPE, RelationshipUtils.inferRelationshipType(getName()));
}
}
return RelationshipUtils.inferRelationshipType(getName());
}
return null;
}
public String relationshipTypeAnnotation() {
if (!persistableAsProperty()) {
if (annotations != null) {
AnnotationInfo relationshipAnnotation = annotations.get(Relationship.class);
if (relationshipAnnotation != null) {
return relationshipAnnotation.get(Relationship.TYPE, null);
}
}
}
return null;
}
public ObjectAnnotations getAnnotations() {
return annotations;
}
// should be improved, as unmanaged types (like ZonedDateTime) are not detected as property but as relationship
// see #347
public boolean persistableAsProperty() {
return DescriptorMappings.describesPrimitve(descriptor)
|| isSupportedNativeType
|| (DescriptorMappings.describesWrapper(descriptor) && typeParameterDescriptor == null)
|| (typeParameterDescriptor != null && DescriptorMappings.describesWrapper((typeParameterDescriptor)))
|| propertyConverter != null
|| compositeConverter != null;
}
public AttributeConverter getPropertyConverter() {
return propertyConverter;
}
public void setPropertyConverter(AttributeConverter<?, ?> propertyConverter) {
if (this.propertyConverter == null && this.compositeConverter == null && propertyConverter != null) {
this.propertyConverter = propertyConverter;
} // we maybe set an annotated converter when object was constructed, so don't override with a default one
}
public boolean hasPropertyConverter() {
return propertyConverter != null;
}
public CompositeAttributeConverter getCompositeConverter() {
return compositeConverter;
}
public void setCompositeConverter(CompositeAttributeConverter<?> converter) {
if (this.propertyConverter == null && this.compositeConverter == null && converter != null) {
this.compositeConverter = converter;
}
}
public boolean hasCompositeConverter() {
return compositeConverter != null;
}
public String relationshipDirection(String defaultDirection) {
if (relationship() != null) {
AnnotationInfo annotationInfo = getAnnotations().get(Relationship.class);
if (annotationInfo == null) {
return defaultDirection;
}
return annotationInfo.get(Relationship.DIRECTION, defaultDirection);
}
throw new RuntimeException("relationship direction call invalid");
}
public boolean isIterable() {
return Iterable.class.isAssignableFrom(fieldType);
}
public boolean isTypeOf(Class<?> type) {
return doesDescriptorMatchType(descriptor, type);
}
public boolean isParameterisedTypeOf(Class<?> type) {
return doesDescriptorMatchType(typeParameterDescriptor, type);
}
public boolean isArrayOf(Class<?> type) {
while (type != null) {
String typeSignature = type.getName();
if (descriptor != null && descriptor.equals(typeSignature + "[]")) {
return true;
}
// #issue 42: check interfaces when types are defined using generics as interface extensions
for (Class<?> iface : type.getInterfaces()) {
typeSignature = iface.getName();
if (descriptor != null && descriptor.equals(typeSignature)) {
return true;
}
}
type = type.getSuperclass();
}
return false;
}
/**
* Get the collection class name for the field
*
* @return collection class name
*/
public String getCollectionClassname() {
return descriptor;
}
public boolean isScalar() {
return !isIterable() && !isArray();
}
public boolean isLabelField() {
return this.getAnnotations().get(Labels.class) != null;
}
public boolean isArray() {
return isArray;
}
public boolean hasAnnotation(String annotationName) {
return getAnnotations().get(annotationName) != null;
}
public boolean hasAnnotation(Class<?> annotationNameClass) {
return getAnnotations().get(annotationNameClass.getName()) != null;
}
/**
* Get the type descriptor
*
* @return the descriptor if the field is scalar or an array, otherwise the type parameter descriptor.
*/
public String getTypeDescriptor() {
if (!isIterable() || isArray()) {
return descriptor;
}
return typeParameterDescriptor;
}
public Class<?> convertedType() {
if (hasPropertyConverter() || hasCompositeConverter()) {
Class converterClass = hasPropertyConverter() ?
getPropertyConverter().getClass() : getCompositeConverter().getClass();
String methodName = hasPropertyConverter() ? "toGraphProperty" : "toGraphProperties";
try {
for (Method method : converterClass.getDeclaredMethods()) {
//we don't want the method on the AttributeConverter interface
if (method.getName().equals(methodName) && !method.isSynthetic()) {
return method.getReturnType();
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return null;
}
/**
* @return <code>true</code> is this field is a constraint rather than just a plain index.
*/
public boolean isConstraint() {
AnnotationInfo idAnnotation = this.getAnnotations().get(Id.class.getName());
if (idAnnotation != null) {
return true;
}
AnnotationInfo indexAnnotation = this.getAnnotations().get(Index.class.getName());
return indexAnnotation != null && indexAnnotation.get("unique", "false").equals("true");
}
// =================================================================================================================
// From FieldAccessor
// =================================================================================================================
public static void write(Field field, Object instance, final Object value) {
AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
try {
field.setAccessible(true);
field.set(instance, value);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
return null;
});
}
public static Object read(Field field, Object instance) {
return AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
try {
field.setAccessible(true);
return field.get(instance);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
});
}
public void write(Object instance, Object value) {
if (hasPropertyConverter()) {
value = getPropertyConverter().toEntityAttribute(value);
write(field, instance, value);
} else {
if (isScalar()) {
String actualTypeDescriptor = getTypeDescriptor();
value = Utils.coerceTypes(DescriptorMappings.getType(actualTypeDescriptor), value);
}
write(field, instance, value);
}
}
/**
* Write the value of the field directly to the instance, bypassing the converters
*
* @param instance class instance
* @param value field value to be written
*/
public void writeDirect(Object instance, Object value) {
write(field, instance, value);
}
public Class<?> type() {
Class convertedType = convertedType();
if (convertedType != null) {
return convertedType;
}
return fieldType;
}
public String relationshipName() {
return this.relationship();
}
public boolean forScalar() {
return !Iterable.class.isAssignableFrom(type()) && !type().isArray();
}
public String typeParameterDescriptor() {
return getTypeDescriptor();
}
public Object read(Object instance) {
return read(containingClassInfo.getField(this), instance);
}
public Object readProperty(Object instance) {
if (hasCompositeConverter()) {
throw new IllegalStateException(
"The readComposite method should be used for fields with a CompositeAttributeConverter");
}
Object value = read(containingClassInfo.getField(this), instance);
if (hasPropertyConverter()) {
value = getPropertyConverter().toGraphProperty(value);
}
return value;
}
public Map<String, ?> readComposite(Object instance) {
if (!hasCompositeConverter()) {
throw new IllegalStateException(
"readComposite should only be used when a field is annotated with a CompositeAttributeConverter");
}
Object value = read(containingClassInfo.getField(this), instance);
return getCompositeConverter().toGraphProperties(value);
}
public String relationshipType() {
return relationship();
}
public String propertyName() {
return property();
}
public boolean isComposite() {
return hasCompositeConverter();
}
public String relationshipDirection() {
ObjectAnnotations annotationOfField = getAnnotations();
if (annotationOfField != null) {
AnnotationInfo relationshipAnnotation = annotationOfField.get(Relationship.class);
if (relationshipAnnotation != null) {
return relationshipAnnotation.get(Relationship.DIRECTION, Relationship.UNDIRECTED);
}
}
return Relationship.UNDIRECTED;
}
public String typeDescriptor() {
return getTypeDescriptor();
}
public Field getField() {
return field;
}
/**
* ClassInfo for the class this field is defined in
*
* @return ClassInfo of containing
*/
public ClassInfo containingClassInfo() {
return containingClassInfo;
}
public boolean isVersionField() {
return field.getAnnotation(Version.class) != null;
}
/**
* @return True if this field info describes the internal identity field.
*/
boolean isInternalIdentity() {
return this.getAnnotations().has(Id.class) &&
this.getAnnotations().has(GeneratedValue.class) &&
((GeneratedValue) this.getAnnotations().get(GeneratedValue.class).getAnnotation())
.strategy().equals(InternalIdStrategy.class);
}
private static boolean doesDescriptorMatchType(String descriptor, Class<?> type) {
while (type != null) {
if (doesDescriptorMatchTypeOrInterface(descriptor, type)) {
return true;
}
type = type.getSuperclass();
}
return false;
}
private static boolean doesDescriptorMatchTypeOrInterface(String descriptorToMatch, Class<?> type) {
String typeSignature = type.getName();
if (descriptorToMatch != null && descriptorToMatch.equals(typeSignature)) {
return true;
}
if (doesAnyInterfaceMatch(descriptorToMatch, type)) {
return true;
}
return false;
}
private static boolean doesAnyInterfaceMatch(String descriptor, Class<?> type) {
for (Class<?> interfaceClass : type.getInterfaces()) {
if (doesDescriptorMatchTypeOrInterface(descriptor, interfaceClass)) {
return true;
}
}
return false;
}
}
|
3e1ef2be3f499631ce8fe0952ae1e6ab4fbb6158 | 1,280 | java | Java | core-customize/hybris/bin/modules/integration-apis/odata2services/src/de/hybris/platform/odata2services/odata/monitoring/ResponseChangeSetEntityBuilder.java | karthik-git-user/SAP-Stage | 72487ab521e7e2411f1b081615817d099edf9744 | [
"Apache-2.0"
] | null | null | null | core-customize/hybris/bin/modules/integration-apis/odata2services/src/de/hybris/platform/odata2services/odata/monitoring/ResponseChangeSetEntityBuilder.java | karthik-git-user/SAP-Stage | 72487ab521e7e2411f1b081615817d099edf9744 | [
"Apache-2.0"
] | null | null | null | core-customize/hybris/bin/modules/integration-apis/odata2services/src/de/hybris/platform/odata2services/odata/monitoring/ResponseChangeSetEntityBuilder.java | karthik-git-user/SAP-Stage | 72487ab521e7e2411f1b081615817d099edf9744 | [
"Apache-2.0"
] | null | null | null | 24.615385 | 93 | 0.803906 | 13,081 | /*
* Copyright (c) 2019 SAP SE or an SAP affiliate company. All rights reserved.
*/
package de.hybris.platform.odata2services.odata.monitoring;
import de.hybris.platform.inboundservices.model.InboundRequestErrorModel;
import de.hybris.platform.integrationservices.util.HttpStatus;
/**
* A builder for {@link ResponseChangeSetEntity}
*/
public class ResponseChangeSetEntityBuilder
{
private HttpStatus statusCode;
private String integrationKey;
private InboundRequestErrorModel requestError;
public static ResponseChangeSetEntityBuilder responseChangeSetEntity()
{
return new ResponseChangeSetEntityBuilder();
}
public ResponseChangeSetEntityBuilder withStatusCode(final String code)
{
return withStatusCode(Integer.parseInt(code));
}
public ResponseChangeSetEntityBuilder withStatusCode(final int code)
{
statusCode = HttpStatus.valueOf(code);
return this;
}
public ResponseChangeSetEntityBuilder withIntegrationKey(final String key)
{
integrationKey = key;
return this;
}
public ResponseChangeSetEntityBuilder withRequestError(final InboundRequestErrorModel error)
{
requestError = error;
return this;
}
public ResponseChangeSetEntity build()
{
return new ResponseChangeSetEntity(integrationKey, statusCode, requestError);
}
}
|
3e1ef2cc9ad7c307d6a84b3551051ced3f7decbd | 399 | java | Java | src/main/java/test/Examples.java | ZhengKaikai1993/ast | 7ec67bbb669414f0aa463aafc7a46790d8c33384 | [
"Apache-2.0"
] | null | null | null | src/main/java/test/Examples.java | ZhengKaikai1993/ast | 7ec67bbb669414f0aa463aafc7a46790d8c33384 | [
"Apache-2.0"
] | null | null | null | src/main/java/test/Examples.java | ZhengKaikai1993/ast | 7ec67bbb669414f0aa463aafc7a46790d8c33384 | [
"Apache-2.0"
] | null | null | null | 18.136364 | 89 | 0.686717 | 13,082 | package test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import parse.DefaultASTVisitor;
public class Examples
{
public static final Logger logger = LoggerFactory.getLogger(DefaultASTVisitor.class);
public void test()
{
TestClass testClass = new TestClass(1000L, 3.0F);
int b = (int) testClass.aFloat;
long d = (int) testClass.aLong;
}
}
|
3e1ef2d7e4b39bfa8748ec874097a05b5ebdd382 | 2,550 | java | Java | Courses + Books/Algorithms/Book/Part 1/02 - Sorting/02_2 - Mergesort/Creative Questions/Exercise_20.java | edaaydinea/365-days-of-coding-challenge | baf06a9bef75ff45194e57357e20085b9cde2498 | [
"MIT"
] | 4 | 2022-01-05T12:14:13.000Z | 2022-01-08T16:03:32.000Z | Courses + Books/Algorithms/Book/Part 1/02 - Sorting/02_2 - Mergesort/Creative Questions/Exercise_20.java | edaaydinea/365-days-of-coding-challenge | baf06a9bef75ff45194e57357e20085b9cde2498 | [
"MIT"
] | null | null | null | Courses + Books/Algorithms/Book/Part 1/02 - Sorting/02_2 - Mergesort/Creative Questions/Exercise_20.java | edaaydinea/365-days-of-coding-challenge | baf06a9bef75ff45194e57357e20085b9cde2498 | [
"MIT"
] | null | null | null | 32.692308 | 75 | 0.438431 | 13,083 | import java.util.Arrays;
import java.util.Random;
public class Exercise_20 {
public static class Merge {
private static Comparable[] aux; // auxiliary array for merges
private static int[] perm;
private static int[] auxp;
public static int[] sort(Comparable[] a) {
aux = new Comparable[a.length]; // Allocate space just once.
perm = new int[a.length];
auxp = new int[a.length];
for (int i = 0; i < a.length; i++)
perm[i] = i;
sort(a,0, a.length - 1);
return perm;
}
private static void sort(Comparable[] a, int lo, int hi) {
// Sort a[lo..hi].
if (hi <= lo) return;
int mid = lo + (hi - lo) / 2;
sort(a, lo, mid); // Sort left half.
sort(a, mid + 1, hi); // Sort right half.
merge(a, lo, mid, hi); // Merge results (code on page 271).
}
public static void merge(Comparable[] a, int lo, int mid, int hi) {
int i = lo, j = mid + 1;
for (int k = lo; k <= hi; k++) {
aux[k] = a[perm[k]];
auxp[k] = perm[k];
}
for (int k = lo; k <= hi; k++) { // Merge back to a[lo..hi].
if (i > mid) {
perm[k] = auxp[j++];
} else if (j > hi) {
perm[k] = auxp[i++];
} else if (less(aux[j], aux[i])) {
perm[k] = auxp[j++];
}
else {
perm[k] = auxp[i++];
}
}
}
private static boolean less(Comparable v, Comparable w) {
return v.compareTo(w) < 0;
}
}
public static void main(String[] args) {
int n = 20;
Integer[] a = new Integer[n];
for (int i = 0; i < n; i++) {
a[i] = i;
}
System.out.println(Arrays.toString(Merge.sort(a)));
System.out.println(Arrays.toString(a));
System.out.println();
for (int i = 0; i < n; i++) {
a[i] = n - 1 - i;
}
System.out.println(Arrays.toString(Merge.sort(a)));
System.out.println(Arrays.toString(a));
System.out.println();
Random r = new Random();
for (int i = 0; i < n; i++) {
a[i] = r.nextInt(n);
}
System.out.println(Arrays.toString(Merge.sort(a)));
System.out.println(Arrays.toString(a));
}
}
|
3e1ef3b35a0e97b4557e44e9b834170fb966ad01 | 6,298 | java | Java | app/src/main/java/com/example/android/miwok/ColorsActivity.java | Riyazmansuri/UdacityCourseProject | 93da8072ffbe304e1fd0199136dd5b6b4d70c706 | [
"Apache-2.0"
] | 5 | 2021-03-18T17:27:49.000Z | 2021-05-17T15:49:38.000Z | app/src/main/java/com/example/android/miwok/ColorsActivity.java | Riyazmansuri/UdacityCourseProject | 93da8072ffbe304e1fd0199136dd5b6b4d70c706 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/android/miwok/ColorsActivity.java | Riyazmansuri/UdacityCourseProject | 93da8072ffbe304e1fd0199136dd5b6b4d70c706 | [
"Apache-2.0"
] | null | null | null | 48.446154 | 129 | 0.646078 | 13,084 | package com.example.android.miwok;
import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.ArrayList;
public class ColorsActivity extends AppCompatActivity {
MediaPlayer mMediaPlayer;
private AudioManager mAudioManager;
private MediaPlayer.OnCompletionListener mCompletionListener = new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
releaseMediaPlayer();
}
};
private AudioManager.OnAudioFocusChangeListener mOnAudioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() {
@Override
public void onAudioFocusChange(int focusChange) {
if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT ||
focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) {
// The AUDIOFOCUS_LOSS_TRANSIENT case means that we've lost audio focus for a
// short amount of time. The AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK case means that
// our app is allowed to continue playing sound but at a lower volume. We'll treat
// both cases the same way because our app is playing short sound files.
// Pause playback and reset player to the start of the file. That way, we can
// play the word from the beginning when we resume playback.
mMediaPlayer.pause();
mMediaPlayer.seekTo(0);
} else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
// The AUDIOFOCUS_GAIN case means we have regained focus and can resume playback.
mMediaPlayer.start();
} else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
// The AUDIOFOCUS_LOSS case means we've lost audio focus and
// Stop playback and clean up resources
releaseMediaPlayer();
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.word_list);
mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
// Create a list of words
final ArrayList<Word> words = new ArrayList<Word>();
words.add(new Word("red", "weṭeṭṭi", R.drawable.color_red, R.raw.color_red));
words.add(new Word("mustard yellow", "chiwiiṭә", R.drawable.color_mustard_yellow,
R.raw.color_mustard_yellow));
words.add(new Word("dusty yellow", "ṭopiisә", R.drawable.color_dusty_yellow,
R.raw.color_dusty_yellow));
words.add(new Word("green", "chokokki", R.drawable.color_green, R.raw.color_green));
words.add(new Word("brown", "ṭakaakki", R.drawable.color_brown, R.raw.color_brown));
words.add(new Word("gray", "ṭopoppi", R.drawable.color_gray, R.raw.color_gray));
words.add(new Word("black", "kululli", R.drawable.color_black, R.raw.color_black));
words.add(new Word("white", "kelelli", R.drawable.color_white, R.raw.color_white));
// Create an {@link WordAdapter}, whose data source is a list of {@link Word}s. The
// adapter knows how to create list items for each item in the list.
WordAdapter adapter = new WordAdapter(this, words,R.color.category_colors);
// Find the {@link ListView} object in the view hierarchy of the {@link Activity}.
// There should be a {@link ListView} with the view ID called list, which is declared in the
// word_list.xml layout file.
ListView listView = (ListView) findViewById(R.id.list);
// Make the {@link ListView} use the {@link WordAdapter} we created above, so that the
// {@link ListView} will display list items for each {@link Word} in the list.
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Word word = words.get(position);
releaseMediaPlayer();
int result = mAudioManager.requestAudioFocus(mOnAudioFocusChangeListener,
AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
// We have audio focus now.
// Create and setup the {@link MediaPlayer} for the audio resource associated
// with the current word
mMediaPlayer = MediaPlayer.create(ColorsActivity.this, word.getAudioResourceId());
// Start the audio file
mMediaPlayer.start();
// Setup a listener on the media player, so that we can stop and release the
// media player once the sound has finished playing.
mMediaPlayer.setOnCompletionListener(mCompletionListener);
}
}
});
}
@Override
protected void onStop() {
super.onStop();
releaseMediaPlayer();
}
private void releaseMediaPlayer() {
// If the media player is not null, then it may be currently playing a sound.
if (mMediaPlayer != null) {
// Regardless of the current state of the media player, release its resources
// because we no longer need it.
mMediaPlayer.release();
// Set the media player back to null. For our code, we've decided that
// setting the media player to null is an easy way to tell that the media player
// is not configured to play an audio file at the moment.
mMediaPlayer = null;
// Regardless of whether or not we were granted audio focus, abandon it. This also
// unregisters the AudioFocusChangeListener so we don't get anymore callbacks.
mAudioManager.abandonAudioFocus(mOnAudioFocusChangeListener);
}
}
}
|
3e1ef4b6dda339b9d60abf9d6ae9f03cfe228c74 | 1,018 | java | Java | chart/src/main/java/io/github/mmm/ui/fx/widget/chart/fx/AdvancedBarChart.java | m-m-m/ui-fx | c3407d0df5d39a274830df0f2c856bc3e08ae474 | [
"Apache-2.0"
] | null | null | null | chart/src/main/java/io/github/mmm/ui/fx/widget/chart/fx/AdvancedBarChart.java | m-m-m/ui-fx | c3407d0df5d39a274830df0f2c856bc3e08ae474 | [
"Apache-2.0"
] | 13 | 2020-05-15T14:26:03.000Z | 2020-10-14T22:25:33.000Z | chart/src/main/java/io/github/mmm/ui/fx/widget/chart/fx/AdvancedBarChart.java | m-m-m/ui-fx | c3407d0df5d39a274830df0f2c856bc3e08ae474 | [
"Apache-2.0"
] | 3 | 2020-04-16T12:09:13.000Z | 2020-07-31T08:01:36.000Z | 22.622222 | 99 | 0.670923 | 13,085 | /* Copyright (c) The m-m-m Team, Licensed under the Apache License, Version 2.0
* http://www.apache.org/licenses/LICENSE-2.0 */
package io.github.mmm.ui.fx.widget.chart.fx;
import javafx.scene.chart.Axis;
import javafx.scene.chart.BarChart;
import javafx.scene.chart.XYChart.Series;
import javafx.scene.layout.Pane;
/**
* {@link BarChart} implementing {@link AdvancedChart}.
*
* @param <X> type of data for X-axis.
* @param <Y> type of data for Y-axis.
*
* @since 1.0.0
*/
public class AdvancedBarChart<X, Y> extends BarChart<X, Y> implements AdvancedChart<Series<X, Y>> {
/**
* The constructor.
*
* @param xAxis the horizontal {@link Axis}.
* @param yAxis the vertical {@link Axis}.
*/
public AdvancedBarChart(Axis<X> xAxis, Axis<Y> yAxis) {
super(xAxis, yAxis);
}
@SuppressWarnings("unchecked")
@Override
public void setAllData(Series<X, Y>... data) {
getData().setAll(data);
}
@Override
public Pane getLegendAsPane() {
return (Pane) getLegend();
}
}
|
3e1ef62ab1831c28c9a37f2d086a8d4475ab59c1 | 719 | java | Java | NLPCCd/Camel/7848_2.java | sgholamian/log-aware-clone-detection | 9993cb081c420413c231d1807bfff342c39aa69a | [
"MIT"
] | null | null | null | NLPCCd/Camel/7848_2.java | sgholamian/log-aware-clone-detection | 9993cb081c420413c231d1807bfff342c39aa69a | [
"MIT"
] | null | null | null | NLPCCd/Camel/7848_2.java | sgholamian/log-aware-clone-detection | 9993cb081c420413c231d1807bfff342c39aa69a | [
"MIT"
] | null | null | null | 34.238095 | 109 | 0.746871 | 13,086 | //,temp,sample_1133.java,2,16,temp,sample_1132.java,2,17
//,3
public class xxx {
public void dummy_method(){
String message = exchange.getIn().getBody(String.class);
Level level = exchange.getIn().getHeader(LEVEL, Level.class);
if (level == null) {
String name = exchange.getIn().getHeader(LEVEL, Level.OK.name(), String.class);
level = Level.valueOf(name);
}
String serviceName = exchange.getIn().getHeader(SERVICE_NAME, exchange.getContext().getName(), String.class);
String hostName = exchange.getIn().getHeader(HOST_NAME, "localhost", String.class);
MessagePayload payload = new MessagePayload(hostName, level, serviceName, message);
if (log.isDebugEnabled()) {
log.info("sending notification to nagios");
}
}
}; |
3e1ef6c5080cbd43bf5a1abe3e2bc85b485262a6 | 953 | java | Java | src/test/java/net/datafaker/idnumbers/SwedishIdNumberTest.java | eltonsandre/datafaker | 7e40a00e7b521cce28555ab006df3952d972e094 | [
"Apache-2.0"
] | null | null | null | src/test/java/net/datafaker/idnumbers/SwedishIdNumberTest.java | eltonsandre/datafaker | 7e40a00e7b521cce28555ab006df3952d972e094 | [
"Apache-2.0"
] | null | null | null | src/test/java/net/datafaker/idnumbers/SwedishIdNumberTest.java | eltonsandre/datafaker | 7e40a00e7b521cce28555ab006df3952d972e094 | [
"Apache-2.0"
] | null | null | null | 34.035714 | 71 | 0.693599 | 13,087 | package net.datafaker.idnumbers;
import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
public class SwedishIdNumberTest {
@Test
public void valid() {
SvSEIdNumber idNumber = new SvSEIdNumber();
assertThat(idNumber.validSwedishSsn("670919-9530"), is(true));
assertThat(idNumber.validSwedishSsn("811228-9874"), is(true));
}
@Test
public void invalid() {
SvSEIdNumber idNumber = new SvSEIdNumber();
assertThat(idNumber.validSwedishSsn("8112289873"), is(false));
assertThat(idNumber.validSwedishSsn("foo228-9873"), is(false));
assertThat(idNumber.validSwedishSsn("811228-9873"), is(false));
assertThat(idNumber.validSwedishSsn("811228-9875"), is(false));
assertThat(idNumber.validSwedishSsn("811200-9874"), is(false));
assertThat(idNumber.validSwedishSsn("810028-9874"), is(false));
}
}
|
3e1ef77dd4775f61d7737c8b5ecfe4f1ee92be47 | 698 | java | Java | src/main/java/com/change/projects/book/model/Books.java | Suyashsudhir2695/bookstore | a032164f19dd41ff5a9473b846ab72e259d775aa | [
"Apache-2.0"
] | null | null | null | src/main/java/com/change/projects/book/model/Books.java | Suyashsudhir2695/bookstore | a032164f19dd41ff5a9473b846ab72e259d775aa | [
"Apache-2.0"
] | null | null | null | src/main/java/com/change/projects/book/model/Books.java | Suyashsudhir2695/bookstore | a032164f19dd41ff5a9473b846ab72e259d775aa | [
"Apache-2.0"
] | null | null | null | 19.942857 | 55 | 0.684814 | 13,088 | package com.change.projects.book.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "books")
public class Books {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;
@Column(name = "book_name")
private String name;
@Column(name = "author")
private String author;
@Column(name = "publisher")
private String publisher;
@Column(name = "price")
private int price;
@Column(name = "year")
private int year;
@Column(name = "image")
private String image;
}
|
3e1ef7bb8a5caebd5894034357c638553fc31911 | 7,076 | java | Java | cloud-azure/src/test/java/com/sequenceiq/cloudbreak/cloud/azure/AzureLoadBalancerModelBuilderTest.java | nkalmar/cloudbreak | f4abaa87cb6bca2de1ae1b28ccc7f14810bb6c4b | [
"Apache-2.0"
] | 174 | 2017-07-14T03:20:42.000Z | 2022-03-25T05:03:18.000Z | cloud-azure/src/test/java/com/sequenceiq/cloudbreak/cloud/azure/AzureLoadBalancerModelBuilderTest.java | nkalmar/cloudbreak | f4abaa87cb6bca2de1ae1b28ccc7f14810bb6c4b | [
"Apache-2.0"
] | 2,242 | 2017-07-12T05:52:01.000Z | 2022-03-31T15:50:08.000Z | cloud-azure/src/test/java/com/sequenceiq/cloudbreak/cloud/azure/AzureLoadBalancerModelBuilderTest.java | nkalmar/cloudbreak | f4abaa87cb6bca2de1ae1b28ccc7f14810bb6c4b | [
"Apache-2.0"
] | 172 | 2017-07-12T08:53:48.000Z | 2022-03-24T12:16:33.000Z | 43.679012 | 132 | 0.718344 | 13,089 | package com.sequenceiq.cloudbreak.cloud.azure;
import static java.util.Collections.emptyMap;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.Test;
import com.sequenceiq.cloudbreak.cloud.azure.loadbalancer.AzureLoadBalancer;
import com.sequenceiq.cloudbreak.cloud.model.CloudInstance;
import com.sequenceiq.cloudbreak.cloud.model.CloudLoadBalancer;
import com.sequenceiq.cloudbreak.cloud.model.CloudStack;
import com.sequenceiq.cloudbreak.cloud.model.Group;
import com.sequenceiq.cloudbreak.cloud.model.GroupNetwork;
import com.sequenceiq.cloudbreak.cloud.model.TargetGroupPortPair;
import com.sequenceiq.common.api.type.InstanceGroupType;
import com.sequenceiq.common.api.type.LoadBalancerSku;
import com.sequenceiq.common.api.type.LoadBalancerType;
import com.sequenceiq.common.api.type.OutboundInternetTraffic;
class AzureLoadBalancerModelBuilderTest {
public static final String STACK_NAME = "stack-name";
public static final String INSTANCE_GROUP_NAME = "bderriso-linz-sdx-gateway";
public static final String INSTANCE_NAME = "bderriso-linz-sdx-g0";
public static final String LOAD_BALANCERS_KEY = "loadBalancers";
public static final String LOAD_BALANCER_STACK_NAME = "LoadBalancerstack-namePRIVATE";
public static final String LOAD_BALANCER_MAPPING_KEY = "loadBalancerMapping";
private AzureLoadBalancerModelBuilder underTest;
@Test
void testGetModel() {
CloudStack mockCloudStack = mock(CloudStack.class);
Group targetGroup = new Group(INSTANCE_GROUP_NAME,
InstanceGroupType.GATEWAY,
List.of(new CloudInstance(INSTANCE_NAME, null, null, "subnet-1", "az1")),
null,
null,
null,
null,
null,
64,
null,
createGroupNetwork(),
emptyMap());
CloudLoadBalancer cloudLoadBalancer = new CloudLoadBalancer(LoadBalancerType.PRIVATE);
cloudLoadBalancer.addPortToTargetGroupMapping(new TargetGroupPortPair(443, 443), Set.of(targetGroup));
when(mockCloudStack.getLoadBalancers()).thenReturn(List.of(cloudLoadBalancer));
underTest = new AzureLoadBalancerModelBuilder(mockCloudStack, STACK_NAME);
Map<String, Object> result = underTest.buildModel();
assertTrue(result.containsKey(LOAD_BALANCERS_KEY));
assertTrue(result.get(LOAD_BALANCERS_KEY) instanceof List);
List<AzureLoadBalancer> loadBalancers = (List<AzureLoadBalancer>) result.get(LOAD_BALANCERS_KEY);
assertEquals(1, loadBalancers.size());
AzureLoadBalancer lb = loadBalancers.get(0);
assertEquals(LOAD_BALANCER_STACK_NAME, lb.getName());
assertEquals(LoadBalancerType.PRIVATE, lb.getType());
assertTrue(result.containsKey(LOAD_BALANCER_MAPPING_KEY));
assertTrue(result.get(LOAD_BALANCER_MAPPING_KEY) instanceof Map);
Map<String, List<AzureLoadBalancer>> mapping = (Map<String, List<AzureLoadBalancer>>) result.get(LOAD_BALANCER_MAPPING_KEY);
List<AzureLoadBalancer> mappingList = mapping.get(INSTANCE_GROUP_NAME);
assertEquals(1, mappingList.size());
assertEquals(LOAD_BALANCER_STACK_NAME, mappingList.get(0).getName());
}
@Test
void testGetModelWithDefaultSku() {
CloudStack mockCloudStack = mock(CloudStack.class);
CloudLoadBalancer cloudLoadBalancer = createCloudLoadBalancer();
when(mockCloudStack.getLoadBalancers()).thenReturn(List.of(cloudLoadBalancer));
underTest = new AzureLoadBalancerModelBuilder(mockCloudStack, STACK_NAME);
Map<String, Object> result = underTest.buildModel();
assertTrue(result.containsKey(LOAD_BALANCERS_KEY));
assertTrue(result.get(LOAD_BALANCERS_KEY) instanceof List);
List<AzureLoadBalancer> loadBalancers = (List<AzureLoadBalancer>) result.get(LOAD_BALANCERS_KEY);
assertEquals(1, loadBalancers.size());
AzureLoadBalancer lb = loadBalancers.get(0);
assertEquals(LoadBalancerSku.getDefault(), lb.getSku());
}
@Test
void testGetModelWithBasicSku() {
CloudStack mockCloudStack = mock(CloudStack.class);
CloudLoadBalancer cloudLoadBalancer = createCloudLoadBalancer(LoadBalancerSku.BASIC);
when(mockCloudStack.getLoadBalancers()).thenReturn(List.of(cloudLoadBalancer));
underTest = new AzureLoadBalancerModelBuilder(mockCloudStack, STACK_NAME);
Map<String, Object> result = underTest.buildModel();
assertTrue(result.containsKey(LOAD_BALANCERS_KEY));
assertTrue(result.get(LOAD_BALANCERS_KEY) instanceof List);
List<AzureLoadBalancer> loadBalancers = (List<AzureLoadBalancer>) result.get(LOAD_BALANCERS_KEY);
assertEquals(1, loadBalancers.size());
AzureLoadBalancer lb = loadBalancers.get(0);
assertEquals(LoadBalancerSku.BASIC, lb.getSku());
}
@Test
void testGetModelWithStandardSku() {
CloudStack mockCloudStack = mock(CloudStack.class);
CloudLoadBalancer cloudLoadBalancer = createCloudLoadBalancer(LoadBalancerSku.STANDARD);
when(mockCloudStack.getLoadBalancers()).thenReturn(List.of(cloudLoadBalancer));
underTest = new AzureLoadBalancerModelBuilder(mockCloudStack, STACK_NAME);
Map<String, Object> result = underTest.buildModel();
assertTrue(result.containsKey(LOAD_BALANCERS_KEY));
assertTrue(result.get(LOAD_BALANCERS_KEY) instanceof List);
List<AzureLoadBalancer> loadBalancers = (List<AzureLoadBalancer>) result.get(LOAD_BALANCERS_KEY);
assertEquals(1, loadBalancers.size());
AzureLoadBalancer lb = loadBalancers.get(0);
assertEquals(LoadBalancerSku.STANDARD, lb.getSku());
}
private GroupNetwork createGroupNetwork() {
return new GroupNetwork(OutboundInternetTraffic.DISABLED, new HashSet<>(), new HashMap<>());
}
private CloudLoadBalancer createCloudLoadBalancer() {
return createCloudLoadBalancer(null);
}
private CloudLoadBalancer createCloudLoadBalancer(LoadBalancerSku sku) {
Group targetGroup = new Group(INSTANCE_GROUP_NAME,
InstanceGroupType.GATEWAY,
List.of(new CloudInstance(INSTANCE_NAME, null, null, "subnet-1", "az1")),
null,
null,
null,
null,
null,
64,
null,
createGroupNetwork(),
emptyMap());
CloudLoadBalancer cloudLoadBalancer = new CloudLoadBalancer(LoadBalancerType.PRIVATE, sku);
cloudLoadBalancer.addPortToTargetGroupMapping(new TargetGroupPortPair(443, 443), Set.of(targetGroup));
return cloudLoadBalancer;
}
} |
3e1ef7de23c30c65761f033ce43a941f65ae03f0 | 8,718 | java | Java | src/main/java/io/zbus/mq/server/MqServer.java | legendzhouqiang/-zbus | 52706c0b746e28db68ac74eeeff75b5a6f498dd0 | [
"MIT"
] | 2 | 2020-03-21T03:00:30.000Z | 2020-07-21T08:52:57.000Z | src/main/java/io/zbus/mq/server/MqServer.java | legendzhouqiang/zbus | 52706c0b746e28db68ac74eeeff75b5a6f498dd0 | [
"MIT"
] | null | null | null | src/main/java/io/zbus/mq/server/MqServer.java | legendzhouqiang/zbus | 52706c0b746e28db68ac74eeeff75b5a6f498dd0 | [
"MIT"
] | null | null | null | 28.86755 | 130 | 0.705437 | 13,090 | package io.zbus.mq.server;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import io.netty.channel.ChannelHandler;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.ssl.SslContext;
import io.zbus.kit.ConfigKit;
import io.zbus.kit.FileKit;
import io.zbus.kit.NetKit;
import io.zbus.kit.StrKit;
import io.zbus.kit.logging.Logger;
import io.zbus.kit.logging.LoggerFactory;
import io.zbus.mq.Broker;
import io.zbus.mq.Message;
import io.zbus.mq.MessageQueue;
import io.zbus.mq.Protocol.ServerInfo;
import io.zbus.mq.Protocol.TopicInfo;
import io.zbus.proxy.http.HttpProxy;
import io.zbus.proxy.http.HttpProxyConfig;
import io.zbus.proxy.tcp.TcpProxy;
import io.zbus.proxy.tcp.TcpProxyConfig;
import io.zbus.transport.CodecInitializer;
import io.zbus.transport.IoAdaptor;
import io.zbus.transport.ServerAddress;
import io.zbus.transport.Session;
import io.zbus.transport.SslKit;
import io.zbus.transport.tcp.TcpServer;
public class MqServer extends TcpServer {
private static final Logger log = LoggerFactory.getLogger(MqServer.class);
private final Map<String, Session> sessionTable = new ConcurrentHashMap<String, Session>();
private final Map<String, MessageQueue> mqTable = new ConcurrentSkipListMap<String, MessageQueue>(String.CASE_INSENSITIVE_ORDER);
final Map<String, String> sslCertTable = new ConcurrentHashMap<String, String>();
private final ScheduledExecutorService scheduledExecutor = Executors.newSingleThreadScheduledExecutor();
private MqServerConfig config;
private ServerAddress serverAddress;
private MqAdaptor mqAdaptor;
private Tracker tracker;
private HttpProxy httpProxy;
private TcpProxy tcpProxy;
private TcpServer monitorServer;
private MonitorAdaptor monitorAdaptor = null;
private AtomicLong infoVersion = new AtomicLong(System.currentTimeMillis());
public MqServer(){
this(new MqServerConfig());
}
public MqServer(String configFile){
this(new MqServerConfig(configFile));
}
public MqServer(MqServerConfig serverConfig){
config = serverConfig.clone();
codec(new CodecInitializer() {
@Override
public void initPipeline(List<ChannelHandler> p) {
p.add(new HttpServerCodec());
p.add(new HttpObjectAggregator(loop.getPackageSizeLimit()));
p.add(new io.zbus.transport.http.MessageCodec());
p.add(new io.zbus.mq.MessageCodec());
}
});
boolean sslEnabled = config.isSslEnabled();
String certFileContent = "";
if (sslEnabled){
try{
certFileContent = FileKit.loadFile(config.getSslCertFile());
SslContext sslContext = SslKit.buildServerSsl(config.getSslCertFile(), config.getSslKeyFile());
loop.setSslContext(sslContext);
} catch (Exception e) {
log.error("SSL init error: " + e.getMessage());
throw new IllegalStateException(e.getMessage(), e.getCause());
}
}
String host = config.getServerHost();
if("0.0.0.0".equals(host)){
host = NetKit.getLocalIp();
}
String address = host+":"+config.getServerPort();
String serverName = config.getServerName();
if(!StrKit.isEmpty(serverName)){
if(serverName.contains(":")){
address = serverName;
} else {
address = serverName + ":"+config.getServerPort();
}
}
serverAddress = new ServerAddress(address, sslEnabled);
if(sslEnabled) { //Add current server's SSL certificate file to table
serverAddress.setCertificate(certFileContent);
sslCertTable.put(serverAddress.getAddress(), certFileContent);
}
this.scheduledExecutor.scheduleAtFixedRate(new Runnable() {
public void run() {
Iterator<Entry<String, MessageQueue>> iter = mqTable.entrySet().iterator();
while(iter.hasNext()){
Entry<String, MessageQueue> e = iter.next();
MessageQueue mq = e.getValue();
mq.cleanSession(null); //null to clean all inactive sessions
}
}
}, 1000, config.getCleanMqInterval(), TimeUnit.MILLISECONDS);
tracker = new Tracker(this);
if(config.isMonitorEnabled()){
Integer monitorPort = config.getMonitorPort();
this.monitorAdaptor = new MonitorAdaptor(this);
if(config.getMonitorPort() != null && monitorPort != config.getServerPort()){
this.monitorServer = new TcpServer(loop);
this.monitorServer.codec(new CodecInitializer() {
@Override
public void initPipeline(List<ChannelHandler> p) {
p.add(new HttpServerCodec());
p.add(new HttpObjectAggregator(loop.getPackageSizeLimit()));
p.add(new io.zbus.transport.http.MessageCodec());
p.add(new io.zbus.mq.MessageCodec());
}
});
this.monitorServer.start(monitorPort, this.monitorAdaptor);
}
}
//adaptor needs tracker built first
if(this.monitorServer != null){
mqAdaptor = new MqAdaptor(this, null);
} else {
mqAdaptor = new MqAdaptor(this, monitorAdaptor);
}
final boolean verbose = config.isVerbose();
if(config.getMessageLogger() == null){
mqAdaptor.setMessageLogger(new MessageLogger() {
@Override
public void log(Message message, Session session) {
if(verbose){
log.info("\n%s", message);
}
}
});
} else {
mqAdaptor.setMessageLogger(config.getMessageLogger());
}
try {
mqAdaptor.loadDiskQueue();
} catch (IOException e) {
log.error("Load Message Queue Error: " + e);
}
loadHttpProxy(config.getHttpProxyConfig());
loadTcpProxy(config.getTcpProxyConfig());
}
private void loadHttpProxy(HttpProxyConfig config){
if(config == null || config.getEntryTable().isEmpty()) return;
try {
Broker broker = new Broker(this);
config.setBroker(broker); //InProc broker
httpProxy = new HttpProxy(config);
httpProxy.start();
} catch (IOException e) {
log.error(e.getMessage(), e.getCause());
}
}
private void loadTcpProxy(TcpProxyConfig config){
if(config == null) return;
try {
tcpProxy = new TcpProxy(config);
tcpProxy.start();
} catch (Exception e) {
log.error(e.getMessage(), e.getCause());
}
}
@Override
public IoAdaptor getIoAdaptor() {
return this.mqAdaptor;
}
public void start() throws Exception{
log.info("Zbus starting...");
long start = System.currentTimeMillis();
this.start(config.getServerHost(), config.getServerPort(), mqAdaptor);
tracker.joinTracker(config.getTrackerList());
long end = System.currentTimeMillis();
log.info("Zbus(%s) started sucessfully in %d ms", serverAddress, (end-start));
}
@Override
public void close() throws IOException {
scheduledExecutor.shutdown();
mqAdaptor.close();
if(monitorServer != null){
monitorServer.close();
}
if(monitorAdaptor != null){
monitorAdaptor.close();
}
tracker.close();
if(httpProxy != null){
httpProxy.close();
}
if(tcpProxy != null) {
tcpProxy.close();
}
super.close();
}
public Map<String, MessageQueue> getMqTable() {
return mqTable;
}
public Map<String, Session> getSessionTable() {
return sessionTable;
}
public ServerAddress getServerAddress() {
return serverAddress;
}
public MqServerConfig getConfig() {
return config;
}
public Tracker getTracker() {
return tracker;
}
public ServerInfo serverInfo() {
Map<String, TopicInfo> table = new HashMap<String, TopicInfo>();
for (Map.Entry<String, MessageQueue> e : this.mqTable.entrySet()) {
TopicInfo info = e.getValue().topicInfo();
info.serverAddress = serverAddress;
table.put(e.getKey(), info);
}
ServerInfo info = new ServerInfo();
info.infoVersion = infoVersion.getAndIncrement();
info.serverAddress = serverAddress;
info.trackerList = this.tracker.trackerList();
info.topicTable = table;
return info;
}
public static void main(String[] args) throws Exception {
String configFile = ConfigKit.option(args, "-conf", "conf/zbus.xml");
final MqServer server;
try{
server = new MqServer(configFile);
server.start();
} catch (Exception e) {
e.printStackTrace(System.err);
log.warn(e.getMessage(), e);
return;
}
Runtime.getRuntime().addShutdownHook(new Thread(){
public void run() {
try {
server.close();
log.info("MqServer shutdown completed");
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
});
}
}
|
3e1ef828d78ae056b4b76581908b76a8980546f2 | 2,037 | java | Java | google-ads/src/main/java/com/google/ads/googleads/v4/services/MutateCustomerClientLinkRequestOrBuilder.java | katka-h/google-ads-java | 342a7cd4a213eb7106685e8dbbd91c2aabca84dc | [
"Apache-2.0"
] | 3 | 2020-12-20T18:56:52.000Z | 2021-07-29T12:12:02.000Z | google-ads/src/main/java/com/google/ads/googleads/v4/services/MutateCustomerClientLinkRequestOrBuilder.java | katka-h/google-ads-java | 342a7cd4a213eb7106685e8dbbd91c2aabca84dc | [
"Apache-2.0"
] | null | null | null | google-ads/src/main/java/com/google/ads/googleads/v4/services/MutateCustomerClientLinkRequestOrBuilder.java | katka-h/google-ads-java | 342a7cd4a213eb7106685e8dbbd91c2aabca84dc | [
"Apache-2.0"
] | 1 | 2021-02-15T04:54:10.000Z | 2021-02-15T04:54:10.000Z | 35.736842 | 136 | 0.712322 | 13,091 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v4/services/customer_client_link_service.proto
package com.google.ads.googleads.v4.services;
public interface MutateCustomerClientLinkRequestOrBuilder extends
// @@protoc_insertion_point(interface_extends:google.ads.googleads.v4.services.MutateCustomerClientLinkRequest)
com.google.protobuf.MessageOrBuilder {
/**
* <pre>
* Required. The ID of the customer whose customer link are being modified.
* </pre>
*
* <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code>
* @return The customerId.
*/
java.lang.String getCustomerId();
/**
* <pre>
* Required. The ID of the customer whose customer link are being modified.
* </pre>
*
* <code>string customer_id = 1 [(.google.api.field_behavior) = REQUIRED];</code>
* @return The bytes for customerId.
*/
com.google.protobuf.ByteString
getCustomerIdBytes();
/**
* <pre>
* Required. The operation to perform on the individual CustomerClientLink.
* </pre>
*
* <code>.google.ads.googleads.v4.services.CustomerClientLinkOperation operation = 2 [(.google.api.field_behavior) = REQUIRED];</code>
* @return Whether the operation field is set.
*/
boolean hasOperation();
/**
* <pre>
* Required. The operation to perform on the individual CustomerClientLink.
* </pre>
*
* <code>.google.ads.googleads.v4.services.CustomerClientLinkOperation operation = 2 [(.google.api.field_behavior) = REQUIRED];</code>
* @return The operation.
*/
com.google.ads.googleads.v4.services.CustomerClientLinkOperation getOperation();
/**
* <pre>
* Required. The operation to perform on the individual CustomerClientLink.
* </pre>
*
* <code>.google.ads.googleads.v4.services.CustomerClientLinkOperation operation = 2 [(.google.api.field_behavior) = REQUIRED];</code>
*/
com.google.ads.googleads.v4.services.CustomerClientLinkOperationOrBuilder getOperationOrBuilder();
}
|
3e1ef87a9e8ea05d787cd8f97f7ee3e68b4c7194 | 3,274 | java | Java | src/java/patents-indexer/xml/us/patent/grant/v40_040927/Figure.java | walid-shalaby/patents-indexer | 7a5c3192f28e2d8a8f0611e4e0ba755f1617d7ca | [
"CC0-1.0"
] | 3 | 2017-05-19T02:01:47.000Z | 2021-02-13T01:49:20.000Z | src/java/patents-indexer/xml/us/patent/grant/v40_040927/Figure.java | walid-shalaby/patents-indexer | 7a5c3192f28e2d8a8f0611e4e0ba755f1617d7ca | [
"CC0-1.0"
] | null | null | null | src/java/patents-indexer/xml/us/patent/grant/v40_040927/Figure.java | walid-shalaby/patents-indexer | 7a5c3192f28e2d8a8f0611e4e0ba755f1617d7ca | [
"CC0-1.0"
] | 2 | 2017-10-15T08:49:57.000Z | 2017-10-19T06:23:33.000Z | 22.895105 | 122 | 0.590715 | 13,092 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.12.16 at 01:06:01 PM EST
//
package xml.us.patent.grant.v40_040927;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlID;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.NormalizedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
/**
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"img"
})
@XmlRootElement(name = "figure")
public class Figure {
@XmlAttribute(name = "id")
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlID
protected String id;
@XmlAttribute(name = "num", required = true)
@XmlJavaTypeAdapter(NormalizedStringAdapter.class)
protected String num;
@XmlAttribute(name = "figure-labels")
@XmlJavaTypeAdapter(NormalizedStringAdapter.class)
protected String figureLabels;
@XmlElement(required = true)
protected Img img;
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
/**
* Gets the value of the num property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getNum() {
return num;
}
/**
* Sets the value of the num property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setNum(String value) {
this.num = value;
}
/**
* Gets the value of the figureLabels property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getFigureLabels() {
return figureLabels;
}
/**
* Sets the value of the figureLabels property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setFigureLabels(String value) {
this.figureLabels = value;
}
/**
* Gets the value of the img property.
*
* @return
* possible object is
* {@link Img }
*
*/
public Img getImg() {
return img;
}
/**
* Sets the value of the img property.
*
* @param value
* allowed object is
* {@link Img }
*
*/
public void setImg(Img value) {
this.img = value;
}
}
|
3e1ef89c827f197fad59b90ca99a2643092f906a | 1,222 | java | Java | app/src/main/java/com/hjq/demo/mvp/MvpPresenter.java | zhangshenzhen/AndroidProject_Structure | 6a13b2c728c5110ff948e639bd43a009f556f4a8 | [
"Apache-2.0"
] | 2 | 2019-11-02T08:42:35.000Z | 2020-03-09T10:21:00.000Z | app/src/main/java/com/hjq/demo/mvp/MvpPresenter.java | zhangshenzhen/AndroidProject_Structure | 6a13b2c728c5110ff948e639bd43a009f556f4a8 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/hjq/demo/mvp/MvpPresenter.java | zhangshenzhen/AndroidProject_Structure | 6a13b2c728c5110ff948e639bd43a009f556f4a8 | [
"Apache-2.0"
] | 1 | 2019-11-02T08:43:09.000Z | 2019-11-02T08:43:09.000Z | 23.960784 | 121 | 0.623568 | 13,093 | package com.hjq.demo.mvp;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
/**
* author : Android 轮子哥
* github : https://github.com/getActivity/AndroidProject
* time : 2018/11/17
* desc : MVP 业务基类
*/
public abstract class MvpPresenter<V extends IMvpView> implements InvocationHandler {
// 当前 View 对象
private V mView;
// 代理对象
private V mProxyView;
public void attach(V view){
mView = view;
// 使用动态代理,解决 getView 为空的问题
mProxyView = (V) Proxy.newProxyInstance(view.getClass().getClassLoader(), view.getClass().getInterfaces(), this);
}
/**
* {@link InvocationHandler}
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// 如果当前还是绑定状态就执行 View 的方法
return isAttached() ? method.invoke(mView, args) : null;
}
public void detach() {
mView = null;
// 这里注意不能把代理对象置空
// mProxyView = null;
}
public boolean isAttached() {
return mProxyView != null && mView != null;
}
public V getView() {
return mProxyView;
}
public abstract void start();
} |
3e1efb7a449ba9f0455926882d150dbfb0c45bd8 | 20,807 | java | Java | src/main/java/com/clarifai/grpc/api/status/BaseResponse.java | Clarifai/clarifai-java-grpc | 112d1b0150bdb718ca8e04a5a9bca39b110ffd87 | [
"Apache-2.0"
] | 5 | 2019-11-19T13:50:21.000Z | 2021-08-16T16:39:34.000Z | src/main/java/com/clarifai/grpc/api/status/BaseResponse.java | Clarifai/clarifai-java-grpc | 112d1b0150bdb718ca8e04a5a9bca39b110ffd87 | [
"Apache-2.0"
] | 9 | 2020-04-21T08:56:26.000Z | 2021-12-23T20:48:59.000Z | src/main/java/com/clarifai/grpc/api/status/BaseResponse.java | Clarifai/clarifai-java-grpc | 112d1b0150bdb718ca8e04a5a9bca39b110ffd87 | [
"Apache-2.0"
] | 3 | 2020-01-30T16:14:04.000Z | 2020-12-21T07:33:40.000Z | 33.83252 | 151 | 0.680829 | 13,094 | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: proto/clarifai/api/status/status.proto
package com.clarifai.grpc.api.status;
/**
* <pre>
* Base message to return when there is a internal server error that
* is not caught elsewhere.
* </pre>
*
* Protobuf type {@code clarifai.api.status.BaseResponse}
*/
public final class BaseResponse extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:clarifai.api.status.BaseResponse)
BaseResponseOrBuilder {
private static final long serialVersionUID = 0L;
// Use BaseResponse.newBuilder() to construct.
private BaseResponse(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private BaseResponse() {
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new BaseResponse();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private BaseResponse(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10: {
com.clarifai.grpc.api.status.Status.Builder subBuilder = null;
if (status_ != null) {
subBuilder = status_.toBuilder();
}
status_ = input.readMessage(com.clarifai.grpc.api.status.Status.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(status_);
status_ = subBuilder.buildPartial();
}
break;
}
default: {
if (!parseUnknownField(
input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.clarifai.grpc.api.status.StatusOuterClass.internal_static_clarifai_api_status_BaseResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.clarifai.grpc.api.status.StatusOuterClass.internal_static_clarifai_api_status_BaseResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.clarifai.grpc.api.status.BaseResponse.class, com.clarifai.grpc.api.status.BaseResponse.Builder.class);
}
public static final int STATUS_FIELD_NUMBER = 1;
private com.clarifai.grpc.api.status.Status status_;
/**
* <code>.clarifai.api.status.Status status = 1;</code>
* @return Whether the status field is set.
*/
public boolean hasStatus() {
return status_ != null;
}
/**
* <code>.clarifai.api.status.Status status = 1;</code>
* @return The status.
*/
public com.clarifai.grpc.api.status.Status getStatus() {
return status_ == null ? com.clarifai.grpc.api.status.Status.getDefaultInstance() : status_;
}
/**
* <code>.clarifai.api.status.Status status = 1;</code>
*/
public com.clarifai.grpc.api.status.StatusOrBuilder getStatusOrBuilder() {
return getStatus();
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (status_ != null) {
output.writeMessage(1, getStatus());
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (status_ != null) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(1, getStatus());
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.clarifai.grpc.api.status.BaseResponse)) {
return super.equals(obj);
}
com.clarifai.grpc.api.status.BaseResponse other = (com.clarifai.grpc.api.status.BaseResponse) obj;
if (hasStatus() != other.hasStatus()) return false;
if (hasStatus()) {
if (!getStatus()
.equals(other.getStatus())) return false;
}
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (hasStatus()) {
hash = (37 * hash) + STATUS_FIELD_NUMBER;
hash = (53 * hash) + getStatus().hashCode();
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.clarifai.grpc.api.status.BaseResponse parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.clarifai.grpc.api.status.BaseResponse parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.clarifai.grpc.api.status.BaseResponse parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.clarifai.grpc.api.status.BaseResponse parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.clarifai.grpc.api.status.BaseResponse parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.clarifai.grpc.api.status.BaseResponse parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.clarifai.grpc.api.status.BaseResponse parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.clarifai.grpc.api.status.BaseResponse parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static com.clarifai.grpc.api.status.BaseResponse parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.clarifai.grpc.api.status.BaseResponse parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static com.clarifai.grpc.api.status.BaseResponse parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.clarifai.grpc.api.status.BaseResponse parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.clarifai.grpc.api.status.BaseResponse prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* <pre>
* Base message to return when there is a internal server error that
* is not caught elsewhere.
* </pre>
*
* Protobuf type {@code clarifai.api.status.BaseResponse}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:clarifai.api.status.BaseResponse)
com.clarifai.grpc.api.status.BaseResponseOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.clarifai.grpc.api.status.StatusOuterClass.internal_static_clarifai_api_status_BaseResponse_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.clarifai.grpc.api.status.StatusOuterClass.internal_static_clarifai_api_status_BaseResponse_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.clarifai.grpc.api.status.BaseResponse.class, com.clarifai.grpc.api.status.BaseResponse.Builder.class);
}
// Construct using com.clarifai.grpc.api.status.BaseResponse.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
}
}
@java.lang.Override
public Builder clear() {
super.clear();
if (statusBuilder_ == null) {
status_ = null;
} else {
status_ = null;
statusBuilder_ = null;
}
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.clarifai.grpc.api.status.StatusOuterClass.internal_static_clarifai_api_status_BaseResponse_descriptor;
}
@java.lang.Override
public com.clarifai.grpc.api.status.BaseResponse getDefaultInstanceForType() {
return com.clarifai.grpc.api.status.BaseResponse.getDefaultInstance();
}
@java.lang.Override
public com.clarifai.grpc.api.status.BaseResponse build() {
com.clarifai.grpc.api.status.BaseResponse result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.clarifai.grpc.api.status.BaseResponse buildPartial() {
com.clarifai.grpc.api.status.BaseResponse result = new com.clarifai.grpc.api.status.BaseResponse(this);
if (statusBuilder_ == null) {
result.status_ = status_;
} else {
result.status_ = statusBuilder_.build();
}
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.clarifai.grpc.api.status.BaseResponse) {
return mergeFrom((com.clarifai.grpc.api.status.BaseResponse)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.clarifai.grpc.api.status.BaseResponse other) {
if (other == com.clarifai.grpc.api.status.BaseResponse.getDefaultInstance()) return this;
if (other.hasStatus()) {
mergeStatus(other.getStatus());
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.clarifai.grpc.api.status.BaseResponse parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (com.clarifai.grpc.api.status.BaseResponse) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private com.clarifai.grpc.api.status.Status status_;
private com.google.protobuf.SingleFieldBuilderV3<
com.clarifai.grpc.api.status.Status, com.clarifai.grpc.api.status.Status.Builder, com.clarifai.grpc.api.status.StatusOrBuilder> statusBuilder_;
/**
* <code>.clarifai.api.status.Status status = 1;</code>
* @return Whether the status field is set.
*/
public boolean hasStatus() {
return statusBuilder_ != null || status_ != null;
}
/**
* <code>.clarifai.api.status.Status status = 1;</code>
* @return The status.
*/
public com.clarifai.grpc.api.status.Status getStatus() {
if (statusBuilder_ == null) {
return status_ == null ? com.clarifai.grpc.api.status.Status.getDefaultInstance() : status_;
} else {
return statusBuilder_.getMessage();
}
}
/**
* <code>.clarifai.api.status.Status status = 1;</code>
*/
public Builder setStatus(com.clarifai.grpc.api.status.Status value) {
if (statusBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
status_ = value;
onChanged();
} else {
statusBuilder_.setMessage(value);
}
return this;
}
/**
* <code>.clarifai.api.status.Status status = 1;</code>
*/
public Builder setStatus(
com.clarifai.grpc.api.status.Status.Builder builderForValue) {
if (statusBuilder_ == null) {
status_ = builderForValue.build();
onChanged();
} else {
statusBuilder_.setMessage(builderForValue.build());
}
return this;
}
/**
* <code>.clarifai.api.status.Status status = 1;</code>
*/
public Builder mergeStatus(com.clarifai.grpc.api.status.Status value) {
if (statusBuilder_ == null) {
if (status_ != null) {
status_ =
com.clarifai.grpc.api.status.Status.newBuilder(status_).mergeFrom(value).buildPartial();
} else {
status_ = value;
}
onChanged();
} else {
statusBuilder_.mergeFrom(value);
}
return this;
}
/**
* <code>.clarifai.api.status.Status status = 1;</code>
*/
public Builder clearStatus() {
if (statusBuilder_ == null) {
status_ = null;
onChanged();
} else {
status_ = null;
statusBuilder_ = null;
}
return this;
}
/**
* <code>.clarifai.api.status.Status status = 1;</code>
*/
public com.clarifai.grpc.api.status.Status.Builder getStatusBuilder() {
onChanged();
return getStatusFieldBuilder().getBuilder();
}
/**
* <code>.clarifai.api.status.Status status = 1;</code>
*/
public com.clarifai.grpc.api.status.StatusOrBuilder getStatusOrBuilder() {
if (statusBuilder_ != null) {
return statusBuilder_.getMessageOrBuilder();
} else {
return status_ == null ?
com.clarifai.grpc.api.status.Status.getDefaultInstance() : status_;
}
}
/**
* <code>.clarifai.api.status.Status status = 1;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.clarifai.grpc.api.status.Status, com.clarifai.grpc.api.status.Status.Builder, com.clarifai.grpc.api.status.StatusOrBuilder>
getStatusFieldBuilder() {
if (statusBuilder_ == null) {
statusBuilder_ = new com.google.protobuf.SingleFieldBuilderV3<
com.clarifai.grpc.api.status.Status, com.clarifai.grpc.api.status.Status.Builder, com.clarifai.grpc.api.status.StatusOrBuilder>(
getStatus(),
getParentForChildren(),
isClean());
status_ = null;
}
return statusBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:clarifai.api.status.BaseResponse)
}
// @@protoc_insertion_point(class_scope:clarifai.api.status.BaseResponse)
private static final com.clarifai.grpc.api.status.BaseResponse DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.clarifai.grpc.api.status.BaseResponse();
}
public static com.clarifai.grpc.api.status.BaseResponse getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<BaseResponse>
PARSER = new com.google.protobuf.AbstractParser<BaseResponse>() {
@java.lang.Override
public BaseResponse parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new BaseResponse(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<BaseResponse> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<BaseResponse> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.clarifai.grpc.api.status.BaseResponse getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
|
3e1efb8db88258451ec481345e9f83b1f459e136 | 862 | java | Java | app/src/main/java/org/chromium/chrome/browser/ntp/cards/AboveTheFoldListItem.java | ApacheJondy/Browser | 0b3ea18f756fc9b504e25c1723c1620ea5c206ae | [
"Apache-2.0"
] | 62 | 2016-07-29T13:15:35.000Z | 2022-03-12T10:23:06.000Z | app/src/main/java/org/chromium/chrome/browser/ntp/cards/AboveTheFoldListItem.java | ApacheJondy/Browser | 0b3ea18f756fc9b504e25c1723c1620ea5c206ae | [
"Apache-2.0"
] | 2 | 2017-04-26T07:49:34.000Z | 2017-10-11T06:43:12.000Z | app/src/main/java/org/chromium/chrome/browser/ntp/cards/AboveTheFoldListItem.java | ApacheJondy/Browser | 0b3ea18f756fc9b504e25c1723c1620ea5c206ae | [
"Apache-2.0"
] | 21 | 2016-12-05T15:03:33.000Z | 2021-09-09T02:13:33.000Z | 41.047619 | 99 | 0.756381 | 13,095 | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.ntp.cards;
/**
* Item in the RecyclerView that will hold the above the fold contents for the NTP, i.e. the
* logo, tiles and search bar that are initially visible when opening the NTP.
*
* When using the new NTP UI, that is based on a RecyclerView, the view containing the entire
* content of the old UI is put in the AboveTheFoldListItem, and inserted in the RecyclerView.
* Other elements coming after it and initially off-screen are just added to the RecyclerView after
* that.
*/
class AboveTheFoldListItem implements NewTabPageListItem {
@Override
public int getType() {
return NewTabPageListItem.VIEW_TYPE_ABOVE_THE_FOLD;
}
} |
3e1efc89d6fcf55d0fae8c1a51af8d3a3df534f4 | 1,140 | java | Java | omnicrow-sdk/src/main/java/com/mobillium/omnicrow/utils/StoreService.java | mobillium/omnicrow-android | 36af8060fa5e706bf7be4b52f096c3ff0feac57e | [
"MIT"
] | 3 | 2017-11-29T11:50:30.000Z | 2019-07-03T08:14:45.000Z | omnicrow-sdk/src/main/java/com/mobillium/omnicrow/utils/StoreService.java | mobillium/omnicrow-android | 36af8060fa5e706bf7be4b52f096c3ff0feac57e | [
"MIT"
] | null | null | null | omnicrow-sdk/src/main/java/com/mobillium/omnicrow/utils/StoreService.java | mobillium/omnicrow-android | 36af8060fa5e706bf7be4b52f096c3ff0feac57e | [
"MIT"
] | null | null | null | 26.511628 | 98 | 0.780702 | 13,096 | package com.mobillium.omnicrow.utils;
import com.mobillium.omnicrow.webservice.models.ActionBeacon;
import com.mobillium.omnicrow.webservice.models.TrackedBeacon;
import java.util.List;
/**
* Created by oguzhandongul on 15/11/2017.
*/
public interface StoreService {
boolean createBeacon(final TrackedBeacon beacon);
boolean updateBeacon(final TrackedBeacon beacon);
boolean deleteBeacon(final String id, boolean cascade);
TrackedBeacon getBeacon(final String id);
List<TrackedBeacon> getBeacons();
boolean updateBeaconDistance(final String id, double distance);
boolean updateBeaconAction(ActionBeacon beacon);
boolean createBeaconAction(ActionBeacon beacon);
List<ActionBeacon> getBeaconActions(final String beaconId);
boolean deleteBeaconAction(final int id);
boolean deleteBeaconActions(final String beaconId);
List<ActionBeacon> getAllEnabledBeaconActions();
boolean updateBeaconActionEnable(final int id, boolean enable);
List<ActionBeacon> getEnabledBeaconActionsByEvent(final int eventType, final String beaconId);
boolean isBeaconExists(String id);
} |
3e1efcf2305d1ff7b51a50f6d1865c0f0bd9107a | 951 | java | Java | src/test/java/org/xbib/time/schedule/util/Integers.java | jprante/time | bb8a53148b00902701dd897615705c532cad7930 | [
"Apache-2.0"
] | null | null | null | src/test/java/org/xbib/time/schedule/util/Integers.java | jprante/time | bb8a53148b00902701dd897615705c532cad7930 | [
"Apache-2.0"
] | null | null | null | src/test/java/org/xbib/time/schedule/util/Integers.java | jprante/time | bb8a53148b00902701dd897615705c532cad7930 | [
"Apache-2.0"
] | null | null | null | 22.116279 | 60 | 0.539432 | 13,097 | package org.xbib.time.schedule.util;
import com.google.common.collect.ForwardingSet;
import java.util.HashSet;
import java.util.Set;
public class Integers extends ForwardingSet<Integer> {
private final Set<Integer> delegate;
public Integers(int... integers) {
delegate = new HashSet<>();
with(integers);
}
@Override
protected Set<Integer> delegate() {
return delegate;
}
public Integers with(int... integers) {
for (int integer : integers) {
add(integer);
}
return this;
}
public Integers withRange(int start, int end) {
for (int i = start; i <= end; i++) {
add(i);
}
return this;
}
public Integers withRange(int start, int end, int mod) {
for (int i = start; i <= end; i++) {
if ((i - start) % mod == 0) {
add(i);
}
}
return this;
}
}
|
3e1efd1ae30428f59d0b75098cd4b8c8ab501d51 | 703 | java | Java | src/main/java/com/cjburkey/claimchunk/service/prereq/claim/PermissionPrereq.java | Geolykt/ClaimChunk | ea4ade28f4b7623d4bbca54064ce3c903711120c | [
"MIT"
] | null | null | null | src/main/java/com/cjburkey/claimchunk/service/prereq/claim/PermissionPrereq.java | Geolykt/ClaimChunk | ea4ade28f4b7623d4bbca54064ce3c903711120c | [
"MIT"
] | null | null | null | src/main/java/com/cjburkey/claimchunk/service/prereq/claim/PermissionPrereq.java | Geolykt/ClaimChunk | ea4ade28f4b7623d4bbca54064ce3c903711120c | [
"MIT"
] | null | null | null | 25.107143 | 76 | 0.721195 | 13,098 | package com.cjburkey.claimchunk.service.prereq.claim;
import com.cjburkey.claimchunk.Utils;
import org.jetbrains.annotations.NotNull;
import java.util.Optional;
import javax.annotation.Nonnull;
public class PermissionPrereq implements IClaimPrereq {
@Override
public int getWeight() {
// Try to check permissions as early as possible
return -100;
}
@Override
public boolean getPassed(@Nonnull @NotNull PrereqClaimData data) {
return Utils.hasPerm(data.player, true, "claim");
}
@Override
public Optional<String> getErrorMessage(@Nonnull PrereqClaimData data) {
return Optional.of(data.claimChunk.getMessages().claimNoPerm);
}
}
|
3e1efd51f8ad230632c35243833e0bc01edafcef | 3,931 | java | Java | src/main/java/com/github/thatcherdev/betterbackdoor/Setup.java | PleXone2019/BetterBackdoor | 8859a8b9a19638e41226b27692b3faaf67d7781c | [
"MIT"
] | null | null | null | src/main/java/com/github/thatcherdev/betterbackdoor/Setup.java | PleXone2019/BetterBackdoor | 8859a8b9a19638e41226b27692b3faaf67d7781c | [
"MIT"
] | null | null | null | src/main/java/com/github/thatcherdev/betterbackdoor/Setup.java | PleXone2019/BetterBackdoor | 8859a8b9a19638e41226b27692b3faaf67d7781c | [
"MIT"
] | 1 | 2020-10-14T07:59:31.000Z | 2020-10-14T07:59:31.000Z | 42.728261 | 158 | 0.687357 | 13,099 | package com.github.thatcherdev.betterbackdoor;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import com.github.thatcherdev.betterbackdoor.backend.Utils;
public class Setup {
/**
* Sets up backdoor.
* <p>
* If {@link packageJre} is true, copies the current machines JRE to directory
* 'backdoor' and {@link #createBat(String, String, String)} is used to create a
* '.bat' file for running the backdoor in the JRE. If {@link packageJre} is
* false but directory 'jre' containing a Windows JRE distribution exists, 'jre'
* is copied to 'backdoor' and {@link #createBat(String, String, String)} is
* used to create a '.bat' file for running the backdoor in the JRE. 'run.jar'
* is copied from 'target' to 'backdoor' and 'ip', a text file containing the
* current machine's IPv4 address, is appended into it using
* {@link #appendJar(String, String, String)}.
*
* @param packageJre if a JRE should be packaged with backdoor
* @throws IOException
*/
public static void create(boolean packageJre) throws IOException {
if (packageJre) {
String jrePath = System.getProperty("java.home");
FileUtils.copyDirectory(new File(jrePath + File.separator + "bin"),
new File("backdoor" + File.separator + "jre" + File.separator + "bin"));
FileUtils.copyDirectory(new File(jrePath + File.separator + "lib"),
new File("backdoor" + File.separator + "jre" + File.separator + "lib"));
createBat("backdoor" + File.separator + "run.bat");
} else if (new File("jre").isDirectory()) {
FileUtils.copyDirectory(new File("jre"), new File("backdoor" + File.separator + "jre"));
createBat("backdoor" + File.separator + "run.bat");
}
FileUtils.copyFile(new File("target" + File.separator + "run.jar"),
new File("backdoor" + File.separator + "run.jar"));
appendJar("backdoor" + File.separator + "run.jar", "ip", Utils.getIP());
}
/**
* Creates a '.bat' batch file for running a jar file in a Java Runtime
* Environment.
*
* @param filePath path of '.bat' batch file to create
* @throws FileNotFoundException
*/
private static void createBat(String filePath) throws FileNotFoundException {
PrintWriter out = new PrintWriter(new File(filePath));
out.println(
"@echo off\n%~d0 & cd %~dp0\necho Set objShell = WScript.CreateObject(\"WScript.Shell\")>run.vbs\necho objShell.Run \"cmd /c "
+ "jre\\bin\\java -jar run.jar\", ^0, True>>run.vbs\nstart run.vbs\ncall:delvbs\n:delvbs\nif exist run.vbs (\n timeout 3 > nul\n del run.vbs\n @exit\n"
+ ") else (\ncall:delvbs\n)\ngoto:eof");
out.flush();
out.close();
}
/**
* Appends a new file with name {@link filename} and contents
* {@link fileContents} into existing jar file with name {@link jarFile}.
*
* @param jarFile name of jar file to append
* @param filename name of new file to append in jar
* @param fileContents contents of new file to append in jar
* @throws IOException
*/
private static void appendJar(String jarFile, String filename, String fileContents) throws IOException {
Map<String, String> env = new HashMap<>();
env.put("create", "true");
try (FileSystem fileSystem = FileSystems.newFileSystem(URI.create("jar:" + Paths.get(jarFile).toUri()), env)) {
try (Writer writer = Files.newBufferedWriter(fileSystem.getPath(filename), StandardCharsets.UTF_8,
StandardOpenOption.CREATE)) {
writer.write(fileContents);
writer.close();
}
}
}
} |
3e1efe2389f0fe219bd15876673d9e3e11a630fd | 738 | java | Java | core/src/com/crashinvaders/common/scene2d/actions/ActAction.java | alexkarezin/gdx-texture-packer-gui | 3fa093c078660e04c0cf3323d98a3d7bbbfab1be | [
"Apache-2.0"
] | 479 | 2016-09-05T01:00:15.000Z | 2022-03-24T09:49:23.000Z | core/src/com/crashinvaders/common/scene2d/actions/ActAction.java | alexkarezin/gdx-texture-packer-gui | 3fa093c078660e04c0cf3323d98a3d7bbbfab1be | [
"Apache-2.0"
] | 126 | 2016-09-06T21:11:08.000Z | 2022-03-30T14:09:02.000Z | core/src/com/crashinvaders/common/scene2d/actions/ActAction.java | alexkarezin/gdx-texture-packer-gui | 3fa093c078660e04c0cf3323d98a3d7bbbfab1be | [
"Apache-2.0"
] | 82 | 2016-09-06T21:53:34.000Z | 2022-03-12T17:33:22.000Z | 21.705882 | 49 | 0.596206 | 13,100 | package com.crashinvaders.common.scene2d.actions;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.scenes.scene2d.Action;
import com.badlogic.gdx.scenes.scene2d.Actor;
public class ActAction extends Action {
private float delta;
public void setDelta(float delta) {
this.delta = delta;
}
@Override
public void reset() {
super.reset();
delta = 0f;
}
@Override
public boolean act(float delta) {
final Actor target = getTarget();
final float timeDelta = this.delta;
Gdx.app.postRunnable(new Runnable() {
@Override
public void run() {
target.act(timeDelta);
}
});
return true;
}
}
|
3e1efe33b4f1080ea14f9bdabfdbe253da3cca27 | 4,144 | java | Java | aws-java-sdk-importexport/src/main/java/com/amazonaws/services/importexport/model/GetShippingLabelResult.java | erbrito/aws-java-sdk | 853b7e82d708465aca43c6013ab1221ce4d50852 | [
"Apache-2.0"
] | 1 | 2019-02-08T15:23:16.000Z | 2019-02-08T15:23:16.000Z | aws-java-sdk-importexport/src/main/java/com/amazonaws/services/importexport/model/GetShippingLabelResult.java | erbrito/aws-java-sdk | 853b7e82d708465aca43c6013ab1221ce4d50852 | [
"Apache-2.0"
] | 1 | 2020-09-21T09:46:45.000Z | 2020-09-21T09:46:45.000Z | aws-java-sdk-importexport/src/main/java/com/amazonaws/services/importexport/model/GetShippingLabelResult.java | erbrito/aws-java-sdk | 853b7e82d708465aca43c6013ab1221ce4d50852 | [
"Apache-2.0"
] | null | null | null | 30.470588 | 149 | 0.6361 | 13,101 | /*
* Copyright 2012-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.importexport.model;
import java.io.Serializable;
import javax.annotation.Generated;
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class GetShippingLabelResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {
private String shippingLabelURL;
private String warning;
/**
* @param shippingLabelURL
*/
public void setShippingLabelURL(String shippingLabelURL) {
this.shippingLabelURL = shippingLabelURL;
}
/**
* @return
*/
public String getShippingLabelURL() {
return this.shippingLabelURL;
}
/**
* @param shippingLabelURL
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetShippingLabelResult withShippingLabelURL(String shippingLabelURL) {
setShippingLabelURL(shippingLabelURL);
return this;
}
/**
* @param warning
*/
public void setWarning(String warning) {
this.warning = warning;
}
/**
* @return
*/
public String getWarning() {
return this.warning;
}
/**
* @param warning
* @return Returns a reference to this object so that method calls can be chained together.
*/
public GetShippingLabelResult withWarning(String warning) {
setWarning(warning);
return this;
}
/**
* Returns a string representation of this object; useful for testing and debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getShippingLabelURL() != null)
sb.append("ShippingLabelURL: ").append(getShippingLabelURL()).append(",");
if (getWarning() != null)
sb.append("Warning: ").append(getWarning());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof GetShippingLabelResult == false)
return false;
GetShippingLabelResult other = (GetShippingLabelResult) obj;
if (other.getShippingLabelURL() == null ^ this.getShippingLabelURL() == null)
return false;
if (other.getShippingLabelURL() != null && other.getShippingLabelURL().equals(this.getShippingLabelURL()) == false)
return false;
if (other.getWarning() == null ^ this.getWarning() == null)
return false;
if (other.getWarning() != null && other.getWarning().equals(this.getWarning()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getShippingLabelURL() == null) ? 0 : getShippingLabelURL().hashCode());
hashCode = prime * hashCode + ((getWarning() == null) ? 0 : getWarning().hashCode());
return hashCode;
}
@Override
public GetShippingLabelResult clone() {
try {
return (GetShippingLabelResult) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
}
|
3e1eff21c85ec9bc2e4e144c90dbbaadcff655e3 | 572 | java | Java | src/main/java/nl/corwur/cytoscape/neo4j/internal/neo4j/ConnectionParameter.java | swarris/cytoscapeneo4j | 8e3892f93dcd5f65ccaaa620729aeac60b4b5a25 | [
"MIT"
] | null | null | null | src/main/java/nl/corwur/cytoscape/neo4j/internal/neo4j/ConnectionParameter.java | swarris/cytoscapeneo4j | 8e3892f93dcd5f65ccaaa620729aeac60b4b5a25 | [
"MIT"
] | null | null | null | src/main/java/nl/corwur/cytoscape/neo4j/internal/neo4j/ConnectionParameter.java | swarris/cytoscapeneo4j | 8e3892f93dcd5f65ccaaa620729aeac60b4b5a25 | [
"MIT"
] | null | null | null | 22 | 78 | 0.636364 | 13,102 | package nl.corwur.cytoscape.neo4j.internal.neo4j;
public class ConnectionParameter {
private final String host;
private final String username;
private final char[] password;
public ConnectionParameter(String url, String username, char[] password) {
this.host = url;
this.username = username;
this.password = password;
}
String getBoltUrl() {
return "bolt://" + host;
}
String getUsername() {
return username;
}
String getPasswordAsString() {
return new String(password);
}
}
|
3e1eff481e0d53a0e336b14c70827da3fbf2673b | 491 | java | Java | thread/src/main/java/com/edoup/thread/practise/concurrent/synchronize/reentrant/ReentrantDemo2.java | EDOUP/java2020 | 9044214cb7f41ca40579c4d27753a0c73718678e | [
"Apache-2.0"
] | null | null | null | thread/src/main/java/com/edoup/thread/practise/concurrent/synchronize/reentrant/ReentrantDemo2.java | EDOUP/java2020 | 9044214cb7f41ca40579c4d27753a0c73718678e | [
"Apache-2.0"
] | null | null | null | thread/src/main/java/com/edoup/thread/practise/concurrent/synchronize/reentrant/ReentrantDemo2.java | EDOUP/java2020 | 9044214cb7f41ca40579c4d27753a0c73718678e | [
"Apache-2.0"
] | null | null | null | 20.458333 | 79 | 0.613035 | 13,103 | package com.edoup.thread.practise.concurrent.synchronize.reentrant;
/**
* <p>
* synchronized -- 可重入锁
* </p>
*
* @author edoup
* @date 2020/4/19 15:06
*/
public class ReentrantDemo2 {
public static void main(String[] args) {
new Thread(()->{doSomething();}).start();
new Thread(()->{doSomething();}).start();
}
private static synchronized void doSomething() {
System.out.println("doSomething()" + Thread.currentThread().getName());
}
}
|
3e1eff4d4fb05fd2af93a72f1ebadc0b050550a9 | 359 | java | Java | quickstart-spring-boot-netty-action/quickstart-spring-boot-netty-action-common/src/main/java/org/quickstart/spring/boot/netty/action/common/util/RandomUtil.java | youngzil/quickstart-spring-boot | 94fde769209bdc3b8a6a174f6bfa8656d0a266db | [
"Apache-2.0"
] | null | null | null | quickstart-spring-boot-netty-action/quickstart-spring-boot-netty-action-common/src/main/java/org/quickstart/spring/boot/netty/action/common/util/RandomUtil.java | youngzil/quickstart-spring-boot | 94fde769209bdc3b8a6a174f6bfa8656d0a266db | [
"Apache-2.0"
] | 7 | 2020-03-04T22:07:18.000Z | 2022-01-21T23:22:41.000Z | quickstart-spring-boot-netty-action/quickstart-spring-boot-netty-action-common/src/main/java/org/quickstart/spring/boot/netty/action/common/util/RandomUtil.java | youngzil/quickstart-spring-boot | 94fde769209bdc3b8a6a174f6bfa8656d0a266db | [
"Apache-2.0"
] | 1 | 2020-09-01T09:17:51.000Z | 2020-09-01T09:17:51.000Z | 17.095238 | 60 | 0.629526 | 13,104 | package org.quickstart.spring.boot.netty.action.common.util;
import java.util.Random;
import java.util.UUID;
/**
* Function:
*
* @author crossoverJie
* Date: 22/05/2018 17:10
* @since JDK 1.8
*/
public class RandomUtil {
public static int getRandom() {
double random = Math.random();
return (int) (random * 100);
}
}
|
3e1f0029e375dfed9f5bd0cf3a00a8a46bf23f1b | 806 | java | Java | src/main/java/edu/mit/jmwe/detect/IMWEDetectorFilter.java | librairy/multi-word-annotator | d258ba3d8577a8b901c941f18c261ad77e4480cb | [
"Apache-2.0"
] | null | null | null | src/main/java/edu/mit/jmwe/detect/IMWEDetectorFilter.java | librairy/multi-word-annotator | d258ba3d8577a8b901c941f18c261ad77e4480cb | [
"Apache-2.0"
] | null | null | null | src/main/java/edu/mit/jmwe/detect/IMWEDetectorFilter.java | librairy/multi-word-annotator | d258ba3d8577a8b901c941f18c261ad77e4480cb | [
"Apache-2.0"
] | null | null | null | 36.636364 | 82 | 0.57196 | 13,105 | /********************************************************************************
* Java MWE Library (jMWE) v1.0.2
* Copyright (c) 2008-2015 Mark A. Finlayson & Nidhi Kulkarni
*
* This program and the accompanying materials are made available under the
* terms of the jMWE License which accompanies this distribution.
* Please check the attached license for more details.
*******************************************************************************/
package edu.mit.jmwe.detect;
/**
* An interface for MWE detectors that act as filters for other MWE detectors
*
* @author M.A. Finlayson
* @version $Id: IMWEDetectorFilter.java 301 2011-05-05 23:07:33Z markaf $
* @since jMWE 1.0.0
*/
public interface IMWEDetectorFilter extends IMWEDetector, IHasMWEDetector {
}
|
3e1f018c09556b284e518c289871d4b70ead0ee1 | 2,789 | java | Java | webapp/src/test/java/com/box/l10n/mojito/service/security/user/UserServiceTest.java | marksteele/mojito | c12887da1b62ed169a9ee1a02c175f059e837872 | [
"Apache-2.0"
] | 325 | 2016-08-18T05:21:04.000Z | 2022-03-22T15:14:23.000Z | webapp/src/test/java/com/box/l10n/mojito/service/security/user/UserServiceTest.java | marksteele/mojito | c12887da1b62ed169a9ee1a02c175f059e837872 | [
"Apache-2.0"
] | 190 | 2016-09-12T21:00:31.000Z | 2022-03-21T21:59:58.000Z | webapp/src/test/java/com/box/l10n/mojito/service/security/user/UserServiceTest.java | samqws-marketing/box_mojito | 65290aeb818102fa2443a637efdccebebfed1eb9 | [
"Apache-2.0"
] | 72 | 2016-08-19T20:37:04.000Z | 2022-03-06T16:09:07.000Z | 38.736111 | 131 | 0.723915 | 13,106 | package com.box.l10n.mojito.service.security.user;
import com.box.l10n.mojito.entity.security.user.User;
import com.box.l10n.mojito.security.Role;
import com.box.l10n.mojito.service.assetExtraction.ServiceTestBase;
import com.box.l10n.mojito.test.TestIdWatcher;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
import org.junit.Rule;
public class UserServiceTest extends ServiceTestBase {
@Autowired
UserService userService;
@Autowired
UserRepository userRepository;
@Rule
public TestIdWatcher testIdWatcher = new TestIdWatcher();
@Test
public void testCreateBasicUser() {
String username = testIdWatcher.getEntityName("testUser");
String pwd = "testPwd1234";
String surname = "surname";
String givenName = "givenName";
String commonName = "commonName";
Role userRole = Role.USER;
String expectedAuthorityName = userService.createAuthorityName(userRole);
User userWithRole = userService.createUserWithRole(username, pwd, userRole, givenName, surname, commonName, false);
User byUsername = userRepository.findByUsername(username);
assertEquals("ID should be the same", userWithRole.getId(), byUsername.getId());
assertNotSame("Password should not be plain", pwd, byUsername.getPassword());
assertFalse("Should have at least one authority", byUsername.getAuthorities().isEmpty());
assertEquals("Should have user role", expectedAuthorityName, byUsername.getAuthorities().iterator().next().getAuthority());
assertEquals(surname, byUsername.getSurname());
assertEquals(givenName, byUsername.getGivenName());
assertEquals(commonName, byUsername.getCommonName());
}
@Test(expected = IllegalStateException.class)
public void testCreateUserWithEmptyPassword() {
String username = "testUser";
String pwd = "";
userService.createUserWithRole(username, pwd, Role.USER);
}
@Test(expected = NullPointerException.class)
public void testCreateUserWithNullPassword() {
String username = "testUser";
String pwd = null;
userService.createUserWithRole(username, pwd, Role.USER);
}
@Test
public void testSystemUserExist() {
User systemUser = userService.findSystemUser();
assertNotNull("System user should always been created.", systemUser);
assertNotNull("System user has a createdByUser", systemUser.getCreatedByUser());
assertFalse("System user should be disabled", systemUser.getEnabled());
}
}
|
3e1f023743d090aea3ca70f9a32df184d1986cae | 7,408 | java | Java | wejar-net/src/main/java/org/wejar/net/http/utils/HttpResponseInfo.java | WejarChan/wejar-utility | e22e40430c77524d39fb8d21da63b4ee786f0b80 | [
"MIT"
] | null | null | null | wejar-net/src/main/java/org/wejar/net/http/utils/HttpResponseInfo.java | WejarChan/wejar-utility | e22e40430c77524d39fb8d21da63b4ee786f0b80 | [
"MIT"
] | 6 | 2020-03-04T22:34:18.000Z | 2021-01-20T23:43:32.000Z | wejar-net/src/main/java/org/wejar/net/http/utils/HttpResponseInfo.java | WejarChan/wejar-utility | e22e40430c77524d39fb8d21da63b4ee786f0b80 | [
"MIT"
] | 1 | 2019-07-30T02:21:27.000Z | 2019-07-30T02:21:27.000Z | 27.641791 | 533 | 0.44101 | 13,107 | package org.wejar.net.http.utils;
import java.io.IOException;
import java.util.Locale;
import org.apache.http.Consts;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.ProtocolVersion;
import org.apache.http.StatusLine;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HttpResponseInfo {
private Logger logger = LoggerFactory.getLogger(HttpResponseInfo.class);
private StatusLine statusLine;
private Header[] headers;
private Locale locale;
private HttpParams params;
private String content;
private String contentType;
private String contentEncoding;
private ProtocolVersion protocolVersion;
public HttpResponseInfo(StatusLine statusLine, Header[] allHeaders, Locale locale, HttpParams params, HttpEntity entity,
ProtocolVersion protocolVersion) {
this.statusLine = statusLine;
this.headers = allHeaders;
this.locale = locale;
this.params = params;
try {
this.content = EntityUtils.toString(entity, Consts.UTF_8);
this.contentType = entity.getContentType().getValue();
if(entity.getContentEncoding() != null){
this.contentEncoding = entity.getContentEncoding().toString();
}
} catch (IOException e) {
logger.info("解析返回信息异常",e);
}
this.protocolVersion = protocolVersion;
}
public StatusLine getStatusLine() {
return statusLine;
}
public Header[] getHeaders() {
return headers;
}
public Locale getLocale() {
return locale;
}
public HttpParams getParams() {
return params;
}
public ProtocolVersion getProtocolVersion() {
return protocolVersion;
}
public String getContent() {
return content;
}
public String getContentType() {
return contentType;
}
public String getContentEncoding() {
return contentEncoding;
}
//
// {
// "headers": [{
// "valuePos": 5,
// "elements": [{
// "parameterCount": 0,
// "name": "Wed",
// "parameters": [],
// "value": ""
// },
// {
// "parameterCount": 0,
// "name": "20 Sep 2017 03:31:45 GMT",
// "parameters": [],
// "value": ""
// }],
// "name": "Date",
// "buffer": {
// "empty": false,
// "full": false
// },
// "value": "Wed, 20 Sep 2017 03:31:45 GMT"
// },
// {
// "valuePos": 13,
// "elements": [{
// "parameterCount": 1,
// "name": "text/html",
// "parameters": [{
// "name": "charset",
// "value": "UTF-8"
// }],
// "value": ""
// }],
// "name": "Content-Type",
// "buffer": {
// "empty": false,
// "full": false
// },
// "value": "text/html; charset=UTF-8"
// },
// {
// "valuePos": 18,
// "elements": [{
// "parameterCount": 0,
// "name": "chunked",
// "parameters": [],
// "value": ""
// }],
// "name": "Transfer-Encoding",
// "buffer": {
// "empty": false,
// "full": false
// },
// "value": "chunked"
// },
// {
// "valuePos": 11,
// "elements": [{
// "parameterCount": 0,
// "name": "keep-alive",
// "parameters": [],
// "value": ""
// }],
// "name": "Connection",
// "buffer": {
// "empty": false,
// "full": false
// },
// "value": "keep-alive"
// },
// {
// "valuePos": 11,
// "elements": [{
// "parameterCount": 0,
// "name": "timeout",
// "parameters": [],
// "value": "20"
// }],
// "name": "Keep-Alive",
// "buffer": {
// "empty": false,
// "full": false
// },
// "value": "timeout=20"
// },
// {
// "valuePos": 5,
// "elements": [{
// "parameterCount": 0,
// "name": "Accept-Encoding",
// "parameters": [],
// "value": ""
// }],
// "name": "Vary",
// "buffer": {
// "empty": false,
// "full": false
// },
// "value": "Accept-Encoding"
// },
// {
// "valuePos": 7,
// "elements": [{
// "parameterCount": 0,
// "name": "WAF1.0",
// "parameters": [],
// "value": ""
// }],
// "name": "Server",
// "buffer": {
// "empty": false,
// "full": false
// },
// "value": "WAF1.0"
// },
// {
// "valuePos": 26,
// "elements": [{
// "parameterCount": 0,
// "name": "max-age",
// "parameters": [],
// "value": "31536000"
// }],
// "name": "Strict-Transport-Security",
// "buffer": {
// "empty": false,
// "full": false
// },
// "value": "max-age=31536000"
// },
// {
// "valuePos": 23,
// "elements": [{
// "parameterCount": 0,
// "name": "nosniff",
// "parameters": [],
// "value": ""
// }],
// "name": "X-Content-Type-Options",
// "buffer": {
// "empty": false,
// "full": false
// },
// "value": "nosniff"
// }],
// "statusLine": {
// "reasonPhrase": "OK",
// "protocolVersion": {
// "protocol": "HTTP",
// "major": 1,
// "minor": 1
// },
// "statusCode": 200
// },
// "contentEncoding": "",
// "protocolVersion": {
// "protocol": "HTTP",
// "major": 1,
// "minor": 1
// },
// "locale": {
// "unicodeLocaleKeys": [],
// "ISO3Language": "zho",
// "country": "CN",
// "displayName": "中文 (中国)",
// "displayVariant": "",
// "language": "zh",
// "displayLanguage": "中文",
// "script": "",
// "unicodeLocaleAttributes": [],
// "displayCountry": "中国",
// "ISO3Country": "CHN",
// "variant": "",
// "extensionKeys": [],
// "displayScript": ""
// },
// "params": {
// "names": []
// },
// "contentType": "text/html; charset=UTF-8",
// "content": "{\"biz_content\":{\"mch_id\":\"10000272\",\"order_no\":\"80020170920113145126703206400201\",\"out_order_no\":\"1505878381781\",\"pay_params\":{\"appId\":\"wxc3f90f556263fb0c\",\"nonceStr\":\"1505878305\",\"package\":\"prepay_id=wx20170920113145418d72c4b60289588677\",\"paySign\":\"F8E146E3E227977C6B8970427BC6311B\",\"signType\":\"MD5\",\"timeStamp\":\"1505878305\"},\"payment_fee\":\"100\"},\"ret_code\":\"0\",\"ret_msg\":\"success\",\"sign_type\":\"MD5\",\"signature\":\"63C40C108B81CE93AB769267FF2EEC5D\"}\r\n"
// }
}
|
3e1f023d6e5ebc8558c34c54d9bc2b2b98557ed2 | 2,820 | java | Java | app/src/main/java/com/example/moviestreamingapp/adapters/CastAdapter.java | Debanshu777/Movie_Streaming_App | 76c49c4bd9ac4394dcf83d6b3d9458705a80a74d | [
"Apache-2.0"
] | 3 | 2020-07-15T18:40:34.000Z | 2020-10-09T14:26:38.000Z | app/src/main/java/com/example/moviestreamingapp/adapters/CastAdapter.java | Debanshu777/Movie_Streaming_App | 76c49c4bd9ac4394dcf83d6b3d9458705a80a74d | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/moviestreamingapp/adapters/CastAdapter.java | Debanshu777/Movie_Streaming_App | 76c49c4bd9ac4394dcf83d6b3d9458705a80a74d | [
"Apache-2.0"
] | 2 | 2021-06-22T11:03:54.000Z | 2021-06-22T12:07:33.000Z | 34.390244 | 140 | 0.703546 | 13,108 | package com.example.moviestreamingapp.adapters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DecodeFormat;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.Target;
import com.example.moviestreamingapp.R;
import com.example.moviestreamingapp.models.Cast;
import com.example.moviestreamingapp.models.CastItemClickListener;
import java.util.List;
import de.hdodenhof.circleimageview.CircleImageView;
public class CastAdapter extends RecyclerView.Adapter<CastAdapter.CastViewHolder> {
Context context;
List<Cast> mData;
CastItemClickListener castItemClickListener;
public CastAdapter(Context context, List<Cast> mData,CastItemClickListener castitemClickListener) {
this.context = context;
this.mData = mData;
this.castItemClickListener=castitemClickListener;
}
@NonNull
@Override
public CastViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view= LayoutInflater.from(context).inflate(R.layout.item_cast,parent,false);
return new CastViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull CastViewHolder holder, int position) {
Cast model=mData.get(position);
holder.cast_name.setText(model.getName());
RequestOptions requestOptions=new RequestOptions();
if(model.getProfilePath()!=null) {
Glide.with(context).load("https://image.tmdb.org/t/p/w500" + model.getProfilePath()).apply(RequestOptions.circleCropTransform())
.transition(DrawableTransitionOptions.withCrossFade())
.into(holder.cast_img);
}
}
@Override
public int getItemCount() {
if(mData.size()<=10){
return mData.size();
}
else
return 10;
}
public class CastViewHolder extends RecyclerView.ViewHolder{
ImageView cast_img;
TextView cast_name;
public CastViewHolder(@NonNull View itemView) {
super(itemView);
cast_img=itemView.findViewById(R.id.image_cast);
cast_name=itemView.findViewById(R.id.cast_name);
cast_img.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
castItemClickListener.onMovieClick(mData.get(getAdapterPosition()),cast_img);
}
});
}
}
}
|
3e1f0251cf2bdbf1f2222c01580585acc6d4e2b6 | 1,846 | java | Java | src/main/java/jp/ac/utokyo/rcast/karkinos/exec/CNVInfo.java | hirokiuedaRcast/karkinos | 9525c4e01a049a30261e306ecc9c4e78b15d8ac2 | [
"Apache-2.0"
] | 7 | 2019-01-12T16:07:07.000Z | 2022-02-28T16:42:24.000Z | src/main/java/jp/ac/utokyo/rcast/karkinos/exec/CNVInfo.java | hirokiuedaRcast/karkinos | 9525c4e01a049a30261e306ecc9c4e78b15d8ac2 | [
"Apache-2.0"
] | 16 | 2017-04-13T04:01:25.000Z | 2021-01-22T10:35:00.000Z | src/main/java/jp/ac/utokyo/rcast/karkinos/exec/CNVInfo.java | hirokiuedaRcast/karkinos | 9525c4e01a049a30261e306ecc9c4e78b15d8ac2 | [
"Apache-2.0"
] | 1 | 2018-11-16T08:56:35.000Z | 2018-11-16T08:56:35.000Z | 22.240964 | 72 | 0.758938 | 13,109 | /*
Copyright Hiroki Ueda
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 jp.ac.utokyo.rcast.karkinos.exec;
public class CNVInfo implements java.io.Serializable{
long normalcnt;
double normaldepth;
double normaldepthAdj;
long tumorcnt;
double tumordepth;
double tumordepthAdj;
double tnratio;
double denoise;
double copynumber;
double tnratioorg;
public CNVInfo(long _normalcnt, double _normaldepth,
double _normaldepthAdj, long _tumorcnt, double _tumordepth,
double _tumordepthAdj, double _tnratio) {
normalcnt = _normalcnt;
normaldepth = _normaldepth;
normaldepthAdj = _normaldepthAdj;
tumorcnt = _tumorcnt;
tumordepth = _tumordepth;
tumordepthAdj = _tumordepthAdj;
tnratio =_tnratio;
tnratioorg = _tnratio;
}
public long getNormalcnt() {
return normalcnt;
}
public double getNormaldepthAdj() {
return normaldepthAdj;
}
public long getTumorcnt() {
return tumorcnt;
}
public double getTumordepthAdj() {
return tumordepthAdj;
}
public double getTnratio() {
return tnratio;
}
public void setDenioseValue(double _denoise) {
denoise = _denoise;
}
public void setCN(double _copynumber) {
copynumber = _copynumber;
}
public double getDenoise() {
return denoise;
}
public double getCopynumber() {
return copynumber;
}
public double getOriginalTnratio() {
return tnratioorg;
}
}
|
3e1f02c6500d8997c762f177c56309b90426c1fc | 2,795 | java | Java | application-server/group-project-application/src/main/java/com/app/groupprojectapplication/domain/VisaStatus.java | YaochengTong/GroupProjectOne | 2dae47d89032cb225bd8ca981c2ae5c07406ca6c | [
"MIT"
] | null | null | null | application-server/group-project-application/src/main/java/com/app/groupprojectapplication/domain/VisaStatus.java | YaochengTong/GroupProjectOne | 2dae47d89032cb225bd8ca981c2ae5c07406ca6c | [
"MIT"
] | null | null | null | application-server/group-project-application/src/main/java/com/app/groupprojectapplication/domain/VisaStatus.java | YaochengTong/GroupProjectOne | 2dae47d89032cb225bd8ca981c2ae5c07406ca6c | [
"MIT"
] | null | null | null | 25.409091 | 160 | 0.620751 | 13,110 | package com.app.groupprojectapplication.domain;
import javax.persistence.*;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.Objects;
import java.util.Set;
@Entity
@Table(name = "visa_status", schema = "hr_db")
public class VisaStatus {
private Integer id;
private String visaType;
private byte isActive;
private Timestamp modificationDate;
private Set<Employee> employeeSet;
private User user;
public VisaStatus() {
}
public VisaStatus(String visaType, byte isActive, Timestamp modificationDate) {
this.visaType = visaType;
this.isActive = isActive;
this.modificationDate = modificationDate;
}
@Id
@Column(name = "id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Basic
@Column(name = "visa_type")
public String getVisaType() {
return visaType;
}
public void setVisaType(String visaType) {
this.visaType = visaType;
}
@Basic
@Column(name = "is_active")
public byte getIsActive() {
return isActive;
}
public void setIsActive(byte isActive) {
this.isActive = isActive;
}
@Basic
@Column(name = "modification_date")
public Timestamp getModificationDate() {
return modificationDate;
}
public void setModificationDate(Timestamp modificationDate) {
this.modificationDate = modificationDate;
}
@OneToMany(fetch = FetchType.LAZY, mappedBy = "visaStatus")
public Set<Employee> getEmployeeSet() {
return employeeSet;
}
public void setEmployeeSet(Set<Employee> employeeSet) {
this.employeeSet = employeeSet;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "creation_user_id", referencedColumnName = "id")
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
VisaStatus that = (VisaStatus) o;
return id == that.id && isActive == that.isActive && Objects.equals(visaType, that.visaType) && Objects.equals(modificationDate, that.modificationDate);
}
@Override
public int hashCode() {
return Objects.hash(id, visaType, isActive, modificationDate);
}
@Override
public String toString() {
return "VisaStatus{" +
"id=" + id +
", visaType='" + visaType + '\'' +
", isActive=" + isActive +
", modificationDate=" + modificationDate +
'}';
}
} |
3e1f033fbe8c1739678ff73b1a08e28f63b88623 | 1,981 | java | Java | aws-java-sdk-rekognition/src/main/java/com/amazonaws/services/rekognition/model/transform/DatasetChangesMarshaller.java | phambryan/aws-sdk-for-java | 0f75a8096efdb4831da8c6793390759d97a25019 | [
"Apache-2.0"
] | null | null | null | aws-java-sdk-rekognition/src/main/java/com/amazonaws/services/rekognition/model/transform/DatasetChangesMarshaller.java | phambryan/aws-sdk-for-java | 0f75a8096efdb4831da8c6793390759d97a25019 | [
"Apache-2.0"
] | null | null | null | aws-java-sdk-rekognition/src/main/java/com/amazonaws/services/rekognition/model/transform/DatasetChangesMarshaller.java | phambryan/aws-sdk-for-java | 0f75a8096efdb4831da8c6793390759d97a25019 | [
"Apache-2.0"
] | null | null | null | 35.375 | 136 | 0.732963 | 13,111 | /*
* Copyright 2016-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.rekognition.model.transform;
import javax.annotation.Generated;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.rekognition.model.*;
import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;
/**
* DatasetChangesMarshaller
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class DatasetChangesMarshaller {
private static final MarshallingInfo<java.nio.ByteBuffer> GROUNDTRUTH_BINDING = MarshallingInfo.builder(MarshallingType.BYTE_BUFFER)
.marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("GroundTruth").build();
private static final DatasetChangesMarshaller instance = new DatasetChangesMarshaller();
public static DatasetChangesMarshaller getInstance() {
return instance;
}
/**
* Marshall the given parameter object.
*/
public void marshall(DatasetChanges datasetChanges, ProtocolMarshaller protocolMarshaller) {
if (datasetChanges == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(datasetChanges.getGroundTruth(), GROUNDTRUTH_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
}
}
|
3e1f041f017d59fdbee68b19cae3184664db3ca3 | 327 | java | Java | core/src/main/java/io/logansquarex/core/typeconverters/DefaultDateConverter.java | bunnyblueair/LoganSquareX | a2be2ed591153849494784762b6f046d316f55e4 | [
"Apache-2.0"
] | 3 | 2018-03-06T12:10:31.000Z | 2018-03-07T12:15:34.000Z | core/src/main/java/io/logansquarex/core/typeconverters/DefaultDateConverter.java | bunnyblueair/LoganSquareX | a2be2ed591153849494784762b6f046d316f55e4 | [
"Apache-2.0"
] | 2 | 2018-03-07T10:07:01.000Z | 2018-03-07T13:02:07.000Z | core/src/main/java/io/logansquarex/core/typeconverters/DefaultDateConverter.java | LoganSquareX/LoganSquareX | b103acfaef53368869ef7120d3826c890c1fc6e9 | [
"Apache-2.0"
] | null | null | null | 25.153846 | 95 | 0.7737 | 13,112 | package io.logansquarex.core.typeconverters;
import java.text.DateFormat;
/** The default DateTypeConverter implementation. Attempts to parse ISO8601-formatted dates. */
public class DefaultDateConverter extends DateTypeConverter {
public DateFormat getDateFormat() {
return new DefaultDateFormatter();
}
}
|
3e1f04b175bd610da7393e756d3a4725faf8eb47 | 965 | java | Java | src/com/google/javascript/jscomp/gwt/super/com/google/javascript/jscomp/PrebuildAst.java | theRobinator/closure-compiler | 947a9947bf21ff6a5a13d1ac950ca08d3ee32342 | [
"Apache-2.0"
] | 4 | 2018-09-03T18:35:59.000Z | 2020-08-08T14:35:20.000Z | src/com/google/javascript/jscomp/gwt/super/com/google/javascript/jscomp/PrebuildAst.java | theRobinator/closure-compiler | 947a9947bf21ff6a5a13d1ac950ca08d3ee32342 | [
"Apache-2.0"
] | null | null | null | src/com/google/javascript/jscomp/gwt/super/com/google/javascript/jscomp/PrebuildAst.java | theRobinator/closure-compiler | 947a9947bf21ff6a5a13d1ac950ca08d3ee32342 | [
"Apache-2.0"
] | 2 | 2018-09-03T18:36:00.000Z | 2021-01-10T13:23:58.000Z | 32.166667 | 82 | 0.74715 | 13,113 | /*
* Copyright 2017 The Closure Compiler Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.javascript.jscomp;
import java.util.List;
/** Gwt-compatible no-op version for {@code PrebuildAst}. */
// TODO(moz): Implement this using GWT's emulation of ListenableFuture and friends
class PrebuildAst {
PrebuildAst(AbstractCompiler compiler, int numParalleThreads) {
}
void prebuild(List<CompilerInput> inputList) {}
}
|
3e1f0512b4a646ce4ed14b02749da56a9a004a88 | 1,480 | java | Java | src/main/java/org/java/gpu/graph/instructions/Branch.java | Fabryprog/java-gpu | 507b392b1ccd8b979090e03a8f762a962f92073c | [
"Apache-2.0"
] | 2 | 2020-12-05T10:16:37.000Z | 2020-12-14T05:21:23.000Z | src/main/java/org/java/gpu/graph/instructions/Branch.java | Fabryprog/java-gpu | 507b392b1ccd8b979090e03a8f762a962f92073c | [
"Apache-2.0"
] | null | null | null | src/main/java/org/java/gpu/graph/instructions/Branch.java | Fabryprog/java-gpu | 507b392b1ccd8b979090e03a8f762a962f92073c | [
"Apache-2.0"
] | null | null | null | 30.833333 | 78 | 0.712162 | 13,114 | /*
* Parallelising JVM Compiler
*
* Copyright 2010 Peter Calvert, University of Cambridge
*
* 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.java.gpu.graph.instructions;
import org.java.gpu.graph.Block;
import org.java.gpu.graph.BlockVisitor;
import java.util.Set;
public interface Branch extends Instruction {
/**
* Returns a set of any destination blocks used by the branch.
*/
public Set<Block> getDestinations();
/**
* Replace any occurances of <code>a</code> within the branch's destinations
* with <code>b</code>, returning the number of replacements made.
*
* @param a Block to be replaced.
* @param b Replacement block.
* @return Number of replacements made.
*/
public int replace(Block a, Block b);
/**
* Acceptor for the BlockVisitor pattern. This should cause visits to any
* blocks referenced by the branch.
*/
public abstract <T> void accept(BlockVisitor<T> visitor);
}
|
3e1f051779d7a8fa44d9b888d34d53d7a16c4cd1 | 374 | java | Java | digiwallet-frauddetection/src/main/java/io/wanderingthinkter/digiwalletfrauddetection/DigiwalletFrauddetectionApplication.java | vishnudivakar31/digi-wallet | 5298c26537b12ce82e34474a1aab896b6b79650e | [
"MIT"
] | null | null | null | digiwallet-frauddetection/src/main/java/io/wanderingthinkter/digiwalletfrauddetection/DigiwalletFrauddetectionApplication.java | vishnudivakar31/digi-wallet | 5298c26537b12ce82e34474a1aab896b6b79650e | [
"MIT"
] | null | null | null | digiwallet-frauddetection/src/main/java/io/wanderingthinkter/digiwalletfrauddetection/DigiwalletFrauddetectionApplication.java | vishnudivakar31/digi-wallet | 5298c26537b12ce82e34474a1aab896b6b79650e | [
"MIT"
] | null | null | null | 26.714286 | 73 | 0.850267 | 13,115 | package io.wanderingthinkter.digiwalletfrauddetection;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DigiwalletFrauddetectionApplication {
public static void main(String[] args) {
SpringApplication.run(DigiwalletFrauddetectionApplication.class, args);
}
}
|
3e1f0528593d0ea9f2dafcd8738ad664f81edd7b | 750 | java | Java | src/main/java/io/waterdrop/sort/PancakeSort.java | Liangyh918/algorithm | 6597da2668c5ffc854b6002631e77413ff7a6902 | [
"Apache-2.0"
] | null | null | null | src/main/java/io/waterdrop/sort/PancakeSort.java | Liangyh918/algorithm | 6597da2668c5ffc854b6002631e77413ff7a6902 | [
"Apache-2.0"
] | null | null | null | src/main/java/io/waterdrop/sort/PancakeSort.java | Liangyh918/algorithm | 6597da2668c5ffc854b6002631e77413ff7a6902 | [
"Apache-2.0"
] | null | null | null | 23.4375 | 69 | 0.662667 | 13,116 | package io.waterdrop.sort;
import io.waterdrop.sort.util.SortUtils;
public class PancakeSort implements SortAlgorithm {
/*
* 煎饼算法,找到未排序部分中的最大的元素,将从该元素到未排序部分的最后一个元素进行逆置操作,
* 直到排序完成。(该算法,只允许使用一种操作逆置某段序列) (non-Javadoc)
*
* @see io.waterdrop.sort.SortAlgorithm#sort(java.lang.Comparable[])
*/
@Override
public <T extends Comparable<T>> T[] sort(T[] unsorted) {
// 外层循环表示已排序部分元素的数量
for (int i = 0; i < unsorted.length; i++) {
int index = 0;
// 内层循环对未排序部分进行遍历,找到最大元素,
// 将从最大元素到未排序部分的最后一个元素进行逆置(flip)
for (int j = 0; j < unsorted.length - i; j++) {
if (SortUtils.less(unsorted[index], unsorted[j])) {
index = j;
}
}
SortUtils.flip(unsorted, index, unsorted.length - i - 1);
}
return unsorted;
}
}
|
3e1f0669c743619b5f33f7b7f36dbb7a8382da85 | 2,022 | java | Java | src/test/java/walkingkooka/tree/text/TextStylePropertyValueTestCase.java | mP1/walkingkooka-tree-text | 23cf2bf8ea5f28458b0a8e055c9b8341efa154f4 | [
"Apache-2.0"
] | null | null | null | src/test/java/walkingkooka/tree/text/TextStylePropertyValueTestCase.java | mP1/walkingkooka-tree-text | 23cf2bf8ea5f28458b0a8e055c9b8341efa154f4 | [
"Apache-2.0"
] | 2 | 2019-08-27T22:27:29.000Z | 2020-03-12T09:24:39.000Z | src/test/java/walkingkooka/tree/text/TextStylePropertyValueTestCase.java | mP1/walkingkooka-tree-text | 23cf2bf8ea5f28458b0a8e055c9b8341efa154f4 | [
"Apache-2.0"
] | null | null | null | 37.444444 | 107 | 0.753215 | 13,117 | /*
* Copyright 2019 Miroslav Pokorny (github.com/mP1)
*
* 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 walkingkooka.tree.text;
import org.junit.jupiter.api.Test;
import walkingkooka.ToStringTesting;
import walkingkooka.collect.map.Maps;
import walkingkooka.reflect.ClassTesting2;
import walkingkooka.tree.expression.ExpressionNumberContexts;
import walkingkooka.tree.json.JsonNode;
import walkingkooka.tree.json.marshall.JsonNodeMarshallContexts;
import walkingkooka.tree.json.marshall.JsonNodeUnmarshallContexts;
public abstract class TextStylePropertyValueTestCase<V> implements ClassTesting2<V>, ToStringTesting<V> {
TextStylePropertyValueTestCase() {
super();
}
@Test
public final void testTextStylePropertyJsonRoundtrip() {
final TextNode properties = TextNode.style(TextStyleNode.NO_CHILDREN)
.setAttributes(Maps.of(this.textStylePropertyName(), this.createTextStylePropertyValue()));
final JsonNode json = JsonNodeMarshallContexts.basic().marshallWithType(properties);
this.checkEquals(properties,
JsonNodeUnmarshallContexts.basic(ExpressionNumberContexts.fake()).unmarshallWithType(json),
() -> "" + properties);
}
@Test
public final void testTextStylePropertyNameCheck() {
this.textStylePropertyName().check(this.createTextStylePropertyValue());
}
abstract V createTextStylePropertyValue();
abstract TextStylePropertyName<V> textStylePropertyName();
}
|
3e1f078e5a3a87dbe6806ebf1819c8a649b21d22 | 857 | java | Java | app/src/main/java/com/frontinelabs/rxsample/model/ModelSlider.java | emjea/RxSample | 504d87d06f2678ed31ea6752e1b18449fbdaf794 | [
"MIT"
] | null | null | null | app/src/main/java/com/frontinelabs/rxsample/model/ModelSlider.java | emjea/RxSample | 504d87d06f2678ed31ea6752e1b18449fbdaf794 | [
"MIT"
] | null | null | null | app/src/main/java/com/frontinelabs/rxsample/model/ModelSlider.java | emjea/RxSample | 504d87d06f2678ed31ea6752e1b18449fbdaf794 | [
"MIT"
] | null | null | null | 19.044444 | 50 | 0.645274 | 13,118 |
package com.frontinelabs.rxsample.model;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class ModelSlider {
@SerializedName("status")
@Expose
private Boolean status;
@SerializedName("data")
@Expose
private List<DataSlider> data = null;
@SerializedName("message")
@Expose
private String message;
public Boolean getStatus() {
return status;
}
public void setStatus(Boolean status) {
this.status = status;
}
public List<DataSlider> getData() {
return data;
}
public void setData(List<DataSlider> data) {
this.data = data;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
|
3e1f07fc888fdc26ab575df20c923d59ad642e4b | 8,150 | java | Java | system-ml/src/main/java/com/ibm/bi/dml/runtime/controlprogram/parfor/opt/CostEstimator.java | alcedo/systemml | 4d371a6d6b52e5517b1411302af3fdd8cd3c156a | [
"Apache-2.0"
] | 5 | 2018-03-17T18:03:12.000Z | 2021-08-25T08:17:09.000Z | system-ml/src/main/java/com/ibm/bi/dml/runtime/controlprogram/parfor/opt/CostEstimator.java | dusenberrymw/IBM-SystemML | fc41ec4f0bd3bc6701c56103afdb409f8b0d9a04 | [
"Apache-2.0"
] | null | null | null | system-ml/src/main/java/com/ibm/bi/dml/runtime/controlprogram/parfor/opt/CostEstimator.java | dusenberrymw/IBM-SystemML | fc41ec4f0bd3bc6701c56103afdb409f8b0d9a04 | [
"Apache-2.0"
] | 6 | 2017-11-26T00:43:09.000Z | 2020-10-02T06:29:30.000Z | 24.622356 | 109 | 0.660368 | 13,119 | /**
* (C) Copyright IBM Corp. 2010, 2015
*
* 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.ibm.bi.dml.runtime.controlprogram.parfor.opt;
import java.util.ArrayList;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.ibm.bi.dml.lops.LopProperties.ExecType;
import com.ibm.bi.dml.runtime.DMLRuntimeException;
import com.ibm.bi.dml.runtime.controlprogram.parfor.opt.OptNode.ParamType;
import com.ibm.bi.dml.runtime.controlprogram.parfor.opt.PerfTestTool.TestMeasure;
/**
* Base class for all potential cost estimators
*
* TODO account for shared read-only matrices when computing aggregated stats
*
*/
public abstract class CostEstimator
{
protected static final Log LOG = LogFactory.getLog(CostEstimator.class.getName());
//default parameters
public static final double DEFAULT_EST_PARALLELISM = 1.0; //default degree of parallelism: serial
public static final long FACTOR_NUM_ITERATIONS = 10; //default problem size
public static final double DEFAULT_TIME_ESTIMATE = 5; //default execution time: 5ms
public static final double DEFAULT_MEM_ESTIMATE_CP = 1024; //default memory consumption: 1KB
public static final double DEFAULT_MEM_ESTIMATE_MR = 10*1024*1024; //default memory consumption: 20MB
/**
* Main leaf node estimation method - to be overwritten by specific cost estimators
*
* @param measure
* @param node
* @return
* @throws DMLRuntimeException
*/
public abstract double getLeafNodeEstimate( TestMeasure measure, OptNode node )
throws DMLRuntimeException;
/**
* Main leaf node estimation method - to be overwritten by specific cost estimators
*
* @param measure
* @param node
* @param et forced execution type for leaf node
* @return
* @throws DMLRuntimeException
*/
public abstract double getLeafNodeEstimate( TestMeasure measure, OptNode node, ExecType et )
throws DMLRuntimeException;
/////////
//methods invariant to concrete estimator
///
/**
* Main estimation method.
*
* @param measure
* @param node
* @return
* @throws DMLRuntimeException
*/
public double getEstimate( TestMeasure measure, OptNode node )
throws DMLRuntimeException
{
return getEstimate(measure, node, null);
}
/**
* Main estimation method.
*
* @param measure
* @param node
* @return
* @throws DMLRuntimeException
*/
public double getEstimate( TestMeasure measure, OptNode node, ExecType et )
throws DMLRuntimeException
{
double val = -1;
if( node.isLeaf() )
{
if( et != null )
val = getLeafNodeEstimate(measure, node, et); //forced type
else
val = getLeafNodeEstimate(measure, node); //default
}
else
{
//aggreagtion methods for different program block types and measure types
//TODO EXEC TIME requires reconsideration of for/parfor/if predicates
//TODO MEMORY requires reconsideration of parfor -> potential overestimation, but safe
String tmp = null;
double N = -1;
switch ( measure )
{
case EXEC_TIME:
switch( node.getNodeType() )
{
case GENERIC:
case FUNCCALL:
val = getSumEstimate(measure, node.getChilds(), et);
break;
case IF:
if( node.getChilds().size()==2 )
val = getWeightedEstimate(measure, node.getChilds(), et);
else
val = getMaxEstimate(measure, node.getChilds(), et);
break;
case WHILE:
val = FACTOR_NUM_ITERATIONS * getSumEstimate(measure, node.getChilds(), et);
break;
case FOR:
tmp = node.getParam(ParamType.NUM_ITERATIONS);
N = (tmp!=null) ? (double)Long.parseLong(tmp) : FACTOR_NUM_ITERATIONS;
val = N * getSumEstimate(measure, node.getChilds(), et);
break;
case PARFOR:
tmp = node.getParam(ParamType.NUM_ITERATIONS);
N = (tmp!=null) ? (double)Long.parseLong(tmp) : FACTOR_NUM_ITERATIONS;
val = N * getSumEstimate(measure, node.getChilds(), et) / node.getK();
break;
default:
//do nothing
}
break;
case MEMORY_USAGE:
switch( node.getNodeType() )
{
case GENERIC:
case FUNCCALL:
case IF:
case WHILE:
case FOR:
val = getMaxEstimate(measure, node.getChilds(), et);
break;
case PARFOR:
if( node.getExecType() == OptNode.ExecType.MR )
val = getMaxEstimate(measure, node.getChilds(), et); //executed in different JVMs
else if ( node.getExecType() == OptNode.ExecType.CP )
val = getMaxEstimate(measure, node.getChilds(), et) * node.getK(); //everything executed within 1 JVM
break;
default:
//do nothing
}
break;
}
}
return val;
}
/**
*
* @param plan
* @param n
* @return
*/
public double computeLocalParBound(OptTree plan, OptNode n)
{
return Math.floor(rComputeLocalValueBound(plan.getRoot(), n, plan.getCK()));
}
/**
*
* @param plan
* @param n
* @return
*/
public double computeLocalMemoryBound(OptTree plan, OptNode n)
{
return rComputeLocalValueBound(plan.getRoot(), n, plan.getCM());
}
/**
*
* @param pn
* @return
*/
public double getMinMemoryUsage(OptNode pn)
{
// TODO implement for DP enum optimizer
throw new RuntimeException("Not implemented yet.");
}
/**
*
* @param measure
* @return
*/
protected double getDefaultEstimate(TestMeasure measure)
{
double val = -1;
switch( measure )
{
case EXEC_TIME: val = DEFAULT_TIME_ESTIMATE; break;
case MEMORY_USAGE: val = DEFAULT_MEM_ESTIMATE_CP; break;
}
return val;
}
/**
*
* @param measure
* @param nodes
* @return
* @throws DMLRuntimeException
*/
protected double getMaxEstimate( TestMeasure measure, ArrayList<OptNode> nodes, ExecType et )
throws DMLRuntimeException
{
double max = Double.MIN_VALUE; //smallest positive value
for( OptNode n : nodes )
{
double tmp = getEstimate( measure, n, et );
if( tmp > max )
max = tmp;
}
return max;
}
/**
*
* @param measure
* @param nodes
* @return
* @throws DMLRuntimeException
*/
protected double getSumEstimate( TestMeasure measure, ArrayList<OptNode> nodes, ExecType et )
throws DMLRuntimeException
{
double sum = 0;
for( OptNode n : nodes )
sum += getEstimate( measure, n, et );
return sum;
}
/**
*
* @param measure
* @param nodes
* @return
* @throws DMLRuntimeException
*/
protected double getWeightedEstimate( TestMeasure measure, ArrayList<OptNode> nodes, ExecType et )
throws DMLRuntimeException
{
double ret = 0;
int len = nodes.size();
for( OptNode n : nodes )
ret += getEstimate( measure, n, et );
ret /= len; //weighting
return ret;
}
/**
*
* @param current
* @param node
* @param currentVal
* @return
*/
protected double rComputeLocalValueBound( OptNode current, OptNode node, double currentVal )
{
if( current == node ) //found node
return currentVal;
else if( current.isLeaf() ) //node not here
return -1;
else
{
switch( current.getNodeType() )
{
case GENERIC:
case FUNCCALL:
case IF:
case WHILE:
case FOR:
for( OptNode c : current.getChilds() )
{
double lval = rComputeLocalValueBound(c, node, currentVal);
if( lval > 0 )
return lval;
}
break;
case PARFOR:
for( OptNode c : current.getChilds() )
{
double lval = rComputeLocalValueBound(c, node, currentVal/current.getK());
if( lval > 0 )
return lval;
}
break;
default:
//do nothing
}
}
return -1;
}
}
|
3e1f082f9206fefe1244d9f969097b69aee975dd | 1,407 | java | Java | src/main/java/automation/pages/MovieAddNewPage.java | bodyajava/javacourse3 | e522211be8e285d1e65526357e878db01236abf1 | [
"Apache-2.0"
] | null | null | null | src/main/java/automation/pages/MovieAddNewPage.java | bodyajava/javacourse3 | e522211be8e285d1e65526357e878db01236abf1 | [
"Apache-2.0"
] | null | null | null | src/main/java/automation/pages/MovieAddNewPage.java | bodyajava/javacourse3 | e522211be8e285d1e65526357e878db01236abf1 | [
"Apache-2.0"
] | null | null | null | 23.065574 | 89 | 0.732054 | 13,120 | package automation.pages;
import static org.openqa.selenium.support.ui.ExpectedConditions.presenceOfElementLocated;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
public class MovieAddNewPage extends InternalPage {
public MovieAddNewPage(PageManager pages) {
super(pages);
}
public MovieAddNewPage ensurePageLoaded() {
super.ensurePageLoaded();
wait.until(presenceOfElementLocated(By.id("imdbsearch")));
return this;
}
@FindBy(xpath = ".//tr[2]/td[2]/input")
private WebElement titleField;
@FindBy(xpath = ".//tr[4]/td[2]/input")
private WebElement yearField;
@FindBy(xpath = ".//tr[17]/td[2]/textarea")
private WebElement plotField;
@FindBy(xpath = ".//tr[27]/td[2]/textarea")
private WebElement producerField;
@FindBy(xpath = ".//tr[30]/td[2]/input")
private WebElement saveButton;
public MovieAddNewPage setTitleField(String text) {
titleField.sendKeys(text);
return this;
}
public MovieAddNewPage setYearField(String text) {
yearField.sendKeys(text);
return this;
}
public MovieAddNewPage setPlotField(String text) {
plotField.sendKeys(text);
return this;
}
public MovieAddNewPage setProducerField(String text) {
producerField.sendKeys(text);
return this;
}
public MovieAddNewPage clickSaveMovieButton() {
saveButton.click();
return this;
}
}
|
3e1f0901355310ad4cc528d309c3d63f06690425 | 5,379 | java | Java | java/timebase/client/src/test/java/deltix/util/vsocket/AioServDirectTest.java | mdvx/TimeBase | 812e178b814a604740da3c15cc64e42c57d69036 | [
"Apache-2.0"
] | null | null | null | java/timebase/client/src/test/java/deltix/util/vsocket/AioServDirectTest.java | mdvx/TimeBase | 812e178b814a604740da3c15cc64e42c57d69036 | [
"Apache-2.0"
] | null | null | null | java/timebase/client/src/test/java/deltix/util/vsocket/AioServDirectTest.java | mdvx/TimeBase | 812e178b814a604740da3c15cc64e42c57d69036 | [
"Apache-2.0"
] | 1 | 2021-07-15T16:28:37.000Z | 2021-07-15T16:28:37.000Z | 34.480769 | 189 | 0.593233 | 13,121 | package deltix.util.vsocket;
import deltix.util.memory.MemoryDataOutput;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.StandardSocketOptions;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.CountDownLatch;
/**
* @author Alexei Osipov
*/
public class AioServDirectTest {
public static void main(String[] args) throws IOException, InterruptedException {
final AsynchronousServerSocketChannel serverChannel =
AsynchronousServerSocketChannel.open()
//.setOption(StandardSocketOptions.SO_SNDBUF, 16 * 1024 * 1024)
.bind(new InetSocketAddress(5000));
serverChannel.accept(null, new CompletionHandler<AsynchronousSocketChannel,Void>() {
public void completed(AsynchronousSocketChannel ch, Void att) {
// accept the next connection
serverChannel.accept(null, this);
// handle this connection
handle(ch);
}
public void failed(Throwable exc, Void att) {
exc.printStackTrace();
}
});
CountDownLatch countDownLatch = new CountDownLatch(1);
Runtime.getRuntime().addShutdownHook(new Thread(countDownLatch::countDown));
countDownLatch.await();
serverChannel.close();
}
private static void handle(AsynchronousSocketChannel ch) {
try {
ch.setOption(StandardSocketOptions.SO_SNDBUF, 16 * 1024 * 1024);
} catch (IOException e) {
e.printStackTrace();
}
int flushLimit = 128 * 1024;
ByteBuffer writeBuffer = ByteBuffer.allocate(flushLimit * 2);
writeBuffer.limit(0);
MessageGenerator mg = new MessageGenerator();
MessageGenerator2 mg2 = new MessageGenerator2();
/*while (mdo.getPosition() < flushLimit) {
mg.writeMessage(mdo);
}
writeBuffer.limit(mdo.getPosition());*/
IntegerWriteContextCompletionHandler handler = new IntegerWriteContextCompletionHandler(writeBuffer, null, flushLimit, mg, ch, mg2);
//handler.prepareForSend(new WriteContext());
handler.prepareForSend2(new WriteContext());
}
private static class MessageGenerator {
//Random rng = new Random(0);
long messageIndex = 0;
void writeMessage(MemoryDataOutput mdo) {
messageIndex ++;
int size = 50 + Long.BYTES;
mdo.writeInt(size);
mdo.writeLong(messageIndex);
for (int i = 0; i < 50; i++) {
mdo.writeByte(i);
}
}
}
private static class MessageGenerator2 {
//Random rng = new Random(0);
long messageIndex = 0;
void writeMessage(ByteBuffer buf) {
messageIndex ++;
int size = 50 + Long.BYTES;
buf.putInt(size);
buf.putLong(messageIndex);
for (int i = 0; i < 50; i++) {
buf.put((byte) i);
}
}
}
private static class WriteContext {
}
private static class IntegerWriteContextCompletionHandler implements CompletionHandler<Integer, WriteContext> {
private final ByteBuffer writeBuffer;
private final MemoryDataOutput mdo;
private final int flushLimit;
private final MessageGenerator mg;
private final AsynchronousSocketChannel ch;
private final MessageGenerator2 mg2;
public IntegerWriteContextCompletionHandler(ByteBuffer writeBuffer, MemoryDataOutput mdo, int flushLimit, MessageGenerator mg, AsynchronousSocketChannel ch, MessageGenerator2 mg2) {
this.writeBuffer = writeBuffer;
this.mdo = mdo;
this.flushLimit = flushLimit;
this.mg = mg;
this.ch = ch;
this.mg2 = mg2;
}
@Override
public void completed(Integer result, WriteContext attachment) {
//prepareForSend(attachment);
prepareForSend2(attachment);
}
private void prepareForSend2(WriteContext attachment) {
if (!ch.isOpen()) {
System.err.println("Channel is closed");
return;
}
int remaining = writeBuffer.remaining();
if (remaining > 0) {
// Some data left in buffer
if (remaining < 512) {
// Amount of data is small - compact buffer
writeBuffer.compact();
} else {
int oldLimit = writeBuffer.limit();
writeBuffer.limit(writeBuffer.capacity());
writeBuffer.position(oldLimit);
}
} else {
// Buffer was fully written
writeBuffer.clear();
}
while (writeBuffer.position() < flushLimit) {
mg2.writeMessage(writeBuffer);
}
writeBuffer.flip();
ch.write(writeBuffer, attachment, this);
}
@Override
public void failed(Throwable exc, WriteContext attachment) {
exc.printStackTrace();
}
}
}
|
3e1f0a74a72f42cc561ad961a133d53f82314c01 | 1,900 | java | Java | tools/proguard/src/proguard/classfile/attribute/visitor/AllInnerClassesInfoVisitor.java | pplante/droidtowers | e0858de70728a54c64d85850ab1aa2ecc3c2ac46 | [
"MIT"
] | 20 | 2015-01-18T16:31:16.000Z | 2021-05-07T00:55:53.000Z | app/src/main/java/proguard/classfile/attribute/visitor/AllInnerClassesInfoVisitor.java | TimScriptov/javaide | b8458f853637280aea89e9991bcff1c6b596491a | [
"Apache-2.0"
] | 1 | 2017-07-29T10:35:42.000Z | 2017-07-29T10:35:42.000Z | app/src/main/java/proguard/classfile/attribute/visitor/AllInnerClassesInfoVisitor.java | TimScriptov/javaide | b8458f853637280aea89e9991bcff1c6b596491a | [
"Apache-2.0"
] | 9 | 2015-04-04T12:33:05.000Z | 2019-06-20T21:43:01.000Z | 34.690909 | 100 | 0.769916 | 13,122 | /*
* ProGuard -- shrinking, optimization, obfuscation, and preverification
* of Java bytecode.
*
* Copyright (c) 2002-2011 Eric Lafortune (nnheo@example.com)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 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 Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package proguard.classfile.attribute.visitor;
import proguard.classfile.*;
import proguard.classfile.attribute.*;
import proguard.classfile.util.SimplifiedVisitor;
/**
* This AttributeVisitor lets a given InnerClassesInfoVisitor visit all
* InnerClassessInfo objects of the InnerClassesAttribute objects it visits.
*
* @author Eric Lafortune
*/
public class AllInnerClassesInfoVisitor
extends SimplifiedVisitor
implements AttributeVisitor
{
private final InnerClassesInfoVisitor innerClassesInfoVisitor;
public AllInnerClassesInfoVisitor(InnerClassesInfoVisitor innerClassesInfoVisitor)
{
this.innerClassesInfoVisitor = innerClassesInfoVisitor;
}
// Implementations for AttributeVisitor.
public void visitAnyAttribute(Clazz clazz, Attribute attribute) {}
public void visitInnerClassesAttribute(Clazz clazz, InnerClassesAttribute innerClassesAttribute)
{
innerClassesAttribute.innerClassEntriesAccept(clazz, innerClassesInfoVisitor);
}
} |
3e1f0b2d1cec135769800e97570764551e7528b1 | 344 | java | Java | src/main/java/com/edlio/emailreplyparser/EmailReplyParser.java | UTBox/EmailReplyParser | a9b7c50dc66253f256b0367f64911676b907d48d | [
"MIT"
] | 1 | 2016-08-20T01:25:14.000Z | 2016-08-20T01:25:14.000Z | src/main/java/com/edlio/emailreplyparser/EmailReplyParser.java | UTBox/EmailReplyParser | a9b7c50dc66253f256b0367f64911676b907d48d | [
"MIT"
] | 2 | 2019-10-25T15:42:00.000Z | 2019-10-31T10:27:24.000Z | src/main/java/com/edlio/emailreplyparser/EmailReplyParser.java | UTBox/EmailReplyParser | a9b7c50dc66253f256b0367f64911676b907d48d | [
"MIT"
] | 1 | 2022-03-10T10:03:33.000Z | 2022-03-10T10:03:33.000Z | 19.111111 | 52 | 0.729651 | 13,123 | package com.edlio.emailreplyparser;
public class EmailReplyParser {
public static Email read(String emailText) {
if (emailText == null)
emailText = "";
EmailParser parser = new EmailParser();
return parser.parse(emailText);
}
public static String parseReply(String emailText) {
return read(emailText).getVisibleText();
}
}
|
3e1f0b7c526cb857afca6531b92d61a99ad50a6d | 94,491 | java | Java | server/src/test/java/org/elasticsearch/cluster/coordination/CoordinatorTests.java | Anyz01/elasticsearch | da3d8fb5b74e99b553e4ab4e04ad8b3fd294e4b3 | [
"Apache-2.0"
] | 1 | 2019-01-22T03:04:40.000Z | 2019-01-22T03:04:40.000Z | server/src/test/java/org/elasticsearch/cluster/coordination/CoordinatorTests.java | Anyz01/elasticsearch | da3d8fb5b74e99b553e4ab4e04ad8b3fd294e4b3 | [
"Apache-2.0"
] | null | null | null | server/src/test/java/org/elasticsearch/cluster/coordination/CoordinatorTests.java | Anyz01/elasticsearch | da3d8fb5b74e99b553e4ab4e04ad8b3fd294e4b3 | [
"Apache-2.0"
] | null | null | null | 52.320598 | 140 | 0.644506 | 13,124 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.cluster.coordination;
import org.apache.logging.log4j.CloseableThreadContext;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.message.ParameterizedMessage;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.Version;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.cluster.ClusterName;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.ClusterStateUpdateTask;
import org.elasticsearch.cluster.ESAllocationTestCase;
import org.elasticsearch.cluster.block.ClusterBlock;
import org.elasticsearch.cluster.coordination.ClusterStatePublisher.AckListener;
import org.elasticsearch.cluster.coordination.CoordinationMetaData.VotingConfiguration;
import org.elasticsearch.cluster.coordination.CoordinationState.PersistedState;
import org.elasticsearch.cluster.coordination.Coordinator.Mode;
import org.elasticsearch.cluster.coordination.CoordinatorTests.Cluster.ClusterNode;
import org.elasticsearch.cluster.metadata.MetaData;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.node.DiscoveryNode.Role;
import org.elasticsearch.cluster.service.ClusterApplier;
import org.elasticsearch.common.Randomness;
import org.elasticsearch.common.UUIDs;
import org.elasticsearch.common.lease.Releasable;
import org.elasticsearch.common.settings.ClusterSettings;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.settings.Settings.Builder;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.discovery.zen.PublishClusterStateStats;
import org.elasticsearch.discovery.zen.UnicastHostsProvider.HostsResolver;
import org.elasticsearch.indices.cluster.FakeThreadPoolMasterService;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.test.disruption.DisruptableMockTransport;
import org.elasticsearch.test.disruption.DisruptableMockTransport.ConnectionStatus;
import org.elasticsearch.transport.TransportService;
import org.hamcrest.Matcher;
import org.junit.Before;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.function.UnaryOperator;
import java.util.stream.Collectors;
import static java.util.Collections.emptySet;
import static org.elasticsearch.cluster.coordination.CoordinationStateTests.clusterState;
import static org.elasticsearch.cluster.coordination.CoordinationStateTests.setValue;
import static org.elasticsearch.cluster.coordination.CoordinationStateTests.value;
import static org.elasticsearch.cluster.coordination.Coordinator.Mode.CANDIDATE;
import static org.elasticsearch.cluster.coordination.Coordinator.Mode.FOLLOWER;
import static org.elasticsearch.cluster.coordination.Coordinator.Mode.LEADER;
import static org.elasticsearch.cluster.coordination.Coordinator.PUBLISH_TIMEOUT_SETTING;
import static org.elasticsearch.cluster.coordination.CoordinatorTests.Cluster.DEFAULT_DELAY_VARIABILITY;
import static org.elasticsearch.cluster.coordination.ElectionSchedulerFactory.ELECTION_BACK_OFF_TIME_SETTING;
import static org.elasticsearch.cluster.coordination.ElectionSchedulerFactory.ELECTION_DURATION_SETTING;
import static org.elasticsearch.cluster.coordination.ElectionSchedulerFactory.ELECTION_INITIAL_TIMEOUT_SETTING;
import static org.elasticsearch.cluster.coordination.FollowersChecker.FOLLOWER_CHECK_INTERVAL_SETTING;
import static org.elasticsearch.cluster.coordination.FollowersChecker.FOLLOWER_CHECK_RETRY_COUNT_SETTING;
import static org.elasticsearch.cluster.coordination.FollowersChecker.FOLLOWER_CHECK_TIMEOUT_SETTING;
import static org.elasticsearch.cluster.coordination.LeaderChecker.LEADER_CHECK_INTERVAL_SETTING;
import static org.elasticsearch.cluster.coordination.LeaderChecker.LEADER_CHECK_RETRY_COUNT_SETTING;
import static org.elasticsearch.cluster.coordination.LeaderChecker.LEADER_CHECK_TIMEOUT_SETTING;
import static org.elasticsearch.cluster.coordination.Reconfigurator.CLUSTER_AUTO_SHRINK_VOTING_CONFIGURATION;
import static org.elasticsearch.discovery.DiscoverySettings.NO_MASTER_BLOCK_ALL;
import static org.elasticsearch.discovery.DiscoverySettings.NO_MASTER_BLOCK_ID;
import static org.elasticsearch.discovery.DiscoverySettings.NO_MASTER_BLOCK_SETTING;
import static org.elasticsearch.discovery.DiscoverySettings.NO_MASTER_BLOCK_WRITES;
import static org.elasticsearch.discovery.PeerFinder.DISCOVERY_FIND_PEERS_INTERVAL_SETTING;
import static org.elasticsearch.node.Node.NODE_NAME_SETTING;
import static org.elasticsearch.transport.TransportService.HANDSHAKE_ACTION_NAME;
import static org.elasticsearch.transport.TransportService.NOOP_TRANSPORT_INTERCEPTOR;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.endsWith;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.greaterThanOrEqualTo;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.lessThan;
import static org.hamcrest.Matchers.lessThanOrEqualTo;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.Matchers.sameInstance;
import static org.hamcrest.Matchers.startsWith;
public class CoordinatorTests extends ESTestCase {
@Before
public void resetPortCounterBeforeEachTest() {
resetPortCounter();
}
public void testCanUpdateClusterStateAfterStabilisation() {
final Cluster cluster = new Cluster(randomIntBetween(1, 5));
cluster.runRandomly();
cluster.stabilise();
final ClusterNode leader = cluster.getAnyLeader();
long finalValue = randomLong();
logger.info("--> submitting value [{}] to [{}]", finalValue, leader);
leader.submitValue(finalValue);
cluster.stabilise(DEFAULT_CLUSTER_STATE_UPDATE_DELAY);
for (final ClusterNode clusterNode : cluster.clusterNodes) {
final String nodeId = clusterNode.getId();
final ClusterState appliedState = clusterNode.getLastAppliedClusterState();
assertThat(nodeId + " has the applied value", value(appliedState), is(finalValue));
}
}
public void testDoesNotElectNonMasterNode() {
final Cluster cluster = new Cluster(randomIntBetween(1, 5), false);
cluster.runRandomly();
cluster.stabilise();
final ClusterNode leader = cluster.getAnyLeader();
assertTrue(leader.localNode.isMasterNode());
}
public void testNodesJoinAfterStableCluster() {
final Cluster cluster = new Cluster(randomIntBetween(1, 5));
cluster.runRandomly();
cluster.stabilise();
final long currentTerm = cluster.getAnyLeader().coordinator.getCurrentTerm();
cluster.addNodesAndStabilise(randomIntBetween(1, 2));
final long newTerm = cluster.getAnyLeader().coordinator.getCurrentTerm();
assertEquals(currentTerm, newTerm);
}
public void testExpandsConfigurationWhenGrowingFromOneNodeToThreeButDoesNotShrink() {
final Cluster cluster = new Cluster(1);
cluster.runRandomly();
cluster.stabilise();
final ClusterNode leader = cluster.getAnyLeader();
cluster.addNodesAndStabilise(2);
{
assertThat(leader.coordinator.getMode(), is(Mode.LEADER));
final VotingConfiguration lastCommittedConfiguration = leader.getLastAppliedClusterState().getLastCommittedConfiguration();
assertThat(lastCommittedConfiguration + " should be all nodes", lastCommittedConfiguration.getNodeIds(),
equalTo(cluster.clusterNodes.stream().map(ClusterNode::getId).collect(Collectors.toSet())));
}
final ClusterNode disconnect1 = cluster.getAnyNode();
logger.info("--> disconnecting {}", disconnect1);
disconnect1.disconnect();
cluster.stabilise();
{
final ClusterNode newLeader = cluster.getAnyLeader();
final VotingConfiguration lastCommittedConfiguration = newLeader.getLastAppliedClusterState().getLastCommittedConfiguration();
assertThat(lastCommittedConfiguration + " should be all nodes", lastCommittedConfiguration.getNodeIds(),
equalTo(cluster.clusterNodes.stream().map(ClusterNode::getId).collect(Collectors.toSet())));
}
}
public void testExpandsConfigurationWhenGrowingFromThreeToFiveNodesAndShrinksBackToThreeOnFailure() {
final Cluster cluster = new Cluster(3);
cluster.runRandomly();
cluster.stabilise();
final ClusterNode leader = cluster.getAnyLeader();
logger.info("setting auto-shrink reconfiguration to true");
leader.submitSetAutoShrinkVotingConfiguration(true);
cluster.stabilise(DEFAULT_CLUSTER_STATE_UPDATE_DELAY);
assertTrue(CLUSTER_AUTO_SHRINK_VOTING_CONFIGURATION.get(leader.getLastAppliedClusterState().metaData().settings()));
cluster.addNodesAndStabilise(2);
{
assertThat(leader.coordinator.getMode(), is(Mode.LEADER));
final VotingConfiguration lastCommittedConfiguration = leader.getLastAppliedClusterState().getLastCommittedConfiguration();
assertThat(lastCommittedConfiguration + " should be all nodes", lastCommittedConfiguration.getNodeIds(),
equalTo(cluster.clusterNodes.stream().map(ClusterNode::getId).collect(Collectors.toSet())));
}
final ClusterNode disconnect1 = cluster.getAnyNode();
final ClusterNode disconnect2 = cluster.getAnyNodeExcept(disconnect1);
logger.info("--> disconnecting {} and {}", disconnect1, disconnect2);
disconnect1.disconnect();
disconnect2.disconnect();
cluster.stabilise();
{
final ClusterNode newLeader = cluster.getAnyLeader();
final VotingConfiguration lastCommittedConfiguration = newLeader.getLastAppliedClusterState().getLastCommittedConfiguration();
assertThat(lastCommittedConfiguration + " should be 3 nodes", lastCommittedConfiguration.getNodeIds().size(), equalTo(3));
assertFalse(lastCommittedConfiguration.getNodeIds().contains(disconnect1.getId()));
assertFalse(lastCommittedConfiguration.getNodeIds().contains(disconnect2.getId()));
}
// we still tolerate the loss of one more node here
final ClusterNode disconnect3 = cluster.getAnyNodeExcept(disconnect1, disconnect2);
logger.info("--> disconnecting {}", disconnect3);
disconnect3.disconnect();
cluster.stabilise();
{
final ClusterNode newLeader = cluster.getAnyLeader();
final VotingConfiguration lastCommittedConfiguration = newLeader.getLastAppliedClusterState().getLastCommittedConfiguration();
assertThat(lastCommittedConfiguration + " should be 3 nodes", lastCommittedConfiguration.getNodeIds().size(), equalTo(3));
assertFalse(lastCommittedConfiguration.getNodeIds().contains(disconnect1.getId()));
assertFalse(lastCommittedConfiguration.getNodeIds().contains(disconnect2.getId()));
assertTrue(lastCommittedConfiguration.getNodeIds().contains(disconnect3.getId()));
}
// however we do not tolerate the loss of yet another one
final ClusterNode disconnect4 = cluster.getAnyNodeExcept(disconnect1, disconnect2, disconnect3);
logger.info("--> disconnecting {}", disconnect4);
disconnect4.disconnect();
cluster.runFor(DEFAULT_STABILISATION_TIME, "allowing time for fault detection");
for (final ClusterNode clusterNode : cluster.clusterNodes) {
assertThat(clusterNode.getId() + " should be a candidate", clusterNode.coordinator.getMode(), equalTo(Mode.CANDIDATE));
}
// moreover we are still stuck even if two other nodes heal
logger.info("--> healing {} and {}", disconnect1, disconnect2);
disconnect1.heal();
disconnect2.heal();
cluster.runFor(DEFAULT_STABILISATION_TIME, "allowing time for fault detection");
for (final ClusterNode clusterNode : cluster.clusterNodes) {
assertThat(clusterNode.getId() + " should be a candidate", clusterNode.coordinator.getMode(), equalTo(Mode.CANDIDATE));
}
// we require another node to heal to recover
final ClusterNode toHeal = randomBoolean() ? disconnect3 : disconnect4;
logger.info("--> healing {}", toHeal);
toHeal.heal();
cluster.stabilise();
}
public void testCanShrinkFromFiveNodesToThree() {
final Cluster cluster = new Cluster(5);
cluster.runRandomly();
cluster.stabilise();
{
final ClusterNode leader = cluster.getAnyLeader();
logger.info("setting auto-shrink reconfiguration to false");
leader.submitSetAutoShrinkVotingConfiguration(false);
cluster.stabilise(DEFAULT_CLUSTER_STATE_UPDATE_DELAY);
assertFalse(CLUSTER_AUTO_SHRINK_VOTING_CONFIGURATION.get(leader.getLastAppliedClusterState().metaData().settings()));
}
final ClusterNode disconnect1 = cluster.getAnyNode();
final ClusterNode disconnect2 = cluster.getAnyNodeExcept(disconnect1);
logger.info("--> disconnecting {} and {}", disconnect1, disconnect2);
disconnect1.disconnect();
disconnect2.disconnect();
cluster.stabilise();
final ClusterNode leader = cluster.getAnyLeader();
{
final VotingConfiguration lastCommittedConfiguration = leader.getLastAppliedClusterState().getLastCommittedConfiguration();
assertThat(lastCommittedConfiguration + " should be all nodes", lastCommittedConfiguration.getNodeIds(),
equalTo(cluster.clusterNodes.stream().map(ClusterNode::getId).collect(Collectors.toSet())));
}
logger.info("setting auto-shrink reconfiguration to true");
leader.submitSetAutoShrinkVotingConfiguration(true);
cluster.stabilise(DEFAULT_CLUSTER_STATE_UPDATE_DELAY * 2); // allow for a reconfiguration
assertTrue(CLUSTER_AUTO_SHRINK_VOTING_CONFIGURATION.get(leader.getLastAppliedClusterState().metaData().settings()));
{
final VotingConfiguration lastCommittedConfiguration = leader.getLastAppliedClusterState().getLastCommittedConfiguration();
assertThat(lastCommittedConfiguration + " should be 3 nodes", lastCommittedConfiguration.getNodeIds().size(), equalTo(3));
assertFalse(lastCommittedConfiguration.getNodeIds().contains(disconnect1.getId()));
assertFalse(lastCommittedConfiguration.getNodeIds().contains(disconnect2.getId()));
}
}
public void testDoesNotShrinkConfigurationBelowThreeNodes() {
final Cluster cluster = new Cluster(3);
cluster.runRandomly();
cluster.stabilise();
final ClusterNode disconnect1 = cluster.getAnyNode();
logger.info("--> disconnecting {}", disconnect1);
disconnect1.disconnect();
cluster.stabilise();
final ClusterNode disconnect2 = cluster.getAnyNodeExcept(disconnect1);
logger.info("--> disconnecting {}", disconnect2);
disconnect2.disconnect();
cluster.runFor(DEFAULT_STABILISATION_TIME, "allowing time for fault detection");
for (final ClusterNode clusterNode : cluster.clusterNodes) {
assertThat(clusterNode.getId() + " should be a candidate", clusterNode.coordinator.getMode(), equalTo(Mode.CANDIDATE));
}
disconnect1.heal();
cluster.stabilise(); // would not work if disconnect1 were removed from the configuration
}
public void testDoesNotShrinkConfigurationBelowFiveNodesIfAutoShrinkDisabled() {
final Cluster cluster = new Cluster(5);
cluster.runRandomly();
cluster.stabilise();
cluster.getAnyLeader().submitSetAutoShrinkVotingConfiguration(false);
cluster.stabilise(DEFAULT_ELECTION_DELAY);
final ClusterNode disconnect1 = cluster.getAnyNode();
final ClusterNode disconnect2 = cluster.getAnyNodeExcept(disconnect1);
logger.info("--> disconnecting {} and {}", disconnect1, disconnect2);
disconnect1.disconnect();
disconnect2.disconnect();
cluster.stabilise();
final ClusterNode disconnect3 = cluster.getAnyNodeExcept(disconnect1, disconnect2);
logger.info("--> disconnecting {}", disconnect3);
disconnect3.disconnect();
cluster.runFor(DEFAULT_STABILISATION_TIME, "allowing time for fault detection");
for (final ClusterNode clusterNode : cluster.clusterNodes) {
assertThat(clusterNode.getId() + " should be a candidate", clusterNode.coordinator.getMode(), equalTo(Mode.CANDIDATE));
}
disconnect1.heal();
cluster.stabilise(); // would not work if disconnect1 were removed from the configuration
}
public void testLeaderDisconnectionWithDisconnectEventDetectedQuickly() {
final Cluster cluster = new Cluster(randomIntBetween(3, 5));
cluster.runRandomly();
cluster.stabilise();
final ClusterNode originalLeader = cluster.getAnyLeader();
logger.info("--> disconnecting leader {}", originalLeader);
originalLeader.disconnect();
logger.info("--> followers get disconnect event for leader {} ", originalLeader);
cluster.getAllNodesExcept(originalLeader).forEach(cn -> cn.onDisconnectEventFrom(originalLeader));
// turn leader into candidate, which stabilisation asserts at the end
cluster.getAllNodesExcept(originalLeader).forEach(cn -> originalLeader.onDisconnectEventFrom(cn));
cluster.stabilise(DEFAULT_DELAY_VARIABILITY // disconnect is scheduled
// then wait for a new election
+ DEFAULT_ELECTION_DELAY
// wait for the removal to be committed
+ DEFAULT_CLUSTER_STATE_UPDATE_DELAY
// then wait for the followup reconfiguration
+ DEFAULT_CLUSTER_STATE_UPDATE_DELAY);
assertThat(cluster.getAnyLeader().getId(), not(equalTo(originalLeader.getId())));
}
public void testLeaderDisconnectionWithoutDisconnectEventDetectedQuickly() {
final Cluster cluster = new Cluster(randomIntBetween(3, 5));
cluster.runRandomly();
cluster.stabilise();
final ClusterNode originalLeader = cluster.getAnyLeader();
logger.info("--> disconnecting leader {}", originalLeader);
originalLeader.disconnect();
cluster.stabilise(Math.max(
// Each follower may have just sent a leader check, which receives no response
defaultMillis(LEADER_CHECK_TIMEOUT_SETTING)
// then wait for the follower to check the leader
+ defaultMillis(LEADER_CHECK_INTERVAL_SETTING)
// then wait for the exception response
+ DEFAULT_DELAY_VARIABILITY
// then wait for a new election
+ DEFAULT_ELECTION_DELAY,
// ALSO the leader may have just sent a follower check, which receives no response
defaultMillis(FOLLOWER_CHECK_TIMEOUT_SETTING)
// wait for the leader to check its followers
+ defaultMillis(FOLLOWER_CHECK_INTERVAL_SETTING)
// then wait for the exception response
+ DEFAULT_DELAY_VARIABILITY)
// FINALLY:
// wait for the removal to be committed
+ DEFAULT_CLUSTER_STATE_UPDATE_DELAY
// then wait for the followup reconfiguration
+ DEFAULT_CLUSTER_STATE_UPDATE_DELAY);
assertThat(cluster.getAnyLeader().getId(), not(equalTo(originalLeader.getId())));
}
public void testUnresponsiveLeaderDetectedEventually() {
final Cluster cluster = new Cluster(randomIntBetween(3, 5));
cluster.runRandomly();
cluster.stabilise();
final ClusterNode originalLeader = cluster.getAnyLeader();
logger.info("--> blackholing leader {}", originalLeader);
originalLeader.blackhole();
// This stabilisation time bound is undesirably long. TODO try and reduce it.
cluster.stabilise(Math.max(
// first wait for all the followers to notice the leader has gone
(defaultMillis(LEADER_CHECK_INTERVAL_SETTING) + defaultMillis(LEADER_CHECK_TIMEOUT_SETTING))
* defaultInt(LEADER_CHECK_RETRY_COUNT_SETTING)
// then wait for a follower to be promoted to leader
+ DEFAULT_ELECTION_DELAY
// and the first publication times out because of the unresponsive node
+ defaultMillis(PUBLISH_TIMEOUT_SETTING)
// there might be a term bump causing another election
+ DEFAULT_ELECTION_DELAY
// then wait for both of:
+ Math.max(
// 1. the term bumping publication to time out
defaultMillis(PUBLISH_TIMEOUT_SETTING),
// 2. the new leader to notice that the old leader is unresponsive
(defaultMillis(FOLLOWER_CHECK_INTERVAL_SETTING) + defaultMillis(FOLLOWER_CHECK_TIMEOUT_SETTING))
* defaultInt(FOLLOWER_CHECK_RETRY_COUNT_SETTING))
// then wait for the new leader to commit a state without the old leader
+ DEFAULT_CLUSTER_STATE_UPDATE_DELAY
// then wait for the followup reconfiguration
+ DEFAULT_CLUSTER_STATE_UPDATE_DELAY,
// ALSO wait for the leader to notice that its followers are unresponsive
(defaultMillis(FOLLOWER_CHECK_INTERVAL_SETTING) + defaultMillis(FOLLOWER_CHECK_TIMEOUT_SETTING))
* defaultInt(FOLLOWER_CHECK_RETRY_COUNT_SETTING)
// then wait for the leader to try and commit a state removing them, causing it to stand down
+ DEFAULT_CLUSTER_STATE_UPDATE_DELAY
));
assertThat(cluster.getAnyLeader().getId(), not(equalTo(originalLeader.getId())));
}
public void testFollowerDisconnectionDetectedQuickly() {
final Cluster cluster = new Cluster(randomIntBetween(3, 5));
cluster.runRandomly();
cluster.stabilise();
final ClusterNode leader = cluster.getAnyLeader();
final ClusterNode follower = cluster.getAnyNodeExcept(leader);
logger.info("--> disconnecting follower {}", follower);
follower.disconnect();
logger.info("--> leader {} and follower {} get disconnect event", leader, follower);
leader.onDisconnectEventFrom(follower);
follower.onDisconnectEventFrom(leader); // to turn follower into candidate, which stabilisation asserts at the end
cluster.stabilise(DEFAULT_DELAY_VARIABILITY // disconnect is scheduled
+ DEFAULT_CLUSTER_STATE_UPDATE_DELAY
// then wait for the followup reconfiguration
+ DEFAULT_CLUSTER_STATE_UPDATE_DELAY);
assertThat(cluster.getAnyLeader().getId(), equalTo(leader.getId()));
}
public void testFollowerDisconnectionWithoutDisconnectEventDetectedQuickly() {
final Cluster cluster = new Cluster(randomIntBetween(3, 5));
cluster.runRandomly();
cluster.stabilise();
final ClusterNode leader = cluster.getAnyLeader();
final ClusterNode follower = cluster.getAnyNodeExcept(leader);
logger.info("--> disconnecting follower {}", follower);
follower.disconnect();
cluster.stabilise(Math.max(
// the leader may have just sent a follower check, which receives no response
defaultMillis(FOLLOWER_CHECK_TIMEOUT_SETTING)
// wait for the leader to check the follower
+ defaultMillis(FOLLOWER_CHECK_INTERVAL_SETTING)
// then wait for the exception response
+ DEFAULT_DELAY_VARIABILITY
// then wait for the removal to be committed
+ DEFAULT_CLUSTER_STATE_UPDATE_DELAY
// then wait for the followup reconfiguration
+ DEFAULT_CLUSTER_STATE_UPDATE_DELAY,
// ALSO the follower may have just sent a leader check, which receives no response
defaultMillis(LEADER_CHECK_TIMEOUT_SETTING)
// then wait for the follower to check the leader
+ defaultMillis(LEADER_CHECK_INTERVAL_SETTING)
// then wait for the exception response, causing the follower to become a candidate
+ DEFAULT_DELAY_VARIABILITY
));
assertThat(cluster.getAnyLeader().getId(), equalTo(leader.getId()));
}
public void testUnresponsiveFollowerDetectedEventually() {
final Cluster cluster = new Cluster(randomIntBetween(3, 5));
cluster.runRandomly();
cluster.stabilise();
final ClusterNode leader = cluster.getAnyLeader();
final ClusterNode follower = cluster.getAnyNodeExcept(leader);
logger.info("--> blackholing follower {}", follower);
follower.blackhole();
cluster.stabilise(Math.max(
// wait for the leader to notice that the follower is unresponsive
(defaultMillis(FOLLOWER_CHECK_INTERVAL_SETTING) + defaultMillis(FOLLOWER_CHECK_TIMEOUT_SETTING))
* defaultInt(FOLLOWER_CHECK_RETRY_COUNT_SETTING)
// then wait for the leader to commit a state without the follower
+ DEFAULT_CLUSTER_STATE_UPDATE_DELAY
// then wait for the followup reconfiguration
+ DEFAULT_CLUSTER_STATE_UPDATE_DELAY,
// ALSO wait for the follower to notice the leader is unresponsive
(defaultMillis(LEADER_CHECK_INTERVAL_SETTING) + defaultMillis(LEADER_CHECK_TIMEOUT_SETTING))
* defaultInt(LEADER_CHECK_RETRY_COUNT_SETTING)
));
assertThat(cluster.getAnyLeader().getId(), equalTo(leader.getId()));
}
public void testAckListenerReceivesAcksFromAllNodes() {
final Cluster cluster = new Cluster(randomIntBetween(3, 5));
cluster.runRandomly();
cluster.stabilise();
final ClusterNode leader = cluster.getAnyLeader();
AckCollector ackCollector = leader.submitValue(randomLong());
cluster.stabilise(DEFAULT_CLUSTER_STATE_UPDATE_DELAY);
for (final ClusterNode clusterNode : cluster.clusterNodes) {
assertTrue("expected ack from " + clusterNode, ackCollector.hasAckedSuccessfully(clusterNode));
}
assertThat("leader should be last to ack", ackCollector.getSuccessfulAckIndex(leader), equalTo(cluster.clusterNodes.size() - 1));
}
public void testAckListenerReceivesNackFromFollower() {
final Cluster cluster = new Cluster(3);
cluster.runRandomly();
cluster.stabilise();
final ClusterNode leader = cluster.getAnyLeader();
final ClusterNode follower0 = cluster.getAnyNodeExcept(leader);
final ClusterNode follower1 = cluster.getAnyNodeExcept(leader, follower0);
follower0.setClusterStateApplyResponse(ClusterStateApplyResponse.FAIL);
AckCollector ackCollector = leader.submitValue(randomLong());
cluster.stabilise(DEFAULT_CLUSTER_STATE_UPDATE_DELAY);
assertTrue("expected ack from " + leader, ackCollector.hasAckedSuccessfully(leader));
assertTrue("expected nack from " + follower0, ackCollector.hasAckedUnsuccessfully(follower0));
assertTrue("expected ack from " + follower1, ackCollector.hasAckedSuccessfully(follower1));
assertThat("leader should be last to ack", ackCollector.getSuccessfulAckIndex(leader), equalTo(1));
}
public void testAckListenerReceivesNackFromLeader() {
final Cluster cluster = new Cluster(3);
cluster.runRandomly();
cluster.stabilise();
final ClusterNode leader = cluster.getAnyLeader();
final ClusterNode follower0 = cluster.getAnyNodeExcept(leader);
final ClusterNode follower1 = cluster.getAnyNodeExcept(leader, follower0);
final long startingTerm = leader.coordinator.getCurrentTerm();
leader.setClusterStateApplyResponse(ClusterStateApplyResponse.FAIL);
AckCollector ackCollector = leader.submitValue(randomLong());
cluster.runFor(DEFAULT_CLUSTER_STATE_UPDATE_DELAY, "committing value");
assertTrue(leader.coordinator.getMode() != Coordinator.Mode.LEADER || leader.coordinator.getCurrentTerm() > startingTerm);
leader.setClusterStateApplyResponse(ClusterStateApplyResponse.SUCCEED);
cluster.stabilise();
assertTrue("expected nack from " + leader, ackCollector.hasAckedUnsuccessfully(leader));
assertTrue("expected ack from " + follower0, ackCollector.hasAckedSuccessfully(follower0));
assertTrue("expected ack from " + follower1, ackCollector.hasAckedSuccessfully(follower1));
assertTrue(leader.coordinator.getMode() != Coordinator.Mode.LEADER || leader.coordinator.getCurrentTerm() > startingTerm);
}
public void testAckListenerReceivesNoAckFromHangingFollower() {
final Cluster cluster = new Cluster(3);
cluster.runRandomly();
cluster.stabilise();
final ClusterNode leader = cluster.getAnyLeader();
final ClusterNode follower0 = cluster.getAnyNodeExcept(leader);
final ClusterNode follower1 = cluster.getAnyNodeExcept(leader, follower0);
logger.info("--> blocking cluster state application on {}", follower0);
follower0.setClusterStateApplyResponse(ClusterStateApplyResponse.HANG);
logger.info("--> publishing another value");
AckCollector ackCollector = leader.submitValue(randomLong());
cluster.runFor(DEFAULT_CLUSTER_STATE_UPDATE_DELAY, "committing value");
assertTrue("expected immediate ack from " + follower1, ackCollector.hasAckedSuccessfully(follower1));
assertFalse("expected no ack from " + leader, ackCollector.hasAckedSuccessfully(leader));
cluster.stabilise(defaultMillis(PUBLISH_TIMEOUT_SETTING));
assertTrue("expected eventual ack from " + leader, ackCollector.hasAckedSuccessfully(leader));
assertFalse("expected no ack from " + follower0, ackCollector.hasAcked(follower0));
}
public void testAckListenerReceivesNacksIfPublicationTimesOut() {
final Cluster cluster = new Cluster(3);
cluster.runRandomly();
cluster.stabilise();
final ClusterNode leader = cluster.getAnyLeader();
final ClusterNode follower0 = cluster.getAnyNodeExcept(leader);
final ClusterNode follower1 = cluster.getAnyNodeExcept(leader, follower0);
follower0.blackhole();
follower1.blackhole();
AckCollector ackCollector = leader.submitValue(randomLong());
cluster.runFor(DEFAULT_CLUSTER_STATE_UPDATE_DELAY, "committing value");
assertFalse("expected no immediate ack from " + leader, ackCollector.hasAcked(leader));
assertFalse("expected no immediate ack from " + follower0, ackCollector.hasAcked(follower0));
assertFalse("expected no immediate ack from " + follower1, ackCollector.hasAcked(follower1));
follower0.heal();
follower1.heal();
cluster.stabilise();
assertTrue("expected eventual nack from " + follower0, ackCollector.hasAckedUnsuccessfully(follower0));
assertTrue("expected eventual nack from " + follower1, ackCollector.hasAckedUnsuccessfully(follower1));
assertTrue("expected eventual nack from " + leader, ackCollector.hasAckedUnsuccessfully(leader));
}
public void testAckListenerReceivesNacksIfLeaderStandsDown() {
final Cluster cluster = new Cluster(3);
cluster.runRandomly();
cluster.stabilise();
final ClusterNode leader = cluster.getAnyLeader();
final ClusterNode follower0 = cluster.getAnyNodeExcept(leader);
final ClusterNode follower1 = cluster.getAnyNodeExcept(leader, follower0);
leader.blackhole();
follower0.onDisconnectEventFrom(leader);
follower1.onDisconnectEventFrom(leader);
// let followers elect a leader among themselves before healing the leader and running the publication
cluster.runFor(DEFAULT_DELAY_VARIABILITY // disconnect is scheduled
+ DEFAULT_ELECTION_DELAY, "elect new leader");
// cluster has two nodes in mode LEADER, in different terms ofc, and the one in the lower term won’t be able to publish anything
leader.heal();
AckCollector ackCollector = leader.submitValue(randomLong());
cluster.stabilise(); // TODO: check if can find a better bound here
assertTrue("expected nack from " + leader, ackCollector.hasAckedUnsuccessfully(leader));
assertTrue("expected nack from " + follower0, ackCollector.hasAckedUnsuccessfully(follower0));
assertTrue("expected nack from " + follower1, ackCollector.hasAckedUnsuccessfully(follower1));
}
public void testAckListenerReceivesNacksFromFollowerInHigherTerm() {
// TODO: needs proper term bumping
// final Cluster cluster = new Cluster(3);
// cluster.runRandomly();
// cluster.stabilise();
// final ClusterNode leader = cluster.getAnyLeader();
// final ClusterNode follower0 = cluster.getAnyNodeExcept(leader);
// final ClusterNode follower1 = cluster.getAnyNodeExcept(leader, follower0);
//
// follower0.coordinator.joinLeaderInTerm(new StartJoinRequest(follower0.localNode, follower0.coordinator.getCurrentTerm() + 1));
// AckCollector ackCollector = leader.submitValue(randomLong());
// cluster.stabilise(DEFAULT_CLUSTER_STATE_UPDATE_DELAY);
// assertTrue("expected ack from " + leader, ackCollector.hasAckedSuccessfully(leader));
// assertTrue("expected nack from " + follower0, ackCollector.hasAckedUnsuccessfully(follower0));
// assertTrue("expected ack from " + follower1, ackCollector.hasAckedSuccessfully(follower1));
}
public void testDiscoveryOfPeersTriggersNotification() {
final Cluster cluster = new Cluster(randomIntBetween(2, 5));
// register a listener and then deregister it again to show that it is not called after deregistration
try (Releasable ignored = cluster.getAnyNode().coordinator.withDiscoveryListener(ActionListener.wrap(() -> {
throw new AssertionError("should not be called");
}))) {
// do nothing
}
final long startTimeMillis = cluster.deterministicTaskQueue.getCurrentTimeMillis();
final ClusterNode bootstrapNode = cluster.getAnyNode();
final AtomicBoolean hasDiscoveredAllPeers = new AtomicBoolean();
assertFalse(bootstrapNode.coordinator.getFoundPeers().iterator().hasNext());
try (Releasable ignored = bootstrapNode.coordinator.withDiscoveryListener(
new ActionListener<Iterable<DiscoveryNode>>() {
@Override
public void onResponse(Iterable<DiscoveryNode> discoveryNodes) {
int peerCount = 0;
for (final DiscoveryNode discoveryNode : discoveryNodes) {
peerCount++;
}
assertThat(peerCount, lessThan(cluster.size()));
if (peerCount == cluster.size() - 1 && hasDiscoveredAllPeers.get() == false) {
hasDiscoveredAllPeers.set(true);
final long elapsedTimeMillis = cluster.deterministicTaskQueue.getCurrentTimeMillis() - startTimeMillis;
logger.info("--> {} discovered {} peers in {}ms", bootstrapNode.getId(), cluster.size() - 1, elapsedTimeMillis);
assertThat(elapsedTimeMillis, lessThanOrEqualTo(defaultMillis(DISCOVERY_FIND_PEERS_INTERVAL_SETTING) * 2));
}
}
@Override
public void onFailure(Exception e) {
throw new AssertionError("unexpected", e);
}
})) {
cluster.runFor(defaultMillis(DISCOVERY_FIND_PEERS_INTERVAL_SETTING) * 2 + randomLongBetween(0, 60000), "discovery phase");
}
assertTrue(hasDiscoveredAllPeers.get());
final AtomicBoolean receivedAlreadyBootstrappedException = new AtomicBoolean();
try (Releasable ignored = bootstrapNode.coordinator.withDiscoveryListener(
new ActionListener<Iterable<DiscoveryNode>>() {
@Override
public void onResponse(Iterable<DiscoveryNode> discoveryNodes) {
// ignore
}
@Override
public void onFailure(Exception e) {
if (e instanceof ClusterAlreadyBootstrappedException) {
receivedAlreadyBootstrappedException.set(true);
} else {
throw new AssertionError("unexpected", e);
}
}
})) {
cluster.stabilise();
}
assertTrue(receivedAlreadyBootstrappedException.get());
}
public void testSettingInitialConfigurationTriggersElection() {
final Cluster cluster = new Cluster(randomIntBetween(1, 5));
cluster.runFor(defaultMillis(DISCOVERY_FIND_PEERS_INTERVAL_SETTING) * 2 + randomLongBetween(0, 60000), "initial discovery phase");
for (final ClusterNode clusterNode : cluster.clusterNodes) {
final String nodeId = clusterNode.getId();
assertThat(nodeId + " is CANDIDATE", clusterNode.coordinator.getMode(), is(CANDIDATE));
assertThat(nodeId + " is in term 0", clusterNode.coordinator.getCurrentTerm(), is(0L));
assertThat(nodeId + " last accepted in term 0", clusterNode.coordinator.getLastAcceptedState().term(), is(0L));
assertThat(nodeId + " last accepted version 0", clusterNode.coordinator.getLastAcceptedState().version(), is(0L));
assertFalse(nodeId + " has not received an initial configuration", clusterNode.coordinator.isInitialConfigurationSet());
assertTrue(nodeId + " has an empty last-accepted configuration",
clusterNode.coordinator.getLastAcceptedState().getLastAcceptedConfiguration().isEmpty());
assertTrue(nodeId + " has an empty last-committed configuration",
clusterNode.coordinator.getLastAcceptedState().getLastCommittedConfiguration().isEmpty());
final Set<DiscoveryNode> foundPeers = new HashSet<>();
clusterNode.coordinator.getFoundPeers().forEach(foundPeers::add);
assertTrue(nodeId + " should not have discovered itself", foundPeers.add(clusterNode.getLocalNode()));
assertThat(nodeId + " should have found all peers", foundPeers, hasSize(cluster.size()));
}
final ClusterNode bootstrapNode = cluster.getAnyNode();
bootstrapNode.applyInitialConfiguration();
assertTrue(bootstrapNode.getId() + " has been bootstrapped", bootstrapNode.coordinator.isInitialConfigurationSet());
cluster.stabilise(
// the first election should succeed, because only one node knows of the initial configuration and therefore can win a
// pre-voting round and proceed to an election, so there cannot be any collisions
defaultMillis(ELECTION_INITIAL_TIMEOUT_SETTING) // TODO this wait is unnecessary, we could trigger the election immediately
// Allow two round-trip for pre-voting and voting
+ 4 * DEFAULT_DELAY_VARIABILITY
// Then a commit of the new leader's first cluster state
+ DEFAULT_CLUSTER_STATE_UPDATE_DELAY
// Then allow time for all the other nodes to join, each of which might cause a reconfiguration
+ (cluster.size() - 1) * 2 * DEFAULT_CLUSTER_STATE_UPDATE_DELAY
// TODO Investigate whether 4 publications is sufficient due to batching? A bound linear in the number of nodes isn't great.
);
}
public void testCannotSetInitialConfigurationTwice() {
final Cluster cluster = new Cluster(randomIntBetween(1, 5));
cluster.runRandomly();
cluster.stabilise();
final Coordinator coordinator = cluster.getAnyNode().coordinator;
assertFalse(coordinator.setInitialConfiguration(coordinator.getLastAcceptedState().getLastCommittedConfiguration()));
}
public void testCannotSetInitialConfigurationWithoutQuorum() {
final Cluster cluster = new Cluster(randomIntBetween(1, 5));
final Coordinator coordinator = cluster.getAnyNode().coordinator;
final VotingConfiguration unknownNodeConfiguration = new VotingConfiguration(Collections.singleton("unknown-node"));
final String exceptionMessage = expectThrows(CoordinationStateRejectedException.class,
() -> coordinator.setInitialConfiguration(unknownNodeConfiguration)).getMessage();
assertThat(exceptionMessage,
startsWith("not enough nodes discovered to form a quorum in the initial configuration [knownNodes=["));
assertThat(exceptionMessage,
endsWith("], VotingConfiguration{unknown-node}]"));
assertThat(exceptionMessage, containsString(coordinator.getLocalNode().toString()));
// This is VERY BAD: setting a _different_ initial configuration. Yet it works if the first attempt will never be a quorum.
assertTrue(coordinator.setInitialConfiguration(new VotingConfiguration(Collections.singleton(coordinator.getLocalNode().getId()))));
cluster.stabilise();
}
public void testDiffBasedPublishing() {
final Cluster cluster = new Cluster(randomIntBetween(1, 5));
cluster.runRandomly();
cluster.stabilise();
final ClusterNode leader = cluster.getAnyLeader();
final long finalValue = randomLong();
final Map<ClusterNode, PublishClusterStateStats> prePublishStats = cluster.clusterNodes.stream().collect(
Collectors.toMap(Function.identity(), cn -> cn.coordinator.stats().getPublishStats()));
logger.info("--> submitting value [{}] to [{}]", finalValue, leader);
leader.submitValue(finalValue);
cluster.stabilise(DEFAULT_CLUSTER_STATE_UPDATE_DELAY);
final Map<ClusterNode, PublishClusterStateStats> postPublishStats = cluster.clusterNodes.stream().collect(
Collectors.toMap(Function.identity(), cn -> cn.coordinator.stats().getPublishStats()));
for (ClusterNode cn : cluster.clusterNodes) {
assertThat(value(cn.getLastAppliedClusterState()), is(finalValue));
if (cn == leader) {
// leader does not update publish stats as it's not using the serialized state
assertEquals(cn.toString(), prePublishStats.get(cn).getFullClusterStateReceivedCount(),
postPublishStats.get(cn).getFullClusterStateReceivedCount());
assertEquals(cn.toString(), prePublishStats.get(cn).getCompatibleClusterStateDiffReceivedCount(),
postPublishStats.get(cn).getCompatibleClusterStateDiffReceivedCount());
assertEquals(cn.toString(), prePublishStats.get(cn).getIncompatibleClusterStateDiffReceivedCount(),
postPublishStats.get(cn).getIncompatibleClusterStateDiffReceivedCount());
} else {
// followers receive a diff
assertEquals(cn.toString(), prePublishStats.get(cn).getFullClusterStateReceivedCount(),
postPublishStats.get(cn).getFullClusterStateReceivedCount());
assertEquals(cn.toString(), prePublishStats.get(cn).getCompatibleClusterStateDiffReceivedCount() + 1,
postPublishStats.get(cn).getCompatibleClusterStateDiffReceivedCount());
assertEquals(cn.toString(), prePublishStats.get(cn).getIncompatibleClusterStateDiffReceivedCount(),
postPublishStats.get(cn).getIncompatibleClusterStateDiffReceivedCount());
}
}
}
public void testJoiningNodeReceivesFullState() {
final Cluster cluster = new Cluster(randomIntBetween(1, 5));
cluster.runRandomly();
cluster.stabilise();
cluster.addNodesAndStabilise(1);
final ClusterNode newNode = cluster.clusterNodes.get(cluster.clusterNodes.size() - 1);
final PublishClusterStateStats newNodePublishStats = newNode.coordinator.stats().getPublishStats();
// initial cluster state send when joining
assertEquals(1L, newNodePublishStats.getFullClusterStateReceivedCount());
// possible follow-up reconfiguration was published as a diff
assertEquals(cluster.size() % 2, newNodePublishStats.getCompatibleClusterStateDiffReceivedCount());
assertEquals(0L, newNodePublishStats.getIncompatibleClusterStateDiffReceivedCount());
}
public void testIncompatibleDiffResendsFullState() {
final Cluster cluster = new Cluster(randomIntBetween(3, 5));
cluster.runRandomly();
cluster.stabilise();
final ClusterNode leader = cluster.getAnyLeader();
final ClusterNode follower = cluster.getAnyNodeExcept(leader);
logger.info("--> blackholing {}", follower);
follower.blackhole();
final PublishClusterStateStats prePublishStats = follower.coordinator.stats().getPublishStats();
logger.info("--> submitting first value to {}", leader);
leader.submitValue(randomLong());
cluster.runFor(DEFAULT_CLUSTER_STATE_UPDATE_DELAY + defaultMillis(PUBLISH_TIMEOUT_SETTING), "publish first state");
logger.info("--> healing {}", follower);
follower.heal();
logger.info("--> submitting second value to {}", leader);
leader.submitValue(randomLong());
cluster.stabilise(DEFAULT_CLUSTER_STATE_UPDATE_DELAY);
final PublishClusterStateStats postPublishStats = follower.coordinator.stats().getPublishStats();
assertEquals(prePublishStats.getFullClusterStateReceivedCount() + 1,
postPublishStats.getFullClusterStateReceivedCount());
assertEquals(prePublishStats.getCompatibleClusterStateDiffReceivedCount(),
postPublishStats.getCompatibleClusterStateDiffReceivedCount());
assertEquals(prePublishStats.getIncompatibleClusterStateDiffReceivedCount() + 1,
postPublishStats.getIncompatibleClusterStateDiffReceivedCount());
}
/**
* Simulates a situation where a follower becomes disconnected from the leader, but only for such a short time where
* it becomes candidate and puts up a NO_MASTER_BLOCK, but then receives a follower check from the leader. If the leader
* does not notice the node disconnecting, it is important for the node not to be turned back into a follower but try
* and join the leader again.
*/
public void testStayCandidateAfterReceivingFollowerCheckFromKnownMaster() {
final Cluster cluster = new Cluster(2, false);
cluster.runRandomly();
cluster.stabilise();
final ClusterNode leader = cluster.getAnyLeader();
final ClusterNode nonLeader = cluster.getAnyNodeExcept(leader);
onNode(nonLeader.getLocalNode(), () -> {
logger.debug("forcing {} to become candidate", nonLeader.getId());
synchronized (nonLeader.coordinator.mutex) {
nonLeader.coordinator.becomeCandidate("forced");
}
logger.debug("simulate follower check coming through from {} to {}", leader.getId(), nonLeader.getId());
nonLeader.coordinator.onFollowerCheckRequest(new FollowersChecker.FollowerCheckRequest(leader.coordinator.getCurrentTerm(),
leader.getLocalNode()));
}).run();
cluster.stabilise();
}
public void testAppliesNoMasterBlockWritesByDefault() {
testAppliesNoMasterBlock(null, NO_MASTER_BLOCK_WRITES);
}
public void testAppliesNoMasterBlockWritesIfConfigured() {
testAppliesNoMasterBlock("write", NO_MASTER_BLOCK_WRITES);
}
public void testAppliesNoMasterBlockAllIfConfigured() {
testAppliesNoMasterBlock("all", NO_MASTER_BLOCK_ALL);
}
private void testAppliesNoMasterBlock(String noMasterBlockSetting, ClusterBlock expectedBlock) {
final Cluster cluster = new Cluster(3);
cluster.runRandomly();
cluster.stabilise();
final ClusterNode leader = cluster.getAnyLeader();
leader.submitUpdateTask("update NO_MASTER_BLOCK_SETTING", cs -> {
final Builder settingsBuilder = Settings.builder().put(cs.metaData().persistentSettings());
settingsBuilder.put(NO_MASTER_BLOCK_SETTING.getKey(), noMasterBlockSetting);
return ClusterState.builder(cs).metaData(MetaData.builder(cs.metaData()).persistentSettings(settingsBuilder.build())).build();
});
cluster.runFor(DEFAULT_CLUSTER_STATE_UPDATE_DELAY, "committing setting update");
leader.disconnect();
cluster.runFor(defaultMillis(FOLLOWER_CHECK_TIMEOUT_SETTING) + defaultMillis(FOLLOWER_CHECK_INTERVAL_SETTING)
+ DEFAULT_CLUSTER_STATE_UPDATE_DELAY, "detecting disconnection");
assertThat(leader.clusterApplier.lastAppliedClusterState.blocks().global(), hasItem(expectedBlock));
// TODO reboot the leader and verify that the same block is applied when it restarts
}
private static long defaultMillis(Setting<TimeValue> setting) {
return setting.get(Settings.EMPTY).millis() + Cluster.DEFAULT_DELAY_VARIABILITY;
}
private static int defaultInt(Setting<Integer> setting) {
return setting.get(Settings.EMPTY);
}
// Updating the cluster state involves up to 7 delays:
// 1. submit the task to the master service
// 2. send PublishRequest
// 3. receive PublishResponse
// 4. send ApplyCommitRequest
// 5. apply committed cluster state
// 6. receive ApplyCommitResponse
// 7. apply committed state on master (last one to apply cluster state)
private static final long DEFAULT_CLUSTER_STATE_UPDATE_DELAY = 7 * DEFAULT_DELAY_VARIABILITY;
private static final int ELECTION_RETRIES = 10;
// The time it takes to complete an election
private static final long DEFAULT_ELECTION_DELAY
// Pinging all peers twice should be enough to discover all nodes
= defaultMillis(DISCOVERY_FIND_PEERS_INTERVAL_SETTING) * 2
// Then wait for an election to be scheduled; we allow enough time for retries to allow for collisions
+ defaultMillis(ELECTION_INITIAL_TIMEOUT_SETTING) * ELECTION_RETRIES
+ defaultMillis(ELECTION_BACK_OFF_TIME_SETTING) * ELECTION_RETRIES * (ELECTION_RETRIES - 1) / 2
+ defaultMillis(ELECTION_DURATION_SETTING) * ELECTION_RETRIES
// Allow two round-trip for pre-voting and voting
+ 4 * DEFAULT_DELAY_VARIABILITY
// Then a commit of the new leader's first cluster state
+ DEFAULT_CLUSTER_STATE_UPDATE_DELAY;
private static final long DEFAULT_STABILISATION_TIME =
// If leader just blackholed, need to wait for this to be detected
(defaultMillis(LEADER_CHECK_INTERVAL_SETTING) + defaultMillis(LEADER_CHECK_TIMEOUT_SETTING))
* defaultInt(LEADER_CHECK_RETRY_COUNT_SETTING)
// then wait for a follower to be promoted to leader
+ DEFAULT_ELECTION_DELAY
// then wait for the new leader to notice that the old leader is unresponsive
+ (defaultMillis(FOLLOWER_CHECK_INTERVAL_SETTING) + defaultMillis(FOLLOWER_CHECK_TIMEOUT_SETTING))
* defaultInt(FOLLOWER_CHECK_RETRY_COUNT_SETTING)
// then wait for the new leader to commit a state without the old leader
+ DEFAULT_CLUSTER_STATE_UPDATE_DELAY;
class Cluster {
static final long EXTREME_DELAY_VARIABILITY = 10000L;
static final long DEFAULT_DELAY_VARIABILITY = 100L;
final List<ClusterNode> clusterNodes;
final DeterministicTaskQueue deterministicTaskQueue = new DeterministicTaskQueue(
// TODO does ThreadPool need a node name any more?
Settings.builder().put(NODE_NAME_SETTING.getKey(), "deterministic-task-queue").build(), random());
private boolean disruptStorage;
private final VotingConfiguration initialConfiguration;
private final Set<String> disconnectedNodes = new HashSet<>();
private final Set<String> blackholedNodes = new HashSet<>();
private final Map<Long, ClusterState> committedStatesByVersion = new HashMap<>();
Cluster(int initialNodeCount) {
this(initialNodeCount, true);
}
Cluster(int initialNodeCount, boolean allNodesMasterEligible) {
deterministicTaskQueue.setExecutionDelayVariabilityMillis(DEFAULT_DELAY_VARIABILITY);
assertThat(initialNodeCount, greaterThan(0));
final Set<String> masterEligibleNodeIds = new HashSet<>(initialNodeCount);
clusterNodes = new ArrayList<>(initialNodeCount);
for (int i = 0; i < initialNodeCount; i++) {
final ClusterNode clusterNode = new ClusterNode(i, allNodesMasterEligible || i == 0 || randomBoolean());
clusterNodes.add(clusterNode);
if (clusterNode.getLocalNode().isMasterNode()) {
masterEligibleNodeIds.add(clusterNode.getId());
}
}
initialConfiguration = new VotingConfiguration(new HashSet<>(
randomSubsetOf(randomIntBetween(1, masterEligibleNodeIds.size()), masterEligibleNodeIds)));
logger.info("--> creating cluster of {} nodes (master-eligible nodes: {}) with initial configuration {}",
initialNodeCount, masterEligibleNodeIds, initialConfiguration);
}
void addNodesAndStabilise(int newNodesCount) {
addNodes(newNodesCount);
stabilise(
// The first pinging discovers the master
defaultMillis(DISCOVERY_FIND_PEERS_INTERVAL_SETTING)
// One message delay to send a join
+ DEFAULT_DELAY_VARIABILITY
// Commit a new cluster state with the new node(s). Might be split into multiple commits, and each might need a
// followup reconfiguration
+ newNodesCount * 2 * DEFAULT_CLUSTER_STATE_UPDATE_DELAY);
// TODO Investigate whether 4 publications is sufficient due to batching? A bound linear in the number of nodes isn't great.
}
void addNodes(int newNodesCount) {
logger.info("--> adding {} nodes", newNodesCount);
final int nodeSizeAtStart = clusterNodes.size();
for (int i = 0; i < newNodesCount; i++) {
final ClusterNode clusterNode = new ClusterNode(nodeSizeAtStart + i, true);
clusterNodes.add(clusterNode);
}
}
int size() {
return clusterNodes.size();
}
void runRandomly() {
// TODO supporting (preserving?) existing disruptions needs implementing if needed, for now we just forbid it
assertThat("may reconnect disconnected nodes, probably unexpected", disconnectedNodes, empty());
assertThat("may reconnect blackholed nodes, probably unexpected", blackholedNodes, empty());
final int randomSteps = scaledRandomIntBetween(10, 10000);
logger.info("--> start of safety phase of at least [{}] steps", randomSteps);
deterministicTaskQueue.setExecutionDelayVariabilityMillis(EXTREME_DELAY_VARIABILITY);
disruptStorage = true;
int step = 0;
long finishTime = -1;
while (finishTime == -1 || deterministicTaskQueue.getCurrentTimeMillis() <= finishTime) {
step++;
final int thisStep = step; // for lambdas
if (randomSteps <= step && finishTime == -1) {
finishTime = deterministicTaskQueue.getLatestDeferredExecutionTime();
deterministicTaskQueue.setExecutionDelayVariabilityMillis(DEFAULT_DELAY_VARIABILITY);
logger.debug("----> [runRandomly {}] reducing delay variability and running until [{}ms]", step, finishTime);
}
try {
if (rarely()) {
final ClusterNode clusterNode = getAnyNodePreferringLeaders();
final int newValue = randomInt();
onNode(clusterNode.getLocalNode(), () -> {
logger.debug("----> [runRandomly {}] proposing new value [{}] to [{}]",
thisStep, newValue, clusterNode.getId());
clusterNode.submitValue(newValue);
}).run();
} else if (rarely()) {
final ClusterNode clusterNode = getAnyNodePreferringLeaders();
final boolean autoShrinkVotingConfiguration = randomBoolean();
onNode(clusterNode.getLocalNode(),
() -> {
logger.debug("----> [runRandomly {}] setting auto-shrink configuration to {} on {}",
thisStep, autoShrinkVotingConfiguration, clusterNode.getId());
clusterNode.submitSetAutoShrinkVotingConfiguration(autoShrinkVotingConfiguration);
}).run();
} else if (rarely()) {
final ClusterNode clusterNode = getAnyNode();
onNode(clusterNode.getLocalNode(), () -> {
logger.debug("----> [runRandomly {}] forcing {} to become candidate", thisStep, clusterNode.getId());
synchronized (clusterNode.coordinator.mutex) {
clusterNode.coordinator.becomeCandidate("runRandomly");
}
}).run();
} else if (rarely()) {
final ClusterNode clusterNode = getAnyNode();
switch (randomInt(2)) {
case 0:
if (clusterNode.heal()) {
logger.debug("----> [runRandomly {}] healing {}", step, clusterNode.getId());
}
break;
case 1:
if (clusterNode.disconnect()) {
logger.debug("----> [runRandomly {}] disconnecting {}", step, clusterNode.getId());
}
break;
case 2:
if (clusterNode.blackhole()) {
logger.debug("----> [runRandomly {}] blackholing {}", step, clusterNode.getId());
}
break;
}
} else if (rarely()) {
final ClusterNode clusterNode = getAnyNode();
onNode(clusterNode.getLocalNode(),
() -> {
logger.debug("----> [runRandomly {}] applying initial configuration {} to {}",
thisStep, initialConfiguration, clusterNode.getId());
clusterNode.coordinator.setInitialConfiguration(initialConfiguration);
}).run();
} else {
if (deterministicTaskQueue.hasDeferredTasks() && randomBoolean()) {
deterministicTaskQueue.advanceTime();
} else if (deterministicTaskQueue.hasRunnableTasks()) {
deterministicTaskQueue.runRandomTask();
}
}
// TODO other random steps:
// - reboot a node
// - abdicate leadership
} catch (CoordinationStateRejectedException | UncheckedIOException ignored) {
// This is ok: it just means a message couldn't currently be handled.
}
assertConsistentStates();
}
disconnectedNodes.clear();
blackholedNodes.clear();
disruptStorage = false;
}
private void assertConsistentStates() {
for (final ClusterNode clusterNode : clusterNodes) {
clusterNode.coordinator.invariant();
}
updateCommittedStates();
}
private void updateCommittedStates() {
for (final ClusterNode clusterNode : clusterNodes) {
ClusterState applierState = clusterNode.coordinator.getApplierState();
ClusterState storedState = committedStatesByVersion.get(applierState.getVersion());
if (storedState == null) {
committedStatesByVersion.put(applierState.getVersion(), applierState);
} else {
assertEquals("expected " + applierState + " but got " + storedState,
value(applierState), value(storedState));
}
}
}
void stabilise() {
stabilise(DEFAULT_STABILISATION_TIME);
}
void stabilise(long stabilisationDurationMillis) {
assertThat("stabilisation requires default delay variability (and proper cleanup of raised variability)",
deterministicTaskQueue.getExecutionDelayVariabilityMillis(), lessThanOrEqualTo(DEFAULT_DELAY_VARIABILITY));
assertFalse("stabilisation requires stable storage", disruptStorage);
if (clusterNodes.stream().allMatch(ClusterNode::isNotUsefullyBootstrapped)) {
assertThat("setting initial configuration may fail with disconnected nodes", disconnectedNodes, empty());
assertThat("setting initial configuration may fail with blackholed nodes", blackholedNodes, empty());
runFor(defaultMillis(DISCOVERY_FIND_PEERS_INTERVAL_SETTING) * 2, "discovery prior to setting initial configuration");
final ClusterNode bootstrapNode = getAnyMasterEligibleNode();
bootstrapNode.applyInitialConfiguration();
} else {
logger.info("setting initial configuration not required");
}
runFor(stabilisationDurationMillis, "stabilising");
final ClusterNode leader = getAnyLeader();
final long leaderTerm = leader.coordinator.getCurrentTerm();
final Matcher<Long> isEqualToLeaderVersion = equalTo(leader.coordinator.getLastAcceptedState().getVersion());
final String leaderId = leader.getId();
assertTrue(leaderId + " has been bootstrapped", leader.coordinator.isInitialConfigurationSet());
assertTrue(leaderId + " exists in its last-applied state", leader.getLastAppliedClusterState().getNodes().nodeExists(leaderId));
assertThat(leaderId + " has applied its state ", leader.getLastAppliedClusterState().getVersion(), isEqualToLeaderVersion);
for (final ClusterNode clusterNode : clusterNodes) {
final String nodeId = clusterNode.getId();
assertFalse(nodeId + " should not have an active publication", clusterNode.coordinator.publicationInProgress());
if (clusterNode == leader) {
continue;
}
if (isConnectedPair(leader, clusterNode)) {
assertThat(nodeId + " is a follower of " + leaderId, clusterNode.coordinator.getMode(), is(FOLLOWER));
assertThat(nodeId + " has the same term as " + leaderId, clusterNode.coordinator.getCurrentTerm(), is(leaderTerm));
assertTrue(nodeId + " has voted for " + leaderId, leader.coordinator.hasJoinVoteFrom(clusterNode.getLocalNode()));
assertThat(nodeId + " has the same accepted state as " + leaderId,
clusterNode.coordinator.getLastAcceptedState().getVersion(), isEqualToLeaderVersion);
if (clusterNode.getClusterStateApplyResponse() == ClusterStateApplyResponse.SUCCEED) {
assertThat(nodeId + " has the same applied state as " + leaderId,
clusterNode.getLastAppliedClusterState().getVersion(), isEqualToLeaderVersion);
assertTrue(nodeId + " is in its own latest applied state",
clusterNode.getLastAppliedClusterState().getNodes().nodeExists(nodeId));
}
assertTrue(nodeId + " is in the latest applied state on " + leaderId,
leader.getLastAppliedClusterState().getNodes().nodeExists(nodeId));
assertTrue(nodeId + " has been bootstrapped", clusterNode.coordinator.isInitialConfigurationSet());
assertThat(nodeId + " has correct master", clusterNode.getLastAppliedClusterState().nodes().getMasterNode(),
equalTo(leader.getLocalNode()));
assertThat(nodeId + " has no NO_MASTER_BLOCK",
clusterNode.getLastAppliedClusterState().blocks().hasGlobalBlock(NO_MASTER_BLOCK_ID), equalTo(false));
} else {
assertThat(nodeId + " is not following " + leaderId, clusterNode.coordinator.getMode(), is(CANDIDATE));
assertThat(nodeId + " has no master", clusterNode.getLastAppliedClusterState().nodes().getMasterNode(), nullValue());
assertThat(nodeId + " has NO_MASTER_BLOCK",
clusterNode.getLastAppliedClusterState().blocks().hasGlobalBlock(NO_MASTER_BLOCK_ID), equalTo(true));
assertFalse(nodeId + " is not in the applied state on " + leaderId,
leader.getLastAppliedClusterState().getNodes().nodeExists(nodeId));
}
}
final Set<String> connectedNodeIds
= clusterNodes.stream().filter(n -> isConnectedPair(leader, n)).map(ClusterNode::getId).collect(Collectors.toSet());
assertThat(leader.getLastAppliedClusterState().getNodes().getSize(), equalTo(connectedNodeIds.size()));
final ClusterState lastAcceptedState = leader.coordinator.getLastAcceptedState();
final VotingConfiguration lastCommittedConfiguration = lastAcceptedState.getLastCommittedConfiguration();
assertTrue(connectedNodeIds + " should be a quorum of " + lastCommittedConfiguration,
lastCommittedConfiguration.hasQuorum(connectedNodeIds));
assertThat("no reconfiguration is in progress",
lastAcceptedState.getLastCommittedConfiguration(), equalTo(lastAcceptedState.getLastAcceptedConfiguration()));
assertThat("current configuration is already optimal",
leader.improveConfiguration(lastAcceptedState), sameInstance(lastAcceptedState));
}
void runFor(long runDurationMillis, String description) {
final long endTime = deterministicTaskQueue.getCurrentTimeMillis() + runDurationMillis;
logger.info("--> runFor({}ms) running until [{}ms]: {}", runDurationMillis, endTime, description);
while (deterministicTaskQueue.getCurrentTimeMillis() < endTime) {
while (deterministicTaskQueue.hasRunnableTasks()) {
try {
deterministicTaskQueue.runRandomTask();
} catch (CoordinationStateRejectedException e) {
logger.debug("ignoring benign exception thrown when stabilising", e);
}
for (final ClusterNode clusterNode : clusterNodes) {
clusterNode.coordinator.invariant();
}
updateCommittedStates();
}
if (deterministicTaskQueue.hasDeferredTasks() == false) {
// A 1-node cluster has no need for fault detection etc so will eventually run out of things to do.
assert clusterNodes.size() == 1 : clusterNodes.size();
break;
}
deterministicTaskQueue.advanceTime();
}
logger.info("--> runFor({}ms) completed run until [{}ms]: {}", runDurationMillis, endTime, description);
}
private boolean isConnectedPair(ClusterNode n1, ClusterNode n2) {
return n1 == n2 ||
(getConnectionStatus(n1.getLocalNode(), n2.getLocalNode()) == ConnectionStatus.CONNECTED
&& getConnectionStatus(n2.getLocalNode(), n1.getLocalNode()) == ConnectionStatus.CONNECTED);
}
ClusterNode getAnyLeader() {
List<ClusterNode> allLeaders = clusterNodes.stream().filter(ClusterNode::isLeader).collect(Collectors.toList());
assertThat("leaders", allLeaders, not(empty()));
return randomFrom(allLeaders);
}
private ConnectionStatus getConnectionStatus(DiscoveryNode sender, DiscoveryNode destination) {
ConnectionStatus connectionStatus;
if (blackholedNodes.contains(sender.getId()) || blackholedNodes.contains(destination.getId())) {
connectionStatus = ConnectionStatus.BLACK_HOLE;
} else if (disconnectedNodes.contains(sender.getId()) || disconnectedNodes.contains(destination.getId())) {
connectionStatus = ConnectionStatus.DISCONNECTED;
} else {
connectionStatus = ConnectionStatus.CONNECTED;
}
return connectionStatus;
}
ClusterNode getAnyMasterEligibleNode() {
return randomFrom(clusterNodes.stream().filter(n -> n.getLocalNode().isMasterNode()).collect(Collectors.toList()));
}
ClusterNode getAnyNode() {
return getAnyNodeExcept();
}
ClusterNode getAnyNodeExcept(ClusterNode... clusterNodes) {
List<ClusterNode> filteredNodes = getAllNodesExcept(clusterNodes);
assert filteredNodes.isEmpty() == false;
return randomFrom(filteredNodes);
}
List<ClusterNode> getAllNodesExcept(ClusterNode... clusterNodes) {
Set<String> forbiddenIds = Arrays.stream(clusterNodes).map(ClusterNode::getId).collect(Collectors.toSet());
List<ClusterNode> acceptableNodes
= this.clusterNodes.stream().filter(n -> forbiddenIds.contains(n.getId()) == false).collect(Collectors.toList());
return acceptableNodes;
}
ClusterNode getAnyNodePreferringLeaders() {
for (int i = 0; i < 3; i++) {
ClusterNode clusterNode = getAnyNode();
if (clusterNode.coordinator.getMode() == LEADER) {
return clusterNode;
}
}
return getAnyNode();
}
class MockPersistedState extends InMemoryPersistedState {
MockPersistedState(long term, ClusterState acceptedState) {
super(term, acceptedState);
}
private void possiblyFail(String description) {
if (disruptStorage && rarely()) {
// TODO revisit this when we've decided how PersistedState should throw exceptions
logger.trace("simulating IO exception [{}]", description);
if (randomBoolean()) {
throw new UncheckedIOException(new IOException("simulated IO exception [" + description + ']'));
} else {
throw new CoordinationStateRejectedException("simulated IO exception [" + description + ']');
}
}
}
@Override
public void setCurrentTerm(long currentTerm) {
possiblyFail("before writing term of " + currentTerm);
super.setCurrentTerm(currentTerm);
// TODO possiblyFail() here if that's a failure mode of the storage layer
}
@Override
public void setLastAcceptedState(ClusterState clusterState) {
possiblyFail("before writing last-accepted state of term=" + clusterState.term() + ", version=" + clusterState.version());
super.setLastAcceptedState(clusterState);
// TODO possiblyFail() here if that's a failure mode of the storage layer
}
}
class ClusterNode {
private final Logger logger = LogManager.getLogger(ClusterNode.class);
private final int nodeIndex;
private Coordinator coordinator;
private DiscoveryNode localNode;
private final PersistedState persistedState;
private FakeClusterApplier clusterApplier;
private AckedFakeThreadPoolMasterService masterService;
private TransportService transportService;
private DisruptableMockTransport mockTransport;
private ClusterStateApplyResponse clusterStateApplyResponse = ClusterStateApplyResponse.SUCCEED;
ClusterNode(int nodeIndex, boolean masterEligible) {
this.nodeIndex = nodeIndex;
localNode = createDiscoveryNode(masterEligible);
persistedState = new MockPersistedState(0L,
clusterState(0L, 0L, localNode, VotingConfiguration.EMPTY_CONFIG, VotingConfiguration.EMPTY_CONFIG, 0L));
onNode(localNode, this::setUp).run();
}
private DiscoveryNode createDiscoveryNode(boolean masterEligible) {
final TransportAddress address = buildNewFakeTransportAddress();
return new DiscoveryNode("", "node" + nodeIndex,
UUIDs.randomBase64UUID(random()), // generated deterministically for repeatable tests
address.address().getHostString(), address.getAddress(), address, Collections.emptyMap(),
masterEligible ? EnumSet.allOf(Role.class) : emptySet(), Version.CURRENT);
}
private void setUp() {
mockTransport = new DisruptableMockTransport(logger) {
@Override
protected DiscoveryNode getLocalNode() {
return localNode;
}
@Override
protected ConnectionStatus getConnectionStatus(DiscoveryNode sender, DiscoveryNode destination) {
return Cluster.this.getConnectionStatus(sender, destination);
}
@Override
protected Optional<DisruptableMockTransport> getDisruptedCapturingTransport(DiscoveryNode node, String action) {
final Predicate<ClusterNode> matchesDestination;
if (action.equals(HANDSHAKE_ACTION_NAME)) {
matchesDestination = n -> n.getLocalNode().getAddress().equals(node.getAddress());
} else {
matchesDestination = n -> n.getLocalNode().equals(node);
}
return clusterNodes.stream().filter(matchesDestination).findAny().map(cn -> cn.mockTransport);
}
@Override
protected void handle(DiscoveryNode sender, DiscoveryNode destination, String action, Runnable doDelivery) {
// handshake needs to run inline as the caller blockingly waits on the result
if (action.equals(HANDSHAKE_ACTION_NAME)) {
onNode(destination, doDelivery).run();
} else {
deterministicTaskQueue.scheduleNow(onNode(destination, doDelivery));
}
}
@Override
protected void onBlackholedDuringSend(long requestId, String action, DiscoveryNode destination) {
if (action.equals(HANDSHAKE_ACTION_NAME)) {
logger.trace("ignoring blackhole and delivering {}", getRequestDescription(requestId, action, destination));
// handshakes always have a timeout, and are sent in a blocking fashion, so we must respond with an exception.
sendFromTo(destination, getLocalNode(), action, getDisconnectException(requestId, action, destination));
} else {
super.onBlackholedDuringSend(requestId, action, destination);
}
}
};
final Settings settings = Settings.builder()
.putList(ClusterBootstrapService.INITIAL_MASTER_NODES_SETTING.getKey(),
ClusterBootstrapService.INITIAL_MASTER_NODES_SETTING.get(Settings.EMPTY)).build(); // suppress auto-bootstrap
final ClusterSettings clusterSettings = new ClusterSettings(settings, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS);
clusterApplier = new FakeClusterApplier(settings, clusterSettings);
masterService = new AckedFakeThreadPoolMasterService("test_node", "test",
runnable -> deterministicTaskQueue.scheduleNow(onNode(localNode, runnable)));
transportService = mockTransport.createTransportService(
settings, deterministicTaskQueue.getThreadPool(runnable -> onNode(localNode, runnable)), NOOP_TRANSPORT_INTERCEPTOR,
a -> localNode, null, emptySet());
coordinator = new Coordinator("test_node", settings, clusterSettings, transportService, writableRegistry(),
ESAllocationTestCase.createAllocationService(Settings.EMPTY), masterService, this::getPersistedState,
Cluster.this::provideUnicastHosts, clusterApplier, Randomness.get());
masterService.setClusterStatePublisher(coordinator);
transportService.start();
transportService.acceptIncomingRequests();
masterService.start();
coordinator.start();
coordinator.startInitialJoin();
}
private PersistedState getPersistedState() {
return persistedState;
}
String getId() {
return localNode.getId();
}
DiscoveryNode getLocalNode() {
return localNode;
}
boolean isLeader() {
return coordinator.getMode() == LEADER;
}
ClusterState improveConfiguration(ClusterState currentState) {
synchronized (coordinator.mutex) {
return coordinator.improveConfiguration(currentState);
}
}
void setClusterStateApplyResponse(ClusterStateApplyResponse clusterStateApplyResponse) {
this.clusterStateApplyResponse = clusterStateApplyResponse;
}
ClusterStateApplyResponse getClusterStateApplyResponse() {
return clusterStateApplyResponse;
}
void submitSetAutoShrinkVotingConfiguration(final boolean autoShrinkVotingConfiguration) {
submitUpdateTask("set master nodes failure tolerance [" + autoShrinkVotingConfiguration + "]", cs ->
ClusterState.builder(cs).metaData(
MetaData.builder(cs.metaData())
.persistentSettings(Settings.builder()
.put(cs.metaData().persistentSettings())
.put(CLUSTER_AUTO_SHRINK_VOTING_CONFIGURATION.getKey(), autoShrinkVotingConfiguration)
.build())
.build())
.build());
}
AckCollector submitValue(final long value) {
return submitUpdateTask("new value [" + value + "]", cs -> setValue(cs, value));
}
AckCollector submitUpdateTask(String source, UnaryOperator<ClusterState> clusterStateUpdate) {
final AckCollector ackCollector = new AckCollector();
onNode(localNode, () -> {
logger.trace("[{}] submitUpdateTask: enqueueing [{}]", localNode.getId(), source);
final long submittedTerm = coordinator.getCurrentTerm();
masterService.submitStateUpdateTask(source,
new ClusterStateUpdateTask() {
@Override
public ClusterState execute(ClusterState currentState) {
assertThat(currentState.term(), greaterThanOrEqualTo(submittedTerm));
masterService.nextAckCollector = ackCollector;
return clusterStateUpdate.apply(currentState);
}
@Override
public void onFailure(String source, Exception e) {
logger.debug(() -> new ParameterizedMessage("failed to publish: [{}]", source), e);
}
@Override
public void clusterStateProcessed(String source, ClusterState oldState, ClusterState newState) {
updateCommittedStates();
ClusterState state = committedStatesByVersion.get(newState.version());
assertNotNull("State not committed : " + newState.toString(), state);
assertEquals(value(state), value(newState));
logger.trace("successfully published: [{}]", newState);
}
});
}).run();
return ackCollector;
}
@Override
public String toString() {
return localNode.toString();
}
boolean heal() {
boolean unBlackholed = blackholedNodes.remove(localNode.getId());
boolean unDisconnected = disconnectedNodes.remove(localNode.getId());
assert unBlackholed == false || unDisconnected == false;
return unBlackholed || unDisconnected;
}
boolean disconnect() {
boolean unBlackholed = blackholedNodes.remove(localNode.getId());
boolean disconnected = disconnectedNodes.add(localNode.getId());
assert disconnected || unBlackholed == false;
return disconnected;
}
boolean blackhole() {
boolean unDisconnected = disconnectedNodes.remove(localNode.getId());
boolean blackholed = blackholedNodes.add(localNode.getId());
assert blackholed || unDisconnected == false;
return blackholed;
}
void onDisconnectEventFrom(ClusterNode clusterNode) {
transportService.disconnectFromNode(clusterNode.localNode);
}
ClusterState getLastAppliedClusterState() {
return clusterApplier.lastAppliedClusterState;
}
void applyInitialConfiguration() {
onNode(localNode, () -> {
try {
coordinator.setInitialConfiguration(initialConfiguration);
logger.info("successfully set initial configuration to {}", initialConfiguration);
} catch (CoordinationStateRejectedException e) {
logger.info(new ParameterizedMessage("failed to set initial configuration to {}", initialConfiguration), e);
}
}).run();
}
private boolean isNotUsefullyBootstrapped() {
return getLocalNode().isMasterNode() == false || coordinator.isInitialConfigurationSet() == false;
}
private class FakeClusterApplier implements ClusterApplier {
final ClusterName clusterName;
private final ClusterSettings clusterSettings;
ClusterState lastAppliedClusterState;
private FakeClusterApplier(Settings settings, ClusterSettings clusterSettings) {
clusterName = ClusterName.CLUSTER_NAME_SETTING.get(settings);
this.clusterSettings = clusterSettings;
}
@Override
public void setInitialState(ClusterState initialState) {
assert lastAppliedClusterState == null;
assert initialState != null;
lastAppliedClusterState = initialState;
}
@Override
public void onNewClusterState(String source, Supplier<ClusterState> clusterStateSupplier, ClusterApplyListener listener) {
switch (clusterStateApplyResponse) {
case SUCCEED:
deterministicTaskQueue.scheduleNow(onNode(localNode, new Runnable() {
@Override
public void run() {
final ClusterState oldClusterState = clusterApplier.lastAppliedClusterState;
final ClusterState newClusterState = clusterStateSupplier.get();
assert oldClusterState.version() <= newClusterState.version() : "updating cluster state from version "
+ oldClusterState.version() + " to stale version " + newClusterState.version();
clusterApplier.lastAppliedClusterState = newClusterState;
final Settings incomingSettings = newClusterState.metaData().settings();
clusterSettings.applySettings(incomingSettings); // TODO validation might throw exceptions here.
listener.onSuccess(source);
}
@Override
public String toString() {
return "apply cluster state from [" + source + "]";
}
}));
break;
case FAIL:
deterministicTaskQueue.scheduleNow(onNode(localNode, new Runnable() {
@Override
public void run() {
listener.onFailure(source, new ElasticsearchException("cluster state application failed"));
}
@Override
public String toString() {
return "fail to apply cluster state from [" + source + "]";
}
}));
break;
case HANG:
if (randomBoolean()) {
deterministicTaskQueue.scheduleNow(onNode(localNode, new Runnable() {
@Override
public void run() {
final ClusterState oldClusterState = clusterApplier.lastAppliedClusterState;
final ClusterState newClusterState = clusterStateSupplier.get();
assert oldClusterState.version() <= newClusterState.version() :
"updating cluster state from version "
+ oldClusterState.version() + " to stale version " + newClusterState.version();
clusterApplier.lastAppliedClusterState = newClusterState;
}
@Override
public String toString() {
return "apply cluster state from [" + source + "] without ack";
}
}));
}
break;
}
}
}
}
private List<TransportAddress> provideUnicastHosts(HostsResolver ignored) {
return clusterNodes.stream().map(ClusterNode::getLocalNode).map(DiscoveryNode::getAddress).collect(Collectors.toList());
}
}
public static Runnable onNode(DiscoveryNode node, Runnable runnable) {
final String nodeId = "{" + node.getId() + "}{" + node.getEphemeralId() + "}";
return new Runnable() {
@Override
public void run() {
try (CloseableThreadContext.Instance ignored = CloseableThreadContext.put("nodeId", nodeId)) {
runnable.run();
}
}
@Override
public String toString() {
return nodeId + ": " + runnable.toString();
}
};
}
static class AckCollector implements AckListener {
private final Set<DiscoveryNode> ackedNodes = new HashSet<>();
private final List<DiscoveryNode> successfulNodes = new ArrayList<>();
private final List<DiscoveryNode> unsuccessfulNodes = new ArrayList<>();
@Override
public void onCommit(TimeValue commitTime) {
// TODO we only currently care about per-node acks
}
@Override
public void onNodeAck(DiscoveryNode node, Exception e) {
assertTrue("duplicate ack from " + node, ackedNodes.add(node));
if (e == null) {
successfulNodes.add(node);
} else {
unsuccessfulNodes.add(node);
}
}
boolean hasAckedSuccessfully(ClusterNode clusterNode) {
return successfulNodes.contains(clusterNode.localNode);
}
boolean hasAckedUnsuccessfully(ClusterNode clusterNode) {
return unsuccessfulNodes.contains(clusterNode.localNode);
}
boolean hasAcked(ClusterNode clusterNode) {
return ackedNodes.contains(clusterNode.localNode);
}
int getSuccessfulAckIndex(ClusterNode clusterNode) {
assert successfulNodes.contains(clusterNode.localNode) : "get index of " + clusterNode;
return successfulNodes.indexOf(clusterNode.localNode);
}
}
static class AckedFakeThreadPoolMasterService extends FakeThreadPoolMasterService {
AckCollector nextAckCollector = new AckCollector();
AckedFakeThreadPoolMasterService(String nodeName, String serviceName, Consumer<Runnable> onTaskAvailableToRun) {
super(nodeName, serviceName, onTaskAvailableToRun);
}
@Override
protected AckListener wrapAckListener(AckListener ackListener) {
final AckCollector ackCollector = nextAckCollector;
nextAckCollector = new AckCollector();
return new AckListener() {
@Override
public void onCommit(TimeValue commitTime) {
ackCollector.onCommit(commitTime);
ackListener.onCommit(commitTime);
}
@Override
public void onNodeAck(DiscoveryNode node, Exception e) {
ackCollector.onNodeAck(node, e);
ackListener.onNodeAck(node, e);
}
};
}
}
/**
* How to behave with a new cluster state
*/
enum ClusterStateApplyResponse {
/**
* Apply the state (default)
*/
SUCCEED,
/**
* Reject the state with an exception.
*/
FAIL,
/**
* Never respond either way.
*/
HANG,
}
}
|
3e1f0ceed849959e1b085a4a3e4dd1a9e34303ca | 16,464 | java | Java | passwdsafe/src/main/java/com/jefftharris/passwdsafe/PasswdSafeListFragment.java | Rushera/passwdsafe | e51c8d19f70c7d2d8e842bcc6f057bdbeba0a78c | [
"Artistic-2.0"
] | null | null | null | passwdsafe/src/main/java/com/jefftharris/passwdsafe/PasswdSafeListFragment.java | Rushera/passwdsafe | e51c8d19f70c7d2d8e842bcc6f057bdbeba0a78c | [
"Artistic-2.0"
] | null | null | null | passwdsafe/src/main/java/com/jefftharris/passwdsafe/PasswdSafeListFragment.java | Rushera/passwdsafe | e51c8d19f70c7d2d8e842bcc6f057bdbeba0a78c | [
"Artistic-2.0"
] | null | null | null | 31.608445 | 132 | 0.580641 | 13,125 | /*
* Copyright (©) 2014 Jeff Harris <upchh@example.com>
* All rights reserved. Use of the code is allowed under the
* Artistic License 2.0 terms, as specified in the LICENSE file
* distributed with this code, or available from
* http://www.opensource.org/licenses/artistic-license-2.0.php
*/
package com.jefftharris.passwdsafe;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.AsyncTaskLoader;
import android.support.v4.content.Loader;
import android.text.TextUtils;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.jefftharris.passwdsafe.lib.view.GuiUtils;
import com.jefftharris.passwdsafe.view.CopyField;
import com.jefftharris.passwdsafe.view.PasswdLocation;
import com.jefftharris.passwdsafe.view.PasswdRecordListData;
import java.util.List;
/**
* Fragment showing lists of items from a PasswdSafe file
*/
public class PasswdSafeListFragment extends ListFragment
implements LoaderManager.LoaderCallbacks<List<PasswdRecordListData>>,
View.OnClickListener
{
/** Mode for which items are shown from the file */
public enum Mode
{
NONE,
GROUPS,
RECORDS,
ALL
}
/** Listener interface for owning activity */
public interface Listener
{
/** Get the current record items in a background thread */
List<PasswdRecordListData> getBackgroundRecordItems(boolean incRecords,
boolean incGroups);
/** Is copying supported */
boolean isCopySupported();
/** Copy a field */
void copyField(CopyField field, String recUuid);
/** Change the location in the password file */
void changeLocation(PasswdLocation location);
/** Update the view for a list of records */
void updateViewList(PasswdLocation location);
}
private Mode itsMode = Mode.NONE;
private PasswdLocation itsLocation;
private boolean itsIsContents = false;
private Listener itsListener;
private View itsGroupPanel;
private TextView itsGroupLabel;
private TextView itsEmptyText;
private ItemListAdapter itsAdapter;
/** Create a new instance */
public static PasswdSafeListFragment newInstance(
PasswdLocation location,
@SuppressWarnings("SameParameterValue") boolean isContents)
{
PasswdSafeListFragment frag = new PasswdSafeListFragment();
Bundle args = new Bundle();
args.putParcelable("location", location);
args.putBoolean("isContents", isContents);
frag.setArguments(args);
return frag;
}
/* (non-Javadoc)
* @see android.support.v4.app.Fragment#onCreate(android.os.Bundle)
*/
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Bundle args = getArguments();
PasswdLocation location;
boolean isContents = false;
if (args != null) {
location = args.getParcelable("location");
isContents = args.getBoolean("isContents", false);
} else {
location = new PasswdLocation();
}
itsLocation = location;
itsIsContents = isContents;
}
@Override
public void onAttach(Context ctx)
{
super.onAttach(ctx);
itsListener = (Listener)ctx;
}
/* (non-Javadoc)
* @see android.support.v4.app.Fragment#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)
*/
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState)
{
View root = inflater.inflate(R.layout.fragment_passwdsafe_list,
container, false);
itsGroupPanel = root.findViewById(R.id.current_group_panel);
itsGroupPanel.setOnClickListener(this);
itsGroupLabel = (TextView)root.findViewById(R.id.current_group_label);
itsEmptyText = (TextView)root.findViewById(android.R.id.empty);
return root;
}
/* (non-Javadoc)
* @see android.support.v4.app.Fragment#onActivityCreated(android.os.Bundle)
*/
@Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
if (itsListener.isCopySupported()) {
registerForContextMenu(getListView());
}
itsAdapter = new ItemListAdapter(itsIsContents, getActivity());
setListAdapter(itsAdapter);
}
/* (non-Javadoc)
* @see android.support.v4.app.Fragment#onResume()
*/
@Override
public void onResume()
{
super.onResume();
if (itsIsContents) {
itsListener.updateViewList(itsLocation);
}
}
@Override
public void onDetach()
{
super.onDetach();
itsListener = null;
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo)
{
super.onCreateContextMenu(menu, v, menuInfo);
AdapterView.AdapterContextMenuInfo info =
(AdapterView.AdapterContextMenuInfo)menuInfo;
PasswdRecordListData listItem = itsAdapter.getItem(info.position);
if (listItem.itsIsRecord) {
menu.setHeaderTitle(listItem.itsTitle);
int group = itsIsContents ? PasswdSafe.CONTEXT_GROUP_LIST_CONTENTS :
PasswdSafe.CONTEXT_GROUP_LIST;
menu.add(group, R.id.menu_copy_user, 0, R.string.copy_user);
menu.add(group, R.id.menu_copy_password, 0, R.string.copy_password);
}
}
@Override
public boolean onContextItemSelected(MenuItem item)
{
int group = itsIsContents ? PasswdSafe.CONTEXT_GROUP_LIST_CONTENTS :
PasswdSafe.CONTEXT_GROUP_LIST;
if (item.getGroupId() != group) {
return super.onContextItemSelected(item);
}
switch (item.getItemId()) {
case R.id.menu_copy_password:
case R.id.menu_copy_user: {
AdapterView.AdapterContextMenuInfo info =
(AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
final PasswdRecordListData listItem =
itsAdapter.getItem(info.position);
if (!listItem.itsIsRecord) {
itsListener.copyField(
(item.getItemId() == R.id.menu_copy_password) ?
CopyField.PASSWORD : CopyField.USER_NAME,
listItem.itsUuid);
}
return true;
}
}
return super.onContextItemSelected(item);
}
/* (non-Javadoc)
* @see android.support.v4.app.ListFragment#onListItemClick(android.widget.ListView, android.view.View, int, long)
*/
@Override
public void onListItemClick(ListView l, View v, int position, long id)
{
PasswdRecordListData item = itsAdapter.getItem(position);
if (item.itsIsRecord) {
itsListener.changeLocation(itsLocation.selectRecord(item.itsUuid));
} else {
itsListener.changeLocation(itsLocation.selectGroup(item.itsTitle));
}
}
/* (non-Javadoc)
* @see android.view.View.OnClickListener#onClick(android.view.View)
*/
@Override
public void onClick(View v)
{
switch(v.getId()) {
case R.id.current_group_panel: {
itsListener.changeLocation(itsLocation.popGroup());
break;
}
}
}
/** Update the location shown by the list */
public void updateLocationView(PasswdLocation location, Mode mode)
{
itsLocation = location;
itsMode = mode;
refreshList();
}
/** Refresh the list due to file changes */
private void refreshList()
{
if (!isResumed()) {
return;
}
LoaderManager lm = getLoaderManager();
lm.destroyLoader(0);
lm.restartLoader(0, null, this);
boolean groupVisible = false;
switch (itsMode) {
case RECORDS:
case NONE: {
groupVisible = false;
break;
}
case GROUPS:
case ALL: {
groupVisible = true;
break;
}
}
if (groupVisible) {
String groupPath = itsLocation.getGroupPath();
if (TextUtils.isEmpty(groupPath)) {
groupVisible = false;
} else {
itsGroupLabel.setText(groupPath);
}
}
itsGroupPanel.setVisibility(groupVisible ? View.VISIBLE : View.GONE);
}
/* (non-Javadoc)
* @see android.support.v4.app.LoaderManager.LoaderCallbacks#onCreateLoader(int, android.os.Bundle)
*/
@Override
public Loader<List<PasswdRecordListData>> onCreateLoader(int id, Bundle args)
{
return new ItemLoader(itsMode, itsListener, getActivity());
}
/* (non-Javadoc)
* @see android.support.v4.app.LoaderManager.LoaderCallbacks#onLoadFinished(android.support.v4.content.Loader, java.lang.Object)
*/
@Override
public void onLoadFinished(Loader<List<PasswdRecordListData>> loader,
List<PasswdRecordListData> data)
{
int selPos = itsAdapter.setData(
data, itsIsContents ? null : itsLocation.getRecord());
if (isResumed()) {
ListView list = getListView();
if (selPos != -1) {
list.setItemChecked(selPos, true);
list.smoothScrollToPosition(selPos);
} else {
list.clearChoices();
}
if (itsEmptyText.getText().length() == 0) {
itsEmptyText.setText(itsIsContents ? R.string.no_records :
R.string.no_groups);
}
}
}
/* (non-Javadoc)
* @see android.support.v4.app.LoaderManager.LoaderCallbacks#onLoaderReset(android.support.v4.content.Loader)
*/
@Override
public void onLoaderReset(Loader<List<PasswdRecordListData>> loader)
{
onLoadFinished(loader, null);
}
/** List adapter for file items */
private static class ItemListAdapter
extends ArrayAdapter<PasswdRecordListData>
{
private final LayoutInflater itsInflater;
private final boolean itsIsContents;
/** Constructor */
public ItemListAdapter(boolean isContents, Context context)
{
super(context, R.layout.passwdsafe_list_item, android.R.id.text1);
itsInflater = (LayoutInflater)context.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
itsIsContents = isContents;
}
/** Set the list data */
public int setData(List<PasswdRecordListData> data,
String selectedRecord)
{
int selectedPos = -1;
setNotifyOnChange(false);
clear();
if (data != null) {
int idx = 0;
for (PasswdRecordListData item: data) {
add(item);
if ((selectedRecord != null) &&
TextUtils.equals(item.itsUuid, selectedRecord)) {
selectedPos = idx;
}
++idx;
}
}
setNotifyOnChange(true);
notifyDataSetChanged();
return selectedPos;
}
/* (non-Javadoc)
* @see android.widget.ArrayAdapter#getView(int, android.view.View, android.view.ViewGroup)
*/
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder itemViews;
if (convertView == null) {
convertView = itsInflater.inflate(R.layout.passwdsafe_list_item,
parent, false);
itemViews = new ViewHolder(convertView);
convertView.setTag(itemViews);
} else {
itemViews = (ViewHolder)convertView.getTag();
}
PasswdRecordListData item = getItem(position);
ListView list = (ListView)parent;
boolean isSelected = list.isItemChecked(position);
itemViews.update(item, isSelected,
!itsIsContents && item.itsIsRecord);
return convertView;
}
/**
* Holder for the views for an item in the list
*/
private static class ViewHolder
{
private final TextView itsTitle;
private final TextView itsUser;
private final TextView itsMatch;
private final ImageView itsIcon;
private final CheckBox itsSelection;
private int itsLastIconImage;
/** Constructor */
public ViewHolder(View view)
{
itsTitle = (TextView)view.findViewById(android.R.id.text1);
itsUser = (TextView)view.findViewById(android.R.id.text2);
itsMatch = (TextView)view.findViewById(R.id.match);
itsIcon = (ImageView)view.findViewById(R.id.icon);
itsSelection = (CheckBox)view.findViewById(R.id.selection);
itsLastIconImage = -1;
}
/** Update the fields for a list item */
public void update(PasswdRecordListData item,
boolean selected,
boolean isLeftListRecord)
{
setText(itsTitle, item.itsTitle);
setText(itsUser, item.itsUser);
setText(itsMatch, item.itsMatch);
if (itsLastIconImage != item.itsIcon) {
itsIcon.setImageResource(item.itsIcon);
itsLastIconImage = item.itsIcon;
}
itsSelection.setChecked(selected);
GuiUtils.setVisible(itsSelection, isLeftListRecord);
itsTitle.requestLayout();
}
/** Set text in a field */
private static void setText(TextView tv, String text)
{
tv.setText((text == null) ? "" : text);
}
}
}
/** Loader for file items */
private static class ItemLoader
extends AsyncTaskLoader<List<PasswdRecordListData>>
{
private final Mode itsMode;
private final Listener itsActListener;
/** Constructor */
public ItemLoader(Mode mode, Listener actListener,
Context context)
{
super(context);
itsMode = mode;
itsActListener = actListener;
}
/** Handle when the loader is started */
@Override
protected void onStartLoading()
{
forceLoad();
}
/* (non-Javadoc)
* @see android.support.v4.content.AsyncTaskLoader#loadInBackground()
*/
@Override
public List<PasswdRecordListData> loadInBackground()
{
boolean incRecords = false;
boolean incGroups = false;
switch (itsMode) {
case NONE: {
break;
}
case RECORDS: {
incRecords = true;
break;
}
case GROUPS: {
incGroups = true;
break;
}
case ALL: {
incRecords = true;
incGroups = true;
break;
}
}
return itsActListener.getBackgroundRecordItems(incRecords,
incGroups);
}
}
}
|
3e1f0da22ffd4247609c57e183b5ccd97bf55307 | 10,222 | java | Java | src/main/java/com/simiacryptus/mindseye/layers/cudnn/ImgBandBiasLayer.java | SimiaCryptus/mindseye | 3ba98c459c8ccb6c382a9b3eb769ee8cd744f82e | [
"Apache-2.0"
] | 8 | 2017-07-08T22:03:35.000Z | 2022-03-29T16:08:27.000Z | src/main/java/com/simiacryptus/mindseye/layers/cudnn/ImgBandBiasLayer.java | SimiaCryptus/mindseye | 3ba98c459c8ccb6c382a9b3eb769ee8cd744f82e | [
"Apache-2.0"
] | 1 | 2018-03-05T15:00:39.000Z | 2018-03-10T16:47:39.000Z | src/main/java/com/simiacryptus/mindseye/layers/cudnn/ImgBandBiasLayer.java | SimiaCryptus/mindseye | 3ba98c459c8ccb6c382a9b3eb769ee8cd744f82e | [
"Apache-2.0"
] | 2 | 2019-01-04T14:13:38.000Z | 2019-09-06T06:45:00.000Z | 30.975758 | 154 | 0.668754 | 13,126 | /*
* Copyright (c) 2018 by Andrew Charneski.
*
* The author licenses this file to you under the
* Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance
* with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.simiacryptus.mindseye.layers.cudnn;
import com.google.gson.JsonObject;
import com.simiacryptus.mindseye.lang.*;
import com.simiacryptus.mindseye.lang.cudnn.*;
import com.simiacryptus.mindseye.layers.java.ProductInputsLayer;
import com.simiacryptus.util.FastRandom;
import com.simiacryptus.util.Util;
import jcuda.jcudnn.cudnnOpTensorDescriptor;
import jcuda.jcudnn.cudnnOpTensorOp;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.function.DoubleSupplier;
import java.util.function.IntToDoubleFunction;
import java.util.stream.Stream;
/**
* This key multiplies together the inputs, element-by-element. It can be used to implement integer-power activation
* layers, such as the square needed in MeanSqLossLayer.
*/
@SuppressWarnings("serial")
public class ImgBandBiasLayer extends LayerBase implements MultiPrecision<ImgBandBiasLayer> {
private Precision precision = Precision.Double;
private Tensor bias;
/**
* Instantiates a new Product inputs key.
*
* @param bands the bands
*/
public ImgBandBiasLayer(int bands) {
this(new Tensor(1, 1, bands));
this.bias.freeRef();
}
/**
* Instantiates a new Product inputs key.
*
* @param bias the bias
*/
public ImgBandBiasLayer(final Tensor bias) {
this.bias = bias;
this.bias.addRef();
}
/**
* Instantiates a new Product inputs key.
*
* @param id the id
* @param rs the rs
*/
protected ImgBandBiasLayer(@Nonnull final JsonObject id, final Map<CharSequence, byte[]> rs) {
super(id);
this.precision = Precision.valueOf(id.getAsJsonPrimitive("precision").getAsString());
this.bias = Tensor.fromJson(id.get("bias"), rs);
}
/**
* From json product inputs key.
*
* @param json the json
* @param rs the rs
* @return the product inputs key
*/
public static ImgBandBiasLayer fromJson(@Nonnull final JsonObject json, Map<CharSequence, byte[]> rs) {
return new ImgBandBiasLayer(json, rs);
}
/**
* Gets compatibility key.
*
* @return the compatibility key
*/
@Nonnull
public Layer getCompatibilityLayer() {
return this.as(ProductInputsLayer.class);
}
@Nullable
@Override
public Result evalAndFree(@Nonnull final Result... inObj) {
if (!CudaSystem.isEnabled()) return getCompatibilityLayer().evalAndFree(inObj);
if (inObj.length != 1) {
throw new IllegalArgumentException("inObj.length=" + inObj.length);
}
Result input = inObj[0];
final TensorList inputData = input.getData();
@Nonnull final int[] inputDimensions = inputData.getDimensions();
final int length = inputData.length();
if (3 != inputDimensions.length) {
throw new IllegalArgumentException("dimensions=" + Arrays.toString(inputDimensions));
}
if (0 == Tensor.length(inputData.getDimensions())) {
return input;
}
if (0 == bias.length()) {
return input;
}
// assert !right.isAlive();
return new Result(CudaSystem.run(gpu -> {
@Nonnull final CudaResource<cudnnOpTensorDescriptor> opDescriptor = gpu.newOpDescriptor(cudnnOpTensorOp.CUDNN_OP_TENSOR_ADD, precision);
@Nonnull final CudaDevice.CudaTensorDescriptor outputDescriptor = gpu.newTensorDescriptor(precision, length,
inputDimensions[2], inputDimensions[1], inputDimensions[0],
inputDimensions[2] * inputDimensions[1] * inputDimensions[0],
inputDimensions[1] * inputDimensions[0],
inputDimensions[0],
1);
@Nullable final CudaTensor inputTensor = gpu.getTensor(inputData, precision, MemoryType.Device, false);
CudaMemory biasMem = gpu.allocate(bias.length() * precision.size, MemoryType.Device, true).write(precision, bias.getData());
int[] biasDim = bias.getDimensions();
CudaDevice.CudaTensorDescriptor biasDescriptor = gpu.newTensorDescriptor(precision, 1, biasDim[2], biasDim[1], biasDim[0],
biasDim[2] * biasDim[1] * biasDim[0], biasDim[1] * biasDim[0], biasDim[0], 1);
//assert lPtr.size == rPtr.size;
@Nonnull final CudaMemory outputPtr = gpu.allocate((long) precision.size * outputDescriptor.nStride * length, MemoryType.Managed.normalize(), true);
CudaMemory inputMemory = inputTensor.getMemory(gpu);
CudaSystem.handle(gpu.cudnnOpTensor(opDescriptor.getPtr(),
precision.getPointer(1.0), inputTensor.descriptor.getPtr(), inputMemory.getPtr(),
precision.getPointer(1.0), biasDescriptor.getPtr(), biasMem.getPtr(),
precision.getPointer(0.0), outputDescriptor.getPtr(), outputPtr.getPtr()));
assert CudaDevice.isThreadDeviceId(gpu.getDeviceId());
inputMemory.dirty();
biasMem.dirty();
outputPtr.dirty();
inputMemory.freeRef();
biasMem.freeRef();
biasDescriptor.freeRef();
inputTensor.freeRef();
opDescriptor.freeRef();
CudaTensor cudaTensor = CudaTensor.wrap(outputPtr, outputDescriptor, precision);
return CudaTensorList.wrap(cudaTensor, length, inputDimensions, precision);
}, inputData), (@Nonnull final DeltaSet<UUID> buffer, @Nonnull final TensorList delta) -> {
if (!isFrozen()) {
@Nonnull double[] biasDelta = CudaSystem.run(gpu -> {
@Nullable final CudaTensor deltaTensor = gpu.getTensor(delta, precision, MemoryType.Device, false);
CudaMemory biasMem = gpu.allocate(bias.length() * precision.size, MemoryType.Device, true).write(precision, bias.getData());
int[] biasDim = bias.getDimensions();
CudaDevice.CudaTensorDescriptor biasDescriptor = gpu.newTensorDescriptor(precision,
1, biasDim[2], biasDim[1], biasDim[0],
biasDim[2] * biasDim[1] * biasDim[0], biasDim[1] * biasDim[0], biasDim[0], 1);
CudaMemory deltaTensorMemory = deltaTensor.getMemory(gpu);
gpu.cudnnConvolutionBackwardBias(precision.getPointer(1.0), deltaTensor.descriptor.getPtr(), deltaTensorMemory.getPtr(),
precision.getPointer(0.0), biasDescriptor.getPtr(), biasMem.getPtr());
assert CudaDevice.isThreadDeviceId(gpu.getDeviceId());
biasMem.dirty();
double[] biasV = new double[bias.length()];
biasMem.read(precision, biasV);
Stream.<ReferenceCounting>of(biasMem, deltaTensorMemory, deltaTensor, biasDescriptor).forEach(ReferenceCounting::freeRef);
return biasV;
}, delta);
buffer.get(ImgBandBiasLayer.this.getId(), bias).addInPlace(biasDelta).freeRef();
}
if (input.isAlive()) {
input.accumulate(buffer, delta);
} else {
delta.freeRef();
}
}) {
@Override
public final void accumulate(DeltaSet<UUID> buffer, TensorList delta) {
getAccumulator().accept(buffer, delta);
}
@Override
protected void _free() {
inputData.freeRef();
input.freeRef();
}
@Override
public boolean isAlive() {
for (@Nonnull final Result element : inObj)
if (element.isAlive()) {
return true;
}
return false;
}
};
}
@Nonnull
@Override
public JsonObject getJson(Map<CharSequence, byte[]> resources, DataSerializer dataSerializer) {
@Nonnull JsonObject json = super.getJsonStub();
json.addProperty("precision", precision.name());
json.add("bias", bias.toJson(resources, dataSerializer));
return json;
}
@Override
public Precision getPrecision() {
return precision;
}
@Nonnull
@Override
public ImgBandBiasLayer setPrecision(final Precision precision) {
this.precision = precision;
return this;
}
@Nonnull
@Override
public List<double[]> state() {
return Arrays.asList(bias.getData());
}
/**
* Add weights img band bias key.
*
* @param f the f
* @return the img band bias key
*/
@Nonnull
public ImgBandBiasLayer addWeights(@Nonnull final DoubleSupplier f) {
Util.add(f, getBias());
return this;
}
/**
* Add weights img band bias key.
*
* @param f the f
* @return the img band bias key
*/
@Nonnull
public ImgBandBiasLayer setWeights(@Nonnull final IntToDoubleFunction f) {
bias.setByCoord(c -> f.applyAsDouble(c.getIndex()));
return this;
}
/**
* Sets weights log.
*
* @param value the value
* @return the weights log
*/
@Nonnull
public ImgBandBiasLayer setWeightsLog(final double value) {
bias.setByCoord(c -> (FastRandom.INSTANCE.random() - 0.5) * Math.pow(10, value));
return this;
}
/**
* Sets and free.
*
* @param tensor the tensor
* @return the and free
*/
public ImgBandBiasLayer setAndFree(final Tensor tensor) {
set(tensor);
tensor.freeRef();
return this;
}
/**
* Set img band bias key.
*
* @param tensor the tensor
* @return the img band bias key
*/
public ImgBandBiasLayer set(final Tensor tensor) {
bias.set(tensor);
return this;
}
/**
* Get bias double [ ].
*
* @return the double [ ]
*/
public double[] getBias() {
return bias.getData();
}
/**
* Sets bias.
*
* @param bias the bias
* @return the bias
*/
public ImgBandBiasLayer setBias(Tensor bias) {
if (this.bias != null) {
this.bias.freeRef();
}
this.bias = bias;
this.bias.addRef();
return this;
}
@Override
protected void _free() {
if (this.bias != null) {
bias.freeRef();
bias = null;
}
super._free();
}
}
|
3e1f0db40e132d64125f3908a6f49fe2e87da9a5 | 9,538 | java | Java | openmeetings-web/src/main/java/org/apache/openmeetings/web/admin/labels/LangPanel.java | vovka3003/openmeetings | cf784135c861860a9dfa8da78525e5552ae23761 | [
"Apache-2.0"
] | 1 | 2019-12-26T09:01:24.000Z | 2019-12-26T09:01:24.000Z | openmeetings-web/src/main/java/org/apache/openmeetings/web/admin/labels/LangPanel.java | vovka3003/openmeetings | cf784135c861860a9dfa8da78525e5552ae23761 | [
"Apache-2.0"
] | null | null | null | openmeetings-web/src/main/java/org/apache/openmeetings/web/admin/labels/LangPanel.java | vovka3003/openmeetings | cf784135c861860a9dfa8da78525e5552ae23761 | [
"Apache-2.0"
] | null | null | null | 34.683636 | 109 | 0.74848 | 13,127 | /*
* 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.openmeetings.web.admin.labels;
import static java.time.Duration.ZERO;
import static org.apache.openmeetings.util.OpenmeetingsVariables.ATTR_CLASS;
import static org.apache.wicket.request.resource.ContentDisposition.ATTACHMENT;
import java.io.IOException;
import java.io.InputStream;
import java.util.AbstractMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.apache.openmeetings.db.dao.label.LabelDao;
import org.apache.openmeetings.db.entity.label.StringLabel;
import org.apache.openmeetings.web.admin.AdminBasePanel;
import org.apache.openmeetings.web.admin.SearchableDataView;
import org.apache.openmeetings.web.app.Application;
import org.apache.openmeetings.web.common.BasePanel;
import org.apache.openmeetings.web.common.ConfirmableAjaxBorder;
import org.apache.openmeetings.web.common.PagedEntityListPanel;
import org.apache.openmeetings.web.data.DataViewContainer;
import org.apache.openmeetings.web.data.OmOrderByBorder;
import org.apache.openmeetings.web.data.SearchableDataProvider;
import org.apache.openmeetings.web.util.upload.BootstrapFileUploadBehavior;
import org.apache.wicket.AttributeModifier;
import org.apache.wicket.ajax.AjaxEventBehavior;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.AjaxFormSubmitBehavior;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.core.request.handler.IPartialPageRequestHandler;
import org.apache.wicket.extensions.ajax.AjaxDownloadBehavior;
import org.apache.wicket.extensions.ajax.markup.html.form.upload.UploadProgressBar;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.upload.FileUpload;
import org.apache.wicket.markup.html.form.upload.FileUploadField;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.request.resource.ResourceStreamResource;
import org.apache.wicket.util.resource.AbstractResourceStream;
import org.apache.wicket.util.resource.IResourceStream;
import org.apache.wicket.util.resource.ResourceStreamNotFoundException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.googlecode.wicket.jquery.core.Options;
import com.googlecode.wicket.jquery.ui.form.button.AjaxButton;
import com.googlecode.wicket.kendo.ui.panel.KendoFeedbackPanel;
/**
* Language Editor, add/insert/update Label and add/delete language contains several Forms and one list
*
* @author solomax, swagner
*
*/
public class LangPanel extends AdminBasePanel {
private static final long serialVersionUID = 1L;
private static final Logger log = LoggerFactory.getLogger(LangPanel.class);
private final KendoFeedbackPanel feedback = new KendoFeedbackPanel("feedback", new Options("button", true));
private LangForm langForm;
private final FileUploadField fileUploadField = new FileUploadField("fileInput");
final WebMarkupContainer listContainer = new WebMarkupContainer("listContainer");
Map.Entry<Long, Locale> language;
public LangPanel(String id) {
super(id);
}
@Override
protected void onInitialize() {
// Create feedback panels
add(feedback.setOutputMarkupId(true));
language = new AbstractMap.SimpleEntry<>(1L, Locale.ENGLISH);
final LabelsForm form = new LabelsForm("form", this, new StringLabel(null, null));
form.setNewVisible(true);
add(form);
final SearchableDataView<StringLabel> dataView = new SearchableDataView<>(
"langList"
, new SearchableDataProvider<>(LabelDao.class) {
private static final long serialVersionUID = 1L;
@Override
public long size() {
return LabelDao.count(language.getValue(), search);
}
@Override
public Iterator<? extends StringLabel> iterator(long first, long count) {
return LabelDao.get(language.getValue(), search, first, count, getSort()).iterator();
}
}) {
private static final long serialVersionUID = 1L;
@Override
protected void populateItem(final Item<StringLabel> item) {
final StringLabel fv = item.getModelObject();
item.add(new Label("key"));
item.add(new Label("value"));
item.add(new AjaxEventBehavior(EVT_CLICK) {
private static final long serialVersionUID = 1L;
@Override
protected void onEvent(AjaxRequestTarget target) {
form.setModelObject(fv);
form.setNewVisible(false);
target.add(form, listContainer);
reinitJs(target);
}
});
item.add(AttributeModifier.append(ATTR_CLASS, getRowClass(fv.getId(), form.getModelObject().getId())));
}
};
add(listContainer.add(dataView).setOutputMarkupId(true));
PagedEntityListPanel navigator = new PagedEntityListPanel("navigator", dataView) {
private static final long serialVersionUID = 1L;
@Override
protected void onEvent(AjaxRequestTarget target) {
dataView.modelChanging();
target.add(listContainer);
}
};
DataViewContainer<StringLabel> container = new DataViewContainer<>(listContainer, dataView, navigator);
container
.addLink(new OmOrderByBorder<>("orderByName", "key", container))
.addLink(new OmOrderByBorder<>("orderByValue", "value", container));
add(container.getLinks());
add(navigator);
langForm = new LangForm("langForm", listContainer, this);
langForm.add(fileUploadField);
langForm.add(new UploadProgressBar("progress", langForm, fileUploadField));
fileUploadField.add(new AjaxFormSubmitBehavior(langForm, "change") {
private static final long serialVersionUID = 1L;
@Override
protected void onSubmit(AjaxRequestTarget target) {
FileUpload download = fileUploadField.getFileUpload();
try {
if (download == null || download.getInputStream() == null) {
feedback.error("File is empty");
return;
}
LabelDao.upload(language.getValue(), download.getInputStream());
} catch (Exception e) {
log.error("Exception on panel language editor import ", e);
feedback.error(e);
}
// repaint the feedback panel so that it is hidden
target.add(listContainer, feedback);
}
});
// Add a component to download a file without page refresh
final AjaxDownloadBehavior download = new AjaxDownloadBehavior(new ResourceStreamResource() {
private static final long serialVersionUID = 1L;
{
setContentDisposition(ATTACHMENT);
setCacheDuration(ZERO);
}
@Override
protected IResourceStream getResourceStream(Attributes attributes) {
final String name = LabelDao.getLabelFileName(language.getValue());
setFileName(name);
return new AbstractResourceStream() {
private static final long serialVersionUID = 1L;
private transient InputStream is;
@Override
public InputStream getInputStream() throws ResourceStreamNotFoundException {
try {
is = Application.class.getResourceAsStream(name);
return is;
} catch (Exception e) {
throw new ResourceStreamNotFoundException(e);
}
}
@Override
public void close() throws IOException {
if (is != null) {
is.close();
is = null;
}
}
};
}
});
langForm.add(download);
langForm.add(new AjaxButton("export"){
private static final long serialVersionUID = 1L;
@Override
protected void onSubmit(AjaxRequestTarget target) {
download.initiate(target);
// repaint the feedback panel so that it is hidden
target.add(feedback);
}
@Override
protected void onError(AjaxRequestTarget target) {
// repaint the feedback panel so errors are shown
target.add(feedback);
}
});
add(langForm);
final AddLanguageDialog addLang = new AddLanguageDialog("addLang", this);
add(addLang, new AjaxLink<Void>("addLangBtn") {
private static final long serialVersionUID = 1L;
@Override
public void onClick(AjaxRequestTarget target) {
addLang.open(target);
}
});
add(BootstrapFileUploadBehavior.INSTANCE);
add(new ConfirmableAjaxBorder("deleteLangBtn", getString("80"), getString("833")) {
private static final long serialVersionUID = 1L;
@Override
protected void onSubmit(AjaxRequestTarget target) {
LabelDao.delete(language.getValue());
List<Map.Entry<Long, Locale>> langs = LangForm.getLanguages();
language = langs.isEmpty() ? null : langs.get(0);
langForm.updateLanguages(target);
target.add(listContainer);
}
});
super.onInitialize();
}
@Override
public BasePanel onMenuPanelLoad(IPartialPageRequestHandler handler) {
reinitJs(handler);
return this;
}
static void reinitJs(IPartialPageRequestHandler handler) {
handler.appendJavaScript("langPanelInit()");
}
public LangForm getLangForm() {
return langForm;
}
}
|
3e1f0e3dcb485a58c2450aeea93e97ae13d163fd | 207 | java | Java | gaf-cloud/gaf-commons/gaf-common-auth/src/main/java/com/supermap/gaf/authority/constant/CommonConstant.java | zhurongcheng/GAF | 1dea35e126178927304355f03cee64fadf2f72c5 | [
"Apache-2.0"
] | 17 | 2021-04-26T01:07:34.000Z | 2022-03-31T08:21:26.000Z | gaf-cloud/gaf-commons/gaf-common-auth/src/main/java/com/supermap/gaf/authority/constant/CommonConstant.java | zhurongcheng/GAF | 1dea35e126178927304355f03cee64fadf2f72c5 | [
"Apache-2.0"
] | 7 | 2021-04-26T07:32:12.000Z | 2021-05-13T03:04:10.000Z | gaf-cloud/gaf-commons/gaf-common-auth/src/main/java/com/supermap/gaf/authority/constant/CommonConstant.java | zhurongcheng/GAF | 1dea35e126178927304355f03cee64fadf2f72c5 | [
"Apache-2.0"
] | 21 | 2021-01-05T05:42:49.000Z | 2021-08-06T08:53:32.000Z | 20.7 | 63 | 0.7343 | 13,128 | package com.supermap.gaf.authority.constant;
/**
* 权限的公用常量
*/
public class CommonConstant {
public static final int OFFSET_MAX_FOR_SQL_BETTER = 100000;
public static final String DESC = "DESC";
}
|
3e1f0e90eae6f9a5c4affed71f0ef5119712208f | 340 | java | Java | registration/src/main/java/com/example/registration/RegistrationApplication.java | 1993ALINE/Spring-Boot | fe0b995f113cb67a1bbdd650f48d13d0c2dae785 | [
"MIT"
] | null | null | null | registration/src/main/java/com/example/registration/RegistrationApplication.java | 1993ALINE/Spring-Boot | fe0b995f113cb67a1bbdd650f48d13d0c2dae785 | [
"MIT"
] | null | null | null | registration/src/main/java/com/example/registration/RegistrationApplication.java | 1993ALINE/Spring-Boot | fe0b995f113cb67a1bbdd650f48d13d0c2dae785 | [
"MIT"
] | null | null | null | 26.153846 | 68 | 0.802941 | 13,129 | package com.example.registration;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class RegistrationApplication {
public static void main(String[] args) {
SpringApplication.run(RegistrationApplication.class, args);
}
}
|
3e1f0f40ce601db6856b0d0c90bf099811ad439d | 1,191 | java | Java | samples/Java/apidemo/ContractLookupButton.java | yellow013/ib-gateway | f97998f8cbfe6ce4c56d58fd2756c018d3b277ba | [
"Apache-2.0"
] | 2 | 2021-05-31T15:58:39.000Z | 2021-07-19T00:49:51.000Z | samples/Java/apidemo/ContractLookupButton.java | yellow013/ib-gateway | f97998f8cbfe6ce4c56d58fd2756c018d3b277ba | [
"Apache-2.0"
] | 7 | 2021-03-10T10:08:30.000Z | 2022-03-02T07:38:13.000Z | samples/Java/apidemo/ContractLookupButton.java | yellow013/ib-gateway | f97998f8cbfe6ce4c56d58fd2756c018d3b277ba | [
"Apache-2.0"
] | 1 | 2021-08-05T00:00:03.000Z | 2021-08-05T00:00:03.000Z | 33.083333 | 106 | 0.776658 | 13,130 | /* Copyright (C) 2019 Interactive Brokers LLC. All rights reserved. This code is subject to the terms
* and conditions of the IB API Non-Commercial License or the IB API Commercial License, as applicable. */
package apidemo;
import java.awt.event.MouseEvent;
import com.ib.client.ContractLookuper;
import apidemo.util.HtmlButton;
public abstract class ContractLookupButton extends HtmlButton {
final ContractSearchDlg m_contractSearchdlg;
public ContractLookupButton(int conId, String exchange, ContractLookuper lookuper) {
super("");
m_contractSearchdlg = new ContractSearchDlg(conId, exchange, lookuper);
setText(m_contractSearchdlg.refContract() == null ? "search..." : m_contractSearchdlg.refContract());
}
@Override
protected void onClicked(MouseEvent e) {
m_contractSearchdlg.setLocationRelativeTo(this.getParent());
m_contractSearchdlg.setVisible(true);
setText(m_contractSearchdlg.refContract() == null ? "search..." : m_contractSearchdlg.refContract());
actionPerformed();
actionPerformed(m_contractSearchdlg.refConId(), m_contractSearchdlg.refExchId());
}
protected abstract void actionPerformed(int refConId, String refExchId);
}
|
3e1f118e8cdb61f6a22222bde2928dc51178040f | 366 | java | Java | mobile_app1/module953/src/main/java/module953packageJava0/Foo52.java | HiWong/android-build-eval | d909ab37bc8d5d3a188ba9c9f0855f846f6f3af6 | [
"Apache-2.0"
] | 70 | 2021-01-22T16:48:06.000Z | 2022-02-16T10:37:33.000Z | mobile_app1/module953/src/main/java/module953packageJava0/Foo52.java | HiWong/android-build-eval | d909ab37bc8d5d3a188ba9c9f0855f846f6f3af6 | [
"Apache-2.0"
] | 16 | 2021-01-22T20:52:52.000Z | 2021-08-09T17:51:24.000Z | mobile_app1/module953/src/main/java/module953packageJava0/Foo52.java | HiWong/android-build-eval | d909ab37bc8d5d3a188ba9c9f0855f846f6f3af6 | [
"Apache-2.0"
] | 5 | 2021-01-26T13:53:49.000Z | 2021-08-11T20:10:57.000Z | 11.4375 | 45 | 0.592896 | 13,131 | package module953packageJava0;
import java.lang.Integer;
public class Foo52 {
Integer int0;
Integer int1;
Integer int2;
public void foo0() {
new module953packageJava0.Foo51().foo4();
}
public void foo1() {
foo0();
}
public void foo2() {
foo1();
}
public void foo3() {
foo2();
}
public void foo4() {
foo3();
}
}
|
3e1f119ee095db4220621f554b0b3cb6b343b9fd | 589 | java | Java | service-api/product-service/src/main/java/com/gabriel/restaurant/product/ProductServiceApplication.java | rgabriel94/restaurant-api | ec9d3a52de53afa1ff0053483a828a5d8a14aa9f | [
"MIT"
] | null | null | null | service-api/product-service/src/main/java/com/gabriel/restaurant/product/ProductServiceApplication.java | rgabriel94/restaurant-api | ec9d3a52de53afa1ff0053483a828a5d8a14aa9f | [
"MIT"
] | null | null | null | service-api/product-service/src/main/java/com/gabriel/restaurant/product/ProductServiceApplication.java | rgabriel94/restaurant-api | ec9d3a52de53afa1ff0053483a828a5d8a14aa9f | [
"MIT"
] | null | null | null | 26.772727 | 68 | 0.828523 | 13,132 | package com.gabriel.restaurant.product;
import org.modelmapper.ModelMapper;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;
@EnableEurekaClient
@SpringBootApplication
public class ProductServiceApplication {
public static void main(String[] args) {
SpringApplication.run(ProductServiceApplication.class, args);
}
@Bean
public ModelMapper modelMapper() {
return new ModelMapper();
}
}
|
3e1f11da3492946e5707cd9ddc8848ea1de90a1b | 552 | java | Java | algoliasearch-core/src/main/java/com/algolia/search/models/settings/SetSettingsResponse.java | Coriell-Life-Sciences/algoliasearch-client-java-2 | f3420c6a809b40ea53a7eaa16a7c0a98913b4cd4 | [
"MIT"
] | 38 | 2016-07-05T11:46:17.000Z | 2022-03-15T12:24:55.000Z | algoliasearch-core/src/main/java/com/algolia/search/models/settings/SetSettingsResponse.java | Coriell-Life-Sciences/algoliasearch-client-java-2 | f3420c6a809b40ea53a7eaa16a7c0a98913b4cd4 | [
"MIT"
] | 624 | 2016-07-05T11:31:41.000Z | 2022-03-22T09:37:55.000Z | algoliasearch-core/src/main/java/com/algolia/search/models/settings/SetSettingsResponse.java | Coriell-Life-Sciences/algoliasearch-client-java-2 | f3420c6a809b40ea53a7eaa16a7c0a98913b4cd4 | [
"MIT"
] | 33 | 2016-07-05T11:37:49.000Z | 2022-03-12T18:25:04.000Z | 25.090909 | 68 | 0.798913 | 13,133 | package com.algolia.search.models.settings;
import com.algolia.search.models.WaitableResponse;
import com.algolia.search.models.indexing.IndexingResponse;
import java.io.Serializable;
import java.time.ZonedDateTime;
public class SetSettingsResponse extends IndexingResponse
implements Serializable, WaitableResponse {
public ZonedDateTime getUpdatedAt() {
return updatedAt;
}
public SetSettingsResponse setUpdatedAt(ZonedDateTime updatedAt) {
this.updatedAt = updatedAt;
return this;
}
private ZonedDateTime updatedAt;
}
|
3e1f12434dd6ec70e3333c43b3e8a12d256d43ac | 4,754 | java | Java | SimpleKML/src/com/ekito/simpleKML/model/NetworkLinkControl.java | polluxcy/SimpleKml | 1adb3788a61fedda8aa42ef975d56c9d44db7da8 | [
"Apache-2.0"
] | 8 | 2017-07-19T17:26:00.000Z | 2022-03-09T01:00:21.000Z | SimpleKML/src/com/ekito/simpleKML/model/NetworkLinkControl.java | polluxcy/SimpleKml | 1adb3788a61fedda8aa42ef975d56c9d44db7da8 | [
"Apache-2.0"
] | 3 | 2017-08-19T07:16:53.000Z | 2017-08-19T07:22:00.000Z | SimpleKML/src/com/ekito/simpleKML/model/NetworkLinkControl.java | polluxcy/SimpleKml | 1adb3788a61fedda8aa42ef975d56c9d44db7da8 | [
"Apache-2.0"
] | 7 | 2017-09-15T20:51:50.000Z | 2021-03-19T14:42:20.000Z | 19.092369 | 80 | 0.678586 | 13,134 | /**
* Copyright 2012 Ekito - http://www.ekito.fr/
*
* 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.ekito.simpleKML.model;
import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementUnion;
/**
* Controls the behavior of files fetched by a {@link NetworkLink}.
*/
public class NetworkLinkControl {
/** The min refresh period. */
@Element(required=false)
private Float minRefreshPeriod;
/** The max session length. */
@Element(required=false)
private Float maxSessionLength;
/** The cookie. */
@Element(required=false)
private String cookie;
/** The message. */
@Element(required=false)
private String message;
/** The link name. */
@Element(required=false)
private String linkName;
/** The link description. */
@Element(required=false)
private String linkDescription;
/** The link snippet. */
@Element(required=false)
private String linkSnippet;
/** The expires. */
@Element(required=false)
private String expires;
/** The update. */
@Element(name="Update", required=false)
private Update update;
/** The abstract view. */
@ElementUnion({
@Element(name="Camera", type=Camera.class, required=false),
@Element(name="LookAt", type=LookAt.class, required=false)
})
private AbstractView abstractView;
/**
* Gets the min refresh period.
*
* @return the min refresh period
*/
public Float getMinRefreshPeriod() {
return minRefreshPeriod;
}
/**
* Sets the min refresh period.
*
* @param minRefreshPeriod the new min refresh period
*/
public void setMinRefreshPeriod(Float minRefreshPeriod) {
this.minRefreshPeriod = minRefreshPeriod;
}
/**
* Gets the max session length.
*
* @return the max session length
*/
public Float getMaxSessionLength() {
return maxSessionLength;
}
/**
* Sets the max session length.
*
* @param maxSessionLength the new max session length
*/
public void setMaxSessionLength(Float maxSessionLength) {
this.maxSessionLength = maxSessionLength;
}
/**
* Gets the cookie.
*
* @return the cookie
*/
public String getCookie() {
return cookie;
}
/**
* Sets the cookie.
*
* @param cookie the new cookie
*/
public void setCookie(String cookie) {
this.cookie = cookie;
}
/**
* Gets the message.
*
* @return the message
*/
public String getMessage() {
return message;
}
/**
* Sets the message.
*
* @param message the new message
*/
public void setMessage(String message) {
this.message = message;
}
/**
* Gets the link name.
*
* @return the link name
*/
public String getLinkName() {
return linkName;
}
/**
* Sets the link name.
*
* @param linkName the new link name
*/
public void setLinkName(String linkName) {
this.linkName = linkName;
}
/**
* Gets the link description.
*
* @return the link description
*/
public String getLinkDescription() {
return linkDescription;
}
/**
* Sets the link description.
*
* @param linkDescription the new link description
*/
public void setLinkDescription(String linkDescription) {
this.linkDescription = linkDescription;
}
/**
* Gets the link snippet.
*
* @return the link snippet
*/
public String getLinkSnippet() {
return linkSnippet;
}
/**
* Sets the link snippet.
*
* @param linkSnippet the new link snippet
*/
public void setLinkSnippet(String linkSnippet) {
this.linkSnippet = linkSnippet;
}
/**
* Gets the expires.
*
* @return the expires
*/
public String getExpires() {
return expires;
}
/**
* Sets the expires.
*
* @param expires the new expires
*/
public void setExpires(String expires) {
this.expires = expires;
}
/**
* Gets the update.
*
* @return the update
*/
public Update getUpdate() {
return update;
}
/**
* Sets the update.
*
* @param update the new update
*/
public void setUpdate(Update update) {
this.update = update;
}
/**
* Gets the abstract view.
*
* @return the abstract view
*/
public AbstractView getAbstractView() {
return abstractView;
}
/**
* Sets the abstract view.
*
* @param abstractView the new abstract view
*/
public void setAbstractView(AbstractView abstractView) {
this.abstractView = abstractView;
}
}
|
3e1f12a65c0ea5330177b21f75f001075518783d | 2,501 | java | Java | src/com/zarkonnen/longan/nnidentifier/network/Network.java | umanda/Longan | e426c43001d298286dad1c1bf82297422c5e67d0 | [
"Apache-2.0"
] | null | null | null | src/com/zarkonnen/longan/nnidentifier/network/Network.java | umanda/Longan | e426c43001d298286dad1c1bf82297422c5e67d0 | [
"Apache-2.0"
] | null | null | null | src/com/zarkonnen/longan/nnidentifier/network/Network.java | umanda/Longan | e426c43001d298286dad1c1bf82297422c5e67d0 | [
"Apache-2.0"
] | null | null | null | 21.560345 | 73 | 0.60056 | 13,135 | package com.zarkonnen.longan.nnidentifier.network;
import java.util.ArrayList;
public class Network {
public final ArrayList<Layer> layers;
public Network(ArrayList<Layer> layers) {
this.layers = layers;
}
public double cutBelowThreshold(double t) {
int nCut = 0;
double nConns = 0;
for (Layer l : layers) {
nConns += l.weights.size();
for (Weight w : l.weights) {
if (Math.abs(w.value) < t) {
w.value = 0;
nCut++;
}
}
}
return nCut / nConns;
}
public void train(float[] input, float[] target, float[] n, float[] m) {
setInput(input);
update();
setTargets(target);
calculateDelta();
adjustWeights(n, m);
}
public void train(float[] input, float[] target, float n, float m) {
setInput(input);
update();
setTargets(target);
calculateDelta();
adjustWeights(n, m);
}
public float[] run(float[] input) {
setInput(input);
update();
float[] output = new float[layers.get(layers.size() - 1).nodes.size()];
for (int i = 0; i < output.length; i++) {
output[i] = layers.get(layers.size() - 1).nodes.get(i).activation;
}
return output;
}
public void setInput(float[] inputs) {
ArrayList<Node> iNodes = layers.get(0).nodes;
assert(inputs.length == iNodes.size());
for (int i = 0; i < inputs.length; i++) {
iNodes.get(i).activation = inputs[i];
}
}
public void setTargets(float[] targets) {
ArrayList<Node> outputs = layers.get(layers.size() - 1).nodes;
assert(targets.length == outputs.size());
for (int i = 0; i < targets.length; i++) {
outputs.get(i).delta = targets[i] - outputs.get(i).activation;
}
}
public void calculateDelta() {
// Don't calc delta for output layer.
for (int i = layers.size() - 2; i >= 0; i--) {
layers.get(i).calculateDelta();
}
}
public void adjustWeights(float n, float m) {
for (int i = layers.size() - 1; i >= 0; i--) {
layers.get(i).adjustWeights(n, m);
}
}
public void adjustWeights(float[] n, float[] m) {
for (int i = layers.size() - 1; i >= 0; i--) {
layers.get(i).adjustWeights(n[i], m[i]);
}
}
public void update() {
for (Layer l : layers) { l.update(); }
}
public String getDetails() {
String d = "";
for (Layer l : layers) {
d += l.getDetails() + "\n";
}
return d;
}
public int numWeights() {
int n = 0;
for (Layer l : layers) {
n += l.weights.size();
}
return n;
}
public int numNodes() {
int n = 0;
for (Layer l : layers) {
n += l.nodes.size();
}
return n;
}
}
|
3e1f13c945895407971642fb51f8012491595c2b | 6,747 | java | Java | src/main/java/it/fattureincloud/sdk/model/PaymentAccount.java | fattureincloud/fattureincloud-java-sdk | d02d29d5d88011e2171ae406aa9b98a71eec3ad2 | [
"MIT"
] | 3 | 2021-12-21T09:19:38.000Z | 2022-01-12T14:06:25.000Z | src/main/java/it/fattureincloud/sdk/model/PaymentAccount.java | fattureincloud/fattureincloud-java-sdk | d02d29d5d88011e2171ae406aa9b98a71eec3ad2 | [
"MIT"
] | null | null | null | src/main/java/it/fattureincloud/sdk/model/PaymentAccount.java | fattureincloud/fattureincloud-java-sdk | d02d29d5d88011e2171ae406aa9b98a71eec3ad2 | [
"MIT"
] | null | null | null | 24.200717 | 263 | 0.664248 | 13,136 | /*
* Fatture in Cloud API v2 - API Reference
* Connect your software with Fatture in Cloud, the invoicing platform chosen by more than 400.000 businesses in Italy. The Fatture in Cloud API is based on REST, and makes possible to interact with the user related data prior authorization via OAuth2 protocol.
*
* The version of the OpenAPI document: 2.0.16
* Contact: nnheo@example.com
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package it.fattureincloud.sdk.model;
import com.google.gson.annotations.SerializedName;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Objects;
import org.openapitools.jackson.nullable.JsonNullable;
/** */
@ApiModel(description = "")
@javax.annotation.Generated(
value = "org.openapitools.codegen.languages.JavaClientCodegen",
date = "2022-05-12T13:23:15.879179Z[Etc/UTC]")
public class PaymentAccount implements Serializable {
private static final long serialVersionUID = 1L;
public static final String SERIALIZED_NAME_ID = "id";
@SerializedName(SERIALIZED_NAME_ID)
private Integer id;
public static final String SERIALIZED_NAME_NAME = "name";
@SerializedName(SERIALIZED_NAME_NAME)
private String name;
public static final String SERIALIZED_NAME_TYPE = "type";
@SerializedName(SERIALIZED_NAME_TYPE)
private PaymentAccountType type = PaymentAccountType.STANDARD;
public static final String SERIALIZED_NAME_IBAN = "iban";
@SerializedName(SERIALIZED_NAME_IBAN)
private String iban;
public static final String SERIALIZED_NAME_SIA = "sia";
@SerializedName(SERIALIZED_NAME_SIA)
private String sia;
public static final String SERIALIZED_NAME_CUC = "cuc";
@SerializedName(SERIALIZED_NAME_CUC)
private String cuc;
public static final String SERIALIZED_NAME_VIRTUAL = "virtual";
@SerializedName(SERIALIZED_NAME_VIRTUAL)
private Boolean virtual;
public PaymentAccount() {}
public PaymentAccount id(Integer id) {
this.id = id;
return this;
}
/**
* Unique identifier
*
* @return id
*/
@javax.annotation.Nullable
@ApiModelProperty(value = "Unique identifier")
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public PaymentAccount name(String name) {
this.name = name;
return this;
}
/**
* Payment account name.
*
* @return name
*/
@javax.annotation.Nullable
@ApiModelProperty(example = "Conto Banca Intesa", value = "Payment account name.")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public PaymentAccount type(PaymentAccountType type) {
this.type = type;
return this;
}
/**
* Get type
*
* @return type
*/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
public PaymentAccountType getType() {
return type;
}
public void setType(PaymentAccountType type) {
this.type = type;
}
public PaymentAccount iban(String iban) {
this.iban = iban;
return this;
}
/**
* Payment account iban.
*
* @return iban
*/
@javax.annotation.Nullable
@ApiModelProperty(value = "Payment account iban.")
public String getIban() {
return iban;
}
public void setIban(String iban) {
this.iban = iban;
}
public PaymentAccount sia(String sia) {
this.sia = sia;
return this;
}
/**
* Payment account sia.
*
* @return sia
*/
@javax.annotation.Nullable
@ApiModelProperty(value = "Payment account sia.")
public String getSia() {
return sia;
}
public void setSia(String sia) {
this.sia = sia;
}
public PaymentAccount cuc(String cuc) {
this.cuc = cuc;
return this;
}
/**
* Payment account cuc.
*
* @return cuc
*/
@javax.annotation.Nullable
@ApiModelProperty(value = "Payment account cuc.")
public String getCuc() {
return cuc;
}
public void setCuc(String cuc) {
this.cuc = cuc;
}
public PaymentAccount virtual(Boolean virtual) {
this.virtual = virtual;
return this;
}
/**
* Determine if the payment method is virtual.
*
* @return virtual
*/
@javax.annotation.Nullable
@ApiModelProperty(value = "Determine if the payment method is virtual.")
public Boolean getVirtual() {
return virtual;
}
public void setVirtual(Boolean virtual) {
this.virtual = virtual;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PaymentAccount paymentAccount = (PaymentAccount) o;
return Objects.equals(this.id, paymentAccount.id)
&& Objects.equals(this.name, paymentAccount.name)
&& Objects.equals(this.type, paymentAccount.type)
&& Objects.equals(this.iban, paymentAccount.iban)
&& Objects.equals(this.sia, paymentAccount.sia)
&& Objects.equals(this.cuc, paymentAccount.cuc)
&& Objects.equals(this.virtual, paymentAccount.virtual);
}
private static <T> boolean equalsNullable(JsonNullable<T> a, JsonNullable<T> b) {
return a == b
|| (a != null
&& b != null
&& a.isPresent()
&& b.isPresent()
&& Objects.deepEquals(a.get(), b.get()));
}
@Override
public int hashCode() {
return Objects.hash(id, name, type, iban, sia, cuc, virtual);
}
private static <T> int hashCodeNullable(JsonNullable<T> a) {
if (a == null) {
return 1;
}
return a.isPresent() ? Arrays.deepHashCode(new Object[] {a.get()}) : 31;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class PaymentAccount {\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" name: ").append(toIndentedString(name)).append("\n");
sb.append(" type: ").append(toIndentedString(type)).append("\n");
sb.append(" iban: ").append(toIndentedString(iban)).append("\n");
sb.append(" sia: ").append(toIndentedString(sia)).append("\n");
sb.append(" cuc: ").append(toIndentedString(cuc)).append("\n");
sb.append(" virtual: ").append(toIndentedString(virtual)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
3e1f13d81747ca8cbe1542be39a2688848a38c0b | 857 | java | Java | app/src/main/java/android/coolweather/com/coolweather/db/County.java | zhy-run/coolweather | 68e0472da4beaa03186e68909f138a43b861504e | [
"Apache-2.0"
] | null | null | null | app/src/main/java/android/coolweather/com/coolweather/db/County.java | zhy-run/coolweather | 68e0472da4beaa03186e68909f138a43b861504e | [
"Apache-2.0"
] | null | null | null | app/src/main/java/android/coolweather/com/coolweather/db/County.java | zhy-run/coolweather | 68e0472da4beaa03186e68909f138a43b861504e | [
"Apache-2.0"
] | null | null | null | 18.234043 | 52 | 0.621937 | 13,137 | package android.coolweather.com.coolweather.db;
import org.litepal.crud.DataSupport;
/**
* Created by zhy on 2020/8/3.
*/
public class County extends DataSupport {
private int id;
private String countryName;
private String weatherId;
private int cityId;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
public String getWeatherId() {
return weatherId;
}
public void setWeatherId(String weatherId) {
this.weatherId = weatherId;
}
public int getCityId() {
return cityId;
}
public void setCityId(int cityId) {
this.cityId = cityId;
}
}
|
3e1f152b041e48ac549322430a7b8849e0661c7c | 7,828 | java | Java | engine/src/org/pentaho/di/trans/steps/excelinput/staxpoi/StaxPoiSheet.java | gretchiemoran/pentaho-kettle | b842c72b3746f3e7ca1648129411f73569a4089a | [
"Apache-2.0"
] | 1 | 2021-04-05T22:32:23.000Z | 2021-04-05T22:32:23.000Z | engine/src/org/pentaho/di/trans/steps/excelinput/staxpoi/StaxPoiSheet.java | gretchiemoran/pentaho-kettle | b842c72b3746f3e7ca1648129411f73569a4089a | [
"Apache-2.0"
] | null | null | null | engine/src/org/pentaho/di/trans/steps/excelinput/staxpoi/StaxPoiSheet.java | gretchiemoran/pentaho-kettle | b842c72b3746f3e7ca1648129411f73569a4089a | [
"Apache-2.0"
] | 1 | 2021-04-05T22:30:46.000Z | 2021-04-05T22:30:46.000Z | 38.372549 | 116 | 0.585973 | 13,138 | /*! ******************************************************************************
*
* Pentaho Data Integration
*
* Copyright (C) 2002-2015 by Pentaho : http://www.pentaho.com
*
*******************************************************************************
*
* 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.
*
******************************************************************************/
/**
* Author = Shailesh Ahuja
*/
package org.pentaho.di.trans.steps.excelinput.staxpoi;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import org.apache.poi.xssf.eventusermodel.XSSFReader;
import org.apache.poi.xssf.model.SharedStringsTable;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.pentaho.di.core.spreadsheet.KCell;
import org.pentaho.di.core.spreadsheet.KSheet;
public class StaxPoiSheet implements KSheet {
private String sheetName;
private InputStream sheetStream;
private XMLStreamReader sheetReader;
// hold the pointer to the current row so that access to the next row in the stream is quick and easy
private int currentRow;
private List<String> headerRow;
private int numRows;
private int numCols;
// variable to hold the shared strings table
private SharedStringsTable sst;
public StaxPoiSheet( XSSFReader reader, String sheetName, String sheetID ) {
this.sheetName = sheetName;
try {
sst = reader.getSharedStringsTable();
sheetStream = reader.getSheet( sheetID );
XMLInputFactory factory = XMLInputFactory.newInstance();
sheetReader = factory.createXMLStreamReader( sheetStream );
headerRow = new ArrayList<String>();
while ( sheetReader.hasNext() ) {
int event = sheetReader.next();
if ( event == XMLStreamConstants.START_ELEMENT && sheetReader.getLocalName().equals( "dimension" ) ) {
String dim = sheetReader.getAttributeValue( null, "ref" ).split( ":" )[1];
numRows = StaxUtil.extractRowNumber( dim );
numCols = StaxUtil.extractColumnNumber( dim );
}
if ( event == XMLStreamConstants.START_ELEMENT && sheetReader.getLocalName().equals( "row" ) ) {
currentRow = Integer.parseInt( sheetReader.getAttributeValue( null, "r" ) );
// calculate the number of columns in the header row
while ( sheetReader.hasNext() ) {
event = sheetReader.next();
if ( event == XMLStreamConstants.END_ELEMENT && sheetReader.getLocalName().equals( "row" ) ) {
// if the row has ended, break the inner while loop
break;
}
if ( event == XMLStreamConstants.START_ELEMENT && sheetReader.getLocalName().equals( "c" ) ) {
String attributeValue = sheetReader.getAttributeValue( null, "t" );
if ( attributeValue != null && attributeValue.equals( "s" ) ) {
// only if the type of the cell is string, we continue
while ( sheetReader.hasNext() ) {
event = sheetReader.next();
if ( event == XMLStreamConstants.START_ELEMENT && sheetReader.getLocalName().equals( "v" ) ) {
int idx = Integer.parseInt( sheetReader.getElementText() );
String content = new XSSFRichTextString( sst.getEntryAt( idx ) ).toString();
headerRow.add( content );
break;
}
}
} else {
break;
}
}
}
// we have parsed the header row
break;
}
}
// numCols = headerRow.size();
} catch ( Exception e ) {
e.printStackTrace();
throw new RuntimeException( e.getMessage() );
}
}
@Override
public KCell[] getRow( int rownr ) {
try {
while ( sheetReader.hasNext() ) {
int event = sheetReader.next();
if ( event == XMLStreamConstants.START_ELEMENT && sheetReader.getLocalName().equals( "row" ) ) {
String rowIndicator = sheetReader.getAttributeValue( null, "r" );
currentRow = Integer.parseInt( rowIndicator );
if ( currentRow < rownr ) {
continue;
}
KCell[] cells = new StaxPoiCell[numCols];
boolean richedRowEnd = false;
for ( int i = 0; i < numCols; i++ ) {
// go to the "c" <cell> tag
while ( sheetReader.hasNext() ) {
if ( event == XMLStreamConstants.START_ELEMENT && sheetReader.getLocalName().equals( "c" ) ) {
break;
}
//if we have empty cell than we could reach and of row before fill all cells, so break all cycle
if ( event == XMLStreamConstants.END_ELEMENT && sheetReader.getLocalName().equals( "row" ) ) {
richedRowEnd = true;
break;
}
event = sheetReader.next();
}
if ( richedRowEnd ) {
break;
}
String cellLocation = sheetReader.getAttributeValue( null, "r" );
int columnIndex = StaxUtil.extractColumnNumber( cellLocation ) - 1;
String cellType = sheetReader.getAttributeValue( null, "t" );
// go to the "v" <value> tag
while ( sheetReader.hasNext() ) {
event = sheetReader.next();
if ( event == XMLStreamConstants.START_ELEMENT && sheetReader.getLocalName().equals( "v" ) ) {
break;
}
if ( event == XMLStreamConstants.END_ELEMENT && sheetReader.getLocalName().equals( "c" ) ) {
// we have encountered an empty/incomplete row, so we set the max rows to current row number
// TODO: accept empty row is option is check and go till the end of the xml (need to detect the end)
numRows = currentRow;
return new KCell[] {};
}
}
String content = null;
if ( cellType != null && cellType.equals( "s" ) ) {
int idx = Integer.parseInt( sheetReader.getElementText() );
content = new XSSFRichTextString( sst.getEntryAt( idx ) ).toString();
} else {
content = sheetReader.getElementText();
}
cells[columnIndex] = new StaxPoiCell( content, currentRow );
}
return cells;
}
}
} catch ( Exception e ) {
throw new RuntimeException( e );
}
numRows = currentRow;
return new KCell[] {};
}
@Override
public String getName() {
return sheetName;
}
@Override
public int getRows() {
return numRows;
}
@Override
public KCell getCell( int colnr, int rownr ) {
if ( rownr == 0 && colnr < numCols ) {
// only possible to return header
return new StaxPoiCell( headerRow.get( colnr ), rownr );
}
return null;
// throw new RuntimeException("getCell(col, row) is not supported yet");
}
public void close() throws IOException, XMLStreamException {
sheetReader.close();
sheetStream.close();
}
}
|
3e1f15f1f9de787c8cf325d84fe3dd4912a7e581 | 19,133 | java | Java | src/main/java/com/laegler/gtfs/common/GtfsDataStructureUtil.java | thlaegler/gtfs-dataflow-pipelines | 4803f91cb9a846d5a69bfdf5e3ace91581dce507 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/laegler/gtfs/common/GtfsDataStructureUtil.java | thlaegler/gtfs-dataflow-pipelines | 4803f91cb9a846d5a69bfdf5e3ace91581dce507 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/laegler/gtfs/common/GtfsDataStructureUtil.java | thlaegler/gtfs-dataflow-pipelines | 4803f91cb9a846d5a69bfdf5e3ace91581dce507 | [
"Apache-2.0"
] | null | null | null | 47.952381 | 100 | 0.705326 | 13,139 | package com.laegler.gtfs.common;
import static java.util.Arrays.asList;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import org.apache.beam.sdk.schemas.Schema;
import org.apache.beam.sdk.schemas.Schema.FieldType;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.ImmutableList;
/**
* Because many GTFS Provider don't stick exactly to the GTFS Specification but rather use custom
* tables and column names we need to map the table and column names to proper GTFS standard.
*/
public class GtfsDataStructureUtil {
private static final Logger LOG = LoggerFactory.getLogger(GtfsDataStructureUtil.class);
// Table names
public static final String AGENCIES = "agency";
public static final String CALENDARS = "calendar";
public static final String CALENDAR_DATES = "calendar_dates";
public static final String FARE_ATTRIBUTES = "fare_attributes";
public static final String FARE_RULES = "fare_rules";
public static final String FEED_INFOS = "feed_info";
public static final String FREQUENCIES = "frequencies";
public static final String ROUTES = "routes";
public static final String SHAPES = "shapes";
public static final String STOP_TIMES = "stop_times";
public static final String STOPS = "stops";
public static final String TRANSFERS = "transfers";
public static final String TRIPS = "trips";
// Table names of Extensions or GTFS-Spec-Updates
public static final String TRANSLATIONS = "translations";
public static final String PATHWAYS = "pathways";
public static final String LEVELS = "levels";
public static final String CALENDAR_ATTRIBUTES = "calendar_attributes";
public static final String DIRECTIONS = "directions";
// this defines the order
public static final List<String> GTFS_TABLES = asList(AGENCIES, ROUTES, FARE_ATTRIBUTES,
FARE_RULES, STOPS, SHAPES, FEED_INFOS, CALENDARS, CALENDAR_DATES, TRIPS, FREQUENCIES,
STOP_TIMES, TRANSFERS, TRANSLATIONS, PATHWAYS, LEVELS, CALENDAR_ATTRIBUTES, DIRECTIONS);
public static final String AGENCY_ID = "agency_id";
public static final String SERVICE_ID = "service_id";
public static final String SECONDARY_SERVICE_ID = "secondary_service_id";
public static final String FARE_ID = "fare_id";
public static final String SECONDARY_FARE_ID = "secondary_fare_id";
public static final String ROUTE_ID = "route_id";
public static final String SECONDARY_ROUTE_ID = "secondary_route_id";
public static final String TRIP_ID = "trip_id";
public static final String SECONDARY_TRIP_ID = "secondary_trip_id";
public static final String STOP_ID = "stop_id";
public static final String SECONDARY_STOP_ID = "secondary_stop_id";
public static final String SHAPE_ID = "shape_id";
public static final String SECONDARY_SHAPE_ID = "secondary_shape_id";
public static final String FREQUENCY_ID = "frequency_id";
public static final String SECONDARY_FREQUENCY_ID = "secondary_frequency_id";
public static final String TRANSFER_ID = "transfer_id";
public static final String TRANS_ID = "trans_id";
public static final String PATHWAY_ID = "pathway_id";
public static final String LEVEL_ID = "level_id";
public static final String DIRECTION_ID = "direction_id";
public static final List<List<String>> TABLE_ALIASES = new LinkedList<>();
// The first column name is the GTFS default name, all following are aliases that are used by some
// providers.
public static final Map<String, List<List<String>>> COLUMN_ALIASES = new HashMap<>();
public static final Map<String, String> UNIQUE_CONSTRAINTS = new HashMap<>();
public static final Map<String, ImmutablePair<String, String>> SECONDARY_ID_COLUMNS =
new HashMap<>();
public static final Map<String, List<ImmutablePair<String, String>>> TIME_TRANSFORMATION =
new HashMap<>();
// Apache Beam specific
public static final Map<String, Schema> SCHEMAS = new HashMap<>();
public static final Map<String, String> UNIQUE_HEADER = new HashMap<>(); // to detect table name
// by header
public static final Map<String, List<String>> HEADERS = new HashMap<>();
// Static initialization
static {
TABLE_ALIASES.add(ImmutableList.of(AGENCIES, "agencies"));
TABLE_ALIASES.add(ImmutableList.of(CALENDARS, "calendars"));
TABLE_ALIASES.add(ImmutableList.of(CALENDAR_DATES));
TABLE_ALIASES.add(ImmutableList.of(FARE_ATTRIBUTES));
TABLE_ALIASES.add(ImmutableList.of(FARE_RULES));
TABLE_ALIASES.add(ImmutableList.of(FEED_INFOS));
TABLE_ALIASES.add(ImmutableList.of(FREQUENCIES));
TABLE_ALIASES.add(ImmutableList.of(ROUTES));
TABLE_ALIASES.add(ImmutableList.of(SHAPES));
TABLE_ALIASES.add(ImmutableList.of(STOP_TIMES));
TABLE_ALIASES.add(ImmutableList.of(STOPS));
TABLE_ALIASES.add(ImmutableList.of(TRANSFERS, "transfer"));
TABLE_ALIASES.add(ImmutableList.of(TRIPS));
TABLE_ALIASES.add(ImmutableList.of(TRANSLATIONS));
TABLE_ALIASES.add(ImmutableList.of(PATHWAYS));
TABLE_ALIASES.add(ImmutableList.of(LEVELS));
TABLE_ALIASES.add(ImmutableList.of(CALENDAR_ATTRIBUTES));
TABLE_ALIASES.add(ImmutableList.of(DIRECTIONS, "direction"));
UNIQUE_CONSTRAINTS.put(AGENCIES, "agency_pkey");
UNIQUE_CONSTRAINTS.put(CALENDARS, "calendar_pkey");
UNIQUE_CONSTRAINTS.put(CALENDAR_DATES, "calendar_dates_pkey");
UNIQUE_CONSTRAINTS.put(FARE_ATTRIBUTES, "fare_attributes_pkey");
UNIQUE_CONSTRAINTS.put(FARE_RULES, "fare_rules_pkey"); // idx_fare_rules_composite_unique
UNIQUE_CONSTRAINTS.put(FEED_INFOS, "feed_info_pkey");
UNIQUE_CONSTRAINTS.put(FREQUENCIES, "frequencies_pkey");
UNIQUE_CONSTRAINTS.put(ROUTES, "routes_pkey");
UNIQUE_CONSTRAINTS.put(SHAPES, "shapes_pkey"); // idx_shapes_shape_id_sequence_unique
UNIQUE_CONSTRAINTS.put(STOP_TIMES, "idx_stop_times_unique"); // idx_stop_times_unique
UNIQUE_CONSTRAINTS.put(STOPS, "stops_pkey");
UNIQUE_CONSTRAINTS.put(TRANSFERS, "transfers_pkey");
UNIQUE_CONSTRAINTS.put(TRIPS, "trips_pkey");
UNIQUE_CONSTRAINTS.put(TRANSLATIONS, "translations_pkey");
UNIQUE_CONSTRAINTS.put(PATHWAYS, "pathways_pkey");
UNIQUE_CONSTRAINTS.put(LEVELS, "levels_pkey");
UNIQUE_CONSTRAINTS.put(CALENDAR_ATTRIBUTES, "calendar_attributes_pkey");
UNIQUE_CONSTRAINTS.put(DIRECTIONS, "directions_pkey");
COLUMN_ALIASES.put(AGENCIES,
asList(asList(AGENCY_ID), asList("agency_lang"), asList("agency_name"),
asList("agency_phone"), asList("agency_timezone"), asList("agency_email"),
asList("agency_url"), asList("agency_fare_url")));
COLUMN_ALIASES.put(CALENDARS,
asList(asList(SERVICE_ID), asList(SECONDARY_SERVICE_ID), asList("service_name"),
asList("start_date"), asList("end_date"), asList("monday"), asList("tuesday"),
asList("wednesday"), asList("thursday"), asList("friday"), asList("saturday"),
asList("sunday")));
COLUMN_ALIASES.put(CALENDAR_DATES,
asList(asList("calendar_date_id"), asList(SERVICE_ID), asList(SECONDARY_SERVICE_ID),
asList("date", "calendar_date"), asList("exception_type"), asList("holiday_name")));
COLUMN_ALIASES.put(FARE_ATTRIBUTES,
asList(asList(FARE_ID), asList(SECONDARY_FARE_ID), asList("currency_type"),
asList("payment_method"), asList(AGENCY_ID), asList("price"),
asList("transfer_duration"), asList(TRANSFERS), asList("transfer_type"),
asList("extra_fare_info"), asList("value_options"), asList("transfers")));
COLUMN_ALIASES.put(FARE_RULES, asList(asList(FARE_ID), asList(SECONDARY_FARE_ID),
asList(ROUTE_ID), asList("origin_id"), asList("destination_id"), asList("contains_id")));
COLUMN_ALIASES.put(FEED_INFOS,
asList(asList("feed_id"), asList("feed_publisher_name"), asList("feed_start_date"),
asList("feed_end_date"), asList("feed_lang"), asList("feed_version"),
asList("feed_publisher_url")));
COLUMN_ALIASES.put(FREQUENCIES,
asList(asList(FREQUENCY_ID), asList(SECONDARY_FREQUENCY_ID), asList(TRIP_ID),
asList("start_time"), asList("end_time"), asList("exact_times", "exact_time"),
asList("headway_secs", "headway_sec")));
COLUMN_ALIASES.put(ROUTES,
asList(asList(ROUTE_ID), asList(SECONDARY_ROUTE_ID), asList(AGENCY_ID),
asList("route_short_name"), asList("route_long_name"), asList("route_desc"),
asList("route_type"), asList("route_url"), asList("route_color"),
asList("route_text_color"), asList("route_sort_order", "sort_order"),
asList("min_headway_minutes"), asList("eligibility_restricted")));
COLUMN_ALIASES.put(SHAPES,
asList(asList(SHAPE_ID), asList(SECONDARY_SHAPE_ID), asList("shape_pt_sequence"),
asList("shape_pt_lat"), asList("shape_pt_lon"), asList("shape_dist_traveled")));
COLUMN_ALIASES.put(STOP_TIMES,
asList(asList("stop_time_id"), asList(STOP_ID), asList(TRIP_ID), asList("stop_sequence"),
asList("arrival_time"), asList("departure_time"), asList("stop_headsign"),
asList("pickup_type"), asList("drop_off_type"), asList("shape_dist_traveled"),
asList("timepoint"), asList("start_service_area_id"), asList("end_service_area_id"),
asList("start_service_area_radius"), asList("end_service_area_radius"),
asList("continuous_pickup"), asList("continuous_drop_off"), asList("pickup_area_id"),
asList("drop_off_area_id"), asList("pickup_service_area_radius"),
asList("drop_off_service_area_radius"), asList("major_stop")));
COLUMN_ALIASES.put(STOPS,
asList(asList(STOP_ID), asList(SECONDARY_STOP_ID), asList("stop_code"), asList("stop_name"),
asList("stop_desc"), asList("stop_lat"), asList("stop_lon"), asList("zone_id"),
asList("stop_url"), asList("location_type"), asList("parent_station"),
asList("stop_timezone"), asList("wheelchair_boarding", "wheelchair_type"),
asList("platform_code"), asList("vehicle_type")));
COLUMN_ALIASES.put(TRANSFERS,
asList(asList(TRANSFER_ID), asList("from_stop_id"), asList("to_stop_id"),
asList("transfer_type"), asList("min_transfer_time", "min_transfer"),
asList("from_trip_id"), asList("to_trip_id")));
COLUMN_ALIASES.put(TRIPS,
asList(asList(TRIP_ID), asList(SECONDARY_TRIP_ID), asList(ROUTE_ID), asList(SHAPE_ID),
asList(SERVICE_ID), asList("direction_id"), asList("block_id"),
asList("wheelchair_accessible", "trip_type"), asList("bikes_allowed"),
asList("trip_short_name"), asList("trip_headsign"), asList("drt_max_travel_time"),
asList("drt_avg_travel_time"), asList("drt_advance_book_min"),
asList("drt_pickup_message"), asList("drt_drop_off_message"),
asList("continuous_pickup_message"), asList("continuous_drop_off_message")));
COLUMN_ALIASES.put(TRANSLATIONS,
asList(asList(TRANS_ID), asList("lang"), asList("translation")));
COLUMN_ALIASES.put(PATHWAYS,
asList(asList("pathway_id"), asList("from_stop_id"), asList("to_stop_id"),
asList("pathway_mode"), asList("is_bidirectional"), asList("length"),
asList("traversal_time"), asList("stair_count"), asList("max_slope"),
asList("min_width"), asList("signposted_as"), asList("reversed_signposted_as")));
COLUMN_ALIASES.put(LEVELS,
asList(asList("level_id"), asList("level_index"), asList("level_name")));
COLUMN_ALIASES.put(CALENDAR_ATTRIBUTES,
asList(asList(SERVICE_ID), asList(SECONDARY_SERVICE_ID), asList("service_description")));
COLUMN_ALIASES.put(DIRECTIONS,
asList(asList(ROUTE_ID), asList(DIRECTION_ID), asList("direction")));
SECONDARY_ID_COLUMNS.put(CALENDARS, ImmutablePair.of(SERVICE_ID, SECONDARY_SERVICE_ID));
SECONDARY_ID_COLUMNS.put(CALENDAR_DATES, ImmutablePair.of(SERVICE_ID, SECONDARY_SERVICE_ID));
SECONDARY_ID_COLUMNS.put(FARE_ATTRIBUTES, ImmutablePair.of(FARE_ID, SECONDARY_FARE_ID));
SECONDARY_ID_COLUMNS.put(FARE_RULES, ImmutablePair.of(FARE_ID, SECONDARY_FARE_ID));
SECONDARY_ID_COLUMNS.put(ROUTES, ImmutablePair.of(ROUTE_ID, SECONDARY_ROUTE_ID));
SECONDARY_ID_COLUMNS.put(SHAPES, ImmutablePair.of(SHAPE_ID, SECONDARY_SHAPE_ID));
SECONDARY_ID_COLUMNS.put(STOPS, ImmutablePair.of(STOP_ID, SECONDARY_STOP_ID));
SECONDARY_ID_COLUMNS.put(TRIPS, ImmutablePair.of(TRIP_ID, SECONDARY_TRIP_ID));
SECONDARY_ID_COLUMNS.put(STOP_TIMES, ImmutablePair.of(TRIP_ID, SECONDARY_TRIP_ID));
SECONDARY_ID_COLUMNS.put(FREQUENCIES, ImmutablePair.of(FREQUENCY_ID, SECONDARY_FREQUENCY_ID));
SECONDARY_ID_COLUMNS.put(CALENDAR_ATTRIBUTES,
ImmutablePair.of(SERVICE_ID, SECONDARY_SERVICE_ID));
TIME_TRANSFORMATION.put(STOP_TIMES,
asList(ImmutablePair.of("arrival_time", "arrival_time_time"),
ImmutablePair.of("departure_time", "departure_time_time")));
TIME_TRANSFORMATION.put(FREQUENCIES, asList(ImmutablePair.of("start_time", "start_time_time"),
ImmutablePair.of("end_time", "end_time_time")));
// Apache Beam specific
SCHEMAS.put(AGENCIES,
Schema.builder().addStringField("route_id").addStringField("agency_id").build());
final Schema.Builder schemaBuilder = Schema.builder();
// @formatter:off
COLUMN_ALIASES.entrySet().forEach(e ->
SCHEMAS.put(e.getKey(),
new Schema(
e.getValue().stream().map(col ->
Schema.Field.of(
col.get(0),
FieldType.STRING
)
).collect(toList())
)
)
);
// @formatter:on
SCHEMAS.put(CALENDARS,
Schema.builder().addStringField("route_id").addStringField("agency_id").build());
// HEADERS = ImmutableList.of(AGENCIES,
// Schema.builder().addStringField("route_id").addStringField("agency_id").build()));
// SCHEMAS.add(ImmutableList.of(CALENDARS, "calendars"));
// SCHEMAS.add(ImmutableList.of(CALENDAR_DATES));
// SCHEMAS.add(ImmutableList.of(FARE_ATTRIBUTES));
// SCHEMAS.add(ImmutableList.of(FARE_RULES));
// SCHEMAS.add(ImmutableList.of(FEED_INFOS));
// SCHEMAS.add(ImmutableList.of(FREQUENCIES));
// SCHEMAS.add(ImmutableList.of(ROUTES));
// SCHEMAS.add(ImmutableList.of(SHAPES));
// SCHEMAS.add(ImmutableList.of(STOP_TIMES));
// SCHEMAS.add(ImmutableList.of(STOPS));
// SCHEMAS.add(ImmutableList.of(TRANSFERS, "transfer"));
// SCHEMAS.add(ImmutableList.of(TRIPS));
// SCHEMAS.add(ImmutableList.of(TRANSLATIONS));
// SCHEMAS.add(ImmutableList.of(PATHWAYS));
// SCHEMAS.add(ImmutableList.of(LEVELS));
// SCHEMAS.add(ImmutableList.of(CALENDAR_ATTRIBUTES));
// SCHEMAS.add(ImmutableList.of(DIRECTIONS, "direction"));
// TABLE_ALIASES.forEach(t -> UNIQUE_HEADER.put(t.get(0), "");
}
private static final String SHOULDBENULL = "SHOULDBENULL";
private GtfsDataStructureUtil() {
throw new IllegalStateException("Cannot instantiate this static class");
}
public static String csvTableNameToDatabaseTableName(final String csvTable) {
List<String> col =
TABLE_ALIASES.stream().filter(a1 -> a1.stream().anyMatch(m -> m.equalsIgnoreCase(csvTable)))
.findFirst().orElse(null);
if (col != null && col.get(0) != null) {
return col.get(0);
}
return csvTable;
}
public static Optional<String> getTableNameFromHeader(String headerLine) {
return UNIQUE_HEADER.entrySet().stream().filter(e -> headerLine.contains(e.getValue()))
.map(e -> e.getKey()).findFirst();
}
public static List<String> csvColumnNamesToDatabaseColumnNames(String tableName,
List<String> csvColumns) {
final List<String> orderedColumns = new LinkedList<>();
List<List<String>> columnAliases = COLUMN_ALIASES.get(tableName);
if (columnAliases != null && !columnAliases.isEmpty()) {
csvColumns.stream().forEach(csv -> {
List<String> col =
columnAliases.stream().filter(a1 -> a1.stream().anyMatch(m -> m.equalsIgnoreCase(csv)))
.findFirst().orElse(null);
if (col != null && !col.isEmpty()) {
orderedColumns.add(col.get(0));
}
});
}
addCustomColumns(orderedColumns, tableName);
return orderedColumns;
}
/**
* GTFS allows times like 25:30:00 but Postgres data type 'time' does not allow such values
* (equals or greater 24). This method creates a valid date. The initially invalid time stays
* untouched in another column.
*
* @param potentiallyInvalidTime a potentially invalid time as String
* @return a valid time as String
*/
public static String getValidTime(String potentiallyInvalidTime) {
if (potentiallyInvalidTime != null) {
if (potentiallyInvalidTime.equalsIgnoreCase(SHOULDBENULL)) {
return null;
}
List<String> timeSegments = Arrays.asList(potentiallyInvalidTime.replace("'", "").split(":"));
if (timeSegments != null && !timeSegments.isEmpty()) {
try {
int gtfsHourOfDay = Integer.parseInt(timeSegments.get(0));
if (gtfsHourOfDay >= 24) {
timeSegments.set(0, String.valueOf(gtfsHourOfDay - 24));
return timeSegments.stream().collect(joining(":"));
}
} catch (NumberFormatException ex) {
LOG.warn("Cannot parse to Integer {} (hour of day)", timeSegments.get(0), ex);
}
}
}
return potentiallyInvalidTime;
}
public static List<String> getLineValues(String line) {
String newLine = line.replace("'", "''");
newLine = newLine.replace("\"", "'");
List<String> parts = asList(newLine.split(",(?=(?:[^']*'[^']*')*[^']*$)", -1));
return parts.stream().map(p -> (p == null || p.isEmpty()) ? SHOULDBENULL : p).collect(toList());
}
public static String csvLineToSqlLine(List<String> lineList) {
String line = lineList.stream().collect(joining("','", "('", "')"));
line = line.replace("(''", "('");
line = line.replace(",''", ",'");
line = line.replace("'')", "')");
line = line.replace("'',", "',");
line = line.replace("'" + SHOULDBENULL + "'", "null");
line = line.replace("'null'", "null");
return line;
}
private static void addCustomColumns(final List<String> defaultColumns, String tableName) {
ImmutablePair<String, String> secondaryId =
SECONDARY_ID_COLUMNS.entrySet().stream().filter(e -> e.getKey().equalsIgnoreCase(tableName))
.map(Entry::getValue).findFirst().orElse(null);
if (secondaryId != null) {
defaultColumns.add(secondaryId.getRight());
}
if (TIME_TRANSFORMATION.containsKey(tableName)) {
TIME_TRANSFORMATION.get(tableName).stream().forEach(t -> defaultColumns.add(t.getRight()));
}
}
}
|
3e1f166dfd651eec1928a895f01b4d2dcf3c0f03 | 1,664 | java | Java | app/src/main/java/com/example/myapplication200122/utils/TitleLayout.java | SmileAlfred/MyApplication200122 | afccc2c1a41647eed510be72b06b1c1cfd9e990e | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/myapplication200122/utils/TitleLayout.java | SmileAlfred/MyApplication200122 | afccc2c1a41647eed510be72b06b1c1cfd9e990e | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/example/myapplication200122/utils/TitleLayout.java | SmileAlfred/MyApplication200122 | afccc2c1a41647eed510be72b06b1c1cfd9e990e | [
"Apache-2.0"
] | null | null | null | 29.714286 | 98 | 0.684495 | 13,140 | package com.example.myapplication200122.utils;
import android.app.Activity;
import android.content.Context;
import android.icu.lang.UCharacter;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import com.example.myapplication200122.R;
/**
* @author LiuSaiSai
* @description:自定义控件 --> 标题栏;需要引用本自定义控件,就在 xml 文件中使用本类
* @date :2020/02/25 9:45
*/
public class TitleLayout extends LinearLayout implements View.OnClickListener {
private final Button backButton;
private final TextView titleText;
private final Button editButton;
public TitleLayout(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
LayoutInflater.from(context).inflate(R.layout.title, this);
backButton = findViewById(R.id.back_button);
titleText = findViewById(R.id.title_text);
editButton = findViewById(R.id.title_edit_button);
titleText.setText(context.getClass().getSimpleName());
backButton.setOnClickListener(this);
editButton.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.back_button:
((Activity) getContext()).finish();
break;
case R.id.title_edit_button:
Toast.makeText(getContext(), "You clicked EditButton", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
}
|
3e1f1708c267d420c04afcda41c00f905ddd39d0 | 4,701 | java | Java | shardingsphere-db-protocol/shardingsphere-db-protocol-mysql/src/main/java/org/apache/shardingsphere/db/protocol/mysql/codec/MySQLPacketCodecEngine.java | jiangtao69039/shardingsphere | 82ff0e3dba7ca8908d6076eb1544fa215c1bc4a1 | [
"Apache-2.0"
] | 2,179 | 2018-05-09T10:07:51.000Z | 2019-01-15T02:16:10.000Z | shardingsphere-db-protocol/shardingsphere-db-protocol-mysql/src/main/java/org/apache/shardingsphere/db/protocol/mysql/codec/MySQLPacketCodecEngine.java | jiangtao69039/shardingsphere | 82ff0e3dba7ca8908d6076eb1544fa215c1bc4a1 | [
"Apache-2.0"
] | 867 | 2018-05-09T14:46:18.000Z | 2019-01-15T03:48:04.000Z | shardingsphere-db-protocol/shardingsphere-db-protocol-mysql/src/main/java/org/apache/shardingsphere/db/protocol/mysql/codec/MySQLPacketCodecEngine.java | jiangtao69039/shardingsphere | 82ff0e3dba7ca8908d6076eb1544fa215c1bc4a1 | [
"Apache-2.0"
] | 617 | 2018-05-09T10:50:21.000Z | 2019-01-14T12:33:35.000Z | 41.236842 | 174 | 0.711763 | 13,141 | /*
* 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.shardingsphere.db.protocol.mysql.codec;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.CompositeByteBuf;
import io.netty.channel.ChannelHandlerContext;
import org.apache.shardingsphere.db.protocol.CommonConstants;
import org.apache.shardingsphere.db.protocol.codec.DatabasePacketCodecEngine;
import org.apache.shardingsphere.db.protocol.error.CommonErrorCode;
import org.apache.shardingsphere.db.protocol.mysql.packet.MySQLPacket;
import org.apache.shardingsphere.db.protocol.mysql.packet.generic.MySQLErrPacket;
import org.apache.shardingsphere.db.protocol.mysql.payload.MySQLPacketPayload;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
/**
* Database packet codec for MySQL.
*/
public final class MySQLPacketCodecEngine implements DatabasePacketCodecEngine<MySQLPacket> {
private static final int MAX_PACKET_LENGTH = 0xFFFFFF;
private static final int PAYLOAD_LENGTH = 3;
private static final int SEQUENCE_LENGTH = 1;
private final List<ByteBuf> pendingMessages = new LinkedList<>();
@Override
public boolean isValidHeader(final int readableBytes) {
return readableBytes >= PAYLOAD_LENGTH + SEQUENCE_LENGTH;
}
@Override
public void decode(final ChannelHandlerContext context, final ByteBuf in, final List<Object> out) {
int payloadLength = in.markReaderIndex().readUnsignedMediumLE();
int remainPayloadLength = SEQUENCE_LENGTH + payloadLength;
if (in.readableBytes() < remainPayloadLength) {
in.resetReaderIndex();
return;
}
ByteBuf message = in.readRetainedSlice(SEQUENCE_LENGTH + payloadLength);
if (MAX_PACKET_LENGTH == payloadLength) {
pendingMessages.add(message);
} else if (pendingMessages.isEmpty()) {
out.add(message);
} else {
aggregateMessages(context, message, out);
}
}
private void aggregateMessages(final ChannelHandlerContext context, final ByteBuf lastMessage, final List<Object> out) {
CompositeByteBuf result = context.alloc().compositeBuffer(pendingMessages.size() + 1);
Iterator<ByteBuf> pendingMessagesIterator = pendingMessages.iterator();
result.addComponent(true, pendingMessagesIterator.next());
while (pendingMessagesIterator.hasNext()) {
result.addComponent(true, pendingMessagesIterator.next().skipBytes(1));
}
if (lastMessage.readableBytes() > 1) {
result.addComponent(true, lastMessage.skipBytes(1));
}
out.add(result);
pendingMessages.clear();
}
@Override
public void encode(final ChannelHandlerContext context, final MySQLPacket message, final ByteBuf out) {
MySQLPacketPayload payload = new MySQLPacketPayload(prepareMessageHeader(out).markWriterIndex(), context.channel().attr(CommonConstants.CHARSET_ATTRIBUTE_KEY).get());
try {
message.write(payload);
// CHECKSTYLE:OFF
} catch (final Exception ex) {
// CHECKSTYLE:ON
out.resetWriterIndex();
new MySQLErrPacket(1, CommonErrorCode.UNKNOWN_EXCEPTION, ex.getMessage()).write(payload);
} finally {
updateMessageHeader(out, message.getSequenceId());
}
}
private ByteBuf prepareMessageHeader(final ByteBuf out) {
return out.writeInt(0);
}
private void updateMessageHeader(final ByteBuf byteBuf, final int sequenceId) {
byteBuf.setMediumLE(0, byteBuf.readableBytes() - PAYLOAD_LENGTH - SEQUENCE_LENGTH);
byteBuf.setByte(3, sequenceId);
}
@Override
public MySQLPacketPayload createPacketPayload(final ByteBuf message, final Charset charset) {
return new MySQLPacketPayload(message, charset);
}
}
|
3e1f1733a261ab06af60a45777789accf60cc7e7 | 230 | java | Java | src/main/java/de/quaddy_services/proxy/events/PortStatusListener.java | c-a-services/escape-from-intranet | 2ef0f234331a71f581445cc296b588ae13d69130 | [
"Apache-2.0"
] | 3 | 2017-01-24T23:18:46.000Z | 2021-05-14T13:51:22.000Z | src/main/java/de/quaddy_services/proxy/events/PortStatusListener.java | c-a-services/escape-from-intranet | 2ef0f234331a71f581445cc296b588ae13d69130 | [
"Apache-2.0"
] | 12 | 2017-01-26T11:57:01.000Z | 2019-07-03T07:42:53.000Z | src/main/java/de/quaddy_services/proxy/events/PortStatusListener.java | c-a-services/escape-from-intranet | 2ef0f234331a71f581445cc296b588ae13d69130 | [
"Apache-2.0"
] | 2 | 2018-05-09T13:14:12.000Z | 2019-05-20T10:15:56.000Z | 14.375 | 59 | 0.682609 | 13,142 | package de.quaddy_services.proxy.events;
import java.util.EventListener;
/**
*
*/
public interface PortStatusListener extends EventListener{
/**
*
*/
void statusChanged(boolean aOkFlag, String aText);
}
|
3e1f17d073db0b11425c79a7c5b1fff5db859405 | 774 | java | Java | src/main/java/kerio/connect/admin/common/SubCondition.java | pascalrobert/kerio-admin | 6e83e7c6e4740d9bdea755d09c7e3736d585b950 | [
"Apache-2.0"
] | 1 | 2016-07-18T02:15:38.000Z | 2016-07-18T02:15:38.000Z | src/main/java/kerio/connect/admin/common/SubCondition.java | pascalrobert/kerio-admin | 6e83e7c6e4740d9bdea755d09c7e3736d585b950 | [
"Apache-2.0"
] | null | null | null | src/main/java/kerio/connect/admin/common/SubCondition.java | pascalrobert/kerio-admin | 6e83e7c6e4740d9bdea755d09c7e3736d585b950 | [
"Apache-2.0"
] | 1 | 2021-03-26T09:46:07.000Z | 2021-03-26T09:46:07.000Z | 19.35 | 74 | 0.647287 | 13,143 | package kerio.connect.admin.common;
import kerio.connect.admin.common.enums.CompareOperator;
public class SubCondition {
String fieldName; ///< left side of condition
CompareOperator comparator; ///< middle of condition
String value;
public SubCondition() {
}
public String getFieldName() {
return fieldName;
}
public void setFieldName(String fieldName) {
this.fieldName = fieldName;
}
public CompareOperator getComparator() {
return comparator;
}
public void setComparator(CompareOperator comparator) {
this.comparator = comparator;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
|
3e1f185553996b3c7ee655fc0af887eaf736f615 | 2,453 | java | Java | org.onexus.website.widget/src/main/java/org/onexus/website/widget/tableviewer/decorators/scale/CategoricalDecoratorCreator.java | onexus/onexus | 2a96e787195e7133a5e0558924598c7816eab782 | [
"Apache-2.0"
] | 2 | 2015-10-09T13:14:20.000Z | 2016-05-05T01:38:29.000Z | org.onexus.website.widget/src/main/java/org/onexus/website/widget/tableviewer/decorators/scale/CategoricalDecoratorCreator.java | onexus/onexus | 2a96e787195e7133a5e0558924598c7816eab782 | [
"Apache-2.0"
] | 9 | 2020-06-30T22:53:38.000Z | 2022-01-21T23:10:11.000Z | org.onexus.website.widget/src/main/java/org/onexus/website/widget/tableviewer/decorators/scale/CategoricalDecoratorCreator.java | onexus/onexus | 2a96e787195e7133a5e0558924598c7816eab782 | [
"Apache-2.0"
] | 1 | 2016-02-24T12:11:20.000Z | 2016-02-24T12:11:20.000Z | 35.042857 | 111 | 0.714227 | 13,144 | /**
* Copyright 2012 Universitat Pompeu Fabra.
*
* 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.onexus.website.widget.tableviewer.decorators.scale;
import org.onexus.collection.api.Collection;
import org.onexus.collection.api.Field;
import org.onexus.resource.api.ParameterKey;
import org.onexus.resource.api.Parameters;
import org.onexus.website.widget.tableviewer.decorators.IDecorator;
import org.onexus.website.widget.tableviewer.decorators.IDecoratorCreator;
import org.onexus.website.widget.tableviewer.decorators.scale.scales.CategoricalColorScale;
import org.onexus.website.widget.tableviewer.decorators.scale.scales.ColorUtils;
import java.awt.*;
import java.util.HashMap;
import java.util.Map;
public class CategoricalDecoratorCreator implements IDecoratorCreator {
@Override
public String getDecoratorId() {
return "CATEGORICAL";
}
@Override
public ParameterKey[] getParameterKeys() {
return CategoricalDecoratorParameters.values();
}
@Override
public IDecorator createDecorator(Collection collection, Field columnField, Parameters parameters) {
Color defaultColor = ColorUtils.stringToColor(parameters.get(CategoricalDecoratorParameters.DEFAULT));
if (defaultColor == null) {
defaultColor = new Color(255, 255, 255);
}
Map<String, Color> colorsMap = new HashMap<String, Color>();
String mapValue = parameters.get(CategoricalDecoratorParameters.MAP);
String items[] = mapValue.split("\\|");
for (String item : items) {
String pair[] = item.split("=");
String key = pair[0].replace('[', ' ').replace(']', ' ').trim();
Color color = ColorUtils.stringToColor(pair[1]);
colorsMap.put(key, color);
}
return new ColorDecorator(columnField, new CategoricalColorScale(defaultColor, colorsMap), null, true);
}
}
|
3e1f1a1afb5e722ce8f6b4328f08c5d022ff79d0 | 1,037 | java | Java | src/main/java/com/sphenon/basics/data/DataSink_WithTypeInfo.java | 616c/java-com.sphenon.components.basics.data | 76dca9b84bcd16df209d621f8c2101db0ab89dea | [
"Apache-2.0"
] | null | null | null | src/main/java/com/sphenon/basics/data/DataSink_WithTypeInfo.java | 616c/java-com.sphenon.components.basics.data | 76dca9b84bcd16df209d621f8c2101db0ab89dea | [
"Apache-2.0"
] | null | null | null | src/main/java/com/sphenon/basics/data/DataSink_WithTypeInfo.java | 616c/java-com.sphenon.components.basics.data | 76dca9b84bcd16df209d621f8c2101db0ab89dea | [
"Apache-2.0"
] | null | null | null | 41.48 | 78 | 0.663452 | 13,145 | package com.sphenon.basics.data;
/****************************************************************************
Copyright 2001-2018 Sphenon GmbH
Licensed under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
License for the specific language governing permissions and limitations
under the License.
*****************************************************************************/
import com.sphenon.basics.context.*;
import com.sphenon.basics.metadata.*;
public interface DataSink_WithTypeInfo {
public Type getContainerType(CallContext context);
public Type getItemType(CallContext context);
public String getSlotId(CallContext context);
}
|
3e1f1aeaf65a3506061995ca55e65d0c3212b3e7 | 1,422 | java | Java | src/main/java/org/projog/core/function/classify/IsInteger.java | ainouche/projog | 5bb82bd64ed9729aa24726a10be3d4e71b55ac49 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/projog/core/function/classify/IsInteger.java | ainouche/projog | 5bb82bd64ed9729aa24726a10be3d4e71b55ac49 | [
"Apache-2.0"
] | null | null | null | src/main/java/org/projog/core/function/classify/IsInteger.java | ainouche/projog | 5bb82bd64ed9729aa24726a10be3d4e71b55ac49 | [
"Apache-2.0"
] | null | null | null | 28.44 | 86 | 0.708861 | 13,146 | /*
* Copyright 2013-2014 S. Webber
*
* 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.projog.core.function.classify;
import org.projog.core.function.AbstractSingletonPredicate;
import org.projog.core.term.Term;
import org.projog.core.term.TermType;
/* TEST
%TRUE integer(1)
%TRUE integer(-1)
%TRUE integer(0)
%FALSE integer(1.0)
%FALSE integer(-1.0)
%FALSE integer(0.0)
%FALSE float('1')
%FALSE float('1.0')
%FALSE integer(a)
%FALSE integer(p(1,2,3))
%FALSE integer([1,2,3])
%FALSE integer([])
%FALSE integer(X)
%FALSE integer(_)
*/
/**
* <code>integer(X)</code> - checks that a term is an integer.
* <p>
* <code>integer(X)</code> succeeds if <code>X</code> currently stands for an integer.
* </p>
*/
public final class IsInteger extends AbstractSingletonPredicate {
@Override
protected boolean evaluate(Term arg) {
return arg.getType() == TermType.INTEGER;
}
}
|
3e1f1b9d6dccc127178570eeaf54c35c8461a606 | 297 | java | Java | src/main/java/com/marke/marketmaker/service/TradeService.java | fuhuahua/marke | c02301a1a6b992bc0e349885276fe56f9830aefa | [
"MIT"
] | null | null | null | src/main/java/com/marke/marketmaker/service/TradeService.java | fuhuahua/marke | c02301a1a6b992bc0e349885276fe56f9830aefa | [
"MIT"
] | null | null | null | src/main/java/com/marke/marketmaker/service/TradeService.java | fuhuahua/marke | c02301a1a6b992bc0e349885276fe56f9830aefa | [
"MIT"
] | null | null | null | 15.631579 | 53 | 0.616162 | 13,147 | package com.marke.marketmaker.service;
import com.marke.marketmaker.domain.Trade;
public interface TradeService {
/**
* 新增交易数据
* @param trade
*/
void save(Trade trade);
/**
* 获取交易数据
* @return
*/
Trade getTradeData(String coin, String coinPair);
}
|
3e1f1bf360ea59782799539b1da079382ec1ecef | 381 | java | Java | design-pattern-java/src/main/java/com/corp/myxof/dp/visitor/ConcreteVisitorB.java | MyXOF/DesignPattern | 98a6d22ab9f41258aa1d2f3073ba1fce32be701b | [
"MIT"
] | null | null | null | design-pattern-java/src/main/java/com/corp/myxof/dp/visitor/ConcreteVisitorB.java | MyXOF/DesignPattern | 98a6d22ab9f41258aa1d2f3073ba1fce32be701b | [
"MIT"
] | null | null | null | design-pattern-java/src/main/java/com/corp/myxof/dp/visitor/ConcreteVisitorB.java | MyXOF/DesignPattern | 98a6d22ab9f41258aa1d2f3073ba1fce32be701b | [
"MIT"
] | null | null | null | 25.4 | 71 | 0.795276 | 13,148 | package com.corp.myxof.dp.visitor;
public class ConcreteVisitorB extends Visitor{
@Override
public void visitConcreteElementA(ConcreteElementA concreteElementA) {
System.out.println("visitB "+concreteElementA.toString());
}
@Override
public void visitConcreteElementB(ConcreteElementB concreteElementB) {
System.out.println("visitB "+concreteElementB.toString());
}
}
|
3e1f1c029a521c908621bcd054052c1099e50506 | 2,063 | java | Java | src/main/java/com/cloudmersive/client/model/AddressVerifySyntaxOnlyResponse.java | Cloudmersive/Cloudmersive.APIClient.Java.Android | 5d90113399e4e47bc5e68cfd70f0152641c86a09 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/cloudmersive/client/model/AddressVerifySyntaxOnlyResponse.java | Cloudmersive/Cloudmersive.APIClient.Java.Android | 5d90113399e4e47bc5e68cfd70f0152641c86a09 | [
"Apache-2.0"
] | null | null | null | src/main/java/com/cloudmersive/client/model/AddressVerifySyntaxOnlyResponse.java | Cloudmersive/Cloudmersive.APIClient.Java.Android | 5d90113399e4e47bc5e68cfd70f0152641c86a09 | [
"Apache-2.0"
] | null | null | null | 30.338235 | 225 | 0.707707 | 13,149 | /**
* validateapi
* The validation APIs help you validate data. Check if an E-mail address is real. Check if a domain is real. Check up on an IP address, and even where it is located. All this and much more is available in the validation API.
*
* OpenAPI spec version: v1
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package com.cloudmersive.client.model;
import io.swagger.annotations.*;
import com.google.gson.annotations.SerializedName;
/**
* Syntactic validity of email address
**/
@ApiModel(description = "Syntactic validity of email address")
public class AddressVerifySyntaxOnlyResponse {
@SerializedName("ValidAddress")
private Boolean validAddress = null;
/**
* True if the email address is syntactically valid, false if it is not
**/
@ApiModelProperty(value = "True if the email address is syntactically valid, false if it is not")
public Boolean getValidAddress() {
return validAddress;
}
public void setValidAddress(Boolean validAddress) {
this.validAddress = validAddress;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AddressVerifySyntaxOnlyResponse addressVerifySyntaxOnlyResponse = (AddressVerifySyntaxOnlyResponse) o;
return (this.validAddress == null ? addressVerifySyntaxOnlyResponse.validAddress == null : this.validAddress.equals(addressVerifySyntaxOnlyResponse.validAddress));
}
@Override
public int hashCode() {
int result = 17;
result = 31 * result + (this.validAddress == null ? 0: this.validAddress.hashCode());
return result;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class AddressVerifySyntaxOnlyResponse {\n");
sb.append(" validAddress: ").append(validAddress).append("\n");
sb.append("}\n");
return sb.toString();
}
}
|
3e1f1c4aaaa6aca21f71f8e0d45aeb66e97f83da | 411 | java | Java | webtack/jsinterop-generator/src/test/fixtures/no_inline_constants/output/gwt/test/java/com/example/JsMathTestCompile.java | akasha/akasha | 59703c113ece4ef6d4e566c55079c85cfd496a7d | [
"Apache-2.0"
] | 16 | 2021-03-28T11:44:44.000Z | 2022-01-11T09:15:24.000Z | webtack/jsinterop-generator/src/test/fixtures/no_inline_constants/output/j2cl/test/java/com/example/JsMathTestCompile.java | akasha/akasha | 59703c113ece4ef6d4e566c55079c85cfd496a7d | [
"Apache-2.0"
] | 35 | 2021-04-26T02:40:19.000Z | 2022-02-28T10:52:33.000Z | webtack/jsinterop-generator/src/test/fixtures/no_inline_constants/output/j2cl/test/java/com/example/JsMathTestCompile.java | realityforge/webtack | 56a2b5de420982d8d8524c6f0bbe1e6324ebe570 | [
"Apache-2.0"
] | 2 | 2021-07-28T02:36:05.000Z | 2021-07-31T06:44:56.000Z | 17.869565 | 44 | 0.698297 | 13,150 | package com.example;
import javax.annotation.Generated;
@Generated("org.realityforge.webtack")
public final class JsMathTestCompile {
public static double getPI() {
return JsMath.PI;
}
public static double getSQRT1_2() {
return JsMath.SQRT1_2;
}
public static double getSQRT2() {
return JsMath.SQRT2;
}
public static double abs(final double x) {
return JsMath.abs( x );
}
}
|
3e1f1c7f178ca529d368c2eb96c320e90ef28159 | 2,364 | java | Java | src/frogmodaiGame/systems/ItemRenderingSystem.java | ZenX2/frogmodaiGame | ca54d479cae8dbc9dfc94348939a0d9da3e491c7 | [
"MIT"
] | 1 | 2018-10-30T04:48:24.000Z | 2018-10-30T04:48:24.000Z | src/frogmodaiGame/systems/ItemRenderingSystem.java | ZenX2/frogmodaiGame | ca54d479cae8dbc9dfc94348939a0d9da3e491c7 | [
"MIT"
] | null | null | null | src/frogmodaiGame/systems/ItemRenderingSystem.java | ZenX2/frogmodaiGame | ca54d479cae8dbc9dfc94348939a0d9da3e491c7 | [
"MIT"
] | null | null | null | 35.818182 | 118 | 0.718697 | 13,151 | package frogmodaiGame.systems;
import com.artemis.Aspect;
import com.artemis.Aspect.Builder;
import com.artemis.BaseSystem;
import com.artemis.ComponentMapper;
import com.artemis.systems.IteratingSystem;
import com.googlecode.lanterna.TextCharacter;
import com.googlecode.lanterna.TextColor;
import com.googlecode.lanterna.screen.Screen;
import frogmodaiGame.*;
import frogmodaiGame.components.*;
public class ItemRenderingSystem extends IteratingSystem {
ComponentMapper<Position> mPosition;
ComponentMapper<Char> mChar;
ComponentMapper<ChunkAddress> mChunkAddress;
ComponentMapper<CameraWindow> mCameraWindow;
ComponentMapper<Sight> mSight;
Screen screen;
public int perspective = -1;
public ItemRenderingSystem(Screen _screen) {
super(Aspect.all(Position.class, Char.class, ChunkAddress.class).exclude(Tile.class, TimedActor.class,
IsInContainer.class));
screen = _screen;
}
@Override
protected void process(int e) {
// Position pos = mPosition.create(e);
// Char character = mChar.create(e);
// ChunkAddress chunkAddress = mChunkAddress.create(e);
// Chunk chunk = FFMain.worldManager.getChunk(chunkAddress.worldID);
//
// Position camPos = mPosition.create(FFMain.cameraID);
// CameraWindow camWindow = mCameraWindow.create(FFMain.cameraID);
//
// if (chunkAddress.worldID == FFMain.worldManager.activeChunk) {
// Position screenPos = new Position();
// screenPos.x = pos.x - camPos.x;
// screenPos.y = pos.y - camPos.y;
// if (screenPos.x >= 0 && screenPos.y >= 0 && screenPos.x < camWindow.width && screenPos.y < camWindow.height) {
// //if (FFMain.playerID == -1 || FFMain.playerID == e) {
// if (perspective == -1) {
// screen.setCharacter(screenPos.x, screenPos.y, character.getTextCharacter());
// } else {
// Position playerPos = mPosition.create(perspective);
// Sight sight = mSight.create(perspective);
// if (pos.withinDistance(playerPos, sight.distance)) {
// if (FFMain.worldManager.getActiveChunk().LOS(playerPos.x, playerPos.y, pos.x, pos.y)) {
// TextCharacter ct = character.getTextCharacter();
// int tile = chunk.getTile(playerPos.x, playerPos.y);
// Char tileChar = mChar.create(tile);
// screen.setCharacter(screenPos.x, screenPos.y, ct.withBackgroundColor(TextColor.ANSI.values()[tileChar.bgc]));
// }
// }
// }
// }
// }
}
}
|
3e1f1d305afd27eb8191a2722de54e5b0a75683c | 641 | java | Java | test/org/pipservices3/commons/data/MultiStringTest.java | pip-services-java/pip-services-commons-java | fbf836b137b2cd3cf2c352f5ccad28aac6ab9ec2 | [
"MIT"
] | null | null | null | test/org/pipservices3/commons/data/MultiStringTest.java | pip-services-java/pip-services-commons-java | fbf836b137b2cd3cf2c352f5ccad28aac6ab9ec2 | [
"MIT"
] | null | null | null | test/org/pipservices3/commons/data/MultiStringTest.java | pip-services-java/pip-services-commons-java | fbf836b137b2cd3cf2c352f5ccad28aac6ab9ec2 | [
"MIT"
] | null | null | null | 25.64 | 49 | 0.605304 | 13,152 | package org.pipservices3.commons.data;
import static org.junit.Assert.*;
import org.junit.Test;
public class MultiStringTest {
@Test
public void testGetAndSet() {
MultiString value = new MultiString();
assertNull(value.get("en"));
value.put("ru", "Russian");
assertEquals("Russian", value.get("ru"));
assertEquals("Russian", value.get("en"));
assertEquals("Russian", value.get("pt"));
value.put("en", "English");
assertEquals("Russian", value.get("ru"));
assertEquals("English", value.get("en"));
assertEquals("English", value.get("pt"));
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.