repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
klimesf/a4m36jee-project | src/test/java/cz/cvut/fel/a4m36jee/airlines/dao/ReservationDaoTest.java | 5634 | package cz.cvut.fel.a4m36jee.airlines.dao;
import cz.cvut.fel.a4m36jee.airlines.Fixtures;
import cz.cvut.fel.a4m36jee.airlines.TestUtils;
import cz.cvut.fel.a4m36jee.airlines.enums.UserRole;
import cz.cvut.fel.a4m36jee.airlines.event.ReservationCreated;
import cz.cvut.fel.a4m36jee.airlines.exception.SeatAlreadyReservedException;
import cz.cvut.fel.a4m36jee.airlines.model.Destination;
import cz.cvut.fel.a4m36jee.airlines.model.Reservation;
import cz.cvut.fel.a4m36jee.airlines.model.validation.Longitude;
import cz.cvut.fel.a4m36jee.airlines.rest.resource.DestinationResource;
import cz.cvut.fel.a4m36jee.airlines.service.DestinationServiceImpl;
import cz.cvut.fel.a4m36jee.airlines.util.Resource;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.arquillian.transaction.api.annotation.TransactionMode;
import org.jboss.arquillian.transaction.api.annotation.Transactional;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import javax.inject.Inject;
import java.util.Date;
/**
* Tests for DAO.
*
* @author moravja8
*/
@RunWith(Arquillian.class)
public class ReservationDaoTest {
@Deployment
public static Archive<?> createDeployment() {
return ShrinkWrap.create(WebArchive.class)
.addPackage(Destination.class.getPackage())
.addPackage(DestinationDAO.class.getPackage())
.addPackage(DestinationServiceImpl.class.getPackage())
.addPackage(ReservationCreated.class.getPackage())
.addPackage(DestinationResource.class.getPackage())
.addPackage(Resource.class.getPackage())
.addPackage(SeatAlreadyReservedException.class.getPackage())
.addPackage(UserRole.class.getPackage())
.addPackage(Fixtures.class.getPackage())
.addPackage(Longitude.class.getPackage())
.addAsResource("META-INF/test-persistence.xml", "META-INF/persistence.xml")
.addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml")
.addAsWebInfResource(EmptyAsset.INSTANCE, "import.sql")
.addAsWebInfResource("datasource.xml");
}
@Inject
private DestinationDAO destinationDAO;
@Inject
private FlightDAO flightDAO;
@Inject
private ReservationDAO reservationDAO;
private Reservation reservationA;
@Before
public void setUp() throws Exception {
TestUtils testUtils = new TestUtils();
testUtils.populateDb(reservationDAO, destinationDAO, flightDAO);
reservationA = new Reservation();
reservationA.setCreated(new Date());
reservationA.setFlight(flightDAO.list().get(0));
reservationA.setPassword("heslo");
reservationA.setSeat(3);
}
@Test
@Transactional(TransactionMode.ROLLBACK)
public void list() throws Exception {
Assert.assertEquals(2, flightDAO.list().size());
}
@Test
@Transactional(TransactionMode.ROLLBACK)
public void save() throws Exception {
reservationDAO.save(reservationA);
Assert.assertEquals(2, flightDAO.list().size());
}
@Test
@Transactional(TransactionMode.ROLLBACK)
public void delete() throws Exception {
reservationDAO.delete(reservationDAO.list().get(0).getId());
Assert.assertEquals(2, reservationDAO.list().size());
}
@Test
@Transactional(TransactionMode.ROLLBACK)
public void deleteByObject() throws Exception {
int actualSize = reservationDAO.list().size();
reservationDAO.save(reservationA);
Assert.assertEquals(actualSize + 1, reservationDAO.list().size());
reservationDAO.delete(reservationA);
Assert.assertEquals(actualSize, reservationDAO.list().size());
}
@Test
@Transactional(TransactionMode.ROLLBACK)
public void find() throws Exception {
Reservation reservation = reservationDAO.find(reservationDAO.list().get(0).getId());
Assert.assertNotNull(reservation);
Assert.assertNotNull(reservation.getId());
Assert.assertNotNull(reservation.getFlight());
Assert.assertNotNull(reservation.getSeat());
Assert.assertNotNull(reservation.getCreated());
Assert.assertNull(reservation.getDeleted());
}
@Test
@Transactional(TransactionMode.ROLLBACK)
public void update() throws Exception {
Reservation reservation = reservationDAO.find(reservationDAO.list().get(0).getId());
Assert.assertNotNull(reservation);
Date newCreated = new Date();
reservation.setCreated(newCreated);
reservationDAO.update(reservation);
Reservation loadedReservation = reservationDAO.find(reservationDAO.list().get(0).getId());
Assert.assertEquals(reservation.getCreated(), loadedReservation.getCreated());
Assert.assertEquals(newCreated, loadedReservation.getCreated());
}
@Test
@Transactional(TransactionMode.ROLLBACK)
public void findBy() throws Exception {
reservationA = reservationDAO.save(reservationA);
Reservation loadedReservation = reservationDAO.findBy("created", reservationA.getCreated()).get(0);
Assert.assertEquals(reservationA.getFlight(), loadedReservation.getFlight());
Assert.assertEquals(reservationA.getSeat(), loadedReservation.getSeat());
}
}
| mit |
jbman/captain-picar | src/main/java/com/github/jbman/picar/captain/ButtonPress.java | 746 | package com.github.jbman.picar.captain;
import java.io.IOException;
import com.github.jbman.jgrove.GrovePi;
import com.github.jbman.jgrove.sensors.Button;
/**
* Class to get press state of button and detecting a long press.
*
* @author Johannes Bergmann
*/
public class ButtonPress {
public static enum Press {
None, ShortPress, LongPress
};
private final Button button;
public ButtonPress(Button button) {
this.button = button;
}
public Press getPress() throws IOException {
boolean buttonPressed = button.isPressed();
if (buttonPressed) {
GrovePi.sleep(500);
// Button still pressed?
if (button.isPressed()) {
return Press.LongPress;
}
}
return buttonPressed ? Press.ShortPress : Press.None;
}
}
| mit |
vuminhkh/tosca-runtime | common/shared-contracts/src/main/java/com/toscaruntime/exception/deployment/workflow/InvalidWorkflowException.java | 373 | package com.toscaruntime.exception.deployment.workflow;
import com.toscaruntime.exception.BadUsageException;
public class InvalidWorkflowException extends BadUsageException {
public InvalidWorkflowException(String message) {
super(message);
}
public InvalidWorkflowException(String message, Throwable cause) {
super(message, cause);
}
}
| mit |
jakobehmsen/midmod | intellij/src/reo/runtime/ReducerConstructor.java | 144 | package reo.runtime;
public interface ReducerConstructor {
Observable create(Object self, Dictionary prototype, Observable[] arguments);
}
| mit |
seriousbusinessbe/java-brusselnieuws-rss | java/brusselnieuws-rss/brusselnieuws-rss-reader-model/src/main/java/be/seriousbusiness/brusselnieuws/rss/reader/model/Article.java | 7179 | package be.seriousbusiness.brusselnieuws.rss.reader.model;
import java.math.BigInteger;
import java.net.URL;
import java.util.Collection;
import org.joda.time.DateTime;
/**
* Represents an article published on a {@link Feed}.
* @author Serious Business
* @author Stefan Borghys
* @version 1.0
* @since 1.0
* @param <MEDIUMTYPE> the type of {@link MediumType} implementation
* @param <MEDIUM> the type of {@link Medium} implementation
* @param <CATEGORY> the type of {@link Category} implementation
* @param <AUTHOR> the type of {@link Author} implementation
* @param <CREATOR> the type of {@link Creator} implementation
*/
public interface Article<MEDIUMTYPE extends MediumType,
MEDIUM extends Medium<MEDIUMTYPE>,
CATEGORY extends Category,
AUTHOR extends Author,
CREATOR extends Creator> extends Id<BigInteger>, Cloneable {
/**
* Get the title.
* @return the title
*/
String getTitle();
/**
* Set a title.
* @param title
* @throws IllegalArgumentException when <code>null</code> or empty
*/
void setTitle(final String title) throws IllegalArgumentException;
/**
* Get the web {@link URL}.
* @return the web {@link URL}
*/
URL getLink();
/**
* Set a web {@link URL}.
* @param link
* @throws IllegalArgumentException when <code>null</code>
*/
void setLink(final URL link) throws IllegalArgumentException;
/**
* Get the description.
* @return the description
*/
String getDescription();
/**
* Set a description.
* @param description
* @throws IllegalArgumentException when <code>null</code> or empty.
*/
void setDescription(final String description) throws IllegalArgumentException;
/**
* Check if a description is set.
* @return <code>true</code> when a description is set
*/
boolean hasDescription();
/**
* Get the number of {@link Author} who wrote this article.
* @return the number of authors, 0 if none
*/
int numberOfAuthors();
/**
* Get the authors.
* @return the {@link Collection} of {@link AUTHOR} who wrote this article, empty when none
*/
Collection<AUTHOR> getAuthors();
/**
* Set a {@link Collection} of {@link AUTHOR}.</br>
* <code>null</code> entries are not added.</br>
* Already added {@link AUTHOR} are also not added.
* @param authors
*/
void setAuthors(final Collection<AUTHOR> authors);
/**
* Add a unique, not <code>null</code> {@link AUTHOR}.</br>
* Not added when <code>null</code> or already added.
* @param author
*/
void add(final AUTHOR author);
/**
* Check if this {@link Article} is written by a specific {@link AUTHOR}.
* @param author the {@link AUTHOR} to look for
* @return <code>true</code> when this {@link Article} is written by a given {@link AUTHOR}
*/
boolean hasAuthor(final AUTHOR author);
/**
* Get the number of {@link CATEGORY} this {@link Article} occurs in.
* @return the number of {@link CATEGORY}, 0 if none
*/
int numberOfCategories();
/**
* Get the {@link Collection} of {@link CATEGORY} this {@link Article} is in.
* @return the {@link Collection} of {@link CATEGORY}, empty when none
*/
Collection<CATEGORY> getCategories();
/**
* Set a {@link Collection} of {@link CATEGORY}.</br>
* <code>null</code> entries are not added.</br>
* Already added {@link CATEGORY} are also not added.
* @param categories
*/
void setCategories(final Collection<CATEGORY> categories);
/**
* Add a unique, not <code>null</code> {@link CATEGORY}.</br>
* Not added when <code>null</code> or already added.
* @param category
*/
void add(final CATEGORY category);
/**
* Check if this {@link Article} is in a specific {@link CATEGORY}.
* @param category the {@link CATEGORY} to look for
* @return <code>true</code> when this {@link Article} is in a given {@link CATEGORY}
*/
boolean hasCategory(final CATEGORY category);
/**
* Get the number of {@link MEDIUM} attached to this {@link Article}.
* @return the number of {@link MEDIUM}, 0 if none
*/
int numberOfMedia();
/**
* Get a {@link Collection} of {@link MEDIUM} (Video(s), image(s), ...) attached to this {@link Article}.
* @return a {@link Collection} of {@link MEDIUM}, empty when none
*/
Collection<MEDIUM> getMedia();
/**
* Set a {@link Collection} of {@link MEDIUM}.</br>
* <code>null</code> entries are not added.</br>
* Already added {@link MEDIUM} are also not added.
* @param media
*/
void setMedia(final Collection<MEDIUM> media);
/**
* Add a unique, not <code>null</code> {@link MEDIUM}.</br>
* Not added when <code>null</code> or already added.
* @param category
*/
void add(final MEDIUM medium);
/**
* Get the number of {@link Creator}(s) who created this article.
* @return the number of creators, 0 if none
*/
int numberOfCreators();
/**
* Get the creators.
* @return the {@link Collection} of {@link CREATOR} who created this article, empty when none
*/
Collection<CREATOR> getCreators();
/**
* Set a {@link Collection} of {@link CREATOR}.</br>
* <code>null</code> entries are not added.</br>
* Already added {@link CREATOR} are also not added.
* @param creators
*/
void setCreators(final Collection<CREATOR> creators);
/**
* Add a unique, not <code>null</code> {@link CREATOR}.</br>
* Not added when <code>null</code> or already added.
* @param creator
*/
void add(final CREATOR creator);
/**
* Check if this {@link Article} is written by a specific {@link CREATOR}.
* @param creator the {@link CREATOR} to look for
* @return <code>true</code> when this {@link Article} is created by a given {@link CREATOR}
*/
boolean hasCreator(final CREATOR creator);
/**
* Get the publication date.
* @return the publication date
*/
DateTime getPublicationDate();
/**
* Set a publication {@link DateTime}
* @param publicationDate
* @throws IllegalArgumentException when <code>null</code> or in the future
*/
void setPublicationDate(final DateTime publicationDate) throws IllegalArgumentException;
/**
* Check if this {@link Article} is read or not.
* @return <code>true</code> when read
*/
boolean isRead();
/**
* Mark this {@link Article} read or not.
* @param read <code>true</code> when read,
* otherwise <code>false</code>
*/
void setRead(final boolean read);
/**
* Mark this {@link Article} as read.
*/
void read();
/**
* Check if this {@link Article} is archived.
* @return< code>true</code> when archived
*/
boolean isArchived();
/**
* Mart this {@link Article} archived or not.
* @param archived <code>true</code> when archived,
* otherwise <code>false</code>
*/
void setArchived(final boolean archived);
/**
* Mark this {@link Article} as archived.
*/
void archive();
/**
* Check if this {@link Article) is marked as favorite.
* @return <code>true</code> when a favorite
*/
boolean isFavorite();
/**
* Mark this {@link Article} as favorite.
* @param favorite <code>true</code> when favorite,
* otherwise <code>false</code>
*/
void setFavorite(final boolean favorite);
/**
* Mark this {@link Article} as favorite.
*/
void favorite();
}
| mit |
selvasingh/azure-sdk-for-java | sdk/metricsadvisor/azure-ai-metricsadvisor/src/test/java/com/azure/ai/metricsadvisor/DataFeedTestBase.java | 26684 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.ai.metricsadvisor;
import com.azure.ai.metricsadvisor.models.AzureAppInsightsDataFeedSource;
import com.azure.ai.metricsadvisor.models.AzureBlobDataFeedSource;
import com.azure.ai.metricsadvisor.models.AzureCosmosDataFeedSource;
import com.azure.ai.metricsadvisor.models.AzureDataExplorerDataFeedSource;
import com.azure.ai.metricsadvisor.models.AzureDataLakeStorageGen2DataFeedSource;
import com.azure.ai.metricsadvisor.models.AzureTableDataFeedSource;
import com.azure.ai.metricsadvisor.models.DataFeed;
import com.azure.ai.metricsadvisor.models.DataFeedAutoRollUpMethod;
import com.azure.ai.metricsadvisor.models.DataFeedGranularity;
import com.azure.ai.metricsadvisor.models.DataFeedGranularityType;
import com.azure.ai.metricsadvisor.models.DataFeedIngestionSettings;
import com.azure.ai.metricsadvisor.models.DataFeedMissingDataPointFillSettings;
import com.azure.ai.metricsadvisor.models.DataFeedOptions;
import com.azure.ai.metricsadvisor.models.DataFeedRollupSettings;
import com.azure.ai.metricsadvisor.models.DataFeedRollupType;
import com.azure.ai.metricsadvisor.models.DataFeedSchema;
import com.azure.ai.metricsadvisor.models.DataFeedSourceType;
import com.azure.ai.metricsadvisor.models.DataSourceMissingDataPointFillType;
import com.azure.ai.metricsadvisor.models.Dimension;
import com.azure.ai.metricsadvisor.models.ElasticsearchDataFeedSource;
import com.azure.ai.metricsadvisor.models.HttpRequestDataFeedSource;
import com.azure.ai.metricsadvisor.models.InfluxDBDataFeedSource;
import com.azure.ai.metricsadvisor.models.Metric;
import com.azure.ai.metricsadvisor.models.MetricsAdvisorServiceVersion;
import com.azure.ai.metricsadvisor.models.MongoDBDataFeedSource;
import com.azure.ai.metricsadvisor.models.MySqlDataFeedSource;
import com.azure.ai.metricsadvisor.models.PostgreSqlDataFeedSource;
import com.azure.ai.metricsadvisor.models.SQLServerDataFeedSource;
import com.azure.core.http.HttpClient;
import com.azure.core.util.Configuration;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.time.OffsetDateTime;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.UUID;
import java.util.function.Consumer;
import static com.azure.ai.metricsadvisor.TestUtils.APP_INSIGHTS_API_KEY;
import static com.azure.ai.metricsadvisor.TestUtils.APP_INSIGHTS_APPLICATION_ID;
import static com.azure.ai.metricsadvisor.TestUtils.APP_INSIGHTS_QUERY;
import static com.azure.ai.metricsadvisor.TestUtils.AZURE_DATALAKEGEN2_ACCOUNT_KEY;
import static com.azure.ai.metricsadvisor.TestUtils.AZURE_DATALAKEGEN2_ACCOUNT_NAME;
import static com.azure.ai.metricsadvisor.TestUtils.AZURE_METRICS_ADVISOR_ENDPOINT;
import static com.azure.ai.metricsadvisor.TestUtils.BLOB_CONNECTION_STRING;
import static com.azure.ai.metricsadvisor.TestUtils.BLOB_TEMPLATE;
import static com.azure.ai.metricsadvisor.TestUtils.COSMOS_DB_CONNECTION_STRING;
import static com.azure.ai.metricsadvisor.TestUtils.DATA_EXPLORER_CONNECTION_STRING;
import static com.azure.ai.metricsadvisor.TestUtils.DATA_EXPLORER_QUERY;
import static com.azure.ai.metricsadvisor.TestUtils.DIRECTORY_TEMPLATE;
import static com.azure.ai.metricsadvisor.TestUtils.ELASTIC_SEARCH_AUTH_HEADER;
import static com.azure.ai.metricsadvisor.TestUtils.ELASTIC_SEARCH_HOST;
import static com.azure.ai.metricsadvisor.TestUtils.FILE_TEMPLATE;
import static com.azure.ai.metricsadvisor.TestUtils.HTTP_URL;
import static com.azure.ai.metricsadvisor.TestUtils.INFLUX_DB_CONNECTION_STRING;
import static com.azure.ai.metricsadvisor.TestUtils.INFLUX_DB_PASSWORD;
import static com.azure.ai.metricsadvisor.TestUtils.INFLUX_DB_USER;
import static com.azure.ai.metricsadvisor.TestUtils.INGESTION_START_TIME;
import static com.azure.ai.metricsadvisor.TestUtils.MONGO_COMMAND;
import static com.azure.ai.metricsadvisor.TestUtils.MONGO_DB_CONNECTION_STRING;
import static com.azure.ai.metricsadvisor.TestUtils.MYSQL_DB_CONNECTION_STRING;
import static com.azure.ai.metricsadvisor.TestUtils.POSTGRE_SQL_DB_CONNECTION_STRING;
import static com.azure.ai.metricsadvisor.TestUtils.SQL_SERVER_CONNECTION_STRING;
import static com.azure.ai.metricsadvisor.TestUtils.TABLE_CONNECTION_STRING;
import static com.azure.ai.metricsadvisor.TestUtils.TABLE_QUERY;
import static com.azure.ai.metricsadvisor.TestUtils.TEMPLATE_QUERY;
import static com.azure.ai.metricsadvisor.TestUtils.TEST_DB_NAME;
import static com.azure.ai.metricsadvisor.TestUtils.getAzureBlobDataFeedSample;
import static com.azure.ai.metricsadvisor.TestUtils.getSQLDataFeedSample;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertIterableEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
public abstract class DataFeedTestBase extends MetricsAdvisorAdministrationClientTestBase {
@Override
protected void beforeTest() {
}
@Test
abstract void createSQLServerDataFeed(HttpClient httpClient, MetricsAdvisorServiceVersion serviceVersion);
@Test
abstract void testListDataFeed(HttpClient httpClient, MetricsAdvisorServiceVersion serviceVersion);
@Test
abstract void testListDataFeedTop3(HttpClient httpClient, MetricsAdvisorServiceVersion serviceVersion);
@Test
abstract void testListDataFeedFilterByCreator(HttpClient httpClient, MetricsAdvisorServiceVersion serviceVersion);
@Test
abstract void testListDataFeedFilterBySourceType(HttpClient httpClient,
MetricsAdvisorServiceVersion serviceVersion);
@Test
abstract void testListDataFeedFilterByStatus(HttpClient httpClient, MetricsAdvisorServiceVersion serviceVersion);
@Test
abstract void testListDataFeedFilterByGranularityType(HttpClient httpClient,
MetricsAdvisorServiceVersion serviceVersion);
void listDataFeedRunner(Consumer<List<DataFeed>> testRunner) {
// create data feeds
testRunner.accept(Arrays.asList(getAzureBlobDataFeedSample(), getSQLDataFeedSample()));
}
void creatDataFeedRunner(Consumer<DataFeed> testRunner, DataFeedSourceType dataFeedSourceType) {
// create data feeds
DataFeed dataFeed;
switch (dataFeedSourceType) {
case AZURE_APP_INSIGHTS:
dataFeed = new DataFeed().setSource(new AzureAppInsightsDataFeedSource(
APP_INSIGHTS_APPLICATION_ID, APP_INSIGHTS_API_KEY, TestUtils.AZURE_CLOUD, APP_INSIGHTS_QUERY));
break;
case AZURE_BLOB:
dataFeed = new DataFeed().setSource(new AzureBlobDataFeedSource(BLOB_CONNECTION_STRING,
TEST_DB_NAME, BLOB_TEMPLATE));
break;
case AZURE_DATA_EXPLORER:
dataFeed =
new DataFeed().setSource(new AzureDataExplorerDataFeedSource(DATA_EXPLORER_CONNECTION_STRING,
DATA_EXPLORER_QUERY));
break;
case AZURE_TABLE:
dataFeed = new DataFeed().setSource(new AzureTableDataFeedSource(TABLE_CONNECTION_STRING,
TABLE_QUERY, TEST_DB_NAME));
break;
case HTTP_REQUEST:
dataFeed = new DataFeed().setSource(new HttpRequestDataFeedSource(HTTP_URL, "GET"));
break;
case INFLUX_DB:
dataFeed = new DataFeed().setSource(new InfluxDBDataFeedSource(INFLUX_DB_CONNECTION_STRING,
TEST_DB_NAME, INFLUX_DB_USER, INFLUX_DB_PASSWORD, TEMPLATE_QUERY));
break;
case MONGO_DB:
dataFeed = new DataFeed().setSource(new MongoDBDataFeedSource(MONGO_DB_CONNECTION_STRING,
TEST_DB_NAME, MONGO_COMMAND));
break;
case MYSQL_DB:
dataFeed = new DataFeed().setSource(new MySqlDataFeedSource(MYSQL_DB_CONNECTION_STRING,
TEMPLATE_QUERY));
break;
case POSTGRE_SQL_DB:
dataFeed = new DataFeed().setSource(new PostgreSqlDataFeedSource(POSTGRE_SQL_DB_CONNECTION_STRING,
TEMPLATE_QUERY));
break;
case SQL_SERVER_DB:
dataFeed = new DataFeed().setSource(new SQLServerDataFeedSource(SQL_SERVER_CONNECTION_STRING,
TEMPLATE_QUERY));
break;
case AZURE_COSMOS_DB:
dataFeed = new DataFeed().setSource(new AzureCosmosDataFeedSource(COSMOS_DB_CONNECTION_STRING,
TEMPLATE_QUERY, TEST_DB_NAME, TEST_DB_NAME));
break;
case ELASTIC_SEARCH:
dataFeed = new DataFeed().setSource(new ElasticsearchDataFeedSource(ELASTIC_SEARCH_HOST, "9200",
ELASTIC_SEARCH_AUTH_HEADER, TEMPLATE_QUERY));
break;
case AZURE_DATA_LAKE_STORAGE_GEN2:
dataFeed = new DataFeed().setSource(new AzureDataLakeStorageGen2DataFeedSource(
AZURE_DATALAKEGEN2_ACCOUNT_NAME,
AZURE_DATALAKEGEN2_ACCOUNT_KEY,
TEST_DB_NAME, DIRECTORY_TEMPLATE, FILE_TEMPLATE));
break;
default:
throw new IllegalStateException("Unexpected value: " + dataFeedSourceType);
}
testRunner.accept(dataFeed.setSchema(new DataFeedSchema(Arrays.asList(
new Metric().setName("cost").setDisplayName("cost"),
new Metric().setName("revenue").setDisplayName("revenue")))
.setDimensions(Arrays.asList(
new Dimension().setName("city").setDisplayName("city"),
new Dimension().setName("category").setDisplayName("category"))))
.setName("java_create_data_feed_test_sample" + UUID.randomUUID())
.setGranularity(new DataFeedGranularity().setGranularityType(DataFeedGranularityType.DAILY))
.setIngestionSettings(new DataFeedIngestionSettings(OffsetDateTime.parse(INGESTION_START_TIME))));
}
void validateDataFeedResult(DataFeed expectedDataFeed, DataFeed actualDataFeed,
DataFeedSourceType dataFeedSourceType) {
assertNotNull(actualDataFeed.getId());
assertNotNull(actualDataFeed.getCreatedTime());
assertNotNull(actualDataFeed.getMetricIds());
assertNotNull(actualDataFeed.getName());
assertEquals(2, actualDataFeed.getMetricIds().size());
assertEquals(dataFeedSourceType, actualDataFeed.getSourceType());
assertNotNull(actualDataFeed.getStatus());
validateDataFeedGranularity(expectedDataFeed.getGranularity(), actualDataFeed.getGranularity());
validateDataFeedIngestionSettings(expectedDataFeed.getIngestionSettings(),
actualDataFeed.getIngestionSettings());
validateDataFeedSchema(expectedDataFeed.getSchema(), actualDataFeed.getSchema());
validateDataFeedOptions(expectedDataFeed.getOptions(), actualDataFeed.getOptions());
validateDataFeedSource(expectedDataFeed, actualDataFeed, dataFeedSourceType);
}
private void validateDataFeedSource(DataFeed expectedDataFeed, DataFeed actualDataFeed,
DataFeedSourceType dataFeedSourceType) {
switch (dataFeedSourceType) {
case AZURE_APP_INSIGHTS:
final AzureAppInsightsDataFeedSource expAzureAppInsightsDataFeedSource =
(AzureAppInsightsDataFeedSource) expectedDataFeed.getSource();
final AzureAppInsightsDataFeedSource actualAzureAppInsightsDataFeedSource =
(AzureAppInsightsDataFeedSource) actualDataFeed.getSource();
assertNotNull(actualAzureAppInsightsDataFeedSource.getApiKey());
assertNotNull(actualAzureAppInsightsDataFeedSource.getApplicationId());
assertEquals(expAzureAppInsightsDataFeedSource.getQuery(),
actualAzureAppInsightsDataFeedSource.getQuery());
assertEquals(expAzureAppInsightsDataFeedSource.getAzureCloud(),
actualAzureAppInsightsDataFeedSource.getAzureCloud());
break;
case AZURE_BLOB:
final AzureBlobDataFeedSource expBlobDataFeedSource =
(AzureBlobDataFeedSource) expectedDataFeed.getSource();
final AzureBlobDataFeedSource actualBlobDataFeedSource =
(AzureBlobDataFeedSource) actualDataFeed.getSource();
assertEquals(expBlobDataFeedSource.getBlobTemplate(), actualBlobDataFeedSource.getBlobTemplate());
assertNotNull(actualBlobDataFeedSource.getConnectionString());
assertEquals(expBlobDataFeedSource.getContainer(), actualBlobDataFeedSource.getContainer());
break;
case AZURE_DATA_EXPLORER:
final AzureDataExplorerDataFeedSource expExplorerDataFeedSource =
(AzureDataExplorerDataFeedSource) expectedDataFeed.getSource();
final AzureDataExplorerDataFeedSource actualExplorerDataFeedSource =
(AzureDataExplorerDataFeedSource) actualDataFeed.getSource();
assertNotNull(actualExplorerDataFeedSource.getConnectionString());
assertEquals(expExplorerDataFeedSource.getQuery(), actualExplorerDataFeedSource.getQuery());
break;
case AZURE_TABLE:
final AzureTableDataFeedSource expTableDataFeedSource =
(AzureTableDataFeedSource) expectedDataFeed.getSource();
final AzureTableDataFeedSource actualTableDataFeedSource =
(AzureTableDataFeedSource) actualDataFeed.getSource();
assertNotNull(actualTableDataFeedSource.getConnectionString());
assertEquals(expTableDataFeedSource.getTableName(), actualTableDataFeedSource.getTableName());
assertEquals(expTableDataFeedSource.getQueryScript(), actualTableDataFeedSource.getQueryScript());
break;
case HTTP_REQUEST:
final HttpRequestDataFeedSource expHttpDataFeedSource =
(HttpRequestDataFeedSource) expectedDataFeed.getSource();
final HttpRequestDataFeedSource actualHttpDataFeedSource =
(HttpRequestDataFeedSource) actualDataFeed.getSource();
assertNotNull(actualHttpDataFeedSource.getUrl());
assertEquals(expHttpDataFeedSource.getHttpHeader(), actualHttpDataFeedSource.getHttpHeader());
assertEquals(expHttpDataFeedSource.getPayload(), actualHttpDataFeedSource.getPayload());
assertEquals(expHttpDataFeedSource.getHttpMethod(), actualHttpDataFeedSource.getHttpMethod());
break;
case INFLUX_DB:
final InfluxDBDataFeedSource expInfluxDataFeedSource =
(InfluxDBDataFeedSource) expectedDataFeed.getSource();
final InfluxDBDataFeedSource actualInfluxDataFeedSource =
(InfluxDBDataFeedSource) actualDataFeed.getSource();
assertNotNull(actualInfluxDataFeedSource.getConnectionString());
assertEquals(expInfluxDataFeedSource.getDatabase(), actualInfluxDataFeedSource.getDatabase());
assertNotNull(actualInfluxDataFeedSource.getPassword());
assertNotNull(actualInfluxDataFeedSource.getUserName());
break;
case MONGO_DB:
final MongoDBDataFeedSource expMongoDataFeedSource =
(MongoDBDataFeedSource) expectedDataFeed.getSource();
final MongoDBDataFeedSource actualMongoDataFeedSource =
(MongoDBDataFeedSource) actualDataFeed.getSource();
assertNotNull(actualMongoDataFeedSource.getConnectionString());
assertEquals(expMongoDataFeedSource.getDatabase(), actualMongoDataFeedSource.getDatabase());
assertEquals(expMongoDataFeedSource.getCommand(), actualMongoDataFeedSource.getCommand());
break;
case MYSQL_DB:
final MySqlDataFeedSource expMySqlDataFeedSource = (MySqlDataFeedSource) expectedDataFeed.getSource();
final MySqlDataFeedSource actualMySqlDataFeedSource = (MySqlDataFeedSource) actualDataFeed.getSource();
assertNotNull(actualMySqlDataFeedSource.getConnectionString());
assertEquals(expMySqlDataFeedSource.getQuery(), actualMySqlDataFeedSource.getQuery());
break;
case POSTGRE_SQL_DB:
final PostgreSqlDataFeedSource expPostGreDataFeedSource =
(PostgreSqlDataFeedSource) expectedDataFeed.getSource();
final PostgreSqlDataFeedSource actualPostGreDataFeedSource =
(PostgreSqlDataFeedSource) actualDataFeed.getSource();
assertNotNull(actualPostGreDataFeedSource.getConnectionString());
assertEquals(expPostGreDataFeedSource.getQuery(), actualPostGreDataFeedSource.getQuery());
break;
case SQL_SERVER_DB:
final SQLServerDataFeedSource expSqlServerDataFeedSource =
(SQLServerDataFeedSource) expectedDataFeed.getSource();
final SQLServerDataFeedSource actualSqlServerDataFeedSource =
(SQLServerDataFeedSource) actualDataFeed.getSource();
assertNotNull(actualSqlServerDataFeedSource.getConnectionString());
assertEquals(expSqlServerDataFeedSource.getQuery(), actualSqlServerDataFeedSource.getQuery());
break;
case AZURE_COSMOS_DB:
final AzureCosmosDataFeedSource expCosmosDataFeedSource =
(AzureCosmosDataFeedSource) expectedDataFeed.getSource();
final AzureCosmosDataFeedSource actualCosmosDataFeedSource =
(AzureCosmosDataFeedSource) actualDataFeed.getSource();
assertEquals(expCosmosDataFeedSource.getCollectionId(), actualCosmosDataFeedSource.getCollectionId());
assertNotNull(actualCosmosDataFeedSource.getConnectionString());
assertEquals(expCosmosDataFeedSource.getDatabase(), actualCosmosDataFeedSource.getDatabase());
assertEquals(expCosmosDataFeedSource.getSqlQuery(), actualCosmosDataFeedSource.getSqlQuery());
break;
case ELASTIC_SEARCH:
final ElasticsearchDataFeedSource expElasticsearchDataFeedSource =
(ElasticsearchDataFeedSource) expectedDataFeed.getSource();
final ElasticsearchDataFeedSource actualDataFeedSource =
(ElasticsearchDataFeedSource) actualDataFeed.getSource();
assertNotNull(actualDataFeedSource.getAuthHeader());
assertNotNull(actualDataFeedSource.getHost());
assertEquals(expElasticsearchDataFeedSource.getPort(), actualDataFeedSource.getPort());
assertEquals(expElasticsearchDataFeedSource.getQuery(), actualDataFeedSource.getQuery());
break;
case AZURE_DATA_LAKE_STORAGE_GEN2:
final AzureDataLakeStorageGen2DataFeedSource expDataLakeStorageGen2DataFeedSource =
(AzureDataLakeStorageGen2DataFeedSource) expectedDataFeed.getSource();
final AzureDataLakeStorageGen2DataFeedSource actualDataLakeFeedSource =
(AzureDataLakeStorageGen2DataFeedSource) actualDataFeed.getSource();
assertNotNull(actualDataLakeFeedSource.getAccountKey());
assertNotNull(actualDataLakeFeedSource.getAccountName());
assertEquals(expDataLakeStorageGen2DataFeedSource.getDirectoryTemplate(),
actualDataLakeFeedSource.getDirectoryTemplate());
assertEquals(expDataLakeStorageGen2DataFeedSource.getFileSystemName(),
actualDataLakeFeedSource.getFileSystemName());
assertEquals(expDataLakeStorageGen2DataFeedSource.getFileTemplate(),
actualDataLakeFeedSource.getFileTemplate());
break;
default:
throw new IllegalStateException("Unexpected value: " + dataFeedSourceType);
}
}
private void validateDataFeedOptions(DataFeedOptions expectedOptions, DataFeedOptions actualOptions) {
if (expectedOptions != null) {
assertEquals(expectedOptions.getDescription(), actualOptions.getDescription());
assertEquals(expectedOptions.getActionLinkTemplate(), actualOptions.getActionLinkTemplate());
assertIterableEquals(expectedOptions.getAdmins(), actualOptions.getAdmins());
assertIterableEquals(expectedOptions.getViewers(), actualOptions.getViewers());
assertNotNull(actualOptions.getAccessMode());
if (expectedOptions.getAccessMode() != null) {
assertEquals(expectedOptions.getAccessMode(), actualOptions.getAccessMode());
}
validateRollUpSettings(expectedOptions.getRollupSettings(), actualOptions.getRollupSettings());
validateFillSettings(expectedOptions.getMissingDataPointFillSettings(),
actualOptions.getMissingDataPointFillSettings());
} else {
// setting defaults
validateRollUpSettings(new DataFeedRollupSettings().setRollupType(DataFeedRollupType.NO_ROLLUP),
actualOptions.getRollupSettings());
validateFillSettings(new DataFeedMissingDataPointFillSettings()
.setFillType(DataSourceMissingDataPointFillType.PREVIOUS_VALUE).setCustomFillValue(0.0),
actualOptions.getMissingDataPointFillSettings());
}
}
private void validateFillSettings(DataFeedMissingDataPointFillSettings expectedFillSettings,
DataFeedMissingDataPointFillSettings actualFillSettings) {
assertEquals(expectedFillSettings.getCustomFillValue(), actualFillSettings.getCustomFillValue());
assertEquals(expectedFillSettings.getFillType(), actualFillSettings.getFillType());
}
private void validateRollUpSettings(DataFeedRollupSettings expectedRollUpSettings,
DataFeedRollupSettings actualRollUpSettings) {
assertEquals(expectedRollUpSettings.getRollupIdentificationValue(), actualRollUpSettings
.getRollupIdentificationValue());
assertEquals(expectedRollUpSettings.getRollupType(), actualRollUpSettings.getRollupType());
if (expectedRollUpSettings.getDataFeedAutoRollUpMethod() != null) {
assertEquals(expectedRollUpSettings.getDataFeedAutoRollUpMethod(), actualRollUpSettings
.getDataFeedAutoRollUpMethod());
}
assertEquals(DataFeedAutoRollUpMethod.NONE, actualRollUpSettings
.getDataFeedAutoRollUpMethod());
}
private void validateDataFeedSchema(DataFeedSchema expectedDataFeedSchema, DataFeedSchema actualDataFeedSchema) {
assertEquals(expectedDataFeedSchema.getDimensions().size(), actualDataFeedSchema.getDimensions().size());
expectedDataFeedSchema.getDimensions().sort(Comparator.comparing(Dimension::getName));
actualDataFeedSchema.getDimensions().sort(Comparator.comparing(Dimension::getName));
for (int i = 0; i < expectedDataFeedSchema.getDimensions().size(); i++) {
Dimension expectedDimension = expectedDataFeedSchema.getDimensions().get(i);
Dimension actualDimension = actualDataFeedSchema.getDimensions().get(i);
assertEquals(expectedDimension.getName(), actualDimension.getName());
assertNotNull(actualDimension.getDisplayName());
if (expectedDimension.getDisplayName() != null) {
assertEquals(expectedDimension.getDisplayName(), actualDimension.getDisplayName());
} else {
assertEquals(expectedDimension.getName(), actualDimension.getDisplayName());
}
}
assertEquals(expectedDataFeedSchema.getMetrics().size(), actualDataFeedSchema.getMetrics().size());
expectedDataFeedSchema.getMetrics().sort(Comparator.comparing(Metric::getName));
actualDataFeedSchema.getMetrics().sort(Comparator.comparing(Metric::getName));
for (int i = 0; i < expectedDataFeedSchema.getMetrics().size(); i++) {
Metric expectedMetric = expectedDataFeedSchema.getMetrics().get(i);
Metric actualMetric = actualDataFeedSchema.getMetrics().get(i);
assertNotNull(actualMetric.getId());
assertEquals(expectedMetric.getName(), actualMetric.getName());
if (expectedMetric.getDescription() != null) {
assertEquals(expectedMetric.getDescription(), actualMetric.getDescription());
}
assertNotNull(actualMetric.getDescription());
if (expectedMetric.getDisplayName() != null) {
assertEquals(expectedMetric.getDisplayName(), actualMetric.getDisplayName());
} else {
assertEquals(expectedMetric.getName(), actualMetric.getDisplayName());
}
}
assertNotNull(actualDataFeedSchema.getTimestampColumn());
}
private void validateDataFeedGranularity(DataFeedGranularity expectedGranularity,
DataFeedGranularity actualGranularity) {
assertEquals(expectedGranularity.getGranularityType(), actualGranularity.getGranularityType());
if (DataFeedGranularityType.CUSTOM.equals(actualGranularity.getGranularityType())) {
assertEquals(expectedGranularity.getCustomGranularityValue(),
actualGranularity.getCustomGranularityValue());
}
}
private void validateDataFeedIngestionSettings(DataFeedIngestionSettings expectedIngestion,
DataFeedIngestionSettings actualIngestion) {
assertEquals(expectedIngestion.getIngestionStartTime(), actualIngestion.getIngestionStartTime());
assertEquals(expectedIngestion.getDataSourceRequestConcurrency(),
actualIngestion.getDataSourceRequestConcurrency());
assertEquals(Duration.ofSeconds(-1), actualIngestion.getIngestionRetryDelay());
assertEquals(Duration.ofSeconds(0), actualIngestion.getIngestionStartOffset());
assertEquals(Duration.ofSeconds(-1), actualIngestion.getStopRetryAfter());
}
String getEndpoint() {
return interceptorManager.isPlaybackMode()
? "https://localhost:8080"
: Configuration.getGlobalConfiguration().get(AZURE_METRICS_ADVISOR_ENDPOINT);
}
}
| mit |
alexandergknoll/calc-pro | app/src/androidTest/java/alexandergknoll/com/calcpro/ApplicationTest.java | 358 | package alexandergknoll.com.calcpro;
import android.app.Application;
import android.test.ApplicationTestCase;
/**
* <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a>
*/
public class ApplicationTest extends ApplicationTestCase<Application> {
public ApplicationTest() {
super(Application.class);
}
} | mit |
dextto/AlgorithmStudy | src/main/java/PukyungUniv/DP02_PathOfSmallestSumOfMatrix.java | 1944 | package PukyungUniv;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
public class DP02_PathOfSmallestSumOfMatrix {
private static final int UP = 1;
private static final int LEFT = 2;
private int[][] m = {
{ 6, 7, 12, 5 },
{ 5, 3, 11, 18 },
{ 7, 17, 3, 3 },
{ 8, 10, 15, 9 },
};
int[][] cache;
int[][] path;
@Test
public void test() {
cache = new int[m.length][m[0].length];
path = new int[m.length][m[0].length];
assertEquals(40, sum());
}
// Bottom-up solution
private int sum() {
for (int j = 0; j < m.length; j++) {
for (int i = 0; i < m[0].length; i++) {
if (j == 0 && i == 0) {
cache[j][i] = m[j][i];
path[j][i] = 0;
} else if (i == 0) {
cache[j][i] = m[j][i] + cache[j - 1][i];
path[j][i] = UP;
} else if (j == 0) {
cache[j][i] = m[j][i] + cache[j][i - 1];
path[j][i] = LEFT;
} else {
cache[j][i] = m[j][i] + Math.min(cache[j - 1][i], cache[j][i - 1]);
if (cache[j - 1][i] < cache[j][i - 1]) {
path[j][i] = UP;
} else {
path[j][i] = LEFT;
}
}
}
}
printPath(m.length - 1, m[0].length - 1);
return cache[m.length - 1][m[0].length - 1];
}
private void printPath(int j, int i) {
if (path[j][i] == 0) {
System.out.println(i + " " + j);
} else {
if (path[j][i] == LEFT) {
printPath(j, i - 1);
} else {
printPath(j - 1, i);
}
System.out.println(i + " " + j);
}
}
} | mit |
lhrl/zheng | zheng-cms/zheng-cms-dao/src/main/java/com/zheng/cms/dao/model/CmsCategoryTagExample.java | 12005 | package com.zheng.cms.dao.model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
public class CmsCategoryTagExample implements Serializable {
protected String orderByClause;
protected boolean distinct;
protected List<Criteria> oredCriteria;
private static final long serialVersionUID = 1L;
private Integer limit;
private Integer offset;
public CmsCategoryTagExample() {
oredCriteria = new ArrayList<Criteria>();
}
public void setOrderByClause(String orderByClause) {
this.orderByClause = orderByClause;
}
public String getOrderByClause() {
return orderByClause;
}
public void setDistinct(boolean distinct) {
this.distinct = distinct;
}
public boolean isDistinct() {
return distinct;
}
public List<Criteria> getOredCriteria() {
return oredCriteria;
}
public void or(Criteria criteria) {
oredCriteria.add(criteria);
}
public Criteria or() {
Criteria criteria = createCriteriaInternal();
oredCriteria.add(criteria);
return criteria;
}
public Criteria createCriteria() {
Criteria criteria = createCriteriaInternal();
if (oredCriteria.size() == 0) {
oredCriteria.add(criteria);
}
return criteria;
}
protected Criteria createCriteriaInternal() {
Criteria criteria = new Criteria();
return criteria;
}
public void clear() {
oredCriteria.clear();
orderByClause = null;
distinct = false;
}
public void setLimit(Integer limit) {
this.limit = limit;
}
public Integer getLimit() {
return limit;
}
public void setOffset(Integer offset) {
this.offset = offset;
}
public Integer getOffset() {
return offset;
}
protected abstract static class GeneratedCriteria implements Serializable {
protected List<Criterion> criteria;
protected GeneratedCriteria() {
super();
criteria = new ArrayList<Criterion>();
}
public boolean isValid() {
return criteria.size() > 0;
}
public List<Criterion> getAllCriteria() {
return criteria;
}
public List<Criterion> getCriteria() {
return criteria;
}
protected void addCriterion(String condition) {
if (condition == null) {
throw new RuntimeException("Value for condition cannot be null");
}
criteria.add(new Criterion(condition));
}
protected void addCriterion(String condition, Object value, String property) {
if (value == null) {
throw new RuntimeException("Value for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value));
}
protected void addCriterion(String condition, Object value1, Object value2, String property) {
if (value1 == null || value2 == null) {
throw new RuntimeException("Between values for " + property + " cannot be null");
}
criteria.add(new Criterion(condition, value1, value2));
}
public Criteria andCategoryTagIdIsNull() {
addCriterion("category_tag_id is null");
return (Criteria) this;
}
public Criteria andCategoryTagIdIsNotNull() {
addCriterion("category_tag_id is not null");
return (Criteria) this;
}
public Criteria andCategoryTagIdEqualTo(Integer value) {
addCriterion("category_tag_id =", value, "categoryTagId");
return (Criteria) this;
}
public Criteria andCategoryTagIdNotEqualTo(Integer value) {
addCriterion("category_tag_id <>", value, "categoryTagId");
return (Criteria) this;
}
public Criteria andCategoryTagIdGreaterThan(Integer value) {
addCriterion("category_tag_id >", value, "categoryTagId");
return (Criteria) this;
}
public Criteria andCategoryTagIdGreaterThanOrEqualTo(Integer value) {
addCriterion("category_tag_id >=", value, "categoryTagId");
return (Criteria) this;
}
public Criteria andCategoryTagIdLessThan(Integer value) {
addCriterion("category_tag_id <", value, "categoryTagId");
return (Criteria) this;
}
public Criteria andCategoryTagIdLessThanOrEqualTo(Integer value) {
addCriterion("category_tag_id <=", value, "categoryTagId");
return (Criteria) this;
}
public Criteria andCategoryTagIdIn(List<Integer> values) {
addCriterion("category_tag_id in", values, "categoryTagId");
return (Criteria) this;
}
public Criteria andCategoryTagIdNotIn(List<Integer> values) {
addCriterion("category_tag_id not in", values, "categoryTagId");
return (Criteria) this;
}
public Criteria andCategoryTagIdBetween(Integer value1, Integer value2) {
addCriterion("category_tag_id between", value1, value2, "categoryTagId");
return (Criteria) this;
}
public Criteria andCategoryTagIdNotBetween(Integer value1, Integer value2) {
addCriterion("category_tag_id not between", value1, value2, "categoryTagId");
return (Criteria) this;
}
public Criteria andCategoryIdIsNull() {
addCriterion("category_id is null");
return (Criteria) this;
}
public Criteria andCategoryIdIsNotNull() {
addCriterion("category_id is not null");
return (Criteria) this;
}
public Criteria andCategoryIdEqualTo(Integer value) {
addCriterion("category_id =", value, "categoryId");
return (Criteria) this;
}
public Criteria andCategoryIdNotEqualTo(Integer value) {
addCriterion("category_id <>", value, "categoryId");
return (Criteria) this;
}
public Criteria andCategoryIdGreaterThan(Integer value) {
addCriterion("category_id >", value, "categoryId");
return (Criteria) this;
}
public Criteria andCategoryIdGreaterThanOrEqualTo(Integer value) {
addCriterion("category_id >=", value, "categoryId");
return (Criteria) this;
}
public Criteria andCategoryIdLessThan(Integer value) {
addCriterion("category_id <", value, "categoryId");
return (Criteria) this;
}
public Criteria andCategoryIdLessThanOrEqualTo(Integer value) {
addCriterion("category_id <=", value, "categoryId");
return (Criteria) this;
}
public Criteria andCategoryIdIn(List<Integer> values) {
addCriterion("category_id in", values, "categoryId");
return (Criteria) this;
}
public Criteria andCategoryIdNotIn(List<Integer> values) {
addCriterion("category_id not in", values, "categoryId");
return (Criteria) this;
}
public Criteria andCategoryIdBetween(Integer value1, Integer value2) {
addCriterion("category_id between", value1, value2, "categoryId");
return (Criteria) this;
}
public Criteria andCategoryIdNotBetween(Integer value1, Integer value2) {
addCriterion("category_id not between", value1, value2, "categoryId");
return (Criteria) this;
}
public Criteria andTagIdIsNull() {
addCriterion("tag_id is null");
return (Criteria) this;
}
public Criteria andTagIdIsNotNull() {
addCriterion("tag_id is not null");
return (Criteria) this;
}
public Criteria andTagIdEqualTo(Integer value) {
addCriterion("tag_id =", value, "tagId");
return (Criteria) this;
}
public Criteria andTagIdNotEqualTo(Integer value) {
addCriterion("tag_id <>", value, "tagId");
return (Criteria) this;
}
public Criteria andTagIdGreaterThan(Integer value) {
addCriterion("tag_id >", value, "tagId");
return (Criteria) this;
}
public Criteria andTagIdGreaterThanOrEqualTo(Integer value) {
addCriterion("tag_id >=", value, "tagId");
return (Criteria) this;
}
public Criteria andTagIdLessThan(Integer value) {
addCriterion("tag_id <", value, "tagId");
return (Criteria) this;
}
public Criteria andTagIdLessThanOrEqualTo(Integer value) {
addCriterion("tag_id <=", value, "tagId");
return (Criteria) this;
}
public Criteria andTagIdIn(List<Integer> values) {
addCriterion("tag_id in", values, "tagId");
return (Criteria) this;
}
public Criteria andTagIdNotIn(List<Integer> values) {
addCriterion("tag_id not in", values, "tagId");
return (Criteria) this;
}
public Criteria andTagIdBetween(Integer value1, Integer value2) {
addCriterion("tag_id between", value1, value2, "tagId");
return (Criteria) this;
}
public Criteria andTagIdNotBetween(Integer value1, Integer value2) {
addCriterion("tag_id not between", value1, value2, "tagId");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria implements Serializable {
protected Criteria() {
super();
}
}
public static class Criterion implements Serializable {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
} | mit |
CarrKnight/MacroIIDiscrete | src/main/java/model/gui/MouseMode.java | 501 | /*
* Copyright (c) 2014 by Ernesto Carrella
* Licensed under MIT license. Basically do what you want with it but cite me and don't sue me. Which is just politeness, really.
* See the file "LICENSE" for more information
*/
package model.gui;
/**
* This at some point might graduate to real class,
* but for now it's just a way to select the mouse mode in the geographical map
* Created by carrknight on 4/25/14.
*/
public enum MouseMode {
SELECTION,
ADD_FIRM,
ADD_CONSUMER
}
| mit |
NotCrowdingOutRuoshi/FSM-Prototype | src/organdonation/states/State.java | 357 | package organdonation.states;
import organdonation.entities.sprites.Sprite;
public abstract class State {
protected Sprite _entity;
protected State(Sprite sprite) {
assert sprite != null;
_entity = sprite;
}
public abstract void enter();
public abstract void execute();
public abstract void exit();
public abstract StateType getType();
}
| mit |
EnricoSchw/readthisstuff.com | src/main/java/com/readthisstuff/rts/web/rest/ProfileInfoResource.java | 1843 | package com.readthisstuff.rts.web.rest;
import com.readthisstuff.rts.config.JHipsterProperties;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.inject.Inject;
import org.springframework.core.env.Environment;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class ProfileInfoResource {
@Inject
Environment env;
@Inject
private JHipsterProperties jHipsterProperties;
@RequestMapping(value = "/profile-info",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
public ProfileInfoResponse getActiveProfiles() {
return new ProfileInfoResponse(env.getActiveProfiles(), getRibbonEnv());
}
private String getRibbonEnv() {
String[] activeProfiles = env.getActiveProfiles();
String[] displayOnActiveProfiles = jHipsterProperties.getRibbon().getDisplayOnActiveProfiles();
if (displayOnActiveProfiles == null) {
return null;
}
List<String> ribbonProfiles = new ArrayList<>(Arrays.asList(displayOnActiveProfiles));
List<String> springBootProfiles = Arrays.asList(activeProfiles);
ribbonProfiles.retainAll(springBootProfiles);
if (ribbonProfiles.size() > 0) {
return ribbonProfiles.get(0);
}
return null;
}
class ProfileInfoResponse {
public String[] activeProfiles;
public String ribbonEnv;
ProfileInfoResponse(String[] activeProfiles,String ribbonEnv) {
this.activeProfiles=activeProfiles;
this.ribbonEnv=ribbonEnv;
}
}
}
| mit |
upperlevel/uppercore | src/main/java/xyz/upperlevel/uppercore/util/Position.java | 2953 | package xyz.upperlevel.uppercore.util;
import lombok.Getter;
import lombok.Setter;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.configuration.serialization.ConfigurationSerializable;
import xyz.upperlevel.uppercore.config.Config;
import xyz.upperlevel.uppercore.config.ConfigConstructor;
import xyz.upperlevel.uppercore.config.ConfigProperty;
import java.util.HashMap;
import java.util.Map;
public class Position implements ConfigurationSerializable {
@Getter
@Setter
private double x, y, z;
@Getter
@Setter
private float yaw, pitch;
public Position() {
}
public Position(double x, double y, double z, float yaw, float pitch) {
this.x = x;
this.y = y;
this.z = z;
this.yaw = yaw;
this.pitch = pitch;
}
public Position(double x, double y, double z) {
this(x, y, z, 0f, 0f);
}
@ConfigConstructor(inlineable = true)
protected Position(@ConfigProperty("x") double x,
@ConfigProperty("y") double y,
@ConfigProperty("z") double z,
@ConfigProperty(value = "yaw", optional = true) Float yaw,
@ConfigProperty(value = "pitch", optional = true) Float pitch) {
this(x, y, z, yaw != null ? yaw : 0.0f, pitch != null ? pitch : 0.0f);
}
public Position(Location location) {
this.x = location.getX();
this.y = location.getY();
this.z = location.getZ();
this.yaw = location.getYaw();
this.pitch = location.getPitch();
}
public Location toLocation(World world) {
return new Location(world, x, y, z, yaw, pitch);
}
public Block toBlock(World world) {
return toLocation(world).getBlock();
}
public Position copy() {
return new Position(x, y, z, yaw, pitch);
}
@Override
public boolean equals(Object object) {
if (object instanceof Position) {
Position position = (Position) object;
return position.x == x &&
position.y == y &&
position.z == z &&
position.yaw == yaw &&
position.pitch == pitch;
}
return super.equals(object);
}
@Override
public Map<String, Object> serialize() {
Map<String, Object> data = new HashMap<>();
data.put("x", x);
data.put("y", y);
data.put("z", z);
data.put("yaw", yaw);
data.put("pitch", pitch);
return data;
}
public static Position deserialize(Map<String, Object> data) {
Config cfg = Config.from(data);
Position r = new Position();
r.x = cfg.getDouble("x");
r.y = cfg.getDouble("y");
r.z = cfg.getDouble("z");
r.yaw = cfg.getFloat("yaw");
r.pitch = cfg.getFloat("pitch");
return r;
}
}
| mit |
legendblade/CraftingHarmonics | src/main/java/org/winterblade/minecraft/harmony/entities/callbacks/TeleportDimensionRelativeCallback.java | 1067 | package org.winterblade.minecraft.harmony.entities.callbacks;
import net.minecraft.entity.Entity;
import net.minecraft.util.math.Vec3d;
import org.winterblade.minecraft.harmony.api.entities.EntityCallback;
import org.winterblade.minecraft.harmony.api.utility.CallbackMetadata;
/**
* Created by Matt on 5/26/2016.
*/
@EntityCallback(name = "teleportRelative")
public class TeleportDimensionRelativeCallback extends TeleportBaseCallback {
/*
* Serialized properties
*/
private double x;
private double y;
private double z;
private double scaling = 1.0;
@Override
protected void applyWithTargetDimension(Entity target, int targetDim, CallbackMetadata metadata) {
// Get their current position...
Vec3d pos = target.getPositionVector();
// If we're crossing dimensions, apply the scaling!
if(target.getEntityWorld().provider.getDimension() != targetDim) {
pos = pos.scale(scaling);
}
// Do the teleport...
teleport(target, targetDim, pos, metadata);
}
}
| mit |
ricardobaumann/spring_blog_frontend | src/main/java/com/github/ricardobaumann/spring_blog_frontend/dtos/UserDTO.java | 253 | package com.github.ricardobaumann.spring_blog_frontend.dtos;
import lombok.AllArgsConstructor;
import lombok.Data;
/**
* Created by ricardobaumann on 22/11/16.
*/
@Data
@AllArgsConstructor
public class UserDTO {
private String access_token;
}
| mit |
yetisno/RuleEngine | RuleEngineCore/src/main/java/org/yetiz/service/rulengine/core/Loggable.java | 4667 | package org.yetiz.service.rulengine.core;
import java.io.Serializable;
import java.util.UUID;
/**
* Created by yeti on 14/12/16.
*/
public abstract class Loggable implements Serializable, Cloneable {
private static final long serialVersionUID = -7745518557889386888L;
public Base BASE = null;
public Loggable() {
_genBase(null);
}
public Loggable(String name) {
_genBase(name);
}
private String _generateID() {
return UUID.randomUUID().toString();
}
private void _genBase(String name) {
BASE = new Base();
BASE.setID(_generateID());
if (name == null) {
BASE.setName(getClass().getCanonicalName());
if (name == null) {
BASE.setName(getClass().getGenericSuperclass().toString());
}
}else{
BASE.setName(name);
}
}
/**
* Creates and returns a copy of this object. The precise meaning
* of "copy" may depend on the class of the object. The general
* intent is that, for any object {@code x}, the expression:
* <blockquote>
* <pre>
* x.clone() != x</pre></blockquote>
* will be true, and that the expression:
* <blockquote>
* <pre>
* x.clone().getClass() == x.getClass()</pre></blockquote>
* will be {@code true}, but these are not absolute requirements.
* While it is typically the case that:
* <blockquote>
* <pre>
* x.clone().equals(x)</pre></blockquote>
* will be {@code true}, this is not an absolute requirement.
*
* By convention, the returned object should be obtained by calling
* {@code super.clone}. If a class and all of its superclasses (except
* {@code Object}) obey this convention, it will be the case that
* {@code x.clone().getClass() == x.getClass()}.
*
* By convention, the object returned by this method should be independent
* of this object (which is being cloned). To achieve this independence,
* it may be necessary to modify one or more fields of the object returned
* by {@code super.clone} before returning it. Typically, this means
* copying any mutable objects that comprise the internal "deep structure"
* of the object being cloned and replacing the references to these
* objects with references to the copies. If a class contains only
* primitive fields or references to immutable objects, then it is usually
* the case that no fields in the object returned by {@code super.clone}
* need to be modified.
*
* The method {@code clone} for class {@code Object} performs a
* specific cloning operation. First, if the class of this object does
* not implement the interface {@code Cloneable}, then a
* {@code CloneNotSupportedException} is thrown. Note that all arrays
* are considered to implement the interface {@code Cloneable} and that
* the return type of the {@code clone} method of an array type {@code T[]}
* is {@code T[]} where T is any reference or primitive type.
* Otherwise, this method creates a new instance of the class of this
* object and initializes all its fields with exactly the contents of
* the corresponding fields of this object, as if by assignment; the
* contents of the fields are not themselves cloned. Thus, this method
* performs a "shallow copy" of this object, not a "deep copy" operation.
*
* The class {@code Object} does not itself implement the interface
* {@code Cloneable}, so calling the {@code clone} method on an object
* whose class is {@code Object} will result in throwing an
* exception at run time.
*
* @return a clone of this instance.
* @throws CloneNotSupportedException if the object's class does not
* support the {@code Cloneable} interface. Subclasses
* that override the {@code clone} method can also
* throw this exception to indicate that an instance cannot
* be cloned.
* @see Cloneable
*/
@Override
public Object clone() {
try {
Loggable rtn = ((Loggable) super.clone());
rtn.BASE = new Base();
rtn.BASE.setID(_generateID());
rtn.BASE.setName(BASE.getName());
return rtn;
} catch (CloneNotSupportedException e) {
return null;
}
}
@Override
public String toString() {
return BASE.toString();
}
public class Base {
protected String id = null;
protected String name = null;
public Base() {
}
public String getID() {
return id;
}
public String getName() {
return name;
}
private void setID(String id) {
this.id = id;
}
private void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "id='" + getID() + '\''
+ ", name='" + getName() + '\'';
}
}
}
| mit |
dzeban/java-exercises | DateFormat.java | 186 | import java.util.Date;
class DateFormat
{
public static void main (String [] args)
{
String s;
s = String.format("%tA %<tB %<td %<tY", new Date());
System.out.println(s);
}
}
| mit |
flightstats/learning | algorithms/src/main/java/com/flightstats/analytics/examples/WineQualityExample.java | 6378 | package com.flightstats.analytics.examples;
import com.flightstats.analytics.tree.Item;
import com.flightstats.analytics.tree.LabeledItem;
import com.flightstats.analytics.tree.Splitter;
import com.flightstats.analytics.tree.decision.RandomForestPersister;
import com.flightstats.analytics.tree.regression.RegressionRandomForest;
import com.flightstats.analytics.tree.regression.RegressionRandomForestTrainer;
import com.flightstats.analytics.tree.regression.RegressionTreeTrainer;
import com.flightstats.analytics.tree.regression.TrainingResults;
import lombok.SneakyThrows;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import static java.util.stream.Collectors.toList;
/**
* RegressionRandomForest example, using the wine quality dataset from : http://archive.ics.uci.edu/ml/datasets/Wine+Quality
*/
public class WineQualityExample {
public static void main(String[] args) throws IOException {
Path dataFile = Paths.get("algorithms/testdata/wine-quality/winequality-white.csv");
List<String> attributes = readAttributes(dataFile);
System.out.println("attributes = " + attributes);
List<LabeledItem<Double>> data = loadData(dataFile, attributes);
int totalNumberOfItems = data.size();
int numberOfTestItems = totalNumberOfItems / 3;
List<LabeledItem<Double>> testSet = data.stream().limit(numberOfTestItems).collect(toList());
List<LabeledItem<Double>> trainingSet = data.stream().skip(numberOfTestItems).collect(toList());
double average = data.stream().mapToDouble(LabeledItem::getLabel).average().getAsDouble();
System.out.println("average value = " + average);
RegressionRandomForest forest = train(attributes, trainingSet);
//an example of how to persist the model
Path modelFile = constructModelFile();
saveModel(forest, modelFile);
RegressionRandomForest loadedForest = loadModel(modelFile);
test(testSet, average, loadedForest);
}
@SneakyThrows
private static Path constructModelFile() {
Path modelDirectory = Paths.get("models");
if (!Files.isDirectory(modelDirectory)) {
Files.createDirectory(modelDirectory);
}
return modelDirectory.resolve("winequality.rf.model.gz");
}
@SneakyThrows
private static List<LabeledItem<Double>> loadData(Path dataFile, List<String> attributes) {
List<LabeledItem<Double>> data = Files.lines(dataFile).skip(1).map(line -> {
String[] pieces = line.split(";");
Map<String, Double> values = new HashMap<>(pieces.length);
for (int i = 0; i < pieces.length - 1; i++) {
String piece = pieces[i];
values.put(attributes.get(i), Double.parseDouble(piece));
}
return new LabeledItem<>(new Item("dummy", new HashMap<>(), values), Double.parseDouble(pieces[pieces.length - 1]));
}).collect(toList());
Collections.shuffle(data);
return data;
}
@SneakyThrows
private static List<String> readAttributes(Path dataFile) {
String headerRow = Files.lines(dataFile).findFirst().get();
List<String> headers = Arrays.stream(headerRow.split(";")).map(s -> s.replaceAll("\"", "")).collect(toList());
return headers.stream().limit(headers.size() - 1).collect(toList());
}
private static RegressionRandomForest train(List<String> attributes, List<LabeledItem<Double>> trainingSet) {
RegressionRandomForestTrainer trainer = new RegressionRandomForestTrainer(new RegressionTreeTrainer(new Splitter<>()));
TrainingResults trainingResults = trainer.train("white wine", 100, trainingSet, attributes);
double outOfBagError = trainingResults.calculateOutOfBagError();
System.out.println("\noutOfBagError = " + outOfBagError);
return trainingResults.getForest();
}
@SneakyThrows
private static RegressionRandomForest loadModel(Path modelFile) {
RegressionRandomForest loadedForest;
try (InputStream modelReader = new GZIPInputStream(Files.newInputStream(modelFile))) {
loadedForest = new RandomForestPersister().loadRegression(modelReader);
}
return loadedForest;
}
@SneakyThrows
private static void saveModel(RegressionRandomForest forest, Path modelFile) {
try (OutputStream modelWriter = new GZIPOutputStream(Files.newOutputStream(modelFile))) {
new RandomForestPersister().save(forest, modelWriter);
}
}
private static void test(List<LabeledItem<Double>> testSet, double average, RegressionRandomForest forest) {
AtomicInteger closeCount = new AtomicInteger(0);
double error = Math.sqrt(testSet.stream().map(i -> {
Double evaluation = forest.evaluate(i.getItem());
// System.out.println("eval:" + evaluation + " label: " + i.getLabel() + " i = " + i);
// System.out.printf("%s\t%s%n", i.getLabel(), evaluation);
double difference = evaluation - i.getLabel();
int roundedResult = (int) Math.round(evaluation);
if (roundedResult == (int) (double) i.getLabel()) {
closeCount.incrementAndGet();
}
return Math.pow(difference, 2);
}).mapToDouble(d -> d).sum()) / testSet.size();
System.out.println("test set error = " + error);
double meanGuessError = Math.sqrt(testSet.stream().map(i -> {
Double evaluation = average;
return Math.pow(evaluation - i.getLabel(), 2);
}).mapToDouble(d -> d).sum()) / testSet.size();
System.out.println("meanGuessError = " + meanGuessError);
System.out.println("% within +/- 1/2 : " + (((double) closeCount.get()) / testSet.size()));
}
public static <T> T time(Supplier<T> supplier) {
long start = System.currentTimeMillis();
T t = supplier.get();
long end = System.currentTimeMillis();
System.out.println("time = " + (end - start));
return t;
}
}
| mit |
Backendless/Android-SDK | src/com/backendless/persistence/PagedQueryBuilder.java | 1691 | package com.backendless.persistence;
import com.backendless.exceptions.ExceptionMessage;
class PagedQueryBuilder<Builder>
{
private int pageSize;
private int offset;
private Builder builder;
PagedQueryBuilder( Builder builder )
{
pageSize = BackendlessDataQuery.DEFAULT_PAGE_SIZE;
offset = BackendlessDataQuery.DEFAULT_OFFSET;
this.builder = builder;
}
Builder setPageSize( int pageSize )
{
validatePageSize( pageSize );
this.pageSize = pageSize;
return builder;
}
Builder setOffset( int offset )
{
validateOffset( offset );
this.offset = offset;
return builder;
}
/**
* Updates offset to point at next data page by adding pageSize.
*/
Builder prepareNextPage()
{
int offset = this.offset + pageSize;
validateOffset( offset );
this.offset = offset;
return builder;
}
/**
* Updates offset to point at previous data page by subtracting pageSize.
*/
Builder preparePreviousPage()
{
int offset = this.offset - pageSize;
validateOffset( offset );
this.offset = offset;
return builder;
}
BackendlessDataQuery build()
{
validateOffset( offset );
validatePageSize( pageSize );
BackendlessDataQuery dataQuery = new BackendlessDataQuery();
dataQuery.setPageSize( pageSize );
dataQuery.setOffset( offset );
return dataQuery;
}
private void validateOffset( int offset )
{
if( offset < 0 )
throw new IllegalArgumentException( ExceptionMessage.WRONG_OFFSET );
}
private void validatePageSize( int pageSize )
{
if( pageSize <= 0 )
throw new IllegalArgumentException( ExceptionMessage.WRONG_PAGE_SIZE );
}
}
| mit |
edljk/Mosek.jl | deps/src/mosek/7/tools/examples/java/qcqo1.java | 6022 | package com.mosek.example;
/*
Copyright: Copyright (c) MOSEK ApS, Denmark. All rights reserved.
File: qcqo1.java
Purpose: Demonstrate how to solve a quadratic
optimization problem using the MOSEK API.
minimize x0^2 + 0.1 x1^2 + x2^2 - x0 x2 - x1
s.t 1 <= x0 + x1 + x2 - x0^2 - x1^2 - 0.1 x2^2 + 0.2 x0 x2
x >= 0
*/
public class qcqo1
{
static final int numcon = 1; /* Number of constraints. */
static final int numvar = 3; /* Number of variables. */
static final int NUMANZ = 3; /* Number of numzeros in A. */
static final int NUMQNZ = 4; /* Number of nonzeros in Q. */
public static void main (String[] args)
{
// Since the value infinity is never used, we define
// 'infinity' symbolic purposes only
double infinity = 0;
double[] c = {0.0, -1.0, 0.0};
mosek.Env.boundkey[] bkc = {mosek.Env.boundkey.lo};
double[] blc = {1.0};
double[] buc = {infinity};
mosek.Env.boundkey[] bkx
= {mosek.Env.boundkey.lo,
mosek.Env.boundkey.lo,
mosek.Env.boundkey.lo};
double[] blx = {0.0,
0.0,
0.0};
double[] bux = {infinity,
infinity,
infinity};
int[][] asub = { {0}, {0}, {0} };
double[][] aval = { {1.0}, {1.0}, {1.0} };
double[] xx = new double[numvar];
mosek.Env
env = null;
mosek.Task
task = null;
try
{
env = new mosek.Env ();
task = new mosek.Task (env, numcon,numvar);
// Directs the log task stream to the user specified
// method task_msg_obj.stream
task.set_Stream(
mosek.Env.streamtype.log,
new mosek.Stream()
{ public void stream(String msg) { System.out.print(msg); }});
/* Give MOSEK an estimate of the size of the input data.
This is done to increase the speed of inputting data.
However, it is optional. */
/* Append 'numcon' empty constraints.
The constraints will initially have no bounds. */
task.appendcons(numcon);
/* Append 'numvar' variables.
The variables will initially be fixed at zero (x=0). */
task.appendvars(numvar);
for(int j=0; j<numvar; ++j)
{
/* Set the linear term c_j in the objective.*/
task.putcj(j,c[j]);
/* Set the bounds on variable j.
blx[j] <= x_j <= bux[j] */
task.putbound(mosek.Env.accmode.var,j,bkx[j],blx[j],bux[j]);
/* Input column j of A */
task.putacol(j, /* Variable (column) index.*/
asub[j], /* Row index of non-zeros in column j.*/
aval[j]); /* Non-zero Values of column j. */
}
/* Set the bounds on constraints.
for i=1, ...,numcon : blc[i] <= constraint i <= buc[i] */
for(int i=0; i<numcon; ++i)
task.putbound(mosek.Env.accmode.con,i,bkc[i],blc[i],buc[i]);
/*
* The lower triangular part of the Q
* matrix in the objective is specified.
*/
int[] qosubi = { 0, 1, 2, 2 };
int[] qosubj = { 0, 1, 0, 2 };
double[] qoval = { 2.0, 0.2, -1.0, 2.0 };
/* Input the Q for the objective. */
task.putqobj(qosubi,qosubj,qoval);
/*
* The lower triangular part of the Q^0
* matrix in the first constraint is specified.
* This corresponds to adding the term
* x0^2 - x1^2 - 0.1 x2^2 + 0.2 x0 x2
*/
int[] qsubi = {0, 1, 2, 2 };
int[] qsubj = {0, 1, 2, 0 };
double[] qval = {-2.0, -2.0, -0.2, 0.2};
/* put Q^0 in constraint with index 0. */
task.putqconk (0,
qsubi,
qsubj,
qval);
task.putobjsense(mosek.Env.objsense.minimize);
/* Solve the problem */
try
{
mosek.Env.rescode termcode = task.optimize();
}
catch (mosek.Warning e)
{
System.out.println (" Mosek warning:");
System.out.println (e.toString ());
}
// Print a summary containing information
// about the solution for debugging purposes
task.solutionsummary(mosek.Env.streamtype.msg);
mosek.Env.solsta solsta[] = new mosek.Env.solsta[1];
/* Get status information about the solution */
task.getsolsta(mosek.Env.soltype.itr,solsta);
task.getxx(mosek.Env.soltype.itr, // Interior solution.
xx);
switch(solsta[0])
{
case optimal:
case near_optimal:
System.out.println("Optimal primal solution\n");
for(int j = 0; j < numvar; ++j)
System.out.println ("x[" + j + "]:" + xx[j]);
break;
case dual_infeas_cer:
case prim_infeas_cer:
case near_dual_infeas_cer:
case near_prim_infeas_cer:
System.out.println("Primal or dual infeasibility.\n");
break;
case unknown:
System.out.println("Unknown solution status.\n");
break;
default:
System.out.println("Other solution status");
break;
}
}
catch (mosek.Exception e)
{
System.out.println ("An error/warning was encountered");
System.out.println (e.msg);
throw e;
}
if (task != null) task.dispose ();
if (env != null) env.dispose ();
} /* Main */
}
| mit |
InnovateUKGitHub/innovation-funding-service | common/ifs-resources/src/main/java/org/innovateuk/ifs/invite/builder/AssessorCreatedInvitePageResourceBuilder.java | 1310 | package org.innovateuk.ifs.invite.builder;
import org.innovateuk.ifs.commons.builder.PageResourceBuilder;
import org.innovateuk.ifs.invite.resource.AssessorCreatedInvitePageResource;
import org.innovateuk.ifs.invite.resource.AssessorCreatedInviteResource;
import java.util.List;
import java.util.function.BiConsumer;
import static java.util.Collections.emptyList;
public class AssessorCreatedInvitePageResourceBuilder
extends PageResourceBuilder<AssessorCreatedInvitePageResource, AssessorCreatedInvitePageResourceBuilder, AssessorCreatedInviteResource> {
public static AssessorCreatedInvitePageResourceBuilder newAssessorCreatedInvitePageResource() {
return new AssessorCreatedInvitePageResourceBuilder(emptyList());
}
public AssessorCreatedInvitePageResourceBuilder(List<BiConsumer<Integer, AssessorCreatedInvitePageResource>> newMultiActions) {
super(newMultiActions);
}
@Override
protected AssessorCreatedInvitePageResourceBuilder createNewBuilderWithActions(List<BiConsumer<Integer, AssessorCreatedInvitePageResource>> actions) {
return new AssessorCreatedInvitePageResourceBuilder(actions);
}
@Override
protected AssessorCreatedInvitePageResource createInitial() {
return new AssessorCreatedInvitePageResource();
}
} | mit |
mickleness/pumpernickel | src/main/java/com/pump/debug/AWTMonitor.java | 8118 | /**
* This software is released as part of the Pumpernickel project.
*
* All com.pump resources in the Pumpernickel project are distributed under the
* MIT License:
* https://raw.githubusercontent.com/mickleness/pumpernickel/master/License.txt
*
* More information about the Pumpernickel project is available here:
* https://mickleness.github.io/pumpernickel/
*/
package com.pump.debug;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.swing.SwingUtilities;
/**
* This class monitors the event dispatch thread.
* <P>
* After 2 seconds if the thread is unresponsive, a list of stack traces is
* printed to the console.
* <P>
* After 15 seconds if the thread is unresponsive, the
* <code>panicListener</code> is notified (if it is non-null). By default the
* <code>panicListener</code> is a {@link com.pump.debug.PanicDialogPrompt}, but
* you can nullify this value or create your own
* {@link com.pump.debug.AWTPanicListener}.
*
* @see <a
* href="https://javagraphics.blogspot.com/2008/06/event-dispatch-thread-responding-to.html">Event
* Dispatch Thread: Responding to Deadlocks</a>
*/
public class AWTMonitor {
static class AWTRunnable implements Runnable {
boolean flag;
public void run() {
flag = true;
}
}
/** The AWTPanicListeners. */
private final static List<AWTPanicListener> panicListeners = new ArrayList<AWTPanicListener>();
/**
* We keep one private copy around, but it isn't added until the install()
* method.
*/
private final static PanicDialogPrompt defaultPrompt = new PanicDialogPrompt();
/**
* Adds a <code>AWTPanicListener</code> to be notified when the EDT appears
* blocked.
*
* @param l
* the listener to add.
*/
public static void addPanicListener(AWTPanicListener l) {
if (panicListeners.contains(l) == true)
return;
panicListeners.add(l);
}
/**
* Removes a <code>AWTPanicListener</code>.
*
* @param l
* the listener to remove.
*/
public static void removePanicListener(AWTPanicListener l) {
panicListeners.remove(l);
}
private static Thread awtMonitorThread;
/**
* This installs a thread that monitors the AWT thread.
* <P>
* If the AWT thread is unresponsive for over 2 seconds, then thread stacks
* are dumped to the console. If the event dispatch thread is unresponsive
* for over 15 seconds, the <code>panicListener</code> (if non-null) is
* notified.
*
* @param applicationName
* the name of the application to present to the user
* @param addPanicDialogPrompt
* if true then the <code>PanicDialogPrompt</code> is added.
*/
public static void installAWTListener(final String applicationName,
boolean addPanicDialogPrompt) {
installAWTListener(applicationName, 2000, 15000, addPanicDialogPrompt);
}
/**
* Installs a thread that monitors the AWT thread.
*
* @param applicationName
* the name of the application to present to the user
* @param stackTraceDelay
* the delay before stack traces are printed to the console
* @param panicListenerDelay
* the delay before invoking the PanicListener.
* @param addPanicDialogPrompt
* if true then the <code>PanicDialogPrompt</code> is added.
*/
public synchronized static void installAWTListener(String applicationName,
long stackTraceDelay, final long panicListenerDelay,
boolean addPanicDialogPrompt) {
if (addPanicDialogPrompt)
addPanicListener(defaultPrompt);
if (awtMonitorThread == null || awtMonitorThread.isAlive() == false) {
awtMonitorThread = createAWTMonitorThread(applicationName,
stackTraceDelay, panicListenerDelay,
"AWT Listener (Debug Tool)", System.err);
awtMonitorThread.start();
}
}
/**
* Create a Thread that monitors the AWT thread.
* <p>
* Generally this method is not recommended for external invocation, but the
* PumpernickelShowcaseApp's demo calls this.
*/
public static Thread createAWTMonitorThread(final String applicationName,
final long stackTraceDelay, final long panicListenerDelay,
final String threadName, final PrintStream dest) {
return new Thread(threadName) {
AWTRunnable awtRunnable = new AWTRunnable();
@Override
public void run() {
/**
* There are two actions that can happen here: 1. "reporting"
* gives a dump stack to the console. 2. "panicking" invokes the
* AWTPanicListener.
*
* An extra half second delay is added before either action. If
* a computer was put to sleep, then immediately after waking
* either action might be triggered: a half-second delay will
* give the EDT a chance to catch up and prove there's not
* really a problem.
*/
while (true) {
awtRunnable.flag = false;
try {
SwingUtilities.invokeLater(awtRunnable);
} catch (RuntimeException e) {
// this can happen super early in construction:
// we can get a NPE from the code:
// Toolkit.getEventQueue().postEvent(
// new InvocationEvent(Toolkit.getDefaultToolkit(),
// runnable));
awtRunnable.flag = true;
}
long start = System.currentTimeMillis();
if (!awtRunnable.flag) {
boolean reportedToConsole = false;
boolean panicked = false;
if (awtRunnable.flag == false) {
long reportNeeded = -1;
long panicNeeded = -1;
while (awtRunnable.flag == false) {
idle();
long current = System.currentTimeMillis();
if (reportedToConsole == false
&& current - start > stackTraceDelay) {
if (reportNeeded == -1) {
reportNeeded = System
.currentTimeMillis();
} else if (current - reportNeeded > 500) {
dumpThreads(
"The AWT thread was unresponsive for "
+ stackTraceDelay
/ 1000
+ " seconds. Here is a stack trace from all available threads:",
dest);
reportedToConsole = true;
}
}
if (panicListeners.size() > 0
&& panicked == false
&& current - start > panicListenerDelay) {
if (panicNeeded == -1) {
panicNeeded = System
.currentTimeMillis();
} else if (current - panicNeeded > 500) {
panicked = true;
Thread panicThread = new Thread(
"Panic Thread") {
@Override
public void run() {
for (int a = 0; a < panicListeners
.size(); a++) {
AWTPanicListener panicListener = panicListeners
.get(a);
try {
panicListener
.AWTPanic(applicationName);
} catch (Exception e) {
e.printStackTrace();
}
}
}
};
panicThread.start();
}
}
}
}
}
idle();
while (System.currentTimeMillis() - start < stackTraceDelay / 10) {
idle();
}
}
}
private void idle() {
try {
Thread.sleep(200);
} catch (Exception e) {
Thread.yield();
}
}
};
}
/**
* This effectively calls Thread.dumpStack() for every available thread.
*
* @param headerText
* text to print that precedes the stack traces.
* @param dest
* the PrintStream to write data to.
*/
public static void dumpThreads(String headerText, PrintStream dest) {
try {
Map<Thread, StackTraceElement[]> map = Thread.getAllStackTraces();
Iterator<Thread> i = map.keySet().iterator();
dest.println(headerText);
while (i.hasNext()) {
Thread key = i.next();
StackTraceElement[] array = map.get(key);
String id = "";
try {
id = " (id = " + key.getId() + ")";
} catch (Throwable e) {
} // we ignore this
dest.println(key.getName() + id);
for (int a = 0; a < array.length; a++) {
dest.println("\t" + array[a]);
}
}
} catch (Throwable e1) {
e1.printStackTrace();
}
}
} | mit |
iutils/iutils-admin | src/main/java/cn/iutils/common/service/CrudService.java | 2077 | package cn.iutils.common.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import cn.iutils.common.BaseEntity;
import cn.iutils.common.ICrudDao;
import cn.iutils.common.Page;
/**
* Service基类
*
* @author cc
*/
@Transactional(readOnly = true)
public abstract class CrudService<D extends ICrudDao<T>, T extends BaseEntity<T>>
extends BaseService {
/**
* 持久层对象
*/
@Autowired
protected D dao;
/**
* 获取单条数据
*
* @param id
* @return
*/
public T get(String id) {
return dao.get(id);
}
/**
* 获取单条数据
*
* @param entity
* @return
*/
public T get(T entity) {
return dao.get(entity);
}
/**
* 查询列表数据
*
* @param entity
* @return
*/
public List<T> findList(T entity) {
return dao.findList(entity);
}
/**
* 查询总数
*
* @return
*/
public int count(Page<T> page) {
return dao.count(page);
}
/**
* 查询分页数据
*
* @param page
* @return
*/
public List<T> findPage(Page<T> page) {
page.setTotal(dao.count(page));
return dao.findPage(page);
}
/**
* 保存数据(插入或更新)
*
* @param entity
*/
@Transactional(readOnly = false)
public int save(T entity) {
if (entity.getIsNewId()) {
entity.preInsert();
return dao.insert(entity);
} else {
entity.preUpdate();
return dao.update(entity);
}
}
/**
* 删除数据
*
* @param entity
*/
@Transactional(readOnly = false)
public int delete(T entity) {
return dao.delete(entity);
}
/**
* 删除数据
*
* @param id
*/
@Transactional(readOnly = false)
public int delete(String id) {
return dao.delete(id);
}
}
| mit |
sussexcoursedata/course_data_project | src/main/java/uk/co/xcri/CourseDirectoryID.java | 1184 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2012.06.29 at 10:15:17 AM BST
//
package uk.co.xcri;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
import org.purl.dc.elements._1.SimpleLiteral;
/**
* Validation of Course Directory ID. See Next Step Course Directory
*
* <p>Java class for courseDirectoryID complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="courseDirectoryID">
* <simpleContent>
* <restriction base="<http://purl.org/dc/elements/1.1/>SimpleLiteral">
* </restriction>
* </simpleContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "courseDirectoryID")
public class CourseDirectoryID
extends SimpleLiteral
{
}
| mit |
zhoujiagen/giant-data-analysis | data-management-infrastructure/infrastructure-commons/src/test/java/com/spike/giantdataanalysis/commons/io/nio/channel/TestMappedByteBufferModes.java | 2803 | package com.spike.giantdataanalysis.commons.io.nio.channel;
import java.io.File;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
/**
* MapMode of MappedByteBuffer
* @author zhoujiagen
*/
public class TestMappedByteBufferModes {
public static void main(String[] args) throws Exception {
File tempFile = File.createTempFile("mmaptest", null);
RandomAccessFile raf = new RandomAccessFile(tempFile, "rw");
FileChannel fc = raf.getChannel();
ByteBuffer bb = ByteBuffer.allocate(100);
bb.put("This is the file content".getBytes());
bb.flip();
fc.write(bb, 0);
bb.clear();
bb.put("This is more file content".getBytes());
bb.flip();
fc.write(bb, 8 * 1024);
long fileSize = fc.size();
MappedByteBuffer ro = fc.map(MapMode.READ_ONLY, 0, fileSize);
MappedByteBuffer rw = fc.map(MapMode.READ_WRITE, 0, fileSize);
MappedByteBuffer cow = fc.map(MapMode.PRIVATE, 0, fileSize);// copy-on-write
System.out.println("Begin");
showBuffer(ro, rw, cow);
System.out.println("Change to COW buffer");
cow.position(8);
cow.put("COW".getBytes());
showBuffer(ro, rw, cow);
System.out.println("Change to R/W buffer");
rw.position(9);
rw.put(" R/W ".getBytes());
rw.position(8194);
rw.put(" R/W ".getBytes());
rw.force();
showBuffer(ro, rw, cow);
System.out.println("Write on channel");
bb.clear();
bb.put("Channel write ".getBytes());
bb.flip();
fc.write(bb, 0);
bb.rewind();
fc.write(bb, 8202);
showBuffer(ro, rw, cow);
System.out.println("Second hange to COW buffer");
cow.position(8207);
cow.put(" COW2 ".getBytes());
showBuffer(ro, rw, cow);
System.out.println("Second change to R/W buffer");
rw.position(0);
rw.put(" R/W2 ".getBytes());
rw.position(8210);
rw.put(" R/W2 ".getBytes());
rw.force();
showBuffer(ro, rw, cow);
// clean up
fc.close();
raf.close();
tempFile.delete();
}
private static void showBuffer(ByteBuffer ro, ByteBuffer rw, ByteBuffer cow) {
dumpBuffer("R/O", ro);
dumpBuffer("R/W", rw);
dumpBuffer("COW", cow);
System.out.println();
}
private static void dumpBuffer(String prefix, ByteBuffer buffer) {
System.out.print(prefix + ": '");
int nulls = 0;
int limit = buffer.limit();
for (int i = 0; i < limit; i++) {
char c = (char) buffer.get(i);// absolute position
if (c == '\u0000') {
nulls++;
continue;
}
if (nulls != 0) {
System.out.print("|[" + nulls + " nulls]|");
nulls = 0;
}
System.out.print(c);
}
System.out.println("'");
}
}
| mit |
asamasoma/rltut | src/main/rltut/screens/QuaffScreen.java | 495 | package rltut.screens;
import rltut.Creature;
import rltut.Item;
public class QuaffScreen extends InventoryBasedScreen {
public QuaffScreen(Creature player) {
super(player);
}
@Override
protected String getVerb() {
return "quaff";
}
@Override
protected boolean isAcceptable(Item item) {
return item.quaffEffect() != null;
}
@Override
protected Screen use(Item item) {
player.quaff(item);
return null;
}
}
| mit |
soboapps/todos | src/com/soboapps/todos/GetToDoImage.java | 3455 | package com.soboapps.todos;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Gravity;
import android.widget.Toast;
public class GetToDoImage extends Activity {
static int random = (int)Math.ceil(Math.random()*100000000);
private static String fname = Integer.toString(random);
private static final int SELECT_PICTURE = 1;
private static String selectedImagePath;
private static String ExternalStorageDirectoryPath = Environment.getExternalStorageDirectory().getAbsolutePath();
private static String targetPath = ExternalStorageDirectoryPath + "/DCIM/ToDo/.nomedia/";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
try {
copyFile(selectedImagePath, targetPath + fname + ".jpg");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
// Copy the file the Hidden Folder
public void copyFile(String selectedImagePath2, String string) throws IOException {
InputStream in = new FileInputStream(selectedImagePath2);
OutputStream out = new FileOutputStream(string);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
Toast customToast = new Toast(getBaseContext());
customToast = Toast.makeText(getBaseContext(), "Image Transferred", Toast.LENGTH_LONG);
customToast.setGravity(Gravity.CENTER|Gravity.CENTER, 0, 0);
customToast.show();
//Restart the Hidden Gallery
StartGallery();
//Delete the File from Main Gallery
deleteFile();
}
// Restart Hidden Gallery
private void StartGallery() {
Intent intent = new Intent(this, GalleryActivity.class);
startActivity(intent);
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
//Delete File from Main Gallery
private void deleteFile() {
File fdelete = new File(selectedImagePath);
fdelete.delete();
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
}
} | mit |
navalev/azure-sdk-for-java | sdk/cosmos/microsoft-azure-cosmos-examples/src/test/java/com/azure/data/cosmos/rx/examples/DatabaseCRUDAsyncAPITest.java | 12343 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.data.cosmos.rx.examples;
import com.azure.data.cosmos.internal.AsyncDocumentClient;
import com.azure.data.cosmos.ConnectionMode;
import com.azure.data.cosmos.ConnectionPolicy;
import com.azure.data.cosmos.ConsistencyLevel;
import com.azure.data.cosmos.CosmosClientException;
import com.azure.data.cosmos.internal.Database;
import com.azure.data.cosmos.DocumentClientTest;
import com.azure.data.cosmos.FeedResponse;
import com.azure.data.cosmos.internal.ResourceResponse;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import reactor.core.publisher.Flux;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.function.Consumer;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.greaterThan;
/**
* This integration test class demonstrates how to use Async API to create,
* delete, replace, and update Databases.
* <p>
* NOTE: you can use rxJava based async api with java8 lambda expression. Use of
* rxJava based async APIs with java8 lambda expressions is much prettier.
* <p>
* You can also use the async API without java8 lambda expression support.
* <p>
* For example
* <ul>
* <li>{@link #createDatabase_Async()} demonstrates how to use async api
* with java8 lambda expression.
*
* <li>{@link #createDatabase_Async_withoutLambda()} demonstrates how to
* do the same thing without lambda expression.
* </ul>
* <p>
* Also if you need to work with Future or CompletableFuture it is possible to
* transform a flux to CompletableFuture. Please see
* {@link #transformObservableToCompletableFuture()}
*/
public class DatabaseCRUDAsyncAPITest extends DocumentClientTest {
private final static int TIMEOUT = 60000;
private final List<String> databaseIds = new ArrayList<>();
private AsyncDocumentClient client;
@BeforeClass(groups = "samples", timeOut = TIMEOUT)
public void setUp() {
ConnectionPolicy connectionPolicy = new ConnectionPolicy().connectionMode(ConnectionMode.DIRECT);
this.clientBuilder()
.withServiceEndpoint(TestConfigurations.HOST)
.withMasterKeyOrResourceToken(TestConfigurations.MASTER_KEY)
.withConnectionPolicy(connectionPolicy)
.withConsistencyLevel(ConsistencyLevel.SESSION);
this.client = this.clientBuilder().build();
}
private Database getDatabaseDefinition() {
Database databaseDefinition = new Database();
databaseDefinition.id(Utils.generateDatabaseId());
databaseIds.add(databaseDefinition.id());
return databaseDefinition;
}
@AfterClass(groups = "samples", timeOut = TIMEOUT)
public void shutdown() {
for (String id : databaseIds) {
Utils.safeClean(client, id);
}
Utils.safeClose(client);
}
/**
* CREATE a database using async api.
* This test uses java8 lambda expression.
* See testCreateDatabase_Async_withoutLambda for usage without lambda.
*/
@Test(groups = "samples", timeOut = TIMEOUT)
public void createDatabase_Async() throws Exception {
Flux<ResourceResponse<Database>> createDatabaseObservable = client.createDatabase(getDatabaseDefinition(),
null);
final CountDownLatch completionLatch = new CountDownLatch(1);
createDatabaseObservable.single() // We know there is only single result
.subscribe(databaseResourceResponse -> {
System.out.println(databaseResourceResponse.getActivityId());
completionLatch.countDown();
}, error -> {
System.err.println(
"an error occurred while creating the database: actual cause: " + error.getMessage());
completionLatch.countDown();
});
// Wait till database creation completes
completionLatch.await();
}
/**
* CREATE a database using async api, without java8 lambda expressions
*/
@Test(groups = "samples", timeOut = TIMEOUT)
public void createDatabase_Async_withoutLambda() throws Exception {
Flux<ResourceResponse<Database>> createDatabaseObservable = client.createDatabase(getDatabaseDefinition(),
null);
final CountDownLatch completionLatch = new CountDownLatch(1);
Consumer<ResourceResponse<Database>> onDatabaseCreationAction = new Consumer<ResourceResponse<Database>>() {
@Override
public void accept(ResourceResponse<Database> resourceResponse) {
// Database is created
System.out.println(resourceResponse.getActivityId());
completionLatch.countDown();
}
};
Consumer<Throwable> onError = new Consumer<Throwable>() {
@Override
public void accept(Throwable error) {
System.err
.println("an error occurred while creating the database: actual cause: " + error.getMessage());
completionLatch.countDown();
}
};
createDatabaseObservable.single() // We know there is only a single event
.subscribe(onDatabaseCreationAction, onError);
// Wait till database creation completes
completionLatch.await();
}
/**
* CREATE a database in a blocking manner
*/
@Test(groups = "samples", timeOut = TIMEOUT)
public void createDatabase_toBlocking() {
Flux<ResourceResponse<Database>> createDatabaseObservable = client.createDatabase(getDatabaseDefinition(),
null);
// toBlocking() converts to a blocking observable.
// single() gets the only result.
createDatabaseObservable.single().block();
}
/**
* Attempt to create a database which already exists
* - First create a database
* - Using the async api generate an async database creation observable
* - Converts the Observable to blocking using Observable.toBlocking() api
* - Catch already exist failure (409)
*/
@Test(groups = "samples", timeOut = TIMEOUT)
public void createDatabase_toBlocking_DatabaseAlreadyExists_Fails() {
Database databaseDefinition = getDatabaseDefinition();
client.createDatabase(databaseDefinition, null).single().block();
// CREATE the database for test.
Flux<ResourceResponse<Database>> databaseForTestObservable = client
.createDatabase(databaseDefinition, null);
try {
databaseForTestObservable.single() // Single
.block(); // Blocks to get the result
assertThat("Should not reach here", false);
} catch (Exception e) {
assertThat("Database already exists.", ((CosmosClientException) e.getCause()).statusCode(),
equalTo(409));
}
}
/**
* You can convert a Flux to a CompletableFuture.
*/
@Test(groups = "samples", timeOut = TIMEOUT)
public void transformObservableToCompletableFuture() throws Exception {
Flux<ResourceResponse<Database>> createDatabaseObservable = client.createDatabase(getDatabaseDefinition(),
null);
CompletableFuture<ResourceResponse<Database>> future = createDatabaseObservable.single().toFuture();
ResourceResponse<Database> rrd = future.get();
assertThat(rrd.getRequestCharge(), greaterThan((double) 0));
System.out.print(rrd.getRequestCharge());
}
/**
* READ a Database in an Async manner
*/
@Test(groups = "samples", timeOut = TIMEOUT)
public void createAndReadDatabase() throws Exception {
// CREATE a database
Database database = client.createDatabase(getDatabaseDefinition(), null).single().block().getResource();
// READ the created database using async api
Flux<ResourceResponse<Database>> readDatabaseObservable = client.readDatabase("dbs/" + database.id(),
null);
final CountDownLatch completionLatch = new CountDownLatch(1);
readDatabaseObservable.single() // We know there is only single result
.subscribe(databaseResourceResponse -> {
System.out.println(databaseResourceResponse.getActivityId());
completionLatch.countDown();
}, error -> {
System.err.println(
"an error occurred while reading the database: actual cause: " + error.getMessage());
completionLatch.countDown();
});
// Wait till read database completes
completionLatch.await();
}
/**
* DELETE a Database in an Async manner
*/
@Test(groups = "samples", timeOut = TIMEOUT)
public void createAndDeleteDatabase() throws Exception {
// CREATE a database
Database database = client.createDatabase(getDatabaseDefinition(), null).single().block().getResource();
// DELETE the created database using async api
Flux<ResourceResponse<Database>> deleteDatabaseObservable = client
.deleteDatabase("dbs/" + database.id(), null);
final CountDownLatch completionLatch = new CountDownLatch(1);
deleteDatabaseObservable.single() // We know there is only single result
.subscribe(databaseResourceResponse -> {
System.out.println(databaseResourceResponse.getActivityId());
completionLatch.countDown();
}, error -> {
System.err.println(
"an error occurred while deleting the database: actual cause: " + error.getMessage());
completionLatch.countDown();
});
// Wait till database deletion completes
completionLatch.await();
}
/**
* Query a Database in an Async manner
*/
@Test(groups = "samples", timeOut = TIMEOUT)
public void databaseCreateAndQuery() throws Exception {
// CREATE a database
Database databaseDefinition = getDatabaseDefinition();
client.createDatabase(databaseDefinition, null).single().block().getResource();
// Query the created database using async api
Flux<FeedResponse<Database>> queryDatabaseObservable = client
.queryDatabases(String.format("SELECT * FROM r where r.id = '%s'", databaseDefinition.id()), null);
final CountDownLatch completionLatch = new CountDownLatch(1);
queryDatabaseObservable.collectList().subscribe(databaseFeedResponseList -> {
// toList() should return a list of size 1
assertThat(databaseFeedResponseList.size(), equalTo(1));
// First element of the list should have only 1 result
FeedResponse<Database> databaseFeedResponse = databaseFeedResponseList.get(0);
assertThat(databaseFeedResponse.results().size(), equalTo(1));
// This database should have the same id as the one we created
Database foundDatabase = databaseFeedResponse.results().get(0);
assertThat(foundDatabase.id(), equalTo(databaseDefinition.id()));
System.out.println(databaseFeedResponse.activityId());
completionLatch.countDown();
}, error -> {
System.err.println("an error occurred while querying the database: actual cause: " + error.getMessage());
completionLatch.countDown();
});
// Wait till database query completes
completionLatch.await();
}
}
| mit |
satokazuma/caseframe | caseframe-gen/src/main/migration/nlp/entity/CaseSlot.java | 1804 | package jp.ac.titech.cs.se.nlp.entity;
import java.util.ArrayList;
import java.util.List;
import jp.ac.titech.cs.se.nlp.entity.logic.ConceptLogicalFormula;
/**
* 格スロット
*
* @author hayashi
* @author rtakizawa
*/
public class CaseSlot {
/**
* 表層格の種類("が", "を", など)
* 表層格一覧はEDR辞書マニュアル(JCC/MANUAL/Japanese/SJIS/EDR_J07A)に記載
* (たぶんこれ)
*/
private String surfaceCase;
/**
* 格の概念の見出し
*/
private String caption;
/**
* このスロットに適合する概念の集合を表す論理式
*/
private ConceptLogicalFormula formula;
@SuppressWarnings("unchecked")
public CaseSlot(List<Object> caseExp) {
List<Object> conceptList;
surfaceCase = (String) caseExp.get(0);
if (caseExp.get(1) instanceof List) {
conceptList = (List<Object>) caseExp.get(1);
} else {
// 概念IDのみの場合リストでくるむ
conceptList = new ArrayList<Object>();
conceptList.add(caseExp.get(1));
}
caption = (String) caseExp.get(2);
formula = ConceptLogicalFormula.parse(conceptList);
}
/**
* この格スロットにconceptIdの概念が入れるかどうか
* @param conceptId
* @return
*/
public boolean accept(int conceptId) {
return formula.eval(conceptId);
}
// とりあえず
@Override
public String toString() {
return "<" + caption + ">" + surfaceCase;
}
public String getSurfaceCase() {
return surfaceCase;
}
public String getCaption() {
return caption;
}
public String getFormulaString() {
return formula.toString();
}
} | mit |
pshynin/JavaRushTasks | 2.JavaCore/src/com/javarush/task/task15/task1530/LatteMaker.java | 427 | package com.javarush.task.task15.task1530;
public class LatteMaker extends DrinkMaker {
@Override
void getRightCup() {
System.out.println("Берем чашку для латте");
}
@Override
void putIngredient() {
System.out.println("Делаем кофе");
}
@Override
void pour() {
System.out.println("Заливаем молоком с пенкой");
}
}
| mit |
AllTheDucks/restful-stripes | src/test/java/com/alltheducks/stripes/rest/RestfulExceptionHandlerTest.java | 3891 | package com.alltheducks.stripes.rest;
import com.alltheducks.stripes.rest.actions.RestfulExceptionHandlerActionBeanTestAction;
import com.alltheducks.stripes.rest.actions.RestfulExceptionHandlerRestfulActionBeanTestAction;
import net.sourceforge.stripes.action.ActionBean;
import net.sourceforge.stripes.controller.DispatcherServlet;
import net.sourceforge.stripes.controller.StripesFilter;
import net.sourceforge.stripes.mock.MockRoundtrip;
import net.sourceforge.stripes.mock.MockServletContext;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
public class RestfulExceptionHandlerTest {
@Test
public void testRestfulException_withRestfulActionBean() throws Exception {
testAction(RestfulExceptionHandlerRestfulActionBeanTestAction.class, "throwRestfulException", "{\"message\":\"Argh\",\"exceptionClass\":\"RestfulException\",\"canonicalExceptionClass\":\"com.alltheducks.stripes.rest.RestfulException\"}", 500);
}
@Test
public void testException_withRestfulActionBean() throws Exception {
testAction(RestfulExceptionHandlerRestfulActionBeanTestAction.class, "throwException", "{\"message\":\"Argh\",\"exceptionClass\":\"Exception\",\"canonicalExceptionClass\":\"java.lang.Exception\"}", 500);
}
@Test
public void testRestfulException501_withRestfulActionBean() throws Exception {
testAction(RestfulExceptionHandlerRestfulActionBeanTestAction.class, "throwRestfulException501", "{\"message\":\"Argh\",\"exceptionClass\":\"RestfulException\",\"canonicalExceptionClass\":\"com.alltheducks.stripes.rest.RestfulException\"}", 501);
}
@Test
public void testRestfulException_withActionBean() throws Exception {
testAction(RestfulExceptionHandlerActionBeanTestAction.class, "throwRestfulException", "{\"message\":\"Argh\",\"exceptionClass\":\"RestfulException\",\"canonicalExceptionClass\":\"com.alltheducks.stripes.rest.RestfulException\"}", 500);
}
@Test(expected = Exception.class)
public void testException_withActionBean() throws Exception {
final MockServletContext context = constructContext();
try {
MockRoundtrip mockRoundtrip = new MockRoundtrip(context, RestfulExceptionHandlerActionBeanTestAction.class);
mockRoundtrip.execute("throwException");
}
finally {
cleanUpContext(context);
}
}
private void testAction(Class<? extends ActionBean> bean, String action, String expectedOutput, int httpStatusCode) throws Exception {
final MockServletContext context = constructContext();
try {
MockRoundtrip mockRoundtrip = new MockRoundtrip(context, bean);
mockRoundtrip.execute(action);
assertEquals(expectedOutput, mockRoundtrip.getOutputString());
assertEquals(httpStatusCode, mockRoundtrip.getResponse().getStatus());
assertNull(mockRoundtrip.getDestination());
}
finally {
cleanUpContext(context);
}
}
public MockServletContext constructContext() {
MockServletContext context = new MockServletContext("test");
// Add the Stripes Filter
Map<String, String> filterParams = new HashMap<String, String>();
filterParams.put("ActionResolver.Packages", "com.alltheducks.stripes.rest.actions");
filterParams.put("ExceptionHandler.Class", "com.alltheducks.stripes.rest.RestfulExceptionHandler");
context.addFilter(StripesFilter.class, "StripesFilter", filterParams);
// Add the Stripes Dispatcher
context.setServlet(DispatcherServlet.class, "StripesDispatcher", null);
return context;
}
public void cleanUpContext(MockServletContext context) {
context.getFilters().get(0).destroy();
}
} | mit |
uhef/Oskari-Routing | service-datamodel/src/main/java/fi/nls/oskari/fe/gml/util/BoundingProperty.java | 71 | package fi.nls.oskari.fe.gml.util;
public class BoundingProperty {
}
| mit |
JEEventStore/JCommonDomain | multitenancy/src/main/java/org/jeecqrs/common/domain/model/multitenancy/MultiTenancyDomainEvent.java | 1400 | /*
* Copyright (c) 2014 Red Rainbow IT Solutions GmbH, Germany
*
* 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.jeecqrs.common.domain.model.multitenancy;
import org.jeecqrs.common.Identity;
import org.jeecqrs.common.domain.model.DomainEvent;
public interface MultiTenancyDomainEvent<T, TID extends Identity> extends DomainEvent<T>, MultiTenancy<TID> {
}
| mit |
olamedia/jogl-postprocessing | src/ru/olamedia/postprocessing/blenders/HardLight.java | 227 | package ru.olamedia.postprocessing.blenders;
import ru.olamedia.postprocessing.BaseShaderBlender;
public class HardLight extends BaseShaderBlender {
@Override
public void init() {
loadFragmentShader("hardLight.fp");
}
}
| mit |
xjyaikj/waiqin | ServiceAssistant/src/com/sealion/serviceassistant/entity/PhoneComplishEntity.java | 1231 | package com.sealion.serviceassistant.entity;
/**
* µç»°½â¾öʵÀý
*/
public class PhoneComplishEntity
{
private int id;
private String order_num; //¹¤µ¥ºÅ
private String q_describe; //ÎÊÌâÃèÊö
private String q_solve; //ÎÊÌâ½â¾ö
private String solve_time; //½â¾öʱ¼ä
private int is_create_new_order; //ÊÇ·ñÉú³É餵¥£¬0:·ñ£¬1£ºÊÇ
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
public String getOrder_num()
{
return order_num;
}
public void setOrder_num(String order_num)
{
this.order_num = order_num;
}
public String getQ_describe()
{
return q_describe;
}
public void setQ_describe(String q_describe)
{
this.q_describe = q_describe;
}
public String getQ_solve()
{
return q_solve;
}
public void setQ_solve(String q_solve)
{
this.q_solve = q_solve;
}
public String getSolve_time()
{
return solve_time;
}
public void setSolve_time(String solve_time)
{
this.solve_time = solve_time;
}
public int getIs_create_new_order()
{
return is_create_new_order;
}
public void setIs_create_new_order(int is_create_new_order)
{
this.is_create_new_order = is_create_new_order;
}
}
| mit |
Mikescher/Project-Euler_Befunge | compiled/Java/Euler_Problem-010.java | 25980 | /* transpiled with BefunCompile v1.3.0 (c) 2017 */
class Program{
private final static String _g = "Ah+LCAAAAAAABADNe3dYU126PSoKiIJ0kCYgIBiqhWIAld4EkdB7ld5LqNKlKE1AikGkKEE6hN6lRoiCFOk9BKSFXvM7wZm5353vzjx35t77PD//YGevvd71rnefs/fJ"+
"9slhjSYmwP8jJFidUC126HbhWmxyfYTgujlSmxurGHQDvDkuTU6cb6p/q/l5m0zb0KfA+pU3hwZTseXDPbFdBqnxqAvS7iTW619fMscLFDCW4E4G0ptwR2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6TWcG7H1Uw50I4LYPUnDHUhJ65AQblYEHY6yBh0fGkrjt4aajncDj42FjqiO0lDHOuORI25nAuwNHdClptFqw"+
"joXg/wGyv0Kgtz0AAA==";
private final long[] g=zc(zd(java.util.Base64.getDecoder().decode(_g)));
private long[]zc(byte[]b){long[]r=new long[2014000];for(int i=0;i<2014000;i++)r[i]=b[i];return r;}
private byte[]zd(byte[]o){byte[]d=java.util.Arrays.copyOfRange(o,1,o.length);for(int i=0;i<o[0];i++)d=zs(d);return d;}
private byte[]zs(byte[]o){try{
java.io.ByteArrayInputStream y=new java.io.ByteArrayInputStream(o);
java.util.zip.GZIPInputStream s=new java.util.zip.GZIPInputStream(y);
java.io.ByteArrayOutputStream a=new java.io.ByteArrayOutputStream();
int res=0;byte buf[]=new byte[1024];while(res>=0){res=s.read(buf,0,1024);if(res>0)a.write(buf,0,res);}return a.toByteArray();
}catch(java.io.IOException e){return null;}}
private long gr(long x,long y){return(x>=0&&y>=0&&x<2000&&y<1007)?g[(int)(y*2000+x)]:0;}
private void gw(long x,long y,long v){if(x>=0&&y>=0&&x<2000&&y<1007)g[(int)(y*2000+x)]=v;}
private long td(long a,long b){return(b==0)?0:(a/b);}
private long tm(long a,long b){return(b==0)?0:(a%b);}
private final static java.util.Stack<Long> s=new java.util.Stack<Long>();
private long sp(){return(s.size()==0)?0:s.pop();}
private void sa(long v){s.push(v);}
private long sr(){return(s.size()==0)?0:s.peek();}
long t0;
private int _0(){
gw(1999,1000,35);
sa(1999999);
sa(1999999);
return 1;
}
private int _1(){
if(sp()!=0)return 15;else return 2;
}
private int _2(){
gw(1,0,2000);
gw(2,0,2000);
gw(0,0,2000000);
gw(3,0,2);
gw(0,1,32);
gw(1,1,32);
gw(5,0,(gr(1,0)*10)+1);
return 3;
}
private int _3(){
gw(tm(gr(3,0),gr(1,0)),(td(gr(3,0),gr(1,0)))+1,88);
sa(gr(3,0)+gr(3,0));
sa((gr(3,0)+gr(3,0))<gr(0,0)?1:0);
return 4;
}
private int _4(){
if(sp()!=0)return 14;else return 5;
}
private int _5(){
sp();
return 6;
}
private int _6(){
sa(gr(3,0)+1);
sa(gr(3,0)+1);
gw(3,0,gr(3,0)+1);
sa(tm(sp(),gr(1,0)));
{long v0=sp();long v1=sp();sa(v0);sa(v1);}
sa(td(sp(),gr(1,0)));
sa(sp()+1L);
{long v0=sp();t0=gr(sp(),v0);}
t0-=32;
return 7;
}
private int _7(){
if((t0)!=0)return 8;else return 6;
}
private int _8(){
if(gr(0,0)>gr(3,0))return 3;else return 9;
}
private int _9(){
gw(3,0,0);
gw(4,0,0);
return 10;
}
private int _10(){
sa(gr(3,0)+1);
sa(gr(3,0)+1);
gw(3,0,gr(3,0)+1);
sa(tm(sp(),gr(1,0)));
{long v0=sp();long v1=sp();sa(v0);sa(v1);}
sa(td(sp(),gr(1,0)));
sa(sp()+1L);
{long v0=sp();t0=gr(sp(),v0);}
t0-=88;
if((t0)!=0)return 12;else return 11;
}
private int _11(){
gw(4,0,gr(3,0)+gr(4,0));
return 12;
}
private int _12(){
if((gr(0,0)-gr(3,0))!=0)return 10;else return 13;
}
private int _13(){
System.out.print(String.valueOf(gr(4,0))+" ");
return 16;
}
private int _14(){
sa(sr());
sa(32);
{long v0=sp();long v1=sp();sa(v0);sa(v1);}
sa(tm(sr(),gr(1,0)));
{long v0=sp();long v1=sp();sa(v0);sa(v1);}
sa(td(sp(),gr(1,0)));
sa(sp()+1L);
{long v0=sp();long v1=sp();gw(v1,v0,sp());}
sa(sp()+gr(3,0));
sa(sr()<gr(0,0)?1:0);
return 4;
}
private int _15(){
sa(sp()-1L);
sa(sr());
sa(35);
{long v0=sp();long v1=sp();sa(v0);sa(v1);}
sa(sr()%2000);
{long v0=sp();long v1=sp();sa(v0);sa(v1);}
sa(sp()/2000L);
sa(sp()+1L);
{long v0=sp();long v1=sp();gw(v1,v0,sp());}
sa(sr());
return 1;
}
public void main(){
int c=0;
while(c<16){
switch(c){
case 0:c=_0();break;
case 1:c=_1();break;
case 2:c=_2();break;
case 3:c=_3();break;
case 4:c=_4();break;
case 5:c=_5();break;
case 6:c=_6();break;
case 7:c=_7();break;
case 8:c=_8();break;
case 9:c=_9();break;
case 10:c=_10();break;
case 11:c=_11();break;
case 12:c=_12();break;
case 13:c=_13();break;
case 14:c=_14();break;
case 15:c=_15();break;
}
}
}
public static void main(String[]a){new Program().main();}
}
| mit |
reactivesw/customer_server | src/main/java/io/reactivesw/catalog/productdiscount/model/RelativeProductDiscountValue.java | 915 | package io.reactivesw.catalog.productdiscount.model;
import com.fasterxml.jackson.annotation.JsonCreator;
import io.reactivesw.common.model.Base;
public final class RelativeProductDiscountValue extends Base implements ProductDiscountValue {
private final Integer permyriad;
@JsonCreator
private RelativeProductDiscountValue(final Integer permyriad) {
this.permyriad = permyriad;
}
/**
* Per ten thousand. The fraction the price is reduced. 1000 will result in a 10% price
* reduction.
*
* @return permyriad
*/
public Integer getPermyriad() {
return permyriad;
}
/**
* Alias for {@link RelativeProductDiscountValue#getPermyriad()}
*
* @return permyriad
*/
public Integer getBasisPoint() {
return getPermyriad();
}
public static RelativeProductDiscountValue of(final Integer permyriad) {
return new RelativeProductDiscountValue(permyriad);
}
}
| mit |
chav1961/purelib | src/test/resources/test/test/NodeLoader.java | 10309 | package test;
import java.awt.BorderLayout;
import java.awt.Component;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTree;
import javax.swing.border.LineBorder;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeWillExpandListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.ExpandVetoException;
import javax.swing.tree.TreeCellRenderer;
import javax.swing.tree.TreeNode;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
import chav1961.purelib.basic.Utils;
import chav1961.purelib.enumerations.ContinueMode;
public class NodeLoader extends JFrame {
private static final long serialVersionUID = -842439308945374954L;
private final JTree navigator;
public NodeLoader(final NavigationNode rootCargo) {
final JSplitPane jsp = new JSplitPane();
final DefaultMutableTreeNode root = new FileTreeNode(rootCargo);
this.navigator = new JTree(root);
final DefaultTreeCellRenderer dtcr = (DefaultTreeCellRenderer)this.navigator.getCellRenderer();
this.navigator.addTreeWillExpandListener(new TreeWillExpandListener() {
@Override
public void treeWillExpand(final TreeExpansionEvent event) throws ExpandVetoException {
final FileTreeNode node = (FileTreeNode)event.getPath().getLastPathComponent();
final NavigationNode nn = (NavigationNode)node.getUserObject();
if (nn instanceof PackageNode) {
for (NavigationNode item : ((PackageNode)nn).children) {
node.add(new FileTreeNode(item));
}
}
else if (nn instanceof ClassNode) {
if (((ClassNode)nn).fields.length > 0) {
for (NavigationNode item : ((ClassNode)nn).fields) {
node.add(new FileTreeNode(item));
}
}
if (((ClassNode)nn).methods.length > 0) {
for (NavigationNode item : ((ClassNode)nn).methods) {
node.add(new FileTreeNode(item));
}
}
if (((ClassNode)nn).constructors.length > 0) {
for (NavigationNode item : ((ClassNode)nn).constructors) {
node.add(new FileTreeNode(item));
}
}
}
else if (nn instanceof FieldNode) {
}
else if (nn instanceof MethodNode) {
if (((MethodNode)nn).parmRef.length > 0) {
for (NavigationNode item : ((MethodNode)nn).parmRef) {
node.add(new FileTreeNode(item));
}
}
}
else if (nn instanceof RootNode) {
node.add(new FileTreeNode(((RootNode)nn).child));
}
((DefaultTreeModel)navigator.getModel()).nodeStructureChanged(node);
}
@Override
public void treeWillCollapse(TreeExpansionEvent event) throws ExpandVetoException {
// TODO Auto-generated method stub
}
});
this.navigator.setCellRenderer(new TreeCellRenderer() {
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus) {
final JLabel label = new JLabel();
if (selected) {
label.setOpaque(true);
label.setBackground(dtcr.getBackgroundSelectionColor());
label.setForeground(dtcr.getTextSelectionColor());
}
if (hasFocus) {
label.setBorder(new LineBorder(dtcr.getBorderSelectionColor()));
}
final NavigationNode nn = (NavigationNode)((FileTreeNode)value).getUserObject();
if (nn instanceof TrivialNode) {
label.setText(((TrivialNode)nn).name);
}
else {
label.setText("ROOT");
}
return label;
}
});
jsp.setLeftComponent(this.navigator);
getContentPane().add(new JScrollPane(this.navigator),BorderLayout.CENTER);
}
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
final DocumentBuilder builder = factory.newDocumentBuilder();
final Document doc = builder.parse(NodeLoader.class.getResourceAsStream("test.xml"));
final Element root = doc.getDocumentElement();
final List<NavigationNode> list = new ArrayList<>();
final NavigationNode[] rootNode = new NavigationNode[1];
final String[] overview = new String[1];
Utils.walkDownXML(root,(mode,node)->{
NavigationNode nn;
switch (mode) {
case ENTER :
switch (node.getTagName()) {
case "navigation" :
list.add(0,new RootNode());
break;
case "package" :
final PackageNode pn = new PackageNode();
pn.name = node.getAttribute("name");
list.add(0,pn);
break;
case "class" :
final ClassNode cn = new ClassNode();
cn.name = node.getAttribute("name");
list.add(0,cn);
break;
case "field" :
final FieldNode fn = new FieldNode();
fn.name = node.getAttribute("name");
list.add(0,fn);
break;
case "method" :
final MethodNode mn = new MethodNode();
mn.name = node.getAttribute("name");
list.add(0,mn);
break;
case "parameter" :
final FieldNode parmn = new FieldNode();
parmn.name = node.getAttribute("name");
list.add(0,parmn);
break;
case "overview" :
overview[0] = node.getTextContent();
break;
default :
}
break;
case EXIT :
switch (node.getTagName()) {
case "navigation" :
rootNode[0] = list.remove(0);
break;
case "package" :
nn = list.remove(0);
if (list.get(0) instanceof PackageNode) {
((PackageNode)list.get(0)).children = Arrays.copyOf(((PackageNode)list.get(0)).children,((PackageNode)list.get(0)).children.length+1);
((PackageNode)list.get(0)).children[((PackageNode)list.get(0)).children.length-1] = nn;
}
else if (list.get(0) instanceof RootNode) {
((RootNode)list.get(0)).child = nn;
}
break;
case "class" :
nn = list.remove(0);
if (list.get(0) instanceof PackageNode) {
((PackageNode)list.get(0)).children = Arrays.copyOf(((PackageNode)list.get(0)).children,((PackageNode)list.get(0)).children.length+1);
((PackageNode)list.get(0)).children[((PackageNode)list.get(0)).children.length-1] = nn;
}
break;
case "field" :
nn = list.remove(0);
if (list.get(0) instanceof ClassNode) {
((ClassNode)list.get(0)).fields = Arrays.copyOf(((ClassNode)list.get(0)).fields,((ClassNode)list.get(0)).fields.length+1);
((ClassNode)list.get(0)).fields[((ClassNode)list.get(0)).fields.length-1] = nn;
}
break;
case "method" :
nn = list.remove(0);
if (list.get(0) instanceof ClassNode) {
((ClassNode)list.get(0)).methods = Arrays.copyOf(((ClassNode)list.get(0)).methods,((ClassNode)list.get(0)).methods.length+1);
((ClassNode)list.get(0)).methods[((ClassNode)list.get(0)).methods.length-1] = nn;
}
break;
case "parameter" :
nn = list.remove(0);
if (list.get(0) instanceof MethodNode) {
((MethodNode)list.get(0)).parmRef = Arrays.copyOf(((MethodNode)list.get(0)).parmRef,((MethodNode)list.get(0)).parmRef.length+1);
((MethodNode)list.get(0)).parmRef[((MethodNode)list.get(0)).parmRef.length-1] = nn;
}
break;
case "overview" :
((RootNode)list.get(0)).overview = overview[0];
break;
default :
}
break;
default:
break;
}
return ContinueMode.CONTINUE;
});
new NodeLoader(rootNode[0]).setVisible(true);
}
static void printTree(final String prefix, final NavigationNode node) {
if (node instanceof PackageNode) {
System.err.print(prefix);
System.err.println("package "+((PackageNode)node).name);
for (NavigationNode item : ((PackageNode)node).children) {
printTree(prefix+"\t",item);
}
}
else if (node instanceof ClassNode) {
System.err.print(prefix);
System.err.println("Class "+((ClassNode)node).name);
if (((ClassNode)node).fields.length > 0) {
System.err.println(prefix+"- fields:");
for (NavigationNode item : ((ClassNode)node).fields) {
printTree(prefix+"\t",item);
}
}
if (((ClassNode)node).methods.length > 0) {
System.err.println(prefix+"- methods:");
for (NavigationNode item : ((ClassNode)node).methods) {
printTree(prefix+"\t",item);
}
}
if (((ClassNode)node).constructors.length > 0) {
System.err.println(prefix+"- constructors:");
for (NavigationNode item : ((ClassNode)node).constructors) {
printTree(prefix+"\t",item);
}
}
}
else if (node instanceof FieldNode) {
System.err.print(prefix);
System.err.println("field "+((FieldNode)node).name);
}
else if (node instanceof MethodNode) {
System.err.print(prefix);
System.err.println("Method "+((MethodNode)node).name);
if (((MethodNode)node).parmRef.length > 0) {
System.err.println(prefix+"- parameters:");
for (NavigationNode item : ((MethodNode)node).parmRef) {
printTree(prefix+"\t",item);
}
}
}
else if (node instanceof RootNode) {
System.err.print(prefix);
System.err.println("navigation");
printTree(prefix+"\t",((RootNode)node).child);
}
}
public static class FileTreeNode extends DefaultMutableTreeNode {
private static final long serialVersionUID = -6014820236428705486L;
public FileTreeNode(final NavigationNode current) {
super(current);
}
@Override
public boolean isLeaf() {
return (getUserObject() instanceof FieldNode);
}
}
}
| mit |
TriumGroup/ReCourse | src/main/java/by/triumgroup/recourse/repository/LessonRepository.java | 3593 | package by.triumgroup.recourse.repository;
import by.triumgroup.recourse.entity.model.Lesson;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.List;
public interface LessonRepository extends PagingAndSortingRepository<Lesson, Integer> {
List<Lesson> findByCourseIdOrderByStartTimeAsc(Integer id, Pageable pageable);
List<Lesson> findByOrderByStartTimeAsc(Pageable pageable);
@Query(value = "SELECT\n" +
" lesson.id,\n" +
" lesson.start_time,\n" +
" lesson.duration,\n" +
" lesson.course_id,\n" +
" lesson.topic,\n" +
" lesson.teacher_id,\n" +
" lesson.task\n" +
"FROM lesson\n" +
" JOIN course ON lesson.course_id = course.id\n" +
"WHERE (course.status != 'DRAFT')\n" +
"ORDER BY start_time ASC \n#pageable\n",
nativeQuery = true)
List<Lesson> findAllExcludeDraftOrderByTimeAsc(Pageable pageable);
List<Lesson> findByTeacherIdOrderByStartTimeAsc(Integer id, Pageable pageable);
List<Lesson> findByTeacherIdAndCourseIdOrderByStartTimeAsc(Integer teacherId, Integer courseId, Pageable pageable);
Lesson findFirstByCourseIdOrderByStartTimeAsc(Integer id);
@Query(value = "SELECT recourse.can_add_lesson(:teacher_id, :new_lesson_start_time, :duration)", nativeQuery = true)
boolean canAddLesson(@Param("new_lesson_start_time") Timestamp startTime,
@Param("teacher_id") Integer teacherId,
@Param("duration") Time duration);
@Query(value = "SELECT recourse.can_update_lesson(:teacher_id, :new_lesson_start_time, :duration, :lesson_id)", nativeQuery = true)
boolean canUpdateLesson(@Param("new_lesson_start_time") Timestamp startTime,
@Param("teacher_id") Integer teacherId,
@Param("duration") Time duration,
@Param("lesson_id") Integer lessonId);
@Query(value = "SELECT lesson.id, lesson.start_time, lesson.duration, lesson.course_id, lesson.topic, lesson.teacher_id, lesson.task\n" +
"FROM lesson\n" +
"JOIN course JOIN course_student\n" +
"ON ((course.id = course_student.course_id) and\n" +
"(course_student.student_id = ?1) and\n" +
"(course.status = 'PUBLISHED') and\n" +
"(lesson.course_id = course.id) and\n" +
"(lesson.start_time > now()))\n" +
"ORDER BY lesson.start_time ASC\n" +
"#pageable\n",
nativeQuery = true)
List<Lesson> findFutureLessonsByUserId(Integer userId, Pageable pageable);
@Query(value = "SELECT lesson.id, lesson.start_time, lesson.duration, lesson.course_id, lesson.topic, lesson.teacher_id, lesson.task\n" +
"FROM lesson\n" +
"JOIN course JOIN course_student\n" +
"ON ((course.id = course_student.course_id) and\n" +
"(course_student.student_id = ?1) and\n" +
"(course.status = 'PUBLISHED') and\n" +
"(lesson.course_id = course.id) and\n" +
"(lesson.start_time <= now()))\n" +
"ORDER BY lesson.start_time ASC\n" +
"#pageable\n",
nativeQuery = true)
List<Lesson> findPastLessonsByUserId(Integer userId, Pageable pageable);
} | mit |
annemariegovindraj/physics_gravity_accel | geography/geography_india/Map.java | 9247 | import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.io.*;
import java.util.*;
import java.awt.image.*;
public class Map extends Applet
implements MouseListener, Runnable // ActionListener
{String mytext, thecorrectanswer ; String question="", evaluation="";
Font questionf= new Font("Dialog", Font.BOLD, 18);
Image img, a_tick,a_cross, evalimg, offScreen;
Graphics imggr, offS;
Color grass =new Color(130,244,138);Color greenPastel= new Color(185,249,190);
String ansLabel[]=new String[8]; //normally only 5
boolean step1=true, step2=false;
boolean quizOver=false, isrunning=false;
int index, correctanswers, totalanswers, totalitems;
int ncorrect, chosenanswer, width,height;
String quizItem[]= new String[100];
Random rs = new Random();
Thread roller;
public void init()
{height=Integer.parseInt(getParameter("height")); width=Integer.parseInt(getParameter("width"));
offScreen=createImage(width, height); offS=offScreen.getGraphics();
offS.setColor(grass); offS.fillRect(0,0,width, height);
mytext=getParameter("text");
for (int i=0; i<50;i++){quizItem[i]="";}
correctanswers=totalanswers=0;
setFont(questionf);
addMouseListener(this);
Image correctimg=getImage(getClass().getResource("tick.gif")); Image wrongimg=getImage(getClass().getResource("cross.gif"));
a_tick=getAlpha(correctimg,104,77); a_cross=getAlpha(wrongimg,77,60);
}
public void start()
{if(roller==null)
{roller=new Thread(this);}
readyingForStart();isrunning=true; roller.start();}
public void stop()
{if(roller!=null) {roller=null;}
isrunning=false;
}
public void readyingForStart()
{totalitems=0; index=0;
String inLine=null; InputStreamReader instream =null;
try{
instream= new InputStreamReader(getClass().getResourceAsStream("Quiz.txt"));
BufferedReader dataStream = new BufferedReader(instream);
while ((inLine=dataStream.readLine())!=null)
{quizItem[totalitems]=inLine;totalitems++;}
}catch(IOException e){showStatus ("error in data reading");}
////mix questions
for (int ii=0;ii<50;ii++)
{int i1=rs.nextInt(totalitems);
int i2=rs.nextInt(totalitems);
String tempostr=quizItem[i1];
quizItem[i1]=quizItem[i2];
quizItem[i2]=tempostr;}
}
public void run()
{while( isrunning==true)
{while(index<totalitems)
{
if(step1==true)
{step2=false;
String s[]= new String[9];
String q = quizItem[index];
StringTokenizer t = new StringTokenizer(q,"$");
int ii=0;
while (t.hasMoreTokens())
{s[ii] = t.nextToken();
ii++;
}
thecorrectanswer=s[2];
question=s[1];
Image im=null;
img=createImage(550, height-2);imggr=img.getGraphics();
imggr.setColor(grass); imggr.fillRect(0,0,550,height-2);
try{MediaTracker tracker = new MediaTracker(this);
im=getImage(getClass().getResource(s[0]));
tracker.addImage(im, 0);
tracker.waitForAll();
}catch(InterruptedException e){showStatus("No picture found");}
imggr.drawImage(im,0,0,this);
if(s[7].equals("?")){}
else { int offsetx=10; int offsety=20;
int mx=Integer.parseInt(s[7]);
int my=Integer.parseInt(s[8]);
imggr.setColor(Color.black);
imggr.setFont(new Font("Dialog", Font.BOLD, 36));
imggr.drawString("*", mx-offsetx, my+offsety);
}
do {ncorrect=(rs.nextInt()%5);} while(ncorrect<0);
int j=0, i=3;
while (j<5)
{ if (j==ncorrect){ansLabel[j]=s[2]; j++;}
else {ansLabel[j]=s[i]; i++; j++;}
}
index++; evaluation=""; evalimg=null;
offS.setColor(grass); offS.fillRect(0,0,width,height);
int jj=0;
step1=false;
while(jj<width)
{ repaint(jj,0,jj+10,height);
try{roller.sleep(30);}catch(InterruptedException e){};
jj+=10;}
for (int ik=0; i<2000; i++)
{ try{roller.sleep(30);}catch(InterruptedException e){};
if((step1==true)||(step2==true)) break;}
} //close if step1==true
if (step2==true)
{ showScore(chosenanswer);
repaint();
try{roller.sleep(1000);}catch(InterruptedException e){};
step2=false; step1=true;}
} //close while
quizOver=true; evaluation= "YOUR FINAL SCORE : "; evalimg=null;
repaint();}}
public Image getAlpha(Image img, int imwidth, int imheight)
{Image a_img;
int[] pixels= new int[imwidth*imheight];
PixelGrabber pg= new PixelGrabber(img,0,0,imwidth,imheight,pixels,0,imwidth);
try{pg.grabPixels();}catch(InterruptedException ie){};
for(int i=0; i<pixels.length; i++)
{int p = pixels[i];
int red = 0xff&(p>>16);
int green = 0xff&(p>>8);
int blue = 0xff&(p);
if ((red>245)&&(green>245)&&(blue>245)){pixels[i]=(0x00000000);}
}
a_img=createImage(new MemoryImageSource(imwidth,imheight,pixels,0,imwidth));
return a_img;
}
/*
public void actionPerformed(ActionEvent e)
{ if (e.getActionCommand()== "Next")
{displayNextQuizItem(); } }
*/
public void mouseClicked(MouseEvent me)
{ chosenanswer=0;
if(step1==false)
{ int coX=me.getX(); int coY=me.getY();
if((coX>590)&&(coY<420)&&(coY>100))
{ chosenanswer=(int)((coY-100)/50);
step2=true; }
else{};
} }
void showScore(int chosenl)
{ if (chosenl==ncorrect)
{ evaluation="CORRECT";correctanswers++;
evalimg=a_tick;
}
else
{evaluation= "WRONG, it is "+thecorrectanswer;
evalimg=a_cross;
}
totalanswers++;
// showStatus(evaluation+correctanswers+" / "+totalanswers);
offS.setColor(grass); offS.fillRect(560,400, width-560, height-400);
offS.setColor(Color.black); offS.drawString(evaluation,660,420);
offS.drawString("SCORE= : "+correctanswers+" / "+totalanswers, 620, 460);
repaint(); //(500,400,width-500,height-400);
}
public void mousePressed(MouseEvent e){};
public void mouseReleased(MouseEvent e){};
public void mouseEntered(MouseEvent e){};
public void mouseExited(MouseEvent e){};
public void update(Graphics g)
{if(quizOver==false)
{ if(img==null) {offS.drawString("no picture",20, 50);}
else {offS.drawImage(img,20,2,this);}
FontMetrics fm;
offS.setFont(questionf);
offS.setColor(Color.black); offS.drawString("SCORE= : "+correctanswers+" / "+totalanswers, 620, 460);
fm=offS.getFontMetrics();
int linel=fm.stringWidth(question);
int lineheight=fm.getHeight();
if(linel<440)
{offS.setColor(greenPastel); offS.fillRect(550,( 55-lineheight+4),450 ,lineheight+6);
offS.setColor(Color.black);offS.drawString(question,560,55);}
else
{int spacelength = fm.stringWidth(" ");
int y=55,wl=0; linel=0; //length of the text
StringTokenizer tt=new StringTokenizer(question+" ?");
String word, linee=""; //contains the text
while(tt.hasMoreTokens())
{ word= tt.nextToken();
if (word.equals("?"))
{offS.setColor(greenPastel); offS.fillRect(550,y-lineheight+4,450, lineheight+6);
offS.setColor(Color.black); offS.drawString (linee+" ?", 560, y);}
else {
wl=fm.stringWidth(word);
linel=linel+spacelength+wl;
if (linel>440)
{offS.setColor(greenPastel); offS.fillRect(550,y-lineheight+4,450,lineheight+6);
offS.setColor(Color.black); offS.drawString (linee, 560, y);
y=y+lineheight; linel=wl; linee=word;
}
else
{linee=linee+" "+word;}
}
}//end of while
} // end of else
for(int k=0;k<5;k++)
{ fm=offS.getFontMetrics();
linel=fm.stringWidth(ansLabel[k]);
int y=100;
if(linel<440)
{ offS.setColor(greenPastel); offS.fillRect(590,100+k*50+2,400,lineheight+2);
offS.setColor(Color.black); offS.drawString(ansLabel[k], 600, k*50+100+lineheight);
}
else
{int spacelength = fm.stringWidth(" ");
int wl=0; linel=0;
StringTokenizer tt=new StringTokenizer(ansLabel[k]);
String word, linee="";
while(tt.hasMoreTokens())
{word= tt.nextToken();
wl=fm.stringWidth(word);
linel=linel+spacelength+wl;
if (linel>440)
{offS.setColor(greenPastel); offS.fillRect(590,k*50+y+2,400,lineheight+2);
offS.setColor(Color.black);offS.drawString (linee, 600, k*50+y+lineheight);
y=y+lineheight; linel=wl; linee=word;
}
else
{linee=linee+" "+word;}
}//end of while
offS.setColor(greenPastel); offS.fillRect(590,k*50+y+2,400,lineheight+2 );
offS.setColor(Color.black);offS.drawString (linee, 600, y+k*50+lineheight);
} // end of else
}// end of for
if(step2==true){offS.drawImage(evalimg,550,102+chosenanswer*50, 40,32,this);
offS.drawImage(a_tick, 550,102+ncorrect*50,40,32,this);}
}
else if (quizOver==true){
offS.setColor(grass); offS.fillRect(0,0,width, height);
offS.setColor(Color.black);offS.drawString(evaluation,620,420);
offS.drawString("SCORE= : "+correctanswers+" / "+totalanswers, 620, 460);
offS.drawString("Program written by annemarie.govindraj@gmail.com", 20, 490);
}
paint(g);
}
public void paint(Graphics g)
{g.drawImage(offScreen,0,0,this);}} | mit |
ponchoblesa/app4all | cordova/platforms/android/src/com/bleasyapplications/app4all/MainActivity.java | 1223 | /*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package com.bleasyapplications.app4all;
import android.os.Bundle;
import org.apache.cordova.*;
public class MainActivity extends CordovaActivity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// Set by <content src="index.html" /> in config.xml
loadUrl(launchUrl);
}
}
| mit |
phil-lopreiato/the-blue-alliance-android | android/src/test/java/com/thebluealliance/androidclient/notifications/AllianceSelectionNotificationTest.java | 4076 | package com.thebluealliance.androidclient.notifications;
import android.app.Notification;
import android.content.Context;
import android.content.Intent;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.thebluealliance.androidclient.DefaultTestRunner;
import com.thebluealliance.androidclient.R;
import com.thebluealliance.androidclient.activities.ViewEventActivity;
import com.thebluealliance.androidclient.adapters.ViewEventFragmentPagerAdapter;
import com.thebluealliance.androidclient.database.writers.EventWriter;
import com.thebluealliance.androidclient.datafeed.framework.ModelMaker;
import com.thebluealliance.androidclient.gcm.notifications.AllianceSelectionNotification;
import com.thebluealliance.androidclient.gcm.notifications.NotificationTypes;
import com.thebluealliance.androidclient.helpers.MyTBAHelper;
import com.thebluealliance.androidclient.models.Event;
import com.thebluealliance.androidclient.models.StoredNotification;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.robolectric.RuntimeEnvironment;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
@RunWith(DefaultTestRunner.class)
public class AllianceSelectionNotificationTest {
@Mock private Context mContext;
@Mock private EventWriter mWriter;
private AllianceSelectionNotification mNotification;
private JsonObject mData;
@Before
public void setUp() {
mContext = RuntimeEnvironment.application.getApplicationContext();
mWriter = mock(EventWriter.class);
mData = ModelMaker.getModel(JsonObject.class, "notification_alliance_selection");
mNotification = new AllianceSelectionNotification(mData.toString(), mWriter);
}
@Test
public void testParseData() {
mNotification.parseMessageData();
assertEquals(mNotification.getEventKey(), "2014necmp");
Event event = mNotification.getEvent();
assertNotNull(event);
}
@Test
public void testDbWrite() {
mNotification.parseMessageData();
mNotification.updateDataLocally();
Event event = mNotification.getEvent();
verify(mWriter).write(eq(event), anyLong());
}
@Test(expected = JsonParseException.class)
public void testNoEvent() {
mData.remove("event");
mNotification = new AllianceSelectionNotification(mData.toString(), mWriter);
mNotification.parseMessageData();
}
@Test
public void testBuildNotification() {
mNotification.parseMessageData();
Notification notification = mNotification.buildNotification(mContext, null);
assertNotNull(notification);
StoredNotification stored = mNotification.getStoredNotification();
assertNotNull(stored);
assertEquals(stored.getType(), NotificationTypes.ALLIANCE_SELECTION);
assertEquals(stored.getTitle(), mContext.getString(R.string.notification_alliances_updated_title, "NECMP"));
assertEquals(stored.getBody(), mContext.getString(R.string.notification_alliances_updated, "New England"));
assertEquals(stored.getMessageData(), mData.toString());
assertEquals(stored.getIntent(), MyTBAHelper.serializeIntent(mNotification.getIntent(mContext)));
assertNotNull(stored.getTime());
}
@Test
public void testGetIntent() {
mNotification.parseMessageData();
Intent intent = mNotification.getIntent(mContext);
assertNotNull(intent);
assertEquals(intent.getComponent().getClassName(), "com.thebluealliance.androidclient.activities.ViewEventActivity");
assertEquals(intent.getStringExtra(ViewEventActivity.EVENTKEY), mNotification.getEventKey());
assertEquals(intent.getIntExtra(ViewEventActivity.TAB, -1), ViewEventFragmentPagerAdapter.TAB_ALLIANCES);
}
}
| mit |
larmer01/Mote | src/edu/missouristate/mote/events/ChangeListener.java | 259 | package edu.missouristate.mote.events;
/**
* Provide a method for indicating that the state of an object has changed.
*/
public interface ChangeListener {
/**
* Indicate that the state of an object has changed.
*/
void stateChanged();
}
| mit |
Tzupy/MT-web-server | src/com/tzupy/utils/ResourcePath.java | 896 | package com.tzupy.utils;
/**
* This class defines paths for known resources.
*/
public abstract class ResourcePath {
//public final static String directory = "/resources/directory.png";
//public final static String file = "/resources/file.png";
//public final static String favIcon = "/resources/server.png";
//public final static String style = "/resources/styles.css";
public final static String directory = "https://raw.githubusercontent.com/Tzupy/MT-web-server/master/resources/directory.png";
public final static String file = "https://raw.githubusercontent.com/Tzupy/MT-web-server/master/resources/file.png";
public final static String favIcon = "https://raw.githubusercontent.com/Tzupy/MT-web-server/master/resources/server.png";
public final static String style = "https://raw.githubusercontent.com/Tzupy/MT-web-server/master/resources/styles.css";
}
| mit |
carlos-sancho-ramirez/java-class-analyzer | src/main/java/sword/java/class_analyzer/code/instructions/AbstractInvokeInstruction.java | 1196 | package sword.java.class_analyzer.code.instructions;
import java.util.HashSet;
import java.util.Set;
import sword.java.class_analyzer.FileError;
import sword.java.class_analyzer.code.ByteCodeInterpreter;
import sword.java.class_analyzer.code.IncompleteInstructionException;
import sword.java.class_analyzer.pool.AbstractMethodEntry;
import sword.java.class_analyzer.pool.ConstantPool;
public abstract class AbstractInvokeInstruction<T extends AbstractMethodEntry> extends AbstractConstantPoolReferenceInstruction {
protected final T mMethod;
protected AbstractInvokeInstruction(byte[] code, int index, ConstantPool pool,
Class<T> entryClass, ByteCodeInterpreter interpreter) throws
IllegalArgumentException, IncompleteInstructionException, FileError {
super(code, index, pool, interpreter);
mMethod = pool.get(mPoolIndex, entryClass);
}
@Override
public Set<AbstractMethodEntry> getKnownInvokedMethods() {
Set<AbstractMethodEntry> methods = new HashSet<AbstractMethodEntry>(1);
methods.add(mMethod);
return methods;
}
protected String methodToString() {
return mMethod.toString();
}
}
| mit |
lwthatcher/Compass | test/other/SupportedDriver.java | 313 | package other;
import org.openqa.selenium.WebDriver;
/**
* Created by lthatch1 on 1/12/2015.
*/
public enum SupportedDriver
{
FireFox,
InternetExplorer,
Chrome,
Safari,
HtmlUnit,
Phantom;
public WebDriver getDriver()
{
return WebdriverFactory.getDriver(this);
}
}
| mit |
andyjko/whyline | edu/cmu/hcii/whyline/io/CreateGraphicsParser.java | 783 | package edu.cmu.hcii.whyline.io;
import edu.cmu.hcii.whyline.bytecode.*;
import edu.cmu.hcii.whyline.trace.*;
/**
* @author Andrew J. Ko
*
*/
public class CreateGraphicsParser extends ExecutionEventParser {
public CreateGraphicsParser(Trace trace) {
super(trace);
}
public static boolean handles(Instruction inst) {
if(!(inst instanceof INVOKEVIRTUAL)) return false;
return ((INVOKEVIRTUAL)inst).getMethodInvoked().matchesClassNameAndDescriptor(QualifiedClassName.get("java/awt/Graphics"), "create", "()Ljava/awt/Graphics;");
}
public boolean handle(int eventID) {
if(trace.getKind(eventID) == EventKind.CREATEGRAPHICS) {
trace.getGraphicsHistory().add(new CreateGraphicsOutputEvent(trace, eventID));
return true;
}
else return false;
}
} | mit |
fredyw/leetcode | src/main/java/leetcode/Problem1176.java | 724 | package leetcode;
/**
* https://leetcode.com/problems/diet-plan-performance/
*/
public class Problem1176 {
public int dietPlanPerformance(int[] calories, int k, int lower, int upper) {
int answer = 0;
int[] sums = new int[calories.length];
for (int i = 0; i < k; i++) {
sums[k - 1] += calories[i];
}
for (int i = 0, j = k; j < calories.length; i++, j++) {
sums[j] = sums[j - 1] + calories[j] - calories[i];
}
for (int i = k - 1; i < sums.length; i++) {
if (sums[i] < lower) {
answer--;
} else if (sums[i] > upper) {
answer++;
}
}
return answer;
}
}
| mit |
per06a/hashcash | java/src/main/java/com/prussell/hashcash/HashCash.java | 4457 | package com.prussell.hashcash;
import java.security.DigestException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.TimeZone;
/***
* Generate and validate HashCash stamps.
*
* @author prussell
*
*/
public class HashCash {
private static final byte[] hashBuff = new byte[20];
private static MessageDigest md = null;
private static int MAX_BITS = hashBuff.length * Byte.SIZE;
private static char[] randChars = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p',
'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', '=', '/', '+' };
private static String genRandStr() {
StringBuilder builder = new StringBuilder();
Random random = new Random();
for (int i = 0; i < 10; i++) {
builder.append(randChars[random.nextInt(randChars.length)]);
}
return builder.toString();
}
/***
* Slightly slower but more convenient version of valid(...). Computes the
* numBits parameter directly from the string with more overhead.
*
* @param stamp
* @return
* @throws NoSuchAlgorithmException
* @throws DigestException
*/
public static boolean isValid(String stamp) throws NoSuchAlgorithmException, DigestException {
return validate(Integer.parseInt(stamp.split(":")[1]), stamp);
}
/***
* Validate a HashCash stamp.
*
* @param numBits
* Number of leading zeroes that must be zero for the stamp to be
* valid
* @param stamp
* The HashCash stamp
* @return true if valid else false
* @throws NoSuchAlgorithmException
* @throws DigestException
*/
public static boolean validate(int numBits, String stamp) throws NoSuchAlgorithmException, DigestException {
if (numBits > MAX_BITS) {
throw new IllegalArgumentException(String.format("Parameter numBits has a maximum size of %d", MAX_BITS));
}
if (md == null) {
md = MessageDigest.getInstance("SHA1");
}
md.reset();
md.update(stamp.getBytes());
md.digest(hashBuff, 0, hashBuff.length);
int i = 0;
int total = 0;
while (i < Math.floor(numBits / 8)) {
total |= hashBuff[i];
i++;
}
if (numBits % 8 != 0) {
/*
* Test any remainder. Example: say that we want to validate 42. 42 % 8 = 2, so
* we need to test that the 6th byte >> (8-2) positions is equal to zero.
*/
total |= (hashBuff[i] >> (Byte.SIZE - (numBits % Byte.SIZE)));
}
return total == 0;
}
/***
* Generate a valid HashCash stamp.
*
* @param numBits
* Number of leading zeroes for the stamp. Increases the amount of
* time to find the stamp as a function of pow(2, numBits). The
* computation is CPU-bound, so faster clock speeds means less real
* time to compute a stamp (at the cost of more energy).
* @param resourceStr
* The client-defined resource string. Could be an email address, ip
* address, etc.
* @return A valid HashCash stamp.
* @throws NoSuchAlgorithmException
* @throws DigestException
*/
public static String generate(int numBits, String resourceStr) throws NoSuchAlgorithmException, DigestException {
if (numBits > MAX_BITS) {
throw new IllegalArgumentException(String.format("Parameter numBits has a maximum size of %d", MAX_BITS));
}
/*
* ver:bits:date:resource:[ext]:rand:counter
*/
String result = null;
Date currDate = new Date(System.currentTimeMillis());
int version = 1;
String dateStr = null;
{
SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddhhmmss");
fmt.setTimeZone(TimeZone.getTimeZone("UTC"));
dateStr = fmt.format(currDate);
}
String ext = "";
String randStr = genRandStr();
int counter = 1;
while (result == null) {
String stamp = String.format("%s:%s:%s:%s:%s:%s:%s", version, numBits, dateStr, resourceStr, ext, randStr,
counter);
if (validate(numBits, stamp)) {
result = stamp;
break;
}
counter++;
}
return result;
}
}
| mit |
noveogroup/Highlightify | highlightify/src/main/java/com/noveogroup/highlightify/Highlightify.java | 5779 | /*
* Copyright (c) 2014. Noveo Group
*
* 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.
*
* Except as contained in this notice, the name(s) of the above copyright holders
* shall not be used in advertising or otherwise to promote the sale, use or
* other dealings in this Software without prior written authorization.
*
* 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 com.noveogroup.highlightify;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class Highlightify {
private static final ColorFilter FILTER = HighlightUtils.newFilter(Color.BLACK);
private static final Map<Target, ColorFilter> TARGETS = new HashMap<Target, ColorFilter>();
static {
TARGETS.put(Target.Background, FILTER);
TARGETS.put(Target.Text, FILTER);
TARGETS.put(Target.Compound, FILTER);
TARGETS.put(Target.Image, FILTER);
}
public static class Builder {
private final Map<Target, ColorFilter> targets = new HashMap<Target, ColorFilter>();
public Builder addTargets(final Target... targets) {
addTargets(FILTER, targets);
return this;
}
public Builder addTargets(final int color, final Target... targets) {
addTargets(HighlightUtils.newFilter(color), targets);
return this;
}
public Builder addTargets(final ColorFilter filter, final Target... targets) {
for (final Target target : targets) {
this.targets.put(target, filter);
}
return this;
}
public Highlightify build() {
return new Highlightify(targets.isEmpty() ? TARGETS : targets);
}
}
private final Map<Target, ColorFilter> targets;
protected Highlightify(final Map<Target, ColorFilter> targets) {
this.targets = targets;
}
public Highlightify() {
this(TARGETS);
}
public Set<Target> getTargets() {
return new HashSet<Target>(targets.keySet());
}
private void highlight(final TextView textView) {
if (targets.containsKey(Target.Text)) {
HighlightUtils.highlightText(targets.get(Target.Text), textView);
}
if (targets.containsKey(Target.Compound)) {
HighlightUtils.highlightCompound(targets.get(Target.Compound), textView);
}
}
// Seems like a PMD bug
@SuppressWarnings("PMD.UnusedPrivateMethod")
private void highlight(final ImageView imageView) {
if (targets.containsKey(Target.Image)) {
HighlightUtils.highlightImage(targets.get(Target.Image), imageView);
}
if (targets.containsKey(Target.ImageBackground)) {
HighlightUtils.highlightBackground(targets.get(Target.ImageBackground), imageView);
}
}
/**
* Highlight views
*
* @param views View objects to highlight
*/
public void highlight(final View... views) {
for (final View view : views) {
if (view instanceof ImageView) {
highlight((ImageView) view);
} else {
if (view instanceof TextView) {
highlight((TextView) view);
}
if (targets.containsKey(Target.Background)) {
HighlightUtils.highlightBackground(targets.get(Target.Background), view);
}
}
}
}
/**
* Highlight clickable views recursively
*
* @param view View object to highlight
*/
public void highlightClickable(final View view) {
if (view instanceof ViewGroup) {
final ViewGroup viewGroup = (ViewGroup) view;
for (int i = 0; i < viewGroup.getChildCount(); i++) {
final View child = viewGroup.getChildAt(i);
highlightClickable(child);
}
}
if (view.isClickable()) {
highlight(view);
}
}
/**
* Highlight supplied View and all its childred
*
* @param view View object to highlight
*/
public void highlightWithChildren(final View view) {
if (view instanceof ViewGroup) {
final ViewGroup viewGroup = (ViewGroup) view;
viewGroup.setAddStatesFromChildren(false);
for (int i = 0; i < viewGroup.getChildCount(); i++) {
final View child = viewGroup.getChildAt(i);
child.setDuplicateParentStateEnabled(true);
highlightWithChildren(child);
}
}
highlight(view);
}
}
| mit |
alewin/moneytracking | SRC/app/src/main/java/com/unibo/koci/moneytracking/Adapters/MoneyItemAdapter.java | 3616 | package com.unibo.koci.moneytracking.Adapters;
/*
* Created by koale on 12/08/17.
*/
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.unibo.koci.moneytracking.Activities.DetailActivity;
import com.unibo.koci.moneytracking.Entities.MoneyItem;
import com.unibo.koci.moneytracking.R;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
public class MoneyItemAdapter extends RecyclerView.Adapter<MoneyItemAdapter.ViewHolder> {
private List<MoneyItem> moneyItems;
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView txtTitle;
public TextView txtAmount;
public TextView txtDate;
public ImageView iconitem;
public View layout;
public ViewHolder(View v) {
super(v);
layout = v;
txtTitle = (TextView) v.findViewById(R.id.itemlist_title);
txtAmount = (TextView) v.findViewById(R.id.itemlist_amount);
txtDate = (TextView) v.findViewById(R.id.itemlist_date);
iconitem = (ImageView) v.findViewById(R.id.itemlist_icon);
}
}
public void add(int position, MoneyItem item) {
moneyItems.add(position, item);
notifyItemInserted(position);
notifyDataSetChanged();
}
public void remove(int position) {
moneyItems.remove(position);
notifyItemRemoved(position);
}
public MoneyItemAdapter(List<MoneyItem> myDataset) {
moneyItems = myDataset;
}
@Override
public MoneyItemAdapter.ViewHolder onCreateViewHolder(final ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View v = inflater.inflate(R.layout.money_item_list, parent, false);
ViewHolder vh = new ViewHolder(v);
return vh;
}
@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
final OnClickListener titleListener = new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), DetailActivity.class);
intent.putExtra("money_item", moneyItems.get(position));
intent.putExtra("planned", false);
v.getContext().startActivity(intent);
notifyDataSetChanged();
}
};
holder.layout.setOnClickListener(titleListener);
String name = moneyItems.get(holder.getAdapterPosition()).getName().toString();
double d_amount = moneyItems.get(holder.getAdapterPosition()).getAmount();
DecimalFormat df = new DecimalFormat("#.00");
String amount = df.format(d_amount);
Date d = (moneyItems.get(holder.getAdapterPosition()).getDate());
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
holder.txtTitle.setText(name);
holder.txtAmount.setText(amount + "€");
holder.txtDate.setText(sdf.format(d.getTime()));
if (moneyItems.get(holder.getAdapterPosition()).getAmount() > 0) {
holder.iconitem.setImageResource(R.drawable.thumb_up);
} else {
holder.iconitem.setImageResource(R.drawable.thumb_down);
}
}
@Override
public int getItemCount() {
return moneyItems.size();
}
} | mit |
GenesysPureEngage/workspace-client-java | src/test/java/com/genesys/workspace/Objects.java | 10768 | package com.genesys.workspace;
import com.genesys.internal.common.ApiResponse;
import com.genesys.internal.workspace.model.*;
import com.genesys.workspace.events.NotificationType;
import com.genesys.workspace.models.AgentState;
import com.genesys.workspace.models.AgentWorkMode;
import com.genesys.workspace.models.CallState;
import com.genesys.workspace.models.KeyValueCollection;
import com.genesys.workspace.models.cfg.ActionCodeType;
import com.genesys.workspace.models.targets.TargetType;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import org.cometd.bayeux.Message;
import org.cometd.common.HashMapMessage;
public class Objects {
final static Random random = new Random();
public static final String SEARCH_TERM = "test";
public static final String SWITCH_NAME = "switch";
public static final String API_KEY = "apiKey";
public static final String BASE_URL = "https://baseUrl";
public static final String CALL_ID = "callid";
public static final String OTHER_CALL_ID = "callid";
public static final String HELD_CALL_ID = "callid";
public static final String PARENT_CALL_ID = "parentCallId";
public static final String DESTINATION = "destination";
public static final String OUTBOUND_CALLER_ID = "outboundCallerId";
public static final String LOCATION = "location";
public static final String DIGITS = "123456";
public static final String WORKMODE = "workMode";
public static final String REASON_CODE = "reasonCode";
public static final Boolean DND = true;
public static final String AGENT_ID = "agentId";
public static final String AGENT_DN = "agentDn";
public static final String PLACE_NAME = "placeName";
public static final String QUEUE_NAME = "queueName";
public static String TOKEN = "token";
public static String AUTH_CODE = "authcode";
public static String REDIRECT_URI = "redirecturi";
public static final String SUBSCRIPTION_ID = "subscriptionId";
public static final String CONNECTION_ID = "connectionId";
public static KeyValueCollection makeUserData() {
return new KeyValueCollection();
}
public static KeyValueCollection makeReasons() {
return new KeyValueCollection();
}
public static KeyValueCollection makeExtensions() {
return new KeyValueCollection();
}
public static Target makeTarget(TargetType type) {
int dbid = random.nextInt();
String number = String.valueOf(random.nextInt());
Target target = new Target();
target.setType(Target.TypeEnum.fromValue(type.getValue()));
target.DBID(dbid);
target.setName(String.format("target %s %d", type, dbid));
target.setSwitchName(SWITCH_NAME);
target.setNumber(number);
return target;
}
public static List<Target> makeTargets(int n) {
TargetType[] types = TargetType.values();
List<Target> list = new ArrayList<>();
for(int i = 0; i < n; ++i) {
Target target = makeTarget(types[random.nextInt(types.length)]);
list.add(target);
}
return list;
}
public static TargetsResponse makeTargetsResponse(int n) {
TargetsResponse response = new TargetsResponse();
response.setStatus(new TargetsResponseStatus());
TargetsResponseData data = new TargetsResponseData();
data.setTotalMatches(n);
data.setTargets(Objects.makeTargets(data.getTotalMatches()));
response.setData(data);
return response;
}
public static ApiSuccessResponse makeResponse(int code) {
ApiSuccessResponse response = new ApiSuccessResponse();
TargetsResponseStatus status = new TargetsResponseStatus();
status.setCode(code);
response.setStatus(status);
return response;
}
public static ApiResponse<ApiSuccessResponse> makeHttpResponse() {
Map<String,List<String>> headers = new HashMap<>();
headers.put("set-cookie", Arrays.asList("WORKSPACE_SESSIONID=sessionid"));
return makeHttpResponse(200, headers);
}
public static ApiResponse<ApiSuccessResponse> makeHttpResponse(int code, Map<String,List<String>> headers) {
ApiResponse<ApiSuccessResponse> response = new ApiResponse<>(code, headers);
return response;
}
private static Object[] makeActionCodes() {
return new Object[]{};
}
private static Object[] makeSettings() {
return new Object[]{};
}
private static Object[] makeBusinessAttributes() {
return new Object[]{};
}
private static Object[] makeTransactions() {
return new Object[]{};
}
private static Object[] makeAgentGroups() {
return new Object[]{};
}
public static Map<String, Object> makeActionCode(String name, ActionCodeType type) {
Map<String,Object> data = new HashMap<>();
data.put("name", name);
data.put("type", type.toString());
return data;
}
public static enum MessageType {
DnStateChanged,
EventError,
CallStateChanged,
WorkspaceInitializationComplete
}
public static Message makeMessage(MessageType type) {
Map<String,Object> data = new HashMap<>();
data.put("messageType", type.toString());
switch (type) {
case DnStateChanged:
data.put("dn", makeDnData());
break;
case EventError:
data.put("error", makeErrorData());
break;
case CallStateChanged:
NotificationType[] types = NotificationType.values();
data.put("notificationType", types[random.nextInt(types.length)].toString());
data.put("call", makeCallData());
break;
case WorkspaceInitializationComplete:
data.put("data", makeInitData());
data.put("state", "Complete");
break;
}
Message message = new HashMapMessage();
message.put(Message.DATA_FIELD, data);
return message;
}
public static Map<String, Object> makeStateChangeData() {
Map<String, Object> map = new HashMap<>();
map.put("dn", makeDnData());
return map;
}
private static Map<String, Object> makeDnData() {
AgentState[] states = AgentState.values();
AgentWorkMode[] modes = AgentWorkMode.values();
return makeDnData(String.valueOf(random.nextInt()), String.valueOf(random.nextInt()), states[random.nextInt(states.length)], modes[random.nextInt(modes.length)], String.valueOf(random.nextInt()), DND);
}
private static Map<String, Object> makeDnData(String agentId, String agentNumber, AgentState state, AgentWorkMode mode, String forwardTo, Boolean dnd) {
Map<String, Object> data = new HashMap<>();
data.put("number", agentNumber);
data.put("agentId", agentId);
data.put("agentState", state.toString());
data.put("agentWorkMode", mode.toString());
data.put("forwardTo", forwardTo);
data.put("dnd", dnd);
return data;
}
public static Map<String, Object> makeCallData() {
CallState[] states = CallState.values();
return makeCallData(String.valueOf(random.nextInt()),
String.valueOf(random.nextInt()),
states[random.nextInt(states.length)],
String.valueOf(random.nextInt()),
String.valueOf(random.nextInt()),
String.valueOf(random.nextInt()),
String.valueOf(random.nextInt()),
makeCapabilities(), makeParticipants(), makeUserDataArray());
}
public static Map<String, Object> makeCallData(
String id,
String callUuid,
CallState state,
String parentConnId,
String previousConnId,
String ani,
String dnis,
Object[] capabilities,
Object[] participantData,
Object[] userData) {
HashMap<String, Object> data = new HashMap<>();
data.put("id", id);
data.put("callUuid", callUuid);
data.put("state", state.toString());
data.put("parentConnId", parentConnId);
data.put("previousConnId", previousConnId);
data.put("ani", ani);
data.put("dnis", dnis);
data.put("capabilities", capabilities);
data.put("participants", participantData);
data.put("userData", userData);
return data;
}
public static Object[] makeUserDataArray() {
return new Object[] {};
}
public static Object[] makeParticipants() {
return new Object[] {};
}
public static Object[] makeCapabilities() {
return new Object[] {};
}
public static Map<String, Object> makeUser() {
Map<String, Object> data = new HashMap<>();
data.put("employeeId", AGENT_ID);
data.put("defaultPlace", PLACE_NAME);
data.put("agentLogin", AGENT_DN);
data.put("userProperties", new Object[]{});
return data;
}
public static Map<String, Object> makeErrorData() {
return makeErrorData("test", 1);
}
public static Map<String, Object> makeErrorData(String msg, int code) {
Map<String,Object> data = new HashMap<>();
data.put("errorMessage", msg);
data.put("errorCode", code);
return data;
}
public static Map<String, Object> makeInitData() {
Map<String, Object> user = makeUser();
Map<String,Object> conf = new HashMap<>();
conf.put("actionCodes", makeActionCodes());
conf.put("settings", makeSettings());
conf.put("businessAttributes", makeBusinessAttributes());
conf.put("transactions", makeTransactions());
conf.put("agentGroups", makeAgentGroups());
Map<String,Object> data = new HashMap<>();
data.put("user", user);
data.put("configuration", conf);
return data;
}
}
| mit |
wolfgangimig/joa | java/joa/src-gen/com/wilutions/mslib/office/FileTypes.java | 858 | /* ** GENEREATED FILE - DO NOT MODIFY ** */
package com.wilutions.mslib.office;
import com.wilutions.com.*;
/**
* FileTypes.
*
*/
@CoInterface(guid="{000C036C-0000-0000-C000-000000000046}")
public interface FileTypes extends IDispatch {
static boolean __typelib__loaded = __TypeLib.load();
@DeclDISPID(1610743808) public IDispatch getApplication() throws ComException;
@DeclDISPID(1610743809) public Integer getCreator() throws ComException;
@DeclDISPID(0) public MsoFileType getItem(final Integer Index) throws ComException;
@DeclDISPID(2) public Integer getCount() throws ComException;
@DeclDISPID(3) public void Add(final MsoFileType FileType) throws ComException;
@DeclDISPID(4) public void Remove(final Integer Index) throws ComException;
@DeclDISPID(-4) public Object get_NewEnum() throws ComException;
}
| mit |
mattinbits/glitter | src/main/java/com/mjlivesey/gl/geometry/Rotation.java | 139 | package com.mjlivesey.gl.geometry;
/**
* Created by Matthew on 21/08/2014.
*/
public abstract class Rotation extends Transformation {
}
| mit |
IDepla/polibox_client | src/main/java/it/polito/ai/polibox/client/http/action/AbstractFileAction.java | 10911 | /*******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2015 Igor Deplano
*
* 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 it.polito.ai.polibox.client.http.action;
import it.polito.ai.polibox.client.filesystem.FileMapInterface;
import it.polito.ai.polibox.client.filesystem.config.FolderMonitorConfigInterface;
import it.polito.ai.polibox.client.filesystem.impl.FilesystemTools;
import it.polito.ai.polibox.client.http.response.Response;
import it.polito.ai.polibox.client.persistency.Resource;
import it.polito.ai.polibox.client.xml.XmlLoaderInterface;
import it.polito.ai.polibox.client.xml.impl.GenericXmlAutoLoader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
public abstract class AbstractFileAction implements FileAction {
@Autowired
protected HttpHelper helper;
@Autowired
protected XmlLoaderInterface<FolderMonitorConfigInterface> folderConfigManager;
@Autowired
protected GenericXmlAutoLoader<FileMapInterface> fileMapLoader;
protected AbstractFileAction() {}
public abstract void createDirectoryHttp(Resource r);
public abstract void createFileHttp(Resource r);
public abstract void renameHttp(Resource old, Resource nuova);
public abstract void deleteHttp(Resource r);
public abstract void ripristinaHttp(Resource r);
public void createDirectoryFs(Resource r) {
String s=r.getName();
try {
if(!s.startsWith(getTargetFolderCanonicalPath())){
s=getTargetFolderCanonicalPath()+r.getName();
}
File f=new File(s);
f.mkdir();
r.setName(s);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public void createFileFs(Resource r) {
String s=r.getName();
// System.out.println(r.getName()+" file creation in filesystem: ");
try {
if(!s.startsWith(getTargetFolderCanonicalPath())){
s=getTargetFolderCanonicalPath()+r.getName();
}
Path p=Paths.get(s);
if(!Files.exists(p.getParent()))
Files.createDirectories(p.getParent());
r.setName(s);
Files.createFile(p);
} catch (FileAlreadyExistsException e){
// System.out.println(r.getName()+" file esisteva già");
} catch (IOException e) {
// System.out.println(r.getName()+" ha lanciato eccezione.");
throw new RuntimeException(e);
}
}
public void renameFs(Resource old, Resource nuova) {
File oldF,newF;
String s,w;
s=old.getName();
w=nuova.getName();
try {
if(!s.startsWith(getTargetFolderCanonicalPath()))
s=getTargetFolderCanonicalPath()+old.getName();
if(!w.startsWith(getTargetFolderCanonicalPath()))
w=getTargetFolderCanonicalPath()+nuova.getName();
oldF=new File(s);
newF=new File(w);
oldF.renameTo(newF);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public void deleteFs(Resource r) {
String s=r.getName();
try {
if(!s.startsWith(getTargetFolderCanonicalPath()))
s=getTargetFolderCanonicalPath()+r.getName();
File o=new File(s);
FilesystemTools.deleteFolder(o);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* lo implemento come nuovo download.
*/
public void ripristinaFs(Resource r) {
// System.out.println("ripristina file system --> download");
download(r);
r.setDeleted(false);
}
public int searchParent(Resource r){
List<Resource> rList=getTargetList();
String name=r.getName().substring(0, r.getName().lastIndexOf("/"));
// System.out.println("stampa: "+name);
for(Resource w : rList){
if(w.getName().compareTo(name)==0){
return w.getId();
}
}
return -1;
}
/**
* upload
*/
public void upload(Resource r) {
FileMapInterface f=fileMapLoader.load();
if(r.isDirectory()){
createDirectoryHttp(r);
f.changeElementToList(getTargetList(), r);
return;
}else if(!r.isDirectory()){
createFileHttp(r);
f.changeElementToList(getTargetList(), r);
// continua con upload
// System.out.println("id:"+r.getId()+"|version:"+r.getVersion()+"|");
File file;
FileInputStream fis = null;
try {
file=new File(r.getName());
fis=new FileInputStream(file);
byte[] buffer = new byte[FilesystemTools.CHUNK_SIZE];
int bytesRead;
int index,i;
String s,d;
WebTarget target=helper.getWebTarget().path("rest/file/"+r.getId()+"/"+r.getVersion());
Form form;
index=0;
byte[] b2,bite;
MessageDigest md = MessageDigest.getInstance("SHA3-512");
while ((bytesRead = fis.read(buffer)) != -1) {
if(bytesRead<buffer.length){
b2=new byte[bytesRead];
for(i=0;i<b2.length;i++){
b2[i]=buffer[i];
}
buffer=b2;
}
if(index==r.getChunkNumber()){
/**
* questo mi serve per i file molto grossi. il so mi splitta il file in versioni differenti,
* nel server c'è il merge quindi non troppi problemi arrivano.
*/
createFileHttp(r);
f.changeElementToList(getTargetList(), r);
}
s=Base64.encodeBase64String(buffer);
// System.out.println("ho letto:"+bytesRead+" bytes |"+buffer.length+"|"+md+"|");
md.reset();
md.update(s.getBytes("UTF-8"));//calcolo digest
bite=md.digest();
d=org.bouncycastle.util.encoders.Hex.toHexString(bite);
// System.out.println("digest:"+d);
form=new Form();
form.param("version", ""+r.getVersion());
form.param("resource", ""+r.getId());
form.param("chunkNumber", ""+index);
form.param("digest", d);
form.param("data", s);
// System.out.println("version:"+r.getVersion()+"|resource:"+r.getId()+"|chunk:"+index+"|of:"+r.getChunkNumber()+"|");
target.request(MediaType.APPLICATION_JSON_TYPE)
.headers(helper.getHeaders())
.post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE),new GenericType<Response<Resource>>(){});
index++;
}
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}finally{
if(fis!=null){
try {
fis.close();
fis=null;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
}
/**
* download
*/
public void download(Resource r) {
FileMapInterface f=fileMapLoader.load();
if(r.isDirectory()){
createDirectoryFs(r);
return;
}else{
createFileFs(r);
System.out.println(r.getName() +" download");
/***
* recupero ultima versione e aggiorno mappa
*/
// System.out.println(r.getName() +" è stata spedita per il recupero ultima versione prima di download");
WebTarget target=helper.getWebTarget().path("rest/your/file/"+r.getId()+"/last");
Response<Resource> response=target.request(MediaType.APPLICATION_JSON_TYPE)
.headers(helper.getHeaders())
.get(new GenericType<Response<Resource>>(){});
for (Resource e : response.getResult()) {
r.updateWithoutName(e);
f.appendToList(getTargetList(), r);
}
// System.out.println(r.getName() +" è stata spedita per il download");
target=helper.getWebTarget().path("rest/file/"+r.getId()+"/"+r.getVersion());
javax.ws.rs.core.Response downloadResponse=target.request(MediaType.APPLICATION_JSON_TYPE)
.headers(helper.getHeaders()).get();
// read response string
InputStream inputStream = downloadResponse.readEntity(InputStream.class);
FileOutputStream outputStream=null;
try {
outputStream = new FileOutputStream(r.getName());
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
} catch (FileNotFoundException e1) {
throw new RuntimeException(e1);
} catch (IOException e1) {
throw new RuntimeException(e1);
}finally{
try {
if(outputStream!=null)
outputStream.close();
} catch (IOException e1) {
throw new RuntimeException(e1);
}
}
}
}
public abstract String getTargetFolderCanonicalPath() throws IOException;
public abstract List<Resource> getTargetList();
public HttpHelper getHelper() {
return helper;
}
public void setHelper(HttpHelper helper) {
this.helper = helper;
}
public XmlLoaderInterface<FolderMonitorConfigInterface> getFolderConfigManager() {
return folderConfigManager;
}
public void setFolderConfigManager(
XmlLoaderInterface<FolderMonitorConfigInterface> folderConfigManager) {
this.folderConfigManager = folderConfigManager;
}
public GenericXmlAutoLoader<FileMapInterface> getFileMapLoader() {
return fileMapLoader;
}
public void setFileMapLoader(
GenericXmlAutoLoader<FileMapInterface> fileMapLoader) {
this.fileMapLoader = fileMapLoader;
}
}
| mit |
RiceKab/project-geowars | projects/parametergame/core/src/be/howest/twentytwo/parametergame/model/system/RenderSystem.java | 2367 | package be.howest.twentytwo.parametergame.model.system;
import be.howest.twentytwo.parametergame.model.component.SpriteComponent;
import be.howest.twentytwo.parametergame.model.component.TransformComponent;
import com.badlogic.ashley.core.Entity;
import com.badlogic.ashley.core.Family;
import com.badlogic.ashley.systems.IteratingSystem;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.utils.viewport.Viewport;
/**
* Responsible for rendering sprites onto the screen.
*/
public class RenderSystem extends IteratingSystem {
public final static int PRIORITY = 0;
private Viewport viewport;
private SpriteBatch batch;
public RenderSystem(SpriteBatch batch, Viewport viewport) {
super(Family.all(TransformComponent.class, SpriteComponent.class).get(), PRIORITY);
this.batch = batch;
this.viewport = viewport;
}
@Override
public void update(float deltaTime) {
getViewport().apply();
getCamera().update(); // TODO: Might not be needed.
batch.setProjectionMatrix(getCamera().combined);
batch.begin();
super.update(deltaTime);
batch.end();
}
@Override
protected void processEntity(Entity entity, float deltaTime) {
TransformComponent transform = TransformComponent.MAPPER.get(entity);
SpriteComponent spriteComp = SpriteComponent.MAPPER.get(entity);
TextureRegion region = spriteComp.getRegion();
if (region == null) {
// Gdx.app.error("RenderSys", "ERR: NULL REGION -- COMPONENT
// INCOMPLETE");
return;
}
float width = region.getRegionWidth();
float height = region.getRegionHeight();
float offsetX = width / 2;
float offsetY = height / 2;
// float scaleX = METERS_PER_PIXEL; // Scale to world size to match
// physics object
// float scaleY = METERS_PER_PIXEL;
float scaleX = transform.getWorldSize().x / region.getRegionWidth();
float scaleY = transform.getWorldSize().y / region.getRegionHeight();
// TODO: Images are rotated here as sprites are all assumed to face
// north.
batch.draw(region, transform.getPos().x - offsetX, transform.getPos().y - offsetY, offsetX, offsetY, width,
height, scaleX, scaleY, transform.getRotation());
}
public Viewport getViewport() {
return viewport;
}
public Camera getCamera() {
return viewport.getCamera();
}
}
| mit |
Azure/azure-sdk-for-java | sdk/logic/azure-resourcemanager-logic/src/main/java/com/azure/resourcemanager/logic/models/WorkflowTriggerReference.java | 2251 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.logic.models;
import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
/** The workflow trigger reference. */
@Fluent
public final class WorkflowTriggerReference extends ResourceReference {
@JsonIgnore private final ClientLogger logger = new ClientLogger(WorkflowTriggerReference.class);
/*
* The workflow name.
*/
@JsonProperty(value = "flowName")
private String flowName;
/*
* The workflow trigger name.
*/
@JsonProperty(value = "triggerName")
private String triggerName;
/**
* Get the flowName property: The workflow name.
*
* @return the flowName value.
*/
public String flowName() {
return this.flowName;
}
/**
* Set the flowName property: The workflow name.
*
* @param flowName the flowName value to set.
* @return the WorkflowTriggerReference object itself.
*/
public WorkflowTriggerReference withFlowName(String flowName) {
this.flowName = flowName;
return this;
}
/**
* Get the triggerName property: The workflow trigger name.
*
* @return the triggerName value.
*/
public String triggerName() {
return this.triggerName;
}
/**
* Set the triggerName property: The workflow trigger name.
*
* @param triggerName the triggerName value to set.
* @return the WorkflowTriggerReference object itself.
*/
public WorkflowTriggerReference withTriggerName(String triggerName) {
this.triggerName = triggerName;
return this;
}
/** {@inheritDoc} */
@Override
public WorkflowTriggerReference withId(String id) {
super.withId(id);
return this;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
@Override
public void validate() {
super.validate();
}
}
| mit |
yurisuzukiltd/AR-Music-Kit | ARMusicKit/app/src/main/java/com/yurisuzuki/ar/PianoMarker.java | 616 | /*
* Author(s): Kosuke Miyoshi, Narrative Nights
*/
package com.yurisuzuki.ar;
import com.yurisuzuki.CameraActivity;
public class PianoMarker extends Marker {
void checkPlaySound(long now, CameraActivity activity) {
if (isTracked()) {
// マーカーを認識していたら、lastTrackedTimeを更新
lastTrackedTime = now;
} else {
// 現在認識しておらず、最後に認識してから1000msec以内だったら、発音する
if (lastTrackedTime > 0 && (now - lastTrackedTime) < 1000) {
lastTrackedTime = -1;
lastPlayTime = now;
activity.playSound(soundId);
}
}
}
}
| mit |
badoualy/kotlogram | tl/src/main/java/com/github/badoualy/telegram/tl/api/request/TLRequestAuthBindTempAuthKey.java | 4410 | package com.github.badoualy.telegram.tl.api.request;
import com.github.badoualy.telegram.tl.TLContext;
import com.github.badoualy.telegram.tl.core.TLBool;
import com.github.badoualy.telegram.tl.core.TLBytes;
import com.github.badoualy.telegram.tl.core.TLMethod;
import com.github.badoualy.telegram.tl.core.TLObject;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import static com.github.badoualy.telegram.tl.StreamUtils.readInt;
import static com.github.badoualy.telegram.tl.StreamUtils.readLong;
import static com.github.badoualy.telegram.tl.StreamUtils.readTLBytes;
import static com.github.badoualy.telegram.tl.StreamUtils.readTLObject;
import static com.github.badoualy.telegram.tl.StreamUtils.writeInt;
import static com.github.badoualy.telegram.tl.StreamUtils.writeLong;
import static com.github.badoualy.telegram.tl.StreamUtils.writeTLBytes;
import static com.github.badoualy.telegram.tl.TLObjectUtils.SIZE_CONSTRUCTOR_ID;
import static com.github.badoualy.telegram.tl.TLObjectUtils.SIZE_INT32;
import static com.github.badoualy.telegram.tl.TLObjectUtils.SIZE_INT64;
import static com.github.badoualy.telegram.tl.TLObjectUtils.computeTLBytesSerializedSize;
/**
* @author Yannick Badoual yann.badoual@gmail.com
* @see <a href="http://github.com/badoualy/kotlogram">http://github.com/badoualy/kotlogram</a>
*/
public class TLRequestAuthBindTempAuthKey extends TLMethod<TLBool> {
public static final int CONSTRUCTOR_ID = 0xcdd42a05;
protected long permAuthKeyId;
protected long nonce;
protected int expiresAt;
protected TLBytes encryptedMessage;
private final String _constructor = "auth.bindTempAuthKey#cdd42a05";
public TLRequestAuthBindTempAuthKey() {
}
public TLRequestAuthBindTempAuthKey(long permAuthKeyId, long nonce, int expiresAt, TLBytes encryptedMessage) {
this.permAuthKeyId = permAuthKeyId;
this.nonce = nonce;
this.expiresAt = expiresAt;
this.encryptedMessage = encryptedMessage;
}
@Override
@SuppressWarnings({"unchecked", "SimplifiableConditionalExpression"})
public TLBool deserializeResponse(InputStream stream, TLContext context) throws IOException {
final TLObject response = readTLObject(stream, context);
if (response == null) {
throw new IOException("Unable to parse response");
}
if (!(response instanceof TLBool)) {
throw new IOException(
"Incorrect response type, expected " + getClass().getCanonicalName() + ", found " + response
.getClass().getCanonicalName());
}
return (TLBool) response;
}
@Override
public void serializeBody(OutputStream stream) throws IOException {
writeLong(permAuthKeyId, stream);
writeLong(nonce, stream);
writeInt(expiresAt, stream);
writeTLBytes(encryptedMessage, stream);
}
@Override
@SuppressWarnings({"unchecked", "SimplifiableConditionalExpression"})
public void deserializeBody(InputStream stream, TLContext context) throws IOException {
permAuthKeyId = readLong(stream);
nonce = readLong(stream);
expiresAt = readInt(stream);
encryptedMessage = readTLBytes(stream, context);
}
@Override
public int computeSerializedSize() {
int size = SIZE_CONSTRUCTOR_ID;
size += SIZE_INT64;
size += SIZE_INT64;
size += SIZE_INT32;
size += computeTLBytesSerializedSize(encryptedMessage);
return size;
}
@Override
public String toString() {
return _constructor;
}
@Override
public int getConstructorId() {
return CONSTRUCTOR_ID;
}
public long getPermAuthKeyId() {
return permAuthKeyId;
}
public void setPermAuthKeyId(long permAuthKeyId) {
this.permAuthKeyId = permAuthKeyId;
}
public long getNonce() {
return nonce;
}
public void setNonce(long nonce) {
this.nonce = nonce;
}
public int getExpiresAt() {
return expiresAt;
}
public void setExpiresAt(int expiresAt) {
this.expiresAt = expiresAt;
}
public TLBytes getEncryptedMessage() {
return encryptedMessage;
}
public void setEncryptedMessage(TLBytes encryptedMessage) {
this.encryptedMessage = encryptedMessage;
}
}
| mit |
freeuni-sdp/xo-game | src/main/java/ge/edu/freeuni/sdp/xo/game/Updater.java | 129 | package ge.edu.freeuni.sdp.xo.game;
public interface Updater {
void update(String player1, String player2, String winner);
}
| mit |
fwumdesoft/FwumDeAPI | src/com/fwumdesoft/api/graphics/Sprite.java | 4402 | package com.fwumdesoft.api.graphics;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsEnvironment;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.Serializable;
import com.fwumdesoft.api.math.geom.Vector2;
/**
* Represents an image with a hit-box and a vector.
* @author Jason Carrete
*/
public class Sprite extends BufferedImage implements Serializable {
private static final long serialVersionUID = -7599243419137335696L;
public final Rectangle2D.Double hitbox;
public final Vector2 v;
private Color bgcolor;
private int stretchWidth, stretchHeight;
private double rotation;
public Sprite(final BufferedImage bimg, double x_spd, double y_spd, int x, int y) {
super(bimg.getWidth(), bimg.getHeight(), bimg.getType());
setData(bimg.getData());
hitbox = new Rectangle2D.Double(x, y, getWidth(), getHeight());
v = new Vector2(x_spd, y_spd);
rotation = 0;
}
public Sprite(final BufferedImage bimg, final Vector2 v, int x, int y) {
this(bimg, v.x, v.y, x, y);
}
public Sprite(final BufferedImage bimg, final Vector2 v) {
this(bimg, v.x, v.y, 0, 0);
}
public Sprite(final BufferedImage bimg) {
this(bimg, 0.0, 0.0, 0, 0);
}
/**
* Sets the background color
* @param background
*/
public void setBackgroundColor(final Color background) {
this.bgcolor = background;
}
public int getStretchWidth() {
return stretchWidth;
}
public int getStretchHeight() {
return stretchHeight;
}
/**
* Sets how many pixels the image will take up when drawn
* @param width The pixel width of the drawn image
*/
public void setStretchWidth(final int width) {
this.stretchWidth = width;
}
/**
* Sets how many pixels the image will take up when drawn
* @param height The pixel height of the drawn image
*/
public void setStretchHeight(final int height) {
this.stretchHeight = height;
}
/**
* Gets how rotated the sprite is when drawn
* @return The rotation
*/
public double getRotation() {
return rotation;
}
/**
* Rotate the sprite when drawn
* @param rotation The degrees to rotate
*/
public void setRotation(final double rotation) {
this.rotation = rotation;
}
/**
* Draws the sprite
* NOTE: Mutates g by adding the sprite
* @param g The graphics object to draw to<br>
*/
public void draw(final Graphics g) {
//Create the correct rotation
AffineTransform rotate = AffineTransform.getRotateInstance(Math.toRadians(rotation));
((Graphics2D)g).transform(rotate);
if(bgcolor == null)
g.drawImage(this, (int)hitbox.x, (int)hitbox.y, stretchWidth, stretchHeight, null);
else
g.drawImage(this, (int)hitbox.x, (int)hitbox.y, stretchWidth, stretchHeight, bgcolor, null);
//Reset rotation
((Graphics2D)g).transform(new AffineTransform());
}
/**
* Updates the state of the sprite
* @param deltaTime How many milliseconds have passed since the last update
*/
public void update(final float deltaTime) {
this.applyVector(deltaTime);
}
/**
* Applies the vector to the position of the sprite.
*/
public void applyVector(final float deltaTime) {
hitbox.x += v.x * deltaTime;
hitbox.y += v.y * deltaTime;
}
/**
* Ensures the Sprite uses a compatible image type with the renderer
* @param image The image loaded from memory
* @return The image converted into a compatible type
*/
public static BufferedImage toCompatibleImage(final BufferedImage image) {
//obtain the current system graphical settings
GraphicsConfiguration gfx_config = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice().getDefaultConfiguration();
//If the image is already optimized, return it
if(image.getColorModel().equals(gfx_config.getColorModel()))
return image;
// image is not optimized, so create a new image that is
BufferedImage new_image = gfx_config.createCompatibleImage(image.getWidth(), image.getHeight(), image.getTransparency());
// get the graphics context of the new image to draw the old image on
Graphics2D g2d = (Graphics2D)new_image.getGraphics();
// actually draw the image and dispose of context no longer needed
g2d.drawImage(image, 0, 0, null);
g2d.dispose();
// return the new optimized image
return new_image;
}
}
| mit |
openforis/calc | calc-core/src/generated/java/org/openforis/calc/persistence/jooq/tables/pojos/ProcessingChainBase.java | 2570 | /**
* This class is generated by jOOQ
*/
package org.openforis.calc.persistence.jooq.tables.pojos;
import java.io.Serializable;
import javax.annotation.Generated;
import org.openforis.calc.engine.ParameterMap;
import org.openforis.calc.engine.Worker.Status;
/**
* This class is generated by jOOQ.
*/
@Generated(
value = {
"http://www.jooq.org",
"jOOQ version:3.6.2"
},
comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class ProcessingChainBase implements Serializable {
private static final long serialVersionUID = -182143266;
private Integer id;
private Integer workspaceId;
private ParameterMap parameters;
private String caption;
private String description;
private Status status;
private String commonScript;
public ProcessingChainBase() {}
public ProcessingChainBase(ProcessingChainBase value) {
this.id = value.id;
this.workspaceId = value.workspaceId;
this.parameters = value.parameters;
this.caption = value.caption;
this.description = value.description;
this.status = value.status;
this.commonScript = value.commonScript;
}
public ProcessingChainBase(
Integer id,
Integer workspaceId,
ParameterMap parameters,
String caption,
String description,
Status status,
String commonScript
) {
this.id = id;
this.workspaceId = workspaceId;
this.parameters = parameters;
this.caption = caption;
this.description = description;
this.status = status;
this.commonScript = commonScript;
}
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getWorkspaceId() {
return this.workspaceId;
}
public void setWorkspaceId(Integer workspaceId) {
this.workspaceId = workspaceId;
}
public ParameterMap getParameters() {
return this.parameters;
}
public void setParameters(ParameterMap parameters) {
this.parameters = parameters;
}
public String getCaption() {
return this.caption;
}
public void setCaption(String caption) {
this.caption = caption;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
public Status getStatus() {
return this.status;
}
public void setStatus(Status status) {
this.status = status;
}
public String getCommonScript() {
return this.commonScript;
}
public void setCommonScript(String commonScript) {
this.commonScript = commonScript;
}
}
| mit |
trevershick/jsoup-configuration | gson/src/main/java/io/shick/jsoup/gson/package-info.java | 463 | /**
* <p>
* Contains the Gson implementation of the Parser and Formatter. This is
* contained within the jsoup-configuration-gson dependency.
* </p>
*
* <pre>
* <code>
*
* <dependency>
* <groupId>io.shick.jsoup</groupId>
* <artifactId>jsoup-configuration-gson</artifactId>
* <version>RELEASE</version>
* </dependency>
* </code>
* </pre>
*/
package io.shick.jsoup.gson;
| mit |
sergiowww/severino | severino/src/main/java/br/mp/mpt/prt8/severino/mediator/AcessoGaragemMediator.java | 5680 | package br.mp.mpt.prt8.severino.mediator;
import java.time.LocalDate;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import br.mp.mpt.prt8.severino.dao.AcessoGaragemRepository;
import br.mp.mpt.prt8.severino.dao.BaseRepositorySpecification;
import br.mp.mpt.prt8.severino.dao.specs.AbstractSpec;
import br.mp.mpt.prt8.severino.dao.specs.AcessoGaragemSpec;
import br.mp.mpt.prt8.severino.entity.AcessoGaragem;
import br.mp.mpt.prt8.severino.entity.FonteDisponibilidade;
import br.mp.mpt.prt8.severino.entity.Local;
import br.mp.mpt.prt8.severino.entity.Veiculo;
import br.mp.mpt.prt8.severino.entity.Visita;
import br.mp.mpt.prt8.severino.mediator.intervalodatas.CheckConflitoIntervalo;
import br.mp.mpt.prt8.severino.mediator.intervalodatas.FluxoCamposIntervalo;
import br.mp.mpt.prt8.severino.utils.EntidadeUtil;
import br.mp.mpt.prt8.severino.utils.NegocioException;
import br.mp.mpt.prt8.severino.valueobject.PessoaDisponibilidade;
/**
* Mediator para acesso garagem.
*
* @author sergio.eoliveira
*
*/
@Service
public class AcessoGaragemMediator extends AbstractSpecMediator<AcessoGaragem, Integer> {
private static final String MENSAGEM_CONFLITO = "O acesso a garagem do veículo placa %s possui intervalo de entrada e saída conflitante com a(s) acessos(s) %s";
@Autowired
private AcessoGaragemRepository acessoGaragemRepository;
@Autowired
private VisitaMediator visitaMediator;
@Autowired
private VeiculoMediator veiculoMediator;
@Autowired
private FluxoCamposIntervalo fluxoCamposIntervalo;
private CheckConflitoIntervalo<String, AcessoGaragem> checkConflitoIntervaloMembro;
@Override
protected BaseRepositorySpecification<AcessoGaragem, Integer> repositoryBean() {
return acessoGaragemRepository;
}
@PostConstruct
public void setUp() {
this.checkConflitoIntervaloMembro = new CheckConflitoIntervalo<String, AcessoGaragem>(acessoGaragemRepository, MENSAGEM_CONFLITO);
}
@Transactional
@Override
public AcessoGaragem save(AcessoGaragem acessoGaragem) {
fluxoCamposIntervalo.setCamposIniciais(acessoGaragem);
if (acessoGaragem.isUsuarioVisitante()) {
checkVisitante(acessoGaragem);
} else {
checkServidorMembro(acessoGaragem);
}
return super.save(acessoGaragem);
}
private void checkVisitante(AcessoGaragem acessoGaragem) {
acessoGaragem.setMotorista(null);
checkVisita(acessoGaragem);
checkVeiculoVisitante(acessoGaragem);
}
private void checkVeiculoVisitante(AcessoGaragem acessoGaragem) {
Veiculo veiculo = acessoGaragem.getVeiculo();
if (!veiculoMediator.isVeiculoVisitante(veiculo)) {
throw new NegocioException("O veículo placa " + veiculo.getId() + " é uma viatura ou pertence a um servidor ou membro!");
}
acessoGaragem.setVeiculo(veiculoMediator.save(veiculo));
}
private void checkVisita(AcessoGaragem acessoGaragem) {
Visita visita = visitaMediator.findOne(Optional.of(acessoGaragem.getVisita().getId()));
LocalDate dataEntrada = visita.getEntradaAsLocalDate();
Integer idAcesso = acessoGaragem.getId();
if ((idAcesso == null && !dataEntrada.equals(LocalDate.now())) || (idAcesso != null && !dataEntrada.equals(acessoGaragem.getEntradaAsLocalDate()))) {
throw new NegocioException("A visita informada não foi cadastrada hoje!");
}
idAcesso = EntidadeUtil.getIdNaoNulo(acessoGaragem);
Integer idVisita = visita.getId();
if (acessoGaragemRepository.countByIdVisita(idVisita, idAcesso) > 0) {
throw new NegocioException("Já existe um acesso associado a visita selecionada!");
}
}
private void checkServidorMembro(AcessoGaragem acessoGaragem) {
String placa = acessoGaragem.getVeiculo().getId();
Veiculo veiculo = veiculoMediator.findByPlaca(placa);
if (veiculo == null) {
throw new NegocioException("Não foi encontrado veículo com a placa " + placa);
}
if (veiculo.getMotorista() == null) {
throw new NegocioException("Este veículo não possui dono!");
}
Integer idAcesso = EntidadeUtil.getIdNaoNulo(acessoGaragem);
Integer idMotorista = veiculo.getMotorista().getId();
if (acessoGaragemRepository.countAcessoMotoristaSemBaixa(idMotorista, idAcesso) > 0) {
throw new NegocioException("O servidor ou membro selecionado (" + idMotorista + ") já entrou na garagem e não saiu!");
}
checkConflitoIntervaloMembro.validar(acessoGaragem, placa);
acessoGaragem.setVeiculo(veiculo);
acessoGaragem.setMotorista(veiculo.getMotorista());
acessoGaragem.setVisita(null);
}
/**
* Buscar registros que ainda não possuem a data de saída.
*
* @return
*/
public List<AcessoGaragem> findAllSemBaixa() {
Local local = usuarioHolder.getLocal();
return acessoGaragemRepository.findBySaidaIsNullAndLocalOrderByEntrada(local);
}
/**
* Buscar o ultimo horario de entrada e saída de cada motorista.
*
* @param inicio
* @param fim
*
* @return
*/
public List<PessoaDisponibilidade> findUltimaDisponibilidade(Date inicio, Date fim) {
Integer idLocal = usuarioHolder.getLocal().getId();
List<PessoaDisponibilidade> acessos = acessoGaragemRepository.findUltimaDisponibilidade(inicio, fim, idLocal);
acessos.forEach(p -> p.setFonte(FonteDisponibilidade.ACESSO_GARAGEM));
return acessos;
}
@Override
public Class<? extends AbstractSpec<AcessoGaragem>> specClass() {
return AcessoGaragemSpec.class;
}
}
| mit |
Alex-BusNet/InfiniteStratos | src/main/java/com/sparta/is/core/utils/FluidStackUtils.java | 3383 | package com.sparta.is.core.utils;
import net.minecraftforge.fluids.FluidRegistry;
import net.minecraftforge.fluids.FluidStack;
import java.util.Comparator;
public class FluidStackUtils
{
public static final Comparator<FluidStack> COMPARATOR = (fluidStack1, fluidStack2) -> {
if (fluidStack1 != null && fluidStack2 != null) {
if (fluidStack1.getFluid() != null && fluidStack2.getFluid() != null) {
if (FluidRegistry.getFluidName(fluidStack1) != null && FluidRegistry.getFluidName(fluidStack2) != null) {
if (FluidRegistry.getFluidName(fluidStack1).equalsIgnoreCase(FluidRegistry.getFluidName(fluidStack2))) {
if (fluidStack1.amount == fluidStack2.amount) {
if (fluidStack1.tag != null && fluidStack2.tag != null) {
return fluidStack1.tag.hashCode() - fluidStack2.tag.hashCode();
}
else if (fluidStack1.tag != null) {
return -1;
}
else if (fluidStack2.tag != null) {
return 1;
}
else {
return 0;
}
}
else {
return fluidStack1.amount - fluidStack2.amount;
}
}
else {
return FluidRegistry.getFluidName(fluidStack1).compareToIgnoreCase(FluidRegistry.getFluidName(fluidStack2));
}
}
else if (FluidRegistry.getFluidName(fluidStack1) != null) {
return -1;
}
else if (FluidRegistry.getFluidName(fluidStack2) != null) {
return 1;
}
else {
return 0;
}
}
else if (fluidStack1.getFluid() != null) {
return -1;
}
else if (fluidStack2.getFluid() != null) {
return 1;
}
else {
return 0;
}
}
else if (fluidStack1 != null) {
return -1;
}
else if (fluidStack2 != null) {
return 1;
}
else {
return 0;
}
};
/**
* TODO Finish JavaDoc
*
* @param fluidStack1
* @param fluidStack2
* @return
*/
public static int compare(FluidStack fluidStack1, FluidStack fluidStack2) {
return COMPARATOR.compare(fluidStack1, fluidStack2);
}
/**
* TODO Finish JavaDoc
*
* @param fluidStack1
* @param fluidStack2
* @return
*/
public static boolean equals(FluidStack fluidStack1, FluidStack fluidStack2) {
return compare(fluidStack1, fluidStack2) == 0;
}
/**
* TODO Finish JavaDoc
*
* @param fluidStack
* @return
*/
public static String toString(FluidStack fluidStack) {
if (fluidStack != null) {
return String.format("%sxfluidStack.%s", fluidStack.amount, fluidStack.getFluid().getName());
}
return "fluidStack[null]";
}
}
| mit |
TheSilkMiner/OpenBlocks | src/main/java/openblocks/common/tileentity/TileEntityBlockPlacer.java | 5003 | package openblocks.common.tileentity;
import net.minecraft.block.Block;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.WorldServer;
import net.minecraftforge.common.capabilities.Capability;
import net.minecraftforge.items.CapabilityItemHandler;
import openblocks.client.gui.GuiBlockPlacer;
import openblocks.common.block.BlockBlockManpulatorBase;
import openblocks.common.block.BlockBlockPlacer;
import openblocks.common.container.ContainerBlockPlacer;
import openmods.api.IHasGui;
import openmods.api.IInventoryCallback;
import openmods.fakeplayer.FakePlayerPool;
import openmods.fakeplayer.UseItemAction;
import openmods.include.IncludeInterface;
import openmods.inventory.GenericInventory;
import openmods.inventory.IInventoryProvider;
import openmods.inventory.TileEntityInventory;
import openmods.utils.OptionalInt;
public class TileEntityBlockPlacer extends TileEntityBlockManipulator implements IHasGui, IInventoryProvider {
static final int BUFFER_SIZE = 9;
private boolean skipActionOnInventoryUpdate = false;
private final GenericInventory inventory = new TileEntityInventory(this, "blockPlacer", false, BUFFER_SIZE)
.addCallback(new IInventoryCallback() {
@Override
public void onInventoryChanged(IInventory inventory, OptionalInt slotNumber) {
markUpdated();
if (!skipActionOnInventoryUpdate && !worldObj.isRemote && isUpdateTriggering(inventory, slotNumber)) {
final IBlockState blockState = worldObj.getBlockState(getPos());
if (blockState.getBlock() instanceof BlockBlockPlacer &&
blockState.getValue(BlockBlockManpulatorBase.POWERED))
triggerBlockAction(blockState);
}
}
private boolean isUpdateTriggering(IInventory inventory, OptionalInt maybeSlotNumber) {
if (!maybeSlotNumber.isPresent()) return true; // full update, trigger everything
final int slotNumber = maybeSlotNumber.get();
return inventory.getStackInSlot(slotNumber) != null;
}
});
@Override
protected boolean canWork(IBlockState targetState, BlockPos target, EnumFacing direction) {
if (inventory.isEmpty()) return false;
final Block block = targetState.getBlock();
return block.isAir(targetState, worldObj, target) || block.isReplaceable(worldObj, target);
}
@Override
protected void doWork(IBlockState targetState, BlockPos target, EnumFacing direction) {
ItemStack stack = null;
int slotId = 0;
for (slotId = 0; slotId < inventory.getSizeInventory(); slotId++) {
stack = inventory.getStackInSlot(slotId);
if (stack != null && stack.stackSize > 0) break;
}
if (stack == null) return;
// this logic is tuned for vanilla blocks (like pistons), which places blocks with front facing player
// so to place object pointing in the same direction as placer, we need configuration player-target-placer
// * 2, since some blocks may take into account player height, so distance must be greater than that
final BlockPos playerPos = target.offset(direction, 2);
final ItemStack result = FakePlayerPool.instance.executeOnPlayer((WorldServer)worldObj, new UseItemAction(
stack,
new Vec3d(playerPos),
new Vec3d(target),
new Vec3d(target).addVector(0.5, 0.5, 0.5),
direction.getOpposite(),
EnumHand.MAIN_HAND));
if (!ItemStack.areItemStacksEqual(result, stack)) {
skipActionOnInventoryUpdate = true;
try {
inventory.setInventorySlotContents(slotId, result);
} finally {
skipActionOnInventoryUpdate = false;
}
}
}
@Override
public Object getServerGui(EntityPlayer player) {
return new ContainerBlockPlacer(player.inventory, this);
}
@Override
public Object getClientGui(EntityPlayer player) {
return new GuiBlockPlacer(new ContainerBlockPlacer(player.inventory, this));
}
@Override
public boolean canOpenGui(EntityPlayer player) {
return true;
}
@Override
@IncludeInterface
public IInventory getInventory() {
return inventory;
}
@Override
public NBTTagCompound writeToNBT(NBTTagCompound tag) {
tag = super.writeToNBT(tag);
inventory.writeToNBT(tag);
return tag;
}
@Override
public void readFromNBT(NBTTagCompound tag) {
super.readFromNBT(tag);
inventory.readFromNBT(tag);
}
@Override
public boolean hasCapability(Capability<?> capability, EnumFacing facing) {
return capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY || super.hasCapability(capability, facing);
}
@Override
@SuppressWarnings("unchecked")
public <T> T getCapability(Capability<T> capability, EnumFacing facing) {
if (capability == CapabilityItemHandler.ITEM_HANDLER_CAPABILITY)
return (T)inventory.getHandler();
return super.getCapability(capability, facing);
}
}
| mit |
dusadpiyush96/Competetive | HackerRank/Algorithm/Implementation/BeautifulDaysAtTheMovies.java | 1023 | import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static boolean isBeautiful(int x,int k){
ArrayList<Integer> list = new ArrayList<Integer>();
int num = x;
while(num!=0){
list.add(num%10);
num/=10;
}
int fac=1;
int xRev=0;
for(int i=list.size()-1;i>=0;i--){
xRev=xRev+list.get(i)*fac;
fac*=10;
}
if(Math.abs(x-xRev)%k==0) return true;
else return false;
}
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner sc=new Scanner(System.in);
int i=sc.nextInt();
int j=sc.nextInt();
int k=sc.nextInt();
int count=0;
for(int a=i;a<=j;a++){
if(isBeautiful(a,k)) count++;
}
System.out.println(count);
}
} | mit |
aterai/java-swing-tips | CursorOfCellComponent/src/java/example/MainPanel.java | 3686 | // -*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
// @homepage@
package example;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.util.Optional;
import java.util.stream.Stream;
import javax.swing.*;
public final class MainPanel extends JPanel {
private MainPanel() {
super(new BorderLayout());
DefaultListModel<String> model = new DefaultListModel<>();
Stream.of("aa", "bbb bbb bbb bb bb", "ccc", "ddd ddd ddd", "eee eee").forEach(model::addElement);
add(new JScrollPane(new LinkCellList<>(model)));
setPreferredSize(new Dimension(320, 240));
}
public static void main(String[] args) {
EventQueue.invokeLater(MainPanel::createAndShowGui);
}
private static void createAndShowGui() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
Toolkit.getDefaultToolkit().beep();
}
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class LinkCellList<E> extends JList<E> {
private int prevIndex = -1;
protected LinkCellList(ListModel<E> model) {
super(model);
}
@Override public void updateUI() {
setForeground(null);
setBackground(null);
setSelectionForeground(null);
setSelectionBackground(null);
super.updateUI();
setFixedCellHeight(32);
setCellRenderer(new LinkCellRenderer<>());
// TEST: putClientProperty("List.isFileList", Boolean.TRUE);
}
@Override protected void processMouseMotionEvent(MouseEvent e) {
Point pt = e.getPoint();
int i = locationToIndex(pt);
E s = getModel().getElementAt(i);
Component c = getCellRenderer().getListCellRendererComponent(this, s, i, false, false);
Rectangle r = getCellBounds(i, i);
c.setBounds(r);
if (prevIndex != i) {
c.doLayout();
}
prevIndex = i;
pt.translate(-r.x, -r.y);
setCursor(Optional.ofNullable(SwingUtilities.getDeepestComponentAt(c, pt.x, pt.y))
.map(Component::getCursor)
.orElse(Cursor.getDefaultCursor()));
}
}
class LinkCellRenderer<E> implements ListCellRenderer<E> {
private final JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));
private final JCheckBox check = new JCheckBox("check") {
@Override public void updateUI() {
super.updateUI();
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
setOpaque(false);
}
};
private final JButton button = new JButton("button") {
@Override public void updateUI() {
super.updateUI();
setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
}
};
private final JLabel label = new JLabel() {
@Override public void updateUI() {
super.updateUI();
setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
}
};
@Override public Component getListCellRendererComponent(JList<? extends E> list, E value, int index, boolean isSelected, boolean cellHasFocus) {
panel.removeAll();
panel.add(label);
panel.add(check);
panel.add(button);
panel.setOpaque(true);
if (isSelected) {
panel.setBackground(list.getSelectionBackground());
panel.setForeground(list.getSelectionForeground());
} else {
panel.setBackground(list.getBackground());
panel.setForeground(list.getForeground());
}
label.setText("<html><a href='#'>" + value);
return panel;
}
}
| mit |
Ashmouth/ProjetCPS | src/streetfighter/main/MainBugEngine.java | 1307 | package streetfighter.main;
import java.awt.Dimension;
import java.awt.Toolkit;
import streetfighter.contracts.EngineContract;
import streetfighter.contracts.FightCharContract;
import streetfighter.contracts.PlayerContract;
import streetfighter.implem.Display;
import streetfighter.implem.FightChar;
import streetfighter.implem.Player;
import streetfighter.implembug.EngineBug;
import streetfighter.services.DisplayService;
import streetfighter.services.EngineService;
import streetfighter.services.FightCharService;
import streetfighter.services.PlayerService;
public class MainBugEngine {
public static void main(String[] args) {
// Engine
EngineService engine = new EngineContract(new EngineBug());
PlayerService p1 = new PlayerContract(new Player());
PlayerService p2 = new PlayerContract(new Player());
FightCharService c1 = new FightCharContract(new FightChar());
FightCharService c2 = new FightCharContract(new FightChar());
c1.init(600, 4, true, engine); // tank
c2.init(150, 10, false, engine); // squishy
p1.init(1);
p2.init(2);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
engine.init(screenSize.width, screenSize.height, 200, p1, p2, c1, c2);
// Display
DisplayService display = new Display();
display.init(engine);
}
}
| mit |
karim/adila | database/src/main/java/adila/db/zte2dv988_zte20v988.java | 201 | // This file is automatically generated.
package adila.db;
/*
* ZTE
*
* DEVICE: ZTE-V988
* MODEL: ZTE V988
*/
final class zte2dv988_zte20v988 {
public static final String DATA = "ZTE||";
}
| mit |
testpress/android | app/src/main/java/in/testpress/testpress/ui/TestpressViewPager.java | 871 | package in.testpress.testpress.ui;
import android.content.Context;
import androidx.viewpager.widget.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
public class TestpressViewPager extends ViewPager {
private boolean enabled;
public TestpressViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
this.enabled = true;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (this.enabled) {
return super.onTouchEvent(event);
}
return false;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
if (this.enabled) {
return super.onInterceptTouchEvent(event);
}
return false;
}
public void setPagingEnabled(boolean enabled) {
this.enabled = enabled;
}
}
| mit |
stefanvstein/stonehorse.candy | src/test/java/stonehorse/candy/A.java | 210 | package stonehorse.candy;
public class A{
public static A a(){
return new A();
}
public static class B extends A{
public static B b(){
return new B();
}
}
}
| mit |
Intel-HLS/GKL | src/test/java/com/intel/gkl/compression/IntelInflaterFactoryUnitTest.java | 812 | package com.intel.gkl.compression;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.util.zip.Inflater;
public class IntelInflaterFactoryUnitTest {
@Test
public void IntelInflaterFactoryReturnsIntelInflaterIfGzipIsSetTest(){
IntelInflaterFactory intelInflaterFactory = new IntelInflaterFactory();
Inflater intelInflater = intelInflaterFactory.makeInflater( true);
Assert.assertTrue(intelInflater instanceof IntelInflater);
}
@Test
public void IntelInflaterFactoryReturnsJavaInflaterIfGzipIsNotSetTest(){
IntelInflaterFactory intelInflaterFactory = new IntelInflaterFactory();
Inflater intelInflater = intelInflaterFactory.makeInflater( false);
Assert.assertFalse(intelInflater instanceof IntelInflater);
}
}
| mit |
aJetHorn/Beginner-Java-Projects | 3.booleans/src/BirthMonth.java | 1936 | import java.util.Scanner;
public class BirthMonth {
public static void main(String args[]){
Scanner input = new Scanner(System.in);
System.out.println("What (numeric) month were you born in? ");
int month = input.nextInt();
if (month <= 12 && month > 0) // checks that the value is between 1 and 12
{
System.out.print("You were born in the same month as ");
switch (month) //the case values below correspond to months beginning with January
{
case 1:
System.out.print("Douglas Engelbart");
break;
case 2:
System.out.print("Steve Jobs");
break;
case 3:
System.out.print("Richard Stallman");
break;
case 4:
System.out.print("Claude Shannon");
break;
case 5:
System.out.print("James Gosling");
break;
case 6:
System.out.print("Alan Turing");
break;
case 7:
System.out.print("Marc Andreessen");
break;
case 8:
System.out.print("Sergey Brin");
break;
case 9:
System.out.print("Dennis Ritchie");
break;
case 10:
System.out.print("Bill Gates");
break;
case 11:
System.out.print("Geore Boole");
break;
case 12:
System.out.print("Grace Hopper");
break;
default:
}
}
else //if month < 1 or month > 12
System.out.println("Invalid Month");
}
}
| mit |
pdeboer/wikilanguage | lib/graphchi-java/src/main/java/com/twitter/pers/graph_generator/EdgeListOutput.java | 1571 | package com.twitter.pers.graph_generator;
import java.io.*;
/**
* @author Aapo Kyrola, akyrola@cs.cmu.edu, akyrola@twitter.com
*/
public class EdgeListOutput implements GraphOutput {
private String fileNamePrefix;
static int partSeq = 0;
public EdgeListOutput(String fileNamePrefix) {
this.fileNamePrefix = fileNamePrefix;
}
@Override
public void addEdges(int[] from, int[] to) {
try {
BufferedWriter dos = partitionOut.get();
int n = from.length;
for(int i=0; i<n; i++) {
dos.write(from[i] + "\t" + to[i] + "\n");
}
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
}
public void finishUp() {
try {
partitionOut.get().close();
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
}
/* Each thread will have a local partition */
private ThreadLocal<BufferedWriter> partitionOut = new ThreadLocal<BufferedWriter>() {
@Override
protected BufferedWriter initialValue() {
try {
int thisPartId;
synchronized (this) {
thisPartId = partSeq++;
}
String fileName = fileNamePrefix + "-part" + thisPartId;
return new BufferedWriter(new FileWriter(fileName));
} catch (Exception err) {
err.printStackTrace();
throw new RuntimeException(err);
}
}
};
}
| mit |
zkastl/EagleCatering | EagleEventPlanning/src/ProblemDomain/Token.java | 2108 | package ProblemDomain;
import java.io.Serializable;
import java.math.BigInteger;
import java.security.SecureRandom;
import java.time.LocalDate;
import java.util.Random;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import DataAccessObjects.TokenDAO;
@XmlRootElement(name = "token")
@Entity(name = "token")
public class Token implements Serializable {
private static final long serialVersionUID = 1L;
@Id // signifies the primary key
@Column(name = "token_id", nullable = false)
@GeneratedValue(strategy = GenerationType.AUTO)
private long tokenID;
@Column(name = "token", nullable = false, length = 40)
private String token;
@Column(name = "expire_date")
private LocalDate expireDate;
@ManyToOne(optional = false)
@JoinColumn(name = "eventPlanner_id", referencedColumnName = "eventPlanner_id")
private EventPlanner planner;
public Token() {
};
public Token(EventPlanner planner) {
setEventPlanner(planner);
Random random = new SecureRandom();
String token = new BigInteger(130, random).toString(32);
setToken(token);
setExpireDate(LocalDate.now());
}
public long getTokenID() {
return this.tokenID;
}
public void setTokenID(long tokenID) {
this.tokenID = tokenID;
}
public String getToken() {
return this.token;
}
@XmlElement
public void setToken(String token) {
this.token = token;
}
public LocalDate getExpireDate() {
return this.expireDate;
}
@XmlElement
public void setExpireDate(LocalDate expireDate) {
this.expireDate = expireDate;
}
public EventPlanner getEventPlanner() {
return this.planner;
}
@XmlElement
public void setEventPlanner(EventPlanner planner) {
this.planner = planner;
}
public Boolean validate() {
return LocalDate.now().equals(getExpireDate());
}
public void save() {
TokenDAO.saveToken(this);
}
} | mit |
venanciolm/afirma-ui-miniapplet_x_x | afirma_ui_miniapplet/src/main/java/com/lowagie/text/pdf/PdfShading.java | 10086 | /*
* Copyright 2002 Paulo Soares
*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the License.
*
* The Original Code is 'iText, a free JAVA-PDF library'.
*
* The Initial Developer of the Original Code is Bruno Lowagie. Portions created by
* the Initial Developer are Copyright (C) 1999, 2000, 2001, 2002 by Bruno Lowagie.
* All Rights Reserved.
* Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer
* are Copyright (C) 2000, 2001, 2002 by Paulo Soares. All Rights Reserved.
*
* Contributor(s): all the names of the contributors are added in the source code
* where applicable.
*
* Alternatively, the contents of this file may be used under the terms of the
* LGPL license (the "GNU LIBRARY GENERAL PUBLIC LICENSE"), in which case the
* provisions of LGPL are applicable instead of those above. If you wish to
* allow use of your version of this file only under the terms of the LGPL
* License and not to allow others to use your version of this file under
* the MPL, indicate your decision by deleting the provisions above and
* replace them with the notice and other provisions required by the LGPL.
* If you do not delete the provisions above, a recipient may use your version
* of this file under either the MPL or the GNU LIBRARY GENERAL PUBLIC LICENSE.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the MPL as stated above or under the terms of the GNU
* Library General Public License as published by the Free Software Foundation;
* either version 2 of the License, or 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 Library general Public License for more
* details.
*
* If you didn't download this code from the following link, you should check if
* you aren't using an obsolete version:
* http://www.lowagie.com/iText/
*/
package com.lowagie.text.pdf;
import java.awt.Color;
import java.io.IOException;
/** Implements the shading dictionary (or stream).
*
* @author Paulo Soares (psoares@consiste.pt)
*/
public class PdfShading {
private PdfDictionary shading;
private final PdfWriter writer;
private int shadingType;
private ColorDetails colorDetails;
private PdfName shadingName;
private PdfIndirectReference shadingReference;
private Color cspace;
/** Holds value of property bBox. */
private float[] bBox;
/** Holds value of property antiAlias. */
private boolean antiAlias = false;
/** Creates new PdfShading */
private PdfShading(final PdfWriter writer) {
this.writer = writer;
}
private void setColorSpace(final Color color) {
this.cspace = color;
final int type = ExtendedColor.getType(color);
PdfObject colorSpace = null;
switch (type) {
case ExtendedColor.TYPE_GRAY: {
colorSpace = PdfName.DEVICEGRAY;
break;
}
case ExtendedColor.TYPE_CMYK: {
colorSpace = PdfName.DEVICECMYK;
break;
}
case ExtendedColor.TYPE_SEPARATION: {
final SpotColor spot = (SpotColor)color;
this.colorDetails = this.writer.addSimple(spot.getPdfSpotColor());
colorSpace = this.colorDetails.getIndirectReference();
break;
}
case ExtendedColor.TYPE_PATTERN:
case ExtendedColor.TYPE_SHADING: {
throwColorSpaceError();
}
default:
colorSpace = PdfName.DEVICERGB;
break;
}
this.shading.put(PdfName.COLORSPACE, colorSpace);
}
public Color getColorSpace() {
return this.cspace;
}
private static void throwColorSpaceError() {
throw new IllegalArgumentException("A tiling or shading pattern cannot be used as a color space in a shading pattern");
}
private static void checkCompatibleColors(final Color c1, final Color c2) {
final int type1 = ExtendedColor.getType(c1);
final int type2 = ExtendedColor.getType(c2);
if (type1 != type2) {
throw new IllegalArgumentException("Both colors must be of the same type.");
}
if (type1 == ExtendedColor.TYPE_SEPARATION && ((SpotColor)c1).getPdfSpotColor() != ((SpotColor)c2).getPdfSpotColor()) {
throw new IllegalArgumentException("The spot color must be the same, only the tint can vary.");
}
if (type1 == ExtendedColor.TYPE_PATTERN || type1 == ExtendedColor.TYPE_SHADING) {
throwColorSpaceError();
}
}
private static float[] getColorArray(final Color color) {
final int type = ExtendedColor.getType(color);
switch (type) {
case ExtendedColor.TYPE_GRAY: {
return new float[]{((GrayColor)color).getGray()};
}
case ExtendedColor.TYPE_CMYK: {
final CMYKColor cmyk = (CMYKColor)color;
return new float[]{cmyk.getCyan(), cmyk.getMagenta(), cmyk.getYellow(), cmyk.getBlack()};
}
case ExtendedColor.TYPE_SEPARATION: {
return new float[]{((SpotColor)color).getTint()};
}
case ExtendedColor.TYPE_RGB: {
return new float[]{color.getRed() / 255f, color.getGreen() / 255f, color.getBlue() / 255f};
}
}
throwColorSpaceError();
return null;
}
private static PdfShading type2(final PdfWriter writer, final Color colorSpace, final float coords[], final float domain[], final PdfFunction function, final boolean extend[]) {
final PdfShading sp = new PdfShading(writer);
sp.shading = new PdfDictionary();
sp.shadingType = 2;
sp.shading.put(PdfName.SHADINGTYPE, new PdfNumber(sp.shadingType));
sp.setColorSpace(colorSpace);
sp.shading.put(PdfName.COORDS, new PdfArray(coords));
if (domain != null) {
sp.shading.put(PdfName.DOMAIN, new PdfArray(domain));
}
sp.shading.put(PdfName.FUNCTION, function.getReference());
if (extend != null && (extend[0] || extend[1])) {
final PdfArray array = new PdfArray(extend[0] ? PdfBoolean.PDFTRUE : PdfBoolean.PDFFALSE);
array.add(extend[1] ? PdfBoolean.PDFTRUE : PdfBoolean.PDFFALSE);
sp.shading.put(PdfName.EXTEND, array);
}
return sp;
}
private static PdfShading type3(final PdfWriter writer, final Color colorSpace, final float coords[], final float domain[], final PdfFunction function, final boolean extend[]) {
final PdfShading sp = type2(writer, colorSpace, coords, domain, function, extend);
sp.shadingType = 3;
sp.shading.put(PdfName.SHADINGTYPE, new PdfNumber(sp.shadingType));
return sp;
}
private static PdfShading simpleAxial(final PdfWriter writer, final float x0, final float y0, final float x1, final float y1, final Color startColor, final Color endColor, final boolean extendStart, final boolean extendEnd) {
checkCompatibleColors(startColor, endColor);
final PdfFunction function = PdfFunction.type2(writer, new float[]{0, 1}, null, getColorArray(startColor),
getColorArray(endColor), 1);
return type2(writer, startColor, new float[]{x0, y0, x1, y1}, null, function, new boolean[]{extendStart, extendEnd});
}
static PdfShading simpleAxial(final PdfWriter writer, final float x0, final float y0, final float x1, final float y1, final Color startColor, final Color endColor) {
return simpleAxial(writer, x0, y0, x1, y1, startColor, endColor, true, true);
}
private static PdfShading simpleRadial(final PdfWriter writer, final float x0, final float y0, final float r0, final float x1, final float y1, final float r1, final Color startColor, final Color endColor, final boolean extendStart, final boolean extendEnd) {
checkCompatibleColors(startColor, endColor);
final PdfFunction function = PdfFunction.type2(writer, new float[]{0, 1}, null, getColorArray(startColor),
getColorArray(endColor), 1);
return type3(writer, startColor, new float[]{x0, y0, r0, x1, y1, r1}, null, function, new boolean[]{extendStart, extendEnd});
}
PdfName getShadingName() {
return this.shadingName;
}
PdfIndirectReference getShadingReference() {
if (this.shadingReference == null) {
this.shadingReference = this.writer.getPdfIndirectReference();
}
return this.shadingReference;
}
void setName(final int number) {
this.shadingName = new PdfName("Sh" + number);
}
void addToBody() throws IOException {
if (this.bBox != null) {
this.shading.put(PdfName.BBOX, new PdfArray(this.bBox));
}
if (this.antiAlias) {
this.shading.put(PdfName.ANTIALIAS, PdfBoolean.PDFTRUE);
}
this.writer.addToBody(this.shading, getShadingReference());
}
PdfWriter getWriter() {
return this.writer;
}
ColorDetails getColorDetails() {
return this.colorDetails;
}
public float[] getBBox() {
return this.bBox;
}
public void setBBox(final float[] bBox) {
if (bBox.length != 4) {
throw new IllegalArgumentException("BBox must be a 4 element array.");
}
this.bBox = bBox;
}
public boolean isAntiAlias() {
return this.antiAlias;
}
public void setAntiAlias(final boolean antiAlias) {
this.antiAlias = antiAlias;
}
}
| mit |
mbuzdalov/non-dominated-sorting | implementations/src/test/java/ru/ifmo/nds/tests/DeductiveSortTest.java | 294 | package ru.ifmo.nds.tests;
import ru.ifmo.nds.DeductiveSort;
import ru.ifmo.nds.NonDominatedSortingFactory;
public class DeductiveSortTest extends CorrectnessTestsBase {
@Override
protected NonDominatedSortingFactory getFactory() {
return DeductiveSort.getInstance();
}
}
| mit |
anedyalkov/Software-Technologies | Exam Preparation I-TODO List/Java Skeleton/src/main/java/todolist/controller/TaskController.java | 2423 | package todolist.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import todolist.bindingModel.TaskBindingModel;
import todolist.entity.Task;
import todolist.repository.TaskRepository;
import java.util.List;
@Controller
public class TaskController {
private final TaskRepository taskRepository;
@Autowired
public TaskController(TaskRepository taskRepository) {
this.taskRepository = taskRepository;
}
@GetMapping("/")
public String index(Model model) {
List<Task> tasks = taskRepository.findAll();
model.addAttribute("tasks", tasks);
model.addAttribute("view", "task/index");
return "base-layout";
}
@GetMapping("/create")
public String create(Model model) {
model.addAttribute("task", new TaskBindingModel());
model.addAttribute("view", "task/create");
return "base-layout";
}
@PostMapping("/create")
public String createProcess(Model model, TaskBindingModel taskBindingModel) {
if (taskBindingModel.getTitle().equals("") ||
taskBindingModel.getComments().equals("")) {
model.addAttribute("task", taskBindingModel);
model.addAttribute("view", "task/create");
return "base-layout";
}
Task task = new Task();
task.setTitle(taskBindingModel.getTitle());
task.setComments(taskBindingModel.getComments());
taskRepository.saveAndFlush(task);
return "redirect:/";
}
@GetMapping("/delete/{id}")
public String delete(Model model, @PathVariable int id) {
Task task = taskRepository.findOne(id);
if (task != null) {
model.addAttribute("task", task);
model.addAttribute("view", "task/delete");
return "base-layout";
}
return "redirect:/";
}
@PostMapping("/delete/{id}")
public String deleteProcess(Model model, @PathVariable int id) {
try {
taskRepository.delete(id);
} catch (Exception ex) {
// Task was not found -> do nothing
}
return "redirect:/";
}
}
| mit |
fpauer/Full-Screen-Video-Android | FullScreenVideo/src/com/example/fullscreenvideo/MainActivity.java | 1289 | package com.example.fullscreenvideo;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnPlayVideo = (Button) findViewById(R.id.btnPlayVideo);
btnPlayVideo.setOnClickListener( new View.OnClickListener() {
@Override
public void onClick(View v) {
String videoPath = "android.resource://" + getPackageName() + "/" + R.raw.video_test;
playVideo( videoPath );
}
});
}
private void playVideo(String videoPath) {
Intent videoPlaybackActivity = new Intent(this, VideoPlayerActivity.class);
videoPlaybackActivity.putExtra("videoPath", videoPath);
startActivity(videoPlaybackActivity);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
| mit |
otiasj/AndroidMemoryLogger | MemoryLogger/src/com/otiasj/memoryLogger/view/OnClickOverlayListener.java | 132 | package com.otiasj.memoryLogger.view;
public interface OnClickOverlayListener {
public void onClick(SystemOverlay rootview);
}
| mit |
NucleusPowered/Nucleus | nucleus-modules/src/main/java/io/github/nucleuspowered/nucleus/modules/misc/commands/SpeedCommand.java | 7535 | /*
* This file is part of Nucleus, licensed under the MIT License (MIT). See the LICENSE.txt file
* at the root of this project for more details.
*/
package io.github.nucleuspowered.nucleus.modules.misc.commands;
import com.google.inject.Inject;
import io.github.nucleuspowered.nucleus.modules.misc.MiscPermissions;
import io.github.nucleuspowered.nucleus.modules.misc.config.MiscConfig;
import io.github.nucleuspowered.nucleus.core.scaffold.command.ICommandContext;
import io.github.nucleuspowered.nucleus.core.scaffold.command.ICommandExecutor;
import io.github.nucleuspowered.nucleus.core.scaffold.command.ICommandResult;
import io.github.nucleuspowered.nucleus.core.scaffold.command.annotation.Command;
import io.github.nucleuspowered.nucleus.core.scaffold.command.annotation.CommandModifier;
import io.github.nucleuspowered.nucleus.core.scaffold.command.annotation.EssentialsEquivalent;
import io.github.nucleuspowered.nucleus.core.scaffold.command.modifier.CommandModifiers;
import io.github.nucleuspowered.nucleus.core.services.INucleusServiceCollection;
import io.github.nucleuspowered.nucleus.core.services.interfaces.IReloadableService;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.LinearComponents;
import net.kyori.adventure.text.format.NamedTextColor;
import org.spongepowered.api.command.exception.CommandException;
import org.spongepowered.api.command.parameter.Parameter;
import org.spongepowered.api.command.parameter.managed.standard.VariableValueParameters;
import org.spongepowered.api.data.DataTransactionResult;
import org.spongepowered.api.data.Key;
import org.spongepowered.api.data.Keys;
import org.spongepowered.api.data.value.Value;
import org.spongepowered.api.entity.living.player.Player;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
@EssentialsEquivalent(value = {"speed", "flyspeed", "walkspeed", "fspeed", "wspeed"}, isExact = false,
notes = "This command either uses your current state or a specified argument to determine whether to alter fly or walk speed.")
@Command(
aliases = "speed",
basePermission = MiscPermissions.BASE_SPEED,
commandDescriptionKey = "speed",
modifiers = {
@CommandModifier(value = CommandModifiers.HAS_WARMUP, exemptPermission = MiscPermissions.EXEMPT_WARMUP_SPEED),
@CommandModifier(value = CommandModifiers.HAS_COOLDOWN, exemptPermission = MiscPermissions.EXEMPT_COOLDOWN_SPEED),
@CommandModifier(value = CommandModifiers.HAS_COST, exemptPermission = MiscPermissions.EXEMPT_COST_SPEED)
},
associatedPermissions = {
MiscPermissions.SPEED_EXEMPT_MAX,
MiscPermissions.OTHERS_SPEED
}
)
public class SpeedCommand implements ICommandExecutor, IReloadableService.Reloadable { //extends AbstractCommand.SimpleTargetOtherPlayer
/**
* As the standard flying speed is 0.05 and the standard walking speed is
* 0.1, we multiply it by 20 and use integers. Standard walking speed is
* therefore 2, standard flying speed - 1.
*/
public static final int multiplier = 20;
private int maxSpeed = 5;
private final Parameter.Value<SpeedType> speedTypeParameter;
private final Parameter.Value<Double> speed = Parameter.builder(Double.class)
.addParser(VariableValueParameters.doubleRange().min(0.0).build())
.key("speed")
.build();
private final Parameter.Value<Boolean> reset = Parameter.builder(Boolean.class)
.key("reset")
.addParser(VariableValueParameters.literalBuilder(Boolean.class).literal(Collections.singleton("reset")).build())
.build();
@Inject
public SpeedCommand() {
final Map<String, SpeedType> keysMap = new HashMap<>();
keysMap.put("fly", SpeedType.FLYING);
keysMap.put("flying", SpeedType.FLYING);
keysMap.put("f", SpeedType.FLYING);
keysMap.put("walk", SpeedType.WALKING);
keysMap.put("w", SpeedType.WALKING);
this.speedTypeParameter = Parameter.builder(SpeedType.class)
.key("type")
.optional()
.addParser(VariableValueParameters.staticChoicesBuilder(SpeedType.class).addChoices(keysMap).build())
.build();
}
@Override
public Parameter[] parameters(final INucleusServiceCollection serviceCollection) {
return new Parameter[] {
serviceCollection.commandElementSupplier().createOnlyOtherPlayerPermissionElement(MiscPermissions.OTHERS_SPEED),
this.speedTypeParameter,
Parameter.firstOfBuilder(this.speed).or(this.reset).optional().build()
};
}
@Override
public ICommandResult execute(final ICommandContext context) throws CommandException {
final Player pl = context.getPlayerFromArgs();
final SpeedType key = context.getOne(this.speedTypeParameter)
.orElseGet(() -> pl.get(Keys.IS_FLYING).orElse(false) ? SpeedType.FLYING : SpeedType.WALKING);
final Double speed = context.getOne(this.speed).orElseGet(() -> {
if (context.hasAny(this.reset)) {
return key == SpeedType.WALKING ? 2.0d : 1.0d;
}
return null;
});
if (speed == null) {
final Component t = LinearComponents.linear(
context.getMessage("command.speed.walk"),
Component.space(),
Component.text(pl.get(Keys.WALKING_SPEED).orElse(0.1d) * SpeedCommand.multiplier, NamedTextColor.YELLOW),
Component.text(", ", NamedTextColor.GREEN),
context.getMessage("command.speed.flying").color(NamedTextColor.GREEN),
Component.text(pl.get(Keys.FLYING_SPEED).orElse(0.1d) * SpeedCommand.multiplier, NamedTextColor.YELLOW),
Component.text(".", NamedTextColor.GREEN));
context.sendMessageText(t);
// Don't trigger cooldowns
return context.failResult();
}
if (speed < 0) {
return context.errorResult("command.speed.negative");
}
if (!context.isConsoleAndBypass() && !context.testPermission(MiscPermissions.SPEED_EXEMPT_MAX) && this.maxSpeed < speed) {
return context.errorResult("command.speed.max", String.valueOf(this.maxSpeed));
}
final DataTransactionResult dtr = pl.offer(key.speedKey, speed / (double) multiplier);
if (dtr.isSuccessful()) {
context.sendMessage("command.speed.success.base", key.name, String.valueOf(speed));
if (!context.is(pl)) {
context.sendMessage("command.speed.success.other", pl.name(), key.name, String.valueOf(speed));
}
return context.successResult();
}
return context.errorResult("command.speed.fail", key.name);
}
@Override public void onReload(final INucleusServiceCollection serviceCollection) {
this.maxSpeed = serviceCollection.configProvider().getModuleConfig(MiscConfig.class).getMaxSpeed();
}
private enum SpeedType {
WALKING(Keys.WALKING_SPEED, "loc:standard.walking"),
FLYING(Keys.FLYING_SPEED, "loc:standard.flying");
final Key<Value<Double>> speedKey;
final String name;
SpeedType(final Key<Value<Double>> speedKey, final String name) {
this.speedKey = speedKey;
this.name = name;
}
}
}
| mit |
blackdoor/breaker | src/main/java/black/door/breaker/CircuitBreakerClosedException.java | 285 | package black.door.breaker;
/**
* Created by nfischer on 3/12/2016.
*/
public class CircuitBreakerClosedException extends Exception{
public CircuitBreakerClosedException(){
super("Breaker is closed. Retry later or manually reset the breaker " +
"with Breaker#reset()");
}
}
| mit |
kenyonduan/amazon-mws | src/main/java/com/amazonservices/mws/finances/MWSFinancesServiceAsync.java | 3940 | /*******************************************************************************
* Copyright 2009-2017 Amazon Services. 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://aws.amazon.com/apache2.0
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*******************************************************************************
* MWS Finances Service
* API Version: 2015-05-01
* Library Version: 2017-07-26
* Generated: Tue Jul 25 12:48:56 UTC 2017
*/
package com.amazonservices.mws.finances;
import java.util.concurrent.Future;
import com.amazonservices.mws.finances.model.*;
/**
* MWSFinances is a service that provides MWS developers access to Sellers
* payments data coming from all types of seller transactions
* which affect the seller account balance
*/
public interface MWSFinancesServiceAsync extends MWSFinancesService {
/**
* List Financial Event Groups
*
* ListFinancialEventGroups can be used to find financial event groups that meet filter criteria.
*
* @param request
* ListFinancialEventGroupsRequest request.
*
* @return Future<ListFinancialEventGroupsResponse> response.
*/
Future<ListFinancialEventGroupsResponse> listFinancialEventGroupsAsync(
ListFinancialEventGroupsRequest request);
/**
* List Financial Event Groups By Next Token
*
* If ListFinancialEventGroups returns a nextToken, thus indicating that there are more groups
* than returned that matched the given filter criteria, ListFinancialEventGroupsByNextToken
* can be used to retrieve those groups using that nextToken.
*
* @param request
* ListFinancialEventGroupsByNextTokenRequest request.
*
* @return Future<ListFinancialEventGroupsByNextTokenResponse> response.
*/
Future<ListFinancialEventGroupsByNextTokenResponse> listFinancialEventGroupsByNextTokenAsync(
ListFinancialEventGroupsByNextTokenRequest request);
/**
* List Financial Events
*
* ListFinancialEvents can be used to find financial events that meet the specified criteria.
*
* @param request
* ListFinancialEventsRequest request.
*
* @return Future<ListFinancialEventsResponse> response.
*/
Future<ListFinancialEventsResponse> listFinancialEventsAsync(
ListFinancialEventsRequest request);
/**
* List Financial Events By Next Token
*
* If ListFinancialEvents returns a nextToken, thus indicating that there are more financial events
* than returned that matched the given filter criteria, ListFinancialEventsByNextToken
* can be used to retrieve those events using that nextToken.
*
* @param request
* ListFinancialEventsByNextTokenRequest request.
*
* @return Future<ListFinancialEventsByNextTokenResponse> response.
*/
Future<ListFinancialEventsByNextTokenResponse> listFinancialEventsByNextTokenAsync(
ListFinancialEventsByNextTokenRequest request);
/**
* Get Service Status
*
*
*
* @param request
* GetServiceStatusRequest request.
*
* @return Future<GetServiceStatusResponse> response.
*/
Future<GetServiceStatusResponse> getServiceStatusAsync(
GetServiceStatusRequest request);
@Override
default ListFinancialEventGroupsResponse listFinancialEventGroups(
ListFinancialEventGroupsRequest request) throws MWSFinancesServiceException {
return null;
}
} | mit |
ProfLuz/Karus-Commons | src/test/java/com/karuslabs/commons/configuration/Yaml.java | 1613 | /*
* The MIT License
*
* Copyright 2017 Karus Labs.
*
* 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 com.karuslabs.commons.configuration;
import org.bukkit.configuration.ConfigurationSection;
import static com.karuslabs.commons.configuration.Configurations.from;
public class Yaml {
public static final ConfigurationSection COMMANDS = from(Yaml.class.getClassLoader().getResourceAsStream("command/commands.yml"));
public static final ConfigurationSection INVALID = from(Yaml.class.getClassLoader().getResourceAsStream("command/invalid.yml"));
}
| mit |
gems-uff/ada | src/main/java/br/uff/ic/archd/db/dao/OriginalNameDao.java | 574 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package br.uff.ic.archd.db.dao;
import java.util.List;
/**
*
* @author wallace
*/
public interface OriginalNameDao {
public void save(String artifactName, String originalName);
public String getOriginalName(String artifactSignature);
public List<String> getArtifactsAlternativesNames(String originalName);
public void save(List<String> artifactNames);
}
| mit |
dru1/wicketblog | src/main/java/at/dru/wicketblog/wicket/component/NavigationPanel.java | 735 | package at.dru.wicketblog.wicket.component;
import at.dru.wicketblog.WicketWebApplication;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.spring.injection.annot.SpringBean;
public class NavigationPanel extends Panel {
private static final long serialVersionUID = 1L;
@SpringBean
private WicketWebApplication wicketWebApplication;
public NavigationPanel(String id) {
super(id);
setRenderBodyOnly(true);
}
@Override
protected void onInitialize() {
super.onInitialize();
add(new Label("appName", wicketWebApplication.getAppName()));
add(new AccountInfoPanel("accountInfo"));
}
}
| mit |
eleks/rnd-android-wear-tesla | wear/src/main/java/com/eleks/tesla/events/CarStateLoadedEvent.java | 363 | package com.eleks.tesla.events;
import com.eleks.tesla.teslalib.models.CarState;
/**
* Created by Ihor.Demedyuk on 13.02.2015.
*/
public class CarStateLoadedEvent {
private CarState mCarState;
public CarStateLoadedEvent(CarState carState) {
mCarState = carState;
}
public CarState getCarState() {
return mCarState;
}
}
| mit |
KROKIteam/KROKI-CERIF-Model | CerifModel/WebApp/src_gen/ejb_generated/CfMetricsKeywConstraints.java | 302 | package ejb_generated;
import adapt.exceptions.InvariantException;
public class CfMetricsKeywConstraints extends CfMetricsKeyw{
private String objectName;
public String getObjectName() {
return objectName;
}
public void setObjectName(String objectName) {
this.objectName = objectName;
}
} | mit |
DavCardenas/ViasBoyaca | RPOYECTO_GRAFOS/src/logic/Status.java | 63 | package logic;
public enum Status {
BUENO,MALO,PESIMO
}
| mit |
acalvoa/EARLGREY | src/earlgrey/annotations/AddPropertieArray.java | 414 | package earlgrey.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Repeatable(GroupPropertiesArray.class)
public @interface AddPropertieArray {
String name();
String[] defaultTo();
}
| mit |
HeisenBugDev/Project-U | src/api/java/com/heisenbugdev/heisenui/api/lib/ITarget.java | 218 | package com.heisenbugdev.heisenui.api.lib;
import java.lang.reflect.Method;
public interface ITarget
{
public void invoke(Object... args);
public Method getMethod();
public Object getObjectInstance();
}
| mit |
neolfdev/dlscxx | java_src/com/trend/hbny/dao/ENowEnergyDao.java | 2602 | /*
* Powered By [柳丰]
* Web Site: http://www.trend.com.cn
*/
package com.trend.hbny.dao;
import java.io.Serializable;
import java.util.List;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.simple.ParameterizedBeanPropertyRowMapper;
import org.springframework.stereotype.Component;
import java.util.*;
import javacommon.base.*;
import javacommon.util.*;
import cn.org.rapid_framework.util.*;
import cn.org.rapid_framework.web.util.*;
import cn.org.rapid_framework.page.*;
import cn.org.rapid_framework.page.impl.*;
import com.trend.hbny.model.*;
import com.trend.hbny.dao.*;
import com.trend.hbny.service.*;
/**
* @author neolf email:neolf(a)foxmail.com
* @version 1.0
* @since 1.0
*/
@Component
public class ENowEnergyDao extends BaseSpringJdbcDao<ENowEnergy,java.lang.Long>{
//注意: getSqlGenerator()可以生成基本的:增删改查sql语句, 通过这个父类已经封装了增删改查操作
public Class getEntityClass() {
return ENowEnergy.class;
}
public void save(ENowEnergy entity) {
String sql = getSqlGenerator().getInsertSql();
//insertWithIdentity(entity,sql); //for sqlserver and mysql
//其它主键生成策略
insertWithOracleSequence(entity,"E_NOW_ENERGY_SEQUENCE",sql); //oracle sequence:
//insertWithDB2Sequence(entity,"E_NOW_ENERGY_SEQUENCE",sql); //db2 sequence:
//insertWithUUID(entity,sql); //uuid
//insertWithAssigned(entity,sql); //手工分配
}
public Page findByPageRequest(PageRequest<Map> pageRequest) {
//XsqlBuilder syntax,please see http://code.google.com/p/rapid-xsqlbuilder
// [column]为字符串拼接, {column}为使用占位符. 以下为图方便采用sql拼接,适用性能要求不高的应用,使用占位符方式可以优化性能.
// [column] 为PageRequest.getFilters()中的key
String sql = "select "+ getSqlGenerator().getColumnsSql("t") + " from E_NOW_ENERGY t where 1=1 "
+ "/~ and t.CO_NO like '[coNo]%' ~/"
+ "/~ and t.TIME_FLAG = '[timeFlag]' ~/"
+ "/~ and t.L_G_FLAG = '[lGFlag]' ~/"
+ "/~ and t.UPDATE_TIME = to_date('[updateTime]' , 'yyyy-mm-dd hh24:mi:ss') ~/"
+ "/~ and t.UPDATE_TIME <= to_date('[maxupdateTime]' , 'yyyy-mm-dd hh24:mi:ss') ~/"
+ "/~ and t.UPDATE_TIME >= to_date('[minupdateTime]' , 'yyyy-mm-dd hh24:mi:ss') ~/"
+ "/~ and t.P = '[p]' ~/"
+ "/~ and t.Q = '[q]' ~/"
+ "/~ order by [sortColumns] ~/";
return pageQuery(sql,pageRequest);
}
}
| mit |
liufeiit/tulip | net/src/test/java/net/demo/netty/fundamental/echo/package-info.java | 152 | /**
*
* @author 刘飞 E-mail:liufei_it@126.com
* @version 1.0
* @since 2014年2月13日 下午2:16:08
*/
package net.demo.netty.fundamental.echo; | mit |
cdunn2001/chug | javasample/Chug.java | 742 | // vim: et ts=8 sts=2 sw=2
//import java.lang.reflect.Class;
public class Chug {
static void p(Object o) {
System.out.println(o.toString());
}
static void findClass(String name) {
try {
Class c = Class.forName(name);
java.lang.reflect.Method methods[] = c.getDeclaredMethods();
p("Num methods for " + name + ": " + methods.length);
for (java.lang.reflect.Method m: methods)
p(m);
} catch (java.lang.ClassNotFoundException e) {
throw new java.lang.RuntimeException(e);
}
}
public static void main(String[] args) {
p("Num args: " + args.length);
for(String arg: args) {
p("Searching for class '" + arg + "'");
findClass(arg);
}
System.exit(0);
}
}
| mit |
lobobrowser/Cobra | src/main/java/org/cobraparser/html/style/CSS2PropertiesContext.java | 1181 | /*
GNU LESSER GENERAL PUBLIC LICENSE
Copyright (C) 2006 The Lobo Project
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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Contact info: lobochief@users.sourceforge.net
*/
package org.cobraparser.html.style;
public interface CSS2PropertiesContext {
public void informLookInvalid();
public void informSizeInvalid();
public void informPositionInvalid();
public void informLayoutInvalid();
public void informInvalid();
public String getDocumentBaseURI();
}
| mit |
niesfisch/java-code-tracer | src/test/java/de/marcelsauer/profiler/transformer/filter/CombinedFilterTest.java | 1470 | package de.marcelsauer.profiler.transformer.filter;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
import de.marcelsauer.profiler.config.Config;
public class CombinedFilterTest {
private Config config = new Config();
private Filter filter = new CombinedFilter(config);
@Test
public void thatInvalidArgumentsDoNotMatch() {
assertFalse(filter.matches(null));
assertFalse(filter.matches(""));
}
@Test
public void thatClassesCanBeIncludedViaAllMatcher() {
// given
config.classes.included.add(".*");
// when
assertTrue(filter.matches("a.b.C"));
}
@Test
public void thatClassesWillBeExcluded() {
// given
config.classes.included.add("a.b.C");
config.classes.excluded.add("a.b.C");
// when
assertFalse(filter.matches("a.b.C"));
}
@Test
public void thatClassesWillBeExcludedViaAllMatcher() {
// given
config.classes.included.add("a.b.C");
config.classes.excluded.add(".*");
// when
assertFalse(filter.matches("a.b.C"));
}
@Test
public void thatClassesWillBeExcludedViaAllMatcherGlobally() {
// given
config.classes.included.add(".*");
config.classes.excluded.add(".*");
// when
assertFalse(filter.matches("a"));
assertFalse(filter.matches("a.b.C"));
}
}
| mit |
akkirilov/SoftUniProject | 07_OOP_Advanced/04_Generics_ex/src/p04_GenericSwapMethodInteger/ListUtils.java | 1564 | package p04_GenericSwapMethodInteger;
import java.util.ArrayList;
import java.util.List;
public class ListUtils<T extends Comparable<T>> {
public static <T extends Comparable<T>> T getMin(List<T> list) {
if (list.isEmpty()) {
throw new IllegalArgumentException();
}
T min = list.get(0);
for (int i = 1; i < list.size(); i++) {
if (min.compareTo(list.get(i)) > 0) {
min = list.get(i);
}
}
return min;
}
public static <T extends Comparable<T>> T getMax(List<T> list) {
if (list.isEmpty()) {
throw new IllegalArgumentException();
}
T max = list.get(0);
for (int i = 1; i < list.size(); i++) {
if (max.compareTo(list.get(i)) < 0) {
max = list.get(i);
}
}
return max;
}
public static <T> List<Integer> getNullIndices(List<T> list) {
if (list.isEmpty()) {
throw new IllegalArgumentException();
}
List<Integer> nullIndices = new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
if (list.get(i) == null) {
nullIndices.add(i);
}
}
return nullIndices;
}
public static <T> void flatten(List<T> destination, List<List<T>> source) {
for (List<T> list : source) {
destination.addAll(list);
}
}
public static <T> void addAll(List<T> destination, List<T> source) {
destination.addAll(source);
}
public static <T> void swap(List<T> source, int indexOne, int indexTwo) {
T one = source.get(indexOne);
source.add(indexOne + 1, source.get(indexTwo));
source.remove(indexOne);
source.add(indexTwo + 1, one);
source.remove(indexTwo);
}
}
| mit |
108bots/archives | sip-security-testing-framework/sstf/SIPStrezz/src/strezzer/FuzzRulesParse.java | 18470 | /*SIP SECURITY TESTING FRAMEWORK - SSTF version 0.1
*Uses the DOM to parse the fuzz Rules XML file and build the Rules objects.
* Then depending on 1) rulename, 2) msg type, 3) testdevice type or 4) targetdevice type
* processes the rules and generates the corresponding template (*.tpl) file
* This .tpl file is a test case. It can be used with Strezz.java to generate the
* actual test XML scenario and CSV files, that will be used by SIPp.
* Author: Hemanth Srinivasan
* Year: 2008
*/
//Pending: Modify to take rulename, msgname, typename parameters
package strezzer;
import javax.swing.*;
import java.util.*;
import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;
public class FuzzRulesParse extends StrezzHeader {
public static ArrayList RulesList = new ArrayList();
public static String allheaderfname = RULES_DIR+"allHeaders.tpl";
public static String allheaderValue = new String();
public static FileWriter tplout;
public static File tpl;
//the byteStream of the entire event data, including sends, recvs, pauses etc
public static ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
//create arrayList to hold the Message byte data after rule processing
public static ArrayList msglinesList = new ArrayList();
//eventType = send, recv, pause -- for now
public static String eventType = new String();
//Syntax = A space delimted set of parameter strings
//parameter string eg: response="100" optional="true" request="ACK" and so on
public static String eventParameters = new String();
public static String inRulesfname = new String ();
//NOTE: Currently, if processing more that one rule, in the same file
//these values will get overwritten to the most recently parsed rule
//All these constitute output tpl file name
public static String outRuleName = new String ();
public static String outRuleMsgType = new String ();
public static String outSelfType = new String ();
public static String outTargetType = new String ();
//public static void main(String[] args) {
public FuzzRulesParse (String rulesfname) {
System.out.println("\n**************Running FuzzRulesParse*********************\n");
/* do {
inRulesfname = null;
inRulesfname = JOptionPane.showInputDialog(null, "Specify Name of xml Rules file:", "Fuzz Test Case Rules", JOptionPane.QUESTION_MESSAGE);
if (inRulesfname == null)
{
System.out.println("\nGoodbye!!!");
System.exit(0);
}
} while ((inRulesfname == "") || (inRulesfname == JOptionPane.UNINITIALIZED_VALUE) || (inRulesfname.length() == 0));
*/
//read rules filename
inRulesfname = rulesfname;
//Parse the Rules file
parseRulesXML(inRulesfname);
//load the AllHeaders template into a local buffer
try {
BufferedReader in = new BufferedReader(new FileReader(allheaderfname));
String str;
while ((str = in.readLine()) != null) {
allheaderValue += str.toLowerCase();
}
in.close();
} catch (IOException e) {
System.out.println ( "Reading AllHeaders file exception =: " + e );
e.printStackTrace();
}
// System.out.println ( "AllHeaders file Data: "+allheaderValue);
// System.out.println ( "AllHeaders file length: "+allheaderValue.length());
//Output template file
String outTPLfname = RULES_TPL_DIR+outRuleName+"_"+outRuleMsgType+"_"+
outSelfType+"_"+outTargetType+".tpl";
try {
tpl = new File(outTPLfname);
boolean s2 = tpl.createNewFile();
tplout = new FileWriter(tpl, true);
} catch (IOException e) {
System.out.println ( "create rules template file exception =: " + e );
e.printStackTrace();
}
for (int i = 0; i < RulesList.size(); i++) {
//display the rules from rules List
printRules((Rules)RulesList.get(i));
//process each rule based create the message
processRule((Rules)RulesList.get(i));
//write msglineList to outtpl file
try {
/* useful when processing multiple rules in a single file
String ruleheading = "Rule #"+i;
tplout.write(ruleheading, 0, ruleheading.length());
tplout.write('\n');
*/
for (int j = 0; j < msglinesList.size(); j++) {
String mline = (String)msglinesList.get(j);
tplout.write(mline, 0, mline.length());
if (!mline.equals("\n"))
tplout.write('\n');
}
tplout.write('\n');
} catch (IOException e) {
System.out.println ( "writing rules template streams exception =: " + e );
e.printStackTrace();
}
//clear msglist
msglinesList.clear();
}
//close the template file streams
try {
tplout.close();
}
catch (IOException e) {
System.out.println ( "closing rules template streams exception =: " + e );
e.printStackTrace();
}
System.out.println("\n**************FuzzRulesParse DONE*********************\n");
}
public static void processRule (Rules r) {
//read the build Order and process each header in that order
StringTokenizer st1 = new StringTokenizer(r.buildValue, ",");
int tokenCount = st1.countTokens();
for (int i = 0; i < tokenCount; i++) {
String hdr = st1.nextToken();
System.out.println ( "Token "+i+": "+hdr);
//if "start" keyword -> first line -> messagetype
if (hdr.equalsIgnoreCase("start"))
hdr = r.msgType;
//if "lb" keyword -> line break, add directly to msglinesList
if (hdr.equalsIgnoreCase("lb")) {
msglinesList.add(new String("\n"));
continue;
}
//find the original hdr value in the allheaderValue
String bsrchdr = "<"+hdr+">";
int bpos = allheaderValue.indexOf(bsrchdr.toLowerCase());
if (bpos < 0) {
System.out.println ( "Warning: Definition for Header '"+hdr+"' not found in"+allheaderfname);
continue;
}
String esrchdr = "</"+hdr+">";
int epos = allheaderValue.indexOf(esrchdr.toLowerCase());
if (epos < 0) {
System.out.println ( "Warning: Closing tag for Header '"+hdr+"' not found in"+allheaderfname);
continue;
}
String orghdrvalue = allheaderValue.substring(bpos+bsrchdr.length(), epos);
System.out.println ( "Allheader Value for Token "+i+": "+orghdrvalue);
//processes each header as per the rule, adds the new header to msglinesList
processHeader ((String)r.mapHeader.get(hdr), orghdrvalue);
}
//print msglinesList
System.out.println ("MsglinesList Contains:");
for (int j = 0; j < msglinesList.size(); j++)
System.out.println(msglinesList.get(j));
}
public static void addHeader2MsgLine(String hdr) {
//the original header from Allheaders.tpl might span multiple
//lines delimite by ### , add each line as list member
StringTokenizer st1 = new StringTokenizer(hdr, "###");
while (st1.hasMoreTokens()) {
msglinesList.add(st1.nextToken());
}
}
public static void processHeader (String hdrule, String orghdr) {
//no rule defined for this, just add orghdr to msglinesList and return
if ((hdrule == null) || (hdrule.length() == 0)) {
addHeader2MsgLine(orghdr);
return;
}
//process and interpret the rule
//if spanning mutiple lines, split the rule
//process each rule: find occurence[arg1 of rule] of pattern[arg2 of rule] and replace it with [arg3 of rule]
StringTokenizer st1 = new StringTokenizer(hdrule, "\n");
while (st1.hasMoreTokens()) {
String srule = st1.nextToken().trim();
System.out.println ( "Trimmed rule: "+srule);
//interpret the rule
StringTokenizer st2 = new StringTokenizer(srule, " ");
int tokenCount = st2.countTokens();
if (tokenCount != 3) {
System.out.println ( "Ignoring Malformed rule: "+srule);
continue;
}
int loc = 0;
String arg1 = st2.nextToken();
String arg2 = st2.nextToken();
String arg3 = st2.nextToken();
try {
if (!arg1.equalsIgnoreCase("all"))
loc = Integer.parseInt(arg1);
} catch (NumberFormatException e) {
System.out.println ( "Integer value expected in place of: " + arg1 );
e.printStackTrace();
System.out.println ( "Ignoring malfomed rule: "+srule);
continue;
}
//count the no: of occurences of the pattern (arg2) in orghdr
int firstindx = orghdr.indexOf(arg2);
if (firstindx < 0) {
System.out.println ( "Pattern not found in Orignal header: "+arg2);
continue;
}
int lastindx = orghdr.lastIndexOf(arg2);
int indxrange = -1;
int patcount = 0;
while (indxrange < lastindx) {
indxrange = orghdr.indexOf(arg2, indxrange+arg2.length());
if (indxrange > -1)
patcount++;
}
if (((loc <= 0) || (loc > patcount)) && (!arg1.equalsIgnoreCase("all"))) {
System.out.println ( "Occurence value doenst match with Original header: "+arg1);
continue;
}
//create array to store the occurence positions
int [] posIndx = new int [patcount];
indxrange = -1;
for (int i = 0; i < patcount; i++) {
indxrange = orghdr.indexOf(arg2, indxrange+arg2.length());
if (indxrange > -1)
posIndx[i] = indxrange;
}
for (int i = 0; i < patcount; i++)
System.out.println ("Pattern Pos:"+posIndx[i]);
String rephdr = new String();
if (arg1.equalsIgnoreCase("all")) { //replace everywhere
int startpos = 0, endpos = 0;
for (int i = 0; i < patcount; i++) {
endpos = posIndx[i];
rephdr += orghdr.substring(startpos, endpos);
rephdr += arg3;
startpos = endpos + arg2.length();
}
//copy to the end of orghdr
rephdr += orghdr.substring(startpos, orghdr.length());
} else { //replace only at position loc
rephdr += orghdr.substring(0, posIndx[loc-1]);
rephdr += arg3;
rephdr += orghdr.substring(posIndx[loc-1]+arg2.length(), orghdr.length());
//System.exit(0);
}
System.out.println ("Orghdr: "+orghdr);
System.out.println ("Rephdr: "+rephdr);
//after processing one rule, use the processes hdr as the orghdr for next rule
orghdr = rephdr;
}
//add the final processed hdr to the msglist
addHeader2MsgLine(orghdr);
}
public static void printRules (Rules r) {
System.out.println("\nRule Name: "+r.ruleName);
System.out.println("\nMessage Type: "+r.msgType);
System.out.println("\nSelf Type: "+r.selfType);
System.out.println("\nTarget Type: "+r.targetType);
System.out.println("\nBuild Order String: "+r.buildValue);
System.out.println("\nHeaders:");
Set set = r.mapHeader.entrySet();
Iterator i = set.iterator();
while(i.hasNext()){
Map.Entry me = (Map.Entry)i.next();
String key = (String)me.getKey();
String value = (String)me.getValue();
System.out.println("Header TYPE: "+key+ " VALUE: "+value.trim());
}
}
public static void parseRulesXML (String fname) {
Document doc = parseXmlFile(fname, false);
parseDocumentObject(doc);
}
public static void parseDocumentObject(Document dom){
//get the root elememt
Element docEle = dom.getDocumentElement();
//get a nodelist of ALL <rule> elements
NodeList nl = docEle.getElementsByTagName("rule");
if(nl != null && nl.getLength() > 0) {
for(int i = 0 ; i < nl.getLength();i++) {
//get the rule element
Element el = (Element)nl.item(i);
//Add Matching condition here. Rules with particular name, msgtype, selfType
//or target type
//get the Rules object
Rules r = getRule(el);
//add it to Ruleslist
RulesList.add(r);
}
}
}
//process the rule element, constructs a Rules object and returns it
public static Rules getRule(Element el) {
//Create a new rule with the value read from the xml nodes
Rules rule = new Rules();
//get rule name
rule.ruleName = el.getAttribute("name");
outRuleName = rule.ruleName;
NodeList msgnl = el.getElementsByTagName("message");
NodeList selfnl = el.getElementsByTagName("testdevice");
NodeList targetnl = el.getElementsByTagName("targetdevice");
NodeList headernl = el.getElementsByTagName("header");
NodeList buildnl = el.getElementsByTagName("build");
//except for header all other tags can appear only once
//so process the first occurence and ignore rest
//Can be expanded later, if required
//message tag
if( msgnl != null && msgnl.getLength() > 0) {
Node n = msgnl.item(0);
// Get all the attributes of an element in a map
NamedNodeMap attrs = n.getAttributes();
// Get number of attributes in the element
int numAttrs = attrs.getLength();
// Process each attribute
for (int i=0; i<numAttrs; i++) {
Attr attr = (Attr)attrs.item(i);
// Get attribute name and value
String attrName = attr.getNodeName();
String attrValue = attr.getNodeValue();
//currently only one attribute named 'type'
if (attrName.equals("type")) {
rule.msgType = attrValue;
outRuleMsgType = rule.msgType;
}
}
}
//testdevice tag
if( selfnl != null && selfnl.getLength() > 0) {
Node n = selfnl.item(0);
// Get all the attributes of an element in a map
NamedNodeMap attrs = n.getAttributes();
// Get number of attributes in the element
int numAttrs = attrs.getLength();
// Process each attribute
for (int i=0; i<numAttrs; i++) {
Attr attr = (Attr)attrs.item(i);
// Get attribute name and value
String attrName = attr.getNodeName();
String attrValue = attr.getNodeValue();
//currently only one attribute named 'type'
if (attrName.equals("type")) {
rule.selfType = attrValue;
outSelfType = rule.selfType;
}
}
}
//targetdevice tag
if( targetnl != null && targetnl.getLength() > 0) {
Node n = targetnl.item(0);
// Get all the attributes of an element in a map
NamedNodeMap attrs = n.getAttributes();
// Get number of attributes in the element
int numAttrs = attrs.getLength();
// Process each attribute
for (int i=0; i<numAttrs; i++) {
Attr attr = (Attr)attrs.item(i);
// Get attribute name and value
String attrName = attr.getNodeName();
String attrValue = attr.getNodeValue();
//currently only one attribute named 'type'
if (attrName.equals("type")) {
rule.targetType = attrValue;
outTargetType = rule.targetType;
}
}
}
//build tag
if( buildnl != null && buildnl.getLength() > 0) {
Node n = buildnl.item(0);
//get the value
rule.buildValue = n.getTextContent();
}
//header tags
if( headernl != null && headernl.getLength() > 0) {
for (int i = 0 ; i < headernl.getLength();i++) {
String hdrType = new String();
String hdrValue = new String();
Node n = headernl.item(i);
// Get all the attributes of an element in a map
NamedNodeMap attrs = n.getAttributes();
// Get number of attributes in the element
int numAttrs = attrs.getLength();
// Process each attribute
for (int j=0; j<numAttrs; j++) {
Attr attr = (Attr)attrs.item(j);
// Get attribute name and value
String attrName = attr.getNodeName();
String attrValue = attr.getNodeValue();
//currently only one attribute named 'type'
if (attrName.equals("type"))
hdrType = attrValue;
}
hdrValue = n.getTextContent();
//System.out.println("IN Header TYPE: "+hdrType+ " IN VALUE: "+hdrValue.trim());
rule.mapHeader.put(hdrType, hdrValue);
}
}
return rule;
}
/*
public static Rules getRule(Element el) {
//Create a new rule with the value read from the xml nodes
Rules rule = new Rules();
//get rule name
rule.ruleName = el.getAttribute("name");
//get all child element
NodeList nl = el.getChildNodes();
if (nl != null && nl.getLength() > 0) {
for (int i = 0 ; i < nl.getLength();i++) {
Element ele = (Element)nl.item(i);
if (ele.getTagName().equals("header")) { //process header and add to header hash map
String hdrType = ele.getAttribute("type");
String hdrValue = ele.getNodeValue();
rule.mapHeader.put(hdrType, hdrValue);
}
else if (ele.getTagName().equals("build")) {
rule.buildValue = ele.getNodeValue();
}
else { //all other tags - get their attributes
if (ele.getTagName().equals("message"))
rule.msgType = ele.getAttribute("type");
if (ele.getTagName().equals("testdevice"))
rule.selfType = ele.getAttribute("type");
if (ele.getTagName().equals("targetdevice"))
rule.targetType = ele.getAttribute("type");
}
}
}
return rule;
}*/
public static Document parseXmlFile(String filename, boolean validating) {
try {
// Create a builder factory
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(validating);
//Using factory get an instance of document builder
DocumentBuilder db = factory.newDocumentBuilder();
// Create the builder and parse the file
Document doc = db.parse(filename);
return doc;
}catch(ParserConfigurationException pce) {
pce.printStackTrace();
}catch(SAXException se) {
se.printStackTrace();
}catch(IOException ioe) {
ioe.printStackTrace();
}
return null;
}
}
class Rules {
String ruleName;
String msgType;
String selfType;
String targetType;
String buildValue;
//Hashmap of header objects
//key = header type
//value = header value = CDATA section
HashMap mapHeader = new HashMap();
}
| mit |
justacoder/mica | src/model/MiiModelEntityReference.java | 2771 |
/*
***************************************************************************
* Mica - the Java(tm) Graphics Framework *
***************************************************************************
* NOTICE: Permission to use, copy, and modify this software and its *
* documentation is hereby granted provided that this notice appears in *
* all copies. *
* *
* Permission to distribute un-modified copies of this software and its *
* documentation is hereby granted provided that no fee is charged and *
* that this notice appears in all copies. *
* *
* SOFTWARE FARM MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE *
* SUITABILITY OF THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING, BUT *
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR *
* A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SOFTWARE FARM SHALL NOT BE *
* LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR *
* CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE, MODIFICATION OR *
* DISTRIBUTION OF THIS SOFTWARE OR ITS DERIVATIVES. *
* *
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND *
* DISTRIBUTORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, *
* UPDATES, ENHANCEMENTS, OR MODIFICATIONS. *
* *
***************************************************************************
* Copyright (c) 1997-2004 Software Farm, Inc. All Rights Reserved. *
***************************************************************************
*/
package com.swfm.mica;
import com.swfm.mica.*;
import com.swfm.mica.util.FastVector;
import com.swfm.mica.util.Strings;
import com.swfm.mica.util.Utility;
import com.swfm.mica.util.TypedVector;
import java.awt.Color;
import java.util.Hashtable;
import java.util.Vector;
/**----------------------------------------------------------------------------------------------
* <p>
*
* @version %I% %G%
* @author Michael L. Davis
* @release 1.4.1
* @module %M%
* @language Java (JDK 1.4)
*----------------------------------------------------------------------------------------------*/
public interface MiiModelEntityReference extends MiiModelEntity
{
MiiModelEntity getReferenced();
}
| mit |