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 |
|---|---|---|---|---|---|
ec515a464bfaddbb5571d086d9dc5cca9ab597c1 | 564 | package com.salvatore.cinemates.utils;
public final class MovieSearchHttpClientConstants {
public static final String HTTPCLIENT_HEADERS_AUTHORIZATION = "Authorization ";
public static final String HTTPCLIENT_HEADERS_AUTHORIZATION_BEARER = "Bearer ";
public static final String HTTPCLIENT_REQUEST_LANGUAGE_FIELD = "language";
public static final String HTTPCLIENT_REQUEST_QUERY_FIELD = "query";
public static final String HTTPCLIENT_REQUEST_LANGUAGE_FIELD_VALUE_ITALIAN = "it-IT";
private MovieSearchHttpClientConstants() {}
}
| 47 | 90 | 0.794326 |
676917deb2f73472c9b1cc33ad42cca4ada9e0d4 | 3,661 | package be.kdg.simulator.domain.generators.impl;
import be.kdg.simulator.commands.SimulatorCommandContext;
import be.kdg.simulator.config.sensorservice.SensorGenerationProperties;
import be.kdg.simulator.domain.generators.ParameterGenerator;
import be.kdg.simulator.domain.model.sensor.Sensor;
import be.kdg.simulator.domain.model.util.CoordRange;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
/**
* Generator class to generate parameters for sensor simulation based on given properties
*/
@Component
public class SensorParameterGenerator implements ParameterGenerator {
private static final Logger LOGGER = LoggerFactory.getLogger(SensorParameterGenerator.class);
private final SensorGenerationProperties properties;
private SimulatorCommandContext ctx;
private long currentCycle;
private long numberOfCycles;
@Autowired
public SensorParameterGenerator(SensorGenerationProperties properties) {
this.properties = properties;
}
@Override
public void initialize() {
numberOfCycles = TimeUnit.MINUTES.toMillis(properties.getTimeSpanInMinutes()) / properties.getAvgDelayInMs();
currentCycle = 0;
}
@Override
public void setContext(SimulatorCommandContext ctx) {
this.ctx = ctx;
}
@Override
public boolean hasNext() {
return currentCycle < numberOfCycles;
}
@Override
public SimulatorCommandContext generateNext() {
ctx.setDelay(getRandomDelay());
ctx.setTimeStamp(getRandomTimeStamp(properties.getAvgDelayInMs(), properties.getDelayVariance()));
ctx.setXCoord(getRandomCoord(properties.getXCoordRange()));
ctx.setYCoord(getRandomCoord(properties.getYCoordRange()));
Sensor sensorWithValue = getRandomSensor(properties.getSensors());
ctx.setSensorType(sensorWithValue.getSensorType());
ctx.setSensorValue(sensorWithValue.getValue());
currentCycle++;
LOGGER.info(String.format("Generated parameters for %d of %d sensors", currentCycle, numberOfCycles));
return ctx;
}
//#region Generation methods
private long getRandomDelay() {
return Math.round(
getRandomValueWithBoundaries(
properties.getAvgDelayInMs() - properties.getDelayVariance(),
properties.getAvgDelayInMs() + properties.getDelayVariance()
)
);
}
private LocalDateTime getRandomTimeStamp(int avgDelay, int avgVariance) {
final long minutesToRetract = currentCycle * (avgDelay + avgVariance);
return LocalDateTime.now().minusMinutes(minutesToRetract);
}
private double getRandomCoord(CoordRange coordRange) {
return getRandomValueWithBoundaries(
coordRange.getMinValue(),
coordRange.getMaxValue()
);
}
private Sensor getRandomSensor(List<Sensor> sensors) {
final int randomIndex = new Random().nextInt(sensors.size());
final Sensor sensor = sensors.get(randomIndex);
final double value = getRandomValueWithBoundaries(
sensor.getMinValue(),
sensor.getMaxValue()
);
sensor.setValue(value);
return sensor;
}
//#endregion
//#region Helper methods
private double getRandomValueWithBoundaries(double min, double max) {
return min + (max - min) * new Random().nextDouble();
}
//#endregion
}
| 34.214953 | 117 | 0.712101 |
ee68b850a75559e897c99be2236b323621085ef6 | 1,549 | package io.spoud.agoora.agents.test.mock;
import io.spoud.agoora.agents.api.client.DataItemClient;
import io.spoud.sdm.global.domain.v1.IdReference;
import io.spoud.sdm.logistics.domain.v1.DataItem;
import io.spoud.sdm.logistics.service.v1.DataItemChange;
import io.spoud.sdm.logistics.service.v1.SaveDataItemRequest;
import lombok.experimental.UtilityClass;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.when;
@UtilityClass
public class DataItemClientMockProvider {
public static Map<String, UUID> uuidByTransportUrl = new HashMap<>();
public static void defaultMock(DataItemClient mock) {
reset(mock);
when(mock.save(any()))
.thenAnswer(
a -> {
SaveDataItemRequest request = a.getArgument(0, SaveDataItemRequest.class);
DataItemChange input = request.getInput();
final UUID uuid = UUID.randomUUID();
uuidByTransportUrl.put(input.getTransportUrl().getValue(), uuid);
return DataItem.newBuilder()
.setId(uuid.toString())
.setName(input.getName().getValue())
.setLabel(input.getLabel().getValue())
.setDataPort(
IdReference.newBuilder()
.setId(input.getDataPortRef().getIdPath().getId())
.build())
.build();
});
}
}
| 35.204545 | 88 | 0.646223 |
3ba6c946f68fc87b2ca6d6deb5e8b163b2de8029 | 619 | package soya.framework.tool.ant;
import org.apache.tools.ant.Task;
import java.lang.reflect.ParameterizedType;
public abstract class AntTask<T extends Task> {
protected T task;
public AntTask() {
try {
Class<T> type = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass())
.getActualTypeArguments()[0];
task = type.newInstance();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
protected abstract void init();
protected Void invoke() {
task.execute();
return null;
}
}
| 22.107143 | 94 | 0.594507 |
a6dfefa542c89bfc49b3cb012d3a1036a5210a85 | 377 | package tools.datasync.utils;
import java.util.concurrent.TimeUnit;
public class TimeSpan {
private long duration;
private TimeUnit unit;
public TimeSpan(long duration, TimeUnit unit) {
super();
this.duration = duration;
this.unit = unit;
}
public long getDuration() {
return duration;
}
public TimeUnit getUnit() {
return unit;
}
}
| 15.08 | 51 | 0.676393 |
3ca4a0eccf7beda06b3afd598b361132aab1a9ba | 3,808 | package openblocks.common.block;
import java.util.Random;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.PropertyBool;
import net.minecraft.block.state.BlockFaceShape;
import net.minecraft.block.state.BlockStateContainer;
import net.minecraft.block.state.IBlockState;
import net.minecraft.util.EnumBlockRenderType;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import openmods.block.OpenBlock;
import openmods.infobook.BookDocumentation;
@BookDocumentation(customName = "sky.normal")
public class BlockSky extends OpenBlock {
private static final int MASK_INVERTED = 1 << 0;
private static final int MASK_POWERED = 1 << 1;
private static final AxisAlignedBB EMPTY = new AxisAlignedBB(0, 0, 0, 0, 0, 0);
public static final PropertyBool INVERTED = PropertyBool.create("inverted");
public static final PropertyBool POWERED = PropertyBool.create("powered");
public static boolean isInverted(int meta) {
return (meta & MASK_INVERTED) != 0;
}
public BlockSky() {
super(Material.IRON);
setDefaultState(getDefaultState().withProperty(POWERED, false));
setRequiresInitialization(true);
}
@Override
protected BlockStateContainer createBlockState() {
return new BlockStateContainer(this, getPropertyOrientation(), INVERTED, POWERED);
}
@Override
public IBlockState getStateFromMeta(int meta) {
return getDefaultState()
.withProperty(POWERED, (meta & MASK_POWERED) != 0)
.withProperty(INVERTED, (meta & MASK_INVERTED) != 0);
}
@Override
public int getMetaFromState(IBlockState state) {
final int isPowered = state.getValue(POWERED)? MASK_POWERED : 0;
final int isInverted = state.getValue(INVERTED)? MASK_INVERTED : 0;
return isPowered | isInverted;
}
@Override
public int damageDropped(IBlockState state) {
return getMetaFromState(state) & MASK_INVERTED;
}
@Override
public void neighborChanged(IBlockState state, World world, BlockPos blockPos, Block neighbour, BlockPos neigbourPos) {
updatePowerState(state, world, blockPos);
super.neighborChanged(state, world, blockPos, neighbour, neigbourPos);
}
@Override
protected boolean onBlockAddedNextTick(World world, BlockPos blockPos, IBlockState state) {
updatePowerState(state, world, blockPos);
return super.onBlockAddedNextTick(world, blockPos, state);
}
private void updatePowerState(IBlockState state, World world, BlockPos pos) {
if (!world.isRemote) {
final boolean isPowered = world.isBlockIndirectlyGettingPowered(pos) > 0;
final boolean isActive = state.getValue(POWERED);
if (isPowered != isActive) world.scheduleUpdate(pos, this, 1);
}
}
@Override
public void updateTick(World world, BlockPos pos, IBlockState state, Random random) {
final boolean isPowered = world.isBlockIndirectlyGettingPowered(pos) > 0;
world.setBlockState(pos, state.withProperty(POWERED, isPowered));
}
public static boolean isActive(IBlockState state) {
boolean isPowered = state.getValue(POWERED);
boolean isInverted = state.getValue(INVERTED);
return isPowered ^ isInverted;
}
@Override
@SuppressWarnings("deprecation")
public AxisAlignedBB getSelectedBoundingBox(IBlockState state, World world, BlockPos pos) {
return isActive(state)? EMPTY : super.getSelectedBoundingBox(state, world, pos);
}
@Override
public EnumBlockRenderType getRenderType(IBlockState state) {
return isActive(state)? EnumBlockRenderType.ENTITYBLOCK_ANIMATED : EnumBlockRenderType.MODEL;
}
@Override
public BlockFaceShape getBlockFaceShape(IBlockAccess worldIn, IBlockState state, BlockPos pos, EnumFacing face) {
return BlockFaceShape.UNDEFINED;
}
}
| 32.827586 | 120 | 0.780725 |
7aee09d21802fdb1157a2874cb53987c32f6c9fd | 803 | class Solution {
public int mctFromLeafValues(int[] arr) {
final int n = arr.length;
// dp[i][j] := min cost of arr[i..j]
int[][] dp = new int[n][n];
// maxVal[i][j] := max value of arr[i..j]
int[][] maxVal = new int[n][n];
for (int i = 0; i < n; ++i)
maxVal[i][i] = arr[i];
for (int d = 1; d < n; ++d)
for (int i = 0; i + d < n; ++i) {
final int j = i + d;
maxVal[i][j] = Math.max(maxVal[i][j - 1], maxVal[i + 1][j]);
}
for (int d = 1; d < n; ++d)
for (int i = 0; i + d < n; ++i) {
final int j = i + d;
dp[i][j] = Integer.MAX_VALUE;
for (int k = i; k < j; ++k)
dp[i][j] = Math.min(dp[i][j], dp[i][k] + dp[k + 1][j] + maxVal[i][k] * maxVal[k + 1][j]);
}
return dp[0][n - 1];
}
}
| 27.689655 | 99 | 0.424658 |
13c5c21c8d63272a00d4fd76af754d3db12c052b | 5,203 | package Reacher;
import Reacher.domain.INode;
import Reacher.domain.Node;
import Reacher.domain.exceptions.NodeNotFoundException;
import com.google.common.collect.ImmutableList;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
public class GraphTest {
List<Node> testNodes;
Graph testGraph;
@BeforeEach
public void setup() {
testNodes = ImmutableList.of(
new Node(1),
new Node(2),
new Node(3),
new Node(4),
new Node(5)
);
var builder = new GraphBuilder();
testNodes.forEach(builder::addNode);
builder.addEdge(1, 2);
builder.addEdge(2, 3);
builder.addEdge(1, 4);
builder.addEdge(3, 5);
builder.addEdge(4, 5);
testGraph = builder.build();
}
@Test
public void testGetDescendantsHappyPath() {
List<INode> descendants = testGraph.getDescendants(2);
List<INode> expected = ImmutableList.of(
testNodes.get(2),
testNodes.get(4)
);
assertEquals(expected, descendants);
}
@Test
public void testGetDescendantsDedupesNodesWhenDescendantViaMultiplePaths() {
List<INode> descendants = testGraph.getDescendants(1);
List<INode> expected = ImmutableList.of(
testNodes.get(1),
testNodes.get(2),
testNodes.get(3),
testNodes.get(4)
);
assertEquals(expected, descendants);
}
@Test
public void testGetDescendantsReturnsEmptyWhenNodeIsALeaf() {
assertTrue(testGraph.getDescendants(5).isEmpty());
}
@Test
public void testGetDescendantsThrowsNotFoundExceptionWhenNodeWithIdDNE() {
NodeNotFoundException exception = assertThrows(NodeNotFoundException.class, () -> testGraph.getAncestors(1000));
assertEquals("Node was not found with the given id: 1000", exception.getMessage());
assertEquals(1000, exception.getNodeId());
}
@Test
public void testDoesPathExistHappyPath() {
assertTrue(testGraph.doesPathExist(1, 5));
assertTrue(testGraph.doesPathExist(1, 2));
assertTrue(testGraph.doesPathExist(1, 4));
assertFalse(testGraph.doesPathExist(5, 1));
assertFalse(testGraph.doesPathExist(4, 3));
assertFalse(testGraph.doesPathExist(3, 4));
}
@Test
public void testDoesPathExistThrowsNotFoundExceptionWhenNodeWithIdDNE() {
NodeNotFoundException exception = assertThrows(NodeNotFoundException.class, () -> testGraph.doesPathExist(1000, 1000));
assertEquals("Node was not found with the given id: 1000", exception.getMessage());
assertEquals(1000, exception.getNodeId());
}
@Test
public void testGetAncestorsThrowsNotFoundExceptionWhenNodeWithIdDNE() {
NodeNotFoundException exception = assertThrows(NodeNotFoundException.class, () -> testGraph.getAncestors(1000));
assertEquals("Node was not found with the given id: 1000", exception.getMessage());
assertEquals(1000, exception.getNodeId());
}
@Test
public void testGetAncestorsThrowsNotFoundExceptionWhenNodePreviouslyExisted() {
testGraph.removeNode(5);
NodeNotFoundException exception = assertThrows(NodeNotFoundException.class, () -> testGraph.getAncestors(5));
assertEquals("Node was not found with the given id: 5", exception.getMessage());
assertEquals(5, exception.getNodeId());
}
@Test
public void testGetAncestorsReturnsCorrectlyHappyPath() {
List<INode> ancestors = testGraph.getAncestors(3);
List<INode> expected = ImmutableList.of(
testNodes.get(0),
testNodes.get(1)
);
assertEquals(expected, ancestors);
}
@Test
public void testGetAncestorsDedupesWhenNodeIsAncestorViaMultiplePaths() {
List<INode> ancestors = testGraph.getAncestors(5);
List<INode> expected = ImmutableList.of(
testNodes.get(0),
testNodes.get(1),
testNodes.get(2),
testNodes.get(3)
);
assertEquals(expected, ancestors);
}
@Test
public void testGetAncestorsReturnsEmptyWhenIdBelongsToRoot() {
assertTrue(testGraph.getAncestors(1).isEmpty());
}
@Test
public void testRemoveNodeRemovesNodeAndEdgesFromGraphCorrectly() {
var builder = new GraphBuilder();
// add every node except E
testNodes.subList(0, testNodes.size() - 1).forEach(builder::addNode);
builder.addEdge(1, 2);
builder.addEdge(2, 3);
builder.addEdge(1, 4);
var expectedGraph = builder.build();
testGraph.removeNode(5);
assertEquals(expectedGraph, testGraph);
}
@Test
public void testRemoveNodeThrowsNotFoundExceptionWhenNodeWithIdDNE() {
NodeNotFoundException exception = assertThrows(NodeNotFoundException.class, () -> testGraph.removeNode(1000));
assertEquals("Node was not found with the given id: 1000", exception.getMessage());
assertEquals(1000, exception.getNodeId());
}
@Test
public void testRemoveNodeThrowsExceptionWhenNodeIsNotALeaf() {
// TODO
}
@Test
public void testAddEdgeHappyPath() {
var expectedGraph = testGraph.toBuilder()
.addEdge(2, 4)
.build();
assertFalse(testGraph.doesPathExist(2, 4));
// check B is not an ancestor of E
assertFalse(testGraph.getAncestors(4).stream().map(INode::getId).anyMatch(id -> id == 2));
testGraph.addEdge(2, 4);
assertTrue(testGraph.doesPathExist(2, 4));
assertTrue(testGraph.getAncestors(4).stream().map(INode::getId).anyMatch(id -> id == 2));
assertEquals(expectedGraph, testGraph);
}
}
| 26.958549 | 121 | 0.743417 |
d86a0555f74317fbaa24c575b6b4a8461ee9fc1b | 1,801 | /*
* Copyright (C) 2019 GFZ German Research Centre for Geosciences
*
* 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://apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the Licence is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and
* limitations under the Licence.
*/
package org.n52.gfz.riesgos.processdescription;
import org.n52.wps.io.data.IData;
import org.n52.wps.webapp.api.FormatEntry;
import java.util.List;
import java.util.Optional;
/**
* Interface for a output element for the process description
* generation.
*/
public interface IProcessDescriptionGeneratorOutputData {
/**
* Identifier of the output.
* @return identifier of the output
*/
String getIdentifier();
/**
* Binding class of the output.
* @return binding class of the output
*/
Class<? extends IData> getBindingClass();
/**
* Optional list with supported crs.
* @return optional list with supported crs
*/
Optional<List<String>> getSupportedCrs();
/**
* Optional default format.
* @return optional default format
*/
Optional<FormatEntry> getDefaultFormat();
/**
* True if the output is optional.
* @return true of the output is optional
*/
boolean isOptional();
/**
* Optional text with the abstract for the identifier.
* @return optional text with the abstrac for the identifier
*/
Optional<String> getAbstract();
}
| 26.101449 | 75 | 0.686841 |
af3ac181c01972a17760074b543446ed28a84b1c | 3,306 | package com.eiffel.codeInsight.completion;
import com.eiffel.psi.EiffelClassDeclaration;
import com.eiffel.psi.EiffelClassUtil;
import com.eiffel.psi.EiffelNewFeature;
import com.intellij.codeInsight.completion.CompletionParameters;
import com.intellij.codeInsight.completion.CompletionResultSet;
import com.intellij.codeInsight.completion.PrioritizedLookupElement;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.codeInsight.lookup.LookupElementPresentation;
import com.intellij.codeInsight.lookup.LookupElementRenderer;
import com.intellij.icons.AllIcons;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import com.intellij.util.ProcessingContext;
import java.util.Map;
public abstract class EiffelCompletionUtilBase {
abstract void addCompletions(CompletionParameters parameters, ProcessingContext context, CompletionResultSet result);
protected void addFeatureNamesForClassInContext(Project project, String className, String context, CompletionResultSet result) {
EiffelClassDeclaration classDeclaration = EiffelClassUtil.findClassDeclaration(project, className);
if (classDeclaration == null) return;
Map<EiffelNewFeature, Integer> newFeatures = classDeclaration.getAllNewFeaturesInContextWithDepth(context);
for (EiffelNewFeature newFeature : newFeatures.keySet()) {
final String formalArguments = newFeature.getSerializedFormalArguments();
final String returnType = newFeature.getTypeString();
final int priority = newFeatures.get(newFeature);
final String name = newFeature.getName();
final String doc = newFeature.getCommentDoc();
LookupElement lookupElement = LookupElementBuilder
.create(name + (formalArguments == null ? "" : "("))
.withRenderer(new LookupElementRenderer<LookupElement>() {
@Override
public void renderElement(LookupElement element, LookupElementPresentation presentation) {
presentation.setIcon(AllIcons.Nodes.Function);
presentation.setItemText(EiffelClassUtil.formalizeName(name));
if (priority == 0) {
presentation.setItemTextBold(true);
}
presentation.setTailText(
(formalArguments == null ? "" : EiffelClassUtil.formalizeName(formalArguments)) +
(doc == null ? "" : " " + doc)
);
presentation.setTypeText(returnType);
}
});
result.addElement(PrioritizedLookupElement.withPriority(
lookupElement, EiffelCompletionPriorities.THRESHOLD - priority
));
}
}
protected void addFeatureNamesForClassInContext(Project project, String className, PsiElement contextElement, CompletionResultSet result) {
addFeatureNamesForClassInContext(project, className, EiffelClassUtil.findClassDeclaration(contextElement).getName(), result);
}
}
| 55.1 | 143 | 0.678161 |
7617deb5035e3b76f789414a1065e1ca8470d15c | 685 | package io.dropwizard.configuration;
import java.io.InputStream;
import java.io.IOException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
/**
* An implementation of {@link ConfigurationSourceProvider} that reads the configuration from the
* local file system.
*/
public class FileConfigurationSourceProvider implements ConfigurationSourceProvider {
@Override
public InputStream open(String path) throws IOException {
final File file = new File(path);
if (!file.exists()) {
throw new FileNotFoundException("File " + file + " not found");
}
return new FileInputStream(file);
}
}
| 28.541667 | 97 | 0.721168 |
cdb5cbae6bc181ad056c140bfff0656f26d21cde | 920 | package org.cyclops.commoncapabilities.modcompat.forestry.capability.work;
import forestry.api.core.IErrorState;
import forestry.core.errors.EnumErrorCode;
import forestry.factory.tiles.TileMoistener;
import org.cyclops.commoncapabilities.api.capability.work.IWorker;
/**
* Worker capability for the TileMoistener.
* @author rubensworks
*/
public class TileMoistenerWorker implements IWorker {
private final TileMoistener tile;
public TileMoistenerWorker(TileMoistener tile) {
this.tile = tile;
}
@Override
public boolean hasWork() {
return doesNotHaveError(EnumErrorCode.NO_RECIPE);
}
protected boolean doesNotHaveError(IErrorState error) {
return !tile.getErrorLogic().contains(error);
}
@Override
public boolean canWork() {
return doesNotHaveError(EnumErrorCode.NOT_DARK) && doesNotHaveError(EnumErrorCode.NO_RESOURCE_LIQUID);
}
}
| 27.058824 | 110 | 0.747826 |
3c85b2f19d8f261e52ce321432a7ce2e53e4c9cc | 3,213 | package com.carros.api;
import com.carros.api.domain.Carro;
import com.carros.api.domain.dto.CarroDTO;
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.boot.test.web.client.TestRestTemplate;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
/**
* Testando API como umtodo
* status, valores, chamadas , retornos
*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = CarrosApplication.class,webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class CarrosAPITest {
@Autowired
protected TestRestTemplate rest;
private ResponseEntity<CarroDTO> getCarro(String url){
return rest.getForEntity(url,CarroDTO.class);
}
private ResponseEntity<List<CarroDTO>> getCarros(String url){
return rest.exchange(url, HttpMethod.GET, null, new ParameterizedTypeReference<List<CarroDTO>>(){
});
}
@Test
public void testList() {
List<CarroDTO> carros = getCarros("/api/v1/carros").getBody();
assertEquals(30,carros.size());
}
@Test
public void testGetNotContent() {
ResponseEntity response = getCarro("/api/v1/carros/111");
assertEquals(response.getStatusCode(),HttpStatus.NOT_FOUND);
}
@Test
public void testListaporTipo(){
assertEquals(10,getCarros("/api/v1/carros/tipo/classicos").getBody().size());
assertEquals(10,getCarros("/api/v1/carros/tipo/esportivos").getBody().size());
assertEquals(10,getCarros("/api/v1/carros/tipo/luxo").getBody().size());
assertEquals(HttpStatus.NO_CONTENT,getCarros("/api/v1/carros/tipo/xxx").getStatusCode());
}
@Test
public void testGeOk(){
ResponseEntity<CarroDTO> response = getCarro("/api/v1/carros/11");
assertEquals(response.getStatusCode(),HttpStatus.OK);
CarroDTO c = response.getBody();
assertEquals("Ferrari FF",c.getNome());
}
@Test
public void testSave(){
// object
Carro carro = new Carro();
carro.setNome("Porshe");
carro.setTipo("Esportivo");
//insert
ResponseEntity response = rest.postForEntity("/api/v1/carros",carro,null);
System.out.println(response);
// verificando se criou
assertEquals(HttpStatus.CREATED,response.getStatusCode());
// Buscando Objeto
String location = response.getHeaders().get("location").get(0);
CarroDTO c = getCarro(location).getBody();
assertNotNull(c);
assertEquals("Porshe",c.getNome());
assertEquals("Esportivo",c.getTipo());
//deletar objeto
rest.delete(location);
// Verificar se deletou
assertEquals(HttpStatus.NOT_FOUND,getCarros(location).getStatusCode());
}
}
| 29.477064 | 109 | 0.6953 |
b9e1a8b915b587a0efaaa4228e5643ed31152410 | 276 | package com.dreamworks.musicwanted.network;
/**
* Created by zhang on 2016/4/23.
*/
public class KoalaHttpStatus {
public final int OK = 0;
public final int IO_ERROR = -1;
public final int JSON_PARSE_ERROR = -2;
public final int NET_ERROR = 3;
}
| 23 | 44 | 0.65942 |
015a6feb6f04393f5171bae76b2fc4f6f5e6a832 | 768 | package com.itmuch.cloud.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import com.itmuch.cloud.entity.User;
@RestController
public class MovieController {
@Autowired
private RestTemplate restTemplate;
@Value("${user.userServicePath}")
private String userServicePath;
@GetMapping("/movie/{id}")
public User findById(@PathVariable Long id) {
return this.restTemplate.getForObject(this.userServicePath + id, User.class);
}
}
| 30.72 | 81 | 0.807292 |
904aeea8603dd872ef235b2496cc5ba0a1fc9cd5 | 3,270 | package com.tank.stage;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.utils.viewport.ExtendViewport;
import com.tank.actor.ui.Background;
import com.tank.game.TankInfinity;
import com.tank.utils.Assets;
import com.tank.utils.Constants;
import com.tank.utils.CycleList;
public class Tutorial extends Stage implements InputProcessor {
protected TankInfinity game;
protected Table uiTable;
protected static CycleList<Texture> slides;
private Background tutorial;
private Skin skin = Assets.manager.get(Assets.skin);
public Tutorial(TankInfinity game) {
// super(new ExtendViewport(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()));
super(new ExtendViewport(Constants.DEFAULT_WIDTH, Constants.DEFAULT_HEIGHT));
this.game = game;
slides = new CycleList<Texture>(new Texture[] { Assets.manager.get(Assets.tutorial_1), Assets.manager.get(Assets.tutorial_2),
Assets.manager.get(Assets.tutorial_3), Assets.manager.get(Assets.tutorial_4), Assets.manager.get(Assets.tutorial_5),
Assets.manager.get(Assets.tutorial_6), Assets.manager.get(Assets.tutorial_7), Assets.manager.get(Assets.tutorial_8),
Assets.manager.get(Assets.tutorial_9), Assets.manager.get(Assets.tutorial_10), Assets.manager.get(Assets.tutorial_11) }, 0, true);
tutorial = new Background(slides.getCurrent());
tutorial.setFill(true);
super.addActor(tutorial);
uiTable = new Table();
buildTable();
super.addActor(uiTable);
}
private void buildTable() {
uiTable.setFillParent(true);
uiTable.setDebug(false); // This is optional, but enables debug lines for tables.
uiTable.defaults().width(250).height(100).space(25);
// Add widgets to the table here.
TextButton nextButton = new TextButton("Next", skin, "defaultLight");
TextButton previousButton = new TextButton("Previous", skin, "defaultLight");
TextButton backButton = new TextButton("Back", skin, "defaultLight");
nextButton.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
slides.cycleBy(1);
tutorial.setTexture(slides.getCurrent());
event.stop();
}
});
previousButton.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
slides.cycleBy(-1);
tutorial.setTexture(slides.getCurrent());
event.stop();
}
});
backButton.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
game.setScreen(game.previousScreen);
event.stop();
}
});
uiTable.add(backButton).colspan(2).expand().top().left();
uiTable.row();
uiTable.add(previousButton).expandX().bottom().left();
uiTable.add(nextButton).expandX().bottom().right();
}
public void goToFirstSlide() {
slides.setIndex(0);
tutorial.setTexture(slides.getCurrent());
}
} | 37.586207 | 135 | 0.729052 |
99691efefef9d9f4acd780d6aba7a9b02ffedd3f | 170 | package Matlab.Utils;
public interface IResult
{
// region PROPERTIES:
Object GetValue();
IReport GetReport();
boolean GetIsOk();
// endregion
}
| 11.333333 | 25 | 0.641176 |
6a0439c0426d7eae5164ef57702b4eaf28b2c4f4 | 46,431 | package org.hl7.fhir.dstu2016may.model;
/*-
* #%L
* org.hl7.fhir.dstu2016may
* %%
* Copyright (C) 2014 - 2019 Health Level 7
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
/*
Copyright (c) 2011+, HL7, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
// Generated on Sun, May 8, 2016 03:05+1000 for FHIR v1.4.0
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.hl7.fhir.exceptions.FHIRException;
import ca.uhn.fhir.model.api.annotation.Child;
import ca.uhn.fhir.model.api.annotation.Description;
import ca.uhn.fhir.model.api.annotation.ResourceDef;
import ca.uhn.fhir.model.api.annotation.SearchParamDefinition;
/**
* This resource provides the status of the payment for goods and services rendered, and the request and response resource references.
*/
@ResourceDef(name="PaymentNotice", profile="http://hl7.org/fhir/Profile/PaymentNotice")
public class PaymentNotice extends DomainResource {
/**
* The Response business identifier.
*/
@Child(name = "identifier", type = {Identifier.class}, order=0, min=0, max=Child.MAX_UNLIMITED, modifier=false, summary=true)
@Description(shortDefinition="Business Identifier", formalDefinition="The Response business identifier." )
protected List<Identifier> identifier;
/**
* The version of the style of resource contents. This should be mapped to the allowable profiles for this and supporting resources.
*/
@Child(name = "ruleset", type = {Coding.class}, order=1, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="Resource version", formalDefinition="The version of the style of resource contents. This should be mapped to the allowable profiles for this and supporting resources." )
protected Coding ruleset;
/**
* The style (standard) and version of the original material which was converted into this resource.
*/
@Child(name = "originalRuleset", type = {Coding.class}, order=2, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="Original version", formalDefinition="The style (standard) and version of the original material which was converted into this resource." )
protected Coding originalRuleset;
/**
* The date when this resource was created.
*/
@Child(name = "created", type = {DateTimeType.class}, order=3, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="Creation date", formalDefinition="The date when this resource was created." )
protected DateTimeType created;
/**
* The Insurer who is target of the request.
*/
@Child(name = "target", type = {Identifier.class, Organization.class}, order=4, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="Insurer or Regulatory body", formalDefinition="The Insurer who is target of the request." )
protected Type target;
/**
* The practitioner who is responsible for the services rendered to the patient.
*/
@Child(name = "provider", type = {Identifier.class, Practitioner.class}, order=5, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="Responsible practitioner", formalDefinition="The practitioner who is responsible for the services rendered to the patient." )
protected Type provider;
/**
* The organization which is responsible for the services rendered to the patient.
*/
@Child(name = "organization", type = {Identifier.class, Organization.class}, order=6, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="Responsible organization", formalDefinition="The organization which is responsible for the services rendered to the patient." )
protected Type organization;
/**
* Reference of resource to reverse.
*/
@Child(name = "request", type = {Identifier.class}, order=7, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="Request reference", formalDefinition="Reference of resource to reverse." )
protected Type request;
/**
* Reference of response to resource to reverse.
*/
@Child(name = "response", type = {Identifier.class}, order=8, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="Response reference", formalDefinition="Reference of response to resource to reverse." )
protected Type response;
/**
* The payment status, typically paid: payment sent, cleared: payment received.
*/
@Child(name = "paymentStatus", type = {Coding.class}, order=9, min=1, max=1, modifier=false, summary=true)
@Description(shortDefinition="Status of the payment", formalDefinition="The payment status, typically paid: payment sent, cleared: payment received." )
protected Coding paymentStatus;
/**
* The date when the above payment action occurrred.
*/
@Child(name = "statusDate", type = {DateType.class}, order=10, min=0, max=1, modifier=false, summary=true)
@Description(shortDefinition="Payment or clearing date", formalDefinition="The date when the above payment action occurrred." )
protected DateType statusDate;
private static final long serialVersionUID = -771143315L;
/**
* Constructor
*/
public PaymentNotice() {
super();
}
/**
* Constructor
*/
public PaymentNotice(Coding paymentStatus) {
super();
this.paymentStatus = paymentStatus;
}
/**
* @return {@link #identifier} (The Response business identifier.)
*/
public List<Identifier> getIdentifier() {
if (this.identifier == null)
this.identifier = new ArrayList<Identifier>();
return this.identifier;
}
public boolean hasIdentifier() {
if (this.identifier == null)
return false;
for (Identifier item : this.identifier)
if (!item.isEmpty())
return true;
return false;
}
/**
* @return {@link #identifier} (The Response business identifier.)
*/
// syntactic sugar
public Identifier addIdentifier() { //3
Identifier t = new Identifier();
if (this.identifier == null)
this.identifier = new ArrayList<Identifier>();
this.identifier.add(t);
return t;
}
// syntactic sugar
public PaymentNotice addIdentifier(Identifier t) { //3
if (t == null)
return this;
if (this.identifier == null)
this.identifier = new ArrayList<Identifier>();
this.identifier.add(t);
return this;
}
/**
* @return {@link #ruleset} (The version of the style of resource contents. This should be mapped to the allowable profiles for this and supporting resources.)
*/
public Coding getRuleset() {
if (this.ruleset == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create PaymentNotice.ruleset");
else if (Configuration.doAutoCreate())
this.ruleset = new Coding(); // cc
return this.ruleset;
}
public boolean hasRuleset() {
return this.ruleset != null && !this.ruleset.isEmpty();
}
/**
* @param value {@link #ruleset} (The version of the style of resource contents. This should be mapped to the allowable profiles for this and supporting resources.)
*/
public PaymentNotice setRuleset(Coding value) {
this.ruleset = value;
return this;
}
/**
* @return {@link #originalRuleset} (The style (standard) and version of the original material which was converted into this resource.)
*/
public Coding getOriginalRuleset() {
if (this.originalRuleset == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create PaymentNotice.originalRuleset");
else if (Configuration.doAutoCreate())
this.originalRuleset = new Coding(); // cc
return this.originalRuleset;
}
public boolean hasOriginalRuleset() {
return this.originalRuleset != null && !this.originalRuleset.isEmpty();
}
/**
* @param value {@link #originalRuleset} (The style (standard) and version of the original material which was converted into this resource.)
*/
public PaymentNotice setOriginalRuleset(Coding value) {
this.originalRuleset = value;
return this;
}
/**
* @return {@link #created} (The date when this resource was created.). This is the underlying object with id, value and extensions. The accessor "getCreated" gives direct access to the value
*/
public DateTimeType getCreatedElement() {
if (this.created == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create PaymentNotice.created");
else if (Configuration.doAutoCreate())
this.created = new DateTimeType(); // bb
return this.created;
}
public boolean hasCreatedElement() {
return this.created != null && !this.created.isEmpty();
}
public boolean hasCreated() {
return this.created != null && !this.created.isEmpty();
}
/**
* @param value {@link #created} (The date when this resource was created.). This is the underlying object with id, value and extensions. The accessor "getCreated" gives direct access to the value
*/
public PaymentNotice setCreatedElement(DateTimeType value) {
this.created = value;
return this;
}
/**
* @return The date when this resource was created.
*/
public Date getCreated() {
return this.created == null ? null : this.created.getValue();
}
/**
* @param value The date when this resource was created.
*/
public PaymentNotice setCreated(Date value) {
if (value == null)
this.created = null;
else {
if (this.created == null)
this.created = new DateTimeType();
this.created.setValue(value);
}
return this;
}
/**
* @return {@link #target} (The Insurer who is target of the request.)
*/
public Type getTarget() {
return this.target;
}
/**
* @return {@link #target} (The Insurer who is target of the request.)
*/
public Identifier getTargetIdentifier() throws FHIRException {
if (!(this.target instanceof Identifier))
throw new FHIRException("Type mismatch: the type Identifier was expected, but "+this.target.getClass().getName()+" was encountered");
return (Identifier) this.target;
}
public boolean hasTargetIdentifier() {
return this.target instanceof Identifier;
}
/**
* @return {@link #target} (The Insurer who is target of the request.)
*/
public Reference getTargetReference() throws FHIRException {
if (!(this.target instanceof Reference))
throw new FHIRException("Type mismatch: the type Reference was expected, but "+this.target.getClass().getName()+" was encountered");
return (Reference) this.target;
}
public boolean hasTargetReference() {
return this.target instanceof Reference;
}
public boolean hasTarget() {
return this.target != null && !this.target.isEmpty();
}
/**
* @param value {@link #target} (The Insurer who is target of the request.)
*/
public PaymentNotice setTarget(Type value) {
this.target = value;
return this;
}
/**
* @return {@link #provider} (The practitioner who is responsible for the services rendered to the patient.)
*/
public Type getProvider() {
return this.provider;
}
/**
* @return {@link #provider} (The practitioner who is responsible for the services rendered to the patient.)
*/
public Identifier getProviderIdentifier() throws FHIRException {
if (!(this.provider instanceof Identifier))
throw new FHIRException("Type mismatch: the type Identifier was expected, but "+this.provider.getClass().getName()+" was encountered");
return (Identifier) this.provider;
}
public boolean hasProviderIdentifier() {
return this.provider instanceof Identifier;
}
/**
* @return {@link #provider} (The practitioner who is responsible for the services rendered to the patient.)
*/
public Reference getProviderReference() throws FHIRException {
if (!(this.provider instanceof Reference))
throw new FHIRException("Type mismatch: the type Reference was expected, but "+this.provider.getClass().getName()+" was encountered");
return (Reference) this.provider;
}
public boolean hasProviderReference() {
return this.provider instanceof Reference;
}
public boolean hasProvider() {
return this.provider != null && !this.provider.isEmpty();
}
/**
* @param value {@link #provider} (The practitioner who is responsible for the services rendered to the patient.)
*/
public PaymentNotice setProvider(Type value) {
this.provider = value;
return this;
}
/**
* @return {@link #organization} (The organization which is responsible for the services rendered to the patient.)
*/
public Type getOrganization() {
return this.organization;
}
/**
* @return {@link #organization} (The organization which is responsible for the services rendered to the patient.)
*/
public Identifier getOrganizationIdentifier() throws FHIRException {
if (!(this.organization instanceof Identifier))
throw new FHIRException("Type mismatch: the type Identifier was expected, but "+this.organization.getClass().getName()+" was encountered");
return (Identifier) this.organization;
}
public boolean hasOrganizationIdentifier() {
return this.organization instanceof Identifier;
}
/**
* @return {@link #organization} (The organization which is responsible for the services rendered to the patient.)
*/
public Reference getOrganizationReference() throws FHIRException {
if (!(this.organization instanceof Reference))
throw new FHIRException("Type mismatch: the type Reference was expected, but "+this.organization.getClass().getName()+" was encountered");
return (Reference) this.organization;
}
public boolean hasOrganizationReference() {
return this.organization instanceof Reference;
}
public boolean hasOrganization() {
return this.organization != null && !this.organization.isEmpty();
}
/**
* @param value {@link #organization} (The organization which is responsible for the services rendered to the patient.)
*/
public PaymentNotice setOrganization(Type value) {
this.organization = value;
return this;
}
/**
* @return {@link #request} (Reference of resource to reverse.)
*/
public Type getRequest() {
return this.request;
}
/**
* @return {@link #request} (Reference of resource to reverse.)
*/
public Identifier getRequestIdentifier() throws FHIRException {
if (!(this.request instanceof Identifier))
throw new FHIRException("Type mismatch: the type Identifier was expected, but "+this.request.getClass().getName()+" was encountered");
return (Identifier) this.request;
}
public boolean hasRequestIdentifier() {
return this.request instanceof Identifier;
}
/**
* @return {@link #request} (Reference of resource to reverse.)
*/
public Reference getRequestReference() throws FHIRException {
if (!(this.request instanceof Reference))
throw new FHIRException("Type mismatch: the type Reference was expected, but "+this.request.getClass().getName()+" was encountered");
return (Reference) this.request;
}
public boolean hasRequestReference() {
return this.request instanceof Reference;
}
public boolean hasRequest() {
return this.request != null && !this.request.isEmpty();
}
/**
* @param value {@link #request} (Reference of resource to reverse.)
*/
public PaymentNotice setRequest(Type value) {
this.request = value;
return this;
}
/**
* @return {@link #response} (Reference of response to resource to reverse.)
*/
public Type getResponse() {
return this.response;
}
/**
* @return {@link #response} (Reference of response to resource to reverse.)
*/
public Identifier getResponseIdentifier() throws FHIRException {
if (!(this.response instanceof Identifier))
throw new FHIRException("Type mismatch: the type Identifier was expected, but "+this.response.getClass().getName()+" was encountered");
return (Identifier) this.response;
}
public boolean hasResponseIdentifier() {
return this.response instanceof Identifier;
}
/**
* @return {@link #response} (Reference of response to resource to reverse.)
*/
public Reference getResponseReference() throws FHIRException {
if (!(this.response instanceof Reference))
throw new FHIRException("Type mismatch: the type Reference was expected, but "+this.response.getClass().getName()+" was encountered");
return (Reference) this.response;
}
public boolean hasResponseReference() {
return this.response instanceof Reference;
}
public boolean hasResponse() {
return this.response != null && !this.response.isEmpty();
}
/**
* @param value {@link #response} (Reference of response to resource to reverse.)
*/
public PaymentNotice setResponse(Type value) {
this.response = value;
return this;
}
/**
* @return {@link #paymentStatus} (The payment status, typically paid: payment sent, cleared: payment received.)
*/
public Coding getPaymentStatus() {
if (this.paymentStatus == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create PaymentNotice.paymentStatus");
else if (Configuration.doAutoCreate())
this.paymentStatus = new Coding(); // cc
return this.paymentStatus;
}
public boolean hasPaymentStatus() {
return this.paymentStatus != null && !this.paymentStatus.isEmpty();
}
/**
* @param value {@link #paymentStatus} (The payment status, typically paid: payment sent, cleared: payment received.)
*/
public PaymentNotice setPaymentStatus(Coding value) {
this.paymentStatus = value;
return this;
}
/**
* @return {@link #statusDate} (The date when the above payment action occurrred.). This is the underlying object with id, value and extensions. The accessor "getStatusDate" gives direct access to the value
*/
public DateType getStatusDateElement() {
if (this.statusDate == null)
if (Configuration.errorOnAutoCreate())
throw new Error("Attempt to auto-create PaymentNotice.statusDate");
else if (Configuration.doAutoCreate())
this.statusDate = new DateType(); // bb
return this.statusDate;
}
public boolean hasStatusDateElement() {
return this.statusDate != null && !this.statusDate.isEmpty();
}
public boolean hasStatusDate() {
return this.statusDate != null && !this.statusDate.isEmpty();
}
/**
* @param value {@link #statusDate} (The date when the above payment action occurrred.). This is the underlying object with id, value and extensions. The accessor "getStatusDate" gives direct access to the value
*/
public PaymentNotice setStatusDateElement(DateType value) {
this.statusDate = value;
return this;
}
/**
* @return The date when the above payment action occurrred.
*/
public Date getStatusDate() {
return this.statusDate == null ? null : this.statusDate.getValue();
}
/**
* @param value The date when the above payment action occurrred.
*/
public PaymentNotice setStatusDate(Date value) {
if (value == null)
this.statusDate = null;
else {
if (this.statusDate == null)
this.statusDate = new DateType();
this.statusDate.setValue(value);
}
return this;
}
protected void listChildren(List<Property> childrenList) {
super.listChildren(childrenList);
childrenList.add(new Property("identifier", "Identifier", "The Response business identifier.", 0, java.lang.Integer.MAX_VALUE, identifier));
childrenList.add(new Property("ruleset", "Coding", "The version of the style of resource contents. This should be mapped to the allowable profiles for this and supporting resources.", 0, java.lang.Integer.MAX_VALUE, ruleset));
childrenList.add(new Property("originalRuleset", "Coding", "The style (standard) and version of the original material which was converted into this resource.", 0, java.lang.Integer.MAX_VALUE, originalRuleset));
childrenList.add(new Property("created", "dateTime", "The date when this resource was created.", 0, java.lang.Integer.MAX_VALUE, created));
childrenList.add(new Property("target[x]", "Identifier|Reference(Organization)", "The Insurer who is target of the request.", 0, java.lang.Integer.MAX_VALUE, target));
childrenList.add(new Property("provider[x]", "Identifier|Reference(Practitioner)", "The practitioner who is responsible for the services rendered to the patient.", 0, java.lang.Integer.MAX_VALUE, provider));
childrenList.add(new Property("organization[x]", "Identifier|Reference(Organization)", "The organization which is responsible for the services rendered to the patient.", 0, java.lang.Integer.MAX_VALUE, organization));
childrenList.add(new Property("request[x]", "Identifier|Reference(Any)", "Reference of resource to reverse.", 0, java.lang.Integer.MAX_VALUE, request));
childrenList.add(new Property("response[x]", "Identifier|Reference(Any)", "Reference of response to resource to reverse.", 0, java.lang.Integer.MAX_VALUE, response));
childrenList.add(new Property("paymentStatus", "Coding", "The payment status, typically paid: payment sent, cleared: payment received.", 0, java.lang.Integer.MAX_VALUE, paymentStatus));
childrenList.add(new Property("statusDate", "date", "The date when the above payment action occurrred.", 0, java.lang.Integer.MAX_VALUE, statusDate));
}
@Override
public Base[] getProperty(int hash, String name, boolean checkValid) throws FHIRException {
switch (hash) {
case -1618432855: /*identifier*/ return this.identifier == null ? new Base[0] : this.identifier.toArray(new Base[this.identifier.size()]); // Identifier
case 1548678118: /*ruleset*/ return this.ruleset == null ? new Base[0] : new Base[] {this.ruleset}; // Coding
case 1089373397: /*originalRuleset*/ return this.originalRuleset == null ? new Base[0] : new Base[] {this.originalRuleset}; // Coding
case 1028554472: /*created*/ return this.created == null ? new Base[0] : new Base[] {this.created}; // DateTimeType
case -880905839: /*target*/ return this.target == null ? new Base[0] : new Base[] {this.target}; // Type
case -987494927: /*provider*/ return this.provider == null ? new Base[0] : new Base[] {this.provider}; // Type
case 1178922291: /*organization*/ return this.organization == null ? new Base[0] : new Base[] {this.organization}; // Type
case 1095692943: /*request*/ return this.request == null ? new Base[0] : new Base[] {this.request}; // Type
case -340323263: /*response*/ return this.response == null ? new Base[0] : new Base[] {this.response}; // Type
case 1430704536: /*paymentStatus*/ return this.paymentStatus == null ? new Base[0] : new Base[] {this.paymentStatus}; // Coding
case 247524032: /*statusDate*/ return this.statusDate == null ? new Base[0] : new Base[] {this.statusDate}; // DateType
default: return super.getProperty(hash, name, checkValid);
}
}
@Override
public void setProperty(int hash, String name, Base value) throws FHIRException {
switch (hash) {
case -1618432855: // identifier
this.getIdentifier().add(castToIdentifier(value)); // Identifier
break;
case 1548678118: // ruleset
this.ruleset = castToCoding(value); // Coding
break;
case 1089373397: // originalRuleset
this.originalRuleset = castToCoding(value); // Coding
break;
case 1028554472: // created
this.created = castToDateTime(value); // DateTimeType
break;
case -880905839: // target
this.target = (Type) value; // Type
break;
case -987494927: // provider
this.provider = (Type) value; // Type
break;
case 1178922291: // organization
this.organization = (Type) value; // Type
break;
case 1095692943: // request
this.request = (Type) value; // Type
break;
case -340323263: // response
this.response = (Type) value; // Type
break;
case 1430704536: // paymentStatus
this.paymentStatus = castToCoding(value); // Coding
break;
case 247524032: // statusDate
this.statusDate = castToDate(value); // DateType
break;
default: super.setProperty(hash, name, value);
}
}
@Override
public void setProperty(String name, Base value) throws FHIRException {
if (name.equals("identifier"))
this.getIdentifier().add(castToIdentifier(value));
else if (name.equals("ruleset"))
this.ruleset = castToCoding(value); // Coding
else if (name.equals("originalRuleset"))
this.originalRuleset = castToCoding(value); // Coding
else if (name.equals("created"))
this.created = castToDateTime(value); // DateTimeType
else if (name.equals("target[x]"))
this.target = (Type) value; // Type
else if (name.equals("provider[x]"))
this.provider = (Type) value; // Type
else if (name.equals("organization[x]"))
this.organization = (Type) value; // Type
else if (name.equals("request[x]"))
this.request = (Type) value; // Type
else if (name.equals("response[x]"))
this.response = (Type) value; // Type
else if (name.equals("paymentStatus"))
this.paymentStatus = castToCoding(value); // Coding
else if (name.equals("statusDate"))
this.statusDate = castToDate(value); // DateType
else
super.setProperty(name, value);
}
@Override
public Base makeProperty(int hash, String name) throws FHIRException {
switch (hash) {
case -1618432855: return addIdentifier(); // Identifier
case 1548678118: return getRuleset(); // Coding
case 1089373397: return getOriginalRuleset(); // Coding
case 1028554472: throw new FHIRException("Cannot make property created as it is not a complex type"); // DateTimeType
case -815579825: return getTarget(); // Type
case 2064698607: return getProvider(); // Type
case 1326483053: return getOrganization(); // Type
case 37106577: return getRequest(); // Type
case 1847549087: return getResponse(); // Type
case 1430704536: return getPaymentStatus(); // Coding
case 247524032: throw new FHIRException("Cannot make property statusDate as it is not a complex type"); // DateType
default: return super.makeProperty(hash, name);
}
}
@Override
public Base addChild(String name) throws FHIRException {
if (name.equals("identifier")) {
return addIdentifier();
}
else if (name.equals("ruleset")) {
this.ruleset = new Coding();
return this.ruleset;
}
else if (name.equals("originalRuleset")) {
this.originalRuleset = new Coding();
return this.originalRuleset;
}
else if (name.equals("created")) {
throw new FHIRException("Cannot call addChild on a primitive type PaymentNotice.created");
}
else if (name.equals("targetIdentifier")) {
this.target = new Identifier();
return this.target;
}
else if (name.equals("targetReference")) {
this.target = new Reference();
return this.target;
}
else if (name.equals("providerIdentifier")) {
this.provider = new Identifier();
return this.provider;
}
else if (name.equals("providerReference")) {
this.provider = new Reference();
return this.provider;
}
else if (name.equals("organizationIdentifier")) {
this.organization = new Identifier();
return this.organization;
}
else if (name.equals("organizationReference")) {
this.organization = new Reference();
return this.organization;
}
else if (name.equals("requestIdentifier")) {
this.request = new Identifier();
return this.request;
}
else if (name.equals("requestReference")) {
this.request = new Reference();
return this.request;
}
else if (name.equals("responseIdentifier")) {
this.response = new Identifier();
return this.response;
}
else if (name.equals("responseReference")) {
this.response = new Reference();
return this.response;
}
else if (name.equals("paymentStatus")) {
this.paymentStatus = new Coding();
return this.paymentStatus;
}
else if (name.equals("statusDate")) {
throw new FHIRException("Cannot call addChild on a primitive type PaymentNotice.statusDate");
}
else
return super.addChild(name);
}
public String fhirType() {
return "PaymentNotice";
}
public PaymentNotice copy() {
PaymentNotice dst = new PaymentNotice();
copyValues(dst);
if (identifier != null) {
dst.identifier = new ArrayList<Identifier>();
for (Identifier i : identifier)
dst.identifier.add(i.copy());
};
dst.ruleset = ruleset == null ? null : ruleset.copy();
dst.originalRuleset = originalRuleset == null ? null : originalRuleset.copy();
dst.created = created == null ? null : created.copy();
dst.target = target == null ? null : target.copy();
dst.provider = provider == null ? null : provider.copy();
dst.organization = organization == null ? null : organization.copy();
dst.request = request == null ? null : request.copy();
dst.response = response == null ? null : response.copy();
dst.paymentStatus = paymentStatus == null ? null : paymentStatus.copy();
dst.statusDate = statusDate == null ? null : statusDate.copy();
return dst;
}
protected PaymentNotice typedCopy() {
return copy();
}
@Override
public boolean equalsDeep(Base other) {
if (!super.equalsDeep(other))
return false;
if (!(other instanceof PaymentNotice))
return false;
PaymentNotice o = (PaymentNotice) other;
return compareDeep(identifier, o.identifier, true) && compareDeep(ruleset, o.ruleset, true) && compareDeep(originalRuleset, o.originalRuleset, true)
&& compareDeep(created, o.created, true) && compareDeep(target, o.target, true) && compareDeep(provider, o.provider, true)
&& compareDeep(organization, o.organization, true) && compareDeep(request, o.request, true) && compareDeep(response, o.response, true)
&& compareDeep(paymentStatus, o.paymentStatus, true) && compareDeep(statusDate, o.statusDate, true)
;
}
@Override
public boolean equalsShallow(Base other) {
if (!super.equalsShallow(other))
return false;
if (!(other instanceof PaymentNotice))
return false;
PaymentNotice o = (PaymentNotice) other;
return compareValues(created, o.created, true) && compareValues(statusDate, o.statusDate, true);
}
public boolean isEmpty() {
return super.isEmpty() && (identifier == null || identifier.isEmpty()) && (ruleset == null || ruleset.isEmpty())
&& (originalRuleset == null || originalRuleset.isEmpty()) && (created == null || created.isEmpty())
&& (target == null || target.isEmpty()) && (provider == null || provider.isEmpty()) && (organization == null || organization.isEmpty())
&& (request == null || request.isEmpty()) && (response == null || response.isEmpty()) && (paymentStatus == null || paymentStatus.isEmpty())
&& (statusDate == null || statusDate.isEmpty());
}
@Override
public ResourceType getResourceType() {
return ResourceType.PaymentNotice;
}
/**
* Search parameter: <b>paymentstatus</b>
* <p>
* Description: <b>The type of payment notice</b><br>
* Type: <b>token</b><br>
* Path: <b>PaymentNotice.paymentStatus</b><br>
* </p>
*/
@SearchParamDefinition(name="paymentstatus", path="PaymentNotice.paymentStatus", description="The type of payment notice", type="token" )
public static final String SP_PAYMENTSTATUS = "paymentstatus";
/**
* <b>Fluent Client</b> search parameter constant for <b>paymentstatus</b>
* <p>
* Description: <b>The type of payment notice</b><br>
* Type: <b>token</b><br>
* Path: <b>PaymentNotice.paymentStatus</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.TokenClientParam PAYMENTSTATUS = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_PAYMENTSTATUS);
/**
* Search parameter: <b>statusdate</b>
* <p>
* Description: <b>The date of the payment action</b><br>
* Type: <b>date</b><br>
* Path: <b>PaymentNotice.statusDate</b><br>
* </p>
*/
@SearchParamDefinition(name="statusdate", path="PaymentNotice.statusDate", description="The date of the payment action", type="date" )
public static final String SP_STATUSDATE = "statusdate";
/**
* <b>Fluent Client</b> search parameter constant for <b>statusdate</b>
* <p>
* Description: <b>The date of the payment action</b><br>
* Type: <b>date</b><br>
* Path: <b>PaymentNotice.statusDate</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.DateClientParam STATUSDATE = new ca.uhn.fhir.rest.gclient.DateClientParam(SP_STATUSDATE);
/**
* Search parameter: <b>created</b>
* <p>
* Description: <b>Creation date fro the notice</b><br>
* Type: <b>date</b><br>
* Path: <b>PaymentNotice.created</b><br>
* </p>
*/
@SearchParamDefinition(name="created", path="PaymentNotice.created", description="Creation date fro the notice", type="date" )
public static final String SP_CREATED = "created";
/**
* <b>Fluent Client</b> search parameter constant for <b>created</b>
* <p>
* Description: <b>Creation date fro the notice</b><br>
* Type: <b>date</b><br>
* Path: <b>PaymentNotice.created</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.DateClientParam CREATED = new ca.uhn.fhir.rest.gclient.DateClientParam(SP_CREATED);
/**
* Search parameter: <b>requestidentifier</b>
* <p>
* Description: <b>The Claim</b><br>
* Type: <b>token</b><br>
* Path: <b>PaymentNotice.requestIdentifier</b><br>
* </p>
*/
@SearchParamDefinition(name="requestidentifier", path="PaymentNotice.request.as(Identifier)", description="The Claim", type="token" )
public static final String SP_REQUESTIDENTIFIER = "requestidentifier";
/**
* <b>Fluent Client</b> search parameter constant for <b>requestidentifier</b>
* <p>
* Description: <b>The Claim</b><br>
* Type: <b>token</b><br>
* Path: <b>PaymentNotice.requestIdentifier</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.TokenClientParam REQUESTIDENTIFIER = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_REQUESTIDENTIFIER);
/**
* Search parameter: <b>providerreference</b>
* <p>
* Description: <b>The reference to the provider</b><br>
* Type: <b>reference</b><br>
* Path: <b>PaymentNotice.providerReference</b><br>
* </p>
*/
@SearchParamDefinition(name="providerreference", path="PaymentNotice.provider.as(Reference)", description="The reference to the provider", type="reference" )
public static final String SP_PROVIDERREFERENCE = "providerreference";
/**
* <b>Fluent Client</b> search parameter constant for <b>providerreference</b>
* <p>
* Description: <b>The reference to the provider</b><br>
* Type: <b>reference</b><br>
* Path: <b>PaymentNotice.providerReference</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.ReferenceClientParam PROVIDERREFERENCE = new ca.uhn.fhir.rest.gclient.ReferenceClientParam(SP_PROVIDERREFERENCE);
/**
* Constant for fluent queries to be used to add include statements. Specifies
* the path value of "<b>PaymentNotice:providerreference</b>".
*/
public static final ca.uhn.fhir.model.api.Include INCLUDE_PROVIDERREFERENCE = new ca.uhn.fhir.model.api.Include("PaymentNotice:providerreference").toLocked();
/**
* Search parameter: <b>requestreference</b>
* <p>
* Description: <b>The Claim</b><br>
* Type: <b>reference</b><br>
* Path: <b>PaymentNotice.requestReference</b><br>
* </p>
*/
@SearchParamDefinition(name="requestreference", path="PaymentNotice.request.as(Reference)", description="The Claim", type="reference" )
public static final String SP_REQUESTREFERENCE = "requestreference";
/**
* <b>Fluent Client</b> search parameter constant for <b>requestreference</b>
* <p>
* Description: <b>The Claim</b><br>
* Type: <b>reference</b><br>
* Path: <b>PaymentNotice.requestReference</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.ReferenceClientParam REQUESTREFERENCE = new ca.uhn.fhir.rest.gclient.ReferenceClientParam(SP_REQUESTREFERENCE);
/**
* Constant for fluent queries to be used to add include statements. Specifies
* the path value of "<b>PaymentNotice:requestreference</b>".
*/
public static final ca.uhn.fhir.model.api.Include INCLUDE_REQUESTREFERENCE = new ca.uhn.fhir.model.api.Include("PaymentNotice:requestreference").toLocked();
/**
* Search parameter: <b>responsereference</b>
* <p>
* Description: <b>The ClaimResponse</b><br>
* Type: <b>reference</b><br>
* Path: <b>PaymentNotice.responseReference</b><br>
* </p>
*/
@SearchParamDefinition(name="responsereference", path="PaymentNotice.response.as(Reference)", description="The ClaimResponse", type="reference" )
public static final String SP_RESPONSEREFERENCE = "responsereference";
/**
* <b>Fluent Client</b> search parameter constant for <b>responsereference</b>
* <p>
* Description: <b>The ClaimResponse</b><br>
* Type: <b>reference</b><br>
* Path: <b>PaymentNotice.responseReference</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.ReferenceClientParam RESPONSEREFERENCE = new ca.uhn.fhir.rest.gclient.ReferenceClientParam(SP_RESPONSEREFERENCE);
/**
* Constant for fluent queries to be used to add include statements. Specifies
* the path value of "<b>PaymentNotice:responsereference</b>".
*/
public static final ca.uhn.fhir.model.api.Include INCLUDE_RESPONSEREFERENCE = new ca.uhn.fhir.model.api.Include("PaymentNotice:responsereference").toLocked();
/**
* Search parameter: <b>organizationidentifier</b>
* <p>
* Description: <b>The organization who generated this resource</b><br>
* Type: <b>token</b><br>
* Path: <b>PaymentNotice.organizationIdentifier</b><br>
* </p>
*/
@SearchParamDefinition(name="organizationidentifier", path="PaymentNotice.organization.as(Identifier)", description="The organization who generated this resource", type="token" )
public static final String SP_ORGANIZATIONIDENTIFIER = "organizationidentifier";
/**
* <b>Fluent Client</b> search parameter constant for <b>organizationidentifier</b>
* <p>
* Description: <b>The organization who generated this resource</b><br>
* Type: <b>token</b><br>
* Path: <b>PaymentNotice.organizationIdentifier</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.TokenClientParam ORGANIZATIONIDENTIFIER = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_ORGANIZATIONIDENTIFIER);
/**
* Search parameter: <b>organizationreference</b>
* <p>
* Description: <b>The organization who generated this resource</b><br>
* Type: <b>reference</b><br>
* Path: <b>PaymentNotice.organizationReference</b><br>
* </p>
*/
@SearchParamDefinition(name="organizationreference", path="PaymentNotice.organization.as(Reference)", description="The organization who generated this resource", type="reference" )
public static final String SP_ORGANIZATIONREFERENCE = "organizationreference";
/**
* <b>Fluent Client</b> search parameter constant for <b>organizationreference</b>
* <p>
* Description: <b>The organization who generated this resource</b><br>
* Type: <b>reference</b><br>
* Path: <b>PaymentNotice.organizationReference</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.ReferenceClientParam ORGANIZATIONREFERENCE = new ca.uhn.fhir.rest.gclient.ReferenceClientParam(SP_ORGANIZATIONREFERENCE);
/**
* Constant for fluent queries to be used to add include statements. Specifies
* the path value of "<b>PaymentNotice:organizationreference</b>".
*/
public static final ca.uhn.fhir.model.api.Include INCLUDE_ORGANIZATIONREFERENCE = new ca.uhn.fhir.model.api.Include("PaymentNotice:organizationreference").toLocked();
/**
* Search parameter: <b>responseidentifier</b>
* <p>
* Description: <b>The ClaimResponse</b><br>
* Type: <b>token</b><br>
* Path: <b>PaymentNotice.responseIdentifier</b><br>
* </p>
*/
@SearchParamDefinition(name="responseidentifier", path="PaymentNotice.response.as(Identifier)", description="The ClaimResponse", type="token" )
public static final String SP_RESPONSEIDENTIFIER = "responseidentifier";
/**
* <b>Fluent Client</b> search parameter constant for <b>responseidentifier</b>
* <p>
* Description: <b>The ClaimResponse</b><br>
* Type: <b>token</b><br>
* Path: <b>PaymentNotice.responseIdentifier</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.TokenClientParam RESPONSEIDENTIFIER = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_RESPONSEIDENTIFIER);
/**
* Search parameter: <b>identifier</b>
* <p>
* Description: <b>The business identifier of the notice</b><br>
* Type: <b>token</b><br>
* Path: <b>PaymentNotice.identifier</b><br>
* </p>
*/
@SearchParamDefinition(name="identifier", path="PaymentNotice.identifier", description="The business identifier of the notice", type="token" )
public static final String SP_IDENTIFIER = "identifier";
/**
* <b>Fluent Client</b> search parameter constant for <b>identifier</b>
* <p>
* Description: <b>The business identifier of the notice</b><br>
* Type: <b>token</b><br>
* Path: <b>PaymentNotice.identifier</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.TokenClientParam IDENTIFIER = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_IDENTIFIER);
/**
* Search parameter: <b>provideridentifier</b>
* <p>
* Description: <b>The reference to the provider</b><br>
* Type: <b>token</b><br>
* Path: <b>PaymentNotice.providerIdentifier</b><br>
* </p>
*/
@SearchParamDefinition(name="provideridentifier", path="PaymentNotice.provider.as(Identifier)", description="The reference to the provider", type="token" )
public static final String SP_PROVIDERIDENTIFIER = "provideridentifier";
/**
* <b>Fluent Client</b> search parameter constant for <b>provideridentifier</b>
* <p>
* Description: <b>The reference to the provider</b><br>
* Type: <b>token</b><br>
* Path: <b>PaymentNotice.providerIdentifier</b><br>
* </p>
*/
public static final ca.uhn.fhir.rest.gclient.TokenClientParam PROVIDERIDENTIFIER = new ca.uhn.fhir.rest.gclient.TokenClientParam(SP_PROVIDERIDENTIFIER);
}
| 41.382353 | 234 | 0.665224 |
8322686d87dfce9a4d402161a651525dfc798985 | 583 | package com.webcps.webcps.model;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import lombok.Data;
@Embeddable
@Data
public class UsUhUserhistoryPK implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "lu_enddate")
private Date luEnddate;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "lu_startdate")
private Date luStartdate;
}
| 18.806452 | 56 | 0.780446 |
981eae7275888c6dc361d535af9fc4928296475f | 922 | package com.mcnz.web;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
/* The Java file upload Servlet example */
@WebServlet(name = "FileUploadServlet", urlPatterns = { "/fileuploadservlet" })
@MultipartConfig(
fileSizeThreshold = 1024 * 1024 * 1, // 1 MB
maxFileSize = 1024 * 1024 * 10, // 10 MB
maxRequestSize = 1024 * 1024 * 100 // 100 MB
)
public class FileUploadServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/* Receive file uploaded to the Servlet from the HTML5 form */
Part filePart = request.getPart("file");
String fileName = filePart.getSubmittedFileName();
for (Part part : request.getParts()) {
part.write("C:\\upload\\" + fileName);
}
response.getWriter().print("The file uploaded sucessfully.");
}
} | 34.148148 | 117 | 0.704989 |
356b4899e97b3bccb91590bdc2bdf306c5bd57d7 | 2,195 | /*
* Copyright (C) 2014-2015 LinkedIn Corp. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use
* this file except in compliance with the License. You may obtain a copy of the
* License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied.
*/
package gobblin.compaction.dataset;
import java.io.IOException;
import java.util.Set;
import org.apache.hadoop.fs.Path;
import com.google.common.collect.Sets;
import gobblin.compaction.mapreduce.MRCompactor;
import gobblin.configuration.State;
/**
* Implementation of {@link DatasetsFinder}. It simply takes {@link MRCompactor#COMPACTION_INPUT_DIR} as input,
* and {@link MRCompactor#COMPACTION_DEST_DIR} as output.
*/
public class SimpleDatasetsFinder extends DatasetsFinder {
public SimpleDatasetsFinder(State state) {
super(state);
}
/**
* Create a dataset using {@link #inputDir} and {@link #destDir}.
* Set dataset input path to be {@link #destDir} if {@link #recompactDatasets} is true.
*/
@Override
public Set<Dataset> findDistinctDatasets() throws IOException {
Set<Dataset> datasets = Sets.newHashSet();
Path inputPath = new Path(this.inputDir);
Path inputLatePath = new Path(inputPath, MRCompactor.COMPACTION_LATE_DIR_SUFFIX);
Path outputPath = new Path(this.destDir);
Path outputLatePath = new Path(outputPath, MRCompactor.COMPACTION_LATE_DIR_SUFFIX);
Dataset dataset =
new Dataset.Builder().withPriority(this.getDatasetPriority(inputPath.getName()))
.withLateDataThresholdForRecompact(this.getDatasetRecompactThreshold(inputPath.getName()))
.withInputPath(this.recompactDatasets ? outputPath : inputPath)
.withInputLatePath(this.recompactDatasets ? outputLatePath : inputLatePath).withOutputPath(outputPath)
.withOutputLatePath(outputLatePath).withOutputTmpPath(new Path(this.tmpOutputDir)).build();
datasets.add(dataset);
return datasets;
}
}
| 38.508772 | 114 | 0.744875 |
b11222559e5cd233affa9eae63ae9ab08a853812 | 265 | package com.axway.apim.servicebroker.service;
public interface Constants {
String VERSION = "1.2.0";
String API_BASEPATH = "/api/portal/v1.3/";
String DOT = ".";
String PUBLISHED = "published";
String CF_BINDING_ID= "cfBindingId";
String VHOST = "vhost";
}
| 22.083333 | 45 | 0.709434 |
75dc2e4b671d13468c8c2460c5c5caf0bccaa767 | 269 | package com.example.linhu.studio6test.singleton;
/**
* Author:linhu
* Email:lhzheng@grandstream.cn
* Date:19-4-24
*/
public class Staff {
public void work(){
//干活
}
protected String getTag(){
return getClass().getSimpleName();
}
}
| 15.823529 | 48 | 0.620818 |
91d12f1763436ae70f86ef548b189d14ae879ef4 | 2,280 | /*
* Project: OSMP
* FileName: InterceptorMappingInfo.java
* version: V1.0
*/
package com.osmp.service.bean;
import com.osmp.jdbc.define.Column;
import com.osmp.service.util.ServiceUtil;
public class InterceptorMappingInfo {
@Column(mapField="interceptorBundle",name="interceptorBundle")
private String interceptorBundle;
@Column(mapField="interceptorVersion",name="interceptorVersion")
private String interceptorVersion;
@Column(mapField="interceptorName",name="interceptorName")
private String interceptorName;
@Column(mapField="serviceBundle",name="serviceBundle")
private String serviceBundle;
@Column(mapField="serviceVersion",name="serviceVersion")
private String serviceVersion;
@Column(mapField="serviceName",name="serviceName")
private String serviceName;
public String getInterceptorBundle() {
return interceptorBundle;
}
public void setInterceptorBundle(String interceptorBundle) {
this.interceptorBundle = interceptorBundle;
}
public String getInterceptorVersion() {
return interceptorVersion;
}
public void setInterceptorVersion(String interceptorVersion) {
this.interceptorVersion = interceptorVersion;
}
public String getInterceptorName() {
return interceptorName;
}
public void setInterceptorName(String interceptorName) {
this.interceptorName = interceptorName;
}
public String getServiceBundle() {
return serviceBundle;
}
public void setServiceBundle(String serviceBundle) {
this.serviceBundle = serviceBundle;
}
public String getServiceVersion() {
return serviceVersion;
}
public void setServiceVersion(String serviceVersion) {
this.serviceVersion = serviceVersion;
}
public String getServiceName() {
return serviceName;
}
public void setServiceName(String serviceName) {
this.serviceName = serviceName;
}
public String generateServiceName(){
return ServiceUtil.generateServiceName(serviceBundle, serviceVersion, serviceName);
}
public String generateInterceptorName(){
return ServiceUtil.generateServiceName(interceptorBundle, interceptorVersion, interceptorName);
}
}
| 33.043478 | 103 | 0.721491 |
46ba81e0df1e996f7cb6c50d66dbdee8de758b34 | 1,565 | /**
* Copyright 2013 Dennis Ippel
*
* 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 rajawali.curves;
import java.util.Stack;
import rajawali.math.vector.Vector3;
public class CompoundCurve3D implements ICurve3D {
protected static final double DELTA = .000001;
protected Stack<ICurve3D> mCurves;
protected int mNumCurves;
protected ICurve3D mCurrentCurve;
public CompoundCurve3D() {
mCurves = new Stack<ICurve3D>();
}
public void addCurve(ICurve3D curve) {
mCurves.add(curve);
mNumCurves++;
}
public void calculatePoint(Vector3 point, double t) {
int currentIndex = (int) Math.floor((t == 1 ? t - DELTA : t) * mNumCurves);
mCurrentCurve = mCurves.get(currentIndex);
double tdivnum = (t * mNumCurves) - currentIndex;
mCurrentCurve.calculatePoint(point, tdivnum);
}
public int getNumCurves()
{
return mCurves.size();
}
public Vector3 getCurrentTangent() {
if(mCurrentCurve == null) return null;
return mCurrentCurve.getCurrentTangent();
}
public void setCalculateTangents(boolean calculateTangents) {
}
}
| 27.946429 | 118 | 0.740575 |
d0cc80d41027267e609548ac73229f37d7cc8619 | 319 | package com.cloud.goods.entity.dto;
import com.cloud.goods.entity.Goods;
import com.cloud.goods.entity.GoodsSku;
import lombok.Data;
import java.util.List;
@Data
public class GoodsDto extends Goods {
private static final long serialVersionUID = -2596408615836602516L;
private List<GoodsSku> goodsSkuList;
}
| 21.266667 | 71 | 0.783699 |
85bbcd3ca1cfe21b7bfe5292d6e19feefd82c7a8 | 910 | package ru.job4j.chess.figures.black;
import ru.job4j.chess.figures.Cell;
import ru.job4j.chess.figures.Figure;
import ru.job4j.chess.figures.figure.Rook;
/**
* The {@code RookBlack} class creates the Black Rook Chess Figure.
*
* @author Alexander Petrenko (Lexer8@gmail.com)
* @version 1.0
* @since 0.1
*/
public class RookBlack extends Rook {
/**
* The class constructor sets position of the Black Rook on the board.
*
* @param position The cell on the chess board, where the Rook stands.
*/
public RookBlack(final Cell position) {
super(position);
}
/**
* The method, which creates a copy of Rook on the new position.
*
* @param dest The cell on the chess board, where the Rook is moving.
* @return A new Rook Figure on a new Cell.
*/
@Override
public Figure copy(Cell dest) {
return new RookBlack(dest);
}
}
| 26 | 74 | 0.656044 |
23b09955de0a49787b42628f177832ff582bb607 | 1,598 | package cla.edg.project.storedev.gen.graphquery;
import java.util.Map;
import com.terapico.generator.Utils;
import cla.edg.modelbean.*;
public class SampleItemTitle extends BaseModelBean{
public String getFullClassName() {
return "com.doublechain.storedev.sampleitemtitle.SampleItemTitle";
}
// 枚举对象
public static EnumAttribute MID = new EnumAttribute("com.doublechain.storedev.sampleitemtitle.SampleItemTitle", "MID");
public static EnumAttribute AFTER = new EnumAttribute("com.doublechain.storedev.sampleitemtitle.SampleItemTitle", "AFTER");
public static EnumAttribute NIGHT = new EnumAttribute("com.doublechain.storedev.sampleitemtitle.SampleItemTitle", "NIGHT");
public static EnumAttribute WEATHER = new EnumAttribute("com.doublechain.storedev.sampleitemtitle.SampleItemTitle", "WEATHER");
// 引用的对象
// 被引用的对象
// 普通属性
public StringAttribute id(){
StringAttribute member = new StringAttribute();
member.setModelTypeName("string");
member.setName("id");
useMember(member);
return member;
}
public StringAttribute name(){
StringAttribute member = new StringAttribute();
member.setModelTypeName("string");
member.setName("name");
useMember(member);
return member;
}
public StringAttribute code(){
StringAttribute member = new StringAttribute();
member.setModelTypeName("string");
member.setName("code");
useMember(member);
return member;
}
public NumberAttribute version(){
NumberAttribute member = new NumberAttribute();
member.setModelTypeName("int");
member.setName("version");
useMember(member);
return member;
}
}
| 25.774194 | 128 | 0.760951 |
a6ff78e10cb9764335aeffb369231e742b46e863 | 5,341 | package org.hisp.dhis.android.core.sms.domain.converter.internal;
import androidx.annotation.NonNull;
import org.hisp.dhis.android.core.arch.helpers.GeometryHelper;
import org.hisp.dhis.android.core.common.State;
import org.hisp.dhis.android.core.enrollment.Enrollment;
import org.hisp.dhis.android.core.enrollment.EnrollmentInternalAccessor;
import org.hisp.dhis.android.core.event.Event;
import org.hisp.dhis.android.core.sms.domain.repository.internal.LocalDbRepository;
import org.hisp.dhis.android.core.systeminfo.DHISVersionManager;
import org.hisp.dhis.android.core.trackedentity.TrackedEntityAttributeValue;
import org.hisp.dhis.android.core.trackedentity.TrackedEntityInstance;
import org.hisp.dhis.android.core.trackedentity.TrackedEntityInstanceInternalAccessor;
import org.hisp.dhis.smscompression.models.EnrollmentSMSSubmission;
import org.hisp.dhis.smscompression.models.SMSAttributeValue;
import org.hisp.dhis.smscompression.models.SMSEvent;
import org.hisp.dhis.smscompression.models.SMSSubmission;
import java.util.ArrayList;
import java.util.List;
import io.reactivex.Completable;
import io.reactivex.Single;
public class EnrollmentConverter extends Converter<TrackedEntityInstance> {
private final String enrollmentUid;
private TrackedEntityInstance trackedEntityInstance;
public EnrollmentConverter(LocalDbRepository localDbRepository,
DHISVersionManager dhisVersionManager,
String enrollmentUid) {
super(localDbRepository, dhisVersionManager);
this.enrollmentUid = enrollmentUid;
}
@Override
public Single<? extends SMSSubmission> convert(@NonNull TrackedEntityInstance tei, String user, int submissionId) {
trackedEntityInstance = tei;
List<Enrollment> enrollments = TrackedEntityInstanceInternalAccessor.accessEnrollments(tei);
if (enrollments == null || enrollments.size() != 1) {
return Single.error(
new IllegalArgumentException("Given instance should have single enrollment")
);
}
List<TrackedEntityAttributeValue> attributeValues = tei.trackedEntityAttributeValues();
if (attributeValues == null) {
return Single.error(
new IllegalArgumentException("Given instance should contain attribute values list")
);
}
return Single.fromCallable(() -> {
Enrollment enrollment = enrollments.get(0);
EnrollmentSMSSubmission subm = new EnrollmentSMSSubmission();
subm.setSubmissionID(submissionId);
subm.setUserID(user);
subm.setEnrollment(enrollment.uid());
subm.setEnrollmentDate(enrollment.enrollmentDate());
subm.setEnrollmentStatus(ConverterUtils.convertEnrollmentStatus(enrollment.status()));
subm.setIncidentDate(enrollment.incidentDate());
subm.setOrgUnit(enrollment.organisationUnit());
subm.setTrackerProgram(enrollment.program());
subm.setTrackedEntityType(tei.trackedEntityType());
subm.setTrackedEntityInstance(enrollment.trackedEntityInstance());
if (GeometryHelper.containsAPoint(enrollment.geometry())) {
subm.setCoordinates(ConverterUtils.convertGeometryPoint(enrollment.geometry()));
}
ArrayList<SMSAttributeValue> values = new ArrayList<>();
for (TrackedEntityAttributeValue attr : attributeValues) {
values.add(createAttributeValue(attr.trackedEntityAttribute(), attr.value()));
}
subm.setValues(values);
List<Event> events = EnrollmentInternalAccessor.accessEvents(enrollments.get(0));
if (events != null) {
ArrayList<SMSEvent> smsEvents = new ArrayList<>();
for (Event event : events) {
smsEvents.add(createSMSEvent(event));
}
subm.setEvents(smsEvents);
}
return subm;
});
}
@Override
public Completable updateSubmissionState(State state) {
return getLocalDbRepository().updateEnrollmentSubmissionState(trackedEntityInstance, state);
}
@Override
public Single<TrackedEntityInstance> readItemFromDb() {
return getLocalDbRepository().getTeiEnrollmentToSubmit(enrollmentUid);
}
private SMSAttributeValue createAttributeValue(String attribute, String value) {
return new SMSAttributeValue(attribute, value);
}
private SMSEvent createSMSEvent(Event e) {
SMSEvent smsEvent = new SMSEvent();
smsEvent.setAttributeOptionCombo(e.attributeOptionCombo());
smsEvent.setProgramStage(e.programStage());
smsEvent.setEvent(e.uid());
smsEvent.setEventStatus(ConverterUtils.convertEventStatus(e.status()));
smsEvent.setEventDate(e.eventDate());
smsEvent.setDueDate(e.dueDate());
smsEvent.setOrgUnit(e.organisationUnit());
smsEvent.setValues(ConverterUtils.convertDataValues(e.attributeOptionCombo(), e.trackedEntityDataValues()));
if (GeometryHelper.containsAPoint(e.geometry())) {
smsEvent.setCoordinates(ConverterUtils.convertGeometryPoint(e.geometry()));
}
return smsEvent;
}
}
| 42.055118 | 119 | 0.699307 |
eac2a3a883a7c8c65be12d5826ffb5b61b7d79ea | 782 | package co.casterlabs.caffeinated.updater.animations;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import co.casterlabs.caffeinated.updater.util.FileUtil;
import lombok.SneakyThrows;
public class PrideAnimation extends DialogAnimation {
private BufferedImage prideImage;
@SneakyThrows
public PrideAnimation() {
this.prideImage = ImageIO.read(FileUtil.loadResourceAsUrl("animation_assets/pride.png"));
}
@Override
public void paintOnBackground(Graphics2D g2d) {
g2d.drawImage(this.prideImage, 0, 0, null);
}
@Override
public boolean shouldShowCasterlabsBanner() {
return false;
}
@Override
public String getIcon() {
return "pride.png";
}
}
| 22.342857 | 97 | 0.716113 |
3b2da521eb684b36eb699bcaabc33d6481b9962b | 166 | package com.hcl.library.dao.generics;
import com.hcl.library.model.Loan;
public interface ILoanDao extends IGenericDao <Loan> {
public Loan findById(int id);
}
| 16.6 | 54 | 0.76506 |
c2d1c114e3cd9e50c0806b31fe8112b3fc9399bf | 661 | /*
* Copyright 2017-2018, Strimzi authors.
* License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html).
*/
package io.strimzi.operator.cluster.model;
/**
* Enum for ImagePullPolicy types. Supports the 3 types supported in Kubernetes / OpenShift:
* - Always
* - Never
* - IfNotPresent
*/
public enum ImagePullPolicy {
ALWAYS("Always"),
IFNOTPRESENT("IfNotPresent"),
NEVER("Never");
private final String imagePullPolicy;
ImagePullPolicy(String imagePullPolicy) {
this.imagePullPolicy = imagePullPolicy;
}
public String toString() {
return imagePullPolicy;
}
}
| 23.607143 | 101 | 0.686838 |
0f59ca2de97d13b2e720a0749140119ce554e4e3 | 664 | package com.jz.nebula.dao.sku;
import com.jz.nebula.entity.sku.SkuAttributeCategory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
public interface SkuAttributeCategoryRepository extends PagingAndSortingRepository<SkuAttributeCategory, Long> {
@Query("select c from SkuAttributeCategory c where lower(c.name) like %?1%")
Page<SkuAttributeCategory> findByNameContaining(@Param("keyword") String keyword, Pageable pageable);
}
| 47.428571 | 112 | 0.831325 |
bcca2aaec4c80520098b614ef73e291620f5d145 | 306 | package tigerworkshop.webapphardwarebridge.interfaces;
public interface WebSocketServerInterface {
void onDataReceived(String channel, String message);
void subscribe(WebSocketServiceInterface service, String channel);
void unsubscribe(WebSocketServiceInterface service, String channel);
}
| 27.818182 | 72 | 0.820261 |
7ed3ac9632cd357997015af8864032293446c0e7 | 4,950 | package com.huifer.hibernatebook.bean;
import com.huifer.hibernatebook.utils.HibernateUtils;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
/**
* 描述:
*
* @author huifer
* @date 2019-02-11
*/
public class HqlTest {
@Test
public void demo1() {
Session session = HibernateUtils.getCurrentSession();
Transaction tx = session.beginTransaction();
Customer customer = new Customer();
customer.setCust_name("dc");
for (int i = 0; i < 10; i++) {
LinkMan linkMan = new LinkMan();
linkMan.setLkm_name("jm" + i);
customer.getLinkMans().add(linkMan);
session.save(linkMan);
}
session.save(customer);
tx.commit();
}
/**
* HQL 简单查询
*/
@Test
public void demo2() {
Session session = HibernateUtils.getCurrentSession();
Transaction tx = session.beginTransaction();
Query from_customer_ = session.createQuery("from Customer ");
List<Customer> list = from_customer_.list();
for (Customer customer : list) {
System.out.println(customer);
}
tx.commit();
}
/**
* 排序查询
*/
@Test
public void demo3() {
Session session = HibernateUtils.getCurrentSession();
Transaction tx = session.beginTransaction();
// List<Customer> customer1 = session.createQuery("from Customer order by cust_id desc ").list();
List<Customer> customer1 = session.createQuery("from Customer order by cust_id asc ").list();
for (Customer customer : customer1) {
System.out.println(customer);
}
tx.commit();
}
/**
* 条件
*/
@Test
public void demo4() {
Session session = HibernateUtils.getCurrentSession();
Transaction tx = session.beginTransaction();
Query query = session.createQuery("from Customer where cust_name = :cust_name ");
query.setParameter("cust_name", "ac");
List<Customer> customer1 = query.list();
for (Customer customer : customer1) {
System.out.println(customer);
}
tx.commit();
}
/**
* 投影查询
*/
@Test
public void demo5() {
Session session = HibernateUtils.getCurrentSession();
Transaction tx = session.beginTransaction();
Query query = session.createQuery("SELECT cust_name,cust_id FROM Customer ");
List list = query.list();
System.out.println(list);
// 在实体类中编写构造方法,构造方法参数为你需要查询的属性
Query query1 = session.createQuery("SELECT new Customer (cust_name) from Customer ");
List list1 = query1.list();
System.out.println(list1);
tx.commit();
}
/**
* 分页查询
*/
@Test
public void demo6() {
Session session = HibernateUtils.getCurrentSession();
Transaction tx = session.beginTransaction();
Query query = session.createQuery("FROM LinkMan ");
query.setFirstResult(0);
query.setMaxResults(10);
List list = query.list();
for (Object o : list) {
System.out.println(o);
}
tx.commit();
}
/**
* 分组查询
*/
@Test
public void demo7() {
Session session = HibernateUtils.getCurrentSession();
Transaction tx = session.beginTransaction();
Query query = session.createQuery("SELECT l.lkm_name, COUNT(*) FROM LinkMan as l GROUP BY l.customer");
List<Object[]> list = query.list();
for (Object[] o : list) {
System.out.println(Arrays.toString(o));
}
tx.commit();
}
/**
* Hql多表查询 内连接
*/
@Test
public void demo8() {
Session session = HibernateUtils.getCurrentSession();
Transaction tx = session.beginTransaction();
Query query = session.createQuery("FROM Customer c inner join c.linkMans");
List<Object[]> list = query.list();
for (Object[] o : list) {
System.out.println(Arrays.toString(o));
}
System.out.println("--------------------------------");
// fetch 会将数据整合 迫切内连接
Query query1 = session.createQuery("select distinct c FROM Customer c inner join fetch c.linkMans");
List<Customer> list1 = query1.list();
for (Customer o : list1) {
System.out.println(o);
}
tx.commit();
}
@Test
public void demo9() {
Session session = HibernateUtils.getCurrentSession();
Transaction tx = session.beginTransaction();
Query query = session.createQuery("FROM Customer c left join c.linkMans");
List<Object[]> list = query.list();
for (Object[] o : list) {
System.out.println(Arrays.toString(o));
}
tx.commit();
}
}
| 26.756757 | 111 | 0.580202 |
cdcb24150707b9ed0c49f52f248440e3ca0d885f | 365 | package com.trkj.framework.mybatisplus.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.trkj.framework.entity.mybatisplus.NoticeDept;
import org.apache.ibatis.annotations.Mapper;
/**
* <p>
* 公告部门表 Mapper 接口
* </p>
*
* @author 劉祁
* @since 2021-12-30
*/
@Mapper
public interface NoticeDeptMapper extends BaseMapper<NoticeDept> {
}
| 19.210526 | 66 | 0.753425 |
949e680efafaa74340a26906c28f5c018eb94894 | 8,604 | /*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright (c) 2008-2009, The KiWi Project (http://www.kiwi-project.eu)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the KiWi Project nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Contributor(s):
*
*
*/
package kiwi.action.revision;
import java.io.Serializable;
import kiwi.action.revision.style.StyleCreator;
import kiwi.api.render.RenderingService;
import kiwi.api.revision.CIVersionService;
import kiwi.api.revision.RevisionBean;
import kiwi.api.revision.RevisionService;
import kiwi.api.revision.UpdateTextContentService.PreviewStyle;
import kiwi.exception.ContentItemDoesNotExistException;
import kiwi.exception.VersionDoesNotExistException;
import kiwi.model.content.ContentItem;
import kiwi.model.content.MediaContent;
import kiwi.model.revision.MetadataUpdate;
import kiwi.model.revision.TaggingUpdate;
import org.jboss.seam.Component;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.log.Log;
/**
* @author Stephanie Stroka (sstroka@salzburgresearch.at)
*
*/
@Name("kiwi.action.revision.previewAction")
@Scope(ScopeType.CONVERSATION)
public class PreviewAction implements Serializable {
private static final long serialVersionUID = 5668835011461415359L;
@Logger
private static Log log;
@In(create=true)
private ContentItem currentContentItem;
private String previewContentHtml;
// @In(required=false)
private RevisionBean selectedRevision;
private String title;
private boolean showDeleted;
private String selectedStyle;
@In
private CIVersionService ciVersionService;
@In
private RevisionService revisionService;
@In
private RenderingService renderingPipeline;
/** metadataUpdate for that version **/
private MetadataUpdate metadataUpdate;
/** taggingUpdate for that version **/
private TaggingUpdate taggingUpdate;
/** mediaContentUpdate for that version **/
private MediaContent mediaContent;
private int indexRevision;
public void beginPreview(RevisionBean rev) {
StyleCreator styleCreator = (StyleCreator) Component.getInstance("kiwi.action.revision.style.styleCreator");
styleCreator.init();
styleCreator.generateStyle();
selectedRevision = rev;
long tmpid = selectedRevision.getVersion().getVersionId()+1;
if(tmpid < Integer.MAX_VALUE) {
indexRevision = (int) tmpid;
}
if(selectedRevision != null) {
title = selectedRevision.getTitle();
try {
if(selectedRevision.getPreviewContentHtml() == null) {
previewContentHtml = ciVersionService.createPreview(selectedRevision.getVersion(),
PreviewStyle.LAST, showDeleted);
previewContentHtml = renderingPipeline.renderHTML(previewContentHtml, currentContentItem);
} else {
previewContentHtml = selectedRevision.getPreviewContentHtml();
}
metadataUpdate = selectedRevision.getVersion().getMetadataUpdate();
taggingUpdate = selectedRevision.getVersion().getTaggingUpdate();
mediaContent = ciVersionService.getLastVersionMediaContent(
selectedRevision.getVersion());
log.debug("preview text: #0 ", previewContentHtml);
} catch (VersionDoesNotExistException e) {
log.error("Problem with viewing text content update: #0 ", e);
} catch (ContentItemDoesNotExistException e) {
log.error("Problem with viewing text content update: #0 ", e);
}
log.info("rendering html content: #0", previewContentHtml);
}
}
/**
* @return the previewContentHtml
*/
public String getPreviewContentHtml() {
log.info("getPreviewContentHtml: #0", previewContentHtml);
return previewContentHtml;
}
/**
* @param previewContentHtml the previewContentHtml to set
*/
public void setPreviewContentHtml(String previewContentHtml) {
log.info("setPreviewContentHtml: #0", previewContentHtml);
this.previewContentHtml = previewContentHtml;
}
/**
* @return the title
*/
public String getTitle() {
return title;
}
/**
* @param title the title to set
*/
public void setTitle(String title) {
this.title = title;
}
public String restore() {
if(selectedRevision == null) {
ViewRevisionsAction viewRevisionAction = (ViewRevisionsAction)
Component.getInstance("kiwi.action.revision.viewRevisionsAction");
selectedRevision = viewRevisionAction.getWikiRevisions()
.get(viewRevisionAction.getWikiRevisions().size() - indexRevision);
}
revisionService.restore(selectedRevision.getVersion().getRevision());
return "/wiki/home.xhtml";
}
/**
* @return the showDeleted
*/
public boolean isShowDeleted() {
return showDeleted;
}
/**
* @param showDeleted the showDeleted to set
*/
public void setShowDeleted(boolean showDeleted) {
// ViewRevisionsAction viewRevisionAction = (ViewRevisionsAction)
// Component.getInstance("kiwi.action.revision.viewRevisionsAction");
this.showDeleted = showDeleted;
// beginPreview(selectedRevision);
refresh();
}
public String refresh() {
beginPreview(selectedRevision);
return "/wiki/preview.xhtml";
}
/**
* @return the selectedStyle
*/
public String getSelectedStyle() {
return selectedStyle;
}
/**
* @param selectedStyle the selectedStyle to set
*/
public void setSelectedStyle(String selectedStyle) {
this.selectedStyle = selectedStyle;
}
/**
* @return the selectedRevision
*/
public RevisionBean getSelectedRevision() {
return selectedRevision;
}
/**
* @param selectedRevision the selectedRevision to set
*/
public void setSelectedRevision(RevisionBean selectedRevision) {
this.selectedRevision = selectedRevision;
}
/**
* @return the metadataUpdate
*/
public MetadataUpdate getMetadataUpdate() {
return metadataUpdate;
}
/**
* @param metadataUpdate the metadataUpdate to set
*/
public void setMetadataUpdate(MetadataUpdate metadataUpdate) {
this.metadataUpdate = metadataUpdate;
}
/**
* @return the taggingUpdate
*/
public TaggingUpdate getTaggingUpdate() {
return taggingUpdate;
}
/**
* @param taggingUpdate the taggingUpdate to set
*/
public void setTaggingUpdate(TaggingUpdate taggingUpdate) {
this.taggingUpdate = taggingUpdate;
}
/**
* @return the media content associated with this version
*/
public MediaContent getMediaContent() {
return mediaContent;
}
/**
* @param mediaContentUpdate the mediacontent associated with this version
*/
public void setMediaContent(MediaContent mediaContent) {
this.mediaContent = mediaContent;
}
/**
* @param indexRevision the indexRevision to set
*/
public void setIndexRevision(int indexRevision) {
ViewRevisionsAction viewRevisionAction = (ViewRevisionsAction)
Component.getInstance("kiwi.action.revision.viewRevisionsAction");
this.indexRevision = indexRevision;
selectedRevision = viewRevisionAction.getWikiRevisions()
.get(viewRevisionAction.getWikiRevisions().size() - indexRevision);
}
/**
* @return the indexRevision
*/
public int getIndexRevision() {
return indexRevision;
}
}
| 29.166102 | 110 | 0.748373 |
45788173c7bda4c0482de0604064079d2b5f5079 | 1,603 | package util;
import java.util.*;
public class SecurityConfig {
public static final String ROLE_ADMIN = "ADMIN";
public static final String ROLE_MANAGER = "MANAGER";
public static final String ROLE_DEVELOPER = "DEVELOPER";
// String: Role
// List<String>: urlPatterns.
private static final Map<String, List<String>> mapConfig = new HashMap<String, List<String>>();
static {
init();
}
private static void init() {
// Configure For "DEVELOPER" Role.
List<String> urlPatterns1 = new ArrayList<String>();
urlPatterns1.add("/task/*");
// urlPatterns1.add("/developer/*");
mapConfig.put(ROLE_DEVELOPER, urlPatterns1);
// Configure For "MANAGER" Role.
List<String> urlPatterns2 = new ArrayList<String>();
urlPatterns2.add("/task/*");
urlPatterns2.add("/task");
urlPatterns2.add("/team/*");
urlPatterns2.add("/team");
urlPatterns2.add("/developers");
urlPatterns2.add("/developers/*");
urlPatterns2.add("/user/manager");
mapConfig.put(ROLE_MANAGER, urlPatterns2);
// Configure For "ADMIN" Role.
List<String> urlPatterns3 = new ArrayList<String>();
urlPatterns3.add("/user");
urlPatterns3.add("/admin");
// urlPatterns3.add("/user/*");
mapConfig.put(ROLE_ADMIN, urlPatterns3);
}
public static Set<String> getAllAppRoles() {
return mapConfig.keySet();
}
public static List<String> getUrlPatternsForRole(String role) {
return mapConfig.get(role);
}
}
| 26.716667 | 99 | 0.618216 |
478c0eeefe83f28d51b15031f706c571b653c549 | 2,555 | package com.AppRH.AppRH.controllers;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import com.AppRH.AppRH.models.Empresa;
import com.AppRH.AppRH.repository.EmpresaRepository;
@Controller
public class EmpresaController {
@Autowired
private EmpresaRepository er;
@RequestMapping("/cadastrarEmpresa")
public String form() {
return "empresa/form-empresa";
};
@RequestMapping(value = "/cadastrarEmpresa", method = RequestMethod.POST)
public String form(@Valid Empresa empresa, BindingResult result, RedirectAttributes attributes) {
if(result.hasErrors()) {
attributes.addFlashAttribute("mensagem", "Verifique os campos");
return "redirect:/cadastrarEmpresa";
}
er.save(empresa);
attributes.addFlashAttribute("mensagem", "Empresa cadastrada com sucesso!");
return "redirect:/cadastrarEmpresa";
}
//Listar Empresa
public ModelAndView listaEmpresa() {
ModelAndView mv = new ModelAndView("empresa/lista-empresa");
Iterable<Empresa>empresa = er.findAll();
mv.addObject("empresa", empresa);
return mv;
}
// Mostra detalhes
@RequestMapping(value = "/empresa/{id}", method = RequestMethod.GET )
public ModelAndView detalheEmpresa(@PathVariable("id") long id) {
Empresa empresa = er.findById(id);
ModelAndView mv = new ModelAndView("empresa/update-empresa");
mv.addObject("empresa", empresa);
return mv;
}
//Altera dados da Empresa!
@RequestMapping("/editar-empresa")
public ModelAndView editarEmpresa(long id) {
Empresa empresa = er.findById(id);
ModelAndView mv = new ModelAndView("empresa/update-empresa");
mv.addObject("empresa", empresa);
return mv;
}
@RequestMapping(value = "/editar-empresa", method = RequestMethod.POST)
public String updateEmpresa(@Valid Empresa empresa, BindingResult result, RedirectAttributes attributes) {
er.save(empresa);
attributes.addFlashAttribute("success", "Empresa alterada com sucesso!");
long idLong = empresa.getId();
String id = "" + idLong;
return "redirect:/empresa/"+ id;
}
//Aqui que eu parei! olha VagaController! linha 114
}
| 27.180851 | 107 | 0.753816 |
9fd2c2613dfba4674504e10521a68f0339e8462f | 4,980 | /*
* 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.gate.varfuncs.functions;
import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.Option;
import net.minidev.json.JSONStyle;
import net.minidev.json.JSONValue;
import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.xpath.XPathAPI;
import org.apache.xpath.objects.XObject;
import org.gate.common.util.GateXMLUtils;
import org.gate.varfuncs.CompoundVariable;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerException;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
// @see org.apache.jmeter.functions.PackageTest for unit tests
/**
* The function represented by this class allows data to be read from XML files.
* Syntax is similar to the CVSRead function. The function allows the test to
* line-thru the nodes in the XML file - one node per each test. E.g. inserting
* the following in the test scripts :
* <p>
* ${_XPath(c:/BOF/abcd.xml,/xpath/)} // match the (first) node
* ${_XPath(c:/BOF/abcd.xml,/xpath/)} // Go to next match of '/xpath/' expression
* <p>
* NOTE: A single instance of each different file/expression combination
* is opened and used for all threads.
*
* @since 2.0.3
*/
public class JSONPath extends AbstractFunction {
private static final Logger log = LogManager.getLogger();
private static final String KEY = "__JSONPath"; // Function name //$NON-NLS-1$
private static final List<String> desc = new LinkedList<>();
private Object[] values; // Parameter list
static {
desc.add("JSON file to get values from"); //$NON-NLS-1$
desc.add("JSONPath expression to match against"); //$NON-NLS-1$
}
private static final Configuration DEFAULT_CONFIGURATION =
Configuration.defaultConfiguration().addOptions(Option.ALWAYS_RETURN_LIST);
public JSONPath() {
}
/**
* {@inheritDoc}
*/
@Override
public synchronized String executeRecursion()
throws InvalidVariableException {
String myValue = ""; //$NON-NLS-1$
String fileName = ((CompoundVariable) values[0]).execute();
String jsonPathString = ((CompoundVariable) values[1]).execute();
if (log.isDebugEnabled()) {
log.debug("execute (" + fileName + " " + jsonPathString + ") ");
}
try {
File file = new File(fileName);
if (file.exists() && file.canRead()) {
List<Object> extractedObjects = JsonPath.compile(jsonPathString).read(
FileUtils.readFileToString(new File(fileName), "UTF-8"), DEFAULT_CONFIGURATION);
if (!extractedObjects.isEmpty()) {
myValue = JSONValue.toJSONString(extractedObjects.get(0), JSONStyle.LT_COMPRESS);
}
} else {
log.warn("Could not read open: {} ", fileName);
}
} catch (IOException e) {
log.warn("Could not read file: {} {}", fileName, e.getMessage(), e);
}
if (log.isDebugEnabled()) {
log.debug("execute value: " + myValue);
}
return myValue;
}
/**
* {@inheritDoc}
*/
@Override
public List<String> getArgumentDesc() {
return desc;
}
/**
* {@inheritDoc}
*/
@Override
public String getReferenceKey() {
return KEY;
}
/**
* {@inheritDoc}
*/
@Override
public synchronized void setParameters(Collection<CompoundVariable> parameters) throws InvalidVariableException {
log.debug("setParameter - Collection.size=" + parameters.size());
values = parameters.toArray();
if (log.isDebugEnabled()) {
for (int i = 0; i < parameters.size(); i++) {
log.debug("i:" + ((CompoundVariable) values[i]).execute());
}
}
checkParameterCount(parameters, 2);
}
}
| 32.763158 | 117 | 0.658233 |
fcaf487966127cd0025c5c422f7dcd92f897eb30 | 8,504 | package sapphire.compiler;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.TreeSet;
import org.apache.harmony.rmi.compiler.RmicUtil;
public class PolicyStub extends Stub {
public PolicyStub(Class<?> cls) throws ClassNotFoundException {
super(cls);
}
@Override
public TreeSet<MethodStub> getMethods() {
TreeSet<MethodStub> ms = new TreeSet<MethodStub>();
Class<?> ancestorClass = stubClass;
while ((!ancestorClass.getSimpleName().equals("SapphireServerPolicyLibrary")) &&
(!ancestorClass.getSimpleName().equals("SapphireGroupPolicyLibrary"))) {
for (Method m : ancestorClass.getDeclaredMethods()) {
// Add public methods to methods vector
if (Modifier.isPublic(m.getModifiers())) {
ms.add(new MethodStub((Method) m));
}
}
ancestorClass = ancestorClass.getSuperclass();
}
return ms;
}
@Override
public String getPackageStatement() {
return ((packageName == null) ? "" //$NON-NLS-1$
: ("package " + GlobalStubConstants.getPolicyPackageName() + ';' + EOLN + EOLN)); //$NON-NLS-1$
}
@Override
public String getStubClassDeclaration() {
StringBuilder buffer = new StringBuilder("");
buffer.append("public final class " + stubName + " extends " + className + " implements ");
buffer.append("sapphire.kernel.common.KernelObjectStub"); //$NON-NLS-1$
buffer.append(" {" + EOLN + EOLN); //$NON-NLS-1$
return buffer.toString();
}
@Override
public String getStubFields() {
StringBuilder buffer = new StringBuilder();
buffer.append(indenter.indent() + "sapphire.kernel.common.KernelOID $__oid = null;" + EOLN);
buffer.append(indenter.indent() + "java.net.InetSocketAddress $__hostname = null;" + EOLN);
return buffer.toString();
}
@Override
public String getStubConstructors() {
StringBuilder buffer = new StringBuilder();
buffer.append(indenter.indent() + "public " + stubName + "(sapphire.kernel.common.KernelOID oid) {" + EOLN);
buffer.append(indenter.tIncrease() + "this.$__oid = oid;" + EOLN + indenter.indent() + "}" + EOLN);
return buffer.toString();
}
@Override
public String getStubAdditionalMethods() {
StringBuilder buffer = new StringBuilder();
/* Implementation for getKernelOID */
buffer.append(indenter.indent() + "public sapphire.kernel.common.KernelOID $__getKernelOID() {" + EOLN);
buffer.append(indenter.tIncrease() + "return this.$__oid;" + EOLN + indenter.indent() + "}" + EOLN + EOLN);
/* Implementation for getHostname */
buffer.append(indenter.indent() + "public java.net.InetSocketAddress $__getHostname() {" + EOLN);
buffer.append(indenter.tIncrease() + "return this.$__hostname;" + EOLN + indenter.indent() + "}" + EOLN + EOLN);
/* Implementation for updateHostname */
buffer.append(indenter.indent() + "public void $__updateHostname(java.net.InetSocketAddress hostname) {" + EOLN);
buffer.append(indenter.tIncrease() + "this.$__hostname = hostname;" + EOLN + indenter.indent() + "}" + EOLN + EOLN);
/* Implementation for makeRPC */
buffer.append(indenter.indent() + "public Object $__makeKernelRPC(java.lang.String method, java.util.ArrayList<Object> params) throws java.rmi.RemoteException, java.lang.Exception {" + EOLN);
buffer.append(indenter.tIncrease() + "sapphire.kernel.common.KernelRPC rpc = new sapphire.kernel.common.KernelRPC($__oid, method, params);" + EOLN);
buffer.append(indenter.tIncrease() + "try {" + EOLN);
buffer.append(indenter.tIncrease(2) + "return sapphire.kernel.common.GlobalKernelReferences.nodeServer.getKernelClient().makeKernelRPC(this, rpc);" + EOLN);
buffer.append(indenter.tIncrease() + "} catch (sapphire.kernel.common.KernelObjectNotFoundException e) {" + EOLN);
buffer.append(indenter.tIncrease(2) + "throw new java.rmi.RemoteException();" + EOLN);
buffer.append(indenter.tIncrease() + "}" + EOLN);
buffer.append(indenter.indent() + "}" + EOLN + EOLN);
/* Override $__initialize */
/*
buffer.append(indenter.indent() + "public void $__initialize(java.lang.String $param_String_1, java.util.ArrayList $param_ArrayList_2) { " + EOLN);
buffer.append(indenter.tIncrease() + "java.util.ArrayList<Object> $__params = new java.util.ArrayList<Object>();" + EOLN);
buffer.append(indenter.tIncrease() + "String $__method = \"$__initialize\";" + EOLN);
buffer.append(indenter.tIncrease() + "$__params.add($param_String_1);" + EOLN);
buffer.append(indenter.tIncrease() + "$__params.add($param_ArrayList_2);" + EOLN);
buffer.append(indenter.tIncrease() + "try {" + EOLN);
buffer.append(indenter.tIncrease(2) + "$__makeKernelRPC($__method, $__params);" + EOLN);
buffer.append(indenter.tIncrease() + "} catch (Exception e) {" +EOLN);
buffer.append(indenter.tIncrease(2) + "e.printStackTrace();" + EOLN);
buffer.append(indenter.tIncrease() + "}" +EOLN);
buffer.append(indenter.indent() + "}" + EOLN + EOLN);
*/
/* Override the other $__initialize */
/*
buffer.append(indenter.indent() + "public void $__initialize(sapphire.common.AppObject $param_AppObject_1) { " + EOLN);
buffer.append(indenter.tIncrease() + "java.util.ArrayList<Object> $__params = new java.util.ArrayList<Object>();" + EOLN);
buffer.append(indenter.tIncrease() + "String $__method = \"$__initialize\";" + EOLN);
buffer.append(indenter.tIncrease() + "$__params.add($param_AppObject_1);" + EOLN);
buffer.append(indenter.tIncrease() + "try {" + EOLN);
buffer.append(indenter.tIncrease(2) + "$__makeKernelRPC($__method, $__params);" + EOLN);
buffer.append(indenter.tIncrease() + "} catch (Exception e) {" +EOLN);
buffer.append(indenter.tIncrease(2) + "e.printStackTrace();" + EOLN);
buffer.append(indenter.tIncrease() + "}" +EOLN);
buffer.append(indenter.indent() + "}" + EOLN + EOLN);
*/
/* Override equals */
buffer.append(indenter.indent() + "@Override" + EOLN);
buffer.append(indenter.indent() + "public boolean equals(Object obj) { " + EOLN);
buffer.append(indenter.tIncrease() + stubName + " other = (" + stubName + ") obj;" + EOLN);
buffer.append(indenter.tIncrease() + "if (! other.$__oid.equals($__oid))" + EOLN);
buffer.append(indenter.tIncrease(2) + "return false;" + EOLN);
buffer.append(indenter.tIncrease() + "return true;" + EOLN);
buffer.append(indenter.indent() + "}" + EOLN);
/* Override hashCode */
buffer.append(indenter.indent() + "@Override" + EOLN);
buffer.append(indenter.indent() + "public int hashCode() { " + EOLN);
buffer.append(indenter.tIncrease() + "return $__oid.getID();" + EOLN);
buffer.append(indenter.indent() + "}" + EOLN);
return buffer.toString();
}
/**
* Returns the stub implementation code section source for this method
*
* @return Stub implementation code for this method.
*/
@Override
public String getMethodContent(MethodStub m) {
StringBuilder buffer = new StringBuilder("");
// Construct list of parameters and String holding the method name
// to call KernelObjectStub.makeRPC
buffer.append(indenter.indent() + "java.util.ArrayList<Object> $__params = new java.util.ArrayList<Object>();" + EOLN); //$NON-NLS-1$
buffer.append(indenter.indent() + "String $__method = \"" + m.genericName + "\";" + EOLN); //$NON-NLS-1$
if (m.numParams > 0) {
// Write invocation parameters.
// TODO: primitive types ??
for (int i = 0; i < m.numParams; i++) {
buffer.append(indenter.indent() + "$__params.add(" + m.paramNames[i]+");" + EOLN);
}
}
// Write return statement.
buffer.append(indenter.indent() + "java.lang.Object $__result = null;" + EOLN);
buffer.append(indenter.indent() + "try {" + EOLN);
buffer.append(indenter.tIncrease() + "$__result = $__makeKernelRPC($__method, $__params);" + EOLN); //$NON-NLS-1$ //$NON-NLS-2$
buffer.append(indenter.indent() + "} catch (Exception e) {" + EOLN); //$NON-NLS-1$ //$NON-NLS-2$
buffer.append(indenter.tIncrease() + "e.printStackTrace();" + EOLN); //$NON-NLS-1$
buffer.append(indenter.indent() + "}" + EOLN); //$NON-NLS-1$
if (!m.retType.getSimpleName().equals("void")) {
buffer.append(indenter.indent() + "return " //$NON-NLS-1$
+ RmicUtil.getReturnObjectString(m.retType, "$__result")
+ ';' + EOLN);
}
return buffer.toString();
}
}
| 48.045198 | 193 | 0.659337 |
cf3b131d8e94d069d8a89ba7d7b6f25d8d28d17b | 4,092 | package ca.uwaterloo.sh6choi.korea101r.fragments.numbers;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.Date;
import java.util.Random;
import ca.uwaterloo.sh6choi.korea101r.R;
import ca.uwaterloo.sh6choi.korea101r.activities.MainActivity;
import ca.uwaterloo.sh6choi.korea101r.fragments.DrawerFragment;
import ca.uwaterloo.sh6choi.korea101r.utils.NumberUtils;
/**
* Created by Samson on 2015-11-02.
*/
public class TimeFragment extends Fragment implements DrawerFragment, View.OnClickListener {
private static final String TAG = TimeFragment.class.getCanonicalName();
private static final String FRAGMENT_TAG = MainActivity.TAG + ".fragment.numbers.time";
protected int mCurHour = -1;
protected int mCurMinute = -1;
protected TextView mNumberTextView;
protected EditText mInputEditText;
protected Button mCheckButton;
public static TimeFragment getInstance(Bundle args) {
TimeFragment fragment = new TimeFragment();
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
setHasOptionsMenu(false);
View contentView = inflater.inflate(R.layout.fragment_numbers, container, false);
return contentView;
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mNumberTextView = (TextView) view.findViewById(R.id.number_text_view);
mNumberTextView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
mInputEditText = (EditText) view.findViewById(R.id.input_edit_text);
mInputEditText.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
mCheckButton = (Button) view.findViewById(R.id.check_button);
mCheckButton.setOnClickListener(this);
switchNumber();
}
@Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.check_button:
String answer = NumberUtils.getCountForm(mCurHour) + "시";
if (mCurMinute > 0) {
answer = answer.concat(NumberUtils.getSinoKoreanNumber(mCurMinute) + "분");
}
if (TextUtils.equals(mInputEditText.getText().toString().replace(" ", ""), answer)) {
switchNumber();
} else {
mInputEditText.setError("Incorrect");
}
break;
}
}
private void switchNumber() {
Random random = new Random(new Date().getTime());
int nextHour;
int nextMinute;
do {
nextHour = random.nextInt(12) + 1;
nextMinute = random.nextInt(60);
} while (nextHour == mCurHour && nextMinute == mCurMinute);
mCurHour = nextHour;
mCurMinute = nextMinute;
mNumberTextView.setText(String.format(getString(R.string.time_format), mCurHour, mCurMinute));
mInputEditText.setText("");
mInputEditText.setError(null);
}
@Override
public String getFragmentTag() {
return FRAGMENT_TAG;
}
@Override
public int getTitleStringResId() {
return R.string.time;
}
@Override
public boolean shouldShowUp() {
return true;
}
@Override
public boolean shouldAddToBackstack() {
return false;
}
@Override
public boolean onBackPressed() {
Intent intent = new Intent(getActivity(), MainActivity.class);
intent.setAction(MainActivity.ACTION_NUMBERS_TIME);
startActivity(intent);
return true;
}
}
| 30.311111 | 123 | 0.671554 |
25a164a22355ffd6bb89fc5f07f40e5e9c90cdc0 | 6,631 | package com.smile.taobaodemo.widget;
import android.app.DialogFragment;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import com.smile.taobaodemo.R;
import com.smile.taobaodemo.base.Constant;
import com.smile.taobaodemo.bean.Address;
import com.smile.taobaodemo.bean.SeedsInfo;
import com.smile.taobaodemo.bean.logisticsInfo;
import com.smile.taobaodemo.ui.activity.MainActivity;
import com.smile.taobaodemo.ui.activity.SucessActivity;
import com.smile.taobaodemo.ui.fragment.AttachDialogFragment;
import com.smile.taobaodemo.ui.fragment.NavWeFragment;
import com.smile.taobaodemo.utils.ToastUtil;
import com.xiasuhuei321.loadingdialog.view.LoadingDialog;
import java.util.List;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.QueryListener;
import cn.bmob.v3.listener.UpdateListener;
public class AddressDialog extends AttachDialogFragment implements View.OnClickListener {
private EditText edit_name;
private EditText edit_phone;
private EditText edit_address;
private Button reap;
boolean flag = false;
private LoadingDialog load;
Address address;
private final Handler mHandler = new Handler();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(DialogFragment.STYLE_NO_FRAME, R.style.MyMiddleDialogStyle);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE); //无标题
getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
View view = inflater.inflate(R.layout.address_dialog,container);
edit_address = (EditText) view.findViewById(R.id.link_address);
edit_name = (EditText) view.findViewById(R.id.link_name);
edit_phone = (EditText) view.findViewById(R.id.link_phpne);
reap = (Button) view.findViewById(R.id.link_ok);
load = setLoad(load);
reap.setOnClickListener(this);
getAdress();
return view;
}
@Override
public void onStart() {
super.onStart();
int dialogHeight = (int) (mContext.getResources().getDisplayMetrics().heightPixels * 0.5);
int dialogWidth = (int) (mContext.getResources().getDisplayMetrics().widthPixels * 0.85);
getDialog().getWindow().setLayout(dialogWidth,dialogHeight);
getDialog().setCanceledOnTouchOutside(true); //点击边际可消失
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.link_ok:
if(edit_address.length() >0 && edit_phone.length()==11 && edit_name.length() >0){
if(address == null){
address.setAddress(edit_address.getText().toString());
address.setName(edit_name.getText().toString());
address.setPhone(edit_phone.getText().toString());
address.setUserId(Constant.USER.getObjectId());
address.save();
}
reap();
dismiss();
}else {
ToastUtil.showShortToast(getActivity(),"请仔细检查输入是否有误"+edit_address.getTextSize()+" "+edit_phone.getTextSize()+" "+edit_name.getTextSize());
}
}
}
public void getAdress(){
BmobQuery<Address> query = new BmobQuery<>();
query.addWhereEqualTo("userId", Constant.USER.getObjectId());
query.findObjects(new FindListener<Address>() {
@Override
public void done(List<Address> list, BmobException e) {
if(e == null){
if(list.size()>0){
address = list.get(0);
ToastUtil.showShortToast(getActivity(),"系统自动为您填写上次保存的收货地址");
edit_name.setText(address.getName());
edit_phone.setText(address.getPhone());
edit_address.setText(address.getAddress());
flag = true;
}else {
ToastUtil.showShortToast(getActivity(),"系统检测到您是第一次收货,在收货完成后会为您自动保存本次地址");
}
}else {
ToastUtil.showShortToast(getActivity(),"出现错误:"+e.getMessage());
}
}
});
}
public void reap(){
load.show();
final SeedsInfo info = new SeedsInfo();
info.setObjectId(getTag());
BmobQuery<SeedsInfo> bmobQuery = new BmobQuery<SeedsInfo>();
bmobQuery.getObject(info.getObjectId(), new QueryListener<SeedsInfo>() {
@Override
public void done(SeedsInfo seedsInfo, BmobException e) {
if(e == null){
final logisticsInfo logisticsInfo = new logisticsInfo();
logisticsInfo.setUserId(Constant.USER.getObjectId());
logisticsInfo.setLogisticsName(seedsInfo.getSeedName());
logisticsInfo.setNum(""+seedsInfo.getSeedArea());
logisticsInfo.setLogisticsNum("稍后为您发货");
logisticsInfo.setUrl(seedsInfo.getUrl());
seedsInfo.delete(new UpdateListener() {
@Override
public void done(BmobException e) {
if(e == null){
logisticsInfo.save();
load.loadSuccess();
}else {
load.loadFailed();
}
}
});
}
}
});
}
private LoadingDialog setLoad(LoadingDialog load){
load = new LoadingDialog(getActivity());
load.setLoadingText("正在收获...");
load.setSuccessText("收获成功");//显示加载成功时的文字
load.setFailedText("收获失败");
load.setLoadSpeed(LoadingDialog.Speed.SPEED_TWO);
return load;
}
}
| 35.843243 | 163 | 0.60926 |
ddd9bc51d284db03332604ffdd60b2c885a9cb5d | 3,388 | package com.denizenscript.denizen.objects.properties.item;
import com.denizenscript.denizen.objects.ItemTag;
import com.denizenscript.denizencore.objects.Mechanism;
import com.denizenscript.denizencore.objects.core.ListTag;
import com.denizenscript.denizencore.objects.ObjectTag;
import com.denizenscript.denizencore.objects.properties.Property;
import com.denizenscript.denizencore.tags.Attribute;
import org.bukkit.Material;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
public class ItemFlags implements Property {
public static boolean describes(ObjectTag item) {
// All items can have flags
return item instanceof ItemTag && ((ItemTag) item).getItemStack().getType() != Material.AIR;
}
public static ItemFlags getFrom(ObjectTag _item) {
if (!describes(_item)) {
return null;
}
else {
return new ItemFlags((ItemTag) _item);
}
}
public static final String[] handledTags = new String[] {
"flags"
};
public static final String[] handledMechs = new String[] {
"flags"
};
private ItemFlags(ItemTag _item) {
item = _item;
}
public ListTag flags() {
ListTag output = new ListTag();
ItemStack itemStack = item.getItemStack();
if (itemStack.hasItemMeta()) {
for (ItemFlag flag : itemStack.getItemMeta().getItemFlags()) {
output.add(flag.name());
}
}
return output;
}
ItemTag item;
@Override
public ObjectTag getObjectAttribute(Attribute attribute) {
if (attribute == null) {
return null;
}
// <--[tag]
// @attribute <ItemTag.flags>
// @returns ListTag
// @mechanism ItemTag.flags
// @group properties
// @description
// Returns a list of flags set on this item.
// Valid flags include: HIDE_ATTRIBUTES, HIDE_DESTROYS, HIDE_ENCHANTS, HIDE_PLACED_ON, HIDE_POTION_EFFECTS, and HIDE_UNBREAKABLE
// NOTE: 'HIDE_POTION_EFFECTS' also hides banner patterns.
// -->
if (attribute.startsWith("flags")) {
return flags()
.getObjectAttribute(attribute.fulfill(1));
}
return null;
}
@Override
public String getPropertyString() {
ListTag flags = flags();
if (flags.size() > 0) {
return flags().identify();
}
else {
return null;
}
}
@Override
public String getPropertyId() {
return "flags";
}
@Override
public void adjust(Mechanism mechanism) {
// <--[mechanism]
// @object ItemTag
// @name flags
// @input ListTag
// @description
// Sets the item's meta flag set.
// @tags
// <ItemTag.flags>
// -->
if (mechanism.matches("flags")) {
ItemMeta meta = item.getItemStack().getItemMeta();
meta.removeItemFlags(ItemFlag.values());
ListTag new_flags = mechanism.valueAsType(ListTag.class);
for (String str : new_flags) {
meta.addItemFlags(ItemFlag.valueOf(str.toUpperCase()));
}
item.getItemStack().setItemMeta(meta);
}
}
}
| 27.544715 | 136 | 0.594746 |
8c7355dda8c75dc78d9a39f5b4b7eaa4bc2f4f30 | 2,771 | package me.onenrico.holoblock.database.sql;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import org.bukkit.scheduler.BukkitRunnable;
import me.onenrico.holoblock.database.Datamanager;
import me.onenrico.holoblock.main.Core;
import me.onenrico.holoblock.utils.MessageUT;
public class SQLite extends Database {
public static String dbname;
public SQLite(Core instance) {
super(instance);
dbname = "database";
HashMap<String, String> map = new HashMap<>();
map.put("Location", "varchar(255)");
map.put("Owner", "TEXT");
map.put("Lines", "TEXT");
map.put("Members", "TEXT");
map.put("Offset", "double");
map.put("Skin", "TEXT");
map.put("Rotation", "TEXT");
map.put("Particle", "TEXT");
SQLiteCreateTokensTable = generateToken("Location", map);
}
public String generateToken(String indexer, HashMap<String, String> map) {
String result = "CREATE TABLE IF NOT EXISTS " + table + " (";
int index = 0;
for (String key : map.keySet()) {
index++;
if (index >= map.keySet().size()) {
result += "`" + key + "` " + map.get(key) + " NOT NULL";
} else {
result += "`" + key + "` " + map.get(key) + " NOT NULL,";
}
}
// result += ",PRIMARY KEY (`Key`)";
// result += ");";
result += ",PRIMARY KEY (`" + indexer + "`));";
return result;
}
public String SQLiteCreateTokensTable = "";
@Override
public Connection getSQLConnection() {
File dataFolder = new File(Core.getThis().getDataFolder() + "/data/");
File dataFile = new File(Core.getThis().getDataFolder() + "/data/", dbname + ".db");
if (!dataFolder.exists()) {
try {
dataFolder.mkdir();
dataFile.createNewFile();
} catch (IOException e) {
MessageUT.debug("File write error: " + dbname + ".db");
}
}
try {
if (connection != null && !connection.isClosed()) {
return connection;
}
Class.forName("org.sqlite.JDBC");
connection = DriverManager.getConnection("jdbc:sqlite:" + dataFile);
return connection;
} catch (SQLException ex) {
MessageUT.debug("G: SQLite exception on initialize");
} catch (ClassNotFoundException ex) {
MessageUT.debug("H: SQLite exception on initialize");
}
return null;
}
@Override
public void load() {
connection = getSQLConnection();
try {
Statement s = connection.createStatement();
s.executeUpdate(SQLiteCreateTokensTable);
s.close();
} catch (SQLException e) {
e.printStackTrace();
}
initialize(new BukkitRunnable() {
@Override
public void run() {
Datamanager.loadHolo();
}
});
}
}
| 27.989899 | 87 | 0.63118 |
e64b7635f9c85cab56ba6dc31fb7d50cb4df09a5 | 2,781 | package net.wasdev.wlp.maven.test.app;
import static org.junit.Assert.*;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.Properties;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;
import org.apache.maven.shared.invoker.DefaultInvocationRequest;
import org.apache.maven.shared.invoker.DefaultInvoker;
import org.apache.maven.shared.invoker.InvocationOutputHandler;
import org.apache.maven.shared.invoker.InvocationRequest;
import org.apache.maven.shared.invoker.InvocationResult;
import org.apache.maven.shared.invoker.Invoker;
import org.junit.Test;
import org.w3c.dom.Document;
/**
*
* libertySettingsFolder test case
*
*/
public class LibertySettingsDirectoryTest {
@Test
public void testLibertyConfigDirValidDir() throws Exception {
File f1 = new File("liberty/etc", "repository.properties");
assertTrue(f1.getCanonicalFile() + " doesn't exist", f1.exists());
}
@Test
public void testLibertyConfigDirInvalidDir() throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
File pomFilePath = new File("../pom.xml");
Document pomFile = builder.parse(pomFilePath);
pomFile.getDocumentElement().normalize();
XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();
String pomVersion = xpath.evaluate("/project/build/plugins/plugin[artifactId='liberty-maven-plugin']/version", pomFile);
Properties props = new Properties();
props.put("pluginVersion", pomVersion);
InvocationRequest request = new DefaultInvocationRequest()
.setPomFile( new File("../src/test/resources/invalidDirPom.xml"))
.setGoals( Collections.singletonList("package"))
.setProperties(props);
InvocationOutputHandler outputHandler = new InvocationOutputHandler(){
@Override
public void consumeLine(String line) throws IOException {
if (line.contains("<libertySettingsFolder> must be a directory")) {
throw new IOException("Caught expected MojoExecutionException - " + line);
}
}
};
Invoker invoker = new DefaultInvoker();
invoker.setOutputHandler(outputHandler);
InvocationResult result = invoker.execute( request );
assertTrue("Exited successfully, expected non-zero exit code.", result.getExitCode() != 0);
assertNotNull("Expected MojoExecutionException to be thrown.", result.getExecutionException());
}
} | 36.116883 | 128 | 0.711255 |
e49da18edfe8724fa0c41589a299392227bf3c53 | 756 | package com.springcloud.demo.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
/**
* @author
* @Description: 文件描述
* @Author:
* @Version:
* @Date 2021/8/19 14:50
*/
@RestController
public class ProviderHaController {
@Value("${server.port}")
private int serverPort;
@GetMapping(value = "hello")
public String hello(HttpServletRequest request) {
String requestURL = request.getRequestURL().toString();
System.out.println(requestURL);
return "ProviderHaController:" + serverPort + ",requestURL=" + requestURL;
}
}
| 25.2 | 82 | 0.72619 |
dd6bb27c290e9eeab8f31d1c2f69f0736913491f | 10,904 | /**
* 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.sqoop.connector.jdbc;
import static org.testng.AssertJUnit.assertNull;
import org.apache.sqoop.common.MutableContext;
import org.apache.sqoop.common.MutableMapContext;
import org.apache.sqoop.common.SqoopException;
import org.apache.sqoop.connector.jdbc.configuration.FromJobConfiguration;
import org.apache.sqoop.connector.jdbc.configuration.LinkConfiguration;
import org.apache.sqoop.etl.io.DataWriter;
import org.apache.sqoop.job.etl.Extractor;
import org.apache.sqoop.job.etl.ExtractorContext;
import org.apache.sqoop.schema.Schema;
import org.apache.sqoop.schema.type.Date;
import org.apache.sqoop.schema.type.Decimal;
import org.apache.sqoop.schema.type.FixedPoint;
import org.apache.sqoop.schema.type.Text;
import org.joda.time.LocalDate;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.Assert.fail;
public class TestExtractor {
private final String tableName;
private final String nullDataTableName;
private GenericJdbcExecutor executor;
private static final int START = -50;
private static final int NUMBER_OF_ROWS = 101;
private static final double EPSILON = 0.01;
public TestExtractor() {
tableName = getClass().getSimpleName().toUpperCase();
nullDataTableName = getClass().getSimpleName().toUpperCase() + "NULL";
}
@BeforeMethod(alwaysRun = true)
public void setUp() {
executor = new GenericJdbcExecutor(GenericJdbcTestConstants.LINK_CONFIG);
if (!executor.existTable(tableName)) {
executor.executeUpdate("CREATE TABLE "
+ executor.delimitIdentifier(tableName)
+ "(ICOL INTEGER PRIMARY KEY, DCOL DOUBLE, VCOL VARCHAR(20), DATECOL DATE)");
for (int i = 0; i < NUMBER_OF_ROWS; i++) {
int value = START + i;
String sql = "INSERT INTO " + executor.delimitIdentifier(tableName)
+ " VALUES(" + value + ", " + value + ", '" + value + "', '2004-10-19')";
executor.executeUpdate(sql);
}
}
}
@AfterMethod(alwaysRun = true)
public void tearDown() {
executor.close();
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test
public void testQuery() throws Exception {
MutableContext context = new MutableMapContext();
LinkConfiguration linkConfig = new LinkConfiguration();
linkConfig.linkConfig.jdbcDriver = GenericJdbcTestConstants.DRIVER;
linkConfig.linkConfig.connectionString = GenericJdbcTestConstants.URL;
FromJobConfiguration jobConfig = new FromJobConfiguration();
context.setString(GenericJdbcConnectorConstants.CONNECTOR_JDBC_FROM_DATA_SQL,
"SELECT * FROM " + executor.delimitIdentifier(tableName) + " WHERE ${CONDITIONS}");
GenericJdbcPartition partition;
Extractor extractor = new GenericJdbcExtractor();
DummyWriter writer = new DummyWriter();
Schema schema = new Schema("TestExtractor");
// dummy columns added, all we need is the column count to match to the
// result set
schema.addColumn(new FixedPoint("c1",2L, true)).addColumn(new Decimal("c2", 5, 2)).addColumn(new Text("c3")).addColumn(new Date("c4"));
ExtractorContext extractorContext = new ExtractorContext(context, writer, schema);
partition = new GenericJdbcPartition();
partition.setConditions("-50.0 <= DCOL AND DCOL < -16.6666666666666665");
extractor.extract(extractorContext, linkConfig, jobConfig, partition);
partition = new GenericJdbcPartition();
partition.setConditions("-16.6666666666666665 <= DCOL AND DCOL < 16.666666666666667");
extractor.extract(extractorContext, linkConfig, jobConfig, partition);
partition = new GenericJdbcPartition();
partition.setConditions("16.666666666666667 <= DCOL AND DCOL <= 50.0");
extractor.extract(extractorContext, linkConfig, jobConfig, partition);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void testSubquery() throws Exception {
MutableContext context = new MutableMapContext();
LinkConfiguration linkConfig = new LinkConfiguration();
linkConfig.linkConfig.jdbcDriver = GenericJdbcTestConstants.DRIVER;
linkConfig.linkConfig.connectionString = GenericJdbcTestConstants.URL;
FromJobConfiguration jobConfig = new FromJobConfiguration();
context.setString(GenericJdbcConnectorConstants.CONNECTOR_JDBC_FROM_DATA_SQL,
"SELECT SQOOP_SUBQUERY_ALIAS.ICOL,SQOOP_SUBQUERY_ALIAS.VCOL,SQOOP_SUBQUERY_ALIAS.DATECOL FROM " + "(SELECT * FROM "
+ executor.delimitIdentifier(tableName) + " WHERE ${CONDITIONS}) SQOOP_SUBQUERY_ALIAS");
GenericJdbcPartition partition;
Extractor extractor = new GenericJdbcExtractor();
DummyWriter writer = new DummyWriter();
Schema schema = new Schema("TestExtractor");
// dummy columns added, all we need is the column count to match to the
// result set
schema.addColumn(new FixedPoint("c1", 2L, true)).addColumn(new Text("c2")).addColumn(new Date("c3"));
ExtractorContext extractorContext = new ExtractorContext(context, writer, schema);
partition = new GenericJdbcPartition();
partition.setConditions("-50 <= ICOL AND ICOL < -16");
extractor.extract(extractorContext, linkConfig, jobConfig, partition);
partition = new GenericJdbcPartition();
partition.setConditions("-16 <= ICOL AND ICOL < 17");
extractor.extract(extractorContext, linkConfig, jobConfig, partition);
partition = new GenericJdbcPartition();
partition.setConditions("17 <= ICOL AND ICOL < 50");
extractor.extract(extractorContext, linkConfig, jobConfig, partition);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test(expectedExceptions = SqoopException.class)
public void testIncorrectSchemaColumnSize() throws Exception {
MutableContext context = new MutableMapContext();
LinkConfiguration linkConfig = new LinkConfiguration();
linkConfig.linkConfig.jdbcDriver = GenericJdbcTestConstants.DRIVER;
linkConfig.linkConfig.connectionString = GenericJdbcTestConstants.URL;
FromJobConfiguration jobConfig = new FromJobConfiguration();
context.setString(
GenericJdbcConnectorConstants.CONNECTOR_JDBC_FROM_DATA_SQL,
"SELECT SQOOP_SUBQUERY_ALIAS.ICOL,SQOOP_SUBQUERY_ALIAS.VCOL FROM " + "(SELECT * FROM "
+ executor.delimitIdentifier(tableName) + " WHERE ${CONDITIONS}) SQOOP_SUBQUERY_ALIAS");
GenericJdbcPartition partition = new GenericJdbcPartition();
Extractor extractor = new GenericJdbcExtractor();
DummyWriter writer = new DummyWriter();
Schema schema = new Schema("TestIncorrectColumns");
ExtractorContext extractorContext = new ExtractorContext(context, writer, schema);
partition.setConditions("-50 <= ICOL AND ICOL < -16");
extractor.extract(extractorContext, linkConfig, jobConfig, partition);
}
@Test
public void testNullValueExtracted() throws Exception {
if (!executor.existTable(nullDataTableName)) {
executor.executeUpdate("CREATE TABLE " + executor.delimitIdentifier(nullDataTableName)
+ "(ICOL INTEGER PRIMARY KEY, DCOL DOUBLE, VCOL VARCHAR(20), DATECOL DATE)");
for (int i = 0; i < NUMBER_OF_ROWS; i++) {
int value = i;
String sql = "INSERT INTO " + executor.delimitIdentifier(nullDataTableName) + " VALUES(" + value + ",null,null,null)";
executor.executeUpdate(sql);
}
}
MutableContext context = new MutableMapContext();
LinkConfiguration linkConfig = new LinkConfiguration();
linkConfig.linkConfig.jdbcDriver = GenericJdbcTestConstants.DRIVER;
linkConfig.linkConfig.connectionString = GenericJdbcTestConstants.URL;
FromJobConfiguration jobConfig = new FromJobConfiguration();
context.setString(GenericJdbcConnectorConstants.CONNECTOR_JDBC_FROM_DATA_SQL,
"SELECT * FROM " + executor.delimitIdentifier(nullDataTableName) + " WHERE ${CONDITIONS}");
Extractor extractor = new GenericJdbcExtractor();
DummyNullDataWriter writer = new DummyNullDataWriter();
Schema schema = new Schema("TestExtractor");
schema.addColumn(new FixedPoint("c1",2L, true)).addColumn(new Decimal("c2", 5, 2)).addColumn(new Text("c3")).addColumn(new Date("c4"));
ExtractorContext extractorContext = new ExtractorContext(context, writer, schema);
GenericJdbcPartition partition = new GenericJdbcPartition();
partition.setConditions("-50 <= ICOL AND ICOL < -16");
extractor.extract(extractorContext, linkConfig, jobConfig, partition);
}
public class DummyWriter extends DataWriter {
int indx = START;
@Override
public void writeArrayRecord(Object[] array) {
boolean parsedDate = false;
for (int i = 0; i < array.length; i++) {
if (array[i] instanceof Integer) {
assertEquals(indx, ((Integer) array[i]).intValue());
} else if (array[i] instanceof Double) {
assertEquals((double)indx, ((Double)array[i]).doubleValue(), EPSILON);
} else if (array[i] instanceof String) {
assertEquals(String.valueOf(indx), array[i].toString());
} else if (array[i] instanceof LocalDate) {
assertEquals("2004-10-19", array[i].toString());
parsedDate = true;
}
}
indx++;
assertEquals(true, parsedDate);
}
@Override
public void writeStringRecord(String text) {
fail("This method should not be invoked.");
}
@Override
public void writeRecord(Object content) {
fail("This method should not be invoked.");
}
}
public class DummyNullDataWriter extends DataWriter {
@Override
public void writeArrayRecord(Object[] array) {
for (int i = 0; i < array.length; i++) {
// primary key cant be null
if (i > 0) {
assertNull(array[i]);
}
}
}
@Override
public void writeStringRecord(String text) {
fail("This method should not be invoked.");
}
@Override
public void writeRecord(Object content) {
fail("This method should not be invoked.");
}
}
} | 38.530035 | 139 | 0.719369 |
f793e5b9d9711158687b2110cdd5c65453537be6 | 7,134 | /* Generated by Together */
package jneat;
/* Generated by Together */
/* Generated by Together */
/* Generated by Together */
/* Generated by Together */
/* Generated by Together */
/* Generated by Together */
/* Generated by Together */
/* Generated by Together */
/* Generated by Together */
/* Generated by Together */
/* Generated by Together */
/* Generated by Together */
/** Organisms are Genomes and Networks with fitness information i.e. The genotype and phenotype together */
public class Organism extends Neat {
/** A measure of fitness for the Organism */
double fitness;
/** A fitness measure that won't change during adjustments */
double orig_fitness;
/** Used just for reporting purposes */
double error;
/** Win marker (if needed for a particular task) */
public boolean winner;
/** The Organism's phenotype */
public Network net;
/** The Organism's genotype */
public Genome genome;
/** The Organism's Species */
Species species;
/** Number of children this Organism may have */
double expected_offspring;
/** Tells which generation this Organism is from */
int generation;
/** Marker for destruction of inferior Organisms */
boolean eliminate;
/** Marks the species champ */
boolean champion;
/** Number of reserved offspring for a population leader */
int super_champ_offspring;
/** Marks the best in population */
boolean pop_champ;
/** Marks the duplicate child of a champion (for tracking purposes) */
boolean pop_champ_child;
/** DEBUG variable- high fitness of champ */
double high_fit;
/** has a change in a structure of baby ? */
boolean mut_struct_baby;
/** has a mating in baby ? */
boolean mate_baby;
public double getFitness() {
return fitness;
}
public void setFitness(double fitness) {
this.fitness = fitness;
}
public double getOrig_fitness() {
return orig_fitness;
}
public void setOrig_fitness(double orig_fitness) {
this.orig_fitness = orig_fitness;
}
public double getError() {
return error;
}
public void setError(double error) {
this.error = error;
}
public boolean getWinner() {
return winner;
}
public void setWinner(boolean winner) {
this.winner = winner;
}
public Network getNet() {
return net;
}
public void setNet(Network net) {
this.net = net;
}
public Species getSpecies() {
return species;
}
public void setSpecies(Species species) {
this.species = species;
}
public double getExpected_offspring() {
return expected_offspring;
}
public void setExpected_offspring(double expected_offspring) {
this.expected_offspring = expected_offspring;
}
public int getGeneration() {
return generation;
}
public void setGeneration(int generation) {
this.generation = generation;
}
public boolean getEliminate() {
return eliminate;
}
public void setEliminate(boolean eliminate) {
this.eliminate = eliminate;
}
public boolean getChampion() {
return champion;
}
public void setChampion(boolean champion) {
this.champion = champion;
}
public int getSuper_champ_offspring() {
return super_champ_offspring;
}
public void setSuper_champ_offspring(int super_champ_offspring) {
this.super_champ_offspring = super_champ_offspring;
}
public boolean getPop_champ() {
return pop_champ;
}
public void setPop_champ(boolean pop_champ) {
this.pop_champ = pop_champ;
}
public boolean getPop_champ_child() {
return pop_champ_child;
}
public void setPop_champ_child(boolean pop_champ_child) {
this.pop_champ_child = pop_champ_child;
}
public double getHigh_fit() {
return high_fit;
}
public void setHigh_fit(double high_fit) {
this.high_fit = high_fit;
}
public boolean getMut_struct_baby() {
return mut_struct_baby;
}
public void setMut_struct_baby(boolean mut_struct_baby) {
this.mut_struct_baby = mut_struct_baby;
}
public boolean getMate_baby() {
return mate_baby;
}
public void setMate_baby(boolean mate_baby) {
this.mate_baby = mate_baby;
}
/**
*
*
*/
public Organism(double xfitness, Genome xgenome, int xgeneration)
{
fitness = xfitness;
orig_fitness = xfitness;
genome = xgenome;
net = genome.genesis(xgenome.genome_id);
species = null;
expected_offspring = 0;
generation = xgeneration;
eliminate = false;
error = 0;
winner = false;
champion = false;
super_champ_offspring = 0;
pop_champ = false;
pop_champ_child = false;
high_fit = 0;
mut_struct_baby = false;
mate_baby = false;
}
public Genome getGenome() {
return genome;
}
public void setGenome(Genome genome) {
this.genome = genome;
}
/**
*
*
*/
public void viewtext()
{
System.out.print("\n-ORGANISM -[genomew_id=" + genome.genome_id + "]");
System.out.print(" Champ(" + champion + ")");
System.out.print(", fit=" + fitness);
System.out.print(", Elim=" + eliminate);
System.out.print(", offspring=" + expected_offspring);
}
} | 28.086614 | 108 | 0.486263 |
883eff102db7656881882d223e119b49f139c37a | 1,494 | package com.legocms.web.controller.admin;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import com.legocms.core.dto.sys.SysSiteInfo;
import com.legocms.core.dto.sys.SysUserInfo;
import com.legocms.core.exception.BusinessException;
import com.legocms.core.web.session.SessionController;
import com.legocms.service.sys.ISysUserService;
public class AdminController extends SessionController {
@Autowired
private ISysUserService userService;
protected SysUserInfo getUser() {
return getAttribute(AdminView.USER_SESSION_KEY);
}
protected void setUser(SysUserInfo user) {
setAttribute(AdminView.USER_SESSION_KEY, user);
}
protected String getUserCode() {
return getUser().getCode();
}
protected void refreshUser() {
SysUserInfo user = userService.findBy(getUserCode());
setUser(user);
setSite(user.getSite());
}
protected void setSite(SysSiteInfo site) {
setAttribute(AdminView.SITE_SESSION_KEY, site);
}
protected SysSiteInfo getSite() {
return getAttribute(AdminView.SITE_SESSION_KEY);
}
protected String getSiteCode() {
SysSiteInfo site = getSite();
BusinessException.check(site != null, "当前无管理站点,请先选择管理站点!");
return site.getCode();
}
protected List<String> getPermissionCodes() {
return getUser().getPermissions();
}
}
| 27.163636 | 68 | 0.680054 |
98abcf5c1e144dc4dca64a58c79b484d45385fdd | 5,875 | package com.amoveo.amoveowallet;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.WindowManager;
import com.amoveo.amoveowallet.common.CacheBean;
import com.amoveo.amoveowallet.fragments.AccessWalletFragment;
import com.amoveo.amoveowallet.fragments.BaseFragment;
import com.amoveo.amoveowallet.presenters.SendPresenter;
import com.amoveo.amoveowallet.presenters.listeners.OnQRScanListener;
import com.amoveo.amoveowallet.toolbars.GoBackListener;
import com.amoveo.amoveowallet.utils.HLog;
import com.aurelhubert.ahbottomnavigation.AHBottomNavigation;
import com.crashlytics.android.Crashlytics;
import io.fabric.sdk.android.Fabric;
import java.io.File;
import java.io.FileWriter;
import static com.amoveo.amoveowallet.api.APIManager.API;
import static com.amoveo.amoveowallet.common.Settings.SETTINGS;
import static com.amoveo.amoveowallet.common.WalletContext.WALLET;
import static com.amoveo.amoveowallet.engine.Engine.ENGINE;
import static com.amoveo.amoveowallet.presenters.operations.LoadCacheOperation.loadCache;
import static com.amoveo.amoveowallet.presenters.operations.LoadContentOperation.loadContent;
import static com.amoveo.amoveowallet.presenters.operations.LoadWordListOperation.loadWordList;
import static com.amoveo.amoveowallet.utils.Utils.GSON;
public class RootActivity extends AppCompatActivity {
private static final String TAG = RootActivity.class.getName();
private static final String TAG_CONTAINER = "container";
private static final String TAG_NAVIGABLE = "navigable";
private OnQRScanListener mQrScanListener;
private AHBottomNavigation mBottomNavigation;
private GoBackListener mGoBackListener;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.root_view);
Fabric.with(this, new Crashlytics());
API.init(this);
start();
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
}
@Override
public void onBackPressed() {
if (null != mGoBackListener) {
GoBackListener listener = mGoBackListener;
mGoBackListener = null;
listener.onNavigationClick();
} else {
super.onBackPressed();
}
}
@Override
protected void onRestart() {
super.onRestart();
start();
}
private void start() {
SETTINGS.expand();
SETTINGS.setCacheFile(new File(getFilesDir(), "cache.json"));
SETTINGS.setContentFile(new File(getFilesDir(), "cws.json"));
ENGINE.restart();
loadWordList(this);
if (SETTINGS.getContentFile().exists()) {
loadCache(this);
loadContent(this, false);
} else {
show(AccessWalletFragment.newInstance());
}
}
@Override
protected void onStop() {
super.onStop();
ENGINE.shutdown();
}
private static final String UNREADABLE = "";
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
synchronized (SETTINGS) {
try {
FileWriter fileWriter = new FileWriter(SETTINGS.getCacheFile());
fileWriter.write(GSON.toJson(new CacheBean()));
fileWriter.close();
} catch (Exception e) {
HLog.error(TAG, "writeContent", e);
}
}
SETTINGS.notifyCollapseTime();
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (null != mQrScanListener && mQrScanListener.onActivityResult(requestCode, resultCode, data)) {
super.onActivityResult(requestCode, resultCode, data);
}
}
public void setOnQRScanListener(OnQRScanListener qrScanListener) {
mQrScanListener = qrScanListener;
}
public void show(final BaseFragment fragment) {
show(fragment, R.id.container, TAG_CONTAINER);
}
public void showNavigable(final BaseFragment fragment) {
show(fragment, R.id.navigable, TAG_NAVIGABLE);
}
private synchronized void show(final BaseFragment fragment, int containerId, String tag) {
FragmentManager fragmentManager = getSupportFragmentManager();
if (null != fragmentManager && !fragmentManager.isDestroyed()) {
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
if (null == fragmentManager.findFragmentByTag(tag)) {
fragmentTransaction.add(containerId, fragment, tag);
} else {
fragmentTransaction.replace(containerId, fragment, tag);
}
fragmentTransaction.commit();
}
}
public void dropWallet() {
SETTINGS.setPin(new byte[]{0});
SETTINGS.notifyPinAttempt(true);
WALLET.dropWallet();
SendPresenter.clear();
SETTINGS.setContentFile(updateFile(SETTINGS.getContentFile(), "cws.json"));
SETTINGS.setCacheFile(updateFile(SETTINGS.getCacheFile(), "cache.json"));
show(AccessWalletFragment.newInstance());
}
private File updateFile(File file, String fileName) {
if (null != file && file.exists()) {
file.delete();
}
return new File(getFilesDir(), fileName);
}
public void setGoBackListener(GoBackListener listener) {
mGoBackListener = listener;
}
public void setBottomNavigation(AHBottomNavigation bottomNavigation) {
mBottomNavigation = bottomNavigation;
}
public void setCurrentItem(int position) {
mBottomNavigation.setCurrentItem(position);
}
} | 32.821229 | 105 | 0.690043 |
f053cc597a8c917368087189024661142a7828a9 | 417 | package net.take.blip;
public final class Constants {
public static final String DEFAULT_DOMAIN = "msging.net";
public static final String DEFAULT_SCHEME = "net.tcp";
public static final String DEFAULT_HOST_NAME = "tcp.msging.net";
public static final int DEFAULT_PORT = 443;
public static final String POSTMASTER = "postmaster";
public static final String DEFAULT_STATE = "default";
}
| 24.529412 | 68 | 0.731415 |
b311c0d5959d02a815cd12b9116fcff1d969f43a | 261 | //TYPE_LINKING
/**
* Same package precedes on-demand import in type-linking =>
* On-demand imports are not ambiguous.
*/
import foo.Foo;
public class Main {
public Main() {}
public static int test() {
Foo foo = new Foo();
return foo.method();
}
}
| 15.352941 | 60 | 0.655172 |
75a513606aa57e00202823656d580d52e0bbeeaa | 7,685 | /**
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.waveprotocol.wave.client.paging;
import junit.framework.TestCase;
import org.waveprotocol.wave.client.paging.Traverser.Point;
import org.waveprotocol.wave.client.paging.Traverser.SimplePoint;
/**
* Tests for {@link Traverser} based on random tree structures and locations.
*
*/
public final class RandomizedTraverserTest extends TestCase {
/** Size of the block tree being tested. */
private int size;
/** Root of tree. */
private Block root;
/**
* Builds the random tree.
*
* @param seed seed for randomizer
* @param size number of blocks to build in the tree
*/
private void setUp(int seed, int size) {
this.size = size;
this.root = RandomTreeBuilder.create().withSeed(seed).withZeroBlockProbability(0.3).build(size);
}
/**
* Runs tests for the four locating methods in {@link Traverser}.
*/
private void doTest() {
// Test an even distribution of 2.size + 2 points over the range:
// [start - E, end + E]
double start = root.getStart() - 20;
double end = root.getEnd() + 20;
int count = size * 2 + 2;
testStartWithin(start, end, count);
testEndWithin(start, end, count);
testStartAfter(start, end, count);
testEndBefore(start, end, count);
}
/**
* For an even distribution of {@code count} positions over the range {@code
* [start, end]}, tests {@link Traverser#locateStartWithin(Block, double)}
* against a trivial brute-force implementation.
*/
private void testStartWithin(double start, double end, double count) {
for (int i = 0; i < count; i++) {
double position = start + i * (end - start) / (count - 1);
Point expected = locateStartWithin(root, position);
Point actual = Traverser.locateStartWithin(root, position);
assertEquals(expected, actual);
}
}
/**
* For an even distribution of {@code count} positions over the range {@code
* [start, end]}, tests {@link Traverser#locateEndWithin(Block, double)}
* against a trivial brute-force implementation.
*/
private void testEndWithin(double start, double end, int count) {
for (int i = 0; i < count; i++) {
double position = start + i * (end - start) / (count - 1);
Point expected = locateEndWithin(root, position);
Point actual = Traverser.locateEndWithin(root, position);
assertEquals(expected, actual);
}
}
/**
* For the cross product of even distributions of {@code count} positions and
* {@code count} points over the range {@code [start, end]}, tests
* {@link Traverser#locateStartAfter(Point, double)} against a trivial
* brute-force implementation.
*/
private void testStartAfter(double start, double end, int count) {
for (int i = 0; i < count; i++) {
double position = start + i * (end - start) / (count - 1);
Point reference = locateEndWithin(root, position);
if (reference != null) {
testStartAfter(reference, start, end, count);
}
}
}
/**
* For the cross product of even distributions of {@code count} positions and
* {@code count} points over the range {@code [start, end]}, tests
* {@link Traverser#locateEndBefore(Point, double)} against a trivial
* brute-force implementation.
*/
private void testEndBefore(double start, double end, int count) {
for (int i = 0; i < count; i++) {
double position = start + i * (end - start) / (count - 1);
Point reference = locateStartWithin(root, position);
if (reference != null) {
testEndBefore(reference, start, end, count);
}
}
}
/**
* For an even distribution of {@code count} points over the range {@code
* [start, end]}, tests {@link Traverser#locateStartAfter(Point, double)}
* against a trivial brute-force implementation.
*/
private void testStartAfter(Point ref, double start, double end, double count) {
for (int i = 0; i < count; i++) {
double position = start + i * (end - start) / (count - 1);
// expected = null means exception expected.
Point expected = ref.absoluteLocation() < position ? locateStartWithin(root, position) : null;
Point actual;
try {
actual = Traverser.locateStartAfter(ref, position);
assertNotNull(actual);
} catch (IllegalArgumentException e) {
actual = null;
}
assertEquals(expected, actual);
}
}
/**
* For an even distribution of {@code count} points over the range {@code
* [start, end]}, tests {@link Traverser#locateEndBefore(Point, double)}
* against a trivial brute-force implementation.
*/
private void testEndBefore(Point ref, double start, double end, double count) {
for (int i = 0; i < count; i++) {
double position = start + i * (end - start) / (count - 1);
// expected = null means exception expected.
Point expected = ref.absoluteLocation() > position ? locateEndWithin(root, position) : null;
Point actual;
try {
actual = Traverser.locateEndBefore(ref, position);
assertNotNull(actual);
} catch (IllegalArgumentException e) {
actual = null;
}
assertEquals(expected, actual);
}
}
/** @return the rightmost point in a tree that is strictly before a position. */
private Point locateStartWithin(Block block, double position) {
return locateStartBefore(SimplePoint.startOf(block), position);
}
/** @return the leftmost point in a tree that is strictly after a position. */
private Point locateEndWithin(Block block, double position) {
return locateEndAfter(SimplePoint.endOf(block), position);
}
/**
* @return the rightmost point in a tree, at or after a reference, that is
* strictly before a position.
*/
private Point locateStartBefore(Point ref, double position) {
SimpleMoveablePoint point = SimpleMoveablePoint.at(ref);
if (point.absoluteLocation() >= position) {
return null;
} else {
while (point.absoluteLocation() < position) {
if (point.hasNext()) {
point.next();
} else {
return point;
}
}
point.previous();
return point;
}
}
/**
* @return the leftmost point in a tree, at or before a reference, that is
* strictly after a position.
*/
private Point locateEndAfter(Point ref, double position) {
SimpleMoveablePoint point = SimpleMoveablePoint.at(ref);
if (point.absoluteLocation() <= position) {
return null;
} else {
while (point.absoluteLocation() > position) {
if (point.hasPrevious()) {
point.previous();
} else {
return point;
}
}
// Backtrack one.
point.next();
return point;
}
}
public void testRandom1() {
setUp(1, 10);
doTest();
}
public void testRandom2() {
setUp(2, 20);
doTest();
}
public void testRandom3() {
setUp(3, 1);
doTest();
}
public void testRandom4() {
setUp(4, 10);
doTest();
}
public void testRandom5() {
setUp(5, 30);
doTest();
}
}
| 31.11336 | 100 | 0.64177 |
23f352095300660e0703861d2b96a96ba3bde835 | 4,839 | /*
* Copyright (C) 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 fathom.xmlrpc;
import com.google.common.base.Optional;
import com.google.common.base.Strings;
import com.google.inject.Inject;
import fathom.authc.StandardCredentials;
import fathom.authc.TokenCredentials;
import fathom.exception.StatusCodeException;
import fathom.realm.Account;
import fathom.rest.Context;
import fathom.rest.security.AuthConstants;
import fathom.security.SecurityManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import ro.pippo.core.route.RouteHandler;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
/**
* @author James Moger.
*/
public abstract class XmlRpcRouteHandler implements RouteHandler<Context> {
private final static String TEXT_XML = "text/xml";
private final Logger log = LoggerFactory.getLogger(XmlRpcRouteHandler.class);
private final XmlRpcMethodRegistrar xmlRpcMethodRegistrar;
@Inject
private SecurityManager securityManager;
@Inject
public XmlRpcRouteHandler(XmlRpcMethodRegistrar xmlRpcMethodRegistrar) {
this.xmlRpcMethodRegistrar = xmlRpcMethodRegistrar;
}
@Override
public void handle(Context context) {
if ("POST".equals(context.getRequestMethod())) {
if (!context.getContentTypes().contains(TEXT_XML)) {
log.warn("{} request from {} did not specify {}, ignoring",
context.getRequestUri(), context.getRequest().getClientIp(), TEXT_XML);
context.next();
return;
}
try {
authenticate(context);
byte[] result;
try (InputStream is = context.getRequest().getHttpServletRequest().getInputStream()) {
XmlRpcRequest request = new XmlRpcRequest();
request.parse(is);
XmlRpcResponse response = new XmlRpcResponse(xmlRpcMethodRegistrar);
result = response.process(request);
}
context.getResponse().ok().contentType(TEXT_XML).contentLength(result.length);
try (OutputStream output = context.getResponse().getOutputStream()) {
output.write(result);
output.flush();
}
} catch (Exception e) {
log.error("Failed to handle XML-RPC request", e);
context.getResponse().internalError().commit();
}
} else {
throw new StatusCodeException(405, "Only POST is supported!");
}
}
protected void authenticate(Context context) {
Account session = context.getSession(AuthConstants.ACCOUNT_ATTRIBUTE);
Account local = context.getLocal(AuthConstants.ACCOUNT_ATTRIBUTE);
Account account = Optional.fromNullable(session).or(Optional.fromNullable(local).or(Account.GUEST));
if (account.isGuest()) {
String authorization = context.getRequest().getHeader("Authorization");
if (!Strings.isNullOrEmpty(authorization)) {
if (authorization.toLowerCase().startsWith("token")) {
String packet = authorization.substring("token".length()).trim();
TokenCredentials credentials = new TokenCredentials(packet);
account = securityManager.authenticate(credentials);
} else if (authorization.toLowerCase().startsWith("basic")) {
String packet = authorization.substring("basic".length()).trim();
String credentials1 = new String(Base64.getDecoder().decode(packet), StandardCharsets.UTF_8);
String[] values1 = credentials1.split(":", 2);
String username = values1[0];
String password = values1[1];
StandardCredentials authenticationToken = new StandardCredentials(username, password);
account = securityManager.authenticate(authenticationToken);
}
}
}
account = Optional.fromNullable(account).or(Account.GUEST);
context.setLocal(AuthConstants.ACCOUNT_ATTRIBUTE, account);
}
}
| 39.663934 | 113 | 0.648894 |
15d60ba142986639f143035076c59c46ac2ccac4 | 627 | package org.vitrivr.cineast.core.util;
import java.util.List;
import org.vitrivr.cineast.core.data.LongDoublePair;
public class RankUtil {
private RankUtil(){}
public static int getRankOfShot(List<LongDoublePair> resultList, long id, int notFoundValue){
int _return = notFoundValue;
int i = 0;
for(LongDoublePair ldp : resultList){
++i;
if(ldp.key == id){
_return = i;
break;
}
}
return _return;
}
public static float getInvertedRank(List<LongDoublePair> resultList, long id){
int rank = getRankOfShot(resultList, id, -1);
if(rank == -1){
return 0f;
}
return 1f / rank;
}
}
| 19 | 94 | 0.682616 |
7a259f1edf48e1153091b676730b054574ae768e | 2,379 | // Copyright (C) 2018 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.googlesource.gerrit.plugins.its.base.workflow;
import com.google.common.base.Strings;
import com.google.inject.Inject;
import java.util.Arrays;
import java.util.Map;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AddPropertyToFieldParametersExtractor {
private static final Logger log =
LoggerFactory.getLogger(AddPropertyToFieldParametersExtractor.class);
@Inject
public AddPropertyToFieldParametersExtractor() {}
/**
* @return The parameters needed to perform an AddPropertyToField action. Empty if the parameters
* could not be extracted.
*/
public Optional<AddPropertyToFieldParameters> extract(
ActionRequest actionRequest, Map<String, String> properties) {
String[] parameters = actionRequest.getParameters();
if (parameters.length != 2) {
log.error(
"Wrong number of received parameters. Received parameters are {}. Exactly two parameters are expected. The first one is the ITS field id, the second one is the event property id",
Arrays.toString(parameters));
return Optional.empty();
}
String propertyId = parameters[0];
if (Strings.isNullOrEmpty(propertyId)) {
log.error("Received property id is blank");
return Optional.empty();
}
String fieldId = parameters[1];
if (Strings.isNullOrEmpty(fieldId)) {
log.error("Received field id is blank");
return Optional.empty();
}
if (!properties.containsKey(propertyId)) {
log.error("No event property found for id {}", propertyId);
return Optional.empty();
}
String propertyValue = properties.get(propertyId);
return Optional.of(new AddPropertyToFieldParameters(propertyValue, fieldId));
}
}
| 34.985294 | 189 | 0.726776 |
4ea2182359071a149ba8ad0caa74354a3dc196f9 | 1,578 | package net.wolfesoftware.jax.codegen;
import java.io.*;
import net.wolfesoftware.jax.ast.*;
import net.wolfesoftware.jax.semalysis.Semalysization;
public class CodeGenerator
{
public static void generate(Semalysization semalysization, String sourceFile, String classPath) throws FileNotFoundException
{
new CodeGenerator(semalysization.root, sourceFile, classPath).generateCode();
}
private final Root root;
private final String sourceFile;
private final String classPath;
public CodeGenerator(Root root, String sourceFile, String classPath)
{
this.root = root;
this.sourceFile = sourceFile;
this.classPath = classPath;
}
private void generateCode() throws FileNotFoundException
{
genCompilationUnit(root.content);
}
private void genCompilationUnit(CompilationUnit compilationUnit) throws FileNotFoundException
{
genClassDeclaration(compilationUnit.classDeclaration);
}
private void genClassDeclaration(ClassDeclaration classDeclaration) throws FileNotFoundException
{
ClassFile classFile = ClassFile.generate(sourceFile, classDeclaration);
String outputFilename = classPath + '/' + classDeclaration.localType.getTypeName() + ".class";
DataOutputStream out = new DataOutputStream(new FileOutputStream(outputFilename));
classFile.write(out);
try {
out.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
| 32.875 | 129 | 0.688847 |
e2c30c0c99677d4ad0c9041fd2c0eafcf8862cd7 | 1,772 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package analyse;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.json.simple.parser.ParseException;
/**
*
* @author antoi
*/
public class Analyse {
/**
* @param args the command line arguments
* @throws java.io.IOException
* @throws java.io.FileNotFoundException
* @throws org.json.simple.parser.ParseException
*/
public static void main(String[] args) throws IOException, FileNotFoundException, ParseException {
/*Utilisation du programme :
Créer les paramètres du patient en accord avec le médecin.
Créer une mesure du type que l'on souhaite analyser. Ne pas oublier de vérifier si la clef correspond à celle dans le fichier
Pour utiliser le programme, il suffit de lancer la fonction miseAjour(Parametres p)
*/
Parametres p = new Parametres();
BpmMicro m = new BpmMicro("Données","BPDataList");
Poids po = new Poids("DonnéesPoids","WeightDataList");
for (int i = 0; i < 1000; i++) {
m.miseAjour(p);
po.miseAjour(p);
}
Alerte a = new Alerte();
String chaineA="";
Gravite gravite = new Gravite("alerteSystem.txt");
int am = gravite.niveauAlerte(gravite.getAlertes().get(0).getDate(),gravite.getAlertes().get(gravite.getAlertes().size()-1).getDate(),chaineA);
chaineA=chaineA+am;
long d = System.currentTimeMillis();
a.transmissionAlerte(chaineA, d);
}
}
| 32.814815 | 152 | 0.626411 |
fbf8f0942696df389be561bff7b47cd30616f3d9 | 1,685 | package unimelb.mf.ssh.plugin.services;
import java.util.Collection;
import arc.mf.plugin.PluginTask;
import arc.xml.XmlDoc.Element;
import arc.xml.XmlWriter;
import io.github.xtman.ssh.client.Connection;
import io.github.xtman.ssh.client.SftpClient;
import io.github.xtman.ssh.client.TransferClient.GetHandler;
import io.github.xtman.util.PathUtils;
public class SvcSftpGet extends AbstractSshGetService {
public static final String SERVICE_NAME = "unimelb.sftp.get";
public SvcSftpGet() {
}
@Override
protected void execute(Connection cxn, Collection<String> paths, String namespace, GetHandler gh, Element args,
Inputs inputs, Outputs outputs, XmlWriter w, OnError onError) throws Throwable {
PluginTask.checkIfThreadTaskAborted();
SftpClient sftp = cxn.createSftpClient();
try {
for (String path : paths) {
PluginTask.checkIfThreadTaskAborted();
String parent = PathUtils.getParent(path);
String name = PathUtils.getLastComponent(path);
if (parent != null) {
sftp.setRemoteBaseDirectory(parent);
} else {
sftp.setRemoteBaseDirectory(Connection.DEFAULT_REMOTE_BASE_DIRECTORY);
}
get(sftp, name, gh, onError.retry(), onError.stopOnError(), w);
}
} finally {
sftp.close();
}
}
@Override
public String description() {
return "Get files from remote server to sepcified asset namespace via SFTP.";
}
@Override
public String name() {
return SvcSftpGet.SERVICE_NAME;
}
}
| 29.051724 | 115 | 0.642136 |
363887f325f4a9fbc08be3e113fb720c94b5f382 | 1,914 | package com.chenshun.test.hadoop.io;
import org.apache.hadoop.io.Writable;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
/**
* User: mew <p />
* Time: 18/2/27 13:41 <p />
* Version: V1.0 <p />
* Description: <p />
*/
public class UserWritable implements Writable {
private int id;
private String name;
public UserWritable() {
}
public UserWritable(int id, String name) {
this.set(id, name);
}
public void set(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void write(DataOutput out) throws IOException {
out.writeInt(id);
out.writeUTF(name);
}
public void readFields(DataInput in) throws IOException {
this.id = in.readInt();
this.name = in.readUTF();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
UserWritable other = (UserWritable) obj;
if (id != other.id) {
return false;
}
if (name == null) {
return other.name == null;
} else {
return name.equals(other.name);
}
}
@Override
public String toString() {
return id + "\t" + name;
}
}
| 19.9375 | 73 | 0.524556 |
126ca15e03c98f307ba68016072c958f47741f81 | 522 | package kg.apc.jmeter.jmxmon.rmi;
import java.io.IOException;
import java.util.Map;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorProvider;
import javax.management.remote.JMXServiceURL;
import kg.apc.jmeter.jmxmon.JMXConnectorEmul;
public class ClientProvider implements JMXConnectorProvider {
@Override
public JMXConnector newJMXConnector(JMXServiceURL serviceURL, Map<String, ?> environment) throws IOException {
return new JMXConnectorEmul();
}
}
| 26.1 | 112 | 0.791188 |
dbeaa9719260fc77e5076a23854514c53b10c05f | 1,347 | package au.com.mineauz.minigames.events;
import au.com.mineauz.minigames.objects.CTFFlag;
import au.com.mineauz.minigames.objects.MinigamePlayer;
import au.com.mineauz.minigames.minigame.Minigame;
public class TakeFlagEvent extends AbstractMinigameEvent {
private CTFFlag flag = null;
private String flagName = null;
private boolean displayMessage = true;
private MinigamePlayer player;
public TakeFlagEvent(Minigame minigame, MinigamePlayer player, CTFFlag flag) {
this(minigame, player, flag, null);
}
public TakeFlagEvent(Minigame minigame, MinigamePlayer player, String flagName) {
this(minigame, player, null, flagName);
}
public TakeFlagEvent(Minigame minigame, MinigamePlayer player, CTFFlag flag, String flagName) {
super(minigame);
this.flag = flag;
this.flagName = flagName;
this.player = player;
}
public boolean isCTFFlag() {
return flag != null;
}
public CTFFlag getFlag() {
return flag;
}
public String getFlagName() {
return flagName;
}
public boolean shouldDisplayMessage() {
return displayMessage;
}
public void setShouldDisplayMessage(boolean arg0) {
displayMessage = arg0;
}
public MinigamePlayer getPlayer() {
return player;
}
}
| 24.490909 | 99 | 0.679287 |
6a7fee5d2904f1d88a133c00b9414ae444516732 | 2,018 | package spyke.database.model;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
@Embeddable
public class PeriodId implements Serializable {
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "start_time")
private Date startTime;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "end_time")
private Date endTime;
@ManyToOne
private Device device;
public PeriodId() {
}
public PeriodId(Date startTime, Date endTime) {
this.startTime = startTime;
this.endTime = endTime;
}
public Date getStartTime() {
return startTime;
}
public Date getEndTime() {
return endTime;
}
public void setDevice(Device device) {
this.device = device;
}
public Device getDevice() {
return device;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof PeriodId)) return false;
PeriodId periodId = (PeriodId) obj;
if (startTime != null ?
!startTime.equals(periodId.getStartTime())
:periodId.getStartTime() != null
&& endTime != null ?
!endTime.equals(periodId.getEndTime())
:periodId.getEndTime() != null
&& device != null ?
!device.equals(periodId.getDevice())
:periodId.getDevice() != null
){
return false;
}
else {
return true;
}
}
@Override
public int hashCode() {
if(this.startTime == null || this.endTime == null){
return -1;
}
return (this.startTime.toString()+this.endTime.toString()+device.getMac()).hashCode();
}
@Override
public String toString() {
return "PeriodId [start_time="
+ startTime
+ ", end_time="
+ endTime
+ ", device_mac="
+ device.getMac()
+ "]\n";
}
}
| 23.741176 | 94 | 0.542616 |
7a9b663846097c85dc247c06666025ba2ea4cdaa | 1,005 | package io.github.kobakei.androidhowtotest.activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.github.kobakei.androidhowtotest.R;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
}
@OnClick(R.id.button1)
void onButton1Clicked() {
Intent intent = new Intent(this, CalculatorActivity.class);
startActivity(intent);
}
@OnClick(R.id.button2)
void onButton2Clicked() {
Intent intent = new Intent(this, LauncherActivity.class);
startActivity(intent);
}
@OnClick(R.id.button3)
void onButton3Clicked() {
Intent intent = new Intent(this, ApiActivity.class);
startActivity(intent);
}
}
| 26.447368 | 67 | 0.708458 |
36573d49df9c10ca45d89b8ee8a7ff38b432bb36 | 6,713 | package com.sequenceiq.environment.environment.flow.deletion.handler;
import static com.sequenceiq.environment.environment.flow.deletion.event.EnvDeleteHandlerSelectors.DELETE_PREREQUISITES_EVENT;
import static com.sequenceiq.environment.environment.flow.deletion.event.EnvDeleteStateSelectors.FINISH_ENV_DELETE_EVENT;
import java.util.Optional;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import com.sequenceiq.cloudbreak.cloud.Setup;
import com.sequenceiq.cloudbreak.cloud.exception.CloudConnectorException;
import com.sequenceiq.cloudbreak.cloud.init.CloudPlatformConnectors;
import com.sequenceiq.cloudbreak.cloud.model.CloudPlatformVariant;
import com.sequenceiq.cloudbreak.cloud.model.Platform;
import com.sequenceiq.cloudbreak.cloud.model.Variant;
import com.sequenceiq.cloudbreak.exception.BadRequestException;
import com.sequenceiq.environment.environment.domain.Environment;
import com.sequenceiq.environment.environment.dto.EnvironmentDeletionDto;
import com.sequenceiq.environment.environment.dto.EnvironmentDto;
import com.sequenceiq.environment.environment.flow.creation.event.EnvCreationEvent;
import com.sequenceiq.environment.environment.flow.deletion.event.EnvDeleteFailedEvent;
import com.sequenceiq.environment.environment.flow.deletion.handler.converter.EnvironmentDtoToPrerequisiteDeleteRequestConverter;
import com.sequenceiq.environment.environment.service.EnvironmentService;
import com.sequenceiq.flow.reactor.api.event.EventSender;
import com.sequenceiq.flow.reactor.api.handler.EventSenderAwareHandler;
import reactor.bus.Event;
@Component
public class PrerequisitesDeleteHandler extends EventSenderAwareHandler<EnvironmentDeletionDto> {
private static final Logger LOGGER = LoggerFactory.getLogger(PrerequisitesDeleteHandler.class);
private final EnvironmentService environmentService;
private final EnvironmentDtoToPrerequisiteDeleteRequestConverter environmentDtoToPrerequisiteDeleteRequestConverter;
private final CloudPlatformConnectors cloudPlatformConnectors;
protected PrerequisitesDeleteHandler(EventSender eventSender, EnvironmentService environmentService,
CloudPlatformConnectors cloudPlatformConnectors,
EnvironmentDtoToPrerequisiteDeleteRequestConverter environmentDtoToPrerequisiteDeleteRequestConverter) {
super(eventSender);
this.environmentService = environmentService;
this.cloudPlatformConnectors = cloudPlatformConnectors;
this.environmentDtoToPrerequisiteDeleteRequestConverter = environmentDtoToPrerequisiteDeleteRequestConverter;
}
@Override
public String selector() {
return DELETE_PREREQUISITES_EVENT.selector();
}
@Override
public void accept(Event<EnvironmentDeletionDto> environmentDtoEvent) {
EnvironmentDeletionDto environmentDeletionDto = environmentDtoEvent.getData();
EnvironmentDto environmentDto = environmentDeletionDto.getEnvironmentDto();
environmentService.findEnvironmentById(environmentDto.getId())
.ifPresentOrElse(environment -> {
try {
deletePrerequisites(environmentDto, environment);
goToFinishedState(environmentDtoEvent);
} catch (Exception e) {
if (environmentDeletionDto.isForceDelete()) {
LOGGER.warn("The %s was not successful but the environment deletion was requested " +
"as force delete so continue the deletion flow", selector());
goToFinishedState(environmentDtoEvent);
} else {
goToFailedState(environmentDtoEvent, e.getMessage());
}
}
}, () -> goToFailedState(environmentDtoEvent, String.format("Environment was not found with id '%s'.", environmentDto.getId()))
);
}
private void deletePrerequisites(EnvironmentDto environmentDto, Environment environment) {
try {
Optional<Setup> setupOptional = getSetupConnector(environmentDto.getCloudPlatform());
if (setupOptional.isEmpty()) {
LOGGER.debug("No setup defined for platform {}, resource group has not been deleted.", environmentDto.getCloudPlatform());
return;
}
setupOptional.get().deleteEnvironmentPrerequisites(environmentDtoToPrerequisiteDeleteRequestConverter.convert(environmentDto));
} catch (Exception e) {
throw new CloudConnectorException("Could not delete resource group" + ExceptionUtils.getRootCauseMessage(e), e);
}
}
private Optional<Setup> getSetupConnector(String cloudPlatform) {
CloudPlatformVariant cloudPlatformVariant = new CloudPlatformVariant(Platform.platform(cloudPlatform), Variant.variant(cloudPlatform));
return Optional.ofNullable(cloudPlatformConnectors.get(cloudPlatformVariant).setup());
}
private void goToFailedState(Event<EnvironmentDeletionDto> environmentDtoEvent, String message) {
LOGGER.debug("Going to failed state, message: {}.", message);
EnvironmentDeletionDto environmentDeletionDto = environmentDtoEvent.getData();
EnvironmentDto environmentDto = environmentDeletionDto.getEnvironmentDto();
EnvDeleteFailedEvent failureEvent = new EnvDeleteFailedEvent(
environmentDto.getId(),
environmentDto.getName(),
new BadRequestException(message),
environmentDto.getResourceCrn());
eventSender().sendEvent(failureEvent, environmentDtoEvent.getHeaders());
}
private void goToFinishedState(Event<EnvironmentDeletionDto> environmentDtoEvent) {
EnvironmentDeletionDto environmentDeletionDto = environmentDtoEvent.getData();
EnvironmentDto environmentDto = environmentDeletionDto.getEnvironmentDto();
EnvCreationEvent envCreationEvent = EnvCreationEvent.builder()
.withResourceId(environmentDto.getResourceId())
.withSelector(FINISH_ENV_DELETE_EVENT.selector())
.withResourceCrn(environmentDto.getResourceCrn())
.withResourceName(environmentDto.getName())
.build();
LOGGER.debug("Proceeding to next flow step: {}.", envCreationEvent.selector());
eventSender().sendEvent(envCreationEvent, environmentDtoEvent.getHeaders());
}
}
| 54.577236 | 151 | 0.729778 |
c562bd20740d6ee86467a78dffef679a47e9e748 | 7,145 | /**
* ************************************************************************
* * The contents of this file are subject to the MRPL 1.2
* * (the "License"), being the Mozilla Public License
* * Version 1.1 with a permitted attribution clause; you may not use this
* * file except in compliance with the License. You may obtain a copy of
* * the License at http://www.floreantpos.org/license.html
* * Software distributed under the License is distributed on an "AS IS"
* * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* * License for the specific language governing rights and limitations
* * under the License.
* * The Original Code is Infinity POS.
* * The Initial Developer of the Original Code is OROCUBE LLC
* * All portions are Copyright (C) 2015 OROCUBE LLC
* * All Rights Reserved.
* ************************************************************************
*/
package com.floreantpos.ui.views.order;
import java.awt.BorderLayout;
import java.awt.CardLayout;
import java.util.HashMap;
import java.util.Map;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import com.floreantpos.bo.ui.BackOfficeWindow;
import com.floreantpos.config.TerminalConfig;
import com.floreantpos.demo.KitchenDisplayView;
import com.floreantpos.extension.ExtensionManager;
import com.floreantpos.extension.OrderServiceExtension;
import com.floreantpos.extension.OrderServiceFactory;
import com.floreantpos.model.OrderType;
import com.floreantpos.model.dao.OrderTypeDAO;
import com.floreantpos.ui.HeaderPanel;
import com.floreantpos.ui.views.CustomerView;
import com.floreantpos.ui.views.IView;
import com.floreantpos.ui.views.LoginView;
import com.floreantpos.ui.views.SwitchboardOtherFunctionsView;
import com.floreantpos.ui.views.SwitchboardView;
import com.floreantpos.ui.views.TableMapView;
import com.floreantpos.ui.views.payment.SettleTicketDialog;
import com.floreantpos.util.TicketAlreadyExistsException;
public class RootView extends com.floreantpos.swing.TransparentPanel {
private CardLayout cards = new CardLayout();
private HeaderPanel headerPanel = new HeaderPanel();
private JPanel contentPanel = new JPanel(cards);
private LoginView loginScreen;
private SettleTicketDialog paymentView;
private String currentViewName;
private IView homeView;
private Map<String, IView> views = new HashMap<String, IView>();
private boolean maintenanceMode;
private static RootView instance;
private RootView() {
setLayout(new BorderLayout());
setBorder(new EmptyBorder(3, 3, 3, 3));
initView();
}
private void initView() {
headerPanel.setVisible(false);
add(headerPanel, BorderLayout.NORTH);
add(contentPanel);
loginScreen = LoginView.getInstance();
addView(loginScreen);
}
public void addView(IView iView) {
views.put(iView.getViewName(), iView);
contentPanel.add(iView.getViewName(), iView.getViewComponent());
}
public void showView(String viewName) {
if (LoginView.VIEW_NAME.equals(viewName)) {
headerPanel.setVisible(false);
}
else {
headerPanel.setVisible(true);
}
currentViewName = viewName;
cards.show(contentPanel, viewName);
headerPanel.updateHomeView(!homeView.getViewName().equals(currentViewName));
headerPanel.updateOthersFunctionsView(!currentViewName.equals(SwitchboardOtherFunctionsView.VIEW_NAME));
headerPanel.updateSwitchBoardView(!currentViewName.equals(SwitchboardView.VIEW_NAME));
}
public void showView(IView view) {
if (!views.containsKey(view.getViewName())) {
addView(view);
}
currentViewName = view.getViewName();
showView(currentViewName);
}
public boolean hasView(String viewName) {
return views.containsKey(viewName);
}
public boolean hasView(IView view) {
return views.containsKey(view.getViewName());
}
public OrderView getOrderView() {
return (OrderView) views.get(OrderView.VIEW_NAME);
}
public boolean isMaintenanceMode() {
return maintenanceMode;
}
public void setMaintenanceMode(boolean b) {
this.maintenanceMode = b;
}
public LoginView getLoginScreen() {
return loginScreen;
}
// public SwitchboardView getSwitchboadView() {
// return switchboardView;
// }
//
// public void setSwitchboardView(SwitchboardView switchboardView) {
// this.switchboardView = switchboardView;
// }
public synchronized static RootView getInstance() {
if (instance == null) {
instance = new RootView();
}
return instance;
}
public SettleTicketDialog getPaymentView() {
return paymentView;
}
public HeaderPanel getHeaderPanel() {
return headerPanel;
}
public String getCurrentViewName() {
return currentViewName;
}
public IView getCurrentView() {
return views.get(currentViewName);
}
public void showDefaultView() {
String defaultViewName = TerminalConfig.getDefaultView();
if (defaultViewName.equals(SwitchboardOtherFunctionsView.VIEW_NAME)) { //$NON-NLS-1$
setAndShowHomeScreen(SwitchboardOtherFunctionsView.getInstance());
}
else if (defaultViewName.equals(KitchenDisplayView.VIEW_NAME)) {
if (!hasView(KitchenDisplayView.getInstance())) {
addView(KitchenDisplayView.getInstance());
}
headerPanel.setVisible(false);
setAndShowHomeScreen(KitchenDisplayView.getInstance());
}
else if (defaultViewName.equals(SwitchboardView.VIEW_NAME)) {
if (loginScreen.isBackOfficeLogin()) {
showBackOffice();
}
setAndShowHomeScreen(SwitchboardView.getInstance());
}
else {
OrderType orderType = OrderTypeDAO.getInstance().findByName(defaultViewName);
if (orderType.isShowTableSelection()) {
TableMapView tableMapView = TableMapView.getInstance(orderType);
tableMapView.updateView();
setAndShowHomeScreen(tableMapView);
}
else if (orderType.isRequiredCustomerData()) {
OrderServiceExtension orderServicePlugin = (OrderServiceExtension) ExtensionManager.getPlugin(OrderServiceExtension.class);
if (orderServicePlugin != null) {
if (orderType.isDelivery()) {
setAndShowHomeScreen(orderServicePlugin.getDeliveryDispatchView(orderType));
}
else {
CustomerView customerView = CustomerView.getInstance(orderType);
customerView.updateView();
setAndShowHomeScreen(customerView);
}
}
else {
CustomerView customerView = CustomerView.getInstance(orderType);
customerView.updateView();
setAndShowHomeScreen(customerView);
}
}
else {
try {
homeView = OrderView.getInstance();
OrderServiceFactory.getOrderService().createNewTicket(orderType, null, null);
} catch (TicketAlreadyExistsException e1) {
}
}
}
}
/**
* @return the loginView
*/
public IView getHomeView() {
return homeView;
}
public void setAndShowHomeScreen(IView homeScreen) {
homeView = homeScreen;
showHomeScreen();
}
public void showHomeScreen() {
showView(getHomeView());
}
public void showBackOffice() {
BackOfficeWindow window = com.floreantpos.util.POSUtil.getBackOfficeWindow();
if (window == null) {
window = new BackOfficeWindow();
}
window.setVisible(true);
window.toFront();
loginScreen.setBackOfficeLogin(false);
}
}
| 28.241107 | 127 | 0.73436 |
ae2f4a9eb9fb1178f06be3af937e746642ce553b | 3,695 | package gr.eap.dxt.sprints;
import android.app.Activity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.Date;
import gr.eap.dxt.R;
import gr.eap.dxt.projects.Project;
import gr.eap.dxt.tools.Keyboard;
/**
* Created by GEO on 15/2/2017.
*/
public class SprintNewDialogActivity extends Activity {
/* Static content for input */
private static Project project;
private static Date startDate;
private static long durationDays;
private static int oldNumber;
public static void setStaticContent(Project _project, Date _startDate, long _durationDays, int _oldNumber){
project = _project;
startDate = _startDate;
durationDays = _durationDays;
oldNumber = _oldNumber;
}
private static void clearStaticContent(){
project = null;
startDate = null;
durationDays = 0;
oldNumber = 0;
}
/* End of static content */
private SprintNewFragment fragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_activity_sprint_new);
if (savedInstanceState == null) {
fragment = SprintNewFragment.newInstance(project, startDate, durationDays, oldNumber);
getFragmentManager().beginTransaction().replace(R.id.container, fragment).commit();
}
TextView myTitleTextView = (TextView) findViewById(R.id.my_title_view);
if (myTitleTextView != null){
if (startDate == null){
myTitleTextView.setText(R.string.sprints_create);
}else{
myTitleTextView.setText(R.string.sprints_add);
}
}
ImageButton backButton = (ImageButton) findViewById(R.id.back);
if (backButton != null){
backButton.setImageResource(R.drawable.ic_action_not_ok);
backButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Keyboard.close(SprintNewDialogActivity.this);
finish();
}
});
}
ImageButton saveButton = (ImageButton) findViewById(R.id.save);
if (saveButton != null){
saveButton.setVisibility(View.VISIBLE);
saveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (fragment != null) fragment.saveChanges();
}
});
}
setDimensions();
}
@Override
protected void onDestroy() {
super.onDestroy();
clearStaticContent();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
setDimensions();
}
private void setDimensions(){
if(getResources().getBoolean(R.bool.large_screen)){
DisplayMetrics metrics = getResources().getDisplayMetrics();
int height = (int) (metrics.heightPixels*0.8);
int width = (int) (metrics.widthPixels*0.8);
getWindow().setLayout(width,height);
return;
}
getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
}
}
| 31.05042 | 112 | 0.612179 |
b45b56189942dcaaf8dd4cb130d2376065ccb3c8 | 1,749 | /*
* Copyright 2020 Syr0ws
*
* 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 fr.syrows.easyinventories.builders;
import fr.syrows.easyinventories.contents.sort.InventorySortType;
import fr.syrows.easyinventories.inventories.SimpleInventory;
public interface AbstractInventoryBuilder<SELF, T extends SimpleInventory> {
/**
* Set the id of the inventory.
*
* @param id - the id of the inventory.
* @return an object of type SELF.
*/
SELF withId(String id);
/**
* Set the title of the inventory.
* @param title - the title of the inventory.
* @return an object of type SELF.
*/
SELF withTitle(String title);
/**
* Set the size of the inventory.
*
* @param size - the size of the inventory.
* @return an object of type SELF.
*/
SELF withSize(int size);
/**
* Set the sort if the inventory.
*
* @param sort - the sort of the inventory.
* @return an object of type SELF.
*/
SELF withSort(InventorySortType sort);
/**
* Get the built inventory with the parameters spcified with the method above.
*
* @return an object of type T.
*/
T build();
}
| 28.209677 | 82 | 0.65466 |
7675a41bf4cdec75732f0b9f2e1c2eb644ee0f5d | 2,849 | /*******************************************************************************
* 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.olingo.odata2.client.core.edm.Impl;
import org.apache.olingo.odata2.api.edm.Edm;
import org.apache.olingo.odata2.api.edm.EdmAnnotationAttribute;
/**
* Objects of this class represent an annotation attribute
*
*/
public class EdmAnnotationAttributeImpl implements EdmAnnotationAttribute {
private String namespace;
private String prefix;
private String name;
private String text;
@Override
public String getNamespace() {
return namespace;
}
@Override
public String getPrefix() {
return prefix;
}
@Override
public String getName() {
return name;
}
@Override
public String getText() {
return text;
}
/**
* Sets the namespace for this {@link EdmAnnotationAttributeImpl}.
* @param namespace
* @return {@link EdmAnnotationAttributeImpl} for method chaining
*/
public EdmAnnotationAttributeImpl setNamespace(final String namespace) {
this.namespace = namespace;
return this;
}
/**
* Sets the prefix for this {@link EdmAnnotationAttributeImpl}.
* @param prefix
* @return {@link EdmAnnotationAttributeImpl} for method chaining
*/
public EdmAnnotationAttributeImpl setPrefix(final String prefix) {
this.prefix = prefix;
return this;
}
/**
* Sets the name for this {@link EdmAnnotationAttributeImpl}.
* @param name
* @return {@link EdmAnnotationAttributeImpl} for method chaining
*/
public EdmAnnotationAttributeImpl setName(final String name) {
this.name = name;
return this;
}
/**
* Sets the text for this {@link EdmAnnotationAttributeImpl}.
* @param text
* @return {@link EdmAnnotationAttributeImpl} for method chaining
*/
public EdmAnnotationAttributeImpl setText(final String text) {
this.text = text;
return this;
}
@Override
public String toString() {
return namespace + Edm.DELIMITER + name;
}
}
| 28.49 | 80 | 0.681643 |
c74e1324e59f5f9d0864d0ebc75552deefb59320 | 4,792 | package com.revature.beans;
public class TRMSForm {
private int form_id;
private int emp_id;
private String name_first;
private String name_last;
private String email;
private String course_title;
private String course_type;
private String course_start_date;
private String course_location;
private int course_cost;
private String grade_format;
private String min_grade;
private String add_doc;
private String final_grade;
private String sup_appden;
private String dh_appden;
private String benco_appden;
private double reim_amount;
public TRMSForm() {
super();
// TODO Auto-generated constructor stub
}
public TRMSForm(int form_id, int emp_id, String name_first, String name_last, String email, String course_title,
String course_type, String course_start_date, String course_location, int course_cost, String grade_format,
String min_grade, String add_doc, String final_grade, String sup_appden, String dh_appden, String benco_appden,
double reim_amount) {
super();
this.form_id = form_id;
this.emp_id = emp_id;
this.name_first = name_first;
this.name_last = name_last;
this.email = email;
this.course_title = course_title;
this.course_type = course_type;
this.course_start_date = course_start_date;
this.course_location = course_location;
this.course_cost = course_cost;
this.grade_format = grade_format;
this.min_grade = min_grade;
this.add_doc = add_doc;
this.final_grade = final_grade;
this.sup_appden = sup_appden;
this.dh_appden = dh_appden;
this.benco_appden = benco_appden;
this.reim_amount = reim_amount;
}
public String getFinal_grade() {
return final_grade;
}
public void setFinal_grade(String final_grade) {
this.final_grade = final_grade;
}
public int getForm_id() {
return form_id;
}
public void setForm_id(int form_id) {
this.form_id = form_id;
}
public int getEmp_id() {
return emp_id;
}
public void setEmp_id(int emp_id) {
this.emp_id = emp_id;
}
public String getName_first() {
return name_first;
}
public void setName_first(String name_first) {
this.name_first = name_first;
}
public String getName_last() {
return name_last;
}
public void setName_last(String name_last) {
this.name_last = name_last;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getCourse_title() {
return course_title;
}
public void setCourse_title(String course_title) {
this.course_title = course_title;
}
public String getCourse_type() {
return course_type;
}
public void setCourse_type(String course_type) {
this.course_type = course_type;
}
public String getCourse_start_date() {
return course_start_date;
}
public void setCourse_start_date(String course_start_date) {
this.course_start_date = course_start_date;
}
public String getCourse_location() {
return course_location;
}
public void setCourse_location(String course_location) {
this.course_location = course_location;
}
public int getCourse_cost() {
return course_cost;
}
public void setCourse_cost(int course_cost) {
this.course_cost = course_cost;
}
public String getGrade_format() {
return grade_format;
}
public void setGrade_format(String grade_format) {
this.grade_format = grade_format;
}
public String getMin_grade() {
return min_grade;
}
public void setMin_grade(String min_grade) {
this.min_grade = min_grade;
}
public String getAdd_doc() {
return add_doc;
}
public void setAdd_doc(String add_doc) {
this.add_doc = add_doc;
}
public String getSup_appden() {
return sup_appden;
}
public void setSup_appden(String sup_appden) {
this.sup_appden = sup_appden;
}
public String getDh_appden() {
return dh_appden;
}
public void setDh_appden(String dh_appden) {
this.dh_appden = dh_appden;
}
public String getBenco_appden() {
return benco_appden;
}
public void setBenco_appden(String benco_appden) {
this.benco_appden = benco_appden;
}
public double getReim_amount() {
return reim_amount;
}
public void setReim_amount(double reim_amount) {
this.reim_amount = reim_amount;
}
@Override
public String toString() {
return "TRMSForm [form_id=" + form_id + ", emp_id=" + emp_id + ", name_first=" + name_first + ", name_last="
+ name_last + ", email=" + email + ", course_title=" + course_title + ", course_type=" + course_type
+ ", course_start_date=" + course_start_date + ", course_location=" + course_location + ", course_cost="
+ course_cost + ", grade_format=" + grade_format + ", min_grade=" + min_grade + ", add_doc=" + add_doc
+ ", final_grade=" + final_grade + ", sup_appden=" + sup_appden + ", dh_appden=" + dh_appden
+ ", benco_appden=" + benco_appden + ", reim_amount=" + reim_amount + "]";
}
}
| 25.902703 | 114 | 0.737062 |
b8f766ed8f41b8865e797c231f834d9bdd81a45f | 1,703 | package com.github.xfslove.shiro.uaa.model;
import java.io.Serializable;
import java.util.Date;
/**
* Created by hanwen on 2017/10/19.
*/
public class AccessToken implements Serializable {
private Long id;
private String accessToken;
private String refreshToken;
private Date accessTokenExpires;
private Date refreshTokenExpires;
private Long accountId;
private Long accessClientId;
private String sessionId;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public String getRefreshToken() {
return refreshToken;
}
public void setRefreshToken(String refreshToken) {
this.refreshToken = refreshToken;
}
public Date getAccessTokenExpires() {
return accessTokenExpires;
}
public void setAccessTokenExpires(Date accessTokenExpires) {
this.accessTokenExpires = accessTokenExpires;
}
public Date getRefreshTokenExpires() {
return refreshTokenExpires;
}
public void setRefreshTokenExpires(Date refreshTokenExpires) {
this.refreshTokenExpires = refreshTokenExpires;
}
public Long getAccessClientId() {
return accessClientId;
}
public void setAccessClientId(Long accessClientId) {
this.accessClientId = accessClientId;
}
public Long getAccountId() {
return accountId;
}
public void setAccountId(Long accountId) {
this.accountId = accountId;
}
public String getSessionId() {
return sessionId;
}
public void setSessionId(String sessionId) {
this.sessionId = sessionId;
}
}
| 18.714286 | 64 | 0.722842 |
b60d397b006b891694976da44342c80347b4dc80 | 1,872 | package demo.model.primary;
import demo.model.primary.builder.PrimaryModelBuilder;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.json.JsonTest;
import org.springframework.boot.test.json.JacksonTester;
import org.springframework.boot.test.json.JsonContent;
import org.springframework.boot.test.json.ObjectContent;
import java.io.IOException;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Fail.fail;
@JsonTest
class PrimaryModelTest {
@Autowired
private JacksonTester<PrimaryModel> jacksonTester;
@Test
void serializesIntoJson() {
PrimaryModel primaryModel = new PrimaryModelBuilder()
.withName("Hello World")
.build();
primaryModel.setId(2381652);
JsonContent<PrimaryModel> jsonContent = null;
try {
jsonContent = jacksonTester.write(primaryModel);
} catch (IOException e) {
fail("Unable to serialize PrimaryModel into JSON", e);
}
assertThat(jsonContent).hasJsonPathValue("$.id");
assertThat(jsonContent).hasJsonPathStringValue("$.name");
}
@Test
void deserializesFromJson() {
String json =
"{" +
" \"id\": 2381652," +
" \"name\": \"Hello World\"" +
"}";
ObjectContent<PrimaryModel> content = null;
try {
content = jacksonTester.parse(json);
} catch (IOException e) {
fail("Unable to deserialize PrimaryModel from JSON", e);
}
assertThat(content.getObject()).isNotNull();
assertThat(content.getObject().getId()).isEqualTo(2381652);
assertThat(content.getObject().getName()).isEqualTo("Hello World");
}
}
| 30.688525 | 75 | 0.650641 |
e27b6911308a51bc1913995e5ec83ddd5eb092d5 | 2,184 | /*
* Copyright 2019-present Open Networking Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.atomix.grpc.impl;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.protobuf.ByteString;
import io.atomix.core.Atomix;
import io.atomix.grpc.event.EventServiceGrpc;
import io.atomix.grpc.event.PublishRequest;
import io.atomix.grpc.event.PublishResponse;
import io.atomix.grpc.event.SubscribeRequest;
import io.atomix.grpc.event.SubscribeResponse;
import io.grpc.stub.StreamObserver;
/**
* gRPC event service implementation.
*/
public class EventServiceImpl extends EventServiceGrpc.EventServiceImplBase {
private final Atomix atomix;
public EventServiceImpl(Atomix atomix) {
this.atomix = atomix;
}
@Override
public StreamObserver<PublishRequest> publish(StreamObserver<PublishResponse> responseObserver) {
return new StreamObserver<PublishRequest>() {
@Override
public void onNext(PublishRequest value) {
atomix.getEventService().broadcast(value.getTopic(), value.getPayload().toByteArray());
}
@Override
public void onError(Throwable t) {
responseObserver.onCompleted();
}
@Override
public void onCompleted() {
responseObserver.onCompleted();
}
};
}
@Override
public void subscribe(SubscribeRequest request, StreamObserver<SubscribeResponse> responseObserver) {
atomix.getEventService().<byte[]>subscribe(request.getTopic(), bytes -> {
responseObserver.onNext(SubscribeResponse.newBuilder()
.setPayload(ByteString.copyFrom(bytes))
.build());
}, MoreExecutors.directExecutor());
}
}
| 32.597015 | 103 | 0.737637 |
32c9e8fd08063d15d4aaedb9e65e3a86b9c0c195 | 1,535 | package edu.neu.his.bean.billRecord;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* 该类对数据库中的bill_record表进行数据持久化操作
*
* @author 王婧怡
* @version 1.0
*/
@Mapper
@Component(value = "AutoBillRecordMapper")
public interface BillRecordMapper {
/**
* 向bill_record表中插入一条数据
* @param billRecord 需要插入表中的BillRecord对象
*/
@Insert("INSERT INTO bill_record(medical_record_id, type , print_status, " +
"cost, should_pay, truely_pay, retail_fee, user_id, create_time) " +
"VALUES(#{medical_record_id}, #{type}, #{print_status}, " +
"#{cost}, #{should_pay}, #{truely_pay}, #{retail_fee}, #{user_id}, #{create_time})")
@Options(useGeneratedKeys = true, keyProperty = "id")
void insert(BillRecord billRecord);
/**
* 根据主键id查找相对应的bill_record表中的记录
* @param id bill_record表的主键,代表票据记录的流水号
* @return 将查找到的记录生成BillRecord对象返回
*/
@Select("SELECT * from bill_record where id = #{id}")
BillRecord find(@Param("id") int id);
/**
* 根据用户id和时间段查找该用户在该时间段的所有票据记录
* @param user_id 需要查找票据记录的用户的id
* @param start_time 查找时间段的开始时间
* @param end_time 查找时间段的结束时间
* @return 返回符合条件的所有票据记录列表
*/
@Select("SELECT * from bill_record where user_id = #{user_id} and create_time > #{start_time} and create_time < #{end_time}")
List<BillRecord> findByUserIdAndTime(@Param("user_id") int user_id, @Param("start_time") String start_time, @Param("end_time") String end_time);
}
| 33.369565 | 148 | 0.681433 |
a9a1ca0b78e7cb33a3aa265b206d22168ef86c3c | 2,174 | // Copyright 2020 Goldman Sachs
//
// 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.finos.legend.pure.m3.execution;
import org.eclipse.collections.api.list.ListIterable;
import org.finos.legend.pure.m3.navigation.ProcessorSupport;
import org.finos.legend.pure.m3.serialization.runtime.Message;
import org.finos.legend.pure.m3.serialization.runtime.PureRuntime;
import org.finos.legend.pure.m4.coreinstance.CoreInstance;
import java.io.OutputStream;
/**
* Function execution which does nothing.
*/
public class VoidFunctionExecution implements FunctionExecution
{
public static final VoidFunctionExecution VOID_FUNCTION_EXECUTION = new VoidFunctionExecution();
private VoidFunctionExecution()
{
// Singleton
}
@Override
public void init(PureRuntime runtime, Message message)
{
}
@Override
public CoreInstance start(CoreInstance func, ListIterable<? extends CoreInstance> arguments)
{
return null;
}
@Override
public void start(CoreInstance func, ListIterable<? extends CoreInstance> arguments, OutputStream outputStream, OutputWriter writer)
{
}
@Override
public Console getConsole()
{
return null;
}
@Override
public boolean isFullyInitializedForExecution()
{
return false;
}
@Override
public void resetEventHandlers()
{
}
@Override
public ProcessorSupport getProcessorSupport()
{
return null;
}
@Override
public PureRuntime getRuntime()
{
return null;
}
@Override
public OutputWriter newOutputWriter()
{
return null;
}
}
| 24.426966 | 136 | 0.707912 |
54576eaa1c96143dee54132d926df36a40c52396 | 2,272 | package unet.motiondetection.listeners;
import java.io.IOException;
import java.util.ArrayList;
public class ScreenSaver {
private boolean running = false, ractive = false;
private static String COMMAND = "gnome-screensaver-command -q | grep -q 'is active'";
private static String[] OPEN_SHELL = { "/bin/sh", "-c", COMMAND };
private static int EXPECTED_EXIT_CODE = 0;
private ArrayList<ScreenSaverListener> listeners = new ArrayList<>();
public void addScreenSaverListener(ScreenSaverListener listener){
listeners.add(listener);
}
public void removeScreenSaverListener(ScreenSaverListener listener){
if(listeners.contains(listener)){
listeners.remove(listener);
}
}
public void start(){
if(!running){
new Thread(new ScreenSaverRunnable()).start();
}
}
public void stop(){
running = false;
}
public static boolean isScreenSaverActive(){
try{
Process process = Runtime.getRuntime().exec(OPEN_SHELL);
return process.waitFor() == EXPECTED_EXIT_CODE;
}catch(IOException | InterruptedException e){
e.printStackTrace();
}
return false;
}
public class ScreenSaverRunnable implements Runnable {
@Override
public void run(){
running = true;
while(running){
try{
Thread.sleep(2000);
}catch(InterruptedException e){
e.printStackTrace();
}
boolean active = isScreenSaverActive();
if(active != ractive){
ractive = active;
if(!listeners.isEmpty()){
if(active){
for(ScreenSaverListener listener : listeners){
listener.userSessionDeactivated(null);
}
}else{
for(ScreenSaverListener listener : listeners){
listener.userSessionActivated(null);
}
}
}
}
}
}
}
}
| 28.049383 | 90 | 0.522887 |
0ca17573d42c68c2357359a955edc8378067b913 | 307 | package boxing;
public class Unit {
private String name;
public Unit(String name) {
super();
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void attack() {
System.out.println( this.name + " >> 공격준비" );
}
} | 13.954545 | 47 | 0.631922 |
72631a28c1b39ad57a1bc1222a8418f5d145892c | 2,425 | /*
* Copyright 2016 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* 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.keycloak.saml.processing.core.saml.v2.holders;
import org.keycloak.dom.saml.v2.assertion.AssertionType;
import org.keycloak.saml.common.constants.JBossSAMLURIConstants;
/**
* Holds essential information about an IDP for creating saml messages.
*
* @author Anil.Saldhana@redhat.com
* @since Dec 10, 2008
*/
public class IDPInfoHolder {
private String subjectConfirmationMethod = JBossSAMLURIConstants.SUBJECT_CONFIRMATION_BEARER.get();
private String nameIDFormat = JBossSAMLURIConstants.NAMEID_FORMAT_TRANSIENT.get();
private String nameIDFormatValue;
private AssertionType assertion;
private int assertionValidityDuration = 5; // 5 Minutes
public int getAssertionValidityDuration() {
return assertionValidityDuration;
}
public void setAssertionValidityDuration(int assertionValidityDuration) {
this.assertionValidityDuration = assertionValidityDuration;
}
public String getSubjectConfirmationMethod() {
return subjectConfirmationMethod;
}
public void setSubjectConfirmationMethod(String subjectConfirmationMethod) {
this.subjectConfirmationMethod = subjectConfirmationMethod;
}
public String getNameIDFormat() {
return nameIDFormat;
}
public void setNameIDFormat(String nameIDFormat) {
this.nameIDFormat = nameIDFormat;
}
public String getNameIDFormatValue() {
return nameIDFormatValue;
}
public void setNameIDFormatValue(String nameIDFormatValue) {
this.nameIDFormatValue = nameIDFormatValue;
}
public AssertionType getAssertion() {
return assertion;
}
public void setAssertion(AssertionType assertion) {
this.assertion = assertion;
}
} | 31.493506 | 103 | 0.741856 |
defbd44be5d27b9e15a76954b92069b6382cd459 | 1,795 | package net.minestom.server.tag;
import net.minestom.server.item.ItemStack;
import org.jglrxavpok.hephaistos.nbt.*;
import java.util.function.Function;
final class Serializers {
static final Entry<?, ?> VOID = new Entry<>(null, null);
static final Entry<Byte, NBTByte> BYTE = new Entry<>(NBTByte::getValue, NBT::Byte);
static final Entry<Short, NBTShort> SHORT = new Entry<>(NBTShort::getValue, NBT::Short);
static final Entry<Integer, NBTInt> INT = new Entry<>(NBTInt::getValue, NBT::Int);
static final Entry<Long, NBTLong> LONG = new Entry<>(NBTLong::getValue, NBT::Long);
static final Entry<Float, NBTFloat> FLOAT = new Entry<>(NBTFloat::getValue, NBT::Float);
static final Entry<Double, NBTDouble> DOUBLE = new Entry<>(NBTDouble::getValue, NBT::Double);
static final Entry<String, NBTString> STRING = new Entry<>(NBTString::getValue, NBT::String);
static final Entry<NBT, NBT> NBT_ENTRY = new Entry<>(Function.identity(), Function.identity());
static final Entry<ItemStack, NBTCompound> ITEM = new Entry<>(ItemStack::fromItemNBT, ItemStack::toItemNBT);
static <T> Entry<T,?> fromTagSerializer(TagSerializer<T> serializer) {
return new Serializers.Entry<>(
(NBTCompound compound) -> {
if (compound.isEmpty()) return null;
return serializer.read(TagHandler.fromCompound(compound));
},
(value) -> {
if (value == null) return NBTCompound.EMPTY;
TagHandler handler = TagHandler.newHandler();
serializer.write(handler, value);
return handler.asCompound();
});
}
record Entry<T, N extends NBT>(Function<N, T> read, Function<T, N> write) {
}
}
| 46.025641 | 112 | 0.638997 |
ee52e74709ee8bf5698423a656661ac5eb4553c8 | 2,856 | package caelum.com.br.cadastro;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
import java.io.Serializable;
import caelum.com.br.cadastro.dao.AlunoDAO;
import caelum.com.br.cadastro.modelo.Aluno;
/**
* Created by fabriciosilva on 2/3/16.
*/
public class FormularioActivity extends Activity {
private String caminhoArquivo;
private FormularioHelper helper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.formulario);
helper = new FormularioHelper(this);
final Aluno alunoParaSerAlterado = (Aluno) getIntent().getSerializableExtra("alunoSelecionado");
if (alunoParaSerAlterado != null) {
helper.colocaAlunoNoFormulario(alunoParaSerAlterado);
}
final Button botao = (Button) findViewById(R.id.botao);
botao.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(FormularioActivity.this,
"Clicou no button", Toast.LENGTH_LONG).show();
Aluno aluno = helper.pegaAlunoDoFormulario();
AlunoDAO dao = new AlunoDAO(FormularioActivity.this);
if (alunoParaSerAlterado != null) {
aluno.setId(alunoParaSerAlterado.getId());
botao.setText("Alterar");
dao.atualizar(aluno);
} else {
dao.insere(aluno);
}
dao.close();
finish();
}
});
ImageView foto = helper.getFoto();
foto.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent irParaCamera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
caminhoArquivo = getExternalFilesDir(null) + "/" + System.currentTimeMillis() + ".png";
File arquivo = new File(caminhoArquivo);
Uri localFoto = Uri.fromFile(arquivo);
irParaCamera.putExtra(MediaStore.EXTRA_OUTPUT, localFoto);
startActivityForResult(irParaCamera, 123);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 123) {
if (resultCode == Activity.RESULT_OK) {
helper.carregaImagem(caminhoArquivo);
} else {
caminhoArquivo = null;
}
}
}
}
| 30.709677 | 104 | 0.610644 |
0c085eeb902265641ed540d591895f73ee831086 | 12,184 | /*
* Copyright 2020 OPS4J.
*
* 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.ops4j.pax.web.service.spi.task;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.ops4j.pax.web.service.WebContainerContext;
import org.ops4j.pax.web.service.spi.model.OsgiContextModel;
import org.ops4j.pax.web.service.spi.model.ServerModel;
import org.ops4j.pax.web.service.spi.model.ServletContextModel;
import org.ops4j.pax.web.service.spi.model.elements.ContainerInitializerModel;
import org.ops4j.pax.web.service.spi.model.elements.ErrorPageModel;
import org.ops4j.pax.web.service.spi.model.elements.EventListenerModel;
import org.ops4j.pax.web.service.spi.model.elements.FilterModel;
import org.ops4j.pax.web.service.spi.model.elements.ServletModel;
import org.ops4j.pax.web.service.spi.model.elements.WelcomeFileModel;
import org.osgi.service.http.HttpContext;
/**
* <p>List of tasks to perform on model. Collects primitive operations which can be reverted if something
* goes wrong, can be delayed if needed or shared between multiple invocations.</p>
*
* <p>The idea is that normal, elementary operation, like registration of a servlet may be associated with
* model-altering operations. If something goes wrong, we'd like to <em>rollback</em> the changes. If everything
* is fine, we can use given batch to:<ul>
* <li>actually apply the operations to global model</li>
* <li>pass the operations (e.g., create servlet context, create osgi context, register servlet) to
* {@link org.ops4j.pax.web.service.spi.ServerController}</li>
* <li>schedule for later invocation when using <em>transactions</em> with
* {@link org.ops4j.pax.web.service.WebContainer#begin(HttpContext)}</li>
* </ul></p>
*
* <p>This class is implemented using the Visitor pattern, where the registration operations (servlet registration,
* error page registration, context configuration, ...) are <em>elements</em> and the classes that should handle
* registration operations (like global {@link ServerModel} or actual server runtime) implement related
* <em>vistors</em>.</p>
*/
public class Batch {
private final List<Change> operations = new LinkedList<>();
private final String description;
public Batch(String description) {
this.description = description;
}
public List<Change> getOperations() {
return operations;
}
/**
* Add new {@link ServletContextModel}
*
* @param model
* @param servletContextModel
*/
public void addServletContextModel(ServerModel model, ServletContextModel servletContextModel) {
operations.add(new ServletContextModelChange(OpCode.ADD, model, servletContextModel));
}
/**
* Add new {@link OsgiContextModel}
*
* @param osgiContextModel
*/
public void addOsgiContextModel(OsgiContextModel osgiContextModel, ServletContextModel servletContextModel) {
operations.add(new OsgiContextModelChange(OpCode.ADD, null, osgiContextModel, servletContextModel));
}
/**
* Remove existing {@link OsgiContextModel}
*
* @param osgiContextModel
*/
public void removeOsgiContextModel(OsgiContextModel osgiContextModel) {
operations.add(new OsgiContextModelChange(OpCode.DELETE, null, osgiContextModel, null));
}
/**
* Mark {@link OsgiContextModel} as associated with {@link WebContainerContext}
*
* @param context
* @param osgiContextModel
*/
public void associateOsgiContextModel(WebContainerContext context, OsgiContextModel osgiContextModel) {
operations.add(new OsgiContextModelChange(OpCode.ASSOCIATE, context, osgiContextModel, null));
}
/**
* Mark {@link OsgiContextModel} as (temporarily) disassociated with {@link WebContainerContext}
*
* @param context
* @param osgiContextModel
*/
public void disassociateOsgiContextModel(WebContainerContext context, OsgiContextModel osgiContextModel) {
operations.add(new OsgiContextModelChange(OpCode.DISASSOCIATE, context, osgiContextModel, null));
}
/**
* Add {@link ServletModel} to {@link ServerModel}
* @param serverModel
* @param model
*/
public void addServletModel(ServerModel serverModel, ServletModel model,
OsgiContextModel ... newModels) {
operations.add(new ServletModelChange(OpCode.ADD, serverModel, model, newModels));
}
/**
* Remove {@link ServletModel} from {@link ServerModel}
* @param serverModel
* @param toUnregister
*/
public void removeServletModels(ServerModel serverModel, Map<ServletModel, Boolean> toUnregister) {
operations.add(new ServletModelChange(OpCode.DELETE, serverModel, toUnregister));
}
/**
* Add {@link ServletModel} to {@link ServerModel} but as <em>disabled</em> model, which can't be registered
* because other model is registered for the same URL pattern. Disabled models can later be registered of
* existing model with higher ranking is unregistered.
*
* @param serverModel
* @param model
*/
public void addDisabledServletModel(ServerModel serverModel, ServletModel model) {
operations.add(new ServletModelChange(OpCode.ADD, serverModel, model, true));
}
/**
* Enable {@link ServletModel}
*
* @param serverModel
* @param model
*/
public void enableServletModel(ServerModel serverModel, ServletModel model) {
operations.add(new ServletModelChange(OpCode.ENABLE, serverModel, model));
}
/**
* Disable {@link ServletModel} from {@link ServerModel}
*
* @param serverModel
* @param model
*/
public void disableServletModel(ServerModel serverModel, ServletModel model) {
operations.add(new ServletModelChange(OpCode.DISABLE, serverModel, model));
}
/**
* Add {@link FilterModel} to {@link ServerModel}
* @param serverModel
* @param model
*/
public void addFilterModel(ServerModel serverModel, FilterModel model, OsgiContextModel ... newModels) {
operations.add(new FilterModelChange(OpCode.ADD, serverModel, model, newModels));
}
/**
* Remove {@link ServletModel} from {@link ServerModel}
* @param serverModel
* @param toUnregister
*/
public void removeFilterModels(ServerModel serverModel, List<FilterModel> toUnregister) {
operations.add(new FilterModelChange(OpCode.DELETE, serverModel, toUnregister));
}
/**
* Add {@link FilterModel} to {@link ServerModel} but as <em>disabled</em> model
*
* @param filterModel
* @param model
*/
public void addDisabledFilterModel(ServerModel serverModel, FilterModel model) {
operations.add(new FilterModelChange(OpCode.ADD, serverModel, model, true));
}
/**
* Enable {@link FilterModel}
*
* @param serverModel
* @param model
*/
public void enableFilterModel(ServerModel serverModel, FilterModel model) {
operations.add(new FilterModelChange(OpCode.ENABLE, serverModel, model));
}
/**
* Disable {@link FilterModel} from {@link ServerModel}
*
* @param serverModel
* @param model
*/
public void disableFilterModel(ServerModel serverModel, FilterModel model) {
operations.add(new FilterModelChange(OpCode.DISABLE, serverModel, model));
}
/**
* Batch (inside batch...) method that passes full information about all filters that should be enabled
* in a set of contexts. To be handled by Server Controller only
*
* @param contextFilters
* @param dynamic should be set to {@code true} when adding a {@link FilterModel} related to
* {@link javax.servlet.ServletContext#addFilter}
*/
public void updateFilters(Map<String, TreeMap<FilterModel, List<OsgiContextModel>>> contextFilters, boolean dynamic) {
operations.add(new FilterStateChange(contextFilters, dynamic));
}
/**
* Add {@link ErrorPageModel} to {@link ServerModel}
* @param serverModel
* @param model
*/
public void addErrorPageModel(ServerModel serverModel, ErrorPageModel model,
OsgiContextModel ... newModels) {
operations.add(new ErrorPageModelChange(OpCode.ADD, serverModel, model, newModels));
}
/**
* Remove {@link ErrorPageModel} from {@link ServerModel}
* @param serverModel
* @param toUnregister
*/
public void removeErrorPageModels(ServerModel serverModel, List<ErrorPageModel> toUnregister) {
operations.add(new ErrorPageModelChange(OpCode.DELETE, serverModel, toUnregister));
}
/**
* Add {@link ErrorPageModel} to {@link ServerModel} but as <em>disabled</em> model
*
* @param serverModel
* @param model
*/
public void addDisabledErrorPageModel(ServerModel serverModel, ErrorPageModel model) {
operations.add(new ErrorPageModelChange(OpCode.ADD, serverModel, model, true));
}
/**
* Enable {@link ErrorPageModel}
*
* @param serverModel
* @param model
*/
public void enableErrorPageModel(ServerModel serverModel, ErrorPageModel model) {
operations.add(new ErrorPageModelChange(OpCode.ENABLE, serverModel, model));
}
/**
* Disable {@link ErrorPageModel} in {@link ServerModel}
*
* @param serverModel
* @param model
*/
public void disableErrorPageModel(ServerModel serverModel, ErrorPageModel model) {
operations.add(new ErrorPageModelChange(OpCode.DISABLE, serverModel, model));
}
/**
* Batch (inside batch...) method that passes full information about all error page models
* that should be enabled in a set of contexts. To be handled by Server Controller only
*
* @param contextErrorPageModels
*/
public void updateErrorPages(Map<String, TreeMap<ErrorPageModel, List<OsgiContextModel>>> contextErrorPageModels) {
operations.add(new ErrorPageStateChange(contextErrorPageModels));
}
/**
* Add new {@link EventListenerModel}
* @param serverModel
* @param model
*/
public void addEventListenerModel(ServerModel serverModel, EventListenerModel model,
OsgiContextModel ... newModels) {
operations.add(new EventListenerModelChange(OpCode.ADD, serverModel, model, newModels));
}
/**
* Remove existing {@link EventListenerModel}
* @param serverModel
* @param models
*/
public void removeEventListenerModels(ServerModel serverModel, List<EventListenerModel> models) {
operations.add(new EventListenerModelChange(OpCode.DELETE, serverModel, models));
}
/**
* Add new {@link ContainerInitializerModel}
* @param serverModel
* @param model
*/
public void addContainerInitializerModel(ServerModel serverModel, ContainerInitializerModel model,
OsgiContextModel ... newModels) {
operations.add(new ContainerInitializerModelChange(OpCode.ADD, serverModel, model, newModels));
}
/**
* Remove existing {@link ContainerInitializerModel}
* @param serverModel
* @param models
*/
public void removeContainerInitializerModels(ServerModel serverModel, List<ContainerInitializerModel> models) {
operations.add(new ContainerInitializerModelChange(OpCode.DELETE, serverModel, models));
}
/**
* Add new {@link WelcomeFileModel}
* @param serverModel
* @param model
*/
public void addWelcomeFileModel(ServerModel serverModel, WelcomeFileModel model,
OsgiContextModel ... newModels) {
operations.add(new WelcomeFileModelChange(OpCode.ADD, serverModel, model, newModels));
}
/**
* Remove {@link WelcomeFileModel}
* @param serverModel
* @param model
*/
public void removeWelcomeFileModel(ServerModel serverModel, WelcomeFileModel model) {
operations.add(new WelcomeFileModelChange(OpCode.DELETE, serverModel, model));
}
/**
* Assuming everything is ok, this method simply invokes all the collected operations which will:<ul>
* <li>alter global {@link ServerModel} sequentially.</li>
* <li>alter actual server runtime</li>
* <li>...</li>
* </ul>
*/
public void accept(BatchVisitor visitor) {
for (Change op : operations) {
op.accept(visitor);
}
}
@Override
public String toString() {
return "Batch{\"" + description + "\"}";
}
}
| 33.750693 | 119 | 0.745404 |
c7024f42380716f2cbb1b420ee66239d62187b5c | 558 | package com.google.android.gms.internal.ads;
import org.json.JSONException;
import org.json.JSONObject;
/* renamed from: com.google.android.gms.internal.ads.jm */
final /* synthetic */ class C9519jm implements zzcuz {
/* renamed from: a */
static final zzcuz f22623a = new C9519jm();
private C9519jm() {
}
/* renamed from: a */
public final void mo28065a(Object obj) {
try {
((JSONObject) obj).getJSONObject("sdk_env").put("container_version", 12451009);
} catch (JSONException e) {
}
}
}
| 24.26087 | 91 | 0.637993 |
cf89109d2a610146a1f15a7b238ebbb696473803 | 479 | package com.baozi.pulsar.issue;
import org.apache.pulsar.client.admin.PulsarAdmin;
import org.apache.pulsar.client.api.PulsarClient;
/**
* @author baozi
*/
public class PulsarAdminTest {
public static void main(String[] args) throws Exception {
String serviceUrl = "https://localhost:8080";
String topic = "public/default/test_avro";
PulsarAdmin admin = PulsarAdmin.builder().serviceHttpUrl(serviceUrl).build();
admin.topics();
}
}
| 23.95 | 85 | 0.697286 |
9edaeb5e88ec41c2a5772bf2d4e86eb94d508283 | 402 | package me.jiangcai.crud.modify;
/**
* @author CJ
*/
public abstract class NullablePC implements PropertyChanger {
@Override
public Object change(Class type, Object origin) {
if (origin == null)
return null;
return nonNullChange(type, origin);
}
@SuppressWarnings("WeakerAccess")
protected abstract Object nonNullChange(Class type, Object origin);
}
| 23.647059 | 71 | 0.676617 |
5c2efd7598067dc679f62a3f699120cd5b6930fc | 1,621 | package com.paulandcode.entity;
import java.io.Serializable;
import java.util.List;
/**
*
* @description: 存放需要放入Redis缓存的数据的信息, 根据这些信息, 再通过Java反射获取数据.
* @author: paulandcode
* @email: paulandcode@gmail.com
* @since: 2018年9月8日 下午2:45:51
*/
public class Data implements Serializable {
private static final long serialVersionUID = 1L;
/** Redis缓存数据时的Key **/
private String key;
/** 所要执行方法所在类的全名称, 包括包名和类名 **/
private String className;
/** 所要执行方法的方法名 **/
private String methodName;
/** 所要执行方法的参数类型列表, 不能用数组, 否则FastJSON解析时会报错 **/
private List<Class<?>> paramTypes;
/** 所要执行方法的参数值列表, 不能用数组, 否则FastJSON解析时会报错 **/
private List<Object> params;
public Data() {
super();
}
public Data(String key, String className, String methodName, List<Class<?>> paramTypes, List<Object> params) {
super();
this.key = key;
this.className = className;
this.methodName = methodName;
this.paramTypes = paramTypes;
this.params = params;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public String getMethodName() {
return methodName;
}
public void setMethodName(String methodName) {
this.methodName = methodName;
}
public List<Class<?>> getParamTypes() {
return paramTypes;
}
public void setParamTypes(List<Class<?>> paramTypes) {
this.paramTypes = paramTypes;
}
public List<Object> getParams() {
return params;
}
public void setParams(List<Object> params) {
this.params = params;
}
} | 19.53012 | 111 | 0.703886 |
26cba373f96551ae4e4a39d96019fc44e1707ebe | 1,502 | package com.byteblogs.plumemo.auth.domain.vo;
import com.baomidou.mybatisplus.annotation.TableField;
import com.byteblogs.common.base.domain.vo.BaseVO;
import com.byteblogs.common.validator.annotion.IntegerNotNull;
import com.byteblogs.common.validator.annotion.NotBlank;
import com.byteblogs.plumemo.auth.domain.validator.InsertSocial;
import com.byteblogs.plumemo.auth.domain.validator.UpdateSocial;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import java.time.LocalDateTime;
/**
* 用户表社交信息表 实体类
* @author nosum
*/
@Data
@EqualsAndHashCode(callSuper = true)
@Accessors(chain = true)
public class AuthUserSocialVO extends BaseVO<AuthUserSocialVO> {
// columns START
@IntegerNotNull(groups = {UpdateSocial.class})
private Long id;
/**
* qq、csdn、wechat、weibo、email等
*/
@NotBlank(groups = {InsertSocial.class})
private String code;
/**
* 内容
*/
@TableField(value = "content")
private String content;
/**
* 展示类型( 1、显示二维码,2、显示账号,3、跳转链接)
*/
@TableField(value = "show_type")
private Integer showType;
/**
* 备注
*/
private String remark;
private String icon;
/**
* 是否删除
*/
@TableField(value = "is_enabled")
private Integer isEnabled;
/**
* 是否主页社交信息
*/
@TableField(value = "is_home")
private Integer isHome;
/**
* 创建时间
*/
@TableField(value = "create_time")
private LocalDateTime createTime;
/**
* 更新时间
*/
@TableField(value = "update_time")
private LocalDateTime updateTime;
// columns END
} | 20.297297 | 64 | 0.727031 |
6eb06e7d3aa7d4167f717025e0a0a4d2abb2170e | 2,106 | package gt.keybord;
import gt.keybord.elephant.R;
import gt.module.constants.AppConstants;
import gt.module.constants.ApplicationPrefs;
import com.example.android.softkeyboard.adapter.ListAdapter;
import com.startapp.android.publish.StartAppAd;
import com.startapp.android.publish.StartAppSDK;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
public class ThemesListActivity extends Activity implements OnItemClickListener{
ApplicationPrefs applicationPrefs;
private GridView listView_themes_list;
private ListAdapter listAdapter;
private StartAppAd startAppAd;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
StartAppSDK.init(ThemesListActivity.this, AppConstants.DeveloperID, AppConstants.ApplicationID, true);
setContentView(R.layout.activity_themes_list);
applicationPrefs = ApplicationPrefs.getInstance(this);
startAppAd = new StartAppAd(getApplicationContext());
initUI();
}
private void initUI() {
// TODO Auto-generated method stub
listAdapter = new ListAdapter(getApplicationContext());
listView_themes_list = (GridView) findViewById(R.id.listView_themes_list);
listView_themes_list.setAdapter(listAdapter);
listView_themes_list.setOnItemClickListener(this);
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
applicationPrefs.setThemesId(position+1);
startAppAd.showAd(); // show the ad
startAppAd.loadAd(); // load the next ad
}
@Override
public void onResume() {
super.onResume();
startAppAd.onResume();
}
@Override
public void onPause() {
super.onPause();
startAppAd.onPause();
}
@Override
public void onBackPressed() {
startAppAd.onBackPressed();
startAppAd.showAd(); // show the ad
startAppAd.loadAd(); // load the next ad
super.onBackPressed();
}
}
| 26.325 | 105 | 0.769706 |
62291407a487cb2d63fdbe4ea2acd51100059374 | 396 | package com.yahoo.vespa.hbase;
import org.apache.commons.codec.digest.DigestUtils;
public class KeyUtils {
public static String encodeKey(String key) {
byte[] sha = DigestUtils.sha1(key);
byte hash = sha[0];
return String.format("%02x:%s", hash, key);
}
public static String decodeKey(String key) {
String originKey = key.split(":", 2)[1];
return originKey;
}
}
| 20.842105 | 51 | 0.671717 |
94c4e8261b7ea48dc58a647d76cdfcae05cc30fa | 9,488 | package de.blau.android.util.mvt.style;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
import android.graphics.Rect;
import androidx.annotation.NonNull;
/**
* Simple collision detection
*
* For a small number of boxes simply sequentially iterating over the existing bounds is most efficient.
*
* To avoid re-constructing lots of boxes we hold them in a pool, the maximum number of boxes we can handle is set via
* the constructor.
*
* @author Simon
*
*/
public class SimpleCollisionDetector implements CollisionDetector {
private static final int DEFAULT_MAXIMUM = 200;
class Box {
private final float[][] vertices = new float[4][2];
private final float[] extreme = new float[] { Float.MAX_VALUE, 0 };
/**
* Check if other intersects this box
*
* @param other the other box
* @return true if it intersects
*/
public boolean intersect(@NonNull Box other) {
float[] start = vertices[0];
for (int i = 0; i < 3; i++) {
float[] next = vertices[(i + 1) % 4];
for (int j = 0; j < 3; j++) {
if (doIntersect(start, next, other.vertices[j], other.vertices[(j + 1) % 4])) {
return true;
}
}
start = next;
}
// is other completely inside
for (float[] p : other.vertices) {
if (isInside(this, p)) {
return true;
}
}
// is this completely inside other
for (float[] p : vertices) {
if (isInside(other, p)) {
return true;
}
}
return false;
}
/**
* Set the vertices of the box from a Rect
*
* @param rect the Rect
*/
public void from(@NonNull Rect rect) {
vertices[0][0] = rect.left;
vertices[0][1] = rect.top;
vertices[1][0] = rect.right;
vertices[1][1] = rect.top;
vertices[2][0] = rect.right;
vertices[2][1] = rect.bottom;
vertices[3][0] = rect.left;
vertices[3][1] = rect.bottom;
}
/**
* Set the vertices of the box from a line and a height
*
* @param start start coordinates
* @param end end coordinates
* @param height the height to use (total height is times 2)
*/
public void from(@NonNull float[] start, @NonNull float[] end, float height) {
float dX = end[0] - start[0];
float dY = end[1] - start[1];
float r = (float) Math.sqrt(dX * dX + dY * dY);
float xDiff = height / r * dY;
float yDiff = height / r * dX;
vertices[0][0] = start[0] + xDiff;
vertices[0][1] = start[1] + yDiff;
vertices[1][0] = end[0] + xDiff;
vertices[1][1] = end[1] + yDiff;
vertices[2][0] = end[0] - xDiff;
vertices[2][1] = end[1] - yDiff;
vertices[3][0] = start[0] - xDiff;
vertices[3][1] = start[1] - yDiff;
}
/**
* from https://www.geeksforgeeks.org/check-if-two-given-line-segments-intersect Given three colinear points p,
* q, r, the function checks if point q lies on line segment 'pr'
*
* @param p 1st point
* @param q 2nd point
* @param r 2rd point
* @return true is on line p - r
*/
boolean onSegment(@NonNull float[] p, @NonNull float[] q, @NonNull float[] r) {
return (q[0] <= Math.max(p[0], r[0]) && q[0] >= Math.min(p[0], r[0]) && q[1] <= Math.max(p[1], r[1]) && q[1] >= Math.min(p[1], r[1]));
}
/**
* Determine winding
*
* To find orientation of ordered triplet (p, q, r). T
*
* he function returns following values
*
* 0 --> p, q and r are colinear
*
* 1 --> Clockwise
*
* 2 --> Counterclockwise
*
* @param p 1st point
* @param q 2nd point
* @param r 3rd point
* @return winding value as described
*/
int orientation(@NonNull float[] p, @NonNull float[] q, @NonNull float[] r) {
// See https://www.geeksforgeeks.org/orientation-3-ordered-points/
// for details of below formula.
int val = (int) ((q[1] - p[1]) * (r[0] - q[0]) - (q[0] - p[0]) * (r[1] - q[1]));
if (val == 0) {
return 0; // colinear
}
return (val > 0) ? 1 : 2; // clock or counterclock wise
}
/**
* Determine if line segment 'p1q1' and 'p2q2' intersect.
*
* @param p1 start line 1
* @param q1 end line 1
* @param p2 start line 2
* @param q2 end line 2
* @return true if the lines intersect
*/
boolean doIntersect(@NonNull float[] p1, @NonNull float[] q1, @NonNull float[] p2, @NonNull float[] q2) {
// Find the four orientations needed for general and
// special cases
int o1 = orientation(p1, q1, p2);
int o2 = orientation(p1, q1, q2);
int o3 = orientation(p2, q2, p1);
int o4 = orientation(p2, q2, q1);
// General case
if (o1 != o2 && o3 != o4) {
return true;
}
// Special Cases
// p1, q1 and p2 are colinear and p2 lies on segment p1q1
if (o1 == 0 && onSegment(p1, p2, q1)) {
return true;
}
// p1, q1 and q2 are colinear and q2 lies on segment p1q1
if (o2 == 0 && onSegment(p1, q2, q1)) {
return true;
}
// p2, q2 and p1 are colinear and p1 lies on segment p2q2
if (o3 == 0 && onSegment(p2, p1, q2)) {
return true;
}
// p2, q2 and q1 are colinear and q1 lies on segment p2q2
return o4 == 0 && onSegment(p2, q1, q2);
}
/**
* Determine if point p is inside the polygon
*
* @param polygon the polygon
* @param p the point
* @return true if inside
*/
boolean isInside(@NonNull Box polygon, @NonNull float[] p) {
extreme[1] = p[1];
int intersections = 0;
int i = 0;
do {
int next = (i + 1) % 4;
if (doIntersect(polygon.vertices[i], polygon.vertices[next], p, extreme)) {
if (orientation(polygon.vertices[i], p, polygon.vertices[next]) == 0) {
return onSegment(polygon.vertices[i], p, polygon.vertices[next]);
}
intersections++;
}
i = next;
} while (i != 0);
return (intersections % 2 == 1);
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
for (float[] v : vertices) {
builder.append("[" + v[0] + "," + v[1] + "]");
}
return builder.toString();
}
}
private final List<Box> boxes = new ArrayList<>();
private final Deque<Box> pool = new ArrayDeque<>();
private final int max;
/**
* Construct a new instance
*/
public SimpleCollisionDetector() {
this(DEFAULT_MAXIMUM);
}
/**
* Construct a new instance
*
* @param max the maximum number of rects (and as a consequence labels) to handle
*/
public SimpleCollisionDetector(int max) {
this.max = max;
}
/**
* Resets the current set of collision boxes and returns them all to the pool
*/
@Override
public void reset() {
pool.addAll(boxes);
boxes.clear();
}
/**
* Check if rect collides with an existing one
*
* If there is no collision adds rect to the exiting ones
*
* @param rect the new Rect
* @return true if there is a collision
*/
@Override
public boolean collides(@NonNull Rect rect) {
if (pool.isEmpty()) {
if (boxes.size() > max) {
return false;
}
pool.add(new Box());
}
Box test = pool.pop();
test.from(rect);
return testForIntersection(test);
}
/**
* Actually test if the Box intersects
*
* @param test the Box
* @return true if it intersects with any of the existing Boxes
*/
private boolean testForIntersection(@NonNull Box test) {
for (Box box : boxes) {
if (box.intersect(test)) {
pool.add(test); // return to pool
return true;
}
}
boxes.add(test);
return false;
}
@Override
public boolean collides(float[] start, float[] end, float height) {
if (pool.isEmpty()) {
if (boxes.size() > max) {
return false;
}
pool.add(new Box());
}
Box test = pool.pop();
test.from(start, end, height);
return testForIntersection(test);
}
}
| 31.732441 | 146 | 0.487879 |
2b52691b76cd9bdd18b4f554489c766489888c64 | 1,122 | package com.newt.mapper.partial;
import com.newt.pojo.partial.UserMenu;
import com.newt.pojo.partial.UserMenuExample;
import com.newt.utils.mapper.BaseMapper;
import java.util.List;
import org.apache.ibatis.annotations.Param;
/**
* Created by Mybatis Generator on 2018/10/26
*/
public interface UserMenuMapper extends BaseMapper<UserMenu> {
long countByExample(UserMenuExample example);
int deleteByExample(UserMenuExample example);
int deleteByPrimaryKey(Integer id);
int insert(UserMenu record);
int insertSelectiveList(@Param("records") List<UserMenu> records);
int insertList(@Param("records") List<UserMenu> records);
int insertSelective(UserMenu record);
List<UserMenu> selectByExample(UserMenuExample example);
UserMenu selectByPrimaryKey(Integer id);
int updateByExampleSelective(@Param("record") UserMenu record, @Param("example") UserMenuExample example);
int updateByExample(@Param("record") UserMenu record, @Param("example") UserMenuExample example);
int updateByPrimaryKeySelective(UserMenu record);
int updateByPrimaryKey(UserMenu record);
} | 29.526316 | 110 | 0.770053 |
3119474e3f2a76113f86b786ff69ef765c9713e3 | 2,518 | /*
* 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.geode.modules.session.installer;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.charset.Charset;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.TemporaryFolder;
import org.apache.geode.test.junit.categories.SessionTest;
@Category(SessionTest.class)
public class InstallerJUnitTest {
@Rule
public TemporaryFolder temporaryFolder = new TemporaryFolder();
@Test
public void installIntoWebXML() throws Exception {
testTransformation("InstallerJUnitTest.web.xml");
}
private void testTransformation(final String name) throws Exception {
File webXmlFile = temporaryFolder.newFile();
FileUtils.copyFile(new File(getClass().getResource(name).getFile()), webXmlFile);
final String[] args = {"-t", "peer-to-peer", "-w", webXmlFile.getAbsolutePath()};
ByteArrayOutputStream output = new ByteArrayOutputStream();
try (InputStream input = new FileInputStream(webXmlFile)) {
new Installer(args).processWebXml(input, output);
}
String expected =
IOUtils.toString(getClass().getResource(name + ".expected"), Charset.defaultCharset())
.replaceAll(IOUtils.LINE_SEPARATOR_WINDOWS, "")
.replaceAll(IOUtils.LINE_SEPARATOR_UNIX, "");
String actual = output.toString().replaceAll(IOUtils.LINE_SEPARATOR_WINDOWS, "")
.replaceAll(IOUtils.LINE_SEPARATOR_UNIX, "");
assertThat(actual).isEqualToIgnoringWhitespace(expected);
}
}
| 38.738462 | 100 | 0.758539 |
55e13592b78a94916c98173a926773032318b983 | 1,840 | package com.hatemzidi.sandbox.keycloak;
import org.keycloak.authentication.AuthenticationFlowContext;
import org.keycloak.authentication.AuthenticationFlowError;
import org.keycloak.authentication.Authenticator;
import org.keycloak.authentication.authenticators.browser.UsernamePasswordForm;
import org.keycloak.events.Errors;
import org.keycloak.services.ServicesLogger;
import javax.ws.rs.core.MultivaluedMap;
public class AlternativeUsernamePasswordForm extends UsernamePasswordForm implements Authenticator {
protected static ServicesLogger log = ServicesLogger.LOGGER;
@Override
public void action(AuthenticationFlowContext context) {
MultivaluedMap<String, String> formData = context.getHttpRequest().getDecodedFormParameters();
if (formData.containsKey("cancel")) {
log.debug("alternative-username-password-form : Form was canceled.");
context.cancelLogin();
return;
}
if (!validateForm(context, formData)) {
log.debug("alternative-username-password-form : Oops! User is not valid : wrong credentials or unknown");
boolean isRequired = context.getExecution().isRequired();
if (!isRequired) {
log.debug("alternative-username-password-form : Execution is not required. Continuing the execution flow to the next 'alternative' task.");
context.attempted();
return;
}
log.debug("alternative-username-password-form : Resetting the flow, all stops here.");
context.getEvent().error(Errors.USER_NOT_FOUND);
context.failure(AuthenticationFlowError.UNKNOWN_USER);
return;
}
log.debug("alternative-username-password-form : User is valid and authenticated.");
context.success();
}
} | 40 | 155 | 0.700543 |
412d3ef4adbe6446c6ffff01a6cb8505a68c2b34 | 3,649 | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.download;
import android.app.DownloadManager;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
/**
* This {@link BroadcastReceiver} handles clicks to download notifications and their action buttons.
* Clicking on an in-progress or failed download will open the download manager. Clicking on
* a complete, successful download will open the file. Clicking on the resume button of a paused
* download will relaunch the browser process and try to resume the download from where it is
* stopped.
*/
public class DownloadBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, Intent intent) {
String action = intent.getAction();
switch (action) {
case DownloadManager.ACTION_NOTIFICATION_CLICKED:
openDownload(context, intent);
break;
case DownloadNotificationService.ACTION_DOWNLOAD_RESUME:
case DownloadNotificationService.ACTION_DOWNLOAD_CANCEL:
case DownloadNotificationService.ACTION_DOWNLOAD_PAUSE:
performDownloadOperation(context, intent);
break;
default:
break;
}
}
/**
* Called to open a given download item that is downloaded by the android DownloadManager.
* @param context Context of the receiver.
* @param intent Intent from the android DownloadManager.
*/
private void openDownload(final Context context, Intent intent) {
long ids[] =
intent.getLongArrayExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS);
if (ids == null || ids.length == 0) {
DownloadManagerService.openDownloadsPage(context);
return;
}
long id = ids[0];
DownloadManager manager =
(DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = manager.getUriForDownloadedFile(id);
if (uri == null) {
// Open the downloads page
DownloadManagerService.openDownloadsPage(context);
} else {
Intent launchIntent = new Intent(Intent.ACTION_VIEW);
launchIntent.setDataAndType(uri, manager.getMimeTypeForDownloadedFile(id));
launchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
context.startActivity(launchIntent);
} catch (ActivityNotFoundException e) {
DownloadManagerService.openDownloadsPage(context);
}
}
}
/**
* Called to perform a download operation. This will call the DownloadNotificationService
* to start the browser process asynchronously, and resume or cancel the download afterwards.
* @param context Context of the receiver.
* @param intent Intent retrieved from the notification.
*/
private void performDownloadOperation(final Context context, Intent intent) {
if (DownloadNotificationService.isDownloadOperationIntent(intent)) {
Intent launchIntent = new Intent(intent);
launchIntent.setComponent(new ComponentName(
context.getPackageName(), DownloadNotificationService.class.getName()));
context.startService(launchIntent);
}
}
} | 42.929412 | 100 | 0.684297 |
0ddc7b4c95146b1d0968ab42a5eff599721bac0f | 511 | package com.steven.game.service.impl;
import com.steven.game.dao.WxTokenMapper;
import com.steven.game.service.TokenService;
import com.steven.game.vo.WxToken;
import org.springframework.beans.factory.annotation.Autowired;
/**
* Created by tianshuai on 2017/9/20/020.
*/
public class TokenServiceImpl implements TokenService {
@Autowired
private WxTokenMapper wxTokenMapper;
@Override
public WxToken selectToken(WxToken wxToken) {
return wxTokenMapper.selectByPrimaryKey(0);
}
}
| 26.894737 | 62 | 0.767123 |
c8e340ba2fa00b8c129d9859dd4e4d154dbe0d40 | 837 | package br_com_gss_secao11;
/**
* AJ025
*
* Getters e Setters
* - Getters
* - é um metodo público, que serve para consultar dados;
* - A nomeclatura desses métodos é get_nome_do_atributo()
*
*/
public class AJ025{
public static void main(String[] args) {
Cliente guilherme = new Cliente("Guilherme", "Rua tal");
Cliente Maria = new Cliente("Maria", "Rua tal");
Conta conta_guilherme = new Conta(1, 100.0f, 300.0f, guilherme);
Conta conta_Maria = new Conta(2, 200.0f, 300.0f, Maria);
System.out.println("Saldo Guilherme " + conta_guilherme.getSaldo());
System.out.println("Saldo Maria " + conta_Maria.getSaldo());
conta_guilherme.sacar(300);
System.out.println("Saldo Guilherme (DEPOIS do saque): " + conta_guilherme.getSaldo());
}
} | 27.9 | 95 | 0.639188 |
037cc78b774078c6e44c67449919d812dac8f304 | 794 | package com.mchekin.leetcodesolutions.removeduplicatesfromsortedarray;
/**
* Problem: <a href="https://leetcode.com/problems/remove-duplicates-from-sorted-array/">Remove Duplicates from Sorted Array</a>
*
* <p>
* Time Complexity: O(n) (where n is the number of numbers in the array)
* Space Complexity: O(1)
*/
public class Solution {
public int removeDuplicates(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
int leftIndex = 1;
int rightIndex = 1;
while(rightIndex < nums.length) {
if (nums[rightIndex-1] != nums[rightIndex]) {
nums[leftIndex] = nums[rightIndex];
leftIndex++;
}
rightIndex++;
}
return leftIndex;
}
}
| 24.060606 | 128 | 0.575567 |
bf541299856f249cf85c95dd6d56ae4ff3632091 | 408 | package org.bird.breeze.util;
import org.junit.Test;
import redis.clients.jedis.Jedis;
public class RedisUtilsTest {
@Test
public void testRedisUtils(){
Jedis jedis = RedisUtils.getJedis();
jedis.setnx("test", "Hello World");
System.out.println("set redis value OK");
String value = jedis.get("test");
System.out.println("get redis value: "+value);
RedisUtils.returnResource(jedis);
}
}
| 20.4 | 48 | 0.715686 |
3c22fa8a33eb858bc7c997d4f2cb4cbfe3ded9c0 | 324 | package com.hangum.core;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class HelloWorldTest {
@Test
void hello() {
HelloWorld helloworld = new HelloWorld();
String returnValue = helloworld.hello("HI");
assertEquals(returnValue, "Hello HI");
}
} | 20.25 | 52 | 0.669753 |
db97ac8d145826da678a565d97c681ec9a68501e | 6,121 |
package com.huawei.bridge.common.config;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.huawei.bridge.common.util.LogUtils;
import com.huawei.bridge.common.util.StringUtils;
/**
* <p>Title: PassPropertyPlacehoder </p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2011</p>
* <p>Company: 华为技术有限公司</p>
* @author Lu Wei 163294
* @version V1.0
* @since 2012-4-13
*/
public final class PasswdPropertyPlaceholder
{
/**待加密的后缀*/
public static final String PWD_SUBFIX = ".password";
/**加密后的后缀*/
public static final String ENCRYPWD_SUBFIX = ".encryptpassword";
private static Logger log = LoggerFactory.getLogger(PasswdPropertyPlaceholder.class);
private static StandardEncryptor encryptor = null;
/**
* 是否需要更新工作秘钥
*/
private static boolean isNeedUpdateWorkKey = false;
/**
* 新工作秘钥的加密工具
*/
private static StandardEncryptor newEncryptor = null;
/**
* 工作秘钥的盐值
*/
public static final String WORKKEY_SALT = "bpst6Ghl08eluQxs8imQsw==";
private PasswdPropertyPlaceholder()
{
}
/**
* 在系统启动时,进行工作秘钥的初始化
*/
public static void init()
{
encryptor = new StandardEncryptor(RootKeyManager.getWorkKey(), WORKKEY_SALT);
isNeedUpdateWorkKey = RootKeyManager.isNeedUpdateWorkKey();
if (isNeedUpdateWorkKey)
{
newEncryptor = new StandardEncryptor(RootKeyManager.getNewWorkKey(), WORKKEY_SALT);
}
}
public static void clean()
{
encryptor = null;
newEncryptor = null;
}
/**
* 该函数主要作用:
* 1) 会对文件中的xxx.password的key进行处理,将其加密,并且替换为xxx.encryptpassword
* 并覆盖原始文件。
* 2) 对propsOut(包含的是处理器前原始文件的key/value)的密码相关属性值进行重新设置
* (xxx.password/xxx.encryptpassword), 替换为xxx/原始密码,供程序使用,
* 程序中只要查询xxx这个键值就可以了。
*
* @param file 需要进行密码替换的文件
* @param propsOut 替换原始文件的密码相关的key/value,如果原先xxx.password,
* 体内换成xxx;如果原始文件中是xxx.encryptpassword,也是替换成key,value都是密码的
* 明文。
*/
public static void loadProperties(String file, Properties propsOut)
{
FileInputStream in = null;
FileOutputStream out = null;
try
{
Properties propConfig = new Properties();
in = new FileInputStream(file);
propConfig.load(in);
propConfig.keySet().iterator();
Iterator<Object> propKeys = propConfig.keySet().iterator();
String propKey = null;
String propVal = null;
String tmpKey = null;
String tmpVal = null;
String tmpDecVal = null;
// 1. 处理密码
while (propKeys.hasNext())
{
propKey = (String) propKeys.next();
propVal = propConfig.getProperty(propKey);
if (propKey.endsWith(PWD_SUBFIX))
{
// 明文 -> 密文
// 配置文件中: XYZ.password -> XYZ.encryptpassword
tmpKey = propKey.replace(PWD_SUBFIX, ENCRYPWD_SUBFIX);
propConfig.setProperty(propKey, ""); // 删除配置文件中的原始密码
if (StringUtils.isNullOrBlank(propVal))
{
continue;
}
tmpVal = encryptor.encryptAES(propVal);
propConfig.setProperty(tmpKey, tmpVal);
// 更新内存中数据(XYZ.password -> XYZ)
propsOut.remove(propKey);
propsOut.setProperty(propKey.substring(0, propKey.length() - PWD_SUBFIX.length()), propVal);
}
else if (propKey.endsWith(ENCRYPWD_SUBFIX))
{
// 密文 -> 明文
// 更新内存中数据(XYZ.encryptpassword -> XYZ)
propsOut.remove(propKey);
if (StringUtils.isNullOrBlank(propVal))
{
propsOut.setProperty(
propKey.substring(0, propKey.length() - ENCRYPWD_SUBFIX.length()),
"");
}
else
{
tmpDecVal = encryptor.decryptAES(propVal);
propsOut.setProperty(
propKey.substring(0, propKey.length() - ENCRYPWD_SUBFIX.length()),
encryptor.decryptAES(propVal));
if (isNeedUpdateWorkKey)
{
//需要更新工作秘钥时,用新的工作秘钥进行加密
propConfig.setProperty(propKey,
newEncryptor.encryptAES(tmpDecVal));
}
}
}
}
// 2. 保存文件
in.close();
out = new FileOutputStream(file);
propConfig.store(out, "Update value");
}
catch (IOException e)
{
log.error("loadProperties {}", LogUtils.encodeForLog(e.getMessage()));
}
finally
{
if (null != in)
{
try
{
in.close();
}
catch (IOException e)
{
log.error("loadProperties {}", LogUtils.encodeForLog(e.getMessage()));
}
}
if (null != out)
{
try
{
out.close();
}
catch (IOException e)
{
log.error("loadProperties {}", LogUtils.encodeForLog(e.getMessage()));
}
}
}
}
}
| 30.30198 | 112 | 0.491096 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.