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 |
|---|---|---|---|---|---|
294163d8a435d621abca87f841857c25b606adc8 | 2,961 | package com.github.kilianB.mutable;
import java.io.Serializable;
/**
* Mutable class wrapper for integer values. Mutable classes are useful in
* lambda expressions or anonymous classes which want to alter the content of a
* variable but are limited to final or effective final variables.
*
* @author Kilian
* @since 1.0.0
*/
public class MutableInteger extends Number implements Mutable<Integer>, Comparable<MutableInteger>, Serializable {
private static final long serialVersionUID = 6846548022746719522L;
private int field;
/**
* Create a mutable Integer with an initial value of 0
*/
public MutableInteger() {
};
/**
* Create a mutable Integer.
*
* @param initialValue the initial value of the integer
*/
public MutableInteger(int initialValue) {
this.field = initialValue;
}
@Override
public int compareTo(MutableInteger o) {
return Integer.compare(field, o.field);
}
@Override
public Integer getValue() {
return Integer.valueOf(field);
}
@Override
public void setValue(Integer newValue) {
field = newValue;
}
/**
* Set the internal field to the new value
*
* @param newValue the new value
* @since 1.2.0
*/
public void setValue(int newValue) {
field = newValue;
}
@Override
public int intValue() {
return field;
}
@Override
public int hashCode() {
return field;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
MutableInteger other = (MutableInteger) obj;
if (field != other.field)
return false;
return true;
}
@Override
public long longValue() {
return field;
}
@Override
public float floatValue() {
return field;
}
@Override
public double doubleValue() {
return field;
}
/**
* Return the internal value and increment it afterwards.
*
* @return the value of the internal field before performing the increment
* operation.
* @since 1.2.0
*/
public Integer getAndIncrement() {
return Integer.valueOf(field++);
}
/**
* Increment the internal value and return the result.
*
* @return the new value after after performing the increment operation.
* @since 1.2.0
*/
public Integer incrementAndGet() {
return Integer.valueOf(++field);
}
/**
* Return the internal value and decrement it afterwards.
*
* @return the value of the internal field before performing the decrement
* operation.
* @since 1.2.0
*/
public Integer getAndDecrement() {
return Integer.valueOf(field--);
}
/**
* Decrement the internal value and return the result.
*
* @return the new value after after performing the decrement operation.
* @since 1.2.0
*/
public Integer decrementAndGet() {
return Integer.valueOf(--field);
}
}
| 21.15 | 115 | 0.655184 |
8291d3ff2d42b938f88160b208c5343d48825678 | 575 | package team.journey.mapper;
import team.journey.pojo.Page;
import team.journey.pojo.Route;
import team.journey.pojo.RouteQueryVo;
import java.util.List;
public interface RouteMapper {
int deleteByPrimaryKey(Integer rid);
int insert(Route record);
int insertSelective(Route record);
Route selectByPrimaryKey(Integer rid);
int updateByPrimaryKeySelective(Route record);
int updateByPrimaryKey(Route record);
int selectCountByVo(RouteQueryVo rqv);
List<Route> selectByVo(RouteQueryVo rqv);
/*Route selectByTitle(String title);*/
} | 21.296296 | 50 | 0.754783 |
8bfbfebb006a2a5295eb0dff635b93f3260951ea | 5,857 | /*
* Copyright 2016 IKS Gesellschaft fuer Informations- und Kommunikationssysteme mbH
*
* 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.iksgmbh.sql.pojomemodb.validator.type;
import com.iksgmbh.sql.pojomemodb.validator.TypeValidator;
import com.iksgmbh.sql.pojomemodb.SQLKeyWords;
import com.iksgmbh.sql.pojomemodb.utils.StringParseUtil;
import java.sql.SQLDataException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import static com.iksgmbh.sql.pojomemodb.SQLKeyWords.*;
public class DateTypeValidator extends TypeValidator
{
private static final ValidatorType VALIDATION_TYPE = ValidatorType.DATE;
private static final String DATE_IN_MILLIS = "DATE_IN_MILLIS:";
private static final SimpleDateFormat MYSQL_D_SIMPLEDATEFORMAT = new SimpleDateFormat("yyyy-MM-dd");
private static final SimpleDateFormat MYSQL_TS_SIMPLEDATEFORMAT = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
@Override
public void validateValueForType(Object value) throws SQLDataException
{
if (value == null) return; // nullable is not checked here
if (SQLKeyWords.NULL.equalsIgnoreCase(value.toString())) return;
try {
if (value instanceof String) {
convertIntoColumnType( (String) value );
return;
}
if (value instanceof Date) {
convertIntoColumnType( DATE_IN_MILLIS + ((Date)value).getTime() );
return;
}
throw new SQLDataException("Value '" + value + "' is not valid");
} catch (SQLDataException e) {
throw new SQLDataException("Value '" + value + "' is not valid");
}
}
@Override
public ValidatorType getType() {
return VALIDATION_TYPE;
}
@Override
public Object convertIntoColumnType(String valueAsString) throws SQLDataException
{
if (SYSDATE.equals(valueAsString)
|| CURRENT_TIMESTAMP.equals(valueAsString)
|| GET_DATE.equals(valueAsString)) {
return new Date();
}
if (valueAsString.startsWith("{") && valueAsString.endsWith("}")) {
return convertMySqlDateFormats(valueAsString);
}
if (valueAsString.startsWith(TO_DATE)) {
return toDate(valueAsString.substring(TO_DATE.length()));
}
if (valueAsString.startsWith(DATE_IN_MILLIS)) {
valueAsString = valueAsString.substring(DATE_IN_MILLIS.length());
return new Date(Long.valueOf(valueAsString));
}
throw new SQLDataException("Insert values '" + valueAsString + "' is no date.");
}
private Object convertMySqlDateFormats(String valueAsString) throws SQLDataException
{
try {
valueAsString = valueAsString.substring(1, valueAsString.length()-1).trim();
if (valueAsString.startsWith("d")) {
valueAsString = valueAsString.substring(1).trim();
if (valueAsString.startsWith("'") && valueAsString.endsWith("'")) {
valueAsString = valueAsString.substring(1, valueAsString.length()-1).trim();
return MYSQL_D_SIMPLEDATEFORMAT.parse(valueAsString);
}
}
if (valueAsString.startsWith("ts")) {
valueAsString = valueAsString.substring(2).trim();
if (valueAsString.startsWith("'") && valueAsString.endsWith("'")) {
valueAsString = valueAsString.substring(1, valueAsString.length()-1).trim();
return MYSQL_TS_SIMPLEDATEFORMAT.parse(valueAsString);
}
}
} catch (Exception pe) {
// do nothing here, handle exception below
}
throw new SQLDataException("Insert values '" + valueAsString + "' cannot be parsed into a date.");
}
private Date toDate(String dateString) throws SQLDataException
{
try {
dateString = StringParseUtil.removeSurroundingPrefixAndPostFix(dateString, "(", ")");
final String[] splitResult = dateString.split(",");
if (splitResult.length != 2) {
throw new SQLDataException("Cannot parse to DateTime: " + dateString);
}
final String dateValue = StringParseUtil.removeSurroundingPrefixAndPostFix(splitResult[0], "'", "'");
final String pattern = StringParseUtil.removeSurroundingPrefixAndPostFix(splitResult[1], "'", "'");
return toDate(dateValue, translateFromOracleToJavaLiterals(pattern));
} catch (Exception e) {
throw new SQLDataException(e);
}
}
private String translateFromOracleToJavaLiterals(String pattern)
{
return pattern.replace('R', 'y')
.replace('D', 'd');
}
private Date toDate(final String value,
final String pattern) throws SQLDataException
{
final SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
try {
return simpleDateFormat.parse(value);
} catch (ParseException e) {
throw new SQLDataException("Cannot convert DateTime: dateAsString=" + value + ", pattern=" + pattern);
}
}
@Override
public Boolean isValue1SmallerThanValue2(Object value1, Object value2) throws SQLDataException
{
if (value1 == null || value2 == null)
return isValue1SmallerThanValue2ForNullvalues(value1, value2);
final Date d1 = (Date) value1;
final Date d2 = (Date) value2;
int result = d1.compareTo(d2);
if (result == 0) return null;
return result == -1;
}
} | 34.251462 | 112 | 0.682261 |
844d2803ef658cdc9646c1ab6488341a63d99f68 | 778 | package softuni.exam.instagraphlite.adapters;
import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class LocalDateTimeAdapterJSON extends TypeAdapter<LocalDateTime> {
@Override
public void write(final JsonWriter jsonWriter, final LocalDateTime localDateTime ) throws IOException {
jsonWriter.value(localDateTime.toString());
}
@Override
public LocalDateTime read( final JsonReader jsonReader ) throws IOException {
return LocalDateTime.from(
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").parse(jsonReader.nextString())
);
}
}
| 31.12 | 107 | 0.753213 |
78e1b11d9363060e008ad6ff225c2534be014c51 | 8,726 | begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/* * 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. */
end_comment
begin_package
DECL|package|org.apache.camel.processor.onexception
package|package
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|processor
operator|.
name|onexception
package|;
end_package
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|ContextTestSupport
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|RuntimeCamelException
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|builder
operator|.
name|RouteBuilder
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|component
operator|.
name|mock
operator|.
name|MockEndpoint
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|camel
operator|.
name|impl
operator|.
name|JndiRegistry
import|;
end_import
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|Before
import|;
end_import
begin_import
import|import
name|org
operator|.
name|junit
operator|.
name|Test
import|;
end_import
begin_comment
comment|/** * Unit test inspired by user forum. */
end_comment
begin_class
DECL|class|OnExceptionRouteWithDefaultErrorHandlerTest
specifier|public
class|class
name|OnExceptionRouteWithDefaultErrorHandlerTest
extends|extends
name|ContextTestSupport
block|{
DECL|field|myOwnHandlerBean
specifier|private
name|MyOwnHandlerBean
name|myOwnHandlerBean
decl_stmt|;
DECL|field|myServiceBean
specifier|private
name|MyServiceBean
name|myServiceBean
decl_stmt|;
annotation|@
name|Test
DECL|method|testNoError ()
specifier|public
name|void
name|testNoError
parameter_list|()
throws|throws
name|Exception
block|{
name|MockEndpoint
name|mock
init|=
name|getMockEndpoint
argument_list|(
literal|"mock:result"
argument_list|)
decl_stmt|;
name|mock
operator|.
name|expectedMessageCount
argument_list|(
literal|1
argument_list|)
expr_stmt|;
name|template
operator|.
name|sendBody
argument_list|(
literal|"direct:start"
argument_list|,
literal|"<order><type>myType</type><user>James</user></order>"
argument_list|)
expr_stmt|;
name|assertMockEndpointsSatisfied
argument_list|()
expr_stmt|;
block|}
annotation|@
name|Test
DECL|method|testFunctionalError ()
specifier|public
name|void
name|testFunctionalError
parameter_list|()
throws|throws
name|Exception
block|{
name|MockEndpoint
name|mock
init|=
name|getMockEndpoint
argument_list|(
literal|"mock:result"
argument_list|)
decl_stmt|;
name|mock
operator|.
name|expectedMessageCount
argument_list|(
literal|0
argument_list|)
expr_stmt|;
name|template
operator|.
name|sendBody
argument_list|(
literal|"direct:start"
argument_list|,
literal|"<order><type>myType</type><user>Func</user></order>"
argument_list|)
expr_stmt|;
name|assertMockEndpointsSatisfied
argument_list|()
expr_stmt|;
name|assertEquals
argument_list|(
literal|"<order><type>myType</type><user>Func</user></order>"
argument_list|,
name|myOwnHandlerBean
operator|.
name|getPayload
argument_list|()
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
DECL|method|testTechnicalError ()
specifier|public
name|void
name|testTechnicalError
parameter_list|()
throws|throws
name|Exception
block|{
name|MockEndpoint
name|mock
init|=
name|getMockEndpoint
argument_list|(
literal|"mock:result"
argument_list|)
decl_stmt|;
name|mock
operator|.
name|expectedMessageCount
argument_list|(
literal|0
argument_list|)
expr_stmt|;
name|template
operator|.
name|sendBody
argument_list|(
literal|"direct:start"
argument_list|,
literal|"<order><type>myType</type><user>Tech</user></order>"
argument_list|)
expr_stmt|;
name|assertMockEndpointsSatisfied
argument_list|()
expr_stmt|;
comment|// should not handle it
name|assertNull
argument_list|(
name|myOwnHandlerBean
operator|.
name|getPayload
argument_list|()
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Test
DECL|method|testErrorWhileHandlingException ()
specifier|public
name|void
name|testErrorWhileHandlingException
parameter_list|()
throws|throws
name|Exception
block|{
name|MockEndpoint
name|mock
init|=
name|getMockEndpoint
argument_list|(
literal|"mock:result"
argument_list|)
decl_stmt|;
name|mock
operator|.
name|expectedMessageCount
argument_list|(
literal|0
argument_list|)
expr_stmt|;
try|try
block|{
name|template
operator|.
name|sendBody
argument_list|(
literal|"direct:start"
argument_list|,
literal|"<order><type>myType</type><user>FuncError</user></order>"
argument_list|)
expr_stmt|;
name|fail
argument_list|(
literal|"Should throw a RuntimeCamelException"
argument_list|)
expr_stmt|;
block|}
catch|catch
parameter_list|(
name|RuntimeCamelException
name|e
parameter_list|)
block|{
name|assertEquals
argument_list|(
literal|"Damn something did not work"
argument_list|,
name|e
operator|.
name|getCause
argument_list|()
operator|.
name|getMessage
argument_list|()
argument_list|)
expr_stmt|;
block|}
name|assertMockEndpointsSatisfied
argument_list|()
expr_stmt|;
comment|// should not handle it
name|assertNull
argument_list|(
name|myOwnHandlerBean
operator|.
name|getPayload
argument_list|()
argument_list|)
expr_stmt|;
block|}
annotation|@
name|Override
annotation|@
name|Before
DECL|method|setUp ()
specifier|public
name|void
name|setUp
parameter_list|()
throws|throws
name|Exception
block|{
name|myOwnHandlerBean
operator|=
operator|new
name|MyOwnHandlerBean
argument_list|()
expr_stmt|;
name|myServiceBean
operator|=
operator|new
name|MyServiceBean
argument_list|()
expr_stmt|;
name|super
operator|.
name|setUp
argument_list|()
expr_stmt|;
block|}
annotation|@
name|Override
DECL|method|createRegistry ()
specifier|protected
name|JndiRegistry
name|createRegistry
parameter_list|()
throws|throws
name|Exception
block|{
name|JndiRegistry
name|jndi
init|=
name|super
operator|.
name|createRegistry
argument_list|()
decl_stmt|;
name|jndi
operator|.
name|bind
argument_list|(
literal|"myOwnHandler"
argument_list|,
name|myOwnHandlerBean
argument_list|)
expr_stmt|;
name|jndi
operator|.
name|bind
argument_list|(
literal|"myServiceBean"
argument_list|,
name|myServiceBean
argument_list|)
expr_stmt|;
return|return
name|jndi
return|;
block|}
annotation|@
name|Override
DECL|method|createRouteBuilder ()
specifier|protected
name|RouteBuilder
name|createRouteBuilder
parameter_list|()
throws|throws
name|Exception
block|{
return|return
operator|new
name|RouteBuilder
argument_list|()
block|{
annotation|@
name|Override
specifier|public
name|void
name|configure
parameter_list|()
throws|throws
name|Exception
block|{
name|errorHandler
argument_list|(
name|defaultErrorHandler
argument_list|()
operator|.
name|maximumRedeliveries
argument_list|(
literal|5
argument_list|)
argument_list|)
expr_stmt|;
name|onException
argument_list|(
name|MyTechnicalException
operator|.
name|class
argument_list|)
operator|.
name|maximumRedeliveries
argument_list|(
literal|0
argument_list|)
operator|.
name|handled
argument_list|(
literal|true
argument_list|)
expr_stmt|;
name|onException
argument_list|(
name|MyFunctionalException
operator|.
name|class
argument_list|)
operator|.
name|maximumRedeliveries
argument_list|(
literal|0
argument_list|)
operator|.
name|handled
argument_list|(
literal|true
argument_list|)
operator|.
name|to
argument_list|(
literal|"bean:myOwnHandler"
argument_list|)
expr_stmt|;
name|from
argument_list|(
literal|"direct:start"
argument_list|)
operator|.
name|choice
argument_list|()
operator|.
name|when
argument_list|()
operator|.
name|xpath
argument_list|(
literal|"//type = 'myType'"
argument_list|)
operator|.
name|to
argument_list|(
literal|"bean:myServiceBean"
argument_list|)
operator|.
name|end
argument_list|()
operator|.
name|to
argument_list|(
literal|"mock:result"
argument_list|)
expr_stmt|;
block|}
block|}
return|;
block|}
block|}
end_class
end_unit
| 16.74856 | 810 | 0.80667 |
7ffe072a41129026bc817ab6210fe440ea5801ad | 5,938 | /*******************************************************************************
* Copyright (c) 2014, 2016 cryptomator.org
* This file is licensed under the terms of the MIT license.
* See the LICENSE.txt file for more info.
*
* Contributors:
* Tillmann Gaida - initial implementation
******************************************************************************/
package org.cryptomator.ui.util;
import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Collections;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.TimeUnit;
import org.cryptomator.ui.util.SingleInstanceManager.LocalInstance;
import org.cryptomator.ui.util.SingleInstanceManager.MessageListener;
import org.cryptomator.ui.util.SingleInstanceManager.RemoteInstance;
import org.junit.Test;
public class SingleInstanceManagerTest {
@Test(timeout = 10000)
public void testTryFillTimeout() throws Exception {
try (final ServerSocket socket = new ServerSocket(0)) {
// we need to asynchronously accept the connection
final ForkJoinTask<?> forked = ForkJoinTask.adapt(() -> {
try {
socket.setSoTimeout(1000);
socket.accept();
} catch (Exception e) {
throw new RuntimeException(e);
}
}).fork();
try (SocketChannel channel = SocketChannel.open()) {
channel.configureBlocking(false);
channel.connect(new InetSocketAddress(InetAddress.getLoopbackAddress(), socket.getLocalPort()));
TimeoutTask.attempt(t -> channel.finishConnect(), 1000, 1);
final ByteBuffer buffer = ByteBuffer.allocate(1);
SingleInstanceManager.tryFill(channel, buffer, 1000);
assertTrue(buffer.hasRemaining());
}
forked.join();
}
}
@Test(timeout = 10000)
public void testTryFill() throws Exception {
try (final ServerSocket socket = new ServerSocket(0)) {
// we need to asynchronously accept the connection
final ForkJoinTask<?> forked = ForkJoinTask.adapt(() -> {
try {
socket.setSoTimeout(1000);
socket.accept().getOutputStream().write(1);
} catch (Exception e) {
throw new RuntimeException(e);
}
}).fork();
try (SocketChannel channel = SocketChannel.open()) {
channel.configureBlocking(false);
channel.connect(new InetSocketAddress(InetAddress.getLoopbackAddress(), socket.getLocalPort()));
TimeoutTask.attempt(t -> channel.finishConnect(), 1000, 1);
final ByteBuffer buffer = ByteBuffer.allocate(1);
SingleInstanceManager.tryFill(channel, buffer, 1000);
assertFalse(buffer.hasRemaining());
}
forked.join();
}
}
String appKey = "APPKEY";
@Test
public void testOneMessage() throws Exception {
ExecutorService exec = Executors.newCachedThreadPool();
try {
final LocalInstance server = SingleInstanceManager.startLocalInstance(appKey, exec);
final Optional<RemoteInstance> r = SingleInstanceManager.getRemoteInstance(appKey);
CountDownLatch latch = new CountDownLatch(1);
final MessageListener listener = spy(new MessageListener() {
@Override
public void handleMessage(String message) {
latch.countDown();
}
});
server.registerListener(listener);
assertTrue(r.isPresent());
String message = "Is this thing on?";
assertTrue(r.get().sendMessage(message, 1000));
System.out.println("wrote message");
latch.await(10, TimeUnit.SECONDS);
verify(listener).handleMessage(message);
} finally {
exec.shutdownNow();
}
}
@Test(timeout = 60000)
public void testALotOfMessages() throws Exception {
final int connectors = 256;
final int messagesPerConnector = 256;
ExecutorService exec = Executors.newSingleThreadExecutor();
ExecutorService exec2 = Executors.newFixedThreadPool(16);
try (final LocalInstance server = SingleInstanceManager.startLocalInstance(appKey, exec)) {
Set<String> sentMessages = new ConcurrentSkipListSet<>();
Set<String> receivedMessages = new HashSet<>();
CountDownLatch sendLatch = new CountDownLatch(connectors);
CountDownLatch receiveLatch = new CountDownLatch(connectors * messagesPerConnector);
server.registerListener(message -> {
receivedMessages.add(message);
receiveLatch.countDown();
});
Set<RemoteInstance> instances = Collections.synchronizedSet(new HashSet<>());
for (int i = 0; i < connectors; i++) {
exec2.submit(() -> {
try {
final Optional<RemoteInstance> r = SingleInstanceManager.getRemoteInstance(appKey);
assertTrue(r.isPresent());
instances.add(r.get());
for (int j = 0; j < messagesPerConnector; j++) {
exec2.submit(() -> {
try {
for (;;) {
final String message = UUID.randomUUID().toString();
if (!sentMessages.add(message)) {
continue;
}
r.get().sendMessage(message, 1000);
break;
}
} catch (Exception e) {
e.printStackTrace();
}
});
}
sendLatch.countDown();
} catch (Throwable e) {
e.printStackTrace();
}
});
}
assertTrue(sendLatch.await(1, TimeUnit.MINUTES));
exec2.shutdown();
assertTrue(exec2.awaitTermination(1, TimeUnit.MINUTES));
assertTrue(receiveLatch.await(1, TimeUnit.MINUTES));
assertEquals(sentMessages, receivedMessages);
for (RemoteInstance remoteInstance : instances) {
try {
remoteInstance.close();
} catch (Exception e) {
e.printStackTrace();
}
}
} finally {
exec.shutdownNow();
exec2.shutdownNow();
}
}
}
| 29.542289 | 100 | 0.681711 |
0c04be96239dc40018561726ce87faa4d809dde6 | 2,368 | package be.kuleuven.cs.gridflex.io;
import com.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Map;
import java.util.Map.Entry;
/**
* Writes the results from experimentation to certain outputs (eg. a logger).
*
* @author Kristof Coninx (kristof.coninx AT cs.kuleuven.be)
*/
public class ResultWriter {
private final Logger logger;
private final Writable target;
private final Map<String, String> resultComponents;
/**
* Default constructor.
*
* @param target The target to take results from.
*/
public ResultWriter(final Writable target) {
this(target, "RESULTS");
}
/**
* Constructor creating new logger programmatically.
*
* @param target The target to take results from.
* @param filename The filename for the logger.
*/
public ResultWriter(final Writable target, final String filename) {
logger = LoggerFactory.getLogger(filename);
this.target = target;
this.resultComponents = Maps.newLinkedHashMap();
}
/**
* Write the outputs of the target.
*/
public synchronized void write() {
writeToLogger(buildMessage());
}
private String buildMessage() {
final StringBuilder b = new StringBuilder()
.append("Writing results:\n")
.append(target.getFormattedResultString())
.append("----------------\n");
if (!this.resultComponents.isEmpty()) {
b.append("Other result components:\n");
for (final Entry<String, String> entry : resultComponents.entrySet()) {
b.append(entry.getKey()).append(":").append(entry.getValue())
.append("\n");
}
}
b.append("----------------\n");
return b.toString();
}
private void writeToLogger(final String message) {
logger.info(message);
}
/**
* Add a key/value string component to this result writer.
*
* @param key the string indicating the key.
* @param value the value for the representing key.
*/
public void addResultComponent(final String key, final String value) {
this.resultComponents.put(key, value);
}
@Override
public String toString() {
return buildMessage();
}
}
| 28.53012 | 83 | 0.60853 |
95dd183894ffcf0747f321d4d199894bd4e710c5 | 483 | package org.camunda.bpm.cockpit.core.test.util;
import org.camunda.bpm.cockpit.test.util.DeploymentHelper;
import org.jboss.shrinkwrap.api.spec.WebArchive;
/**
* Tomcat test container
*
* @author nico.rehwaldt
*/
public class TestContainer {
public static void addContainerSpecificResources(WebArchive archive) {
archive
.addAsManifestResource("context.xml")
.addAsLibraries(DeploymentHelper.getResteasyJaxRs())
.addAsWebInfResource("web.xml");
}
}
| 23 | 72 | 0.749482 |
64502d8d36d5562d37921684abeeb56c60a60aa0 | 201 | package org.mimosaframework.orm.sql;
public interface CommonWhereCompareBuilder<T>
extends
AbsWhereValueBuilder<T>,
AbsColumnBuilder<T>,
OperatorFunctionBuilder<T> {
}
| 22.333333 | 45 | 0.701493 |
0f363291703937ce90c71c31534512e34782f422 | 484 |
package goja.castor.castor;
import java.util.Map;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import goja.castor.Castor;
import goja.exceptions.FailToCastObjectException;
@SuppressWarnings({"rawtypes"})
public class String2Map extends Castor<String, Map> {
@Override
public Map cast(String src, Class<?> toType, String... args) throws FailToCastObjectException {
return JSON.parseObject(src, new TypeReference<Map>(){});
}
}
| 24.2 | 99 | 0.752066 |
7389db97b5d4482b74c54a3965c8d283b0b227ca | 1,034 | package study.addressbook.tests;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import study.addressbook.model.GroupData;
import study.addressbook.model.Groups;
import java.util.Set;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.testng.Assert.assertEquals;
public class GroupDeletionTests extends TestBase {
@BeforeMethod
public void ensurePreconditions(){
app.goTo().groupPage();
if (app.group().all().size() == 0){
app.group().create(new GroupData().withName("studyGroup2"));
}
}
@Test
public void groupDeletion() {
Groups before = app.group().all();
GroupData deletedGroup = before.iterator().next();
app.group().delete(deletedGroup);
assertThat(app.group().count(),equalTo(before.size() - 1));
Set<GroupData> after = app.group().all();
assertThat(after, equalTo(before.without(deletedGroup)));
}
}
| 27.945946 | 72 | 0.680851 |
867997e366f596041b14befb371cb9bf23dbcd27 | 2,140 | /*
Copyright 2020 The Cytoscape Consortium
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package org.cytoscape.file_transfer.internal;
import java.io.File;
import org.cytoscape.work.AbstractTaskFactory;
import org.cytoscape.work.TaskIterator;
public class FromSandboxTaskFactory extends AbstractTaskFactory{
public static final String DESCRIPTION = "Transfer a file from sandbox";
//Note: we can use markdown in our long descriptions, hence the ``` code block style.
public static final String LONG_DESCRIPTION = "Given a sandbox (as ```sandboxName```) and file within it (as ```fileName```), returns a Base64-encoded file image ```fileBase64```, the full file path ```filePath``` and a small amount of file metadata ```fileByteCount``` and ```modifiedTime```.";
private File sandboxParentDirFile;
public FromSandboxTaskFactory(File sandboxParentDirFile) {
super();
this.sandboxParentDirFile = sandboxParentDirFile;
}
public boolean isReady() {
return true;
}
public TaskIterator createTaskIterator() {
return new TaskIterator(new FromSandboxTask(sandboxParentDirFile));
}
}
| 46.521739 | 297 | 0.765888 |
9600aa75e8ce454be9ef37c280a3f2265ebebfa9 | 1,957 | package com.pm.server.repository;
import java.util.List;
import com.pm.server.datatype.Coordinate;
import com.pm.server.datatype.Pacdot;
public interface PacdotRepository {
/**
* Adds a pacdot to the repository.
*
* @param pacdot Pacdot to be added
* @throws IllegalArgumentException if a pacdot already exists at the
* given location
* @throws NullPointerException if the pacdot or the location is null
*/
void addPacdot(Pacdot pacdot)
throws IllegalArgumentException, NullPointerException;
/**
* Deletes a pacdot from the repository.
*
* @param location Location of the pacdot
* @throws IllegalArgumentException if the pacdot does not exist in
* the repository
* @throws NullPointerException if the location is null
*/
void deletePacdotByLocation(Coordinate location)
throws IllegalArgumentException, NullPointerException;
/**
* Retrieves the pacdot at the given location.
*
* Returns null if no pacdot with the given location is found
*
* @param location Location of the requested pacdot
* @throws NullPointerException if the location is null
* @return the requested pacdot
*/
Pacdot getPacdotByLocation(Coordinate location)
throws NullPointerException;
/**
* Retrieves all pacdots in the repository.
*
* @return all pacdots
*/
List<Pacdot> getAllPacdots();
/**
* Sets the eaten status of a pacdot to true/false.
*
* Idempotent (e.g. eaten to eaten is valid)
*
* @param location Location of the requested pacdot
* @param eaten Whether or not the pacdot has been eaten
* @throws NullPointerException if the location given is null
*/
void setEatenStatusByLocation(Coordinate location, boolean eaten)
throws NullPointerException;
/**
* Resets all Pacdots to uneaten.
*
* Idempotent (e.g. can be used when no Pacdots have been eaten yet)
*
*/
void resetPacdots();
/**
* Removes all pacdots from the repository.
*/
void clear();
}
| 25.415584 | 70 | 0.727133 |
6b7e1ee1097565dc1ba929ac6e14dd885f1fcf22 | 2,055 | /*
* Copyright (c) 2014 ICM Uniwersytet Warszawski All rights reserved.
* See LICENCE.txt file for licensing information.
*/
package pl.edu.icm.unity.server.translation.in;
import org.apache.log4j.Logger;
import org.apache.log4j.NDC;
import pl.edu.icm.unity.exceptions.EngineException;
import pl.edu.icm.unity.server.authn.remote.RemotelyAuthenticatedInput;
import pl.edu.icm.unity.server.translation.ExecutionBreakException;
import pl.edu.icm.unity.server.translation.TranslationActionInstance;
import pl.edu.icm.unity.server.utils.Log;
import pl.edu.icm.unity.types.translation.TranslationActionType;
/**
* Instance of this interface is configured with parameters and performs a translation
* of a remotely obtained information about a client.
* @author K. Benedyczak
*/
public abstract class InputTranslationAction extends TranslationActionInstance
{
private static final Logger LOG = Log.getLogger(Log.U_SERVER_TRANSLATION, InputTranslationAction.class);
public InputTranslationAction(TranslationActionType actionType, String[] parameters)
{
super(actionType, parameters);
}
/**
* Performs the translation.
* @param input
* @param mvelCtx context which can be used in MVEL expression evaluation
* @param currentProfile name of the current profile
* @return result of the mapping
* @throws EngineException when an error occurs. You can throw {@link ExecutionBreakException}
* to gently stop the processing of further rules.
*/
public final MappingResult invoke(RemotelyAuthenticatedInput input, Object mvelCtx,
String currentProfile) throws EngineException
{
try
{
NDC.push("[" + input + "]");
return invokeWrapped(input, mvelCtx, currentProfile);
} catch (Exception e)
{
if (LOG.isDebugEnabled())
{
LOG.debug("Error getting mapping result.", e);
}
throw new EngineException(e);
} finally
{
NDC.pop();
}
}
protected abstract MappingResult invokeWrapped(RemotelyAuthenticatedInput input, Object mvelCtx,
String currentProfile) throws EngineException;
}
| 31.136364 | 105 | 0.764477 |
3cb132462583009a2b654951b4e47fdbece699b0 | 483 | package com.nealma.util;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Created by neal.ma on 3/30/16.
*/
public class TimeTools {
public static String getDateString(Date date){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return sdf.format(date);
}
public static void main(String[] args) throws ParseException {
System.out.println(getDateString(new Date()));
}
}
| 23 | 75 | 0.691511 |
163a1eddcdcbfac24450ebe0102e08d7ad6bbba9 | 3,681 | package com.swmansion.reanimated.bridging;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.facebook.react.bridge.Dynamic;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableNativeArray;
import com.facebook.react.bridge.ReadableNativeMap;
import com.facebook.react.bridge.ReadableType;
import com.facebook.react.bridge.WritableNativeArray;
import static com.swmansion.reanimated.bridging.BridgingUtils.toDouble;
public class ReanimatedWritableNativeArray extends WritableNativeArray implements ReanimatedBridge.ReanimatedArray {
public static ReanimatedWritableNativeArray fromArray(Object[] array){
ReanimatedWritableNativeArray out = new ReanimatedWritableNativeArray();
for (int i = 0; i < array.length; i++) {
out.pushDynamic(BridgingUtils.nativeCloneDeep(array[i]));
}
return out;
}
public static ReanimatedWritableNativeArray fromArray(ReadableArray array) {
if (array instanceof ReanimatedWritableNativeArray) {
return ((ReanimatedWritableNativeArray) array);
} else {
ReanimatedWritableNativeArray out = new ReanimatedWritableNativeArray();
for (Object value: array.toArrayList()) {
out.pushDynamic(BridgingUtils.nativeCloneDeep(value));
}
return out;
}
}
private final ReadableArrayResolver resolver;
public ReanimatedWritableNativeArray() {
super();
resolver = new ReadableArrayResolver(this);
}
@Override
public Object resolve(int index) {
return new ReanimatedDynamic(getDynamic(index)).value();
}
@Override
public ReadableArrayResolver resolver() {
return resolver;
}
@Nullable
@Override
public ReadableNativeArray getArray(int index) {
index = resolver.resolveIndex(index);
return fromArray(super.getArray(index));
}
@Override
public boolean getBoolean(int index) {
index = resolver.resolveIndex(index);
return super.getType(index) == ReadableType.Boolean ?
super.getBoolean(index) :
super.getDouble(index) == 1;
}
@Override
public double getDouble(int index) {
index = resolver.resolveIndex(index);
return super.getType(index) == ReadableType.Boolean ?
toDouble(super.getBoolean(index)) :
super.getDouble(index);
}
@NonNull
@Override
public Dynamic getDynamic(int index) {
index = resolver.resolveIndex(index);
return super.getDynamic(index);
}
@Override
public void pushDynamic(Object o) {
ReadableArrayResolver.pushVariant(this, BridgingUtils.nativeCloneDeep(o));
}
@Override
public int getInt(int index) {
index = resolver.resolveIndex(index);
return super.getInt(index);
}
@Nullable
@Override
public ReadableNativeMap getMap(int index) {
index = resolver.resolveIndex(index);
return ReanimatedWritableNativeMap.fromMap(super.getMap(index));
}
@Nullable
@Override
public String getString(int index) {
index = resolver.resolveIndex(index);
return super.getString(index);
}
@NonNull
@Override
public ReadableType getType(int index) {
index = resolver.resolveIndex(index);
return super.getType(index);
}
public ReanimatedWritableNativeArray copy() {
ReanimatedWritableNativeArray copy = new ReanimatedWritableNativeArray();
ReadableArrayResolver.addAll(copy, this);
return copy;
}
}
| 29.685484 | 116 | 0.677262 |
01e60fb57c3aff5a388d738cb5241f17d84e0f14 | 945 | package org.interonet.mercury.controller;
import org.interonet.mercury.domain.auth.Credential;
import org.interonet.mercury.domain.auth.Token;
import org.interonet.mercury.service.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(value = "/auth")
@EnableAutoConfiguration
public class AuthController {
@Autowired
AuthService authService;
@RequestMapping(value = "/token", method = RequestMethod.POST)
public Token postUser(@RequestBody Credential credential) throws Exception {
return authService.updateTokenByCredential(credential);
}
} | 39.375 | 80 | 0.822222 |
1c5c4da939ed226f8552d5d274602e3cb14f4457 | 1,665 | package com.sunkuet02.micro.authentication.controller;
import com.sunkuet02.micro.authentication.dto.request.LoginRequest;
import com.sunkuet02.micro.authentication.dto.response.LoginResponse;
import com.sunkuet02.micro.authentication.security.jwt.JwtTokenProvider;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class AuthController {
private final static Logger logger = LogManager.getLogger(AuthController.class);
private final AuthenticationManager authenticationManager;
private final JwtTokenProvider tokenProvider;
public AuthController(AuthenticationManager authenticationManager, JwtTokenProvider tokenProvider) {
this.authenticationManager = authenticationManager;
this.tokenProvider = tokenProvider;
}
@PostMapping("/login")
public LoginResponse login(@RequestBody LoginRequest request) {
authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(request.getUsername(), request.getPassword()));
String token = tokenProvider.createToken(request.getUsername(), request.getPassword());
logger.info("Created token for {}", request.getUsername());
return new LoginResponse(token);
}
}
| 42.692308 | 130 | 0.811411 |
0012c416b55d6c140f7d79ea9d64a136b976e284 | 438 | package com.example.nasa;
import com.example.nasa.config.Config;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
@SpringBootApplication
public class NasaApplication {
public static void main(String[] args) {
SpringApplication.run(NasaApplication.class, args);
}
}
| 27.375 | 81 | 0.810502 |
99fe776c058158091a75c11f20a794248c23c244 | 2,819 | package com.easy.core.install;
import com.easy.core.action.function.ExecuteXmlSqlAction;
import com.easy.core.icons.EasyIcon;
import com.intellij.execution.lineMarker.RunLineMarkerContributor;
import com.intellij.openapi.actionSystem.ActionManager;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.ui.Messages;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.intellij.psi.impl.source.xml.XmlTagImpl;
import com.intellij.psi.xml.XmlFile;
import com.intellij.psi.xml.XmlTag;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MybatisXmlContributor extends RunLineMarkerContributor {
private final List<String> sqlMethod = new ArrayList<>(Arrays.asList("select", "update", "insert", "delete"));
@Nullable
@Override
public Info getInfo(@NotNull PsiElement element) {
try {
PsiFile containingFile = element.getContainingFile();
if (containingFile instanceof XmlFile && element instanceof XmlTag) {
boolean anyMatch = sqlMethod.parallelStream().anyMatch(p -> ((XmlTagImpl) element).getName().equals(p));
if (anyMatch) {
AnAction[] array = new AnAction[1];
array[0] = new AnAction("execute") {
@Override
public void actionPerformed(@NotNull AnActionEvent anActionEvent) {
ExecuteXmlSqlAction executeXmlSqlAction = (ExecuteXmlSqlAction) ActionManager.getInstance().getAction("ExecuteXmlSqlActionId");
executeXmlSqlAction.setPsiElement(element);
executeXmlSqlAction.actionPerformed(anActionEvent);
}
};
// array[1] = new AnAction("SQM") {
// @Override
// public void actionPerformed(@NotNull AnActionEvent anActionEvent) {
// SqmScanAction sqmScanAction = (SqmScanAction) ActionManager.getInstance().getAction("SqmScanActionId");
// sqmScanAction.setPsiElement(element);
// sqmScanAction.actionPerformed(anActionEvent);
// }
// };
return new Info(EasyIcon.RUN, array, psiElement1 -> "request");
}
}
} catch (Exception e) {
System.out.println("MybatisXmlContributor.getInfo");
e.printStackTrace();
Messages.showErrorDialog(e.getMessage(), "MybatisXmlContributor");
}
return null;
}
}
| 43.369231 | 155 | 0.628237 |
818d8d62ded3ece0b2a56a5f893f05cc9a98a23a | 665 | package yuown.isee.jpa.repository;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Repository;
import yuown.isee.entity.Configuration;
@Repository
public interface ConfigurationRepository extends BaseRepository<Configuration, Integer> {
public Configuration findByName(String name);
public Page<Configuration> findAllByNameLikeOrderByIdDesc(String string, Pageable pageRequest);
public Page<Configuration> findAllByNameLike(String string, Pageable pageRequest);
public List<Configuration> findByAutoLoad(boolean autoLoad);
} | 30.227273 | 97 | 0.81203 |
57cda67d13ec6ed32e9807657380d6c4682b1c46 | 535 | package org.yuequan.thread.practice.single.thread.execution.extra;
import java.util.Random;
public class UserThread extends Thread{
private final static Random random = new Random(26535);
private final BoundedResource resource;
public UserThread(BoundedResource resource){
this.resource = resource;
}
@Override
public void run() {
try {
while (true){
resource.use();
Thread.sleep(3000);
}
}catch (InterruptedException e){}
}
}
| 23.26087 | 66 | 0.624299 |
88fa622fd3dfff7e7b4553020b590eb39f1c4e39 | 2,216 | package io.coronet.slug;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import io.coronet.slug.antlr.SlugParser.DocsContext;
import io.coronet.slug.antlr.SlugParser.FieldContext;
import io.coronet.slug.antlr.SlugParser.SlugContext;
/**
* Freemarker model type for a slug.
*/
public class SlugModel {
private final String pkg;
private final String docs;
private final String name;
private final List<FieldModel> fields;
/**
* @param pkg the java package for this slug
* @param context the antlr context to adapt from
*/
public SlugModel(String pkg, SlugContext context) {
this(pkg,
docsFrom(context.docs()),
context.name().getText(),
fieldsFrom(context.fields().field()));
}
private static String docsFrom(DocsContext docs) {
return (docs == null || docs.docstring() == null ? null : docs.docstring().getText());
}
private static List<FieldModel> fieldsFrom(List<FieldContext> fields) {
List<FieldModel> result = new ArrayList<>(fields.size());
for (FieldContext field : fields) {
result.add(new FieldModel(field));
}
return result;
}
/**
* @param pkg the java package for this slug
* @param docs the docstring for this slug
* @param name the name of this slug
* @param fields the field models for this slug
*/
public SlugModel(
String pkg,
String docs,
String name,
List<FieldModel> fields) {
this.pkg = pkg;
this.docs = docs;
this.name = name;
this.fields = fields;
}
/**
* @return the java package for this slug
*/
public String getPackage() {
return pkg;
}
/**
* @return the docstring for this slug
*/
public String getDocs() {
return docs;
}
/**
* @return the name of this slug
*/
public String getName() {
return name;
}
/**
* @return the list of fields for this slug
*/
public List<FieldModel> getFields() {
return Collections.unmodifiableList(fields);
}
}
| 24.622222 | 94 | 0.598827 |
3f0d5b96b1403b47293a2fe4904dbcff1161fd3b | 6,119 | /*
* Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.carbon.identity.api.server.application.management.v1.core.functions.application.inbound;
import org.wso2.carbon.identity.api.server.application.management.v1.core.functions.application.inbound.oauth2.OAuthInboundFunctions;
import org.wso2.carbon.identity.api.server.application.management.v1.core.functions.application.inbound.saml.SAMLInboundFunctions;
import org.wso2.carbon.identity.application.authentication.framework.util.FrameworkConstants;
import org.wso2.carbon.identity.application.common.model.InboundAuthenticationConfig;
import org.wso2.carbon.identity.application.common.model.InboundAuthenticationRequestConfig;
import org.wso2.carbon.identity.application.common.model.ServiceProvider;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* Utility functions related to application inbound protocols.
*/
public class InboundFunctions {
private InboundFunctions() {
}
/**
* Extract the inbound configuration of a particular type from an application and converts it to the API model.
*
* @param application
* @param inboundType Inbound Type
* @return
*/
public static InboundAuthenticationRequestConfig getInboundAuthenticationRequestConfig(ServiceProvider application,
String inboundType) {
InboundAuthenticationConfig inboundAuthConfig = application.getInboundAuthenticationConfig();
if (inboundAuthConfig != null) {
InboundAuthenticationRequestConfig[] inbounds = inboundAuthConfig.getInboundAuthenticationRequestConfigs();
if (inbounds != null) {
return Arrays.stream(inbounds)
.filter(inbound -> inboundType.equals(inbound.getInboundAuthType()))
.findAny()
.orElse(null);
}
}
return null;
}
public static String getInboundAuthKey(ServiceProvider application,
String inboundType) {
InboundAuthenticationConfig inboundAuthConfig = application.getInboundAuthenticationConfig();
if (inboundAuthConfig != null) {
InboundAuthenticationRequestConfig[] inbounds = inboundAuthConfig.getInboundAuthenticationRequestConfigs();
if (inbounds != null) {
return Arrays.stream(inbounds)
.filter(inbound -> inboundType.equals(inbound.getInboundAuthType()))
.findAny()
.map(InboundAuthenticationRequestConfig::getInboundAuthKey)
.orElse(null);
}
}
return null;
}
public static void rollbackInbounds(List<InboundAuthenticationRequestConfig> currentlyAddedInbounds) {
for (InboundAuthenticationRequestConfig inbound : currentlyAddedInbounds) {
rollbackInbound(inbound);
}
}
public static void rollbackInbound(InboundAuthenticationRequestConfig inbound) {
switch (inbound.getInboundAuthType()) {
case FrameworkConstants.StandardInboundProtocols.SAML2:
SAMLInboundFunctions.deleteSAMLServiceProvider(inbound);
break;
case FrameworkConstants.StandardInboundProtocols.OAUTH2:
OAuthInboundFunctions.deleteOAuthInbound(inbound);
break;
case FrameworkConstants.StandardInboundProtocols.WS_TRUST:
WSTrustInboundFunctions.deleteWSTrustConfiguration(inbound);
break;
default:
// No rollbacks required for other inbounds.
break;
}
}
public static void updateOrInsertInbound(ServiceProvider application,
InboundAuthenticationRequestConfig newInbound) {
InboundAuthenticationConfig inboundAuthConfig = application.getInboundAuthenticationConfig();
if (inboundAuthConfig != null) {
InboundAuthenticationRequestConfig[] inbounds = inboundAuthConfig.getInboundAuthenticationRequestConfigs();
if (inbounds != null) {
Map<String, InboundAuthenticationRequestConfig> inboundAuthConfigs =
Arrays.stream(inbounds).collect(
Collectors.toMap(InboundAuthenticationRequestConfig::getInboundAuthType,
Function.identity()));
inboundAuthConfigs.put(newInbound.getInboundAuthType(), newInbound);
inboundAuthConfig.setInboundAuthenticationRequestConfigs(
inboundAuthConfigs.values().toArray(new InboundAuthenticationRequestConfig[0]));
} else {
addNewInboundToSp(application, newInbound);
}
} else {
// Create new inbound auth config.
addNewInboundToSp(application, newInbound);
}
}
private static void addNewInboundToSp(ServiceProvider application, InboundAuthenticationRequestConfig newInbound) {
InboundAuthenticationConfig inboundAuth = new InboundAuthenticationConfig();
inboundAuth.setInboundAuthenticationRequestConfigs(new InboundAuthenticationRequestConfig[]{newInbound});
application.setInboundAuthenticationConfig(inboundAuth);
}
}
| 43.707143 | 133 | 0.674947 |
83e3942eb29b0500ad974e4307b40f42b854498a | 9,705 | /*
* Copyright 1999-2019 Seata.io Group.
*
* 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.seata.core.store.db.sql.log;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
/**
* @author: will
*/
public class LogStoreSqlsFactoryTest {
private static LogStoreSqls mysqlLog = LogStoreSqlsFactory.getLogStoreSqls("mysql");
private static LogStoreSqls oracleLog = LogStoreSqlsFactory.getLogStoreSqls("oracle");
private static LogStoreSqls pgLog = LogStoreSqlsFactory.getLogStoreSqls("postgresql");
private static LogStoreSqls h2Log = LogStoreSqlsFactory.getLogStoreSqls("h2");
private static LogStoreSqls oceanbase = LogStoreSqlsFactory.getLogStoreSqls("oceanbase");
private static String globalTable = "global_table";
private static String branchTable = "branch_table";
@Test
public void mysqlLogTest() {
String sql = mysqlLog.getInsertGlobalTransactionSQL(globalTable);
Assertions.assertNotNull(sql);
sql = mysqlLog.getUpdateGlobalTransactionStatusSQL(globalTable);
Assertions.assertNotNull(sql);
sql = mysqlLog.getDeleteGlobalTransactionSQL(globalTable);
Assertions.assertNotNull(sql);
sql = mysqlLog.getQueryGlobalTransactionSQL(globalTable);
Assertions.assertNotNull(sql);
sql = mysqlLog.getQueryGlobalTransactionSQLByTransactionId(globalTable);
Assertions.assertNotNull(sql);
sql = mysqlLog.getQueryGlobalTransactionSQLByStatus(globalTable, "1");
Assertions.assertNotNull(sql);
sql = mysqlLog.getQueryGlobalTransactionForRecoverySQL(globalTable);
Assertions.assertNotNull(sql);
sql = mysqlLog.getInsertBranchTransactionSQL(branchTable);
Assertions.assertNotNull(sql);
sql = mysqlLog.getUpdateBranchTransactionStatusSQL(branchTable);
Assertions.assertNotNull(sql);
sql = mysqlLog.getDeleteBranchTransactionByBranchIdSQL(branchTable);
Assertions.assertNotNull(sql);
sql = mysqlLog.getDeleteBranchTransactionByXId(branchTable);
Assertions.assertNotNull(sql);
sql = mysqlLog.getQueryBranchTransaction(branchTable);
Assertions.assertNotNull(sql);
sql = mysqlLog.getQueryBranchTransaction(branchTable, "1");
Assertions.assertNotNull(sql);
sql = mysqlLog.getQueryGlobalMax(globalTable);
Assertions.assertNotNull(sql);
sql = mysqlLog.getQueryBranchMax(branchTable);
Assertions.assertNotNull(sql);
}
@Test
public void oracleLogTest() {
String sql = oracleLog.getInsertGlobalTransactionSQL(globalTable);
Assertions.assertNotNull(sql);
sql = oracleLog.getUpdateGlobalTransactionStatusSQL(globalTable);
Assertions.assertNotNull(sql);
sql = oracleLog.getDeleteGlobalTransactionSQL(globalTable);
Assertions.assertNotNull(sql);
sql = oracleLog.getQueryGlobalTransactionSQL(globalTable);
Assertions.assertNotNull(sql);
sql = oracleLog.getQueryGlobalTransactionSQLByTransactionId(globalTable);
Assertions.assertNotNull(sql);
sql = oracleLog.getQueryGlobalTransactionSQLByStatus(globalTable, "1");
Assertions.assertNotNull(sql);
sql = oracleLog.getQueryGlobalTransactionForRecoverySQL(globalTable);
Assertions.assertNotNull(sql);
sql = oracleLog.getInsertBranchTransactionSQL(branchTable);
Assertions.assertNotNull(sql);
sql = oracleLog.getUpdateBranchTransactionStatusSQL(branchTable);
Assertions.assertNotNull(sql);
sql = oracleLog.getDeleteBranchTransactionByBranchIdSQL(branchTable);
Assertions.assertNotNull(sql);
sql = oracleLog.getDeleteBranchTransactionByXId(branchTable);
Assertions.assertNotNull(sql);
sql = oracleLog.getQueryBranchTransaction(branchTable);
Assertions.assertNotNull(sql);
sql = oracleLog.getQueryBranchTransaction(branchTable, "1");
Assertions.assertNotNull(sql);
sql = oracleLog.getQueryGlobalMax(globalTable);
Assertions.assertNotNull(sql);
sql = oracleLog.getQueryBranchMax(branchTable);
Assertions.assertNotNull(sql);
}
@Test
public void pgLogTest() {
String sql = pgLog.getInsertGlobalTransactionSQL(globalTable);
Assertions.assertNotNull(sql);
sql = pgLog.getUpdateGlobalTransactionStatusSQL(globalTable);
Assertions.assertNotNull(sql);
sql = pgLog.getDeleteGlobalTransactionSQL(globalTable);
Assertions.assertNotNull(sql);
sql = pgLog.getQueryGlobalTransactionSQL(globalTable);
Assertions.assertNotNull(sql);
sql = pgLog.getQueryGlobalTransactionSQLByTransactionId(globalTable);
Assertions.assertNotNull(sql);
sql = pgLog.getQueryGlobalTransactionSQLByStatus(globalTable, "1");
Assertions.assertNotNull(sql);
sql = pgLog.getQueryGlobalTransactionForRecoverySQL(globalTable);
Assertions.assertNotNull(sql);
sql = pgLog.getInsertBranchTransactionSQL(branchTable);
Assertions.assertNotNull(sql);
sql = pgLog.getUpdateBranchTransactionStatusSQL(branchTable);
Assertions.assertNotNull(sql);
sql = pgLog.getDeleteBranchTransactionByBranchIdSQL(branchTable);
Assertions.assertNotNull(sql);
sql = pgLog.getDeleteBranchTransactionByXId(branchTable);
Assertions.assertNotNull(sql);
sql = pgLog.getQueryBranchTransaction(branchTable);
Assertions.assertNotNull(sql);
sql = pgLog.getQueryBranchTransaction(branchTable, "1");
Assertions.assertNotNull(sql);
sql = pgLog.getQueryGlobalMax(globalTable);
Assertions.assertNotNull(sql);
sql = pgLog.getQueryBranchMax(branchTable);
Assertions.assertNotNull(sql);
}
@Test
public void h2LogTest() {
String sql = h2Log.getInsertGlobalTransactionSQL(globalTable);
Assertions.assertNotNull(sql);
sql = h2Log.getUpdateGlobalTransactionStatusSQL(globalTable);
Assertions.assertNotNull(sql);
sql = h2Log.getDeleteGlobalTransactionSQL(globalTable);
Assertions.assertNotNull(sql);
sql = h2Log.getQueryGlobalTransactionSQL(globalTable);
Assertions.assertNotNull(sql);
sql = h2Log.getQueryGlobalTransactionSQLByTransactionId(globalTable);
Assertions.assertNotNull(sql);
sql = h2Log.getQueryGlobalTransactionSQLByStatus(globalTable, "1");
Assertions.assertNotNull(sql);
sql = h2Log.getQueryGlobalTransactionForRecoverySQL(globalTable);
Assertions.assertNotNull(sql);
sql = h2Log.getInsertBranchTransactionSQL(branchTable);
Assertions.assertNotNull(sql);
sql = h2Log.getUpdateBranchTransactionStatusSQL(branchTable);
Assertions.assertNotNull(sql);
sql = h2Log.getDeleteBranchTransactionByBranchIdSQL(branchTable);
Assertions.assertNotNull(sql);
sql = h2Log.getDeleteBranchTransactionByXId(branchTable);
Assertions.assertNotNull(sql);
sql = h2Log.getQueryBranchTransaction(branchTable);
Assertions.assertNotNull(sql);
sql = h2Log.getQueryBranchTransaction(branchTable, "1");
Assertions.assertNotNull(sql);
sql = h2Log.getQueryGlobalMax(globalTable);
Assertions.assertNotNull(sql);
sql = h2Log.getQueryBranchMax(branchTable);
Assertions.assertNotNull(sql);
}
@Test
public void oceanbaseLogTest() {
String sql = oceanbase.getInsertGlobalTransactionSQL(globalTable);
Assertions.assertNotNull(sql);
sql = oceanbase.getUpdateGlobalTransactionStatusSQL(globalTable);
Assertions.assertNotNull(sql);
sql = oceanbase.getDeleteGlobalTransactionSQL(globalTable);
Assertions.assertNotNull(sql);
sql = oceanbase.getQueryGlobalTransactionSQL(globalTable);
Assertions.assertNotNull(sql);
sql = oceanbase.getQueryGlobalTransactionSQLByTransactionId(globalTable);
Assertions.assertNotNull(sql);
sql = oceanbase.getQueryGlobalTransactionSQLByStatus(globalTable, "1");
Assertions.assertNotNull(sql);
sql = oceanbase.getQueryGlobalTransactionForRecoverySQL(globalTable);
Assertions.assertNotNull(sql);
sql = oceanbase.getInsertBranchTransactionSQL(branchTable);
Assertions.assertNotNull(sql);
sql = oceanbase.getUpdateBranchTransactionStatusSQL(branchTable);
Assertions.assertNotNull(sql);
sql = oceanbase.getDeleteBranchTransactionByBranchIdSQL(branchTable);
Assertions.assertNotNull(sql);
sql = oceanbase.getDeleteBranchTransactionByXId(branchTable);
Assertions.assertNotNull(sql);
sql = oceanbase.getQueryBranchTransaction(branchTable);
Assertions.assertNotNull(sql);
sql = oceanbase.getQueryBranchTransaction(branchTable, "1");
Assertions.assertNotNull(sql);
sql = oceanbase.getQueryGlobalMax(globalTable);
Assertions.assertNotNull(sql);
sql = oceanbase.getQueryBranchMax(branchTable);
Assertions.assertNotNull(sql);
}
}
| 45.139535 | 93 | 0.723648 |
351fb57323b0ac39202564d400d2f61ea043f256 | 3,099 | /*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2011, Red Hat Inc. or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Inc.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*/
package org.hibernate.test.annotations.derivedidentities.e1.b;
import org.junit.Test;
import org.hibernate.Session;
import org.hibernate.test.util.SchemaUtil;
import org.hibernate.testing.junit4.BaseCoreFunctionalTestCase;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
/**
* @author Emmanuel Bernard
*/
public class DerivedIdentitySimpleParentEmbeddedIdDepTest extends BaseCoreFunctionalTestCase {
@Test
public void testManyToOne() throws Exception {
assertTrue( SchemaUtil.isColumnPresent( "Dependent", "emp_empId", configuration() ) );
assertTrue( ! SchemaUtil.isColumnPresent( "Dependent", "empPK", configuration() ) );
Employee e = new Employee();
e.empId = 1;
e.empName = "Emmanuel";
Session s = openSession( );
s.getTransaction().begin();
Dependent d = new Dependent();
d.emp = e;
d.id = new DependentId();
d.id.name = "Doggy";
s.persist( d );
s.persist( e );
s.flush();
s.clear();
d = (Dependent) s.get( Dependent.class, d.id );
assertEquals( d.id.empPK, d.emp.empId );
s.getTransaction().rollback();
s.close();
}
@Test
public void testOneToOne() throws Exception {
assertTrue( SchemaUtil.isColumnPresent( "ExclusiveDependent", "FK", configuration() ) );
assertTrue( ! SchemaUtil.isColumnPresent( "ExclusiveDependent", "empPK", configuration() ) );
Employee e = new Employee();
e.empId = 1;
e.empName = "Emmanuel";
Session s = openSession( );
s.getTransaction().begin();
s.persist( e );
ExclusiveDependent d = new ExclusiveDependent();
d.emp = e;
d.id = new DependentId();
d.id.name = "Doggy";
//d.id.empPK = e.empId; //FIXME not needed when foreign is enabled
s.persist( d );
s.flush();
s.clear();
d = (ExclusiveDependent) s.get( ExclusiveDependent.class, d.id );
assertEquals( d.id.empPK, d.emp.empId );
s.getTransaction().rollback();
s.close();
}
@Override
protected Class<?>[] getAnnotatedClasses() {
return new Class<?>[] {
Dependent.class,
Employee.class,
ExclusiveDependent.class
};
}
}
| 32.28125 | 95 | 0.715392 |
ce9fa9836d2cafd3f66926660caf3f9afe3f81ed | 2,754 | /*
* Copyright (C) 2016 Red Hat, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.syndesis.common.util;
import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
/**
* Unit tests for RandomValueGenerator
*/
public class RandomValueGeneratorTest {
@Test
public void testNegativeValue() {
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> RandomValueGenerator.generate("alphanum:-1"))
.withMessage("Cannot generate a string of negative length");
}
@Test
public void testPatternRespectedWithDefault() {
for (int i = 0; i < 20; i++) {
final String value = RandomValueGenerator.generate("alphanum");
assertThat(value).matches("[A-Za-z0-9]{40}");
}
}
@Test
public void testPatternRespectedWithLength() {
for (int i = 0; i < 20; i++) {
final String value = RandomValueGenerator.generate("alphanum:12");
assertThat(value).matches("[A-Za-z0-9]{12}");
}
}
@Test
public void testTrueRandom() {
final Set<String> gen = new HashSet<>();
for (int i = 0; i < 20; i++) {
final String value = RandomValueGenerator.generate("alphanum:80");
assertThat(value).matches("[A-Za-z0-9]{80}");
gen.add(value);
}
assertThat(gen.size()).isGreaterThan(10);
}
@Test
public void testUnknownGenerator() {
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> RandomValueGenerator.generate("alphanumx"))
.withMessage("Unsupported generator scheme: alphanumx");
}
@Test
public void testWrongValueType() {
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> RandomValueGenerator.generate("alphanum:aa"))
.withMessage("Unexpected string after the alphanum scheme: expected length");
}
@Test
public void testZeroValue() {
final String value = RandomValueGenerator.generate("alphanum:0");
assertThat(value).isEqualTo("");
}
}
| 32.785714 | 128 | 0.66703 |
6cb949c369d6bd4d26da78a1389277756ed7485c | 2,382 | package io.kidsfirst.core.service;
import com.amazonaws.services.kms.AWSKMS;
import com.amazonaws.services.kms.AWSKMSClient;
import com.amazonaws.services.kms.model.DecryptRequest;
import com.amazonaws.services.kms.model.EncryptRequest;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
@Slf4j
@Service
public class KMSService {
private Environment env;
private String keyId;
private AWSKMS kms;
public KMSService(Environment env){
this.env = env;
this.keyId = this.env.getProperty("application.kms", this.env.getProperty("kms"));
// Do we need to make this configurable via the application.yml?
this.kms = AWSKMSClient.builder().build();
}
public String encrypt(String original) {
try {
val bufferedOriginal = StringToByteBuffer(original);
val encryptRequest = new EncryptRequest();
encryptRequest.withKeyId(keyId);
encryptRequest.setPlaintext(bufferedOriginal);
val result = kms.encrypt(encryptRequest);
val bufferedCipher = result.getCiphertextBlob();
return ByteBufferToString(bufferedCipher);
} catch (UnsupportedEncodingException e){
// Shouldn't be reachable, handle anyways
log.error(e.getMessage(), e);
return null;
}
}
public String decrypt(String cipher) {
try {
val bufferedCipher = StringToByteBuffer(cipher);
val decryptRequest = new DecryptRequest();
decryptRequest.setCiphertextBlob(bufferedCipher);
val result = kms.decrypt(decryptRequest);
val bufferedOriginal = result.getPlaintext();
return ByteBufferToString(bufferedOriginal);
} catch (UnsupportedEncodingException e){
// Shouldn't be reachable, handle anyways
log.error(e.getMessage(), e);
return null;
}
}
private ByteBuffer StringToByteBuffer(String string) throws UnsupportedEncodingException {
val bytes = string.getBytes(StandardCharsets.ISO_8859_1);
return ByteBuffer.wrap(bytes);
}
private String ByteBufferToString(ByteBuffer buffer) throws UnsupportedEncodingException {
byte[] bytes;
bytes = buffer.array();
return new String(bytes, StandardCharsets.ISO_8859_1);
}
}
| 29.04878 | 92 | 0.736776 |
b5a8ba05d11b303813cbac78140c634d05c01ebb | 431 | package dev.patika.fourthhomework.model;
import com.fasterxml.jackson.annotation.JsonTypeName;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.Entity;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@JsonTypeName("PermanentInstructor")
public class PermanentInstructor extends dev.patika.fourthhomework.model.Instructor {
private double fixedSalary;
}
| 20.52381 | 85 | 0.835267 |
1e2487bca60d893128cbc078991b54247b2436fb | 3,735 | package de.pmoit.voiceassistant.tts;
import static javax.sound.sampled.FloatControl.Type.MASTER_GAIN;
import java.io.IOException;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.FloatControl;
import javax.sound.sampled.SourceDataLine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import marytts.util.data.audio.StereoAudioInputStream;
/**
* Class for handling and playing audio. Enables the voice to be louder and
* manages the audiothread.
*
*/
class AudioPlayer {
private AudioPlayerThread audioPlayerThread;
private AudioInputStream ais;
private boolean stopThread;
private Logger logger = LoggerFactory.getLogger(getClass());
/**
* Cancel the AudioPlayer which will cause the Thread to exit.
*/
public void interrupt() {
if (audioPlayerThread != null)
audioPlayerThread.interrupt();
}
public void play(AudioInputStream audio) {
play(audio, 1F);
}
/**
* Start the audioplayer thread.
*
* @param audio
* @param gain
*/
public void play(AudioInputStream audio, float gain) {
if (audioPlayerThread != null) {
try {
audioPlayerThread.join();
} catch (InterruptedException e) {
logger.warn(e.getMessage(), e);
}
}
audioPlayerThread = new AudioPlayerThread(gain);
this.ais = audio;
audioPlayerThread.start();
}
private class AudioPlayerThread extends Thread {
private final int STEREO = 3;
private SourceDataLine sdLine;
private final float gain;
private AudioPlayerThread(float gain) {
this.setDaemon(false);
this.gain = gain;
}
private void setMasterGain() {
if (sdLine != null && sdLine.isControlSupported(MASTER_GAIN)) {
float value = ( float ) ( 20 * Math.log10(gain <= 0.0 ? 0.0000 : gain) );
FloatControl control = ( FloatControl ) sdLine.getControl(MASTER_GAIN);
control.setValue(value);
}
}
@Override
public void run() {
ais = new StereoAudioInputStream(ais, STEREO);
AudioFormat audioFormat = ais.getFormat();
DataLine.Info info = new DataLine.Info(SourceDataLine.class, audioFormat);
try {
if (sdLine == null) {
sdLine = ( SourceDataLine ) AudioSystem.getLine(info);
setMasterGain();
}
sdLine.open(audioFormat);
sdLine.start();
writeDataToLine();
if ( ! stopThread) {
sdLine.drain();
}
} catch (Exception e) {
logger.warn(e.getMessage(), e);
return;
} finally {
sdLine.close();
}
}
private void writeDataToLine() throws IOException {
int readLine = 0;
byte[] data = new byte[65532];
while ( ( readLine != - 1 ) && ( ! stopThread )) {
readLine = ais.read(data, 0, data.length);
if (readLine >= 0) {
sdLine.write(data, 0, readLine);
}
}
}
/**
* Stops AudioPlayer and thread.
*/
@Override
public void interrupt() {
if (sdLine != null) {
sdLine.stop();
}
stopThread = true;
super.interrupt();
}
}
}
| 28.082707 | 89 | 0.550736 |
1e573f7a96815999c286d3e52b311a505620684d | 196 | package pl.com.bottega.ecommerce.sales.readmodel.offer;
public class OfferQuery {
public boolean isBestBeforeExpired() {
// TODO Auto-generated method stub
return false;
}
}
| 16.333333 | 56 | 0.704082 |
352da8ea640e1900da5c0c2228311e242ce10e1a | 15,509 | // Copyright 2021 Code Intelligence GmbH
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.code_intelligence.jazzer.runtime;
import com.code_intelligence.jazzer.api.HookType;
import com.code_intelligence.jazzer.api.MethodHook;
import java.lang.invoke.MethodHandle;
import java.util.Arrays;
import java.util.Map;
import java.util.TreeMap;
@SuppressWarnings("unused")
final public class TraceCmpHooks {
@MethodHook(type = HookType.BEFORE, targetClassName = "java.lang.Byte", targetMethod = "compare",
targetMethodDescriptor = "(BB)I")
@MethodHook(type = HookType.BEFORE, targetClassName = "java.lang.Byte",
targetMethod = "compareUnsigned", targetMethodDescriptor = "(BB)I")
@MethodHook(type = HookType.BEFORE, targetClassName = "java.lang.Short", targetMethod = "compare",
targetMethodDescriptor = "(SS)I")
@MethodHook(type = HookType.BEFORE, targetClassName = "java.lang.Short",
targetMethod = "compareUnsigned", targetMethodDescriptor = "(SS)I")
@MethodHook(type = HookType.BEFORE, targetClassName = "java.lang.Integer",
targetMethod = "compare", targetMethodDescriptor = "(II)I")
@MethodHook(type = HookType.BEFORE, targetClassName = "java.lang.Integer",
targetMethod = "compareUnsigned", targetMethodDescriptor = "(II)I")
public static void
integerCompare(MethodHandle method, Object thisObject, Object[] arguments, int hookId) {
TraceDataFlowNativeCallbacks.traceCmpInt((int) arguments[0], (int) arguments[1], hookId);
}
@MethodHook(type = HookType.BEFORE, targetClassName = "java.lang.Byte",
targetMethod = "compareTo", targetMethodDescriptor = "(Ljava/lang/Byte;)I")
@MethodHook(type = HookType.BEFORE, targetClassName = "java.lang.Short",
targetMethod = "compareTo", targetMethodDescriptor = "(Ljava/lang/Short;)I")
@MethodHook(type = HookType.BEFORE, targetClassName = "java.lang.Integer",
targetMethod = "compareTo", targetMethodDescriptor = "(Ljava/lang/Integer;)I")
public static void
integerCompareTo(MethodHandle method, Object thisObject, Object[] arguments, int hookId) {
TraceDataFlowNativeCallbacks.traceCmpInt((int) thisObject, (int) arguments[0], hookId);
}
@MethodHook(type = HookType.BEFORE, targetClassName = "java.lang.Long", targetMethod = "compare",
targetMethodDescriptor = "(JJ)I")
@MethodHook(type = HookType.BEFORE, targetClassName = "java.lang.Long",
targetMethod = "compareUnsigned", targetMethodDescriptor = "(JJ)I")
public static void
longCompare(MethodHandle method, Object thisObject, Object[] arguments, int hookId) {
TraceDataFlowNativeCallbacks.traceCmpLong((long) arguments[0], (long) arguments[1], hookId);
}
@MethodHook(type = HookType.BEFORE, targetClassName = "java.lang.Long",
targetMethod = "compareTo", targetMethodDescriptor = "(Ljava/lang/Long;)I")
public static void
longCompareTo(MethodHandle method, Long thisObject, Object[] arguments, int hookId) {
TraceDataFlowNativeCallbacks.traceCmpLong(thisObject, (long) arguments[0], hookId);
}
@MethodHook(type = HookType.AFTER, targetClassName = "java.lang.String", targetMethod = "equals")
@MethodHook(type = HookType.AFTER, targetClassName = "java.lang.String",
targetMethod = "equalsIgnoreCase")
public static void
equals(
MethodHandle method, String thisObject, Object[] arguments, int hookId, Boolean returnValue) {
if (arguments[0] instanceof String && !returnValue) {
// The precise value of the result of the comparison is not used by libFuzzer as long as it is
// non-zero.
TraceDataFlowNativeCallbacks.traceStrcmp(thisObject, (String) arguments[0], 1, hookId);
}
}
@MethodHook(
type = HookType.AFTER, targetClassName = "java.lang.String", targetMethod = "compareTo")
@MethodHook(type = HookType.AFTER, targetClassName = "java.lang.String",
targetMethod = "compareToIgnoreCase")
public static void
compareTo(
MethodHandle method, String thisObject, Object[] arguments, int hookId, Integer returnValue) {
if (arguments[0] instanceof String && returnValue != 0) {
TraceDataFlowNativeCallbacks.traceStrcmp(
thisObject, (String) arguments[0], returnValue, hookId);
}
}
@MethodHook(
type = HookType.AFTER, targetClassName = "java.lang.String", targetMethod = "contentEquals")
public static void
contentEquals(
MethodHandle method, String thisObject, Object[] arguments, int hookId, Boolean returnValue) {
if (arguments[0] instanceof CharSequence && !returnValue) {
TraceDataFlowNativeCallbacks.traceStrcmp(
thisObject, ((CharSequence) arguments[0]).toString(), 1, hookId);
}
}
@MethodHook(type = HookType.AFTER, targetClassName = "java.lang.String",
targetMethod = "regionMatches", targetMethodDescriptor = "(ZILjava/lang/String;II)Z")
public static void
regionsMatches5(
MethodHandle method, Object thisObject, Object[] arguments, int hookId, Boolean returnValue) {
if (!returnValue) {
int toffset = (int) arguments[1];
String other = (String) arguments[2];
int ooffset = (int) arguments[3];
int len = (int) arguments[4];
regionMatchesInternal((String) thisObject, toffset, other, ooffset, len, hookId);
}
}
@MethodHook(type = HookType.AFTER, targetClassName = "java.lang.String",
targetMethod = "regionMatches", targetMethodDescriptor = "(ILjava/lang/String;II)Z")
public static void
regionMatches4(
MethodHandle method, Object thisObject, Object[] arguments, int hookId, Boolean returnValue) {
if (!returnValue) {
int toffset = (int) arguments[0];
String other = (String) arguments[1];
int ooffset = (int) arguments[2];
int len = (int) arguments[3];
regionMatchesInternal((String) thisObject, toffset, other, ooffset, len, hookId);
}
}
private static void regionMatchesInternal(
String thisString, int toffset, String other, int ooffset, int len, int hookId) {
if (toffset < 0 || ooffset < 0)
return;
int cappedThisStringEnd = Math.min(toffset + len, thisString.length());
int cappedOtherStringEnd = Math.min(ooffset + len, other.length());
String thisPart = thisString.substring(toffset, cappedThisStringEnd);
String otherPart = other.substring(ooffset, cappedOtherStringEnd);
TraceDataFlowNativeCallbacks.traceStrcmp(thisPart, otherPart, 1, hookId);
}
@MethodHook(
type = HookType.AFTER, targetClassName = "java.lang.String", targetMethod = "contains")
public static void
contains(
MethodHandle method, String thisObject, Object[] arguments, int hookId, Boolean returnValue) {
if (arguments[0] instanceof CharSequence && !returnValue) {
TraceDataFlowNativeCallbacks.traceStrstr(
thisObject, ((CharSequence) arguments[0]).toString(), hookId);
}
}
@MethodHook(type = HookType.AFTER, targetClassName = "java.lang.String", targetMethod = "indexOf")
@MethodHook(
type = HookType.AFTER, targetClassName = "java.lang.String", targetMethod = "lastIndexOf")
@MethodHook(
type = HookType.AFTER, targetClassName = "java.lang.StringBuffer", targetMethod = "indexOf")
@MethodHook(type = HookType.AFTER, targetClassName = "java.lang.StringBuffer",
targetMethod = "lastIndexOf")
@MethodHook(
type = HookType.AFTER, targetClassName = "java.lang.StringBuilder", targetMethod = "indexOf")
@MethodHook(type = HookType.AFTER, targetClassName = "java.lang.StringBuilder",
targetMethod = "lastIndexOf")
public static void
indexOf(
MethodHandle method, Object thisObject, Object[] arguments, int hookId, Integer returnValue) {
if (arguments[0] instanceof String && returnValue == -1) {
TraceDataFlowNativeCallbacks.traceStrstr(
thisObject.toString(), (String) arguments[0], hookId);
}
}
@MethodHook(
type = HookType.AFTER, targetClassName = "java.lang.String", targetMethod = "startsWith")
@MethodHook(
type = HookType.AFTER, targetClassName = "java.lang.String", targetMethod = "endsWith")
public static void
startsWith(
MethodHandle method, String thisObject, Object[] arguments, int hookId, Boolean returnValue) {
if (!returnValue) {
TraceDataFlowNativeCallbacks.traceStrstr(thisObject, (String) arguments[0], hookId);
}
}
@MethodHook(type = HookType.AFTER, targetClassName = "java.lang.String", targetMethod = "replace",
targetMethodDescriptor =
"(Ljava/lang/CharSequence;Ljava/lang/CharSequence;)Ljava/lang/String;")
public static void
replace(
MethodHandle method, Object thisObject, Object[] arguments, int hookId, String returnValue) {
String original = (String) thisObject;
String target = arguments[0].toString();
// Report only if the replacement was not successful.
if (original.equals(returnValue)) {
TraceDataFlowNativeCallbacks.traceStrstr(original, target, hookId);
}
}
@MethodHook(type = HookType.AFTER, targetClassName = "java.util.Arrays", targetMethod = "equals",
targetMethodDescriptor = "([B[B)Z")
public static void
arraysEquals(
MethodHandle method, Object thisObject, Object[] arguments, int hookId, Boolean returnValue) {
byte[] first = (byte[]) arguments[0];
byte[] second = (byte[]) arguments[1];
if (!returnValue) {
TraceDataFlowNativeCallbacks.traceMemcmp(first, second, 1, hookId);
}
}
@MethodHook(type = HookType.AFTER, targetClassName = "java.util.Arrays", targetMethod = "equals",
targetMethodDescriptor = "([BII[BII)Z")
public static void
arraysEqualsRange(
MethodHandle method, Object thisObject, Object[] arguments, int hookId, Boolean returnValue) {
byte[] first =
Arrays.copyOfRange((byte[]) arguments[0], (int) arguments[1], (int) arguments[2]);
byte[] second =
Arrays.copyOfRange((byte[]) arguments[3], (int) arguments[4], (int) arguments[5]);
if (!returnValue) {
TraceDataFlowNativeCallbacks.traceMemcmp(first, second, 1, hookId);
}
}
@MethodHook(type = HookType.AFTER, targetClassName = "java.util.Arrays", targetMethod = "compare",
targetMethodDescriptor = "([B[B)I")
@MethodHook(type = HookType.AFTER, targetClassName = "java.util.Arrays",
targetMethod = "compareUnsigned", targetMethodDescriptor = "([B[B)I")
public static void
arraysCompare(
MethodHandle method, Object thisObject, Object[] arguments, int hookId, Integer returnValue) {
byte[] first = (byte[]) arguments[0];
byte[] second = (byte[]) arguments[1];
if (returnValue != 0) {
TraceDataFlowNativeCallbacks.traceMemcmp(first, second, returnValue, hookId);
}
}
@MethodHook(type = HookType.AFTER, targetClassName = "java.util.Arrays", targetMethod = "compare",
targetMethodDescriptor = "([BII[BII)I")
@MethodHook(type = HookType.AFTER, targetClassName = "java.util.Arrays",
targetMethod = "compareUnsigned", targetMethodDescriptor = "([BII[BII)I")
public static void
arraysCompareRange(
MethodHandle method, Object thisObject, Object[] arguments, int hookId, Integer returnValue) {
byte[] first =
Arrays.copyOfRange((byte[]) arguments[0], (int) arguments[1], (int) arguments[2]);
byte[] second =
Arrays.copyOfRange((byte[]) arguments[3], (int) arguments[4], (int) arguments[5]);
if (returnValue != 0) {
TraceDataFlowNativeCallbacks.traceMemcmp(first, second, returnValue, hookId);
}
}
// The maximal number of elements of a non-TreeMap Map that will be sorted and searched for the
// key closest to the current lookup key in the mapGet hook.
private static final int MAX_NUM_KEYS_TO_ENUMERATE = 100;
@MethodHook(type = HookType.AFTER, targetClassName = "com.google.common.collect.ImmutableMap",
targetMethod = "get")
@MethodHook(
type = HookType.AFTER, targetClassName = "java.util.AbstractMap", targetMethod = "get")
@MethodHook(type = HookType.AFTER, targetClassName = "java.util.EnumMap", targetMethod = "get")
@MethodHook(type = HookType.AFTER, targetClassName = "java.util.HashMap", targetMethod = "get")
@MethodHook(
type = HookType.AFTER, targetClassName = "java.util.LinkedHashMap", targetMethod = "get")
@MethodHook(type = HookType.AFTER, targetClassName = "java.util.Map", targetMethod = "get")
@MethodHook(type = HookType.AFTER, targetClassName = "java.util.SortedMap", targetMethod = "get")
@MethodHook(type = HookType.AFTER, targetClassName = "java.util.TreeMap", targetMethod = "get")
@MethodHook(type = HookType.AFTER, targetClassName = "java.util.concurrent.ConcurrentMap",
targetMethod = "get")
public static void
mapGet(
MethodHandle method, Object thisObject, Object[] arguments, int hookId, Object returnValue) {
if (returnValue != null)
return;
if (thisObject == null)
return;
final Map map = (Map) thisObject;
if (map.size() == 0)
return;
final Object currentKey = arguments[0];
if (currentKey == null)
return;
// Find two valid map keys that bracket currentKey.
// This is a generalization of libFuzzer's __sanitizer_cov_trace_switch:
// https://github.com/llvm/llvm-project/blob/318942de229beb3b2587df09e776a50327b5cef0/compiler-rt/lib/fuzzer/FuzzerTracePC.cpp#L564
Object lowerBoundKey = null;
Object upperBoundKey = null;
if (map instanceof TreeMap) {
final TreeMap treeMap = (TreeMap) map;
lowerBoundKey = treeMap.floorKey(currentKey);
upperBoundKey = treeMap.ceilingKey(currentKey);
} else if (currentKey instanceof Comparable) {
final Comparable comparableKey = (Comparable) currentKey;
// Find two keys that bracket currentKey.
// Note: This is not deterministic if map.size() > MAX_NUM_KEYS_TO_ENUMERATE.
int enumeratedKeys = 0;
for (Object validKey : map.keySet()) {
if (validKey == null)
continue;
// If the key sorts lower than the non-existing key, but higher than the current lower
// bound, update the lower bound and vice versa for the upper bound.
if (comparableKey.compareTo(validKey) > 0
&& (lowerBoundKey == null || ((Comparable) validKey).compareTo(lowerBoundKey) > 0)) {
lowerBoundKey = validKey;
}
if (comparableKey.compareTo(validKey) < 0
&& (upperBoundKey == null || ((Comparable) validKey).compareTo(upperBoundKey) < 0)) {
upperBoundKey = validKey;
}
if (enumeratedKeys++ > MAX_NUM_KEYS_TO_ENUMERATE)
break;
}
}
// Modify the hook ID so that compares against distinct valid keys are traced separately.
if (lowerBoundKey != null) {
TraceDataFlowNativeCallbacks.traceGenericCmp(
currentKey, lowerBoundKey, hookId + lowerBoundKey.hashCode());
}
if (upperBoundKey != null) {
TraceDataFlowNativeCallbacks.traceGenericCmp(
currentKey, upperBoundKey, hookId + upperBoundKey.hashCode());
}
}
}
| 46.854985 | 135 | 0.703849 |
c9f1c8178f5b539203e272a72ba7edde40f36b0e | 1,564 | package supermarket;
import java.util.ArrayList;
import java.util.List;
public class Cashier{
private List<Customer> customerQueue;
private final int id;
private CashierState state;
private final int MAXQUEUE = 5;
public Cashier(int id){
customerQueue = new ArrayList<>();
state = CashierState.CLOSED;
this.id = id;
}
public boolean addCustomerToQueue(Customer customer){
if(customerQueue.size() == MAXQUEUE){
System.out.println("The cashier queue is full, sorry customer "+ customer.getId());
return false;
}
else{
customerQueue.add(0, customer);
return true;
}
}
public int getQueueSize(){
return customerQueue.size();
}
public Customer processOrder(){
if(customerQueue.isEmpty())
return null;
else
return customerQueue.remove(customerQueue.size()-1);
}
public String toString(){
StringBuilder cashierAsStr = new StringBuilder("C"+id+": ");
for (Customer c: customerQueue) {
cashierAsStr.append("o["+ c.getId()+"] ");
}
return cashierAsStr.toString();
}
public CashierState getState() {
return state;
}
public void setState(CashierState state) {
this.state = state;
System.out.println("Cashier "+id+" is now "+state);
if(state == CashierState.CLOSED){
customerQueue.clear();
}
}
public int getId() {
return id;
}
}
| 24.061538 | 95 | 0.581841 |
316bba6f048a20a26eaaedb74773132708b90986 | 2,150 | package com.wanhive.iot.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import org.glassfish.jersey.client.ClientProperties;
import com.wanhive.iot.bean.User;
/**
* Servlet implementation class SignOutServlet
*/
@WebServlet(description = "Signs out an user", urlPatterns = { "/SignOut" })
public class SignOutServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private void deleteSession(String baseUrl, String token) {
Client client = null;
try {
if (token == null || token.length() == 0) {
return;
}
client = ClientBuilder.newClient();
client.target(baseUrl).path("api/user/token").property(ClientProperties.FOLLOW_REDIRECTS, Boolean.TRUE)
.request().header("Authorization", new StringBuilder().append("Bearer ").append(token).toString())
.delete();
} finally {
try {
if (client != null)
client.close();
} catch (Exception e) {
}
}
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
try {
User user = (User) session.getAttribute("user");
if (user != null) {
String baseUrl = new StringBuilder().append("http://localhost:").append(request.getServerPort())
.append(request.getContextPath()).toString();
deleteSession(baseUrl, user.getToken());
}
} finally {
session.invalidate();
response.sendRedirect("index.jsp");
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
| 29.452055 | 106 | 0.726512 |
ae047c4905dbb692ce8d506479149ff82643e234 | 1,211 | /*
* Copyright (c) 2018 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 org.bicarb.core.system.bean;
import com.github.slugify.Slugify;
import org.springframework.stereotype.Component;
/**
* SlugifyHelper.
*
* @author olOwOlo
*/
@Component
public class SlugifyHelper {
private static final Slugify SLUGIFY = new Slugify().withTransliterator(true);
/**
* Slugify string, truncate at 255 characters.
* @param raw raw string
* @return slug
*/
public String slugify(String raw) {
String slug = SLUGIFY.slugify(raw);
if (slug.length() > 255) {
return slug.substring(0, 255);
} else {
return slug;
}
}
}
| 25.765957 | 80 | 0.702725 |
6c465266bdd5b923550245e9f19bfcb98dbc0017 | 1,473 | /*
* Copyright (c) CovertJaguar, 2014 http://railcraft.info
*
* This code is the property of CovertJaguar
* and may only be used with explicit written
* permission unless otherwise specified on the
* license page at http://railcraft.info/wiki/info:license.
*/
package mods.railcraft.common.gui.containers;
import mods.railcraft.common.blocks.machine.ITankTile;
import mods.railcraft.common.fluids.tanks.StandardTank;
import mods.railcraft.common.gui.slots.SlotOutput;
import mods.railcraft.common.gui.widgets.FluidGaugeWidget;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.inventory.Slot;
public class ContainerTank extends RailcraftContainer {
private final ITankTile tile;
public ContainerTank(InventoryPlayer inventoryplayer, ITankTile tile) {
super(tile.getInventory());
this.tile = tile;
StandardTank tank = tile.getTank();
if (tank != null) {
addWidget(new FluidGaugeWidget(tank, 35, 23, 176, 0, 48, 47));
}
addSlot(tile.getInputSlot(tile.getInventory(), 0, 116, 21));
addSlot(new SlotOutput(tile.getInventory(), 1, 116, 56));
for (int i = 0; i < 3; i++) {
for (int k = 0; k < 9; k++) {
addSlot(new Slot(inventoryplayer, k + i * 9 + 9, 8 + k * 18, 84 + i * 18));
}
}
for (int j = 0; j < 9; j++) {
addSlot(new Slot(inventoryplayer, j, 8 + j * 18, 142));
}
}
}
| 32.733333 | 91 | 0.644942 |
bbccb842aa3c86c86b42bb9cd1ddc661ff304ac2 | 1,274 | /*
* Copyright 2014-2016 Smart Society Services B.V.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*/
package org.opensmartgridplatform.domain.microgrids.valueobjects;
import java.io.Serializable;
import org.joda.time.DateTime;
public class SetPoint implements Serializable {
private static final long serialVersionUID = -8781688280636819412L;
private final int id;
private final String node;
private final double value;
private final DateTime startTime;
private final DateTime endTime;
public SetPoint(
final int id,
final String node,
final double value,
final DateTime startTime,
final DateTime endTime) {
super();
this.id = id;
this.node = node;
this.value = value;
this.startTime = startTime;
this.endTime = endTime;
}
public int getId() {
return this.id;
}
public String getNode() {
return this.node;
}
public double getValue() {
return this.value;
}
public DateTime getStartTime() {
return this.startTime;
}
public DateTime getEndTime() {
return this.endTime;
}
}
| 21.965517 | 92 | 0.693878 |
db2cf6d18da3cb34f7fb41c0037346cc4f2a545b | 128 | package com.libs.modelos;
public class data_disparo {
public int id;
public int bala;
public boolean disparando;
}
| 16 | 30 | 0.710938 |
3b1cf39e569533ec9bdb08c56e9084083e1206ca | 1,706 | package org.tvrenamer.controller;
import static org.tvrenamer.model.util.Constants.*;
import org.tvrenamer.model.ShowStore;
import org.tvrenamer.view.UIStarter;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.LogManager;
class Launcher {
private static void initializeLogger() {
// Find logging.properties file inside jar
try (InputStream loggingConfigStream
= Launcher.class.getResourceAsStream(LOGGING_PROPERTIES))
{
if (loggingConfigStream == null) {
System.err.println("Warning: logging properties not found.");
} else {
LogManager.getLogManager().readConfiguration(loggingConfigStream);
}
} catch (IOException e) {
System.err.println("Exception thrown while loading logging config");
e.printStackTrace();
}
}
/**
* Shut down any threads that we know might be running. Sadly hard-coded.
*/
private static void tvRenamerThreadShutdown() {
MoveRunner.shutDown();
ShowStore.cleanUp();
ListingsLookup.cleanUp();
}
/**
* All this application does is run the UI, with no arguments. Configuration
* comes from the PREFERENCES_FILE (see Constants.java). But in the future,
* it might be able to do different things depending on command-line arguments.
*
* @param args
* not actually processed, at this time
*/
public static void main(String[] args) {
initializeLogger();
UIStarter ui = new UIStarter();
int status = ui.run();
tvRenamerThreadShutdown();
System.exit(status);
}
}
| 31.018182 | 83 | 0.640094 |
94dda374397a9ab5a59ac58d21681373db3f0ae1 | 6,416 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package entidades;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
/**
*
* @author Akari
*/
@Entity
@Table(name = "producto")
@NamedQueries({
@NamedQuery(name = "getProducto", query = "SELECT p FROM Producto p WHERE p.isbn = :isbn")})
public class Producto implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "idproducto")
private Integer idproducto;
@Basic(optional = false)
@Column(name = "titulo")
private String titulo;
@Basic(optional = false)
@Column(name = "autor")
private String autor;
@Basic(optional = false)
@Column(name = "editorial")
private String editorial;
@Basic(optional = false)
@Column(name = "isbn")
private String isbn;
@Column(name = "a\u00f1o")
private String año;
@Column(name = "paginas")
private Integer paginas;
@Basic(optional = false)
@Column(name = "resumen")
private String resumen;
@Column(name = "descripcion")
private String descripcion;
@Basic(optional = false)
@Column(name = "precio")
private float precio;
@Basic(optional = false)
@Column(name = "stock")
private int stock;
@Basic(optional = false)
@Column(name = "descatalogado")
private int descatalogado;
@Lob
@Column(name = "imagen")
private byte[] imagen;
@JoinColumn(name = "seccion", referencedColumnName = "idseccion")
@ManyToOne(optional = false, fetch = FetchType.LAZY)
private Seccion seccion;
@JoinColumn(name = "lengua", referencedColumnName = "ididioma")
@ManyToOne(fetch = FetchType.LAZY)
private Idioma lengua;
@OneToMany(mappedBy = "producto", fetch = FetchType.LAZY)
private List<Detalle> detalleList;
public Producto() {
}
public Producto(Integer idproducto) {
this.idproducto = idproducto;
}
public Producto(Integer idproducto, String titulo, String autor, String editorial, String isbn, String resumen, float precio, int stock, int descatalogado) {
this.idproducto = idproducto;
this.titulo = titulo;
this.autor = autor;
this.editorial = editorial;
this.isbn = isbn;
this.resumen = resumen;
this.precio = precio;
this.stock = stock;
this.descatalogado = descatalogado;
}
public Integer getIdproducto() {
return idproducto;
}
public void setIdproducto(Integer idproducto) {
this.idproducto = idproducto;
}
public String getTitulo() {
return titulo;
}
public void setTitulo(String titulo) {
this.titulo = titulo;
}
public String getAutor() {
return autor;
}
public void setAutor(String autor) {
this.autor = autor;
}
public String getEditorial() {
return editorial;
}
public void setEditorial(String editorial) {
this.editorial = editorial;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public String getAño() {
return año;
}
public void setAño(String año) {
this.año = año;
}
public Integer getPaginas() {
return paginas;
}
public void setPaginas(Integer paginas) {
this.paginas = paginas;
}
public String getResumen() {
return resumen;
}
public void setResumen(String resumen) {
this.resumen = resumen;
}
public String getDescripcion() {
return descripcion;
}
public void setDescripcion(String descripcion) {
this.descripcion = descripcion;
}
public float getPrecio() {
return precio;
}
public void setPrecio(float precio) {
this.precio = precio;
}
public int getStock() {
return stock;
}
public void setStock(int stock) {
this.stock = stock;
}
public int getDescatalogado() {
return descatalogado;
}
public void setDescatalogado(int descatalogado) {
this.descatalogado = descatalogado;
}
public byte[] getImagen() {
return imagen;
}
public void setImagen(byte[] imagen) {
this.imagen = imagen;
}
public Seccion getSeccion() {
return seccion;
}
public void setSeccion(Seccion seccion) {
this.seccion = seccion;
}
public Idioma getLengua() {
return lengua;
}
public void setLengua(Idioma lengua) {
this.lengua = lengua;
}
public List<Detalle> getDetalleList() {
return detalleList;
}
public void setDetalleList(List<Detalle> detalleList) {
this.detalleList = detalleList;
}
@Override
public int hashCode() {
int hash = 0;
hash += (idproducto != null ? idproducto.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Producto)) {
return false;
}
Producto other = (Producto) object;
if ((this.idproducto == null && other.idproducto != null) || (this.idproducto != null && !this.idproducto.equals(other.idproducto))) {
return false;
}
return true;
}
@Override
public String toString() {
return "entidades.Producto[ idproducto=" + idproducto + " ]";
}
}
| 25.259843 | 162 | 0.606764 |
640c41d8c7e30db15e65209190f93a6062cb5fdb | 4,800 | package theDragonkin.orbs.Flameweaver;
import basemod.abstracts.CustomOrb;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.MathUtils;
import com.evacipated.cardcrawl.mod.stslib.actions.defect.EvokeSpecificOrbAction;
import com.megacrit.cardcrawl.actions.AbstractGameAction;
import com.megacrit.cardcrawl.actions.common.DamageAction;
import com.megacrit.cardcrawl.cards.DamageInfo;
import com.megacrit.cardcrawl.core.CardCrawlGame;
import com.megacrit.cardcrawl.dungeons.AbstractDungeon;
import com.megacrit.cardcrawl.localization.OrbStrings;
import com.megacrit.cardcrawl.monsters.AbstractMonster;
import com.megacrit.cardcrawl.orbs.AbstractOrb;
import com.megacrit.cardcrawl.ui.panels.EnergyPanel;
import com.megacrit.cardcrawl.vfx.FlameBallParticleEffect;
import com.megacrit.cardcrawl.vfx.combat.DarkOrbActivateEffect;
import theDragonkin.DragonkinMod;
import static theDragonkin.DragonkinMod.makeOrbPath;
public class Ember extends CustomOrb {
// Standard ID/Description
public static final String ORB_ID = DragonkinMod.makeID("Ember");
private static final OrbStrings orbString = CardCrawlGame.languagePack.getOrbString(ORB_ID);
public static final String[] DESCRIPTIONS = orbString.DESCRIPTION;
private static final int PASSIVE_AMOUNT = 3;
private static final int EVOKE_AMOUNT = 3;
// Animation Rendering Numbers - You can leave these at default, or play around with them and see what they change.
private float vfxTimer = 1.0f;
private float vfxIntervalMin = 0.1f;
private float vfxIntervalMax = 0.4f;
private static final float ORB_WAVY_DIST = 0.04f;
private static final float PI_4 = 12.566371f;
private AbstractMonster Target;
public Ember(AbstractMonster target, int base) {
// The passive/evoke description we pass in here, specifically, don't matter
// You can ctrl+click on CustomOrb from the `extends CustomOrb` above.
// You'll see below we override CustomOrb's updateDescription function with our own, and also, that's where the passiveDescription and evokeDescription
// parameters are used. If your orb doesn't use any numbers/doesn't change e.g "Evoke: shuffle your draw pile."
// then you don't need to override the update description method and can just pass in the parameters here.
super(ORB_ID, orbString.NAME, PASSIVE_AMOUNT, EVOKE_AMOUNT, DESCRIPTIONS[1], DESCRIPTIONS[2], makeOrbPath("default_orb.png"));
Target = target;
updateDescription();
baseEvokeAmount = base;
basePassiveAmount = base;
angle = MathUtils.random(360.0f); // More Animation-related Numbers
channelAnimTimer = 0.5f;
}
@Override
public void updateDescription() { // Set the on-hover description of the orb
applyFocus(); // Apply Focus (Look at the next method)
if (Target != null){
description = DESCRIPTIONS[0] + DESCRIPTIONS[1] + evokeAmount + DESCRIPTIONS[2] + Target.name;
}
}
public void applyFocus() {
passiveAmount = basePassiveAmount;
evokeAmount = baseEvokeAmount;
}
@Override
public void onEvoke() { // 1.On Orb Evoke
AbstractDungeon.actionManager.addToBottom(new DamageAction(Target,new DamageInfo(AbstractDungeon.player,evokeAmount, DamageInfo.DamageType.THORNS),
AbstractGameAction.AttackEffect.FIRE));
}
@Override
public void updateAnimation() {// You can totally leave this as is.
// If you want to create a whole new orb effect - take a look at conspire's Water Orb. It includes a custom sound, too!
super.updateAnimation();
angle += Gdx.graphics.getDeltaTime() * 45.0f;
vfxTimer -= Gdx.graphics.getDeltaTime();
if (vfxTimer < 0.0f) {
AbstractDungeon.effectList.add(new FlameBallParticleEffect(cX, cY,evokeAmount));
vfxTimer = MathUtils.random(vfxIntervalMin, vfxIntervalMax);
}
}
// Render the orb.
@Override
public void render(SpriteBatch sb) {
renderText(sb);
}
@Override
public void triggerEvokeAnimation() { // The evoke animation of this orb is the dark-orb activation effect.
AbstractDungeon.effectsQueue.add(new DarkOrbActivateEffect(cX, cY));
}
@Override
public void playChannelSFX() { // When you channel this orb, the ATTACK_FIRE effect plays ("Fwoom").
CardCrawlGame.sound.play("ATTACK_FIRE", 0.1f);
}
@Override
public void onEndOfTurn() {
if (EnergyPanel.totalCount > 0) {
AbstractDungeon.actionManager.addToBottom(new EvokeSpecificOrbAction(this));
}
}
@Override
public AbstractOrb makeCopy() {
return new Ember(Target,evokeAmount);
}
}
| 41.73913 | 159 | 0.719583 |
7ae38e97e5d47ff2e52530d5cd3220f78beb82b0 | 627 | package dmillerw.log.util;
import com.google.common.collect.Lists;
import java.util.List;
import java.util.Set;
public class CollectionHelper {
public static <T> List<T> setToList(Set<T> set) {
List<T> list = Lists.newArrayList();
for (T t : set) {
list.add(t);
}
return list;
}
public static <T> boolean arrayContains(T search, T[] array, boolean def) {
if (array == null) {
return def;
}
for (T t : array) {
if (search.equals(t)) {
return true;
}
}
return false;
}
}
| 20.225806 | 79 | 0.518341 |
c0ae6c14653c673d5e56ddd37eabf745300c01b5 | 1,684 | package view;
import controller.Command;
import controller.Config;
import controller.ContentService;
import controller.commands.CancelCommand;
import controller.commands.CloseContentCommand;
import controller.commands.OpenContentCommand;
import model.Content;
import model.Folder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class ShowFolderView extends SelectionView {
final ContentService contentService;
final Folder folder;
public ShowFolderView(ContentService contentService, Folder folder) {
this.contentService = contentService;
this.folder = folder;
}
@Override
protected List<Command> getCommands() {
List<Command> commands = new ArrayList<>();
// Commands to open content of this folder
for (Map.Entry<String, Content> entry : folder.getContents().entrySet()) {
commands.add(new OpenContentCommand(contentService, entry.getValue()));
}
commands.add(null);
// Command to navigate back
commands.add(new CloseContentCommand(contentService));
// Command to end the navigation
commands.add(new CancelCommand(contentService));
return commands;
}
@Override
protected String getMessage() {
StringBuilder message = new StringBuilder(Config.resourceBundle.getString("content.view.ShowFolderView.Message"));
message.append("\n\n> ").append(this.contentService.getRoot().getName());
for (String s : this.contentService.getNavigationPath()) {
message.append("/").append(s);
}
message.append(":");
return message.toString();
}
}
| 28.066667 | 122 | 0.691805 |
ce95bdb6b17079cb5b7e1b4176f06e1d8f93af64 | 2,634 | package tr.com.infumia.infumialib.platform.paper.smartinventory.listener;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryAction;
import org.bukkit.event.inventory.InventoryClickEvent;
import tr.com.infumia.infumialib.platform.paper.smartinventory.SmartInventory;
import tr.com.infumia.infumialib.platform.paper.smartinventory.event.IcClickEvent;
import tr.com.infumia.infumialib.platform.paper.smartinventory.event.PgBottomClickEvent;
import tr.com.infumia.infumialib.platform.paper.smartinventory.event.PgClickEvent;
import tr.com.infumia.infumialib.platform.paper.smartinventory.event.PgOutsideClickEvent;
import tr.com.infumia.infumialib.platform.paper.smartinventory.util.SlotPos;
/**
* a class that represents inventory click listeners.
*/
public final class InventoryClickListener implements Listener {
/**
* listens inventory click events.
*
* @param event the event to listen.
*/
@EventHandler
public void onInventoryClick(final InventoryClickEvent event) {
SmartInventory.getHolder(event.getWhoClicked().getUniqueId()).ifPresent(holder -> {
if (event.getAction() == InventoryAction.COLLECT_TO_CURSOR) {
event.setCancelled(true);
return;
}
final var page = holder.getPage();
final var contents = holder.getContents();
final var plugin = holder.getPlugin();
final var clicked = event.getClickedInventory();
if (clicked == null) {
page.accept(new PgOutsideClickEvent(contents, event, plugin));
return;
}
final var player = event.getWhoClicked();
if (clicked.equals(player.getOpenInventory().getBottomInventory())) {
page.accept(new PgBottomClickEvent(contents, event, plugin));
return;
}
final var current = event.getCurrentItem();
if (current == null || current.getType() == Material.AIR) {
page.accept(new PgClickEvent(contents, event, plugin));
return;
}
final var slot = event.getSlot();
final var row = slot / 9;
final var column = slot % 9;
if (!page.checkBounds(row, column)) {
return;
}
final var slotPos = SlotPos.of(row, column);
if (!contents.isEditable(slotPos)) {
event.setCancelled(true);
}
contents.get(slotPos).ifPresent(item ->
item.accept(new IcClickEvent(contents, event, item, plugin)));
if (!contents.isEditable(slotPos) && player instanceof Player) {
((Player) player).updateInventory();
}
});
}
}
| 38.173913 | 89 | 0.702733 |
02d1e1caf1319ebad3cdb1177f517546e1031d7f | 2,053 | /* Copyright 2019, Michael Werzen
*
* 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.
*
* Portions of this software are Copyright 2018, TessaTech LLC.
*
* Such portions are licensed under the MIT License (the "License"); you may not use this file
* except in compliance with the License.
* You may obtain a copy of the License at
* https://opensource.org/licenses/MIT
*/
package com.mikewerzen.zen.zenframework.logging;
import com.mikewerzen.zen.zenframework.logging.builder.LogMessageBuilder;
import com.mikewerzen.zen.zenframework.logging.export.LogDataExporter;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class ZenLogManager
{
private static final Logger logger = LogManager.getLogger(ZenLogManager.class);
@Value("${log.export.enabled:false}")
private boolean exportEnabled = false;
@Autowired
private LogMessageBuilder logMessageBuilder;
@Autowired
private LogDataExporter logDataExporter;
public void logTransaction(Object response)
{
writeLogMessage(logMessageBuilder.buildTransactionLog(response));
}
public void logEvent(Object response)
{
writeLogMessage(logMessageBuilder.buildEventLog(response));
}
private void writeLogMessage(String logMessage)
{
logger.info(logMessage);
if (exportEnabled)
{
logDataExporter.exportLogMessage(logMessage);
}
}
}
| 30.191176 | 94 | 0.777886 |
31381a55683d5d78ca3ba6e358f267d42e8455cd | 1,335 | package cn.iocoder.yudao.module.bpm.dal.dataobject.oa;
import cn.iocoder.yudao.module.bpm.enums.task.BpmProcessInstanceResultEnum;
import lombok.*;
import java.util.*;
import com.baomidou.mybatisplus.annotation.*;
import cn.iocoder.yudao.framework.mybatis.core.dataobject.BaseDO;
/**
* OA 请假申请 DO
*
* {@link #day} 请假天数,目前先简单做。一般是分成请假上午和下午,可以是 1 整天,可以是 0.5 半天
*
* @author jason
* @author 芋道源码
*/
@TableName("bpm_oa_leave")
@Data
@EqualsAndHashCode(callSuper = true)
@ToString(callSuper = true)
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class BpmOALeaveDO extends BaseDO {
/**
* 请假表单主键
*/
@TableId
private Long id;
/**
* 申请人的用户编号
*
* 关联 AdminUserDO 的 id 属性
*/
private Long userId;
/**
* 请假类型
*/
@TableField("`type`")
private String type;
/**
* 原因
*/
private String reason;
/**
* 开始时间
*/
private Date startTime;
/**
* 结束时间
*/
private Date endTime;
/**
* 请假天数
*/
private Long day;
/**
* 请假的结果
*
* 枚举 {@link BpmProcessInstanceResultEnum}
* 考虑到简单,所以直接复用了 BpmProcessInstanceResultEnum 枚举,也可以自己定义一个枚举哈
*/
private Integer result;
/**
* 对应的流程编号
*
* 关联 ProcessInstance 的 id 属性
*/
private String processInstanceId;
}
| 18.040541 | 75 | 0.611985 |
3ffea115e49fa4d9bad5be563a65e1317c4a9a8a | 849 | package com.nf147.platform.service.impl;
import com.nf147.platform.entity.GeEnterpriseCategory;
import com.nf147.platform.service.GeEnterpriseCategoryService;
import org.springframework.stereotype.Service;
import java.util.List;
/**
*周
* // TODO: 2019/2/18
*
*/
@Service
public class GeEnterpriseCategoryServiceImpl implements GeEnterpriseCategoryService {
@Override
public int deleteByPrimaryKey(Integer id) {
return 0;
}
@Override
public int insert(GeEnterpriseCategory record) {
return 0;
}
@Override
public GeEnterpriseCategory selectByPrimaryKey(Integer id) {
return null;
}
@Override
public List<GeEnterpriseCategory> selectAll() {
return null;
}
@Override
public int updateByPrimaryKey(GeEnterpriseCategory record) {
return 0;
}
}
| 20.707317 | 85 | 0.704358 |
10a14f4700e598089dd1760a466fc1d9dba71dc8 | 3,160 | package ampcontrol.model.training.model.layerblocks;
import org.deeplearning4j.nn.conf.layers.BatchNormalization;
import org.deeplearning4j.nn.conf.layers.Layer;
import org.junit.Test;
import org.nd4j.linalg.activations.IActivation;
import org.nd4j.linalg.activations.impl.ActivationCube;
import java.util.function.Function;
import static org.junit.Assert.assertTrue;
/**
* Test cases for {@link Conv2DBatchNormBefore}
*
* @author Christian Skärby
*/
public class Conv2DBatchNormBeforeTest {
/**
* Test that name contains all set parameters
*/
@Test
public void name() {
final int nrofKernels = 666;
final int kernelSize = 777;
final int stride_h = 888;
final int stride_w = 999;
final IActivation act = new ActivationCube();
String result = new Conv2DBatchNormBefore()
.setNrofKernels(nrofKernels)
.setKernelSize(kernelSize)
.setStride_h(stride_h)
.setStride_w(stride_w)
.setActivation(act)
.name();
assertTrue("Parameter not part of name!", result.contains(String.valueOf(nrofKernels)));
assertTrue("Parameter not part of name!", result.contains(String.valueOf(kernelSize)));
assertTrue("Parameter not part of name!", result.contains(String.valueOf(stride_h)));
assertTrue("Parameter not part of name!", result.contains(String.valueOf(stride_w)));
assertTrue("Parameter not part of name!", result.contains(LayerBlockConfig.actToStr(act)));
}
/**
* Test that name contains all set parameters
*/
@Test
public void name2() {
final int nrofKernels = 666;
final int kernelSize_h = 777;
final int kernelSize_w = 888;
final int stride = 999;
final IActivation act = new ActivationCube();
String result = new Conv2DBatchNormBefore()
.setNrofKernels(nrofKernels)
.setKernelSize_h(kernelSize_h)
.setKernelSize_w(kernelSize_w)
.setStride(stride)
.setActivation(act)
.name();
assertTrue("Parameter not part of name!", result.contains(String.valueOf(nrofKernels)));
assertTrue("Parameter not part of name!", result.contains(String.valueOf(kernelSize_h)));
assertTrue("Parameter not part of name!", result.contains(String.valueOf(kernelSize_w)));
assertTrue("Parameter not part of name!", result.contains(String.valueOf(stride)));
assertTrue("Parameter not part of name!", result.contains(LayerBlockConfig.actToStr(act)));
}
/**
* Test addLayers. Tests internals which is bad, but CBA to do anything else for such a simple class.
*/
@Test
public void addLayers() {
final Function<Layer, Boolean> layerChecker = new ProbingBuilderAdapter.FunctionQueue<>(
layer -> layer instanceof BatchNormalization,
Conv2DTest.conv2dLayerChecker);
final LayerBlockConfig toTest = new Conv2DBatchNormBefore();
ProbingBuilderAdapter.testLayerBlock(layerChecker, toTest, 2);
}
} | 40 | 105 | 0.660443 |
fbee5108d0f10ff985cfb8ed618a7149509e97f2 | 5,545 | /*
* Copyright © 2014 Stefan Niederhauser (nidin@gmx.ch)
*
* 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 guru.nidi.ramlproxy.core;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
public class MockServlet extends HttpServlet {
private final static Logger log = LoggerFactory.getLogger(MockServlet.class);
private final static Map<String, String> EXTENSION_MIME_TYPE = new HashMap<>();
static {
EXTENSION_MIME_TYPE.put("json", "application/json");
EXTENSION_MIME_TYPE.put("xml", "application/xml");
EXTENSION_MIME_TYPE.put("txt", "text/plain");
}
private final ObjectMapper mapper = new ObjectMapper();
private final File mockDir;
public MockServlet(File mockDir) {
this.mockDir = mockDir;
}
@Override
public void init() throws ServletException {
super.init();
log.info("Mock started");
}
@Override
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
final String pathInfo = req.getPathInfo();
final int pos = pathInfo.lastIndexOf('/');
final String path = pathInfo.substring(1, pos + 1);
final String name = pathInfo.substring(pos + 1);
final File targetDir = new File(mockDir, path);
final File file = findFileOrParent(targetDir, name, req.getMethod());
CommandDecorators.ALLOW_ORIGIN.set(req, res);
if (file == null) {
res.sendError(HttpServletResponse.SC_NOT_FOUND, "No or multiple file '" + name + "' found in directory '" + targetDir.getAbsolutePath() + "'");
return;
}
handleMeta(req, res, file.getParentFile(), file.getName());
res.setContentLength((int) file.length());
res.setContentType(mineType(file));
final ServletOutputStream out = res.getOutputStream();
try (final InputStream in = new FileInputStream(file)) {
copy(in, out);
} catch (IOException e) {
res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Problem delivering file '" + file.getAbsolutePath() + "': " + e);
}
out.flush();
}
private File findFileOrParent(File targetDir, String name, String method) {
File file = findFile(targetDir, name, method);
while (file == null && targetDir != null && !targetDir.equals(mockDir.getParentFile())) {
file = findFile(targetDir, "RESPONSE", method);
targetDir = targetDir.getParentFile();
}
return file;
}
private void handleMeta(HttpServletRequest req, HttpServletResponse res, File targetDir, String name) {
final int dotPos = name.lastIndexOf('.');
if (dotPos > 0) {
name = name.substring(0, dotPos);
}
final File metaFile = findFile(targetDir, "META-" + name, req.getMethod());
if (metaFile != null) {
try {
final ReponseMetaData meta = new ReponseMetaData(mapper.readValue(metaFile, Map.class));
meta.apply(res);
} catch (Exception e) {
log.warn("Problem applying meta data for '" + targetDir + "/" + name + "': " + e);
}
}
}
private void copy(InputStream in, OutputStream out) throws IOException {
final byte[] buf = new byte[4096];
int read;
while ((read = in.read(buf)) > 0) {
out.write(buf, 0, read);
}
}
private File findFile(File dir, String name, String method) {
final File methodFile = findFile(dir, method + "-" + name);
final File generalFile = findFile(dir, name);
return methodFile == null ? generalFile : methodFile;
}
private File findFile(File dir, final String name) {
final File[] files = dir.listFiles();
if (files == null) {
return null;
}
File res = null;
for (final File file : files) {
final String fileName = file.getName();
final int dotPos = fileName.lastIndexOf('.');
if (dotPos > 0 && fileName.substring(0, dotPos).equals(name)) {
if (EXTENSION_MIME_TYPE.containsKey(fileName.substring(dotPos + 1))) {
if (res == null) {
res = file;
} else {
return null;
}
}
}
}
return res;
}
private String mineType(File file) {
final String fileName = file.getName();
final int dotPos = fileName.lastIndexOf('.');
return EXTENSION_MIME_TYPE.get(fileName.substring(dotPos + 1));
}
}
| 37.214765 | 155 | 0.622002 |
8b8a23668b31dfdeaf8dd74d47fa9f87acd50cc2 | 275 | package lru_cache;
public class Main {
public static void main(String[] args) {
LRUCache2 lruCache = new LRUCache2(2);
lruCache.put(1, 1);
lruCache.put(2, 2);
lruCache.get(1);
lruCache.put(3, 3);
lruCache.get(2);
}
}
| 19.642857 | 46 | 0.56 |
1795b52f98f2b46bd12bfc3d57c1d9d9a6e02af8 | 425 | package xyz.nucleoid.extras.mixin;
import net.minecraft.entity.Entity;
import net.minecraft.server.world.ServerEntityManager;
import net.minecraft.server.world.ServerWorld;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.gen.Accessor;
@Mixin(ServerWorld.class)
public interface ServerWorldAccessor {
@Accessor("entityManager")
ServerEntityManager<Entity> nucleoid$getEntityManager();
}
| 30.357143 | 60 | 0.818824 |
f62f63f02d13717b873928d64a0c04a70b71dec7 | 4,327 | package Java8Streams;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class JavaStreams {
public static void main(String[] args) throws IOException {
// 1. Integer Stream
IntStream
.range(1, 10)
.forEach(System.out::print);
System.out.println();
// 2. Integer Stream with skip
IntStream
.range(1, 10)
.skip(5)
.forEach(x -> System.out.println(x));
System.out.println();
// 3. Integer Stream with sum
System.out.println(
IntStream
.range(1, 5)
.sum());
System.out.println();
// 4. Stream.of, sorted and findFirst
Stream.of("Ava", "Aneri", "Alberto")
.sorted()
.findFirst()
.ifPresent(System.out::println);
// 5. Stream from Array, sort, filter and print
String[] names = {"Al", "Ankit", "Kushal", "Brent", "Sarika", "amanda", "Hans", "Shivika", "Sarah"};
Arrays.stream(names) // same as Stream.of(names)
.filter(x -> x.startsWith("S"))
.sorted()
.forEach(System.out::println);
// 6. average of squares of an int array
Arrays.stream(new int[] {2, 4, 6, 8, 10})
.map(x -> x * x)
.average()
.ifPresent(System.out::println);
// 7. Stream from List, filter and print
List<String> people = Arrays.asList("Al", "Ankit", "Brent", "Sarika", "amanda", "Hans", "Shivika", "Sarah");
people
.stream()
.map(String::toLowerCase)
.filter(x -> x.startsWith("a"))
.forEach(System.out::println);
// 8. Stream rows from text file, sort, filter, and print
Stream<String> bands = Files.lines(Paths.get("Java8Streams/bands.txt"));
bands
.sorted()
.filter(x -> x.length() > 13)
.forEach(System.out::println);
bands.close();
// 9. Stream rows from text file and save to List
List<String> bands2 = Files.lines(Paths.get("Java8Streams/bands.txt"))
.filter(x -> x.contains("jit"))
.collect(Collectors.toList());
bands2.forEach(x -> System.out.println(x));
// 10. Stream rows from CSV file and count
Stream<String> rows1 = Files.lines(Paths.get("Java8Streams/data.txt"));
int rowCount = (int)rows1
.map(x -> x.split(","))
.filter(x -> x.length == 3)
.count();
System.out.println(rowCount + " rows.");
rows1.close();
// 11. Stream rows from CSV file, parse data from rows
Stream<String> rows2 = Files.lines(Paths.get("Java8Streams/data.txt"));
rows2
.map(x -> x.split(","))
.filter(x -> x.length == 3)
.filter(x -> Integer.parseInt(x[1]) > 15)
.forEach(x -> System.out.println(x[0] + " " + x[1] + " " + x[2]));
rows2.close();
// 12. Stream rows from CSV file, store fields in HashMap
Stream<String> rows3 = Files.lines(Paths.get("Java8Streams/data.txt"));
Map<String, Integer> map = new HashMap<>();
map = rows3
.map(x -> x.split(","))
.filter(x -> x.length == 3)
.filter(x -> Integer.parseInt(x[1]) > 15)
.collect(Collectors.toMap(
x -> x[0],
x -> Integer.parseInt(x[1])));
rows3.close();
for (String key : map.keySet()) {
System.out.println(key + " " + map.get(key));
}
// 13. Reduction - sum
double total = Stream.of(7.3, 1.5, 4.8)
.reduce(0.0, (Double a, Double b) -> a + b);
System.out.println("Total = " + total);
// 14. Reduction - summary statistics
IntSummaryStatistics summary = IntStream.of(7, 2, 19, 88, 73, 4, 10)
.summaryStatistics();
System.out.println(summary);
}
}
| 36.669492 | 116 | 0.503813 |
5eb0c753302f9a81086b0a718aa3f230db50e32f | 3,764 | package edu.qc.seclass.rlm;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.SearchView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
DatabaseHelper db;
Button btnAddData;
Button btnviewAll;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new DatabaseHelper(MainActivity.this);
SearchView searchBar = findViewById(R.id.reminderSearch);
searchBar.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
searchReminders(query);
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
populateMyLists();
}
public void showMessage(String title, String Message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(Message);
builder.show();
}
// Launch the New List activity
public void launchNewListActivity(View v) {
Intent i = new Intent(this, NewListActivity.class);
startActivity(i);
}
public void launchNewReminderActivity (View v) {
Intent i = new Intent(this, NewReminderActivity.class);
startActivity(i);
}
public void launchViewListActivity (View v) {
Intent i = new Intent(this, ViewListActivity.class);
//Pass in the List's information so the constructor in the ViewListActivity.java file can put together the list based on queries.
String listName = ((Button)v).getText().toString();
i.putExtra("ListName",listName);
startActivity(i);
}
private void populateMyLists () {
// TODO: Get a list of ReminderList(s) from DB
ArrayList<ReminderList> reminderLists = db.getAllDataList();
LinearLayout listOfLists = findViewById(R.id.listView);
listOfLists.removeAllViewsInLayout();
// TODO: Create a new view for each ReminderList in the ScrollableListView
for (ReminderList r : reminderLists) {
Button b = new Button(MainActivity.this);
b.setText(r.getListName());
b.setBackgroundColor(Color.WHITE);
b.setTextColor(Color.BLACK);
b.setId(Integer.parseInt(r.getListId()));
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
launchViewListActivity(v);
}
});
listOfLists.addView(b);
}
}
// public void searchButtonListener (View v) {
// SearchView searchBar = findViewById(R.id.reminderSearch);
// String query = searchBar.getQuery().toString();
// searchReminders(query);
// }
public void searchReminders (String query) {
System.out.println(query);
Intent i = new Intent(this, ViewListActivity.class);
i.putExtra("ListName", "Search");
i.putExtra("query", query);
startActivity(i);
}
@Override
protected void onPause () {
super.onPause();
db.close();
}
@Override
protected void onResume() {
super.onResume();
populateMyLists();
}
}
| 30.354839 | 137 | 0.6339 |
7d107cc7b2ac7c8464e6cafc37944d8823630367 | 281 | package br.com.cartorio.service;
import java.util.List;
import br.com.cartorio.model.Cartorio;
public interface CartorioService {
List<Cartorio> getAllCartorios();
void saveCartorio(Cartorio cartorio);
Cartorio getCartorioById(long id);
void deleteCartorioById(long id);
}
| 20.071429 | 38 | 0.793594 |
c2ec00b311a27af2d6100ef4d48f5fa828eac65a | 1,595 | package net.tenie.myblog.entity;
import org.hibernate.validator.constraints.Length;
import net.tenie.myblog.validate.Email;
import net.tenie.myblog.validate.Phone;
import net.tenie.myblog.validate.Required;
public class VisitorDTO {
private Integer id;
@Length(max=30)
private String name;
@Email
private String email;
@Length(max=100)
private String url;
@Length(max=300)
private String comment;
private Integer parentId;
private Integer postId;
@Length(max=300)
private String message;
@Phone
private String phone;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Integer getPostId() {
return postId;
}
public void setPostId(Integer postId) {
this.postId = postId;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getParentId() {
return parentId;
}
public void setParentId(Integer parentId) {
this.parentId = parentId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
}
| 14.241071 | 50 | 0.690909 |
d06ff78a4f065a973221ab1231874b7758c666a1 | 1,733 | package advancedObjects;
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.MobileElement;
import io.appium.java_client.TouchAction;
import io.appium.java_client.touch.offset.PointOption;
import org.openqa.selenium.Rectangle;
import org.openqa.selenium.support.FindBy;
import java.util.List;
public class SwipeableVertical extends BaseScreenAdvanced{
public SwipeableVertical(AppiumDriver<MobileElement> driver) {
super(driver);
}
@FindBy(id = "com.h6ah4i.android.example.advrecyclerview:id/container")
List<MobileElement> listVerticalElements;
public SwipeableVertical swipeDown(){
MobileElement firstElement = listVerticalElements.get(0);
Rectangle rectangle = firstElement.getRect();
int yFrom = rectangle.getY()+20;
int x = rectangle.getX() + rectangle.getWidth()/2;
int yTo = rectangle.getY() + rectangle.getHeight()-20;
TouchAction<?> touchAction = new TouchAction<>(driver);
touchAction.longPress(PointOption.point(x, yFrom))
.moveTo(PointOption.point(x, yTo))
.release().perform();
return this;
}
public SwipeableVertical SwipeUp(){
MobileElement firstElement = listVerticalElements.get(4);
Rectangle rectangle = firstElement.getRect();
int yFrom = rectangle.getY() + rectangle.getHeight()-100;
int x = rectangle.getX() + rectangle.getWidth()/2;
int yTo = rectangle.getY()+20;
TouchAction<?> touchAction = new TouchAction<>(driver);
touchAction.longPress(PointOption.point(x, yFrom))
.moveTo(PointOption.point(x, yTo))
.release().perform();
return this;
}
}
| 32.698113 | 75 | 0.678015 |
b9ef587fc4c9134c0e941d02c0202d148ea87886 | 1,311 | package com.ares.gui.guis.containergui.buttons;
import com.ares.gui.buttons.ToggleButton;
import com.ares.gui.guis.AresGui;
import com.ares.hack.hacks.BaseHack;
import com.ares.gui.buttons.Button;
public class HackToggleButton extends Button
{
private BaseHack hack;
public HackToggleButton(final AresGui a1, final int a2, final int a3, final int a4, final int a5, final BaseHack a6) {
super(a1, a2, a3, a4, a5, "");
this.hack = a6;
}
public BaseHack getHack() {
/*SL:21*/return this.hack;
}
public void setToggle(final boolean a1) {
/*SL:26*/this.hack.setEnabled(a1);
}
public boolean getToggled() {
/*SL:31*/return this.hack.getEnabled();
}
public void toggle() {
/*SL:36*/this.setToggle(!this.getToggled());
}
public void draw() {
/*SL:42*/if (this.hack.getEnabled()) {
HackToggleButton.mc.func_110434_K().func_110577_a(ToggleButton.ON_SWITCH);
}
else {
HackToggleButton.mc.func_110434_K().func_110577_a(ToggleButton.OFF_SWITCH);
}
func_146110_a(/*EL:51*/this.field_146128_h, this.field_146129_i, 0.0f, 0.0f, this.field_146120_f, this.field_146121_g, (float)this.field_146120_f, (float)this.field_146121_g);
}
}
| 30.488372 | 183 | 0.643783 |
0085384e66e0df8ef59495c6bf903c767f64e3ec | 2,467 | package gui.components;
import java.awt.AlphaComposite;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Insets;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.Arc2D;
import java.awt.geom.Area;
import java.awt.geom.Ellipse2D;
import java.awt.geom.GeneralPath;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.plaf.basic.BasicProgressBarUI;
public class ProgressCircleUI extends BasicProgressBarUI
{
@Override
public Dimension getPreferredSize(JComponent c)
{
Dimension d = super.getPreferredSize(c);
int v = Math.max(d.width, d.height);
d.setSize(v, v);
return d;
}
@Override
public void paint(Graphics g, JComponent c)
{
Insets b = progressBar.getInsets(); // area for border
int barRectWidth = progressBar.getWidth();
int barRectHeight = progressBar.getHeight();
if (barRectWidth <= 0 || barRectHeight <= 0)
{
return;
}
// draw the cells
Graphics2D g2 = (Graphics2D) g.create();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2.setPaint(progressBar.getForeground());
double degree = 360 * progressBar.getPercentComplete();
double sz = Math.min(barRectWidth, barRectHeight);
double cx = barRectWidth * .5;
double cy = barRectHeight * .5;
double or = sz * .5;
double ir = or - 2; // or - 20;
Shape outer = new Arc2D.Double(cx - or, cy - or, sz, sz, 90 - degree, degree, Arc2D.PIE);
g2.setComposite(AlphaComposite.SrcAtop);
g2.fill(outer);
Image logo = new ImageIcon(getClass().getResource("/images/logo_splash_inner.png")).getImage();
g2.drawImage(logo, -10, -10, logo.getWidth(null), logo.getHeight(null), null);
// Deal with possible text painting
if (progressBar.isStringPainted())
{
//paintString(g, b.left, b.top, barRectWidth/2, barRectHeight, 0, b);
FontMetrics lFontMetrics = progressBar.getFontMetrics(progressBar.getFont());
g2.drawString(progressBar.getString(), barRectWidth - lFontMetrics.stringWidth(progressBar.getString()), 300);
}
g2.dispose();
}
}
| 32.893333 | 114 | 0.724362 |
ff7c42aeda62cfa230fd489af6e4dfa62df7cb93 | 2,256 | /*
* Project: Confile
* File: YamlRepresenter.java
* Last Modified: 1/17/21, 8:38 PM
*
* Copyright 2021 AJ Romaniello
*
* 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.coachluck.confile.file;
import io.coachluck.confile.ConfigurationSection;
import io.coachluck.confile.serialization.ConfigurationSerializable;
import io.coachluck.confile.serialization.ConfigurationSerialization;
import org.jetbrains.annotations.NotNull;
import org.yaml.snakeyaml.nodes.Node;
import org.yaml.snakeyaml.representer.Representer;
import java.util.LinkedHashMap;
import java.util.Map;
public class YamlRepresenter extends Representer {
public YamlRepresenter() {
this.multiRepresenters.put(ConfigurationSection.class, new RepresentConfigurationSection());
this.multiRepresenters.put(ConfigurationSerializable.class, new RepresentConfigurationSerializable());
this.multiRepresenters.remove(Enum.class);
}
private class RepresentConfigurationSection extends RepresentMap {
@NotNull
public Node representData(@NotNull Object data) {
return super.representData(((ConfigurationSection) data).getValues(false));
}
}
private class RepresentConfigurationSerializable extends RepresentMap {
@NotNull
public Node representData(@NotNull Object data) {
ConfigurationSerializable serializable = (ConfigurationSerializable) data;
Map<String, Object> values = new LinkedHashMap<>();
values.put("==", ConfigurationSerialization.getAlias(serializable.getClass()));
values.putAll(serializable.serialize());
return super.representData(values);
}
}
} | 36.387097 | 110 | 0.725177 |
b8b88fa85ac196d46c1937dabf3bd72f66a18268 | 1,247 | /*
* 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 com.levien.synthesizer.core.model.oscillator;
import com.levien.synthesizer.core.model.FrequencyProvider;
import com.levien.synthesizer.core.model.SynthesisTime;
/**
* An oscillator module that outputs a square wave.
*/
public class Square extends Oscillator {
public Square(FrequencyProvider frequency) {
super(frequency);
sine_ = new Sine(frequency);
}
public double computeValue(SynthesisTime time) {
// The easiest way to make a square wave is to take a sine wave and round it to -1 or 1.
if (sine_.getValue(time) > 0.0) {
return 1.0;
} else {
return -1.0;
}
}
private Sine sine_;
}
| 29.690476 | 92 | 0.715317 |
a4fdfa8d83cbc2fcc42eb11a9535effa8142f42a | 3,530 | /*
* JTrozear.java
*
* Created on 29 de abril de 2005, 8:59
*/
package trozearImages;
import java.awt.*;
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;
public class JTrozear implements ImageObserver{
/** Creates a new instance of JTrozear */
public JTrozear() {
}
public void trozear(Image poImage,String psPathFicheSinExtension, int plPixelX, int plPixelY, double pdX, double pdY, double pdResolucionX, double pdResolucionY) throws Exception {
int lAnchoTotal = poImage.getWidth(this);
int lAltoTotal = poImage.getHeight(this);
int lNumeroX = lAnchoTotal / plPixelX;
int lNumeroY = lAltoTotal / plPixelY;
if((lAnchoTotal % plPixelX)>0.0){
lNumeroX++;
}
if((lAltoTotal % plPixelY)>0.0){
lNumeroY++;
}
BufferedImage loImageAux = new BufferedImage(plPixelX, plPixelY, BufferedImage.TYPE_INT_RGB);
Graphics2D loG= (Graphics2D)loImageAux.getGraphics();
int lX=0;
int lY=0;
int lAncho;
int lAlto;
for(int i = 0; i < lNumeroX; i++) {
lY=0;
for(int ii = 0; ii < lNumeroY; ii++){
lAncho = plPixelX;
lAlto =plPixelY;
if((lX+lAncho) > lAnchoTotal){
lAncho = lAnchoTotal - lX;
}
if((lY+lAlto) > lAltoTotal){
lAlto = lAltoTotal - lY;
}
if((lAncho != loImageAux.getWidth())||(lAlto != loImageAux.getHeight()) ){
loImageAux = new BufferedImage(lAncho, lAlto, BufferedImage.TYPE_INT_RGB);
loG= (Graphics2D)loImageAux.getGraphics();
}
loG.drawImage(poImage,0,0,lAncho,lAlto,lX,lY,lX+lAncho,lY+lAlto,this);
escribir(loImageAux, psPathFicheSinExtension, i, ii, (lX * pdResolucionX) + pdX, (lY * pdResolucionY) + pdY, pdResolucionX,pdResolucionY);
lY+=plPixelY;
}
lX+=plPixelX;
}
}
private void escribir(BufferedImage loImageAux, String psPathFicheSinExtension, int i, int ii, double pdX, double pdY, double pdResolucionX, double pdResolucionY) throws Exception {
String lsNombreCompletoSinExt = psPathFicheSinExtension + "_" + String.valueOf(i) +"_" + String.valueOf(ii);
//guardar image
File loFile = new File(lsNombreCompletoSinExt + ".jpg");
loFile.delete();
ImageIO.write(loImageAux, "jpg", loFile);
//guardar xml
FileOutputStream loOut = new FileOutputStream(lsNombreCompletoSinExt + ".xml");
try{
PrintWriter out = new PrintWriter(loOut);
out.println("<?xml version=\"1.0\"?>");
out.println("<metadata>");
out.println("<meta id=\"142\" content=\""+String.valueOf(pdX)+"\"/>");
out.println("<meta id=\"143\" content=\""+String.valueOf(pdY)+"\"/>");
out.println("<meta id=\"144\" content=\""+String.valueOf(pdResolucionX)+"\"/>");
out.println("<meta id=\"145\" content=\""+String.valueOf(pdResolucionY)+"\"/>");
out.println("</metadata>");
out.close();
}finally{
loOut.close();
}
}
public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) {
if((infoflags & 0xc0) != 0){
return false;
} else {
return true;
}
}
}
| 37.157895 | 185 | 0.563456 |
01219fade630f1bf86dcb88dbb1edc16820f34a2 | 3,734 | // Copyright 2017 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 codeu.model.store.basic;
import codeu.model.data.User;
import codeu.model.data.Notification;
import codeu.model.store.persistence.PersistentStorageAgent;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Store class that uses in-memory data structures to hold values and automatically loads from and
* saves to PersistentStorageAgent. It's a singleton so all servlet classes can access the same
* instance.
*/
public class NotificationStore {
/** Singleton instance of NotificationStore. */
private static NotificationStore instance;
/**
* Returns the singleton instance of NotificationStore that should be shared between all servlet
* classes. Do not call this function from a test; use getTestInstance() instead.
*/
public static NotificationStore getInstance() {
if (instance == null) {
instance = new NotificationStore(PersistentStorageAgent.getInstance(), UserStore.getInstance());
}
return instance;
}
/**
* Instance getter function used for testing. Supply a mock for PersistentStorageAgent and UserStore.
*
* @param persistentStorageAgent a mock used for testing
*/
public static NotificationStore getTestInstance(PersistentStorageAgent persistentStorageAgent, UserStore userStore) {
return new NotificationStore(persistentStorageAgent, userStore);
}
/**
* The PersistentStorageAgent responsible for loading Notifications from and saving Notifications to
* Datastore.
*/
private PersistentStorageAgent persistentStorageAgent;
private UserStore userStore;
/** The in-memory list of Notifications. */
private List<Notification> notifications;
/** This class is a singleton, so its constructor is private. Call getInstance() instead. */
private NotificationStore(PersistentStorageAgent persistentStorageAgent, UserStore userStore) {
this.persistentStorageAgent = persistentStorageAgent;
this.userStore = userStore;
notifications = new ArrayList<>();
}
public UUID getuserMentioned(String content){
Pattern pattern = Pattern.compile("@([^\\s]+)");
Matcher matcher = pattern.matcher(content);
User matchedUser = null;
if(matcher.find()) {
String group = matcher.group(1);
matchedUser = userStore.getUser(group);
}
if(matchedUser != null){
return matchedUser.getId();
}
return null;
}
public List<Notification> loadNotifications(){
return notifications;
}
/** Add a new notification to the current set of notifications known to the application. */
public void addNotification(Notification notification) {
notifications.add(notification);
persistentStorageAgent.writeThrough(notification);
}
/** Sets the List of Notifications stored by this NotificationStore. */
public void setNotifications(List<Notification> notifications) {
this.notifications = notifications;
}
}
| 35.226415 | 121 | 0.711302 |
4b5d281edd13f0deefe450a45e08a55fc5145cc3 | 289 | package cn.wolfcode.wolf2w.mapper;
import cn.wolfcode.wolf2w.domain.Region;
import cn.wolfcode.wolf2w.domain.StrategyRank;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
*攻略排行统计操作数据库接口
*/
public interface StrategyRankMapper extends BaseMapper<StrategyRank> {
}
| 24.083333 | 71 | 0.782007 |
57a182c661ba77cdcb8a38b5bc9c74b58ff7a555 | 380 | package uk.co.mattwhitaker.atlassian.jiracloudagileextended.model;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
public class IssueLinkType {
private long id;
private String name;
private String outwardName;
private String inwardName;
private Boolean isSubTaskLinkType;
private Boolean isSystemLinkType;
}
| 21.111111 | 66 | 0.781579 |
880b177b7b081dccc804dfb31082f5b24ab22c7a | 9,525 | ////////////////////////////////////////////////////////////////////////
/*
File: GeneralVerticalNearsidePerspectiveProjection.java
Author: Peter Hollemans
Date: 2012/11/02
CoastWatch Software Library and Utilities
Copyright (c) 2012 National Oceanic and Atmospheric Administration
All rights reserved.
Developed by: CoastWatch / OceanWatch
Center for Satellite Applications and Research
http://coastwatch.noaa.gov
For conditions of distribution and use, see the accompanying
license.txt file.
*/
////////////////////////////////////////////////////////////////////////
// Package
// -------
package noaa.coastwatch.util.trans;
// Imports
// -------
import java.awt.geom.AffineTransform;
import java.awt.geom.NoninvertibleTransformException;
import java.util.List;
import java.util.ArrayList;
import noaa.coastwatch.util.trans.GCTPCStyleProjection;
import noaa.coastwatch.util.trans.GCTPStyleProjection;
import noaa.coastwatch.util.trans.ProjectionConstants;
import noaa.coastwatch.util.EarthLocation;
import noaa.coastwatch.util.DataLocation;
/**
* The <code>GeneralVerticalNearsidePerspectiveProjection</code> class performs
* General Vertical Nearside Perspective map projection calculations.
*
* @author Peter Hollemans
* @since 3.3.0
*/
public class GeneralVerticalNearsidePerspectiveProjection
extends GCTPCStyleProjection {
// Variables
// ---------
private double R; // Radius of the earth (sphere)
private double cos_p15; // Cosine of the center latitude
private double false_easting; // x offset in meters
private double false_northing; // y offset in meters
private double lat_center; // Center latitude (projection center)
private double lon_center; // Center longitude (projection center)
private double p; // Height above sphere
private double sin_p15; // Sine of the center latitude
////////////////////////////////////////////////////////////
/**
* Performs initialization of the projection constants.
*
* @param r the (I) Radius of the earth (sphere).
* @param h the height above sphere.
* @param center_long the (I) Center longitude.
* @param center_lat the (I) Center latitude.
* @param false_east the x offset in meters.
* @param false_north the y offset in meters.
*
* @return OK on success, or not OK on failure.
*/
private long projinit (
double r,
double h,
double center_long,
double center_lat,
double false_east,
double false_north
) {
/*Place parameters in static storage for common use
-------------------------------------------------*/
R = r;
p = 1.0 + h / R;
lon_center = center_long;
lat_center = center_lat;
false_easting = false_east;
false_northing = false_north;
sin_p15 = Math.sin (center_lat); cos_p15 = Math.cos (center_lat);
/*Report parameters to the user
-----------------------------*/
ptitle ("GENERAL VERTICAL NEAR-SIDE PERSPECTIVE");
radius (r);
genrpt (h,"Height of Point Above Surface of Sphere: ");
cenlon (center_long);
cenlat (center_lat);
offsetp (false_easting, false_northing);
return (OK);
} // projinit
////////////////////////////////////////////////////////////
/**
* Constructs a map projection from the specified projection and
* affine transform. The {@link SpheroidConstants} and
* {@link ProjectionConstants} class should be consulted for
* valid parameter constants.
*
* @param rMajor the semi-major axis in meters.
* @param dimensions the dimensions of the data grid as <code>[rows,
* columns]</code>.
* @param affine the affine transform for translating data
* <code>[row, column]</code> to map <code>[x, y]</code>.
* @param h the height above sphere.
* @param center_long the (I) Center longitude.
* @param center_lat the (I) Center latitude.
* @param falseEast the false easting value.
* @param falseNorth the false northing value.
*
* @throws NoninvertibleTransformException if the map
* projection to data coordinate affine transform is not
* invertible.
* @throws IllegalArgumentException if the paramaters have an inconsistency.
*/
public GeneralVerticalNearsidePerspectiveProjection (
double rMajor,
int[] dimensions,
AffineTransform affine,
double h, // height above sphere
double center_long, // (I) Center longitude
double center_lat, // (I) Center latitude
double falseEast,
double falseNorth
) throws NoninvertibleTransformException {
// Initialize
// ----------
super (GVNSP, 0, rMajor, rMajor, dimensions, affine);
setFalse (falseEast, falseNorth);
long result = projinit (rMajor, h, center_long, center_lat,
falseEast, falseNorth);
if (result != OK)
throw new IllegalArgumentException ("Projection parameter inconsistency detected");
createBoundaryHandler();
} // GeneralVerticalNearsidePerspectiveProjection constructor
////////////////////////////////////////////////////////////
protected long projfor (
double lat,
double lon,
double x[],
double y[]
) {
double dlon;
double sinphi, cosphi;
double coslon;
double g;
double ksp;
/*Forward equations
-----------------*/
dlon = adjust_lon (lon - lon_center);
sinphi = Math.sin (lat); cosphi = Math.cos (lat);
coslon = Math.cos (dlon);
g = sin_p15*sinphi + cos_p15*cosphi*coslon;
if (g < (1.0/ p))
{
p_error ("Point cannot be projected","gvnsp-for");
return (153);
}
ksp = (p - 1.0)/(p - g);
x[0] = false_easting + R*ksp*cosphi*Math.sin (dlon);
y[0] = false_northing + R*ksp*(cos_p15*sinphi - sin_p15*cosphi*coslon);
return (OK);
} // projfor
////////////////////////////////////////////////////////////
protected long projinv (
double x,
double y,
double lon[],
double lat[]
) {
double rh;
double r;
double con;
double com;
double z, sinz, cosz;
/*Inverse equations
-----------------*/
x -= false_easting;
y -= false_northing;
rh = Math.sqrt (x*x + y*y);
r = rh / R;
con = p - 1.0;
com = p + 1.0;
if (r > Math.sqrt (con/com))
{
p_error ("Input data error","gvnsp-for");
return (155);
}
sinz = (p - Math.sqrt (1.0 - (r*r*com) / con)) / (con / r + r/con);
z = asinz (sinz);
sinz = Math.sin (z); cosz = Math.cos (z);
lon[0] = lon_center;
if (Math.abs (rh) <= EPSLN)
{
lat[0] = lat_center;
return (OK);
}
lat[0] = asinz (cosz*sin_p15 + ( y*sinz*cos_p15)/rh);
con = Math.abs (lat_center) - HALF_PI;
if (Math.abs (con) <= EPSLN)
{
if (lat_center >= 0.0)
{
lon[0] = adjust_lon (lon_center + Math.atan2 (x, -y));
return (OK);
}
else
{
lon[0] = adjust_lon (lon_center - Math.atan2 (-x, y));
return (OK);
}
}
con = cosz - sin_p15*Math.sin (lat[0]);
if ((Math.abs (con) < EPSLN) && (Math.abs (x) < EPSLN))
return (OK);
lon[0] = adjust_lon (lon_center + Math.atan2 ((x*sinz*cos_p15), (con*rh)));
return (OK);
} // projinv
////////////////////////////////////////////////////////////
/** The GVNSP implementation of the boundary cut test. */
private boolean isBoundaryCut (
EarthLocation a,
EarthLocation b
) {
boolean cut;
DataLocation dataLoc = new DataLocation (2);
transform (a, dataLoc);
boolean aValid = dataLoc.isValid();
transform (b, dataLoc);
boolean bValid = dataLoc.isValid();
cut = (!aValid || !bValid);
return (cut);
} // isBoundaryCut
////////////////////////////////////////////////////////////
/** Creates a boundary handler for this projection. */
private void createBoundaryHandler () {
List<EarthLocation> locList = new ArrayList<>();
// What we do here is trace out a circle of maximum radius in (x,y)
// map space and then transform each map coordiante to (lat,lon) and
// build a list of (lat,lon) locations for the boundary. We trace out
// the points at a spacing of about 1/2 degree.
double rMax = R*Math.sqrt ((p - 1.0) / (p + 1.0)) * (1.0 - EPSLN);
double[] lon = new double[1];
double[] lat = new double[1];
int points = 720;
double dtheta = 2*Math.PI / points;
for (int point = 0; point <= points; point++) {
double theta = dtheta * point;
double x = rMax * Math.cos (theta);
double y = rMax * Math.sin (theta);
long ret = projinv (x, y, lon, lat);
if (ret != OK) {
throw new IllegalStateException ("Error in gvnsp projinv computing boundary at theta = " +
Math.toDegrees (theta) + " and (x,y) = " + x + "," + y);
} // if
EarthLocation loc = new EarthLocation (
Math.toDegrees (lat[0]),
Math.toDegrees (lon[0]),
datum
);
locList.add (loc);
} // for
boundaryHandler = new BoundaryHandler ((a, b) -> isBoundaryCut (a, b), List.of (locList));
} // createBoundaryHandler
////////////////////////////////////////////////////////////
} // GeneralVerticalNearsidePerspectiveProjection
////////////////////////////////////////////////////////////////////////
| 29.580745 | 98 | 0.573228 |
fa58f639a57dee9fa6c423145ab4a54b513251d0 | 2,081 | package cn.oftenporter.oftendb.data;
import cn.oftenporter.oftendb.db.Condition;
import cn.oftenporter.oftendb.db.NameValues;
import cn.oftenporter.oftendb.db.QuerySettings;
import cn.oftenporter.porter.core.base.InNames;
import cn.oftenporter.porter.core.base.WObject;
import com.alibaba.fastjson.JSONObject;
import java.lang.reflect.Field;
/**
* Created by https://github.com/CLovinr on 2016/9/9.
*/
public abstract class DataAble implements Cloneable
{
public static final int OPTION_CODE_DEFAULT = -1;
public static final int OPTION_CODE_EXISTS = -2;
public static final int OPTION_CODE_LOGIN = -3;
/**
* 得到所属集合(或表)名称。
*
* @return
*/
public abstract String getCollectionName();
public abstract Condition forQuery();
public abstract KeysSelection keys();
public abstract JSONObject toJsonObject();
// public abstract Field getField(String fieldName)throws NoSuchFieldException;
protected abstract NameValues toNameValues(ParamsGetter.Params params) throws Exception;
public abstract void whenSetDataFinished(SetType setType, int optionCode, WObject wObject,
DBHandleAccess dbHandleAccess) throws DataException;
protected abstract void setParams(InNames.Name[] neceFields, Object[] nvalues, InNames.Name[] unneceFields,
Object[] uvalues,InNames.Name
[] innerNames,Object[] innerValues) throws Exception;
/**
* 得到数据库选择的键。
* @return
*/
protected abstract String[] getFinalKeys(KeysSelection keysSelection, ParamsGetter.Params params);
protected abstract void dealNames(Condition condition);
protected abstract void dealNames(QuerySettings querySettings);
protected abstract DataAble cloneData();
/**
* 转换ParamsSelection为Condition
*
* @param dbHandleSource
* @param selection
* @param wObject
* @param params
* @return
*/
protected abstract Condition getQuery(DBHandleSource dbHandleSource, ParamsSelection selection, WObject wObject,
ParamsGetter.Params params);
}
| 30.15942 | 116 | 0.727535 |
b90be5bff5ae0e0287a52be650b364de71367108 | 16,366 | /*
* Copyright (c) 2020, Wild Adventure
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. 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.
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
* 4. Redistribution of this software in source or binary forms shall be free
* of all charges or fees to the recipient of this software.
*
* 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.
*/
package wild.core.commands;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
import java.util.logging.Level;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.DyeColor;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.block.Sign;
import org.bukkit.block.banner.Pattern;
import org.bukkit.block.banner.PatternType;
import org.bukkit.command.CommandSender;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.BannerMeta;
import org.bukkit.inventory.meta.SkullMeta;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.potion.PotionEffectType;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import wild.api.WildCommons;
import wild.api.WildConstants;
import wild.api.command.CommandFramework.Permission;
import wild.api.command.SubCommandFramework;
import wild.api.item.BookTutorial;
import wild.api.item.CustomSkullAdapter;
import wild.api.item.ItemBuilder;
import wild.core.WildCommonsPermissions;
import wild.core.WildCommonsPlugin;
import wild.core.utils.GenericUtils;
import wild.core.utils.ReflectionUtils;
@Permission(WildCommonsPermissions.USE_COMMAND)
public class WildCommonsCommand extends SubCommandFramework {
public WildCommonsCommand(JavaPlugin plugin, String label) {
super(plugin, label);
}
@Override
public void noArgs(CommandSender sender) {
sender.sendMessage(ChatColor.DARK_GREEN + "Comandi WildCommons:");
for (SubCommandDetails subCommand : getAccessibleSubCommands(sender)) {
sender.sendMessage(ChatColor.GREEN + "/wildcommons " + subCommand.getName() + (subCommand.getUsage() != null ? " " + subCommand.getUsage() : ""));
}
}
@SubCommand("setslots")
@SubCommandUsage("<numero>")
@SubCommandMinArgs(1)
public void setslotsSub(CommandSender sender, String label, String[] args) {
int newSlots = CommandValidate.getPositiveInteger(args[0]);
try {
Object playerList = ReflectionUtils.getPrivateField(Bukkit.getServer(), "playerList");
ReflectionUtils.setPrivateField(playerList.getClass().getSuperclass(), playerList, "maxPlayers", newSlots);
sender.sendMessage(ChatColor.GREEN + "Hai impostato gli slot a " + newSlots + " fino al prossimo riavvio.");
} catch (Exception e) {
e.printStackTrace();
throw new ExecuteException("Impossibile impostare gli slot. Controlla la console.");
}
}
@SubCommand("head")
@SubCommandUsage("<uuid|texture URL>")
@SubCommandMinArgs(1)
public void headSub(CommandSender sender, String label, String[] args) {
Player player = CommandValidate.getPlayerSender(sender);
CustomSkullAdapter skullAdapter;
if (args[0].length() == 36 || args[0].length() == 32) {
String uuid = args[0].replace("-", "");
try {
JsonObject json = GenericUtils.readJsonElementFromURL("https://sessionserver.mojang.com/session/minecraft/profile/" + uuid).getAsJsonObject();
if (json.get("errorMessage") != null) {
throw new ExecuteException("Errore: " + json.get("errorMessage"));
}
JsonArray properties = json.get("properties").getAsJsonArray();
String base64Texture = properties.iterator().next().getAsJsonObject().get("value").getAsString();
skullAdapter = CustomSkullAdapter.fromEncodedTexture(base64Texture);
} catch (IOException e) {
e.printStackTrace();
throw new ExecuteException("Errore: " + e.getClass().getName());
}
} else {
String textureUrl = "http://textures.minecraft.net/texture/" + args[0];
skullAdapter = CustomSkullAdapter.fromURL(textureUrl);
}
ItemStack head = ItemBuilder.of(Material.SKULL_ITEM).durability(3).build();
SkullMeta headMeta = (SkullMeta) head.getItemMeta();
skullAdapter.apply(headMeta);
head.setItemMeta(headMeta);
player.getInventory().addItem(head);
}
@SubCommand("cleanup")
public void cleanupSub(CommandSender sender, String label, String[] args) {
File pluginsFolder = new File("plugins");
CommandValidate.isTrue(pluginsFolder.isDirectory(), "La cartella plugins non esiste!");
List<File> removeList = Lists.newArrayList();
List<String> whitelist = Arrays.asList("update", "Updater", "PluginMetrics");
for (File file : pluginsFolder.listFiles()) {
if (file.isDirectory()) {
if (whitelist.contains(file.getName())) {
continue;
}
removeList.add(file);
}
}
for (File file : pluginsFolder.listFiles()) {
if (file.isFile()) {
if (file.length() < 10) {
removeList.add(file);
continue;
}
try {
String pluginName = GenericUtils.getPluginYmlName(file);
for (Iterator<File> iter = removeList.iterator(); iter.hasNext();) {
if (iter.next().getName().equals(pluginName)) {
iter.remove(); // Non togliere se appartiene a un plugin nella cartella plugins
}
}
} catch (IOException e) {
e.printStackTrace();
sender.sendMessage(ChatColor.RED + "Impossibile leggere il file " + file.getName());
return;
}
}
}
CommandValidate.isTrue(!removeList.isEmpty(), "Non ci sono file da rimuovere.");
if (args.length > 0 && args[0].equalsIgnoreCase("confirm")) {
int removed = 0;
for (File toRemove : removeList) {
try {
FileUtils.forceDelete(toRemove);
removed++;
} catch (IOException e) {
e.printStackTrace();
sender.sendMessage(ChatColor.RED + "Impossibile cancellare " + toRemove.getName());
}
}
sender.sendMessage(ChatColor.YELLOW + "Rimossi " + removed + " file.");
} else {
StringBuilder filesMessage = new StringBuilder();
for (File toRemove : removeList) {
if (filesMessage.length() != 0) {
filesMessage.append(ChatColor.GRAY + ", ");
}
filesMessage.append(ChatColor.YELLOW + toRemove.getName());
}
sender.sendMessage(ChatColor.RED + "Verranno rimossi i seguenti " + removeList.size() + " file: ");
sender.sendMessage(filesMessage.toString());
sender.sendMessage(ChatColor.GRAY + "Usa \"/" + label + " cleanup confirm\" per continuare.");
}
}
@SubCommand("banner")
public void bannerSub(CommandSender sender, String label, String[] args) {
Player player = CommandValidate.getPlayerSender(sender);
ItemStack item = new ItemStack(Material.BANNER);
BannerMeta bannerMeta = (BannerMeta) item.getItemMeta();
bannerMeta.setBaseColor(DyeColor.BLACK);
bannerMeta.addPattern(new Pattern(DyeColor.LIME, PatternType.TRIANGLE_BOTTOM));
bannerMeta.addPattern(new Pattern(DyeColor.BLACK, PatternType.TRIANGLES_BOTTOM));
bannerMeta.addPattern(new Pattern(DyeColor.BLACK, PatternType.CROSS));
bannerMeta.addPattern(new Pattern(DyeColor.LIME, PatternType.STRIPE_LEFT));
bannerMeta.addPattern(new Pattern(DyeColor.LIME, PatternType.STRIPE_RIGHT));
bannerMeta.addPattern(new Pattern(DyeColor.BLACK, PatternType.BORDER));
bannerMeta.addPattern(new Pattern(DyeColor.BLACK, PatternType.STRIPE_TOP));
item.setItemMeta(bannerMeta);
player.getInventory().addItem(item);
player.sendMessage(ChatColor.GREEN + "Hai ricevuto il banner!");
}
@SubCommand("setline")
@SubCommandUsage("<numero> <testo>")
@SubCommandMinArgs(2)
public void setlineSub(CommandSender sender, String label, String[] args) {
Block block = CommandValidate.getPlayerSender(sender).getTargetBlock((Set<Material>) null, 20);
CommandValidate.notNull(block, "Il blocco è troppo lontano.");
BlockState blockstate = block.getState();
CommandValidate.isTrue(blockstate != null && blockstate instanceof Sign, "Non stai guardando un cartello.");
int line = CommandValidate.getInteger(args[0]);
CommandValidate.isTrue(1 <= line && line <= 4, "Inserisci un numero fra 1 e 4.");
String newText = WildCommons.color(StringUtils.join(args, " ", 1, args.length));
if (newText.equals("\"\"")) {
newText = null;
}
Sign sign = (Sign) blockstate;
sign.setLine(line - 1, newText);
sign.update(false, false);
sender.sendMessage(ChatColor.GREEN + "Hai impostato la " + line + "° linea.");
}
@SubCommand("replacecolor")
@SubCommandUsage("<linea> <colore>")
@SubCommandMinArgs(2)
public void replacecolorSub(CommandSender sender, String label, String[] args) {
Block block = CommandValidate.getPlayerSender(sender).getTargetBlock((Set<Material>) null, 20);
CommandValidate.notNull(block, "Il blocco è troppo lontano.");
BlockState blockstate = block.getState();
CommandValidate.isTrue(blockstate != null && blockstate instanceof Sign, "Non stai guardando un cartello.");
int line;
if (args[0].equalsIgnoreCase("*")) {
line = 0;
} else {
line = CommandValidate.getInteger(args[0]);
CommandValidate.isTrue(1 <= line && line <= 4, "Inserisci un numero fra 1 e 4.");
}
int line0 = line - 1;
Sign sign = (Sign) blockstate;
String newColor = WildCommons.color(args[1]);
CommandValidate.isTrue(ChatColor.stripColor(newColor).isEmpty(), "Hai inserito dei non-colori.");
if (line0 == -1) {
String[] lines = sign.getLines();
for (int i = 0; i < lines.length; i++) {
sign.setLine(i, lines[i].replaceAll(("(?i)(§[1-9A-FK-O])+"), newColor));
}
} else {
sign.setLine(line0, sign.getLine(line0).replaceAll(("(?i)(§[1-9A-FK-O])+"), newColor));
}
sign.update(false, false);
sender.sendMessage(ChatColor.GREEN + "Hai cambiato colore nel cartello.");
}
@SubCommand("book")
@SubCommandUsage("<file>")
@SubCommandMinArgs(1)
public void bookSub(CommandSender sender, String label, String[] args) {
Player player = CommandValidate.getPlayerSender(sender);
String path = args[0];
File bookFile = new File(path);
CommandValidate.isTrue(bookFile.isFile(), "File non trovato.");
new BookTutorial(WildCommonsPlugin.instance, bookFile, "BookCommand", "WildCommons").giveTo(player);
player.sendMessage(ChatColor.GREEN + "Hai ricevuto il libro!");
}
@SubCommand("translation")
public void translationSub(CommandSender sender, String label, String[] args) {
if (args.length == 0) {
sender.sendMessage(ChatColor.DARK_GREEN + "Comandi traduzioni:");
sender.sendMessage(ChatColor.GREEN + "/" + label + " translation todo");
sender.sendMessage(ChatColor.GREEN + "/" + label + " translation reload");
return;
}
if (args[0].equalsIgnoreCase("todo")) {
List<String> missingMaterials = Lists.newArrayList();
List<String> missingEnchants = Lists.newArrayList();
List<String> missingPotionEffects = Lists.newArrayList();
List<String> missingEntityTypes = Lists.newArrayList();
for (Entry<Material, String> entry : WildCommonsPlugin.materialTranslationsMap.entrySet()) {
if (entry.getValue().equals(entry.getKey().toString())) {
// Se è uguale al toString(), non è tradotto.
missingMaterials.add(entry.getKey().toString());
}
}
for (Entry<Enchantment, String> entry : WildCommonsPlugin.enchantmentTranslationsMap.entrySet()) {
if (entry.getValue().equals(entry.getKey().getName())) {
// Se è uguale al getName(), non è tradotto.
missingEnchants.add(entry.getKey().getName());
}
}
for (Entry<PotionEffectType, String> entry : WildCommonsPlugin.potionEffectsTranslationsMap.entrySet()) {
if (entry.getValue().equals(entry.getKey().getName())) {
// Se è uguale al getName(), non è tradotto.
missingPotionEffects.add(entry.getKey().getName());
}
}
for (Entry<EntityType, String> entry : WildCommonsPlugin.entityTypesTranslationsMap.entrySet()) {
if (entry.getValue().equals(entry.getKey().toString())) {
// Se è uguale al toString(), non è tradotto.
missingEntityTypes.add(entry.getKey().toString());
}
}
sender.sendMessage(ChatColor.DARK_GREEN + "Materiali non tradotti (" + missingMaterials.size() + "):");
sender.sendMessage(ChatColor.GREEN + Joiner.on(", ").join(missingMaterials));
sender.sendMessage(ChatColor.DARK_GREEN + "Incantesimi non tradotti (" + missingEnchants.size() + "):");
sender.sendMessage(ChatColor.GREEN + Joiner.on(", ").join(missingEnchants));
sender.sendMessage(ChatColor.DARK_GREEN + "Effetti non tradotti (" + missingPotionEffects.size() + "):");
sender.sendMessage(ChatColor.GREEN + Joiner.on(", ").join(missingPotionEffects));
sender.sendMessage(ChatColor.DARK_GREEN + "Entità non tradotte (" + missingEntityTypes.size() + "):");
sender.sendMessage(ChatColor.GREEN + Joiner.on(", ").join(missingEntityTypes));
return;
}
if (args[0].equalsIgnoreCase("reload")) {
try {
WildCommonsPlugin.instance.loadTranslations();
sender.sendMessage(ChatColor.GREEN + "Traduzioni ricaricate.");
} catch (Exception ex) {
sender.sendMessage(ChatColor.RED + "Impossibile leggere le traduzioni, guarda la console.");
WildCommonsPlugin.instance.getLogger().log(Level.WARNING, "Impossibile leggere le traduzioni", ex);
}
return;
}
}
@SubCommand("lagtest")
@SubCommandUsage("[-bar]")
public void lagtestSub(CommandSender sender, String label, String[] args) {
LagtestRunnable previousTask = LagtestRunnable.tasks.get(sender);
if (previousTask == null) {
LagtestRunnable newTask = new LagtestRunnable(sender, args.length > 0 && args[0].equalsIgnoreCase("-bar"));
LagtestRunnable.tasks.put(sender, newTask);
newTask.runTaskTimer(WildCommonsPlugin.instance, 1, 1);
sender.sendMessage(ChatColor.GREEN + "Lagtest avviato.");
} else {
previousTask.cancel();
LagtestRunnable.tasks.remove(sender);
sender.sendMessage(ChatColor.GREEN + "Lagtest stoppato.");
}
}
@SuppressWarnings("deprecation")
@SubCommand("debug")
public void debugSub(CommandSender sender, String label, String[] args) {
final Player player = CommandValidate.getPlayerSender(sender);
WildCommons.sendActionBar(player, ChatColor.GREEN + "Test" + ChatColor.AQUA + "Test");
WildConstants.Titles.sendCountdownStarted(player, 10);
}
}
| 39.723301 | 150 | 0.701882 |
14fed56641617ab7a1b38dc276f23536371d97ac | 1,291 | package com.ruihai.xingka.ui.caption.publisher;
import com.ruihai.xingka.ui.caption.publisher.bean.PublishBean;
import java.util.concurrent.LinkedBlockingQueue;
/**
* Created by zecker on 15/10/2.
*/
public class PublishQueue extends LinkedBlockingQueue<PublishBean> {
private PublishQueueCallback callback;
public PublishQueue(PublishQueueCallback callback) {
this.callback = callback;
}
@Override
public PublishBean poll() {
PublishBean bean = super.poll();
if(callback != null && bean != null)
callback.onPublishPoll(bean);
return bean;
}
@Override
public void clear() {
super.clear();
}
@Override
public boolean add(PublishBean e) {
boolean r = super.add(e);
if(r && callback != null)
callback.onPublishAdd(e);
return r;
}
@Override
public PublishBean peek() {
PublishBean bean = super.peek();
if(bean != null && callback != null)
callback.onPublishPeek(bean);
return bean;
}
public interface PublishQueueCallback {
public void onPublishPoll(PublishBean bean);
public void onPublishAdd(PublishBean bean);
public void onPublishPeek(PublishBean bean);
}
}
| 22.258621 | 68 | 0.632843 |
4d69d4a4b169aa19615915777bf7a4abd1b70ab6 | 1,914 | package org.basex.query.value.item;
import org.basex.query.*;
import org.basex.query.util.collation.*;
import org.basex.query.value.type.*;
import org.basex.util.*;
/**
* Untyped atomic item ({@code xs:untypedAtomic}).
*
* @author BaseX Team 2005-19, BSD License
* @author Christian Gruen
*/
public final class Atm extends Item {
/** String data. */
private final byte[] value;
/**
* Constructor.
* @param value value
*/
public Atm(final byte[] value) {
super(AtomType.ATM);
this.value = value;
}
/**
* Constructor.
* @param value value
*/
public Atm(final String value) {
this(Token.token(value));
}
@Override
public byte[] string(final InputInfo ii) {
return value;
}
@Override
public boolean bool(final InputInfo ii) {
return value.length != 0;
}
@Override
public boolean eq(final Item item, final Collation coll, final StaticContext sc,
final InputInfo ii) throws QueryException {
return item.type.isUntyped() ? coll == null ? Token.eq(value, item.string(ii)) :
coll.compare(value, item.string(ii)) == 0 : item.eq(this, coll, sc, ii);
}
@Override
public boolean sameKey(final Item item, final InputInfo ii) throws QueryException {
return item.type.isStringOrUntyped() && eq(item, null, null, ii);
}
@Override
public int diff(final Item item, final Collation coll, final InputInfo ii)
throws QueryException {
return item.type.isUntyped() ? coll == null ? Token.diff(value, item.string(ii)) :
coll.compare(value, item.string(ii)) : -item.diff(this, coll, ii);
}
@Override
public boolean equals(final Object obj) {
return this == obj || obj instanceof Atm && Token.eq(value, ((Atm) obj).value);
}
@Override
public String toJava() {
return Token.string(value);
}
@Override
public String toString() {
return Token.string(toQuotedToken(value));
}
}
| 24.227848 | 86 | 0.660397 |
908b1aa59095c10ff308a182f761454187ee6d3e | 11,517 | /**
* The MIT License
*
* Copyright (c) 2017, Mahmoud Ben Hassine (mahmoud.benhassine@icloud.com)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package io.github.benas.randombeans.util;
import io.github.benas.randombeans.beans.*;
import org.junit.jupiter.api.Test;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import static org.assertj.core.api.Assertions.assertThat;
public class ReflectionUtilsTest {
@Test
public void testGetDeclaredFields() throws Exception {
BigDecimal javaVersion = new BigDecimal(System.getProperty("java.specification.version"));
if (javaVersion.compareTo(new BigDecimal("12")) >= 0) {
assertThat(ReflectionUtils.getDeclaredFields(Street.class)).hasSize(21);
} else if (javaVersion.compareTo(new BigDecimal("9")) >= 0) {
assertThat(ReflectionUtils.getDeclaredFields(Street.class)).hasSize(22);
} else {
assertThat(ReflectionUtils.getDeclaredFields(Street.class)).hasSize(20);
}
}
@Test
public void testGetInheritedFields() throws Exception {
assertThat(ReflectionUtils.getInheritedFields(SocialPerson.class)).hasSize(11);
}
@Test
public void testIsStatic() throws Exception {
assertThat(ReflectionUtils.isStatic(Human.class.getField("SERIAL_VERSION_UID"))).isTrue();
}
@Test
public void testIsInterface() throws Exception {
assertThat(ReflectionUtils.isInterface(List.class)).isTrue();
assertThat(ReflectionUtils.isInterface(Mammal.class)).isTrue();
assertThat(ReflectionUtils.isInterface(MammalImpl.class)).isFalse();
assertThat(ReflectionUtils.isInterface(ArrayList.class)).isFalse();
}
@Test
public void testIsAbstract() throws Exception {
assertThat(ReflectionUtils.isAbstract(Foo.class)).isFalse();
assertThat(ReflectionUtils.isAbstract(Bar.class)).isTrue();
}
@Test
public void testIsPublic() throws Exception {
assertThat(ReflectionUtils.isPublic(Foo.class)).isTrue();
assertThat(ReflectionUtils.isPublic(Dummy.class)).isFalse();
}
@Test
public void testIsArrayType() throws Exception {
assertThat(ReflectionUtils.isArrayType(int[].class)).isTrue();
assertThat(ReflectionUtils.isArrayType(Foo.class)).isFalse();
}
@Test
public void testIsEnumType() throws Exception {
assertThat(ReflectionUtils.isEnumType(Gender.class)).isTrue();
assertThat(ReflectionUtils.isEnumType(Foo.class)).isFalse();
}
@Test
public void testIsCollectionType() throws Exception {
assertThat(ReflectionUtils.isCollectionType(CustomList.class)).isTrue();
assertThat(ReflectionUtils.isCollectionType(Foo.class)).isFalse();
}
@Test
public void testIsMapType() throws Exception {
assertThat(ReflectionUtils.isMapType(CustomMap.class)).isTrue();
assertThat(ReflectionUtils.isMapType(Foo.class)).isFalse();
}
@Test
public void testIsJdkBuiltIn() throws Exception {
assertThat(ReflectionUtils.isJdkBuiltIn(ArrayList.class)).isTrue();
assertThat(ReflectionUtils.isJdkBuiltIn(CustomList.class)).isFalse();
}
@Test
public void getWrapperTypeTest() throws Exception {
assertThat(ReflectionUtils.getWrapperType(Byte.TYPE)).isEqualTo(Byte.class);
assertThat(ReflectionUtils.getWrapperType(Short.TYPE)).isEqualTo(Short.class);
assertThat(ReflectionUtils.getWrapperType(Integer.TYPE)).isEqualTo(Integer.class);
assertThat(ReflectionUtils.getWrapperType(Long.TYPE)).isEqualTo(Long.class);
assertThat(ReflectionUtils.getWrapperType(Double.TYPE)).isEqualTo(Double.class);
assertThat(ReflectionUtils.getWrapperType(Float.TYPE)).isEqualTo(Float.class);
assertThat(ReflectionUtils.getWrapperType(Boolean.TYPE)).isEqualTo(Boolean.class);
assertThat(ReflectionUtils.getWrapperType(Character.TYPE)).isEqualTo(Character.class);
assertThat(ReflectionUtils.getWrapperType(String.class)).isEqualTo(String.class);
}
@Test
public void testIsPrimitiveFieldWithDefaultValue() throws Exception {
Class<PrimitiveFieldsWithDefaultValuesBean> defaultValueClass = PrimitiveFieldsWithDefaultValuesBean.class;
PrimitiveFieldsWithDefaultValuesBean defaultValueBean = new PrimitiveFieldsWithDefaultValuesBean();
assertThat(ReflectionUtils.isPrimitiveFieldWithDefaultValue(defaultValueBean, defaultValueClass.getField("bool"))).isTrue();
assertThat(ReflectionUtils.isPrimitiveFieldWithDefaultValue(defaultValueBean, defaultValueClass.getField("b"))).isTrue();
assertThat(ReflectionUtils.isPrimitiveFieldWithDefaultValue(defaultValueBean, defaultValueClass.getField("s"))).isTrue();
assertThat(ReflectionUtils.isPrimitiveFieldWithDefaultValue(defaultValueBean, defaultValueClass.getField("i"))).isTrue();
assertThat(ReflectionUtils.isPrimitiveFieldWithDefaultValue(defaultValueBean, defaultValueClass.getField("l"))).isTrue();
assertThat(ReflectionUtils.isPrimitiveFieldWithDefaultValue(defaultValueBean, defaultValueClass.getField("f"))).isTrue();
assertThat(ReflectionUtils.isPrimitiveFieldWithDefaultValue(defaultValueBean, defaultValueClass.getField("d"))).isTrue();
assertThat(ReflectionUtils.isPrimitiveFieldWithDefaultValue(defaultValueBean, defaultValueClass.getField("c"))).isTrue();
Class<PrimitiveFieldsWithNonDefaultValuesBean> nonDefaultValueClass = PrimitiveFieldsWithNonDefaultValuesBean.class;
PrimitiveFieldsWithNonDefaultValuesBean nonDefaultValueBean = new PrimitiveFieldsWithNonDefaultValuesBean();
assertThat(ReflectionUtils.isPrimitiveFieldWithDefaultValue(nonDefaultValueBean, nonDefaultValueClass.getField("bool"))).isFalse();
assertThat(ReflectionUtils.isPrimitiveFieldWithDefaultValue(nonDefaultValueBean, nonDefaultValueClass.getField("b"))).isFalse();
assertThat(ReflectionUtils.isPrimitiveFieldWithDefaultValue(nonDefaultValueBean, nonDefaultValueClass.getField("s"))).isFalse();
assertThat(ReflectionUtils.isPrimitiveFieldWithDefaultValue(nonDefaultValueBean, nonDefaultValueClass.getField("i"))).isFalse();
assertThat(ReflectionUtils.isPrimitiveFieldWithDefaultValue(nonDefaultValueBean, nonDefaultValueClass.getField("l"))).isFalse();
assertThat(ReflectionUtils.isPrimitiveFieldWithDefaultValue(nonDefaultValueBean, nonDefaultValueClass.getField("f"))).isFalse();
assertThat(ReflectionUtils.isPrimitiveFieldWithDefaultValue(nonDefaultValueBean, nonDefaultValueClass.getField("d"))).isFalse();
assertThat(ReflectionUtils.isPrimitiveFieldWithDefaultValue(nonDefaultValueBean, nonDefaultValueClass.getField("c"))).isFalse();
}
@Test
public void testGetReadMethod() throws NoSuchFieldException {
assertThat(ReflectionUtils.getReadMethod(PrimitiveFieldsWithDefaultValuesBean.class.getDeclaredField("b"))).isEmpty();
final Optional<Method> readMethod =
ReflectionUtils.getReadMethod(Foo.class.getDeclaredField("bar"));
assertThat(readMethod).isNotNull();
assertThat(readMethod.get().getName()).isEqualTo("getBar");
}
@Test
public void testGetAnnotation() throws NoSuchMethodException, NoSuchFieldException {
Field field = AnnotatedBean.class.getDeclaredField("fieldAnnotation");
assertThat(ReflectionUtils.getAnnotation(field, NotNull.class)).isInstanceOf(NotNull.class);
field = AnnotatedBean.class.getDeclaredField("methodAnnotation");
assertThat(ReflectionUtils.getAnnotation(field, NotNull.class)).isInstanceOf(NotNull.class);
field = AnnotatedBean.class.getDeclaredField("noAnnotation");
assertThat(ReflectionUtils.getAnnotation(field, NotNull.class)).isNull();
}
@Test
public void testIsAnnotationPresent() throws NoSuchMethodException, NoSuchFieldException {
Field field = AnnotatedBean.class.getDeclaredField("fieldAnnotation");
assertThat(ReflectionUtils.isAnnotationPresent(field, NotNull.class)).isTrue();
field = AnnotatedBean.class.getDeclaredField("methodAnnotation");
assertThat(ReflectionUtils.isAnnotationPresent(field, NotNull.class)).isTrue();
field = AnnotatedBean.class.getDeclaredField("noAnnotation");
assertThat(ReflectionUtils.isAnnotationPresent(field, NotNull.class)).isFalse();
}
@SuppressWarnings("unused")
private class PrimitiveFieldsWithDefaultValuesBean {
public boolean bool;
public byte b;
public short s;
public int i;
public long l;
public float f;
public double d;
public char c;
}
@SuppressWarnings("unused")
private class PrimitiveFieldsWithNonDefaultValuesBean {
public boolean bool = true;
public byte b = (byte) 1;
public short s = (short) 1;
public int i = 1;
public long l = 1L;
public float f = 1.0F;
public double d = 1.0D;
public char c = 'a';
}
public static class AnnotatedBean {
@NotNull
private String fieldAnnotation;
private String methodAnnotation;
private String noAnnotation;
public String getFieldAnnotation() {
return fieldAnnotation;
}
public void setFieldAnnotation(String fieldAnnotation) {
this.fieldAnnotation = fieldAnnotation;
}
@NotNull
public String getMethodAnnotation() {
return methodAnnotation;
}
public void setMethodAnnotation(String methodAnnotation) {
this.methodAnnotation = methodAnnotation;
}
public String getNoAnnotation() {
return noAnnotation;
}
public void setNoAnnotation(String noAnnotation) {
this.noAnnotation = noAnnotation;
}
}
private class Dummy { }
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
@Documented
public @interface NotNull {
}
}
| 45.164706 | 139 | 0.732569 |
40cb81ae614697dbb7390c44d9a791404c8ba487 | 565 | package servlets.filters;
import java.sql.Timestamp;
/**
* Created by Андрей on 20.10.2017.
*/
public class Filter_User {
private String login;
private String email;
private String password;
public Filter_User(String login, String email, String password) {
this.email = email;
this.login = login;
this.password = password;
}
public String getEmail() {
return email;
}
public String getLogin() {
return login;
}
public String getPassword() {
return password;
}
}
| 16.617647 | 69 | 0.615929 |
3570b3e45c0274eba128ce09475dd2f4bf2d6fcb | 428 | package ru.vsu.db.provider;
import ru.vsu.db.entity.Socks;
import ru.vsu.db.entity.SocksId;
import java.util.Optional;
public interface SocksProvider {
Optional<Socks> findById(String color, Integer cottonPart);
Socks save(Socks entity);
Integer sumOfQuantityByColorAndCottonPartGreaterThan(String color, Integer cottonPart);
Integer sumOfQuantityByColorAndCottonPartLessThan(String color, Integer cottonPart);
}
| 23.777778 | 89 | 0.808411 |
fbe5c3bde98876f219d178fc3fc1c3d59db6035e | 17,047 | /*
* Copyright 2019 Laurent PAGE, Apache Licence 2.0
*/
package live.page.web.system.json;
import com.fasterxml.jackson.databind.ObjectMapper;
import live.page.web.system.db.tags.DbTags;
import live.page.web.utils.Fx;
import live.page.web.utils.Hidder;
import org.bson.BsonDocument;
import org.bson.BsonDocumentWrapper;
import org.bson.Document;
import org.bson.codecs.configuration.CodecRegistry;
import org.bson.conversions.Bson;
import org.bson.types.Binary;
import org.bson.types.Decimal128;
import java.io.Serializable;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* A cool toolkit for Json manipulation
*/
public class Json implements Map<String, Object>, Serializable, Bson {
//The real store
private final LinkedHashMap<String, Object> datas;
/**
* Init empty
*/
public Json() {
datas = new LinkedHashMap<>();
}
/**
* Init this a Json string, parse and make
*/
public Json(String json_string) {
datas = new LinkedHashMap<>();
if (json_string == null || json_string.equals("null")) {
return;
}
try {
ObjectMapper objmapper = new ObjectMapper();
DateFormat df = new SimpleDateFormat(Fx.ISO_DATE);
df.setTimeZone(TimeZone.getTimeZone("UTC"));
objmapper.setDateFormat(df);
putAll(objmapper.readValue(json_string, Json.class));
} catch (Exception e) {
if (Fx.IS_DEBUG) {
e.printStackTrace();
}
}
}
/**
* Init and put Map object entries
*
* @param map for initialisation
*/
public Json(Map<String, Object> map) {
datas = new LinkedHashMap<>();
datas.putAll(map);
}
/**
* Init and put anything have entries
*
* @param obj for initialisation
*/
public Json(Object obj) {
datas = new LinkedHashMap<>();
if (obj == null) {
return;
}
putAll((Map<String, Object>) obj);
}
/**
* Init with one entry
*
* @param key to put where
* @param value to put at key
*/
public Json(String key, Object value) {
datas = new LinkedHashMap<>();
datas.put(key, value);
}
private <T> T get(String key, Class<T> clazz) {
try {
if (get(key) == null) {
return null;
}
if (clazz.equals(Integer.class)) {
return clazz.cast(((Number) datas.get(key)).intValue());
}
return clazz.cast(datas.get(key));
} catch (Exception e) {
return null;
}
}
/**
* Get the ID as _id or id
*
* @return the id as String
*/
public String getId() {
if (containsKey("_id")) {
return getString("_id");
} else {
return getString("id");
}
}
/**
* Get anything from key
*
* @param key where find value
* @return value at key
*/
public Object get(String key) {
return datas.get(key);
}
/**
* Get anything from key with a failure value
*
* @param key where find the value
* @param def returned if there is no entry at key
* @return value at key
*/
public Object get(String key, Object def) {
if (get(key) == null) {
return def;
}
return get(key);
}
/**
* Get a string with a length limitation
*
* @param key where find the value
* @return null or a truncated string
*/
public String getString(String key) {
if (key == null) {
return null;
}
String val = get(key, String.class);
if (val == null) {
return null;
}
return Fx.truncate(val, 1000);
}
/**
* Get a string with a length limitation with a failure value
*
* @param key where find the value
* @param def returned if there is no entry at key
* @return null or a truncated string
*/
public String getString(String key, String def) {
if (containsKey(key) && get(key) != null) {
return getString(key);
}
return def;
}
/**
* Get a string with a limitation to possibles values
*
* @param key where find the value
* @param possibles values
* @return null or a value in possibles parameter
*/
public String getChoice(String key, String... possibles) {
for (String possible : possibles) {
if (possible.equals(get(key))) {
return getString(key);
}
}
return null;
}
/**
* Get a string
*
* @param key where find the value
* @return null or a string
*/
public String getText(String key) {
return get(key, String.class);
}
/**
* Get a string with a failure value
*
* @param key where find the value
* @param def returned if there is no entry at key
* @return null or a string
*/
public String getText(String key, String def) {
if (containsKey(key)) {
String text = getText(key);
if (text == null) {
return def;
}
return text;
}
return def;
}
/**
* Get a boolean with a failure value
*
* @param key where find the value
* @param def returned if there is no entry at key
* @return true or false
*/
public boolean getBoolean(String key, boolean def) {
try {
if (containsKey(key) && get(key) != null) {
return get(key, Boolean.class);
}
return def;
} catch (Exception e) {
if (getString(key, "").equals("true")) {
return true;
}
if (getString(key, "").equals("false")) {
return false;
}
return def;
}
}
/**
* Get a Date object at key
*
* @param key where find the value
* @return null or a Date object
*/
public Date getDate(String key) {
return get(key, Date.class);
}
/**
* Get a Date object at key with a failure value
*
* @param key where find the value
* @param def returned if there is no entry at key
* @return null or a Date object
*/
public Date getDate(String key, Date def) {
if (get(key) == null) {
return def;
}
return get(key, Date.class);
}
/**
* Parse a string value as a Date object
* Needed to parse when Json is created from a string
*
* @param key where find the value
* @return null or a Date object
*/
public Date parseDate(String key) {
if (getString(key) == null) {
return null;
}
try {
SimpleDateFormat fm = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
fm.setTimeZone(TimeZone.getTimeZone("UTC"));
return fm.parse(getString(key));
} catch (Exception e) {
return null;
}
}
/**
* Get a Integer at key
*
* @param key where find the value
* @return int value
*/
public int getInteger(String key) {
if (get(key).getClass().equals(Long.class)) {
return get(key, Long.class).intValue();
}
try {
return get(key, Integer.class);
} catch (Exception e) {
return Integer.parseInt(getString(key));
}
}
/**
* Get a Integer at key with a failure value
*
* @param key where find the value
* @param def returned if there is no entry at key
* @return int value
*/
public int getInteger(String key, int def) {
try {
if (datas.get(key) == null) {
return def;
}
return (int) get(key);
} catch (Exception e) {
try {
return Integer.parseInt(getString(key));
} catch (Exception ex) {
return def;
}
}
}
/**
* Get a Double at key
*
* @param key where find the value
* @return double value
*/
public double getDouble(String key) {
try {
return get(key, Double.class);
} catch (Exception e) {
return Double.parseDouble(getString(key));
}
}
/**
* Get a Double at key with a failure value
*
* @param key where find the value
* @param def returned if there is no entry at key
* @return double value
*/
public double getDouble(String key, double def) {
if (datas.get(key) == null) {
return def;
}
try {
return getDouble(key);
} catch (Exception e) {
try {
return getInteger(key);
} catch (Exception ex) {
return def;
}
}
}
/**
* Get a BigDecimal at key with a failure value
*
* @param key where find the value
* @param def returned if there is no entry at key
* @return BigDecimal value
*/
public BigDecimal getBigDecimal(String key, double def) {
if (get(key) instanceof Decimal128) {
return get(key, Decimal128.class).bigDecimalValue();
}
if (get(key) instanceof BigDecimal) {
return get(key, BigDecimal.class);
}
if (get(key) instanceof Double) {
return BigDecimal.valueOf(get(key, Double.class));
}
if (get(key) instanceof Float) {
return BigDecimal.valueOf(get(key, Float.class));
}
if (get(key) instanceof Long) {
return BigDecimal.valueOf(get(key, Long.class));
}
if (get(key) instanceof Integer) {
return BigDecimal.valueOf(get(key, Integer.class));
}
return BigDecimal.valueOf(def);
}
/**
* Get a List of string
*
* @param key where find the values
* @return List of string values
*/
public List<String> getList(String key) {
return getList(key, String.class);
}
/**
* Get a List of object in a specific class
*
* @param key where find the values
* @param clazz Class of the objects in the result
* @return List of objects values
*/
public <T> List<T> getList(String key, Class<T> clazz) {
return (List<T>) datas.get(key);
}
/**
* Get a Json
*
* @param key where find the json
* @return Json value
*/
public Json getJson(String key) {
if (get(key) == null) {
return null;
}
try {
if (get(key).getClass().equals(Json.class)) {
return get(key, Json.class);
} else if (get(key).getClass().equals(Document.class)) {
return new Json(get(key, Document.class));
} else {
return new Json(get(key));
}
} catch (Exception e) {
return null;
}
}
/**
* Get a List of Jsons
*
* @param key where find the jsons
* @return List of Jsons values
*/
public List<Json> getListJson(String key) {
if (key == null || get(key) == null) {
return null;
}
Iterator list = get(key, List.class).iterator();
List<Json> outlist = new ArrayList<>();
while (list.hasNext()) {
Object obj = list.next();
if (Json.class.isAssignableFrom(obj.getClass())) {
outlist.add((Json) obj);
} else if (Map.class.isAssignableFrom(obj.getClass())) {
outlist.add(new Json(obj));
} else {
return null;
}
}
return outlist;
}
/**
* Get Binary Data at a key
*
* @param key where find the binary
* @return binary value
*/
public Binary getBinary(String key) {
return get(key, Binary.class);
}
/**
* Count entries in this object
*
* @return number of entries
*/
@Override
public int size() {
return datas.size();
}
/**
* Is this object empty ?
*
* @return true if empty
*/
@Override
public boolean isEmpty() {
return datas.isEmpty();
}
/**
* Is this object contains entry at this key ?
*
* @param key where to find entry
* @return true if contains
*/
@Override
public boolean containsKey(Object key) {
return datas.containsKey(key);
}
/**
* Is this object contains this value ?
*
* @param value to find in this object
* @return true if contains
*/
@Override
public boolean containsValue(Object value) {
return datas.containsValue(value);
}
/**
* Get entry at a specific key
*
* @param key where find the value
* @return the entry value
*/
@Override
public Object get(Object key) {
return datas.get(key);
}
/**
* Put a value in this Json object at the end
*
* @param key where to put an entry
* @param value to put in entry
* @return this object
*/
public Json put(String key, Object value) {
datas.remove(key);
datas.put(key, value);
return this;
}
/**
* Put a value in this Json object at first
*
* @param key where to put an entry
* @param value to put in entry
* @return this object
*/
public Json prepend(String key, Object value) {
datas.remove(key);
Json clone = new Json(this);
datas.clear();
datas.put(key, value);
datas.putAll(clone);
return this;
}
/**
* Put a value in this Json object at the same place if exists, or at the end
*
* @param key where to put an entry
* @param value to put in entry
* @return this object
*/
public Json set(String key, Object value) {
datas.put(key, value);
return this;
}
/**
* Put all entry of a Map object
*
* @param map where entries have to be putted
*/
@Override
public void putAll(Map<? extends String, ?> map) {
datas.putAll(map);
}
/**
* Put all entry of a Json object
*
* @param map where entries have to be putted
*/
public Json putAll(Json map) {
datas.putAll(map);
return this;
}
/**
* Json contain entry at this key ?
*
* @param key where to find entry
* @return true if Json contain entry
*/
public boolean containsKey(String key) {
return datas.containsKey(key);
}
/**
* Remove entry
*
* @param key where to find the entry
* @return this Json object
*/
public Json remove(String key) {
datas.remove(key);
return this;
}
/**
* Remove value
*
* @param object to remove
* @return value of this entry
*/
@Override
public Object remove(Object object) {
return datas.remove(object);
}
/**
* Create or add value to a List in this object
*
* @param key where to find or create a List
* @param value to add to the List
* @return this Json object
*/
public Json add(String key, Object value) {
List<Object> values = getList(key, Object.class);
if (values == null) {
values = new ArrayList<>();
}
values.add(value);
return put(key, values);
}
/**
* Create or add value to a List in this object at a specific position
*
* @param key where to find or create a List
* @param value to add to the List
* @param position where to add value
* @return this Json object
*/
public Json add(String key, Object value, int position) {
List<Object> values = getList(key, Object.class);
if (values == null) {
values = new ArrayList<>();
}
values.add(position, value);
return put(key, values);
}
/**
* Get all entries in this object
*
* @return entries
*/
@Override
public Set<java.util.Map.Entry<String, Object>> entrySet() {
return datas.entrySet();
}
/**
* Get all keys in this object
*
* @return keys
*/
@Override
public Set<String> keySet() {
return datas.keySet();
}
/**
* Get all keys in this object
*
* @return List of keys
*/
public List<String> keyList() {
List<String> keys = new ArrayList<>();
Collections.addAll(keys, datas.keySet().toArray(new String[0]));
return keys;
}
/**
* Get all values in this object
*
* @return values
*/
@Override
public Collection<Object> values() {
return datas.values();
}
/**
* Clear/Empty this Json object
*/
@Override
public void clear() {
datas.clear();
}
/**
* Stringify this object as JavaScript standard
*
* @return a string usable in JavaScript
*/
@Override
public String toString() {
return XMLJsonParser.toJSON(this);
}
/**
* Stringify this object as JavaScript standard in low weight/compressed
*
* @return a compressed string usable in JavaScript
*/
public String toString(boolean compressed) {
return XMLJsonParser.toJSON(this, compressed);
}
/**
* To MongoDb document
*
* @return BsonDocument
*/
@Override
public <C> BsonDocument toBsonDocument(final Class<C> documentClass, final CodecRegistry codecRegistry) {
return new BsonDocumentWrapper<Json>(this, codecRegistry.get(Json.class));
}
/**
* Get a hashed representation
*
* @return a hash of this object
*/
public String getHash() {
return "i" + Hidder.encodeString(String.valueOf(toString().hashCode()));
}
/**
* Simple clone function
*
* @return a clone of this object
*/
@Override
public Json clone() {
try {
return (Json) super.clone();
} catch (CloneNotSupportedException e) {
return new Json(this);
}
}
/**
* Get a List representation of this Object
*
* @return a List of the entries
*/
public List<Json> toList() {
List<Json> arr = new ArrayList<>();
for (Entry<String, Object> entry : datas.entrySet()) {
arr.add(new Json("key", entry.getKey()).put("value", entry.getValue()));
}
return arr;
}
/**
* Get the key of a value
*
* @return the first key where the value can be found
*/
public String findKey(Object value) {
if (value == null) {
return null;
}
for (Entry<String, Object> set : entrySet()) {
if (set.getValue().equals(value)) {
return set.getKey();
}
}
return null;
}
/**
* Get a DbTags
*
* @param key where find
* @return a DbTags
*/
public DbTags getParent(String key) {
try {
return new DbTags(getString(key));
} catch (Exception e) {
return null;
}
}
/**
* Get a List of DbTags
*
* @param key where find
* @return a List of DbTags
*/
public List<DbTags> getParents(String key) {
try {
List<DbTags> parents = new ArrayList<>();
for (String parent : getList(key)) {
parents.add(new DbTags(parent));
}
return parents;
} catch (Exception e) {
return null;
}
}
/**
* Sort entries by key
*
* @return Json where entries are alphabetical ordered
*/
public Json sort() {
List<String> keys = Arrays.asList(keySet().toArray(new String[0]));
Collections.sort(keys);
Collections.reverse(keys);
keys.forEach((key) -> prepend(key, get(key)));
return this;
}
}
| 20.055294 | 106 | 0.636476 |
d01efd6415ba7476ee89b624e07b8dd188f676a0 | 2,117 | package ui.dialog;
import core.Version;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Dialog;
import javafx.scene.image.ImageView;
import javafx.scene.layout.GridPane;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import ui.EmbeddedIcons;
public class AboutDialogFx extends Dialog{
private final Font fontFieldHeader;
private final Font fontFieldValue;
public AboutDialogFx() {
fontFieldHeader = Font.font(Font.getDefault().getFamily(), FontWeight.BOLD, Font.getDefault().getSize());
fontFieldValue = Font.getDefault();
initComponents();
}
private void initComponents() {
setTitle("About GRASSMARLIN");
GridPane layout = new GridPane();
// Logo:
ImageView imgLogo = EmbeddedIcons.Logo_Large.getImage();
layout.add(imgLogo, 0, 0, 1, 5);
//Title
Text textTitle = new Text();
textTitle.setText("GRASSMARLIN");
textTitle.setFont(Font.font(Font.getDefault().getFamily(), FontWeight.BOLD, 14.0));
layout.add(textTitle, 1, 0, 2, 1);
//Subtitle
Text textSubtitle = new Text();
textSubtitle.setText("SCADA and ICS analysis tool");
layout.add(textSubtitle, 1, 1, 2, 1);
//TODO: Version/Vendor should have some right padding for the headers.
//Version
Text headerVersion = new Text("Version");
headerVersion.setFont(fontFieldHeader);
layout.add(headerVersion, 1, 2);
Text valueVersion = new Text(Version.APPLICATION_VERSION);
valueVersion.setFont(fontFieldValue);
layout.add(valueVersion, 2, 2);
//Vendor
Text headerVendor = new Text("Vendor");
headerVendor.setFont(fontFieldHeader);
layout.add(headerVendor, 1, 3);
Text valueVendor = new Text("Department of Defense");
valueVendor.setFont(fontFieldValue);
layout.add(valueVendor, 2, 3);
this.getDialogPane().setContent(layout);
this.getDialogPane().getButtonTypes().add(ButtonType.CLOSE);
}
}
| 32.075758 | 113 | 0.665092 |
24fdf3ff379c2ff13d77a62613f0fe74b94577d1 | 4,805 | /* license: https://mit-license.org
*
* Star Trek: Interstellar Transport
*
* Written in 2021 by Moky <albert.moky@gmail.com>
*
* ==============================================================================
* The MIT License (MIT)
*
* Copyright (c) 2021 Albert Moky
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
* ==============================================================================
*/
package chat.dim.type;
import java.util.HashMap;
import java.util.Map;
import java.util.WeakHashMap;
public abstract class WeakKeyPairMap<K, V> implements KeyPairMap<K, V> {
private final K defaultKey;
// because the remote address will always different to local address, so
// we shared the same map for all directions here:
// mapping: (remote, local) => Connection
// mapping: (remote, null) => Connection
// mapping: (local, null) => Connection
private final Map<K, Map<K, V>> map = new HashMap<>();
protected WeakKeyPairMap(K any) {
super();
defaultKey = any;
}
@Override
public V get(K remote, K local) {
K key1, key2;
if (remote == null) {
assert local != null : "local & remote addresses should not empty at the same time";
key1 = local;
key2 = null;
} else {
key1 = remote;
key2 = local;
}
Map<K, V> table = map.get(key1);
if (table == null) {
return null;
}
V value;
if (key2 != null) {
// mapping: (remote, local) => Connection
value = table.get(key2);
if (value != null) {
return value;
}
// take any Connection connected to remote
return table.get(defaultKey);
}
// mapping: (remote, null) => Connection
// mapping: (local, null) => Connection
value = table.get(defaultKey);
if (value != null) {
// take the value with empty key2
return value;
}
// take any Connection connected to remote / bound to local
for (V v : table.values()) {
if (v != null) {
return v;
}
}
return null;
}
@Override
public void set(K remote, K local, V value) {
// create indexes with key pair (remote, local)
K key1, key2;
if (remote == null) {
assert local != null : "local & remote addresses should not empty at the same time";
key1 = local;
key2 = defaultKey;
} else if (local == null) {
key1 = remote;
key2 = defaultKey;
} else {
key1 = remote;
key2 = local;
}
Map<K, V> table = map.get(key1);
if (table != null) {
if (value == null) {
table.remove(key2);
} else {
table.put(key2, value);
}
} else if (value != null) {
table = new WeakHashMap<>();
table.put(key2, value);
map.put(key1, table);
}
}
@Override
public V remove(K remote, K local, V value) {
// remove indexes with key pair (remote, local)
K key1, key2;
if (remote == null) {
assert local != null : "local & remote addresses should not empty at the same time";
key1 = local;
key2 = defaultKey;
} else if (local == null) {
key1 = remote;
key2 = defaultKey;
} else {
key1 = remote;
key2 = local;
}
Map<K, V> table = map.get(key1);
return table == null ? null : table.remove(key2);
}
}
| 33.838028 | 96 | 0.541727 |
a30c5712c64c5064ae579bc2a8993f7d05a6d259 | 2,577 | package gov.healthit.chpl.entity.surveillance;
import java.time.LocalDate;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import gov.healthit.chpl.entity.listing.CertifiedProductSummaryEntity;
import lombok.Getter;
import lombok.Setter;
@Entity
@Table(name = "pending_surveillance")
@Getter
@Setter
public class PendingSurveillanceEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "surveillance_id_to_replace")
private String survFriendlyIdToReplace;
@Column(name = "certified_product_unique_id")
private String certifiedProductUniqueId;
@Column(name = "certified_product_id")
private Long certifiedProductId;
@OneToOne(optional = true, fetch = FetchType.LAZY)
@JoinColumn(name = "certified_product_id", insertable = false, updatable = false)
private CertifiedProductSummaryEntity certifiedProduct;
@Column(name = "start_date")
private LocalDate startDate;
@Column(name = "end_date")
private LocalDate endDate;
@Column(name = "type_value")
private String surveillanceType;
@Column(name = "randomized_sites_used")
private Integer numRandomizedSites;
@Column(name = "deleted")
private Boolean deleted;
@Column(name = "last_modified_user")
private Long lastModifiedUser;
@Column(name = "creation_date", insertable = false, updatable = false)
private Date creationDate;
@Column(name = "last_modified_date", insertable = false, updatable = false)
private Date lastModifiedDate;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "pendingSurveillanceId")
@Basic(optional = false)
@Column(name = "pending_surveillance_id", nullable = false)
private Set<PendingSurveillanceRequirementEntity> surveilledRequirements =
new HashSet<PendingSurveillanceRequirementEntity>();
@OneToMany(fetch = FetchType.LAZY, mappedBy = "pendingSurveillanceId")
@Basic(optional = false)
@Column(name = "pending_surveillance_id", nullable = false)
private Set<PendingSurveillanceValidationEntity> validation = new HashSet<PendingSurveillanceValidationEntity>();
}
| 31.048193 | 117 | 0.762127 |
6dbbb54756717f623ac4ef91143343d846e27adb | 184 | package com.symphony.logmxparser.base;
import com.lightysoft.logmx.business.ParsedEntry;
public interface EntryConsumer {
void addParsedEntry(ParsedEntry entry) throws Exception;
}
| 23 | 57 | 0.831522 |
7d0bcb10e365135dcc90b317fc15c22c235f5004 | 819 | package cn.hotpot.alchemy.level;
import cn.hotpot.alchemy.player.AlchemyPlayer;
import cn.hotpot.enums.ElixirSpecies;
import lombok.Data;
import lombok.RequiredArgsConstructor;
/**
* @author: qinzhu
* @since: 2020/08/15
* 炼丹等级
*/
@Data
@RequiredArgsConstructor
public abstract class BaseAlchemyLevel implements Level {
private final String title;
private final BaseAlchemyLevel nextLevel;
@Override
public void tryUpgrade(AlchemyPlayer player) {
if (canUpgrade(player)) {
player.setAlchemyLevel(nextLevel);
player.setAlchemyExp(0);
}
}
/**
* 获得炼丹成功几率加成
*
* @param elixirSpecies 丹药种类
* @return 返回值范围[0, 1000] e.g. 返回50表示成功几率增加千分之五十
*/
public abstract Integer getTheChanceOfSuccessBonus(ElixirSpecies elixirSpecies);
}
| 22.75 | 84 | 0.697192 |
2b4c791ae9df87b53ca8a80cf3e6e0002f7d81bd | 1,989 | package com.tang.util;
import android.content.Context;
import android.os.Build;
import android.os.Environment;
import java.io.File;
public class AppFilePath {
// KeyStore文件外置存储目录
public static String Wallet_DIR;
public static void init(Context context) {
Wallet_DIR = context.getFilesDir().getAbsolutePath();
}
/**
* 这种目录下的文件在应用被卸载时也会跟着被删除
*
* @param context
* @return
*/
public static File getExternalFilesDir(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
File path = context.getExternalFilesDir(null);
if (path != null) {
return path;
}
}
final String filesDir = "/Android/data/" + context.getPackageName() + "/files/";
return new File(Environment.getExternalStorageDirectory().getPath() + filesDir);
}
/**
* 这种目录下的文件在应用被卸载时也会跟着被删除
*
* @param context
* @return
*/
public static File getExternalCacheDir(Context context) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
File path = context.getExternalCacheDir();
if (path != null) {
return path;
}
}
final String cacheDir = "/Android/data/" + context.getPackageName() + "/cache/";
return new File(Environment.getExternalStorageDirectory().getPath() + cacheDir);
}
/**
* 这种目录下的文件在应用被卸载时不会被删除
* 钱包等数据可以存放到这里
*
* @return
*/
public static String getExternalPrivatePath(String name) {
String namedir = "/" + name + "/";
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())
|| !Environment.isExternalStorageRemovable()) {
return Environment.getExternalStorageDirectory().getPath() + namedir;
} else {
return null;
// return new File(DATA_ROOT_DIR_OUTER, name).getPath();
}
}
}
| 25.831169 | 88 | 0.600804 |
acecbda81d8a932a21bb76eb2d6cef3e3e2f018b | 2,731 | /**
Copyright 2008 University of Rochester
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package edu.ur.hibernate.ir.item.db;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import edu.ur.hibernate.HbCrudDAO;
import edu.ur.ir.item.VersionedItem;
import edu.ur.ir.item.VersionedItemDAO;
import edu.ur.ir.user.IrUser;
/**
* Represents an item that has one or more versions in the system.
*
* @author Nathan Sarr
*
*/
public class HbVersionedItemDAO implements VersionedItemDAO{
/** eclipse generated id */
private static final long serialVersionUID = -5349746984347671168L;
/** Helper for persisting information using hibernate. */
private final HbCrudDAO<VersionedItem> hbCrudDAO;
/**
* Default Constructor
*/
public HbVersionedItemDAO() {
hbCrudDAO = new HbCrudDAO<VersionedItem>(VersionedItem.class);
}
/**
* Set the session factory.
*
* @param sessionFactory
*/
public void setSessionFactory(SessionFactory sessionFactory)
{
hbCrudDAO.setSessionFactory(sessionFactory);
}
public Long getCount() {
Query q = hbCrudDAO.getSessionFactory().getCurrentSession().getNamedQuery("versionedItemCount");
return (Long)q.uniqueResult();
}
public VersionedItem getById(Long id, boolean lock) {
return hbCrudDAO.getById(id, lock);
}
public void makePersistent(VersionedItem entity) {
hbCrudDAO.makePersistent(entity);
}
public void makeTransient(VersionedItem entity) {
hbCrudDAO.makeTransient(entity);
}
@SuppressWarnings("unchecked")
public List<VersionedItem> getAllNameOrder() {
DetachedCriteria dc = DetachedCriteria.forClass(VersionedItem.class);
dc.addOrder(Order.asc("name"));
return (List<VersionedItem>) hbCrudDAO.getHibernateTemplate().findByCriteria(dc);
}
@SuppressWarnings("unchecked")
public List<VersionedItem> getAllVersionedItemsForUser(IrUser user) {
return (List<VersionedItem>) hbCrudDAO.getHibernateTemplate().findByNamedQuery("getAllVersionedItemsForUser", user.getId());
}
}
| 29.053191 | 127 | 0.729037 |
011a7cfc81795112b16f79b22ecfb141291723e9 | 19,945 | package net.bytebuddy.agent.builder;
import net.bytebuddy.description.type.PackageDescription;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.dynamic.DynamicType;
import net.bytebuddy.matcher.ElementMatchers;
import net.bytebuddy.test.utility.JavaVersionRule;
import net.bytebuddy.test.utility.MockitoRule;
import net.bytebuddy.utility.JavaModule;
import net.bytebuddy.utility.JavaType;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.MethodRule;
import org.junit.rules.TestRule;
import org.mockito.Mock;
import java.io.PrintStream;
import java.lang.instrument.Instrumentation;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static net.bytebuddy.matcher.ElementMatchers.none;
import static net.bytebuddy.test.utility.FieldByFieldComparison.hasPrototype;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.*;
public class AgentBuilderListenerTest {
private static final String FOO = "foo";
private static final boolean LOADED = true;
@Rule
public TestRule mockitoRule = new MockitoRule(this);
@Rule
public MethodRule javaVersionRule = new JavaVersionRule();
@Mock
private AgentBuilder.Listener first, second;
@Mock
private TypeDescription typeDescription;
@Mock
private ClassLoader classLoader;
@Mock
private JavaModule module;
@Mock
private DynamicType dynamicType;
@Mock
private Throwable throwable;
@Before
public void setUp() throws Exception {
when(typeDescription.getName()).thenReturn(FOO);
}
@Test
public void testNoOp() throws Exception {
AgentBuilder.Listener.NoOp.INSTANCE.onDiscovery(FOO, classLoader, module, LOADED);
AgentBuilder.Listener.NoOp.INSTANCE.onTransformation(typeDescription, classLoader, module, LOADED, dynamicType);
verifyZeroInteractions(dynamicType);
AgentBuilder.Listener.NoOp.INSTANCE.onError(FOO, classLoader, module, LOADED, throwable);
verifyZeroInteractions(throwable);
AgentBuilder.Listener.NoOp.INSTANCE.onIgnored(typeDescription, classLoader, module, LOADED);
AgentBuilder.Listener.NoOp.INSTANCE.onComplete(FOO, classLoader, module, LOADED);
}
@Test
public void testPseudoAdapter() throws Exception {
AgentBuilder.Listener listener = new PseudoAdapter();
listener.onDiscovery(FOO, classLoader, module, LOADED);
listener.onTransformation(typeDescription, classLoader, module, LOADED, dynamicType);
verifyZeroInteractions(dynamicType);
listener.onError(FOO, classLoader, module, LOADED, throwable);
verifyZeroInteractions(throwable);
listener.onIgnored(typeDescription, classLoader, module, LOADED);
listener.onComplete(FOO, classLoader, module, LOADED);
}
@Test
public void testCompoundOnDiscovery() throws Exception {
new AgentBuilder.Listener.Compound(first, second).onDiscovery(FOO, classLoader, module, LOADED);
verify(first).onDiscovery(FOO, classLoader, module, LOADED);
verifyNoMoreInteractions(first);
verify(second).onDiscovery(FOO, classLoader, module, LOADED);
verifyNoMoreInteractions(second);
}
@Test
public void testCompoundOnTransformation() throws Exception {
new AgentBuilder.Listener.Compound(first, second).onTransformation(typeDescription, classLoader, module, LOADED, dynamicType);
verify(first).onTransformation(typeDescription, classLoader, module, LOADED, dynamicType);
verifyNoMoreInteractions(first);
verify(second).onTransformation(typeDescription, classLoader, module, LOADED, dynamicType);
verifyNoMoreInteractions(second);
}
@Test
public void testCompoundOnError() throws Exception {
new AgentBuilder.Listener.Compound(first, second).onError(FOO, classLoader, module, LOADED, throwable);
verify(first).onError(FOO, classLoader, module, LOADED, throwable);
verifyNoMoreInteractions(first);
verify(second).onError(FOO, classLoader, module, LOADED, throwable);
verifyNoMoreInteractions(second);
}
@Test
public void testCompoundOnIgnored() throws Exception {
new AgentBuilder.Listener.Compound(first, second).onIgnored(typeDescription, classLoader, module, LOADED);
verify(first).onIgnored(typeDescription, classLoader, module, LOADED);
verifyNoMoreInteractions(first);
verify(second).onIgnored(typeDescription, classLoader, module, LOADED);
verifyNoMoreInteractions(second);
}
@Test
public void testCompoundOnComplete() throws Exception {
new AgentBuilder.Listener.Compound(first, second).onComplete(FOO, classLoader, module, LOADED);
verify(first).onComplete(FOO, classLoader, module, LOADED);
verifyNoMoreInteractions(first);
verify(second).onComplete(FOO, classLoader, module, LOADED);
verifyNoMoreInteractions(second);
}
@Test
public void testStreamWritingOnDiscovery() throws Exception {
PrintStream printStream = mock(PrintStream.class);
AgentBuilder.Listener listener = new AgentBuilder.Listener.StreamWriting(printStream);
listener.onDiscovery(FOO, classLoader, module, LOADED);
verify(printStream).printf("[Byte Buddy] DISCOVERY %s [%s, %s, %s, loaded=%b]%n", FOO, classLoader, module, Thread.currentThread(), LOADED);
verifyNoMoreInteractions(printStream);
}
@Test
public void testStreamWritingOnTransformation() throws Exception {
PrintStream printStream = mock(PrintStream.class);
AgentBuilder.Listener listener = new AgentBuilder.Listener.StreamWriting(printStream);
listener.onTransformation(typeDescription, classLoader, module, LOADED, dynamicType);
verify(printStream).printf("[Byte Buddy] TRANSFORM %s [%s, %s, %s, loaded=%b]%n", FOO, classLoader, module, Thread.currentThread(), LOADED);
verifyNoMoreInteractions(printStream);
}
@Test
public void testStreamWritingOnError() throws Exception {
PrintStream printStream = mock(PrintStream.class);
AgentBuilder.Listener listener = new AgentBuilder.Listener.StreamWriting(printStream);
listener.onError(FOO, classLoader, module, LOADED, throwable);
verify(printStream).printf("[Byte Buddy] ERROR %s [%s, %s, %s, loaded=%b]%n", FOO, classLoader, module, Thread.currentThread(), LOADED);
verifyNoMoreInteractions(printStream);
verify(throwable).printStackTrace(printStream);
verifyNoMoreInteractions(throwable);
}
@Test
public void testStreamWritingOnComplete() throws Exception {
PrintStream printStream = mock(PrintStream.class);
AgentBuilder.Listener listener = new AgentBuilder.Listener.StreamWriting(printStream);
listener.onComplete(FOO, classLoader, module, LOADED);
verify(printStream).printf("[Byte Buddy] COMPLETE %s [%s, %s, %s, loaded=%b]%n", FOO, classLoader, module, Thread.currentThread(), LOADED);
verifyNoMoreInteractions(printStream);
}
@Test
public void testStreamWritingOnIgnore() throws Exception {
PrintStream printStream = mock(PrintStream.class);
AgentBuilder.Listener listener = new AgentBuilder.Listener.StreamWriting(printStream);
listener.onIgnored(typeDescription, classLoader, module, LOADED);
verify(printStream).printf("[Byte Buddy] IGNORE %s [%s, %s, %s, loaded=%b]%n", FOO, classLoader, module, Thread.currentThread(), LOADED);
verifyNoMoreInteractions(printStream);
}
@Test
public void testStreamWritingStandardOutput() throws Exception {
assertThat(AgentBuilder.Listener.StreamWriting.toSystemOut(), hasPrototype((AgentBuilder.Listener) new AgentBuilder.Listener.StreamWriting(System.out)));
}
@Test
public void testStreamWritingStandardError() throws Exception {
assertThat(AgentBuilder.Listener.StreamWriting.toSystemError(), hasPrototype((AgentBuilder.Listener) new AgentBuilder.Listener.StreamWriting(System.err)));
}
@Test
public void testStreamWritingTransformationsOnly() throws Exception {
PrintStream target = mock(PrintStream.class);
assertThat(new AgentBuilder.Listener.StreamWriting(target).withTransformationsOnly(),
hasPrototype((AgentBuilder.Listener) new AgentBuilder.Listener.WithTransformationsOnly(new AgentBuilder.Listener.StreamWriting(target))));
}
@Test
public void testStreamWritingErrorOnly() throws Exception {
PrintStream target = mock(PrintStream.class);
assertThat(new AgentBuilder.Listener.StreamWriting(target).withErrorsOnly(),
hasPrototype((AgentBuilder.Listener) new AgentBuilder.Listener.WithErrorsOnly(new AgentBuilder.Listener.StreamWriting(target))));
}
@Test
public void testTransformationsOnly() {
AgentBuilder.Listener delegate = mock(AgentBuilder.Listener.class);
AgentBuilder.Listener listener = new AgentBuilder.Listener.WithTransformationsOnly(delegate);
listener.onDiscovery(FOO, classLoader, module, LOADED);
listener.onTransformation(typeDescription, classLoader, module, LOADED, dynamicType);
listener.onError(FOO, classLoader, module, LOADED, throwable);
listener.onIgnored(typeDescription, classLoader, module, LOADED);
listener.onComplete(FOO, classLoader, module, LOADED);
verify(delegate).onTransformation(typeDescription, classLoader, module, LOADED, dynamicType);
verify(delegate).onError(FOO, classLoader, module, LOADED, throwable);
verifyNoMoreInteractions(delegate);
}
@Test
public void testErrorsOnly() {
AgentBuilder.Listener delegate = mock(AgentBuilder.Listener.class);
AgentBuilder.Listener listener = new AgentBuilder.Listener.WithErrorsOnly(delegate);
listener.onDiscovery(FOO, classLoader, module, LOADED);
listener.onTransformation(typeDescription, classLoader, module, LOADED, dynamicType);
listener.onError(FOO, classLoader, module, LOADED, throwable);
listener.onIgnored(typeDescription, classLoader, module, LOADED);
listener.onComplete(FOO, classLoader, module, LOADED);
verify(delegate).onError(FOO, classLoader, module, LOADED, throwable);
verifyNoMoreInteractions(delegate);
}
@Test
public void testFilteringDoesNotMatch() throws Exception {
AgentBuilder.Listener delegate = mock(AgentBuilder.Listener.class);
AgentBuilder.Listener listener = new AgentBuilder.Listener.Filtering(none(), delegate);
listener.onDiscovery(FOO, classLoader, module, LOADED);
listener.onTransformation(typeDescription, classLoader, module, LOADED, dynamicType);
listener.onError(FOO, classLoader, module, LOADED, throwable);
listener.onIgnored(typeDescription, classLoader, module, LOADED);
listener.onComplete(FOO, classLoader, module, LOADED);
verifyZeroInteractions(delegate);
}
@Test
public void testFilteringMatch() throws Exception {
AgentBuilder.Listener delegate = mock(AgentBuilder.Listener.class);
AgentBuilder.Listener listener = new AgentBuilder.Listener.Filtering(ElementMatchers.any(), delegate);
listener.onDiscovery(FOO, classLoader, module, LOADED);
listener.onTransformation(typeDescription, classLoader, module, LOADED, dynamicType);
listener.onError(FOO, classLoader, module, LOADED, throwable);
listener.onIgnored(typeDescription, classLoader, module, LOADED);
listener.onComplete(FOO, classLoader, module, LOADED);
verify(delegate).onDiscovery(FOO, classLoader, module, LOADED);
verify(delegate).onTransformation(typeDescription, classLoader, module, LOADED, dynamicType);
verify(delegate).onError(FOO, classLoader, module, LOADED, throwable);
verify(delegate).onIgnored(typeDescription, classLoader, module, LOADED);
verify(delegate).onComplete(FOO, classLoader, module, LOADED);
verifyNoMoreInteractions(delegate);
}
@Test
public void testReadEdgeAddingListenerNotSupported() throws Exception {
Instrumentation instrumentation = mock(Instrumentation.class);
AgentBuilder.Listener listener = new AgentBuilder.Listener.ModuleReadEdgeCompleting(instrumentation, false, Collections.<JavaModule>emptySet());
listener.onTransformation(mock(TypeDescription.class), mock(ClassLoader.class), JavaModule.UNSUPPORTED, LOADED, mock(DynamicType.class));
}
@Test
public void testReadEdgeAddingListenerUnnamed() throws Exception {
Instrumentation instrumentation = mock(Instrumentation.class);
JavaModule source = mock(JavaModule.class), target = mock(JavaModule.class);
AgentBuilder.Listener listener = new AgentBuilder.Listener.ModuleReadEdgeCompleting(instrumentation, false, Collections.singleton(target));
listener.onTransformation(mock(TypeDescription.class), mock(ClassLoader.class), source, LOADED, mock(DynamicType.class));
verify(source).isNamed();
verifyNoMoreInteractions(source);
verifyZeroInteractions(target);
}
@Test
public void testReadEdgeAddingListenerCanRead() throws Exception {
Instrumentation instrumentation = mock(Instrumentation.class);
JavaModule source = mock(JavaModule.class), target = mock(JavaModule.class);
when(source.isNamed()).thenReturn(true);
when(source.canRead(target)).thenReturn(true);
AgentBuilder.Listener listener = new AgentBuilder.Listener.ModuleReadEdgeCompleting(instrumentation, false, Collections.singleton(target));
listener.onTransformation(mock(TypeDescription.class), mock(ClassLoader.class), source, LOADED, mock(DynamicType.class));
verify(source).isNamed();
verify(source).canRead(target);
verifyNoMoreInteractions(source);
verifyZeroInteractions(target);
}
@Test
@JavaVersionRule.Enforce(9)
public void testReadEdgeAddingListenerNamedCannotRead() throws Exception {
Instrumentation instrumentation = mock(Instrumentation.class);
JavaModule source = mock(JavaModule.class), target = mock(JavaModule.class);
when(source.isNamed()).thenReturn(true);
when(source.canRead(target)).thenReturn(false);
AgentBuilder.Listener listener = new AgentBuilder.Listener.ModuleReadEdgeCompleting(instrumentation, false, Collections.singleton(target));
when(Instrumentation.class.getMethod("isModifiableModule", JavaType.MODULE.load()).invoke(instrumentation, (Object) null)).thenReturn(true);
listener.onTransformation(mock(TypeDescription.class), mock(ClassLoader.class), source, LOADED, mock(DynamicType.class));
verify(source).isNamed();
verify(source).canRead(target);
Instrumentation.class.getMethod("redefineModule",
JavaType.MODULE.load(),
Set.class,
Map.class,
Map.class,
Set.class,
Map.class).invoke(verify(instrumentation),
null,
Collections.singleton(null),
Collections.<String, Set<JavaModule>>emptyMap(),
Collections.<String, Set<JavaModule>>emptyMap(),
Collections.<Class<?>>emptySet(),
Collections.<Class<?>, List<Class<?>>>emptyMap());
verify(source, times(2)).unwrap();
verifyNoMoreInteractions(source);
verify(target).unwrap();
verifyNoMoreInteractions(target);
}
@Test
public void testReadEdgeAddingListenerDuplexNotSupported() throws Exception {
Instrumentation instrumentation = mock(Instrumentation.class);
AgentBuilder.Listener listener = new AgentBuilder.Listener.ModuleReadEdgeCompleting(instrumentation, true, Collections.<JavaModule>emptySet());
listener.onTransformation(mock(TypeDescription.class), mock(ClassLoader.class), JavaModule.UNSUPPORTED, LOADED, mock(DynamicType.class));
}
@Test
public void testReadEdgeAddingListenerDuplexUnnamed() throws Exception {
Instrumentation instrumentation = mock(Instrumentation.class);
JavaModule source = mock(JavaModule.class), target = mock(JavaModule.class);
AgentBuilder.Listener listener = new AgentBuilder.Listener.ModuleReadEdgeCompleting(instrumentation, true, Collections.singleton(target));
listener.onTransformation(mock(TypeDescription.class), mock(ClassLoader.class), source, LOADED, mock(DynamicType.class));
verify(source).isNamed();
verifyNoMoreInteractions(source);
verifyZeroInteractions(target);
}
@Test
public void testReadEdgeAddingListenerDuplexCanRead() throws Exception {
Instrumentation instrumentation = mock(Instrumentation.class);
JavaModule source = mock(JavaModule.class), target = mock(JavaModule.class);
TypeDescription typeDescription = mock(TypeDescription.class);
PackageDescription packageDescription = mock(PackageDescription.class);
when(typeDescription.getPackage()).thenReturn(packageDescription);
when(source.isNamed()).thenReturn(true);
when(source.canRead(target)).thenReturn(true);
when(source.isOpened(packageDescription, target)).thenReturn(true);
when(target.canRead(source)).thenReturn(true);
AgentBuilder.Listener listener = new AgentBuilder.Listener.ModuleReadEdgeCompleting(instrumentation, true, Collections.singleton(target));
listener.onTransformation(typeDescription, mock(ClassLoader.class), source, LOADED, mock(DynamicType.class));
verify(source).isNamed();
verify(source).canRead(target);
verify(source).isOpened(packageDescription, target);
verifyNoMoreInteractions(source);
verify(target).canRead(source);
verifyNoMoreInteractions(target);
}
@Test
@JavaVersionRule.Enforce(9)
public void testReadEdgeAddingListenerNamedDuplexCannotRead() throws Exception {
Instrumentation instrumentation = mock(Instrumentation.class);
JavaModule source = mock(JavaModule.class), target = mock(JavaModule.class);
when(source.isNamed()).thenReturn(true);
when(source.canRead(target)).thenReturn(false);
when(target.canRead(source)).thenReturn(false);
when(Instrumentation.class.getMethod("isModifiableModule", JavaType.MODULE.load()).invoke(instrumentation, (Object) null)).thenReturn(true);
AgentBuilder.Listener listener = new AgentBuilder.Listener.ModuleReadEdgeCompleting(instrumentation, true, Collections.singleton(target));
listener.onTransformation(mock(TypeDescription.class), mock(ClassLoader.class), source, LOADED, mock(DynamicType.class));
Instrumentation.class.getMethod("redefineModule",
JavaType.MODULE.load(),
Set.class,
Map.class,
Map.class,
Set.class,
Map.class).invoke(verify(instrumentation, times(2)),
null,
Collections.singleton(null),
Collections.<String, Set<JavaModule>>emptyMap(),
Collections.<String, Set<JavaModule>>emptyMap(),
Collections.<Class<?>>emptySet(),
Collections.<Class<?>, List<Class<?>>>emptyMap());
verify(source).isNamed();
verify(source).canRead(target);
verify(source, times(3)).unwrap();
verifyNoMoreInteractions(source);
verify(target).canRead(source);
verify(target, times(3)).unwrap();
verifyNoMoreInteractions(target);
}
private static class PseudoAdapter extends AgentBuilder.Listener.Adapter {
/* empty */
}
}
| 49.987469 | 163 | 0.72008 |
3b3b9ef49054650a5acb8460ba2d1d10e09d2d7d | 14,845 | /*
* Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
* Copyright [2016-2018] EMBL-European Bioinformatics Institute
*
* 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.
*/
/*
* Copyright (C) 2004 EBI, GRL
*
* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation,
* Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.ensembl.healthcheck.testcase.variation;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Properties;
import org.ensembl.healthcheck.DatabaseRegistryEntry;
import org.ensembl.healthcheck.DatabaseType;
import org.ensembl.healthcheck.ReportManager;
import org.ensembl.healthcheck.Team;
import org.ensembl.healthcheck.testcase.SingleDatabaseTestCase;
import org.ensembl.healthcheck.util.DBUtils;
/**
* Check that the tables handling variation sets are valid and won't cause problems
*/
public class VariationSet extends SingleDatabaseTestCase {
// The maximum variation_set_id value that we can store in the set construct in the variation_feature table
private static final int MAX_VARIATION_SET_ID = 64;
/**
* Creates a new instance of VariationSetTestCase
*/
public VariationSet() {
setDescription("Checks that the variation_set tables are valid");
setTeamResponsible(Team.VARIATION);
}
// ---------------------------------------------------------------------
/**
* Store the SQL queries in a Properties object.
*/
private Properties getSQLQueries() {
// Store all the needed SQL statements in a Properties object
Properties sqlQueries = new Properties();
String query;
// Query checking that no variation set has more than one parent
query =
"SELECT DISTINCT vss1.variation_set_sub FROM variation_set_structure vss1 JOIN variation_set_structure vss2 ON (vss2.variation_set_sub = vss1.variation_set_sub AND vss2.variation_set_super != vss1.variation_set_super)";
sqlQueries.setProperty("multiParent", query);
// Query getting all parent variation sets
query = "SELECT DISTINCT vss.variation_set_super FROM variation_set_structure vss";
sqlQueries.setProperty("parentSets", query);
// Query getting the name for a variation set id
query = "SELECT vs.name FROM variation_set vs WHERE vs.variation_set_id = ? LIMIT 1";
sqlQueries.setProperty("setName", query);
// Query checking the name for a variation set id is defined
query = "SELECT count(*) FROM variation_set vs WHERE vs.name is NULL OR vs.name='NULL' ";
sqlQueries.setProperty("setCheckName", query);
// Query checking the description for a variation set id is defined
query = "SELECT count(*) FROM variation_set vs WHERE vs.description is NULL OR vs.description='NULL' ";
sqlQueries.setProperty("setCheckDescription", query);
// Query checking the short name for a variation set id exists and is defined in the attrib table
query = "SELECT count(*) FROM variation_set vs LEFT JOIN attrib a ON (vs.short_name_attrib_id = a.attrib_id) WHERE vs.variation_set_id IS NOT NULL AND a.value IS NULL";
sqlQueries.setProperty("setCheckShortName", query);
// Query getting the subsets for a parent variation set id
query = "SELECT vss.variation_set_sub FROM variation_set_structure vss WHERE vss.variation_set_super = ?";
sqlQueries.setProperty("subSet", query);
// Query getting all combinations of variation sets that contain at least one common variation. These can be checked that none
// of them have a (grand)parent-child relationship
query =
"SELECT DISTINCT vsv1.variation_set_id, vsv2.variation_set_id FROM variation_set_variation vsv1 JOIN variation_set_variation vsv2 ON (vsv2.variation_id = vsv1.variation_id AND vsv2.variation_set_id > vsv1.variation_set_id)";
sqlQueries.setProperty("setCombos", query);
// Query for checking that the primary keys of all variation sets will fit into the variation_set_id set column in
// variation_feature
query = "SELECT COUNT(*) FROM variation_set vs WHERE vs.variation_set_id > ?";
sqlQueries.setProperty("variationSetIds", query);
return sqlQueries;
}
/**
* Check that the variation set data makes sense and has a valid tree structure.
*
* @param dbre
* The database to check.
* @return true if the test passed.
*/
public boolean run(DatabaseRegistryEntry dbre) {
boolean result = true;
String msg = "";
Connection con = dbre.getConnection();
try {
// Store all the needed SQL statements in a Properties object
Properties sqlQueries = getSQLQueries();
Statement stmt = con.createStatement();
ResultSet rs;
boolean fetch;
// Prepare a statement for getting the variation set name from an id
PreparedStatement setName = con.prepareStatement(sqlQueries.getProperty("setName"));
// Prepare a statement for getting the variation subsets for an id
PreparedStatement subSet = con.prepareStatement(sqlQueries.getProperty("subSet"));
// Check that no variation set is missing the short name
int countShortNames = DBUtils.getRowCount(con,sqlQueries.getProperty("setCheckShortName"));
if (countShortNames > 0) {
result = false;
ReportManager.problem(this, con, "There are " + String.valueOf(countShortNames)
+ " variation set(s) whose short name 'short_name_attrib_id' is missing OR is not defined in 'attrib' table");
}
// Check that no variation set is missing the name
int countNames = DBUtils.getRowCount(con,sqlQueries.getProperty("setCheckName"));
if (countNames > 0) {
result = false;
ReportManager.problem(this, con, "There are " + String.valueOf(countNames)
+ " variation set(s) whose 'name' is missing");
}
// Check that no variation set is missing the description
int countDesc = DBUtils.getRowCount(con,sqlQueries.getProperty("setCheckDescription"));
if (countDesc > 0) {
result = false;
ReportManager.problem(this, con, "There are " + String.valueOf(countDesc)
+ " variation set(s) whose 'description' is missing");
}
// Check that no subset has more than one parent
if ((rs = stmt.executeQuery(sqlQueries.getProperty("multiParent"))) != null && (fetch = rs.next())) {
String sets = "";
while (fetch) {
sets += "[" + this.getVariationSetName(rs.getInt(1), setName) + "], ";
fetch = rs.next();
}
ReportManager.problem(this, con, "Variation sets " + sets.substring(0, sets.length() - 2) + " have more than one parent set");
result = false;
} else {
msg += "No variation sets have more than one super set\n";
}
// Check that no variation set is a subset of itself
boolean no_reticulation = true;
if ((rs = stmt.executeQuery(sqlQueries.getProperty("parentSets"))) != null && (fetch = rs.next())) {
while (fetch && no_reticulation) {
int parent_id = rs.getInt(1);
ArrayList path = this.getAllSubsets(parent_id, new ArrayList(), subSet);
// If the tree structure is invalid, the path will contain "(!)"
if (path.contains("(!)")) {
// Translate the dbIDs of the nodes to the corresponding names stored in the variation_set table
String nodes = "";
for (int i = 0; i < (path.size() - 1); i++) {
nodes += "[" + this.getVariationSetName(((Integer) path.get(i)).intValue(), setName) + "]->";
}
nodes = nodes.substring(0, nodes.length() - 2) + " (!)";
ReportManager.problem(this, con, "There is a variation set that is a subset of itself, " + nodes);
result = false;
no_reticulation = false;
}
fetch = rs.next();
}
}
if (no_reticulation) {
msg += "No variation set is a subset of itself\n";
}
// Check that variations that are in a subset are not also present in the superset(s)
// If there are problems with the set tree structure, we must skip this test
if (no_reticulation) {
rs = stmt.executeQuery(sqlQueries.getProperty("setCombos"));
boolean redundant = false;
while (rs != null && rs.next()) {
Integer set1 = new Integer(rs.getInt(1));
Integer set2 = new Integer(rs.getInt(2));
Hashtable tree = this.getSetHierarchy(set1, subSet);
boolean related = this.isSubSet(set2, tree);
if (!related) {
tree = this.getSetHierarchy(set2, subSet);
related = this.isSubSet(set1, tree);
Integer t = set2;
set2 = set1;
set1 = t;
}
if (related) {
ReportManager.problem(this, con, "The variation set '" + this.getVariationSetName(set1.intValue(), setName) + "' contains variations that are also present in the subset '"
+ this.getVariationSetName(set2.intValue(), setName) + "'. Preferrably, only the subset '" + this.getVariationSetName(set2.intValue(), setName) + "' should contain those variations");
result = false;
}
}
if (!redundant) {
msg += "No nested sets contain overlapping variations\n";
}
} else {
ReportManager.info(this, con, "Will not look for overlapping variations in nested subsets because of problems with the nested set structure");
}
// Prepare a statement for checking the variation_set_ids
PreparedStatement vsIds = con.prepareStatement(sqlQueries.getProperty("variationSetIds"));
vsIds.setInt(1, MAX_VARIATION_SET_ID);
rs = vsIds.executeQuery();
// Check the returned count, it should be 0
rs.next();
int count = rs.getInt(1);
if (count > 0) {
result = false;
ReportManager.problem(this, con, "There are " + String.valueOf(count)
+ " variation set(s) whose primary key 'variation_set_id' is too large to be stored in the variation_set_id column in the variation_feature table");
}
} catch (Exception e) {
ReportManager.problem(this, con, "Exception occured during healthcheck: " + e.toString());
result = false;
}
if (result) {
ReportManager.correct(this, con, msg);
}
return result;
} // run
// -----------------------------------------------------------------
private String getVariationSetName(int variationSetId, PreparedStatement pStmt) throws Exception {
pStmt.setInt(1, variationSetId);
ResultSet rs = pStmt.executeQuery();
String name = "";
if (rs.next()) {
name = rs.getString(1);
}
return name;
} // getVariationSetName
// -----------------------------------------------------------------
/**
* Recursively parses the subset tree of a variation set. If a condition is encountered where a variation set has already been
* observed higher up in the tree, the recursion will abort and the last element of the returned ArrayList will be a string "(!)".
*
* @param parent
* The database id of the variation set to get subsets for.
* @param path
* An ArrayList containing the dbIDs of nodes already visited in the tree.
* @param con
* A connection object to the database.
* @return ArrayList containing the dbIDs of visited nodes in the tree. If a reticulation in the tree has been encountered, the
* last element will be a string "(!)".
*/
private ArrayList getAllSubsets(int parent, ArrayList path, PreparedStatement pStmt) throws Exception {
boolean seen = path.contains(new Integer(parent));
path.add(new Integer(parent));
if (seen) {
path.add("(!)");
return path;
}
pStmt.setInt(1, parent);
ResultSet rs;
ArrayList subPath = new ArrayList(path);
// As long as there are sub sets, get all subsets for each of them
if (pStmt.execute()) {
rs = pStmt.getResultSet();
while (rs.next() && !seen) {
int id = rs.getInt(1);
subPath = this.getAllSubsets(id, new ArrayList(path), pStmt);
seen = subPath.contains("(!)");
}
}
if (seen) {
return new ArrayList(subPath);
}
return new ArrayList(path);
} // getAllSubsets
// -----------------------------------------------------------------
/**
* Get the Tree structure including and below the supplied set as a Hashtable. Each set is represented with its dbID as key and a
* Hashtable containing its subsets as value.
*/
private Hashtable getSetHierarchy(Integer current, PreparedStatement pStmt) throws Exception {
// Create a hashtable to hold this node's subtree
Hashtable subtree = new Hashtable();
// Get all the children of the current node's trees
pStmt.setInt(1, current.intValue());
ResultSet rs;
// As long as there are sub sets, get all subsets for each of them
if (pStmt.execute()) {
rs = pStmt.getResultSet();
while (rs.next()) {
// Add the child's subtree
Integer nextId = new Integer(rs.getInt(1));
subtree.putAll(this.getSetHierarchy(nextId, pStmt));
}
}
// Finally, add the subtree as a value to the current node
Hashtable tree = new Hashtable();
tree.put(current, subtree);
return tree;
}
/**
* Test whether a given set id is a subset in the specified hierarchy
*/
private boolean isSubSet(Integer query, Hashtable tree) throws Exception {
// Loop over the values in the current tree until it's empty or we have encountered the query set
boolean isSubSet = false;
Enumeration keys = tree.keys();
while (!isSubSet && keys.hasMoreElements()) {
Integer key = (Integer) keys.nextElement();
isSubSet = key.equals(query);
if (!isSubSet) {
isSubSet = this.isSubSet(query, (Hashtable) tree.get(key));
}
}
return isSubSet;
}
/**
* This only applies to variation databases.
*/
public void types() {
removeAppliesToType(DatabaseType.OTHERFEATURES);
removeAppliesToType(DatabaseType.CDNA);
removeAppliesToType(DatabaseType.CORE);
removeAppliesToType(DatabaseType.VEGA);
}
} // EmptyVariationTablesTestCase
| 38.161954 | 228 | 0.696127 |
618cd2bd18032c885d1833a9d1a8eba6fa02a749 | 18,756 | /*
* Copyright © 2013-2022 Metreeca srl
*
* 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.metreeca.rest;
import com.metreeca.json.Values;
import java.io.UncheckedIOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;
import java.util.function.Function;
import java.util.regex.Pattern;
import static com.metreeca.json.Values.AbsoluteIRIPattern;
import static java.util.Arrays.asList;
import static java.util.Collections.*;
/**
* HTTP request.
*/
public final class Request extends Message<Request> {
public static final String GET="GET"; // https://tools.ietf.org/html/rfc7231#section-4.3.1
public static final String HEAD="HEAD"; // https://tools.ietf.org/html/rfc7231#section-4.3.2
public static final String POST="POST"; // https://tools.ietf.org/html/rfc7231#section-4.3.3
public static final String PUT="PUT"; // https://tools.ietf.org/html/rfc7231#section-4.3.4
public static final String PATCH="PATCH"; // https://tools.ietf.org/html/rfc5789#section-2
public static final String DELETE="DELETE"; // https://tools.ietf.org/html/rfc7231#section-4.3.5
public static final String CONNECT="CONNECT"; // https://tools.ietf.org/html/rfc7231#section-4.3.6
public static final String OPTIONS="OPTIONS"; // https://tools.ietf.org/html/rfc7231#section-4.3.7
public static final String TRACE="TRACE"; // https://tools.ietf.org/html/rfc7231#section-4.3.8
private static final Pattern HTMLPattern=Pattern.compile("\\btext/x?html\\b");
private static final Pattern FilePattern=Pattern.compile("\\.\\w+$");
private static final Collection<String> Safe=new HashSet<>(asList(
GET, HEAD, OPTIONS, TRACE // https://tools.ietf.org/html/rfc7231#section-4.2.1
));
private static final Collection<String> Remote=new HashSet<>(asList(
"feed:", "ftp:", "http:", "https", "imap", "ldap:", "ldaps", "message:", "pop:", "s3:"
));
public static Map<String, List<String>> search(final String query) {
if ( query == null ) {
throw new NullPointerException("null query");
}
final Map<String, List<String>> parameters=new LinkedHashMap<>();
final int length=query.length();
for (int head=0, tail; head < length; head=tail+1) {
try {
final int equal=query.indexOf('=', head);
final int ampersand=query.indexOf('&', head);
tail=(ampersand >= 0) ? ampersand : length;
final boolean split=equal >= 0 && equal < tail;
final String label=URLDecoder.decode(query.substring(head, split ? equal : tail), "UTF-8");
final String value=URLDecoder.decode(query.substring(split ? equal+1 : tail, tail), "UTF-8");
parameters.compute(label, (name, values) -> {
final List<String> strings=(values != null) ? values : new ArrayList<>();
strings.add(value);
return strings;
});
} catch ( final UnsupportedEncodingException unexpected ) {
throw new UncheckedIOException(unexpected);
}
}
return parameters;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
private Object user;
private Set<Object> roles=emptySet();
private String method=GET;
private String base=Values.Base;
private String path="/";
private String item=base;
private String query="";
private final Map<String, List<String>> parameters=new LinkedHashMap<>();
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Retrieves the focus IRI of this request.
*
* @return the absolute IRI obtained by concatenating {@linkplain #base() base} and {@linkplain #path() path} for
* this request
*/
@Override public String item() {
return item;
}
/**
* Retrieves the originating request for this request.
*
* @return this request
*/
@Override public Request request() {
return this;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Creates a response for this request.
*
* @param mapper the mapping function used to initialize the new response; must return a non-null value
*
* @return a new lazy response for this request
*
* @throws NullPointerException if {@code mapper} is null or return a null value
*/
public Future<Response> reply(final Function<Response, Response> mapper) {
if ( mapper == null ) {
throw new NullPointerException("null mapper");
}
return consumer -> consumer.accept(new Response(this).map(mapper));
}
//// Checks ////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Checks if this request is safe.
*
* @return {@code true} if this request is <a href="https://tools.ietf.org/html/rfc7231#section-4.2.1">safe</a> ,
* that is if it's not expected to cause any state change on the origin server ; {@code false} otherwise
*/
public boolean safe() {
return Safe.contains(method);
}
/**
* Checks if this request is remote.
*
* @return {@code true} if the {@link #item() focus IRI} of this request is based on a remote dereferenceable
* <a href="https://www.iana.org/assignments/uri-schemes/uri-schemes.xhtml#uri-schemes-1">URI scheme</a>; {@code
* false} otherwise
*/
public boolean remote() {
return Remote.stream().anyMatch(item::startsWith);
}
/**
* Checks if this request targets a collection.
*
* @return {@code true} if the {@link #path()} of this request includes a trailing slash; {@code false} otherwise
*
* @see <a href="https://www.w3.org/TR/ldp-bp/#include-a-trailing-slash-in-container-uris">Linked Data Platform Best
* Practices and Guidelines - § 2.6 Include a trailing slash in container URIs</a>
*/
public boolean collection() {
return path.endsWith("/");
}
/**
* Checks if this request targets a browser route.
*
* @return {@code true} if the {@linkplain #method() method} of this request is {@link #safe() safe} and its {@code
* Accept} header includes a MIME type usually associated with an interactive browser-managed HTTP request (e.g.
* {@code text/html} and its {@link #path() path} doesn't contain a filename extension (e.g. {@code .html}); {@code
* false}, otherwise
*/
public boolean route() {
return safe() && (!FilePattern.matcher(path).find()
&& headers("Accept").stream().anyMatch(value -> HTMLPattern.matcher(value).find())
);
}
/**
* Checks if this request targets a browser asset.
*
* @return {@code true} if the {@linkplain #method() method} of this request is {@link #safe() safe} and its {@code
* Accept} header includes a MIME type usually associated with an interactive browser-managed HTTP request (e.g.
* {@code text/html} or its {@link #path() path} contains a filename extension (e.g. {@code .html}); {@code false},
* otherwise
*/
public boolean asset() {
return safe() && (FilePattern.matcher(path).find()
|| headers("Accept").stream().anyMatch(value -> HTMLPattern.matcher(value).find())
);
}
/**
* Checks if this request if performed by a user in a target set of roles.
*
* @param roles the target set if roles to be checked
*
* @return {@code true} if this request is performed by a {@linkplain #user() user} in one of the given {@code
* roles}, that is if {@code roles} and {@linkplain #roles() request roles} are not disjoint
*/
public boolean role(final Object... roles) {
return role(asList(roles));
}
/**
* Checks if this request if performed by a user in a target set of roles.
*
* @param roles the target set if roles to be checked
*
* @return {@code true} if this request is performed by a {@linkplain #user() user} in one of the given {@code
* roles}, that is if {@code roles} and {@linkplain #roles() request roles} are not disjoint
*/
public boolean role(final Collection<Object> roles) {
if ( roles == null ) {
throw new NullPointerException("null roles");
}
return !disjoint(this.roles, roles);
}
//// Actor ////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Retrieves the identifier of the request user.
*
* @return an optional identifier for the user performing this request or the empty optional if no user is
* authenticated
*/
public Optional<Object> user() { return Optional.ofNullable(user); }
/**
* Configures the identifier of the request user.
*
* @param user an identifier for the user performing this request or {@code null} if no user is authenticated
*
* @return this request
*/
public Request user(final Object user) {
this.user=user;
return this;
}
/**
* Retrieves the roles attributed to the request user.
*
* @return a set of values uniquely identifying the roles attributed to the request {@linkplain #user() user}
*/
public Set<Object> roles() { return unmodifiableSet(roles); }
/**
* Configures the roles attributed to the request user.
*
* @param roles a collection of values uniquely identifying the roles assigned to the request {@linkplain #user()
* user}
*
* @return this request
*
* @throws NullPointerException if {@code roles} is null or contains a {@code null} value
*/
public Request roles(final Object... roles) {
return roles(asList(roles));
}
/**
* Configures the roles attributed to the request user.
*
* @param roles a collection of IRIs uniquely identifying the roles assigned to the request {@linkplain #user()
* user}
*
* @return this request
*
* @throws NullPointerException if {@code roles} is null or contains a {@code null} value
*/
public Request roles(final Collection<Object> roles) {
if ( roles == null || roles.stream().anyMatch(Objects::isNull) ) {
throw new NullPointerException("null roles");
}
this.roles=new LinkedHashSet<>(roles);
return this;
}
//// Action ///////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Retrieves the HTTP method of this request.
*
* @return the HTTP method of this request; in upper case
*/
public String method() {
return method;
}
/**
* Configures the HTTP method of this request.
*
* @param method the HTTP method for this request; will be automatically converted to upper case
*
* @return this request
*
* @throws NullPointerException if {@code method} is null
*/
public Request method(final String method) {
if ( method == null ) {
throw new NullPointerException("null method");
}
this.method=method.toUpperCase(Locale.ROOT);
return this;
}
/**
* Retrieves the base IRI of this request.
*
* @return the base IRI of this request, that is the base IRI if the linked data server handling the request;
* includes a trailing slash
*/
public String base() {
return base;
}
/**
* Configures the base IRI of this request.
*
* @param base the base IRI for this request, that is the base IRI if the linked data server handling the request
*
* @return this request
*
* @throws NullPointerException if {@code base} is null
* @throws IllegalArgumentException if {@code base} is not an absolute IRI or if it doesn't include a trailing slash
*/
public Request base(final String base) {
if ( base == null ) {
throw new NullPointerException("null base");
}
if ( !AbsoluteIRIPattern.matcher(base).matches() ) {
throw new IllegalArgumentException("not an absolute base IRI");
}
if ( !base.endsWith("/") ) {
throw new IllegalArgumentException("missing trailing slash in base IRI");
}
this.base=base;
this.item=base+path.substring(1);
return this;
}
/**
* Retrieves the resource path of this request.
*
* @return the resource path of this request, that is the absolute server path of the linked data resources this
* request refers to; includes a leading slash
*/
public String path() {
return path;
}
/**
* Configures the resource path of this request.
*
* @param path the resource path of this request, that is the absolute server path of the linked data resources this
* request refers to
*
* @return this request
*
* @throws NullPointerException if {@code path} is null
* @throws IllegalArgumentException if {@code path} doesn't include a leading slash
*/
public Request path(final String path) {
if ( path == null ) {
throw new NullPointerException("null resource path");
}
if ( !path.startsWith("/") ) {
throw new IllegalArgumentException("missing leading / in resource path");
}
this.path=path;
this.item=base+path.substring(1);
return this;
}
/**
* Retrieves the query of this request.
*
* @return the query this request; doesn't include a leading question mark
*/
public String query() {
return query;
}
/**
* Configures the query of this request.
*
* @param query the query of this request; doesn't include a leading question mark
*
* @return this request
*
* @throws NullPointerException if {@code query} is null
*/
public Request query(final String query) {
if ( query == null ) {
throw new NullPointerException("null query");
}
this.query=query;
return this;
}
/**
* Retrieves the target resource of this request.
*
* @return the full URL of the target resource of this request, including {@link #base() base}, {@link #path() path}
* and optional {@link #query() query}
*/
public String resource() {
return query.isEmpty() ? item() : item()+"?"+query;
}
//// Parameters ///////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Retrieves request accepted languages.
*
* @return a list of language tags included in the {@code Accept-Language} header of this request or an empty
* list if
* no such header is included; may include a wildcard tag ({@code *})
*/
public List<String> langs() {
return header("Accept-Language")
.map(Format::langs)
.orElse(emptyList());
}
/**
* Retrieves request query parameters.
*
* @return an immutable and possibly empty map from query parameters names to collections of values
*/
public Map<String, List<String>> parameters() {
return unmodifiableMap(parameters);
}
/**
* Configures request query parameters.
*
* <p>Existing values are overwritten.</p>
*
* @param parameters a map from parameter names to lists of values
*
* @return this message
*
* @throws NullPointerException if {@code parameters} is null or contains either null keys or null values
*/
public Request parameters(final Map<String, ? extends Collection<String>> parameters) {
if ( parameters == null ) {
throw new NullPointerException("null parameters");
}
parameters.forEach((name, value) -> { // ;( parameters.containsKey()/ContainsValue() can throw NPE
if ( name == null ) {
throw new NullPointerException("null parameter name");
}
if ( value == null ) {
throw new NullPointerException("null parameter value");
}
});
this.parameters.clear();
parameters.forEach(this::parameters);
return this;
}
/**
* Retrieves request query parameter value.
*
* @param name the name of the query parameter whose value is to be retrieved
*
* @return an optional value containing the first value among those returned by {@link #parameters(String)}, if one
* is present; an empty optional otherwise
*
* @throws NullPointerException if {@code name} is null
*/
public Optional<String> parameter(final String name) {
if ( name == null ) {
throw new NullPointerException("null name");
}
return parameters(name).stream().findFirst();
}
/**
* Configures request query parameter value.
*
* <p>Existing values are overwritten.</p>
*
* @param name the name of the query parameter whose value is to be configured
* @param value the new value for {@code name}
*
* @return this message
*
* @throws NullPointerException if either {@code name} or {@code value} is null
*/
public Request parameter(final String name, final String value) {
if ( name == null ) {
throw new NullPointerException("null name");
}
if ( value == null ) {
throw new NullPointerException("null value");
}
return parameters(name, value);
}
/**
* Retrieves request query parameter values.
*
* @param name the name of the query parameter whose values are to be retrieved
*
* @return an immutable and possibly empty collection of values
*/
public List<String> parameters(final String name) {
if ( name == null ) {
throw new NullPointerException("null name");
}
return unmodifiableList(parameters.getOrDefault(name, emptyList()));
}
/**
* Configures request query parameter values.
*
* <p>Existing values are overwritten.</p>
*
* @param name the name of the query parameter whose values are to be configured
* @param values a possibly empty collection of values
*
* @return this message
*
* @throws NullPointerException if either {@code name} or {@code values} is null or if {@code values} contains a
* {@code null} value
*/
public Request parameters(final String name, final String... values) {
return parameters(name, asList(values));
}
/**
* Configures request query parameter values.
*
* <p>Existing values are overwritten.</p>
*
* @param name the name of the query parameter whose values are to be configured
* @param values a possibly empty collection of values
*
* @return this message
*
* @throws NullPointerException if either {@code name} or {@code values} is null or if {@code values} contains a
* {@code null} value
*/
public Request parameters(final String name, final Collection<String> values) {
if ( name == null ) {
throw new NullPointerException("null name");
}
if ( values == null ) {
throw new NullPointerException("null values");
}
if ( values.contains(null) ) {
throw new NullPointerException("null value");
}
if ( values.isEmpty() ) {
parameters.remove(name);
} else {
parameters.put(name, unmodifiableList(new ArrayList<>(values)));
}
return this;
}
}
| 28.591463 | 117 | 0.653071 |
eb7bd5e71feca1bca3370faa4807c2cd59fbfc93 | 2,456 | package com.hubspot.jinjava.el.ext.eager;
import com.hubspot.jinjava.el.ext.DeferredParsingException;
import com.hubspot.jinjava.el.ext.ExtendedParser;
import com.hubspot.jinjava.interpret.DeferredValueException;
import com.hubspot.jinjava.util.EagerExpressionResolver;
import de.odysseus.el.tree.Bindings;
import de.odysseus.el.tree.impl.ast.AstIdentifier;
import javax.el.ELContext;
public interface EvalResultHolder {
Object getAndClearEvalResult();
boolean hasEvalResult();
Object eval(Bindings bindings, ELContext elContext);
static String reconstructNode(
Bindings bindings,
ELContext context,
EvalResultHolder astNode,
DeferredParsingException exception,
boolean preserveIdentifier
) {
String partiallyResolvedImage;
if (
astNode instanceof AstIdentifier &&
(
preserveIdentifier ||
ExtendedParser.INTERPRETER.equals(((AstIdentifier) astNode).getName())
)
) {
astNode.getAndClearEvalResult(); // clear unused result
partiallyResolvedImage = ((AstIdentifier) astNode).getName();
} else if (astNode.hasEvalResult()) {
partiallyResolvedImage =
EagerExpressionResolver.getValueAsJinjavaStringSafe(
astNode.getAndClearEvalResult()
);
} else if (exception != null && exception.getSourceNode() == astNode) {
partiallyResolvedImage = exception.getDeferredEvalResult();
} else {
try {
partiallyResolvedImage =
EagerExpressionResolver.getValueAsJinjavaStringSafe(
astNode.eval(bindings, context)
);
} catch (DeferredParsingException e) {
partiallyResolvedImage = e.getDeferredEvalResult();
} finally {
astNode.getAndClearEvalResult();
}
}
return partiallyResolvedImage;
}
static DeferredParsingException convertToDeferredParsingException(
RuntimeException original
) {
DeferredValueException deferredValueException;
if (!(original instanceof DeferredValueException)) {
if (original.getCause() instanceof DeferredValueException) {
deferredValueException = (DeferredValueException) original.getCause();
} else {
throw original;
}
} else {
deferredValueException = (DeferredValueException) original;
}
if (deferredValueException instanceof DeferredParsingException) {
return (DeferredParsingException) deferredValueException;
}
return null;
}
}
| 32.315789 | 78 | 0.717427 |
f92ef00a6bc650982d39d6905fd3b85abe41a561 | 3,648 | /*
* ====================================================================
* Ikasan Enterprise Integration Platform
*
* Distributed under the Modified BSD License.
* Copyright notice: The copyright for this software and a full listing
* of individual contributors are as shown in the packaged copyright.txt
* file.
*
* 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 ORGANIZATION 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.
* ====================================================================
*
*/
package org.ikasan.component.factory.spring.common;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import java.lang.reflect.InvocationTargetException;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* Util class to Merge One Beans Properties into another. Used by shared properties.
*/
public class BeanMergeUtil {
public static <T> T mergeSourceIntoTargetBean(T source, T target) throws InvocationTargetException, IllegalAccessException {
BeanUtils.copyProperties(source, target, getNullPropertyNames(source));
return target;
}
public static String[] getNullPropertyNames (Object source) {
final BeanWrapper src = new BeanWrapperImpl(source);
java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();
Set<String> emptyNames = new HashSet<String>();
for(java.beans.PropertyDescriptor pd : pds) {
Object srcValue = src.getPropertyValue(pd.getName());
if (srcValue == null) emptyNames.add(pd.getName());
else if (srcValue instanceof Collection && CollectionUtils.isEmpty((Collection)srcValue)){
emptyNames.add(pd.getName());
}
else if (srcValue instanceof Map && MapUtils.isEmpty((Map)srcValue)){
emptyNames.add(pd.getName());
}
}
String[] result = new String[emptyNames.size()];
return emptyNames.toArray(result);
}
}
| 41.931034 | 128 | 0.70011 |
0f532a3037a55db7533308192a4e75ecbda5ffa4 | 123 | package learnsomejava;
class Calculator {
int performIntegerArithmetic(char operator, int value1, int value2) {
}
}
| 13.666667 | 71 | 0.747967 |
7ff7452ce5e6585b6f9e8b9cf0a057028f075f03 | 523 | package ru.job4j.tracker;
/**
* @author Evgeny Butov (mailto:but87@mail.ru)
* @version 1.0
* @since 19.08.2018
*/
public interface UserAction {
/**
* Метод возвращает ключ опции.
* @return ключ
*/
int key();
/**
* Основной метод.
* @param input объект типа Input
* @param tracker объект типа Tracker
*/
void execute(Input input, Tracker tracker);
/**
* Метод возвращает информацию о данном пункте меню.
* @return Строка меню
*/
String info();
} | 20.92 | 56 | 0.596558 |
2ead37ee3f4af71327acf01f9285512b84d26cdb | 1,048 | package user;
import org.junit.Test;
import static org.junit.Assert.*;
public class userControllerTest {
@Test
public void authenticate() {
userDb list = new userDb();
userController test = new userController();
list.insert("user1", "password1");
list.insert("user2", "password2");
list.insert("user3", "password3");
list.display();
if(test.authenticate(list, "user1", "password1") == true)
{
System.out.println("Logged In");
}
else
{
System.out.println("Access Denied");
}
if(test.authenticate(list, "user4", "password4") == true)
{
System.out.println("Logged In");
}
else
{
System.out.println("Access Denied");
}
if(test.authenticate(list, "user1", "password2") == true)
{
System.out.println("Logged In");
}
else
{
System.out.println("Access Denied");
}
}
} | 20.54902 | 65 | 0.510496 |
f4073323e0f64810f5951327c5c85da1918ff139 | 2,985 | package net.filebot.torrent;
import static java.util.Collections.*;
import static java.util.stream.Collectors.*;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;
import java.util.Map;
import com.dampcake.bencode.Bencode;
import com.dampcake.bencode.Type;
import net.filebot.vfs.FileInfo;
import net.filebot.vfs.SimpleFileInfo;
public class Torrent {
private String name;
private String encoding;
private String createdBy;
private String announce;
private String comment;
private Long creationDate;
private Long pieceLength;
private List<FileInfo> files;
private boolean singleFileTorrent;
protected Torrent() {
// used by serializer
}
public Torrent(File torrent) throws IOException {
this(decodeTorrent(torrent));
}
public Torrent(Map<?, ?> torrentMap) {
createdBy = getString(torrentMap.get("created by"));
announce = getString(torrentMap.get("announce"));
comment = getString(torrentMap.get("comment"));
creationDate = getLong(torrentMap.get("creation date"));
Map<?, ?> info = getMap(torrentMap.get("info"));
name = getString(info.get("name"));
pieceLength = getLong(info.get("piece length"));
if (info.containsKey("files")) {
// torrent contains multiple entries
singleFileTorrent = false;
files = getList(info.get("files")).stream().map(this::getMap).map(f -> {
String path = getList(f.get("path")).stream().map(Object::toString).collect(joining("/"));
long length = getLong(f.get("length"));
return new SimpleFileInfo(path, length);
}).collect(toList());
} else {
// torrent contains only a single entry
singleFileTorrent = true;
files = singletonList(new SimpleFileInfo(name, getLong(info.get("length"))));
}
}
private static Map<?, ?> decodeTorrent(File torrent) throws IOException {
byte[] bytes = Files.readAllBytes(torrent.toPath());
return new Bencode().decode(bytes, Type.DICTIONARY);
}
private String getString(Object value) {
if (value instanceof CharSequence) {
return value.toString();
}
return "";
}
private long getLong(Object value) {
if (value instanceof Number) {
return ((Number) value).longValue();
}
return -1;
}
private Map<?, ?> getMap(Object value) {
if (value instanceof Map) {
return (Map) value;
}
return emptyMap();
}
private List<?> getList(Object value) {
if (value instanceof List) {
return (List) value;
}
return emptyList();
}
public String getAnnounce() {
return announce;
}
public String getComment() {
return comment;
}
public String getCreatedBy() {
return createdBy;
}
public Long getCreationDate() {
return creationDate;
}
public String getEncoding() {
return encoding;
}
public List<FileInfo> getFiles() {
return unmodifiableList(files);
}
public String getName() {
return name;
}
public Long getPieceLength() {
return pieceLength;
}
public boolean isSingleFileTorrent() {
return singleFileTorrent;
}
}
| 22.111111 | 94 | 0.703518 |
d988d15bf6e899945b665b6e6175b56dea84d2d5 | 7,714 | /*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered.org <http://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.mod.guice;
import com.google.inject.AbstractModule;
import com.google.inject.Provider;
import com.google.inject.TypeLiteral;
import ninja.leaping.configurate.commented.CommentedConfigurationNode;
import ninja.leaping.configurate.hocon.HoconConfigurationLoader;
import ninja.leaping.configurate.loader.ConfigurationLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spongepowered.api.plugin.PluginContainer;
import org.spongepowered.api.service.config.ConfigDir;
import org.spongepowered.api.service.config.DefaultConfig;
import java.io.File;
import java.lang.annotation.Annotation;
import javax.inject.Inject;
/**
* Guice module that contains injections for a single plugin.
*/
public class SpongePluginGuiceModule extends AbstractModule {
private final PluginContainer container;
public SpongePluginGuiceModule(PluginContainer container) {
this.container = container;
}
@Override
protected void configure() {
DefaultConfig pluginConfigPrivate = new ConfigFileAnnotation(false);
DefaultConfig pluginConfigShared = new ConfigFileAnnotation(true);
ConfigDir pluginDirPrivate = new ConfigDirAnnotation(false);
bind(PluginContainer.class).toInstance(this.container);
bind(Logger.class).toInstance(LoggerFactory.getLogger(this.container.getId()));
bind(File.class).annotatedWith(pluginDirPrivate)
.toProvider(PluginConfigDirProvider.class); // plugin-private config directory (shared dir is in the global guice module)
bind(File.class).annotatedWith(pluginConfigShared).toProvider(PluginSharedConfigFileProvider.class); // shared-directory config file
bind(File.class).annotatedWith(pluginConfigPrivate).toProvider(PluginPrivateConfigFileProvider.class); // plugin-private directory config file
bind(new TypeLiteral<ConfigurationLoader<CommentedConfigurationNode>>() {
}).annotatedWith(pluginConfigShared)
.toProvider(PluginSharedHoconConfigProvider.class); // loader for shared-directory config file
bind(new TypeLiteral<ConfigurationLoader<CommentedConfigurationNode>>() {
}).annotatedWith(pluginConfigPrivate)
.toProvider(PluginPrivateHoconConfigProvider.class); // loader for plugin-private directory config file
}
public boolean isFlowerPot() {
return false;
}
// This is strange, but required for Guice and annotations with values.
private static class ConfigFileAnnotation implements DefaultConfig {
boolean shared;
ConfigFileAnnotation(boolean isShared) {
this.shared = isShared;
}
@Override
public boolean sharedRoot() {
return this.shared;
}
@Override
public Class<? extends Annotation> annotationType() {
return DefaultConfig.class;
}
// See Javadocs for java.lang.annotation.Annotation for specification of equals, hashCode, toString
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || !(o instanceof DefaultConfig)) {
return false;
}
DefaultConfig that = (DefaultConfig) o;
return sharedRoot() == that.sharedRoot();
}
@Override
public int hashCode() {
return (127 * "sharedRoot".hashCode()) ^ Boolean.valueOf(sharedRoot()).hashCode();
}
@Override
public String toString() {
return "@org.spongepowered.api.service.config.Config("
+ "sharedRoot=" + this.shared
+ ')';
}
}
private static class PluginSharedConfigFileProvider implements Provider<File> {
private final PluginContainer container;
private final File root;
@Inject
private PluginSharedConfigFileProvider(PluginContainer container, @ConfigDir(sharedRoot = true) File sharedConfigDir) {
this.container = container;
this.root = sharedConfigDir;
}
@Override
public File get() {
return new File(this.root, this.container.getId() + ".conf");
}
}
private static class PluginPrivateConfigFileProvider implements Provider<File> {
private final PluginContainer container;
private final File root;
@Inject
private PluginPrivateConfigFileProvider(PluginContainer container, @ConfigDir(sharedRoot = false) File sharedConfigDir) {
this.container = container;
this.root = sharedConfigDir;
}
@Override
public File get() {
return new File(this.root, this.container.getId() + ".conf");
}
}
private static class PluginSharedHoconConfigProvider implements Provider<ConfigurationLoader<CommentedConfigurationNode>> {
private final File configFile;
@Inject
private PluginSharedHoconConfigProvider(@DefaultConfig(sharedRoot = true) File configFile) {
this.configFile = configFile;
}
@Override
public ConfigurationLoader<CommentedConfigurationNode> get() {
return HoconConfigurationLoader.builder().setFile(this.configFile).build();
}
}
private static class PluginPrivateHoconConfigProvider implements Provider<ConfigurationLoader<CommentedConfigurationNode>> {
private final File configFile;
@Inject
private PluginPrivateHoconConfigProvider(@DefaultConfig(sharedRoot = false) File configFile) {
this.configFile = configFile;
}
@Override
public ConfigurationLoader<CommentedConfigurationNode> get() {
return HoconConfigurationLoader.builder().setFile(this.configFile).build();
}
}
private static class PluginConfigDirProvider implements Provider<File> {
private final PluginContainer container;
private final File sharedConfigDir;
@Inject
private PluginConfigDirProvider(PluginContainer container, @ConfigDir(sharedRoot = true) File sharedConfigDir) {
this.container = container;
this.sharedConfigDir = sharedConfigDir;
}
@Override
public File get() {
return new File(this.sharedConfigDir, this.container.getId() + "/");
}
}
}
| 37.2657 | 150 | 0.690303 |
1b25096de4df0ad5dbf6088e39cddfb98aa99c13 | 34,195 | /**
* Copyright (C) 2020 Jan Schäfer (jansch@users.sourceforge.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jskat.ai.newalgorithm;
import java.util.ArrayList;
import java.util.List;
import org.jskat.ai.newalgorithm.exception.IllegalMethodException;
import org.jskat.util.Card;
import org.jskat.util.CardList;
import org.jskat.util.GameType;
import org.jskat.util.Player;
import org.jskat.util.Rank;
import org.jskat.util.Suit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class AlgorithmOpponentSuit extends AbstractAlgorithmAI {
private static final Logger log = LoggerFactory.getLogger(AlgorithmOpponentSuit.class);
AlgorithmOpponentSuit(final AlgorithmAI p, final GameType pGameType) {
super(p, pGameType);
log.debug(String.format("/s is %s", myPlayer.getPlayerName(), this
.getClass().getName()));
}
@Override
protected Card startGame() {
log.debug("Suit-Opponent starts Game: "
+ knowledge.getCurrentTrick().getForeHand());
return playStartGameCard(knowledge.getOwnCards(),
knowledge.getTrickCards(), oPlayedCards, oNotOpponentCards,
oSituation, knowledge.getPlayerPosition(),
knowledge.getDeclarer());
}
@Override
protected Card playForehandCard() {
log.debug("Suit-Opponent plays Forehand-Card: "
+ knowledge.getCurrentTrick().getForeHand());
return playForehandCard(knowledge.getOwnCards(),
knowledge.getTrickCards(), oPlayedCards, oNotOpponentCards,
oSituation, knowledge.getPlayerPosition(),
knowledge.getDeclarer());
}
@Override
protected Card playMiddlehandCard() {
log.debug("Suit-Opponent plays Middlehand-Card: "
+ knowledge.getCurrentTrick().getMiddleHand());
return playMiddlehandCard(
myPlayer.getPlayableCards(knowledge.getTrickCards()),
knowledge.getTrickCards(), oPlayedCards, oNotOpponentCards,
oSituation, knowledge.getPlayerPosition(),
knowledge.getDeclarer());
}
@Override
protected Card playRearhandCard() {
log.debug("Suit-Opponent plays Rearhand-Card: "
+ knowledge.getCurrentTrick().getRearHand());
return playRearhandCard(
myPlayer.getPlayableCards(knowledge.getTrickCards()),
knowledge.getTrickCards(), oPlayedCards, oNotOpponentCards,
oSituation, knowledge.getPlayerPosition(),
knowledge.getDeclarer());
}
@Override
public CardList discardSkat(final BidEvaluator bidEvaluator) {
throw new IllegalMethodException(
"AlgorithmOpponentSuit has nothing to discard!");
}
// static methods for creating JUnit-tests and test cardplaybehavior
public static Card playStartGameCard(final CardList pCards, final CardList pTrickCards,
final CardList pPlayedCards, final CardList pNotOpponentCards,
final Situation pSituation, final Player pPlayerPosition, final Player pDeclarer) {
pCards.sort(pSituation.getGameType());
final boolean tDeclarerInMiddle = pPlayerPosition.getLeftNeighbor() == pDeclarer;
final CardList tPossibleHighCard = new CardList();
final CardList tPossibleLowCard = new CardList();
for (final Suit s : Suit.values()) {
if (s == pSituation.getTrumpSuit()
|| pCards.getSuitCount(s, false) == 0) {
continue;
}
if (pCards.get(pCards.getFirstIndexOfSuit(s, false)).getRank() == Rank.ACE) {
tPossibleHighCard.add(pCards.get(pCards.getFirstIndexOfSuit(s,
false)));
}
if ((tDeclarerInMiddle || pCards.getSuitCount(s, false) >= 3)
&& pCards.get(pCards.getLastIndexOfSuit(s, false))
.getPoints() <= 0) {
tPossibleLowCard.add(pCards.get(pCards.getLastIndexOfSuit(s,
false)));
}
}
if (!tPossibleHighCard.isEmpty()) {
return playRandomCard(tPossibleHighCard);
}
if (!tPossibleLowCard.isEmpty()) {
return playRandomCard(tPossibleLowCard);
}
return playForehandCard(pCards, pTrickCards, pPlayedCards,
pNotOpponentCards, pSituation, pPlayerPosition, pDeclarer);
}
public static Card playForehandCard(final CardList pCards, final CardList pTrickCards,
final CardList pPlayedCards, final CardList pNotOpponentCards,
final Situation pSituation, final Player pPlayerPosition, final Player pDeclarer) {
pCards.sort(pSituation.getGameType());
final boolean tDeclarerInMiddle = pPlayerPosition.getLeftNeighbor() == pDeclarer;
final CardList possibleCards = new CardList();
for (final Suit lSuit : Suit.values()) {
if (lSuit == pSituation.getTrumpSuit()
|| pCards.getSuitCount(lSuit, false) == 0) {
continue;
}
final Card possibleHighCard = pCards.get(pCards.getFirstIndexOfSuit(
lSuit, false)); // highest Card
final Card possibleLowCard = pCards.get(pCards.getLastIndexOfSuit(lSuit,
false)); // lowest Card
// Wenn nur eine Karte und diese weniger als 10 Puntke wert ist
if (possibleHighCard.equals(possibleLowCard)
&& possibleHighCard.getPoints() < 10) {
possibleCards.add(possibleHighCard);
}
// Wenn der Solo-Spieler in Mittelhand
if (tDeclarerInMiddle) {
// Wenn nur noch der Spieler selbst Karten der Farbe hat ->
// versuchen Truempfe vom Solo-Spieler ziehen
if ((Helper.getSuitCardsToBinary(pPlayedCards, lSuit) & Helper
.getSuitCardsToBinary(pCards, lSuit)) == 127) {
return possibleHighCard;
}
possibleCards.add(possibleLowCard);
} else {
if ((Helper.getSuitCardsToBinary(pPlayedCards, lSuit) & Helper
.getSuitCardsToBinary(pCards, lSuit)) == 127
&& pCards.getSuitCount(lSuit, false) <= 3) {
return possibleHighCard;
}
if (possibleLowCard.getPoints() <= 4) {
possibleCards.add(possibleLowCard);
}
}
// Wenn der Spieler die hoechste Karte der Farbe hat
// und der Solo-Spieler nicht blank ist
if (pPlayedCards.getSuitCount(lSuit, false) <= 4
&& (pPlayerPosition.getLeftNeighbor() == pDeclarer
&& !pSituation.isLeftPlayerBlankOnColor(lSuit)
|| pPlayerPosition
.getRightNeighbor() == pDeclarer
&& !pSituation.isRightPlayerBlankOnColor(lSuit))
&& Helper.isHighestSuitCard(possibleHighCard,
pSituation.getGameType(), pPlayedCards, null)) {
return possibleHighCard;
}
}
if (!possibleCards.isEmpty()) {
return playRandomCard(possibleCards);
}
return getRandomAllowedCard(pCards, null, pSituation.getGameType());
}
public static Card playMiddlehandCard(final CardList pCards,
final CardList pTrickCards, final CardList pPlayedCards,
final CardList pNotOpponentCards, final Situation pSituation,
final Player pPlayerPosition, final Player pDeclarer) {
pCards.sort(pSituation.getGameType());
final boolean tDeclarerInForhand = pPlayerPosition.getRightNeighbor() == pDeclarer;
final Card tForehandCard = pTrickCards.get(0);
final Suit tSuit = tForehandCard.getSuit();
ArrayList<Suit> tDeclarerBlankSuits = pSituation
.getLeftPlayerBlankSuits();
if (pPlayerPosition.getRightNeighbor() == pDeclarer) {
tDeclarerBlankSuits = pSituation.getRightPlayerBlankSuits();
}
final CardList possibleCards = new CardList();
// Trumpfkarte wurde gespielt
if (tForehandCard.getSuit() == pSituation.getTrumpSuit()
|| tForehandCard.getRank() == Rank.JACK) {
// Wenn Solo-Spieler in Forehand sitzt und die erste Karte des
// Tricks seine ist
if (tDeclarerInForhand) {
// Wenn der Spieler Trumpfkarten hat
if (pCards.hasTrump(pSituation.getGameType())) {
final int tTrumpCount = Helper.countJacks(pCards)
+ pCards.getSuitCount(pSituation.getTrumpSuit(),
false);
if (tTrumpCount == 1) {
return pCards.get(0);
}
// Wenn schlagbar
if (pCards.get(0).beats(pSituation.getGameType(),
tForehandCard)) {
if (pCards.contains(Card.getCard(
pSituation.getTrumpSuit(), Rank.ACE))
&& Rank.ACE.toBinaryFlag() > tForehandCard
.getRank().toBinaryFlag()) {
return Card.getCard(pSituation.getTrumpSuit(),
Rank.ACE);
} else if (pCards.contains(Card.getCard(
pSituation.getTrumpSuit(), Rank.TEN))
&& Rank.TEN.toBinaryFlag() > tForehandCard
.getRank().toBinaryFlag()) {
return Card.getCard(pSituation.getTrumpSuit(),
Rank.TEN);
}
return getLowestBeatingCard(pCards,
pSituation.getGameType(), tForehandCard);
}
return Helper.getLowestTrumpValueCard(pCards,
pSituation.getTrumpSuit(), true);
}
// Wenn kein Trumpf mehr auf der Hand
for (final Suit lSuit : Suit.values()) {
if (lSuit == pSituation.getTrumpSuit()
|| pCards.getSuitCount(lSuit, false) == 0) {
continue;
}
final Card possibleHighCard = pCards.get(pCards
.getFirstIndexOfSuit(lSuit, false)); // highest Card
final Card possibleLowCard = pCards.get(pCards
.getLastIndexOfSuit(lSuit, false)); // lowest Card
// Wenn nur eine Karte der Farbe und nicht das Ass
if (possibleHighCard == possibleLowCard
&& possibleHighCard.getRank() != Rank.ACE) {
// Wenns kein Ass oder 10 ist TODO
if (possibleHighCard.getRank() == Rank.TEN) {
if (Helper
.getSuitCardsToBinary(pPlayedCards, lSuit) >= Rank.ACE
.toBinaryFlag()) {
continue;
}
possibleCards.add(possibleHighCard);
} else {
return possibleHighCard;
}
} else if (Helper.getSuitCardsToBinary(pPlayedCards, lSuit) > 2) {
return possibleLowCard;
// Wenn genau 2 Karten
} else {
possibleCards.add(possibleLowCard);
}
}
}
// Solo-Spieler sitzt in Hinterhand
else {
// Wenn nur noch ein Trumpf
if (Helper.getTrumpCardsToBinary(pCards,
pSituation.getTrumpSuit()) == 1) {
return pCards.get(0);
}
// Wenn der Spieler Trumpfkarten hat
if (pCards.hasTrump(pSituation.getGameType())) {
// Wenn der Trumpf vom Mitspieler nicht geschlagen werden
// kann
if (Helper.isHighestTrumpCard(tForehandCard,
pSituation.getGameType(), pPlayedCards)) {
final Card tPossibleCard = Helper.getHighestValueCard(pCards,
pSituation.getTrumpSuit(), true);
// Wenn die HighValueCard des Spielers danach die
// hoechste Karte ist
if (Helper.isHighestTrumpCard(tPossibleCard,
pSituation.getGameType(), pPlayedCards)) {
return pCards
.get(pCards.getIndexOf(tPossibleCard) + 1);
}
return tPossibleCard;
}
// Wenn das gelegte Ass oder die gelegte 10 die hoechste
// Karte ist
if (tForehandCard.getRank() == Rank.ACE
&& (Helper.getTrumpCardsToBinary(pPlayedCards,
pSituation.getTrumpSuit())
& Helper
.getTrumpCardsToBinary(pCards,
pSituation.getTrumpSuit())) >= 1920 // CJ,
// SJ,
// HJ,
// DJ
|| tForehandCard.getRank() == Rank.TEN
&& (Helper.getTrumpCardsToBinary(pPlayedCards,
pSituation.getTrumpSuit())
& Helper
.getTrumpCardsToBinary(pCards,
pSituation.getTrumpSuit())) >= 1984) { // CJ,
// SJ,
// HJ,
// DJ,
// ACE
return pCards.get(pCards.getFirstIndexOfSuit(
pSituation.getTrumpSuit(), false));
}
// Wenn Trumpfkarte auf der Hand -> niedrigste spielen
if (pCards.getSuitCount(pSituation.getTrumpSuit(), false) > 0) {
return pCards.get(pCards.getLastIndexOfSuit(
pSituation.getTrumpSuit(), false));
}
// Sonst niedrigsten Buben spielen
return pCards.get(Helper.countJacks(pCards) - 1);
}
// Wenn keine Trumpfkarte in der Hand
// Wenn der Trumpf vom Mitspieler nicht geschlagen werden kann
if (Helper.isHighestTrumpCard(tForehandCard,
pSituation.getGameType(), pPlayedCards)) {
for (int i = 0; i < tDeclarerBlankSuits.size(); i++) {
final Card lCard = Helper.getHighestValueCard(pCards,
tDeclarerBlankSuits.get(i), false);
if (lCard != null && lCard.getPoints() >= 10) {
return lCard;
}
possibleCards.add(lCard);
}
if (possibleCards.size() > 0) {
return playRandomCard(possibleCards);
}
}
// Spiele zuerst niedrige Karten der blanken Farbe des
// Solo-Spielers
for (int i = 0; i < tDeclarerBlankSuits.size(); i++) {
final Card lCard = Helper.getLowestValueCard(pCards,
tDeclarerBlankSuits.get(i));
if (lCard != null) {
if (lCard.getPoints() <= 3) {
return lCard;
}
possibleCards.add(lCard);
}
}
for (final Suit s : Suit.values()) {
final Card lCard = Helper.getLowestValueCard(pCards, s);
if (lCard != null) {
if (lCard.getPoints() <= 3) {
return lCard;
}
possibleCards.add(lCard);
}
}
if (possibleCards.size() > 0) {
return playRandomCard(possibleCards);
}
}
}
// Wenn nur eine Karte der Farbe vorhanden
if (pCards.getSuitCount(tSuit, false) == 1) {
return pCards.get(pCards.getFirstIndexOfSuit(tSuit, false));
}
// Keine Trumpkarte wurde gespielt
if (tDeclarerInForhand) {
// Wenn der Spieler bedienen kann/muss
if (pCards.getSuitCount(tSuit, false) > 1) {
final Card possibleHighCard = pCards.get(pCards.getFirstIndexOfSuit(
tSuit, false)); // highest Card
final Card possibleLowCard = pCards.get(pCards.getLastIndexOfSuit(
tSuit, false)); // lowest Card
// Wenn der Solo-Spieler schlagbar ist -> schlagen
if (possibleHighCard.beats(pSituation.getGameType(),
tForehandCard)) {
// Wenn die zweithöchste Karte anschliessend unschlagbar
// ist
if (Helper.isHighestSuitCard(pCards.get(pCards
.getFirstIndexOfSuit(tSuit, false) + 1), pSituation
.getGameType(),
pNotOpponentCards, pTrickCards)) {
return possibleHighCard;
}
for (int i = pCards.getLastIndexOfSuit(tSuit, false); i >= pCards
.getFirstIndexOfSuit(tSuit, false); i--) {
if (pCards.get(i).beats(pSituation.getGameType(),
tForehandCard)) {
return pCards.get(i);
}
}
}
final int i = Helper.getSuitCardsToBinary(pNotOpponentCards, tSuit)
+ Helper.getSuitCardsToBinary(pTrickCards, tSuit);
if (Helper.getSuitCardsToBinary(pNotOpponentCards, tSuit)
+ Helper.getSuitCardsToBinary(pTrickCards, tSuit) == 127) {
return possibleHighCard;
}
return possibleLowCard;
}
// Wenn keine Karte dieser Farbe
// Wenn Trumpfkarte vorhanden
if (pCards.hasTrump(pSituation.getGameType())) {
final Card tPossibleCard = Helper.getHighestValueCard(pCards,
pSituation.getTrumpSuit(), true);
final int jackCount = Helper.countJacks(pCards);
if (tPossibleCard != null) {
// Wenn die hochwertige Karte des Spielers die hoechste
// Trumpkarte ist
if (Helper.isHighestTrumpCard(tPossibleCard,
pSituation.getGameType(), pPlayedCards)
&& pCards.get(pCards.getIndexOf(tPossibleCard) + 1)
.getSuit() == pSituation.getTrumpSuit()) {
return pCards.get(pCards.getIndexOf(tPossibleCard) + 1);
}
return tPossibleCard;
} else if (jackCount > 0) {
return pCards.get(jackCount - 1);
}
}
// TODO: Wenn vom Mitspieler schlagbar -> hochwertige Karte, sonst
// niedrige Karte spielen
// Wenn die Karte des Solo-Spielers nicht die hoechste ist
if (!Helper.isHighestSuitCard(tForehandCard,
pSituation.getGameType(), pPlayedCards, pTrickCards)
&& pPlayedCards.getSuitCount(pSituation.getTrumpSuit(),
false) < 3
|| pPlayedCards.getSuitCount(pSituation.getTrumpSuit(),
false) > 5) {
for (int i = 0; i < tDeclarerBlankSuits.size(); i++) {
final Card lCard = Helper.getHighestValueCard(pCards,
tDeclarerBlankSuits.get(i), false);
if (lCard != null && lCard.getPoints() >= 10) {
possibleCards.add(lCard);
}
}
if (possibleCards.size() > 0) {
return playRandomCard(possibleCards);
}
}
// Solo-Spielers blanke Farben abwerfen wenn <= 4 Punkte Karte
// vorhanden
for (int i = 0; i < tDeclarerBlankSuits.size(); i++) {
final Card lCard = Helper.getLowestValueCard(pCards,
tDeclarerBlankSuits.get(i));
if (lCard != null && lCard.getPoints() <= 4) {
possibleCards.add(lCard);
}
}
if (possibleCards.size() > 0) {
return playRandomCard(possibleCards);
}
}
// Forehand-Karte ist keine Trumpfkarte und Solo-Spieler sitzt in
// Hinterhand
else {
// Wenn mehr als eine Karte der Farbe habe und bedienen kann/muss
if (pCards.getSuitCount(tSuit, false) > 1) {
// Solo-Spieler ist blank auf der Farbe -> niedrigste Karte
// legen
if (!tDeclarerBlankSuits.contains(tSuit)) {
return pCards.get(pCards.getLastIndexOfSuit(tSuit, false));
}
return pCards.get(pCards.getFirstIndexOfSuit(tSuit, false));
} else if (pCards.getSuitCount(tSuit, false) == 0) {
// Wenn >= 10 Punkte im Stich und Spieler hat den hoechsten
// Trumpf in der Hand
if (tDeclarerBlankSuits.contains(pSituation.getTrumpSuit())
&& tForehandCard.getPoints() >= 10
&& pCards.get(0).getSuit() == pSituation.getTrumpSuit()
&& Helper.isHighestTrumpCard(pCards.get(0),
pSituation.getGameType(), pPlayedCards)) {
return pCards.get(0);
}
// Solo-Spieler hat wahrscheinlich noch eine Karte und A oder 10
// ist noch nicht gespielt
if (!tDeclarerBlankSuits.contains(pSituation.getTrumpSuit())
&& (!pPlayedCards.contains(Card.getCard(
pSituation.getTrumpSuit(), Rank.ACE))
|| !pPlayedCards.contains(Card.getCard(
pSituation.getTrumpSuit(), Rank.TEN))
|| tForehandCard
.getPoints() >= 10)) {
if (pCards.hasTrump(pSituation.getGameType())) {
return Helper.getHighestValueCard(pCards,
pSituation.getTrumpSuit(), true);
}
return pCards.get(Helper.countJacks(pCards) - 1);
}
}
if (tDeclarerBlankSuits.contains(pSituation.getTrumpSuit())
|| Helper.isHighestTrumpCard(pCards.get(0),
pSituation.getGameType(), pPlayedCards)) {
return pCards.get(0); // highest Card
} else {
return pCards.get(pCards.getLastIndexOfSuit(
pSituation.getTrumpSuit(), false));
}
}
return getRandomAllowedCard(pCards, tForehandCard,
pSituation.getGameType());
}
public static Card playRearhandCard(final CardList pCards, final CardList pTrickCards,
final CardList pPlayedCards, final CardList pNotOpponentCards,
final Situation pSituation, final Player pPlayerPosition, final Player pDeclarer) {
pCards.sort(pSituation.getGameType());
final Card tForehandCard = pTrickCards.get(0);
final Suit tSuit = tForehandCard.getSuit();
final Card tMiddlehandCard = pTrickCards.get(1);
CardList possibleCards = new CardList();
Card tCardToBeat = tForehandCard;
if (tMiddlehandCard.beats(pSituation.getGameType(), tCardToBeat)) {
tCardToBeat = tMiddlehandCard;
}
final Suit tCardToBeatSuit = tCardToBeat.getSuit();
ArrayList<Suit> tDeclarerBlankSuits = pSituation
.getLeftPlayerBlankSuits();
if (pPlayerPosition.getRightNeighbor() == pDeclarer) {
tDeclarerBlankSuits = pSituation.getRightPlayerBlankSuits();
}
// Wenn der Stich bislang dem Solo-Spieler gehoert
// Wenn Middlehand die hoehere ist und rechts vom Spieler sitzt der
// Solo-Spieler
// oder Forehand ist der Solo-Spieler und liegt vorne
if (tMiddlehandCard.beats(pSituation.getGameType(), tForehandCard) == (pPlayerPosition
.getRightNeighbor() == pDeclarer)) {
// Wenn Solo-Spieler in Forehand sitzt
if (tCardToBeat == tForehandCard) {
// Wenn kein Trumpf
if (!tForehandCard.isTrump(pSituation.getGameType())) {
// Wenn bedienen kann/muss
if (pCards.getSuitCount(tCardToBeatSuit, false) > 0) {
// Wenn schlagbar
if (pCards.get(
pCards.getFirstIndexOfSuit(tCardToBeatSuit,
false))
.beats(pSituation.getGameType(),
tCardToBeat)) {
return getLowestBeatingCard(pCards,
pSituation.getGameType(), tCardToBeat);
}
return pCards.get(pCards.getLastIndexOfSuit(
tCardToBeatSuit, false));
}
// Wenn genug Punkte im Stich und Trumpf vorhanden -> Punkte
// mitnehmen
if (pCards.hasTrump(pSituation.getGameType())
&& tForehandCard.getPoints()
+ tMiddlehandCard.getPoints() >= 10) {
if (pCards.hasTrump(pSituation.getGameType())) {
return Helper.getHighestValueCard(pCards,
pSituation.getTrumpSuit(), true);
}
return pCards.get(Helper.countJacks(pCards) - 1);
}
// FremdSuit-Karte abwerfen
for (final Suit lSuit : Suit.values()) {
final int lSuitCount = pCards.getSuitCount(lSuit, false);
if (lSuit == pSituation.getTrumpSuit()
|| lSuitCount == 0) {
continue;
}
final Card possibleHighCard = pCards.get(pCards
.getFirstIndexOfSuit(lSuit, false)); // highest
// Card
final Card possibleLowCard = pCards.get(pCards
.getLastIndexOfSuit(lSuit, false)); // lowest
// Card
// Wenn eine Karte der Farbe
if (lSuitCount == 1) {
// Solo-Spieler hat Farbe blank && Kartenwert < 10
if (tDeclarerBlankSuits.contains(lSuit)
&& possibleLowCard.getPoints() < 10) {
possibleCards.add(possibleLowCard);
}
// Wenn die Karte 0 Wert hat -> Farbe blank spielen
if (possibleLowCard.getPoints() == 0) {
return possibleLowCard;
}
}
// Wenn zwei Karte der Farbe
if (lSuitCount == 2) {
// Solo-Spieler hat Farbe blank && Kartenwert < 10
if (tDeclarerBlankSuits.contains(lSuit)
&& possibleLowCard.getPoints() < 10) {
possibleCards.add(possibleLowCard);
}
// Wenn niedrige Karte 7,8,9 oder Q ist und die hohe
// Karte unschlagbar ist
if (possibleLowCard.getPoints() <= 3
&& Helper.isHighestSuitCard(
possibleHighCard,
pSituation.getGameType(),
pPlayedCards, pTrickCards)) {
possibleCards.add(possibleLowCard);
}
}
if (lSuitCount > 2) {
// Wenn niedrige Karte 7,8,9 oder Q ist
if (possibleLowCard.getPoints() < 4) {
possibleCards.add(possibleLowCard);
}
}
}
if (!possibleCards.isEmpty()) {
return playRandomCard(possibleCards);
}
// mit einem niedrigen Trumpf mitnehmen
if (pCards.getSuitCount(pSituation.getTrumpSuit(), false) > 0) {
return Helper.getLowestTrumpValueCard(pCards,
pSituation.getTrumpSuit(), false);
}
}
// Wenn Trumpf
else {
// Wenn bedienen kann/muss
if (pCards.hasTrump(pSituation.getGameType())) {
// Wenn schlagbar
if (pCards.get(0).beats(pSituation.getGameType(),
tCardToBeat)) {
return getLowestBeatingCard(pCards,
pSituation.getGameType(), tCardToBeat);
}
// nicht schlagbar
return Helper.getLowestTrumpValueCard(pCards,
pSituation.getTrumpSuit(), true);
}
// FremdSuit-Karte abwerfen
for (final Suit lSuit : Suit.values()) {
final int lSuitCount = pCards.getSuitCount(lSuit, false);
if (lSuit == pSituation.getTrumpSuit()
|| lSuitCount == 0) {
continue;
}
final Card possibleHighCard = pCards.get(pCards
.getFirstIndexOfSuit(lSuit, false)); // highest
// Card
final Card possibleLowCard = pCards.get(pCards
.getLastIndexOfSuit(lSuit, false)); // lowest
// Card
// Wenn eine Karte der Farbe
if (lSuitCount == 1) {
// Solo-Spieler hat Farbe blank && Kartenwert < 10
if (tDeclarerBlankSuits.contains(lSuit)
&& possibleLowCard.getPoints() < 10) {
possibleCards.add(possibleLowCard);
}
// Wenn die Karte 0 Wert hat -> Farbe blank spielen
if (possibleLowCard.getPoints() == 0) {
return possibleLowCard;
}
}
// Wenn zwei Karte der Farbe
if (lSuitCount == 2) {
// Solo-Spieler hat Farbe blank && Kartenwert < 10
if (tDeclarerBlankSuits.contains(lSuit)
&& possibleLowCard.getPoints() < 10) {
possibleCards.add(possibleLowCard);
}
// Wenn niedrige Karte 7,8,9 oder Q ist und die hohe
// Karte unschlagbar ist
if (possibleLowCard.getPoints() <= 3
&& Helper.isHighestSuitCard(
possibleHighCard,
pSituation.getGameType(),
pPlayedCards, pTrickCards)) {
possibleCards.add(possibleLowCard);
}
}
if (lSuitCount > 2) {
// Wenn niedrige Karte 7,8,9 oder Q ist
if (possibleLowCard.getPoints() < 4) {
possibleCards.add(possibleLowCard);
}
}
}
if (!possibleCards.isEmpty()) {
return playRandomCard(possibleCards);
}
}
}
// Solo-Spieler ist in Mittelhand und bislang gehört ihm der
// Stich
// Wenn Vorhand schon eine Trumpfkarte ist
if (tForehandCard.isTrump(pSituation.getGameType())) {
// Wenn der Spieler noch einen Trumpf auf der Hand hat
if (pCards.hasTrump(pSituation.getGameType())) {
// niedrigen Trumpf
if (pCards.get(0).beats(pSituation.getGameType(),
tCardToBeat)) {
return getLowestBeatingCard(pCards,
pSituation.getGameType(), tCardToBeat);
}
return getLowValueTrumpCard(pCards,
pSituation.getTrumpSuit());
}
// Kein Trumpf mehr auf der Hand
possibleCards = getPossibleMaxValueCards(pCards, 0,
pSituation.getTrumpSuit());
if (!possibleCards.isEmpty()) {
return playRandomCard(possibleCards);
}
possibleCards = getPossibleMaxValueCards(pCards, 3,
pSituation.getTrumpSuit());
if (!possibleCards.isEmpty()) {
return playRandomCard(possibleCards);
}
possibleCards = getPossibleMaxValueCards(pCards, 4,
pSituation.getTrumpSuit());
if (!possibleCards.isEmpty()) {
return playRandomCard(possibleCards);
}
}
// Wenn Vorhand eine andere Farbe ist
// UND Solo-Spieler sticht mit Trumpf
else if (!tForehandCard.isTrump(pSituation.getGameType())
&& tMiddlehandCard.isTrump(pSituation.getGameType())) {
if (pCards.hasSuit(pSituation.getGameType(), tSuit)) {
return Helper.getLowestValueCard(pCards, tSuit);
}
}
// Wenn Solo-Spieler mit selber Farbe den Stich haelt
else {
// Wenn der Spieler eine Karte der Farbe hat
if (pCards.hasSuit(pSituation.getGameType(), tSuit)) {
final Card firstCard = pCards.get(pCards.getFirstIndexOfSuit(
tSuit, false));
final Card secondCard = pCards.get(pCards.getFirstIndexOfSuit(
tSuit, false));
// Wenn mit zweiter Karte schlagbar
if (secondCard.beats(pSituation.getGameType(), tCardToBeat)) {
// Wenn es moeglich ist, dass eine Karte dazwischen beim
// Solo-Spieler ist
final List<Rank> ranks = Rank.getRankList();
for (int i = ranks.indexOf(firstCard.getRank()) + 1; i < ranks
.indexOf(secondCard.getRank()); i++) {
if (!pNotOpponentCards.contains(Card.getCard(
firstCard.getSuit(), ranks.get(i)))) {
return secondCard;
}
}
return firstCard;
}
if (firstCard.beats(pSituation.getGameType(), tCardToBeat)) {
return firstCard;
}
return Helper.getLowestValueCard(pCards, tSuit);
} else {
// Wenn mehr als 10 Punkte im Stich und noch Trumpf auf der
// Hand
if (tForehandCard.getPoints() + tMiddlehandCard.getPoints() >= 8
&& pCards.hasTrump(pSituation.getGameType())) {
return Helper.getHighestValueCard(pCards,
pSituation.getTrumpSuit(), true);
}
// Lusche abwerfen
possibleCards = getPossibleMaxValueCards(pCards, 0,
pSituation.getTrumpSuit());
if (!possibleCards.isEmpty()) {
return playRandomCard(possibleCards);
}
possibleCards = getPossibleMaxValueCards(pCards, 3,
pSituation.getTrumpSuit());
if (!possibleCards.isEmpty()) {
return playRandomCard(possibleCards);
}
possibleCards = getPossibleMaxValueCards(pCards, 4,
pSituation.getTrumpSuit());
if (!possibleCards.isEmpty()) {
return playRandomCard(possibleCards);
}
}
}
}
// Wenn Trumpf bedient werden muss
if (tSuit == pSituation.getTrumpSuit()
|| tForehandCard.getRank() == Rank.JACK) {
if (pCards.hasTrump(pSituation.getGameType())) {
return Helper.getHighestValueCard(pCards,
pSituation.getTrumpSuit(), true);
}
if (Helper.countJacks(pCards) > 0) {
return pCards.get(Helper.countJacks(pCards) - 1);
}
}
// Wenn bedienen kann/muss
final int tSuitCount = pCards.getSuitCount(tSuit, false);
if (tSuitCount == 1) {
// Karte spielen
return pCards.get(pCards.getFirstIndexOfSuit(tSuit, false));
} else if (tSuitCount == 2) {
final Card possibleHighCard = pCards.get(pCards.getFirstIndexOfSuit(
tSuit, false)); // highest Card
final Card possibleLowCard = pCards.get(pCards.getLastIndexOfSuit(tSuit,
false)); // lowest Card
// Spieler spielt die hoechste Karte, wenn:
// - hoechste Karte hat und es sind nur noch 3 Karten im Spiel
// - pDeclarer in Mittelhand und hat die Farbe schon blank
// - pDeclarer in Forhand und hat die Farbe schon blank
if (Helper.isHighestSuitCard(possibleHighCard,
pSituation.getGameType(), pPlayedCards, pTrickCards)
&& (pNotOpponentCards.getSuitCount(tSuit, false) > 4 || possibleHighCard
.getRank().toBinaryFlag() >> 1 == possibleLowCard
.getRank().toBinaryFlag())
|| pDeclarer == Player.MIDDLEHAND
&& pSituation.isRightPlayerBlankOnColor(tSuit)
|| pDeclarer == Player.FOREHAND
&& pSituation.isLeftPlayerBlankOnColor(tSuit)) {
return possibleHighCard;
}
possibleCards.add(possibleLowCard);
} else if (tSuitCount > 2) {
final Card possibleHighCard = pCards.get(pCards.getFirstIndexOfSuit(
tSuit, false)); // highest Card
final Card possibleLowCard = pCards.get(pCards.getLastIndexOfSuit(tSuit,
false)); // lowest Card
if (Helper.isHighestSuitCard(possibleHighCard,
pSituation.getGameType(), pPlayedCards, pTrickCards)
&& possibleHighCard.getRank().toBinaryFlag() >> 1 == pCards
.get(pCards.getFirstIndexOfSuit(tSuit, false) + 1)
.getRank().toBinaryFlag()
|| pNotOpponentCards.getSuitCount(tSuit, false) > 4) {
return possibleHighCard;
}
possibleCards.add(pCards.get(pCards.getFirstIndexOfSuit(tSuit,
false) + 1));
} else if (tSuitCount == 0) {
for (final Suit lSuit : Suit.values()) {
final int lSuitCount = pCards.getSuitCount(lSuit, false);
if (lSuit == pSituation.getTrumpSuit() || lSuitCount == 0) {
continue;
}
final Card possibleHighCard = pCards.get(pCards.getFirstIndexOfSuit(
lSuit, false)); // highest Card
final Card possibleLowCard = pCards.get(pCards.getLastIndexOfSuit(
lSuit, false)); // lowest Card
// Wenn nur eine Karte der Farbe und diese Karte ist nicht die
// hoechste Karte
if (lSuitCount == 1) {
if (!Helper
.isHighestSuitCard(possibleHighCard,
pSituation.getGameType(), pPlayedCards,
pTrickCards)) {
return possibleHighCard;
}
} else if (lSuitCount == 2) {
// Wenn die hoehere Karte die hoechste ist
if (Helper
.isHighestSuitCard(possibleHighCard,
pSituation.getGameType(), pPlayedCards,
pTrickCards)) {
final CardList after = new CardList(pPlayedCards);
after.add(possibleHighCard);
// Wenn die niedrigere Karte die Hoechste nach der
// Hoechsten ist --> Hoechste spielen, sonst die
// niedrige spielen
if (possibleHighCard.getRank().toBinaryFlag() >> 1 == possibleLowCard
.getRank().toBinaryFlag()) {
return possibleHighCard;
}
}
if (possibleLowCard.getPoints() > 3) {
return possibleLowCard;
}
possibleCards.add(possibleLowCard);
}
// Mehr Karten als 2 von der Farbe
else {
// Wenn die hoehere Karte die hoechste ist
if (Helper
.isHighestSuitCard(possibleHighCard,
pSituation.getGameType(), pPlayedCards,
pTrickCards)) {
final CardList after = new CardList(pPlayedCards);
after.add(possibleHighCard);
// Wenn die niedrigere Karte die Hoechste nach der
// Hoechsten ist --> Hoechste spielen, sonst die
// niedrige spielen
if (possibleHighCard.getRank().toBinaryFlag() >> 1 == pCards
.get(pCards.getFirstIndexOfSuit(lSuit, false) + 1)
.getRank().toBinaryFlag()) {
return possibleHighCard;
}
}
possibleCards.add(possibleHighCard);
}
}
}
if (!possibleCards.isEmpty()) {
return playRandomCard(possibleCards);
}
return getRandomAllowedCard(pCards, tForehandCard,
pSituation.getGameType());
}
protected static CardList getPossibleMaxValueCards(final CardList pCards,
final int pMaxCardValue, final Suit pTrumpSuit) {
final CardList possibleCards = new CardList();
for (final Suit lSuit : Suit.values()) {
if (lSuit == pTrumpSuit) {
continue;
}
final int suitCount = pCards.getSuitCount(lSuit, false);
final Card possibleHighCard = pCards.get(pCards.getFirstIndexOfSuit(
lSuit, false));
final Card possibleLowCard = pCards.get(pCards.getLastIndexOfSuit(lSuit,
false));
if (suitCount > 0 && possibleHighCard == possibleLowCard
&& possibleLowCard.getPoints() <= pMaxCardValue) {
possibleCards.add(possibleLowCard);
} else if (suitCount > 2
&& possibleLowCard.getPoints() <= pMaxCardValue) {
possibleCards.add(possibleLowCard);
}
}
return possibleCards;
}
} | 35.252577 | 88 | 0.668256 |
93c8243549f957ba9077c98ff6bec7c37bfd55c4 | 3,462 | package com.wiley.fordummies.androidsdk.tictactoe;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteStatement;
import com.wiley.fordummies.androidsdk.tictactoe.AccountDbSchema.AccountsTable;
import java.util.ArrayList;
import java.util.List;
/**
* Singleton class for user Accounts.
*
* Created by adamcchampion on 2017/08/04.
*/
public class AccountSingleton {
private static AccountSingleton sAccount;
private SQLiteDatabase mDatabase;
private static final String INSERT_STMT = "INSERT INTO " + AccountsTable.NAME + " (name, password) VALUES (?, ?)" ;
public static AccountSingleton get(Context context) {
if (sAccount == null) {
sAccount = new AccountSingleton(context);
}
return sAccount;
}
private AccountSingleton(Context context) {
AccountDbHelper dbHelper = new AccountDbHelper(context.getApplicationContext());
mDatabase = dbHelper.getWritableDatabase();
}
private static ContentValues getContentValues(Account account) {
ContentValues values = new ContentValues();
values.put(AccountsTable.Cols.NAME, account.getName());
values.put(AccountsTable.Cols.PASSWORD, account.getPassword());
return values;
}
/**
* Add a new user Account to the database. This DB logic uses code from Jake Wharton:
* http://jakewharton.com/kotlin-is-here/ (slide 61). It's much easier in Kotlin!
*
* @param account Account object
*/
void addAccount(Account account) {
ContentValues contentValues = getContentValues(account);
mDatabase.beginTransaction();
try {
SQLiteStatement statement = mDatabase.compileStatement(INSERT_STMT);
statement.bindString(1, contentValues.getAsString(AccountsTable.Cols.NAME));
statement.bindString(2, contentValues.getAsString(AccountsTable.Cols.PASSWORD));
statement.executeInsert();
mDatabase.setTransactionSuccessful();
} finally {
mDatabase.endTransaction();
}
}
/**
* Delete all user accounts from the database. This DB logic uses code from Jake Wharton:
* http://jakewharton.com/kotlin-is-here/ (slide 61). It's much easier in Kotlin!
*/
public void deleteAllAccounts() {
mDatabase.beginTransaction();
try {
mDatabase.delete(AccountsTable.NAME, null, null);
mDatabase.setTransactionSuccessful();
} finally {
mDatabase.endTransaction();
}
}
private AccountCursorWrapper queryAccounts() {
Cursor cursor = mDatabase.query(
AccountsTable.NAME,
null, // columns; null selects all columns
null,
null,
null, // GROUP BY
null, // HAVING
null // ORDER BY
);
return new AccountCursorWrapper(cursor);
}
List<Account> getAccounts() {
List<Account> accountList = new ArrayList<>();
try (AccountCursorWrapper cursor = queryAccounts()) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
accountList.add(cursor.getAccount());
cursor.moveToNext();
}
}
return accountList;
}
}
| 31.472727 | 119 | 0.640381 |
ceaae5905d5c17b87e2ba74c31fafe2cec5cf37b | 1,262 | package com.ss.editor.ui.component.asset.tree.context.menu.action;
import com.ss.editor.Messages;
import com.ss.editor.ui.Icons;
import com.ss.editor.ui.component.asset.tree.resource.ResourceElement;
import com.ss.editor.ui.component.creator.FileCreatorDescription;
import com.ss.editor.ui.component.creator.FileCreatorRegistry;
import javafx.collections.ObservableList;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuItem;
import javafx.scene.image.ImageView;
import org.jetbrains.annotations.NotNull;
import com.ss.rlib.common.util.array.Array;
/**
* The action to create a new file.
*
* @author JavaSaBr
*/
public class NewFileAction extends Menu {
@NotNull
private static final FileCreatorRegistry CREATOR_REGISTRY = FileCreatorRegistry.getInstance();
public NewFileAction(@NotNull final ResourceElement element) {
setText(Messages.ASSET_COMPONENT_RESOURCE_TREE_CONTEXT_MENU_NEW_FILE);
setGraphic(new ImageView(Icons.NEW_FILE_16));
final ObservableList<MenuItem> items = getItems();
final Array<FileCreatorDescription> descriptions = CREATOR_REGISTRY.getDescriptions();
descriptions.forEach(description -> items.add(new NewFileByCreatorAction(element, description)));
}
}
| 35.055556 | 105 | 0.785261 |
eda48a722bbdebf12a7b5dca52d50644b9614942 | 2,149 | /*
*
* Copyright (c) 2006-2020, Speedment, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); You may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.speedment.common.codegen.internal.model;
import com.speedment.common.codegen.model.Class;
import com.speedment.common.codegen.model.JavadocTag;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.NoSuchElementException;
import static org.junit.jupiter.api.Assertions.*;
final class JavadocTagImplTest extends AbstractTest<JavadocTag> {
private final static String NAME = "A";
public JavadocTagImplTest() {
super(() -> new JavadocTagImpl(NAME),
a -> a.imports(List.class),
a -> a.setText("V"),
a -> a.setValue("V"),
a -> a.imports(Integer.class),
a -> a.setText("V"),
a -> a.setName("B")
);
}
@Test
void constructor() {
final String text = "T";
final JavadocTag tag = new JavadocTagImpl(NAME, text);
assertEquals(text, tag.getText().orElseThrow(NoSuchElementException::new));
}
@Test
void constructor2() {
final String text = "T";
final String value = "V";
final JavadocTag tag = new JavadocTagImpl(NAME, value, text);
assertEquals(value, tag.getValue().orElseThrow(NoSuchElementException::new));
assertEquals(text, tag.getText().orElseThrow(NoSuchElementException::new));
}
@Test
void imports() {
assertTrue(instance().getImports().isEmpty());
}
@Test
void getValue() {
assertFalse(instance().getValue().isPresent());
}
} | 31.144928 | 85 | 0.652396 |
ba9045896cc58f9ce0dc6fce90998ae81b244c1a | 240 | package lecho.lib.hellocharts.listener;
import lecho.lib.hellocharts.model.SliceValue;
public interface PieChartOnValueSelectListener extends OnValueDeselectListener {
public void onValueSelected(int arcIndex, SliceValue value);
}
| 21.818182 | 80 | 0.829167 |
efa72c736743851614df98096ca7b624f022cd98 | 6,610 | /*
* Copyright 2014 Capptain
*
* Licensed under the CAPPTAIN SDK LICENSE (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://app.capptain.com/#tos
*
* This file is supplied "as-is." You bear the risk of using it.
* Capptain gives no express or implied warranties, guarantees or conditions.
* You may have additional consumer rights under your local laws which this agreement cannot change.
* To the extent permitted under your local laws, Capptain excludes the implied warranties of merchantability,
* fitness for a particular purpose and non-infringement.
*/
package com.ubikod.capptain.android.sdk.reach.activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import com.ubikod.capptain.android.sdk.activity.CapptainActivity;
import com.ubikod.capptain.android.sdk.reach.CapptainReachAgent;
import com.ubikod.capptain.android.sdk.reach.CapptainReachInteractiveContent;
import com.ubikod.capptain.utils.ResourcesUtils;
/**
* Base class for all activities displaying Reach content.
*/
public abstract class CapptainContentActivity<T extends CapptainReachInteractiveContent> extends
CapptainActivity
{
/** Content of this activity */
protected T mContent;
/** Action button */
protected TextView mActionButton;
@Override
protected void onCreate(Bundle savedInstanceState)
{
/* No title section on the top */
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
/* Get content */
mContent = CapptainReachAgent.getInstance(this).getContent(getIntent());
if (mContent == null)
{
/* If problem with content, exit */
finish();
return;
}
/* Inflate layout */
setContentView(getLayoutId(getLayoutName()));
/* Set title */
TextView titleView = getView("title");
String title = mContent.getTitle();
if (title != null)
titleView.setText(title);
else
titleView.setVisibility(View.GONE);
/* Set body */
setBody(mContent.getBody(), getView("body"));
/* Action button */
mActionButton = getView("action");
String actionLabel = mContent.getActionLabel();
if (actionLabel != null)
{
mActionButton.setText(actionLabel);
mActionButton.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
/* Action the content */
action();
}
});
}
/* No action label means no action button */
else
mActionButton.setVisibility(View.GONE);
/* Exit button */
Button exitButton = getView("exit");
String exitLabel = mContent.getExitLabel();
if (exitLabel != null)
{
exitButton.setText(exitLabel);
exitButton.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
/* Exit the content */
exit();
}
});
}
/* No exit label means no exit button */
else
exitButton.setVisibility(View.GONE);
/* Hide spacers if only one button is visible (or none) */
ViewGroup layout = getView("capptain_button_bar");
boolean hideSpacer = actionLabel == null || exitLabel == null;
for (int i = 0; i < layout.getChildCount(); i++)
{
View view = layout.getChildAt(i);
if ("spacer".equals(view.getTag()))
if (hideSpacer)
view.setVisibility(View.VISIBLE);
else
view.setVisibility(View.GONE);
}
/* Hide button bar if both action and exit buttons are hidden */
if (actionLabel == null && exitLabel == null)
layout.setVisibility(View.GONE);
}
@Override
protected void onResume()
{
/* Mark the content displayed */
mContent.displayContent(this);
super.onResume();
}
@Override
protected void onPause()
{
if (isFinishing() && mContent != null)
{
/*
* Exit content on exit, this is has no effect if another process method has already been
* called so we don't have to check anything here.
*/
mContent.exitContent(this);
}
super.onPause();
}
@Override
protected void onUserLeaveHint()
{
finish();
}
/**
* Render the body of the content into the specified view.
* @param body content body.
* @param view body view.
*/
protected void setBody(String body, View view)
{
TextView textView = (TextView) view;
textView.setText(body);
}
/**
* Get resource identifier.
* @param name resource name.
* @param defType resource type like "layout" or "id".
* @return resource identifier or 0 if not found.
*/
protected int getId(String name, String defType)
{
return ResourcesUtils.getId(this, name, defType);
}
/**
* Get layout identifier by its resource name.
* @param name layout resource name.
* @return layout identifier or 0 if not found.
*/
protected int getLayoutId(String name)
{
return getId(name, "layout");
}
/**
* Get identifier by its resource name.
* @param name identifier resource name.
* @return identifier or 0 if not found.
*/
protected int getId(String name)
{
return getId(name, "id");
}
/**
* Get a view by its resource name.
* @param name view identifier resource name.
* @return view or 0 if not found.
*/
@SuppressWarnings("unchecked")
protected <V extends View> V getView(String name)
{
return (V) findViewById(getId(name));
}
/**
* Get layout resource name corresponding to this activity.
* @return layout resource name corresponding to this activity.
*/
protected abstract String getLayoutName();
/** Execute the action if any of the content, report it and finish the activity */
protected void action()
{
/* Delegate action */
onAction();
/* And quit */
finish();
}
/** Exit the content and report it */
protected void exit()
{
/* Report exit */
mContent.exitContent(getApplicationContext());
/* And quit */
finish();
}
/**
* Called when the action button is clicked.
*/
protected abstract void onAction();
}
| 26.869919 | 111 | 0.63298 |
81666af7e54e0d44fd331c44f7613b5b3eae2d0f | 3,666 | package org.bouncycastle.jcajce.provider.symmetric;
import java.security.AlgorithmParameters;
import java.security.InvalidAlgorithmParameterException;
import java.security.SecureRandom;
import java.security.spec.AlgorithmParameterSpec;
import javax.crypto.spec.IvParameterSpec;
import org.bouncycastle.crypto.BlockCipher;
import org.bouncycastle.crypto.CipherKeyGenerator;
import org.bouncycastle.crypto.engines.Shacal2Engine;
import org.bouncycastle.crypto.modes.CBCBlockCipher;
import org.bouncycastle.jcajce.provider.config.ConfigurableProvider;
import org.bouncycastle.jcajce.provider.symmetric.util.BaseAlgorithmParameterGenerator;
import org.bouncycastle.jcajce.provider.symmetric.util.BaseBlockCipher;
import org.bouncycastle.jcajce.provider.symmetric.util.BaseKeyGenerator;
import org.bouncycastle.jcajce.provider.symmetric.util.BlockCipherProvider;
import org.bouncycastle.jcajce.provider.symmetric.util.IvAlgorithmParameters;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
public final class Shacal2
{
private Shacal2()
{
}
public static class ECB
extends BaseBlockCipher
{
public ECB()
{
super(new BlockCipherProvider()
{
public BlockCipher get()
{
return new Shacal2Engine();
}
});
}
}
public static class CBC
extends BaseBlockCipher
{
public CBC()
{
super(new CBCBlockCipher(new Shacal2Engine()), 256);//block size
}
}
public static class KeyGen
extends BaseKeyGenerator
{
public KeyGen()
{
super("Shacal2", 512, new CipherKeyGenerator());//key size
}
}
public static class AlgParamGen
extends BaseAlgorithmParameterGenerator
{
protected void engineInit(
AlgorithmParameterSpec genParamSpec,
SecureRandom random)
throws InvalidAlgorithmParameterException
{
throw new InvalidAlgorithmParameterException("No supported AlgorithmParameterSpec for Shacal2 parameter generation.");
}
protected AlgorithmParameters engineGenerateParameters()
{
byte[] iv = new byte[32];// block size 256
if (random == null)
{
random = new SecureRandom();
}
random.nextBytes(iv);
AlgorithmParameters params;
try
{
params = AlgorithmParameters.getInstance("Shacal2", BouncyCastleProvider.PROVIDER_NAME);
params.init(new IvParameterSpec(iv));
}
catch (Exception e)
{
throw new RuntimeException(e.getMessage());
}
return params;
}
}
public static class AlgParams
extends IvAlgorithmParameters
{
protected String engineToString()
{
return "Shacal2 IV";
}
}
public static class Mappings
extends SymmetricAlgorithmProvider
{
private static final String PREFIX = Shacal2.class.getName();
public Mappings()
{
}
public void configure(ConfigurableProvider provider)
{
provider.addAlgorithm("Cipher.Shacal2", PREFIX + "$ECB");
provider.addAlgorithm("KeyGenerator.Shacal2", PREFIX + "$KeyGen");
provider.addAlgorithm("AlgorithmParameterGenerator.Shacal2", PREFIX + "$AlgParamGen");
provider.addAlgorithm("AlgorithmParameters.Shacal2", PREFIX + "$AlgParams");
}
}
}
| 29.328 | 130 | 0.636934 |
d7f2efb153b917a8726e09dfbebb40ab19ece63b | 1,431 | package com.kingsunsoft.sdk.login.net;
import com.kingsunsoft.sdk.login.net.request.ChangePwdReq;
import com.kingsunsoft.sdk.login.net.request.GetProductListReq;
import com.kingsunsoft.sdk.login.net.request.GetVerifyCodeReq;
import com.kingsunsoft.sdk.login.net.request.LoginReq;
import com.kingsunsoft.sdk.login.net.request.PayOrderReq;
import com.kingsunsoft.sdk.login.net.request.RegisterReq;
import com.kingsunsoft.sdk.login.net.request.ResetPwdReq;
import com.kingsunsoft.sdk.login.net.request.UpdateUserInfoReq;
import com.kingsunsoft.sdk.mod.Request;
import com.kingsunsoft.sdk.mod.Response;
import io.reactivex.Maybe;
import retrofit2.http.Body;
import retrofit2.http.POST;
/**
* Created by hu.yang on 2017/5/15.
*/
public interface Api {
@POST("/")
Maybe<Response> loginReq(@Body LoginReq req);
@POST("/")
Maybe<Response> registerReq(@Body RegisterReq req);
@POST("/")
Maybe<Response> getVerifyCodeReq(@Body GetVerifyCodeReq req);
@POST("/")
Maybe<Response> changePwdReq(@Body ChangePwdReq req);
@POST("/")
Maybe<Response> resetPwdReq(@Body ResetPwdReq req);
@POST("/")
Maybe<Response> updateUserInfoReq(@Body UpdateUserInfoReq req);
@POST("/")
Maybe<Response> getProductList(@Body GetProductListReq req);
@POST("/")
Maybe<Response> payOrderRequest(@Body PayOrderReq req);
@POST("/")
Maybe<Response> businessReq(@Body Request req);
}
| 27.519231 | 67 | 0.738644 |
9b6bedef8b22059aa2b8b3bbed906f5e6c1736c9 | 592 | package kr.co.popone.fitts.feature.identification.view;
import kotlin.Unit;
import kotlin.jvm.functions.Function0;
import kotlin.jvm.internal.Lambda;
final class IdentificationActivity$onBackPressed$1 extends Lambda implements Function0<Unit> {
final /* synthetic */ IdentificationActivity this$0;
IdentificationActivity$onBackPressed$1(IdentificationActivity identificationActivity) {
this.this$0 = identificationActivity;
super(0);
}
public final void invoke() {
this.this$0.setResult(0);
this.this$0.finish();
}
}
| 29.6 | 95 | 0.709459 |
2bb782b7f88508bea3b1c4b6a2af729fc588e0d5 | 1,667 | package com.example.roberto.hilda_app;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.ButtonBarLayout;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
Button btnClick;
Button btnReset;
TextView txtCount;
int intCountValue;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Connecting variables with the layout
btnClick = (Button)findViewById(R.id.buttonClick);
btnReset = (Button)findViewById(R.id.buttonReset);
txtCount = (TextView)findViewById(R.id.textViewCount);
btnClick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String countValue = txtCount.getText().toString();
intCountValue = Integer.parseInt(countValue);
intCountValue ++;
txtCount.setText(String.valueOf(intCountValue));
}
});
btnReset.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
intCountValue = 0;
txtCount.setText(String.valueOf(intCountValue));
}
});
}
// Button for navegation
public void gotoNewClient(View view){
Intent NextPage = new Intent(MainActivity.this, Nuevo_Cliente.class);
startActivity(NextPage);
}
}
| 27.327869 | 77 | 0.653269 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.