hexsha stringlengths 40 40 | size int64 8 1.04M | content stringlengths 8 1.04M | avg_line_length float64 2.24 100 | max_line_length int64 4 1k | alphanum_fraction float64 0.25 0.97 |
|---|---|---|---|---|---|
6b255f6a81d587c8ecb993270a5a28bd4a9c52b8 | 269 | package com.immplah.repositories;
import com.immplah.entities.MedicationPlan;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.UUID;
public interface MedicationPlanRepository extends JpaRepository<MedicationPlan, UUID> {
}
| 22.416667 | 88 | 0.802974 |
e5c4e159d5034ec427f75f643263277103d46351 | 7,884 | package com.deftwun.zombiecopter;
import net.dermetfan.gdx.physics.box2d.Box2DMapObjectParser;
import com.badlogic.ashley.core.Entity;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.maps.Map;
import com.badlogic.gdx.maps.MapLayer;
import com.badlogic.gdx.maps.MapObject;
import com.badlogic.gdx.maps.MapObjects;
import com.badlogic.gdx.maps.MapProperties;
import com.badlogic.gdx.maps.objects.RectangleMapObject;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.utils.Logger;
import com.badlogic.gdx.utils.ObjectMap;
import com.deftwun.zombiecopter.components.PhysicsComponent;
import com.deftwun.zombiecopter.systems.SpawnSystem;
public class Level {
private Logger logger = new Logger("Level",Logger.INFO);
private TiledMap map;
private OrthogonalTiledMapRenderer mapRenderer;
private SpriteBatch batch;
private Entity entity;
public Level() {
logger.debug("initialising");
batch = new SpriteBatch();
map = null;
}
public Level(String fileName){
logger.debug("initialising");
batch = new SpriteBatch();
loadTiledMap(fileName);
}
public void clear(){
logger.debug("Clearing");
if (map != null) {
map.dispose();
map = null;
}
if (entity != null){
App.engine.removeEntity(entity);
entity = null;
}
if (mapRenderer != null){
mapRenderer.dispose();
mapRenderer = null;
}
}
public Entity getEntity(){
return entity;
}
public void loadTiledMap(String mapName){
logger.debug("Loading TiledMap: " + mapName);
this.clear();
try{
map = new TmxMapLoader().load(mapName);
}
catch(Exception e){
logger.error("Map load failed .. " + e.getMessage());
return;
}
mapRenderer = new OrthogonalTiledMapRenderer(map,batch);
createPhysics(map);
createEntities(map);
createSpawnZones(map);
createDropOffPoints(map);
}
private void createPhysics(Map map) {
logger.debug("Creating Physics");
String layerName = "physics";
//Layer objects
MapLayer layer = map.getLayers().get(layerName);
if (layer == null) {
logger.error("layer " + layerName + " does not exist");
return;
}
World world = App.engine.systems.physics.world;
//world.dispose();
Box2DMapObjectParser parser = new Box2DMapObjectParser(1/App.engine.PIXELS_PER_METER);
parser.load(world,layer);
logger.debug(parser.getBodies().size + " bodies were parsed in layer '" + layerName + "'");
logger.debug(parser.getFixtures().size + " fixtures were parsed in layer '" + layerName + "'");
//Level Entity (If it has physics then it needs to be associated with an entity,
// other wise collisions won't be handled properly.)
entity = App.engine.createEntity();
PhysicsComponent physics = App.engine.createComponent(PhysicsComponent.class);
for (ObjectMap.Entry<String,Body> entry : parser.getBodies()){
physics.addBody(entry.key,entry.value);
}
physics.setFilter(CollisionBits.Terrain,CollisionBits.Mask_Terrain);
entity.add(physics);
App.engine.addEntity(entity);
}
private void createDropOffPoints(Map map){
logger.debug("Creating DropOffPoints");
String layerName = "dropoff";
//dropOffPoint map layer
MapLayer layer = map.getLayers().get(layerName);
if (layer == null) {
logger.error("layer " + layerName + " does not exist");
return;
}
//Layer objects
MapObjects objects = layer.getObjects();
for (MapObject mapObj : objects){
//Object properties.
//name and position are set by the tiled editor. The rest are custom properties
Vector2 position = new Vector2();
float range = 1;
MapProperties prop = mapObj.getProperties();
Object x = prop.get("x"),
y = prop.get("y"),
r = prop.get("range");
if (r != null) range = Float.parseFloat(r.toString());
if (x != null && y != null)
position.set((Float)x,(Float)y).scl(1/App.engine.PIXELS_PER_METER);
App.engine.systems.dropoff.add(new DropOffPoint(position,range));
}
}
private void createSpawnZones(Map map){
logger.debug("Creating SpawnPoints");
String layerName = "spawn";
//spawnPoint map layer
MapLayer layer = map.getLayers().get(layerName);
if (layer == null) {
logger.error("layer " + layerName + " does not exist");
return;
}
//Layer objects
float units = App.engine.PIXELS_PER_METER;
MapObjects objects = layer.getObjects();
for (MapObject mapObj : objects){
logger.debug("found spawn zone");
//Spawn area rectangle
Rectangle rect;
if (mapObj instanceof RectangleMapObject){
rect = ((RectangleMapObject) mapObj).getRectangle();
rect.height /= units;
rect.width /= units;
rect.x /= units;
rect.y /= units;
}
else {
logger.error("spawn zones should only be rectangles");
continue;
}
//Object properties.
//name and position are set by the tiled editor. The rest are custom properties
String name = mapObj.getName();
int maximum = 0;
float delay = 3;
logger.debug("Creating '" + name + "' spawn zone");
MapProperties prop = mapObj.getProperties();
Object max = prop.get("maximum"),
dly = prop.get("delay");
if (max != null) maximum = Integer.parseInt(max.toString());
if (dly != null) delay = Float.parseFloat(dly.toString());
SpawnSystem spawner = App.engine.systems.spawn;
spawner.add(new SpawnZone(rect,name,maximum,delay));
}
}
private void createEntities(Map map) {
logger.debug("Creating Entities");
String layerName = "entities";
MapLayer layer = map.getLayers().get(layerName);
if (layer == null) {
logger.error("layer " + layerName + " does not exist");
return;
}
//Entity objects
Vector2 position = new Vector2(),
velocity = new Vector2();
MapObjects objects = layer.getObjects();
for (MapObject mapObj : objects){
MapProperties prop = mapObj.getProperties();
Object x = prop.get("x"),
y = prop.get("y"),
vx = prop.get("vx"),
vy = prop.get("vy");
position.set(0,0);
velocity.set(0,0);
if (x != null && y != null)
position.set((Float)x,(Float)y).scl(1/App.engine.PIXELS_PER_METER);
if (vx != null && y != null)
velocity.set((Float)vx,(Float)vy);
logger.debug(" -Create: " + mapObj.getName());
Entity e = App.engine.factory.build(mapObj.getName(),position,velocity);
if (mapObj.getName().equals("player")) App.engine.systems.player.setPlayer(e);
}
}
public void render(Matrix4 projection){
mapRenderer.setView((OrthographicCamera) App.engine.systems.camera.getCamera());
mapRenderer.render();
}
public void renderLayer(String layerName, Matrix4 projection){
mapRenderer.setView((OrthographicCamera) App.engine.systems.camera.getCamera());
MapLayer layer = map.getLayers().get(layerName);
if (layer != null) mapRenderer.renderTileLayer((TiledMapTileLayer) layer);
}
public void renderLayer(int index, Matrix4 projection){
mapRenderer.setView((OrthographicCamera) App.engine.systems.camera.getCamera());
MapLayer layer = map.getLayers().get(index);
if (layer != null) mapRenderer.renderTileLayer((TiledMapTileLayer) layer);
}
}
| 30.091603 | 98 | 0.668696 |
777029bfb30e3be085503aa12bde12bf348316fa | 3,528 | package ch.epfl.rigel.coordinates;
import ch.epfl.rigel.math.Angle;
import ch.epfl.rigel.math.Polynomial;
import org.junit.jupiter.api.Test;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import static ch.epfl.rigel.astronomy.Epoch.J2000;
import static ch.epfl.rigel.coordinates.CoordinateAssertions.assertEquals2;
import static java.lang.Math.asin;
import static java.lang.Math.atan2;
import static java.lang.Math.cos;
import static java.lang.Math.sin;
import static java.lang.Math.tan;
/**
* @author Antonio Jimenez (314363)
* @author Alexis Horner (315780)
*/
public class EclipticToEquatorialConversionTest {
double epsilon(ZonedDateTime when) {
double T = J2000.julianCenturiesUntil(when);
Polynomial polE = Polynomial.of(Angle.ofArcsec(0.00181), Angle.ofArcsec(-0.0006),
Angle.ofArcsec(-46.815), Angle.ofDMS(23, 26, 21.45));
return polE.at(T);
}
EquatorialCoordinates eclipticToEquatorial(ZonedDateTime when, EclipticCoordinates ecl) {
final double lb = ecl.lon();
final double bt = ecl.lat();
double e = epsilon(when);
double alpha = Angle.normalizePositive(atan2(sin(lb)*cos(e) - tan(bt)*sin(e), cos(lb)));
double delta = asin(sin(bt)*cos(e) + cos(bt)*sin(e)*sin(lb));
return EquatorialCoordinates.of(alpha, delta);
}
@Test
void applyWorksOnNormalCases() {
ZonedDateTime when = ZonedDateTime.of(0, 1, 1,
0, 0, 0, 0,
ZoneId.of("UTC-2"));
EclipticToEquatorialConversion converter = new EclipticToEquatorialConversion(when);
EclipticCoordinates ecl = EclipticCoordinates.of(Angle.ofDeg(142.001247515), Angle.ofDeg(-12.586657));
assertEquals2(eclipticToEquatorial(when, ecl), converter.apply(ecl), 1e-9);
when = ZonedDateTime.of(2021, 7, 12,
1, 18, 59, 9_071_411,
ZoneId.of("UTC-6"));
converter = new EclipticToEquatorialConversion(when);
ecl = EclipticCoordinates.of(Angle.ofDeg(90.0), Angle.ofDeg(0.0));
assertEquals2(eclipticToEquatorial(when, ecl), converter.apply(ecl), 1e-9);
}
@Test
void applyWorksOnEdgeCases() {
ZonedDateTime when = ZonedDateTime.of(1500, 12, 31,
12, 0, 0, 0,
ZoneId.of("UTC+1"));
EclipticToEquatorialConversion converter = new EclipticToEquatorialConversion(when);
EclipticCoordinates ecl = EclipticCoordinates.of(Angle.ofDeg(179.9999999), Angle.ofDeg(90.0));
assertEquals2(eclipticToEquatorial(when, ecl), converter.apply(ecl), 1e-9);
when = ZonedDateTime.of(2020, 2, 29,
0, 0, 0, 1_051_151,
ZoneId.of("UTC"));
converter = new EclipticToEquatorialConversion(when);
ecl = EclipticCoordinates.of(Angle.ofDeg(0.0), Angle.ofDeg(-90.0));
assertEquals2(eclipticToEquatorial(when, ecl), converter.apply(ecl), 1e-9);
when = ZonedDateTime.of(3000, 2, 28,
0, 0, 0, 4_071,
ZoneId.of("UTC+10"));
converter = new EclipticToEquatorialConversion(when);
ecl = EclipticCoordinates.of(Angle.ofDeg(90.0), Angle.ofDeg(0.0));
assertEquals2(eclipticToEquatorial(when, ecl), converter.apply(ecl), 1e-9);
}
}
| 44.1 | 110 | 0.614229 |
255465a762653c8938f89f43e9037296ef83cb36 | 1,533 | package com.company.template.client;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.mock.http.client.MockClientHttpResponse;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.hasSize;
/**
* @author Idan Rozenfeld
*/
@RunWith(SpringRunner.class)
@SpringBootTest(properties = "template.client.api.path=someServer")
public class AutoConfigurationWithCustomBeansTest {
@Autowired(required = false)
private RestTemplate restTemplate;
@Test
public void shouldInstantiateCustomRestTemplate() {
assertThat(restTemplate.getInterceptors(), hasSize(1));
}
@Configuration
@EnableAutoConfiguration
public static class Application {
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.interceptors((request, body, execution) ->
new MockClientHttpResponse(new byte[]{}, HttpStatus.OK)).build();
}
}
}
| 33.326087 | 85 | 0.778213 |
79c134690f8ba5fcf1aee1de40ad5f31578c0e58 | 6,488 | /*
* Copyright 2018 Marco Helmich
*
* 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.mhelmich.kafka.protocol.generator;
import com.google.common.collect.ImmutableMap;
import org.antlr.v4.runtime.ParserRuleContext;
import org.antlr.v4.runtime.tree.ParseTreeProperty;
import org.mhelmich.kafka.protocol.generator.gen.KafkaProtocolBaseListener;
import org.mhelmich.kafka.protocol.generator.gen.KafkaProtocolParser;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
class KafkaProtocolListener extends KafkaProtocolBaseListener {
private String entityName;
private String versionNumber;
private final ParseTreeProperty<String> leftSideName = new ParseTreeProperty<>();
private final Map<String, List<TypeDefinition>> complexTypeToDefinitions = new HashMap<>();
private final Map<String, List<TypeDefinition>> primitiveTypeToDefinitions = new HashMap<>();
@Override
public void exitEntity_name(KafkaProtocolParser.Entity_nameContext ctx) {
entityName = ctx.getText().replace(" ", "_");
}
@Override
public void exitVersion_number(KafkaProtocolParser.Version_numberContext ctx) {
versionNumber = ctx.getText();
}
@Override
public void enterLeft_side(KafkaProtocolParser.Left_sideContext ctx) {
complexTypeToDefinitions.putIfAbsent(ctx.getText(), new LinkedList<>());
primitiveTypeToDefinitions.putIfAbsent(ctx.getText(), new LinkedList<>());
}
@Override
public void exitLeft_side(KafkaProtocolParser.Left_sideContext ctx) {
// this will end up being the struct name
String futureStructName;
if (ctx.getChildCount() > 1) {
// this has an entity name and a version number
// in this case we want to filter out the string "Version:" and just use the version number
KafkaProtocolParser.Entity_nameContext entityNameCtx = ctx.getChild(KafkaProtocolParser.Entity_nameContext.class, 0);
KafkaProtocolParser.VersionContext versionCtx = ctx.getChild(KafkaProtocolParser.VersionContext.class, 0);
KafkaProtocolParser.Version_numberContext verionNumberCtx = versionCtx.getChild(KafkaProtocolParser.Version_numberContext.class, 0);
futureStructName = entityNameCtx.getText() + verionNumberCtx.getText();
} else {
futureStructName = ctx.getText();
}
leftSideName.put(ctx.getParent(), futureStructName);
complexTypeToDefinitions.putIfAbsent(futureStructName, new LinkedList<>());
primitiveTypeToDefinitions.putIfAbsent(futureStructName, new LinkedList<>());
}
@Override
public void exitComplex_type(KafkaProtocolParser.Complex_typeContext ctx) {
if (isRightSide(ctx)) {
String name = getLeftSideName(ctx);
if (name != null) {
List<TypeDefinition> types = complexTypeToDefinitions.get(name);
if (types != null) {
String text = ctx.getText();
boolean isArray = isArray(ctx);
types.add(new TypeDefinition(text, isArray, true));
}
}
}
}
@Override
public void exitPrimitive_type(KafkaProtocolParser.Primitive_typeContext ctx) {
if (isRightSide(ctx)) {
String name = getLeftSideName(ctx);
if (name != null) {
List<TypeDefinition> names = primitiveTypeToDefinitions.get(name);
if (names != null) {
String text = ctx.getText();
boolean isArray = isArray(ctx);
names.add(new TypeDefinition(text, isArray, false));
}
}
}
}
private boolean isRightSide(ParserRuleContext ctx) {
return KafkaProtocolParser.Right_sideContext.class.equals(ctx.getParent().getClass()) || KafkaProtocolParser.Right_sideContext.class.equals(ctx.getParent().getParent().getClass());
}
private String getLeftSideName(ParserRuleContext srcCtx) {
return leftSideName.get(getBnfLineCtx(srcCtx));
}
private boolean isArray(ParserRuleContext ctx) {
return KafkaProtocolParser.Complex_arrayContext.class.equals(ctx.getParent().getClass()) || KafkaProtocolParser.Primitive_arrayContext.class.equals(ctx.getParent().getClass());
}
private KafkaProtocolParser.Bnf_lineContext getBnfLineCtx(ParserRuleContext srcCtx) {
ParserRuleContext x = srcCtx;
while (!KafkaProtocolParser.Bnf_lineContext.class.equals(x.getClass())) {
x = x.getParent();
}
return (KafkaProtocolParser.Bnf_lineContext)x;
}
String getFileName() {
return (versionNumber == null) ? entityName : entityName + "_" + versionNumber;
}
String getVersionNumber() {
return versionNumber;
}
Map<String, List<TypeDefinition>> getComplexTypeToDefinitions() {
ImmutableMap.Builder<String, List<TypeDefinition>> builder = ImmutableMap.builderWithExpectedSize(complexTypeToDefinitions.size());
complexTypeToDefinitions.entrySet().stream()
.filter(e -> e.getValue().size() > 0)
.forEach(e -> builder.put(e.getKey(), e.getValue()));
return builder.build();
}
Map<String, List<TypeDefinition>> getPrimitiveTypeToDefinitions() {
ImmutableMap.Builder<String, List<TypeDefinition>> builder = ImmutableMap.builderWithExpectedSize(primitiveTypeToDefinitions.size());
primitiveTypeToDefinitions.entrySet().stream()
.filter(e -> e.getValue().size() > 0)
.forEach(e -> builder.put(e.getKey(), e.getValue()));
return builder.build();
}
// interesting for exception handling
void dump() {
System.err.println(getFileName());
System.err.println(getComplexTypeToDefinitions());
System.err.println(getPrimitiveTypeToDefinitions());
}
}
| 41.858065 | 188 | 0.682645 |
a0ef8e369f1e2e560d042f60bc3935e16c801f9d | 3,824 | package dev.shelenkov.portfolio.security.oauth2.loginprocessors;
import dev.shelenkov.portfolio.domain.Account;
import dev.shelenkov.portfolio.service.account.AccountService;
import dev.shelenkov.portfolio.service.registration.RegistrationService;
import lombok.Data;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.security.config.oauth2.client.CommonOAuth2Provider;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestOperations;
import org.springframework.web.client.RestTemplate;
import java.util.List;
import java.util.Map;
@Component
public class GitHubOAuth2LoginProcessor extends AbstractOAuth2LoginProcessor {
private static final String GET_EMAIL_URL = "https://api.github.com/user/emails";
private final RegistrationService registrationService;
private final RestOperations restOperations;
public GitHubOAuth2LoginProcessor(AccountService accountService,
ClientRegistrationRepository clientRegistrationRepository,
RegistrationService registrationService) {
super(accountService, clientRegistrationRepository);
this.registrationService = registrationService;
this.restOperations = new RestTemplate();
}
@Override
public String getSupportedRegistrationId() {
return CommonOAuth2Provider.GITHUB.name();
}
@Override
protected Account loadUserByOauth2Id(String oauth2Id) {
return getAccountService().getByGithubId(oauth2Id);
}
@Override
protected Account registerNewAccount(Map<String, Object> userAttributes,
String email,
String oauth2Id) {
String username = (String) userAttributes.get("login");
return registrationService.registerNewGitHubUser(username, email, oauth2Id);
}
@Override
protected void setOAuth2IdForAccount(Account account, String oauth2Id) {
account.setGithubId(oauth2Id);
}
@Override
protected String getVerifiedEmail(Map<String, Object> userAttributes, String accessToken) {
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken);
//noinspection AnonymousInnerClassMayBeStatic,AnonymousInnerClass
ResponseEntity<List<GitHubOAuth2LoginProcessor.GitHubEmail>> emailResponse
= restOperations.exchange(
GET_EMAIL_URL, HttpMethod.GET, new HttpEntity<>(headers),
new ParameterizedTypeReference<List<GitHubOAuth2LoginProcessor.GitHubEmail>>() {});
/*
* Response example:
* [{"email":"anshelen@yandex.ru","primary":true,"verified":true,"visibility":"private"},
* {"email":"32411111+Anshelen@users.noreply.github.com","primary":false,"verified":true,"visibility":null}]
*/
List<GitHubOAuth2LoginProcessor.GitHubEmail> emails = emailResponse.getBody();
if (emails == null) {
throw new RuntimeException("Not expected response from OAuth2 provider: " + emailResponse);
}
return emails.stream()
.filter(e -> e.isPrimary() && e.isVerified())
.findFirst().map(GitHubOAuth2LoginProcessor.GitHubEmail::getEmail).orElse(null);
}
@Data
private static class GitHubEmail {
private String email;
private boolean primary;
private boolean verified;
private String visibility;
}
}
| 41.565217 | 116 | 0.715481 |
1e554b750fcf97d15cb3a8703fc03ef1541621d1 | 16,620 | /**
* Licensed to Apereo under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright ownership. Apereo
* licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use
* this file except in compliance with the License. You may obtain a copy of the License at the
* following location:
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>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.apereo.portal.shell;
import com.google.common.collect.ImmutableSet;
import com.google.common.io.Files;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import org.apache.commons.io.Charsets;
import org.apache.commons.lang.StringUtils;
import org.apereo.portal.IUserIdentityStore;
import org.apereo.portal.io.xml.IPortalData;
import org.apereo.portal.io.xml.IPortalDataHandlerService;
import org.apereo.portal.io.xml.PortalDataHandlerServiceUtils;
import org.apereo.portal.jpa.VersionedDataUpdater;
import org.apereo.portal.tools.DbTest;
import org.apereo.portal.tools.dbloader.DbLoaderConfigBuilder;
import org.apereo.portal.tools.dbloader.IDbLoader;
import org.apereo.portal.tools.dbloader.ISchemaExport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.stereotype.Service;
/**
* Utility used by the groovy scripts generated in build.xml and passed into PortalShell
*
*/
@Service("portalShellBuildHelper")
public class PortalShellBuildHelperImpl implements PortalShellBuildHelper {
private static final Pattern COMMA_DELIM = Pattern.compile(",");
private IDbLoader dbLoader;
private Map<String, ISchemaExport> schemaExportBeans;
private IPortalDataHandlerService portalDataHandlerService;
private IUserIdentityStore userIdentityStore;
private DbTest dbTest;
private VersionedDataUpdater versionedDataUpdater;
@Autowired
public void setVersionedDataUpdater(VersionedDataUpdater versionedDataUpdater) {
this.versionedDataUpdater = versionedDataUpdater;
}
@Autowired
public void setDbLoader(IDbLoader dbLoader) {
this.dbLoader = dbLoader;
}
@Autowired
public void setSchemaExportBeans(Map<String, ISchemaExport> schemaExportBeans) {
this.schemaExportBeans = schemaExportBeans;
}
@Autowired
public void setPortalDataHandlerService(IPortalDataHandlerService portalDataHandlerService) {
this.portalDataHandlerService = portalDataHandlerService;
}
@Autowired
public void setUserIdentityStore(IUserIdentityStore userIdentityStore) {
this.userIdentityStore = userIdentityStore;
}
@Autowired
public void setDbTest(DbTest dbTest) {
this.dbTest = dbTest;
}
@Override
public void dbTest() {
this.dbTest.printDbInfo();
}
@Override
public void db(
String target,
String tablesFile,
String dataFile,
String scriptFile,
boolean dropTables,
boolean createTables,
boolean populateTables) {
try {
PortalShell.LOGGER.info("");
PortalShell.LOGGER.info("");
//DbLoader Script
final DbLoaderConfigBuilder dbLoaderConfig = new DbLoaderConfigBuilder();
dbLoaderConfig.setTablesFile(tablesFile);
dbLoaderConfig.setDataFile(dataFile);
if (StringUtils.isNotBlank(scriptFile)) {
dbLoaderConfig.setScriptFile(scriptFile);
}
dbLoaderConfig.setDropTables(dropTables);
dbLoaderConfig.setCreateTables(createTables);
dbLoaderConfig.setPopulateTables(populateTables);
PortalShell.LOGGER.info("Running DbLoader with: " + dbLoaderConfig);
dbLoader.process(dbLoaderConfig);
} catch (Exception e) {
throw new RuntimeException(
target + " for " + tablesFile + " and " + dataFile + " failed", e);
}
}
@Override
public void hibernateCreate(
String target, String databaseQualifier, boolean export, String outputFile) {
final ISchemaExport schemaExportBean = getSchemaExport(databaseQualifier);
if (schemaExportBean == null) {
throw new RuntimeException(
target + " could not find schemaExportBean " + databaseQualifier);
}
try {
PortalShell.LOGGER.info("");
PortalShell.LOGGER.info("");
PortalShell.LOGGER.info("Hibernate Create DDL: " + databaseQualifier);
outputFile = StringUtils.trimToNull(outputFile);
schemaExportBean.create(export, outputFile, true);
this.versionedDataUpdater.postInitDatabase(databaseQualifier);
} catch (Exception e) {
throw new RuntimeException(target + " for " + databaseQualifier + " failed", e);
}
}
@Override
public void hibernateDrop(
String target, String databaseQualifier, boolean export, String outputFile) {
final ISchemaExport schemaExportBean = this.getSchemaExport(databaseQualifier);
if (schemaExportBean == null) {
throw new RuntimeException(
target + " could not find schemaExportBean " + databaseQualifier);
}
try {
PortalShell.LOGGER.info("");
PortalShell.LOGGER.info("");
PortalShell.LOGGER.info("Hibernate Drop DDL: " + databaseQualifier);
outputFile = StringUtils.trimToNull(outputFile);
schemaExportBean.drop(export, outputFile, true);
} catch (Exception e) {
throw new RuntimeException(target + " for " + databaseQualifier + " failed", e);
}
}
@Override
public void hibernateUpdate(
String target, String databaseQualifier, boolean export, String outputFile) {
//TODO add upgrade-state to up_version table to handle a failure during the hbm2ddl update
this.versionedDataUpdater.preUpdateDatabase(databaseQualifier);
updateScript(target, databaseQualifier, outputFile, export);
this.versionedDataUpdater.postUpdateDatabase(databaseQualifier);
}
@Override
public void hibernateGenerateScript(
String target, String databaseQualifier, String outputFile) {
updateScript(target, databaseQualifier, outputFile, false);
}
/**
* This runs a database update or just generates the script
*
* @param target the database to target
* @param databaseQualifier The Spring database qualifier
* @param outputFile The output file to utilize to generate the scripts
* @param runIt Do you want to run it, or just generate the script?
*/
private void updateScript(
String target, String databaseQualifier, String outputFile, boolean runIt) {
final ISchemaExport schemaExportBean = this.getSchemaExport(databaseQualifier);
if (schemaExportBean == null) {
throw new RuntimeException(
target + " could not find schemaExportBean " + databaseQualifier);
}
try {
PortalShell.LOGGER.info("");
PortalShell.LOGGER.info("");
PortalShell.LOGGER.info("Hibernate Update DDL: " + databaseQualifier);
outputFile = StringUtils.trimToNull(outputFile);
schemaExportBean.update(runIt, outputFile, true);
} catch (Exception e) {
throw new RuntimeException(target + " for " + databaseQualifier + " failed", e);
}
}
@Override
public void dataList(String target, String type) {
try {
if (StringUtils.isBlank(type)) {
//List Data Types Script
PortalShell.LOGGER.info("");
PortalShell.LOGGER.info("");
PortalShell.LOGGER.info("Export and Delete Support by Data Type");
PortalDataHandlerServiceUtils.format(portalDataHandlerService, PortalShell.LOGGER);
PortalShell.LOGGER.info(
"Add -Dtype=dataType To get a list of data keys for the type");
} else {
//List Data Script
final Iterable<? extends IPortalData> data =
portalDataHandlerService.getPortalData(type);
PortalShell.LOGGER.info("");
PortalShell.LOGGER.info("");
PortalShell.LOGGER.info("All " + type + " data");
PortalDataHandlerServiceUtils.format(data, PortalShell.LOGGER);
}
} catch (Exception e) {
throw new RuntimeException(target + " failed", e);
}
}
@Override
public void dataExport(
String target, String dataDir, String type, String sysid, String logDir) {
PortalShell.LOGGER.info("");
PortalShell.LOGGER.info("");
final File dataDirFile = new File(dataDir);
if (StringUtils.isNotBlank(type) && StringUtils.isNotBlank(sysid)) {
try {
for (final String id : COMMA_DELIM.split(sysid)) {
PortalShell.LOGGER.info(
"Exporting Data " + id + " of type " + type + " to: " + dataDir);
portalDataHandlerService.exportData(type, id, dataDirFile);
}
} catch (Exception e) {
throw new RuntimeException(
target + " to " + dataDir + " of " + type + " " + sysid + " failed", e);
}
} else if (StringUtils.isNotBlank(type)) {
try {
final Set<String> types = ImmutableSet.copyOf(COMMA_DELIM.split(type));
if (types.size() == 1) {
PortalShell.LOGGER.info(
"Exporting All Data of type " + type + " to: " + dataDir);
} else {
PortalShell.LOGGER.info(
"Exporting All Data of types " + types + " to: " + dataDir);
}
portalDataHandlerService.exportAllDataOfType(
types,
dataDirFile,
new IPortalDataHandlerService.BatchExportOptions()
.setLogDirectoryParent(logDir));
} catch (Exception e) {
throw new RuntimeException(
target + " to " + dataDir + " of " + type + " failed", e);
}
} else {
try {
PortalShell.LOGGER.info("Exporting All Data to: " + dataDir);
portalDataHandlerService.exportAllData(
dataDirFile,
new IPortalDataHandlerService.BatchExportOptions()
.setLogDirectoryParent(logDir));
} catch (Exception e) {
throw new RuntimeException(target + " to " + dataDir + " failed", e);
}
}
}
@Override
public void dataImport(
String target, String dataDir, String pattern, String file, String logDir) {
dataImport(target, dataDir, pattern, file, null, logDir);
}
@Override
public void dataImport(
String target,
String dataDir,
String pattern,
String filesList,
String archive,
String logDir) {
PortalShell.LOGGER.info("");
PortalShell.LOGGER.info("");
if (!StringUtils.isBlank(filesList)) {
final String[] fileNames = filesList.split(",");
for (String fileName : fileNames) {
this.importFromFile(target, fileName);
}
} else if (!StringUtils.isBlank(archive)) {
this.importFromArchive(target, logDir, archive);
} else if (!StringUtils.isBlank(dataDir)) {
this.importFromDirectoryUsingPattern(target, logDir, dataDir, pattern);
} else {
throw new RuntimeException(
target + " failed: One of dataDir, files, or archive must be specified");
}
}
private void importFromFile(final String target, final String filePath) {
PortalShell.LOGGER.info("Importing Data from: " + filePath);
try {
portalDataHandlerService.importData(new FileSystemResource(filePath));
} catch (Exception e) {
throw new RuntimeException(target + " for " + filePath + " failed", e);
}
}
private void importFromArchive(final String target, final String logDir, final String archive) {
PortalShell.LOGGER.info("Importing Data from: " + archive);
try {
portalDataHandlerService.importDataArchive(
new FileSystemResource(archive),
new IPortalDataHandlerService.BatchImportOptions()
.setLogDirectoryParent(logDir));
} catch (Exception e) {
throw new RuntimeException(target + " for " + archive + " failed", e);
}
}
private void importFromDirectoryUsingPattern(
final String target, final String logDir, final String dataDir, final String pattern) {
PortalShell.LOGGER.info("Importing Data from: " + dataDir + " that matches " + pattern);
final String patternToUse = StringUtils.trimToNull(pattern);
try {
portalDataHandlerService.importDataDirectory(
new File(dataDir),
patternToUse,
new IPortalDataHandlerService.BatchImportOptions()
.setLogDirectoryParent(logDir));
} catch (Exception e) {
if (pattern != null) {
throw new RuntimeException(
target + " from " + dataDir + " matching " + patternToUse + " failed", e);
} else {
throw new RuntimeException(target + " from " + dataDir + " failed", e);
}
}
}
@Override
public void dataDelete(String target, String type, String sysid) {
//Data Delete Script
PortalShell.LOGGER.info("");
PortalShell.LOGGER.info("");
for (final String id : COMMA_DELIM.split(sysid)) {
try {
PortalShell.LOGGER.info("Deleting Data " + id + " of type " + type);
portalDataHandlerService.deleteData(type, id);
} catch (Exception e) {
throw new RuntimeException(target + " for " + type + " and " + id + " failed", e);
}
}
}
@Override
public void deleteUser(String target, String user) {
try {
//Delete USer Script
PortalShell.LOGGER.info("");
PortalShell.LOGGER.info("");
userIdentityStore.removePortalUID(user);
} catch (Exception e) {
throw new RuntimeException(target + " for " + user + " failed", e);
}
}
private ISchemaExport getSchemaExport(String persistenceUnit) {
for (final ISchemaExport schemaExport : this.schemaExportBeans.values()) {
if (persistenceUnit.equals(schemaExport.getPersistenceUnitName())) {
return schemaExport;
}
}
throw new IllegalArgumentException(
"No ISchemaExport bean found for persistence unit: '" + persistenceUnit + "'");
}
@Override
public String getFilesListStringFromInput(String file, String files, String filesListFile)
throws IOException {
if (StringUtils.isNotBlank(file)) {
return file;
} else if (StringUtils.isNotBlank(files)) {
return files;
} else if (StringUtils.isNotBlank(filesListFile)) {
return this.getFilesListStringFromFilesListFile(filesListFile);
} else {
return "";
}
}
private String getFilesListStringFromFilesListFile(String filesListFile) throws IOException {
List<String> lines = Files.readLines(new File(filesListFile), Charsets.UTF_8);
return StringUtils.join(lines, ",");
}
}
| 39.29078 | 100 | 0.615463 |
145288749af2262fd17b306cd5e43338bd4b4546 | 2,678 | package com.fasterxml.uuid;
import java.util.Comparator;
import java.util.UUID;
/**
* Default {@link java.util.UUID} comparator is not very useful, since
* it just does blind byte-by-byte comparison which does not work well
* for time+location - based UUIDs. Additionally it also uses signed
* comparisons for longs which can lead to unexpected behavior
* This comparator does implement proper lexical ordering: starting with
* type (different types are collated
* separately), followed by time and location (for time/location based),
* and simple lexical (byte-by-byte) ordering for name/hash and random
* variants.
*
* @author tatu
*/
public class UUIDComparator implements Comparator<UUID>
{
@Override
public int compare(UUID u1, UUID u2)
{
return staticCompare(u1, u2);
}
/**
* Static helper method that can be used instead of instantiating comparator
* (used by unit tests, can be used by code too)
*/
public static int staticCompare(UUID u1, UUID u2)
{
// First: major sorting by types
int type = u1.version();
int diff = type - u2.version();
if (diff != 0) {
return diff;
}
// Second: for time-based variant, order by time stamp:
if (type == UUIDType.TIME_BASED.raw()) {
diff = compareULongs(u1.timestamp(), u2.timestamp());
if (diff == 0) {
// or if that won't work, by other bits lexically
diff = compareULongs(u1.getLeastSignificantBits(), u2.getLeastSignificantBits());
}
} else {
// note: java.util.UUIDs compares with sign extension, IMO that's wrong, so:
diff = compareULongs(u1.getMostSignificantBits(),
u2.getMostSignificantBits());
if (diff == 0) {
diff = compareULongs(u1.getLeastSignificantBits(),
u2.getLeastSignificantBits());
}
}
return diff;
}
protected final static int compareULongs(long l1, long l2) {
int diff = compareUInts((int) (l1 >> 32), (int) (l2 >> 32));
if (diff == 0) {
diff = compareUInts((int) l1, (int) l2);
}
return diff;
}
protected final static int compareUInts(int i1, int i2)
{
/* bit messier due to java's insistence on signed values: if both
* have same sign, normal comparison (by subtraction) works fine;
* but if signs don't agree need to resolve differently
*/
if (i1 < 0) {
return (i2 < 0) ? (i1 - i2) : 1;
}
return (i2 < 0) ? -1 : (i1 - i2);
}
}
| 34.333333 | 97 | 0.592233 |
5529dceb7c5c813b2a800fdccf16f5ef7c02c110 | 216 | package test.listeners;
import org.testng.Assert;
import org.testng.annotations.Test;
public class SetStatusSample {
@Test
public void aFailingTest() {
Assert.fail("Failing deliberately");
}
}
| 16.615385 | 44 | 0.703704 |
1e6f7fb9d6707e91d23ace9fe239b82bb735b544 | 7,125 | package de.gurkenlabs.litiengine.gui;
import de.gurkenlabs.litiengine.Align;
import de.gurkenlabs.litiengine.Valign;
import de.gurkenlabs.litiengine.graphics.ImageRenderer;
import de.gurkenlabs.litiengine.graphics.Spritesheet;
import de.gurkenlabs.litiengine.resources.Resources;
import de.gurkenlabs.litiengine.util.Imaging;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.geom.Point2D;
import java.awt.image.BufferedImage;
import java.util.Optional;
import javax.swing.JLabel;
public class ImageComponent extends GuiComponent {
public static final int BACKGROUND_INDEX = 0;
public static final int BACKGROUND_HOVER_INDEX = 1;
public static final int BACKGROUND_PRESSED_INDEX = 2;
public static final int BACKGROUND_DISABLED_INDEX = 3;
private BufferedImage baseImage;
private BufferedImage scaledImage;
private Spritesheet spritesheet;
private ImageScaleMode imageScaleMode = ImageScaleMode.NORMAL;
private Align imageAlign = Align.CENTER;
private Valign imageValign = Valign.MIDDLE;
public ImageComponent(final double x, final double y, final Image image) {
super(x, y, image.getWidth(null), image.getHeight(null));
this.baseImage = (BufferedImage) image;
}
public ImageComponent(final double x, final double y, final double width, final double height) {
super(x, y, width, height);
}
public ImageComponent(
final double x, final double y, final double width, final double height, final String text) {
super(x, y, width, height);
Font defFont = new JLabel().getFont().deriveFont((float) (this.getHeight() * 3 / 6f));
if (this.getFont() == null) {
this.setFont(defFont);
}
this.setText(text);
}
public ImageComponent(
final double x, final double y, final double width, final double height, final Image image) {
super(x, y, width, height);
this.setImage(image);
}
public ImageComponent(
final double x,
final double y,
final double width,
final double height,
final Spritesheet spritesheet,
final String text,
final Image image) {
this(x, y, width, height, text);
this.spritesheet = spritesheet;
this.setImageAlign(Align.LEFT);
this.setImageValign(Valign.TOP);
if (image != null) {
this.baseImage = (BufferedImage) image;
}
}
public Image getBackground() {
if (this.getSpritesheet() == null) {
return null;
}
final String cacheKey =
this.getSpritesheet().getName().hashCode()
+ "_"
+ this.isHovered()
+ "_"
+ this.isPressed()
+ "_"
+ this.isEnabled()
+ "_"
+ this.getWidth()
+ "x"
+ this.getHeight();
Optional<BufferedImage> opt = Resources.images().tryGet(cacheKey);
if (opt.isPresent()) {
return opt.get();
}
int spriteIndex = BACKGROUND_INDEX;
if (!this.isEnabled()
&& this.getSpritesheet().getTotalNumberOfSprites() > BACKGROUND_DISABLED_INDEX) {
spriteIndex = BACKGROUND_DISABLED_INDEX;
} else if (this.isPressed()
&& this.getSpritesheet().getTotalNumberOfSprites() > BACKGROUND_PRESSED_INDEX) {
spriteIndex = BACKGROUND_PRESSED_INDEX;
} else if (this.isHovered()
&& this.getSpritesheet().getTotalNumberOfSprites() > BACKGROUND_HOVER_INDEX) {
spriteIndex = BACKGROUND_HOVER_INDEX;
}
BufferedImage img =
Imaging.scale(
this.getSpritesheet().getSprite(spriteIndex),
(int) this.getWidth(),
(int) this.getHeight());
if (img != null) {
Resources.images().add(cacheKey, img);
}
return img;
}
public void rescaleImage() {
if (this.baseImage == null) {
return;
}
int imageWidth = (int) this.getWidth();
int imageHeight = (int) this.getHeight();
boolean keepRatio;
switch (this.getImageScaleMode()) {
case STRETCH:
keepRatio = false;
break;
case FIT:
keepRatio = true;
break;
default:
return;
}
final String cacheKey =
String.format("%s_%dx%d_%b", this.baseImage.hashCode(), imageWidth, imageHeight, keepRatio);
Optional<BufferedImage> opt = Resources.images().tryGet(cacheKey);
if (opt.isPresent()) {
this.scaledImage = opt.get();
return;
} else {
this.scaledImage = Imaging.scale(this.baseImage, imageWidth, imageHeight, keepRatio);
}
Resources.images().add(cacheKey, this.scaledImage);
}
public BufferedImage getImage() {
if (this.scaledImage == null) {
return this.baseImage;
}
return this.scaledImage;
}
public Align getImageAlign() {
return this.imageAlign;
}
public ImageScaleMode getImageScaleMode() {
return this.imageScaleMode;
}
public Valign getImageValign() {
return this.imageValign;
}
@Override
public void render(final Graphics2D g) {
if (this.isSuspended() || !this.isVisible()) {
return;
}
final Image bg = this.getBackground();
if (bg != null) {
ImageRenderer.render(g, bg, this.getLocation());
}
final BufferedImage img = this.getImage();
if (img != null) {
ImageRenderer.render(g, img, this.getImageLocation(img));
}
super.render(g);
}
public void setImage(final Image image) {
this.baseImage = (BufferedImage) image;
this.rescaleImage();
}
public void setImageScaleMode(ImageScaleMode imageScaleMode) {
this.imageScaleMode = imageScaleMode;
this.rescaleImage();
}
public void setSpriteSheet(final Spritesheet spr) {
this.spritesheet = spr;
}
public void setImageAlign(Align imageAlign) {
this.imageAlign = imageAlign;
}
public void setImageValign(Valign imageValign) {
this.imageValign = imageValign;
}
@Override
public void setHeight(double height) {
super.setHeight(height);
this.rescaleImage();
}
@Override
public void setWidth(double width) {
super.setWidth(width);
this.rescaleImage();
}
protected Spritesheet getSpritesheet() {
return this.spritesheet;
}
private Point2D getImageLocation(final Image img) {
double x = this.getX();
double y = this.getY();
if (this.getImageScaleMode() == ImageScaleMode.STRETCH) {
return new Point2D.Double(x, y);
}
if (this.getImageAlign() == Align.RIGHT) {
x = x + this.getWidth() - img.getWidth(null);
} else if (this.getImageAlign() == Align.CENTER) {
x = x + this.getWidth() / 2.0 - img.getWidth(null) / 2.0;
}
if (this.getImageValign() == Valign.DOWN) {
y = y + this.getHeight() - img.getHeight(null);
} else if (this.getImageValign() == Valign.MIDDLE) {
y = y + this.getHeight() / 2.0 - img.getHeight(null) / 2.0;
}
return new Point2D.Double(x, y);
}
}
| 28.614458 | 101 | 0.631018 |
6fa8428495b99e4e1068e4c9f382e9de02d5f2b8 | 1,634 | package edu.psu.sweng500.emrms.mappers;
import edu.psu.sweng500.emrms.model.HEncounter;
import edu.psu.sweng500.emrms.model.HPatient;
import java.util.ArrayList;
import java.util.List;
public class LocallyCachedPatientMapper implements PatientMapper {
List<HPatient> patientList;
public LocallyCachedPatientMapper() {
patientList = new ArrayList<>();
}
@Override
public List<HPatient> readAll() {
return patientList;
}
@Override
public void deleteAll() {
patientList.clear();
}
@Override
public void create() {
patientList.add(new HPatient());
}
@Override
public void insertPatient(HPatient patient) {
patientList.add(new HPatient());
}
@Override
public void insertEncounterDetails(HEncounter hEncounter) {
// TODO Auto-generated method stub
}
@Override
public void insertPerson(HPatient patient) {
// TODO Auto-generated method stub
}
@Override
public void insertPatientName(HPatient patient) {
// TODO Auto-generated method stub
}
@Override
public void insertPatientAddress(HPatient patient) {
// TODO Auto-generated method stub
}
@Override
public void revisePerson(HPatient patient) throws Exception {
}
@Override
public void revisePersonName(HPatient patient) throws Exception {
}
@Override
public void revisePersonAddress(HPatient patient) throws Exception {
}
@Override
public void insertPatientIdentifiers(HPatient patient) {
// TODO Auto-generated method stub
}
}
| 19.686747 | 72 | 0.669523 |
047fe748c1ffa3d9a5191fefa27b5ca1e35a8391 | 822 | /**
* Eleventh Java example program.
*
* @version 1.0 6th of June, 2019
* @author Amurita
*/
package de.amurita.chaptertwo;
// Class to show differences between Remainder and Division
public class RemainderAndDivDemo {
// Print different Remainder and Division results
public static void main ( String [] args ) {
System.out.println( "+5% +3 = " + (+5% +3) ); // 2
System.out.println( "+5 / +3 = " + (+5 / +3) ); // 1
System.out.println( "+5% -3 = " + (+5% -3) ); // 2
System.out.println( "+5 / -3 = " + (+5 / -3) ); // -1
System.out.println( "-5% +3 = " + (-5% +3) ); // -2
System.out.println( "-5 / +3 = " + (-5 / +3) ); // -1
System.out.println( "-5% -3 = " + (-5% -3) ); // -2
System.out.println( "-5 / -3 = " + (-5 / -3) ); // 1
}
}
| 32.88 | 61 | 0.492701 |
e810bbdc332c626c9f5aa301f24fa87fb8fb5ace | 7,714 | package com.github.mx.bizlog.aop;
import com.github.mx.bizlog.bean.LogOps;
import com.github.mx.bizlog.bean.LogRecord;
import com.github.mx.bizlog.context.BizLog;
import com.github.mx.bizlog.context.LogContext;
import com.github.mx.bizlog.extend.LogOperator;
import com.github.mx.bizlog.extend.LogPersistence;
import com.github.mx.bizlog.extend.defaults.DefaultLogOperator;
import com.github.mx.bizlog.parser.LogValueParser;
import com.github.mx.bizlog.util.LogHelper;
import com.github.mx.nacos.config.core.ConfigFactory;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.aop.framework.AopProxyUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.CollectionUtils;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
* Create by max on 2021/02/27
**/
@Slf4j
public class LogInterceptor extends LogValueParser implements InitializingBean, MethodInterceptor, Serializable {
private static final long serialVersionUID = -8123862383945755569L;
@Getter
@Setter
private transient LogOperationSource logOperationSource;
private transient LogPersistence logPersistence;
private transient LogOperator logOperator;
@Override
public void afterPropertiesSet() {
logPersistence = beanFactory.getBean(LogPersistence.class);
logOperator = beanFactory.getBean(LogOperator.class);
Preconditions.checkNotNull(logPersistence, "logPersistence not null");
BizLog.setLogPersistence(logPersistence);
}
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
Method method = invocation.getMethod();
return execute(invocation, invocation.getThis(), method, invocation.getArguments());
}
private Object execute(MethodInvocation invoker, Object target, Method method, Object[] args) throws Throwable {
Class<?> targetClass = getTargetClass(target);
Object ret = null;
boolean success = true;
String errorMsg = "";
Throwable throwable = null;
LocalDateTime startTime = LocalDateTime.now();
try {
LogContext.putEmptySpan();
ret = invoker.proceed();
} catch (Exception e) {
success = false;
String stackTrace = ExceptionUtils.getStackTrace(e);
errorMsg = stackTrace.substring(0, Math.min(stackTrace.length(), 1024)) + "...";
throwable = e;
} finally {
LocalDateTime endTime = LocalDateTime.now();
// 处理及记录日志
processLog(method, args, targetClass, ret, success, errorMsg, startTime, endTime);
LogContext.clear();
}
if (throwable != null) {
throw throwable;
}
return ret;
}
private Class<?> getTargetClass(Object target) {
return AopProxyUtils.ultimateTargetClass(target);
}
private void processLog(Method method, Object[] args, Class<?> targetClass, Object ret, boolean success,
String errorMsg, LocalDateTime startTime, LocalDateTime endTime) {
try {
Collection<LogOps> operations = getLogOperationSource().computeLogOperations(method, targetClass);
if (!CollectionUtils.isEmpty(operations)) {
recordLog(ret, method, args, operations, targetClass, success, errorMsg, startTime, endTime);
}
} catch (Exception e) {
//记录日志错误不要影响业务
log.error("process log record parse exception", e);
}
}
private void recordLog(Object ret, Method method, Object[] args, Collection<LogOps> operations, Class<?> targetClass,
boolean success, String errorMsg, LocalDateTime startTime, LocalDateTime endTime) {
for (LogOps logOps : operations) {
try {
String action = success ? logOps.getSuccessLogTemplate() : logOps.getFailLogTemplate();
if (StringUtils.isNotEmpty(logOps.getBizId())) {
LogRecord logRecord = this.wrapper(ret, method, args, targetClass, success, errorMsg, logOps, action, startTime, endTime);
if (Objects.nonNull(logRecord)) {
Preconditions.checkNotNull(logPersistence, "logPersistence not init!!");
this.logPersistence.log(logRecord);
}
}
} catch (Exception e) {
log.error("log record execute exception", e);
}
}
}
private LogRecord wrapper(Object ret, Method method, Object[] args, Class<?> targetClass, boolean success,
String errorMsg, LogOps logOps, String action, LocalDateTime startTime, LocalDateTime endTime) {
String bizId = logOps.getBizId();
String title = logOps.getTitle();
String logType = logOps.getLogType().name();
String operatorId = logOps.getOperatorId();
String category = logOps.getCategory();
String detail = logOps.getDetail();
String content = logOps.getContent();
String condition = logOps.getCondition();
//获取需要解析的表达式
List<String> spElTemplates;
String realOperator = "";
if (StringUtils.isEmpty(operatorId) || DefaultLogOperator.DEFAULT_OPERATOR_ID.equalsIgnoreCase(operatorId)) {
spElTemplates = Lists.newArrayList(title, bizId, action, category, detail, content);
if (StringUtils.isEmpty(logOperator.getOperatorId())) {
log.warn("operatorId is null");
}
realOperator = logOperator.getOperatorId();
} else {
spElTemplates = Lists.newArrayList(title, bizId, action, category, content, detail, operatorId);
}
if (!StringUtils.isEmpty(condition)) {
spElTemplates.add(condition);
}
Map<String, String> expressionValues = processTemplate(spElTemplates, ret, targetClass, method, args, errorMsg);
action = (success && ret == null) ? StringUtils.EMPTY : action;
if (!conditionPassed(condition, expressionValues)) {
return null;
}
return LogRecord.builder()
.appName(ConfigFactory.getApplicationName())
.title(expressionValues.get(title))
.logType(logType)
.bizId(expressionValues.get(bizId))
.success(success)
.category(expressionValues.get(category))
.action(expressionValues.get(action))
.detail(expressionValues.get(detail))
.content(expressionValues.get(content))
.operatorId(StringUtils.isNotEmpty(realOperator) ? realOperator : expressionValues.get(operatorId))
.startTime(LogHelper.localDateTime2Stamp(startTime))
.endTime(LogHelper.localDateTime2Stamp(endTime))
.createTime(LogHelper.localDateTime2Stamp(LocalDateTime.now()))
.build();
}
private boolean conditionPassed(String condition, Map<String, String> expressionValues) {
return StringUtils.isEmpty(condition) || StringUtils.endsWithIgnoreCase(expressionValues.get(condition), "true");
}
} | 43.829545 | 142 | 0.661913 |
bb56f2847814accf949c75d502c7ae18cc8978f7 | 1,158 | /*
* 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.openejb.api.resource;
/**
* Called to setup a service/resource.
*
* It is called at the very beginning of resource configuration (ie before provider are resolved)
* so the resource can be fully configured.
*
* @param <T> Service or AbstractService or Resource.
*/
public interface Template<T> {
void configure(T resource);
}
| 38.6 | 97 | 0.748705 |
5da1df9ad1b6fa1e3947bd4d89737bb37af3b6cb | 820 | /*Given 2 int values, return whichever value is nearest to the value 10, or return 0 in the event of a tie.
Note that Math.abs(n) returns the absolute value of a number.
close10(8, 13) → 8
close10(13, 8) → 8
close10(13, 7) → 0
*/
public class close10 {
public static void main(String[] args) {
int output=close10(8,13);
System.out.println(output);
int output1=close10(13,8);
System.out.println(output1);
int output2=close10(13,7);
System.out.println(output2);
int output3=close10(11,11);
System.out.println(output3);
}
public static int close10(int a, int b){
if (Math.abs(a-10) < Math.abs(b-10))
return a;
else if (Math.abs(a-10) > Math.abs(b-10))
return b;
else
return 0;
}
}
| 29.285714 | 107 | 0.590244 |
55ec43ebc727e65a89f3e20ec61aba1fb98031b0 | 15,140 | /**
* 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.hive.beeline;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
import junit.framework.TestCase;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.metastore.HiveMetaException;
import org.apache.hadoop.hive.metastore.MetaStoreSchemaInfo;
import org.apache.hive.beeline.HiveSchemaHelper;
import org.apache.hive.beeline.HiveSchemaHelper.NestedScriptParser;
import org.apache.hive.beeline.HiveSchemaHelper.PostgresCommandParser;
import org.apache.hive.beeline.HiveSchemaTool;
public class TestSchemaTool extends TestCase {
private HiveSchemaTool schemaTool;
private HiveConf hiveConf;
private String testMetastoreDB;
@Override
protected void setUp() throws Exception {
super.setUp();
testMetastoreDB = System.getProperty("java.io.tmpdir") +
File.separator + "test_metastore-" + new Random().nextInt();
System.setProperty(HiveConf.ConfVars.METASTORECONNECTURLKEY.varname,
"jdbc:derby:" + testMetastoreDB + ";create=true");
hiveConf = new HiveConf(this.getClass());
schemaTool = new HiveSchemaTool(System.getProperty("test.tmp.dir"), hiveConf, "derby");
System.setProperty("beeLine.system.exit", "true");
}
@Override
protected void tearDown() throws Exception {
File metaStoreDir = new File(testMetastoreDB);
if (metaStoreDir.exists()) {
FileUtils.deleteDirectory(metaStoreDir);
}
}
/**
* Test dryrun of schema initialization
* @throws Exception
*/
public void testSchemaInitDryRun() throws Exception {
schemaTool.setDryRun(true);
schemaTool.doInit("0.7.0");
schemaTool.setDryRun(false);
try {
schemaTool.verifySchemaVersion();
} catch (HiveMetaException e) {
// The connection should fail since it the dry run
return;
}
fail("Dry run shouldn't create actual metastore");
}
/**
* Test dryrun of schema upgrade
* @throws Exception
*/
public void testSchemaUpgradeDryRun() throws Exception {
schemaTool.doInit("0.7.0");
schemaTool.setDryRun(true);
schemaTool.doUpgrade("0.7.0");
schemaTool.setDryRun(false);
try {
schemaTool.verifySchemaVersion();
} catch (HiveMetaException e) {
// The connection should fail since it the dry run
return;
}
fail("Dry run shouldn't upgrade metastore schema");
}
/**
* Test schema initialization
* @throws Exception
*/
public void testSchemaInit() throws Exception {
schemaTool.doInit(MetaStoreSchemaInfo.getHiveSchemaVersion());
schemaTool.verifySchemaVersion();
}
/**
* Test schema upgrade
* @throws Exception
*/
public void testSchemaUpgrade() throws Exception {
boolean foundException = false;
// Initialize 0.7.0 schema
schemaTool.doInit("0.7.0");
// verify that driver fails due to older version schema
try {
schemaTool.verifySchemaVersion();
} catch (HiveMetaException e) {
// Expected to fail due to old schema
foundException = true;
}
if (!foundException) {
throw new Exception("Hive operations shouldn't pass with older version schema");
}
// upgrade schema from 0.7.0 to latest
schemaTool.doUpgrade("0.7.0");
// verify that driver works fine with latest schema
schemaTool.verifySchemaVersion();
}
/**
* Test script formatting
* @throws Exception
*/
public void testScripts() throws Exception {
String testScript[] = {
"-- this is a comment",
"DROP TABLE IF EXISTS fooTab;",
"/*!1234 this is comment code like mysql */;",
"CREATE TABLE fooTab(id INTEGER);",
"DROP TABLE footab;",
"-- ending comment"
};
String resultScript[] = {
"DROP TABLE IF EXISTS fooTab",
"/*!1234 this is comment code like mysql */",
"CREATE TABLE fooTab(id INTEGER)",
"DROP TABLE footab",
};
String expectedSQL = StringUtils.join(resultScript, System.getProperty("line.separator")) +
System.getProperty("line.separator");
File testScriptFile = generateTestScript(testScript);
String flattenedSql = HiveSchemaTool.buildCommand(
HiveSchemaHelper.getDbCommandParser("derby"),
testScriptFile.getParentFile().getPath(), testScriptFile.getName());
assertEquals(expectedSQL, flattenedSql);
}
/**
* Test nested script formatting
* @throws Exception
*/
public void testNestedScriptsForDerby() throws Exception {
String childTab1 = "childTab1";
String childTab2 = "childTab2";
String parentTab = "fooTab";
String childTestScript1[] = {
"-- this is a comment ",
"DROP TABLE IF EXISTS " + childTab1 + ";",
"CREATE TABLE " + childTab1 + "(id INTEGER);",
"DROP TABLE " + childTab1 + ";"
};
String childTestScript2[] = {
"-- this is a comment",
"DROP TABLE IF EXISTS " + childTab2 + ";",
"CREATE TABLE " + childTab2 + "(id INTEGER);",
"-- this is also a comment",
"DROP TABLE " + childTab2 + ";"
};
String parentTestScript[] = {
" -- this is a comment",
"DROP TABLE IF EXISTS " + parentTab + ";",
" -- this is another comment ",
"CREATE TABLE " + parentTab + "(id INTEGER);",
"RUN '" + generateTestScript(childTestScript1).getName() + "';",
"DROP TABLE " + parentTab + ";",
"RUN '" + generateTestScript(childTestScript2).getName() + "';",
"--ending comment ",
};
File testScriptFile = generateTestScript(parentTestScript);
String flattenedSql = HiveSchemaTool.buildCommand(
HiveSchemaHelper.getDbCommandParser("derby"),
testScriptFile.getParentFile().getPath(), testScriptFile.getName());
assertFalse(flattenedSql.contains("RUN"));
assertFalse(flattenedSql.contains("comment"));
assertTrue(flattenedSql.contains(childTab1));
assertTrue(flattenedSql.contains(childTab2));
assertTrue(flattenedSql.contains(parentTab));
}
/**
* Test nested script formatting
* @throws Exception
*/
public void testNestedScriptsForMySQL() throws Exception {
String childTab1 = "childTab1";
String childTab2 = "childTab2";
String parentTab = "fooTab";
String childTestScript1[] = {
"/* this is a comment code */",
"DROP TABLE IF EXISTS " + childTab1 + ";",
"CREATE TABLE " + childTab1 + "(id INTEGER);",
"DROP TABLE " + childTab1 + ";"
};
String childTestScript2[] = {
"/* this is a special exec code */;",
"DROP TABLE IF EXISTS " + childTab2 + ";",
"CREATE TABLE " + childTab2 + "(id INTEGER);",
"-- this is a comment",
"DROP TABLE " + childTab2 + ";"
};
String parentTestScript[] = {
" -- this is a comment",
"DROP TABLE IF EXISTS " + parentTab + ";",
" /* this is special exec code */;",
"CREATE TABLE " + parentTab + "(id INTEGER);",
"SOURCE " + generateTestScript(childTestScript1).getName() + ";",
"DROP TABLE " + parentTab + ";",
"SOURCE " + generateTestScript(childTestScript2).getName() + ";",
"--ending comment ",
};
File testScriptFile = generateTestScript(parentTestScript);
String flattenedSql = HiveSchemaTool.buildCommand(
HiveSchemaHelper.getDbCommandParser("mysql"),
testScriptFile.getParentFile().getPath(), testScriptFile.getName());
assertFalse(flattenedSql.contains("RUN"));
assertFalse(flattenedSql.contains("comment"));
assertTrue(flattenedSql.contains(childTab1));
assertTrue(flattenedSql.contains(childTab2));
assertTrue(flattenedSql.contains(parentTab));
}
/**
* Test script formatting
* @throws Exception
*/
public void testScriptWithDelimiter() throws Exception {
String testScript[] = {
"-- this is a comment",
"DROP TABLE IF EXISTS fooTab;",
"DELIMITER $$",
"/*!1234 this is comment code like mysql */$$",
"CREATE TABLE fooTab(id INTEGER)$$",
"CREATE PROCEDURE fooProc()",
"SELECT * FROM fooTab;",
"CALL barProc();",
"END PROCEDURE$$",
"DELIMITER ;",
"DROP TABLE footab;",
"-- ending comment"
};
String resultScript[] = {
"DROP TABLE IF EXISTS fooTab",
"/*!1234 this is comment code like mysql */",
"CREATE TABLE fooTab(id INTEGER)",
"CREATE PROCEDURE fooProc()" + " " +
"SELECT * FROM fooTab;" + " " +
"CALL barProc();" + " " +
"END PROCEDURE",
"DROP TABLE footab",
};
String expectedSQL = StringUtils.join(resultScript, System.getProperty("line.separator")) +
System.getProperty("line.separator");
File testScriptFile = generateTestScript(testScript);
NestedScriptParser testDbParser = HiveSchemaHelper.getDbCommandParser("mysql");
String flattenedSql = HiveSchemaTool.buildCommand(testDbParser,
testScriptFile.getParentFile().getPath(), testScriptFile.getName());
assertEquals(expectedSQL, flattenedSql);
}
/**
* Test script formatting
* @throws Exception
*/
public void testScriptMultiRowComment() throws Exception {
String testScript[] = {
"-- this is a comment",
"DROP TABLE IF EXISTS fooTab;",
"DELIMITER $$",
"/*!1234 this is comment code like mysql */$$",
"CREATE TABLE fooTab(id INTEGER)$$",
"DELIMITER ;",
"/* multiline comment started ",
" * multiline comment continue",
" * multiline comment ended */",
"DROP TABLE footab;",
"-- ending comment"
};
String parsedScript[] = {
"DROP TABLE IF EXISTS fooTab",
"/*!1234 this is comment code like mysql */",
"CREATE TABLE fooTab(id INTEGER)",
"DROP TABLE footab",
};
String expectedSQL = StringUtils.join(parsedScript, System.getProperty("line.separator")) +
System.getProperty("line.separator");
File testScriptFile = generateTestScript(testScript);
NestedScriptParser testDbParser = HiveSchemaHelper.getDbCommandParser("mysql");
String flattenedSql = HiveSchemaTool.buildCommand(testDbParser,
testScriptFile.getParentFile().getPath(), testScriptFile.getName());
assertEquals(expectedSQL, flattenedSql);
}
/**
* Test nested script formatting
* @throws Exception
*/
public void testNestedScriptsForOracle() throws Exception {
String childTab1 = "childTab1";
String childTab2 = "childTab2";
String parentTab = "fooTab";
String childTestScript1[] = {
"-- this is a comment ",
"DROP TABLE IF EXISTS " + childTab1 + ";",
"CREATE TABLE " + childTab1 + "(id INTEGER);",
"DROP TABLE " + childTab1 + ";"
};
String childTestScript2[] = {
"-- this is a comment",
"DROP TABLE IF EXISTS " + childTab2 + ";",
"CREATE TABLE " + childTab2 + "(id INTEGER);",
"-- this is also a comment",
"DROP TABLE " + childTab2 + ";"
};
String parentTestScript[] = {
" -- this is a comment",
"DROP TABLE IF EXISTS " + parentTab + ";",
" -- this is another comment ",
"CREATE TABLE " + parentTab + "(id INTEGER);",
"@" + generateTestScript(childTestScript1).getName() + ";",
"DROP TABLE " + parentTab + ";",
"@" + generateTestScript(childTestScript2).getName() + ";",
"--ending comment ",
};
File testScriptFile = generateTestScript(parentTestScript);
String flattenedSql = HiveSchemaTool.buildCommand(
HiveSchemaHelper.getDbCommandParser("oracle"),
testScriptFile.getParentFile().getPath(), testScriptFile.getName());
assertFalse(flattenedSql.contains("@"));
assertFalse(flattenedSql.contains("comment"));
assertTrue(flattenedSql.contains(childTab1));
assertTrue(flattenedSql.contains(childTab2));
assertTrue(flattenedSql.contains(parentTab));
}
/**
* Test script formatting
* @throws Exception
*/
public void testPostgresFilter() throws Exception {
String testScript[] = {
"-- this is a comment",
"DROP TABLE IF EXISTS fooTab;",
HiveSchemaHelper.PostgresCommandParser.POSTGRES_STRING_COMMAND_FILTER + ";",
"CREATE TABLE fooTab(id INTEGER);",
"DROP TABLE footab;",
"-- ending comment"
};
String resultScriptwithFilter[] = {
"DROP TABLE IF EXISTS fooTab",
HiveSchemaHelper.PostgresCommandParser.POSTGRES_STRING_COMMAND_FILTER,
"CREATE TABLE fooTab(id INTEGER)",
"DROP TABLE footab",
};
String resultScriptwithoutFilter[] = {
"DROP TABLE IF EXISTS fooTab",
"CREATE TABLE fooTab(id INTEGER)",
"DROP TABLE footab",
};
String expectedSQL = StringUtils.join(resultScriptwithFilter, System.getProperty("line.separator")) +
System.getProperty("line.separator");
File testScriptFile = generateTestScript(testScript);
String flattenedSql = HiveSchemaTool.buildCommand(
HiveSchemaHelper.getDbCommandParser("postgres"),
testScriptFile.getParentFile().getPath(), testScriptFile.getName());
assertEquals(expectedSQL, flattenedSql);
System.setProperty(HiveSchemaHelper.PostgresCommandParser.POSTGRES_SKIP_STANDARD_STRING, "true");
NestedScriptParser postgresParser = HiveSchemaHelper.getDbCommandParser("postgres");
postgresParser.setDbOpts(PostgresCommandParser.POSTGRES_SKIP_STANDARD_STRING);
expectedSQL = StringUtils.join(resultScriptwithoutFilter, System.getProperty("line.separator")) +
System.getProperty("line.separator");
testScriptFile = generateTestScript(testScript);
flattenedSql = HiveSchemaTool.buildCommand(
postgresParser,
testScriptFile.getParentFile().getPath(), testScriptFile.getName());
assertEquals(expectedSQL, flattenedSql);
}
private File generateTestScript(String [] stmts) throws IOException {
File testScriptFile = File.createTempFile("schematest", ".sql");
testScriptFile.deleteOnExit();
FileWriter fstream = new FileWriter(testScriptFile.getPath());
BufferedWriter out = new BufferedWriter(fstream);
for (String line: stmts) {
out.write(line);
out.newLine();
}
out.close();
return testScriptFile;
}
}
| 34.965358 | 105 | 0.662153 |
ad6499f27f372a234acab74e7a57bdaea21fa65c | 18,977 | /*
* This is the source code of Telegram for Android v. 1.4.x.
* It is licensed under GNU GPL v. 2 or later.
* You should have received a copy of the license in this archive (see LICENSE).
*
* Copyright Nikolai Kudashov, 2013-2014.
*/
package com.yahala.ui;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import com.yahala.android.OSUtilities;
import com.yahala.messenger.R;
import com.yahala.messenger.FileLog;
import com.yahala.android.LocaleController;
import com.yahala.ui.Adapters.BaseFragmentAdapter;
import com.yahala.ui.Views.BaseFragment;
import com.yahala.ui.Views.ColorPickerView;
public class ProfileNotificationsActivity extends BaseFragment {
private ListView listView;
private String dialog_id;
private int settingsNotificationsRow;
private int settingsVibrateRow;
private int settingsSoundRow;
private int settingsLedRow;
private int rowCount = 0;
@Override
public void onFragmentDestroy() {
super.onFragmentDestroy();
}
@Override
public boolean onFragmentCreate() {
dialog_id = getArguments().getString("dialog_id");
FileLog.e("dialog_id", "" + dialog_id);
settingsNotificationsRow = rowCount++;
settingsVibrateRow = rowCount++;
settingsLedRow = rowCount++;
settingsSoundRow = rowCount++;
return super.onFragmentCreate();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (fragmentView == null) {
fragmentView = inflater.inflate(R.layout.settings_layout, container, false);
listView = (ListView) fragmentView.findViewById(R.id.listView);
listView.setAdapter(new ListAdapter(getParentActivity()));
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l) {
if (i == settingsVibrateRow || i == settingsNotificationsRow) {
if (getParentActivity() == null) {
return;
}
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
builder.setItems(new CharSequence[]{
LocaleController.getString("Default", R.string.Default),
LocaleController.getString("Enabled", R.string.Enabled),
LocaleController.getString("Disabled", R.string.Disabled)
}, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
if (i == settingsVibrateRow) {
editor.putInt("vibrate_" + dialog_id, which);
} else if (i == settingsNotificationsRow) {
editor.putInt("notify2_" + dialog_id, which);
}
editor.commit();
if (listView != null) {
listView.invalidateViews();
}
}
});
builder.setNegativeButton(LocaleController.getString("Cancel", R.string.Cancel), null);
showAlertDialog(builder);
} else if (i == settingsSoundRow) {
try {
Intent tmpIntent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
tmpIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE, RingtoneManager.TYPE_NOTIFICATION);
tmpIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, true);
// tmpIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_TITLE, "Yahala Incoming Message");
tmpIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_DEFAULT_URI, RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
/* */
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
Uri currentSound = null;
String defaultPath = null;
Uri defaultUri = OSUtilities.getMediaUri("Yahala Incoming Message");//Settings.System.DEFAULT_NOTIFICATION_URI;
if (defaultUri != null) {
defaultPath = defaultUri.getPath();
}
FileLog.d("content://media/external/audio/media/", defaultUri.getPath());
String path = preferences.getString("sound_path_" + dialog_id, defaultPath);
if (path != null && !path.equals("NoSound")) {
if (path.equals(defaultPath)) {
currentSound = defaultUri;
} else {
currentSound = Uri.parse(path);
}
}
tmpIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, currentSound);
startActivityForResult(tmpIntent, 0);
} catch (Exception e) {
FileLog.e("tmessages", e);
}
} else if (i == settingsLedRow) {
if (getParentActivity() == null) {
return;
}
LayoutInflater li = (LayoutInflater) getParentActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = li.inflate(R.layout.settings_color_dialog_layout, null, false);
final ColorPickerView colorPickerView = (ColorPickerView) view.findViewById(R.id.color_picker);
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
if (preferences.contains("color_" + dialog_id)) {
colorPickerView.setOldCenterColor(preferences.getInt("color_" + dialog_id, 0xff00ff00));
} else {
/* if ((int)dialog_id < 0) {
colorPickerView.setOldCenterColor(preferences.getInt("GroupLed", 0xff00ff00));
} else {*/
colorPickerView.setOldCenterColor(preferences.getInt("MessagesLed", 0xff00ff00));
//}
}
AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
builder.setTitle(LocaleController.getString("LedColor", R.string.LedColor));
builder.setView(view);
builder.setPositiveButton(LocaleController.getString("Set", R.string.Set), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int which) {
final SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("color_" + dialog_id, colorPickerView.getColor());
editor.commit();
listView.invalidateViews();
}
});
builder.setNeutralButton(LocaleController.getString("Disabled", R.string.Disabled), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
final SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("color_" + dialog_id, 0);
editor.commit();
listView.invalidateViews();
}
});
builder.setNegativeButton(LocaleController.getString("Default", R.string.Default), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
final SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.remove("color_" + dialog_id);
editor.commit();
listView.invalidateViews();
}
});
showAlertDialog(builder);
}
}
});
} else {
ViewGroup parent = (ViewGroup) fragmentView.getParent();
if (parent != null) {
parent.removeView(fragmentView);
}
}
return fragmentView;
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (data == null) {
return;
}
Uri ringtone = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
String name = null;
if (ringtone != null) {
Ringtone rng = RingtoneManager.getRingtone(ApplicationLoader.applicationContext, ringtone);
if (rng != null) {
if (ringtone.equals(Settings.System.DEFAULT_NOTIFICATION_URI)) {
name = LocaleController.getString("Default", R.string.Default);
} else {
name = rng.getTitle(getParentActivity());
}
rng.stop();
}
}
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
FileLog.e("name", name);
if (requestCode == 0) {
if (name != null && ringtone != null) {
editor.putString("sound_" + dialog_id, name);
editor.putString("sound_path_" + dialog_id, ringtone.toString());
} else {
editor.putString("sound_" + dialog_id, "NoSound");
editor.putString("sound_path_" + dialog_id, "NoSound");
}
}
editor.commit();
listView.invalidateViews();
}
}
private class ListAdapter extends BaseFragmentAdapter {
private Context mContext;
public ListAdapter(Context context) {
mContext = context;
}
@Override
public boolean areAllItemsEnabled() {
return true;
}
@Override
public boolean isEnabled(int i) {
return true;
}
@Override
public int getCount() {
return rowCount;
}
@Override
public Object getItem(int i) {
return null;
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public boolean hasStableIds() {
return false;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
int type = getItemViewType(i);
if (type == 0) {
if (view == null) {
LayoutInflater li = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = li.inflate(R.layout.user_profile_leftright_row_layout, viewGroup, false);
}
TextView textView = (TextView) view.findViewById(R.id.settings_row_text);
TextView detailTextView = (TextView) view.findViewById(R.id.settings_row_text_detail);
View divider = view.findViewById(R.id.settings_row_divider);
if (i == settingsVibrateRow) {
textView.setText(LocaleController.getString("Vibrate", R.string.Vibrate));
divider.setVisibility(View.VISIBLE);
SharedPreferences preferences = mContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
int value = preferences.getInt("vibrate_" + dialog_id, 0);
if (value == 0) {
detailTextView.setText(LocaleController.getString("Default", R.string.Default));
} else if (value == 1) {
detailTextView.setText(LocaleController.getString("Enabled", R.string.Enabled));
} else if (value == 2) {
detailTextView.setText(LocaleController.getString("Disabled", R.string.Disabled));
}
} else if (i == settingsNotificationsRow) {
textView.setText(LocaleController.getString("Notifications", R.string.Notifications));
divider.setVisibility(View.VISIBLE);
SharedPreferences preferences = mContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
int value = preferences.getInt("notify2_" + dialog_id, 0);
if (value == 0) {
detailTextView.setText(LocaleController.getString("Default", R.string.Default));
} else if (value == 1) {
detailTextView.setText(LocaleController.getString("Enabled", R.string.Enabled));
} else if (value == 2) {
detailTextView.setText(LocaleController.getString("Disabled", R.string.Disabled));
}
}
}
if (type == 1) {
if (view == null) {
LayoutInflater li = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = li.inflate(R.layout.settings_row_detail_layout, viewGroup, false);
}
TextView textView = (TextView) view.findViewById(R.id.settings_row_text);
TextView detailTextView = (TextView) view.findViewById(R.id.settings_row_text_detail);
View divider = view.findViewById(R.id.settings_row_divider);
if (i == settingsSoundRow) {
SharedPreferences preferences = mContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
String name = preferences.getString("sound_" + dialog_id, "Yahala Incoming Message" /*LocaleController.getString("Default", R.string.Default)*/);
if (name.equals("NoSound")) {
detailTextView.setText(LocaleController.getString("NoSound", R.string.NoSound));
} else {
detailTextView.setText(name);
}
textView.setText(LocaleController.getString("Sound", R.string.Sound));
divider.setVisibility(View.INVISIBLE);
}
} else if (type == 2) {
if (view == null) {
LayoutInflater li = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = li.inflate(R.layout.settings_row_color_layout, viewGroup, false);
}
TextView textView = (TextView) view.findViewById(R.id.settings_row_text);
View colorView = view.findViewById(R.id.settings_color);
View divider = view.findViewById(R.id.settings_row_divider);
textView.setText(LocaleController.getString("LedColor", R.string.LedColor));
SharedPreferences preferences = ApplicationLoader.applicationContext.getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
if (preferences.contains("color_" + dialog_id)) {
colorView.setBackgroundColor(preferences.getInt("color_" + dialog_id, 0xff00ff00));
} else {
/* if ((int)dialog_id < 0) {
colorView.setBackgroundColor(preferences.getInt("GroupLed", 0xff00ff00));
} else {*/
colorView.setBackgroundColor(preferences.getInt("MessagesLed", 0xff00ff00));
// }
}
divider.setVisibility(View.VISIBLE);
}
return view;
}
@Override
public int getItemViewType(int i) {
if (i == settingsNotificationsRow || i == settingsVibrateRow) {
return 0;
} else if (i == settingsSoundRow) {
return 1;
} else if (i == settingsLedRow) {
return 2;
}
return 0;
}
@Override
public int getViewTypeCount() {
return 3;
}
@Override
public boolean isEmpty() {
return false;
}
}
}
| 49.290909 | 168 | 0.547505 |
0fd1b2f8a28ae93d6bafc606c06455c2877dd700 | 803 | package bleserial;
import tinyb.BluetoothDevice;
public class BluetoothDeviceWrapper {
private final BluetoothDevice device;
public BluetoothDeviceWrapper(BluetoothDevice device) {
this.device = device;
}
public BluetoothDevice getDevice() {
return device;
}
@Override
public String toString() {
return device.getName();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
BluetoothDeviceWrapper that = (BluetoothDeviceWrapper) o;
return device != null ? device.equals(that.device) : that.device == null;
}
@Override
public int hashCode() {
return device != null ? device.hashCode() : 0;
}
}
| 21.702703 | 81 | 0.628892 |
044790eeb2ccf6d8e66b666c372fed5b76cb9477 | 9,339 | package org.codehaus.mojo.jaxb2.shared.version;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.codehaus.mojo.jaxb2.shared.Validate;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.StringTokenizer;
import java.util.TreeMap;
/**
* Trivial parser to handle depends-plugin-style files.
*
* @author <a href="mailto:lj@jguru.se">Lennart Jörelid</a>, jGuru Europe AB
* @since 2.0
*/
public final class DependsFileParser {
/**
* String indicating that a line in a dependencies.properties file contains a version definition.
*/
private static final String VERSION_LINE_INDICATOR = "/version";
/**
* String indicating that a line in a dependencies.properties file contains a type definition.
*/
private static final String TYPE_LINE_INDICATOR = "/type";
/**
* String indicating that a line in a dependencies.properties file contains a scope definition.
*/
private static final String SCOPE_LINE_INDICATOR = "/scope";
// Internal state
private static final String GROUP_ARTIFACT_SEPARATOR = "/";
private static final String KEY_VALUE_SEPARATOR = "=";
private static final String DEPENDENCIES_PROPERTIES_FILE = "META-INF/maven/dependencies.properties";
private static final String GENERATION_PREFIX = "# Generated at: ";
/**
* The key where the build time as found within the dependencies.properties file is found.
*/
public static final String BUILDTIME_KEY = "buildtime";
/**
* The key holding the artifactId of this plugin (within the dependencies.properties file).
*/
public static final String OWN_ARTIFACTID_KEY = "artifactId";
/**
* The key holding the groupId of this plugin (within the dependencies.properties file).
*/
public static final String OWN_GROUPID_KEY = "groupId";
/**
* The key holding the version of this plugin (within the dependencies.properties file).
*/
public static final String OWN_VERSION_KEY = "version";
/**
* Hide constructors for utility classes
*/
private DependsFileParser() {
}
/**
* Extracts all build-time dependency information from a dependencies.properties file
* embedded in this plugin's JAR.
*
* @param artifactId This plugin's artifactId.
* @return A SortedMap relating [groupId]/[artifactId] keys to DependencyInfo values.
* @throws java.lang.IllegalStateException if no artifact in the current Thread's context ClassLoader
* contained the supplied artifactNamePart.
*/
public static SortedMap<String, String> getVersionMap(final String artifactId) {
// Check sanity
Validate.notEmpty(artifactId, "artifactNamePart");
Exception extractionException = null;
try {
// Get the ClassLoader used
final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
final List<URL> manifestURLs = Collections.list(
contextClassLoader.getResources(DEPENDENCIES_PROPERTIES_FILE));
// Find the latest of the URLs matching, to cope with test-scope dependencies.
URL matching = null;
for (URL current : manifestURLs) {
if (current.toString().contains(artifactId)) {
matching = current;
}
}
if (matching != null) {
return getVersionMap(matching);
}
} catch (Exception e) {
extractionException = e;
}
// We should never wind up here ...
if (extractionException != null) {
throw new IllegalStateException("Could not read data from manifest.", extractionException);
} else {
throw new IllegalStateException("Found no manifest corresponding to artifact name snippet '"
+ artifactId + "'.");
}
}
/**
* Extracts all build-time dependency information from a dependencies.properties file
* embedded in this plugin's JAR.
*
* @param anURL The non-empty URL to a dependencies.properties file.
* @return A SortedMap holding all entries in the dependencies.properties file, plus its build
* time which is found under the {@code buildtime} key.
* @throws java.lang.IllegalStateException if no artifact in the current Thread's context ClassLoader
* contained the supplied artifactNamePart.
*/
public static SortedMap<String, String> getVersionMap(final URL anURL) {
// Check sanity
Validate.notNull(anURL, "anURL");
final SortedMap<String, String> toReturn = new TreeMap<String, String>();
try {
final BufferedReader in = new BufferedReader(new InputStreamReader(anURL.openStream()));
String aLine = null;
while ((aLine = in.readLine()) != null) {
final String trimmedLine = aLine.trim();
if (trimmedLine.contains(GENERATION_PREFIX)) {
toReturn.put(BUILDTIME_KEY, aLine.substring(GENERATION_PREFIX.length()));
} else if ("".equals(trimmedLine) || trimmedLine.startsWith("#")) {
// Empty lines and comments should be ignored.
continue;
} else if (trimmedLine.contains("=")) {
// Stash this for later use.
StringTokenizer tok = new StringTokenizer(trimmedLine, KEY_VALUE_SEPARATOR, false);
Validate.isTrue(tok.countTokens() == 2, "Found incorrect dependency.properties line ["
+ aLine + "]");
final String key = tok.nextToken().trim();
final String value = tok.nextToken().trim();
toReturn.put(key, value);
}
}
} catch (IOException e) {
throw new IllegalStateException("Could not parse dependency properties '" + anURL.toString() + "'", e);
}
// All done.
return toReturn;
}
/**
* Converts a SortedMap received from a {@code getVersionMap} call to hold DependencyInfo values,
* and keys on the form {@code groupId/artifactId}.
*
* @param versionMap A non-null Map, as received from a call to {@code getVersionMap}.
* @return a SortedMap received from a {@code getVersionMap} call to hold DependencyInfo values,
* and keys on the form {@code groupId/artifactId}.
*/
public static SortedMap<String, DependencyInfo> createDependencyInfoMap(
final SortedMap<String, String> versionMap) {
// Check sanity
Validate.notNull(versionMap, "anURL");
final SortedMap<String, DependencyInfo> toReturn = new TreeMap<String, DependencyInfo>();
// First, only find the version lines.
for (Map.Entry<String, String> current : versionMap.entrySet()) {
final String currentKey = current.getKey().trim();
if (currentKey.contains(VERSION_LINE_INDICATOR)) {
final StringTokenizer tok = new StringTokenizer(currentKey, GROUP_ARTIFACT_SEPARATOR, false);
Validate.isTrue(tok.countTokens() == 3, "Expected key on the form [groupId]"
+ GROUP_ARTIFACT_SEPARATOR + "[artifactId]" + VERSION_LINE_INDICATOR + ", but got ["
+ currentKey + "]");
final String groupId = tok.nextToken();
final String artifactId = tok.nextToken();
final DependencyInfo di = new DependencyInfo(groupId, artifactId, current.getValue());
toReturn.put(di.getGroupArtifactKey(), di);
}
}
for (Map.Entry<String, DependencyInfo> current : toReturn.entrySet()) {
final String currentKey = current.getKey();
final DependencyInfo di = current.getValue();
final String scope = versionMap.get(currentKey + SCOPE_LINE_INDICATOR);
final String type = versionMap.get(currentKey + TYPE_LINE_INDICATOR);
if (scope != null) {
di.setScope(scope);
}
if (type != null) {
di.setType(type);
}
}
// All done.
return toReturn;
}
}
| 38.432099 | 115 | 0.633473 |
bd680254022bc96fbad2d408e7fcdb56749b2caa | 2,833 | /*
* Copyright 1999-2019 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.chaosblade.exec.common.plugin;
import com.alibaba.chaosblade.exec.common.aop.PredicateResult;
import com.alibaba.chaosblade.exec.common.constant.ModelConstant;
import com.alibaba.chaosblade.exec.common.model.BaseModelSpec;
import com.alibaba.chaosblade.exec.common.model.Model;
import com.alibaba.chaosblade.exec.common.model.action.delay.DelayActionSpec;
import com.alibaba.chaosblade.exec.common.model.action.exception.ThrowCustomExceptionActionSpec;
import com.alibaba.chaosblade.exec.common.model.action.exception.ThrowDeclaredExceptionActionSpec;
import com.alibaba.chaosblade.exec.common.model.action.returnv.ReturnValueActionSpec;
/**
* @author Changjun Xiao
*/
public class MethodModelSpec extends BaseModelSpec {
public MethodModelSpec() {
addThrowExceptionActionDef();
addReturnValueAction();
addDelayAction();
addMethodMatcherDef();
}
private void addDelayAction() {
addActionSpec(new DelayActionSpec());
}
private void addReturnValueAction() {
ReturnValueActionSpec returnValueActionSpec = new ReturnValueActionSpec();
addActionSpec(returnValueActionSpec);
}
private void addMethodMatcherDef() {
addMatcherDefToAllActions(new ClassNameMatcherSpec());
addMatcherDefToAllActions(new MethodNameMatcherSpec(true));
}
private void addThrowExceptionActionDef() {
ThrowCustomExceptionActionSpec throwCustomExceptionActionDef = new ThrowCustomExceptionActionSpec();
ThrowDeclaredExceptionActionSpec throwDeclaredExceptionActionDef = new ThrowDeclaredExceptionActionSpec();
addActionSpec(throwCustomExceptionActionDef);
addActionSpec(throwDeclaredExceptionActionDef);
}
@Override
protected PredicateResult preMatcherPredicate(Model matcherSpecs) {
return PredicateResult.success();
}
@Override
public String getTarget() {
return ModelConstant.JVM_TARGET;
}
@Override
public String getShortDesc() {
return "method";
}
@Override
public String getLongDesc() {
return "method";
}
@Override
public String getExample() {
return "method";
}
}
| 32.94186 | 114 | 0.742323 |
35f300bfa01f8ce99ef25a38f418dc1b8011af08 | 630 | package no.nav.aura.appconfig.security;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Spnego extends Login {
@XmlAttribute
private String ldapResourceAlias = "ldap";
@XmlAttribute
private String fallbackLoginPagePath;
public String getLdapResourceAlias() {
return ldapResourceAlias;
}
public String getFallbackLoginPagePath() {
return fallbackLoginPagePath;
}
}
| 25.2 | 49 | 0.769841 |
3c67ee7e19875701b354cf204eeea3cd9fb32e89 | 1,408 | package com.simibubi.create.content.curiosities.tools;
import me.pepperbell.simplenetworking.C2SPacket;
import me.pepperbell.simplenetworking.SimpleChannel;
import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.network.PacketBuffer;
import net.minecraft.network.play.ServerPlayNetHandler;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.ResourceLocation;
public class BlueprintAssignCompleteRecipePacket implements C2SPacket {
private ResourceLocation recipeID;
protected BlueprintAssignCompleteRecipePacket() {}
public BlueprintAssignCompleteRecipePacket(ResourceLocation recipeID) {
this.recipeID = recipeID;
}
@Override
public void read(PacketBuffer buffer) {
recipeID = buffer.readResourceLocation();
}
@Override
public void write(PacketBuffer buffer) {
buffer.writeResourceLocation(recipeID);
}
@Override
public void handle(MinecraftServer server, ServerPlayerEntity player, ServerPlayNetHandler handler, SimpleChannel.ResponseTarget responseTarget) {
server
.execute(() -> {
if (player == null)
return;
if (player.openContainer instanceof BlueprintContainer) {
BlueprintContainer c = (BlueprintContainer) player.openContainer;
player.getServerWorld()
.getRecipeManager()
.getRecipe(recipeID)
.ifPresent(r -> BlueprintItem.assignCompleteRecipe(c.ghostInventory, r));
}
});
}
}
| 29.333333 | 147 | 0.786932 |
f5c3d6c98191ee257e9e9d72c17bea30cdcf3095 | 5,115 | package paul.smash.display;
import java.awt.Canvas;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.Timer;
import paul.smash.framework.GameObject;
import paul.smash.framework.KeyboardInput;
import paul.smash.framework.ObjectType;
import paul.smash.framework.PlayerType;
import paul.smash.framework.StageType;
import paul.smash.objects.Platform;
import paul.smash.objects.Player;
public class Game extends Canvas implements Runnable {
private boolean running = false;
private Stage stage;
public static int HEIGHT;
public static int WIDTH;
private Helper helper;
private static final int INTERVAL = 35;
public int count = 0;
private PlayerType characterOne;
private PlayerType characterTwo;
private int playerOneWidth;
private int playerTwoWidth;
private int playerOneHeight;
private int playerTwoHeight;
private Player playerOne;
private Player playerTwo;
private Hud hudOne;
private Hud hudTwo;
private boolean gameOver;
private void initialize() {
// Define dimensions for characters in the game
switch (characterOne) {
case KIRBY:
playerOneWidth = 32;
playerOneHeight = 32;
break;
case PIKACHU:
playerOneWidth = 32;
playerOneHeight = 32;
break;
case GANONDORF:
playerOneWidth = 32;
playerOneHeight = 64;
break;
case MARIO:
playerOneWidth = 32;
playerOneHeight = 50;
break;
}
switch (characterTwo) {
case KIRBY:
playerTwoWidth = 32;
playerTwoHeight = 32;
break;
case PIKACHU:
playerTwoWidth = 32;
playerTwoHeight = 32;
break;
case GANONDORF:
playerTwoWidth = 32;
playerTwoHeight = 64;
break;
case MARIO:
playerTwoWidth = 32;
playerTwoHeight = 50;
break;
}
WIDTH = getWidth();
HEIGHT = getHeight();
// helper = new Helper();
for (Platform p : stage.platforms) {
helper.addObject(p);
}
playerOne = new Player(340, 0, playerOneWidth, playerOneHeight, helper, ObjectType.PLAYER_ONE, characterOne);
playerTwo = new Player(420, 0, playerTwoWidth, playerTwoHeight, helper, ObjectType.PLAYER_TWO, characterTwo);
helper.addObject(playerOne);
helper.addObject(playerTwo);
hudOne = new Hud(100, 395, 150, 150, playerOne); // y was 365
hudTwo = new Hud(528, 395, 150, 150, playerTwo);
helper.addObject(hudOne);
helper.addObject(hudTwo);
}
public int getPlayerTwoHeight() {
return playerTwoHeight;
}
public void setPlayerTwoHeight(int playerTwoHeight) {
this.playerTwoHeight = playerTwoHeight;
}
public PlayerType getCharacterOne() {
return characterOne;
}
public PlayerType getCharacterTwo() {
return characterTwo;
}
@Override
public void run() {
Graphics g = this.getGraphics();
// this.addKeyListener(new KeyboardInput(helper));
initialize();
this.addKeyListener(new KeyboardInput(helper));
Timer timer = new Timer(INTERVAL, new ActionListener() {
public void actionPerformed(ActionEvent e) {
count++;
helper.tick();
boolean playerOnHud = playerOne.getBounds().intersects(hudOne.getBounds())
|| playerOne.getBounds().intersects(hudTwo.getBounds())
|| playerTwo.getBounds().intersects(hudOne.getBounds())
|| playerTwo.getBounds().intersects(hudTwo.getBounds());
if (playerOnHud || playerOne.stockLost() || playerTwo.stockLost()) {
stage.showAgain();
hudOne.showAgain();
hudTwo.showAgain();
}
draw(g);
if (playerOne.getNumStocks() == 0 || playerTwo.getNumStocks() == 0) {
gameOver = true;
}
}
});
timer.start();
setFocusable(true); // THIS MAY NEED TO CHANGE LATER
}
public void start() {
this.run();
running = true;
}
public void draw(Graphics g) {
this.createBufferStrategy(4);
if (gameOver) {
try {
BufferedImage gameOver = ImageIO.read(new File("res/game_over.png"));
g.drawImage(gameOver, WIDTH / 2 - 250, 180, 600, 180, null );
} catch (IOException e) {
System.out.println("Internal Error:" + e.getMessage());
}
}
// Display the stage background image
else {
stage.show(g);
helper.draw(g);
hudOne.show(g);
hudTwo.show(g);
}
}
public static void main(String[] args) {
GameMenu m = new GameMenu(800, 578, "Super Smash Bros CIS 120 Main Menu");
while (true) {
if (m.getCharacterOne() != null && m.getCharacterTwo() != null && m.getStageType() != null
&& m.pressedStart()) {
new Window(800, 578, "Super Smash Bros CIS 120", m.getStageType(), m.getCharacterOne(),
m.getCharacterTwo());
break;
} else {
System.out.println("");
}
}
// SwingUtilities.invokeLater(new Game());
}
public void setStage(Stage stage) {
this.stage = stage;
}
public void setCharacterOne(PlayerType characterOne) {
this.characterOne = characterOne;
}
public void setCharacterTwo(PlayerType characterTwo) {
this.characterTwo = characterTwo;
}
public Helper getHelper() {
return this.helper;
}
public void setHelper(Helper helper) {
this.helper = helper;
}
}
| 23.901869 | 111 | 0.699902 |
a25a01d2d690a91f18ab546cb288a953ca730704 | 4,190 | package com.centit.app.cmipmodule.gwsp.entity;
import java.io.Serializable;
/**
* <一句话功能简述>
* @Description<功能详细描述>
*
* @author rqj
* @Version [版本号, 2015-9-15]
*/
/**
* <一句话功能简述>
*
* @Description<功能详细描述>
*
* @author rqj
* @Version [版本号, 2015-9-15]
*/
public class GWSPDetailBizDataResponse implements Serializable
{
/**
*
*/
private static final long serialVersionUID = 1L;
private String hid;
private String title;
private String createusername;
private String createdatetime;
private String modifydatetime;
private String handlestatus;
private String collectstatus;
private String did;
private String wfname;
/**
* 获取 hid
*
* @return 返回 hid
* @author rqj
*/
public String getHid()
{
return hid;
}
/**
* 设置 hid
*
* @param hid 对hid进行赋值
* @author rqj
*/
public void setHid(String hid)
{
this.hid = hid;
}
/**
* 获取 title
*
* @return 返回 title
* @author rqj
*/
public String getTitle()
{
return title;
}
/**
* 设置 title
*
* @param title 对title进行赋值
* @author rqj
*/
public void setTitle(String title)
{
this.title = title;
}
/**
* 获取 createusername
*
* @return 返回 createusername
* @author rqj
*/
public String getCreateusername()
{
return createusername;
}
/**
* 设置 createusername
*
* @param createusername 对createusername进行赋值
* @author rqj
*/
public void setCreateusername(String createusername)
{
this.createusername = createusername;
}
/**
* 获取 createdatetime
*
* @return 返回 createdatetime
* @author rqj
*/
public String getCreatedatetime()
{
return createdatetime;
}
/**
* 设置 createdatetime
*
* @param createdatetime 对createdatetime进行赋值
* @author rqj
*/
public void setCreatedatetime(String createdatetime)
{
this.createdatetime = createdatetime;
}
/**
* 获取 modifydatetime
*
* @return 返回 modifydatetime
* @author rqj
*/
public String getModifydatetime()
{
return modifydatetime;
}
/**
* 设置 modifydatetime
*
* @param modifydatetime 对modifydatetime进行赋值
* @author rqj
*/
public void setModifydatetime(String modifydatetime)
{
this.modifydatetime = modifydatetime;
}
/**
* 获取 handlestatus
*
* @return 返回 handlestatus
* @author rqj
*/
public String getHandlestatus()
{
return handlestatus;
}
/**
* 设置 handlestatus
*
* @param handlestatus 对handlestatus进行赋值
* @author rqj
*/
public void setHandlestatus(String handlestatus)
{
this.handlestatus = handlestatus;
}
/**
* 获取 collectstatus
*
* @return 返回 collectstatus
* @author rqj
*/
public String getCollectstatus()
{
return collectstatus;
}
/**
* 设置 collectstatus
*
* @param collectstatus 对collectstatus进行赋值
* @author rqj
*/
public void setCollectstatus(String collectstatus)
{
this.collectstatus = collectstatus;
}
/**
* 获取 did
*
* @return 返回 did
* @author rqj
*/
public String getDid()
{
return did;
}
/**
* 设置 did
*
* @param did 对did进行赋值
* @author rqj
*/
public void setDid(String did)
{
this.did = did;
}
/**
* 获取 wfname
*
* @return 返回 wfname
* @author rqj
*/
public String getWfname()
{
return wfname;
}
/**
* 设置 wfname
*
* @param wfname 对wfname进行赋值
* @author rqj
*/
public void setWfname(String wfname)
{
this.wfname = wfname;
}
}
| 17.102041 | 62 | 0.511217 |
50b06e1be41b365177de5f092f6df1f8bbeb6b13 | 955 | package org.sagebionetworks.web.client.jsinterop;
import jsinterop.annotations.JsFunction;
import jsinterop.annotations.JsNullable;
import jsinterop.annotations.JsOverlay;
import jsinterop.annotations.JsPackage;
import jsinterop.annotations.JsType;
@JsType(isNative = true, namespace = JsPackage.GLOBAL, name = "Object")
public class EntityModalProps extends ReactComponentProps {
@JsFunction
public interface Callback {
void run();
}
String entityId;
boolean show;
@JsNullable
Callback onClose;
@JsNullable
String initialTab; // "METADATA" | "ANNOTATIONS"
@JsNullable
boolean showTabs;
@JsOverlay
public static EntityModalProps create(String entityId, boolean show, Callback onClose, String initialTab, boolean showTabs) {
EntityModalProps props = new EntityModalProps();
props.entityId = entityId;
props.show = show;
props.onClose = onClose;
props.initialTab = initialTab;
props.showTabs = showTabs;
return props;
}
}
| 25.810811 | 126 | 0.781152 |
1feebe0e7a40954934213a8e849ca17c8625ccc7 | 1,273 | package com.study.medium.four.threeSumClosest;
import java.util.Arrays;
//16. 最接近的三数之和
//给你一个长度为 n 的整数数组 nums 和 一个目标值 target。请你从 nums 中选出三个整数,使它们的和与 target 最接近。
//返回这三个数的和。
//假定每组输入只存在恰好一个解。
//
//示例 1:
//输入:nums = [-1,2,1,-4], target = 1
//输出:2
//解释:与 target 最接近的和是 2 (-1 + 2 + 1 = 2) 。
//示例 2:
//输入:nums = [0,0,0], target = 1
//输出:0
//
//提示:
//3 <= nums.length <= 1000
//-1000 <= nums[i] <= 1000
//-104 <= target <= 104
//
//链接:https://leetcode-cn.com/problems/3sum-closest/
class Solution {
public int threeSumClosest(int[] nums, int target) {
int res = 999999;
Arrays.sort(nums);
for (int i = 0; i < nums.length; i++) {
if (i > 0 && nums[i] == nums[i - 1]) continue;
int left = i + 1, right = nums.length - 1;
while (left < right) {
int sum = nums[i] + nums[left] + nums[right];
if (sum == target) return target;
if (Math.abs(sum - target) < Math.abs(res - target)) res = sum;
if (sum < target) {
while (left < right && nums[left] == nums[++left]) ;
} else {
while (left < right && nums[right] == nums[--right]) ;
}
}
}
return res;
}
}
| 28.288889 | 79 | 0.498036 |
a273c7f8edf4b2de84c00ccdef10fbc0fd97f8ac | 2,394 | package ie.dit.giantbombapp.model.pojos;
import com.google.gson.annotations.SerializedName;
/**
* Author: Graham Byrne
*
* Created: 22/11/2016
* Modified: 25/11/2016
*
* POJO for the Review JSON object found on the Giantbomb API
*
* SerialisedName annotation is used to specify the JSON form of the variable
* name
*/
public class Review
{
@SerializedName("api_detail_url")
private String apiDetailUrl;
private String deck;
private String description;
private Game game;
@SerializedName("publish_date")
private String publishDate;
private Release release;
private String reviewer;
private int score;
@SerializedName("site_detail_url")
private String siteDetailUrl;
private String platforms;
public String getApiDetailUrl()
{
return apiDetailUrl;
}
public void setApiDetailUrl(String apiDetailUrl)
{
this.apiDetailUrl = apiDetailUrl;
}
public String getDeck()
{
return deck;
}
public void setDeck(String deck)
{
this.deck = deck;
}
public String getDescription()
{
return description;
}
public void setDescription(String description)
{
this.description = description;
}
public Game getGame()
{
return game;
}
public void setGame(Game game)
{
this.game = game;
}
public String getPublishDate()
{
return publishDate;
}
public void setPublishDate(String publishDate)
{
this.publishDate = publishDate;
}
public Release getRelease()
{
return release;
}
public void setRelease(Release release)
{
this.release = release;
}
public String getReviewer()
{
return reviewer;
}
public void setReviewer(String reviewer)
{
this.reviewer = reviewer;
}
public int getScore()
{
return score;
}
public void setScore(int score)
{
this.score = score;
}
public String getSiteDetailUrl()
{
return siteDetailUrl;
}
public void setSiteDetailUrl(String siteDetailUrl)
{
this.siteDetailUrl = siteDetailUrl;
}
public String getPlatforms()
{
return platforms;
}
public void setPlatforms(String platforms)
{
this.platforms = platforms;
}
}
| 18 | 77 | 0.621136 |
6910230ab3c948ebf4faf439a7444f36c3f25fbb | 1,051 | package seedu.address.ui;
// @@author itsdickson
import static org.junit.Assert.assertEquals;
import static seedu.address.ui.ThemesWindow.THEMES_FILE_PATH;
import java.net.URL;
import org.junit.Before;
import org.junit.Test;
import org.testfx.api.FxToolkit;
import guitests.guihandles.ThemesWindowHandle;
import javafx.stage.Stage;
public class ThemesWindowTest extends GuiUnitTest {
private ThemesWindow themesWindow;
private ThemesWindowHandle themesWindowHandle;
@Before
public void setUp() throws Exception {
guiRobot.interact(() -> themesWindow = new ThemesWindow());
Stage themesWindowStage = FxToolkit.setupStage((stage) -> stage.setScene(themesWindow.getRoot().getScene()));
FxToolkit.showStage();
themesWindowHandle = new ThemesWindowHandle(themesWindowStage);
}
@Test
public void display() {
URL expectedThemesPage = ThemesWindow.class.getResource(THEMES_FILE_PATH);
assertEquals(expectedThemesPage, themesWindowHandle.getLoadedUrl());
}
}
// @@author
| 28.405405 | 117 | 0.745956 |
5692ebd11942728e95933302392cb7db61b5a5cc | 10,559 | package com.coinninja.coinkeeper.service.client;
import com.coinninja.coinkeeper.TestCoinKeeperApplication;
import com.coinninja.coinkeeper.service.client.model.CNPricing;
import com.coinninja.coinkeeper.service.client.model.GsonAddress;
import com.coinninja.coinkeeper.service.client.model.TransactionDetail;
import com.coinninja.coinkeeper.service.client.model.TransactionStats;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.ArgumentMatchers;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.OkHttpClient;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import static junit.framework.Assert.assertTrue;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(RobolectricTestRunner.class)
@Config(application = TestCoinKeeperApplication.class)
public class CoinKeeperApiClientTest {
private CoinKeeperApiClient apiClient;
private MockWebServer server;
@Before
public void setUp() {
server = new MockWebServer();
apiClient = createClient(server.url("").toString());
}
@After
public void tearDown() {
try {
server.shutdown();
} catch (Exception e) {
}
}
@Test
public void order_of_tx_resposne() {
String json = "[{\"hash\":\"82a2d283543af94a31ba835bc95c2049e2bb4fb75a91b79a94c137c5e40ae2ee\",\"txid\":\"82a2d283543af94a31ba835bc95c2049e2bb4fb75a91b79a94c137c5e40ae2ee\"," +
"\"size\":247,\"vsize\":166,\"weight\":661,\"version\":1,\"locktime\":0,\"coinbase\":false,\"blockhash\":\"0000000000000000002b47fa958ff8cd3d7e865ef08cb2230b1805fbddadd300\"" +
",\"blockheight\":562165,\"height\":103,\"time\":1549642028," +
"\"received_time\":1549642028,\"blocktime\":1549642028,\"vin\":" +
"[{\"txid\":\"11fb6b149f6952d2ec2c643ebddd0a08cade890e2818c85e6ae1db43b43f714a\",\"vout\":1,\"scriptSig\":" +
"{\"asm\":\"00144a95b3c08579531f841a8aee18d2d5c31c1bb6a6\",\"hex\":\"1600144a95b3c08579531f841a8aee18d2d5c31c1bb6a6\"}," +
"\"txinwitness\":[\"304402201149422cd5906f69daf3bd8f78fc06ae9bf8c8bf2fc3b56ca641d79ca044e4fe022001dbe82065943ea0dc75b5e956a0f5f2fe060993803c51ccb5e71637b46c4a4701\",\"03befc7e3f868f4cd123badabb8df0ae49b1d45e221c39d8cd9f56fdaadc035d5a\"],\"sequence\":4294967295,\"previousoutput\":{\"value\":1020110,\"n\":1,\"scriptPubKey\":{\"asm\":\"OP_HASH160 8f98f8a5e5110306c89fd04d8fd877bdcb135406 OP_EQUAL\",\"hex\":\"a9148f98f8a5e5110306c89fd04d8fd877bdcb13540687\",\"reqsigs\":1,\"type\":\"scripthash\",\"addresses\":[\"3EnHoc8QCGSCgiPoAjAEewKsu2fpuw7qh2\"]}}}],\"vout\":[{\"value\":725308,\"n\":0,\"scriptPubKey\":{\"asm\":\"OP_HASH160 082578c0addb14c6782bd41bdc3ad1b5fe34e106 OP_EQUAL\",\"hex\":\"a914082578c0addb14c6782bd41bdc3ad1b5fe34e10687\",\"reqsigs\":1,\"type\":\"scripthash\",\"addresses\":" +
"[\"32S6Df4d3skdaR8oPNYLY1A73qrRo4jpgT\"]}},{\"value\":286094,\"n\":1,\"scriptPubKey\":{\"asm\":\"OP_HASH160 770929bd1d7ca5d7d014b535ac17227fe3a8f412 OP_EQUAL\",\"hex\":\"a914770929bd1d7ca5d7d014b535ac17227fe3a8f41287\",\"reqsigs\":1,\"type\":\"scripthash\",\"addresses\":[\"3CYRK2kACzepjdnx2nmN2XnCYhRP2DbCYS\"]}}],\"blocks\":[\"0000000000000000002b47fa958ff8cd3d7e865ef08cb2230b1805fbddadd300\"]}]";
server.enqueue(new MockResponse().setResponseCode(200).setBody(json));
String[] txids = new String[1];
txids[0] = "txid";
Response response = apiClient.getTransactions(txids);
List<TransactionDetail> details = (List<TransactionDetail>) response.body();
TransactionDetail transactionDetail = details.get(0);
assertThat(transactionDetail.getHash(), equalTo("82a2d283543af94a31ba835bc95c2049e2bb4fb75a91b79a94c137c5e40ae2ee"));
}
@Test
public void exposes_health_check_api_call() {
server.enqueue(new MockResponse().setResponseCode(200).setBody("{\n" + "" +
"\"message\": \"OK\"\n" + "}"));
Response response = apiClient.checkHealth();
assertTrue(response.isSuccessful());
}
@Test
public void fetches_current_state_information() {
server.enqueue(new MockResponse().setResponseCode(200)
.setBody(MockAPIData.PRICING));
Response response = apiClient.getCurrentState();
CurrentState state = (CurrentState) response.body();
assertThat(state.getBlockheight(), equalTo(518631));
assertThat(state.getFees().getSlow(), equalTo(40.1));
assertThat(state.getFees().getMed(), equalTo(20.1));
assertThat(state.getFees().getFast(), equalTo(10.0));
assertThat(state.getLatestPrice().toFormattedCurrency(), equalTo("$418.66"));
}
@Test
public void itFetchesStatsForATransaction() {
server.enqueue(new MockResponse().setResponseCode(200)
.setBody(MockAPIData.TRANSACTION_STATS));
String transactionId = "7f3a2790d59853fdc620b8cd23c8f68158f8bbdcd337a5f2451620d6f76d4e03";
Response response = apiClient.getTransactionStats(transactionId);
TransactionStats transactionStats = (TransactionStats) response.body();
assertThat(transactionStats.getTransactionId(), equalTo("7f3a2790d59853fdc620b8cd23c8f68158f8bbdcd337a5f2451620d6f76d4e03"));
assertThat(transactionStats.isCoinBase(), equalTo(false));
assertThat(transactionStats.getFeesRate(), equalTo(1015821L));
assertThat(transactionStats.getFees(), equalTo(170658L));
assertThat(transactionStats.getMiner(), equalTo("GBMiners"));
assertThat(transactionStats.getVinValue(), equalTo(180208833L));
assertThat(transactionStats.getVoutValue(), equalTo(179858833L));
}
@Test
public void sends_expected_contract_for_multiple_transactions() throws IOException {
ArgumentCaptor<JsonObject> argumentCaptor = ArgumentCaptor.forClass(JsonObject.class);
String[] txids = {"---txid--1---", "---txid--2---"};
CoinKeeperClient client = mock(CoinKeeperClient.class);
Call<List<TransactionDetail>> call = mock(Call.class);
when(call.execute()).thenReturn(Response.success(new ArrayList<TransactionDetail>()));
when(client.queryTransactions(ArgumentMatchers.any())).thenReturn(call);
CoinKeeperApiClient apiClient = new CoinKeeperApiClient(client);
apiClient.getTransactions(txids);
verify(client).queryTransactions(argumentCaptor.capture());
JsonArray jsonArray = argumentCaptor.getValue().getAsJsonObject("query").
getAsJsonObject("terms").
getAsJsonArray("txid");
Gson gson = new Gson();
String[] strings = gson.fromJson(jsonArray, String[].class);
assertThat(strings, equalTo(txids));
}
@Test
public void sends_expected_contract_when_quering_for_addresses() throws IOException {
ArgumentCaptor<JsonObject> argumentCaptor = ArgumentCaptor.forClass(JsonObject.class);
String[] inAddresses = {"1Gy2Ast7uT13wQByPKs9Vi9Qj1BVcARgVQ", "3PxEH5t91Cio4B7LCZCEWQEGGxaqGW5HkX"};
CoinKeeperClient client = mock(CoinKeeperClient.class);
Call call = mock(Call.class);
when(call.execute()).thenReturn(Response.success(new ArrayList<GsonAddress>()));
when(client.getAddresses(ArgumentMatchers.any(JsonObject.class), ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt())).thenReturn(call);
CoinKeeperApiClient apiClient = new CoinKeeperApiClient(client);
apiClient.queryAddressesFor(inAddresses, 1);
verify(client).getAddresses(argumentCaptor.capture(), eq(1), anyInt());
JsonArray jsonArray = argumentCaptor.getValue().getAsJsonObject("query").
getAsJsonObject("terms").
getAsJsonArray("address");
Gson gson = new Gson();
String[] strings = gson.fromJson(jsonArray, String[].class);
assertThat(strings, equalTo(inAddresses));
}
@Test
public void gets_historical_pricing_for_transaction_id() throws InterruptedException {
String JSON = "{\n" +
"\"time\": \"2016-05-17 00:00:00\",\n" +
"\"average\": 457.91\n" +
"}";
server.enqueue(new MockResponse().setResponseCode(200).setBody(JSON));
String txid = "--txid--";
Response response = apiClient.getHistoricPrice(txid);
CNPricing pricing = (CNPricing) response.body();
assertThat(pricing.getAverage(), equalTo(45791L));
assertThat(server.takeRequest().getPath(), equalTo(String.format("/pricing/%s", txid)));
}
@Test
public void queries_multiple_addresses_in_blocks() {
String[] inAddresses = {"1Gy2Ast7uT13wQByPKs9Vi9Qj1BVcARgVQ", "3PxEH5t91Cio4B7LCZCEWQEGGxaqGW5HkX"};
server.enqueue(new MockResponse().setResponseCode(200)
.setBody(MockAPIData.ADDRESS_QUERY_RESPONSE__PAGE_1));
Response response = apiClient.queryAddressesFor(inAddresses, 1);
List<GsonAddress> addresses = (List<GsonAddress>) response.body();
assertThat(addresses.size(), equalTo(3));
assertThat(addresses.get(0).getAddress(), equalTo("1Gy2Ast7uT13wQByPKs9Vi9Qj1BVcARgVQ"));
assertThat(addresses.get(1).getAddress(), equalTo("3PxEH5t91Cio4B7LCZCEWQEGGxaqGW5HkX"));
assertThat(addresses.get(2).getAddress(), equalTo("3PxEH5t91Cio4B7LCZCEWQEGGxaqGW5HkX"));
}
private CoinKeeperApiClient createClient(String host) {
CoinKeeperClient client = new Retrofit.Builder().
baseUrl(host).
client(new OkHttpClient.Builder()
.build())
.addConverterFactory(GsonConverterFactory.create()).
build().create(CoinKeeperClient.class);
return new CoinKeeperApiClient(client);
}
} | 47.138393 | 811 | 0.706033 |
36b22ed04728f1c48b3d012e71d384773bfd5f75 | 2,044 | package org.firstinspires.ftc.teamcode.subsystems;
import com.qualcomm.robotcore.hardware.DcMotor;
import com.qualcomm.robotcore.hardware.DcMotorEx;
import com.qualcomm.robotcore.hardware.Servo;
import org.firstinspires.ftc.teamcode.Robot;
//6766.2 encoder ticks
public class Arm implements SubSystems {
public DcMotor armLiftUpper;
public DcMotorEx armLiftLower;
public DcMotor zipTies;
public Servo flipBucket;
Robot robot;
double num;
double armPower;
public double servoPosition = 0;
double ticks = 6766.2;
boolean lock;
boolean direction;
public Arm(Robot robot) {
this.robot = robot;
armLiftUpper = robot.hardwareMap.get(DcMotorEx.class, "arm_motor");
armLiftLower = robot.hardwareMap.get(DcMotorEx.class, "arm_motor2");
flipBucket = robot.hardwareMap.get(Servo.class, "bucket_servo");
zipTies = robot.hardwareMap.get(DcMotor.class, "intake_motor");
}
@Override
public void update() {
zipTies.setPower(num);
if(armLiftUpper.getCurrentPosition() < 2000) {
armLiftLower.setPower(armPower);
armLiftUpper.setPower(-armPower);
}
else {
armLiftLower.setPower(0);
}
flipBucket.setPosition(servoPosition);
}
public void intake(double power) {
num = power;
}
public void autoIntake(double power) {
num = power;
}
public void armSpeed(double position) {
armPower = position;
}
// public void servoPosition(boolean direction1) {
// if(direction1)
// {
// servoPosition = servoPosition + 0.01;
// if(servoPosition > 1)
// {
// servoPosition = 1;
// }
//
// }
// else
// {
// servoPosition = servoPosition- 0.01;
// if(servoPosition < 0)
// {
// servoPosition = 0;
// }
// }
// }
//
// public void lock(boolean x)
// {
// lock = x;
// }
} | 25.234568 | 76 | 0.591977 |
d99166386954dc608e58b015832d0c6f0b1d8acf | 3,627 | package TreeAutomataParser;
import java.io.PrintWriter;
import java.util.ArrayList;
public class TreeNode {
public TreeNode(ArrayList<SymbolWithArityNode> aList, String ID, ArrayList<String> sList, ArrayList<String> fList, ArrayList<TransitionNode> tList){
arityList = aList;
myID = ID;
stateList = sList;
finalStateList = fList;
transitionList = tList;
}
public void unparse(PrintWriter p){
//print Ops first
p.print("Ops ");
for(SymbolWithArityNode node: arityList){
p.print(node.getSymbol());
p.print(":");
p.print(node.getArity());
p.print(" ");
}
p.print(System.getProperty("line.separator"));
p.print(System.getProperty("line.separator"));
//then print ID
p.print("Automation ");
p.print(myID);
p.print(System.getProperty("line.separator"));
p.print(System.getProperty("line.separator"));
//then print states
p.print("States ");
for(String s: stateList){
p.print(s);
p.print(" ");
}
p.print(System.getProperty("line.separator"));
p.print(System.getProperty("line.separator"));
//then print final states
p.print("Final States ");
for(String s: finalStateList){
p.print(s);
p.print(" ");
}
p.print(System.getProperty("line.separator"));
p.print(System.getProperty("line.separator"));
//then print transitions
p.println("Transitions");
for (TransitionNode node: transitionList){
node.unparse(p);
}
p.print(System.getProperty("line.separator"));
p.print(System.getProperty("line.separator"));
}
public String toString(){
//print Ops first
StringBuilder s = new StringBuilder();
s.append("Ops ");
for(SymbolWithArityNode node: arityList){
s.append(node.getSymbol());
s.append(":");
s.append(node.getArity());
s.append(" ");
}
s.append(System.getProperty("line.separator"));
s.append(System.getProperty("line.separator"));
//then print ID
s.append("Automation ");
s.append(myID);
s.append(System.getProperty("line.separator"));
s.append(System.getProperty("line.separator"));
//then print states
s.append("States ");
for(String str: stateList){
s.append(str);
s.append(" ");
}
s.append(System.getProperty("line.separator"));
s.append(System.getProperty("line.separator"));
//then print final states
s.append("Final States ");
for(String str: finalStateList){
s.append(str);
s.append(" ");
}
s.append(System.getProperty("line.separator"));
s.append(System.getProperty("line.separator"));
//then print transitions
s.append("Transitions");
s.append(System.getProperty("line.separator"));
for (TransitionNode node: transitionList){
node.toString(s);
}
s.append(System.getProperty("line.separator"));
s.append(System.getProperty("line.separator"));
return s.toString();
}
public ArrayList<SymbolWithArityNode> getArity(){
return arityList;
}
public String getID(){
return myID;
}
public ArrayList<String> getStates(){
return stateList;
}
public ArrayList<String> getFinalStates(){
return finalStateList;
}
public ArrayList<TransitionNode> getTransitions(){
return transitionList;
}
private ArrayList<SymbolWithArityNode> arityList;
private String myID;
private ArrayList<String> stateList;
private ArrayList<String> finalStateList;
private ArrayList<TransitionNode> transitionList;
}
| 26.474453 | 149 | 0.63689 |
9f540f01c276f3b4a87edfbd685708dfb96ccf28 | 13,723 | package us.ihmc.gdx.ui.affordances;
import com.badlogic.gdx.graphics.g3d.Renderable;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Pool;
import controller_msgs.msg.dds.FootstepDataListMessage;
import imgui.flag.ImGuiMouseButton;
import imgui.internal.ImGui;
import us.ihmc.avatar.drcRobot.DRCRobotModel;
import us.ihmc.avatar.drcRobot.ROS2SyncedRobotModel;
import us.ihmc.avatar.networkProcessor.footstepPlanningModule.FootstepPlanningModuleLauncher;
import us.ihmc.avatar.ros2.ROS2ControllerHelper;
import us.ihmc.behaviors.tools.BehaviorTools;
import us.ihmc.behaviors.tools.footstepPlanner.MinimalFootstep;
import us.ihmc.communication.packets.ExecutionMode;
import us.ihmc.euclid.Axis3D;
import us.ihmc.euclid.axisAngle.AxisAngle;
import us.ihmc.euclid.geometry.Pose3D;
import us.ihmc.euclid.geometry.interfaces.Pose3DReadOnly;
import us.ihmc.euclid.referenceFrame.FramePose3D;
import us.ihmc.euclid.referenceFrame.ReferenceFrame;
import us.ihmc.euclid.tuple2D.Point2D;
import us.ihmc.footstepPlanning.*;
import us.ihmc.footstepPlanning.graphSearch.parameters.FootstepPlannerParametersBasics;
import us.ihmc.gdx.input.ImGui3DViewInput;
import us.ihmc.gdx.ui.GDXImGuiBasedUI;
import us.ihmc.gdx.ui.gizmo.GDXFootstepPlannerGoalGizmo;
import us.ihmc.gdx.ui.graphics.GDXFootstepGraphic;
import us.ihmc.gdx.ui.graphics.GDXFootstepPlanGraphic;
import us.ihmc.mecano.frames.MovingReferenceFrame;
import us.ihmc.robotics.referenceFrames.ReferenceFrameMissingTools;
import us.ihmc.robotics.robotSide.RobotSide;
import us.ihmc.robotics.robotSide.SegmentDependentList;
import us.ihmc.robotics.robotSide.SideDependentList;
import us.ihmc.tools.thread.MissingThreadTools;
import us.ihmc.tools.thread.ResettableExceptionHandlingExecutorService;
import java.util.ArrayList;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
public class GDXWalkPathControlRing
{
private final GDXFootstepPlannerGoalGizmo footstepPlannerGoalGizmo = new GDXFootstepPlannerGoalGizmo();
private boolean selected = false;
private boolean modified = false;
private boolean mouseIntersectsRing;
private ROS2SyncedRobotModel syncedRobot;
private ROS2ControllerHelper ros2Helper;
private MovingReferenceFrame midFeetZUpFrame;
private ResettableExceptionHandlingExecutorService footstepPlanningThread;
private FootstepPlannerParametersBasics footstepPlannerParameters;
private GDXFootstepGraphic leftStanceFootstepGraphic;
private GDXFootstepGraphic rightStanceFootstepGraphic;
private GDXFootstepGraphic leftGoalFootstepGraphic;
private GDXFootstepGraphic rightGoalFootstepGraphic;
private final FramePose3D leftStanceFootPose = new FramePose3D();
private final FramePose3D rightStanceFootPose = new FramePose3D();
private final FramePose3D leftGoalFootPose = new FramePose3D();
private final FramePose3D rightGoalFootPose = new FramePose3D();
private ReferenceFrame goalFrame;
private final FramePose3D goalPose = new FramePose3D();
private final FramePose3D midFeetZUpPose = new FramePose3D();
private final FramePose3D startPose = new FramePose3D();
private SideDependentList<MovingReferenceFrame> footFrames;
private final AtomicInteger footstepPlannerId = new AtomicInteger(0);
private FootstepPlanningModule footstepPlanner;
private GDXFootstepPlanGraphic foostepPlanGraphic;
private double halfIdealFootstepWidth;
private volatile FootstepPlan footstepPlan;
private volatile FootstepPlan footstepPlanToGenerateMeshes;
private final AxisAngle walkFacingDirection = new AxisAngle();
public void create(GDXImGuiBasedUI baseUI, DRCRobotModel robotModel, ROS2SyncedRobotModel syncedRobot, ROS2ControllerHelper ros2Helper)
{
this.syncedRobot = syncedRobot;
this.ros2Helper = ros2Helper;
footstepPlannerGoalGizmo.create(baseUI.get3DSceneManager().getCamera3D());
baseUI.addImGui3DViewInputProcessor(this::process3DViewInput);
midFeetZUpFrame = syncedRobot.getReferenceFrames().getMidFeetZUpFrame();
footFrames = syncedRobot.getReferenceFrames().getSoleFrames();
// periodic thread to footstep plan
footstepPlanningThread = MissingThreadTools.newSingleThreadExecutor("WalkPathControlPlanning", true, 1);
footstepPlannerParameters = robotModel.getFootstepPlannerParameters();
SegmentDependentList<RobotSide, ArrayList<Point2D>> contactPoints = robotModel.getContactPointParameters().getControllerFootGroundContactPoints();
leftStanceFootstepGraphic = new GDXFootstepGraphic(contactPoints, RobotSide.LEFT);
rightStanceFootstepGraphic = new GDXFootstepGraphic(contactPoints, RobotSide.RIGHT);
leftGoalFootstepGraphic = new GDXFootstepGraphic(contactPoints, RobotSide.LEFT);
rightGoalFootstepGraphic = new GDXFootstepGraphic(contactPoints, RobotSide.RIGHT);
goalFrame = ReferenceFrameMissingTools.constructFrameWithChangingTransformToParent("goalPose",
ReferenceFrame.getWorldFrame(),
footstepPlannerGoalGizmo.getTransform());
footstepPlanner = FootstepPlanningModuleLauncher.createModule(robotModel);
foostepPlanGraphic = new GDXFootstepPlanGraphic(contactPoints);
leftStanceFootstepGraphic.create();
rightStanceFootstepGraphic.create();
leftGoalFootstepGraphic.create();
rightGoalFootstepGraphic.create();
halfIdealFootstepWidth = footstepPlannerParameters.getIdealFootstepWidth() / 2.0;
leftStanceFootPose.getPosition().addY(halfIdealFootstepWidth);
rightStanceFootPose.getPosition().subY(halfIdealFootstepWidth);
leftStanceFootstepGraphic.setPose(leftStanceFootPose);
rightStanceFootstepGraphic.setPose(rightStanceFootPose);
}
public void update()
{
if (!modified)
{
footstepPlannerGoalGizmo.getTransform().set(midFeetZUpFrame.getTransformToWorldFrame());
}
if (footstepPlanToGenerateMeshes != null)
{
foostepPlanGraphic.generateMeshes(MinimalFootstep.reduceFootstepPlanForUIMessager(footstepPlanToGenerateMeshes, "Walk Path Control Ring Plan"));
footstepPlanToGenerateMeshes = null;
}
foostepPlanGraphic.update();
}
// This happens after update.
public void process3DViewInput(ImGui3DViewInput input)
{
boolean leftMouseReleasedWithoutDrag = input.mouseReleasedWithoutDrag(ImGuiMouseButton.Left);
footstepPlannerGoalGizmo.process3DViewInput(input);
mouseIntersectsRing = footstepPlannerGoalGizmo.getHollowCylinderIntersects();
if (!modified && mouseIntersectsRing && leftMouseReleasedWithoutDrag)
{
selected = true;
modified = true;
walkFacingDirection.set(Axis3D.Z, 0.0);
updateStuff();
queueFootstepPlan();
}
if (selected && !footstepPlannerGoalGizmo.getIntersectsAny() && leftMouseReleasedWithoutDrag)
{
selected = false;
}
if (modified && mouseIntersectsRing && leftMouseReleasedWithoutDrag)
{
selected = true;
}
if (modified)
{
updateStuff();
}
if (selected && leftMouseReleasedWithoutDrag)
{
if (footstepPlannerGoalGizmo.getPositiveXArrowIntersects())
{
walkFacingDirection.set(Axis3D.Z, 0.0);
}
else if (footstepPlannerGoalGizmo.getPositiveYArrowIntersects())
{
walkFacingDirection.set(Axis3D.Z, Math.PI / 2.0);
}
else if (footstepPlannerGoalGizmo.getNegativeXArrowIntersects())
{
walkFacingDirection.set(Axis3D.Z, Math.PI);
}
else if (footstepPlannerGoalGizmo.getNegativeYArrowIntersects())
{
walkFacingDirection.set(Axis3D.Z, -Math.PI / 2.0);
}
if (footstepPlannerGoalGizmo.getIntersectsAnyArrow())
{
footstepPlannerGoalGizmo.getTransform().appendOrientation(walkFacingDirection);
updateStuff();
queueFootstepPlan();
}
}
if (selected && footstepPlannerGoalGizmo.isBeingDragged())
{
queueFootstepPlan();
}
if (selected && ImGui.isKeyReleased(input.getSpaceKey()))
{
// Send footsteps to robot
double swingDuration = 1.2;
double transferDuration = 0.8;
FootstepDataListMessage footstepDataListMessage = FootstepDataMessageConverter.createFootstepDataListFromPlan(footstepPlan,
swingDuration,
transferDuration);
footstepDataListMessage.getQueueingProperties().setExecutionMode(ExecutionMode.OVERRIDE.toByte());
footstepDataListMessage.getQueueingProperties().setMessageId(UUID.randomUUID().getLeastSignificantBits());
ros2Helper.publishToController(footstepDataListMessage);
}
if (modified && selected && ImGui.isKeyReleased(input.getDeleteKey()))
{
selected = false;
modified = false;
foostepPlanGraphic.clear();
}
if (selected && ImGui.isKeyReleased(input.getEscapeKey()))
{
selected = false;
}
footstepPlannerGoalGizmo.setShowArrows(selected);
footstepPlannerGoalGizmo.setHighlightingEnabled(modified);
}
private void queueFootstepPlan()
{
footstepPlanningThread.clearQueueAndExecute(() -> planFoosteps(new Pose3D(leftStanceFootPose),
new Pose3D(rightStanceFootPose),
new Pose3D(leftGoalFootPose),
new Pose3D(rightGoalFootPose)));
}
private void updateStuff()
{
goalFrame.update();
goalPose.setToZero(goalFrame);
// goalPose.appendRotation(walkFacingDirection);
leftGoalFootPose.setIncludingFrame(goalPose);
leftGoalFootPose.getPosition().addY(halfIdealFootstepWidth);
leftGoalFootPose.changeFrame(ReferenceFrame.getWorldFrame());
rightGoalFootPose.setIncludingFrame(goalPose);
rightGoalFootPose.getPosition().subY(halfIdealFootstepWidth);
rightGoalFootPose.changeFrame(ReferenceFrame.getWorldFrame());
leftStanceFootPose.setToZero(footFrames.get(RobotSide.LEFT));
leftStanceFootPose.changeFrame(ReferenceFrame.getWorldFrame());
rightStanceFootPose.setToZero(footFrames.get(RobotSide.RIGHT));
rightStanceFootPose.changeFrame(ReferenceFrame.getWorldFrame());
double lowestStanceZ = Math.min(leftStanceFootPose.getZ(), rightStanceFootPose.getZ());
leftStanceFootPose.setZ(lowestStanceZ);
rightStanceFootPose.setZ(lowestStanceZ);
goalPose.changeFrame(ReferenceFrame.getWorldFrame());
midFeetZUpPose.setToZero(midFeetZUpFrame);
midFeetZUpPose.changeFrame(ReferenceFrame.getWorldFrame());
startPose.setToZero(midFeetZUpFrame);
startPose.changeFrame(ReferenceFrame.getWorldFrame());
startPose.getOrientation().set(goalPose.getOrientation());
leftGoalFootstepGraphic.setPose(leftGoalFootPose);
rightGoalFootstepGraphic.setPose(rightGoalFootPose);
}
private void planFoosteps(Pose3DReadOnly leftStanceFootPose,
Pose3DReadOnly rightStanceFootPose,
Pose3DReadOnly leftGoalFootPose,
Pose3DReadOnly rightGoalFootPose)
{
FootstepPlannerRequest footstepPlannerRequest = new FootstepPlannerRequest();
footstepPlannerRequest.setPlanBodyPath(false);
footstepPlannerRequest.getBodyPathWaypoints().add(midFeetZUpPose);
footstepPlannerRequest.getBodyPathWaypoints().add(startPose);
footstepPlannerRequest.getBodyPathWaypoints().add(goalPose);
footstepPlannerRequest.setStartFootPoses(leftStanceFootPose, rightStanceFootPose);
footstepPlannerRequest.setGoalFootPoses(leftGoalFootPose, rightGoalFootPose);
footstepPlannerRequest.setAssumeFlatGround(true);
footstepPlannerRequest.setRequestId(footstepPlannerId.getAndIncrement());
FootstepPlannerOutput footstepPlannerOutput = footstepPlanner.handleRequest(footstepPlannerRequest);
footstepPlan = footstepPlanToGenerateMeshes = new FootstepPlan(footstepPlannerOutput.getFootstepPlan());
}
public void getVirtualRenderables(Array<Renderable> renderables, Pool<Renderable> pool)
{
if (modified)
{
leftStanceFootstepGraphic.getRenderables(renderables, pool);
rightStanceFootstepGraphic.getRenderables(renderables, pool);
leftGoalFootstepGraphic.getRenderables(renderables, pool);
rightGoalFootstepGraphic.getRenderables(renderables, pool);
foostepPlanGraphic.getRenderables(renderables, pool);
}
if (modified || mouseIntersectsRing)
{
footstepPlannerGoalGizmo.getRenderables(renderables, pool);
}
}
public void clearGraphics()
{
leftStanceFootstepGraphic.setPose(BehaviorTools.createNaNPose());
rightStanceFootstepGraphic.setPose(BehaviorTools.createNaNPose());
leftGoalFootstepGraphic.setPose(BehaviorTools.createNaNPose());
rightGoalFootstepGraphic.setPose(BehaviorTools.createNaNPose());
foostepPlanGraphic.clear();
}
public void destroy()
{
footstepPlanningThread.destroy();
foostepPlanGraphic.destroy();
}
}
| 45.743333 | 153 | 0.724331 |
40f9e6e90450eb0b2a4609489fe1ea85a6b3450b | 4,110 | /**
*
*/
package org.einnovator.blueprint.entity1.manager;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.einnovator.blueprint.entity1.model.Status;
import org.einnovator.blueprint.entity1.model.MyEntity;
import org.einnovator.blueprint.entity1.modelx.MyEntityFilter;
import org.einnovator.blueprint.entity1.repository.MyEntityRepository;
import org.einnovator.common.config.AppConfiguration;
import org.einnovator.common.config.UIConfiguration;
import org.einnovator.jpa.manager.ManagerBaseImpl3;
import org.einnovator.jpa.repository.RepositoryBase2;
import org.einnovator.social.client.manager.ChannelManager;
import org.einnovator.social.client.model.Channel;
import org.einnovator.util.MappingUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
/**
*
*/
@Service
public class MyEntityManagerImpl extends ManagerBaseImpl3<MyEntity> implements MyEntityManager {
private final Log logger = LogFactory.getLog(getClass());
public static final String SUPERHEROS_RESOURCE_JSON = "data/entities.json";
@Autowired
private MyEntityRepository repository;
@Autowired
private ChannelManager channelManager;
@Autowired
private UIConfiguration ui;
@Autowired
private AppConfiguration app;
@Override
protected RepositoryBase2<MyEntity, Long> getRepository() {
return repository;
}
@Override
public MyEntity find(MyEntity entity) {
MyEntity entity0 = super.find(entity);
if (entity0!=null) {
return entity0;
}
if (entity.getName()!=null) {
entity0 = findOneByName(entity.getName());
if (entity0!=null) {
return entity0;
}
}
return entity0;
}
@Override
public MyEntity findOneByName(String name) {
Optional<MyEntity> entity = repository.findOneByName(name);
return entity.isPresent() ? processAfterLoad(entity.get(), null) : null;
}
@Override
public Page<MyEntity> findAll(MyEntityFilter filter, Pageable pageable) {
populate();
Page<MyEntity> page = null;
if (filter!=null) {
if (filter.getStatus()!=null || filter.getCheck()!=null) {
String q = filter.getQ()!=null ? "%" + filter.getQ().trim() + "%" : "%";
Collection<Status> statuss = filter.getStatus()!=null ? Collections.singleton(filter.getStatus()) : Arrays.asList(Status.values());
if (filter.getCheck()!=null) {
page = repository.findAllByNameLikeAndStatusInAndCheck(q, statuss, filter.getCheck(), pageable);
} else {
page = repository.findAllByNameLikeAndStatusIn(q, statuss, pageable);
}
} else if (filter.getQ()!=null){
String q = "%" + filter.getQ().trim() + "%";
page = repository.findAllByNameLike(q, pageable);
}
}
if (page==null) {
page = repository.findAll(pageable);
}
return processAfterLoad(page, null);
}
@Override
public void processAfterPersistence(MyEntity entity) {
super.processAfterPersistence(entity);
Channel channel = entity.makeChannel(getBaseUri());
channel = channelManager.createOrUpdateChannel(channel, null);
if (channel!=null && entity.getChannelId()==null) {
entity.setChannelId(channel.getUuid());
repository.save(entity);
}
}
public String getBaseUri() {
return ui.getLink(app.getId());
}
private boolean init;
public void populate() {
populate(true);
}
@Override
public void populate(boolean force) {
if (force || !init) {
init = true;
if (!force && repository.count()!=0) {
return;
}
logger.info("populate: ");
MyEntity[] entities = MappingUtils.readJson(new ClassPathResource(SUPERHEROS_RESOURCE_JSON), MyEntity[].class);
createOrUpdate(Arrays.asList(entities));
}
}
}
| 29.148936 | 136 | 0.712409 |
a649f0ef89b578565d95466e8f8cfbd8961963a9 | 2,057 | package com.app.app1.activities.user;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.app.app1.R;
import com.app.app1.config.ConfiguracaoFirebase;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseAuth;
import java.util.Objects;
public class AlterarSenhaActivity extends AppCompatActivity {
private EditText etASEmail;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alterar_senha);
Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Alterar Senha");
etASEmail = findViewById(R.id.etASEmail);
}
public void enviarEmail(View view) {
FirebaseAuth auth = ConfiguracaoFirebase.getFirebaseAutenticacao();
String email = etASEmail.getText().toString().trim(); //remove espaços no inicio e fim da string
auth.sendPasswordResetEmail(email)
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if(task.isSuccessful()) {
Toast.makeText(AlterarSenhaActivity.this, "Email enviado", Toast.LENGTH_SHORT).show();
finish();
}else {
Toast.makeText(AlterarSenhaActivity.this, "Email não cadastrado", Toast.LENGTH_SHORT).show();
}
}
});
}
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
}
| 33.177419 | 113 | 0.673797 |
b714102fcd67c19ee96f39d581340bb3a18deecb | 2,835 | package com.gioov.oryx.quartz.service.impl;
import com.gioov.oryx.common.easyui.Pagination;
import com.gioov.oryx.common.util.SpringContextUtil;
import com.gioov.oryx.quartz.entity.JobRuntimeLogEntity;
import com.gioov.oryx.quartz.mapper.JobRuntimeLogMapper;
import com.gioov.oryx.quartz.service.JobRuntimeLogService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import java.util.Date;
/**
* @author godcheese [godcheese@outlook.com]
* @date 2019-02-13
*/
@Service
public class JobRuntimeLogServiceImpl implements JobRuntimeLogService {
private static final Logger LOGGER = LoggerFactory.getLogger(JobRuntimeLogServiceImpl.class);
private JobRuntimeLogMapper jobRuntimeLogMapper;
public JobRuntimeLogServiceImpl() {
jobRuntimeLogMapper = (JobRuntimeLogMapper) SpringContextUtil.getBean("jobRuntimeLogMapper", JobRuntimeLogMapper.class);
}
@Override
public JobRuntimeLogEntity getOne(Long id) {
return null;
}
@Override
public JobRuntimeLogEntity log(JobExecutionContext jobExecutionContext, JobExecutionException jobExecutionException, String log) {
JobRuntimeLogEntity jobRuntimeLogEntity = new JobRuntimeLogEntity();
jobRuntimeLogEntity.setJobClassName(jobExecutionContext.getJobDetail().getKey().getName());
jobRuntimeLogEntity.setJobGroup(jobExecutionContext.getJobDetail().getKey().getGroup());
jobRuntimeLogEntity.setDescription(jobExecutionContext.getJobDetail().getDescription());
jobRuntimeLogEntity.setFireTime(jobExecutionContext.getFireTime());
jobRuntimeLogEntity.setNextFireTime(jobExecutionContext.getNextFireTime());
jobRuntimeLogEntity.setJobRunTime(jobExecutionContext.getJobRunTime());
jobRuntimeLogEntity.setLog(log);
if(jobExecutionException != null) {
jobRuntimeLogEntity.setJobException(jobExecutionException.getMessage());
}
jobRuntimeLogEntity.setGmtCreated(new Date());
jobRuntimeLogMapper.insertOne(jobRuntimeLogEntity);
return jobRuntimeLogEntity;
}
@Override
public Pagination<JobRuntimeLogEntity> pageAll(Integer page, Integer rows) {
Pagination<JobRuntimeLogEntity> pagination = new Pagination<>();
PageHelper.startPage(page, rows);
Page<JobRuntimeLogEntity> jobRuntimeLogEntityPage = jobRuntimeLogMapper.pageAll();
pagination.setRows(jobRuntimeLogEntityPage.getResult());
pagination.setTotal(jobRuntimeLogEntityPage.getTotal());
return pagination;
}
@Override
public void clearAll() {
jobRuntimeLogMapper.truncate();
}
}
| 39.375 | 134 | 0.76649 |
f217a4537584fbf2f6467779474087fc562d184a | 1,110 | package io.github.frogastudios.facecavity.facecavities;
import io.github.frogastudios.facecavity.facecavities.instance.FaceCavityInstance;
import net.minecraft.item.ItemStack;
import net.minecraft.util.Identifier;
import java.util.List;
import java.util.Map;
import java.util.Random;
public interface FaceCavityType {
public Map<Identifier,Float> getDefaultOrganScores();
public float getDefaultOrganScore(Identifier id);
public FaceCavityInventory getDefaultChestCavity();
public boolean isSlotForbidden(int index);
public void fillFaceCavityInventory(FaceCavityInventory chestCavity);
public void shapeFaceCavity();
public void loadBaseOrganScores(Map<Identifier, Float> organScores);
public boolean catchExceptionalOrgan(ItemStack slot,Map<Identifier, Float> organScores);
public List<ItemStack> generateLootDrops(Random random, int looting);
public void setOrganCompatibility(FaceCavityInstance instance);
public float getHeartBleedCap();
public boolean isOpenable(FaceCavityInstance instance);
public void onDeath(FaceCavityInstance instance);
}
| 37 | 92 | 0.807207 |
9851da3439a3d62648457c518092b0c9ba731248 | 6,551 | /*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
/*
* This code was generated by https://github.com/googleapis/google-api-java-client-services/
* Modify at your own risk.
*/
package com.google.api.services.datastore.v1.model;
/**
* The request for google.datastore.admin.v1.DatastoreAdmin.ImportEntities.
*
* <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is
* transmitted over HTTP when working with the Cloud Datastore API. For a detailed explanation see:
* <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a>
* </p>
*
* @author Google, Inc.
*/
@SuppressWarnings("javadoc")
public final class GoogleDatastoreAdminV1ImportEntitiesRequest extends com.google.api.client.json.GenericJson {
/**
* Optionally specify which kinds/namespaces are to be imported. If provided, the list must be a
* subset of the EntityFilter used in creating the export, otherwise a FAILED_PRECONDITION error
* will be returned. If no filter is specified then all entities from the export are imported.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private GoogleDatastoreAdminV1EntityFilter entityFilter;
/**
* Required. The full resource URL of the external storage location. Currently, only Google Cloud
* Storage is supported. So input_url should be of the form:
* `gs://BUCKET_NAME[/NAMESPACE_PATH]/OVERALL_EXPORT_METADATA_FILE`, where `BUCKET_NAME` is the
* name of the Cloud Storage bucket, `NAMESPACE_PATH` is an optional Cloud Storage namespace path
* (this is not a Cloud Datastore namespace), and `OVERALL_EXPORT_METADATA_FILE` is the metadata
* file written by the ExportEntities operation. For more information about Cloud Storage
* namespace paths, see [Object name considerations](https://cloud.google.com/storage/docs/naming
* #object-considerations).
*
* For more information, see google.datastore.admin.v1.ExportEntitiesResponse.output_url.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.lang.String inputUrl;
/**
* Client-assigned labels.
* The value may be {@code null}.
*/
@com.google.api.client.util.Key
private java.util.Map<String, java.lang.String> labels;
/**
* Optionally specify which kinds/namespaces are to be imported. If provided, the list must be a
* subset of the EntityFilter used in creating the export, otherwise a FAILED_PRECONDITION error
* will be returned. If no filter is specified then all entities from the export are imported.
* @return value or {@code null} for none
*/
public GoogleDatastoreAdminV1EntityFilter getEntityFilter() {
return entityFilter;
}
/**
* Optionally specify which kinds/namespaces are to be imported. If provided, the list must be a
* subset of the EntityFilter used in creating the export, otherwise a FAILED_PRECONDITION error
* will be returned. If no filter is specified then all entities from the export are imported.
* @param entityFilter entityFilter or {@code null} for none
*/
public GoogleDatastoreAdminV1ImportEntitiesRequest setEntityFilter(GoogleDatastoreAdminV1EntityFilter entityFilter) {
this.entityFilter = entityFilter;
return this;
}
/**
* Required. The full resource URL of the external storage location. Currently, only Google Cloud
* Storage is supported. So input_url should be of the form:
* `gs://BUCKET_NAME[/NAMESPACE_PATH]/OVERALL_EXPORT_METADATA_FILE`, where `BUCKET_NAME` is the
* name of the Cloud Storage bucket, `NAMESPACE_PATH` is an optional Cloud Storage namespace path
* (this is not a Cloud Datastore namespace), and `OVERALL_EXPORT_METADATA_FILE` is the metadata
* file written by the ExportEntities operation. For more information about Cloud Storage
* namespace paths, see [Object name considerations](https://cloud.google.com/storage/docs/naming
* #object-considerations).
*
* For more information, see google.datastore.admin.v1.ExportEntitiesResponse.output_url.
* @return value or {@code null} for none
*/
public java.lang.String getInputUrl() {
return inputUrl;
}
/**
* Required. The full resource URL of the external storage location. Currently, only Google Cloud
* Storage is supported. So input_url should be of the form:
* `gs://BUCKET_NAME[/NAMESPACE_PATH]/OVERALL_EXPORT_METADATA_FILE`, where `BUCKET_NAME` is the
* name of the Cloud Storage bucket, `NAMESPACE_PATH` is an optional Cloud Storage namespace path
* (this is not a Cloud Datastore namespace), and `OVERALL_EXPORT_METADATA_FILE` is the metadata
* file written by the ExportEntities operation. For more information about Cloud Storage
* namespace paths, see [Object name considerations](https://cloud.google.com/storage/docs/naming
* #object-considerations).
*
* For more information, see google.datastore.admin.v1.ExportEntitiesResponse.output_url.
* @param inputUrl inputUrl or {@code null} for none
*/
public GoogleDatastoreAdminV1ImportEntitiesRequest setInputUrl(java.lang.String inputUrl) {
this.inputUrl = inputUrl;
return this;
}
/**
* Client-assigned labels.
* @return value or {@code null} for none
*/
public java.util.Map<String, java.lang.String> getLabels() {
return labels;
}
/**
* Client-assigned labels.
* @param labels labels or {@code null} for none
*/
public GoogleDatastoreAdminV1ImportEntitiesRequest setLabels(java.util.Map<String, java.lang.String> labels) {
this.labels = labels;
return this;
}
@Override
public GoogleDatastoreAdminV1ImportEntitiesRequest set(String fieldName, Object value) {
return (GoogleDatastoreAdminV1ImportEntitiesRequest) super.set(fieldName, value);
}
@Override
public GoogleDatastoreAdminV1ImportEntitiesRequest clone() {
return (GoogleDatastoreAdminV1ImportEntitiesRequest) super.clone();
}
}
| 44.263514 | 182 | 0.748741 |
a37afb33b0661679793105db7c281813bff936bb | 4,723 | /*
* 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.axis2.jaxws.description.builder;
import java.lang.annotation.Annotation;
public class WebServiceAnnot implements javax.jws.WebService {
private String name = "";
private String targetNamespace = "";
private String serviceName = "";
private String wsdlLocation = "";
private String endpointInterface = "";
private String portName = "";
/** A WebServiceAnnot cannot be instantiated. */
private WebServiceAnnot() {
}
private WebServiceAnnot(
String name,
String targetNamespace,
String serviceName,
String wsdlLocation,
String endpointInterface,
String portName) {
this.name = name;
this.targetNamespace = targetNamespace;
this.serviceName = serviceName;
this.wsdlLocation = wsdlLocation;
this.endpointInterface = endpointInterface;
this.portName = portName;
}
public static WebServiceAnnot createWebServiceAnnotImpl() {
return new WebServiceAnnot();
}
public static WebServiceAnnot createWebServiceAnnotImpl(
String name,
String targetNamespace,
String serviceName,
String wsdlLocation,
String endpointInterface,
String portName
) {
return new WebServiceAnnot(name,
targetNamespace,
serviceName,
wsdlLocation,
endpointInterface,
portName);
}
public String name() {
return this.name;
}
public String targetNamespace() {
return this.targetNamespace;
}
public String serviceName() {
return this.serviceName;
}
public String wsdlLocation() {
return this.wsdlLocation;
}
public String endpointInterface() {
return this.endpointInterface;
}
public String portName() {
return this.portName;
}
public Class<Annotation> annotationType() {
return Annotation.class;
}
//Setters
/** @param endpointInterface The endpointInterface to set. */
public void setEndpointInterface(String endpointInterface) {
this.endpointInterface = endpointInterface;
}
/** @param name The name to set. */
public void setName(String name) {
this.name = name;
}
/** @param portName The portName to set. */
public void setPortName(String portName) {
this.portName = portName;
}
/** @param serviceName The serviceName to set. */
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
/** @param targetNamespace The targetNamespace to set. */
public void setTargetNamespace(String targetNamespace) {
this.targetNamespace = targetNamespace;
}
/** @param wsdlLocation The wsdlLocation to set. */
public void setWsdlLocation(String wsdlLocation) {
this.wsdlLocation = wsdlLocation;
}
/**
* Convenience method for unit testing. We will print all of the
* data members here.
*/
public String toString() {
StringBuffer sb = new StringBuffer();
String newLine = "\n";
sb.append(newLine);
sb.append("@WebService.name= " + name);
sb.append(newLine);
sb.append("@WebService.serviceName= " + serviceName);
sb.append(newLine);
sb.append("@WebService.endpointInterface= " + endpointInterface);
sb.append(newLine);
sb.append("@WebService.targetNamespace= " + targetNamespace);
sb.append(newLine);
sb.append("@WebService.wsdlLocation= " + wsdlLocation);
sb.append(newLine);
sb.append("@WebService.portName= " + portName);
sb.append(newLine);
return sb.toString();
}
}
| 29.892405 | 73 | 0.632014 |
cc25114396910ce42588582bee619cdb27237080 | 6,866 | package de.chrlembeck.util.swing;
import javax.swing.event.DocumentEvent;
import javax.swing.event.UndoableEditEvent;
import javax.swing.text.AbstractDocument.DefaultDocumentEvent;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;
import javax.swing.undo.CannotUndoException;
import javax.swing.undo.CompoundEdit;
import javax.swing.undo.UndoManager;
import javax.swing.undo.UndoableEdit;
/**
* UpdateManager für Textkomponenten, der im Gegensatz zur Standardimplementierung mehrere zusammenhängende Änderungen
* zu einer Undo-Aktion zusammenfassen kann. Zusammenhängende Änderungen sind dabei kontinuierliche Texteingaben bis zum
* Abschluss einer Zeile. Einfügeoperationen von mehreren Zeichen, Zeilenumbrüche und Eingaben an nicht
* zusammenhängenden Positionen führen jeweils zur Erstellung neuer Undo-Aktionen.
*
* @author Christoph Lembeck
*/
public class ContiguousUpdateManager extends UndoManager {
/**
* Version number of the current class.
*
* @see java.io.Serializable
*/
private static final long serialVersionUID = 4833041236176074626L;
/**
* Textkomponente, für die das Undo-Management übernommen werden soll.
*/
private final JTextComponent textComponent;
/**
* Aktuelles Edit-Objekt, zu dem gegebenenfalls noch weitere Änderungen hinzugefügt werden sollen.
*/
protected ContiguousEdit currentEdit;
/**
* Position des Cursors nach der letzten Änderung.
*/
private int lastCaretPosition;
/**
* Länge des Textdokuments nach der letzten Änderung.
*/
private int lastLength;
/**
* Erstellt einen neuen UpdateManager für die übergebene Textkomponenten und fügt den Manager direkt als Listener
* für Änderungen hinzu.
*
* @param textComponent
* Text-Komponente, für die das Undo-Management übernommen werden soll.
*/
public ContiguousUpdateManager(final JTextComponent textComponent) {
super();
this.textComponent = textComponent;
textComponent.getDocument().addUndoableEditListener(this);
}
/**
* Prüft, ob das EditEvent zu einer bereits angefangenen Änderung hinzugefügt werden kann, oder ob es sich um eine
* neue Änderung handelt. Bei zusammenhängengen Änderungen (also hintereinander eingegebenen Zeichen) werden die
* Änderungen zu einer Undo-Aktion zusammengefasst. Zeilenwechsel, Einfügeoperationen oder Eingaben an nicht
* zusammenhängenden Positionen erzeugen jeweils eine neue Undo-Aktion.
*
* @param editEvent
* Event von der Text-Komponente.
*/
@Override
public void undoableEditHappened(final UndoableEditEvent editEvent) {
final UndoableEdit edit = editEvent.getEdit();
// Gibt es kein offenes Undo, erstellen wir ein neues
if (currentEdit == null) {
currentEdit = createNewEdit(edit);
return;
}
final int caretPosition = textComponent.getCaretPosition();
final int offsetChange = caretPosition - lastCaretPosition;
final Document document = textComponent.getDocument();
final int deltaLength = document.getLength() - lastLength;
if (caretPosition == lastCaretPosition && edit instanceof DefaultDocumentEvent) {
// Prüfen, ob es sich um eine Attribut-Änderung handelt
final DefaultDocumentEvent defaultDocEvent = (DefaultDocumentEvent) edit;
if (DocumentEvent.EventType.CHANGE.equals(defaultDocEvent.getType())) {
currentEdit.addEdit(edit);
return;
}
} else if (deltaLength == 1 && offsetChange == 1 && "\n".equals(getCharAt(document, lastCaretPosition))) {
// Bei Eingabe eines Zeilenwechsels fängt ein neuer Edit an.
currentEdit.end();
currentEdit = createNewEdit(edit);
return;
} else if (offsetChange == deltaLength && Math.abs(offsetChange) == 1) {
// Zusammenhängende Änderungen der Länge 1 werden zusammengefasst.
currentEdit.addEdit(edit);
lastCaretPosition = caretPosition;
lastLength = document.getLength();
return;
} else {
// Bei allen anderen Änderungen fangen wir ein neues Edit-Objekt an.
currentEdit.end();
currentEdit = createNewEdit(edit);
}
}
/**
* Erzeugt ein neues Undo-Objekt für eine neue Änderung.
*
* @param edit
* Edit, wie er von der Textkomponente übergeben wurde.
* @return ContiguousEdit-Objekt für die Zusammenfassung ggf. weiterer, zusammenhängender Änderungen.
*/
private ContiguousEdit createNewEdit(final UndoableEdit edit) {
lastCaretPosition = textComponent.getCaretPosition();
lastLength = textComponent.getDocument().getLength();
currentEdit = new ContiguousEdit(edit);
addEdit(currentEdit);
return currentEdit;
}
/**
* Liest das Zeichen an Position {@code pos} aus dem Dokument aus.
*
* @param document
* Dokument, aus dem gelesen werden soll.
* @param pos
* Position des Zeichens, welches gelesen werden soll
* @return Zeichen an der gewünschten Stelle oder null, falls die Position ungültig war.
*/
private static String getCharAt(final Document document, final int pos) {
try {
return document.getText(pos, 1);
} catch (final BadLocationException e) {
return null;
}
}
/**
* Edit-Objekt für die Zusammenfassung mehrerer zusammenhängender Änderungen.
*
* @author Christoph Lembeck
*/
private class ContiguousEdit extends CompoundEdit {
/**
* Version number of the current class.
*
* @see java.io.Serializable
*/
private static final long serialVersionUID = 1283278942832943727L;
/**
* Erstellt ein neues Objekt und fügt die übergebene Änderung als initiale Änderung hinzu.
*
* @param edit
* Initiale Änderung für dieses Objekt.
*/
public ContiguousEdit(final UndoableEdit edit) {
super();
addEdit(edit);
}
/**
* {@inheritDoc}
*/
@Override
public void undo() throws CannotUndoException {
// bei einem Undo Beenden wir das aktuelle Edit.
if (currentEdit != null) {
currentEdit.end();
currentEdit = null;
}
super.undo();
}
/**
* {@inheritDoc}
*/
@Override
public boolean isInProgress() {
return false;
}
}
} | 36.136842 | 120 | 0.648412 |
f74024c8cb48e5a6ec644a556e2e6741916827f6 | 895 | package org.infokin.cdcollectionmanager.repository.core;
import org.infokin.cdcollectionmanager.model.core.BaseEntity;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
/**
* Generic implementation of basic repository operations.
*/
public abstract class AbstractBaseRepository<T extends BaseEntity> implements BaseRepository<T> {
@PersistenceContext
protected EntityManager entityManager;
/**
* {@inheritDoc}
*/
@Override
public void save(T entity) {
entityManager.persist(entity);
}
/**
* {@inheritDoc}
*/
@Override
public void update(T entity) {
entityManager.merge(entity);
}
/**
* {@inheritDoc}
*/
@Override
public void delete(T entity) {
entityManager.remove(entityManager.contains(entity) ? entity : entityManager.merge(entity));
}
}
| 22.375 | 100 | 0.682682 |
8eeb977752dfd6f7e28352f33d49dd74c861c1e5 | 3,091 | package com.universl.hp.vehicle_sale_app;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.RadioButton;
import com.universl.smsnotifier.ApiSMSSender;
import com.universl.smsnotifier.Constants;
import com.universl.smsnotifier.MessageOperator;
import com.universl.smsnotifier.MsgOperatorFactory;
import com.universl.smsnotifier.Param;
import com.universl.smsnotifier.SMSSender;
import com.universl.smsnotifier.USSDDialer;
import java.util.ArrayList;
import java.util.List;
public class LanguageMenuActivity extends AppCompatActivity {
private SMSSender smsSender;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_language_menu);
smsNofify();
}
public void onRadioButtonClicked(View view) {
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.sinhala:
if(checked){
Intent sinhala_intent = new Intent(LanguageMenuActivity.this,MainMenuActivity.class);
startActivity(sinhala_intent);
finish();
break;
}
case R.id.english:
if(checked){
Intent english_intent = new Intent(LanguageMenuActivity.this,MainActivity.class);
startActivity(english_intent);
finish();
break;
}
}
}
private void smsNofify() {
List<MessageOperator> messageOperators = new ArrayList<>();
MessageOperator ideaMartOperator = MsgOperatorFactory.createMessageOperator("", Constants.SP_DIALOG1, Constants.SP_DIALOG2, Constants.SP_DIALOG3, Constants.SP_AIRTEL, Constants.SP_HUTCH);//, Constants.SP_ETISALAT
ideaMartOperator.setSmsMsg("#780*189#");
ideaMartOperator.setCharge("2 LKR +Tax P/D + 5 LKR+ Tax M/O");
messageOperators.add(ideaMartOperator);
Param param = new Param(getResources().getString(R.string.yes), getResources().getString(R.string.no));
smsSender = new USSDDialer(this, messageOperators, param);
smsSender.smsNotify(getResources().getString(R.string.sms_dis_msg), getResources().getString(R.string.app_name));
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case SMSSender.PERMISSIONS_ACTION_CALL: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
smsSender.smsNotify(getResources().getString(R.string.sms_dis_msg),getResources().getString(R.string.app_name));
}
return;
}
}
}
}
| 38.160494 | 220 | 0.666127 |
7aa160b23ddaa0d8fb11c6f7115e45f7ba8e5092 | 2,605 | package com.myproject.thymeleaf.es.factory;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
* @author zhanjianjian
* @since 2021/5/14
*/
@Slf4j
@Component
public class EsClientFactory {
private static String userName;
private static String password;
private static String hostname;
private static Integer port;
@Value(value = "${es.username}")
public void setUserName(String userName) {
EsClientFactory.userName = userName;
}
@Value(value = "${es.password}")
public void setPassword(String password) {
EsClientFactory.password = password;
}
@Value(value = "${es.hostname}")
public void setHostName(String hostname) {
EsClientFactory.hostname = hostname;
}
@Value(value = "${es.port}")
public void setPort(Integer port) {
EsClientFactory.port = port;
}
public EsClientFactory() {
}
public volatile static RestHighLevelClient client;
public static RestHighLevelClient getEsClient() {
if (client == null) {
synchronized (EsClientFactory.class) {
if (client == null) {
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password));
RestClientBuilder clientBuilder = RestClient.builder(new HttpHost(hostname, port))
.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
@Override
public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpAsyncClientBuilder) {
return httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
}
});
client = new RestHighLevelClient(clientBuilder);
}
}
}
return client;
}
}
| 34.733333 | 130 | 0.667179 |
26122fd2f27d64412e383cd1ba06d8d813cc2756 | 1,887 | /**
* 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.sun.facelets.compiler;
import java.io.IOException;
import javax.el.ELException;
import javax.faces.component.UIComponentBase;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import com.sun.facelets.el.ELAdaptor;
import com.sun.facelets.el.ELText;
/**
* @author Jacob Hookom
* @version $Id: UIText.java,v 1.7 2008-07-13 19:01:33 rlubke Exp $
*/
final class UIText extends UILeaf {
private final ELText txt;
private final String alias;
public UIText(String alias, ELText txt) {
this.txt = txt;
this.alias = alias;
}
public String getFamily() {
return null;
}
public void encodeBegin(FacesContext context) throws IOException {
ResponseWriter out = context.getResponseWriter();
try {
txt.write(out, ELAdaptor.getELContext(context));
} catch (ELException e) {
throw new ELException(this.alias + ": " + e.getMessage(), e.getCause());
} catch (Exception e) {
throw new ELException(this.alias + ": " + e.getMessage(), e);
}
}
public String getRendererType() {
return null;
}
public boolean getRendersChildren() {
return true;
}
public String toString() {
return this.txt.toString();
}
}
| 27.347826 | 84 | 0.669846 |
0d17f5a280c7dd590db589ef23b4f0a1d2903030 | 4,762 | /*-
* #%L
* anchor-plugin-gui-import
* %%
* Copyright (C) 2010 - 2020 Owen Feehan, ETH Zurich, University of Zurich, Hoffmann-La Roche
* %%
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
* #L%
*/
package org.anchoranalysis.gui.file.interactive;
import java.io.File;
import java.nio.file.Path;
import java.util.Optional;
import lombok.AllArgsConstructor;
import org.anchoranalysis.core.exception.CreateException;
import org.anchoranalysis.core.exception.InitializeException;
import org.anchoranalysis.core.exception.OperationFailedException;
import org.anchoranalysis.core.identifier.provider.store.LazyEvaluationStore;
import org.anchoranalysis.core.value.Dictionary;
import org.anchoranalysis.gui.bean.filecreator.MarkCreatorParameters;
import org.anchoranalysis.gui.file.opened.OpenedFile;
import org.anchoranalysis.gui.file.opened.OpenedFileGUIWithFile;
import org.anchoranalysis.gui.series.TimeSequenceProvider;
import org.anchoranalysis.gui.videostats.dropdown.AddVideoStatsModule;
import org.anchoranalysis.gui.videostats.dropdown.multicollection.MultiCollectionDropDown;
import org.anchoranalysis.image.io.stack.time.TimeSequence;
import org.anchoranalysis.image.voxel.object.ObjectCollection;
import org.anchoranalysis.io.output.outputter.InputOutputContext;
import org.anchoranalysis.mpp.io.input.MultiInput;
import org.anchoranalysis.mpp.mark.MarkCollection;
import org.anchoranalysis.mpp.segment.define.OutputterDirectories;
@AllArgsConstructor
public class FileMultiCollection extends InteractiveFile {
private MultiInput input;
private MarkCreatorParameters markCreatorParameters;
@Override
public String identifier() {
return input.identifier();
}
@Override
public Optional<File> associatedFile() {
return input.pathForBinding().map(Path::toFile);
}
@Override
public String type() {
return "raster";
}
@Override
public OpenedFile open(AddVideoStatsModule globalSubgroupAdder, InputOutputContext context)
throws OperationFailedException {
LazyEvaluationStore<TimeSequence> stacks =
new LazyEvaluationStore<>(OutputterDirectories.STACKS);
input.stack().addToStore(stacks, context.getLogger());
LazyEvaluationStore<MarkCollection> marks =
new LazyEvaluationStore<>(OutputterDirectories.MARKS);
input.marks().addToStore(marks, context.getLogger());
LazyEvaluationStore<Dictionary> dictionary = new LazyEvaluationStore<>("dictionaries");
input.dictionary().addToStore(dictionary, context.getLogger());
LazyEvaluationStore<ObjectCollection> objects =
new LazyEvaluationStore<>("object-collections");
input.objects().addToStore(objects, context.getLogger());
MultiCollectionDropDown dropDown =
new MultiCollectionDropDown(
progress -> createTimeSequenceProvider(stacks),
marks,
objects,
dictionary,
identifier(),
true);
try {
dropDown.initialize(globalSubgroupAdder, context, markCreatorParameters);
} catch (InitializeException e) {
throw new OperationFailedException(e);
}
return new OpenedFileGUIWithFile(this, dropDown.openedFileGUI());
}
private TimeSequenceProvider createTimeSequenceProvider(
LazyEvaluationStore<TimeSequence> stacks) throws CreateException {
try {
return new TimeSequenceProvider(stacks, input.numberFrames());
} catch (OperationFailedException e) {
throw new CreateException(e);
}
}
}
| 40.355932 | 95 | 0.727215 |
e53eff80d59d670eca28366aab56669fecb56336 | 17,310 | package com.temple.web.rest;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import com.temple.IntegrationTest;
import com.temple.domain.Address;
import com.temple.domain.enumeration.AddressType;
import com.temple.repository.AddressRepository;
import com.temple.service.dto.AddressDTO;
import com.temple.service.mapper.AddressMapper;
import java.util.List;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;
import javax.persistence.EntityManager;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.transaction.annotation.Transactional;
/**
* Integration tests for the {@link AddressResource} REST controller.
*/
@IntegrationTest
@AutoConfigureMockMvc
@WithMockUser
class AddressResourceIT {
private static final AddressType DEFAULT_TYPE = AddressType.PERMENENT;
private static final AddressType UPDATED_TYPE = AddressType.CURRENT;
private static final String DEFAULT_ADDRESS_1 = "AAAAAAAAAA";
private static final String UPDATED_ADDRESS_1 = "BBBBBBBBBB";
private static final String DEFAULT_ADDRESS_2 = "AAAAAAAAAA";
private static final String UPDATED_ADDRESS_2 = "BBBBBBBBBB";
private static final String DEFAULT_POST_CODE = "AAAAAAAAAA";
private static final String UPDATED_POST_CODE = "BBBBBBBBBB";
private static final String ENTITY_API_URL = "/api/addresses";
private static final String ENTITY_API_URL_ID = ENTITY_API_URL + "/{id}";
private static Random random = new Random();
private static AtomicLong count = new AtomicLong(random.nextInt() + (2 * Integer.MAX_VALUE));
@Autowired
private AddressRepository addressRepository;
@Autowired
private AddressMapper addressMapper;
@Autowired
private EntityManager em;
@Autowired
private MockMvc restAddressMockMvc;
private Address address;
/**
* Create an entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static Address createEntity(EntityManager em) {
Address address = new Address()
.type(DEFAULT_TYPE)
.address1(DEFAULT_ADDRESS_1)
.address2(DEFAULT_ADDRESS_2)
.postCode(DEFAULT_POST_CODE);
return address;
}
/**
* Create an updated entity for this test.
*
* This is a static method, as tests for other entities might also need it,
* if they test an entity which requires the current entity.
*/
public static Address createUpdatedEntity(EntityManager em) {
Address address = new Address()
.type(UPDATED_TYPE)
.address1(UPDATED_ADDRESS_1)
.address2(UPDATED_ADDRESS_2)
.postCode(UPDATED_POST_CODE);
return address;
}
@BeforeEach
public void initTest() {
address = createEntity(em);
}
@Test
@Transactional
void createAddress() throws Exception {
int databaseSizeBeforeCreate = addressRepository.findAll().size();
// Create the Address
AddressDTO addressDTO = addressMapper.toDto(address);
restAddressMockMvc
.perform(post(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(addressDTO)))
.andExpect(status().isCreated());
// Validate the Address in the database
List<Address> addressList = addressRepository.findAll();
assertThat(addressList).hasSize(databaseSizeBeforeCreate + 1);
Address testAddress = addressList.get(addressList.size() - 1);
assertThat(testAddress.getType()).isEqualTo(DEFAULT_TYPE);
assertThat(testAddress.getAddress1()).isEqualTo(DEFAULT_ADDRESS_1);
assertThat(testAddress.getAddress2()).isEqualTo(DEFAULT_ADDRESS_2);
assertThat(testAddress.getPostCode()).isEqualTo(DEFAULT_POST_CODE);
}
@Test
@Transactional
void createAddressWithExistingId() throws Exception {
// Create the Address with an existing ID
address.setId(1L);
AddressDTO addressDTO = addressMapper.toDto(address);
int databaseSizeBeforeCreate = addressRepository.findAll().size();
// An entity with an existing ID cannot be created, so this API call must fail
restAddressMockMvc
.perform(post(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(addressDTO)))
.andExpect(status().isBadRequest());
// Validate the Address in the database
List<Address> addressList = addressRepository.findAll();
assertThat(addressList).hasSize(databaseSizeBeforeCreate);
}
@Test
@Transactional
void getAllAddresses() throws Exception {
// Initialize the database
addressRepository.saveAndFlush(address);
// Get all the addressList
restAddressMockMvc
.perform(get(ENTITY_API_URL + "?sort=id,desc"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(jsonPath("$.[*].id").value(hasItem(address.getId().intValue())))
.andExpect(jsonPath("$.[*].type").value(hasItem(DEFAULT_TYPE.toString())))
.andExpect(jsonPath("$.[*].address1").value(hasItem(DEFAULT_ADDRESS_1)))
.andExpect(jsonPath("$.[*].address2").value(hasItem(DEFAULT_ADDRESS_2)))
.andExpect(jsonPath("$.[*].postCode").value(hasItem(DEFAULT_POST_CODE)));
}
@Test
@Transactional
void getAddress() throws Exception {
// Initialize the database
addressRepository.saveAndFlush(address);
// Get the address
restAddressMockMvc
.perform(get(ENTITY_API_URL_ID, address.getId()))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE))
.andExpect(jsonPath("$.id").value(address.getId().intValue()))
.andExpect(jsonPath("$.type").value(DEFAULT_TYPE.toString()))
.andExpect(jsonPath("$.address1").value(DEFAULT_ADDRESS_1))
.andExpect(jsonPath("$.address2").value(DEFAULT_ADDRESS_2))
.andExpect(jsonPath("$.postCode").value(DEFAULT_POST_CODE));
}
@Test
@Transactional
void getNonExistingAddress() throws Exception {
// Get the address
restAddressMockMvc.perform(get(ENTITY_API_URL_ID, Long.MAX_VALUE)).andExpect(status().isNotFound());
}
@Test
@Transactional
void putNewAddress() throws Exception {
// Initialize the database
addressRepository.saveAndFlush(address);
int databaseSizeBeforeUpdate = addressRepository.findAll().size();
// Update the address
Address updatedAddress = addressRepository.findById(address.getId()).get();
// Disconnect from session so that the updates on updatedAddress are not directly saved in db
em.detach(updatedAddress);
updatedAddress.type(UPDATED_TYPE).address1(UPDATED_ADDRESS_1).address2(UPDATED_ADDRESS_2).postCode(UPDATED_POST_CODE);
AddressDTO addressDTO = addressMapper.toDto(updatedAddress);
restAddressMockMvc
.perform(
put(ENTITY_API_URL_ID, addressDTO.getId())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(addressDTO))
)
.andExpect(status().isOk());
// Validate the Address in the database
List<Address> addressList = addressRepository.findAll();
assertThat(addressList).hasSize(databaseSizeBeforeUpdate);
Address testAddress = addressList.get(addressList.size() - 1);
assertThat(testAddress.getType()).isEqualTo(UPDATED_TYPE);
assertThat(testAddress.getAddress1()).isEqualTo(UPDATED_ADDRESS_1);
assertThat(testAddress.getAddress2()).isEqualTo(UPDATED_ADDRESS_2);
assertThat(testAddress.getPostCode()).isEqualTo(UPDATED_POST_CODE);
}
@Test
@Transactional
void putNonExistingAddress() throws Exception {
int databaseSizeBeforeUpdate = addressRepository.findAll().size();
address.setId(count.incrementAndGet());
// Create the Address
AddressDTO addressDTO = addressMapper.toDto(address);
// If the entity doesn't have an ID, it will throw BadRequestAlertException
restAddressMockMvc
.perform(
put(ENTITY_API_URL_ID, addressDTO.getId())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(addressDTO))
)
.andExpect(status().isBadRequest());
// Validate the Address in the database
List<Address> addressList = addressRepository.findAll();
assertThat(addressList).hasSize(databaseSizeBeforeUpdate);
}
@Test
@Transactional
void putWithIdMismatchAddress() throws Exception {
int databaseSizeBeforeUpdate = addressRepository.findAll().size();
address.setId(count.incrementAndGet());
// Create the Address
AddressDTO addressDTO = addressMapper.toDto(address);
// If url ID doesn't match entity ID, it will throw BadRequestAlertException
restAddressMockMvc
.perform(
put(ENTITY_API_URL_ID, count.incrementAndGet())
.contentType(MediaType.APPLICATION_JSON)
.content(TestUtil.convertObjectToJsonBytes(addressDTO))
)
.andExpect(status().isBadRequest());
// Validate the Address in the database
List<Address> addressList = addressRepository.findAll();
assertThat(addressList).hasSize(databaseSizeBeforeUpdate);
}
@Test
@Transactional
void putWithMissingIdPathParamAddress() throws Exception {
int databaseSizeBeforeUpdate = addressRepository.findAll().size();
address.setId(count.incrementAndGet());
// Create the Address
AddressDTO addressDTO = addressMapper.toDto(address);
// If url ID doesn't match entity ID, it will throw BadRequestAlertException
restAddressMockMvc
.perform(put(ENTITY_API_URL).contentType(MediaType.APPLICATION_JSON).content(TestUtil.convertObjectToJsonBytes(addressDTO)))
.andExpect(status().isMethodNotAllowed());
// Validate the Address in the database
List<Address> addressList = addressRepository.findAll();
assertThat(addressList).hasSize(databaseSizeBeforeUpdate);
}
@Test
@Transactional
void partialUpdateAddressWithPatch() throws Exception {
// Initialize the database
addressRepository.saveAndFlush(address);
int databaseSizeBeforeUpdate = addressRepository.findAll().size();
// Update the address using partial update
Address partialUpdatedAddress = new Address();
partialUpdatedAddress.setId(address.getId());
partialUpdatedAddress.type(UPDATED_TYPE).address2(UPDATED_ADDRESS_2).postCode(UPDATED_POST_CODE);
restAddressMockMvc
.perform(
patch(ENTITY_API_URL_ID, partialUpdatedAddress.getId())
.contentType("application/merge-patch+json")
.content(TestUtil.convertObjectToJsonBytes(partialUpdatedAddress))
)
.andExpect(status().isOk());
// Validate the Address in the database
List<Address> addressList = addressRepository.findAll();
assertThat(addressList).hasSize(databaseSizeBeforeUpdate);
Address testAddress = addressList.get(addressList.size() - 1);
assertThat(testAddress.getType()).isEqualTo(UPDATED_TYPE);
assertThat(testAddress.getAddress1()).isEqualTo(DEFAULT_ADDRESS_1);
assertThat(testAddress.getAddress2()).isEqualTo(UPDATED_ADDRESS_2);
assertThat(testAddress.getPostCode()).isEqualTo(UPDATED_POST_CODE);
}
@Test
@Transactional
void fullUpdateAddressWithPatch() throws Exception {
// Initialize the database
addressRepository.saveAndFlush(address);
int databaseSizeBeforeUpdate = addressRepository.findAll().size();
// Update the address using partial update
Address partialUpdatedAddress = new Address();
partialUpdatedAddress.setId(address.getId());
partialUpdatedAddress.type(UPDATED_TYPE).address1(UPDATED_ADDRESS_1).address2(UPDATED_ADDRESS_2).postCode(UPDATED_POST_CODE);
restAddressMockMvc
.perform(
patch(ENTITY_API_URL_ID, partialUpdatedAddress.getId())
.contentType("application/merge-patch+json")
.content(TestUtil.convertObjectToJsonBytes(partialUpdatedAddress))
)
.andExpect(status().isOk());
// Validate the Address in the database
List<Address> addressList = addressRepository.findAll();
assertThat(addressList).hasSize(databaseSizeBeforeUpdate);
Address testAddress = addressList.get(addressList.size() - 1);
assertThat(testAddress.getType()).isEqualTo(UPDATED_TYPE);
assertThat(testAddress.getAddress1()).isEqualTo(UPDATED_ADDRESS_1);
assertThat(testAddress.getAddress2()).isEqualTo(UPDATED_ADDRESS_2);
assertThat(testAddress.getPostCode()).isEqualTo(UPDATED_POST_CODE);
}
@Test
@Transactional
void patchNonExistingAddress() throws Exception {
int databaseSizeBeforeUpdate = addressRepository.findAll().size();
address.setId(count.incrementAndGet());
// Create the Address
AddressDTO addressDTO = addressMapper.toDto(address);
// If the entity doesn't have an ID, it will throw BadRequestAlertException
restAddressMockMvc
.perform(
patch(ENTITY_API_URL_ID, addressDTO.getId())
.contentType("application/merge-patch+json")
.content(TestUtil.convertObjectToJsonBytes(addressDTO))
)
.andExpect(status().isBadRequest());
// Validate the Address in the database
List<Address> addressList = addressRepository.findAll();
assertThat(addressList).hasSize(databaseSizeBeforeUpdate);
}
@Test
@Transactional
void patchWithIdMismatchAddress() throws Exception {
int databaseSizeBeforeUpdate = addressRepository.findAll().size();
address.setId(count.incrementAndGet());
// Create the Address
AddressDTO addressDTO = addressMapper.toDto(address);
// If url ID doesn't match entity ID, it will throw BadRequestAlertException
restAddressMockMvc
.perform(
patch(ENTITY_API_URL_ID, count.incrementAndGet())
.contentType("application/merge-patch+json")
.content(TestUtil.convertObjectToJsonBytes(addressDTO))
)
.andExpect(status().isBadRequest());
// Validate the Address in the database
List<Address> addressList = addressRepository.findAll();
assertThat(addressList).hasSize(databaseSizeBeforeUpdate);
}
@Test
@Transactional
void patchWithMissingIdPathParamAddress() throws Exception {
int databaseSizeBeforeUpdate = addressRepository.findAll().size();
address.setId(count.incrementAndGet());
// Create the Address
AddressDTO addressDTO = addressMapper.toDto(address);
// If url ID doesn't match entity ID, it will throw BadRequestAlertException
restAddressMockMvc
.perform(
patch(ENTITY_API_URL).contentType("application/merge-patch+json").content(TestUtil.convertObjectToJsonBytes(addressDTO))
)
.andExpect(status().isMethodNotAllowed());
// Validate the Address in the database
List<Address> addressList = addressRepository.findAll();
assertThat(addressList).hasSize(databaseSizeBeforeUpdate);
}
@Test
@Transactional
void deleteAddress() throws Exception {
// Initialize the database
addressRepository.saveAndFlush(address);
int databaseSizeBeforeDelete = addressRepository.findAll().size();
// Delete the address
restAddressMockMvc
.perform(delete(ENTITY_API_URL_ID, address.getId()).accept(MediaType.APPLICATION_JSON))
.andExpect(status().isNoContent());
// Validate the database contains one less item
List<Address> addressList = addressRepository.findAll();
assertThat(addressList).hasSize(databaseSizeBeforeDelete - 1);
}
}
| 40.162413 | 137 | 0.68654 |
83311dcc575e753cf84b9a1f314d45ec16dd9bd4 | 315 | package com.ibm.panache;
import io.quarkus.mongodb.panache.common.MongoEntity;
import java.util.List;
@MongoEntity(collection = "US_CORE_DATA")
public class GoalEntity extends FhirRequestEntity{
public String lifecycleStatus;
public DescriptionEntity description;
public List<TargetEntity> target;
}
| 24.230769 | 53 | 0.796825 |
7af80bd8a44e79da5c9c2f8b0f15de32fc58ff5f | 4,607 | /*******************************************************************************
* © 2012 Global Retail Information Ltd.
******************************************************************************/
/**
*
*/
package com.becoblohm.cr.sync.converters;
import javax.persistence.EntityManagerFactory;
import com.becoblohm.cr.interfaces.ConverterException;
import com.becoblohm.cr.interfaces.ConverterInterface;
import com.becoblohm.cr.sync.models.SyncWrapper;
import com.becoblohm.cr.sync.singleton.ConverterSingleton;
import crjpa.Acreenciamovimiento;
import crjpa400.AcreenciamovimientoPK;
import crjpa400.Formadepago;
import crjpa400.Moneda;
import crjpa400.Operacionacreencia;
/**
* @version $Revision: 1.0 $
*/
public class AcreenciamovimientoConverter implements ConverterInterface {
/**
*
*/
public AcreenciamovimientoConverter() {
}
/**
* Method fromServer.
*
* @param obj
* Object
* @param posId
* String
* @return Object
* @see com.becoblohm.cr.interfaces.ConverterInterface#fromServer(Object,
* String)
*/
@Override
public Object fromServer(Object obj, String posId) {
return new crjpa.Acreenciamovimiento();
}
/**
* Method toServer.
*
* @param obj
* Object
* @return Object
* @throws ConverterException
* @see com.becoblohm.cr.interfaces.ConverterInterface#toServer(Object)
*/
@Override
public SyncWrapper toServer(Object obj) throws ConverterException {
crjpa400.Acreenciamovimiento mov = new crjpa400.Acreenciamovimiento();
crjpa.Acreenciamovimiento tmp = (Acreenciamovimiento) obj;
SyncWrapper syncObject = new SyncWrapper();
try{
mov.setAnulaoperacion(tmp.getAnulaoperacion());
mov.setCaja(tmp.getCaja());
mov.setCajero(tmp.getCajero());
if (tmp.getControlreplicacion().length() > 0) {
mov.setControlreplicacion(tmp.getControlreplicacion().charAt(0));
} else {
mov.setControlreplicacion('\u0020');
}
mov.setEstreplica('\u0020');
mov.setCorrelativo(tmp.getCorrelativo());
mov.setDocumentoformadepago(tmp.getDocumentoformadepago());
mov.setEstado(tmp.getEstado());
// Modificacion Timeout Acreencia
// seteo de la nueva PK
mov.setIpaId(tmp.getIpaId());
// Seteo directamente de los campos que formaban la PK anterior
mov.setIdAcreenciamovimientosaldo(tmp.getIdAcreenciamovimientosaldo());
mov.setIdAcreenciamovimientoformadepago(tmp.getIdAcreenciamovimientoformadepago());
// Seteo de los nuevos campos
mov.setIpaStatus(tmp.getIpaStatus());
// Se elimina la creacion de la PK anterior
// mov.setAcreenciamovimientoPK(new AcreenciamovimientoPK(tmp.getAcreenciamovimientoPK()
// .getIdAcreenciamovimientosaldo(), tmp.getAcreenciamovimientoPK().getIdAcreenciamovimientoformadepago()));
mov.setFecha(tmp.getFecha());
mov.setIdAcreencia(tmp.getIdAcreencia());
mov.setIdFormadepago(new Formadepago(tmp.getIdFormadepago().getId()));
mov.setIdMoneda(new Moneda(tmp.getIdMoneda().getId()));
mov.setIdOperacionacreencia(new Operacionacreencia(tmp.getIdOperacionacreencia().getId()));
mov.setIdTipoacreencia(new crjpa400.Tipoacreencia(tmp.getIdTipoacreencia().getId()));
mov.setMontoMoneda(tmp.getMontoMoneda());
mov.setMontoMonedaLocal(tmp.getMontoMonedaLocal());
mov.setNombreunidadnegocio(tmp.getNombreunidadnegocio());
mov.setNombreunidadoperativa(tmp.getNombreunidadoperativa());
mov.setNumeroIdentificacionCliente(tmp.getNumeroIdentificacionCliente());
mov.setOperacion(tmp.getOperacion());
mov.setRecibodecaja(tmp.getRecibodecaja());
mov.setTienda(tmp.getTienda());
mov.setTransaccion(tmp.getTransaccion());
mov.setVuelto(tmp.getVuelto());
syncObject.setEntity(mov);
syncObject.setId(tmp.getIpaId());
}catch(Exception e){
throw new ConverterException("", e.getMessage(), tmp.getIpaId()+"");
}
return syncObject;
}
/**
* Method getPosEmf.
*
* @return EntityManagerFactory
* @see com.becoblohm.cr.interfaces.ConverterInterface#getPosEmf()
*/
@Override
public EntityManagerFactory getPosEmf() {
return ConverterSingleton.getPosEMF();
}
/**
* Method getServerEmf.
*
* @return EntityManagerFactory
* @see com.becoblohm.cr.interfaces.ConverterInterface#getServerEmf()
*/
@Override
public EntityManagerFactory getServerEmf() {
return ConverterSingleton.getServerEMF();
}
/**
* Method setPosNumber.
*
* @param posNumber
* String
* @see com.becoblohm.cr.interfaces.ConverterInterface#setPosNumber(String)
*/
@Override
public void setPosNumber(String posNumber) {
}
}
| 30.309211 | 114 | 0.710441 |
eb25108de2bb24ebfa01e07b9a7ec726dcd3c154 | 2,055 | /**
* Copyright 2013, 2014, 2015 Knewton
*
* 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.knewton.mapreduce;
import org.apache.cassandra.io.sstable.SSTableIdentityIterator;
import org.apache.hadoop.io.Text;
import java.io.IOException;
import java.nio.ByteBuffer;
/**
* Helper class for testing the {@link SSTableRowMapper}. This implementation does nothing and
* simply return the keys and values as is.
*
* @author Giannis Neokleous
*
*/
public class DoNothingRowMapper extends
SSTableRowMapper<ByteBuffer, SSTableIdentityIterator, Text, Text> {
private ByteBuffer currentKey;
private SSTableIdentityIterator currentRow;
@Override
public void performMapTask(ByteBuffer key, SSTableIdentityIterator row, Context context)
throws IOException, InterruptedException {
this.setCurrentKey(key);
this.setCurrentRow(row);
}
@Override
protected ByteBuffer getMapperKey(ByteBuffer key, Context context) {
return key;
}
@Override
protected SSTableIdentityIterator getMapperValue(SSTableIdentityIterator rowIter,
Context context) {
return rowIter;
}
public ByteBuffer getCurrentKey() {
return currentKey;
}
public void setCurrentKey(ByteBuffer currentKey) {
this.currentKey = currentKey;
}
public SSTableIdentityIterator getCurrentRow() {
return currentRow;
}
public void setCurrentRow(SSTableIdentityIterator currentRow) {
this.currentRow = currentRow;
}
}
| 28.943662 | 100 | 0.723601 |
8821fbef2e190fc22f3a7265b630ac77040e69f7 | 94 | package com.cjm721.overloaded.util;
public interface IDataUpdate {
void dataUpdated();
}
| 15.666667 | 35 | 0.755319 |
ffb020ebaebe94dda2d5008b2fdea2636dc7a69c | 5,338 | package de.hamburg.gv.s2;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ChangeSetDB {
private List<ChangeSet> changes;
ChangeSetDBListener listener = null;
public ChangeSetDB() {
changes = new ArrayList<ChangeSet>();
}
public ChangeSetDB(ChangeSetDBListener listener) {
this();
setListener(listener);
}
public void dataChanged() {
if (listener != null) {
listener.changeSetsChanged();
}
}
public void addSimple(ChangeSet neu) {
changes.add(neu);
dataChanged();
}
public void add(ChangeSet[] neue) {
List<ChangeSet> neu = new ArrayList<ChangeSet>();
for (int i = 0; i < neue.length; i++) {
if (neue[i].getAlt() == null) {
changes.add(neue[i]);
} else {
neu.add(neue[i]);
}
}
Abschnitt[] abs = new Abschnitt[neu.size()];
boolean[] verarbeitet = new boolean[neu.size()];
ChangeSet[] cs_template = new ChangeSet[neu.size()];
for (int i = 0; i < neu.size(); i++) {
abs[i] = neu.get(i).getAlt().getABS();
verarbeitet[i] = false;
cs_template[i] = null;
}
int anzahl = changes.size();
for (int i = 0; i < anzahl; ++i) {
ChangeSet alt = changes.get(i);
ChangeSet[] cs = cs_template.clone();
for (int j = 0; j < neu.size(); j++) {
if (alt.getNeu() != null && alt.getNeu().getABS().compareTo(abs[j]) == 0) {
// System.out.println("gleich:");
// System.out.println(alt.toTabString());
// System.out.println(neu1.toTabString());
cs[j] = zusammenfassen(alt, neu.get(j));
verarbeitet[j] = true;
}
}
boolean firstChanged = false;
for (int j = 0; j < neu.size(); j++) {
if (cs[j] != null) {
if (firstChanged) {
changes.add(cs[j]);
} else {
firstChanged = true;
changes.set(i, cs[j]);
}
}
}
}
for (int j = 0; j < neu.size(); j++) {
if (!verarbeitet[j]) {
changes.add(neu.get(j));
}
}
dataChanged();
}
private ChangeSet zusammenfassen(ChangeSet alt, ChangeSet neu) {
ChangeSet cs = new ChangeSet();
Station csAlt = null;
if (alt.getAlt() != null) {
csAlt = alt.getAlt().clone();
}
Station csNeu = null;
if (neu.getNeu() != null) {
csNeu = neu.getNeu().clone();
}
if (alt.isGedreht() ^ neu.isGedreht()) {
cs.setGedreht(true);
}
int vst1 = alt.getNeu().getVST();
int bst1 = alt.getNeu().getBST();
// int len1 = bst1 - vst1;
int vst2 = neu.getAlt().getVST();
int bst2 = neu.getAlt().getBST();
int vstZ = max(vst1, vst2);
int bstZ = min(bst1, bst2);
int lenZ = bstZ - vstZ;
if (lenZ <= 0) {
return null;
}
if (csAlt != null) {
int vstA = vstZ - alt.getNeu().getVST() + alt.getAlt().getVST();
int bstA = vstA + lenZ;
csAlt.setVST(vstA);
csAlt.setBST(bstA);
}
if (csNeu != null) {
int vstE = vstZ - neu.getAlt().getVST() + neu.getNeu().getVST();
int bstE = vstE + lenZ;
csNeu.setVST(vstE);
csNeu.setBST(bstE);
}
cs.setAlt(csAlt);
cs.setNeu(csNeu);
if (alt.getAlt() == null) {
System.out.println("gibts");
System.out.println(cs.toString());
}
return cs;
}
private int min(int m, int n) {
if (m > n)
return n;
return m;
}
private int max(int m, int n) {
if (m > n)
return m;
return n;
}
public List<ChangeSet> getAll() {
return changes;
}
public void sort() {
Collections.sort(changes);
dataChanged();
}
public void clearData() {
changes.clear();
}
public int size() {
return changes.size();
}
public ChangeSet get(int reihe) {
return changes.get(reihe);
}
public void set(int row, ChangeSet cs) {
changes.set(row, cs);
dataChanged();
}
public void remove(int row) {
changes.remove(row);
dataChanged();
}
public void saveToFile(File exportFile) {
String text = "";
for (ChangeSet cs : this.changes) {
text += cs.toString("\t") + "\n";
}
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(exportFile));
writer.write(text);
} catch (IOException e) {
} finally {
try {
if (writer != null)
writer.close();
} catch (IOException e) {
}
}
}
public void importFromFile(File importFile) {
try {
BufferedReader in = new BufferedReader(new FileReader(importFile));
String line = "";
while ((line = in.readLine()) != null) {
System.out.println("Buchstaben: " + line.length());
String[] input = line.split("\t");
if (input.length < 4) {
continue;
}
ChangeSet cs = new ChangeSet();
System.out.println("Teile: " + input.length);
// for (String s : input)
// System.out.print(s);
if (input.length >= 4) {
cs.setAlt(Station.fromString(input[0], input[1], input[2], input[3]));
}
if (input.length >= 8) {
cs.setNeu(Station.fromString(input[4], input[5], input[6], input[7]));
}
if (input.length == 9) {
cs.setGedreht(Boolean.valueOf(input[8]));
}
this.addSimple(cs);
// System.out.println(this.size());
}
in.close();
} catch (IOException e) {
System.err.println("cat: Fehler beim Verarbeiten");
}
dataChanged();
}
public void setListener(ChangeSetDBListener listener) {
this.listener = listener;
}
}
| 21.18254 | 79 | 0.603784 |
2befc27966c9f355398e9c2137d1a612baa0ff42 | 614 | package io.github.lasyard.spring.web;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.annotation.Nonnull;
@Controller
public class MainController {
private static final String VIEW_INDEX = "index";
private static int counter = 0;
@RequestMapping(value = "/", method = RequestMethod.GET)
public String index(@Nonnull Model model) {
model.addAttribute("counter", counter++);
return VIEW_INDEX;
}
}
| 27.909091 | 62 | 0.754072 |
9c3f9d4d3c18c26ea2e99ba172a4e842f0b3166a | 1,585 | package com.crossoverjie.netty.server.learning.handle;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
/**
* Function:消息处理器
*
* @author crossoverJie
* Date: 14/02/2018 00:39
* @since JDK 1.8
*/
@ChannelHandler.Sharable
public class TimeServiceHandle extends ChannelInboundHandlerAdapter{
private final static Logger LOGGER = org.slf4j.LoggerFactory.getLogger(TimeServiceHandle.class);
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
ByteBuf time = ctx.alloc().buffer(4);
time.writeInt((int) (System.currentTimeMillis() / 1000L + 2208988800L)) ;
ChannelFuture channelFuture = ctx.writeAndFlush(time);
channelFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (channelFuture == future){
ctx.close() ;
}
}
}) ;
}
@Override
public void channelReadComplete(ChannelHandlerContext channelHandlerContext) throws Exception {
//将未决消息冲刷到远程节点,并关闭连接
channelHandlerContext.writeAndFlush(Unpooled.EMPTY_BUFFER)
.addListener(ChannelFutureListener.CLOSE);
}
@Override
public void exceptionCaught(ChannelHandlerContext channelHandlerContext, Throwable throwable) throws Exception {
throwable.printStackTrace();
channelHandlerContext.close();
}
}
| 31.078431 | 116 | 0.690221 |
7b030a921403ddeba23988e8e6cfbdedd6f55363 | 558 | package com.servlet.project1;
public class PendingClaim {
private String claimRequestor;
private String claimType;
public PendingClaim(String claimRequestor, String claimType) {
// TODO Auto-generated constructor stub
}
public PendingClaim() {}
public String getClaimRequestor() {
return claimRequestor;
}
public void setClaimRequestor(String claimRequestor) {
this.claimRequestor = claimRequestor;
}
public String getClaimType() {
return claimType;
}
public void setClaimType(String claimType) {
this.claimType = claimType;
}
}
| 22.32 | 63 | 0.763441 |
92fa6471ba2b14e8acf81286418f0f7f1b6b6216 | 3,227 | package eu.neclab.ngsildbroker.commons.tools;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import eu.neclab.ngsildbroker.commons.datatypes.CSourceNotification;
import eu.neclab.ngsildbroker.commons.datatypes.CSourceRegistration;
import eu.neclab.ngsildbroker.commons.datatypes.Entity;
import eu.neclab.ngsildbroker.commons.datatypes.Notification;
import eu.neclab.ngsildbroker.commons.enums.TriggerReason;
public abstract class EntityTools {
private static final String BROKER_PREFIX = "ngsildbroker:";
public static URI getRandomID(String prefix) throws URISyntaxException {
if (prefix == null) {
prefix = ":";
}
if (!prefix.endsWith(":")) {
prefix += ":";
}
URI result;
result = new URI(BROKER_PREFIX + prefix + UUID.randomUUID().getLeastSignificantBits());
return result;
}
public static List<CSourceNotification> squashCSourceNotifications(List<CSourceNotification> data) {
List<CSourceRegistration> newData = new ArrayList<CSourceRegistration>();
List<CSourceRegistration> updatedData = new ArrayList<CSourceRegistration>();
List<CSourceRegistration> deletedData = new ArrayList<CSourceRegistration>();
List<CSourceNotification> result = new ArrayList<CSourceNotification>();
for (CSourceNotification notification : data) {
switch (notification.getTriggerReason()) {
case newlyMatching:
newData.addAll(notification.getData());
break;
case updated:
updatedData.addAll(notification.getData());
break;
case noLongerMatching:
deletedData.addAll(notification.getData());
break;
default:
break;
}
}
long now = System.currentTimeMillis();
try {
if(!newData.isEmpty()) {
result.add(new CSourceNotification(getRandomID("csource"),data.get(0).getSubscriptionId(),new Date(now),TriggerReason.newlyMatching,newData, data.get(0).getErrorMsg(),data.get(0).getErrorType(),data.get(0).getShortErrorMsg(),data.get(0).isSuccess()));
}
if(!updatedData.isEmpty()) {
result.add(new CSourceNotification(getRandomID("csource"),data.get(0).getSubscriptionId(),new Date(now),TriggerReason.updated,updatedData, data.get(0).getErrorMsg(),data.get(0).getErrorType(),data.get(0).getShortErrorMsg(),data.get(0).isSuccess()));
}
if(!deletedData.isEmpty()) {
result.add(new CSourceNotification(getRandomID("csource"),data.get(0).getSubscriptionId(),new Date(now),TriggerReason.noLongerMatching,deletedData, data.get(0).getErrorMsg(),data.get(0).getErrorType(),data.get(0).getShortErrorMsg(),data.get(0).isSuccess()));
}
} catch (URISyntaxException e) {
//left empty intentionally should never happen
throw new AssertionError();
}
return result;
}
public static Notification squashNotifications(List<Notification> data) {
List<Entity> newData = new ArrayList<Entity>();
for (Notification notification : data) {
newData.addAll(notification.getData());
}
return new Notification(data.get(0).getId(), System.currentTimeMillis(),
data.get(0).getSubscriptionId(), newData, data.get(0).getErrorMsg(), data.get(0).getErrorType(),
data.get(0).getShortErrorMsg(), data.get(0).isSuccess());
}
}
| 37.523256 | 261 | 0.746824 |
51d113860e52e036b576d695fbb20b1fac3fb056 | 1,061 | package ru.stqa.pft.addressbook.model;
import com.google.common.collect.ForwardingSet;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
/**
* Created by Julia on 5/12/2017.
*/
public class Contacts extends ForwardingSet<ContactData> {
private Set<ContactData> contactDelegate;
public Contacts() {
contactDelegate = new HashSet<ContactData>();
}
public Contacts(Contacts contactSet) {
contactDelegate = new HashSet<ContactData>(contactSet.delegate());
}
public Contacts(Collection<ContactData> contact) {
contactDelegate = new HashSet<ContactData>(contact);
}
@Override
protected Set<ContactData> delegate() {
return contactDelegate;
}
public Contacts withAdded(ContactData contact){
Contacts newSet = new Contacts(this);
newSet.add(contact);
return newSet;
}
public Contacts without(ContactData contact){
Contacts newSet = new Contacts(this);
newSet.remove(contact);
return newSet;
}
}
| 24.113636 | 74 | 0.68049 |
31f1ed28e549a6a8c5041da06d7efb4b8f9f62dd | 2,326 | package Service;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import java.net.Authenticator;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
/**
*
* @author ASUS
*/
public class ServiceMail {
public static void SendMail(String recepient,String corps) throws Exception {
System.out.println("Preparing to send email");
Properties properties = new Properties();
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.smtp.host", "smtp.gmail.com");
properties.put("mail.smtp.port", "587");
properties.put("mail.transport.protocol", "smtp");
String MyEmail="bahouri001@gmail.com";
String mdpEmail="aqwsefv123";
Session session= Session.getInstance(properties, new javax.mail.Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(MyEmail, mdpEmail);
}
});
Message message= prepareMessage(session,MyEmail,recepient,corps);
Transport.send(message);
System.out.println("Message sent 🙂 ");
}
private static Message prepareMessage(Session session,String MyEmail,String recepient,String corps) {
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress(MyEmail));
message.setRecipient(Message.RecipientType.TO, new InternetAddress(recepient));
message.setSubject("nouveauté sur velo.tn");
message.setText(corps);
return message;
} catch (Exception ex) {
Logger.getLogger(ServiceMail.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
} | 34.205882 | 106 | 0.638865 |
ca1b05b47138a9d2996c9260131d1b3c48fc8806 | 394 | package edu.udel.cis.vsl.abc.ast.type.common;
public class TypeKey {
private CommonType type;
public TypeKey(CommonType type) {
this.type = type;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof TypeKey) {
TypeKey that = (TypeKey) obj;
return type == that.type;
}
return false;
}
@Override
public int hashCode() {
return type.objectCode();
}
}
| 14.592593 | 45 | 0.677665 |
1337cd233e624e9e55c0e335167890b733c24f7e | 1,119 | /*
* Copyright (c) 1998-2018 University Corporation for Atmospheric Research/Unidata
* See LICENSE for license information.
*/
// $Id: InvCrawlablePair.java 63 2006-07-12 21:50:51Z edavis $
package thredds.cataloggen;
import thredds.catalog.InvDataset;
import thredds.crawlabledataset.CrawlableDataset;
/**
* Helper class to contain an InvDataset and its corresponding CrawlableDataset.
*
* Used by CollectionLevelScanner to provide access to:
* 1) All generated collection dataset objects (InvCatalogRef) and their corresponding CrawlableDataset objects;
* 2) All generated atomic dataset objects (InvDataset) and their corresponding CrawlableDataset objects.
*
*/
public class InvCrawlablePair
{
private CrawlableDataset crawlableDataset;
private InvDataset invDataset;
public InvCrawlablePair( CrawlableDataset crawlableDataset, InvDataset invDataset )
{
this.crawlableDataset = crawlableDataset;
this.invDataset = invDataset;
}
public CrawlableDataset getCrawlableDataset()
{
return crawlableDataset;
}
public InvDataset getInvDataset()
{
return invDataset;
}
}
| 27.975 | 112 | 0.778374 |
07fc77d402be4a884766c1f290e5a1b6b1135275 | 2,333 | package fr.utbm.gl52.graph.model;
import java.util.Collection;
import java.util.Iterator;
import fr.utbm.gl52.graph.factory.GraphFactory;
import fr.utbm.gl52.graph.observer.GraphListener;
/** This interface represents a graph. Each node and edge may contains data.
*
* @author sgalland
* @param <N> the type of the nodes into the graph.
* @param <E> the type of the edges into the graph.
* @param <D> the type of the data that is stored into the graph.
*/
public interface Graph<N extends GraphNode<N, E, D>, E extends GraphEdge<N, E, D>, D> extends Iterable<N> {
/** Replies the graph element factory that is used by this graph.
*
* @return the factory.
*/
GraphFactory<N, E> getFactory();
/** Replies the unmodifiable collection of the graph nodes.
*
* @return the nodes.
*/
Collection<N> getNodes();
/** Replies the unmodifiable collection of the graph edges.
*
* @return the edges.
*/
Collection<E> getEdges();
/** Add a node into the graph.
*
* @param node the node to add.
*/
void addNode(N node);
/** Add a node into the graph.
*
* @param name the name of the element.
* @return the created node.
*/
default N addNode(String name) {
final N node = getFactory().createNode(name);
addNode(node);
return node;
}
/** Add an edge into the graph.
*
* @param name the name of the element.
* @param start the starting node for the edge.
* @param end the end node for the edge.
* @return the created edge.
*/
default E addEdge(String name, N start, N end) {
final E edge = getFactory().createEdge(name);
addEdge(edge, start, end);
return edge;
}
/** Add an edge into the graph.
*
* @param edge the edge to add.
* @param start the starting node for the edge.
* @param end the end node for the edge.
*/
void addEdge(E edge, N start, N end);
/** Replies an iterator on the data that are stored into the graph.
*
* @return the data iterator.
*/
Iterator<D> dataIterator();
@Override
Iterator<N> iterator();
/** Add an observer on the events related to the graph.
*
* @param observer the observer to add.
*/
void addGraphListener(GraphListener observer);
/** Add an observer on the events related to the graph.
*
* @param observer the observer to remove.
*/
void removeGraphListener(GraphListener observer);
}
| 24.302083 | 107 | 0.678526 |
0affbc770a26a0cd9f460f7b690ab3263dfc5d4a | 5,860 | package model;
import com.avaje.ebean.Page;
import com.fasterxml.jackson.annotation.JsonIgnore;
import play.db.ebean.Model;
import javax.persistence.*;
import java.util.List;
/**
* Bean to store generic data generated by a sensor.
* Created by Mathieu on 23/01/2015.
*/
@Entity
public class Data extends Model{
@EmbeddedId @JsonIgnore
public PrimKey primKey;
/**
* A numeric representation of the collected data.
*/
public double value;
@Embeddable
public class PrimKey {
public long timestamp;
public String mote;
public String label;
public PrimKey() {
}
public PrimKey(long timestamp, String mote, String label) {
this.timestamp = timestamp;
this.mote = mote;
this.label = label;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof PrimKey)) return false;
PrimKey primKey = (PrimKey) o;
if (timestamp != primKey.timestamp) return false;
if (label != null ? !label.equals(primKey.label) : primKey.label != null) return false;
if (mote != null ? !mote.equals(primKey.mote) : primKey.mote != null) return false;
return true;
}
@Override
public int hashCode() {
int result = (int) (timestamp ^ (timestamp >>> 32));
result = 31 * result + mote.hashCode();
result = 31 * result + label.hashCode();
return result;
}
@Override
public String toString() {
return "PrimKey{" +
"timestamp=" + timestamp +
", mote='" + mote + '\'' +
", label='" + label + '\'' +
'}';
}
}
public Data() {
}
public Data(long timestamp, double value, String label, String mote) {
this.value = value;
this.primKey = new PrimKey(timestamp, mote, label);
}
public static Model.Finder<PrimKey,Data> find = new Model.Finder<>(PrimKey.class, Data.class);
public static List<Data> all() {
return find.all();
}
public static Data create(Data data) {
data.save();
return data;
}
public static Page<Data> page(int page, int pageSize, String sortBy, String order, String filter) {
return
find.where()
.ilike("mote", "%" + filter + "%")
.orderBy(sortBy+ " " + order)
.findPagingList(pageSize)
.setFetchAhead(false)
.getPage(page);
}
public static Page<Data> pageTime(int page, int pageSize, String sortBy, String order, String filter, long beginTmp, long endTmp) {
return
find.where()
.between("timestamp", beginTmp, endTmp)
.ilike("mote", "%" + filter + "%")
.orderBy(sortBy+ " " + order)
.findPagingList(pageSize)
.setFetchAhead(false)
.getPage(page);
}
/**
* Returns the timestamp of the measure.
* @return measure's timestamp.
*/
public long getTimestamp() {
return primKey.timestamp;
}
/**
* Changes measure's timestamp.
* @param timestamp the new timestamp.
*/
public void setTimestamp(long timestamp) {
primKey.timestamp = timestamp;
}
/**
* Returns the measure's associated label.
* @return the associated label.
*/
public String getLabel() {
return primKey.label;
}
/**
* Changes the measure's associated label.
* @param label the new label.
*/
public void setLabel(String label) {
primKey.label = label;
}
/**
* Returns the measure's numerical value.
* @return the numerical value.
*/
public double getValue() {
return value;
}
/**
* Changes the measure's numerical value.
* @param value the new value.
*/
public void setValue(double value) {
this.value = value;
}
/**
* Returns the string identifying the mote which has taken the measure.
* @return the string identifying the mote.
*/
public String getMote() {
return primKey.mote;
}
/**
* Changes the string identifying the mote which has taken the measure.
* @param mote the new string.
*/
public void setMote(String mote) {
primKey.mote = mote;
}
public PrimKey getPrimKey() {
return primKey;
}
public void setPrimKey(PrimKey primKey) {
this.primKey = primKey;
}
@Override
public String toString() {
return "Data{" +
"primKey=" + getPrimKey() +
", value=" + getValue() +
'}';
}
public static void deleteOldData() {
// delete data according to retention delay in parameters
Param param;
try {
param = Param.find.ref("dataRetention");
// param exists
int retention = Integer.parseInt(param.getParamValue());
if(retention > 1) { // erase data
long now = System.currentTimeMillis() / 1000; // in seconds
long endErase = now - retention * 24 * 3600;
for(Data data : Data.find.where().between("timestamp", 0, endErase).findList()) {
data.delete();
}
}
} catch(EntityNotFoundException e) { // param does not exist
param = new Param();
param.setParamKey("dataRetention");
param.setParamValue("-1");
param.save();
}
}
}
| 27.383178 | 135 | 0.532423 |
49b00cbfcb073f018b0a9198b6537e3f713dd3cc | 178 | package com.paragon_software.article_manager;
interface OnFavoritesButtonStateChangedListener extends ArticleControllerAPI.Notifier
{
void onFavoritesButtonStateChanged();
}
| 22.25 | 85 | 0.870787 |
701acaaac52d7120ef493debde66acc005746439 | 5,199 | /*
* Copyright 2020 Red Hat
*
* 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.apicurio.registry.utils.converter;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.apicurio.registry.rest.client.RegistryClient;
import io.apicurio.registry.serde.ParsedSchema;
import io.apicurio.registry.serde.ParsedSchemaImpl;
import io.apicurio.registry.serde.SchemaLookupResult;
import io.apicurio.registry.serde.SchemaParser;
import io.apicurio.registry.serde.SchemaResolverConfigurer;
import io.apicurio.registry.serde.strategy.ArtifactReference;
import io.apicurio.registry.types.ArtifactType;
import io.apicurio.registry.utils.IoUtil;
import io.apicurio.registry.utils.converter.json.FormatStrategy;
import io.apicurio.registry.utils.converter.json.PrettyFormatStrategy;
import org.apache.kafka.common.header.Headers;
import org.apache.kafka.connect.data.Schema;
import org.apache.kafka.connect.data.SchemaAndValue;
import org.apache.kafka.connect.json.JsonConverter;
import org.apache.kafka.connect.json.JsonConverterConfig;
import org.apache.kafka.connect.storage.Converter;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
/**
* @author Ales Justin
* @author Fabian Martinez
*/
public class ExtJsonConverter extends SchemaResolverConfigurer<JsonNode, Object> implements Converter, SchemaParser<JsonNode>, AutoCloseable {
private final JsonConverter jsonConverter;
private final ObjectMapper mapper;
private FormatStrategy formatStrategy;
public ExtJsonConverter() {
this(null);
}
public ExtJsonConverter(RegistryClient client) {
super(client);
this.jsonConverter = new JsonConverter();
this.mapper = new ObjectMapper();
this.formatStrategy = new PrettyFormatStrategy();
}
public ExtJsonConverter setFormatStrategy(FormatStrategy formatStrategy) {
this.formatStrategy = Objects.requireNonNull(formatStrategy);
return this;
}
@Override
public void configure(Map<String, ?> configs, boolean isKey) {
super.configure(configs, isKey, this);
Map<String, Object> wrapper = new HashMap<>(configs);
wrapper.put(JsonConverterConfig.SCHEMAS_ENABLE_CONFIG, false);
jsonConverter.configure(wrapper, isKey);
}
@Override
public byte[] fromConnectData(String topic, Schema schema, Object value) {
return fromConnectData(topic, null, schema, value);
}
@Override
public byte[] fromConnectData(String topic, Headers headers, Schema schema, Object value) {
if (schema == null && value == null) {
return null;
}
JsonNode jsonSchema = jsonConverter.asJsonSchema(schema);
String schemaString = jsonSchema != null ? jsonSchema.toString() : null;
ParsedSchema<JsonNode> parsedSchema = new ParsedSchemaImpl<JsonNode>()
.setParsedSchema(jsonSchema)
.setRawSchema(IoUtil.toBytes(schemaString));
SchemaLookupResult<JsonNode> schemaLookupResult = getSchemaResolver().resolveSchema(topic, headers, value, parsedSchema);
byte[] payload = jsonConverter.fromConnectData(topic, schema, value);
return formatStrategy.fromConnectData(schemaLookupResult.getGlobalId(), payload);
}
@Override
public SchemaAndValue toConnectData(String topic, byte[] value) {
FormatStrategy.IdPayload ip = formatStrategy.toConnectData(value);
long globalId = ip.getGlobalId();
SchemaLookupResult<JsonNode> schemaLookupResult = getSchemaResolver().resolveSchemaByArtifactReference(ArtifactReference.builder().globalId(globalId).build());
Schema schema = jsonConverter.asConnectSchema(schemaLookupResult.getSchema());
byte[] payload = ip.getPayload();
SchemaAndValue sav = jsonConverter.toConnectData(topic, payload);
return new SchemaAndValue(schema, sav.value());
}
/**
* @see io.apicurio.registry.serde.SchemaParser#artifactType()
*/
@Override
public ArtifactType artifactType() {
return ArtifactType.KCONNECT;
}
/**
* @see io.apicurio.registry.serde.SchemaParser#parseSchema(byte[])
*/
@Override
public JsonNode parseSchema(byte[] rawSchema) {
try {
return mapper.readTree(rawSchema);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
/**
* @see java.lang.AutoCloseable#close()
*/
@Override
public void close() throws Exception {
jsonConverter.close();
}
}
| 34.66 | 167 | 0.722254 |
223d9fc0cf9f5c8662301999a3ebc96e872fd092 | 2,012 | package br.ufpb.dcx.sisclinica;
import br.ufpb.dcx.sisclinica.exceptions.MedicamentoJaExisteException;
import java.util.ArrayList;
import java.util.List;
public class Receita {
private Medico medico;
private Paciente paciente;
private String data;
private List<Medicamento> medicamentos;
public Receita(Medico medico, Paciente paciente, String data){
this.medico = medico;
this.paciente = paciente;
this.data = data;
this.medicamentos = new ArrayList<>();
}
public void cadastraMedicamento(Medicamento medicamento) throws MedicamentoJaExisteException {
for(Medicamento med: medicamentos)
if(medicamento.getNome().equals(med.getNome())) {
if(medicamento.getMiligrama().equals(med.getMiligrama())) {
throw new MedicamentoJaExisteException("O medicamento de nome" + medicamento.getNome() + " e miligrama"+medicamento.getMiligrama()+" j� existe");
}
}else {
medicamentos.add(medicamento);
}
}
@Override
public String toString() {
String stringMedicamentos = "";
for(Medicamento m : this.getMedicamentos()){
stringMedicamentos += m.getNome();
stringMedicamentos += " :" +m.getMiligrama() + "\n";
}
return "Medico: "+this.medico.getNome()+"\n"
+"Paciente: "+this.paciente.getNome()+"\n"
+"Data: "+this.data+"\n"
+"Medicamentos: "+stringMedicamentos;
}
public Medico getMedico() {
return this.medico;
}
public void setMedico(Medico medico) {
this.medico = medico;
}
public Paciente getPaciente() {
return paciente;
}
public void setPaciente(Paciente paciente) {
this.paciente = paciente;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public List<Medicamento> getMedicamentos() {
return medicamentos;
}
public void setMedicamentos(List<Medicamento> medicamentos) {
this.medicamentos = medicamentos;
}
}
| 23.395349 | 150 | 0.662525 |
bb446113615c861af6403c49c208c9ddf4e2b120 | 7,568 | package results_panel.statistics;
import sequenced_tracer_panel.tracer_panel.Trace;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.util.ArrayList;
public class TraceVisualizerPanel extends JPanel {
private final int BORDER = 30;
private ArrayList<Trace>[] positionTraces;
private Point startButtonLocation;
private Dimension startButtonSize;
private Point endButtonLocation;
private Dimension endButtonSize;
private int xMin, xMax, yMin, yMax;
private Color[] colorList;
public TraceVisualizerPanel(ArrayList<Trace>[] positionTraces,
Point startButtonLocation,
Dimension startButtonSize,
Point endButtonLocation,
Dimension endButtonSize)
{
super();
setLayout(null);
this.positionTraces = positionTraces;
this.startButtonSize = startButtonSize;
this.startButtonLocation = startButtonLocation;
this.endButtonSize = endButtonSize;
this.endButtonLocation = endButtonLocation;
setupBounds();
// TODO: test
setBackground(Color.white);
colorList = new Color[]{
new Color(65, 148, 182),
new Color(166, 183, 118),
new Color(230, 201, 94),
new Color(26, 60, 84),
new Color(176, 58, 42),
new Color(225, 115, 55)
};
this.setBorder(BorderFactory.createEmptyBorder(BORDER, BORDER, BORDER, BORDER));
}
@Override
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g.create();
drawButtons(g2d);
drawTraces(g2d);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(
xMax - xMin + (2 * BORDER),
yMax - yMin + (2 *BORDER)
);
}
public void setupBounds()
{
if (positionTraces == null) return;
Point firstPoint = positionTraces[0].get(0).points.get(0);
xMin = firstPoint.x;
xMax = firstPoint.x;
yMin = firstPoint.y;
yMax = firstPoint.y;
// TODO: REMOVE
System.out.println("xMin: " + xMin);
System.out.println("xMax: " + xMax);
// TODO: REMOVE
System.out.println("yMin: " + yMin);
System.out.println("yMax: " + yMax);
// Check points in traces to see if they contain point mins and maxes
for (ArrayList<Trace> traceList : positionTraces) {
for (Trace trace : traceList) {
for (Point point : trace.points)
{
// Check x min and max
if (point.x < xMin) {
xMin = point.x;
}
else if (point.x > xMax) {
xMax = point.x;
}
// Check y min and max
if (point.y < yMin) {
yMin = point.y;
}
else if (point.y > yMax) {
yMax = point.y;
}
}
}
}
// Check startButton corners
Point lowerButtonCorner;
Point upperButtonCorner;
lowerButtonCorner = new Point(startButtonLocation.x - (startButtonSize.width / 2),
startButtonLocation.y - (startButtonSize.height / 2)
);
upperButtonCorner = new Point(startButtonLocation.x + (startButtonSize.width / 2),
startButtonLocation.y + (startButtonSize.height / 2)
);
if (lowerButtonCorner.x < xMin) {
xMin = lowerButtonCorner.x;
}
else if (upperButtonCorner.x > xMax) {
xMax = upperButtonCorner.x;
}
if (lowerButtonCorner.y < yMin) {
yMin = lowerButtonCorner.y;
}
else if (upperButtonCorner.y > yMax) {
yMax = upperButtonCorner.y;
}
// Check endButton corners
lowerButtonCorner = new Point(endButtonLocation.x - (endButtonSize.width / 2),
endButtonLocation.y - (endButtonSize.height / 2)
);
upperButtonCorner = new Point(endButtonLocation.x + (endButtonSize.width / 2),
endButtonLocation.y + (endButtonSize.height / 2)
);
if (lowerButtonCorner.x < xMin) {
xMin = lowerButtonCorner.x;
}
else if (upperButtonCorner.x > xMax) {
xMax = upperButtonCorner.x;
}
if (lowerButtonCorner.y < yMin) {
yMin = lowerButtonCorner.y;
}
else if (upperButtonCorner.y > yMax) {
yMax = upperButtonCorner.y;
}
}
private void drawTraces(Graphics2D g2d)
{
if (positionTraces == null) return;
Point a;
Point b = new Point();
g2d.setColor(Color.black);
for (int r = 0; r < positionTraces.length; ++r) {
g2d.setStroke(new BasicStroke(1));
// Set trace color
if (r >= colorList.length) {
g2d.setColor(Color.black);
} else {
g2d.setColor(colorList[r]);
}
// Draw traces in round
for (Trace trace : positionTraces[r]) {
for (int i = 0; i < trace.points.size() - 1; ++i) {
a = trace.points.get(i);
b = trace.points.get(i + 1);
a = new Point(trace.points.get(i));
b = new Point(trace.points.get(i + 1));
a.x -= xMin - BORDER;
a.y -= yMin - BORDER;
b.x -= xMin - BORDER;
b.y -= yMin - BORDER;
g2d.drawLine(a.x, a.y, b.x, b.y);
g2d.fillOval(b.x - 1, b.y - 1, 2, 2);
}
// place endpoint on trace
g2d.fillOval(b.x-2, b.y-2, 4, 4);
}
}
}
private void drawButtons(Graphics2D g2d)
{
Point[] buttonLocationArr = new Point[]{startButtonLocation, endButtonLocation};
Dimension[] buttonSizeArr = new Dimension[]{startButtonSize, endButtonSize};
for (int i = 0; i < buttonLocationArr.length; ++i) {
g2d.setColor(Color.gray);
int posX = buttonLocationArr[i].x;
int posY = buttonLocationArr[i].y;
int centerX = posX - (int)(buttonSizeArr[i].getWidth() / 2);
int centerY = posY - (int)(buttonSizeArr[i].getHeight() / 2);
centerX -= xMin - BORDER;
centerY -= yMin - BORDER;
int width = buttonSizeArr[i].width;
int height = buttonSizeArr[i].height;
final float dash1[] = {10.0f};
final BasicStroke dashed =
new BasicStroke(1.0f,
BasicStroke.CAP_BUTT,
BasicStroke.JOIN_MITER,
10.0f, dash1, 0.0f);
g2d.setStroke(dashed);
g2d.draw(
new RoundRectangle2D.Double(
centerX,
centerY,
width,
height,
10,
10
)
);
}
}
}
| 27.223022 | 90 | 0.493922 |
c58bb5128211cf85d58a15fc8b12cb45d11b0dc0 | 8,031 | package org.apache.fop.render.rtf.rtflib.rtfdoc;
import java.io.IOException;
import java.io.Writer;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
public class RtfTextrun extends RtfContainer {
private boolean bSuppressLastPar = false;
private RtfListItem rtfListItem;
private RtfSpaceManager rtfSpaceManager = new RtfSpaceManager();
RtfTextrun(RtfContainer parent, Writer w, RtfAttributes attrs) throws IOException {
super(parent, w, attrs);
}
private void addOpenGroupMark(RtfAttributes attrs) throws IOException {
new RtfTextrun.RtfOpenGroupMark(this, this.writer, attrs);
}
private void addCloseGroupMark() throws IOException {
new RtfTextrun.RtfCloseGroupMark(this, this.writer);
}
public void pushBlockAttributes(RtfAttributes attrs) throws IOException {
this.rtfSpaceManager.stopUpdatingSpaceBefore();
RtfSpaceSplitter splitter = this.rtfSpaceManager.pushRtfSpaceSplitter(attrs);
this.addOpenGroupMark(splitter.getCommonAttributes());
}
public void popBlockAttributes() throws IOException {
this.rtfSpaceManager.popRtfSpaceSplitter();
this.rtfSpaceManager.stopUpdatingSpaceBefore();
this.addCloseGroupMark();
}
public void pushInlineAttributes(RtfAttributes attrs) throws IOException {
this.rtfSpaceManager.pushInlineAttributes(attrs);
this.addOpenGroupMark(attrs);
}
public void addPageNumberCitation(String refId) throws IOException {
new RtfPageNumberCitation(this, this.writer, refId);
}
public void popInlineAttributes() throws IOException {
this.rtfSpaceManager.popInlineAttributes();
this.addCloseGroupMark();
}
public void addString(String s) throws IOException {
if (!s.equals("")) {
RtfAttributes attrs = this.rtfSpaceManager.getLastInlineAttribute();
this.rtfSpaceManager.pushRtfSpaceSplitter(attrs);
this.rtfSpaceManager.setCandidate(attrs);
new RtfString(this, this.writer, s);
this.rtfSpaceManager.popRtfSpaceSplitter();
}
}
public RtfFootnote addFootnote() throws IOException {
return new RtfFootnote(this, this.writer);
}
public void addParagraphBreak() throws IOException {
List children = this.getChildren();
int deletedCloseGroupCount = 0;
for(ListIterator lit = children.listIterator(children.size()); lit.hasPrevious() && lit.previous() instanceof RtfTextrun.RtfCloseGroupMark; ++deletedCloseGroupCount) {
lit.remove();
}
if (children.size() != 0) {
this.setChildren(children);
new RtfTextrun.RtfParagraphBreak(this, this.writer);
for(int i = 0; i < deletedCloseGroupCount; ++i) {
this.addCloseGroupMark();
}
}
}
public void addLeader(RtfAttributes attrs) throws IOException {
new RtfLeader(this, this.writer, attrs);
}
public void addPageNumber(RtfAttributes attr) throws IOException {
new RtfPageNumber(this, this.writer, attr);
}
public RtfHyperLink addHyperlink(RtfAttributes attr) throws IOException {
return new RtfHyperLink(this, this.writer, attr);
}
public void addBookmark(String id) throws IOException {
if (id != "") {
new RtfBookmark(this, this.writer, id);
}
}
public RtfExternalGraphic newImage() throws IOException {
return new RtfExternalGraphic(this, this.writer);
}
public static RtfTextrun getTextrun(RtfContainer container, Writer writer, RtfAttributes attrs) throws IOException {
List list = container.getChildren();
if (list.size() == 0) {
RtfTextrun textrun = new RtfTextrun(container, writer, attrs);
list.add(textrun);
return textrun;
} else {
Object obj = list.get(list.size() - 1);
if (obj instanceof RtfTextrun) {
return (RtfTextrun)obj;
} else {
RtfTextrun textrun = new RtfTextrun(container, writer, attrs);
list.add(textrun);
return textrun;
}
}
}
public void setSuppressLastPar(boolean bSuppress) {
this.bSuppressLastPar = bSuppress;
}
protected void writeRtfContent() throws IOException {
boolean bHasTableCellParent = this.getParentOfClass(RtfTableCell.class) != null;
RtfAttributes attrBlockLevel = new RtfAttributes();
boolean bLast = false;
Iterator it = this.parent.getChildren().iterator();
while(it.hasNext()) {
if (it.next() == this) {
bLast = !it.hasNext();
break;
}
}
RtfTextrun.RtfParagraphBreak lastParagraphBreak = null;
if (bLast) {
Iterator it = this.getChildren().iterator();
while(it.hasNext()) {
RtfElement e = (RtfElement)it.next();
if (e instanceof RtfTextrun.RtfParagraphBreak) {
lastParagraphBreak = (RtfTextrun.RtfParagraphBreak)e;
} else if (!(e instanceof RtfTextrun.RtfOpenGroupMark) && !(e instanceof RtfTextrun.RtfCloseGroupMark) && e.isEmpty()) {
lastParagraphBreak = null;
}
}
}
this.writeAttributes(this.attrib, (String[])null);
if (this.rtfListItem != null) {
this.rtfListItem.getRtfListStyle().writeParagraphPrefix(this);
}
boolean bPrevPar = false;
boolean bFirst = true;
Iterator it = this.getChildren().iterator();
while(true) {
while(it.hasNext()) {
RtfElement e = (RtfElement)it.next();
boolean bRtfParagraphBreak = e instanceof RtfTextrun.RtfParagraphBreak;
if (bHasTableCellParent) {
attrBlockLevel.set(e.getRtfAttributes());
}
boolean bHide = false;
bHide = bRtfParagraphBreak && (bPrevPar || bFirst || this.bSuppressLastPar && bLast && lastParagraphBreak != null && e == lastParagraphBreak);
if (!bHide) {
this.newLine();
e.writeRtf();
if (this.rtfListItem != null && e instanceof RtfTextrun.RtfParagraphBreak) {
this.rtfListItem.getRtfListStyle().writeParagraphPrefix(this);
}
}
if (e instanceof RtfTextrun.RtfParagraphBreak) {
bPrevPar = true;
} else if (!(e instanceof RtfTextrun.RtfCloseGroupMark) && !(e instanceof RtfTextrun.RtfOpenGroupMark)) {
bPrevPar = bPrevPar && e.isEmpty();
bFirst = bFirst && e.isEmpty();
}
}
if (bHasTableCellParent) {
this.writeAttributes(attrBlockLevel, (String[])null);
}
return;
}
}
public void setRtfListItem(RtfListItem listItem) {
this.rtfListItem = listItem;
}
public RtfListItem getRtfListItem() {
return this.rtfListItem;
}
private class RtfParagraphBreak extends RtfElement {
RtfParagraphBreak(RtfContainer parent, Writer w) throws IOException {
super(parent, w);
}
public boolean isEmpty() {
return false;
}
protected void writeRtfContent() throws IOException {
this.writeControlWord("par");
}
}
private class RtfCloseGroupMark extends RtfElement {
RtfCloseGroupMark(RtfContainer parent, Writer w) throws IOException {
super(parent, w);
}
public boolean isEmpty() {
return false;
}
protected void writeRtfContent() throws IOException {
this.writeGroupMark(false);
}
}
private class RtfOpenGroupMark extends RtfElement {
RtfOpenGroupMark(RtfContainer parent, Writer w, RtfAttributes attr) throws IOException {
super(parent, w, attr);
}
public boolean isEmpty() {
return false;
}
protected void writeRtfContent() throws IOException {
this.writeGroupMark(true);
this.writeAttributes(this.getRtfAttributes(), (String[])null);
}
}
}
| 31.996016 | 173 | 0.644627 |
e6aa49bc153302db647b2a36cecc26780f42088e | 962 | package ru.intertrust.cm.core.gui.model.action;
import ru.intertrust.cm.core.config.DefaultFormEditingStyleConfig;
import ru.intertrust.cm.core.gui.model.plugin.FormPluginData;
/**
* @author Denis Mitavskiy
* Date: 25.09.13
* Time: 18:19
*/
public class SaveActionData extends ActionData {
private FormPluginData formPluginData;
private DefaultFormEditingStyleConfig defaultFormEditingStyleConfig;
public FormPluginData getFormPluginData() {
return formPluginData;
}
public void setFormPluginData(FormPluginData formPluginData) {
this.formPluginData = formPluginData;
}
public DefaultFormEditingStyleConfig getDefaultFormEditingStyleConfig() {
return defaultFormEditingStyleConfig;
}
public void setDefaultFormEditingStyleConfig(DefaultFormEditingStyleConfig defaultFormEditingStyleConfig) {
this.defaultFormEditingStyleConfig = defaultFormEditingStyleConfig;
}
}
| 31.032258 | 111 | 0.767152 |
f7c3eb64251ebffa3a5340f42033e140da7c7b2c | 1,170 | package com.tvycas.countyinfo.model;
import androidx.room.Entity;
import java.util.ArrayList;
/**
* A POJO for storing full information about a country with the bounding box.
*/
@Entity(tableName = "country_info")
public class CountryInfoWithMap extends CountryInfo {
BoundingBox boundingBox;
public CountryInfoWithMap(Currency currency, ArrayList<Language> langs, String name,
String countryCode, String capital, int population, String nativeName, BoundingBox boundingBox) {
super(new ArrayList<Currency>() {{
add(currency);
}}, langs, name, countryCode, capital, population, nativeName);
this.boundingBox = boundingBox;
}
public CountryInfoWithMap(CountryInfo countryInfo, BoundingBox boundingBox) {
super(countryInfo.getCurrencies(), countryInfo.getLangs(),
countryInfo.getName(), countryInfo.getCountryCode(),
countryInfo.getCapital(), countryInfo.getPopulation(),
countryInfo.getNativeName());
this.boundingBox = boundingBox;
}
public BoundingBox getBoundingBox() {
return boundingBox;
}
}
| 33.428571 | 127 | 0.682906 |
bdd9990a1bb53d0bb06dd8eb97ba932553ec3f03 | 389 | package com.contentstack.gqlspring.models;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
@Data
public class FooterModel {
@JsonProperty
public Object logoConnection;
@JsonProperty
public Object navigation;
@JsonProperty
public String title;
@JsonProperty
public String copyright;
@JsonProperty
public Object social;
} | 19.45 | 53 | 0.745501 |
f4233d8eb648af14112abc9e40ccca7e46d3fc1a | 6,279 | package com.orientechnologies.orient.core.metadata.security;
import com.orientechnologies.common.log.OLogManager;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.exception.OSecurityAccessException;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.security.OSecurityManager;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* @author Andrey Lomakin (a.lomakin-at-orientdb.com)
* @since 03/11/14
*/
public class OImmutableUser implements OSecurityUser {
private static final long serialVersionUID = 1L;
private final long version;
private final String name;
private final String password;
private final Set<OImmutableRole> roles = new HashSet<OImmutableRole>();
private final STATUSES status;
private final ORID rid;
private final OUser user;
public OImmutableUser(long version, OUser user) {
this.version = version;
this.name = user.getName();
this.password = user.getPassword();
this.status = user.getAccountStatus();
this.rid = user.getIdentity().getIdentity();
this.user = user;
for (ORole role : user.getRoles()) {
roles.add(new OImmutableRole(role));
}
}
public OSecurityRole allow(final ORule.ResourceGeneric resourceGeneric, final String resourceSpecific, final int iOperation) {
if (roles.isEmpty())
throw new OSecurityAccessException(getName(), "User '" + getName() + "' has no role defined");
final OSecurityRole role = checkIfAllowed(resourceGeneric, resourceSpecific, iOperation);
if (role == null)
throw new OSecurityAccessException(getName(), "User '" + getName() + "' does not have permission to execute the operation '"
+ ORole.permissionToString(iOperation) + "' against the resource: " + resourceGeneric + "." + resourceSpecific);
return role;
}
public OSecurityRole checkIfAllowed(final ORule.ResourceGeneric resourceGeneric, final String resourceSpecific,
final int iOperation) {
for (OImmutableRole r : roles) {
if (r == null)
OLogManager.instance().warn(this,
"User '%s' has a null role, ignoring it. Consider fixing this user's roles before continuing", getName());
else if (r.allow(resourceGeneric, resourceSpecific, iOperation))
return r;
}
return null;
}
public boolean isRuleDefined(final ORule.ResourceGeneric resourceGeneric, String resourceSpecific) {
for (OImmutableRole r : roles)
if (r == null)
OLogManager.instance().warn(this,
"User '%s' has a null role, ignoring it. Consider fixing this user's roles before continuing", getName());
else if (r.hasRule(resourceGeneric, resourceSpecific))
return true;
return false;
}
@Override
@Deprecated
public OSecurityRole allow(String iResource, int iOperation) {
final String resourceSpecific = ORule.mapLegacyResourceToSpecificResource(iResource);
final ORule.ResourceGeneric resourceGeneric = ORule.mapLegacyResourceToGenericResource(iResource);
if (resourceSpecific == null || resourceSpecific.equals("*"))
return allow(resourceGeneric, null, iOperation);
return allow(resourceGeneric, resourceSpecific, iOperation);
}
@Override
@Deprecated
public OSecurityRole checkIfAllowed(String iResource, int iOperation) {
final String resourceSpecific = ORule.mapLegacyResourceToSpecificResource(iResource);
final ORule.ResourceGeneric resourceGeneric = ORule.mapLegacyResourceToGenericResource(iResource);
if (resourceSpecific == null || resourceSpecific.equals("*"))
return checkIfAllowed(resourceGeneric, null, iOperation);
return checkIfAllowed(resourceGeneric, resourceSpecific, iOperation);
}
@Override
@Deprecated
public boolean isRuleDefined(String iResource) {
final String resourceSpecific = ORule.mapLegacyResourceToSpecificResource(iResource);
final ORule.ResourceGeneric resourceGeneric = ORule.mapLegacyResourceToGenericResource(iResource);
if (resourceSpecific == null || resourceSpecific.equals("*"))
return isRuleDefined(resourceGeneric, null);
return isRuleDefined(resourceGeneric, resourceSpecific);
}
public boolean checkPassword(final String iPassword) {
return OSecurityManager.instance().checkPassword(iPassword, getPassword());
}
public String getName() {
return name;
}
public OUser setName(final String iName) {
throw new UnsupportedOperationException();
}
public String getPassword() {
return password;
}
public OUser setPassword(final String iPassword) {
throw new UnsupportedOperationException();
}
public STATUSES getAccountStatus() {
return status;
}
public void setAccountStatus(STATUSES accountStatus) {
throw new UnsupportedOperationException();
}
public Set<OImmutableRole> getRoles() {
return Collections.unmodifiableSet(roles);
}
public OUser addRole(final String iRole) {
throw new UnsupportedOperationException();
}
public OUser addRole(final OSecurityRole iRole) {
throw new UnsupportedOperationException();
}
public boolean removeRole(final String iRoleName) {
throw new UnsupportedOperationException();
}
public boolean hasRole(final String iRoleName, final boolean iIncludeInherited) {
for (Iterator<OImmutableRole> it = roles.iterator(); it.hasNext();) {
final OSecurityRole role = it.next();
if (role.getName().equals(iRoleName))
return true;
if (iIncludeInherited) {
OSecurityRole r = role.getParentRole();
while (r != null) {
if (r.getName().equals(iRoleName))
return true;
r = r.getParentRole();
}
}
}
return false;
}
@Override
public String toString() {
return getName();
}
public long getVersion() {
return version;
}
@Override
public OIdentifiable getIdentity() {
return rid;
}
@Override
public ODocument getDocument() {
return user.getDocument();
}
}
| 31.238806 | 130 | 0.709667 |
b37e5e974b5363451f9e0e8b370e614a7e49f3bf | 226 | class Main {
public static void main(String[] s){
A myVar;
int x;
x = new A().run(new Derived());
}
}
class Base {
}
class Derived extends Base {
}
class A {
public int run(Base b) {
return 1;
}
}
| 11.3 | 37 | 0.557522 |
e23851083fe65e698924580fb75bc53aa44a9728 | 327 | package org.hazelcast.addon.cluster.expiration;
public class SessionExpirationServiceStatus implements SessionExpirationServiceStatusMBean {
private Integer queueSize = 0;
@Override
public Integer getQueueSize() {
return queueSize;
}
public void setQueueSize(Integer queueSize) {
this.queueSize = queueSize;
}
}
| 20.4375 | 92 | 0.792049 |
068fbaea3c227afe2976ff63e44282b90920b004 | 7,426 | package cherry.sqlapp.db.gen.mapper;
import cherry.sqlapp.db.gen.dto.SqltoolLoad;
import cherry.sqlapp.db.gen.dto.SqltoolLoadCriteria;
import java.util.List;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.DeleteProvider;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.InsertProvider;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.SelectProvider;
import org.apache.ibatis.annotations.Update;
import org.apache.ibatis.annotations.UpdateProvider;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.type.JdbcType;
public interface SqltoolLoadMapper {
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table SQLTOOL_LOAD
*
* @mbggenerated
*/
@SelectProvider(type=SqltoolLoadSqlProvider.class, method="countByExample")
int countByExample(SqltoolLoadCriteria example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table SQLTOOL_LOAD
*
* @mbggenerated
*/
@DeleteProvider(type=SqltoolLoadSqlProvider.class, method="deleteByExample")
int deleteByExample(SqltoolLoadCriteria example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table SQLTOOL_LOAD
*
* @mbggenerated
*/
@Delete({
"delete from SQLTOOL_LOAD",
"where ID = #{id,jdbcType=INTEGER}"
})
int deleteByPrimaryKey(Integer id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table SQLTOOL_LOAD
*
* @mbggenerated
*/
@Insert({
"insert into SQLTOOL_LOAD (DATABASE_NAME, QUERY, ",
"UPDATED_AT, CREATED_AT, ",
"LOCK_VERSION, DELETED_FLG)",
"values (#{databaseName,jdbcType=VARCHAR}, #{query,jdbcType=VARCHAR}, ",
"#{updatedAt,jdbcType=TIMESTAMP}, #{createdAt,jdbcType=TIMESTAMP}, ",
"#{lockVersion,jdbcType=INTEGER}, #{deletedFlg,jdbcType=INTEGER})"
})
@Options(useGeneratedKeys=true,keyProperty="id")
int insert(SqltoolLoad record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table SQLTOOL_LOAD
*
* @mbggenerated
*/
@InsertProvider(type=SqltoolLoadSqlProvider.class, method="insertSelective")
@Options(useGeneratedKeys=true,keyProperty="id")
int insertSelective(SqltoolLoad record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table SQLTOOL_LOAD
*
* @mbggenerated
*/
@SelectProvider(type=SqltoolLoadSqlProvider.class, method="selectByExample")
@Results({
@Result(column="ID", property="id", jdbcType=JdbcType.INTEGER, id=true),
@Result(column="DATABASE_NAME", property="databaseName", jdbcType=JdbcType.VARCHAR),
@Result(column="QUERY", property="query", jdbcType=JdbcType.VARCHAR),
@Result(column="UPDATED_AT", property="updatedAt", jdbcType=JdbcType.TIMESTAMP),
@Result(column="CREATED_AT", property="createdAt", jdbcType=JdbcType.TIMESTAMP),
@Result(column="LOCK_VERSION", property="lockVersion", jdbcType=JdbcType.INTEGER),
@Result(column="DELETED_FLG", property="deletedFlg", jdbcType=JdbcType.INTEGER)
})
List<SqltoolLoad> selectByExampleWithRowbounds(SqltoolLoadCriteria example, RowBounds rowBounds);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table SQLTOOL_LOAD
*
* @mbggenerated
*/
@SelectProvider(type=SqltoolLoadSqlProvider.class, method="selectByExample")
@Results({
@Result(column="ID", property="id", jdbcType=JdbcType.INTEGER, id=true),
@Result(column="DATABASE_NAME", property="databaseName", jdbcType=JdbcType.VARCHAR),
@Result(column="QUERY", property="query", jdbcType=JdbcType.VARCHAR),
@Result(column="UPDATED_AT", property="updatedAt", jdbcType=JdbcType.TIMESTAMP),
@Result(column="CREATED_AT", property="createdAt", jdbcType=JdbcType.TIMESTAMP),
@Result(column="LOCK_VERSION", property="lockVersion", jdbcType=JdbcType.INTEGER),
@Result(column="DELETED_FLG", property="deletedFlg", jdbcType=JdbcType.INTEGER)
})
List<SqltoolLoad> selectByExample(SqltoolLoadCriteria example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table SQLTOOL_LOAD
*
* @mbggenerated
*/
@Select({
"select",
"ID, DATABASE_NAME, QUERY, UPDATED_AT, CREATED_AT, LOCK_VERSION, DELETED_FLG",
"from SQLTOOL_LOAD",
"where ID = #{id,jdbcType=INTEGER}"
})
@Results({
@Result(column="ID", property="id", jdbcType=JdbcType.INTEGER, id=true),
@Result(column="DATABASE_NAME", property="databaseName", jdbcType=JdbcType.VARCHAR),
@Result(column="QUERY", property="query", jdbcType=JdbcType.VARCHAR),
@Result(column="UPDATED_AT", property="updatedAt", jdbcType=JdbcType.TIMESTAMP),
@Result(column="CREATED_AT", property="createdAt", jdbcType=JdbcType.TIMESTAMP),
@Result(column="LOCK_VERSION", property="lockVersion", jdbcType=JdbcType.INTEGER),
@Result(column="DELETED_FLG", property="deletedFlg", jdbcType=JdbcType.INTEGER)
})
SqltoolLoad selectByPrimaryKey(Integer id);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table SQLTOOL_LOAD
*
* @mbggenerated
*/
@UpdateProvider(type=SqltoolLoadSqlProvider.class, method="updateByExampleSelective")
int updateByExampleSelective(@Param("record") SqltoolLoad record, @Param("example") SqltoolLoadCriteria example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table SQLTOOL_LOAD
*
* @mbggenerated
*/
@UpdateProvider(type=SqltoolLoadSqlProvider.class, method="updateByExample")
int updateByExample(@Param("record") SqltoolLoad record, @Param("example") SqltoolLoadCriteria example);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table SQLTOOL_LOAD
*
* @mbggenerated
*/
@UpdateProvider(type=SqltoolLoadSqlProvider.class, method="updateByPrimaryKeySelective")
int updateByPrimaryKeySelective(SqltoolLoad record);
/**
* This method was generated by MyBatis Generator.
* This method corresponds to the database table SQLTOOL_LOAD
*
* @mbggenerated
*/
@Update({
"update SQLTOOL_LOAD",
"set DATABASE_NAME = #{databaseName,jdbcType=VARCHAR},",
"QUERY = #{query,jdbcType=VARCHAR},",
"UPDATED_AT = #{updatedAt,jdbcType=TIMESTAMP},",
"CREATED_AT = #{createdAt,jdbcType=TIMESTAMP},",
"LOCK_VERSION = #{lockVersion,jdbcType=INTEGER},",
"DELETED_FLG = #{deletedFlg,jdbcType=INTEGER}",
"where ID = #{id,jdbcType=INTEGER}"
})
int updateByPrimaryKey(SqltoolLoad record);
} | 40.802198 | 117 | 0.699838 |
1a7d1fb376096a5edced06837de3b9d39cef6f1e | 7,992 | // Copyright (C) 2016 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.server.account;
import static com.google.common.truth.Truth.assertThat;
import com.google.common.base.Splitter;
import com.google.gerrit.entities.Account;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import org.junit.Test;
public class AuthorizedKeysTest {
private static final String KEY1 =
"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQCgug5VyMXQGnem2H1KVC4/HcRcD4zzBqS"
+ "uJBRWVonSSoz3RoAZ7bWXCVVGwchtXwUURD689wFYdiPecOrWOUgeeyRq754YWRhU+W28"
+ "vf8IZixgjCmiBhaL2gt3wff6pP+NXJpTSA4aeWE5DfNK5tZlxlSxqkKOS8JRSUeNQov5T"
+ "w== john.doe@example.com";
private static final String KEY1_WITH_NEWLINES =
"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQCgug5VyMXQGnem2H1KVC4/HcRcD4zzBqS\n"
+ "uJBRWVonSSoz3RoAZ7bWXCVVGwchtXwUURD689wFYdiPecOrWOUgeeyRq754YWRhU+W28\n"
+ "vf8IZixgjCmiBhaL2gt3wff6pP+NXJpTSA4aeWE5DfNK5tZlxlSxqkKOS8JRSUeNQov5T\n"
+ "w== john.doe@example.com";
private static final String KEY2 =
"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQDm5yP7FmEoqzQRDyskX+9+N0q9GrvZeh5"
+ "RG52EUpE4ms/Ujm3ewV1LoGzc/lYKJAIbdcZQNJ9+06EfWZaIRA3oOwAPe1eCnX+aLr8E"
+ "6Tw2gDMQOGc5e9HfyXpC2pDvzauoZNYqLALOG3y/1xjo7IH8GYRS2B7zO/Mf9DdCcCKSf"
+ "w== john.doe@example.com";
private static final String KEY3 =
"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQCaS7RHEcZ/zjl9hkWkqnm29RNr2OQ/TZ5"
+ "jk2qBVMH3BgzPsTsEs+7ag9tfD8OCj+vOcwm626mQBZoR2e3niHa/9gnHBHFtOrGfzKbp"
+ "RjTWtiOZbB9HF+rqMVD+Dawo/oicX/dDg7VAgOFSPothe6RMhbgWf84UcK5aQd5eP5y+t"
+ "Q== john.doe@example.com";
private static final String KEY4 =
"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQDIJzW9BaAeO+upFletwwEBnGS15lJmS5i"
+ "08/NiFef0jXtNNKcLtnd13bq8jOi5VA2is0bwof1c8YbwcvUkdFa8RL5aXoyZBpfYZsWs"
+ "/YBLZGiHy5rjooMZQMnH37A50cBPnXr0AQz0WRBxLDBDyOZho+O/DfYAKv4rzPSQ3yw4+"
+ "w== john.doe@example.com";
private static final String KEY5 =
"ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQCgBRKGhiXvY6D9sM+Vbth5Kate57YF7kD"
+ "rqIyUiYIMJK93/AXc8qR/J/p3OIFQAxvLz1qozAur3j5HaiwvxVU19IiSA0vafdhaDLRi"
+ "zRuEL5e/QOu9yGq9xkWApCmg6edpWAHG+Bx4AldU78MiZvzoB7gMMdxc9RmZ1gYj/DjxV"
+ "w== john.doe@example.com";
private final Account.Id accountId = Account.id(1);
@Test
public void test() throws Exception {
List<Optional<AccountSshKey>> keys = new ArrayList<>();
StringBuilder expected = new StringBuilder();
assertSerialization(keys, expected);
assertParse(expected, keys);
expected.append(addKey(keys, KEY1));
assertSerialization(keys, expected);
assertParse(expected, keys);
expected.append(addKey(keys, KEY2));
assertSerialization(keys, expected);
assertParse(expected, keys);
expected.append(addInvalidKey(keys, KEY3));
assertSerialization(keys, expected);
assertParse(expected, keys);
expected.append(addKey(keys, KEY4));
assertSerialization(keys, expected);
assertParse(expected, keys);
expected.append(addDeletedKey(keys));
assertSerialization(keys, expected);
assertParse(expected, keys);
expected.append(addKey(keys, KEY5));
assertSerialization(keys, expected);
assertParse(expected, keys);
}
@Test
public void parseWindowsLineEndings() throws Exception {
List<Optional<AccountSshKey>> keys = new ArrayList<>();
StringBuilder authorizedKeys = new StringBuilder();
authorizedKeys.append(toWindowsLineEndings(addKey(keys, KEY1)));
assertParse(authorizedKeys, keys);
authorizedKeys.append(toWindowsLineEndings(addKey(keys, KEY2)));
assertParse(authorizedKeys, keys);
authorizedKeys.append(toWindowsLineEndings(addInvalidKey(keys, KEY3)));
assertParse(authorizedKeys, keys);
authorizedKeys.append(toWindowsLineEndings(addKey(keys, KEY4)));
assertParse(authorizedKeys, keys);
authorizedKeys.append(toWindowsLineEndings(addDeletedKey(keys)));
assertParse(authorizedKeys, keys);
authorizedKeys.append(toWindowsLineEndings(addKey(keys, KEY5)));
assertParse(authorizedKeys, keys);
}
@Test
public void validity() throws Exception {
AccountSshKey key = AccountSshKey.create(accountId, -1, KEY1);
assertThat(key.valid()).isFalse();
key = AccountSshKey.create(accountId, 0, KEY1);
assertThat(key.valid()).isFalse();
key = AccountSshKey.create(accountId, 1, KEY1);
assertThat(key.valid()).isTrue();
}
@Test
public void getters() throws Exception {
AccountSshKey key = AccountSshKey.create(accountId, 1, KEY1);
assertThat(key.sshPublicKey()).isEqualTo(KEY1);
List<String> keyParts = Splitter.on(" ").splitToList(KEY1);
assertThat(key.algorithm()).isEqualTo(keyParts.get(0));
assertThat(key.encodedKey()).isEqualTo(keyParts.get(1));
assertThat(key.comment()).isEqualTo(keyParts.get(2));
}
@Test
public void keyWithNewLines() throws Exception {
AccountSshKey key = AccountSshKey.create(accountId, 1, KEY1_WITH_NEWLINES);
assertThat(key.sshPublicKey()).isEqualTo(KEY1);
List<String> keyParts = Splitter.on(" ").splitToList(KEY1);
assertThat(key.algorithm()).isEqualTo(keyParts.get(0));
assertThat(key.encodedKey()).isEqualTo(keyParts.get(1));
assertThat(key.comment()).isEqualTo(keyParts.get(2));
}
private static String toWindowsLineEndings(String s) {
return s.replace("\n", "\r\n");
}
private static void assertSerialization(
List<Optional<AccountSshKey>> keys, StringBuilder expected) {
assertThat(AuthorizedKeys.serialize(keys)).isEqualTo(expected.toString());
}
private static void assertParse(
StringBuilder authorizedKeys, List<Optional<AccountSshKey>> expectedKeys) {
Account.Id accountId = Account.id(1);
List<Optional<AccountSshKey>> parsedKeys =
AuthorizedKeys.parse(accountId, authorizedKeys.toString());
assertThat(parsedKeys).containsExactlyElementsIn(expectedKeys);
int seq = 1;
for (Optional<AccountSshKey> sshKey : parsedKeys) {
if (sshKey.isPresent()) {
assertThat(sshKey.get().accountId()).isEqualTo(accountId);
assertThat(sshKey.get().seq()).isEqualTo(seq);
}
seq++;
}
}
/**
* Adds the given public key as new SSH key to the given list.
*
* @return the expected line for this key in the authorized_keys file
*/
private static String addKey(List<Optional<AccountSshKey>> keys, String pub) {
AccountSshKey key = AccountSshKey.create(Account.id(1), keys.size() + 1, pub);
keys.add(Optional.of(key));
return key.sshPublicKey() + "\n";
}
/**
* Adds the given public key as invalid SSH key to the given list.
*
* @return the expected line for this key in the authorized_keys file
*/
private static String addInvalidKey(List<Optional<AccountSshKey>> keys, String pub) {
AccountSshKey key = AccountSshKey.createInvalid(Account.id(1), keys.size() + 1, pub);
keys.add(Optional.of(key));
return AuthorizedKeys.INVALID_KEY_COMMENT_PREFIX + key.sshPublicKey() + "\n";
}
/**
* Adds a deleted SSH key to the given list.
*
* @return the expected line for this key in the authorized_keys file
*/
private static String addDeletedKey(List<Optional<AccountSshKey>> keys) {
keys.add(Optional.empty());
return AuthorizedKeys.DELETED_KEY_COMMENT + "\n";
}
}
| 39.176471 | 89 | 0.728353 |
6da1de650cdf56600d7241e7895c2bb6e4beda55 | 7,243 | package org.deeplearning4j.examples.feedforward.regression;
import org.deeplearning4j.examples.feedforward.regression.function.MathFunction;
import org.deeplearning4j.examples.feedforward.regression.function.SinXDivXMathFunction;
import org.nd4j.linalg.activations.Activation;
import org.nd4j.linalg.dataset.api.iterator.DataSetIterator;
import org.deeplearning4j.datasets.iterator.impl.ListDataSetIterator;
import org.deeplearning4j.nn.api.OptimizationAlgorithm;
import org.deeplearning4j.nn.conf.MultiLayerConfiguration;
import org.deeplearning4j.nn.conf.NeuralNetConfiguration;
import org.deeplearning4j.nn.conf.Updater;
import org.deeplearning4j.nn.conf.layers.DenseLayer;
import org.deeplearning4j.nn.conf.layers.OutputLayer;
import org.deeplearning4j.nn.multilayer.MultiLayerNetwork;
import org.deeplearning4j.nn.weights.WeightInit;
import org.deeplearning4j.optimize.listeners.ScoreIterationListener;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.dataset.DataSet;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.lossfunctions.LossFunctions;
import javax.swing.*;
import java.util.Collections;
import java.util.List;
import java.util.Random;
/**Example: Train a network to reproduce certain mathematical functions, and plot the results.
* Plotting of the network output occurs every 'plotFrequency' epochs. Thus, the plot shows the accuracy of the network
* predictions as training progresses.
* A number of mathematical functions are implemented here.
* Note the use of the identity function on the network output layer, for regression
*
* @author Alex Black
*/
public class RegressionMathFunctions {
//Random number generator seed, for reproducability
public static final int seed = 12345;
//Number of iterations per minibatch
public static final int iterations = 1;
//Number of epochs (full passes of the data)
public static final int nEpochs = 2000;
//How frequently should we plot the network output?
public static final int plotFrequency = 500;
//Number of data points
public static final int nSamples = 1000;
//Batch size: i.e., each epoch has nSamples/batchSize parameter updates
public static final int batchSize = 100;
//Network learning rate
public static final double learningRate = 0.01;
public static final Random rng = new Random(seed);
public static final int numInputs = 1;
public static final int numOutputs = 1;
public static void main(final String[] args){
//Switch these two options to do different functions with different networks
final MathFunction fn = new SinXDivXMathFunction();
final MultiLayerConfiguration conf = getDeepDenseLayerNetworkConfiguration();
//Generate the training data
final INDArray x = Nd4j.linspace(-10,10,nSamples).reshape(nSamples, 1);
final DataSetIterator iterator = getTrainingData(x,fn,batchSize,rng);
//Create the network
final MultiLayerNetwork net = new MultiLayerNetwork(conf);
net.init();
net.setListeners(new ScoreIterationListener(1));
//Train the network on the full data set, and evaluate in periodically
final INDArray[] networkPredictions = new INDArray[nEpochs/ plotFrequency];
for( int i=0; i<nEpochs; i++ ){
iterator.reset();
net.fit(iterator);
if((i+1) % plotFrequency == 0) networkPredictions[i/ plotFrequency] = net.output(x, false);
}
//Plot the target data and the network predictions
plot(fn,x,fn.getFunctionValues(x),networkPredictions);
}
/** Returns the network configuration, 2 hidden DenseLayers of size 50.
*/
private static MultiLayerConfiguration getDeepDenseLayerNetworkConfiguration() {
final int numHiddenNodes = 50;
return new NeuralNetConfiguration.Builder()
.seed(seed)
.iterations(iterations)
.optimizationAlgo(OptimizationAlgorithm.STOCHASTIC_GRADIENT_DESCENT)
.learningRate(learningRate)
.weightInit(WeightInit.XAVIER)
.updater(Updater.NESTEROVS).momentum(0.9)
.list()
.layer(0, new DenseLayer.Builder().nIn(numInputs).nOut(numHiddenNodes)
.activation(Activation.TANH).build())
.layer(1, new DenseLayer.Builder().nIn(numHiddenNodes).nOut(numHiddenNodes)
.activation(Activation.TANH).build())
.layer(2, new OutputLayer.Builder(LossFunctions.LossFunction.MSE)
.activation(Activation.IDENTITY)
.nIn(numHiddenNodes).nOut(numOutputs).build())
.pretrain(false).backprop(true).build();
}
/** Create a DataSetIterator for training
* @param x X values
* @param function Function to evaluate
* @param batchSize Batch size (number of examples for every call of DataSetIterator.next())
* @param rng Random number generator (for repeatability)
*/
private static DataSetIterator getTrainingData(final INDArray x, final MathFunction function, final int batchSize, final Random rng) {
final INDArray y = function.getFunctionValues(x);
final DataSet allData = new DataSet(x,y);
final List<DataSet> list = allData.asList();
Collections.shuffle(list,rng);
return new ListDataSetIterator(list,batchSize);
}
//Plot the data
private static void plot(final MathFunction function, final INDArray x, final INDArray y, final INDArray... predicted) {
final XYSeriesCollection dataSet = new XYSeriesCollection();
addSeries(dataSet,x,y,"True Function (Labels)");
for( int i=0; i<predicted.length; i++ ){
addSeries(dataSet,x,predicted[i],String.valueOf(i));
}
final JFreeChart chart = ChartFactory.createXYLineChart(
"Regression Example - " + function.getName(), // chart title
"X", // x axis label
function.getName() + "(X)", // y axis label
dataSet, // data
PlotOrientation.VERTICAL,
true, // include legend
true, // tooltips
false // urls
);
final ChartPanel panel = new ChartPanel(chart);
final JFrame f = new JFrame();
f.add(panel);
f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
}
private static void addSeries(final XYSeriesCollection dataSet, final INDArray x, final INDArray y, final String label){
final double[] xd = x.data().asDouble();
final double[] yd = y.data().asDouble();
final XYSeries s = new XYSeries(label);
for( int j=0; j<xd.length; j++ ) s.add(xd[j],yd[j]);
dataSet.addSeries(s);
}
}
| 43.89697 | 138 | 0.678724 |
d754f758ff808f715c4cdc9c576dfc81d18009ed | 847 | package prIndicePalabras;
import java.io.PrintWriter;
import java.util.*;
public class IndiceContador extends IndiceAbstracto{
private SortedMap<String, Integer> indice;
public IndiceContador() {
indice = new TreeMap<String, Integer>();
}
@Override
public void resolver(String delimitadores) {
indice.clear();
for(String frase:frases) {
try(Scanner sc = new Scanner(frase)){
sc.useDelimiter(delimitadores);
anyadir(sc);
}
}
}
private void anyadir(Scanner sc) {
while(sc.hasNext()) {
String str = sc.next().toLowerCase();
Integer n = indice.get(str);
if(n == null) {
n = 0;
}
n++;
indice.put(str, n);
}
}
@Override
public void presentarIndice(PrintWriter pw) {
for(Map.Entry<String, Integer> e: indice.entrySet()) {
pw.println(e.getKey() + " " + e.getValue());
}
}
}
| 18.413043 | 56 | 0.649351 |
a5ac85f5b0369cba5d4bbe25614de74830474075 | 1,458 | package net.omniscimus.fireworks.commands;
import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.apache.commons.cli.CommandLine;
import net.omniscimus.fireworks.ShowHandler;
/**
* This command stops the last started fireworks show.
*
* @author Omniscimus
*/
public class StopCommand extends FireworksCommand {
private final ShowHandler showHandler;
/**
* Creates a new StopCommand.
*
* @param showHandler the ShowHandler to use for stopping shows
*/
public StopCommand(ShowHandler showHandler) {
this.showHandler = showHandler;
}
@Override
public void run(CommandSender sender, CommandLine commandLine) {
if (showHandler.getNumberOfRunningShows() == 0) {
sender.sendMessage(
ChatColor.GOLD + "No shows are currently running!");
} else {
try {
showHandler.stopLastShow();
sender.sendMessage(
ChatColor.GOLD + "Fireworks show stopped.");
} catch (UnsupportedEncodingException ex) {
sender.sendMessage(ChatColor.GOLD + "Something went wrong while removing the show from the file of saved shows.");
Logger.getLogger(StopCommand.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
| 29.16 | 130 | 0.65775 |
fc3a307a4752a5f101a92fbc3d69a5af0c86d1da | 5,765 | /*
* Copyright 2021 Karlsruhe Institute of Technology.
* 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 edu.kit.datamanager.repo.util;
import edu.kit.datamanager.exceptions.UnsupportedMediaTypeException;
import edu.kit.datamanager.repo.util.validators.EValidatorMode;
import edu.kit.datamanager.repo.util.validators.IIdentifierValidator;
import edu.kit.datamanager.repo.util.validators.impl.DOIValidator;
import edu.kit.datamanager.repo.util.validators.impl.HandleValidator;
import edu.kit.datamanager.repo.util.validators.impl.ISBNValidator;
import edu.kit.datamanager.repo.util.validators.impl.URLValidator;
import org.datacite.schema.kernel_4.RelatedIdentifierType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
/**
* This class provides an util to validate identifiers.
*
* @author maximilianiKIT
*/
public class ValidatorUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(ValidatorUtil.class);
private static final ValidatorUtil soleInstance = new ValidatorUtil();
private static final Map<RelatedIdentifierType, IIdentifierValidator> validators;
private static EValidatorMode mode = EValidatorMode.FULL;
static {
Map<RelatedIdentifierType, IIdentifierValidator> validators1 = new HashMap<>();
validators1.put(RelatedIdentifierType.HANDLE, new HandleValidator());
validators1.put(RelatedIdentifierType.DOI, new DOIValidator());
validators1.put(RelatedIdentifierType.URL, new URLValidator());
validators1.put(RelatedIdentifierType.ISBN, new ISBNValidator());
if (LOGGER.isInfoEnabled()) {
for (RelatedIdentifierType type : validators1.keySet()) LOGGER.info("Validator found for '{}'", type);
}
validators = validators1;
}
/**
* This private constructor enforces singularity.
*/
private ValidatorUtil() {
}
/**
* This method returns the singleton.
*
* @return singleton instance of this class
*/
public static ValidatorUtil getSingleton() {
return soleInstance;
}
/**
* This method returns a list of the types of all implemented validators.
*
* @return a list of RelatedIdentifierType.
*/
public List<RelatedIdentifierType> getAllAvailableValidatorTypes() {
List<RelatedIdentifierType> result = new ArrayList<>();
validators.forEach((key, value) -> result.add(key));
LOGGER.debug("All available validator types: {}", result);
return result;
}
/**
* This method is a setter for the validator mode.
* @param mode the new validator mode from the enum.
*/
public void setMode(EValidatorMode mode) {
LOGGER.info("Changed validator mode to {}", mode);
if(mode == EValidatorMode.OFF) LOGGER.warn("You disabled the validation of identifiers. THIS IS NOT RECOMMENDED!");
ValidatorUtil.mode = mode;
}
/**
* This method is a setter for the validator mode.
* @return the actual validator mode.
*/
public EValidatorMode getMode() {
return mode;
}
/**
* This method checks if the type passed in the parameter is valid and then uses the corresponding validator to check the input.
*
* @param input The input which gets validated.
* @param type The type of the validator.
* @return true if the input and type are valid.
* May throw an exception if the input or the type is invalid or other errors occur.
*/
public boolean isValid(String input, RelatedIdentifierType type) {
LOGGER.debug("Validate identifier '{}' with type '{}'...", input, type);
boolean result = false;
if (validators.containsKey(type)) {
if (validators.get(type).isValid(input, type)) {
LOGGER.debug("Valid input {} and valid input type{}!", input, type);
result = true;
}
} else {
LOGGER.warn("No matching validator found for type {}. Please check the available types.", type);
throw new UnsupportedMediaTypeException("No matching validator found. Please check the available types.");
}
return result;
}
/**
* This method checks if the type passed in the parameter is valid and then uses the corresponding validator to check the input.
*
* @param input The input which gets validated.
* @param type The type of the validator as string.
* @return true if the input and type are valid.
* May throw an exception if the input or the type is invalid or other errors occur.
*/
public boolean isValid(String input, String type) {
LOGGER.debug("Validate identifier '{}' with type '{}'...", input, type);
boolean result = false;
try {
RelatedIdentifierType rType = RelatedIdentifierType.valueOf(type);
result = isValid(input, rType);
} catch (IllegalArgumentException e) {
LOGGER.warn("No matching validator found for type {}. Please check the available types.", type);
throw new UnsupportedMediaTypeException("No matching validator found. Please check the available types.");
}
return result;
}
}
| 39.758621 | 132 | 0.684302 |
f5d0cf627e9a0d6ce1998eb702bbe88578715b1a | 682 | package sample;
/*
Create java Date from specific time example.
This example shows how to create a java Date object for specific date and time.
*/
import java.util.Date;
public class CreateDateFromSpecificTimeExample {
public static void main(String[] args) {
/*
To create a Date object for sepefic date and time use
Date(long date) constuctor where date is the number of milliseconds
since January 1, 1970, 00:00:00 GMT.
*/
//date after one year of January 1, 1970, 00:00:00 GMT
Date d = new Date(365L * 24L * 60L * 60L * 1000L);
System.out.println(d);
}
}
/*
TYPICAL Output Would be
Thu Jan 01 00:00:00 EST 1971
*/
| 23.517241 | 81 | 0.671554 |
6266f170d8cd948d05dcb029b60ec1dcb5a1a144 | 54,463 | /*
* 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.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: storage-hbase/src/main/java/org/apache/kylin/storage/hbase/cube/v1/filter/protobuf/FilterExt.proto
package org.apache.kylin.storage.hbase.cube.v1.filter.generated;
public final class FilterProtosExt {
private FilterProtosExt() {}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistry registry) {
}
public interface BytesBytesPairOrBuilder
extends com.google.protobuf.MessageOrBuilder {
// required bytes first = 1;
/**
* <code>required bytes first = 1;</code>
*/
boolean hasFirst();
/**
* <code>required bytes first = 1;</code>
*/
com.google.protobuf.ByteString getFirst();
// required bytes second = 2;
/**
* <code>required bytes second = 2;</code>
*/
boolean hasSecond();
/**
* <code>required bytes second = 2;</code>
*/
com.google.protobuf.ByteString getSecond();
}
/**
* Protobuf type {@code BytesBytesPair}
*/
public static final class BytesBytesPair extends
com.google.protobuf.GeneratedMessage
implements BytesBytesPairOrBuilder {
// Use BytesBytesPair.newBuilder() to construct.
private BytesBytesPair(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
super(builder);
this.unknownFields = builder.getUnknownFields();
}
private BytesBytesPair(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
private static final BytesBytesPair defaultInstance;
public static BytesBytesPair getDefaultInstance() {
return defaultInstance;
}
public BytesBytesPair getDefaultInstanceForType() {
return defaultInstance;
}
private final com.google.protobuf.UnknownFieldSet unknownFields;
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private BytesBytesPair(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
initFields();
int mutable_bitField0_ = 0;
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;
default: {
if (!parseUnknownField(input, unknownFields,
extensionRegistry, tag)) {
done = true;
}
break;
}
case 10: {
bitField0_ |= 0x00000001;
first_ = input.readBytes();
break;
}
case 18: {
bitField0_ |= 0x00000002;
second_ = input.readBytes();
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e.getMessage()).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.internal_static_BytesBytesPair_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.internal_static_BytesBytesPair_fieldAccessorTable
.ensureFieldAccessorsInitialized(
org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair.class, org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair.Builder.class);
}
public static com.google.protobuf.Parser<BytesBytesPair> PARSER =
new com.google.protobuf.AbstractParser<BytesBytesPair>() {
public BytesBytesPair parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new BytesBytesPair(input, extensionRegistry);
}
};
@java.lang.Override
public com.google.protobuf.Parser<BytesBytesPair> getParserForType() {
return PARSER;
}
private int bitField0_;
// required bytes first = 1;
public static final int FIRST_FIELD_NUMBER = 1;
private com.google.protobuf.ByteString first_;
/**
* <code>required bytes first = 1;</code>
*/
public boolean hasFirst() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>required bytes first = 1;</code>
*/
public com.google.protobuf.ByteString getFirst() {
return first_;
}
// required bytes second = 2;
public static final int SECOND_FIELD_NUMBER = 2;
private com.google.protobuf.ByteString second_;
/**
* <code>required bytes second = 2;</code>
*/
public boolean hasSecond() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>required bytes second = 2;</code>
*/
public com.google.protobuf.ByteString getSecond() {
return second_;
}
private void initFields() {
first_ = com.google.protobuf.ByteString.EMPTY;
second_ = com.google.protobuf.ByteString.EMPTY;
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized != -1) return isInitialized == 1;
if (!hasFirst()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasSecond()) {
memoizedIsInitialized = 0;
return false;
}
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
getSerializedSize();
if (((bitField0_ & 0x00000001) == 0x00000001)) {
output.writeBytes(1, first_);
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
output.writeBytes(2, second_);
}
getUnknownFields().writeTo(output);
}
private int memoizedSerializedSize = -1;
public int getSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) == 0x00000001)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(1, first_);
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(2, second_);
}
size += getUnknownFields().getSerializedSize();
memoizedSerializedSize = size;
return size;
}
private static final long serialVersionUID = 0L;
@java.lang.Override
protected java.lang.Object writeReplace()
throws java.io.ObjectStreamException {
return super.writeReplace();
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair)) {
return super.equals(obj);
}
org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair other = (org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair) obj;
boolean result = true;
result = result && (hasFirst() == other.hasFirst());
if (hasFirst()) {
result = result && getFirst()
.equals(other.getFirst());
}
result = result && (hasSecond() == other.hasSecond());
if (hasSecond()) {
result = result && getSecond()
.equals(other.getSecond());
}
result = result &&
getUnknownFields().equals(other.getUnknownFields());
return result;
}
private int memoizedHashCode = 0;
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptorForType().hashCode();
if (hasFirst()) {
hash = (37 * hash) + FIRST_FIELD_NUMBER;
hash = (53 * hash) + getFirst().hashCode();
}
if (hasSecond()) {
hash = (37 * hash) + SECOND_FIELD_NUMBER;
hash = (53 * hash) + getSecond().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair parseFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input);
}
public static org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input, extensionRegistry);
}
public static org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static Builder newBuilder() { return Builder.create(); }
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder(org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair prototype) {
return newBuilder().mergeFrom(prototype);
}
public Builder toBuilder() { return newBuilder(this); }
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessage.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code BytesBytesPair}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessage.Builder<Builder>
implements org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPairOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.internal_static_BytesBytesPair_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.internal_static_BytesBytesPair_fieldAccessorTable
.ensureFieldAccessorsInitialized(
org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair.class, org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair.Builder.class);
}
// Construct using org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessage.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
}
}
private static Builder create() {
return new Builder();
}
public Builder clear() {
super.clear();
first_ = com.google.protobuf.ByteString.EMPTY;
bitField0_ = (bitField0_ & ~0x00000001);
second_ = com.google.protobuf.ByteString.EMPTY;
bitField0_ = (bitField0_ & ~0x00000002);
return this;
}
public Builder clone() {
return create().mergeFrom(buildPartial());
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.internal_static_BytesBytesPair_descriptor;
}
public org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair getDefaultInstanceForType() {
return org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair.getDefaultInstance();
}
public org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair build() {
org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair buildPartial() {
org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair result = new org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair(this);
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
to_bitField0_ |= 0x00000001;
}
result.first_ = first_;
if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
to_bitField0_ |= 0x00000002;
}
result.second_ = second_;
result.bitField0_ = to_bitField0_;
onBuilt();
return result;
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair) {
return mergeFrom((org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair other) {
if (other == org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair.getDefaultInstance()) return this;
if (other.hasFirst()) {
setFirst(other.getFirst());
}
if (other.hasSecond()) {
setSecond(other.getSecond());
}
this.mergeUnknownFields(other.getUnknownFields());
return this;
}
public final boolean isInitialized() {
if (!hasFirst()) {
return false;
}
if (!hasSecond()) {
return false;
}
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair) e.getUnfinishedMessage();
throw e;
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
// required bytes first = 1;
private com.google.protobuf.ByteString first_ = com.google.protobuf.ByteString.EMPTY;
/**
* <code>required bytes first = 1;</code>
*/
public boolean hasFirst() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
/**
* <code>required bytes first = 1;</code>
*/
public com.google.protobuf.ByteString getFirst() {
return first_;
}
/**
* <code>required bytes first = 1;</code>
*/
public Builder setFirst(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000001;
first_ = value;
onChanged();
return this;
}
/**
* <code>required bytes first = 1;</code>
*/
public Builder clearFirst() {
bitField0_ = (bitField0_ & ~0x00000001);
first_ = getDefaultInstance().getFirst();
onChanged();
return this;
}
// required bytes second = 2;
private com.google.protobuf.ByteString second_ = com.google.protobuf.ByteString.EMPTY;
/**
* <code>required bytes second = 2;</code>
*/
public boolean hasSecond() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
/**
* <code>required bytes second = 2;</code>
*/
public com.google.protobuf.ByteString getSecond() {
return second_;
}
/**
* <code>required bytes second = 2;</code>
*/
public Builder setSecond(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000002;
second_ = value;
onChanged();
return this;
}
/**
* <code>required bytes second = 2;</code>
*/
public Builder clearSecond() {
bitField0_ = (bitField0_ & ~0x00000002);
second_ = getDefaultInstance().getSecond();
onChanged();
return this;
}
// @@protoc_insertion_point(builder_scope:BytesBytesPair)
}
static {
defaultInstance = new BytesBytesPair(true);
defaultInstance.initFields();
}
// @@protoc_insertion_point(class_scope:BytesBytesPair)
}
public interface FuzzyRowFilterV2OrBuilder
extends com.google.protobuf.MessageOrBuilder {
// repeated .BytesBytesPair fuzzy_keys_data = 1;
/**
* <code>repeated .BytesBytesPair fuzzy_keys_data = 1;</code>
*/
java.util.List<org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair>
getFuzzyKeysDataList();
/**
* <code>repeated .BytesBytesPair fuzzy_keys_data = 1;</code>
*/
org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair getFuzzyKeysData(int index);
/**
* <code>repeated .BytesBytesPair fuzzy_keys_data = 1;</code>
*/
int getFuzzyKeysDataCount();
/**
* <code>repeated .BytesBytesPair fuzzy_keys_data = 1;</code>
*/
java.util.List<? extends org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPairOrBuilder>
getFuzzyKeysDataOrBuilderList();
/**
* <code>repeated .BytesBytesPair fuzzy_keys_data = 1;</code>
*/
org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPairOrBuilder getFuzzyKeysDataOrBuilder(
int index);
}
/**
* Protobuf type {@code FuzzyRowFilterV2}
*/
public static final class FuzzyRowFilterV2 extends
com.google.protobuf.GeneratedMessage
implements FuzzyRowFilterV2OrBuilder {
// Use FuzzyRowFilterV2.newBuilder() to construct.
private FuzzyRowFilterV2(com.google.protobuf.GeneratedMessage.Builder<?> builder) {
super(builder);
this.unknownFields = builder.getUnknownFields();
}
private FuzzyRowFilterV2(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); }
private static final FuzzyRowFilterV2 defaultInstance;
public static FuzzyRowFilterV2 getDefaultInstance() {
return defaultInstance;
}
public FuzzyRowFilterV2 getDefaultInstanceForType() {
return defaultInstance;
}
private final com.google.protobuf.UnknownFieldSet unknownFields;
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private FuzzyRowFilterV2(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
initFields();
int mutable_bitField0_ = 0;
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;
default: {
if (!parseUnknownField(input, unknownFields,
extensionRegistry, tag)) {
done = true;
}
break;
}
case 10: {
if (!((mutable_bitField0_ & 0x00000001) == 0x00000001)) {
fuzzyKeysData_ = new java.util.ArrayList<org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair>();
mutable_bitField0_ |= 0x00000001;
}
fuzzyKeysData_.add(input.readMessage(org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair.PARSER, extensionRegistry));
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e.getMessage()).setUnfinishedMessage(this);
} finally {
if (((mutable_bitField0_ & 0x00000001) == 0x00000001)) {
fuzzyKeysData_ = java.util.Collections.unmodifiableList(fuzzyKeysData_);
}
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.internal_static_FuzzyRowFilterV2_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.internal_static_FuzzyRowFilterV2_fieldAccessorTable
.ensureFieldAccessorsInitialized(
org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.FuzzyRowFilterV2.class, org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.FuzzyRowFilterV2.Builder.class);
}
public static com.google.protobuf.Parser<FuzzyRowFilterV2> PARSER =
new com.google.protobuf.AbstractParser<FuzzyRowFilterV2>() {
public FuzzyRowFilterV2 parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new FuzzyRowFilterV2(input, extensionRegistry);
}
};
@java.lang.Override
public com.google.protobuf.Parser<FuzzyRowFilterV2> getParserForType() {
return PARSER;
}
// repeated .BytesBytesPair fuzzy_keys_data = 1;
public static final int FUZZY_KEYS_DATA_FIELD_NUMBER = 1;
private java.util.List<org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair> fuzzyKeysData_;
/**
* <code>repeated .BytesBytesPair fuzzy_keys_data = 1;</code>
*/
public java.util.List<org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair> getFuzzyKeysDataList() {
return fuzzyKeysData_;
}
/**
* <code>repeated .BytesBytesPair fuzzy_keys_data = 1;</code>
*/
public java.util.List<? extends org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPairOrBuilder>
getFuzzyKeysDataOrBuilderList() {
return fuzzyKeysData_;
}
/**
* <code>repeated .BytesBytesPair fuzzy_keys_data = 1;</code>
*/
public int getFuzzyKeysDataCount() {
return fuzzyKeysData_.size();
}
/**
* <code>repeated .BytesBytesPair fuzzy_keys_data = 1;</code>
*/
public org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair getFuzzyKeysData(int index) {
return fuzzyKeysData_.get(index);
}
/**
* <code>repeated .BytesBytesPair fuzzy_keys_data = 1;</code>
*/
public org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPairOrBuilder getFuzzyKeysDataOrBuilder(
int index) {
return fuzzyKeysData_.get(index);
}
private void initFields() {
fuzzyKeysData_ = java.util.Collections.emptyList();
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized != -1) return isInitialized == 1;
for (int i = 0; i < getFuzzyKeysDataCount(); i++) {
if (!getFuzzyKeysData(i).isInitialized()) {
memoizedIsInitialized = 0;
return false;
}
}
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
getSerializedSize();
for (int i = 0; i < fuzzyKeysData_.size(); i++) {
output.writeMessage(1, fuzzyKeysData_.get(i));
}
getUnknownFields().writeTo(output);
}
private int memoizedSerializedSize = -1;
public int getSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
for (int i = 0; i < fuzzyKeysData_.size(); i++) {
size += com.google.protobuf.CodedOutputStream
.computeMessageSize(1, fuzzyKeysData_.get(i));
}
size += getUnknownFields().getSerializedSize();
memoizedSerializedSize = size;
return size;
}
private static final long serialVersionUID = 0L;
@java.lang.Override
protected java.lang.Object writeReplace()
throws java.io.ObjectStreamException {
return super.writeReplace();
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.FuzzyRowFilterV2)) {
return super.equals(obj);
}
org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.FuzzyRowFilterV2 other = (org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.FuzzyRowFilterV2) obj;
boolean result = true;
result = result && getFuzzyKeysDataList()
.equals(other.getFuzzyKeysDataList());
result = result &&
getUnknownFields().equals(other.getUnknownFields());
return result;
}
private int memoizedHashCode = 0;
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptorForType().hashCode();
if (getFuzzyKeysDataCount() > 0) {
hash = (37 * hash) + FUZZY_KEYS_DATA_FIELD_NUMBER;
hash = (53 * hash) + getFuzzyKeysDataList().hashCode();
}
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.FuzzyRowFilterV2 parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.FuzzyRowFilterV2 parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.FuzzyRowFilterV2 parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.FuzzyRowFilterV2 parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.FuzzyRowFilterV2 parseFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.FuzzyRowFilterV2 parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.FuzzyRowFilterV2 parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input);
}
public static org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.FuzzyRowFilterV2 parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseDelimitedFrom(input, extensionRegistry);
}
public static org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.FuzzyRowFilterV2 parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return PARSER.parseFrom(input);
}
public static org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.FuzzyRowFilterV2 parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return PARSER.parseFrom(input, extensionRegistry);
}
public static Builder newBuilder() { return Builder.create(); }
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder(org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.FuzzyRowFilterV2 prototype) {
return newBuilder().mergeFrom(prototype);
}
public Builder toBuilder() { return newBuilder(this); }
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessage.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* Protobuf type {@code FuzzyRowFilterV2}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessage.Builder<Builder>
implements org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.FuzzyRowFilterV2OrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.internal_static_FuzzyRowFilterV2_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.internal_static_FuzzyRowFilterV2_fieldAccessorTable
.ensureFieldAccessorsInitialized(
org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.FuzzyRowFilterV2.class, org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.FuzzyRowFilterV2.Builder.class);
}
// Construct using org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.FuzzyRowFilterV2.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessage.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
getFuzzyKeysDataFieldBuilder();
}
}
private static Builder create() {
return new Builder();
}
public Builder clear() {
super.clear();
if (fuzzyKeysDataBuilder_ == null) {
fuzzyKeysData_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
} else {
fuzzyKeysDataBuilder_.clear();
}
return this;
}
public Builder clone() {
return create().mergeFrom(buildPartial());
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.internal_static_FuzzyRowFilterV2_descriptor;
}
public org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.FuzzyRowFilterV2 getDefaultInstanceForType() {
return org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.FuzzyRowFilterV2.getDefaultInstance();
}
public org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.FuzzyRowFilterV2 build() {
org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.FuzzyRowFilterV2 result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
public org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.FuzzyRowFilterV2 buildPartial() {
org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.FuzzyRowFilterV2 result = new org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.FuzzyRowFilterV2(this);
int from_bitField0_ = bitField0_;
if (fuzzyKeysDataBuilder_ == null) {
if (((bitField0_ & 0x00000001) == 0x00000001)) {
fuzzyKeysData_ = java.util.Collections.unmodifiableList(fuzzyKeysData_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.fuzzyKeysData_ = fuzzyKeysData_;
} else {
result.fuzzyKeysData_ = fuzzyKeysDataBuilder_.build();
}
onBuilt();
return result;
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.FuzzyRowFilterV2) {
return mergeFrom((org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.FuzzyRowFilterV2)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.FuzzyRowFilterV2 other) {
if (other == org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.FuzzyRowFilterV2.getDefaultInstance()) return this;
if (fuzzyKeysDataBuilder_ == null) {
if (!other.fuzzyKeysData_.isEmpty()) {
if (fuzzyKeysData_.isEmpty()) {
fuzzyKeysData_ = other.fuzzyKeysData_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureFuzzyKeysDataIsMutable();
fuzzyKeysData_.addAll(other.fuzzyKeysData_);
}
onChanged();
}
} else {
if (!other.fuzzyKeysData_.isEmpty()) {
if (fuzzyKeysDataBuilder_.isEmpty()) {
fuzzyKeysDataBuilder_.dispose();
fuzzyKeysDataBuilder_ = null;
fuzzyKeysData_ = other.fuzzyKeysData_;
bitField0_ = (bitField0_ & ~0x00000001);
fuzzyKeysDataBuilder_ =
com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ?
getFuzzyKeysDataFieldBuilder() : null;
} else {
fuzzyKeysDataBuilder_.addAllMessages(other.fuzzyKeysData_);
}
}
}
this.mergeUnknownFields(other.getUnknownFields());
return this;
}
public final boolean isInitialized() {
for (int i = 0; i < getFuzzyKeysDataCount(); i++) {
if (!getFuzzyKeysData(i).isInitialized()) {
return false;
}
}
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.FuzzyRowFilterV2 parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.FuzzyRowFilterV2) e.getUnfinishedMessage();
throw e;
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
// repeated .BytesBytesPair fuzzy_keys_data = 1;
private java.util.List<org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair> fuzzyKeysData_ =
java.util.Collections.emptyList();
private void ensureFuzzyKeysDataIsMutable() {
if (!((bitField0_ & 0x00000001) == 0x00000001)) {
fuzzyKeysData_ = new java.util.ArrayList<org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair>(fuzzyKeysData_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilder<
org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair, org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair.Builder, org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPairOrBuilder> fuzzyKeysDataBuilder_;
/**
* <code>repeated .BytesBytesPair fuzzy_keys_data = 1;</code>
*/
public java.util.List<org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair> getFuzzyKeysDataList() {
if (fuzzyKeysDataBuilder_ == null) {
return java.util.Collections.unmodifiableList(fuzzyKeysData_);
} else {
return fuzzyKeysDataBuilder_.getMessageList();
}
}
/**
* <code>repeated .BytesBytesPair fuzzy_keys_data = 1;</code>
*/
public int getFuzzyKeysDataCount() {
if (fuzzyKeysDataBuilder_ == null) {
return fuzzyKeysData_.size();
} else {
return fuzzyKeysDataBuilder_.getCount();
}
}
/**
* <code>repeated .BytesBytesPair fuzzy_keys_data = 1;</code>
*/
public org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair getFuzzyKeysData(int index) {
if (fuzzyKeysDataBuilder_ == null) {
return fuzzyKeysData_.get(index);
} else {
return fuzzyKeysDataBuilder_.getMessage(index);
}
}
/**
* <code>repeated .BytesBytesPair fuzzy_keys_data = 1;</code>
*/
public Builder setFuzzyKeysData(
int index, org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair value) {
if (fuzzyKeysDataBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureFuzzyKeysDataIsMutable();
fuzzyKeysData_.set(index, value);
onChanged();
} else {
fuzzyKeysDataBuilder_.setMessage(index, value);
}
return this;
}
/**
* <code>repeated .BytesBytesPair fuzzy_keys_data = 1;</code>
*/
public Builder setFuzzyKeysData(
int index, org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair.Builder builderForValue) {
if (fuzzyKeysDataBuilder_ == null) {
ensureFuzzyKeysDataIsMutable();
fuzzyKeysData_.set(index, builderForValue.build());
onChanged();
} else {
fuzzyKeysDataBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
* <code>repeated .BytesBytesPair fuzzy_keys_data = 1;</code>
*/
public Builder addFuzzyKeysData(org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair value) {
if (fuzzyKeysDataBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureFuzzyKeysDataIsMutable();
fuzzyKeysData_.add(value);
onChanged();
} else {
fuzzyKeysDataBuilder_.addMessage(value);
}
return this;
}
/**
* <code>repeated .BytesBytesPair fuzzy_keys_data = 1;</code>
*/
public Builder addFuzzyKeysData(
int index, org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair value) {
if (fuzzyKeysDataBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureFuzzyKeysDataIsMutable();
fuzzyKeysData_.add(index, value);
onChanged();
} else {
fuzzyKeysDataBuilder_.addMessage(index, value);
}
return this;
}
/**
* <code>repeated .BytesBytesPair fuzzy_keys_data = 1;</code>
*/
public Builder addFuzzyKeysData(
org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair.Builder builderForValue) {
if (fuzzyKeysDataBuilder_ == null) {
ensureFuzzyKeysDataIsMutable();
fuzzyKeysData_.add(builderForValue.build());
onChanged();
} else {
fuzzyKeysDataBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
* <code>repeated .BytesBytesPair fuzzy_keys_data = 1;</code>
*/
public Builder addFuzzyKeysData(
int index, org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair.Builder builderForValue) {
if (fuzzyKeysDataBuilder_ == null) {
ensureFuzzyKeysDataIsMutable();
fuzzyKeysData_.add(index, builderForValue.build());
onChanged();
} else {
fuzzyKeysDataBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
* <code>repeated .BytesBytesPair fuzzy_keys_data = 1;</code>
*/
public Builder addAllFuzzyKeysData(
java.lang.Iterable<? extends org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair> values) {
if (fuzzyKeysDataBuilder_ == null) {
ensureFuzzyKeysDataIsMutable();
super.addAll(values, fuzzyKeysData_);
onChanged();
} else {
fuzzyKeysDataBuilder_.addAllMessages(values);
}
return this;
}
/**
* <code>repeated .BytesBytesPair fuzzy_keys_data = 1;</code>
*/
public Builder clearFuzzyKeysData() {
if (fuzzyKeysDataBuilder_ == null) {
fuzzyKeysData_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
fuzzyKeysDataBuilder_.clear();
}
return this;
}
/**
* <code>repeated .BytesBytesPair fuzzy_keys_data = 1;</code>
*/
public Builder removeFuzzyKeysData(int index) {
if (fuzzyKeysDataBuilder_ == null) {
ensureFuzzyKeysDataIsMutable();
fuzzyKeysData_.remove(index);
onChanged();
} else {
fuzzyKeysDataBuilder_.remove(index);
}
return this;
}
/**
* <code>repeated .BytesBytesPair fuzzy_keys_data = 1;</code>
*/
public org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair.Builder getFuzzyKeysDataBuilder(
int index) {
return getFuzzyKeysDataFieldBuilder().getBuilder(index);
}
/**
* <code>repeated .BytesBytesPair fuzzy_keys_data = 1;</code>
*/
public org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPairOrBuilder getFuzzyKeysDataOrBuilder(
int index) {
if (fuzzyKeysDataBuilder_ == null) {
return fuzzyKeysData_.get(index); } else {
return fuzzyKeysDataBuilder_.getMessageOrBuilder(index);
}
}
/**
* <code>repeated .BytesBytesPair fuzzy_keys_data = 1;</code>
*/
public java.util.List<? extends org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPairOrBuilder>
getFuzzyKeysDataOrBuilderList() {
if (fuzzyKeysDataBuilder_ != null) {
return fuzzyKeysDataBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(fuzzyKeysData_);
}
}
/**
* <code>repeated .BytesBytesPair fuzzy_keys_data = 1;</code>
*/
public org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair.Builder addFuzzyKeysDataBuilder() {
return getFuzzyKeysDataFieldBuilder().addBuilder(
org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair.getDefaultInstance());
}
/**
* <code>repeated .BytesBytesPair fuzzy_keys_data = 1;</code>
*/
public org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair.Builder addFuzzyKeysDataBuilder(
int index) {
return getFuzzyKeysDataFieldBuilder().addBuilder(
index, org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair.getDefaultInstance());
}
/**
* <code>repeated .BytesBytesPair fuzzy_keys_data = 1;</code>
*/
public java.util.List<org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair.Builder>
getFuzzyKeysDataBuilderList() {
return getFuzzyKeysDataFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilder<
org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair, org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair.Builder, org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPairOrBuilder>
getFuzzyKeysDataFieldBuilder() {
if (fuzzyKeysDataBuilder_ == null) {
fuzzyKeysDataBuilder_ = new com.google.protobuf.RepeatedFieldBuilder<
org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair, org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPair.Builder, org.apache.kylin.storage.hbase.cube.v1.filter.generated.FilterProtosExt.BytesBytesPairOrBuilder>(
fuzzyKeysData_,
((bitField0_ & 0x00000001) == 0x00000001),
getParentForChildren(),
isClean());
fuzzyKeysData_ = null;
}
return fuzzyKeysDataBuilder_;
}
// @@protoc_insertion_point(builder_scope:FuzzyRowFilterV2)
}
static {
defaultInstance = new FuzzyRowFilterV2(true);
defaultInstance.initFields();
}
// @@protoc_insertion_point(class_scope:FuzzyRowFilterV2)
}
private static com.google.protobuf.Descriptors.Descriptor
internal_static_BytesBytesPair_descriptor;
private static
com.google.protobuf.GeneratedMessage.FieldAccessorTable
internal_static_BytesBytesPair_fieldAccessorTable;
private static com.google.protobuf.Descriptors.Descriptor
internal_static_FuzzyRowFilterV2_descriptor;
private static
com.google.protobuf.GeneratedMessage.FieldAccessorTable
internal_static_FuzzyRowFilterV2_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor
getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor
descriptor;
static {
java.lang.String[] descriptorData = {
"\nbstorage-hbase/src/main/java/org/apache" +
"/kylin/storage/hbase/cube/v1/filter/prot" +
"obuf/FilterExt.proto\"/\n\016BytesBytesPair\022\r" +
"\n\005first\030\001 \002(\014\022\016\n\006second\030\002 \002(\014\"<\n\020FuzzyRo" +
"wFilterV2\022(\n\017fuzzy_keys_data\030\001 \003(\0132\017.Byt" +
"esBytesPairBR\n7org.apache.kylin.storage." +
"hbase.cube.v1.filter.generatedB\017FilterPr" +
"otosExtH\001\210\001\001\240\001\001"
};
com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() {
public com.google.protobuf.ExtensionRegistry assignDescriptors(
com.google.protobuf.Descriptors.FileDescriptor root) {
descriptor = root;
internal_static_BytesBytesPair_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_BytesBytesPair_fieldAccessorTable = new
com.google.protobuf.GeneratedMessage.FieldAccessorTable(
internal_static_BytesBytesPair_descriptor,
new java.lang.String[] { "First", "Second", });
internal_static_FuzzyRowFilterV2_descriptor =
getDescriptor().getMessageTypes().get(1);
internal_static_FuzzyRowFilterV2_fieldAccessorTable = new
com.google.protobuf.GeneratedMessage.FieldAccessorTable(
internal_static_FuzzyRowFilterV2_descriptor,
new java.lang.String[] { "FuzzyKeysData", });
return null;
}
};
com.google.protobuf.Descriptors.FileDescriptor
.internalBuildGeneratedFileFrom(descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
}, assigner);
}
// @@protoc_insertion_point(outer_class_scope)
}
| 40.283284 | 313 | 0.669372 |
d8804ff435df14e49beedc392f3880f73b1e1b7e | 3,462 | /*
* 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.uima.ducc.ws.db;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class DbMachine implements IDbMachine{
private Map<String, Object> map = new HashMap<String, Object>();
private enum Key {
classes, // [weekly urgent background normal reserve JobDriver high debug low standalone fixed]
reservable, // [true]
share_order, // [2]
assignments, // [0]
blacklisted, // [false]
memory, // [30]
online, // [true]
ip, // [192.168.4.4]
heartbeats, // [0]
nodepool, // [--default--]
shares_left, // [2]
quantum, // [15]
name, // [bluejws67-4]
responsive, // [true]
};
public DbMachine(Map<String, Object> map) {
initMap(map);
}
private void initMap(Map<String, Object> value) {
if(value != null) {
map.putAll(value);
}
}
public List<String> getClasses() {
List<String> retVal = new ArrayList<String>();
String classes = (String) map.get(Key.classes.name());
if(classes != null) {
String[] array = classes.split("\\s+");
if(array != null) {
retVal = Arrays.asList(array);
}
}
return retVal;
}
public Boolean getReservable() {
Boolean retVal = (Boolean) map.get(Key.reservable.name());
return retVal;
}
public Integer getShareOrder() {
Integer retVal = (Integer) map.get(Key.share_order.name());
return retVal;
}
public Integer getAssignments() {
Integer retVal = (Integer) map.get(Key.assignments.name());
return retVal;
}
public Boolean getBlacklisted() {
Boolean retVal = (Boolean) map.get(Key.blacklisted.name());
return retVal;
}
public Integer getMemory() {
Integer retVal = (Integer) map.get(Key.memory.name());
return retVal;
}
public Boolean getOnline() {
Boolean retVal = (Boolean) map.get(Key.online.name());
return retVal;
}
public String getIp() {
String retVal = (String) map.get(Key.ip.name());
return retVal;
}
public Integer getHeartbeats() {
Integer retVal = (Integer) map.get(Key.heartbeats.name());
return retVal;
}
public String getNodePool() {
String retVal = (String) map.get(Key.nodepool.name());
return retVal;
}
public Integer getSharesLeft() {
Integer retVal = (Integer) map.get(Key.shares_left.name());
return retVal;
}
public Integer getQuantum() {
Integer retVal = (Integer) map.get(Key.quantum.name());
return retVal;
}
public String getName() {
String retVal = (String) map.get(Key.name.name());
return retVal;
}
public Boolean getResponsive() {
Boolean retVal = (Boolean) map.get(Key.responsive.name());
return retVal;
}
}
| 25.455882 | 100 | 0.679954 |
4faf4a1984688886f65fc6a84562b20bb98f4948 | 515 | /*
* Copyright (C) 2017 Baidu, Inc. All Rights Reserved.
*/
package com.baidu.aip.face;
import com.baidu.aip.ImageFrame;
/**
* FaceDetectManager 人脸检测之前的回调。可以对图片进行预处理。如果ImageFrame中的argb数据为空,将不进行检测。
*/
public interface FaceProcessor {
/**
* FaceDetectManager 回调该方法,对图片帧进行处理。
* @param detectManager 回调的 FaceDetectManager
* @param frame 需要处理的图片帧。
* @return 返回true剩下的FaceProcessor将不会被回调。
*/
boolean process(FaceDetectManager detectManager, ImageFrame frame);
}
| 25.75 | 74 | 0.697087 |
e48dbd9db15e46ebfb7523282cac4229851ba8fa | 2,444 | package gov.nist.registry.ws.sq.ebxmlrr21.test;
import gov.nist.registry.common2.registry.Metadata;
import gov.nist.registry.common2.registry.storedquery.StoredQuerySupport;
import gov.nist.registry.ws.sq.ebxmlrr21.EbXML21QuerySupport;
import gov.nist.registry.ws.sq.test.TestBase;
import gov.nist.registry.ws.sq.test.testdata.FindDocsTestData;
import java.util.List;
import org.apache.axiom.om.OMAttribute;
import org.apache.axiom.om.OMElement;
import org.testng.annotations.Test;
public class ValidateProperUids extends TestBase {
FindDocsTestData testdata;
public ValidateProperUids() throws Exception {
super();
}
@Test
public void newUids() throws Exception {
StoredQuerySupport sqs = new StoredQuerySupport(this , log);
EbXML21QuerySupport eqs = new EbXML21QuerySupport(sqs);
testdata = new FindDocsTestData();
List<OMElement> eoElements = testdata.getDocElements();
Metadata m = new Metadata();
m.addToMetadata(eoElements, false);
// assign new uids that don't exist in registry
String uid_prefix = "999.999.9.";
int counter = 1;
for (OMElement ele : eoElements) {
String id = m.getId(ele);
OMAttribute uid_att = m.getUniqueIdAttribute(id);
uid_att.setAttributeValue(uid_prefix + Integer.toString(counter));
counter++;
}
try {
eqs.validateProperUids(m);
} catch (Exception e) {
System.out.println(e.getMessage());
assert false;
}
}
@Test
public void sameUids() throws Exception {
StoredQuerySupport sqs = new StoredQuerySupport(this , log);
EbXML21QuerySupport eqs = new EbXML21QuerySupport(sqs);
testdata = new FindDocsTestData();
List<OMElement> eoElements = testdata.getDocElements();
Metadata m = new Metadata();
m.addToMetadata(eoElements, false);
try {
eqs.validateProperUids(m);
} catch (Exception e) {
System.out.println(e.getMessage());
assert false;
}
}
@Test
public void differentHash() throws Exception {
StoredQuerySupport sqs = new StoredQuerySupport(this , log);
EbXML21QuerySupport eqs = new EbXML21QuerySupport(sqs);
testdata = new FindDocsTestData();
List<OMElement> eoElements = testdata.getDocElements();
Metadata m = new Metadata();
m.addToMetadata(eoElements, false);
for (OMElement eo : eoElements) {
m.setSlotValue(eo, "hash", 0, "ee34");
}
try {
eqs.validateProperUids(m);
} catch (Exception e) {
System.out.println(e.getMessage());
assert false;
}
assert false;
}
}
| 26.565217 | 73 | 0.732406 |
5727e2d98b70fed2da5bd0307d2aeffa8654ce19 | 1,123 | package com.ceiba.festivos.comando.manejador;
import com.ceiba.ComandoRespuesta;
import com.ceiba.festivos.comando.ComandoFestivos;
import com.ceiba.festivos.servicio.ServicioCrearFestivos;
import com.ceiba.manejador.ManejadorComandoRespuesta;
import com.ceiba.festivos.modelo.entidad.Festivos;
import org.springframework.stereotype.Component;
import com.ceiba.festivos.comando.fabrica.FabricaFestivos;
@Component
public class ManejadorCrearFestivos implements ManejadorComandoRespuesta<ComandoFestivos, ComandoRespuesta<Long>> {
private final FabricaFestivos fabricaFestivos;
private final ServicioCrearFestivos servicioCrearFestivos;
public ManejadorCrearFestivos(FabricaFestivos fabricaFestivos, ServicioCrearFestivos servicioCrearFestivos) {
this.fabricaFestivos = fabricaFestivos;
this.servicioCrearFestivos = servicioCrearFestivos;
}
public ComandoRespuesta<Long> ejecutar(ComandoFestivos comandoFestivos) {
Festivos festivos = this.fabricaFestivos.crear(comandoFestivos);
return new ComandoRespuesta<>(this.servicioCrearFestivos.ejecutar(festivos));
}
}
| 40.107143 | 115 | 0.821015 |
9a633c9349e18a2212f31e9fa1170f8b248ba99a | 1,196 | package hackerrank.datastructures.stacks;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class BalancedBracketsTest {
private final BalancedBrackets balancedBrackets;
public BalancedBracketsTest() {
balancedBrackets = new BalancedBrackets();
}
@Test
void testIsBalanced1() {
assertEquals("YES", balancedBrackets.isBalanced("{[()]}"));
assertEquals("YES", balancedBrackets.isBalanced("{{[[(())]]}}"));
assertEquals("YES", balancedBrackets.isBalanced("{(([])[])[]}[]"));
assertEquals("NO", balancedBrackets.isBalanced("{[(])}"));
assertEquals("NO", balancedBrackets.isBalanced("{"));
assertEquals("NO", balancedBrackets.isBalanced("]"));
}
@Test
void testIsBalancedMethod2() {
assertEquals("YES", balancedBrackets.isBalancedConcise("{[()]}"));
assertEquals("YES", balancedBrackets.isBalancedConcise("{{[[(())]]}}"));
assertEquals("YES", balancedBrackets.isBalancedConcise("{(([])[])[]}[]"));
assertEquals("NO", balancedBrackets.isBalancedConcise("{[(])}"));
assertEquals("NO", balancedBrackets.isBalancedConcise("{"));
assertEquals("NO", balancedBrackets.isBalancedConcise("]"));
}
} | 35.176471 | 78 | 0.681438 |
31b53164e1d92d5336301c921142e1b4889ba4ca | 4,469 | /*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the "License"). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied, as more fully set forth in the License.
*
* See the NOTICE file distributed with this work for information regarding copyright ownership.
*/
package alluxio.worker.netty;
import alluxio.Constants;
import alluxio.network.protocol.RPCBlockReadRequest;
import alluxio.network.protocol.RPCBlockWriteRequest;
import alluxio.network.protocol.RPCErrorResponse;
import alluxio.network.protocol.RPCFileReadRequest;
import alluxio.network.protocol.RPCFileWriteRequest;
import alluxio.network.protocol.RPCMessage;
import alluxio.network.protocol.RPCRequest;
import alluxio.network.protocol.RPCResponse;
import alluxio.worker.AlluxioWorkerService;
import com.google.common.base.Preconditions;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import javax.annotation.concurrent.NotThreadSafe;
/**
* This class processes {@link RPCRequest} messages and delegates them to the appropriate
* handlers to return {@link RPCResponse} messages.
*/
@ChannelHandler.Sharable
@NotThreadSafe
final class DataServerHandler extends SimpleChannelInboundHandler<RPCMessage> {
private static final Logger LOG = LoggerFactory.getLogger(Constants.LOGGER_TYPE);
/** Handler for any block store requests. */
private final BlockDataServerHandler mBlockHandler;
/** Handler for any file system requests. */
private final UnderFileSystemDataServerHandler mUnderFileSystemHandler;
/**
* Creates a new instance of {@link DataServerHandler}.
*
* @param worker the Alluxio worker handle
*/
public DataServerHandler(final AlluxioWorkerService worker) {
Preconditions.checkNotNull(worker, "worker");
mBlockHandler = new BlockDataServerHandler(worker.getBlockWorker());
mUnderFileSystemHandler = new UnderFileSystemDataServerHandler(worker.getFileSystemWorker());
}
@Override
public void channelRead0(final ChannelHandlerContext ctx, final RPCMessage msg)
throws IOException {
switch (msg.getType()) {
case RPC_BLOCK_READ_REQUEST:
assert msg instanceof RPCBlockReadRequest;
mBlockHandler.handleBlockReadRequest(ctx, (RPCBlockReadRequest) msg);
break;
case RPC_BLOCK_WRITE_REQUEST:
assert msg instanceof RPCBlockWriteRequest;
mBlockHandler.handleBlockWriteRequest(ctx, (RPCBlockWriteRequest) msg);
break;
case RPC_FILE_READ_REQUEST:
assert msg instanceof RPCFileReadRequest;
mUnderFileSystemHandler.handleFileReadRequest(ctx, (RPCFileReadRequest) msg);
break;
case RPC_FILE_WRITE_REQUEST:
assert msg instanceof RPCFileWriteRequest;
mUnderFileSystemHandler.handleFileWriteRequest(ctx, (RPCFileWriteRequest) msg);
break;
case RPC_ERROR_RESPONSE:
// TODO(peis): Fix this, we should not assert here.
assert msg instanceof RPCErrorResponse;
LOG.error("Received an error response from the client: " + msg.toString());
break;
default:
RPCErrorResponse resp = new RPCErrorResponse(RPCResponse.Status.UNKNOWN_MESSAGE_ERROR);
ctx.writeAndFlush(resp);
// TODO(peis): Fix this. We should not throw an exception here.
throw new IllegalArgumentException(
"No handler implementation for rpc msg type: " + msg.getType());
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
LOG.warn("Exception thrown while processing request", cause);
// TODO(peis): This doesn't have to be decode error, it can also be any network errors such as
// connection reset. Fix this ALLUXIO-2235.
RPCErrorResponse resp = new RPCErrorResponse(RPCResponse.Status.DECODE_ERROR);
ChannelFuture channelFuture = ctx.writeAndFlush(resp);
// Close the channel because it is likely a network error.
channelFuture.addListener(ChannelFutureListener.CLOSE);
}
}
| 41.37963 | 98 | 0.763482 |
e11313168655eb3ec6953ee609b239fed4019a26 | 855 | package JavaCode.random_records.N1_100;
import JavaCode.linked_list.ListNode;
/**
* author:fangjie
* time:2019/11/28
*/
public class N83_remove_duplicates_from_sorted_list {
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public ListNode deleteDuplicates(ListNode head) {
ListNode p=head,q;
while (p!=null)
{
q=p.next;
while (q!=null&&q.val==p.val) q=q.next;
p.next=q;
p=q;
}
return head;
}
}
/*
给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。
示例 1:
输入: 1->1->2
输出: 1->2
示例 2:
输入: 1->1->2->3->3
输出: 1->2->3
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*/
| 19.883721 | 70 | 0.577778 |
05a29c510259d98337e17aaa2e5c9253e3210ab7 | 807 | package com.jhnuxer.gametest0.iarm2;
import java.util.*;
import com.jhnuxer.math.*;
import com.jhnuxer.gametest0.*;
public class Iarm2SmootheTerrainPass extends AIarm2GenPass {
int smootheRadius;
UShortMap map;
private int x;
private int y;
public Iarm2SmootheTerrainPass(Iarm2 iarm,int sr) {
super("Smoothing Terrain",iarm.w*iarm.h*4,iarm);
this.smootheRadius = sr;
this.map = iarm2.elev;
}
public void run() {
UShortMap usm = new UShortMap(iarm2.w,iarm2.h);
for (y = 0; y < iarm2.h; y++) {
for (x = 0; x < iarm2.w; x++) usm.set(x,y,map.getAvg(x,y,smootheRadius));
}
for (int k = 0; k < iarm2.h; k++) {
for (int h = 0; h < iarm2.w; h++) map.set(h,k,usm.get(h,k));
}
}
public int getCompleted() {
return ((y * iarm2.w) + x) * 4;
}
}
| 23.735294 | 79 | 0.61834 |
18d9a6c71d5f556888f4c8f74c005db67e458483 | 18,177 | package appointmentscheduler.service.user;
import appointmentscheduler.dto.phonenumber.PhoneNumberDTO;
import appointmentscheduler.dto.settings.UpdateSettingsDTO;
import appointmentscheduler.dto.user.UpdateEmailDTO;
import appointmentscheduler.dto.user.UpdatePasswordDTO;
import appointmentscheduler.dto.user.UserLoginDTO;
import appointmentscheduler.dto.user.UserRegisterDTO;
import appointmentscheduler.entity.business.Business;
import appointmentscheduler.entity.phonenumber.PhoneNumber;
import appointmentscheduler.entity.role.RoleEnum;
import appointmentscheduler.entity.settings.Settings;
import appointmentscheduler.entity.user.Employee;
import appointmentscheduler.entity.user.User;
import appointmentscheduler.entity.user.UserFactory;
import appointmentscheduler.entity.verification.ResetPasswordToken;
import appointmentscheduler.entity.verification.Verification;
import appointmentscheduler.exception.*;
import appointmentscheduler.repository.*;
import appointmentscheduler.util.JwtProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DataAccessException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import javax.mail.MessagingException;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
@Service
public class UserService {
private static final Logger logger = Logger.getLogger(UserService.class.getName());
private final UserRepository userRepository;
private final EmployeeRepository employeeRepository;
private final VerificationRepository verificationRepository;
private final JwtProvider jwtProvider;
private final BCryptPasswordEncoder bCryptPasswordEncoder;
private final AuthenticationManager authenticationManager;
private final SettingsRepository settingsRepository;
private final PhoneNumberRepository phoneNumberRepository;
private final BusinessRepository businessRepository;
private final ResetPasswordTokenRepository resetPasswordTokenRepository;
//private final UserFileRepository userFileRepository;
// private final UserFileStorageService userFileStorageService;
@Autowired
public UserService(
EmployeeRepository employeeRepository, BusinessRepository businessRepository, UserRepository userRepository,
JwtProvider jwtProvider,
VerificationRepository verificationRepository, BCryptPasswordEncoder bCryptPasswordEncoder,
@Qualifier("authenticationManagerBean") AuthenticationManager authenticationManager, SettingsRepository settingsRepository,
PhoneNumberRepository phoneNumberRepository, ResetPasswordTokenRepository resetPasswordTokenRepository
) {
this.employeeRepository = employeeRepository;
this.businessRepository = businessRepository;
this.userRepository = userRepository;
this.verificationRepository = verificationRepository;
this.jwtProvider = jwtProvider;
this.bCryptPasswordEncoder = bCryptPasswordEncoder;
this.authenticationManager = authenticationManager;
this.settingsRepository = settingsRepository;
this.phoneNumberRepository = phoneNumberRepository;
this.resetPasswordTokenRepository = resetPasswordTokenRepository;
}
public Map<String, Object> register(UserRegisterDTO userRegisterDTO, RoleEnum role) throws IOException, MessagingException, NoSuchAlgorithmException {
if (userRepository.findByEmailIgnoreCase(userRegisterDTO.getEmail()).orElse(null) != null) {
throw new UserAlreadyExistsException(String.format("A user with the email %s already exists.", userRegisterDTO.getEmail()));
}
final User user = new User();
user.setFirstName(userRegisterDTO.getFirstName());
user.setLastName(userRegisterDTO.getLastName());
user.setEmail(userRegisterDTO.getEmail());
user.setPassword(bCryptPasswordEncoder.encode(userRegisterDTO.getPassword()));
if (userRegisterDTO.getPhoneNumber() != null) {
PhoneNumberDTO phoneNumberDTO = userRegisterDTO.getPhoneNumber();
PhoneNumber phoneNumber = new PhoneNumber(
phoneNumberDTO.getCountryCode(),
phoneNumberDTO.getAreaCode(),
phoneNumberDTO.getNumber()
);
user.setPhoneNumber(phoneNumber);
phoneNumber.setUser(user);
}
if(role.toString().equals(RoleEnum.ADMIN.toString())){
user.setRole(RoleEnum.ADMIN.toString());
}else{
user.setRole(RoleEnum.CLIENT.toString());
}
User savedUser = userRepository.save(user);
Verification verification = new Verification(savedUser);
verificationRepository.save(verification);
String token = generateToken(savedUser, userRegisterDTO.getPassword());
return buildTokenRegisterMap( token, verification);
}
public Map<String, String> login(UserLoginDTO userLoginDTO) {
User user = userRepository.findByEmailIgnoreCase(userLoginDTO.getEmail())
.orElseThrow(() -> new BadCredentialsException("Incorrect email/password combination."));
if (!user.isVerified())
throw new ModelValidationException("Incomplete verification");
String token = generateToken(user, userLoginDTO.getPassword());
return buildTokenMap(token);
}
private Map<String, String> buildTokenMap(String token) {
Map<String, String> map = new HashMap<>();
map.put("token", token);
return map;
}
private Map<String, Object> buildTokenRegisterMap(String token, Verification verification) {
Map<String, Object> map = new HashMap<>();
map.put("token", token);
map.put("verification", verification);
return map;
}
public User findUserById(long id) {
return userRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException(String.format("User with id %d not found.", id)));
}
public User findUserByEmail(String email) {
return userRepository.findByEmailIgnoreCase(email)
.orElseThrow(() -> new ResourceNotFoundException(String.format("User with email %d not found.", email)));
}
// todo change user repository to query the businessId also, user table doesnt have businessId
public User findUserByIdAndBusinessId(long id, long businessId) {
User user = userRepository.findByIdAndBusinessId(id, businessId).
orElseThrow(() -> new ResourceNotFoundException(String.format("User with id %d and business id %d " +
"not found.", id, businessId)));
return user;
}
public Employee findByIdAndBusinessId(long id, long businessId) {
return employeeRepository.findByIdAndBusinessId(id, businessId).
orElseThrow(() -> new ResourceNotFoundException(String.format("Employee with id %d and business id %d" +
" " +
"not found.", id, businessId)));
}
public List<User> findAllByBusinessId(long id) {
return userRepository.findAllByBusinessId(id)
.orElseThrow(() -> new ResourceNotFoundException(String.format("Users for business ID %d " +
"not found.", id)));
}
public void associateBusinessToUser(long businessId, long userId){
Business business = this.businessRepository.findById(businessId).get();
User user = this.userRepository.findById(userId).get();
business.setOwner(user);
this.businessRepository.save(business);
}
public Map<String, String> updateUser(User user, long businessId) throws DataAccessException {
Business business = businessRepository.findById(businessId)
.orElseThrow(() -> new ResourceNotFoundException(String.format("Business with ID %d not found.",
businessId)));
user.setBusiness(business);
userRepository.save(user);
return message("User updated");
}
public Map<String, String> updateUserRole(User user, long businessId, String role) throws DataAccessException {
Business business = businessRepository.findById(businessId)
.orElseThrow(() -> new ResourceNotFoundException(String.format("Business with ID %d not found.",
businessId)));
Employee employee = new Employee();
employee.setBusiness(business);
employee.setRole(role);
employee.setFirstName(user.getFirstName());
employee.setLastName(user.getLastName());
employee.setPassword(user.getPassword());
employee.setVerified(user.isVerified());
employee.setCreatedAt(user.getCreatedAt());
employee.setUpdatedAt(user.getUpdatedAt());
employee.setSettings(user.getSettings());
employee.setEmail(user.getEmail());
userRepository.delete(user);
employeeRepository.save(employee);
return message("User updated");
}
private String generateToken(User user, String unhashedPassword) {
Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(user.getId(), unhashedPassword));
SecurityContextHolder.getContext().setAuthentication(authentication);
return jwtProvider.generateToken(user, authentication);
}
public Map<String, String> updateEmail(long id, String oldEmail, UpdateEmailDTO updateEmailDTO) {
User user = userRepository.findByIdAndEmailIgnoreCase(id, oldEmail)
.orElseThrow(() -> new ResourceNotFoundException(String.format("User with ID %d and email %s not found.", id, oldEmail)));
if (updateEmailDTO.getPassword() == null || !bCryptPasswordEncoder.matches(updateEmailDTO.getPassword(), user.getPassword())) {
throw new IncorrectPasswordException("Incorrect password.");
}
if (updateEmailDTO.getNewEmail() == null) {
throw new InvalidUpdateException("You must provide a new email.");
}
if (user.getEmail().equalsIgnoreCase(updateEmailDTO.getNewEmail())) {
throw new InvalidUpdateException(String.format("Your email is already %s.", user.getEmail()));
}
if (userRepository.findByEmailIgnoreCase(updateEmailDTO.getNewEmail()).orElse(null) != null) {
throw new UserAlreadyExistsException(String.format("A user with the email %s already exists.", updateEmailDTO.getNewEmail()));
}
user.setEmail(updateEmailDTO.getNewEmail());
userRepository.save(user);
return message(String.format("You've successfully updated your email to %s.", user.getEmail()));
}
public Map<String, String> updatePassword(long id, UpdatePasswordDTO updatePasswordDTO) {
User user = userRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException(String.format("User with ID %d not found.", id)));
if (updatePasswordDTO.getOldPassword() == null || !bCryptPasswordEncoder.matches(updatePasswordDTO.getOldPassword(), user.getPassword())) {
throw new IncorrectPasswordException("The old password you provided is incorrect.");
}
if (updatePasswordDTO.getNewPassword() == null) {
throw new PasswordNotProvidedExcetion("You must provide a new password.");
}
user.setPassword(bCryptPasswordEncoder.encode(updatePasswordDTO.getNewPassword()));
userRepository.save(user);
return message("You've successfully updated your password.");
}
public Map<String, String> resetPassword(long id, String newPassword) {
User user = userRepository.findById(id)
.orElseThrow(() -> new ResourceNotFoundException(String.format("User with ID %d not found.", id)));
if (newPassword == null) {
throw new PasswordNotProvidedExcetion("You must provide a new password.");
}
user.setPassword(bCryptPasswordEncoder.encode(newPassword));
userRepository.save(user);
return message("You've successfully updated your password.");
}
public Settings getSettings(long userId) {
return settingsRepository.findByUserId(userId)
.orElseThrow(() -> new ResourceNotFoundException(String.format("Settings not found under user with ID %d.", userId)));
}
public Map<String, String> updateSettings(long userId, UpdateSettingsDTO updateSettingsDTO) {
Settings settings = getSettings(userId);
settings.setEmailReminder(updateSettingsDTO.isEmailReminder());
settings.setTextReminder(updateSettingsDTO.isTextReminder());
settingsRepository.save(settings);
String message;
boolean emailReminder = settings.isEmailReminder();
boolean textReminder = settings.isTextReminder();
if (!emailReminder && !textReminder) {
message = "You will no longer receive reminders for upcoming appointments.";
} else if (emailReminder && !textReminder) {
message = "You will now only receive reminders for upcoming appointments via email.";
} else if (!emailReminder && textReminder) {
message = "You will now only receive reminders for upcoming appointments via text message.";
} else {
message = "You will now receive reminders for upcoming appointments via both email and text message.";
}
return message(message);
}
public PhoneNumber getPhoneNumber(long userId) {
return phoneNumberRepository.findByUserId(userId).orElse(null);
}
public Map<String, String> saveOrUpdatePhoneNumber(long userId, PhoneNumberDTO phoneNumberDTO) {
PhoneNumber phoneNumber = phoneNumberRepository.findByUserId(userId).orElse(null);
String message;
if (phoneNumber != null) {
phoneNumber.setCountryCode(phoneNumberDTO.getCountryCode());
phoneNumber.setAreaCode(phoneNumberDTO.getAreaCode());
phoneNumber.setNumber(phoneNumberDTO.getNumber());
message = "You've successfully updated your phone number.";
} else {
User user = userRepository.findById(userId)
.orElseThrow(() -> new ResourceNotFoundException(String.format("User with ID %d not found.", userId)));
phoneNumber = new PhoneNumber(phoneNumberDTO.getCountryCode(), phoneNumberDTO.getAreaCode(), phoneNumberDTO.getAreaCode(), user);
message = "You've successfully saved your phone number.";
}
phoneNumberRepository.save(phoneNumber);
return message(message);
}
public Map<String, String> deletePhoneNumber(long userId) {
PhoneNumber phoneNumber = phoneNumberRepository.findByUserId(userId)
.orElseThrow(() -> new ResourceNotFoundException(String.format("Phone number not found user used with ID %d.", userId)));
phoneNumberRepository.delete(phoneNumber);
return message("You've successfully deleted your phone number.");
}
private Map<String, String> message(String message) {
Map<String, String> map = new HashMap<>();
map.put("message", message);
return map;
}
public Map<String, Object> businessRegister(UserRegisterDTO userRegisterDTO, Business business) throws IOException, MessagingException, NoSuchAlgorithmException {
if (userRepository.findByEmailIgnoreCase(userRegisterDTO.getEmail()).orElse(null) != null) {
throw new UserAlreadyExistsException(String.format("A user with the email %s already exists.", userRegisterDTO.getEmail()));
}
User user = UserFactory.createAdmin(business, User.class, userRegisterDTO.getFirstName(), userRegisterDTO.getLastName(), userRegisterDTO.getEmail(), bCryptPasswordEncoder.encode(userRegisterDTO.getPassword()));
if (userRegisterDTO.getPhoneNumber() != null) {
PhoneNumberDTO phoneNumberDTO = userRegisterDTO.getPhoneNumber();
PhoneNumber phoneNumber = new PhoneNumber(
phoneNumberDTO.getCountryCode(),
phoneNumberDTO.getAreaCode(),
phoneNumberDTO.getNumber()
);
user.setPhoneNumber(phoneNumber);
phoneNumber.setUser(user);
}
user.setRole(RoleEnum.ADMIN.toString());
User savedUser = userRepository.save(user);
Verification verification = new Verification(savedUser);
verificationRepository.save(verification);
String token = generateToken(savedUser, userRegisterDTO.getPassword());
return buildTokenRegisterMap( token, verification);
}
public void createResetPasswordTokenForUser(User user, String token) {
ResetPasswordToken resetPasswordToken = new ResetPasswordToken(token, user);
resetPasswordTokenRepository.save(resetPasswordToken);
}
public List<User> findAllClients() {
List<User> userlist = userRepository.findByRole(RoleEnum.CLIENT);
if (userlist == null) {
throw new ResourceNotFoundException("Clients not found");
}
return userlist;
}
public List<User> findAllUsersForBusiness(long businessId, RoleEnum roleEnum) {
return userRepository.findByRoleOrBusinessIdOrderByRole(roleEnum, businessId).orElseThrow(() -> new ResourceNotFoundException(String.format(
"Users not found for business with id %d .", businessId)));
}
}
| 44.660934 | 218 | 0.706442 |
36a3a29ea8e0d9eb42cfe40586b0daf0f8d360df | 807 | package com.rarchives.ripme.tst.ripper.rippers;
import java.io.IOException;
import java.net.URL;
import com.rarchives.ripme.ripper.rippers.TapasticRipper;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
public class TapasticRipperTest extends RippersTest {
@Test
@Disabled("ripper broken")
public void testTapasticRip() throws IOException {
TapasticRipper ripper = new TapasticRipper(new URL("https://tapas.io/series/TPIAG"));
testRipper(ripper);
}
@Test
public void testGetGID() throws IOException {
URL url = new URL("https://tapas.io/series/TPIAG");
TapasticRipper ripper = new TapasticRipper(url);
Assertions.assertEquals("series_ TPIAG", ripper.getGID(url));
}
}
| 31.038462 | 93 | 0.722429 |
4b772b7edb002ad6d8152acbdc30b5ae59167ae9 | 1,810 | package at.petrak.hexcasting.common.items.colorizer;
import at.petrak.hexcasting.api.cap.Colorizer;
import at.petrak.hexcasting.api.item.ColorizerItem;
import net.minecraft.world.item.Item;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.phys.Vec3;
import java.util.UUID;
public class ItemPrideColorizer extends Item implements ColorizerItem {
private final int idx;
public ItemPrideColorizer(int idx, Properties pProperties) {
super(pProperties);
this.idx = idx;
}
@Override
public int color(ItemStack stack, UUID owner, float time, Vec3 position) {
return Colorizer.morphBetweenColors(getColors(), new Vec3(0.1, 0.1, 0.1), time / 20 / 20, position);
}
public int[] getColors() {
return COLORS[this.idx];
}
private static final int[][] COLORS;
static {
COLORS = new int[][]{
{0xeb92ea, 0xffffff, 0x6ac2e4},
{0xd82f3a, 0xe0883f, 0xebf367, 0x2db418, 0x2f4dd8},
{0x16a10c, 0x82eb8b, 0xffffff, 0x7a8081},
{0x333233, 0x9a9fa1, 0xffffff, 0x7210bc},
{0xdb45ff, 0x9c2bd0, 0x6894d4},
{0xe278ef, 0xebf367, 0x6ac2e4},
{0xca78ef, 0xffffff, 0x2db418},
{0x9a9fa1, 0xfcb1ff, 0xffffff},
{0xebf367, 0xffffff, 0x7210bc, 0x333233},
{0xd82f3a, 0xefb87d, 0xffffff, 0xfbacf9},
{0x9a9fa1, 0xa9ffff, 0xffffff},
{0xfbacf9, 0xffffff, 0x9c2bd0, 0x333233, 0x2f4dd8},
{0xebf367, 0x7210bc}, // how to do an intersex gradient escapes me
{0x7210bc, 0xebf367, 0xffffff, 0x82dceb, 0x2f4dd8}
};
for (int[] color : COLORS) {
for (int i = 0; i < color.length; i++) {
color[i] |= 0xff_000000;
}
}
}
}
| 33.518519 | 108 | 0.61768 |
4d641f8a7b460ca2aef78c8ba676ecc70cb95683 | 625 | package org.yangdongdong.springcloud.service;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.yangdongdong.springcloud.RetryApplication;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = RetryApplication.class)
public class RetryServiceTest {
@Autowired
private RetryService retryservice;
@Test
public void testCall() throws Exception{
retryservice.call();
}
}
| 27.173913 | 71 | 0.8032 |
696cccae40e55d9f29a46b5798fecabc230525b7 | 384 | package com.smartling.api.jobs.v3.pto.account;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
@Data
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
@Builder
public class IssuesCountsPTO
{
private int sourceIssuesCount;
private int translationIssuesCount;
}
| 20.210526 | 46 | 0.817708 |
56e5a0e00ca7229c53bf41b5da7ff8fac4954b6d | 10,104 | package application.view.game;
import java.util.ArrayList;
import java.util.List;
import application.Main;
import application.ai.Ai;
import application.ai.Ai.Node;
import application.view.game.HexGrid.Tile;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.Cursor;
import javafx.scene.Scene;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;
public class Game {
private Stage primaryStage;
private Scene scene;
private AnchorPane mainLayout;
private HexGrid hexGrid;
private Text textCurrentPlayer;
private boolean gameEnded;
private ArrayList<ArrayList<Tile>> connectedPathsListWhite = new ArrayList<ArrayList<Tile>>();
private ArrayList<ArrayList<Tile>> connectedPathsListBlack = new ArrayList<ArrayList<Tile>>();
private String playerWhite;
private String playerBlack;
private Color playerWhiteColor = Color.LIGHTSTEELBLUE;
private Color playerBlackColor = Color.BLACK.brighter();
private int aiDepth;
private int currentPlayer;
public void init(Stage primaryStage) {
try {
this.primaryStage = primaryStage;
FXMLLoader loader = new FXMLLoader();
loader.setLocation(Main.class.getResource("view/game/GameView.fxml"));
mainLayout = loader.load();
GameViewController gameViewController = (GameViewController) loader.getController();
this.scene = new Scene(mainLayout);
this.primaryStage.setScene(scene);
this.primaryStage.show();
gameViewController.getSplitPane().lookupAll(".split-pane-divider").stream()
.forEach(div -> div.setMouseTransparent(true));
hexGrid = gameViewController.getHexGrid();
hexGrid.createHexGrid();
hexGrid.printBoardStatus();
gameEnded = false;
currentPlayer = 0;
playerBlack = "Anonymous";
playerWhite = "Anonymous";
aiDepth = 5;
textCurrentPlayer = gameViewController.getTextCurrentPlayer();
textCurrentPlayer.setText("Black's turn" + " (" + playerBlack + ")");
} catch (Exception e) {
e.printStackTrace();
}
}
public void run() {
primaryStage.getScene().getWindow().addEventFilter(WindowEvent.WINDOW_CLOSE_REQUEST, this::closeWindowEvent);
for (int x = 0; x < hexGrid.getTilesPerRow(); x++) {
for (int y = 0; y < hexGrid.getRowCount(); y++) {
hexGrid.getTileCoordArray()[x][y].addEventFilter(MouseEvent.MOUSE_CLICKED, tileClickedEvent);
hexGrid.getTileCoordArray()[x][y].setOnMouseEntered((new EventHandler<MouseEvent>() {
public void handle(MouseEvent event) {
scene.setCursor(Cursor.HAND);
}
}));
hexGrid.getTileCoordArray()[x][y].setOnMouseExited((new EventHandler<MouseEvent>() {
public void handle(MouseEvent event) {
scene.setCursor(Cursor.DEFAULT);
}
}));
}
}
}
EventHandler<MouseEvent> tileClickedEvent = new EventHandler<MouseEvent>() {
@Override
public void handle(MouseEvent e) {
if (!gameEnded) {
Object target = e.getTarget();
if (target instanceof Tile) {
if (((Tile) target).getStonePlaced() == 0) {
/**
* if (currentPlayer % 2 == 1) { hexGrid.drawStone((Tile) target,
* playerWhiteColor); ((Tile) target).setStonePlaced(currentPlayer % 2 + 1);
* checkAdjacentHexes((Tile) target); currentPlayer++;
* textCurrentPlayer.setText("Black's turn" + " (" + playerBlack + ")"); }
**/
if (currentPlayer % 2 == 0) {
hexGrid.drawStone((Tile) target, playerBlackColor);
((Tile) target).setStonePlaced(currentPlayer % 2 + 1);
checkAdjacentHexes((Tile) target);
currentPlayer++;
textCurrentPlayer.setText("White's turn" + " (" + playerWhite + ")");
aiMove();
}
} else
System.out.println("There already is a stone" + " (" + ((Tile) target).getStonePlaced() + ") "
+ "on this tile");
}
}
}
};
private void aiMove() {
Ai ai = new Ai(hexGrid);
System.out.println("Current advantage: ");
System.out.println(
ai.minimaxAb(hexGrid.intFromTile(), aiDepth, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, true));
System.out.println("Amount of Alpha cut-offs: " + ai.getAlphaCutoffCounter());
System.out.println("Amount of Beta cut-offs: " + ai.getBetaCutoffCounter());
System.out.println("Current best AI move: ");
System.out.println(ai.currentBestMove[0] + " " + ai.currentBestMove[1]);
if (ai.currentBestMove[0] != -2 && ai.currentBestMove[1] != -2) {
hexGrid.drawStone(hexGrid.getTile(ai.currentBestMove[0], ai.currentBestMove[1]), playerWhiteColor);
hexGrid.getTile(ai.currentBestMove[0], ai.currentBestMove[1]).setStonePlaced(currentPlayer % 2 + 1);
}
List<Node> aiShortestPathFilteredList;
List<Node> playerShortestPathFilteredList;
aiShortestPathFilteredList = ai.getComputerShortestPath(hexGrid.intFromTile());
playerShortestPathFilteredList = ai.getPlayerShortestPath(hexGrid.intFromTile());
System.out.println("Shortest path for AI: " + aiShortestPathFilteredList.size());
for (Node node : aiShortestPathFilteredList) {
System.out.println(node.getXHexCoord() + " " + node.getYHexCoord());
}
System.out.println("Shortest path for player: " + playerShortestPathFilteredList.size());
for (Node node : playerShortestPathFilteredList) {
System.out.println(node.getXHexCoord() + " " + node.getYHexCoord());
}
currentPlayer++;
textCurrentPlayer.setText("Black's turn" + " (" + playerBlack + ")");
}
private void closeWindowEvent(WindowEvent event) {
System.out.println("Window close request ...");
}
private void checkAdjacentHexes(Tile tile) {
ArrayList<Tile> adjacentTiles = tile.getAdjacentTilesOfSameColour(hexGrid.getTileCoordArray());
ArrayList<Tile> tempPath = new ArrayList<Tile>();
boolean preexistingPath = false;
System.out.println("Adjacent tiles:");
for (int i = 0; i < adjacentTiles.size(); i++)
System.out.println(adjacentTiles.get(i).getXHexCoord() + " " + adjacentTiles.get(i).getYHexCoord());
adjacentTiles.add(tile);
if (tile.getStonePlaced() == 2) {
for (int i = 0; i < connectedPathsListWhite.size(); i++) {
for (int j = 0; j < adjacentTiles.size(); j++) {
if (connectedPathsListWhite.get(i).contains(adjacentTiles.get(j))) {
tempPath.addAll(connectedPathsListWhite.get(i));
tempPath.addAll(adjacentTiles);
connectedPathsListWhite.get(i).clear();
preexistingPath = true;
if (connectedPathsListWhite.size() <= i)
break;
}
}
}
connectedPathsListWhite.removeIf(p -> p.isEmpty());
if (preexistingPath == false) {
connectedPathsListWhite.add(adjacentTiles);
} else {
ArrayList<Tile> tempPathDuplicatesRemoved = new ArrayList<Tile>();
for (int i = 0; i < tempPath.size(); i++) {
if (!tempPathDuplicatesRemoved.contains(tempPath.get(i)))
tempPathDuplicatesRemoved.add(tempPath.get(i));
}
connectedPathsListWhite.add(tempPathDuplicatesRemoved);
}
System.out.println("All (White) connected paths:");
for (int i = 0; i < connectedPathsListWhite.size(); i++) {
for (int j = 0; j < connectedPathsListWhite.get(i).size(); j++) {
System.out.println(connectedPathsListWhite.get(i).get(j).getXHexCoord() + " "
+ connectedPathsListWhite.get(i).get(j).getYHexCoord());
}
System.out.println();
}
boolean containsLeft;
boolean containsRight;
for (int i = 0; i < connectedPathsListWhite.size(); i++) {
containsLeft = containsRight = false;
for (int j = 0; j < connectedPathsListWhite.get(i).size(); j++) {
if (connectedPathsListWhite.get(i).get(j).getXHexCoord() == 0)
containsLeft = true;
if (connectedPathsListWhite.get(i).get(j).getXHexCoord() == hexGrid.getTilesPerRow() - 1)
containsRight = true;
}
if (containsLeft && containsRight) {
System.out.println("White has won");
gameEnded = true;
}
}
}
if (tile.getStonePlaced() == 1) {
for (int i = 0; i < connectedPathsListBlack.size(); i++) {
for (int j = 0; j < adjacentTiles.size(); j++) {
if (connectedPathsListBlack.get(i).contains(adjacentTiles.get(j))) {
tempPath.addAll(connectedPathsListBlack.get(i));
tempPath.addAll(adjacentTiles);
connectedPathsListBlack.get(i).clear();
preexistingPath = true;
if (connectedPathsListBlack.size() <= i)
break;
}
}
}
connectedPathsListBlack.removeIf(p -> p.isEmpty());
if (preexistingPath == false) {
connectedPathsListBlack.add(adjacentTiles);
} else {
ArrayList<Tile> tempPathDuplicatesRemoved = new ArrayList<Tile>();
for (int i = 0; i < tempPath.size(); i++) {
if (!tempPathDuplicatesRemoved.contains(tempPath.get(i)))
tempPathDuplicatesRemoved.add(tempPath.get(i));
}
connectedPathsListBlack.add(tempPathDuplicatesRemoved);
}
System.out.println("All (Black) connected paths:");
for (int i = 0; i < connectedPathsListBlack.size(); i++) {
for (int j = 0; j < connectedPathsListBlack.get(i).size(); j++) {
System.out.println(connectedPathsListBlack.get(i).get(j).getXHexCoord() + " "
+ connectedPathsListBlack.get(i).get(j).getYHexCoord());
}
System.out.println();
}
boolean containsTop;
boolean containsBottom;
for (int i = 0; i < connectedPathsListBlack.size(); i++) {
containsTop = containsBottom = false;
for (int j = 0; j < connectedPathsListBlack.get(i).size(); j++) {
if (connectedPathsListBlack.get(i).get(j).getYHexCoord() == 0)
containsTop = true;
if (connectedPathsListBlack.get(i).get(j).getYHexCoord() == hexGrid.getRowCount() - 1)
containsBottom = true;
}
if (containsTop && containsBottom) {
System.out.println("Black has won");
gameEnded = true;
}
}
}
}
}
| 35.083333 | 112 | 0.66439 |
92712d5c38c630fada37fac997ac61a70e8acb68 | 1,004 | package com.ronguan.activity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.WindowManager;
import com.ronguan.R;
/**
* 加载页面
*
* @author zhou
*
*/
public class LoadingActivity extends Activity {
private static final int DELAYMILLIS = 500;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_loading);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);// 去掉系统的标题栏
Intent service = new Intent();
// Intent.setClass(LoadingActivity.this, ShengCaiService.class);
startService(service);
// 默认显示.5s 然后跳转到广告页面
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Intent intent = new Intent();
intent.setClass(LoadingActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
}, DELAYMILLIS);
}
}
| 23.348837 | 122 | 0.74502 |
47a3b9a5543d9ed73628f3b907aaa94d40f232c8 | 2,550 | /**
* 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.pulsar.broker.admin;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertTrue;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
import lombok.extern.slf4j.Slf4j;
import org.apache.pulsar.broker.MultiBrokerBaseTest;
import org.apache.pulsar.broker.PulsarService;
import org.apache.pulsar.broker.loadbalance.LeaderBroker;
import org.apache.pulsar.client.admin.PulsarAdmin;
import org.apache.pulsar.client.admin.PulsarAdminException;
import org.testng.annotations.Test;
/**
* Test multi-broker admin api.
*/
@Slf4j
@Test(groups = "broker-admin")
public class AdminApiMultiBrokersTest extends MultiBrokerBaseTest {
@Override
protected int numberOfAdditionalBrokers() {
return 3;
}
@Override
protected void doInitConf() throws Exception {
super.doInitConf();
}
@Override
protected void onCleanup() {
super.onCleanup();
}
@Test(timeOut = 30 * 1000)
public void testGetLeaderBroker()
throws ExecutionException, InterruptedException, PulsarAdminException {
List<PulsarService> allBrokers = getAllBrokers();
Optional<LeaderBroker> leaderBroker =
allBrokers.get(0).getLeaderElectionService().readCurrentLeader().get();
assertTrue(leaderBroker.isPresent());
log.info("Leader broker is {}", leaderBroker);
for (PulsarAdmin admin : getAllAdmins()) {
String serviceUrl = admin.brokers().getLeaderBroker().getServiceUrl();
log.info("Pulsar admin get leader broker is {}", serviceUrl);
assertEquals(leaderBroker.get().getServiceUrl(), serviceUrl);
}
}
}
| 35.416667 | 87 | 0.72549 |
1436fa03f7a2dd2f4338e535aa989d0dd071b2ba | 1,770 | package com.rockwellcollins.atc.resolute.analysis.views;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.Viewer;
import com.rockwellcollins.atc.resolute.analysis.results.ClaimResult;
import com.rockwellcollins.atc.resolute.analysis.results.FailResult;
import com.rockwellcollins.atc.resolute.analysis.results.ResoluteResult;
public class ResoluteResultContentProvider implements ITreeContentProvider {
@Override
public void dispose() {
}
@Override
public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
}
@Override
public Object[] getElements(Object inputElement) {
@SuppressWarnings("rawtypes")
List roots = (List) inputElement;
return roots.toArray();
}
@Override
public Object[] getChildren(Object parentElement) {
if (parentElement instanceof ResoluteResult) {
ResoluteResult node = (ResoluteResult) parentElement;
return flatten(node.getChildren()).toArray();
} else {
throw new IllegalArgumentException();
}
}
private List<ResoluteResult> flatten(List<ResoluteResult> children) {
List<ResoluteResult> results = new ArrayList<ResoluteResult>();
for (ResoluteResult child : children) {
if (child instanceof ClaimResult || child instanceof FailResult) {
results.add(child);
} else {
results.addAll(flatten(child.getChildren()));
}
}
return results;
}
@Override
public Object getParent(Object element) {
return null;
}
@Override
public boolean hasChildren(Object element) {
if (element instanceof ResoluteResult) {
ResoluteResult node = (ResoluteResult) element;
return !flatten(node.getChildren()).isEmpty();
} else {
throw new IllegalArgumentException();
}
}
}
| 26.818182 | 76 | 0.758757 |
28664b57b5d98b8abe0b94a7cf8ed6aead3b0a5c | 4,103 | package com.github.mauricioaniche.ck.metric;
import com.github.mauricioaniche.ck.CKClassResult;
import com.github.mauricioaniche.ck.CKMethodResult;
import java.util.*;
import java.util.stream.Collectors;
//we ignore invocations in the super class, because they are always outside the current class and can never return
@RunAfter(metrics={RFC.class, MethodLevelFieldUsageCount.class})
public class MethodInvocationsLocal implements CKASTVisitor, ClassLevelMetric {
//Recursively extract all method invocations starting with the given method
//Explored contains all previously explored invocations
//Invocations contains all direct method invocations of interest
//The algorithm is a depth first search
private Map<String, Set<String>> invocations(String invokedMethod, Map<String, Set<String>> explored, HashMap<String, Set<String>> invocations){
//only explore local method invocations that were not previously explored
Set<String> exploredKeys = explored.keySet();
Set<String> nextInvocations = invocations.get(invokedMethod).stream()
.filter(invoked -> !exploredKeys.contains(invoked) && !invoked.equals(invokedMethod))
.collect(Collectors.toSet());
if(nextInvocations.size() > 0){
explored.put(invokedMethod, nextInvocations);
for (String nextInvocation : nextInvocations){
explored = invocations(nextInvocation, explored, invocations);
}
}
//Stops when all invocations are explored: there are no more invocations to be explored
return explored;
}
//Generate an indirect method invocations map
//Method contains all methods of interest
//Invocations contains all indirect method invocations of interest with the calling method
private HashMap<String, Map<String, Set<String>>> invocationsIndirect(Set<CKMethodResult> methods, HashMap<String, Set<String>> methodInvocationsLocal){
HashMap<String, Map<String, Set<String>>> methodInvocationsIndirectLocal = new HashMap<>();
//extract all indirect local invocations for all methods in the current class
for (CKMethodResult method : methods){
//extract all local invocations for the current method
Map<String, Set<String>> localInvocations = invocations(method.getQualifiedMethodName(), new HashMap(), methodInvocationsLocal);
methodInvocationsIndirectLocal.put(method.getQualifiedMethodName(), localInvocations);
}
return methodInvocationsIndirectLocal;
}
//Extract all local(inner-class) method invocations and save them in a HashMap
private HashMap<String, Set<String>> extractLocalInvocations(Set<CKMethodResult> methods){
HashMap<String, Set<String>> methodInvocationsLocal = new HashMap<>();
Set<String> methodNames = methods.stream().map(CKMethodResult::getQualifiedMethodName).collect(Collectors.toSet());
for (CKMethodResult method : methods){
Set<String> invokedLocal = method.getMethodInvocations().stream()
.filter(methodNames::contains)
.collect(Collectors.toSet());
methodInvocationsLocal.put(method.getQualifiedMethodName(), invokedLocal);
}
return methodInvocationsLocal;
}
public void setResult(CKClassResult result) {
//extract all direct local invocations for all methods in the current class
Set<CKMethodResult> methods = result.getMethods();
HashMap<String, Set<String>> methodInvocationsLocal = extractLocalInvocations(methods);
for (CKMethodResult method : methods){
method.setMethodInvocationLocal(methodInvocationsLocal.get(method.getQualifiedMethodName()));
}
HashMap<String, Map<String, Set<String>>> methodInvocationsIndirectLocal = invocationsIndirect(methods, methodInvocationsLocal);
for (CKMethodResult method : methods){
method.setMethodInvocationsIndirectLocal(methodInvocationsIndirectLocal.get(method.getQualifiedMethodName()));
}
}
} | 54.706667 | 156 | 0.720692 |
6d88443dc9dcf7ba04f29f2955b16de186391988 | 474 | package com.jerry.spel;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestSpel {
@Test
public void demo()
{
String xmlPath="com/jerry/spel/bean.xml";
ApplicationContext applicationContext=new ClassPathXmlApplicationContext(xmlPath);
Customer customer=(Customer) applicationContext.getBean("customerId");
System.out.println(customer);
}
}
| 26.333333 | 84 | 0.805907 |
12b1cda89c0a58f808d0ab2d2aaa058a7179d63b | 825 | package com.gisquest.webgis.modules.sys.entity;
/**
* 日志对象
*
* @author Jisj1
*
*/
public class Log {
/** 操作用户Id */
private String userId;
/** 操作行为 */
private String action;
/** 操作信息 */
private String info;
/** 操作时间 */
private String date;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
| 15.865385 | 47 | 0.551515 |
52adef7b51828104415144d13d092b7b2e32014c | 3,332 | package models;
import com.avaje.ebean.Model;
import com.avaje.ebean.annotation.DbJsonB;
import com.fasterxml.jackson.databind.JsonNode;
import io.swagger.annotations.ApiModelProperty;
import play.libs.Json;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* Created by arkady on 15/02/16.
*/
@Entity
@Table(name = "venue")
public class Venue extends Model {
public Venue() {
}
public Venue(Long id) {
this.id = id;
}
@Id
private Long id;
@ApiModelProperty(required = true)
private String name;
@ApiModelProperty(required = true)
private String address;
private String placeId;
private String coverUrl;
private String logoUrl;
@ApiModelProperty(required = true)
private Integer capacity;
@Column(columnDefinition = "varchar(32)", nullable = false)
private String timeZone;
@DbJsonB
private JsonNode tags;
@Transient
@ApiModelProperty(readOnly = true)
@Enumerated(EnumType.STRING)
private VenueRequestStatus requestStatus;
@Transient
@ApiModelProperty(readOnly = true)
@Enumerated(EnumType.STRING)
private List<VenueRole> preferredRoles;
@Enumerated(EnumType.STRING)
@Column(nullable = false)
private VenueType venueType = VenueType.VENUE;
@Transient
private int unreadNotifications;
public static Finder<Long, Venue> finder = new Finder<>(Venue.class);
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCoverUrl() {
return coverUrl;
}
public void setCoverUrl(String coverUrl) {
this.coverUrl = coverUrl;
}
public String getLogoUrl() {
return logoUrl;
}
public void setLogoUrl(String logoUrl) {
this.logoUrl = logoUrl;
}
public Integer getCapacity() {
return capacity;
}
public void setCapacity(Integer capacity) {
this.capacity = capacity;
}
public VenueRequestStatus getRequestStatus() {
return requestStatus;
}
public void setRequestStatus(VenueRequestStatus requestStatus) {
this.requestStatus = requestStatus;
}
public List<VenueRole> getPreferredRoles() {
return preferredRoles;
}
public void setPreferredRoles(List<VenueRole> preferredRoles) {
this.preferredRoles = preferredRoles;
}
public String getTimeZone() {
return timeZone;
}
public void setTimeZone(String timeZone) {
this.timeZone = timeZone;
}
public String getPlaceId() {
return placeId;
}
public void setPlaceId(String placeId) {
this.placeId = placeId;
}
public List<String> getTags() {
if (tags != null) {
final List<String> tagList = Arrays.asList(Json.fromJson(tags, String[].class));
return new ArrayList<>(tagList);
} else {
return new ArrayList<>();
}
}
public void setTags(List<String> tags) {
this.tags = Json.toJson(tags);
}
public VenueType getVenueType() {
return venueType;
}
public void setVenueType(VenueType venueType) {
this.venueType = venueType;
}
public int getUnreadNotifications() {
return unreadNotifications;
}
public void setUnreadNotifications(int unreadNotifications) {
this.unreadNotifications = unreadNotifications;
}
}
| 18.511111 | 83 | 0.730492 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.