hexsha stringlengths 40 40 | size int64 3 1.05M | ext stringclasses 1 value | lang stringclasses 1 value | max_stars_repo_path stringlengths 5 1.02k | max_stars_repo_name stringlengths 4 126 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses list | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 5 1.02k | max_issues_repo_name stringlengths 4 114 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses list | max_issues_count float64 1 92.2k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 5 1.02k | max_forks_repo_name stringlengths 4 136 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses list | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | avg_line_length float64 2.55 99.9 | max_line_length int64 3 1k | alphanum_fraction float64 0.25 1 | index int64 0 1M | content stringlengths 3 1.05M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3e06dfb5e9ddcc9ca3219f5b18d036e753fd50b2 | 3,815 | java | Java | odfdom/src/main/java/org/odftoolkit/odfdom/type/DateOrDateTime.java | kv-gh/odftoolkit | db2ab605e8d498ce3f007af7900c6c6b94d718aa | [
"Apache-2.0"
] | 75 | 2018-12-13T16:05:55.000Z | 2022-02-08T18:42:56.000Z | odfdom/src/main/java/org/odftoolkit/odfdom/type/DateOrDateTime.java | HeikoStudt/odftoolkit | b7f5bebfc8dac7e1c68e659db6ccc224272f7e53 | [
"Apache-2.0"
] | 99 | 2019-02-14T11:09:45.000Z | 2022-03-02T19:05:11.000Z | odfdom/src/main/java/org/odftoolkit/odfdom/type/DateOrDateTime.java | HeikoStudt/odftoolkit | b7f5bebfc8dac7e1c68e659db6ccc224272f7e53 | [
"Apache-2.0"
] | 42 | 2019-02-15T11:06:34.000Z | 2022-02-09T02:35:36.000Z | 39.237113 | 100 | 0.724383 | 2,918 | /**
* **********************************************************************
*
* <p>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
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>Unless required by applicable law or agreed to in writing, software distributed under the
* License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*
* <p>**********************************************************************
*/
package org.odftoolkit.odfdom.type;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
/**
* This class represents the in OpenDocument format used data type lyhxr@example.com dateOrDateTime}
*/
public class DateOrDateTime implements OdfDataType {
private XMLGregorianCalendar mDateOrDateTime;
/**
* Construct an newly DateOrDateTime object that represents the specified XMLGregorianCalendar
* value
*
* @param dateOrDateTime the value to be represented by the DateOrDateTime Object
* @throws IllegalArgumentException if the given argument is not a valid DateOrDateTime
*/
public DateOrDateTime(XMLGregorianCalendar dateOrDateTime) throws IllegalArgumentException {
if (DateOrDateTime.isValid(dateOrDateTime)) {
mDateOrDateTime = dateOrDateTime;
} else {
throw new IllegalArgumentException("parameter is invalid for datatype DateOrDateTime");
}
}
/**
* Returns a String Object representing this DateOrDateTime value
*
* @return return a string representation of the value of this DateOrDateTime object
*/
@Override
public String toString() {
return mDateOrDateTime.toXMLFormat();
}
/**
* Returns a DateOrDateTime instance representing the specified String value
*
* @param stringValue a String value
* @return return a DateOrDateTime instance representing stringValue
* @throws IllegalArgumentException if the given argument is not a valid DateOrDateTime
*/
public static DateOrDateTime valueOf(String stringValue) throws IllegalArgumentException {
try {
DatatypeFactory aFactory = new org.apache.xerces.jaxp.datatype.DatatypeFactoryImpl();
return new DateOrDateTime(aFactory.newXMLGregorianCalendar(stringValue));
} catch (IllegalArgumentException ex) {
Logger.getLogger(DateOrDateTime.class.getName())
.log(Level.SEVERE, "parameter is invalid for datatype DateOrDateTime", ex);
throw new IllegalArgumentException("parameter is invalid for datatype DateOrDateTime");
}
}
/**
* Returns the value of this DateOrDateTime object as an XMLGregorianCalendar
*
* @return the XMLGregorianCalendar value of this DateOrDateTime object.
*/
public XMLGregorianCalendar getXMLGregorianCalendar() {
return mDateOrDateTime;
}
/**
* check if the specified XMLGregorianCalendar instance is a valid lyhxr@example.com dateOrDateTime}
* data type
*
* @param dateOrDateTime the value to be tested
* @return true if the value of argument is valid for lyhxr@example.com dateOrDateTime} data type
* false otherwise
*/
public static boolean isValid(XMLGregorianCalendar dateOrDateTime) {
return (Date.isValid(dateOrDateTime) || DateTime.isValid(dateOrDateTime));
}
}
|
3e06dfc67cfe8c6f6c645fd4f31adecb7b6f9eeb | 2,426 | java | Java | modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201308/ProposalLineItemServiceInterfacecreateProposalLineItem.java | david-gorisse/googleads-java-lib | 03b8c7e83bc5a361e374d345afdd93290d143c34 | [
"Apache-2.0"
] | null | null | null | modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201308/ProposalLineItemServiceInterfacecreateProposalLineItem.java | david-gorisse/googleads-java-lib | 03b8c7e83bc5a361e374d345afdd93290d143c34 | [
"Apache-2.0"
] | null | null | null | modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201308/ProposalLineItemServiceInterfacecreateProposalLineItem.java | david-gorisse/googleads-java-lib | 03b8c7e83bc5a361e374d345afdd93290d143c34 | [
"Apache-2.0"
] | null | null | null | 29.585366 | 139 | 0.619126 | 2,919 |
package com.google.api.ads.dfp.jaxws.v201308;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
*
* Creates a new {@link ProposalLineItem}.
*
* The following fields are required:
* <ul>
* <li>{@link ProposalLineItem#proposalId}</li>
* <li>{@link ProposalLineItem#rateCardId}</li>
* <li>{@link ProposalLineItem#productId}</li>
* <li>{@link ProposalLineItem#name}</li>
* <li>{@link ProposalLineItem#startDateTime}</li>
* <li>{@link ProposalLineItem#endDateTime}</li>
* </ul>
*
* @param proposalLineItem the proposal line item to create
* @return the created proposal line item with its ID filled in
*
*
* <p>Java class for createProposalLineItem element declaration.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <element name="createProposalLineItem">
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="proposalLineItem" type="{https://www.google.com/apis/ads/publisher/v201308}ProposalLineItem" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </element>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"proposalLineItem"
})
@XmlRootElement(name = "createProposalLineItem")
public class ProposalLineItemServiceInterfacecreateProposalLineItem {
protected ProposalLineItem proposalLineItem;
/**
* Gets the value of the proposalLineItem property.
*
* @return
* possible object is
* {@link ProposalLineItem }
*
*/
public ProposalLineItem getProposalLineItem() {
return proposalLineItem;
}
/**
* Sets the value of the proposalLineItem property.
*
* @param value
* allowed object is
* {@link ProposalLineItem }
*
*/
public void setProposalLineItem(ProposalLineItem value) {
this.proposalLineItem = value;
}
}
|
3e06dff56449bbd9df41d5e53cde35bb376bdfbc | 1,182 | java | Java | entity-view/testsuite/src/test/java/com/blazebit/persistence/view/testsuite/basic/model/PersonDuplicateCollectionUsageValidationView.java | aboodz/blaze-persistence | f002cfd8de37223d6e3f1c91a6260e113980a29b | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | entity-view/testsuite/src/test/java/com/blazebit/persistence/view/testsuite/basic/model/PersonDuplicateCollectionUsageValidationView.java | aboodz/blaze-persistence | f002cfd8de37223d6e3f1c91a6260e113980a29b | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | entity-view/testsuite/src/test/java/com/blazebit/persistence/view/testsuite/basic/model/PersonDuplicateCollectionUsageValidationView.java | aboodz/blaze-persistence | f002cfd8de37223d6e3f1c91a6260e113980a29b | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | 30.307692 | 90 | 0.751269 | 2,920 | /*
* Copyright 2014 - 2020 Blazebit.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.blazebit.persistence.view.testsuite.basic.model;
import java.util.Set;
import com.blazebit.persistence.view.EntityView;
import com.blazebit.persistence.view.Mapping;
import com.blazebit.persistence.testsuite.entity.Person;
/**
*
* @author Christian Beikov
* @since 1.0.0
*/
@EntityView(Person.class)
public interface PersonDuplicateCollectionUsageValidationView extends IdHolderView<Long> {
@Mapping("ownedDocuments.id")
public Set<Long> getOwnedDocumentIds();
@Mapping("ownedDocuments.name")
public Set<String> getOwnerDocumentNames();
}
|
3e06e17b3727db312c6384d4b92aaca8ad94ac10 | 29,090 | java | Java | jpa/odata-jpa-processor/src/main/java/org/apache/olingo/jpa/processor/core/query/AbstractCriteriaQueryBuilder.java | FWidm/olingo-jpa-processor-v4 | 981ef97952a115edf36c282dcbe9c0453ab4717d | [
"Apache-2.0"
] | 6 | 2018-03-08T18:07:50.000Z | 2021-02-04T08:52:18.000Z | jpa/odata-jpa-processor/src/main/java/org/apache/olingo/jpa/processor/core/query/AbstractCriteriaQueryBuilder.java | FWidm/olingo-jpa-processor-v4 | 981ef97952a115edf36c282dcbe9c0453ab4717d | [
"Apache-2.0"
] | 9 | 2018-10-30T09:13:51.000Z | 2022-02-09T16:12:31.000Z | jpa/odata-jpa-processor/src/main/java/org/apache/olingo/jpa/processor/core/query/AbstractCriteriaQueryBuilder.java | FWidm/olingo-jpa-processor-v4 | 981ef97952a115edf36c282dcbe9c0453ab4717d | [
"Apache-2.0"
] | 5 | 2018-05-15T18:39:12.000Z | 2021-02-11T11:53:42.000Z | 42.57101 | 166 | 0.735521 | 2,921 | package org.apache.olingo.jpa.processor.core.query;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import javax.persistence.EntityManager;
import javax.persistence.Tuple;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.From;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Path;
import javax.persistence.criteria.Selection;
import javax.persistence.criteria.Subquery;
import org.apache.olingo.commons.api.edm.EdmNavigationProperty;
import org.apache.olingo.commons.api.edm.EdmType;
import org.apache.olingo.commons.api.http.HttpStatusCode;
import org.apache.olingo.jpa.metadata.core.edm.entity.DataAccessConditioner;
import org.apache.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationAttribute;
import org.apache.olingo.jpa.metadata.core.edm.mapper.api.JPAAssociationPath;
import org.apache.olingo.jpa.metadata.core.edm.mapper.api.JPAEntityType;
import org.apache.olingo.jpa.metadata.core.edm.mapper.api.JPAMemberAttribute;
import org.apache.olingo.jpa.metadata.core.edm.mapper.api.JPASelector;
import org.apache.olingo.jpa.metadata.core.edm.mapper.api.JPAStructuredType;
import org.apache.olingo.jpa.metadata.core.edm.mapper.exception.ODataJPAModelException;
import org.apache.olingo.jpa.metadata.core.edm.mapper.impl.IntermediateServiceDocument;
import org.apache.olingo.jpa.processor.JPAODataRequestContext;
import org.apache.olingo.jpa.processor.core.exception.ODataJPAQueryException;
import org.apache.olingo.jpa.processor.core.filter.JPAEntityFilterProcessor;
import org.apache.olingo.jpa.processor.core.query.result.NavigationKeyBuilder;
import org.apache.olingo.server.api.OData;
import org.apache.olingo.server.api.ODataApplicationException;
import org.apache.olingo.server.api.uri.UriInfoResource;
import org.apache.olingo.server.api.uri.UriParameter;
import org.apache.olingo.server.api.uri.UriResource;
import org.apache.olingo.server.api.uri.UriResourceEntitySet;
import org.apache.olingo.server.api.uri.UriResourceNavigation;
import org.apache.olingo.server.api.uri.queryoption.FilterOption;
import org.apache.olingo.server.api.uri.queryoption.OrderByItem;
import org.apache.olingo.server.api.uri.queryoption.OrderByOption;
import org.apache.olingo.server.api.uri.queryoption.SearchOption;
import org.apache.olingo.server.api.uri.queryoption.SkipOption;
import org.apache.olingo.server.api.uri.queryoption.TopOption;
import org.apache.olingo.server.api.uri.queryoption.expression.Expression;
import org.apache.olingo.server.api.uri.queryoption.expression.ExpressionVisitException;
import org.apache.olingo.server.api.uri.queryoption.expression.Member;
import org.apache.olingo.server.api.uri.queryoption.expression.VisitableExpression;
public abstract class AbstractCriteriaQueryBuilder<QT extends CriteriaQuery<DT>, DT> extends AbstractQueryBuilder {
protected static enum InitializationState {
NotInitialized, Initialized;
}
/**
* Helper class to access the right entity ('FROM') for filter expression
*
*/
protected class FilterQueryBuilderContext implements FilterContextQueryBuilderIfc {
private final JPAEntityType scopeEntity;
private final From<?, ?> filterFrom;
FilterQueryBuilderContext(final JPAEntityType filterEntity, final From<?, ?> filterFrom) {
this.scopeEntity = filterEntity;
this.filterFrom = filterFrom;
}
@Override
public JPAODataRequestContext getContext() {
return AbstractCriteriaQueryBuilder.this.context;
}
@Override
public EntityManager getEntityManager() {
return AbstractCriteriaQueryBuilder.this.getEntityManager();
}
@Override
public <T> Subquery<T> createSubquery(final Class<T> subqueryResultType) {
return AbstractCriteriaQueryBuilder.this.createSubquery(subqueryResultType);
}
@Override
public JPAEntityType getQueryResultType() {
return scopeEntity;
}
@Override
public From<?, ?> getQueryResultFrom() {
return filterFrom;
}
}
private final JPAODataRequestContext context;
private final NavigationIfc uriNavigation;
private final EdmType edmType;
private final UriResourceEntitySet queryStartUriResource;
private final JPAEntityType jpaStartEntityType;
private final List<UriParameter> keyPredicates;
private final NavigationKeyBuilder jpaStartNavigationKeyBuilder;
private List<NavigationBuilder> navigationQueryList = null;
private InitializationState initStateType = InitializationState.NotInitialized;
protected AbstractCriteriaQueryBuilder(final JPAODataRequestContext context, final NavigationIfc uriInfo,
final EntityManager em)
throws ODataApplicationException, ODataJPAModelException {
super(em);
this.uriNavigation = uriInfo;
this.context = context;
this.queryStartUriResource = Util.determineStartingEntityUriResource(uriInfo.getFirstStep());
assert queryStartUriResource != null;
this.keyPredicates = determineKeyPredicates(queryStartUriResource);
this.edmType = queryStartUriResource.getType();
this.jpaStartEntityType = context.getEdmProvider().getServiceDocument().getEntityType(edmType);
assert jpaStartEntityType != null;
jpaStartNavigationKeyBuilder = new NavigationKeyBuilder(jpaStartEntityType);
}
protected abstract <T> Subquery<T> createSubquery(Class<T> subqueryResultType);
protected void assertInitialized() {
if (initStateType != InitializationState.Initialized) {
throw new IllegalStateException("Not initialized");
}
}
protected final IntermediateServiceDocument getServiceDocument() {
return context.getEdmProvider().getServiceDocument();
}
protected final OData getOData() {
return context.getOdata();
}
protected final JPAODataRequestContext getContext() {
return context;
}
/**
*
* @return The entries from {@link UriInfoResource#getUriResourceParts()} that can be navigated, to avoid
* simple/complex properties at end of path.
*/
private static List<UriResource> extractNavigableResourcePath(final IntermediateServiceDocument sd,
final List<UriResource> resourceParts) throws ODataApplicationException {
if (!Util.hasNavigation(resourceParts)) {
return resourceParts;
}
final List<JPANavigationPropertyInfo> naviPathList = Util.determineNavigations(sd, resourceParts);
return resourceParts.subList(0, naviPathList.size());
}
/**
*
* @return The key builder matching rows from this query and expanded entities via navigation. The returned is not the
* last key builder of navigation path, but that one, that will come into effect as key builder to map entities
* from @ElementCollection or $expand queries to results of the query represented by this query builder.
* @see #getQueryResultNavigationKeyBuilder()
*/
protected final NavigationKeyBuilder getLastAffectingNavigationKeyBuilder() {
assertInitialized();
if (navigationQueryList.isEmpty() || navigationQueryList.size() < 2) {
return jpaStartNavigationKeyBuilder;
}
// ignore the last navigation entry, because not necessary for navigation key building
return navigationQueryList.get(navigationQueryList.size() - 2).getNavigationKeyBuilder();
}
private NavigationBuilder determineLastWorkingNavigationBuilder() {
// ignore the last navigation entry, because not necessary for navigation key building
// ignore also dummy nav queries (for @ElementCollection with navigation to property)
for (int i = navigationQueryList.size(); i > 0; i--) {
final NavigationBuilder navBuilder = navigationQueryList.get(i - 1);
if (navBuilder.isWorking()) {
return navBuilder;
}
}
return null;
}
/**
*
* @return The key builder of last navigation element in query. This can be an 'not working' navigation builder.
* @see #getLastAffectingNavigationKeyBuilder()
*/
protected final NavigationKeyBuilder getQueryResultNavigationKeyBuilder() {
assertInitialized();
final NavigationBuilder last = determineLastWorkingNavigationBuilder();
if (last == null) {
return jpaStartNavigationKeyBuilder;
}
return last.getNavigationKeyBuilder();
}
// TODO try to remove this separate init step, maybe we can do that in the constructor again...
protected void initializeQuery() throws ODataJPAModelException, ODataApplicationException {
navigationQueryList = createNavigationElements();
if (initStateType == InitializationState.Initialized) {
throw new IllegalStateException("Already initialized");
}
initStateType = InitializationState.Initialized;
}
/**
*
* @return The {@link #getQueryStartFrom() starting} query entity type.
*/
public final JPAEntityType getQueryStartType() {
return jpaStartEntityType;
}
protected final NavigationIfc getNavigation() {
return uriNavigation;
}
/**
*
* @return The initial {@link From starting} entity table before first join.
*/
public abstract <T> From<T, T> getQueryStartFrom();
@SuppressWarnings("unchecked")
public final From<DT, DT> getQueryResultFrom() {
assertInitialized();
final NavigationBuilder last = determineLastWorkingNavigationBuilder();
// the resulting type is always the end navigation path or if not given the starting 'from'
if (last == null) {
return getQueryStartFrom();
}
return (From<DT, DT>) last.getQueryResultFrom();
}
public final JPAEntityType getQueryResultType() {
assertInitialized();
final NavigationBuilder last = determineLastWorkingNavigationBuilder();
if (last == null) {
return getQueryStartType();
}
return (JPAEntityType) last.getQueryResultType();
}
protected final EdmType getQueryResultEdmType() {
assertInitialized();
final NavigationBuilder last = determineLastWorkingNavigationBuilder();
if (last == null) {
return edmType;
}
return last.getNavigationUriInfoResource().getType();
}
/**
* Limits in the query will result in LIMIT, SKIP, OFFSET/FETCH or other
* database specific expression used for pagination of SQL result set. This will
* affect also all dependent queries for $expand's or @ElementCollection loading
* related queries.
*
* @return TRUE if the resulting query will have limits reflecting the presence
* of $skip or $top in request.
* @throws ODataJPAQueryException
*/
protected final boolean hasQueryLimits() throws ODataJPAQueryException {
return (determineSkipValue() != null || determineTopValue() != null);
}
private Integer determineSkipValue() throws ODataJPAQueryException {
final UriInfoResource uriResource = getNavigation().getLastStep();
final SkipOption skipOption = uriResource.getSkipOption();
if (skipOption == null) {
return null;
}
final int skipNumber = skipOption.getValue();
if (skipNumber >= 0) {
return Integer.valueOf(skipNumber);
} else {
throw new ODataJPAQueryException(ODataJPAQueryException.MessageKeys.QUERY_PREPARATION_INVALID_VALUE,
HttpStatusCode.BAD_REQUEST, Integer.toString(skipNumber), "$skip");
}
}
private Integer determineTopValue() throws ODataJPAQueryException {
final UriInfoResource uriResource = getNavigation().getLastStep();
final TopOption topOption = uriResource.getTopOption();
if (topOption == null) {
return null;
}
final int topNumber = topOption.getValue();
if (topNumber >= 0) {
return Integer.valueOf(topNumber);
} else {
throw new ODataJPAQueryException(ODataJPAQueryException.MessageKeys.QUERY_PREPARATION_INVALID_VALUE,
HttpStatusCode.BAD_REQUEST, Integer.toString(topNumber), "$top");
}
}
/**
* Applies the $skip and $top options of the OData request to the query. The
* values are defined as follows:
* <ul>
* <li>The $top system query option specifies a non-negative integer n that
* limits the number of items returned from a collection.
* <li>The $skip system query option specifies a non-negative integer n that
* excludes the first n items of the queried collection from the result.
* </ul>
* For details see: <a href=
* "http://docs.oasis-open.org/odata/odata/v4.0/errata02/os/complete/part1-protocol/odata-v4.0-errata02-os-part1-protocol-complete.html#_Toc406398306"
* >OData Version 4.0 Part 1 - 172.16.17.32 System Query Option $top</a>
*
* @throws ODataApplicationException
*/
protected final void addTopSkip(final TypedQuery<Tuple> tq) throws ODataApplicationException {
/*
* Where $top and $skip are used together, $skip MUST be applied before $top, regardless of the order in which they
* appear in the request.
* If no unique ordering is imposed through an $orderby query option, the service MUST impose a stable ordering
* across requests that include $skip.
* URL example: http://localhost:8080/BuPa/BuPa.svc/Organizations?$count=true&$skip=5
*/
final Integer topValue = determineTopValue();
if (topValue != null) {
tq.setMaxResults(topValue.intValue());
}
final Integer skipValue = determineSkipValue();
if (skipValue != null) {
tq.setFirstResult(skipValue.intValue());
}
}
private List<NavigationBuilder> createNavigationElements() throws ODataJPAModelException, ODataApplicationException {
final List<UriResource> resourceParts = uriNavigation.getUriResourceParts();
// 1. Determine all relevant associations
final List<JPANavigationPropertyInfo> naviPathList = Util.determineNavigations(getServiceDocument(), resourceParts);
// 2. Create the queries and roots
final List<NavigationBuilder> navigationQueryList = new ArrayList<NavigationBuilder>(uriNavigation
.getUriResourceParts().size());
From<?, ?> parentFrom = getQueryStartFrom();// ==scope before navigation
NavigationKeyBuilder keyBuilderParent = jpaStartNavigationKeyBuilder;
for (final JPANavigationPropertyInfo naviInfo : naviPathList) {
if (naviInfo.getNavigationPath() == null) {
LOG.log(Level.SEVERE, "Association for navigation path to '"
+ naviInfo.getNavigationUriResource().getType().getName() + "' not found. Cannot resolve target entity");
continue;
}
final NavigationBuilder navQuery = new NavigationBuilder(naviInfo.getNavigationUriResource(), naviInfo
.getNavigationPath(), parentFrom, keyBuilderParent, getEntityManager());
navigationQueryList.add(navQuery);
parentFrom = navQuery.getQueryResultFrom();
keyBuilderParent = navQuery.getNavigationKeyBuilder();
}
return navigationQueryList;
}
@SuppressWarnings("unchecked")
private javax.persistence.criteria.Expression<Boolean> createWhereFromAccessConditioner()
throws ODataApplicationException {
final DataAccessConditioner<Object> dac = (DataAccessConditioner<Object>) getQueryResultType()
.getDataAccessConditioner();
if (dac == null) {
return null;
}
getContext().getDependencyInjector().injectDependencyValues(dac);
return dac.buildSelectCondition(getEntityManager(), (From<Object, Object>) getQueryResultFrom());
}
private final javax.persistence.criteria.Expression<Boolean> createWhereFromFilter(
final FilterContextQueryBuilderIfc filterContext, final List<UriResource> navPath, final FilterOption filterOption)
throws ExpressionVisitException, ODataApplicationException {
// determine the navigation builder matching the filter affecting path element
final VisitableExpression filterExpression = filterOption.getExpression();
if (filterExpression == null) {
return null;
}
final JPAEntityFilterProcessor<Boolean> filterProcessor = new JPAEntityFilterProcessor<Boolean>(getContext().getOdata(),
getContext()
.getEdmProvider().getServiceDocument(), getEntityManager(),
filterContext.getQueryResultType(), getContext().getDatabaseProcessor(), navPath, filterExpression,
filterContext);
return filterProcessor.compile();
}
protected javax.persistence.criteria.Expression<Boolean> createWhere() throws ODataApplicationException,
ODataJPAModelException {
javax.persistence.criteria.Expression<Boolean> whereCondition = createWhereFromKeyPredicates();
final javax.persistence.criteria.Expression<Boolean> accessConditionerClause =
createWhereFromAccessConditioner();
whereCondition = combineAND(whereCondition, accessConditionerClause);
// http://docs.oasis-open.org/odata/odata/v4.0/errata02/os/complete/part1-protocol/odata-v4.0-errata02-os-part1-protocol-complete.html#_Toc406398301
// http://docs.oasis-open.org/odata/odata/v4.0/errata02/os/complete/part2-url-conventions/odata-v4.0-errata02-os-part2-url-conventions-complete.html#_Toc406398094
// https://tools.oasis-open.org/version-control/browse/wsvn/odata/trunk/spec/ABNF/odata-abnf-construction-rules.txt
try {
// 1. check filter for current entity
final FilterOption filterOption = uriNavigation.getFilterOption(queryStartUriResource);
if (filterOption != null/* isLastNavigableElementInUriResource(uriInfo, queryStartUriResource) */) {
// no navigation, so we may have an filter directly for this entity
final List<UriResource> navPath = extractNavigableResourcePath(context.getEdmProvider().getServiceDocument(),
uriNavigation.getFirstStep().getUriResourceParts());
final FilterQueryBuilderContext filterContext = new FilterQueryBuilderContext(jpaStartEntityType,
getQueryStartFrom());
final javax.persistence.criteria.Expression<Boolean> filterCondition = createWhereFromFilter(filterContext,
navPath,
filterOption);
whereCondition = combineAND(whereCondition, filterCondition);
}
// 2. check filter for navigation elements also
for (final NavigationBuilder navQuery : navigationQueryList) {
if (!navQuery.isWorking()) {
continue;
}
final FilterOption navFilterOption = uriNavigation.getFilterOption(navQuery.getNavigationUriInfoResource());
if (navFilterOption == null) {
continue;
}
// TODO type cast ok? -> prefer JPAStructuredType
final FilterQueryBuilderContext navFilterContext = new FilterQueryBuilderContext((JPAEntityType) navQuery
.getQueryResultType(),
navQuery.getQueryResultFrom());
// build a navigation (sub) path up to the navigation element resource
final List<UriResource> navResourcePath = new LinkedList<UriResource>();
for (final UriResource current : uriNavigation.getUriResourceParts()) {
navResourcePath.add(current);
if (current == navQuery.getNavigationUriInfoResource()) {
break;
}
}
final List<UriResource> navFilterPath = extractNavigableResourcePath(context.getEdmProvider()
.getServiceDocument(), navResourcePath);
final javax.persistence.criteria.Expression<Boolean> navFilterCondition = createWhereFromFilter(
navFilterContext, navFilterPath, navFilterOption);
whereCondition = combineAND(whereCondition, navFilterCondition);
}
} catch (final ExpressionVisitException e) {
throw new ODataJPAQueryException(ODataJPAQueryException.MessageKeys.QUERY_PREPARATION_FILTER_ERROR,
HttpStatusCode.BAD_REQUEST, e);
}
final javax.persistence.criteria.Expression<Boolean> existsSubQuery = buildNavigationWhereClause();
whereCondition = combineAND(whereCondition, existsSubQuery);
whereCondition = combineAND(whereCondition, createWhereFromSearchOption(uriNavigation.getLastStep()
.getSearchOption()));
return whereCondition;
}
/**
*
* @return The identifiers for {@link #getQueryStartFrom()}
*/
private final List<UriParameter> getKeyPredicates() {
return keyPredicates;
}
private final javax.persistence.criteria.Expression<Boolean> createWhereFromKeyPredicates()
throws ODataApplicationException {
// javax.persistence.criteria.Expression<Boolean> whereCondition = null;
// final List<UriResource> resources = uriResource.getUriResourceParts();
final List<UriParameter> keyPredicates = getKeyPredicates();
// keys are always for start table, not for target after joins
final From<?, ?> root = getQueryStartFrom();
final JPAEntityType rootType = getQueryStartType();
// Given key: Organizations('1')
return extendWhereByKey(root, rootType, keyPredicates);
}
/**
* Generate sub-queries in order to select the target of a navigation to a different entity
* <p>
* In case of multiple navigation steps a inner navigation has a dependency in both directions, to the upper and to
* the lower query:
* <p>
* <code>SELECT * FROM upper WHERE EXISTS( <p>
* SELECT ... FROM inner WHERE upper = inner<p>
* AND EXISTS( SELECT ... FROM lower<p>
* WHERE inner = lower))</code>
* <p>
* This is solved by a three steps approach
* @throws ODataJPAModelException
*/
private javax.persistence.criteria.Expression<Boolean> buildNavigationWhereClause()
throws ODataApplicationException, ODataJPAModelException {
// 3. Create select statements
javax.persistence.criteria.Expression<Boolean> whereCondition = null;
for (final NavigationBuilder navQuery : navigationQueryList) {
if (!navQuery.isWorking()) {
continue;
}
final javax.persistence.criteria.Expression<Boolean> where = navQuery.buildJoinWhere();
whereCondition = combineAND(whereCondition, where);
}
return whereCondition;
}
/**
* Search at OData:
* <p>
* <a href=
* "http://docs.oasis-open.org/odata/odata/v4.0/os/part1-protocol/odata-v4.0-os-part1-protocol.html#_Toc372793700">
* OData Version 4.0 Part 1 - 192.168.3.11 System Query Option $search</a>
* <p>
* <a href=
* "http://docs.oasis-open.org/odata/odata/v4.0/os/part2-url-conventions/odata-v4.0-os-part2-url-conventions.html#_Toc372793865">
* OData Version 4.0 Part 2 - 5.1.7 System Query Option $search</a>
*
* @return
* @throws ODataApplicationException
* @throws ODataJPAModelException
*/
private javax.persistence.criteria.Expression<Boolean> createWhereFromSearchOption(final SearchOption searchOption)
throws ODataApplicationException,
ODataJPAModelException {
final FilterQueryBuilderContext filterHelper = new FilterQueryBuilderContext(getQueryResultType(),
getQueryResultFrom());
final SearchSubQueryBuilder searchQuery = new SearchSubQueryBuilder(filterHelper, searchOption);
final Subquery<?> subquery = searchQuery.getSubQueryExists();
if (subquery == null) {
return null;
}
return getCriteriaBuilder().exists(subquery);
}
protected final List<JPAAssociationAttribute> extractOrderByNaviAttributes() throws ODataApplicationException {
// TODO useless functionality, because we are joining already all navigation parts?!
final OrderByOption orderBy = uriNavigation.getLastStep().getOrderByOption();
if (orderBy == null) {
return Collections.emptyList();
}
final JPAStructuredType jpaEntityType = getQueryResultType();
final List<JPAAssociationAttribute> naviAttributes = new ArrayList<JPAAssociationAttribute>();
for (final OrderByItem orderByItem : orderBy.getOrders()) {
final Expression expression = orderByItem.getExpression();
if (!Member.class.isInstance(expression)) {
LOG.log(Level.WARNING, "OrderBy is supported only for Member expresssions not for " + expression.getClass()
.getSimpleName());
continue;
}
final UriInfoResource resourcePath = ((Member) expression).getResourcePath();
for (final UriResource uriResource : resourcePath.getUriResourceParts()) {
if (!UriResourceNavigation.class.isInstance(uriResource)) {
continue;
}
final EdmNavigationProperty edmNaviProperty = ((UriResourceNavigation) uriResource)
.getProperty();
try {
naviAttributes.add((JPAAssociationAttribute) jpaEntityType
.getAssociationPath(edmNaviProperty.getName()).getLeaf());
} catch (final ODataJPAModelException e) {
throw new ODataJPAQueryException(
ODataJPAQueryException.MessageKeys.QUERY_RESULT_CONV_ERROR,
HttpStatusCode.INTERNAL_SERVER_ERROR, e);
}
}
}
return naviAttributes;
}
/**
* The value of the $select query option is a comma-separated list of <b>properties</b>, qualified action names,
* qualified function names, the <b>star operator (*)</b>, or the star operator prefixed with the namespace or alias
* of the schema in order to specify all operations defined in the schema. See:
* <a
* href=
* "http://docs.oasis-open.org/odata/odata/v4.0/errata02/os/complete/part1-protocol/odata-v4.0-errata02-os-part1-protocol-complete.html#_Toc406398297"
* >OData Version 4.0 Part 1 - 192.168.127.12 System Query Option $select</a>
* <p>
* See also:
* <a
* href=
* "http://docs.oasis-open.org/odata/odata/v4.0/errata02/os/complete/part2-url-conventions/odata-v4.0-errata02-os-part2-url-conventions-complete.html#_Toc406398163"
* >OData Version 4.0 Part 2 - 5.1.3 System Query Option $select</a>
*
* @param select
* @return
* @throws ODataApplicationException
*/
protected final List<Selection<?>> createSelectClause(final Collection<? extends JPASelector> jpaPathList)
throws ODataJPAQueryException {
final List<Selection<?>> selections = new LinkedList<Selection<?>>();
// add keys from this query also if navigation exists
if (!navigationQueryList.isEmpty()) {
final List<JPASelector> listAssociationJoinKeyPaths = jpaStartNavigationKeyBuilder.getNavigationKeyPaths();
for (final JPASelector jPath : listAssociationJoinKeyPaths) {
// use FROM of starting entity, because the keys are all from that starting entity
final Path<?> p = convertToCriteriaAliasPath(getQueryStartFrom(), jPath, jpaStartNavigationKeyBuilder
.getNavigationAliasPrefix());
if (p == null) {
continue;
}
selections.add(p);
}
}
// Build select clause
for (final JPASelector jpaPath : jpaPathList) {
final Path<?> p = convertToCriteriaAliasPath(getQueryResultFrom(), jpaPath, null);
if (p == null) {
continue;
}
selections.add(p);
}
// add selection of all JOIN table keys, required to handle $expand entity mapping
selections.addAll(buildNavigationKeySelectionClauses());
return selections;
}
private List<Selection<?>> buildNavigationKeySelectionClauses() throws ODataJPAQueryException {
final List<Selection<?>> selections = new LinkedList<Selection<?>>();
// ignore the last navigation, because not neccessary to build entity navigation key
for (int i = 0; i < navigationQueryList.size() - 1; i++) {
final NavigationBuilder navQuery = navigationQueryList.get(i);
if (!navQuery.isWorking()) {
continue;
}
try {
final List<Selection<?>> joinSelection = navQuery.buildNavigationKeySelection();
selections.addAll(joinSelection);
} catch (ODataJPAModelException | ODataApplicationException e) {
throw new ODataJPAQueryException(ODataJPAQueryException.MessageKeys.QUERY_PREPARATION_ERROR,
HttpStatusCode.INTERNAL_SERVER_ERROR, e);
}
}
return selections;
}
protected final Map<String, From<?, ?>> createFromClause(final List<JPAAssociationAttribute> orderByTarget)
throws ODataApplicationException {
final HashMap<String, From<?, ?>> joinTables = new HashMap<String, From<?, ?>>();
final From<?, ?> root = getQueryResultFrom();
// 1. Create root
final JPAEntityType jpaEntityType = getQueryResultType();
joinTables.put(jpaEntityType.getInternalName(), root);
// 2. OrderBy navigation property
for (final JPAAssociationAttribute orderBy : orderByTarget) {
final Join<?, ?> join = root.join(orderBy.getInternalName(), JoinType.LEFT);
// Take on condition from JPA metadata; no explicit on
joinTables.put(orderBy.getInternalName(), join);
}
return joinTables;
}
/**
* @return A unique and reproducible alias name to access the attribute value in
* the result set after loading
*/
@Deprecated
protected static final String buildTargetJoinAlias(final JPAAssociationPath association,
final JPAMemberAttribute targetAttribute) {
return association.getAlias().concat("_").concat(targetAttribute.getInternalName());
}
}
|
3e06e3feaf98192548e093e8cd391d49351ca263 | 812 | java | Java | spring-propertysource-example/src/main/java/net/alanbinu/springboot2/springpropertysourceexample/DataSourceConfig.java | Cinta-tony/Spring-Boot-Advanced-Projects | ab6af8a1fccf7c39223ed9b20acc80a433d8be38 | [
"MIT"
] | null | null | null | spring-propertysource-example/src/main/java/net/alanbinu/springboot2/springpropertysourceexample/DataSourceConfig.java | Cinta-tony/Spring-Boot-Advanced-Projects | ab6af8a1fccf7c39223ed9b20acc80a433d8be38 | [
"MIT"
] | null | null | null | spring-propertysource-example/src/main/java/net/alanbinu/springboot2/springpropertysourceexample/DataSourceConfig.java | Cinta-tony/Spring-Boot-Advanced-Projects | ab6af8a1fccf7c39223ed9b20acc80a433d8be38 | [
"MIT"
] | 1 | 2021-12-13T18:08:00.000Z | 2021-12-13T18:08:00.000Z | 17.276596 | 96 | 0.699507 | 2,922 | package net.guides.springboot2.springpropertysourceexample;
public class DataSourceConfig {
private String driver;
private String url;
private String username;
private String password;
@Override
public String toString()
{
return "DataSourceConfig [driver=" + driver + ", url=" + url + ", username=" + username + "]";
}
public String getDriver()
{
return driver;
}
public void setDriver(String driver)
{
this.driver = driver;
}
public String getUrl()
{
return url;
}
public void setUrl(String url)
{
this.url = url;
}
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
}
|
3e06e447a2ddfd97f819123cb32c40f4050358d5 | 405 | java | Java | x-wing/src/main/java/io/enforcer/xwing/ProcessFinder.java | kavehg/enforcer-one | 2aeda6d3c589214c7a4a0409ddad396dd701bb31 | [
"Apache-2.0"
] | null | null | null | x-wing/src/main/java/io/enforcer/xwing/ProcessFinder.java | kavehg/enforcer-one | 2aeda6d3c589214c7a4a0409ddad396dd701bb31 | [
"Apache-2.0"
] | 1 | 2019-03-14T18:15:52.000Z | 2019-03-14T18:15:52.000Z | x-wing/src/main/java/io/enforcer/xwing/ProcessFinder.java | kavehg/enforcer-one | 2aeda6d3c589214c7a4a0409ddad396dd701bb31 | [
"Apache-2.0"
] | null | null | null | 22.5 | 69 | 0.698765 | 2,923 | package io.enforcer.xwing;
import java.util.Set;
/**
* Created by kavehg on 7/27/2015.
*/
public interface ProcessFinder {
/**
* Given a string return all process Ids that contain this string
*
* @param searchFilter string by which to filter processes
* @return process Ids matching search filter
*/
Set<MonitoredProcess> getMatchingProcesses(String searchFilter);
}
|
3e06e4c65c41aebae5cfb4bc055a48450fe724ad | 747 | java | Java | src/main/java/com/hubspot/jinjava/lib/filter/ListFilter.java | ahuus1/jinjava-1.6-compatible | 8b8ac11c232310ef76b175e13f9b08c4af44a4fa | [
"Apache-2.0"
] | null | null | null | src/main/java/com/hubspot/jinjava/lib/filter/ListFilter.java | ahuus1/jinjava-1.6-compatible | 8b8ac11c232310ef76b175e13f9b08c4af44a4fa | [
"Apache-2.0"
] | null | null | null | src/main/java/com/hubspot/jinjava/lib/filter/ListFilter.java | ahuus1/jinjava-1.6-compatible | 8b8ac11c232310ef76b175e13f9b08c4af44a4fa | [
"Apache-2.0"
] | null | null | null | 20.75 | 84 | 0.677376 | 2,924 | package com.hubspot.jinjava.lib.filter;
import java.util.Collection;
import java.util.List;
import com.google.common.collect.Lists;
import com.hubspot.jinjava.interpret.JinjavaInterpreter;
public class ListFilter implements Filter {
@Override
public String getName() {
return "list";
}
@Override
public Object filter(Object var, JinjavaInterpreter interpreter, String... args) {
List<?> result;
if(var instanceof String) {
result = Lists.newArrayList(((String) var).toCharArray());
}
else if(Collection.class.isAssignableFrom(var.getClass())) {
result = Lists.newArrayList((Collection<?>) var);
}
else {
result = Lists.newArrayList(var);
}
return result;
}
}
|
3e06e5fd3363047fbb7472825f4b109b7f465959 | 1,147 | java | Java | src/main/java/gwt/material/design/addins/client/timepicker/MaterialTimePickerDarkTheme.java | vokke/gwt-material-addins | 4014982b0f8b8d1115239e284965a564760d2804 | [
"Apache-2.0"
] | 37 | 2015-11-19T15:53:12.000Z | 2021-04-03T22:38:18.000Z | src/main/java/gwt/material/design/addins/client/timepicker/MaterialTimePickerDarkTheme.java | vokke/gwt-material-addins | 4014982b0f8b8d1115239e284965a564760d2804 | [
"Apache-2.0"
] | 360 | 2015-12-01T15:20:51.000Z | 2021-12-23T14:08:34.000Z | src/main/java/gwt/material/design/addins/client/timepicker/MaterialTimePickerDarkTheme.java | vokke/gwt-material-addins | 4014982b0f8b8d1115239e284965a564760d2804 | [
"Apache-2.0"
] | 57 | 2015-11-30T17:25:28.000Z | 2022-01-29T18:09:10.000Z | 35.84375 | 112 | 0.753269 | 2,925 | /*
* #%L
* GwtMaterial
* %%
* Copyright (C) 2015 - 2019 GwtMaterialDesign
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package gwt.material.design.addins.client.timepicker;
import gwt.material.design.addins.client.MaterialAddins;
import gwt.material.design.addins.client.dark.AddinsWidgetDarkTheme;
public class MaterialTimePickerDarkTheme extends AddinsWidgetDarkTheme {
public MaterialTimePickerDarkTheme() {
super(MaterialAddins.isDebug() ? MaterialTimePickerDebugClientBundle.INSTANCE.timepickerDarkCssDebug() :
MaterialTimePickerClientBundle.INSTANCE.timepickerDarkCss());
}
}
|
3e06e6caf0bf3d2749b51233658883cbeb129ddb | 1,055 | java | Java | src/taglib/src/main/java/org/apache/struts/taglib/html/FileTag.java | caseydunham/struts-1.3.5 | 11342b2ad3cba622ed6b3e8f84854bef0bdfe271 | [
"Apache-2.0"
] | null | null | null | src/taglib/src/main/java/org/apache/struts/taglib/html/FileTag.java | caseydunham/struts-1.3.5 | 11342b2ad3cba622ed6b3e8f84854bef0bdfe271 | [
"Apache-2.0"
] | null | null | null | src/taglib/src/main/java/org/apache/struts/taglib/html/FileTag.java | caseydunham/struts-1.3.5 | 11342b2ad3cba622ed6b3e8f84854bef0bdfe271 | [
"Apache-2.0"
] | null | null | null | 29.305556 | 78 | 0.674882 | 2,926 | /*
* $Id: FileTag.java 376841 2006-02-10 21:01:28Z husted $
*
* Copyright 1999,2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.struts.taglib.html;
/**
* Custom tag for input fields of type "file".
*
* @version $Rev: 376841 $ $Date: 2004-10-16 12:38:42 -0400 (Sat, 16 Oct 2004)
* $
*/
public class FileTag extends BaseFieldTag {
/**
* Construct a new instance of this tag.
*/
public FileTag() {
super();
this.type = "file";
}
}
|
3e06e8b30951b58d7a7109937afb3669923fe029 | 1,131 | java | Java | src/main/java/com/example/hookahshop_diploma/util/ImageSender.java | Antaaaaa/hookahshop_diploma | f4b8e9508f92198f4b6250c7053fa01fb2231462 | [
"MIT"
] | null | null | null | src/main/java/com/example/hookahshop_diploma/util/ImageSender.java | Antaaaaa/hookahshop_diploma | f4b8e9508f92198f4b6250c7053fa01fb2231462 | [
"MIT"
] | null | null | null | src/main/java/com/example/hookahshop_diploma/util/ImageSender.java | Antaaaaa/hookahshop_diploma | f4b8e9508f92198f4b6250c7053fa01fb2231462 | [
"MIT"
] | null | null | null | 30.567568 | 91 | 0.731211 | 2,927 | package com.example.hookahshop_diploma.util;
import com.cloudinary.Cloudinary;
import com.cloudinary.utils.ObjectUtils;
import lombok.SneakyThrows;
import org.cloudinary.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.nio.file.Files;
import java.util.Map;
@Component
public class ImageSender {
@Value("${com.cloudinary.cloud_name}")
String mCloudName;
@Value("${com.cloudinary.api_key}")
String mApiKey;
@Value("${com.cloudinary.api_secret}")
String mApiSecret;
@SneakyThrows
public String uploadImageAndGetUrl(MultipartFile image){
Cloudinary c=new Cloudinary("cloudinary://"+mApiKey+":"+mApiSecret+"@"+mCloudName);
File f= Files.createTempFile("temp", image.getOriginalFilename()).toFile();
image.transferTo(f);
Map response=c.uploader().upload(f, ObjectUtils.emptyMap());
JSONObject json=new JSONObject(response);
String url=json.getString("url");
return url;
}
}
|
3e06e8f60008404b09793c2cdfb67857fb00918a | 1,671 | java | Java | src/main/java/com/hydronitrogen/datacollector/importer/YahooFinanceUtils.java | k0r0p/datacollector | 52a999f2a5e7913d19cab2881bf2e26084a2347f | [
"Apache-2.0"
] | 1 | 2019-12-03T11:01:57.000Z | 2019-12-03T11:01:57.000Z | src/main/java/com/hydronitrogen/datacollector/importer/YahooFinanceUtils.java | k0r0p/datacollector | 52a999f2a5e7913d19cab2881bf2e26084a2347f | [
"Apache-2.0"
] | null | null | null | src/main/java/com/hydronitrogen/datacollector/importer/YahooFinanceUtils.java | k0r0p/datacollector | 52a999f2a5e7913d19cab2881bf2e26084a2347f | [
"Apache-2.0"
] | null | null | null | 33.42 | 114 | 0.640335 | 2,928 | package com.hydronitrogen.datacollector.importer;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.commons.io.IOUtils;
import org.joda.time.DateTime;
/**
* @author hkothari
*
*/
public final class YahooFinanceUtils {
private YahooFinanceUtils() {
// Utility class -- do not instantiate.
}
// s = TICKER, a = start month 2 digits, b = start day 2 digits, c = start year
// d = end month 2 digits, e = end day 2 digits, f = end year
private static final String CSV_DOWNLOAD_URL = "http://ichart.finance.yahoo.com/table.csv?"
+ "s=%s&a=%02d&b=%02d&c=%d&d=%02d&e=%02d&f=%d&g=d&ignore=.csv";
/**
* Gets the historical price data from Yahoo Finance.
* @param ticker the stock ticker to look up
* @param startDate the date from which to begin prices.
* @param endDate the last date of prices to include.
* @return a String of a CSV of historical prices.
*/
public static String getHistoricalPrices(String ticker, DateTime startDate, DateTime endDate) {
String downloadUrl = String.format(CSV_DOWNLOAD_URL, ticker, startDate.getMonthOfYear(),
startDate.getDayOfMonth(), startDate.getYear(), endDate.getMonthOfYear(), endDate.getDayOfMonth(),
endDate.getYear());
URL url;
try {
url = new URL(downloadUrl);
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
try {
return IOUtils.toString(url.openStream());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
|
3e06e95843dbc04f02ac22952ca9b85a58c9de5a | 565 | java | Java | ruoyi-common/src/main/java/com/ruoyi/common/annotation/RepeatSubmit.java | wcw0329/RuoYi | fa6fd08332da607972367f34686b05fb6110cd64 | [
"MIT"
] | 1,966 | 2018-08-11T12:52:25.000Z | 2022-03-31T15:50:41.000Z | ruoyi-common/src/main/java/com/ruoyi/common/annotation/RepeatSubmit.java | wcw0329/RuoYi | fa6fd08332da607972367f34686b05fb6110cd64 | [
"MIT"
] | 105 | 2019-10-04T05:48:05.000Z | 2022-03-24T03:38:47.000Z | ruoyi-common/src/main/java/com/ruoyi/common/annotation/RepeatSubmit.java | wcw0329/RuoYi | fa6fd08332da607972367f34686b05fb6110cd64 | [
"MIT"
] | 807 | 2019-01-03T06:11:28.000Z | 2022-03-31T05:47:51.000Z | 19.482759 | 52 | 0.715044 | 2,929 | package com.ruoyi.common.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 自定义注解防止表单重复提交
*
* @author ruoyi
*
*/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RepeatSubmit
{
/**
* 间隔时间(ms),小于此时间视为重复提交
*/
public int interval() default 5000;
/**
* 提示消息
*/
public String message() default "不允许重复提交,请稍后再试";
} |
3e06ea03970ec7e2bd3d0ea115fc77bfbed038eb | 1,517 | java | Java | processing/src/main/java/io/druid/segment/column/LongColumn.java | jisookim0513/druid | 177b575d416a142424a2a8792e669ae07e771562 | [
"Apache-2.0"
] | 7 | 2019-01-27T14:45:47.000Z | 2021-12-18T08:24:18.000Z | processing/src/main/java/io/druid/segment/column/LongColumn.java | jisookim0513/druid | 177b575d416a142424a2a8792e669ae07e771562 | [
"Apache-2.0"
] | 3 | 2021-01-21T01:41:58.000Z | 2021-12-14T21:54:59.000Z | processing/src/main/java/io/druid/segment/column/LongColumn.java | jisookim0513/druid | 177b575d416a142424a2a8792e669ae07e771562 | [
"Apache-2.0"
] | 7 | 2016-05-12T18:59:53.000Z | 2019-10-18T18:19:32.000Z | 27.089286 | 89 | 0.752142 | 2,930 | /*
* Licensed to Metamarkets Group Inc. (Metamarkets) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. Metamarkets 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 io.druid.segment.column;
import io.druid.segment.data.CompressedLongsIndexedSupplier;
/**
*/
public class LongColumn extends AbstractColumn
{
private static final ColumnCapabilitiesImpl CAPABILITIES = new ColumnCapabilitiesImpl()
.setType(ValueType.LONG);
private final CompressedLongsIndexedSupplier column;
public LongColumn(CompressedLongsIndexedSupplier column)
{
this.column = column;
}
@Override
public ColumnCapabilities getCapabilities()
{
return CAPABILITIES;
}
@Override
public int getLength()
{
return column.size();
}
@Override
public GenericColumn getGenericColumn()
{
return new IndexedLongsGenericColumn(column.get());
}
}
|
3e06ebb0a1855d2b26139cab323a3be8148ea148 | 1,165 | java | Java | dropwizard-jdbi/src/main/java/io/dropwizard/jdbi/jersey/LoggingDBIExceptionMapper.java | karandkanwar/dropwizard | 90a939ae5838361bc99447964cc7285aad9ad8d5 | [
"Apache-2.0"
] | 2 | 2015-04-15T06:34:55.000Z | 2019-05-07T09:50:43.000Z | dropwizard-jdbi/src/main/java/io/dropwizard/jdbi/jersey/LoggingDBIExceptionMapper.java | karandkanwar/dropwizard | 90a939ae5838361bc99447964cc7285aad9ad8d5 | [
"Apache-2.0"
] | 10 | 2020-06-08T13:50:09.000Z | 2020-08-11T05:19:55.000Z | dropwizard-jdbi/src/main/java/io/dropwizard/jdbi/jersey/LoggingDBIExceptionMapper.java | karandkanwar/dropwizard | 90a939ae5838361bc99447964cc7285aad9ad8d5 | [
"Apache-2.0"
] | 10 | 2016-07-11T12:40:49.000Z | 2022-02-23T10:34:45.000Z | 32.361111 | 92 | 0.723605 | 2,931 | package io.dropwizard.jdbi.jersey;
import com.google.common.annotations.VisibleForTesting;
import io.dropwizard.jersey.errors.LoggingExceptionMapper;
import org.skife.jdbi.v2.exceptions.DBIException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ws.rs.ext.Provider;
import java.sql.SQLException;
/**
* Iterates through a DBIException's cause if it's a SQLException otherwise log as normal.
*/
@Provider
public class LoggingDBIExceptionMapper extends LoggingExceptionMapper<DBIException> {
private static Logger logger = LoggerFactory.getLogger(LoggingDBIExceptionMapper.class);
@Override
protected void logException(long id, DBIException exception) {
final Throwable cause = exception.getCause();
if (cause instanceof SQLException) {
for (Throwable throwable : (SQLException) cause) {
logger.error(formatLogMessage(id, throwable), throwable);
}
} else {
logger.error(formatLogMessage(id, exception), exception);
}
}
@VisibleForTesting
static synchronized void setLogger(Logger newLogger) {
logger = newLogger;
}
}
|
3e06ed269576a6a91bbb210d650124a038d1ad64 | 967 | java | Java | easyrouter-merge/src/main/java/me/zane/easyrouter_merge/RouterModulePlugin.java | Zane96/EasyRouter | 29e8a3c00dffdb653aa0bab3f29ec2e1528a0c69 | [
"Apache-2.0"
] | 176 | 2017-02-25T13:35:16.000Z | 2022-02-15T01:21:22.000Z | easyrouter-merge/src/main/java/me/zane/easyrouter_merge/RouterModulePlugin.java | Zane96/EasyRouter | 29e8a3c00dffdb653aa0bab3f29ec2e1528a0c69 | [
"Apache-2.0"
] | null | null | null | easyrouter-merge/src/main/java/me/zane/easyrouter_merge/RouterModulePlugin.java | Zane96/EasyRouter | 29e8a3c00dffdb653aa0bab3f29ec2e1528a0c69 | [
"Apache-2.0"
] | 23 | 2017-07-06T04:10:33.000Z | 2021-02-16T14:00:34.000Z | 34.607143 | 121 | 0.717234 | 2,932 | package me.zane.easyrouter_merge;
import com.android.build.gradle.BaseExtension;
import org.gradle.api.Project;
import org.gradle.api.Plugin;
import org.gradle.api.ProjectConfigurationException;
/**
* Created by Zane on 2018/4/19.
* Email: nnheo@example.com
*/
public class RouterModulePlugin implements Plugin<Project> {
@Override
public void apply(Project project) {
BaseExtension androidExtension = (BaseExtension) project.getExtensions().getByName("android");
if (project.getPlugins().findPlugin("com.android.application") != null) {
androidExtension.registerTransform(new ApplicationTransform());
} else if (project.getPlugins().findPlugin("com.android.library") != null) {
androidExtension.registerTransform(new LibraryTransform(project));
} else {
throw new ProjectConfigurationException("Need android application/library plugin to be applied first", null);
}
}
}
|
3e06eddecde4db5846e69952f5f0839184dc53bc | 1,430 | java | Java | api/spdorm/src/main/java/com/rmuti/spdorm/model/service/HistoryRepository.java | spdorm/spdorm.github.io | 4b81b0878c2a09af6a7a49f14d17dad8223a6e54 | [
"MIT"
] | null | null | null | api/spdorm/src/main/java/com/rmuti/spdorm/model/service/HistoryRepository.java | spdorm/spdorm.github.io | 4b81b0878c2a09af6a7a49f14d17dad8223a6e54 | [
"MIT"
] | 14 | 2019-08-13T02:50:33.000Z | 2019-11-21T09:40:02.000Z | api/spdorm/src/main/java/com/rmuti/spdorm/model/service/HistoryRepository.java | spdorm/spdorm.github.io | 4b81b0878c2a09af6a7a49f14d17dad8223a6e54 | [
"MIT"
] | 3 | 2019-09-02T19:04:37.000Z | 2021-07-14T05:12:03.000Z | 42.058824 | 213 | 0.745455 | 2,933 | package com.rmuti.spdorm.model.service;
import java.util.Date;
import java.util.List;
import com.rmuti.spdorm.model.table.History;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import javax.transaction.Transactional;
public interface HistoryRepository extends JpaRepository<History, Integer> {
History findByHistoryId(int historyId);
@Query(value = "select * from history a where a.dorm_id = ?1 and a.user_id = ?2 and a.history_status = ?3", nativeQuery = true)
History findByDormIdAndUserId(int dormId, int userId, String status);
@Query(value = "select a.*,b.user_username,b.user_firstname,b.user_lastname from history a left join user_profile b on a.user_id = b.user_id where a.dorm_id = ?1 and a.history_status = ?2", nativeQuery = true)
List<Object[]> listByDormId(int dormId,String status);
@Transactional
@Modifying
@Query(value = "update history a set a.room_id = ?2, a.time_in = ?3 , a.history_status = ?4 where a.history_id = ?1", nativeQuery = true)
void updateHistory(int historyId,int roomId, Date timeIn, String status);
@Transactional
@Modifying
@Query(value = "update history a set a.time_out = ?2, a.history_status = ?3 where a.history_id = ?1",nativeQuery = true)
void cancel(int historyId,Date timeOut, String status);
}
|
3e06ee300f68edc2e019c3ea88e66e28bee524c9 | 847 | java | Java | netty-base/src/main/java/com/star/base/nio/MappedByBuffer.java | CodePrometheus/Netty | 105102d0475362895440dd3257f79cbd851f221e | [
"MIT"
] | null | null | null | netty-base/src/main/java/com/star/base/nio/MappedByBuffer.java | CodePrometheus/Netty | 105102d0475362895440dd3257f79cbd851f221e | [
"MIT"
] | null | null | null | netty-base/src/main/java/com/star/base/nio/MappedByBuffer.java | CodePrometheus/Netty | 105102d0475362895440dd3257f79cbd851f221e | [
"MIT"
] | null | null | null | 29.206897 | 94 | 0.688312 | 2,934 | package com.star.base.nio;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
/**
* 可以让文件直接在内存(堆外内存)修改,操作系统不需要拷贝一次
*
* @Author: zzStar
* @Date: 11-08-2020 16:54
*/
public class MappedByBuffer {
public static void main(String[] args) throws IOException {
RandomAccessFile randomAccessFile = new RandomAccessFile("file.txt", "rw");
// 获取对应的文件通道
FileChannel channel = randomAccessFile.getChannel();
// 参数1:使用的模式 参数2:可以直接修改的起始位置 参数3:映射到内存的大小,即将文件的多少个字节映射到内存
MappedByteBuffer mappedByteBuffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, 5);
mappedByteBuffer.put(0, (byte) 'G');
mappedByteBuffer.put(4, (byte) '!');
randomAccessFile.close();
System.out.println(" 修改成功 ");
}
}
|
3e06ee7f662eddf8f3f4f9282b82778cda1ceb0e | 414 | java | Java | Soundwind-backend/src/main/java/com/framework/enums/ResultCode.java | yfhcoming/JavaEE-backEnd | a048956f74fbbeb60404a59bb829dfb7590858b9 | [
"MIT"
] | null | null | null | Soundwind-backend/src/main/java/com/framework/enums/ResultCode.java | yfhcoming/JavaEE-backEnd | a048956f74fbbeb60404a59bb829dfb7590858b9 | [
"MIT"
] | null | null | null | Soundwind-backend/src/main/java/com/framework/enums/ResultCode.java | yfhcoming/JavaEE-backEnd | a048956f74fbbeb60404a59bb829dfb7590858b9 | [
"MIT"
] | null | null | null | 18 | 48 | 0.642512 | 2,935 | package com.framework.enums;
import lombok.Getter;
/**
* 框架层异常,非业务异常
*/
@Getter
public enum ResultCode implements StatusCode {
SUCCESS(1000, "请求成功"),
FAILED(1001, "请求失败"),
VALIDATE_ERROR(1002, "参数校验失败"),
RESPONSE_PACK_ERROR(1003, "response返回包装失败");
private int code;
private String msg;
ResultCode(int code, String msg) {
this.code = code;
this.msg = msg;
}
}
|
3e06ee8f327751e4ad18b549964ac4bf79002d87 | 2,410 | java | Java | app/src/main/java/com/fjoglar/lyricly/songs/favorite/FavoriteSongsViewModel.java | ptsiogas4/lyricly | 8e19f8da278b78bd98698c877e26ea32be7776f7 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/fjoglar/lyricly/songs/favorite/FavoriteSongsViewModel.java | ptsiogas4/lyricly | 8e19f8da278b78bd98698c877e26ea32be7776f7 | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/fjoglar/lyricly/songs/favorite/FavoriteSongsViewModel.java | ptsiogas4/lyricly | 8e19f8da278b78bd98698c877e26ea32be7776f7 | [
"Apache-2.0"
] | null | null | null | 33.943662 | 86 | 0.719502 | 2,936 | /*
* Copyright 2018 Felipe Joglar Santos
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fjoglar.lyricly.songs.favorite;
import com.fjoglar.lyricly.data.SongsRepository;
import com.fjoglar.lyricly.songs.SongsResponse;
import com.fjoglar.lyricly.songs.SongsViewModel;
import com.fjoglar.lyricly.util.schedulers.SchedulerProvider;
import androidx.annotation.Nullable;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import io.reactivex.disposables.CompositeDisposable;
public class FavoriteSongsViewModel extends ViewModel implements SongsViewModel {
private SongsRepository mSongsRepository;
private final CompositeDisposable mDisposables = new CompositeDisposable();
private final MutableLiveData<SongsResponse> mResponse = new MutableLiveData<>();
private final MutableLiveData<Boolean> mLoadingState = new MutableLiveData<>();
public FavoriteSongsViewModel(@Nullable SongsRepository songsRepository) {
mSongsRepository = songsRepository;
mLoadingState.setValue(false);
getFavoriteSongs();
}
@Override
protected void onCleared() {
mDisposables.clear();
}
@Override
public LiveData<SongsResponse> getResponse() {
return mResponse;
}
@Override
public LiveData<Boolean> getLoadingState() {
return mLoadingState;
}
private void getFavoriteSongs() {
mDisposables.add(new GetFavoriteSongsUseCase().execute(mSongsRepository, null)
.subscribeOn(SchedulerProvider.getInstance().io())
.observeOn(SchedulerProvider.getInstance().ui())
.subscribe(
songs -> mResponse.setValue(SongsResponse.load(songs)),
error -> mResponse.setValue(SongsResponse.error(error))
)
);
}
}
|
3e06eeb04cda771982f41c57d19cf515abca5cb2 | 1,914 | java | Java | ZWBH-Android/app/src/main/java/com/ruitukeji/zwbh/mine/shippercertification/dialog/SubmitBouncedDialog.java | 921668753/wztx-shipper-android | 73946a321e065c6d2ed4bd60d09912f058c606e9 | [
"Apache-2.0"
] | null | null | null | ZWBH-Android/app/src/main/java/com/ruitukeji/zwbh/mine/shippercertification/dialog/SubmitBouncedDialog.java | 921668753/wztx-shipper-android | 73946a321e065c6d2ed4bd60d09912f058c606e9 | [
"Apache-2.0"
] | null | null | null | ZWBH-Android/app/src/main/java/com/ruitukeji/zwbh/mine/shippercertification/dialog/SubmitBouncedDialog.java | 921668753/wztx-shipper-android | 73946a321e065c6d2ed4bd60d09912f058c606e9 | [
"Apache-2.0"
] | null | null | null | 29.446154 | 94 | 0.680251 | 2,937 | package com.ruitukeji.zwbh.mine.shippercertification.dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import com.ruitukeji.zwbh.R;
import com.ruitukeji.zwbh.common.BaseDialog;
/**
* 货主认证---提交弹框
* Created by Administrator on 2017/11/28.
*/
public abstract class SubmitBouncedDialog extends BaseDialog implements View.OnClickListener {
private Context context;
private TextView tv_cancel;
private TextView tv_determine;
private TextView tv_content;
public SubmitBouncedDialog(Context context) {
super(context, R.style.dialog);
this.context = context;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_markedasreadbounced);
Window dialogWindow = getWindow();
WindowManager.LayoutParams lp = dialogWindow.getAttributes();
lp.width= WindowManager.LayoutParams.MATCH_PARENT;
lp.height= WindowManager.LayoutParams.MATCH_PARENT;
dialogWindow.setAttributes(lp);
initView();
}
private void initView() {
tv_content = (TextView) findViewById(R.id.tv_content);
tv_content.setText(context.getString(R.string.confirmationInformation));
tv_cancel = (TextView) findViewById(R.id.tv_cancel);
tv_cancel.setOnClickListener(this);
tv_determine = (TextView) findViewById(R.id.tv_determine);
tv_determine.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.tv_cancel:
cancel();
break;
case R.id.tv_determine:
confirm();
break;
}
}
public abstract void confirm();
}
|
3e06ef4b68a9f5044a6bcbb36a6ec2d3e819f803 | 1,843 | java | Java | transpiler/java/com/google/j2cl/transpiler/ast/BooleanLiteral.java | axls/j2cl | 307b545a0180d8469acf648f56351adb72ba42ae | [
"Apache-2.0"
] | 3 | 2019-10-21T19:35:33.000Z | 2021-10-12T10:18:53.000Z | transpiler/java/com/google/j2cl/transpiler/ast/BooleanLiteral.java | axls/j2cl | 307b545a0180d8469acf648f56351adb72ba42ae | [
"Apache-2.0"
] | 4 | 2019-09-30T14:43:31.000Z | 2021-02-05T02:10:12.000Z | transpiler/java/com/google/j2cl/transpiler/ast/BooleanLiteral.java | axls/j2cl | 307b545a0180d8469acf648f56351adb72ba42ae | [
"Apache-2.0"
] | 6 | 2019-09-13T14:15:54.000Z | 2020-04-22T23:23:09.000Z | 27.102941 | 80 | 0.721107 | 2,938 | /*
* Copyright 2015 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.j2cl.transpiler.ast;
import com.google.j2cl.common.visitor.Processor;
import com.google.j2cl.common.visitor.Visitable;
/** Boolean literal node. */
@Visitable
public class BooleanLiteral extends Literal {
private static final ThreadLocal<BooleanLiteral> FALSE =
ThreadLocal.withInitial(() -> new BooleanLiteral(false));
private static final ThreadLocal<BooleanLiteral> TRUE =
ThreadLocal.withInitial(() -> new BooleanLiteral(true));
private final boolean value;
private BooleanLiteral(boolean value) {
this.value = value;
}
public static BooleanLiteral get(boolean value) {
return value ? TRUE.get() : FALSE.get();
}
public boolean getValue() {
return value;
}
@Override
public String getSourceText() {
return value ? "true" : "false";
}
@Override
public TypeDescriptor getTypeDescriptor() {
return PrimitiveTypes.BOOLEAN;
}
@Override
public Expression prefixNot() {
return get(!value);
}
@Override
public BooleanLiteral clone() {
// Boolean literals are value types do not need to be actually cloned.
return this;
}
@Override
public Node accept(Processor processor) {
return Visitor_BooleanLiteral.visit(processor, this);
}
}
|
3e06eff11aae3d2991cc8e803ac8c57e2209d883 | 2,504 | java | Java | app/src/main/java/com/bl/locodroid/MenuActivity.java | nmalesic/LocoDroid | bd0fb0bac08bc924a7a3d4dd67dee46a8ba0929d | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/bl/locodroid/MenuActivity.java | nmalesic/LocoDroid | bd0fb0bac08bc924a7a3d4dd67dee46a8ba0929d | [
"Apache-2.0"
] | null | null | null | app/src/main/java/com/bl/locodroid/MenuActivity.java | nmalesic/LocoDroid | bd0fb0bac08bc924a7a3d4dd67dee46a8ba0929d | [
"Apache-2.0"
] | null | null | null | 34.777778 | 103 | 0.559505 | 2,939 | package com.bl.locodroid;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.bl.locodroid.model.LocoModel;
import com.bl.locodroid.user.UserListActivity;
/**
* Created by SRABOIS on 22/02/2016.
*/
public class MenuActivity extends AppCompatActivity {
LocoModel model;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected (MenuItem item){
model = LocoModel.getInstance(this);
switch (item.getItemId()){
case R.id.menu_about:
Intent myIntent_about = new Intent(MenuActivity.this, AboutActivity.class);
startActivity(myIntent_about);
return true;
case R.id.menu_quit:
finish();
return true;
case R.id.menu_register:
Intent myIntent_register = new Intent(MenuActivity.this, RegisterActivity.class);
startActivity(myIntent_register);
return true;
case R.id.menu_connect:
Intent myIntent_connect = new Intent(MenuActivity.this, LoginActivity.class);
startActivity(myIntent_connect);
finish();
return true;
case R.id.menu_disconnect:
model.disconnect();
startActivity(new Intent(this, MainActivity.class));
finish();
return true;
case R.id.menu_home:
Intent myIntent_home = new Intent(MenuActivity.this, MainActivity.class);
startActivity(myIntent_home);
return true;
case R.id.menu_search:
Intent myIntent_list = new Intent(MenuActivity.this, UserListActivity.class);
startActivity(myIntent_list);
return true;
case R.id.menu_profile:
Intent myIntent_profile = new Intent(MenuActivity.this, UserProfileActivity.class);
startActivity(myIntent_profile);
return true;
default:return true;
}
}
}
|
3e06f15758daaf4431f65d534f804e1452997034 | 779 | java | Java | src/main/java/com/asksunny/tool/BulkRegistrationConfiguration.java | devsunny/common-tools | d476be7380aa9f77af54435d6cae5f00bd3d6d39 | [
"MIT"
] | null | null | null | src/main/java/com/asksunny/tool/BulkRegistrationConfiguration.java | devsunny/common-tools | d476be7380aa9f77af54435d6cae5f00bd3d6d39 | [
"MIT"
] | null | null | null | src/main/java/com/asksunny/tool/BulkRegistrationConfiguration.java | devsunny/common-tools | d476be7380aa9f77af54435d6cae5f00bd3d6d39 | [
"MIT"
] | null | null | null | 19.974359 | 94 | 0.747112 | 2,940 | package com.asksunny.tool;
import java.util.List;
public class BulkRegistrationConfiguration {
private Resource resource;
private List<SchemaMapping> schemaMappings;
public BulkRegistrationConfiguration() {
}
public static BulkRegistrationConfiguration newInstance()
{
return new BulkRegistrationConfiguration();
}
public Resource getResource() {
return resource;
}
public BulkRegistrationConfiguration setResource(Resource resource) {
this.resource = resource;
return this;
}
public List<SchemaMapping> getSchemaMappings() {
return schemaMappings;
}
public BulkRegistrationConfiguration setSchemaMappings(List<SchemaMapping> schemaMappings) {
this.schemaMappings = schemaMappings;
return this;
}
}
|
3e06f1d4324820e39411d807d69ab41ce81b90c2 | 1,516 | java | Java | management/src/main/javax/management/j2ee/statistics/JTAStats.java | cquoss/jboss-4.2.3.GA-jdk8 | f3acab9a69c764365bb3f38c0e9a01708dd22b4b | [
"Apache-2.0"
] | null | null | null | management/src/main/javax/management/j2ee/statistics/JTAStats.java | cquoss/jboss-4.2.3.GA-jdk8 | f3acab9a69c764365bb3f38c0e9a01708dd22b4b | [
"Apache-2.0"
] | null | null | null | management/src/main/javax/management/j2ee/statistics/JTAStats.java | cquoss/jboss-4.2.3.GA-jdk8 | f3acab9a69c764365bb3f38c0e9a01708dd22b4b | [
"Apache-2.0"
] | null | null | null | 32.404255 | 70 | 0.729481 | 2,941 | /*
* JBoss, Home of Professional Open Source.
* Copyright 2006, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This 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 software 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 software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package javax.management.j2ee.statistics;
/**
* Specifies the statistics provided by a JTA resource.
*
* @author efpyi@example.com
*/
public interface JTAStats extends Stats
{
/**
* Number of active transactions.
*/
public CountStatistic getActiveCount();
/**
* Number of committed transactions.
*/
public CountStatistic getCommittedCount();
/**
* Number of rolled-back transactions.
*/
public CountStatistic getRolledbackCount();
}
|
3e06f232b0fd40999515651e2c5df23d5cd6b132 | 9,220 | java | Java | compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/intrinsics/IntrinsicMethods.java | lsmaira/kotlin | c72cf02e6cfdc611ffa0f56e097a5882bd7de41a | [
"Apache-2.0"
] | 152 | 2016-02-03T20:19:47.000Z | 2021-05-28T07:08:12.000Z | compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/intrinsics/IntrinsicMethods.java | lsmaira/kotlin | c72cf02e6cfdc611ffa0f56e097a5882bd7de41a | [
"Apache-2.0"
] | 1 | 2021-02-24T04:02:24.000Z | 2021-02-24T04:02:24.000Z | compiler/ir/backend.jvm/src/org/jetbrains/kotlin/backend/jvm/intrinsics/IntrinsicMethods.java | lsmaira/kotlin | c72cf02e6cfdc611ffa0f56e097a5882bd7de41a | [
"Apache-2.0"
] | 54 | 2016-02-29T16:27:38.000Z | 2020-12-26T15:02:23.000Z | 48.526316 | 159 | 0.712256 | 2,942 | /*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.backend.jvm.intrinsics;
import com.google.common.collect.ImmutableList;
import kotlin.text.StringsKt;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.builtins.KotlinBuiltIns;
import org.jetbrains.kotlin.builtins.PrimitiveType;
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor;
import org.jetbrains.kotlin.lexer.KtTokens;
import org.jetbrains.kotlin.name.FqName;
import org.jetbrains.kotlin.name.FqNameUnsafe;
import org.jetbrains.kotlin.name.Name;
import org.jetbrains.kotlin.resolve.jvm.AsmTypes;
import org.jetbrains.kotlin.resolve.jvm.JvmPrimitiveType;
import org.jetbrains.kotlin.types.expressions.OperatorConventions;
import org.jetbrains.org.objectweb.asm.Type;
import static org.jetbrains.kotlin.builtins.KotlinBuiltIns.*;
import static org.jetbrains.org.objectweb.asm.Opcodes.*;
public class IntrinsicMethods {
public static final String INTRINSICS_CLASS_NAME = "kotlin/jvm/internal/Intrinsics";
private static final FqName KOTLIN_JVM = new FqName("kotlin.jvm");
/* package */ static final FqNameUnsafe RECEIVER_PARAMETER_FQ_NAME = new FqNameUnsafe("T");
private static final IntrinsicMethod UNARY_MINUS = new UnaryMinus();
private static final IntrinsicMethod UNARY_PLUS = new UnaryPlus();
private static final IntrinsicMethod NUMBER_CAST = new NumberCast();
private static final IntrinsicMethod INV = new Inv();
private static final IntrinsicMethod RANGE_TO = new RangeTo();
private static final IntrinsicMethod INC = new Increment(1);
private static final IntrinsicMethod DEC = new Increment(-1);
private static final IntrinsicMethod HASH_CODE = new HashCode();
private static final IntrinsicMethod ARRAY_SIZE = new ArraySize();
private static final Equals EQUALS = new Equals(KtTokens.EQEQ);
private static final IteratorNext ITERATOR_NEXT = new IteratorNext();
private static final ArraySet ARRAY_SET = new ArraySet();
private static final ArrayGet ARRAY_GET = new ArrayGet();
private static final StringPlus STRING_PLUS = new StringPlus();
private static final ToString TO_STRING = new ToString();
private static final Clone CLONE = new Clone();
private static final IntrinsicMethod ARRAY_ITERATOR = new ArrayIterator();
private final IntrinsicsMap intrinsicsMap = new IntrinsicsMap();
public IntrinsicMethods() {
intrinsicsMap.registerIntrinsic(KOTLIN_JVM, RECEIVER_PARAMETER_FQ_NAME, "javaClass", -1, JavaClassProperty.INSTANCE);
intrinsicsMap.registerIntrinsic(KOTLIN_JVM, KotlinBuiltIns.FQ_NAMES.kClass, "java", -1, new KClassJavaProperty());
intrinsicsMap.registerIntrinsic(new FqName("kotlin.jvm.internal.unsafe"), null, "monitorEnter", 1, MonitorInstruction.MONITOR_ENTER);
intrinsicsMap.registerIntrinsic(new FqName("kotlin.jvm.internal.unsafe"), null, "monitorExit", 1, MonitorInstruction.MONITOR_EXIT);
intrinsicsMap.registerIntrinsic(KOTLIN_JVM, KotlinBuiltIns.FQ_NAMES.array, "isArrayOf", 0, new IsArrayOf());
intrinsicsMap.registerIntrinsic(BUILT_INS_PACKAGE_FQ_NAME, null, "arrayOf", 1, new ArrayOf());
ImmutableList<Name> primitiveCastMethods = OperatorConventions.NUMBER_CONVERSIONS.asList();
for (Name method : primitiveCastMethods) {
String methodName = method.asString();
declareIntrinsicFunction(FQ_NAMES.number, methodName, 0, NUMBER_CAST);
for (PrimitiveType type : PrimitiveType.NUMBER_TYPES) {
declareIntrinsicFunction(type.getTypeFqName(), methodName, 0, NUMBER_CAST);
}
}
for (PrimitiveType type : PrimitiveType.NUMBER_TYPES) {
FqName typeFqName = type.getTypeFqName();
declareIntrinsicFunction(typeFqName, "plus", 0, UNARY_PLUS);
declareIntrinsicFunction(typeFqName, "unaryPlus", 0, UNARY_PLUS);
declareIntrinsicFunction(typeFqName, "minus", 0, UNARY_MINUS);
declareIntrinsicFunction(typeFqName, "unaryMinus", 0, UNARY_MINUS);
declareIntrinsicFunction(typeFqName, "inv", 0, INV);
declareIntrinsicFunction(typeFqName, "rangeTo", 1, RANGE_TO);
declareIntrinsicFunction(typeFqName, "inc", 0, INC);
declareIntrinsicFunction(typeFqName, "dec", 0, DEC);
}
for (PrimitiveType type : PrimitiveType.values()) {
FqName typeFqName = type.getTypeFqName();
Type asmPrimitiveType = AsmTypes.valueTypeForPrimitive(type);
if (asmPrimitiveType == Type.FLOAT_TYPE || asmPrimitiveType == Type.DOUBLE_TYPE) {
declareIntrinsicFunction(typeFqName, "equals", 1, new TotalOrderEquals(asmPrimitiveType));
}
else {
declareIntrinsicFunction(typeFqName, "equals", 1, EQUALS);
}
declareIntrinsicFunction(typeFqName, "hashCode", 0, HASH_CODE);
declareIntrinsicFunction(typeFqName, "toString", 0, TO_STRING);
intrinsicsMap.registerIntrinsic(
BUILT_INS_PACKAGE_FQ_NAME, null, StringsKt.decapitalize(type.getArrayTypeName().asString()) + "Of", 1, new ArrayOf()
);
}
declareBinaryOp("plus", IADD);
declareBinaryOp("minus", ISUB);
declareBinaryOp("times", IMUL);
declareBinaryOp("div", IDIV);
declareBinaryOp("mod", IREM);
declareBinaryOp("rem", IREM);
declareBinaryOp("shl", ISHL);
declareBinaryOp("shr", ISHR);
declareBinaryOp("ushr", IUSHR);
declareBinaryOp("and", IAND);
declareBinaryOp("or", IOR);
declareBinaryOp("xor", IXOR);
declareIntrinsicFunction(FQ_NAMES._boolean, "not", 0, new Not());
declareIntrinsicFunction(FQ_NAMES.string, "plus", 1, new Concat());
declareIntrinsicFunction(FQ_NAMES.string, "get", 1, new StringGetChar());
declareIntrinsicFunction(FQ_NAMES.cloneable, "clone", 0, CLONE);
intrinsicsMap.registerIntrinsic(BUILT_INS_PACKAGE_FQ_NAME, KotlinBuiltIns.FQ_NAMES.any, "toString", 0, TO_STRING);
intrinsicsMap.registerIntrinsic(BUILT_INS_PACKAGE_FQ_NAME, KotlinBuiltIns.FQ_NAMES.string, "plus", 1, STRING_PLUS);
intrinsicsMap.registerIntrinsic(BUILT_INS_PACKAGE_FQ_NAME, null, "arrayOfNulls", 1, new NewArray());
for (PrimitiveType type : PrimitiveType.values()) {
declareIntrinsicFunction(type.getTypeFqName(), "compareTo", 1, new CompareTo());
declareIntrinsicFunction(COLLECTIONS_PACKAGE_FQ_NAME.child(Name.identifier(type.getTypeName().asString() + "Iterator")), "next", 0, ITERATOR_NEXT);
}
declareArrayMethods();
}
private void declareArrayMethods() {
for (JvmPrimitiveType jvmPrimitiveType : JvmPrimitiveType.values()) {
declareArrayMethods(jvmPrimitiveType.getPrimitiveType().getArrayTypeFqName());
}
declareArrayMethods(FQ_NAMES.array.toSafe());
}
private void declareArrayMethods(@NotNull FqName arrayTypeFqName) {
declareIntrinsicFunction(arrayTypeFqName, "size", -1, ARRAY_SIZE);
declareIntrinsicFunction(arrayTypeFqName, "set", 2, ARRAY_SET);
declareIntrinsicFunction(arrayTypeFqName, "get", 1, ARRAY_GET);
declareIntrinsicFunction(arrayTypeFqName, "clone", 0, CLONE);
declareIntrinsicFunction(arrayTypeFqName, "iterator", 0, ARRAY_ITERATOR);
declareIntrinsicFunction(arrayTypeFqName, "<init>", 2, ArrayConstructor.INSTANCE);
}
private void declareBinaryOp(@NotNull String methodName, int opcode) {
BinaryOp op = new BinaryOp(opcode);
for (PrimitiveType type : PrimitiveType.values()) {
declareIntrinsicFunction(type.getTypeFqName(), methodName, 1, op);
}
}
private void declareIntrinsicFunction(
@NotNull FqName classFqName,
@NotNull String methodName,
int arity,
@NotNull IntrinsicMethod implementation
) {
intrinsicsMap.registerIntrinsic(classFqName, null, methodName, arity, implementation);
}
private void declareIntrinsicFunction(
@NotNull FqNameUnsafe classFqName,
@NotNull String methodName,
int arity,
@NotNull IntrinsicMethod implementation
) {
intrinsicsMap.registerIntrinsic(classFqName.toSafe(), null, methodName, arity, implementation);
}
@Nullable
public IntrinsicMethod getIntrinsic(@NotNull CallableMemberDescriptor descriptor) {
return intrinsicsMap.getIntrinsic(descriptor);
}
}
|
3e06f24b39c9b6455baf3b806dd783480fc76829 | 2,845 | java | Java | weblab-json-schema/src/main/java/ucles/weblab/common/schema/webapi/MoreFormats.java | cambridgeweblab/api-schema | 267a65b7fc7a1bf3db3adf7d74db6c6357b288d1 | [
"Apache-2.0"
] | 1 | 2020-10-02T09:52:21.000Z | 2020-10-02T09:52:21.000Z | weblab-json-schema/src/main/java/ucles/weblab/common/schema/webapi/MoreFormats.java | cambridgeweblab/api-schema | 267a65b7fc7a1bf3db3adf7d74db6c6357b288d1 | [
"Apache-2.0"
] | 1 | 2018-05-17T09:49:34.000Z | 2020-10-02T10:57:25.000Z | weblab-json-schema/src/main/java/ucles/weblab/common/schema/webapi/MoreFormats.java | cambridgeweblab/api-schema | 267a65b7fc7a1bf3db3adf7d74db6c6357b288d1 | [
"Apache-2.0"
] | null | null | null | 37.434211 | 156 | 0.672759 | 2,943 | package ucles.weblab.common.schema.webapi;
/**
* This class holds constants for custom formats, in addition to the standard formats in
* {@link com.fasterxml.jackson.databind.jsonFormatVisitors.JsonValueFormat}.
*
* @since 22/10/15
*/
public final class MoreFormats {
/**
* Enums to be presented as radio buttons.
*/
public static final String RADIO = "radio";
/**
* This should be an precise decimal value.
*/
public static final String CURRENCY = "currency";
/**
* Data that is naturally presented in a list. In order to do this, an {@link JsonSchema#enumRef() enumRef} will need to be provided too.
*/
public static final String LIST = "list";
/**
* Data that is naturally presented in a text area. This could apply to an array of strings (where each string is on a new line) or a multi-line string.
*/
public static final String TEXTAREA = "textarea";
/**
* A date in ISO 8601 format of YYYY-MM-DDThh:mm:ss (no timezone). This is the recommended form of date/timestamp.
*/
public static final String LOCAL_DATE_TIME = "local-date-time";
/**
* A date in ISO 8601 format of YYYY-MM-DDThh:mm:ss (no timezone).
*/
public static final String BIRTH_DATE_TIME = "birth-date";
/**
* A duration in ISO 8601 format of P[nY][nM][nD]T[nH][nM][nS]
*/
public static final String DURATION = "duration";
/**
* An ISO 3166-1 alpha-2 country code. A UI would probably present this as a list of known countries.
*/
public static final String COUNTRY = "country";
/**
* Data that is naturally tabular. A UI would probably present give the user the opportunity to upload this as CSV as well as entering it interactively.
* This would only really apply to an array of object types.
*/
public static final String TABLE = "table";
/**
* An e-mail address which requires double-entry validation to be sure it's correct.
*/
public static final String CONFIRMED_EMAIL = "confirm-email";
/**
* The current view context of the UI. This is filled by the UI with some information to identify the currently displayed view.
*/
public static final String CURRENT_VIEW_CONTEXT = "current-view-context";
/**
* Data that represents a rating of some sort. A UI may decide to present this e.g. as a star graphic.
* Additional constraints on the minimum and maximum values should be present otherwise a UI will have to make assumptions.
*/
public static final String RATING = "rating";
/**
* A universally unique identifier. This would not normally be entered but instead generated if a new one is required.
*/
public static final String UUID = "uuid";
private MoreFormats() {
// prevent instantiation
}
}
|
3e06f2ef6a07131f3c12245fc94f0bf65dc11f0e | 8,365 | java | Java | store-implementation/federated-store/src/test/java/uk/gov/gchq/gaffer/federatedstore/operation/FederatedOperationChainTest.java | r001zse/Gaffer | 6abb5e8e3e96fb04add505beb2ad3ae5ae469f1c | [
"Apache-2.0"
] | null | null | null | store-implementation/federated-store/src/test/java/uk/gov/gchq/gaffer/federatedstore/operation/FederatedOperationChainTest.java | r001zse/Gaffer | 6abb5e8e3e96fb04add505beb2ad3ae5ae469f1c | [
"Apache-2.0"
] | 10 | 2019-08-15T11:07:32.000Z | 2019-08-27T11:59:06.000Z | store-implementation/federated-store/src/test/java/uk/gov/gchq/gaffer/federatedstore/operation/FederatedOperationChainTest.java | r001zse/Gaffer | 6abb5e8e3e96fb04add505beb2ad3ae5ae469f1c | [
"Apache-2.0"
] | 1 | 2019-10-23T07:45:58.000Z | 2019-10-23T07:45:58.000Z | 38.906977 | 113 | 0.573939 | 2,944 | /*
* Copyright 2017-2019 Crown Copyright
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.gov.gchq.gaffer.federatedstore.operation;
import com.google.common.collect.Sets;
import org.junit.Test;
import uk.gov.gchq.gaffer.commonutil.JsonAssert;
import uk.gov.gchq.gaffer.commonutil.StringUtil;
import uk.gov.gchq.gaffer.commonutil.iterable.CloseableIterable;
import uk.gov.gchq.gaffer.data.element.Element;
import uk.gov.gchq.gaffer.operation.OperationChain;
import uk.gov.gchq.gaffer.operation.OperationTest;
import uk.gov.gchq.gaffer.operation.impl.get.GetAllElements;
import java.util.Set;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class FederatedOperationChainTest extends OperationTest<FederatedOperationChain> {
@Override
public void builderShouldCreatePopulatedOperation() {
// Given
final OperationChain<CloseableIterable<? extends Element>> opChain = new OperationChain.Builder()
.first(new GetAllElements())
.build();
// When
final FederatedOperationChain op = new FederatedOperationChain.Builder<>()
.operationChain(opChain)
.option("key", "value")
.build();
// Then
assertEquals(opChain, op.getOperationChain());
assertEquals("value", op.getOption("key"));
}
@Test
@Override
public void shouldShallowCloneOperation() {
// Given
final OperationChain<CloseableIterable<? extends Element>> opChain = new OperationChain.Builder()
.first(new GetAllElements())
.build();
final FederatedOperationChain op = new FederatedOperationChain.Builder<>()
.operationChain(opChain)
.option("key", "value")
.build();
// When
final FederatedOperationChain clone = op.shallowClone();
// Then
assertNotSame(op.getOperationChain(), clone.getOperationChain());
assertEquals(1, clone.getOperationChain().getOperations().size());
assertEquals(GetAllElements.class, clone.getOperationChain().getOperations().get(0).getClass());
assertEquals("value", clone.getOption("key"));
}
@Override
public void shouldJsonSerialiseAndDeserialise() {
// Given
final OperationChain<CloseableIterable<? extends Element>> opChain = new OperationChain.Builder()
.first(new GetAllElements())
.build();
final FederatedOperationChain op = new FederatedOperationChain.Builder<>()
.operationChain(opChain)
.option("key", "value")
.build();
// When
final byte[] json = toJson(op);
final FederatedOperationChain deserialisedOp = fromJson(json);
// Then
JsonAssert.assertEquals(StringUtil.toBytes(String.format("{%n" +
" \"class\" : \"uk.gov.gchq.gaffer.federatedstore.operation.FederatedOperationChain\",%n" +
" \"operationChain\" : {%n" +
" \"operations\" : [ {%n" +
" \"class\" : \"uk.gov.gchq.gaffer.operation.impl.get.GetAllElements\"%n" +
" } ]%n" +
" },%n" +
" \"options\" : {%n" +
" \"key\" : \"value\"%n" +
" }%n" +
"}")), json);
assertEquals(1, deserialisedOp.getOperationChain().getOperations().size());
assertEquals(GetAllElements.class, deserialisedOp.getOperationChain().getOperations().get(0).getClass());
assertEquals("value", deserialisedOp.getOption("key"));
}
@Test
public void shouldThrowAnErrorIfJsonDeserialiseWithoutOperationChain() {
// Given
final String json = String.format("{%n" +
" \"class\" : \"uk.gov.gchq.gaffer.federatedstore.operation.FederatedOperationChain\",%n" +
" \"options\" : {%n" +
" \"key\" : \"value\"%n" +
" }%n" +
"}");
// When / Then
try {
fromJson(StringUtil.toBytes(json));
fail("Exception expected");
} catch (final RuntimeException e) {
assertTrue(e.getMessage().contains("operationChain is required"));
}
}
@Test
public void shouldJsonDeserialiseWithInvalidOperationChainClassName() {
// Given
final String json = String.format("{%n" +
" \"class\" : \"uk.gov.gchq.gaffer.federatedstore.operation.FederatedOperationChain\",%n" +
" \"operationChain\" : {%n" +
" \"class\" : \"uk.gov.gchq.gaffer.operation.OperationChainInvalidClassName\",%n" +
" \"operations\" : [ {%n" +
" \"class\" : \"uk.gov.gchq.gaffer.operation.impl.get.GetAllElements\"%n" +
" } ]%n" +
" },%n" +
" \"options\" : {%n" +
" \"key\" : \"value\"%n" +
" }%n" +
"}");
// When / Then
try {
fromJson(StringUtil.toBytes(json));
fail("Exception expected");
} catch (final RuntimeException e) {
assertTrue(e.getMessage().contains("Class name should be"));
}
}
@Test
public void shouldJsonDeserialiseWithOperationChainClassName() {
// Given
final String json = String.format("{%n" +
" \"class\" : \"uk.gov.gchq.gaffer.federatedstore.operation.FederatedOperationChain\",%n" +
" \"operationChain\" : {%n" +
" \"class\" : \"uk.gov.gchq.gaffer.operation.OperationChain\",%n" +
" \"operations\" : [ {%n" +
" \"class\" : \"uk.gov.gchq.gaffer.operation.impl.get.GetAllElements\"%n" +
" } ]%n" +
" },%n" +
" \"options\" : {%n" +
" \"key\" : \"value\"%n" +
" }%n" +
"}");
// When
final FederatedOperationChain deserialisedOp = fromJson(StringUtil.toBytes(json));
// Then
assertEquals(1, deserialisedOp.getOperationChain().getOperations().size());
assertEquals(GetAllElements.class, deserialisedOp.getOperationChain().getOperations().get(0).getClass());
assertEquals("value", deserialisedOp.getOption("key"));
}
@Test
public void shouldJsonDeserialiseWithoutOperationChainClassName() {
// Given
final String json = String.format("{%n" +
" \"class\" : \"uk.gov.gchq.gaffer.federatedstore.operation.FederatedOperationChain\",%n" +
" \"operationChain\" : {%n" +
" \"operations\" : [ {%n" +
" \"class\" : \"uk.gov.gchq.gaffer.operation.impl.get.GetAllElements\"%n" +
" } ]%n" +
" },%n" +
" \"options\" : {%n" +
" \"key\" : \"value\"%n" +
" }%n" +
"}");
// When
final FederatedOperationChain deserialisedOp = fromJson(StringUtil.toBytes(json));
// Then
assertEquals(1, deserialisedOp.getOperationChain().getOperations().size());
assertEquals(GetAllElements.class, deserialisedOp.getOperationChain().getOperations().get(0).getClass());
assertEquals("value", deserialisedOp.getOption("key"));
}
@Override
protected Set<String> getRequiredFields() {
return Sets.newHashSet("operationChain");
}
@Override
protected FederatedOperationChain getTestObject() {
return new FederatedOperationChain();
}
}
|
3e06f300917f588636660183d42e9505ee625282 | 4,344 | java | Java | src/main/java/com/rc/KohonenDataProcessor.java | rcorbish/DataSense | 6a1b5e99ba27f2f051aeab2f0732c11ee22f27ae | [
"Unlicense"
] | null | null | null | src/main/java/com/rc/KohonenDataProcessor.java | rcorbish/DataSense | 6a1b5e99ba27f2f051aeab2f0732c11ee22f27ae | [
"Unlicense"
] | null | null | null | src/main/java/com/rc/KohonenDataProcessor.java | rcorbish/DataSense | 6a1b5e99ba27f2f051aeab2f0732c11ee22f27ae | [
"Unlicense"
] | null | null | null | 29.958621 | 88 | 0.646179 | 2,945 | package com.rc;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class KohonenDataProcessor extends DataProcessor {
final static Logger log = LoggerFactory.getLogger( KohonenDataProcessor.class ) ;
public Dataset load( InputStream data, ProcessorOptions options ) throws IOException {
Dataset dataset = Loader.load( DataProcessor.ROWS_TO_KEEP, data, options ) ;
if( options.square ) {
dataset.square( options.keepOriginal );
}
if( options.log ) {
dataset.log( options.keepOriginal );
}
if( options.reciprocal ) {
dataset.reciprocal( options.keepOriginal );
}
if( options.normalize ) {
dataset.normalize();
}
return dataset ;
}
public Object process( Dataset dataset ) {
Matrix A = dataset.train ;
Matrix T = dataset.test ;
int feature = dataset.getFeatureColumnIndex() ;
Matrix F = A.extractColumns( feature ) ;
Matrix YR = T.extractColumns( feature ) ;
Matrix uniqueValues = F.getUniqueValues( 0.1 ) ;
F.map( e -> uniqueValues.indexOf(e, 0.1) ) ;
int numInputs = A.N ;
int numFeatures = uniqueValues.length() ;
final int TARGET_SPACE_SIZE = (int)Math.ceil( Math.sqrt( numFeatures * 2 ) ) ;
log.info( "Using {} x {} feature space", TARGET_SPACE_SIZE, TARGET_SPACE_SIZE ) ;
Matrix targetSpace[] = new Matrix[ TARGET_SPACE_SIZE * TARGET_SPACE_SIZE ] ;
for( int i=0 ; i<targetSpace.length ; i++ ) {
targetSpace[i] = Matrix.rand( numInputs, 1 ) ;
}
double learningRate = 1.0 ;
final int ITERATIONS = 100 ;
double MAP_RADIUS = TARGET_SPACE_SIZE / 1.25 ;
double RADIUS_LAMBDA = ITERATIONS / Math.log( MAP_RADIUS ) ;
for( int iteration=0 ; iteration<ITERATIONS ; iteration++ ) {
double radius = MAP_RADIUS * Math.exp( -iteration/RADIUS_LAMBDA ) ;
log.debug( "Iteration {} - radius = {}", iteration, radius ) ;
Matrix shuffle = Matrix.shuffle( A.M ) ;
for( int m=0 ; m<A.M ; m++ ) {
int ix = (int)shuffle.get(m) ;
Matrix observation = A.copyRows(ix) ;
int closestIndex = findClosestIndex(observation, targetSpace ) ;
// Now move all vectors towards the answer
// depending on how near they are to the 'closest'
// Matrix closest = targetSpace[ closestIndex ] ;
int x0 = closestIndex % TARGET_SPACE_SIZE ;
int y0 = closestIndex / TARGET_SPACE_SIZE ;
for( int i=0 ; i<targetSpace.length ; i++ ) {
// calc distance between closest & each vector in the target
int x1 = i % TARGET_SPACE_SIZE ;
int y1 = i / TARGET_SPACE_SIZE ;
double proximity = Math.sqrt( (x0-x1)*(x0-x1) + (y0-y1)*(y0-y1) ) ;
if( proximity <= radius ) {
double theta = Math.exp( -(proximity*proximity) / ( 2 * radius ) ) ;
double rate = learningRate * theta ;
Matrix delta = observation.sub( targetSpace[i] ).mul( rate ) ;
// log.debug( "Moving\n{} by\n{} due to\n{}",targetSpace[i], delta, observation ) ;
targetSpace[i].addi( delta ) ;
}
}
}
log.debug( "Iteration {} complete", iteration ) ;
}
log.info( "Iterations complete" ) ;
// value in dataset -> zero based index
Map<Integer,Integer> featureKeys = new HashMap<>() ;
for( int m=0 ; m<A.M ; m++ ) {
Matrix observation = A.copyRows(m) ;
int closestIndex = findClosestIndex(observation, targetSpace ) ;
featureKeys.put( closestIndex, (int)F.get(m) ) ;
log.info( "{} : {} -> {}", m, F.get(m), targetSpace[closestIndex] ) ;
}
log.info( "Feature keys in target: {}", featureKeys ) ;
Matrix Y = new Matrix( YR.M ) ;
for( int m=0 ; m<T.M ; m++ ) {
Matrix observation = T.copyRows(m) ;
int closestIndex = findClosestIndex( observation, targetSpace ) ;
log.debug( "Mapping {} using {}", closestIndex, featureKeys ) ;
Y.put( m, closestIndex ) ;
}
Map<Integer,Integer> inverseFeatureKeys = new HashMap<>() ;
return score( YR, Y, inverseFeatureKeys ) ;
}
protected int findClosestIndex( Matrix v, Matrix w[] ) {
double closestDistance = v.sub( w[0] ).norm() ;
int closestIndex = 0 ;
for( int i=1 ; i<w.length ; i++ ) {
double distance = v.sub( w[i] ).norm() ;
if( distance < closestDistance ) {
closestIndex = i ;
closestDistance = distance ;
}
}
return closestIndex ;
}
}
|
3e06f3b3e3a8a6366354dd81aefa5cbc9454eadd | 2,008 | java | Java | src/test/java/dev/carrico/daotests/ExpenseDaoTests.java | Lcarrico/ExpenseAPI | 02905f80f7addefc634462b3083d65c79674a2a9 | [
"Apache-2.0"
] | null | null | null | src/test/java/dev/carrico/daotests/ExpenseDaoTests.java | Lcarrico/ExpenseAPI | 02905f80f7addefc634462b3083d65c79674a2a9 | [
"Apache-2.0"
] | null | null | null | src/test/java/dev/carrico/daotests/ExpenseDaoTests.java | Lcarrico/ExpenseAPI | 02905f80f7addefc634462b3083d65c79674a2a9 | [
"Apache-2.0"
] | null | null | null | 29.529412 | 91 | 0.707669 | 2,946 | package dev.carrico.daotests;
import dev.carrico.daos.ExpenseDAO;
import dev.carrico.daos.ExpenseDaoPostgres;
import dev.carrico.entities.Expense;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import java.util.Set;
@MockitoSettings(strictness = Strictness.LENIENT)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@ExtendWith(MockitoExtension.class)
public class ExpenseDaoTests {
// @Mock
private ExpenseDAO expenseDAO = new ExpenseDaoPostgres();
private static Expense testExpense = null;
@Order(1)
@Test
void create_expense(){
this.testExpense = this.expenseDAO.createExpense(new Expense(0, 100, "refund", 1));
System.out.println(this.testExpense);
Assertions.assertNotNull(this.testExpense);
Assertions.assertNotEquals(0, this.testExpense.getExpenseId());
}
@Order(2)
@Test
void get_expense_by_id(){
Expense e = this.expenseDAO.getExpenseById(this.testExpense.getExpenseId());
Assertions.assertNotNull(e);
Assertions.assertEquals(e.getExpenseId(), this.testExpense.getExpenseId());
Assertions.assertEquals(e.getAmount(), this.testExpense.getAmount());
}
@Order(3)
@Test
void get_all_expenses(){
Set<Expense> expenses = this.expenseDAO.getAllExpenses();
Assertions.assertTrue(expenses.size() >= 1);
}
@Order(4)
@Test
void update_expense(){
this.testExpense.setAmount(150);
Expense e = this.expenseDAO.updateExpense(this.testExpense);
Assertions.assertEquals(this.testExpense.getAmount(), e.getAmount());
}
@Order(5)
@Test
void delete_expense(){
int testId = this.testExpense.getExpenseId();
boolean result = this.expenseDAO.deleteExpenseById(testId);
Assertions.assertTrue(result);
}
}
|
3e06f40f95c0444c6de39aaff638928d3cb66b9e | 754 | java | Java | a8/a8/a8.fsa1a/src/main/java/d/ls/core/utl/fsa/aset/AutomatonSet1.java | dwisianto/dk.brics.automaton | 9da6305646096fd7cf61561cc96e6077334de9d6 | [
"BSD-3-Clause"
] | null | null | null | a8/a8/a8.fsa1a/src/main/java/d/ls/core/utl/fsa/aset/AutomatonSet1.java | dwisianto/dk.brics.automaton | 9da6305646096fd7cf61561cc96e6077334de9d6 | [
"BSD-3-Clause"
] | null | null | null | a8/a8/a8.fsa1a/src/main/java/d/ls/core/utl/fsa/aset/AutomatonSet1.java | dwisianto/dk.brics.automaton | 9da6305646096fd7cf61561cc96e6077334de9d6 | [
"BSD-3-Clause"
] | 1 | 2019-12-15T03:35:08.000Z | 2019-12-15T03:35:08.000Z | 22.176471 | 94 | 0.755968 | 2,947 | package d.ls.core.utl.fsa.aset;
import dk.brics.automaton.Automaton;
import dk.brics.automaton.BasicAutomata;
import dk.brics.automaton.BasicOperations;
public class AutomatonSet1 {
private Automaton mergedAutomaton;
public AutomatonSet1() {
}
public void add(String newTerm) {
newTerm = newTerm.toUpperCase();
if (mergedAutomaton == null) {
mergedAutomaton = BasicAutomata.makeString(newTerm);
} else {
mergedAutomaton = BasicOperations.union(mergedAutomaton,BasicAutomata.makeString(newTerm));
}
mergedAutomaton = Automaton.minimize(mergedAutomaton);
}
public int numNodes() {
return mergedAutomaton.getNumberOfStates();
}
public int numTransitions() {
return mergedAutomaton.getNumberOfTransitions();
}
}
|
3e06f4250af6263cfa8a865945b44cfc7edabe5a | 1,283 | java | Java | hbase-client/src/main/java/org/apache/hadoop/hbase/MultiActionResultTooLarge.java | unozawah/hbase | 00075ea4fc0ca13a763a1acf8bcb52b7f168018a | [
"Apache-2.0"
] | 4,857 | 2015-01-02T11:45:14.000Z | 2022-03-31T14:00:55.000Z | hbase-client/src/main/java/org/apache/hadoop/hbase/MultiActionResultTooLarge.java | unozawah/hbase | 00075ea4fc0ca13a763a1acf8bcb52b7f168018a | [
"Apache-2.0"
] | 4,070 | 2015-05-01T02:52:57.000Z | 2022-03-31T23:54:50.000Z | hbase-client/src/main/java/org/apache/hadoop/hbase/MultiActionResultTooLarge.java | unozawah/hbase | 00075ea4fc0ca13a763a1acf8bcb52b7f168018a | [
"Apache-2.0"
] | 3,611 | 2015-01-02T11:33:55.000Z | 2022-03-31T11:12:19.000Z | 37.735294 | 87 | 0.765394 | 2,948 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.hbase;
import org.apache.yetus.audience.InterfaceAudience;
/**
* Exception thrown when the result needs to be chunked on the server side.
* It signals that retries should happen right away and not count against the number of
* retries because some of the multi was a success.
*/
@InterfaceAudience.Public
public class MultiActionResultTooLarge extends RetryImmediatelyException {
public MultiActionResultTooLarge(String s) {
super(s);
}
}
|
3e06f61f95406b99964c44b87a80ab77973e0831 | 786 | java | Java | member/src/main/java/com/freedy/mall/member/entity/GrowthChangeHistoryEntity.java | Freedy001/gulimall | 3e2b3881f2f605be7f159d56b9554ccd72aef336 | [
"Apache-2.0"
] | 2 | 2021-07-10T16:20:54.000Z | 2021-07-20T02:01:42.000Z | member/src/main/java/com/freedy/mall/member/entity/GrowthChangeHistoryEntity.java | Freedy001/gulimall | 3e2b3881f2f605be7f159d56b9554ccd72aef336 | [
"Apache-2.0"
] | null | null | null | member/src/main/java/com/freedy/mall/member/entity/GrowthChangeHistoryEntity.java | Freedy001/gulimall | 3e2b3881f2f605be7f159d56b9554ccd72aef336 | [
"Apache-2.0"
] | null | null | null | 16.020408 | 64 | 0.696815 | 2,949 | package com.freedy.mall.member.entity;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
/**
* 成长值变化历史记录
*
* @author freedy
* @email upchh@example.com
* @date 2021-01-30 21:32:06
*/
@Data
@TableName("ums_growth_change_history")
public class GrowthChangeHistoryEntity implements Serializable {
private static final long serialVersionUID = 1L;
/**
* id
*/
@TableId
private Long id;
/**
* member_id
*/
private Long memberId;
/**
* create_time
*/
private Date createTime;
/**
* 改变的值(正负计数)
*/
private Integer changeCount;
/**
* 备注
*/
private String note;
/**
* 积分来源[0-购物,1-管理员修改]
*/
private Integer sourceType;
}
|
3e06f6253f9d2e22c217387fc3662ff7963032f6 | 282 | java | Java | src/main/java/dev/vality/magista/dao/InvoiceDao.java | valitydev/magista | 3cafc8678603a9ebd6c6748fa1030a9d1b2b38d9 | [
"Apache-2.0"
] | null | null | null | src/main/java/dev/vality/magista/dao/InvoiceDao.java | valitydev/magista | 3cafc8678603a9ebd6c6748fa1030a9d1b2b38d9 | [
"Apache-2.0"
] | 9 | 2022-02-23T14:57:13.000Z | 2022-03-30T01:50:11.000Z | src/main/java/dev/vality/magista/dao/InvoiceDao.java | valitydev/magista | 3cafc8678603a9ebd6c6748fa1030a9d1b2b38d9 | [
"Apache-2.0"
] | null | null | null | 17.625 | 58 | 0.758865 | 2,950 | package dev.vality.magista.dao;
import dev.vality.magista.domain.tables.pojos.InvoiceData;
import java.util.List;
public interface InvoiceDao {
InvoiceData get(String invoiceId);
void insert(List<InvoiceData> invoices);
void update(List<InvoiceData> invoices);
}
|
3e06f667c2eb5996f23d3db22aaf256e86b627aa | 769 | java | Java | src/main/java/com/mikeio/RemembermeApplication.java | msoli/-rememberme | 4d2d664ae17ab9221879241e93a2f28335357d6f | [
"Apache-2.0"
] | null | null | null | src/main/java/com/mikeio/RemembermeApplication.java | msoli/-rememberme | 4d2d664ae17ab9221879241e93a2f28335357d6f | [
"Apache-2.0"
] | null | null | null | src/main/java/com/mikeio/RemembermeApplication.java | msoli/-rememberme | 4d2d664ae17ab9221879241e93a2f28335357d6f | [
"Apache-2.0"
] | null | null | null | 30.76 | 84 | 0.823147 | 2,951 | package com.mikeio;
import com.mikeio.config.MikeIoProperties;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
public class RemembermeApplication extends SpringBootServletInitializer {
/**
* Used when run as WAR
*/
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
return builder.sources(JhipsterSampleApplicationNg2App.class);
}
}
|
3e06f7a577adb89925482f335f8d29cab352f600 | 487 | java | Java | samples/word/build/src/office/MsoButtonState.java | nosdod/CDWriterJava | 7146689889d8d50d7162b21ea0b98fc5c2364306 | [
"BSD-2-Clause"
] | null | null | null | samples/word/build/src/office/MsoButtonState.java | nosdod/CDWriterJava | 7146689889d8d50d7162b21ea0b98fc5c2364306 | [
"BSD-2-Clause"
] | null | null | null | samples/word/build/src/office/MsoButtonState.java | nosdod/CDWriterJava | 7146689889d8d50d7162b21ea0b98fc5c2364306 | [
"BSD-2-Clause"
] | null | null | null | 15.21875 | 49 | 0.564682 | 2,952 | package office ;
import com4j.*;
/**
*/
public enum MsoButtonState implements ComEnum {
/**
* <p>
* The value of this constant is 0
* </p>
*/
msoButtonUp(0),
/**
* <p>
* The value of this constant is -1
* </p>
*/
msoButtonDown(-1),
/**
* <p>
* The value of this constant is 2
* </p>
*/
msoButtonMixed(2),
;
private final int value;
MsoButtonState(int value) { this.value=value; }
public int comEnumValue() { return value; }
}
|
3e06f9270824a4d8807557a8a979e0a50ddf7e0c | 1,203 | java | Java | src/main/java/cn/edu/sdjzu/xg/bysj/service/ApplicationForSupervisorService.java | JillFishing/bysjByGradle | 89e89bf0dd2e845a88ea7e4ff593e5e01151982a | [
"Apache-2.0"
] | null | null | null | src/main/java/cn/edu/sdjzu/xg/bysj/service/ApplicationForSupervisorService.java | JillFishing/bysjByGradle | 89e89bf0dd2e845a88ea7e4ff593e5e01151982a | [
"Apache-2.0"
] | null | null | null | src/main/java/cn/edu/sdjzu/xg/bysj/service/ApplicationForSupervisorService.java | JillFishing/bysjByGradle | 89e89bf0dd2e845a88ea7e4ff593e5e01151982a | [
"Apache-2.0"
] | null | null | null | 41.482759 | 122 | 0.790524 | 2,953 | package cn.edu.sdjzu.xg.bysj.service;
//201902104050 姜瑞临
import cn.edu.sdjzu.xg.bysj.dao.ApplicationForSupervisorDao;
import cn.edu.sdjzu.xg.bysj.domain.ApplicationForSupervisorEntry;
import cn.edu.sdjzu.xg.bysj.domain.Student;
import util.JdbcHelper;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;
public class ApplicationForSupervisorService {
private static ApplicationForSupervisorDao applicationForSupervisorDao = ApplicationForSupervisorDao.getInstance();
private static ApplicationForSupervisorService applicationForSupervisorService =new ApplicationForSupervisorService();
private ApplicationForSupervisorService(){}
public static ApplicationForSupervisorService getInstance(){
return applicationForSupervisorService;
}
public boolean add(List<ApplicationForSupervisorEntry> applicationForSupervisorEntries,
String selfIntro, Student student) throws SQLException {
Connection conn = JdbcHelper.getConn();
boolean add = applicationForSupervisorDao.add(applicationForSupervisorEntries,selfIntro,student,conn);
conn.close();
return add;
}
}
|
3e06f9d5e9f294bf0415ad0745b4727446c74891 | 256 | java | Java | clivia-user/src/main/java/org/lpw/clivia/user/stat/StatDao.java | heisedebaise/clivia | 34f0f010fc595c38ec85b7f2b6ec5ae2f1a5ef29 | [
"MIT"
] | null | null | null | clivia-user/src/main/java/org/lpw/clivia/user/stat/StatDao.java | heisedebaise/clivia | 34f0f010fc595c38ec85b7f2b6ec5ae2f1a5ef29 | [
"MIT"
] | 12 | 2020-07-10T01:10:34.000Z | 2022-03-29T08:20:43.000Z | clivia-user/src/main/java/org/lpw/clivia/user/stat/StatDao.java | heisedebaise/clivia | 34f0f010fc595c38ec85b7f2b6ec5ae2f1a5ef29 | [
"MIT"
] | null | null | null | 18.285714 | 70 | 0.730469 | 2,954 | package org.lpw.clivia.user.stat;
import org.lpw.photon.dao.orm.PageList;
import java.sql.Date;
interface StatDao {
PageList<StatModel> query(String date, int pageSize, int pageNum);
StatModel find(Date date);
void save(StatModel stat);
}
|
3e06fa12445690edda8089883ea25faa84d475bc | 2,081 | java | Java | src/test/java/org/antvillage/cards/SimpleCardTest.java | joostvunderink/ant-village | 4c5176abc93687516b962cf9e5a97b2b172d3029 | [
"Apache-2.0"
] | null | null | null | src/test/java/org/antvillage/cards/SimpleCardTest.java | joostvunderink/ant-village | 4c5176abc93687516b962cf9e5a97b2b172d3029 | [
"Apache-2.0"
] | null | null | null | src/test/java/org/antvillage/cards/SimpleCardTest.java | joostvunderink/ant-village | 4c5176abc93687516b962cf9e5a97b2b172d3029 | [
"Apache-2.0"
] | null | null | null | 23.382022 | 60 | 0.62518 | 2,955 | package org.antvillage.cards;
import static org.junit.Assert.assertEquals;
import org.antvillage.cards.base.FestivalCard;
import org.antvillage.cards.base.LaboratoryCard;
import org.antvillage.cards.base.MarketCard;
import org.antvillage.cards.base.SmithyCard;
import org.antvillage.cards.base.VillageCard;
import org.antvillage.cards.base.WoodcutterCard;
import org.antvillage.cards.intrigue.GreatHallCard;
import org.antvillage.cards.intrigue.HaremCard;
import org.antvillage.cards.seaside.BazaarCard;
import org.junit.Test;
public class SimpleCardTest {
private Object[][] tests = {
/*
class,
vp, cost, money, buys, draws, actions
is_action, is_treasure, is_victory
*/
{
new BazaarCard(),
0, 5, 1, 0, 1, 2,
true, false, false
},
{
new FestivalCard(),
0, 5, 2, 1, 0, 2,
true, false, false
},
{
new GreatHallCard(),
1, 3, 0, 0, 1, 1,
true, false, true
},
{
new HaremCard(),
2, 6, 2, 0, 0, 0,
false, true, true
},
{
new LaboratoryCard(),
0, 5, 0, 0, 2, 1,
true, false, false
},
{
new MarketCard(),
0, 5, 1, 1, 1, 1,
true, false, false
},
{
new SmithyCard(),
0, 4, 0, 0, 3, 0,
true, false, false
},
{
new VillageCard(),
0, 3, 0, 0, 1, 2,
true, false, false
},
{
new WoodcutterCard(),
0, 3, 2, 1, 0, 0,
true, false, false
},
};
@Test
public void testAll() {
for (int i = 0; i < tests.length; i++) {
Object[] testparams = tests[i];
Card card = (Card)testparams[0];
assertEquals(card.getVictoryPoints(), testparams[1]);
assertEquals(card.getCost(null), testparams[2]);
assertEquals(card.getMoneyValue(null), testparams[3]);
assertEquals(card.getExtraBuys(), testparams[4]);
assertEquals(card.getExtraDraws(), testparams[5]);
assertEquals(card.getExtraActions(), testparams[6]);
assertEquals(card.isAction(), testparams[7]);
assertEquals(card.isTreasure(), testparams[8]);
assertEquals(card.isVictory(), testparams[9]);
}
}
}
|
3e06fb606f58a9cc4d421913c5f810db34145bc1 | 585 | java | Java | src/main/java/de/unistuttgart/ims/coref/annotator/plugins/AbstractExportPlugin.java | bkis/CorefAnnotator | 088d6a9458b51e1782b01a5f0c8248bab170efdb | [
"Apache-2.0"
] | 20 | 2018-03-28T03:48:16.000Z | 2022-02-15T08:11:24.000Z | src/main/java/de/unistuttgart/ims/coref/annotator/plugins/AbstractExportPlugin.java | bkis/CorefAnnotator | 088d6a9458b51e1782b01a5f0c8248bab170efdb | [
"Apache-2.0"
] | 333 | 2018-02-07T14:19:18.000Z | 2022-02-17T12:12:31.000Z | src/main/java/de/unistuttgart/ims/coref/annotator/plugins/AbstractExportPlugin.java | bkis/CorefAnnotator | 088d6a9458b51e1782b01a5f0c8248bab170efdb | [
"Apache-2.0"
] | 6 | 2019-03-15T23:27:23.000Z | 2021-09-19T10:28:57.000Z | 20.172414 | 68 | 0.793162 | 2,956 | package de.unistuttgart.ims.coref.annotator.plugins;
import java.io.File;
import java.util.function.Consumer;
import org.kordamp.ikonli.Ikon;
import org.kordamp.ikonli.materialdesign.MaterialDesign;
import de.unistuttgart.ims.coref.annotator.Constants;
public abstract class AbstractExportPlugin implements ExportPlugin {
@Override
public String[] getSupportedLanguages() {
return Constants.SUPPORTED_LANGUAGES;
}
@Override
public Ikon getIkon() {
return MaterialDesign.MDI_FILE_EXPORT;
}
@Override
public Consumer<File> getPostExportAction() {
return null;
}
}
|
3e06fb86f179f62118c2d9b974e8bbe7d0bafa9b | 10,047 | java | Java | src/main/java/co/nyzo/verifier/client/commands/CycleTransactionListCommand.java | daveybrown/nyzoVerifier | e38fb81c1c20555ddceb35cb74b4bc91b5f28d15 | [
"Unlicense"
] | null | null | null | src/main/java/co/nyzo/verifier/client/commands/CycleTransactionListCommand.java | daveybrown/nyzoVerifier | e38fb81c1c20555ddceb35cb74b4bc91b5f28d15 | [
"Unlicense"
] | null | null | null | src/main/java/co/nyzo/verifier/client/commands/CycleTransactionListCommand.java | daveybrown/nyzoVerifier | e38fb81c1c20555ddceb35cb74b4bc91b5f28d15 | [
"Unlicense"
] | null | null | null | 44.653333 | 119 | 0.602568 | 2,957 | package co.nyzo.verifier.client.commands;
import co.nyzo.verifier.*;
import co.nyzo.verifier.client.*;
import co.nyzo.verifier.messages.CycleTransactionSignature;
import co.nyzo.verifier.messages.TransactionListResponse;
import co.nyzo.verifier.nyzoString.*;
import co.nyzo.verifier.util.IpUtil;
import co.nyzo.verifier.util.PrintUtil;
import co.nyzo.verifier.util.ThreadUtil;
import java.nio.ByteBuffer;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
public class CycleTransactionListCommand implements Command {
@Override
public String getShortCommand() {
return "CTL";
}
@Override
public String getLongCommand() {
return "cycleList";
}
@Override
public String getDescription() {
return "list cycle transactions";
}
@Override
public String[] getArgumentNames() {
return new String[] { "in-cycle verifier key (leave empty to list locally stored transactions)" };
}
@Override
public String[] getArgumentIdentifiers() {
return new String[] { "verifierKey" };
}
@Override
public boolean requiresValidation() {
return true;
}
@Override
public boolean requiresConfirmation() {
return false;
}
@Override
public boolean isLongRunning() {
return true;
}
@Override
public ValidationResult validate(List<String> argumentValues, CommandOutput output) {
ValidationResult result = null;
try {
// Make a list for the argument result items.
List<ArgumentResult> argumentResults = new ArrayList<>();
// Check the verifier key.
NyzoString verifierKey = NyzoStringEncoder.decode(argumentValues.get(0));
if (verifierKey instanceof NyzoStringPrivateSeed) {
argumentResults.add(new ArgumentResult(true, NyzoStringEncoder.encode(verifierKey)));
} else if (argumentValues.get(0).trim().isEmpty()) {
argumentResults.add(new ArgumentResult(true, ""));
} else {
String message = "not a valid Nyzo string private key";
argumentResults.add(new ArgumentResult(false, argumentValues.get(0), message));
if (argumentValues.get(0).length() >= 64) {
PrivateNyzoStringCommand.printHexWarning(output);
}
}
// Produce the result.
result = new ValidationResult(argumentResults);
} catch (Exception ignored) { }
// If the confirmation result is null, create an exception result. This will only happen if an exception is not
// handled properly by the validation code.
if (result == null) {
result = ValidationResult.exceptionResult(getArgumentNames().length);
}
return result;
}
@Override
public ExecutionResult run(List<String> argumentValues, CommandOutput output) {
try {
// If a key was provided, query the corresponding verifier.
if (!argumentValues.get(0).isEmpty()) {
NyzoStringPrivateSeed verifierKey =
(NyzoStringPrivateSeed) NyzoStringEncoder.decode(argumentValues.get(0));
byte[] identifier = KeyUtil.identifierForSeed(verifierKey.getSeed());
// Print a warning if the verifier does not appear to be in the cycle.
if (!BlockManager.verifierInCurrentCycle(ByteBuffer.wrap(identifier))) {
output.println(ConsoleColor.Yellow.background() + "warning: the verifier you specified does " +
"not appear to be in the cycle" + ConsoleColor.reset);
}
// Query each verifier that matches the specified key. This should be an in-cycle verifier to work
// properly, but the verifier will respond as long as the message is signed by the correct key.
int numberQueried = 0;
AtomicInteger numberWaiting = new AtomicInteger(0);
for (Node node : ClientNodeManager.getMesh()) {
if (ByteUtil.arraysAreEqual(node.getIdentifier(), identifier)) {
output.println("querying node " + NicknameManager.get(identifier));
numberQueried++;
numberWaiting.incrementAndGet();
Message message = new Message(MessageType.CycleTransactionListRequest49, null);
message.sign(verifierKey.getSeed());
Message.fetchTcp(IpUtil.addressAsString(node.getIpAddress()), MeshListener.standardPortTcp,
message, new MessageCallback() {
@Override
public void responseReceived(Message message) {
processResponse(message);
numberWaiting.decrementAndGet();
}
});
}
}
// Wait for all responses to be processed.
while (numberWaiting.get() > 0) {
ThreadUtil.sleep(300L);
}
}
// Perform maintenance on the transaction manager. This removes old transactions.
CycleTransactionManager.performMaintenance();
// Show the transactions.
List<Transaction> transactions = getTransactionList();
if (transactions.isEmpty()) {
ConsoleUtil.printTable(output, "no cycle transactions available");
} else {
List<String> indexColumn = new ArrayList<>(Collections.singletonList("index"));
List<String> initiatorColumn = new ArrayList<>(Collections.singletonList("initiator"));
List<String> receiverColumn = new ArrayList<>(Collections.singletonList("receiver"));
List<String> amountColumn = new ArrayList<>(Collections.singletonList("amount"));
List<String> blockColumn = new ArrayList<>(Collections.singletonList("block"));
List<String> numberOfSignaturesColumn = new ArrayList<>(Collections.singletonList("# signatures"));
for (int i = 0; i < transactions.size(); i++) {
indexColumn.add(i + "");
Transaction transaction = transactions.get(i);
NyzoStringPublicIdentifier initiator =
new NyzoStringPublicIdentifier(transaction.getSenderIdentifier());
initiatorColumn.add(NyzoStringEncoder.encode(initiator));
NyzoStringPublicIdentifier receiver =
new NyzoStringPublicIdentifier(transaction.getReceiverIdentifier());
receiverColumn.add(NyzoStringEncoder.encode(receiver));
amountColumn.add(PrintUtil.printAmount(transaction.getAmount()));
blockColumn.add(BlockManager.heightForTimestamp(transaction.getTimestamp()) + "");
numberOfSignaturesColumn.add((transaction.getCycleSignatures().size() + 1) + "");
}
ConsoleUtil.printTable(Arrays.asList(indexColumn, initiatorColumn, receiverColumn, amountColumn,
blockColumn, numberOfSignaturesColumn), new HashSet<>(Collections.singletonList(0)), output);
}
} catch (Exception e) {
output.println(ConsoleColor.Red + "unexpected issue listing cycle transactions: " +
PrintUtil.printException(e) + ConsoleColor.reset);
}
return null;
}
private static void processResponse(Message message) {
if (message != null && (message.getContent() instanceof TransactionListResponse)) {
TransactionListResponse response = (TransactionListResponse) message.getContent();
for (Transaction transaction : response.getTransactions()) {
// Register the transaction.
CycleTransactionManager.registerTransaction(transaction, null, null);
// Register the signatures. In the registerTransaction() method, signatures are only registered for new
// cycle transactions.
for (ByteBuffer signer : transaction.getCycleSignatures().keySet()) {
CycleTransactionSignature signature =
new CycleTransactionSignature(transaction.getSenderIdentifier(), signer.array(),
transaction.getCycleSignatures().get(signer));
CycleTransactionManager.registerSignature(signature);
}
}
}
}
public static List<Transaction> getTransactionList() {
// Impose a standard ordering on transactions.
List<Transaction> transactions = new ArrayList<>(CycleTransactionManager.getTransactions());
transactions.sort(new Comparator<Transaction>() {
@Override
public int compare(Transaction transaction1, Transaction transaction2) {
// Primary ordering is on timestamp, secondary ordering is on initiator identifier string.
if (transaction1.getTimestamp() != transaction2.getTimestamp()) {
return Long.compare(transaction1.getTimestamp(), transaction2.getTimestamp());
} else {
NyzoStringPublicIdentifier initiator1 =
new NyzoStringPublicIdentifier(transaction1.getSenderIdentifier());
NyzoStringPublicIdentifier initiator2 =
new NyzoStringPublicIdentifier(transaction2.getSenderIdentifier());
return NyzoStringEncoder.encode(initiator1).compareTo(NyzoStringEncoder.encode(initiator2));
}
}
});
return transactions;
}
}
|
3e06ff4b9bf1086fae94f3fb2d4bfbb1e2d5d17d | 2,836 | java | Java | library/src/main/java/cn/sswukang/library/adapter/sticky/StickyHeaderAdapter.java | sswukang/RvAdapter | 5ec3d0f77c8c1e113db2d21a934a62050a1ad15e | [
"Apache-2.0"
] | 4 | 2017-02-16T09:45:17.000Z | 2017-12-11T08:41:42.000Z | library/src/main/java/cn/sswukang/library/adapter/sticky/StickyHeaderAdapter.java | sswukang/RvAdapter | 5ec3d0f77c8c1e113db2d21a934a62050a1ad15e | [
"Apache-2.0"
] | null | null | null | library/src/main/java/cn/sswukang/library/adapter/sticky/StickyHeaderAdapter.java | sswukang/RvAdapter | 5ec3d0f77c8c1e113db2d21a934a62050a1ad15e | [
"Apache-2.0"
] | null | null | null | 27.533981 | 102 | 0.675599 | 2,958 | package cn.sswukang.library.adapter.sticky;
import androidx.annotation.LayoutRes;
import androidx.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.List;
import cn.sswukang.library.adapter.base.BaseViewHolder;
import cn.sswukang.library.adapter.single.SingleAdapter;
import cn.sswukang.library.lib.sticky_header.sticky.StickyRecyclerHeadersAdapter;
/**
* 粘性头部适配器。
*
* @author sswukang on 2017/2/21 11:03
* @version 1.0
*/
public abstract class StickyHeaderAdapter<T> extends SingleAdapter<T>
implements StickyRecyclerHeadersAdapter<BaseViewHolder> {
// sticky header res id;
@LayoutRes
private int headerLayoutId;
// sticky header layout height;
private int headerHeight;
/**
* @param headerLayoutId header需要的布局资源id
* @param layoutId content需要的布局资源id
* @param data 数据
*/
public StickyHeaderAdapter(@LayoutRes int headerLayoutId, @LayoutRes int layoutId, List<T> data) {
super(layoutId, data);
this.headerLayoutId = headerLayoutId;
this.headerHeight = setHeaderHeight();
}
/**
* 设置item总个数(不允许设置无限轮播)
*/
@Override
public final int getItemCount() {
return super.getItemCount();
}
@Override
public final long getHeaderId(int position) {
return getHeaderId(position, getDataItem(position));
}
@Override
public final BaseViewHolder onCreateHeaderViewHolder(ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View root = inflater.inflate(headerLayoutId, parent, false);
return BaseViewHolder.get(root, headerLayoutId, this);
}
@Override
public final void onBindHeaderViewHolder(BaseViewHolder holder, int position) {
convertHeader(position, getDataItem(position), holder);
}
/**
* 开放粘性头部高度,方便 recycler view 滚动。
*
* @return sticky header height
*/
public int getHeaderHeight() {
return headerHeight;
}
/**
* 设置粘性头部高度,方便sticky header定位
*
* @return sticky header height
*/
public abstract int setHeaderHeight();
/**
* 获得 header id 。如果某几个条目有相同的header,其id 需相同。
* 如某条目不需要header,则return < 0 即可。
* 例:字符串可以用 String.charAt(0)
*
* @param position 当前item的position
* @param t position 对应的对象
* @return header id {@link StickyRecyclerHeadersAdapter#getHeaderId(int)}
*/
public abstract long getHeaderId(int position, @Nullable T t);
/**
* 填充粘性头部显示的内容
*
* @param position header 条目下标
* @param t header 对象数据封装
* @param holder {@link BaseViewHolder}
*/
public abstract void convertHeader(int position, @Nullable T t, BaseViewHolder holder);
}
|
3e06ff863fb8862076fa3441a37b6fb105eefaf8 | 219 | java | Java | src/DGP/CJLU/Experiment8/Lab1/LoopFunction.java | Lightczx/CJLU.Java.Algorithm | e9130e7de47ddce54ebb0a5e0489754a8ea3748f | [
"MIT"
] | null | null | null | src/DGP/CJLU/Experiment8/Lab1/LoopFunction.java | Lightczx/CJLU.Java.Algorithm | e9130e7de47ddce54ebb0a5e0489754a8ea3748f | [
"MIT"
] | null | null | null | src/DGP/CJLU/Experiment8/Lab1/LoopFunction.java | Lightczx/CJLU.Java.Algorithm | e9130e7de47ddce54ebb0a5e0489754a8ea3748f | [
"MIT"
] | null | null | null | 14.6 | 35 | 0.598174 | 2,959 | package DGP.CJLU.Experiment8.Lab1;
/**
* @author 16861
*/
@FunctionalInterface
interface LoopFunction<T> {
/**
* loop function
*
* @param v the vertex
*/
void invoke(Graph<T>.Vertex v);
}
|
3e06ff9e2e197b799c99d58fd481a7243175b16a | 66,440 | java | Java | agave-apps/apps-core/src/test/java/org/iplantc/service/apps/model/GSoftwareParameterTest.java | agaveplatform/science-apis | 7ca81d9124bfb446edc5f92050733adb75b938d5 | [
"BSD-3-Clause"
] | null | null | null | agave-apps/apps-core/src/test/java/org/iplantc/service/apps/model/GSoftwareParameterTest.java | agaveplatform/science-apis | 7ca81d9124bfb446edc5f92050733adb75b938d5 | [
"BSD-3-Clause"
] | 8 | 2017-08-26T15:48:36.000Z | 2020-07-03T03:35:16.000Z | agave-apps/apps-core/src/test/java/org/iplantc/service/apps/model/GSoftwareParameterTest.java | agaveplatform/science-apis | 7ca81d9124bfb446edc5f92050733adb75b938d5 | [
"BSD-3-Clause"
] | 1 | 2018-05-30T03:55:22.000Z | 2018-05-30T03:55:22.000Z | 78.441558 | 228 | 0.686665 | 2,960 | package org.iplantc.service.apps.model;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.iplantc.service.apps.model.enumerations.SoftwareParameterType;
import org.iplantc.service.apps.util.ServiceUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.util.*;
/**
* Created with IntelliJ IDEA.
* User: steve
* Date: 4/5/12
* Time: 12:50 PM
* To change this template use File | Settings | File Templates.
*/
@Test(groups = {"unit"})
public class GSoftwareParameterTest extends GModelTestCommon {
private final SoftwareParameter parameter = new SoftwareParameter();
@BeforeClass
public void setUp() throws Exception {
super.setUp();
}
@DataProvider(name = "dataTestParameter")
public Object[][] createData1() {
return jtd.dataTestParameter;
}
@DataProvider(name = "dataTestParameterValue")
public Object[][] createData2() {
return jtd.dataTestParameterValue;
}
@DataProvider(name = "dataTestParameterDetails")
public Object[][] createData3() {
return jtd.dataTestInputsDetails;
}
@DataProvider(name = "dataTestParameterSemanticsOntology")
public Object[][] createData4() {
return jtd.dataTestParameterSemanticsOntology;
}
@Test (groups="model", dataProvider="dataTestParameter")
public void parameterFromJSON(String name, Object changeValue, String message, boolean expectExceptionThrown) throws Exception {
JSONObject jsonTree = new JSONObject(jsonTreeParameters.toString());
jsonTree.put(name, changeValue);
super.commonSoftwareFromJSON(parameter, jsonTree, name, changeValue, message, expectExceptionThrown);
}
@Test(groups = "model", dataProvider = "dataTestParameterValue")
public void parameterValueFromJSON(String name, Object changeValue, String message, boolean expectExceptionThrown) throws Exception {
JSONObject jsonTree = new JSONObject(jsonTreeParameters.toString());
jsonTree.getJSONObject("value").put(name, changeValue);
jsonTree.getJSONObject("semantics").put("minCardinality", StringUtils.equals(name, "required") || StringUtils.equals(name, "visible") ? 1 : 0);
super.commonSoftwareFromJSON(parameter, jsonTree, name, changeValue, message, expectExceptionThrown);
}
@DataProvider(name = "parameterRequiredAndVisibleRespectCardinalityProvider")
public Object[][] parameterRequiredAndVisibleRespectCardinalityProvider() {
return new Object[][]{
// { required, visible, minCardinality, shouldThrowException, message }
{true, true, 0, true, "required parameters must have minCardinality > 0"},
{true, false, 0, true, "hidden parameters must have minCardinality > 0"},
{false, true, 0, false, "visible, optional parameters can have minCardinality = 0"},
{false, false, 0, true, "hidden parameters must have minCardinality > 0"}
};
}
@Test(groups = "model", dataProvider = "parameterRequiredAndVisibleRespectCardinalityProvider")
public void parameterRequiredAndVisibleRespectCardinality(boolean required, boolean visible, int minCardinality, boolean shouldThrowException, String message) {
try {
JSONObject jsonTree = new JSONObject(jsonTreeParameters.toString());
jsonTree.getJSONObject("value").put("required", required);
jsonTree.getJSONObject("value").put("visible", visible);
jsonTree.getJSONObject("semantics").put("minCardinality", minCardinality);
jsonTree.getJSONObject("semantics").put("maxCardinality", -1);
jsonTree.getJSONObject("value").put("default", "foo");
Assert.assertNotNull(SoftwareParameter.fromJSON(jsonTree), "Null parameter returned from SoftwareParameter.fromJSON");
} catch (Exception e) {
Assert.assertTrue(shouldThrowException, message);
}
}
@DataProvider(name = "parameterValueEnumFromJSONProvider")
public Object[][] parameterValueEnumFromJSONProvider() throws Exception {
JSONObject alpha = new JSONObject();
alpha.put("alpha", "alpha");
JSONObject beta = new JSONObject();
beta.put("beta", "beta");
JSONObject gamma = new JSONObject();
gamma.put("gamma", "gamma");
JSONObject delta = new JSONObject();
delta.put("delta1", "delta1");
delta.put("delta2", "delta2");
return new Object[][]{
{"", "cannot set input.value.enum_value to empty string", true},
{new JSONObject(), "cannot set input.value.enum_value to empty object", true},
{new JSONArray(new JSONObject[]{alpha, beta, new JSONObject()}), "cannot set input.value.enum_value to array with empty object", true},
{Arrays.asList(alpha, beta, delta), "cannot set input.value.enum_value to array with object with more than one attribute", true},
{Arrays.asList(new JSONObject(), new JSONObject(), new JSONArray()), "cannot set input.value.enum_value to array with arraylist in it", true},
{Arrays.asList("gamma", "beta", new JSONArray()), "cannot set input.value.enum_value to array of string with arraylist in it", true},
{Arrays.asList(new JSONObject(), new JSONObject(), new JSONObject()), "cannot set input.value.enum_value to array of empty objects", true},
{null, "cannot set input.value.enum_value to null", true},
{"abracadabra", "cannot set input.value.enum_value to string", true},
{25, "cannot set input.value.enum_value to 25", true},
{Arrays.asList(alpha, beta, gamma), "should allow seting input.value.enum_value to array of json objects", false},
{Arrays.asList(alpha, beta, "gamma"), "should allow seting input.value.enum_value to array of single attribute objects and strings", false},
{Arrays.asList(alpha, "beta", "gamma"), "should allow seting input.value.enum_value to array of single attribute objects and strings", false},
{Arrays.asList("alpha", "beta", "gamma"), "should allow seting input.value.enum_value to array of single attribute strings", false},
};
}
@Test(groups = "model", dataProvider = "parameterValueEnumFromJSONProvider")
public void parameterValueEnumFromJSON(Object enumValue, String message, boolean expectExceptionThrown)
throws Exception {
JSONObject jsonTree = new JSONObject(jsonTreeParameters.toString());
jsonTree.getJSONObject("value").remove("type");
jsonTree.getJSONObject("value").put("type", SoftwareParameterType.enumeration.name());
jsonTree.getJSONObject("value").remove("validator");
jsonTree.getJSONObject("value").remove("default");
jsonTree.getJSONObject("value").put("default", "alpha");
jsonTree.getJSONObject("value").remove("enum_values");
jsonTree.getJSONObject("value").remove("enumValues");
jsonTree.getJSONObject("value").put("enumValues", enumValue);
super.commonSoftwareFromJSON(parameter, jsonTree, "enum_value", enumValue, message, expectExceptionThrown);
}
@DataProvider(name = "parameterValueEnumDefaultFromJSONProvider")
public Object[][] parameterValueEnumDefaultFromJSONProvider() throws Exception {
return new Object[][]{
{"", "empty string default value should throw exception", true},
{new JSONArray(Collections.singletonList("")), "empty string default value should throw exception", true},
{25L, "numeric default value should throw exception", true},
{new JSONArray(Collections.singletonList(25L)), "numeric default value should throw exception", true},
{Boolean.TRUE, "boolean true default value should throw exception", true},
{Boolean.FALSE, "boolean false default value should throw exception", true},
{new JSONArray(Collections.singletonList(Boolean.TRUE)), "array of boolean true default value should throw exception", true},
{new JSONArray(Collections.singletonList(Boolean.FALSE)), "array of boolean false default value should throw exception", true},
{new JSONObject(), "empty object for default value should throw exception", true},
{"alpha", "single value enum values should not throw exception", false},
{"beta", "single value enum values should not throw exception", false},
{"gamma", "single value enum values should not throw exception", false},
{"zed", "single value other than one of enum values should throw exception", true},
{new JSONArray(new String[]{"zed"}), "array with value other than one of enum values should throw exception", true},
{new JSONArray(new String[]{"alpha"}), "array with one of enum values should pass with enum", false},
{new JSONArray(), "empty jsonarray default value should pass with enum", false},
{new JSONArray(Collections.singletonList((String) null)), "array with null value should throw exception", true},
};
}
@Test(groups = "model", dataProvider = "parameterValueEnumDefaultFromJSONProvider")
public void parameterValueEnumDefaultFromJSON(Object changeValue, String message, boolean expectExceptionThrown)
throws Exception {
JSONObject alpha = new JSONObject();
alpha.put("alpha", "alpha");
JSONObject beta = new JSONObject();
beta.put("beta", "beta");
JSONObject gamma = new JSONObject();
gamma.put("gamma", "gamma");
JSONObject jsonTree = new JSONObject(jsonTreeParameters.toString());
jsonTree.getJSONObject("value").remove("type");
jsonTree.getJSONObject("value").put("type", SoftwareParameterType.enumeration.name());
jsonTree.getJSONObject("value").remove("validator");
jsonTree.getJSONObject("value").remove("enum_values");
jsonTree.getJSONObject("value").remove("enumValues");
jsonTree.getJSONObject("value").put("enumValues", new JSONArray(new JSONObject[]{alpha, beta, gamma}));
jsonTree.getJSONObject("value").remove("default");
jsonTree.getJSONObject("value").put("default", changeValue);
super.commonSoftwareFromJSON(parameter, jsonTree, "default", changeValue, message, expectExceptionThrown);
}
@Test(groups = "model", dataProvider = "dataTestParameterDetails")
public void parameterDetailsFromJSON(String name, Object changeValue, String message, boolean expectExceptionThrown) throws Exception {
JSONObject jsonTree = new JSONObject(jsonTreeParameters.toString());
jsonTree.getJSONObject("details").put(name, changeValue);
super.commonSoftwareFromJSON(parameter, jsonTree, name, changeValue, message, expectExceptionThrown);
}
@DataProvider(name = "parameterTypeEnforcedOnDefaultValueProvider")
public Object[][] parameterTypeEnforcedOnDefaultValueProvider() {
Object positiveInteger = 5;
Object negativeInteger = 5;
Object positiveDecimal = 5.5f;
Object negativeDecimal = (float) -5.5;
Object nonEmptyString = "hello";
Object emptyString = "";
Object trueValue = Boolean.TRUE;
Object falseValue = Boolean.FALSE;
Object jsonObject = new JSONObject();
Object emptyArray = new JSONArray();
Object numberArray = new JSONArray(Collections.singletonList(positiveInteger));
Object stringArray = new JSONArray(Collections.singletonList(nonEmptyString));
Object booleanArray = new JSONArray(Collections.singletonList(trueValue));
Object objectArray = new JSONArray(Collections.singletonList(jsonObject));
List<Object> allObjects = Arrays.asList(positiveInteger, negativeInteger, positiveDecimal, negativeDecimal,
trueValue, falseValue, nonEmptyString, emptyString, jsonObject, emptyArray, objectArray, numberArray, stringArray, booleanArray);
Map<SoftwareParameterType, List<Object>> map = new HashMap<>();
map.put(SoftwareParameterType.number, Arrays.asList(positiveInteger, negativeInteger, positiveDecimal, negativeDecimal, emptyArray, numberArray));
map.put(SoftwareParameterType.flag, Arrays.asList(trueValue, falseValue, emptyArray, booleanArray));
map.put(SoftwareParameterType.bool, Arrays.asList(trueValue, falseValue, emptyArray, booleanArray));
map.put(SoftwareParameterType.string, Arrays.asList(nonEmptyString, emptyString, emptyArray, stringArray));
List<Object[]> testData = new ArrayList<>();
for (SoftwareParameterType type : map.keySet()) {
for (Object object : allObjects) {
if (map.get(type).contains(object)) {
testData.add(new Object[]{
type,
object,
"Setting input.value.default to " + object.toString() + " with input.value.type = number should be allowed",
false});
} else {
testData.add(new Object[]{
type,
object,
"Setting input.value.default to " + object.toString() + " with input.value.type = number should not be allowed",
true});
}
}
testData.add(new Object[]{
type,
null,
"Setting input.value.default to null with input.value.type = number should be allowed",
false});
}
return testData.toArray(new Object[56][4]);
}
@Test(groups = "model", dataProvider = "parameterTypeEnforcedOnDefaultValueProvider")
public void parameterTypeEnforcedOnDefaultValue(SoftwareParameterType type, Object changeValue, String message, boolean exceptionThrown) throws Exception {
JSONObject jsonTree = new JSONObject(jsonTreeParameters.toString());
jsonTree.getJSONObject("value").put("type", type);
jsonTree.getJSONObject("value").put("validator", (String) null);
jsonTree.getJSONObject("value").put("default", changeValue);
super.commonSoftwareFromJSON(parameter, jsonTree, "default", changeValue, message, exceptionThrown);
}
@Test(groups = "model", dataProvider = "dataTestParameterSemanticsOntology")
public void parameterSemanticsFromJSON(String name, Object changeValue, String message, boolean expectExceptionThrown) throws Exception {
JSONObject jsonTree = new JSONObject(jsonTreeParameters.toString());
jsonTree.getJSONObject("semantics").put(name, changeValue);
jsonTree.getJSONObject("value").put("required", false);
jsonTree.getJSONObject("value").put("visible", true);
super.commonSoftwareFromJSON(parameter, jsonTree, name, changeValue, message, expectExceptionThrown);
}
@DataProvider(name = "inputsValidatorEnforcedOnDefaultValueProvider")
public Object[][] inputsValidatorEnforcedOnDefaultValueProvider() {
return new Object[][]{
{".*\\.pdf$", "something.png", "Default value not matching regex should throw exception", true},
{".*\\.pdf$", "something.pdf2", "Default value not matching regex should throw exception", true},
{".*\\.pdf$", "pdf", "Default value not matching regex should throw exception", true},
{null, "", "Empty default value should pass matching regex", false},
{"", "", "Empty default value should pass empty regex", false},
{"\\s*", "", "Empty default value should pass matching regex", false},
{".*\\.pdf$", "", "Empty default value should pass matching regex", true},
{".*\\.pdf$", null, "Null default value should pass despite regex", false},
{".*\\.pdf$", "something.pdf", "Default value matching regex should pass", false},
{".*\\.pdf$", ".pdf", "Default value matching regex should pass", false},
{".*\\.pdf$", "something.png.pdf", "Default value matching regex should pass", false},
};
}
@Test(groups = "model", dataProvider = "inputsValidatorEnforcedOnDefaultValueProvider")
public void inputsValidatorEnforcedOnDefaultValue(String validator, String defaultValue, String message, boolean exceptionThrown) throws Exception {
JSONObject jsonTree = new JSONObject(jsonTreeParameters.toString());
jsonTree.getJSONObject("value").put("validator", validator);
jsonTree.getJSONObject("value").put("default", defaultValue);
super.commonSoftwareFromJSON(parameter, jsonTree, "default", defaultValue, message, exceptionThrown);
}
@DataProvider(name = "inputsValidatorEnforcedOnDefaultValueArrayProvider")
public Object[][] inputsValidatorEnforcedOnDefaultValueArrayProvider() {
String emptyString = "";
String nullString = null;
String validFileExtension = "pdf";
String badFileExtension = "png";
String basename = "something";
String badFileExtenstion = basename + "." + badFileExtension;
String badFileExtensionSuffix = basename + "." + validFileExtension + "2";
String badFileExtensionPrefix = basename + ".df";
String matchingFilename = basename + "." + validFileExtension;
String matchingExtension = "." + validFileExtension;
String matchingFilenameWithMultipleExtensions = badFileExtenstion + matchingExtension;
return new Object[][]{
// null checks should pass since parameter has default of 0
{".*\\.pdf$", new JSONArray(Collections.singletonList(nullString)), "Null default value should pass despite regex", false},
{".*\\.pdf$", new JSONArray(Arrays.asList(nullString, nullString)), "all null values in default value array should pass despite regex", false},
// Single value arrays
{".*\\.pdf$", new JSONArray(Collections.singletonList(badFileExtenstion)), "Default value not matching regex should throw exception", true},
{".*\\.pdf$", new JSONArray(Collections.singletonList(badFileExtensionSuffix)), "Default value not matching regex should throw exception", true},
{".*\\.pdf$", new JSONArray(Collections.singletonList(badFileExtensionPrefix)), "Default value not matching regex should throw exception", true},
{emptyString, new JSONArray(Collections.singletonList(emptyString)), "Empty default value should pass when regex matches", false},
{"\\s*", new JSONArray(Collections.singletonList(emptyString)), "Empty default value should pass when regex matches", false},
{nullString, new JSONArray(Collections.singletonList(emptyString)), "Empty default value should pass when regex is null", false},
{".*\\.pdf$", new JSONArray(Collections.singletonList(emptyString)), "Empty default value should throw exception when it does not match", true},
{".*\\.pdf$", new JSONArray(Collections.singletonList("something.pdf")), "Default value matching regex should pass", false},
{".*\\.pdf$", new JSONArray(Collections.singletonList(".pdf")), "Default value matching regex should pass", false},
{".*\\.pdf$", new JSONArray(Collections.singletonList("something.png.pdf")), "Default value matching regex should pass", false},
// Mixed value arrays
{".*\\.pdf$", new JSONArray(Arrays.asList(badFileExtenstion, badFileExtenstion)), "both values in default value array not matching regex should throw exception", true},
{".*\\.pdf$", new JSONArray(Arrays.asList(badFileExtensionSuffix, badFileExtensionSuffix)), "both values in default value array not matching regex should throw exception", true},
{".*\\.pdf$", new JSONArray(Arrays.asList(badFileExtensionPrefix, badFileExtensionPrefix)), "both values in default value array not matching regex should throw exception", true},
{".*\\.pdf$", new JSONArray(Arrays.asList("something.png", matchingFilename)), "Any entry in default value array not matching regex should throw exception", true},
{".*\\.pdf$", new JSONArray(Arrays.asList("something.pdf2", matchingFilename)), "Any entry in default value array not matching regex should throw exception", true},
{".*\\.pdf$", new JSONArray(Arrays.asList("pdf", matchingFilename)), "Any entry in default value array not matching regex should throw exception", true},
{emptyString, new JSONArray(Arrays.asList(emptyString, emptyString)), "all empty values in default value array should pass when regex matches", false},
{"\\s*", new JSONArray(Arrays.asList(emptyString, emptyString)), "all empty values in default value array should pass when regex matches", false},
{nullString, new JSONArray(Arrays.asList(emptyString, emptyString)), "all empty values in default value array should pass when regex is null", false},
{".*\\.pdf$", new JSONArray(Arrays.asList(emptyString, emptyString)), "all empty values in default value array should throw exception when regex does not match", true},
{".*\\.pdf$", new JSONArray(Arrays.asList(matchingFilename, matchingFilename)), "both values in default value matching regex should pass", false},
{".*\\.pdf$", new JSONArray(Arrays.asList(matchingExtension, matchingExtension)), "both values in default value matching regex should pass", false},
{".*\\.pdf$", new JSONArray(Arrays.asList(matchingFilenameWithMultipleExtensions, matchingFilenameWithMultipleExtensions)), "both values in default value matching regex should pass", false},
};
}
@Test(groups = "model", dataProvider = "inputsValidatorEnforcedOnDefaultValueArrayProvider")
public void inputsValidatorEnforcedOnDefaultArrayValue(String validator, JSONArray defaultValue, String message, boolean exceptionThrown) throws Exception {
JSONObject jsonTree = new JSONObject(jsonTreeParameters.toString());
jsonTree.getJSONObject("semantics").put("maxCardinality", -1);
jsonTree.getJSONObject("value").put("validator", validator);
jsonTree.getJSONObject("value").put("default", defaultValue);
super.commonSoftwareFromJSON(parameter, jsonTree, "default", defaultValue, message, exceptionThrown);
}
@DataProvider(name = "inputsValidatorFiltersRedundantValuesFromDefaultValueArrayProvider")
public Object[][] inputsValidatorFiltersRedundantValuesFromDefaultValueArrayProvider() {
String emptyString = "";
String nullString = null;
String foofile = "foo.pdf";
String barfile = "bar.pdf";
return new Object[][]{
// Single value retains in array
// {nullString, new String[]{}, "null value should be reduced to an empty default value array"},
{emptyString, new String[]{emptyString}, "single empty string should be reduced to a single empty string in the resulting default value array"},
{foofile, new String[]{foofile}, "single string should be reduced to a single string in the resulting default value array"},
// Single value array retains in array
{new JSONArray(Collections.singletonList(nullString)), new String[]{}, "null value array should be reduced to an empty default value array"},
{new JSONArray(Collections.singletonList(emptyString)), new String[]{emptyString}, "single empty string array should be retained in the resulting default value array"},
{new JSONArray(Collections.singletonList(foofile)), new String[]{foofile}, "single string array should be retained in the resulting default value array"},
// Redundant values get filtered to single value
{new JSONArray(Arrays.asList(nullString, nullString)), new String[]{}, "multiple null strings should be reduced to an empty default value array"},
{new JSONArray(Arrays.asList(nullString, emptyString)), new String[]{emptyString}, "null strings should be removed from the default value array"},
{new JSONArray(Arrays.asList(nullString, foofile)), new String[]{foofile}, "null strings should be removed and valid value retained in the default value array"},
{new JSONArray(Arrays.asList(nullString, barfile)), new String[]{barfile}, "null strings should be removed and valid value retained in the default value array"},
{new JSONArray(Arrays.asList(nullString, nullString, nullString)), new String[]{}, "multiple null strings should be reduced to an empty default value array"},
{new JSONArray(Arrays.asList(nullString, nullString, emptyString)), new String[]{emptyString}, "null strings should be removed and valid value retained in the default value array"},
{new JSONArray(Arrays.asList(nullString, nullString, foofile)), new String[]{foofile}, "null strings should be removed and valid value retained in the default value array"},
{new JSONArray(Arrays.asList(nullString, nullString, barfile)), new String[]{barfile}, "null strings should be removed and valid value retained in the default value array"},
{new JSONArray(Arrays.asList(emptyString, emptyString)), new String[]{emptyString}, "multiple empty strings should be reduced to a single empty string in the default value array"},
{new JSONArray(Arrays.asList(emptyString, foofile)), new String[]{emptyString, foofile}, "unique entries should be retained in the default value array"},
{new JSONArray(Arrays.asList(emptyString, barfile)), new String[]{emptyString, barfile}, "unique entries should be retained in the default value array"},
{new JSONArray(Arrays.asList(foofile, emptyString)), new String[]{foofile, emptyString}, "unique entries should be retained in the default value array"},
{new JSONArray(Arrays.asList(barfile, emptyString)), new String[]{barfile, emptyString}, "unique entries should be retained in the default value array"},
{new JSONArray(Arrays.asList(foofile, emptyString, barfile)), new String[]{foofile, emptyString, barfile}, "unique entries should be retained in the default value array"},
{new JSONArray(Arrays.asList(emptyString, emptyString, emptyString)), new String[]{emptyString}, "redundant empty strings should be reduced to a single empty string in the default value array"},
{new JSONArray(Arrays.asList(emptyString, emptyString, foofile)), new String[]{emptyString, foofile}, "multiple empty strings should be removed and unique values should be retained in the default value array"},
{new JSONArray(Arrays.asList(emptyString, emptyString, barfile)), new String[]{emptyString, barfile}, "multiple empty strings should be removed and unique values should be retained in the default value array"},
{new JSONArray(Arrays.asList(emptyString, foofile, emptyString)), new String[]{emptyString, foofile}, "multiple empty strings should be removed and unique values should be retained in the default value array"},
{new JSONArray(Arrays.asList(emptyString, barfile, emptyString)), new String[]{emptyString, barfile}, "multiple empty strings should be removed and unique values should be retained in the default value array"},
{new JSONArray(Arrays.asList(foofile, emptyString, emptyString)), new String[]{foofile, emptyString}, "multiple empty strings should be removed and unique values should be retained in the default value array"},
{new JSONArray(Arrays.asList(barfile, emptyString, emptyString)), new String[]{barfile, emptyString}, "multiple empty strings should be removed and unique values should be retained in the default value array"},
{new JSONArray(Arrays.asList(foofile, foofile)), new String[]{foofile}, "redundant strings should be reduced to a single string in the default value array"},
{new JSONArray(Arrays.asList(foofile, foofile, foofile)), new String[]{foofile}, "redundant strings should be reduced to a single string in the default value array"},
{new JSONArray(Arrays.asList(barfile, foofile, foofile)), new String[]{barfile, foofile}, "redundant strings should be reduced to a single string and unique values should be retained in the default value array"},
{new JSONArray(Arrays.asList(foofile, barfile, foofile)), new String[]{foofile, barfile}, "redundant strings should be reduced to a single string and unique values should be retained in the default value array"},
{new JSONArray(Arrays.asList(foofile, foofile, barfile)), new String[]{foofile, barfile}, "redundant strings should be reduced to a single string and unique values should be retained in the default value array"},
{new JSONArray(Arrays.asList(barfile, barfile)), new String[]{barfile}, "redundant strings should be reduced to a single string in the default value array"},
{new JSONArray(Arrays.asList(barfile, barfile, barfile)), new String[]{barfile}, "redundant strings should be reduced to a single string in the default value array"},
{new JSONArray(Arrays.asList(foofile, barfile, barfile)), new String[]{foofile, barfile}, "redundant strings should be reduced to a single string and unique values should be retained in the default value array"},
{new JSONArray(Arrays.asList(barfile, foofile, barfile)), new String[]{barfile, foofile}, "redundant strings should be reduced to a single string and unique values should be retained in the default value array"},
{new JSONArray(Arrays.asList(barfile, barfile, foofile)), new String[]{barfile, foofile}, "redundant strings should be reduced to a single string and unique values should be retained in the default value array"},
};
}
@Test (groups={"model"}, dataProvider="inputsValidatorFiltersRedundantValuesFromDefaultValueArrayProvider")
public void inputsValidatorFiltersRedundantValuesFromDefaultValueArray(Object defaultValue, String[] expectedValues, String message)
throws Exception {
JSONObject jsonTree = new JSONObject(jsonTreeParameters.toString());
jsonTree.getJSONObject("semantics").put("maxCardinality", -1);
jsonTree.getJSONObject("value").put("default", defaultValue);
SoftwareParameter parameter = SoftwareParameter.fromJSON(jsonTree);
String[] defaultValuesArray = ServiceUtils.getStringValuesFromJsonArray(parameter.getDefaultValueAsJsonArray(), false);
Assert.assertEquals(defaultValuesArray.length, expectedValues.length,
"The number of expected values after parsing the input did not match the actual values after parsing.");
for (String expectedValue : expectedValues) {
Assert.assertTrue(List.of(defaultValuesArray).contains(expectedValue), "expected value " +
expectedValue + " was not found in the default value array after parsing the input");
}
}
@DataProvider(name = "inputDefaultValueArrayRetainsOrderingProvider")
public Object[][] inputDefaultValueArrayRetainsOrderingProviderProvider() {
String emptyString = "";
String foofile = "foo.pdf";
String barfile = "bar.pdf";
String scatfile = "scat.pdf";
return new Object[][]{
{new JSONArray(Arrays.asList(emptyString, emptyString)), new String[]{emptyString}},
{new JSONArray(Arrays.asList(emptyString, foofile)), new String[]{emptyString, foofile}},
{new JSONArray(Arrays.asList(emptyString, barfile)), new String[]{emptyString, barfile}},
{new JSONArray(Arrays.asList(foofile, emptyString)), new String[]{foofile, emptyString}},
{new JSONArray(Arrays.asList(barfile, emptyString)), new String[]{barfile, emptyString}},
{new JSONArray(Arrays.asList(emptyString, emptyString, foofile)), new String[]{emptyString, foofile}},
{new JSONArray(Arrays.asList(emptyString, emptyString, barfile)), new String[]{emptyString, barfile}},
{new JSONArray(Arrays.asList(emptyString, foofile, emptyString)), new String[]{emptyString, foofile}},
{new JSONArray(Arrays.asList(emptyString, barfile, emptyString)), new String[]{emptyString, barfile}},
{new JSONArray(Arrays.asList(foofile, emptyString, emptyString)), new String[]{foofile, emptyString}},
{new JSONArray(Arrays.asList(barfile, emptyString, emptyString)), new String[]{barfile, emptyString}},
{new JSONArray(Arrays.asList(barfile, foofile, foofile)), new String[]{barfile, foofile}},
{new JSONArray(Arrays.asList(foofile, barfile, foofile)), new String[]{foofile, barfile}},
{new JSONArray(Arrays.asList(foofile, foofile, barfile)), new String[]{foofile, barfile}},
{new JSONArray(Arrays.asList(foofile, barfile, barfile)), new String[]{foofile, barfile}},
{new JSONArray(Arrays.asList(barfile, foofile, barfile)), new String[]{barfile, foofile}},
{new JSONArray(Arrays.asList(barfile, barfile, foofile)), new String[]{barfile, foofile}},
{new JSONArray(Arrays.asList(foofile, barfile, scatfile)), new String[]{foofile, barfile, scatfile}},
{new JSONArray(Arrays.asList(foofile, scatfile, barfile)), new String[]{foofile, scatfile, barfile}},
{new JSONArray(Arrays.asList(barfile, scatfile, foofile)), new String[]{barfile, scatfile, foofile}},
{new JSONArray(Arrays.asList(barfile, foofile, scatfile)), new String[]{barfile, foofile, scatfile}},
{new JSONArray(Arrays.asList(scatfile, barfile, foofile)), new String[]{scatfile, barfile, foofile}},
{new JSONArray(Arrays.asList(scatfile, foofile, barfile)), new String[]{scatfile, foofile, barfile}},
};
}
@Test (groups="model", dataProvider="inputDefaultValueArrayRetainsOrderingProvider")
public void inputDefaultValueArrayRetainsOrdering(JSONArray defaultValue, String[] expectedValues) {
try {
JSONObject jsonTree = new JSONObject(jsonTreeParameters.toString());
jsonTree.getJSONObject("semantics").put("maxCardinality", -1);
jsonTree.getJSONObject("value").put("default", defaultValue);
SoftwareParameter parameter = SoftwareParameter.fromJSON(jsonTree);
String[] defaultValuesArray = ServiceUtils.getStringValuesFromJsonArray(parameter.getDefaultValueAsJsonArray(), false);
for (int i = 0; i < expectedValues.length; i++) {
Assert.assertEquals(defaultValuesArray[i], expectedValues[i], "order was not preserved " +
defaultValuesArray[i] + " was expected, but " + expectedValues[i] + " was found.");
}
} catch (Exception e) {
e.printStackTrace();
Assert.fail(e.getMessage());
}
}
@DataProvider(name = "inputOntologyArrayRetainsOrderingProvider")
public Object[][] inputOntologyArrayRetainsOrderingProvider() {
String foofile = "http://sswap.org/foo.xml";
String barfile = "http://sswap.org/bar.xml";
String scatfile = "http://sswap.org/scat.xml";
return new Object[][]{
{new JSONArray(Arrays.asList(barfile, foofile, foofile)), new String[]{barfile, foofile}},
{new JSONArray(Arrays.asList(foofile, barfile, foofile)), new String[]{foofile, barfile}},
{new JSONArray(Arrays.asList(foofile, foofile, barfile)), new String[]{foofile, barfile}},
{new JSONArray(Arrays.asList(foofile, barfile, barfile)), new String[]{foofile, barfile}},
{new JSONArray(Arrays.asList(barfile, foofile, barfile)), new String[]{barfile, foofile}},
{new JSONArray(Arrays.asList(barfile, barfile, foofile)), new String[]{barfile, foofile}},
{new JSONArray(Arrays.asList(foofile, barfile, scatfile)), new String[]{foofile, barfile, scatfile}},
{new JSONArray(Arrays.asList(foofile, scatfile, barfile)), new String[]{foofile, scatfile, barfile}},
{new JSONArray(Arrays.asList(barfile, scatfile, foofile)), new String[]{barfile, scatfile, foofile}},
{new JSONArray(Arrays.asList(barfile, foofile, scatfile)), new String[]{barfile, foofile, scatfile}},
{new JSONArray(Arrays.asList(scatfile, barfile, foofile)), new String[]{scatfile, barfile, foofile}},
{new JSONArray(Arrays.asList(scatfile, foofile, barfile)), new String[]{scatfile, foofile, barfile}},
};
}
@Test(groups = "model", dataProvider = "inputOntologyArrayRetainsOrderingProvider")
public void inputOntologyArrayRetainsOrdering(JSONArray defaultValue, String[] expectedValues) {
try {
JSONObject jsonTree = new JSONObject(jsonTreeParameters.toString());
jsonTree.getJSONObject("semantics").put("ontology", defaultValue);
SoftwareParameter parameter = SoftwareParameter.fromJSON(jsonTree);
List<String> ontologies = parameter.getOntologyAsList();
for (int i = 0; i < expectedValues.length; i++) {
Assert.assertEquals(ontologies.get(i), expectedValues[i], "order was not preserved " +
ontologies.get(i) + " was expected, but " + expectedValues[i] + " was found.");
}
} catch (Exception e) {
e.printStackTrace();
Assert.fail(e.getMessage());
}
}
@DataProvider(name = "inputsFiltersRedundantValuesFromOntologyProvider")
public Object[][] inputsFiltersRedundantValuesFromOntologyProvider() {
String emptyString = "";
String foofile = "http://sswap.org/foo.xml";
String barfile = "http://sswap.org/bar.xml";
return new Object[][]{
// Single value array retains in array
{new JSONArray(List.of(emptyString)), new String[]{}, "single empty string array should be reduced to an empty ontology list"},
{new JSONArray(List.of(foofile)), new String[]{foofile}, "single string array should be retained in the resulting ontology list"},
{new JSONArray(Arrays.asList(emptyString, emptyString)), new String[]{}, "multiple empty strings should be reduced to an empty ontology list"},
{new JSONArray(Arrays.asList(emptyString, foofile)), new String[]{foofile}, "unique entries should be retained in the ontology list"},
{new JSONArray(Arrays.asList(emptyString, barfile)), new String[]{barfile}, "unique entries should be retained in the ontology list"},
{new JSONArray(Arrays.asList(foofile, emptyString)), new String[]{foofile}, "unique entries should be retained in the ontology list"},
{new JSONArray(Arrays.asList(barfile, emptyString)), new String[]{barfile}, "unique entries should be retained in the ontology list"},
{new JSONArray(Arrays.asList(foofile, emptyString, barfile)), new String[]{foofile, barfile}, "unique entries should be retained in the ontology list"},
{new JSONArray(Arrays.asList(emptyString, emptyString, emptyString)), new String[]{}, "redundant empty strings should be reduced to a single empty string in the ontology list"},
{new JSONArray(Arrays.asList(emptyString, emptyString, foofile)), new String[]{foofile}, "multiple empty strings should be removed and unique values should be retained in the ontology list"},
{new JSONArray(Arrays.asList(emptyString, emptyString, barfile)), new String[]{barfile}, "multiple empty strings should be removed and unique values should be retained in the ontology list"},
{new JSONArray(Arrays.asList(emptyString, foofile, emptyString)), new String[]{foofile}, "multiple empty strings should be removed and unique values should be retained in the ontology list"},
{new JSONArray(Arrays.asList(emptyString, barfile, emptyString)), new String[]{barfile}, "multiple empty strings should be removed and unique values should be retained in the ontology list"},
{new JSONArray(Arrays.asList(foofile, emptyString, emptyString)), new String[]{foofile}, "multiple empty strings should be removed and unique values should be retained in the ontology list"},
{new JSONArray(Arrays.asList(barfile, emptyString, emptyString)), new String[]{barfile}, "multiple empty strings should be removed and unique values should be retained in the ontology list"},
{new JSONArray(Arrays.asList(foofile, foofile)), new String[]{foofile}, "redundant strings should be reduced to a single string in the ontology list"},
{new JSONArray(Arrays.asList(foofile, foofile, foofile)), new String[]{foofile}, "redundant strings should be reduced to a single string in the ontology list"},
{new JSONArray(Arrays.asList(barfile, foofile, foofile)), new String[]{barfile, foofile}, "redundant strings should be reduced to a single string and unique values should be retained in the ontology list"},
{new JSONArray(Arrays.asList(foofile, barfile, foofile)), new String[]{foofile, barfile}, "redundant strings should be reduced to a single string and unique values should be retained in the ontology list"},
{new JSONArray(Arrays.asList(foofile, foofile, barfile)), new String[]{foofile, barfile}, "redundant strings should be reduced to a single string and unique values should be retained in the ontology list"},
{new JSONArray(Arrays.asList(barfile, barfile)), new String[]{barfile}, "redundant strings should be reduced to a single string in the ontology list"},
{new JSONArray(Arrays.asList(barfile, barfile, barfile)), new String[]{barfile}, "redundant strings should be reduced to a single string in the ontology list"},
{new JSONArray(Arrays.asList(foofile, barfile, barfile)), new String[]{foofile, barfile}, "redundant strings should be reduced to a single string and unique values should be retained in the ontology list"},
{new JSONArray(Arrays.asList(barfile, foofile, barfile)), new String[]{barfile, foofile}, "redundant strings should be reduced to a single string and unique values should be retained in the ontology list"},
{new JSONArray(Arrays.asList(barfile, barfile, foofile)), new String[]{barfile, foofile}, "redundant strings should be reduced to a single string and unique values should be retained in the ontology list"},
};
}
@Test(groups = "model", dataProvider = "inputsFiltersRedundantValuesFromOntologyProvider")
public void inputsFiltersRedundantValuesFromOntology(Object defaultValue, String[] expectedValues, String message)
throws Exception {
JSONObject jsonTree = new JSONObject(jsonTreeParameters.toString());
jsonTree.getJSONObject("semantics").put("ontology", defaultValue);
SoftwareParameter parameter = SoftwareParameter.fromJSON(jsonTree);
List<String> ontologies = parameter.getOntologyAsList();
Assert.assertEquals(expectedValues.length, ontologies.size(),
"The number of expected values after parsing the input did not match the actual values after parsing.");
for (String expectedValue : expectedValues) {
Assert.assertTrue(ontologies.contains(expectedValue), "expected value " +
expectedValue + " was not found in the default value array after parsing the input");
}
}
@DataProvider(name = "parametersDefaultValuesHonorCardinalityProvider")
public Object[][] parametersDefaultValuesHonorCardinalityProvider() {
String emptyString = "";
String nullString = null;
String foo = "foo";
return new Object[][]{
// Single value against minCardinality
{nullString, 0, -1, false, "null string should be allowed as a default value when minCardinality is zero"},
{emptyString, 0, -1, false, "empty string should be allowed as a default value when minCardinality is zero"},
{foo, 0, -1, false, "string should be as a default value allowed when minCardinality is zero"},
{nullString, 1, -1, true, "null default value should throw exception when minCardinality is 1"},
{emptyString, 1, -1, false, "empty string should be allowed as a default value when minCardinality is 1"},
{foo, 1, -1, false, "string should be as a default value allowed when minCardinality is 1"},
{nullString, 2, -1, true, "null default value should throw exception when minCardinality is 2"},
{emptyString, 2, -1, true, "empty string should throw exception when minCardinality is 2"},
{foo, 2, -1, true, "string should throw exception when minCardinality is 2"},
// Single value against maxCardinality
{nullString, 0, 0, true, "maxCardinality should not be zero"},
{nullString, 0, 1, false, "null string should be allowed as a default value when maxCardinality is 1"},
{emptyString, 0, 1, false, "empty string should be allowed as a default value when maxCardinality is 1"},
{foo, 0, 1, false, "string should be as a default value allowed when maxCardinality is 1"},
{nullString, 0, 2, false, "null string should be allowed as a default value when maxCardinality is 2"},
{emptyString, 0, 2, false, "empty string should be allowed as a default value when maxCardinality is 2"},
{foo, 0, 2, false, "string should be as a default value allowed when maxCardinality is 2"},
{foo, 0, 0, true, "maxCardinality should throw an exception if set to zero"},
// Single value array against minCardinality
{new JSONArray(Collections.singletonList(nullString)), 0, -1, false, "array with single null string should be allowed as a default value when minCardinality is zero"},
{new JSONArray(Collections.singletonList(emptyString)), 0, -1, false, "array with single empty string should be allowed as a default value when minCardinality is zero"},
{new JSONArray(Collections.singletonList(foo)), 0, -1, false, "array with single string should be as a default value allowed when minCardinality is zero"},
{new JSONArray(Collections.singletonList(foo)), 1, 0, true, "min cardinality should throw an exception if less than min cardinality"},
{new JSONArray(Collections.singletonList(nullString)), 1, -1, true, "array with single null default value should throw exception when minCardinality is 1"},
{new JSONArray(Collections.singletonList(emptyString)), 1, -1, false, "array with single empty string should be allowed as a default value when minCardinality is 1"},
{new JSONArray(Collections.singletonList(foo)), 1, -1, false, "array with single string should be as a default value allowed when minCardinality is 1"},
{new JSONArray(Collections.singletonList(nullString)), 2, -1, true, "array with single null default value should throw exception when minCardinality is 2"},
{new JSONArray(Collections.singletonList(emptyString)), 2, -1, true, "array with single empty string should throw exception when minCardinality is 2"},
{new JSONArray(Collections.singletonList(foo)), 2, -1, true, "array with single string should throw exception when minCardinality is 2"},
// Single value array against maxCardinality
{new JSONArray(Collections.singletonList(nullString)), 0, 0, true, "array with single null value should throw exception when maxCardinality is zero"},
{new JSONArray(Collections.singletonList(nullString)), 0, 1, false, "array with single null string should be allowed as a default value when maxCardinality is 1"},
{new JSONArray(Collections.singletonList(emptyString)), 0, 1, false, "array with single empty string should be allowed as a default value when maxCardinality is 1"},
{new JSONArray(Collections.singletonList(foo)), 0, 1, false, "array with single string should be as a default value allowed when maxCardinality is 1"},
{new JSONArray(Collections.singletonList(nullString)), 0, 2, false, "array with single null array should be allowed as a default value when maxCardinality is 2"},
{new JSONArray(Collections.singletonList(emptyString)), 0, 2, false, "array with single empty string should be allowed as a default value when maxCardinality is 2"},
{new JSONArray(Collections.singletonList(foo)), 0, 2, false, "array with single string should be as a default value allowed when maxCardinality is 2"},
// Multiple value array against minCardinality 0
{new JSONArray(Arrays.asList(nullString, nullString)), 0, -1, false, "array with double null string should be allowed as a default value when minCardinality is zero"},
{new JSONArray(Arrays.asList(nullString, emptyString)), 0, -1, false, "array with null and empty string string should be allowed as a default value when minCardinality is zero"},
{new JSONArray(Arrays.asList(nullString, foo)), 0, -1, false, "array with null and single string should be allowed as a default value when minCardinality is zero"},
{new JSONArray(Arrays.asList(emptyString, emptyString)), 0, -1, false, "array with double empty string should be allowed as a default value when minCardinality is zero"},
{new JSONArray(Arrays.asList(emptyString, foo)), 0, -1, false, "array with empty and string should be allowed as a default value when minCardinality is zero"},
{new JSONArray(Arrays.asList(foo, foo)), 0, -1, false, "array with double string should be allowed as a default value when minCardinality is zero"},
// Multiple value array against minCardinality 1
{new JSONArray(Arrays.asList(nullString, nullString)), 1, -1, true, "array with double null string should fail when minCardinality is 1"},
{new JSONArray(Arrays.asList(nullString, emptyString)), 1, -1, false, "array with null and empty string string should be allowed as a default value when minCardinality is 1"},
{new JSONArray(Arrays.asList(nullString, foo)), 1, -1, false, "array with null and single string should be allowed as a default value when minCardinality is 1"},
{new JSONArray(Arrays.asList(emptyString, emptyString)), 1, -1, false, "array with double empty string should be allowed as a default value when minCardinality is 1"},
{new JSONArray(Arrays.asList(emptyString, foo)), 1, -1, false, "array with empty and string should be allowed as a default value when minCardinality is 1"},
{new JSONArray(Arrays.asList(foo, foo)), 1, -1, false, "array with double string should be allowed as a default value when minCardinality is 1"},
// Multiple value array against minCardinality 3
{new JSONArray(Arrays.asList(nullString, nullString)), 3, -1, true, "array with double null string should fail when minCardinality is 3"},
{new JSONArray(Arrays.asList(nullString, emptyString)), 3, -1, true, "array with null and empty string string should fail when minCardinality is 3"},
{new JSONArray(Arrays.asList(nullString, foo)), 3, -1, true, "array with null and single string should fail when minCardinality is 3"},
{new JSONArray(Arrays.asList(emptyString, emptyString)), 3, -1, true, "array with double empty string should fail when minCardinality is 3"},
{new JSONArray(Arrays.asList(emptyString, foo)), 3, -1, true, "array with empty and string should fail when minCardinality is 3"},
{new JSONArray(Arrays.asList(foo, foo)), 3, -1, true, "array with double string should fail when minCardinality is 3"},
// Multiple value array against min and max Cardinality 1
{new JSONArray(Arrays.asList(nullString, nullString)), 1, 1, true, "array with double null string should fail when minCardinality and maxCardinality are 1"},
{new JSONArray(Arrays.asList(nullString, emptyString)), 1, 1, false, "array with null and empty string string should be allowed when minCardinality and maxCardinality are 1"},
{new JSONArray(Arrays.asList(nullString, foo)), 1, 1, false, "array with null and single string should be allowed when minCardinality and maxCardinality are 1"},
{new JSONArray(Arrays.asList(emptyString, emptyString)), 1, 1, true, "array with double empty string should fail when minCardinality and maxCardinality are 1"},
{new JSONArray(Arrays.asList(emptyString, foo)), 1, 1, true, "array with empty and string should fail when minCardinality and maxCardinality are 1"},
{new JSONArray(Arrays.asList(foo, foo)), 1, 1, true, "array with double string should fail when minCardinality and maxCardinality are 1"},
// Multiple value array against min and max Cardinality 3
{new JSONArray(Arrays.asList(nullString, nullString)), 3, 3, true, "array with double null string should fail when minCardinality and maxCardinality are 3"},
{new JSONArray(Arrays.asList(nullString, emptyString)), 3, 3, true, "array with null and empty string string should fail when minCardinality and maxCardinality are 3"},
{new JSONArray(Arrays.asList(nullString, foo)), 3, 3, true, "array with null and single string should fail when minCardinality and maxCardinality are 3"},
{new JSONArray(Arrays.asList(emptyString, emptyString)), 3, 3, true, "array with double empty string should fail when minCardinality and maxCardinality are 3"},
{new JSONArray(Arrays.asList(emptyString, foo)), 3, 3, true, "array with empty and string should fail when minCardinality and maxCardinality are 3"},
{new JSONArray(Arrays.asList(foo, foo)), 3, 3, true, "array with double string should fail when minCardinality and maxCardinality are 3"},
{new JSONArray(Collections.singletonList(nullString)), 1, -1, true, "array with single null default value should throw exception when minCardinality is 1"},
{new JSONArray(Collections.singletonList(emptyString)), 1, -1, false, "array with single empty string should be allowed as a default value when minCardinality is 1"},
{new JSONArray(Collections.singletonList(foo)), 1, -1, false, "array with single string should be as a default value allowed when minCardinality is 1"},
{new JSONArray(Collections.singletonList(nullString)), 2, -1, true, "array with single null default value should throw exception when minCardinality is 2"},
{new JSONArray(Collections.singletonList(emptyString)), 2, -1, true, "array with single empty string should throw exception when minCardinality is 2"},
{new JSONArray(Collections.singletonList(foo)), 2, -1, true, "array with single string should throw exception when minCardinality is 2"},
// Single value array against maxCardinality
{new JSONArray(Collections.singletonList(nullString)), 0, 0, true, "array with single null value should throw exception when maxCardinality is zero"},
{new JSONArray(Collections.singletonList(nullString)), 0, 1, false, "array with single null string should be allowed as a default value when maxCardinality is 1"},
{new JSONArray(Collections.singletonList(emptyString)), 0, 1, false, "array with single empty string should be allowed as a default value when maxCardinality is 1"},
{new JSONArray(Collections.singletonList(foo)), 0, 1, false, "array with single string should be as a default value allowed when maxCardinality is 1"},
{new JSONArray(Collections.singletonList(nullString)), 0, 2, false, "array with single null array should be allowed as a default value when maxCardinality is 2"},
{new JSONArray(Collections.singletonList(emptyString)), 0, 2, false, "array with single empty string should be allowed as a default value when maxCardinality is 2"},
{new JSONArray(Collections.singletonList(foo)), 0, 2, false, "array with single string should be as a default value allowed when maxCardinality is 2"},
};
}
@Test(groups = "model", dataProvider = "parametersDefaultValuesHonorCardinalityProvider")
public void parametersDefaultValuesHonorCardinality(Object defaultValue, int minCardinality, int maxCardinality, boolean shouldThrowException, String message) {
try {
JSONObject jsonTree = new JSONObject(jsonTreeParameters.toString());
jsonTree.getJSONObject("semantics").put("maxCardinality", Integer.valueOf(maxCardinality));
jsonTree.getJSONObject("semantics").put("minCardinality", Integer.valueOf(minCardinality));
jsonTree.getJSONObject("value").put("default", defaultValue);
Assert.assertNotNull(SoftwareParameter.fromJSON(jsonTree), message);
} catch (Throwable e) {
Assert.assertTrue(shouldThrowException, message);
// } catch (Throwable e) {
// Assert.assertTrue(shouldThrowException, message);
}
}
@Test(groups = "model")
public void softwareParameterEnumeratedValueCloneCopiesEverything() {
SoftwareParameter param = new SoftwareParameter();
param.setId(1L);
SoftwareParameterEnumeratedValue enumValue = new SoftwareParameterEnumeratedValue("alpha", "The alpha parameter", param);
SoftwareParameterEnumeratedValue clonedEnumValue = enumValue.clone();
Assert.assertEquals(clonedEnumValue.getLabel(), enumValue.getLabel(), "label attribute was not cloned from one software parameter enum value to another");
Assert.assertEquals(clonedEnumValue.getValue(), enumValue.getValue(), "value attribute was not cloned from one software parameter enum value to another");
Assert.assertNull(clonedEnumValue.getSoftwareParameter(), "softwareParameter should not be cloned from one software parameter enum value to another");
}
@Test(groups = "model")
public void parameterCloneCopiesEverything() {
try {
// create a software object for the original parameter's reference
Software software = new Software();
software.setId(1L);
// set fields to positive values to ensure we do not get false positives during clone.
SoftwareParameter param = new SoftwareParameter();
param.setId(1L);
param.setArgument("fooargument");
param.setEnquote(true);
param.addEnumValue(new SoftwareParameterEnumeratedValue("alpha", "The alpha parameter", param));
param.addEnumValue(new SoftwareParameterEnumeratedValue("beta", "The beta parameter", param));
param.addEnumValue(new SoftwareParameterEnumeratedValue("gamma", "The gamma parameter", param));
param.setKey("fookey");
param.setLabel("foolabel");
param.setMaxCardinality(12);
param.setMinCardinality(1);
param.setOntology(new JSONArray().put("xs:string").put("xs:foo").toString());
param.setOrder(6);
param.setRepeatArgument(true);
param.setRequired(false);
param.setShowArgument(true);
param.setSoftware(software);
param.setType(SoftwareParameterType.enumeration);
param.setValidator(".*");
param.setVisible(false);
software.addParameter(param);
// create a new software object to assign during the clone
Software clonedSoftware = new Software();
clonedSoftware.setId(2L);
// run the clone
SoftwareParameter clonedParameter = param.clone(clonedSoftware);
// validate every field was copied
Assert.assertEquals(clonedParameter.getArgument(), param.getArgument(), "Argument was not cloned from one software parameter to another");
Assert.assertEquals(clonedParameter.getDefaultValueAsJsonArray().toString(), param.getDefaultValueAsJsonArray().toString(), "defaultValue attribute was not cloned from one software parameter to another");
Assert.assertEquals(clonedParameter.getDescription(), param.getDescription(), "description attribute was not cloned from one software parameter to another");
Assert.assertEquals(clonedParameter.isEnquote(), param.isEnquote(), "enquote attribute was not cloned from one software parameter to another");
Assert.assertNull(clonedParameter.getId(), "id attribute should not be cloned from one software parameter to another");
Assert.assertEquals(clonedParameter.getKey(), param.getKey(), "key attribute was not cloned from one software parameter to another");
Assert.assertEquals(clonedParameter.getLabel(), param.getLabel(), "lable attribute was not cloned from one software parameter to another");
Assert.assertEquals(clonedParameter.getMaxCardinality(), param.getMaxCardinality(), "maxCardinality attribute was not cloned from one software parameter to another");
Assert.assertEquals(clonedParameter.getMinCardinality(), param.getMinCardinality(), "minCardinality attribute was not cloned from one software parameter to another");
Assert.assertTrue(CollectionUtils.isEqualCollection(clonedParameter.getOntologyAsList(), param.getOntologyAsList()), "ontology attribute was not cloned from one software parameter to another");
Assert.assertEquals(clonedParameter.getOrder(), param.getOrder(), "order attribute was not cloned from one software parameter to another");
Assert.assertEquals(clonedParameter.isRepeatArgument(), param.isRepeatArgument(), "repeatArgument attribute was not cloned from one software parameter to another");
Assert.assertEquals(clonedParameter.isRequired(), param.isRequired(), "required attribute was not cloned from one software parameter to another");
Assert.assertEquals(clonedParameter.isShowArgument(), param.isShowArgument(), "showArgument attribute was not cloned from one software parameter to another");
Assert.assertNotNull(clonedParameter.getSoftware(), "Sofware reference was not cloned from one software parameter to another");
Assert.assertEquals(clonedParameter.getSoftware().getId(), clonedSoftware.getId(), "Wrong software reference was not cloned from one software parameter to another");
Assert.assertEquals(clonedParameter.getType(), param.getType(), "parameter type attribute was not cloned from one software parameter to another");
Assert.assertEquals(clonedParameter.isVisible(), param.isVisible(), "visible attribute was not cloned from one software parameter to another");
Assert.assertEquals(clonedParameter.getValidator(), param.getValidator(), "Argument was not cloned from one software parameter to another");
Assert.assertTrue(CollectionUtils.isEqualCollection(clonedParameter.getEnumValues(), param.getEnumValues()), "enumValues attribute was not cloned from one software parameter to another");
for (SoftwareParameterEnumeratedValue enumValue : clonedParameter.getEnumValues()) {
Assert.assertNotNull(enumValue.getSoftwareParameter(), "software parameter association should be present in all software parameter enum values after clone");
Assert.assertEquals(enumValue.getSoftwareParameter(), clonedParameter, "enum value should reference the cloned software parameter, not the original after cloneing a software parameter");
}
// do a sanity check by serializing the json as well
Assert.assertEquals(param.toJSON(), clonedParameter.toJSON(), "cloned parameter serialized to different value than original parameter.");
} catch (Exception e) {
Assert.fail("Cloning software parameter should not throw exception", e);
}
}
// @Test (groups="model", dataProvider="inputsFiltersRedundantValuesFromOntologyProvider")
// public void inputsFiltersRedundantValuesFromFileTypes(Object defaultValue, String[] expectedValues, String message)
// throws Exception
// {
// JSONObject jsonTree = new JSONObject(jsonTreeParameters.toString());
// jsonTree.getJSONObject("semantics").put("fileTypes", defaultValue);
// SoftwareParameter parameter = SoftwareParameter.fromJSON(jsonTree);
//
// List<String> filesTypes = parameter.getFileTypesAsList();
//
// Assert.assertEquals(expectedValues.length, filesTypes.size(),
// "The number of expected values after parsing the input did not match the actual values after parsing.");
//
// for(String expectedValue: expectedValues)
// {
// Assert.assertTrue(filesTypes.contains(expectedValue), "expected value " +
// expectedValue + " was not found in the default value array after parsing the input");
// }
// }
}
|
3e07000682154d83e91a4abe5403f23105f20876 | 2,114 | java | Java | java/compiler/impl/src/com/intellij/packaging/impl/elements/TestModuleOutputElementType.java | teddywest32/intellij-community | e0268d7a1da1d318b441001448cdd3e8929b2f29 | [
"Apache-2.0"
] | 2 | 2018-12-29T09:53:39.000Z | 2018-12-29T09:53:42.000Z | java/compiler/impl/src/com/intellij/packaging/impl/elements/TestModuleOutputElementType.java | tnorbye/intellij-community | f01cf262fc196bf4dbb99e20cd937dee3705a7b6 | [
"Apache-2.0"
] | null | null | null | java/compiler/impl/src/com/intellij/packaging/impl/elements/TestModuleOutputElementType.java | tnorbye/intellij-community | f01cf262fc196bf4dbb99e20cd937dee3705a7b6 | [
"Apache-2.0"
] | 1 | 2019-07-18T16:50:52.000Z | 2019-07-18T16:50:52.000Z | 36.448276 | 118 | 0.793756 | 2,961 | /*
* Copyright 2000-2011 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.packaging.impl.elements;
import com.intellij.openapi.compiler.CompilerBundle;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModulePointer;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ui.configuration.ModulesProvider;
import com.intellij.util.PlatformIcons;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.jps.model.java.JavaModuleSourceRootTypes;
import javax.swing.*;
/**
* @author nik
*/
public class TestModuleOutputElementType extends ModuleOutputElementTypeBase<TestModuleOutputPackagingElement> {
public static final TestModuleOutputElementType ELEMENT_TYPE = new TestModuleOutputElementType();
public TestModuleOutputElementType() {
super("module-test-output", CompilerBundle.message("element.type.name.module.test.output"));
}
@NotNull
@Override
public TestModuleOutputPackagingElement createEmpty(@NotNull Project project) {
return new TestModuleOutputPackagingElement(project);
}
protected ModuleOutputPackagingElementBase createElement(@NotNull Project project, @NotNull ModulePointer pointer) {
return new TestModuleOutputPackagingElement(project, pointer);
}
@Override
public Icon getCreateElementIcon() {
return PlatformIcons.TEST_SOURCE_FOLDER;
}
public boolean isSuitableModule(ModulesProvider modulesProvider, Module module) {
return !modulesProvider.getRootModel(module).getSourceRoots(JavaModuleSourceRootTypes.TESTS).isEmpty();
}
}
|
3e070009d27db115c8fe4f2e9e7097d85eb10fc0 | 2,230 | java | Java | src/main/java/com/ultracart/admin/v2/swagger/ProgressResponseBody.java | UltraCart/rest_api_v2_sdk_java | aff5ac367c25a663209d32e8ec6d4c069917b1dc | [
"Apache-2.0"
] | null | null | null | src/main/java/com/ultracart/admin/v2/swagger/ProgressResponseBody.java | UltraCart/rest_api_v2_sdk_java | aff5ac367c25a663209d32e8ec6d4c069917b1dc | [
"Apache-2.0"
] | 1 | 2021-02-06T14:31:50.000Z | 2021-02-06T14:31:50.000Z | src/main/java/com/ultracart/admin/v2/swagger/ProgressResponseBody.java | UltraCart/rest_api_v2_sdk_java | aff5ac367c25a663209d32e8ec6d4c069917b1dc | [
"Apache-2.0"
] | null | null | null | 29.012987 | 104 | 0.655327 | 2,962 | /*
* UltraCart Rest API V2
* UltraCart REST API Version 2
*
* OpenAPI spec version: 2.0.0
* Contact: nnheo@example.com
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package com.ultracart.admin.v2.swagger;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.ResponseBody;
import java.io.IOException;
import okio.Buffer;
import okio.BufferedSource;
import okio.ForwardingSource;
import okio.Okio;
import okio.Source;
public class ProgressResponseBody extends ResponseBody {
public interface ProgressListener {
void update(long bytesRead, long contentLength, boolean done);
}
private final ResponseBody responseBody;
private final ProgressListener progressListener;
private BufferedSource bufferedSource;
public ProgressResponseBody(ResponseBody responseBody, ProgressListener progressListener) {
this.responseBody = responseBody;
this.progressListener = progressListener;
}
@Override
public MediaType contentType() {
return responseBody.contentType();
}
@Override
public long contentLength() throws IOException {
return responseBody.contentLength();
}
@Override
public BufferedSource source() throws IOException {
if (bufferedSource == null) {
bufferedSource = Okio.buffer(source(responseBody.source()));
}
return bufferedSource;
}
private Source source(Source source) {
return new ForwardingSource(source) {
long totalBytesRead = 0L;
@Override
public long read(Buffer sink, long byteCount) throws IOException {
long bytesRead = super.read(sink, byteCount);
// read() returns the number of bytes read, or -1 if this source is exhausted.
totalBytesRead += bytesRead != -1 ? bytesRead : 0;
progressListener.update(totalBytesRead, responseBody.contentLength(), bytesRead == -1);
return bytesRead;
}
};
}
}
|
3e07003c09e31d7142fbed893d1681601fcd4b94 | 1,819 | java | Java | momas-deliver-mgr/momas-deliver-mgr-webservice/src/main/java/cc/momas/customer/ws/QueryAllShopsByAssociateResponse.java | Sod-Momas/momas-project | 1372b15c2f2d78560e688acaff65e43dc7643a1b | [
"Apache-2.0"
] | null | null | null | momas-deliver-mgr/momas-deliver-mgr-webservice/src/main/java/cc/momas/customer/ws/QueryAllShopsByAssociateResponse.java | Sod-Momas/momas-project | 1372b15c2f2d78560e688acaff65e43dc7643a1b | [
"Apache-2.0"
] | null | null | null | momas-deliver-mgr/momas-deliver-mgr-webservice/src/main/java/cc/momas/customer/ws/QueryAllShopsByAssociateResponse.java | Sod-Momas/momas-project | 1372b15c2f2d78560e688acaff65e43dc7643a1b | [
"Apache-2.0"
] | null | null | null | 25.985714 | 117 | 0.633865 | 2,963 |
package cc.momas.customer.ws;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>queryAllShopsByAssociateResponse complex type的 Java 类。
*
* <p>以下模式片段指定包含在此类中的预期内容。
*
* <pre>
* <complexType name="queryAllShopsByAssociateResponse">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="return" type="{http://ws.customer.momas.cc/}shops" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "queryAllShopsByAssociateResponse", propOrder = {
"_return"
})
public class QueryAllShopsByAssociateResponse {
@XmlElement(name = "return")
protected List<Shops> _return;
/**
* Gets the value of the return property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the return property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getReturn().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link Shops }
*
*
*/
public List<Shops> getReturn() {
if (_return == null) {
_return = new ArrayList<Shops>();
}
return this._return;
}
}
|
3e07007a60b89eadbc400173305d13257ac09c1c | 13,249 | java | Java | PhotoChop/app/src/main/java/es/molestudio/photochop/controller/activity/MainActivity.java | ChusSenosiain/PhotoChop | 1e7db17278818b0d183e5fbe5e16f21097ea6e64 | [
"Apache-2.0"
] | null | null | null | PhotoChop/app/src/main/java/es/molestudio/photochop/controller/activity/MainActivity.java | ChusSenosiain/PhotoChop | 1e7db17278818b0d183e5fbe5e16f21097ea6e64 | [
"Apache-2.0"
] | null | null | null | PhotoChop/app/src/main/java/es/molestudio/photochop/controller/activity/MainActivity.java | ChusSenosiain/PhotoChop | 1e7db17278818b0d183e5fbe5e16f21097ea6e64 | [
"Apache-2.0"
] | null | null | null | 32.957711 | 118 | 0.656502 | 2,964 | package es.molestudio.photochop.controller.activity;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.provider.MediaStore;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.getbase.floatingactionbutton.FloatingActionButton;
import com.getbase.floatingactionbutton.FloatingActionsMenu;
import com.parse.ParseUser;
import es.molestudio.photochop.R;
import es.molestudio.photochop.View.AppTextView;
import es.molestudio.photochop.controller.ImageManagerImpl;
import es.molestudio.photochop.controller.LoginManager;
import es.molestudio.photochop.controller.LoginManagerWrap;
import es.molestudio.photochop.controller.adapter.ADPDrawer;
import es.molestudio.photochop.controller.fragment.GridFragment;
import es.molestudio.photochop.controller.fragment.SignInFragment;
import es.molestudio.photochop.controller.location.MyLocation;
import es.molestudio.photochop.controller.util.Log;
import es.molestudio.photochop.model.ObjectDrawerItem;
import es.molestudio.photochop.model.User;
public class MainActivity extends ActionBarActivity
implements View.OnClickListener,
ListView.OnItemClickListener,
MyLocation.ChangeLocationListener,
LoginManager.LoginActionListener {
private static final int RQ_CAPTURE_IMAGE = 1001;
private Location mLocation;
private MyLocation mMyLocation;
private DrawerLayout mDrawerLayout;
private LinearLayout mDrawerLinearLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private FloatingActionsMenu mFloatingActionsMenu;
private GridFragment mGridFragment;
private ImageView mIvUserImage;
private AppTextView mtvUserName;
private AppTextView mtvSubtitle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up toolbar as actionbar
Toolbar toolbar = (Toolbar) findViewById(R.id.tb_toolbar);
setSupportActionBar(toolbar);
// Set up toolbar
ActionBar actionBar = getSupportActionBar();
actionBar.setTitle(getString(R.string.app_name));
// enable ActionBar app icon to behave as action to toggle nav drawer
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayShowCustomEnabled(true);
View view = getLayoutInflater().inflate(R.layout.action_bar_title_center, null);
TextView tvTitle = (TextView) view.findViewById(R.id.tv_title);
tvTitle.setText(getString(R.string.title_main_action_bar));
actionBar.setCustomView(view);
// Show the grid
FragmentManager manager = getSupportFragmentManager();
mGridFragment = (GridFragment) manager.findFragmentById(R.id.fragment_holder);
if (mGridFragment == null) {
mGridFragment = (GridFragment) GridFragment.newInstance(null);
manager.beginTransaction()
.add(R.id.fragment_holder, mGridFragment)
.commit();
}
// Set up the drawer
// Left Drawer items
configLeftDrawer();
mFloatingActionsMenu = (FloatingActionsMenu) findViewById(R.id.multiple_actions);
FloatingActionButton btnCamera = (FloatingActionButton) findViewById(R.id.btn_new_photo);
FloatingActionButton btnImportFromGallery = (FloatingActionButton) findViewById(R.id.btn_import_from_gallery);
btnCamera.setOnClickListener(this);
btnImportFromGallery.setOnClickListener(this);
mDrawerList.setOnItemClickListener(this);
}
/**
* Go to gallery: the default intent for choose an image doesn't allow to choose multiple images
* we have to create a custom selectable gallery
*/
private void importFromGallery() {
mFloatingActionsMenu.collapse();
Intent imageGallery = new Intent(this, GalleryActivity.class);
startActivityForResult(imageGallery, GalleryActivity.RQ_SELECT_IMAGE);
}
/**
* Take a photo
*/
private void takePhoto() {
mFloatingActionsMenu.collapse();
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, RQ_CAPTURE_IMAGE);
mMyLocation = new MyLocation(this, this);
}
/**
* About intent
*/
private void showAbout() {
Intent aboutIntent = new Intent(MainActivity.this, AboutActivity.class);
startActivity(aboutIntent);
}
/**
* Load user data on drawer
*/
private void loadUserData() {
if (ParseUser.getCurrentUser() != null) {
mtvUserName.setText(ParseUser.getCurrentUser().getString("nickname"));
mtvSubtitle.setText("");
} else {
mtvUserName.setText(getString(R.string.tv_user_nickname_default));
mtvSubtitle.setText(getString(R.string.app_name));
Drawable drawable = getResources().getDrawable(R.drawable.ic_account_circle_white_48dp);
drawable.setColorFilter(getResources().getColor(R.color.light_primary_color), PorterDuff.Mode.MULTIPLY);
mIvUserImage.setImageDrawable(drawable);
}
}
/**
* Config drawer
*/
private void configLeftDrawer() {
// User Data frame layout
mIvUserImage = (ImageView) findViewById(R.id.iv_user_image);
mtvUserName = (AppTextView) findViewById(R.id.tv_user_nickname);
mtvSubtitle = (AppTextView) findViewById(R.id.tv_subtitle);
RelativeLayout rlUserData = (RelativeLayout) findViewById(R.id.user_data_holder);
rlUserData.setOnClickListener(this);
loadUserData();
// List items
String[] drawerMenuItems = getResources().getStringArray(R.array.drawer_main_items);
ObjectDrawerItem[] drawerItems = new ObjectDrawerItem[drawerMenuItems.length];
drawerItems[0] = new ObjectDrawerItem(R.drawable.ic_settings_white_24dp, drawerMenuItems[0]);
drawerItems[1] = new ObjectDrawerItem(R.drawable.ic_help_white_24dp, drawerMenuItems[1]);
drawerItems[2] = new ObjectDrawerItem(R.drawable.ic_exit_to_app_white_24dp, drawerMenuItems[2]);
ADPDrawer adpDrawer = new ADPDrawer(this, drawerItems);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerLinearLayout = (LinearLayout) findViewById(R.id.left_drawer);
mDrawerList = (ListView) findViewById(R.id.list_view_drawer);
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
mDrawerList.setAdapter(adpDrawer);
mDrawerToggle = new ActionBarDrawerToggle(this,
mDrawerLayout,
R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View view) {
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
/**
* If the user is logged, go to user config.
* If the user isn't logged, go to loggin page
*/
private void userConfig() {
mDrawerLayout.closeDrawer(mDrawerLinearLayout);
ParseUser parseUser = ParseUser.getCurrentUser();
if (parseUser == null) {
Intent logginIntent = new Intent(MainActivity.this, LogInActivity.class);
startActivityForResult(logginIntent, LogInActivity.RQ_LOGGIN);
} else {
//Intent userInfo = new Intent(MainActivity.this, UserConfigActivity.class);
//startActivity(userInfo);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK && data != null) {
// Photo
if (requestCode == RQ_CAPTURE_IMAGE) {
finishLocationService();
new ImageManagerImpl(this).saveNewImageOnBD(data.getData(), mLocation);
mGridFragment.updateImagesFromBD(true);
}
// Import Image(s) from gallery
else if (requestCode == GalleryActivity.RQ_SELECT_IMAGE) {
boolean newImages = data.getBooleanExtra(GridFragment.NEW_IMAGES_ON_BD, false);
if (newImages){
mGridFragment.updateImagesFromBD(true);
}
} else if (requestCode == LogInActivity.RQ_LOGGIN) {
boolean loginOK = data.getBooleanExtra(SignInFragment.LOGIN_OK, false);
if (loginOK) {
loadUserData();
}
}
}
}
/**
* Finish the location service
*/
private void finishLocationService() {
if (mMyLocation != null) {
mMyLocation.stopLocationService();
}
}
/**
* Logout
*/
private void logOut() {
if (ParseUser.getCurrentUser() != null) {
LoginManagerWrap.getLoginManager(this).signOut(this);
} else {
Toast.makeText(this, getString(R.string.message_logout_with_no_loggin), Toast.LENGTH_SHORT).show();
}
}
/**
* Select item from drawer
* @param position
*/
private void selectItem(int position) {
mDrawerList.setItemChecked(position, true);
mDrawerLayout.closeDrawer(mDrawerLinearLayout);
}
@Override
protected void onDestroy() {
super.onDestroy();
finishLocationService();
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
////////////////////////////////////////////////////////////////////
// INTERFACE IMPLEMENTATION
////////////////////////////////////////////////////////////////////
// View.OnClickListener
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_new_photo:
// Camera intent
takePhoto();
break;
case R.id.btn_import_from_gallery:
// Gallery intent
importFromGallery();
break;
case R.id.user_data_holder:
// User config or login
userConfig();
break;
}
}
// MyLocation.ChangeLocationListener
@Override
public void onLocationChanged(Location location) {
mLocation = location;
Log.d("Location received " + location.getLatitude() + " " + location.getLongitude());
}
// ListView.OnItemClickListener
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
switch (position) {
// TODO: Preferences
case 0:
Toast.makeText(this, "Under Construction :)", Toast.LENGTH_LONG).show();
break;
// About
case 1:
showAbout();
break;
// Logout
case 2:
logOut();
break;
}
}
// LoginManager.LoginActionListener (for logout)
@Override
public void onDone(User user, Exception error) {
if (error == null) {
loadUserData();
Toast.makeText(this, getString(R.string.user_logout_ok), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, getString(R.string.user_logout_error), Toast.LENGTH_SHORT).show();
}
}
}
|
3e0700f048a04c48f000ce6e630bd8095260932b | 302 | java | Java | app/src/main/java/au/com/wallaceit/voicemail/mailstore/migrations/MigrationTo53.java | ajobbins/visualvoicemail | 696a710dc6f6b7be861c259ce9520e82c9333013 | [
"BSD-3-Clause"
] | 8 | 2016-07-21T05:30:29.000Z | 2021-08-04T17:28:02.000Z | app/src/main/java/au/com/wallaceit/voicemail/mailstore/migrations/MigrationTo53.java | ajobbins/visualvoicemail | 696a710dc6f6b7be861c259ce9520e82c9333013 | [
"BSD-3-Clause"
] | null | null | null | app/src/main/java/au/com/wallaceit/voicemail/mailstore/migrations/MigrationTo53.java | ajobbins/visualvoicemail | 696a710dc6f6b7be861c259ce9520e82c9333013 | [
"BSD-3-Clause"
] | 8 | 2016-07-06T10:40:40.000Z | 2020-02-22T22:25:56.000Z | 25.166667 | 90 | 0.774834 | 2,965 | package au.com.wallaceit.voicemail.mailstore.migrations;
import android.database.sqlite.SQLiteDatabase;
class MigrationTo53 {
public static void removeNullValuesFromEmptyColumnInMessagesTable(SQLiteDatabase db) {
db.execSQL("UPDATE messages SET empty = 0 WHERE empty IS NULL");
}
}
|
3e0701e12e9a88f1e9e1fbb459a57b91e30ab068 | 2,581 | java | Java | waf/src/main/java/com/jdcloud/sdk/service/waf/model/EnableReq.java | jdcloud-apigateway/jdcloud-sdk-java | 62e0924aa4b7f51fc8d73404bdc7aa38d820732e | [
"Apache-2.0"
] | 38 | 2018-04-19T09:53:59.000Z | 2021-11-08T12:52:15.000Z | waf/src/main/java/com/jdcloud/sdk/service/waf/model/EnableReq.java | jdcloud-apigateway/jdcloud-sdk-java | 62e0924aa4b7f51fc8d73404bdc7aa38d820732e | [
"Apache-2.0"
] | 22 | 2018-04-24T12:17:20.000Z | 2022-03-31T10:39:18.000Z | waf/src/main/java/com/jdcloud/sdk/service/waf/model/EnableReq.java | jdcloud-apigateway/jdcloud-sdk-java | 62e0924aa4b7f51fc8d73404bdc7aa38d820732e | [
"Apache-2.0"
] | 53 | 2018-04-19T10:48:05.000Z | 2022-03-16T09:15:16.000Z | 17.923611 | 76 | 0.574583 | 2,966 | /*
* Copyright 2018 JDCLOUD.COM
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http:#www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*
*
*
* Contact:
*
* NOTE: This class is auto generated by the jdcloud code generator program.
*/
package com.jdcloud.sdk.service.waf.model;
import com.jdcloud.sdk.annotation.Required;
/**
* enableReq
*/
public class EnableReq implements java.io.Serializable {
private static final long serialVersionUID = 1L;
/**
* WAF实例id
* Required:true
*/
@Required
private String wafInstanceId;
/**
* 域名
* Required:true
*/
@Required
private String domain;
/**
* 是否使能,0表示否
* Required:true
*/
@Required
private Integer enable;
/**
* get WAF实例id
*
* @return
*/
public String getWafInstanceId() {
return wafInstanceId;
}
/**
* set WAF实例id
*
* @param wafInstanceId
*/
public void setWafInstanceId(String wafInstanceId) {
this.wafInstanceId = wafInstanceId;
}
/**
* get 域名
*
* @return
*/
public String getDomain() {
return domain;
}
/**
* set 域名
*
* @param domain
*/
public void setDomain(String domain) {
this.domain = domain;
}
/**
* get 是否使能,0表示否
*
* @return
*/
public Integer getEnable() {
return enable;
}
/**
* set 是否使能,0表示否
*
* @param enable
*/
public void setEnable(Integer enable) {
this.enable = enable;
}
/**
* set WAF实例id
*
* @param wafInstanceId
*/
public EnableReq wafInstanceId(String wafInstanceId) {
this.wafInstanceId = wafInstanceId;
return this;
}
/**
* set 域名
*
* @param domain
*/
public EnableReq domain(String domain) {
this.domain = domain;
return this;
}
/**
* set 是否使能,0表示否
*
* @param enable
*/
public EnableReq enable(Integer enable) {
this.enable = enable;
return this;
}
} |
3e0702c676cb7ec7bbc154f882eb8ee11b4181e7 | 578 | java | Java | POSNirvanaORM/src/com/nirvanaxp/types/entities/catalog/items/ItemsToItemsChar_.java | apoorva223054/SF3 | 4dab425963cf35481d2a386782484b769df32986 | [
"Apache-2.0"
] | null | null | null | POSNirvanaORM/src/com/nirvanaxp/types/entities/catalog/items/ItemsToItemsChar_.java | apoorva223054/SF3 | 4dab425963cf35481d2a386782484b769df32986 | [
"Apache-2.0"
] | null | null | null | POSNirvanaORM/src/com/nirvanaxp/types/entities/catalog/items/ItemsToItemsChar_.java | apoorva223054/SF3 | 4dab425963cf35481d2a386782484b769df32986 | [
"Apache-2.0"
] | null | null | null | 41.285714 | 80 | 0.847751 | 2,967 | package com.nirvanaxp.types.entities.catalog.items;
import com.nirvanaxp.types.entities.POSNirvanaBaseClass_;
import javax.annotation.Generated;
import javax.persistence.metamodel.SingularAttribute;
import javax.persistence.metamodel.StaticMetamodel;
@Generated(value="Dali", date="2019-03-25T12:57:24.326+0530")
@StaticMetamodel(ItemsToItemsChar.class)
public class ItemsToItemsChar_ extends POSNirvanaBaseClass_ {
public static volatile SingularAttribute<ItemsToItemsChar, String> itemsCharId;
public static volatile SingularAttribute<ItemsToItemsChar, String> itemsId;
}
|
3e0704ff8b1bcf316c1db8f081d40ece74e8e66f | 732 | java | Java | runtime/src/main/java/io/micronaut/discovery/cloud/gcp/package-info.java | dancegit/micronaut-core | 762cfe087d6ab68e4c7fa52d770fefeddb30f8cd | [
"Apache-2.0"
] | 1 | 2020-06-20T02:01:35.000Z | 2020-06-20T02:01:35.000Z | runtime/src/main/java/io/micronaut/discovery/cloud/gcp/package-info.java | dancegit/micronaut-core | 762cfe087d6ab68e4c7fa52d770fefeddb30f8cd | [
"Apache-2.0"
] | 969 | 2020-09-18T02:03:38.000Z | 2022-03-31T02:04:27.000Z | runtime/src/main/java/io/micronaut/discovery/cloud/gcp/package-info.java | dancegit/micronaut-core | 762cfe087d6ab68e4c7fa52d770fefeddb30f8cd | [
"Apache-2.0"
] | 1 | 2021-01-29T10:12:49.000Z | 2021-01-29T10:12:49.000Z | 30.5 | 75 | 0.736339 | 2,968 | /*
* Copyright 2017-2020 original authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Google Compute cloud configuration.
*
* @author graemerocher
* @since 1.0
*/
package io.micronaut.discovery.cloud.gcp;
|
3e07064ce753a4776460a1030b297d864d0043a4 | 9,281 | java | Java | core/src/com/unlucky/inventory/Item.java | begumerkal/PROJEM23 | 4b472172c1a341587fff644e8626116da532cf4c | [
"MIT"
] | 173 | 2018-05-31T02:41:11.000Z | 2022-03-21T16:39:53.000Z | core/src/com/unlucky/inventory/Item.java | begumerkal/PROJEM23 | 4b472172c1a341587fff644e8626116da532cf4c | [
"MIT"
] | 23 | 2018-01-07T19:51:25.000Z | 2018-07-02T19:16:47.000Z | core/src/com/unlucky/inventory/Item.java | begumerkal/PROJEM23 | 4b472172c1a341587fff644e8626116da532cf4c | [
"MIT"
] | 69 | 2018-05-07T09:27:13.000Z | 2022-03-26T20:31:27.000Z | 29.463492 | 144 | 0.541644 | 2,969 | package com.unlucky.inventory;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.unlucky.resource.ResourceManager;
import com.unlucky.resource.Util;
/**
* An Item is held by an inventory slot and can be one of:
* - potion (restores current hp)
* - equip (several categories of equips)
* - misc (some other useless thing)
*
* @author Ming Li
*/
public class Item {
// id
public String name;
// name displayed on tooltip
public String labelName;
// for rendering onto tooltip
public String desc;
// type of item
/**
* 0 - potion
* 1 - misc
* 2 - helmet
* 3 - armor
* 4 - weapon
* 5 - gloves
* 6 - shoes
* 7 - necklace
* 8 - shield
* 9 - ring
* 10 - enchant scroll
*/
public int type;
/**
* items are weighted with rarity meaning
* different likelihoods to drop
* 0 - common (60% chance out of all items)
* 1 - rare (25% chance)
* 2 - epic (10% chance)
* 3 - legendary (5% chance)
*/
public int rarity;
// the range of enemy levels that can drop this item
public int minLevel;
public int maxLevel;
// item stats
// if hp is negative then its absolute value is the percentage hp that the item gives
// used to separate percentage hp from regular hp potions
public int hp = 0;
public int mhp = 0;
public int dmg = 0;
public int acc = 0;
public int sell = 0;
// potions can give exp (percentage)
public int exp = 0;
// an item's index in the inventory
public int index;
// whether or not this item is equipped
public boolean equipped = false;
// the number of successful enchants on the item
public int enchants = 0;
public int enchantCost;
// percentage bonus enchant chance from scrolls
public int bonusEnchantChance = 0;
// for enchant scrolls representing the bonus enchant percentage that the scroll gives
public int eChance = 0;
// rendering
public Image actor;
public int imgIndex;
/**
* For potions
* Only can be consumed for hp or sold for gold
*
* @param name
* @param desc
* @param rarity
* @param imgIndex for textureregion in spritesheet
* @param hp
* @param sell
*/
public Item(ResourceManager rm, String name, String desc, int rarity, int imgIndex, int minLevel, int maxLevel, int hp, int exp, int sell) {
this.name = name;
this.desc = desc;
this.rarity = rarity;
this.imgIndex = imgIndex;
this.minLevel = minLevel;
this.maxLevel = maxLevel;
this.hp = hp;
this.exp = exp;
this.sell = sell;
type = 0;
actor = new Image(rm.items20x20[0][imgIndex]);
labelName = name;
}
/**
* For misc items
* Only can be sold for gold
*
* @param name
* @param desc
* @param rarity
* @param imgIndex
* @param sell
*/
public Item(ResourceManager rm, String name, String desc, int rarity, int imgIndex, int minLevel, int maxLevel, int sell) {
this.name = name;
this.desc = desc;
this.rarity = rarity;
this.imgIndex = imgIndex;
this.minLevel = minLevel;
this.maxLevel = maxLevel;
this.sell = sell;
type = 1;
actor = new Image(rm.items20x20[1][imgIndex]);
labelName = name;
}
/**
* For all types of equips
* Gives increased stats and can be sold for gold
*
* @param name
* @param desc
* @param type
* @param rarity
* @param imgIndex
* @param mhp
* @param dmg
* @param acc
* @param sell
*/
public Item(ResourceManager rm, String name, String desc, int type, int rarity, int imgIndex, int minLevel, int maxLevel,
int mhp, int dmg, int acc, int sell) {
this.name = name;
this.desc = desc;
this.type = type;
this.rarity = rarity;
this.imgIndex = imgIndex;
this.minLevel = minLevel;
this.maxLevel = maxLevel;
this.mhp = mhp;
this.dmg = dmg;
this.acc = acc;
this.sell = sell;
actor = new Image(rm.items20x20[type][imgIndex]);
labelName = name;
}
/**
* For enchant scrolls
*
* @param rm
* @param name
* @param desc
* @param rarity
* @param imgIndex
* @param eChance
* @param sell
*/
public Item(ResourceManager rm, String name, String desc, int rarity, int imgIndex, int minLevel, int maxLevel, int eChance, int sell) {
this.name = name;
this.desc = desc;
this.rarity = rarity;
this.imgIndex = imgIndex;
this.minLevel = minLevel;
this.maxLevel = maxLevel;
this.eChance = eChance;
this.sell = sell;
type = 10;
actor = new Image(rm.items20x20[10][imgIndex]);
labelName = name;
}
/**
* Adjusts the stats/attributes of an Item based on a given level
* Only called once per item's existence
*
* @param level
*/
public void adjust(int level) {
// max hp will be scaled by 5-7 parts of original item stat added on each level
// dmg is scaled 4-6 parts of original per level
int mhpSeed = mhp / MathUtils.random(5, 7);
int dmgSeed = dmg / MathUtils.random(4, 6);
// set initial enchant cost
int enchantSeed = MathUtils.random(50, 100);
int sellSeed = sell / MathUtils.random(10, 15);
for (int i = 0; i < level - 1; i++) {
mhp += mhpSeed;
dmg += dmgSeed;
sell += sellSeed;
}
for (int i = 0; i < level; i++) {
enchantCost += enchantSeed;
}
}
/**
* Returns the full description with all stats and descriptions
* concatenated into a single string
*
* @return
*/
public String getFullDesc() {
String ret = "";
if (type == 0) {
// percentage hp potions
if (hp < 0) ret = desc + "\nRECOVER " + -hp + "% OF HP";
// exp potions
else if (exp > 0) ret = desc + "\nGIVES " + exp + "% EXP";
else ret = desc + "\nHEALS FOR " + hp + " HP";
ret += "\n\ndouble tap to consume";
} else if (type == 1) {
ret = desc;
} else if (type >= 2 && type <= 9) {
ret = desc + "\n";
if (mhp != 0) ret += "+" + mhp + " HP\n";
if (dmg != 0) ret += "+" + dmg + " DAMAGE\n";
if (acc != 0) ret += "+" + acc + "% ACCURACY";
if (bonusEnchantChance != 0) ret += "\n+" + bonusEnchantChance + "% BONUS ENCHANT CHANCE";
} else if (type == 10) {
ret = desc + "\n+" + eChance + "% ENCHANT CHANCE";
ret += "\n\ndrag onto an equip to use";
}
// remove newline from end of string if there is one
ret = ret.trim();
return ret;
}
/**
* Enchanting an item (equip) causes its stats (except accuracy)
* to be multiplied by random values depending on the item's rarity
* There is a 50% chance that the enchant succeeds
* If it fails, there is a 40% chance that the item gets destroyed
* "+(num success)" is added to the item's name
* An item can be enchanted as many times as possible
*
* This method deals with enchant success
*
*/
public void enchant() {
float multiplier = 1.f;
bonusEnchantChance = 0;
switch (rarity) {
// common
case 0:
multiplier = MathUtils.random(Util.COMMON_ENCHANT_MIN, Util.COMMON_ENCHANT_MAX);
break;
// rare
case 1:
multiplier = MathUtils.random(Util.RARE_ENCHANT_MIN, Util.RARE_ENCHANT_MAX);
break;
// epic
case 2:
multiplier = MathUtils.random(Util.EPIC_ENCHANT_MIN, Util.EPIC_ENCHANT_MAX);
break;
// legendary
case 3:
multiplier = MathUtils.random(Util.LEGENDARY_ENCHANT_MIN, Util.LEGENDARY_ENCHANT_MAX);
break;
}
mhp = (int) (mhp * multiplier);
dmg = (int) (dmg * multiplier);
sell = (int) (sell * multiplier);
enchantCost = (int) (enchantCost * multiplier);
enchants++;
// every 5 enchants an item goes up 1 rarity
if (enchants % 5 == 0) rarity++;
if (rarity > 3) rarity = 3;
// enchant number indicator
labelName = "+" + enchants + " " + name;
}
/**
* Returns the item's name as [RARITY] [name] for dialog box
*
* @return
*/
public String getDialogName() {
String ret = "";
switch (rarity) {
case 0:
ret = "[COMMON] " + name;
break;
case 1:
ret = "[RARE] " + name;
break;
case 2:
ret = "[EPIC] " + name;
break;
case 3:
ret = "[LEGENDARY] " + name;
break;
}
return ret;
}
}
|
3e070650e94d5def9f0bc1313409f16d046b6c62 | 1,230 | java | Java | pd-tools/pd-tools-databases/src/main/java/com/itheima/pinda/database/properties/DatabaseProperties.java | gnehcgnaw/pinda-authority | e85571f6cee76225b2b4a6e5c43434edb8aae0a1 | [
"Apache-2.0"
] | null | null | null | pd-tools/pd-tools-databases/src/main/java/com/itheima/pinda/database/properties/DatabaseProperties.java | gnehcgnaw/pinda-authority | e85571f6cee76225b2b4a6e5c43434edb8aae0a1 | [
"Apache-2.0"
] | null | null | null | pd-tools/pd-tools-databases/src/main/java/com/itheima/pinda/database/properties/DatabaseProperties.java | gnehcgnaw/pinda-authority | e85571f6cee76225b2b4a6e5c43434edb8aae0a1 | [
"Apache-2.0"
] | null | null | null | 27.333333 | 110 | 0.613008 | 2,970 | package com.itheima.pinda.database.properties;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.boot.context.properties.ConfigurationProperties;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static com.itheima.pinda.database.properties.DatabaseProperties.PREFIX;
/**
* 客户端认证配置
*/
@ConfigurationProperties(prefix = PREFIX)
@Data
@NoArgsConstructor
public class DatabaseProperties {
public static final String PREFIX = "pinda.database";
/**
* 攻击 SQL 阻断解析器
*/
public Boolean isBlockAttack = false;
/**
* 是否启用数据权限
*/
//private Boolean isDataScope = true;
/**
* 事务超时时间
*/
private int txTimeout = 60 * 60;
/**
* 统一管理事务的方法名
*/
private List<String> transactionAttributeList = new ArrayList<>(Arrays.asList("add*", "save*", "insert*",
"create*", "update*", "edit*", "upload*", "delete*", "remove*",
"clean*", "recycle*", "batch*", "mark*", "disable*", "enable*", "handle*", "syn*",
"reg*", "gen*", "*Tx"
));
/**
* 事务扫描基础包
*/
private String transactionScanPackage = "com.itheima.pinda";
}
|
3e0706756417cc0c75d32c4e7e01d4b45b4803eb | 1,516 | java | Java | app/src/link/zhidou/translator/service/LowStorageReceiver.java | rllen/Settings | 25fb6211c02c399b5bda1ee650ce41e1e996ce3c | [
"MIT"
] | null | null | null | app/src/link/zhidou/translator/service/LowStorageReceiver.java | rllen/Settings | 25fb6211c02c399b5bda1ee650ce41e1e996ce3c | [
"MIT"
] | null | null | null | app/src/link/zhidou/translator/service/LowStorageReceiver.java | rllen/Settings | 25fb6211c02c399b5bda1ee650ce41e1e996ce3c | [
"MIT"
] | null | null | null | 33.688889 | 99 | 0.674802 | 2,971 | package link.zhidou.translator.service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AlertDialog;
import android.view.WindowManager;
import link.zhidou.translator.R;
/**
* created by yue.gan 18-8-22
*/
public class LowStorageReceiver extends BroadcastReceiver {
public void registSelf (Context context) {
IntentFilter intentFilter = new IntentFilter(Intent.ACTION_DEVICE_STORAGE_LOW);
context.registerReceiver(this, intentFilter);
}
public void unregistSelf (Context context) {
context.unregisterReceiver(this);
}
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (Intent.ACTION_DEVICE_STORAGE_LOW.equals(action)) {
AlertDialog dialog = new AlertDialog.Builder(context, R.style.LightAlertDialog)
.setCancelable(false)
.setMessage(R.string.low_memory_warning)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).create();
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
dialog.show();
}
}
}
|
3e0706a63d1a1acdc2220a0989ac572b201e79ae | 4,266 | java | Java | gorun-android/app/src/main/java/com/semihbkgr/gorun/activity/StartActivity.java | SemihBKGR/GoRun | d55907c37305c5e14b2194e5d1c49e02c2ff4b78 | [
"Apache-2.0"
] | 6 | 2021-09-27T05:20:08.000Z | 2022-02-01T19:51:47.000Z | gorun-android/app/src/main/java/com/semihbkgr/gorun/activity/StartActivity.java | SemihBKGR/gorun | 3db4a2f768446fd257fbb134c2016421d4b9aaee | [
"Apache-2.0"
] | null | null | null | gorun-android/app/src/main/java/com/semihbkgr/gorun/activity/StartActivity.java | SemihBKGR/gorun | 3db4a2f768446fd257fbb134c2016421d4b9aaee | [
"Apache-2.0"
] | null | null | null | 46.369565 | 307 | 0.601266 | 2,972 | package com.semihbkgr.gorun.activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.semihbkgr.gorun.AppConstants;
import com.semihbkgr.gorun.AppContext;
import com.semihbkgr.gorun.R;
import com.semihbkgr.gorun.snippet.CacheableSnippetService;
import com.semihbkgr.gorun.snippet.Snippet;
import com.semihbkgr.gorun.snippet.SnippetInfo;
import com.semihbkgr.gorun.util.http.ResponseCallback;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
public class StartActivity extends AppCompatActivity {
public static final String TAG = StartActivity.class.getName();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
AppContext.initialize(getApplicationContext());
new Handler(getMainLooper())
.postDelayed(() -> {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}, AppConstants.Values.LOGO_ON_SCREEN_TIME_MS);
}
@Override
protected void onStart() {
super.onStart();
AppContext.instance().snippetService.getAllSnippetInfosAsync(new ResponseCallback<List<SnippetInfo>>() {
@Override
public void onResponse(List<SnippetInfo> data) {
AppContext.instance().executorService.execute(() -> {
Map<Integer, SnippetInfo> idSnippetInfoMap = new HashMap<>();
data.forEach(snippetInfo -> idSnippetInfoMap.put(snippetInfo.id, snippetInfo));
List<SnippetInfo> snippetInfoList = AppContext.instance().snippetService.getAllSavedSnippetInfos();
snippetInfoList.forEach(snippetInfo -> {
if (idSnippetInfoMap.containsKey(snippetInfo.id)) {
if (idSnippetInfoMap.get(snippetInfo.id).versionId != snippetInfo.versionId) {
Log.i(TAG, "onResponse: snippet version is old, snippetId: " + snippetInfo.id);
AppContext.instance().snippetService.getSnippetAsync(snippetInfo.id, new ResponseCallback<Snippet>() {
@Override
public void onResponse(Snippet data) {
AppContext.instance().snippetService.update(data);
Log.i(TAG, "onResponse: snippet is updated, snippetId: " + data.id);
}
@Override
public void onFailure(Exception e) {
runOnUiThread(() -> Toast.makeText(StartActivity.this, "Request error", Toast.LENGTH_SHORT).show());
}
});
} else
Log.i(TAG, "onResponse: snippet is up-to-date, snippetId: " + snippetInfo.id);
} else {
AppContext.instance().snippetService.delete(snippetInfo.id);
Log.i(TAG, "onResponse: snippet deleted, snippetId: " + snippetInfo.id);
}
});
});
}
@Override
public void onFailure(Exception e) {
runOnUiThread(() -> Toast.makeText(StartActivity.this, "Connection error", Toast.LENGTH_SHORT).show());
}
});
if (AppContext.instance().snippetService instanceof CacheableSnippetService)
AppContext.instance().scheduledExecutorService.scheduleWithFixedDelay(((CacheableSnippetService) AppContext.instance().snippetService)::clearExpiredCaches, AppConstants.Values.CACHE_EXPIRED_CLEAR_TIME_INTERVAL_MS, AppConstants.Values.CACHE_EXPIRED_CLEAR_TIME_INTERVAL_MS, TimeUnit.MILLISECONDS);
}
}
|
3e070731b91cb5cd72acf6fcc76988eed2f286c9 | 3,422 | java | Java | ph-holiday/src/main/java/com/helger/holiday/mgr/CalendarHierarchy.java | phax/ph-datetime | e10bfcbc7c4779544fe837524afa645ef5da97e8 | [
"Apache-2.0"
] | 1 | 2015-12-22T16:22:21.000Z | 2015-12-22T16:22:21.000Z | ph-holiday/src/main/java/com/helger/holiday/mgr/CalendarHierarchy.java | phax/ph-datetime | e10bfcbc7c4779544fe837524afa645ef5da97e8 | [
"Apache-2.0"
] | null | null | null | ph-holiday/src/main/java/com/helger/holiday/mgr/CalendarHierarchy.java | phax/ph-datetime | e10bfcbc7c4779544fe837524afa645ef5da97e8 | [
"Apache-2.0"
] | null | null | null | 28.516667 | 107 | 0.696669 | 2,973 | /*
* Copyright (C) 2014-2021 Philip Helger (www.helger.com)
* philip[at]helger[dot]com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.helger.holiday.mgr;
import java.util.Locale;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import com.helger.commons.ValueEnforcer;
import com.helger.commons.annotation.ReturnsMutableCopy;
import com.helger.commons.collection.impl.CommonsHashMap;
import com.helger.commons.collection.impl.ICommonsMap;
import com.helger.commons.hashcode.HashCodeGenerator;
import com.helger.commons.id.IHasID;
import com.helger.commons.locale.country.ECountry;
import com.helger.commons.string.ToStringGenerator;
/**
* Bean class for describing the configuration hierarchy.
*
* @author Sven Diedrichsen
* @author Philip Helger
*/
public final class CalendarHierarchy implements IHasID <String>
{
private final String m_sID;
private final ECountry m_eCountry;
private final ICommonsMap <String, CalendarHierarchy> m_aChildren = new CommonsHashMap <> ();
/**
* Constructor which takes a eventually existing parent hierarchy node and the
* ID of this hierarchy.
*
* @param aParent
* parent entry
* @param sID
* Calendar ID
* @param eCountry
* Country to use
*/
public CalendarHierarchy (@Nullable final CalendarHierarchy aParent,
@Nonnull final String sID,
@Nullable final ECountry eCountry)
{
ValueEnforcer.notNull (sID, "ID");
m_sID = aParent == null ? sID : aParent.getID () + "_" + sID;
m_eCountry = eCountry;
}
@Nonnull
public String getID ()
{
return m_sID;
}
/**
* Returns the hierarchies description text from the resource bundle.
*
* @param aContentLocale
* Locale to return the description text for.
* @return Description text
*/
@Nonnull
public String getDescription (final Locale aContentLocale)
{
final String ret = m_eCountry == null ? null : m_eCountry.getDisplayText (aContentLocale);
return ret != null ? ret : "undefined";
}
public void addChild (@Nonnull final CalendarHierarchy aChild)
{
m_aChildren.put (aChild.getID (), aChild);
}
@Nonnull
@ReturnsMutableCopy
public ICommonsMap <String, CalendarHierarchy> getChildren ()
{
return m_aChildren.getClone ();
}
@Override
public boolean equals (final Object o)
{
if (o == this)
return true;
if (o == null || !getClass ().equals (o.getClass ()))
return false;
final CalendarHierarchy rhs = (CalendarHierarchy) o;
return m_sID.equals (rhs.m_sID);
}
@Override
public int hashCode ()
{
return new HashCodeGenerator (this).append (m_sID).getHashCode ();
}
@Override
public String toString ()
{
return new ToStringGenerator (this).append ("ID", m_sID).append ("country", m_eCountry).getToString ();
}
}
|
3e07077a717c637e49db341b8c5e8d690c79f236 | 577 | java | Java | stroom-node/stroom-node-impl-db-jooq/src/main/java/stroom/node/impl/db/jooq/Tables.java | jsoref/stroom | 2905180082b8f210cb9895d66d36d322df6ccf0e | [
"Apache-2.0"
] | 2 | 2020-03-23T21:22:34.000Z | 2020-03-23T21:23:14.000Z | stroom-node/stroom-node-impl-db-jooq/src/main/java/stroom/node/impl/db/jooq/Tables.java | CharlyOscarGolf/stroom | bbdd0833e6ff8895eacf3f59708a25eb06c8ed5b | [
"Apache-2.0"
] | null | null | null | stroom-node/stroom-node-impl-db-jooq/src/main/java/stroom/node/impl/db/jooq/Tables.java | CharlyOscarGolf/stroom | bbdd0833e6ff8895eacf3f59708a25eb06c8ed5b | [
"Apache-2.0"
] | null | null | null | 19.233333 | 78 | 0.639515 | 2,974 | /*
* This file is generated by jOOQ.
*/
package stroom.node.impl.db.jooq;
import stroom.node.impl.db.jooq.tables.Node;
import javax.annotation.Generated;
/**
* Convenience access to all tables in stroom
*/
@Generated(
value = {
"http://www.jooq.org",
"jOOQ version:3.11.9"
},
comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class Tables {
/**
* The table <code>stroom.node</code>.
*/
public static final Node NODE = stroom.node.impl.db.jooq.tables.Node.NODE;
}
|
3e0707a04ade6462ff1fd4bce04dd2ccf48b9f23 | 284 | java | Java | bytekit/src/main/java/com/taobao/arthas/bytekit/asm/inst/NewField.java | happycodingjava/arthas | fec87d4dd9a9a3761734c00c3f0b8ca10e36aaaf | [
"Apache-2.0"
] | 3 | 2020-11-12T06:10:55.000Z | 2021-01-09T04:57:33.000Z | bytekit/src/main/java/com/taobao/arthas/bytekit/asm/inst/NewField.java | MrZhengliang/arthas | 9046dbb93242f8b0a26cede4c6ec10b41f9b1c76 | [
"Apache-2.0"
] | 3 | 2021-12-09T19:27:17.000Z | 2021-12-14T21:47:58.000Z | bytekit/src/main/java/com/taobao/arthas/bytekit/asm/inst/NewField.java | MrZhengliang/arthas | 9046dbb93242f8b0a26cede4c6ec10b41f9b1c76 | [
"Apache-2.0"
] | null | null | null | 28.4 | 51 | 0.816901 | 2,975 | package com.taobao.arthas.bytekit.asm.inst;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ java.lang.annotation.ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface NewField {
} |
3e0707b38225dcbf5114e70a5c4722cade9fdcd2 | 848 | java | Java | Java/Udemy/Master Microservices with Spring Boot and Spring Cloud/currency-conversion-service/src/main/java/net/dvt32/microservices/CurrencyExchangeServiceProxy.java | dvt32/cpp-journey | afd7db7a1ad106c41601fb09e963902187ae36e6 | [
"MIT"
] | 1 | 2018-05-24T11:30:05.000Z | 2018-05-24T11:30:05.000Z | Java/Udemy/Master Microservices with Spring Boot and Spring Cloud/currency-conversion-service/src/main/java/net/dvt32/microservices/CurrencyExchangeServiceProxy.java | dvt32/cpp-journey | afd7db7a1ad106c41601fb09e963902187ae36e6 | [
"MIT"
] | null | null | null | Java/Udemy/Master Microservices with Spring Boot and Spring Cloud/currency-conversion-service/src/main/java/net/dvt32/microservices/CurrencyExchangeServiceProxy.java | dvt32/cpp-journey | afd7db7a1ad106c41601fb09e963902187ae36e6 | [
"MIT"
] | 2 | 2017-08-11T06:53:30.000Z | 2017-08-29T12:07:52.000Z | 38.545455 | 81 | 0.762972 | 2,976 | package net.dvt32.microservices;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
// @FeignClient(name = "currency-exchange-service", url = "localhost:8000")
// @FeignClient(name = "currency-exchange-service")
@FeignClient(name = "netflix-zuul-api-gateway-server")
@RibbonClient(name = "currency-exchange-service")
public interface CurrencyExchangeServiceProxy {
// @GetMapping("/currency-exchange/from/{from}/to/{to}")
@GetMapping("/currency-exchange-service/currency-exchange/from/{from}/to/{to}")
public CurrencyConversionBean retrieveExchangeValue(
@PathVariable("from") String from,
@PathVariable("to") String to
);
}
|
3e07081b6f2e870b6377b39d35ae28fab9f2d7da | 2,063 | java | Java | src/main/java/frc/robot/Logs.java | VeryCleverName3/Toast-Robotics-Code | 6939254ca3079662182e9ee06f65dfe674337e2a | [
"BSD-3-Clause"
] | null | null | null | src/main/java/frc/robot/Logs.java | VeryCleverName3/Toast-Robotics-Code | 6939254ca3079662182e9ee06f65dfe674337e2a | [
"BSD-3-Clause"
] | null | null | null | src/main/java/frc/robot/Logs.java | VeryCleverName3/Toast-Robotics-Code | 6939254ca3079662182e9ee06f65dfe674337e2a | [
"BSD-3-Clause"
] | null | null | null | 27.506667 | 88 | 0.62094 | 2,977 | package frc.robot;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
import edu.wpi.first.wpilibj.Filesystem;
public class Logs {
private static final String DIR = "/logs/";
private static Logger logger;
private static FileHandler file;
private static SimpleFormatter formatter;
public static void Init() {
logger = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
logger.setLevel(Level.SEVERE);
try {
String local = Filesystem.getDeployDirectory().toPath().toString();
SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd - HH:mm:ss");
Date date = new Date(System.currentTimeMillis());
String filename = local + DIR + timeFormat.format(date) + ".log";
file = new FileHandler(filename);
formatter = new SimpleFormatter();
file.setFormatter(formatter);
logger.addHandler(file);
} catch (SecurityException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static Logger getLogger() {
if (logger == null) {
Logs.Init();
}
return logger;
}
public static String format(String msg) {
return "[" + TeamUtils.getCurrentTime() + "]: " + msg;
}
public static void info(String msg) {
getLogger().info(format(msg));
}
public static void warning(String msg) {
getLogger().warning(msg);
}
public static void severe(String msg) {
getLogger().severe(msg);
}
public static void fine(String msg) {
getLogger().fine(msg);
}
public static void finer(String msg) {
getLogger().finer(msg);
}
public static void finest(String msg) {
getLogger().finest(msg);
}
}
|
3e070825e47d1bfc6cd9eb251a773491b1d142a1 | 225 | java | Java | src/main/java/com/ibm/service/ServerService.java | Bartoss/DetectVM2OpenStack | 2ffc8d7a95c9702c81e4bd5f3b388e58f85ab964 | [
"Unlicense"
] | null | null | null | src/main/java/com/ibm/service/ServerService.java | Bartoss/DetectVM2OpenStack | 2ffc8d7a95c9702c81e4bd5f3b388e58f85ab964 | [
"Unlicense"
] | null | null | null | src/main/java/com/ibm/service/ServerService.java | Bartoss/DetectVM2OpenStack | 2ffc8d7a95c9702c81e4bd5f3b388e58f85ab964 | [
"Unlicense"
] | null | null | null | 15 | 37 | 0.733333 | 2,978 | package com.ibm.service;
import com.ibm.model.Server;
import java.util.List;
public interface ServerService {
List<Server> getServerList();
void addServer(Server server);
void deleteServer(Server server);
}
|
3e0708cc9e5b2090203bd223f233ac2c9c79c714 | 5,902 | java | Java | cruise-control/src/main/java/com/linkedin/kafka/cruisecontrol/config/BrokerCapacityInfo.java | mkandi/cruise-control | f82de3dfe7c257fd446a83e23490218746e90d5a | [
"BSD-2-Clause"
] | null | null | null | cruise-control/src/main/java/com/linkedin/kafka/cruisecontrol/config/BrokerCapacityInfo.java | mkandi/cruise-control | f82de3dfe7c257fd446a83e23490218746e90d5a | [
"BSD-2-Clause"
] | null | null | null | cruise-control/src/main/java/com/linkedin/kafka/cruisecontrol/config/BrokerCapacityInfo.java | mkandi/cruise-control | f82de3dfe7c257fd446a83e23490218746e90d5a | [
"BSD-2-Clause"
] | null | null | null | 39.346667 | 146 | 0.735344 | 2,979 | /*
* Copyright 2018 LinkedIn Corp. Licensed under the BSD 2-Clause License (the "License"). See License in the project root for license information.
*/
package com.linkedin.kafka.cruisecontrol.config;
import com.linkedin.kafka.cruisecontrol.common.Resource;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
public class BrokerCapacityInfo {
public final static short DEFAULT_NUM_CPU_CORES = 1;
private final static String DEFAULT_ESTIMATION_INFO = "";
private final static Map<String, Double> DEFAULT_DISK_CAPACITY_BY_LOGDIR = null;
private final Map<Resource, Double> _capacity;
private final String _estimationInfo;
private final Map<String, Double> _diskCapacityByLogDir;
private final short _numCpuCores;
/**
* BrokerCapacityInfo with the given capacity, estimation, per absolute logDir disk capacity, and number of CPU cores.
*
* @param capacity Capacity information for each resource.
* @param estimationInfo Description if there is any capacity estimation, null or {@link #DEFAULT_ESTIMATION_INFO} otherwise.
* @param diskCapacityByLogDir Disk capacity by absolute logDir.
* @param numCpuCores Number of CPU cores.
*/
public BrokerCapacityInfo(Map<Resource, Double> capacity,
String estimationInfo,
Map<String, Double> diskCapacityByLogDir,
short numCpuCores) {
sanityCheckCapacity(capacity);
_capacity = capacity;
_estimationInfo = estimationInfo == null ? DEFAULT_ESTIMATION_INFO : estimationInfo;
_diskCapacityByLogDir = diskCapacityByLogDir;
_numCpuCores = numCpuCores;
}
/**
* BrokerCapacityInfo with the given capacity, per absolute logDir disk capacity, and number of CPU cores.
*
* @param capacity Capacity information for each resource.
* @param diskCapacityByLogDir Disk capacity by absolute logDir.
* @param numCpuCores Number of CPU cores.
*/
public BrokerCapacityInfo(Map<Resource, Double> capacity, Map<String, Double> diskCapacityByLogDir, short numCpuCores) {
this(capacity, DEFAULT_ESTIMATION_INFO, diskCapacityByLogDir, numCpuCores);
}
/**
* BrokerCapacityInfo with the given capacity and number of CPU cores.
*
* @param capacity Capacity information for each resource.
* @param numCpuCores Number of CPU cores.
*/
public BrokerCapacityInfo(Map<Resource, Double> capacity, short numCpuCores) {
this(capacity, DEFAULT_ESTIMATION_INFO, DEFAULT_DISK_CAPACITY_BY_LOGDIR, numCpuCores);
}
/**
* BrokerCapacityInfo with the given capacity, estimation, and per absolute logDir disk capacity.
*
* @param capacity Capacity information for each resource.
* @param estimationInfo Description if there is any capacity estimation, null or {@link #DEFAULT_ESTIMATION_INFO} otherwise.
* @param diskCapacityByLogDir Disk capacity by absolute logDir.
*/
public BrokerCapacityInfo(Map<Resource, Double> capacity, String estimationInfo, Map<String, Double> diskCapacityByLogDir) {
this(capacity, estimationInfo, diskCapacityByLogDir, DEFAULT_NUM_CPU_CORES);
}
/**
* BrokerCapacityInfo with no capacity information specified per absolute logDir.
*
* @param capacity Capacity information for each resource.
* @param estimationInfo Description if there is any capacity estimation, null or {@link #DEFAULT_ESTIMATION_INFO} otherwise.
*/
public BrokerCapacityInfo(Map<Resource, Double> capacity, String estimationInfo) {
this(capacity, estimationInfo, DEFAULT_DISK_CAPACITY_BY_LOGDIR, DEFAULT_NUM_CPU_CORES);
}
/**
* BrokerCapacityInfo with no estimation.
*
* @param capacity Capacity information for each resource.
* @param diskCapacityByLogDir Disk capacity by absolute logDir.
*/
public BrokerCapacityInfo(Map<Resource, Double> capacity, Map<String, Double> diskCapacityByLogDir) {
this(capacity, DEFAULT_ESTIMATION_INFO, diskCapacityByLogDir, DEFAULT_NUM_CPU_CORES);
}
/**
* BrokerCapacityInfo with no estimation, no capacity information specified per absolute logDir.
*
* @param capacity Capacity information for each resource.
*/
public BrokerCapacityInfo(Map<Resource, Double> capacity) {
this(capacity, DEFAULT_ESTIMATION_INFO, DEFAULT_DISK_CAPACITY_BY_LOGDIR, DEFAULT_NUM_CPU_CORES);
}
/**
* @return The broker capacity for different resource types.
*/
public Map<Resource, Double> capacity() {
return _capacity;
}
/**
* @return True if the capacity of the broker for at least one resource is based on an estimation, false otherwise.
*/
public boolean isEstimated() {
return !_estimationInfo.isEmpty();
}
/**
* @return {@link #DEFAULT_ESTIMATION_INFO} if no estimation, related estimation info otherwise.
*/
public String estimationInfo() {
return _estimationInfo;
}
/**
* @return Disk capacity by absolute logDir if specified, {@link #DEFAULT_DISK_CAPACITY_BY_LOGDIR} otherwise.
*/
public Map<String, Double> diskCapacityByLogDir() {
return _diskCapacityByLogDir;
}
/**
* @return Number of CPU cores (if provided), {@link #DEFAULT_NUM_CPU_CORES} otherwise.
*/
public short numCpuCores() {
return _numCpuCores;
}
/**
* Sanity check to ensure the provided capacity information contains all the resource type.
* @param capacity The provided capacity map.
*/
static void sanityCheckCapacity(Map<Resource, Double> capacity) {
Set<Resource> providedResource = capacity.keySet();
Set<Resource> missingResource = Resource.cachedValues().stream().filter(r -> !providedResource.contains(r))
.collect(Collectors.toSet());
if (!missingResource.isEmpty()) {
throw new IllegalArgumentException(String.format("Provided capacity information missing value for resource %s.", missingResource));
}
}
}
|
3e070997a24f2c117648d60656dbbdd57c7b6f25 | 1,650 | java | Java | bundles/org.pgcase.xobot.workspace.team.ui/src/org/pgcase/xobot/workspace/team/ui/XobotDisconnectAction.java | pgcase/xobot-ide | 9e18e9f41c27234c73dd1310372619b79cd3e6e6 | [
"Apache-2.0"
] | 2 | 2018-12-27T14:00:36.000Z | 2019-01-04T16:48:28.000Z | bundles/org.pgcase.xobot.workspace.team.ui/src/org/pgcase/xobot/workspace/team/ui/XobotDisconnectAction.java | pgcase/xobot-ide | 9e18e9f41c27234c73dd1310372619b79cd3e6e6 | [
"Apache-2.0"
] | 3 | 2019-01-17T18:42:34.000Z | 2019-02-13T11:51:39.000Z | bundles/org.pgcase.xobot.workspace.team.ui/src/org/pgcase/xobot/workspace/team/ui/XobotDisconnectAction.java | pgcase/xobot-ide | 9e18e9f41c27234c73dd1310372619b79cd3e6e6 | [
"Apache-2.0"
] | 1 | 2019-02-10T19:26:34.000Z | 2019-02-10T19:26:34.000Z | 35.106383 | 117 | 0.674545 | 2,980 | /*******************************************************************************
* Copyright (c) 2018-2020 ArSysOp
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*
* Contributors:
* ArSysOp - initial API and implementation
*******************************************************************************/
package org.pgcase.xobot.workspace.team.ui;
import org.eclipse.core.resources.IProject;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.team.core.RepositoryProvider;
import org.eclipse.team.core.TeamException;
import org.eclipse.team.internal.ui.actions.TeamAction;
public class XobotDisconnectAction extends TeamAction {
protected void execute(IAction action) {
IProject projects[] = getSelectedProjects();
try {
for (int i = 0; i < projects.length; i++) {
RepositoryProvider.unmap(projects[i]);
}
} catch (TeamException e) {
ErrorDialog.openError(getShell(), WorkspaceTeamUIMessages.XobotDisconnectAction_error_title, null, e.getStatus());
}
}
public boolean isEnabled() {
return true;
}
}
|
3e0709aed6dae0fd0fd176d4aa2c9a287f470785 | 823 | java | Java | interview-preparation/src/main/java/zipFile/dto/ResponseWrapper.java | basic2avg2excellent/springboot-solutions | 818554baac74d557d8db1f2847ae8652bcbe925e | [
"Apache-2.0"
] | null | null | null | interview-preparation/src/main/java/zipFile/dto/ResponseWrapper.java | basic2avg2excellent/springboot-solutions | 818554baac74d557d8db1f2847ae8652bcbe925e | [
"Apache-2.0"
] | 1 | 2021-08-23T02:49:50.000Z | 2021-08-23T02:49:50.000Z | interview-preparation/src/main/java/zipFile/dto/ResponseWrapper.java | basic2avg2excellent/springboot-solutions | 818554baac74d557d8db1f2847ae8652bcbe925e | [
"Apache-2.0"
] | null | null | null | 19.139535 | 75 | 0.624544 | 2,981 | package zipFile.dto;
public class ResponseWrapper {
private Object payload;
private int statusCode;
private String message;
public ResponseWrapper(){
}
public ResponseWrapper(Object payload, int statusCode, String message){
this.payload = payload;
this.statusCode = statusCode;
this.message = message;
}
public Object getPayload() {
return payload;
}
public void setPayload(Object payload) {
this.payload = payload;
}
public int getStatusCode() {
return statusCode;
}
public void setStatusCode(int statusCode) {
this.statusCode = statusCode;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
|
3e0709b8a3d777f9f56e6af2ea991817ff1f97a5 | 1,400 | java | Java | src/test/java/com/btisystems/pronx/ems/schemas/meta/notification/FieldListTest.java | btisystems/snmp-core | 8f572449d685cc5e9f26eefb387617d17d1507f7 | [
"Apache-2.0"
] | 2 | 2019-10-25T19:10:19.000Z | 2021-01-15T02:09:36.000Z | src/test/java/com/btisystems/pronx/ems/schemas/meta/notification/FieldListTest.java | btisystems/snmp-core | 8f572449d685cc5e9f26eefb387617d17d1507f7 | [
"Apache-2.0"
] | 1 | 2016-10-24T14:06:22.000Z | 2016-10-24T14:06:22.000Z | src/test/java/com/btisystems/pronx/ems/schemas/meta/notification/FieldListTest.java | btisystems/snmp-core | 8f572449d685cc5e9f26eefb387617d17d1507f7 | [
"Apache-2.0"
] | 1 | 2016-10-21T21:27:49.000Z | 2016-10-21T21:27:49.000Z | 29.787234 | 87 | 0.697857 | 2,982 | /*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.btisystems.pronx.ems.schemas.meta.notification;
import java.util.Arrays;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* Test class in addition to {@link NotificationBeansTest}
*/
public class FieldListTest {
private FieldDescription[] descriptions;
public FieldListTest() {
}
@Before
public void setUp() {
descriptions = new FieldDescription[]{new FieldDescription().withName("Test")};
}
@Test
public void shouldTestWithMethods() {
final FieldList fl = new FieldList();
fl.withFieldDescription(descriptions);
assertEquals(1, fl.getFieldDescription().size());
fl.withFieldDescription(Arrays.asList(descriptions));
assertEquals(2, fl.getFieldDescription().size());
}
}
|
3e070a4ae67883563c5958722eedf364a608ea20 | 917 | java | Java | app/src/main/java/com/example/zhumingren/myapplication/MainActivity.java | HOLDfoot/FacebookPhotoPicker | f3218d40abfddc6378ab82ffdcbaf5b176c5d123 | [
"MIT"
] | null | null | null | app/src/main/java/com/example/zhumingren/myapplication/MainActivity.java | HOLDfoot/FacebookPhotoPicker | f3218d40abfddc6378ab82ffdcbaf5b176c5d123 | [
"MIT"
] | null | null | null | app/src/main/java/com/example/zhumingren/myapplication/MainActivity.java | HOLDfoot/FacebookPhotoPicker | f3218d40abfddc6378ab82ffdcbaf5b176c5d123 | [
"MIT"
] | null | null | null | 26.2 | 85 | 0.717557 | 2,983 | package com.example.zhumingren.myapplication;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.example.facebookphotopicker.FacebookSignInActivity;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button btnSkip;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
private void initView() {
btnSkip = (Button) findViewById(R.id.btn_skipto_signin);
btnSkip.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.btn_skipto_signin) {
startActivity(new Intent(this, FacebookSignInActivity.class));
}
}
}
|
3e070ada6ebf070b017e7c5d20c67af87748bc16 | 2,326 | java | Java | appsrv/src/main/java/at/htl/boundary/CourseEndpoint.java | htl-leonding-project/2021-da-online-dance-practice-2 | 932570cd277bb03ad0b306f7677d5aa757364030 | [
"Unlicense"
] | null | null | null | appsrv/src/main/java/at/htl/boundary/CourseEndpoint.java | htl-leonding-project/2021-da-online-dance-practice-2 | 932570cd277bb03ad0b306f7677d5aa757364030 | [
"Unlicense"
] | null | null | null | appsrv/src/main/java/at/htl/boundary/CourseEndpoint.java | htl-leonding-project/2021-da-online-dance-practice-2 | 932570cd277bb03ad0b306f7677d5aa757364030 | [
"Unlicense"
] | 2 | 2021-11-18T10:35:57.000Z | 2021-12-17T07:53:16.000Z | 28.716049 | 101 | 0.66552 | 2,984 | package at.htl.boundary;
import at.htl.control.CourseRepository;
import at.htl.control.LevelRepository;
import at.htl.entity.Course;
import at.htl.entity.Level;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.transaction.Transactional;
import javax.ws.rs.*;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;
import java.net.URI;
@RequestScoped
@Path("/course")
public class CourseEndpoint {
@Inject
CourseRepository courseRepository;
@Inject
LevelRepository levelRepository;
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response findAll() {
return Response.ok(courseRepository.listAll()).build();
}
@POST
@Path("/create")
@Transactional
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response create(String levelId, @Context UriInfo info, String title, String description) {
Level level = levelRepository.findById(levelId);
Course course = new Course (title, description, level);
courseRepository.persist(course);
return Response.created(URI.create(info.getPath() + "/"+ course.id)).build();
}
@GET
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response findById(@PathParam("id") long id) {
return Response.ok(courseRepository.findById(id)).build();
}
@DELETE
@Path("{id}")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Transactional
public Response delete(@PathParam("id") Long id) {
try {
courseRepository.deleteById(id);
return Response
.noContent()
.build();
} catch (IllegalArgumentException e) {
return Response
.status(400)
.header("Reason","Course with id" +id + "does not exist")
.build();
}
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response findCourseByLevel(Level level) {
return Response.ok().entity(courseRepository.findCourseByLevel(level)).build();
}
}
|
3e070b06d08b53d0a4d7b470bae309b50f6c7139 | 34,258 | java | Java | app/src/main/java/org/bingmaps/app/DialogLauncher.java | Alfanski/BananaFree | aa3a36339e17804f277959dcc51de62ff583aabf | [
"MIT"
] | null | null | null | app/src/main/java/org/bingmaps/app/DialogLauncher.java | Alfanski/BananaFree | aa3a36339e17804f277959dcc51de62ff583aabf | [
"MIT"
] | null | null | null | app/src/main/java/org/bingmaps/app/DialogLauncher.java | Alfanski/BananaFree | aa3a36339e17804f277959dcc51de62ff583aabf | [
"MIT"
] | null | null | null | 53.361371 | 257 | 0.512231 | 2,985 | package org.bingmaps.app;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnMultiChoiceClickListener;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.util.DebugUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import org.bingmaps.bsds.BingSpatialDataService;
import org.bingmaps.bsds.Record;
import org.bingmaps.rest.BingMapsRestService;
import org.bingmaps.rest.RoutePathOutput;
import org.bingmaps.rest.RouteRequest;
import org.bingmaps.rest.models.ItineraryItem;
import org.bingmaps.rest.models.Location;
import org.bingmaps.sdk.BingMapsView;
import org.bingmaps.sdk.Color;
import org.bingmaps.sdk.EntityLayer;
import org.bingmaps.sdk.LocationRect;
import org.bingmaps.sdk.Point;
import org.bingmaps.sdk.Polyline;
import org.bingmaps.sdk.PolylineOptions;
import org.bingmaps.sdk.Pushpin;
import org.bingmaps.sdk.PushpinOptions;
import org.bingmaps.sdk.TileLayer;
import org.bingmaps.sdk.Utilities;
import java.util.HashMap;
public class DialogLauncher {
private static final String TAG = "DialogLauncher";
private static String currentBananaFree = "";
public static void basicReadWrite(String location, boolean bananaFree, String comment) {
// [START write_message]
// Write a message to the database
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("stations/"+location+"/comment");
myRef.setValue(comment);
myRef = database.getReference("stations/"+location+"/bananaFree");
myRef.setValue(""+bananaFree);
// [END write_message]
// [START read_message]
// Read from the database
myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
String value = dataSnapshot.getKey();
Log.d(TAG, "Value is: " + value);
}
@Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
}
});
// [END read_message]
}
public static void LaunchAboutDialog(final Activity activity) {
final View aboutView = activity.getLayoutInflater().inflate(R.layout.about, (ViewGroup) activity.findViewById(R.id.aboutView));
AlertDialog.Builder aboutAlert = new AlertDialog.Builder(activity)
.setTitle(activity.getString(R.string.about))
.setIcon(android.R.drawable.ic_dialog_info)
.setView(aboutView)
.setPositiveButton(activity.getString(R.string.ok), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled. Do nothing
}
});
aboutAlert.show();
}
public static void LaunchLayersDialog(final Activity activity, final BingMapsView bingMapsView, final CharSequence[] dataLayers, boolean[] dataLayerSelections) {
new AlertDialog.Builder(activity)
.setIcon(android.R.drawable.ic_menu_slideshow)
.setTitle(activity.getString(R.string.layers))
.setMultiChoiceItems(dataLayers, dataLayerSelections, new OnMultiChoiceClickListener() {
public void onClick(DialogInterface arg0, int idx, boolean isChecked) {
if (dataLayers[idx] == activity.getString(R.string.traffic)) {
if (isChecked) {
bingMapsView.getLayerManager().addLayer(new TileLayer(activity.getString(R.string.traffic), org.bingmaps.sdk.Constants.TrafficTileLayerURI, 0.5));
} else {
bingMapsView.getLayerManager().clearLayer(activity.getString(R.string.traffic));
}
}
//Add support for more map data layers here
}
})
.setPositiveButton(activity.getString(R.string.close), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
}
})
.show();
}
public static void LaunchSearchDialog(Activity activity, final BingMapsView bingMapsView, final Handler loadingScreenHandler) {
final View searchView = activity.getLayoutInflater().inflate(R.layout.search_input, (ViewGroup) activity.findViewById(R.id.searchInputView));
AlertDialog.Builder searchAlert = new AlertDialog.Builder(activity)
.setTitle(activity.getString(R.string.search))
.setIcon(android.R.drawable.ic_menu_search)
.setView(searchView)
.setNegativeButton(activity.getString(R.string.cancel), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled. Do nothing
}
})
.setPositiveButton(activity.getString(R.string.search), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
EditText input = (EditText) searchView.findViewById(R.id.searchInput);
String searchText = input.getText().toString().trim();
if (!Utilities.isNullOrEmpty(searchText)) {
Message viewMsg = new Message();
viewMsg.arg1 = 1;
loadingScreenHandler.sendMessage(viewMsg);
try {
BingMapsRestService bmService = new BingMapsRestService(Constants.BingMapsKey);
bmService.GeocodeAsyncCompleted = new Handler() {
public void handleMessage(Message msg) {
if (msg.obj != null) {
org.bingmaps.rest.models.Location[] locations = (org.bingmaps.rest.models.Location[]) msg.obj;
org.bingmaps.rest.models.Location l = locations[0];
if (l.Point != null) {
clearLayers(bingMapsView);
EntityLayer searchLayer = (EntityLayer) bingMapsView.getLayerManager().getLayerByName(Constants.DataLayers.Search);
FirebaseDatabase database = FirebaseDatabase.getInstance();
String key = (l.Point.Latitude+"_"+l.Point.Longitude).replace(".", "p");
DatabaseReference bananaFreeRef = database.getReference("stations/"+key+"/bananaFree");
currentBananaFree = "";
listenToValue(bananaFreeRef);
PushpinOptions po = new PushpinOptions();
po.Icon = currentBananaFree == null || currentBananaFree == "" ? Constants.PushpinIcons.Access: Boolean.parseBoolean(currentBananaFree) == true ? Constants.PushpinIcons.Access: Constants.PushpinIcons.NOAccess;
po.Width = 20;
po.Height = 35;
po.Anchor = new Point(4, 35);
Pushpin location = new Pushpin(l.Point, po);
searchLayer.add(location);
bingMapsView.getLayerManager().addLayer(searchLayer);
searchLayer.updateLayer();
bingMapsView.setCenterAndZoom(l.Point, Constants.DefaultSearchZoomLevel);
Message v = new Message();
v.arg1 = 0;
loadingScreenHandler.sendMessage(v);
} else {
Message v = new Message();
v.arg1 = 0;
loadingScreenHandler.sendMessage(v);
}
} else {
Message v = new Message();
v.arg1 = 0;
loadingScreenHandler.sendMessage(v);
}
}
};
bmService.GeocodeAsync(searchText);
} catch (Exception e) {
Message v = new Message();
v.arg1 = 0;
loadingScreenHandler.sendMessage(v);
}
}
}
});
searchAlert.show();
}
public static void LaunchFailureInputDialog(Activity activity, final BingMapsView bingMapsView, final Handler loadingScreenHandler) {
final View failureView = activity.getLayoutInflater().inflate(R.layout.failure_input, (ViewGroup) activity.findViewById(R.id.failureInputView));
AlertDialog.Builder searchAlert = new AlertDialog.Builder(activity)
.setTitle(activity.getString(R.string.report_failure))
.setIcon(android.R.drawable.ic_menu_search)
.setView(failureView)
.setNegativeButton(activity.getString(R.string.cancel), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled. Do nothing
}
})
.setPositiveButton(activity.getString(R.string.report), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
EditText input = (EditText) failureView.findViewById(R.id.failureStationName);
String failureText = input.getText().toString().trim();
if (!Utilities.isNullOrEmpty(failureText)) {
Message viewMsg = new Message();
viewMsg.arg1 = 1;
loadingScreenHandler.sendMessage(viewMsg);
try {
BingMapsRestService bmService = new BingMapsRestService(Constants.BingMapsKey);
bmService.GeocodeAsyncCompleted = new Handler() {
public void handleMessage(Message msg) {
if (msg.obj != null) {
org.bingmaps.rest.models.Location[] locations = (org.bingmaps.rest.models.Location[]) msg.obj;
org.bingmaps.rest.models.Location l = locations[0];
if (l.Point != null) {
clearLayers(bingMapsView);
EntityLayer bananaLayer = (EntityLayer) bingMapsView.getLayerManager().getLayerByName(Constants.DataLayers.Banana);
EditText comment = (EditText) failureView.findViewById(R.id.failureComment);
basicReadWrite((l.Point.Latitude+"_"+l.Point.Longitude).replace(".","p"), false,comment.getText().toString().trim());
PushpinOptions po = new PushpinOptions();
po.Icon = Constants.PushpinIcons.NOAccess;
po.Width = 20;
po.Height = 35;
po.Anchor = new Point(4, 35);
Pushpin location = new Pushpin(l.Point, po);
bananaLayer.add(location);
bingMapsView.getLayerManager().addLayer(bananaLayer);
bananaLayer.updateLayer();
bingMapsView.setCenterAndZoom(l.Point, Constants.DefaultSearchZoomLevel);
Message v = new Message();
v.arg1 = 0;
loadingScreenHandler.sendMessage(v);
} else {
Message v = new Message();
v.arg1 = 0;
loadingScreenHandler.sendMessage(v);
}
} else {
Message v = new Message();
v.arg1 = 0;
loadingScreenHandler.sendMessage(v);
}
}
};
bmService.GeocodeAsync(failureText);
} catch (Exception e) {
Message v = new Message();
v.arg1 = 0;
loadingScreenHandler.sendMessage(v);
}
}
}
});
searchAlert.show();
}
public static void listenToValue(DatabaseReference dbRef){
dbRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
currentBananaFree = dataSnapshot.getValue(String.class);
//do what you want with the email
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public static void clearLayers(BingMapsView bingMapsView){
EntityLayer routeLayer = (EntityLayer) bingMapsView.getLayerManager().getLayerByName(Constants.DataLayers.Route);
EntityLayer bananaLayer = (EntityLayer) bingMapsView.getLayerManager().getLayerByName(Constants.DataLayers.Banana);
EntityLayer searchLayer = (EntityLayer) bingMapsView.getLayerManager().getLayerByName(Constants.DataLayers.Search);
if (routeLayer == null) {
routeLayer = new EntityLayer(Constants.DataLayers.Route);
bingMapsView.getLayerManager().addLayer(routeLayer);
}
if (bananaLayer == null) {
bananaLayer = new EntityLayer(Constants.DataLayers.Banana);
bingMapsView.getLayerManager().addLayer(bananaLayer);
}
if (searchLayer == null) {
searchLayer = new EntityLayer(Constants.DataLayers.Search);
bingMapsView.getLayerManager().addLayer(searchLayer);
}
bananaLayer.clear();
routeLayer.clear();
searchLayer.clear();
}
public static boolean renderRoute(org.bingmaps.rest.models.Route route, int routeIndex, BingMapsView bingMapsView){
boolean result = true;
clearLayers(bingMapsView);
EntityLayer routeLayer = (EntityLayer) bingMapsView.getLayerManager().getLayerByName(Constants.DataLayers.Route);
FirebaseDatabase database = FirebaseDatabase.getInstance();
PushpinOptions pOption1 = new PushpinOptions();
pOption1.Icon = Constants.PushpinIcons.BigStart;
pOption1.Width = 43;
pOption1.Height = 55;
pOption1.Anchor = new Point(20, 36);
// pOption1.ZIndex = 1000;
Pushpin start = new Pushpin(route.RouteLegs.get(0).ActualStart, pOption1);
routeLayer.add(start);
for(ItineraryItem item: route.RouteLegs.get(0).ItineraryItems){
PushpinOptions viaOption = pOption1.clone();
String key = (item.ManeuverPoint.Latitude+"_"+item.ManeuverPoint.Longitude).replace(".", "p");
DatabaseReference bananaFreeRef = database.getReference("stations/"+key+"/bananaFree");
currentBananaFree = "";
listenToValue(bananaFreeRef);
pOption1.Icon = currentBananaFree == null || currentBananaFree == "" ? Constants.PushpinIcons.Access: Boolean.parseBoolean(currentBananaFree) == true ? Constants.PushpinIcons.Access: Constants.PushpinIcons.NOAccess;
result = !(currentBananaFree.equals("false"));
Pushpin viaPushpin = new Pushpin(item.ManeuverPoint, viaOption);
routeLayer.add(viaPushpin);
}
PushpinOptions pOption2 = pOption1.clone();
pOption2.Icon = Constants.PushpinIcons.BigEnd;
pOption2.Text = route.RouteLegs.get(0).EndLocation.Name;
Pushpin end = new Pushpin(route.RouteLegs.get(0).ActualEnd, pOption2);
routeLayer.add(end);
/*PolylineOptions polyOptions = new PolylineOptions();
polyOptions.StrokeColor = new Color((byte) 0, (byte) 0, (byte) 0, (byte) 0 );
polyOptions.StrokeThickness = 25;*/
Polyline routeLine = new Polyline(route.RoutePath);
// routeLine.Options = polyOptions;
routeLayer.add(routeLine);
bingMapsView.getLayerManager().addLayer(routeLayer);
routeLine = null;
routeLayer.updateLayer();
if (route.BoundingBox != null) {
bingMapsView.setMapView(route.BoundingBox);
}
route = null;
return result;
}
public static void LaunchDirectionsDialog(final Activity activity, final BingMapsView bingMapsView, final Handler loadingScreenHandler) {
final View directionsView = activity.getLayoutInflater().inflate(R.layout.directions_input, (ViewGroup) activity.findViewById(R.id.directionsInputView));
AlertDialog.Builder directionsAlert = new AlertDialog.Builder(activity)
.setTitle(activity.getString(R.string.directions))
.setView(directionsView)
.setIcon(android.R.drawable.ic_menu_directions)
.setNegativeButton(activity.getString(R.string.cancel), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled. Do nothing
}
})
.setPositiveButton(activity.getString(R.string.getDirections), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
final EditText fromInput = (EditText) directionsView.findViewById(R.id.directionsFromInput);
final EditText toInput = (EditText) directionsView.findViewById(R.id.directionsToInput);
String fromText = fromInput.getText().toString().trim();
String toText = toInput.getText().toString().trim();
if (!Utilities.isNullOrEmpty(fromText) && !Utilities.isNullOrEmpty(toText)) {
Message viewMsg = new Message();
viewMsg.arg1 = 1;
loadingScreenHandler.sendMessage(viewMsg);
try {
BingMapsRestService bmService = new BingMapsRestService(Constants.BingMapsKey);
bmService.RouteAsyncCompleted = new Handler() {
public void handleMessage(Message msg) {
if (msg.obj != null) {
org.bingmaps.rest.models.Route route = (org.bingmaps.rest.models.Route) msg.obj;
boolean bananaFree = renderRoute(route, 0, bingMapsView);
msg.obj = null;
}
Message v = new Message();
v.arg1 = 0;
loadingScreenHandler.sendMessage(v);
}
};
RouteRequest rr = new RouteRequest();
rr.addWaypoint(fromText);
rr.addWaypoint(toText);
//rr.setRoutePathOutput(RoutePathOutput.Points);
bmService.RouteAsync(rr);
} catch (Exception e) {
Message v = new Message();
v.arg1 = 0;
loadingScreenHandler.sendMessage(v);
}
}
}
});
directionsAlert.show();
}
public static void LaunchEntityDetailsDialog(final Activity activity, final HashMap<String, Object> metadata) {
if (metadata.size() > 0) {
if (metadata.containsKey("record") && metadata.get("record").getClass() == Record.class) {
Record record = (Record) metadata.get("record");
String title = Utilities.isNullOrEmpty(record.DisplayName) ?
activity.getString(R.string.details) : record.DisplayName;
final ScrollView detailsView = (ScrollView) activity.getLayoutInflater().inflate(R.layout.details_view, (ViewGroup) activity.findViewById(R.id.detailsView));
if (record.Address != null) {
TextView addressView = (TextView) detailsView.findViewById(R.id.detailsAddress);
addressView.setText(activity.getString(R.string.address) + record.Address.toString());
}
if (!Utilities.isNullOrEmpty(record.Phone)) {
final String phone = "tel:" + record.Phone;
ImageButton phoneBtn = (ImageButton) detailsView.findViewById(R.id.detailsPhoneBtn);
phoneBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//Call phone number
Intent i = new Intent(Intent.ACTION_DIAL, Uri.parse(phone));
activity.startActivity(i);
}
});
phoneBtn.setVisibility(View.VISIBLE);
}
//OPTION Add custom content to view
LinearLayout ccView = (LinearLayout) detailsView.findViewById(R.id.detailsCustomContent);
if (record.Metadata.containsKey("Manager")) {
String manager = (String) record.Metadata.get("Manager");
if (!Utilities.isNullOrEmpty(manager)) {
TextView managerView = new TextView(activity);
managerView.setText("Manager: " + manager);
ccView.addView(managerView);
}
}
if (record.Metadata.containsKey("StoreType")) {
String storeType = (String) record.Metadata.get("StoreType");
if (!Utilities.isNullOrEmpty(storeType)) {
TextView storeTypeView = new TextView(activity);
storeTypeView.setText("Store Type: " + storeType);
ccView.addView(storeTypeView);
}
}
AlertDialog.Builder detailsAlert = new AlertDialog.Builder(activity)
.setTitle(title)
.setView(detailsView)
.setNegativeButton(activity.getString(R.string.close), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled. Do nothing
}
});
detailsAlert.show();
} else {
//OPTION add support for HashMap so that data other than records
//from the Bing Spatial Data Services can be rendered.
}
}
}
public static void LaunchOverrideCultureDialog(final Activity activity, final BingMapsView bingMapsView) {
final View cultureView = activity.getLayoutInflater().inflate(R.layout.culture_input, (ViewGroup) activity.findViewById(R.id.cultureInputView));
AlertDialog.Builder cultureAlert = new AlertDialog.Builder(activity)
.setTitle(activity.getString(R.string.culture_mkt_param))
.setIcon(android.R.drawable.ic_menu_search)
.setView(cultureView)
.setNegativeButton(activity.getString(R.string.cancel), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled. Do nothing
}
})
.setPositiveButton(activity.getString(R.string.change), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
EditText input = (EditText) cultureView.findViewById(R.id.cultureInput);
bingMapsView.overrideCulture(input.getText().toString().trim());
}
});
cultureAlert.show();
}
public static void DemoDataApi(final BingMapsView bingMapsView, final Handler loadingScreenHandler, org.bingmaps.rest.models.Location l) {
//Search for nearby locations
BingSpatialDataService bsds = new BingSpatialDataService(
Constants.BingSpatialAccessId,
Constants.BingSpatialDataSourceName,
Constants.BingSpatialEntityTypeName,
Constants.BingSpatialQueryKey);
//Perform a nearby search for POI data
bsds.FindByAreaCompleted = new Handler() {
public void handleMessage(Message msg) {
if (msg.obj != null) {
Record[] records = (Record[]) msg.obj;
EntityLayer el = (EntityLayer) bingMapsView.getLayerManager().getLayerByName(Constants.DataLayers.Search);
double maxLat = -90, minLat = 90, maxLon = -180, minLon = 180;
for (Record r : records) {
Pushpin p = new Pushpin(r.Location);
p.Title = r.DisplayName;
if (r.Location.Latitude > maxLat) {
maxLat = r.Location.Latitude;
}
if (r.Location.Longitude > maxLon) {
maxLon = r.Location.Longitude;
}
if (r.Location.Latitude < minLat) {
minLat = r.Location.Latitude;
}
if (r.Location.Longitude < minLon) {
minLon = r.Location.Longitude;
}
HashMap<String, Object> metadata = new HashMap<String, Object>();
metadata.put("record", r);
el.add(p, metadata);
}
bingMapsView.setMapView(new LocationRect(maxLat, maxLon, minLat, minLon));
el.updateLayer();
}
Message v = new Message();
v.arg1 = 0;
loadingScreenHandler.sendMessage(v);
}
};
bsds.FindByArea(l.Point, Constants.SearchRadiusKM, null);
}
public static void LaunchAccessibleDialog(Activity activity, final BingMapsView bingMapsView, final Handler loadingScreenHandler) {
final View accessibleView = activity.getLayoutInflater().inflate(R.layout.accessible_input, (ViewGroup) activity.findViewById(R.id.accessibleView));
AlertDialog.Builder accessibleAlert = new AlertDialog.Builder(activity)
.setTitle("Confirm Accessibility")
.setIcon(android.R.drawable.ic_menu_crop)
.setView(accessibleView)
.setNegativeButton(activity.getString(R.string.cancel), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled. Do nothing
}
})
.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
EditText input = (EditText) accessibleView.findViewById(R.id.accessibleInput);
String accessibilityText = input.getText().toString().trim();
if (!Utilities.isNullOrEmpty(accessibilityText)) {
Message viewMsg = new Message();
viewMsg.arg1 = 1;
loadingScreenHandler.sendMessage(viewMsg);
try {
BingMapsRestService bmService = new BingMapsRestService(Constants.BingMapsKey);
bmService.GeocodeAsyncCompleted = new Handler() {
public void handleMessage(Message msg) {
if (msg.obj != null) {
org.bingmaps.rest.models.Location[] locations = (org.bingmaps.rest.models.Location[]) msg.obj;
org.bingmaps.rest.models.Location l = locations[0];
if (l.Point != null) {
clearLayers(bingMapsView);
EntityLayer searchLayer = (EntityLayer) bingMapsView.getLayerManager().getLayerByName(Constants.DataLayers.Search);
basicReadWrite((l.Point.Latitude+"_"+l.Point.Longitude).replace(".","p"),true, "");
PushpinOptions po = new PushpinOptions();
po.Icon = Constants.PushpinIcons.Access;
po.Width = 20;
po.Height = 35;
po.Anchor = new Point(4, 35);
Pushpin location = new Pushpin(l.Point, po);
searchLayer.add(location);
bingMapsView.getLayerManager().addLayer(searchLayer);
searchLayer.updateLayer();
bingMapsView.setCenterAndZoom(l.Point, Constants.DefaultSearchZoomLevel);
Message v = new Message();
v.arg1 = 0;
loadingScreenHandler.sendMessage(v);
} else {
Message v = new Message();
v.arg1 = 0;
loadingScreenHandler.sendMessage(v);
}
} else {
Message v = new Message();
v.arg1 = 0;
loadingScreenHandler.sendMessage(v);
}
}
};
bmService.GeocodeAsync(accessibilityText);
} catch (Exception e) {
Message v = new Message();
v.arg1 = 0;
loadingScreenHandler.sendMessage(v);
}
}
}
});
accessibleAlert.show();
}
}
|
3e070b140730c6a21e3b26a9187b8983ceeedf82 | 2,884 | java | Java | src/test/java/com/trickl/oanda/client/BaseRestClientTest.java | trickl/oanda-java-client | f9bd6664b2cb6f1ce8242618d51aadc07a6c8eeb | [
"Apache-2.0"
] | 1 | 2021-02-17T07:26:08.000Z | 2021-02-17T07:26:08.000Z | src/test/java/com/trickl/oanda/client/BaseRestClientTest.java | trickl/oanda-java-client | f9bd6664b2cb6f1ce8242618d51aadc07a6c8eeb | [
"Apache-2.0"
] | null | null | null | src/test/java/com/trickl/oanda/client/BaseRestClientTest.java | trickl/oanda-java-client | f9bd6664b2cb6f1ce8242618d51aadc07a6c8eeb | [
"Apache-2.0"
] | null | null | null | 32.772727 | 94 | 0.730583 | 2,986 | package com.trickl.oanda.client;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.function.Consumer;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
import okhttp3.mockwebserver.RecordedRequest;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.reactive.ReactorClientHttpConnector;
import org.springframework.web.reactive.function.client.WebClient;
public abstract class BaseRestClientTest {
protected MockWebServer server;
protected WebClient webClient;
protected Validator validator;
protected void startServer() {
server = new MockWebServer();
webClient =
WebClient.builder()
.clientConnector(new ReactorClientHttpConnector())
.baseUrl(server.url("/").toString())
.build();
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
validator = factory.getValidator();
}
protected void prepareResponse(String fileName) throws IOException {
Path responsePath = classAsResourcePathConvention(this.getClass(), fileName);
String responseContent = new String(Files.readAllBytes(responsePath));
prepareResponse(
response ->
response.setHeader("Content-Type", "application/json").setBody(responseContent));
}
protected void prepareResponse(Consumer<MockResponse> consumer) {
MockResponse response = new MockResponse();
consumer.accept(response);
this.server.enqueue(response);
}
protected void expectPath(String path) {
expectRequest(path, HttpMethod.GET);
}
protected void expectRequest(String path, HttpMethod method) {
expectRequest(
request -> {
assertThat(request.getPath()).isEqualTo(path);
assertThat(request.getMethod()).isEqualTo(method.toString());
});
}
protected void expectRequest(Consumer<RecordedRequest> consumer) {
try {
consumer.accept(this.server.takeRequest());
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
throw new IllegalStateException(ex);
}
}
protected void expectRequestCount(int count) {
assertThat(this.server.getRequestCount()).isEqualTo(count);
}
private <T> Path classAsResourcePathConvention(Class<T> clazz, String filename) {
String resourcePath = clazz.getProtectionDomain().getCodeSource().getLocation().getPath();
String projectDir = resourcePath.substring(0, resourcePath.indexOf("target"));
return Paths.get(
projectDir,
"src/test/resources/",
clazz.getPackage().getName().replaceAll("\\.", "/"),
filename);
}
}
|
3e070b486cd32d2ffdec8527f75aabe1ed8a248d | 1,813 | java | Java | src/main/java/es/upm/oeg/librairy/api/model/Task.java | librairy/api | 50fb1a4b1c4c37849378aaab6dedcd9fe95c38d0 | [
"Apache-2.0"
] | null | null | null | src/main/java/es/upm/oeg/librairy/api/model/Task.java | librairy/api | 50fb1a4b1c4c37849378aaab6dedcd9fe95c38d0 | [
"Apache-2.0"
] | null | null | null | src/main/java/es/upm/oeg/librairy/api/model/Task.java | librairy/api | 50fb1a4b1c4c37849378aaab6dedcd9fe95c38d0 | [
"Apache-2.0"
] | 1 | 2019-10-01T13:35:54.000Z | 2019-10-01T13:35:54.000Z | 25.549296 | 74 | 0.657111 | 2,987 | package es.upm.oeg.librairy.api.model;
import es.upm.oeg.librairy.api.facade.model.avro.AnnotationsRequest;
import es.upm.oeg.librairy.api.facade.model.avro.DocumentsRequest;
import es.upm.oeg.librairy.api.facade.model.avro.TopicsRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Badenes Olmedo, Carlos <dycjh@example.com>
*/
public class Task {
private static final Logger LOG = LoggerFactory.getLogger(Task.class);
private TopicsRequest topicsRequest;
private AnnotationsRequest annotationsRequest;
private DocumentsRequest documentsRequest;
public enum Type {
TOPICS, ANNOTATIONS, DOCUMENTS, CLEAN
}
private final Type type;
public Task(DocumentsRequest request) {
this.type = Type.DOCUMENTS;
this.documentsRequest = request;
}
public Task() {
this.type = Type.CLEAN;
}
public Task(TopicsRequest topicsRequest) {
this.type = Type.TOPICS;
this.topicsRequest = topicsRequest;
}
public Task(AnnotationsRequest annotationsRequest) {
this.type = Type.ANNOTATIONS;
this.annotationsRequest = annotationsRequest;
}
public Type getType() {
return type;
}
public TopicsRequest getTopicsRequest() {
return topicsRequest;
}
public AnnotationsRequest getAnnotationsRequest() {
return annotationsRequest;
}
public DocumentsRequest getDocumentsRequest() {
return documentsRequest;
}
@Override
public String toString() {
return "Task{" +
"topicsRequest=" + topicsRequest +
", annotationsRequest=" + annotationsRequest +
", documentsRequest=" + documentsRequest +
", type=" + type +
'}';
}
}
|
3e070c0e5cebde7472aad42059990f0ae124a2f1 | 1,797 | java | Java | modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201408/RateCardAction.java | david-gorisse/googleads-java-lib | 03b8c7e83bc5a361e374d345afdd93290d143c34 | [
"Apache-2.0"
] | null | null | null | modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201408/RateCardAction.java | david-gorisse/googleads-java-lib | 03b8c7e83bc5a361e374d345afdd93290d143c34 | [
"Apache-2.0"
] | null | null | null | modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201408/RateCardAction.java | david-gorisse/googleads-java-lib | 03b8c7e83bc5a361e374d345afdd93290d143c34 | [
"Apache-2.0"
] | null | null | null | 24.958333 | 113 | 0.648303 | 2,988 |
package com.google.api.ads.dfp.jaxws.v201408;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlType;
/**
*
* Represents the actions that can be performed on {@link RateCard} objects.
*
*
* <p>Java class for RateCardAction complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="RateCardAction">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="RateCardAction.Type" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "RateCardAction", propOrder = {
"rateCardActionType"
})
@XmlSeeAlso({
ActivateRateCards.class,
DeactivateRateCards.class
})
public abstract class RateCardAction {
@XmlElement(name = "RateCardAction.Type")
protected String rateCardActionType;
/**
* Gets the value of the rateCardActionType property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRateCardActionType() {
return rateCardActionType;
}
/**
* Sets the value of the rateCardActionType property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRateCardActionType(String value) {
this.rateCardActionType = value;
}
}
|
3e070d6b9ae5cd7a5e720b378374523d440ca290 | 5,889 | java | Java | data-holder/src/main/java/au/org/consumerdatastandards/holder/api/ApiControllerBase.java | tsunami-code/java-artefacts | 6ac50b885e91de0e27144861f41d2b2c08c61211 | [
"MIT"
] | null | null | null | data-holder/src/main/java/au/org/consumerdatastandards/holder/api/ApiControllerBase.java | tsunami-code/java-artefacts | 6ac50b885e91de0e27144861f41d2b2c08c61211 | [
"MIT"
] | null | null | null | data-holder/src/main/java/au/org/consumerdatastandards/holder/api/ApiControllerBase.java | tsunami-code/java-artefacts | 6ac50b885e91de0e27144861f41d2b2c08c61211 | [
"MIT"
] | null | null | null | 42.366906 | 137 | 0.67295 | 2,989 | package au.org.consumerdatastandards.holder.api;
import au.org.consumerdatastandards.holder.model.LinksPaginated;
import au.org.consumerdatastandards.holder.model.MetaPaginated;
import au.org.consumerdatastandards.holder.model.TxMetaPaginated;
import au.org.consumerdatastandards.holder.util.WebUtil;
import org.apache.commons.validator.routines.InetAddressValidator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpHeaders;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.NativeWebRequest;
import javax.validation.ValidationException;
import java.util.UUID;
public class ApiControllerBase {
private final static String V = "x-v";
private final static String MIN_V = "x-min-v";
private final static String CORRELATION_ID = "x-Correlation-Id";
private final static String FAPI_INTERACTION_ID = "x-fapi-interaction-id";
private final static String BASE64_PATTERN = "^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?$";
protected Logger logger = LoggerFactory.getLogger(this.getClass());
protected Integer getPagingValue(Integer page, int defaultValue) {
return page != null && page > 0 ? page : defaultValue;
}
protected void validatePageInputs(Integer page, Integer pageSize) {
if (page != null && page < 1 || pageSize != null && pageSize < 1) {
throw new ValidationException("Invalid page or page-size");
}
}
protected boolean hasSupportedVersion(Integer xMinV, Integer xV) {
if (xV == null) return false;
return (xMinV == null || getCurrentVersion() >= xMinV) && (xMinV != null || getCurrentVersion() >= xV);
}
protected Integer getSupportedVersion(Integer xMinV, Integer xV) {
validateHeaders(xMinV, xV);
if (xMinV == null) return xV;
return Math.min(xV, getCurrentVersion());
}
protected Integer getCurrentVersion() {
return 1;
}
protected HttpHeaders generateResponseHeaders(NativeWebRequest request) {
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.set("content-type", "application/json");
Integer xMinV = null;
String minV = request.getHeader(MIN_V);
if (StringUtils.hasText(minV)) {
xMinV = Integer.parseInt(minV);
}
Integer xV = Integer.parseInt(request.getHeader(V));
responseHeaders.set(V, "" + getSupportedVersion(xMinV, xV));
String correlationId = request.getHeader(CORRELATION_ID);
if (!StringUtils.isEmpty(correlationId)) {
responseHeaders.set(CORRELATION_ID, correlationId);
}
String fapiInteractionId = request.getHeader(FAPI_INTERACTION_ID);
if (!StringUtils.isEmpty(fapiInteractionId)) {
responseHeaders.set(FAPI_INTERACTION_ID, fapiInteractionId);
} else {
responseHeaders.set(FAPI_INTERACTION_ID, UUID.randomUUID().toString());
}
return responseHeaders;
}
protected void validateHeaders(Integer xMinV, Integer xV) {
if (!hasSupportedVersion(xMinV, xV)) {
String message = String.format(
"Unsupported version requested, minimum version specified is %d, maximum version specified is %d, current version is %d",
xMinV, xV, getCurrentVersion());
throw new VersionNotSupportedException(message);
}
}
protected void validateHeaders(String xCdsClientHeaders,
String xFapiCustomerIpAddress,
Integer xMinV, Integer xV) {
validateHeaders(xMinV, xV);
if (StringUtils.hasText(xFapiCustomerIpAddress)) {
InetAddressValidator inetAddressValidator = InetAddressValidator.getInstance();
if (!inetAddressValidator.isValid(xFapiCustomerIpAddress)) {
throw new ValidationException("request header x-fapi-customer-ip-address is not valid IP address");
}
if (StringUtils.isEmpty(xCdsClientHeaders)) {
throw new ValidationException("request header x-cds-client-headers is not present");
} else if (!xCdsClientHeaders.matches(BASE64_PATTERN)) {
throw new ValidationException("request header x-cds-client-headers is not Base64 encoded");
}
}
}
protected LinksPaginated getLinkData(NativeWebRequest request, Page page, Integer actualPage, Integer actualPageSize) {
LinksPaginated linkData = new LinksPaginated();
linkData.setSelf(WebUtil.getOriginalUrl(request));
if (page.getTotalPages() == 0) {
linkData.setFirst(null);
linkData.setLast(null);
} else {
linkData.setFirst(WebUtil.getPaginatedLink(request, 1, actualPageSize));
linkData.setLast(WebUtil.getPaginatedLink(request, page.getTotalPages(), actualPageSize));
}
if (page.hasPrevious()) {
linkData.setPrev(WebUtil.getPaginatedLink(request, actualPage - 1, actualPageSize));
}
if (page.hasNext()) {
linkData.setPrev(WebUtil.getPaginatedLink(request, actualPage + 1, actualPageSize));
}
return linkData;
}
protected MetaPaginated getMetaData(Page page) {
MetaPaginated metaData = new MetaPaginated();
metaData.setTotalPages(page.getTotalPages());
metaData.setTotalRecords((int)page.getTotalElements());
return metaData;
}
protected TxMetaPaginated getTxMetaData(Page page, boolean isQueryParamUnsupported) {
TxMetaPaginated metaData = new TxMetaPaginated();
metaData.setTotalPages(page.getTotalPages());
metaData.setTotalRecords((int)page.getTotalElements());
return metaData;
}
}
|
3e070dccd5ecbc2e36fc91185ef5b9ecd5fc338d | 2,020 | java | Java | src/main/java/space/devport/wertik/treasures/commands/tool/subcommands/DeleteSubCommand.java | Wertik/ShinyTreasures | 16ddbb0fa2572bc59d8dadba9cfc653d6f515f8c | [
"MIT"
] | null | null | null | src/main/java/space/devport/wertik/treasures/commands/tool/subcommands/DeleteSubCommand.java | Wertik/ShinyTreasures | 16ddbb0fa2572bc59d8dadba9cfc653d6f515f8c | [
"MIT"
] | null | null | null | src/main/java/space/devport/wertik/treasures/commands/tool/subcommands/DeleteSubCommand.java | Wertik/ShinyTreasures | 16ddbb0fa2572bc59d8dadba9cfc653d6f515f8c | [
"MIT"
] | null | null | null | 31.5625 | 88 | 0.662376 | 2,990 | package space.devport.wertik.treasures.commands.tool.subcommands;
import org.bukkit.command.CommandSender;
import org.jetbrains.annotations.Nullable;
import space.devport.dock.commands.struct.ArgumentRange;
import space.devport.dock.commands.struct.CommandResult;
import space.devport.wertik.treasures.TreasurePlugin;
import space.devport.wertik.treasures.commands.TreasureSubCommand;
import space.devport.wertik.treasures.system.tool.struct.PlacementTool;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
public class DeleteSubCommand extends TreasureSubCommand {
public DeleteSubCommand(TreasurePlugin plugin) {
super(plugin, "delete");
}
@Override
protected CommandResult perform(CommandSender sender, String label, String[] args) {
PlacementTool tool = plugin.getToolManager().getTool(args[0]);
if (tool == null) {
language.getPrefixed("Commands.Invalid-Tool")
.replace("%param%", args[0])
.send(sender);
return CommandResult.FAILURE;
}
plugin.getToolManager().deleteTool(tool);
language.getPrefixed("Commands.Tools.Delete.Done")
.replace("%tool%", tool.getName())
.send(sender);
return CommandResult.SUCCESS;
}
@Override
public List<String> requestTabComplete(CommandSender sender, String[] args) {
if (args.length == 1) {
return plugin.getToolManager().getLoadedTools().values().stream()
.map(PlacementTool::getName)
.collect(Collectors.toList());
}
return new ArrayList<>();
}
@Override
public @Nullable String getDefaultUsage() {
return "/%label% delete <toolName>";
}
@Override
public @Nullable String getDefaultDescription() {
return "Delete a tool.";
}
@Override
public @Nullable ArgumentRange getRange() {
return new ArgumentRange(1);
}
}
|
3e070e27a338e7d88fa011fdba12bad18ba4de25 | 27,248 | java | Java | src/main/java/marc/henrard/murisq/pricer/decomposition/MulticurveEquivalent.java | marc-henrard/muRisQ-ir-models | 30e909262102278777f90c64a7295c99da631b4e | [
"Apache-2.0"
] | 5 | 2019-02-15T05:36:30.000Z | 2022-03-24T19:41:23.000Z | src/main/java/marc/henrard/murisq/pricer/decomposition/MulticurveEquivalent.java | marc-henrard/muRisQ-ir-models | 30e909262102278777f90c64a7295c99da631b4e | [
"Apache-2.0"
] | null | null | null | src/main/java/marc/henrard/murisq/pricer/decomposition/MulticurveEquivalent.java | marc-henrard/muRisQ-ir-models | 30e909262102278777f90c64a7295c99da631b4e | [
"Apache-2.0"
] | 1 | 2021-08-31T04:29:48.000Z | 2021-08-31T04:29:48.000Z | 38.485876 | 134 | 0.666361 | 2,991 | /**
* Copyright (C) 2015 - present by Marc Henrard.
*/
package marc.henrard.murisq.pricer.decomposition;
import java.io.Serializable;
import org.joda.beans.ImmutableBean;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import org.joda.beans.JodaBeanUtils;
import org.joda.beans.MetaProperty;
import org.joda.beans.impl.direct.DirectFieldsBeanBuilder;
import org.joda.beans.impl.direct.DirectMetaBean;
import org.joda.beans.impl.direct.DirectMetaPropertyMap;
import com.google.common.collect.ImmutableList;
import com.opengamma.strata.collect.ArgChecker;
import com.opengamma.strata.product.rate.IborRateComputation;
import com.opengamma.strata.product.rate.OvernightCompoundedRateComputation;
import com.opengamma.strata.product.swap.NotionalExchange;
import org.joda.beans.Bean;
import org.joda.beans.impl.direct.DirectMetaProperty;
import org.joda.beans.MetaBean;
import org.joda.beans.gen.BeanDefinition;
import org.joda.beans.gen.PropertyDefinition;
/**
* Class describing the dates and amount required to price interest rate derivatives in the multi-curve framework.
* The data type is used in particular for Monte Carlo pricing.
* <p>
* One 'equivalent' is generated for each decision time, they are not path dependent but a simplified description
* of the decision or option to take.
*/
@BeanDefinition(factoryName = "of")
public final class MulticurveEquivalent
implements ImmutableBean, Serializable {
/** The date at which an exercise or fixing takes place. */
@PropertyDefinition
private final ZonedDateTime decisionTime;
/** The dates and amounts impacting the value through discount factors at each decision date. */
@PropertyDefinition(validate = "notNull")
private final List<NotionalExchange> discountFactorPayments;
/** The rates impacting the value through ibor fixing at the decision date. */
@PropertyDefinition(validate = "notNull")
private final List<IborRateComputation> iborComputations;
/** The reference amounts and payment date for each ibor observation. */
@PropertyDefinition(validate = "notNull")
private final List<NotionalExchange> iborPayments;
/** The date impacting the value through overnight compounded periods at the decision date. */
@PropertyDefinition(validate = "notNull")
private final List<OvernightCompoundedRateComputation> onComputations;
/** The reference amounts and payment date for each overnight observation. */
@PropertyDefinition(validate = "notNull")
private final List<NotionalExchange> onPayments;
//-------------------------------------------------------------------------
/**
* Creates an empty schedule with all the lists empty and the decision date the given date.
*
* @return the schedule
*/
public static MulticurveEquivalent empty() {
return MulticurveEquivalent.builder()
.discountFactorPayments(new ArrayList<NotionalExchange>())
.iborComputations(new ArrayList<IborRateComputation>())
.iborPayments(new ArrayList<NotionalExchange>())
.onComputations(new ArrayList<OvernightCompoundedRateComputation>())
.onPayments(new ArrayList<NotionalExchange>())
.build();
}
//-------------------------------------------------------------------------
/**
* Combines this schedule with another instance.
* <p>
* This returns a new schedule instance with the specified payments added.
* This instance is immutable and unaffected by this method.
* The result may contain duplicate payments.
*
* @param other the other schedule
* @return an instance based on this one, with the other instance added
*/
public MulticurveEquivalent combinedWith(MulticurveEquivalent other) {
ArgChecker.isTrue(this.decisionTime == null ||
other.decisionTime == null ||
this.decisionTime.equals(other.decisionTime), "decision dates should be equal");
List<NotionalExchange> combinedDiscountFactorPayments = new ArrayList<>(discountFactorPayments);
combinedDiscountFactorPayments.addAll(other.discountFactorPayments);
List<IborRateComputation> combinedIborObservations = new ArrayList<>(iborComputations);
combinedIborObservations.addAll(other.iborComputations);
List<NotionalExchange> combinedIborPayments = new ArrayList<>(iborPayments);
combinedIborPayments.addAll(other.iborPayments);
List<OvernightCompoundedRateComputation> combinedOnObservations = new ArrayList<>(onComputations);
combinedOnObservations.addAll(other.onComputations);
List<NotionalExchange> combinedOnPayments = new ArrayList<>(onPayments);
combinedOnPayments.addAll(other.onPayments);
return MulticurveEquivalent.builder()
.decisionTime((decisionTime != null) ? decisionTime : other.decisionTime)
.discountFactorPayments(combinedDiscountFactorPayments)
.iborComputations(combinedIborObservations)
.iborPayments(combinedIborPayments)
.onComputations(combinedOnObservations)
.onPayments(combinedOnPayments)
.build();
}
//------------------------- AUTOGENERATED START -------------------------
/**
* The meta-bean for {@code MulticurveEquivalent}.
* @return the meta-bean, not null
*/
public static MulticurveEquivalent.Meta meta() {
return MulticurveEquivalent.Meta.INSTANCE;
}
static {
MetaBean.register(MulticurveEquivalent.Meta.INSTANCE);
}
/**
* The serialization version id.
*/
private static final long serialVersionUID = 1L;
/**
* Obtains an instance.
* @param decisionTime the value of the property
* @param discountFactorPayments the value of the property, not null
* @param iborComputations the value of the property, not null
* @param iborPayments the value of the property, not null
* @param onComputations the value of the property, not null
* @param onPayments the value of the property, not null
* @return the instance
*/
public static MulticurveEquivalent of(
ZonedDateTime decisionTime,
List<NotionalExchange> discountFactorPayments,
List<IborRateComputation> iborComputations,
List<NotionalExchange> iborPayments,
List<OvernightCompoundedRateComputation> onComputations,
List<NotionalExchange> onPayments) {
return new MulticurveEquivalent(
decisionTime,
discountFactorPayments,
iborComputations,
iborPayments,
onComputations,
onPayments);
}
/**
* Returns a builder used to create an instance of the bean.
* @return the builder, not null
*/
public static MulticurveEquivalent.Builder builder() {
return new MulticurveEquivalent.Builder();
}
private MulticurveEquivalent(
ZonedDateTime decisionTime,
List<NotionalExchange> discountFactorPayments,
List<IborRateComputation> iborComputations,
List<NotionalExchange> iborPayments,
List<OvernightCompoundedRateComputation> onComputations,
List<NotionalExchange> onPayments) {
JodaBeanUtils.notNull(discountFactorPayments, "discountFactorPayments");
JodaBeanUtils.notNull(iborComputations, "iborComputations");
JodaBeanUtils.notNull(iborPayments, "iborPayments");
JodaBeanUtils.notNull(onComputations, "onComputations");
JodaBeanUtils.notNull(onPayments, "onPayments");
this.decisionTime = decisionTime;
this.discountFactorPayments = ImmutableList.copyOf(discountFactorPayments);
this.iborComputations = ImmutableList.copyOf(iborComputations);
this.iborPayments = ImmutableList.copyOf(iborPayments);
this.onComputations = ImmutableList.copyOf(onComputations);
this.onPayments = ImmutableList.copyOf(onPayments);
}
@Override
public MulticurveEquivalent.Meta metaBean() {
return MulticurveEquivalent.Meta.INSTANCE;
}
//-----------------------------------------------------------------------
/**
* Gets the date at which an exercise or fixing takes place.
* @return the value of the property
*/
public ZonedDateTime getDecisionTime() {
return decisionTime;
}
//-----------------------------------------------------------------------
/**
* Gets the dates and amounts impacting the value through discount factors at each decision date.
* @return the value of the property, not null
*/
public List<NotionalExchange> getDiscountFactorPayments() {
return discountFactorPayments;
}
//-----------------------------------------------------------------------
/**
* Gets the rates impacting the value through ibor fixing at the decision date.
* @return the value of the property, not null
*/
public List<IborRateComputation> getIborComputations() {
return iborComputations;
}
//-----------------------------------------------------------------------
/**
* Gets the reference amounts and payment date for each ibor observation.
* @return the value of the property, not null
*/
public List<NotionalExchange> getIborPayments() {
return iborPayments;
}
//-----------------------------------------------------------------------
/**
* Gets the date impacting the value through overnight compounded periods at the decision date.
* @return the value of the property, not null
*/
public List<OvernightCompoundedRateComputation> getOnComputations() {
return onComputations;
}
//-----------------------------------------------------------------------
/**
* Gets the reference amounts and payment date for each overnight observation.
* @return the value of the property, not null
*/
public List<NotionalExchange> getOnPayments() {
return onPayments;
}
//-----------------------------------------------------------------------
/**
* Returns a builder that allows this bean to be mutated.
* @return the mutable builder, not null
*/
public Builder toBuilder() {
return new Builder(this);
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj != null && obj.getClass() == this.getClass()) {
MulticurveEquivalent other = (MulticurveEquivalent) obj;
return JodaBeanUtils.equal(decisionTime, other.decisionTime) &&
JodaBeanUtils.equal(discountFactorPayments, other.discountFactorPayments) &&
JodaBeanUtils.equal(iborComputations, other.iborComputations) &&
JodaBeanUtils.equal(iborPayments, other.iborPayments) &&
JodaBeanUtils.equal(onComputations, other.onComputations) &&
JodaBeanUtils.equal(onPayments, other.onPayments);
}
return false;
}
@Override
public int hashCode() {
int hash = getClass().hashCode();
hash = hash * 31 + JodaBeanUtils.hashCode(decisionTime);
hash = hash * 31 + JodaBeanUtils.hashCode(discountFactorPayments);
hash = hash * 31 + JodaBeanUtils.hashCode(iborComputations);
hash = hash * 31 + JodaBeanUtils.hashCode(iborPayments);
hash = hash * 31 + JodaBeanUtils.hashCode(onComputations);
hash = hash * 31 + JodaBeanUtils.hashCode(onPayments);
return hash;
}
@Override
public String toString() {
StringBuilder buf = new StringBuilder(224);
buf.append("MulticurveEquivalent{");
buf.append("decisionTime").append('=').append(JodaBeanUtils.toString(decisionTime)).append(',').append(' ');
buf.append("discountFactorPayments").append('=').append(JodaBeanUtils.toString(discountFactorPayments)).append(',').append(' ');
buf.append("iborComputations").append('=').append(JodaBeanUtils.toString(iborComputations)).append(',').append(' ');
buf.append("iborPayments").append('=').append(JodaBeanUtils.toString(iborPayments)).append(',').append(' ');
buf.append("onComputations").append('=').append(JodaBeanUtils.toString(onComputations)).append(',').append(' ');
buf.append("onPayments").append('=').append(JodaBeanUtils.toString(onPayments));
buf.append('}');
return buf.toString();
}
//-----------------------------------------------------------------------
/**
* The meta-bean for {@code MulticurveEquivalent}.
*/
public static final class Meta extends DirectMetaBean {
/**
* The singleton instance of the meta-bean.
*/
static final Meta INSTANCE = new Meta();
/**
* The meta-property for the {@code decisionTime} property.
*/
private final MetaProperty<ZonedDateTime> decisionTime = DirectMetaProperty.ofImmutable(
this, "decisionTime", MulticurveEquivalent.class, ZonedDateTime.class);
/**
* The meta-property for the {@code discountFactorPayments} property.
*/
@SuppressWarnings({"unchecked", "rawtypes" })
private final MetaProperty<List<NotionalExchange>> discountFactorPayments = DirectMetaProperty.ofImmutable(
this, "discountFactorPayments", MulticurveEquivalent.class, (Class) List.class);
/**
* The meta-property for the {@code iborComputations} property.
*/
@SuppressWarnings({"unchecked", "rawtypes" })
private final MetaProperty<List<IborRateComputation>> iborComputations = DirectMetaProperty.ofImmutable(
this, "iborComputations", MulticurveEquivalent.class, (Class) List.class);
/**
* The meta-property for the {@code iborPayments} property.
*/
@SuppressWarnings({"unchecked", "rawtypes" })
private final MetaProperty<List<NotionalExchange>> iborPayments = DirectMetaProperty.ofImmutable(
this, "iborPayments", MulticurveEquivalent.class, (Class) List.class);
/**
* The meta-property for the {@code onComputations} property.
*/
@SuppressWarnings({"unchecked", "rawtypes" })
private final MetaProperty<List<OvernightCompoundedRateComputation>> onComputations = DirectMetaProperty.ofImmutable(
this, "onComputations", MulticurveEquivalent.class, (Class) List.class);
/**
* The meta-property for the {@code onPayments} property.
*/
@SuppressWarnings({"unchecked", "rawtypes" })
private final MetaProperty<List<NotionalExchange>> onPayments = DirectMetaProperty.ofImmutable(
this, "onPayments", MulticurveEquivalent.class, (Class) List.class);
/**
* The meta-properties.
*/
private final Map<String, MetaProperty<?>> metaPropertyMap$ = new DirectMetaPropertyMap(
this, null,
"decisionTime",
"discountFactorPayments",
"iborComputations",
"iborPayments",
"onComputations",
"onPayments");
/**
* Restricted constructor.
*/
private Meta() {
}
@Override
protected MetaProperty<?> metaPropertyGet(String propertyName) {
switch (propertyName.hashCode()) {
case 676112585: // decisionTime
return decisionTime;
case -423483075: // discountFactorPayments
return discountFactorPayments;
case -1568013720: // iborComputations
return iborComputations;
case 1878994953: // iborPayments
return iborPayments;
case -39109877: // onComputations
return onComputations;
case -142331348: // onPayments
return onPayments;
}
return super.metaPropertyGet(propertyName);
}
@Override
public MulticurveEquivalent.Builder builder() {
return new MulticurveEquivalent.Builder();
}
@Override
public Class<? extends MulticurveEquivalent> beanType() {
return MulticurveEquivalent.class;
}
@Override
public Map<String, MetaProperty<?>> metaPropertyMap() {
return metaPropertyMap$;
}
//-----------------------------------------------------------------------
/**
* The meta-property for the {@code decisionTime} property.
* @return the meta-property, not null
*/
public MetaProperty<ZonedDateTime> decisionTime() {
return decisionTime;
}
/**
* The meta-property for the {@code discountFactorPayments} property.
* @return the meta-property, not null
*/
public MetaProperty<List<NotionalExchange>> discountFactorPayments() {
return discountFactorPayments;
}
/**
* The meta-property for the {@code iborComputations} property.
* @return the meta-property, not null
*/
public MetaProperty<List<IborRateComputation>> iborComputations() {
return iborComputations;
}
/**
* The meta-property for the {@code iborPayments} property.
* @return the meta-property, not null
*/
public MetaProperty<List<NotionalExchange>> iborPayments() {
return iborPayments;
}
/**
* The meta-property for the {@code onComputations} property.
* @return the meta-property, not null
*/
public MetaProperty<List<OvernightCompoundedRateComputation>> onComputations() {
return onComputations;
}
/**
* The meta-property for the {@code onPayments} property.
* @return the meta-property, not null
*/
public MetaProperty<List<NotionalExchange>> onPayments() {
return onPayments;
}
//-----------------------------------------------------------------------
@Override
protected Object propertyGet(Bean bean, String propertyName, boolean quiet) {
switch (propertyName.hashCode()) {
case 676112585: // decisionTime
return ((MulticurveEquivalent) bean).getDecisionTime();
case -423483075: // discountFactorPayments
return ((MulticurveEquivalent) bean).getDiscountFactorPayments();
case -1568013720: // iborComputations
return ((MulticurveEquivalent) bean).getIborComputations();
case 1878994953: // iborPayments
return ((MulticurveEquivalent) bean).getIborPayments();
case -39109877: // onComputations
return ((MulticurveEquivalent) bean).getOnComputations();
case -142331348: // onPayments
return ((MulticurveEquivalent) bean).getOnPayments();
}
return super.propertyGet(bean, propertyName, quiet);
}
@Override
protected void propertySet(Bean bean, String propertyName, Object newValue, boolean quiet) {
metaProperty(propertyName);
if (quiet) {
return;
}
throw new UnsupportedOperationException("Property cannot be written: " + propertyName);
}
}
//-----------------------------------------------------------------------
/**
* The bean-builder for {@code MulticurveEquivalent}.
*/
public static final class Builder extends DirectFieldsBeanBuilder<MulticurveEquivalent> {
private ZonedDateTime decisionTime;
private List<NotionalExchange> discountFactorPayments = ImmutableList.of();
private List<IborRateComputation> iborComputations = ImmutableList.of();
private List<NotionalExchange> iborPayments = ImmutableList.of();
private List<OvernightCompoundedRateComputation> onComputations = ImmutableList.of();
private List<NotionalExchange> onPayments = ImmutableList.of();
/**
* Restricted constructor.
*/
private Builder() {
}
/**
* Restricted copy constructor.
* @param beanToCopy the bean to copy from, not null
*/
private Builder(MulticurveEquivalent beanToCopy) {
this.decisionTime = beanToCopy.getDecisionTime();
this.discountFactorPayments = ImmutableList.copyOf(beanToCopy.getDiscountFactorPayments());
this.iborComputations = ImmutableList.copyOf(beanToCopy.getIborComputations());
this.iborPayments = ImmutableList.copyOf(beanToCopy.getIborPayments());
this.onComputations = ImmutableList.copyOf(beanToCopy.getOnComputations());
this.onPayments = ImmutableList.copyOf(beanToCopy.getOnPayments());
}
//-----------------------------------------------------------------------
@Override
public Object get(String propertyName) {
switch (propertyName.hashCode()) {
case 676112585: // decisionTime
return decisionTime;
case -423483075: // discountFactorPayments
return discountFactorPayments;
case -1568013720: // iborComputations
return iborComputations;
case 1878994953: // iborPayments
return iborPayments;
case -39109877: // onComputations
return onComputations;
case -142331348: // onPayments
return onPayments;
default:
throw new NoSuchElementException("Unknown property: " + propertyName);
}
}
@SuppressWarnings("unchecked")
@Override
public Builder set(String propertyName, Object newValue) {
switch (propertyName.hashCode()) {
case 676112585: // decisionTime
this.decisionTime = (ZonedDateTime) newValue;
break;
case -423483075: // discountFactorPayments
this.discountFactorPayments = (List<NotionalExchange>) newValue;
break;
case -1568013720: // iborComputations
this.iborComputations = (List<IborRateComputation>) newValue;
break;
case 1878994953: // iborPayments
this.iborPayments = (List<NotionalExchange>) newValue;
break;
case -39109877: // onComputations
this.onComputations = (List<OvernightCompoundedRateComputation>) newValue;
break;
case -142331348: // onPayments
this.onPayments = (List<NotionalExchange>) newValue;
break;
default:
throw new NoSuchElementException("Unknown property: " + propertyName);
}
return this;
}
@Override
public Builder set(MetaProperty<?> property, Object value) {
super.set(property, value);
return this;
}
@Override
public MulticurveEquivalent build() {
return new MulticurveEquivalent(
decisionTime,
discountFactorPayments,
iborComputations,
iborPayments,
onComputations,
onPayments);
}
//-----------------------------------------------------------------------
/**
* Sets the date at which an exercise or fixing takes place.
* @param decisionTime the new value
* @return this, for chaining, not null
*/
public Builder decisionTime(ZonedDateTime decisionTime) {
this.decisionTime = decisionTime;
return this;
}
/**
* Sets the dates and amounts impacting the value through discount factors at each decision date.
* @param discountFactorPayments the new value, not null
* @return this, for chaining, not null
*/
public Builder discountFactorPayments(List<NotionalExchange> discountFactorPayments) {
JodaBeanUtils.notNull(discountFactorPayments, "discountFactorPayments");
this.discountFactorPayments = discountFactorPayments;
return this;
}
/**
* Sets the {@code discountFactorPayments} property in the builder
* from an array of objects.
* @param discountFactorPayments the new value, not null
* @return this, for chaining, not null
*/
public Builder discountFactorPayments(NotionalExchange... discountFactorPayments) {
return discountFactorPayments(ImmutableList.copyOf(discountFactorPayments));
}
/**
* Sets the rates impacting the value through ibor fixing at the decision date.
* @param iborComputations the new value, not null
* @return this, for chaining, not null
*/
public Builder iborComputations(List<IborRateComputation> iborComputations) {
JodaBeanUtils.notNull(iborComputations, "iborComputations");
this.iborComputations = iborComputations;
return this;
}
/**
* Sets the {@code iborComputations} property in the builder
* from an array of objects.
* @param iborComputations the new value, not null
* @return this, for chaining, not null
*/
public Builder iborComputations(IborRateComputation... iborComputations) {
return iborComputations(ImmutableList.copyOf(iborComputations));
}
/**
* Sets the reference amounts and payment date for each ibor observation.
* @param iborPayments the new value, not null
* @return this, for chaining, not null
*/
public Builder iborPayments(List<NotionalExchange> iborPayments) {
JodaBeanUtils.notNull(iborPayments, "iborPayments");
this.iborPayments = iborPayments;
return this;
}
/**
* Sets the {@code iborPayments} property in the builder
* from an array of objects.
* @param iborPayments the new value, not null
* @return this, for chaining, not null
*/
public Builder iborPayments(NotionalExchange... iborPayments) {
return iborPayments(ImmutableList.copyOf(iborPayments));
}
/**
* Sets the date impacting the value through overnight compounded periods at the decision date.
* @param onComputations the new value, not null
* @return this, for chaining, not null
*/
public Builder onComputations(List<OvernightCompoundedRateComputation> onComputations) {
JodaBeanUtils.notNull(onComputations, "onComputations");
this.onComputations = onComputations;
return this;
}
/**
* Sets the {@code onComputations} property in the builder
* from an array of objects.
* @param onComputations the new value, not null
* @return this, for chaining, not null
*/
public Builder onComputations(OvernightCompoundedRateComputation... onComputations) {
return onComputations(ImmutableList.copyOf(onComputations));
}
/**
* Sets the reference amounts and payment date for each overnight observation.
* @param onPayments the new value, not null
* @return this, for chaining, not null
*/
public Builder onPayments(List<NotionalExchange> onPayments) {
JodaBeanUtils.notNull(onPayments, "onPayments");
this.onPayments = onPayments;
return this;
}
/**
* Sets the {@code onPayments} property in the builder
* from an array of objects.
* @param onPayments the new value, not null
* @return this, for chaining, not null
*/
public Builder onPayments(NotionalExchange... onPayments) {
return onPayments(ImmutableList.copyOf(onPayments));
}
//-----------------------------------------------------------------------
@Override
public String toString() {
StringBuilder buf = new StringBuilder(224);
buf.append("MulticurveEquivalent.Builder{");
buf.append("decisionTime").append('=').append(JodaBeanUtils.toString(decisionTime)).append(',').append(' ');
buf.append("discountFactorPayments").append('=').append(JodaBeanUtils.toString(discountFactorPayments)).append(',').append(' ');
buf.append("iborComputations").append('=').append(JodaBeanUtils.toString(iborComputations)).append(',').append(' ');
buf.append("iborPayments").append('=').append(JodaBeanUtils.toString(iborPayments)).append(',').append(' ');
buf.append("onComputations").append('=').append(JodaBeanUtils.toString(onComputations)).append(',').append(' ');
buf.append("onPayments").append('=').append(JodaBeanUtils.toString(onPayments));
buf.append('}');
return buf.toString();
}
}
//-------------------------- AUTOGENERATED END --------------------------
}
|
3e070e7476301e5bd545ef1cb9e5ef313668f1cb | 1,138 | java | Java | app/src/main/java/com/rafaelkarlo/workmode/mainscreen/config/AndroidModule.java | themobilecoder/work-mode-android | 00d127e3e481bf6e18d5a28d4c0ee143f3182122 | [
"MIT"
] | null | null | null | app/src/main/java/com/rafaelkarlo/workmode/mainscreen/config/AndroidModule.java | themobilecoder/work-mode-android | 00d127e3e481bf6e18d5a28d4c0ee143f3182122 | [
"MIT"
] | null | null | null | app/src/main/java/com/rafaelkarlo/workmode/mainscreen/config/AndroidModule.java | themobilecoder/work-mode-android | 00d127e3e481bf6e18d5a28d4c0ee143f3182122 | [
"MIT"
] | 1 | 2020-04-07T17:05:45.000Z | 2020-04-07T17:05:45.000Z | 24.212766 | 82 | 0.749561 | 2,992 | package com.rafaelkarlo.workmode.mainscreen.config;
import android.app.AlarmManager;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.preference.PreferenceManager;
import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
@Module
public class AndroidModule {
private final Application application;
public AndroidModule(Application application) {
this.application = application;
}
@Provides
@Singleton
public Context provideContext() {
return application;
}
@Provides
@Singleton
public AudioManager provideAudioManager() {
return (AudioManager) application.getSystemService(Context.AUDIO_SERVICE);
}
@Provides
@Singleton
public AlarmManager provideAlarmManager() {
return (AlarmManager) application.getSystemService(Context.ALARM_SERVICE);
}
@Provides
@Singleton
public SharedPreferences provideSharedPreferences() {
return PreferenceManager.getDefaultSharedPreferences(application);
}
}
|
3e070f33c46f958010ee9f29bc57e8148bfd1fc1 | 1,012 | java | Java | src/main/java/frc/robot/commands/StopIntake.java | swissskimmilk/2022-Quara-Wallace | cbcc233c80b38ea0568e7d549956579cb0511626 | [
"BSD-3-Clause"
] | null | null | null | src/main/java/frc/robot/commands/StopIntake.java | swissskimmilk/2022-Quara-Wallace | cbcc233c80b38ea0568e7d549956579cb0511626 | [
"BSD-3-Clause"
] | null | null | null | src/main/java/frc/robot/commands/StopIntake.java | swissskimmilk/2022-Quara-Wallace | cbcc233c80b38ea0568e7d549956579cb0511626 | [
"BSD-3-Clause"
] | null | null | null | 24.682927 | 55 | 0.699605 | 2,993 | package frc.robot.commands;
import com.ctre.phoenix.motorcontrol.can.WPI_VictorSPX;
import edu.wpi.first.wpilibj2.command.CommandBase;
import frc.robot.Constants;
import frc.robot.RobotContainer;
import frc.robot.subsystems.Intake;
import frc.robot.subsystems.Climber;
public class StopIntake extends CommandBase{
private Intake subSysIntake;
private Climber m_Climber;
private boolean shooting = false;
private boolean finished = false;
public StopIntake(Intake mIntake, Climber climber)
{
subSysIntake = mIntake;
m_Climber = climber;
addRequirements(subSysIntake, m_Climber);
}
@Override
public void initialize() {
// RobotContainer.topShooter.stopMotor();
// RobotContainer.bottomShooter.stopMotor();
RobotContainer.climberMotor.stopMotor();
}
@Override
public void execute() {
}
@Override
public boolean isFinished() {
// command ends when toggled instead
return true;
}
}
|
3e070f92938bf8c1ecf81b704ea81dfc2bdf31ce | 2,056 | java | Java | clouddriver-core/src/main/groovy/com/netflix/spinnaker/clouddriver/orchestration/events/CreateServerGroupEvent.java | gopaljayanthi/clouddriver | 351a4331560e67d255983c1b3b6122f68a741d27 | [
"Apache-2.0"
] | 382 | 2015-11-16T17:54:23.000Z | 2022-03-24T05:35:37.000Z | clouddriver-core/src/main/groovy/com/netflix/spinnaker/clouddriver/orchestration/events/CreateServerGroupEvent.java | gopaljayanthi/clouddriver | 351a4331560e67d255983c1b3b6122f68a741d27 | [
"Apache-2.0"
] | 2,541 | 2015-11-17T11:22:10.000Z | 2022-03-28T22:30:12.000Z | clouddriver-core/src/main/groovy/com/netflix/spinnaker/clouddriver/orchestration/events/CreateServerGroupEvent.java | gopaljayanthi/clouddriver | 351a4331560e67d255983c1b3b6122f68a741d27 | [
"Apache-2.0"
] | 1,229 | 2015-11-16T19:22:35.000Z | 2022-03-28T18:32:40.000Z | 23.906977 | 76 | 0.655642 | 2,994 | /*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.clouddriver.orchestration.events;
public class CreateServerGroupEvent implements OperationEvent {
private final OperationEvent.Type type = OperationEvent.Type.SERVER_GROUP;
private final OperationEvent.Action action = OperationEvent.Action.CREATE;
private final String cloudProvider;
private final String accountId;
private final String region;
private final String name;
public CreateServerGroupEvent(
String cloudProvider, String accountId, String region, String name) {
this.cloudProvider = cloudProvider;
this.accountId = accountId;
this.region = region;
this.name = name;
}
@Override
public OperationEvent.Type getType() {
return type;
}
@Override
public OperationEvent.Action getAction() {
return action;
}
@Override
public String getCloudProvider() {
return cloudProvider;
}
public String getAccountId() {
return accountId;
}
public String getRegion() {
return region;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "CreateServerGroupEvent{"
+ "type="
+ type
+ ", action="
+ action
+ ", cloudProvider='"
+ cloudProvider
+ '\''
+ ", accountId='"
+ accountId
+ '\''
+ ", region='"
+ region
+ '\''
+ ", name='"
+ name
+ '\''
+ '}';
}
}
|
3e0710ecd969892636620b3371b9cc358574070a | 2,192 | java | Java | xmi/src/main/java/uk/ac/kent/cs/kmf/xmi/XMIReader.java | opatrascoiu/jmf | be597da51fa5964f07ee74213640894af8fff535 | [
"Apache-2.0"
] | null | null | null | xmi/src/main/java/uk/ac/kent/cs/kmf/xmi/XMIReader.java | opatrascoiu/jmf | be597da51fa5964f07ee74213640894af8fff535 | [
"Apache-2.0"
] | null | null | null | xmi/src/main/java/uk/ac/kent/cs/kmf/xmi/XMIReader.java | opatrascoiu/jmf | be597da51fa5964f07ee74213640894af8fff535 | [
"Apache-2.0"
] | null | null | null | 27.746835 | 96 | 0.718066 | 2,995 | package uk.ac.kent.cs.kmf.xmi;
import java.io.File;
import java.io.FileReader;
import java.io.InputStream;
import java.io.Reader;
import uk.ac.kent.cs.kmf.util.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
public class XMIReader
implements IXMIReader
{
public XMIReader() {
}
public XMIFile read(String xmiFileName, ILog log) throws Exception {
this.xmiFileName = xmiFileName;
this.file = new File(xmiFileName);
this.reader = new FileReader(file);
this.log = log;
return read(reader);
}
public XMIFile read(File file, ILog log) throws Exception {
this.xmiFileName = file.getAbsolutePath();
this.file = file;
try {
this.reader = new FileReader(xmiFileName);
} catch (Exception e) {
e.printStackTrace();
}
this.log = log;
return read(reader);
}
public XMIFile read(InputStream stream, ILog log) throws Exception {
return read(stream);
}
protected XMIFile read(Reader reader) throws Exception {
// Create the XML Reader
XMLReader xmlReader = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
// Create and register the XMI Handler
XMIFile xmiFile = new XMIFile(xmiFileName);
XMIHandler handler = new XMIHandler(xmiFile, log);
xmlReader.setContentHandler(handler);
xmlReader.setErrorHandler(handler);
//--- Parse the input file ---
InputSource inputSource = new InputSource(reader);
xmlReader.parse(inputSource);
//--- Return the result ---
return xmiFile;
}
protected XMIFile read(InputStream stream) throws Exception {
// Create the XML Reader
XMLReader xmlReader = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
// Create and register the XMI Handler
XMIFile xmiFile = new XMIFile(xmiFileName);
XMIHandler handler = new XMIHandler(xmiFile, log);
xmlReader.setContentHandler(handler);
xmlReader.setErrorHandler(handler);
//--- Parse the input file ---
InputSource inputSource = new InputSource(stream);
xmlReader.parse(inputSource);
//--- Return the result ---
return xmiFile;
}
protected Reader reader;
protected File file;
protected String xmiFileName;
protected ILog log;
} |
3e071114608826eef1eb42dded8005349975e08d | 2,482 | java | Java | gradle/gradle-2.1/src/core-impl/org/gradle/api/internal/artifacts/ivyservice/ivyresolve/BaseModuleComponentRepositoryAccess.java | tkmnet/RCRS-ADF | e9caa872b92a32f4b2e394953a2c5c5f0890bf58 | [
"BSD-2-Clause"
] | null | null | null | gradle/gradle-2.1/src/core-impl/org/gradle/api/internal/artifacts/ivyservice/ivyresolve/BaseModuleComponentRepositoryAccess.java | tkmnet/RCRS-ADF | e9caa872b92a32f4b2e394953a2c5c5f0890bf58 | [
"BSD-2-Clause"
] | null | null | null | gradle/gradle-2.1/src/core-impl/org/gradle/api/internal/artifacts/ivyservice/ivyresolve/BaseModuleComponentRepositoryAccess.java | tkmnet/RCRS-ADF | e9caa872b92a32f4b2e394953a2c5c5f0890bf58 | [
"BSD-2-Clause"
] | null | null | null | 47.730769 | 178 | 0.806608 | 2,996 | /*
* Copyright 2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.api.internal.artifacts.ivyservice.ivyresolve;
import org.gradle.api.artifacts.component.ModuleComponentIdentifier;
import org.gradle.api.internal.artifacts.ivyservice.*;
import org.gradle.api.internal.artifacts.metadata.ComponentArtifactMetaData;
import org.gradle.api.internal.artifacts.metadata.ComponentMetaData;
import org.gradle.api.internal.artifacts.metadata.DependencyMetaData;
import org.gradle.api.internal.component.ArtifactType;
public class BaseModuleComponentRepositoryAccess implements ModuleComponentRepositoryAccess {
private final ModuleComponentRepositoryAccess delegate;
public BaseModuleComponentRepositoryAccess(ModuleComponentRepositoryAccess delegate) {
this.delegate = delegate;
}
public void listModuleVersions(DependencyMetaData dependency, BuildableModuleVersionSelectionResolveResult result) {
delegate.listModuleVersions(dependency, result);
}
public void resolveComponentMetaData(DependencyMetaData dependency, ModuleComponentIdentifier moduleComponentIdentifier, BuildableModuleVersionMetaDataResolveResult result) {
delegate.resolveComponentMetaData(dependency, moduleComponentIdentifier, result);
}
public void resolveModuleArtifacts(ComponentMetaData component, ArtifactType artifactType, BuildableArtifactSetResolveResult result) {
delegate.resolveModuleArtifacts(component, artifactType, result);
}
public void resolveModuleArtifacts(ComponentMetaData component, ComponentUsage componentUsage, BuildableArtifactSetResolveResult result) {
delegate.resolveModuleArtifacts(component, componentUsage, result);
}
public void resolveArtifact(ComponentArtifactMetaData artifact, ModuleSource moduleSource, BuildableArtifactResolveResult result) {
delegate.resolveArtifact(artifact, moduleSource, result);
}
}
|
3e07118dce01c21e15bbae1223ba7058fad2454e | 1,583 | java | Java | Components/CommonCore/Source/gov/sandia/cognition/math/DifferentiableEvaluator.java | Markoy8/Foundry | c3ec00a8efe08a25dd5eae7150b788e4486c0e6e | [
"BSD-3-Clause"
] | 122 | 2015-01-19T17:36:40.000Z | 2022-02-25T20:22:22.000Z | Components/CommonCore/Source/gov/sandia/cognition/math/DifferentiableEvaluator.java | Markoy8/Foundry | c3ec00a8efe08a25dd5eae7150b788e4486c0e6e | [
"BSD-3-Clause"
] | 45 | 2015-01-23T06:28:33.000Z | 2021-05-18T19:11:29.000Z | Components/CommonCore/Source/gov/sandia/cognition/math/DifferentiableEvaluator.java | Markoy8/Foundry | c3ec00a8efe08a25dd5eae7150b788e4486c0e6e | [
"BSD-3-Clause"
] | 42 | 2015-01-20T03:07:17.000Z | 2021-08-18T08:51:55.000Z | 29.314815 | 81 | 0.704359 | 2,997 | /*
* File: DifferentiableEvaluator.java
* Authors: Kevin R. Dixon
* Company: Sandia National Laboratories
* Project: Cognitive Framework Lite
*
* Copyright September 10, 2007, Sandia Corporation. Under the terms of Contract
* DE-AC04-94AL85000, there is a non-exclusive license for use of this work by
* or on behalf of the U.S. Government. Export of this program may require a
* license from the United States Government. See CopyrightHistory.txt for
* complete details.
*
*/
package gov.sandia.cognition.math;
import gov.sandia.cognition.annotation.CodeReview;
import gov.sandia.cognition.util.CloneableSerializable;
import gov.sandia.cognition.evaluator.Evaluator;
/**
* Interface that indicates that the Evaluator can be differentiated about the
* given input.
*
* @param <InputType> Input to the Evaluator
* @param <OutputType> Output of the Evaluator
* @param <DerivativeType> Derivative of the Evaluator
*
* @author Kevin R. Dixon
* @since 2.0
*
*/
@CodeReview(
reviewer="Kevin R. Dixon",
date="2008-02-08",
changesNeeded=false,
comments="Looks fine."
)
public interface DifferentiableEvaluator<InputType, OutputType, DerivativeType>
extends Evaluator<InputType, OutputType>
{
/**
* Differentiates the output with respect to the input
* @param input
* Input about which to compute the derivative
* @return
* Derivative of the output with respect to the given input
*/
public DerivativeType differentiate(
InputType input );
}
|
3e071414c059d392128fab7198ad4411ab779c81 | 7,926 | java | Java | tetrecs/src/main/java/uk/ac/soton/comp1206/component/GameBlock.java | Royc30ne/TetrECS_Game | 1af071abfa81a56c9b1a833cbf3c5a0b60958a15 | [
"MIT"
] | 1 | 2022-02-03T16:24:40.000Z | 2022-02-03T16:24:40.000Z | tetrecs/src/main/java/uk/ac/soton/comp1206/component/GameBlock.java | Royc30ne/TetrECS_Game | 1af071abfa81a56c9b1a833cbf3c5a0b60958a15 | [
"MIT"
] | null | null | null | tetrecs/src/main/java/uk/ac/soton/comp1206/component/GameBlock.java | Royc30ne/TetrECS_Game | 1af071abfa81a56c9b1a833cbf3c5a0b60958a15 | [
"MIT"
] | null | null | null | 27.051195 | 124 | 0.572925 | 2,998 | package uk.ac.soton.comp1206.component;
import javafx.animation.AnimationTimer;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.value.ObservableValue;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.*;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
/**
* The Visual User Interface component representing a single block in the grid.
*
* Extends Canvas and is responsible for drawing itself.
*
* Displays an empty square (when the value is 0) or a coloured square depending on value.
*
* The GameBlock value should be bound to a corresponding block in the Grid model.
*/
public class GameBlock extends Canvas {
private static final Logger logger = LogManager.getLogger(GameBlock.class);
private boolean center = false;
private boolean hover = false;
private FadeoutTimer fadeoutTimer = null;
private boolean canBePlaced = true;
/**
* The set of colours for different pieces
*/
public static final Color[] COLOURS = {
Color.TRANSPARENT,
Color.DEEPPINK,
Color.RED,
Color.ORANGE,
Color.YELLOW,
Color.YELLOWGREEN,
Color.LIME,
Color.GREEN,
Color.DARKGREEN,
Color.DARKTURQUOISE,
Color.DEEPSKYBLUE,
Color.AQUA,
Color.AQUAMARINE,
Color.BLUE,
Color.MEDIUMPURPLE,
Color.PURPLE
};
private final GameBoard gameBoard;
private final double width;
private final double height;
/**
* The column this block exists as in the grid
*/
private final int x;
/**
* The row this block exists as in the grid
*/
private final int y;
/**
* The value of this block (0 = empty, otherwise specifies the colour to render as)
*/
private final IntegerProperty value = new SimpleIntegerProperty(0);
/**
* Create a new single Game Block
* @param gameBoard the board this block belongs to
* @param x the column the block exists in
* @param y the row the block exists in
* @param width the width of the canvas to render
* @param height the height of the canvas to render
*/
public GameBlock(GameBoard gameBoard, int x, int y, double width, double height) {
this.gameBoard = gameBoard;
this.width = width;
this.height = height;
this.x = x;
this.y = y;
//A canvas needs a fixed width and height
setWidth(width);
setHeight(height);
//Do an initial paint
paint();
//When the value property is updated, call the internal updateValue method
value.addListener(this::updateValue);
}
/**
* When the value of this block is updated,
* @param observable what was updated
* @param oldValue the old value
* @param newValue the new value
*/
private void updateValue(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
paint();
}
/**
* Handle painting of the block canvas
*/
public void paint() {
//If the block is empty, paint as empty
if(value.get() == 0) {
paintEmpty();
} else {
//If the block is not empty, paint with the colour represented by the value
paintColor(COLOURS[value.get()]);
}
if(center) {
drawCircle();
}
if(hover) {
paintHover();
}
if(!canBePlaced) {
cantPlace();
}
}
/**
* Paint this canvas empty
*/
private void paintEmpty() {
var gc = getGraphicsContext2D();
//Clear
gc.clearRect(0,0,width,height);
//Fill
gc.setFill(Color.color(0,0,0,0.4));
gc.fillRect(0,0, width, height);
//Border
gc.setStroke(Color.color(1,1,1,0.2));
gc.strokeRect(0,0,width,height);
}
/**
* Paint this canvas with the given colour
* @param colour the colour to paint
*/
private void paintColor(Paint colour) {
var gc = getGraphicsContext2D();
//Clear
gc.clearRect(0,0,width,height);
//Colour fill
gc.setFill(colour);
gc.fillRect(0,0, width, height);
gc.setFill(Color.color(1, 1, 1.0, 0.2));
gc.fillPolygon(new double[]{0, 0, this.width}, new double[]{0, this.height, this.height}, 3);
gc.setFill(Color.color(1, 1, 1, 0.3));
gc.fillRect(0.0D, 0, this.width, 3);
gc.setFill(Color.color(1, 1, 1, 0));
gc.fillRect(0, 0, 3, this.height);
gc.setFill(Color.color(0, 0, 0, 0.1));
gc.fillRect(this.width - 3, 0, this.width, this.height);
gc.setFill(Color.color(0.0, 0.0, 0.0, 0.1));
gc.fillRect(0, this.height - 3, this.width, this.height);
//Border
gc.setStroke(Color.color(0,0,0,0.7));
gc.strokeRect(0,0,width,height);
}
/**
* paint the hovered block
*/
private void paintHover() {
GraphicsContext gc = getGraphicsContext2D();
gc.setFill(Color.color(1,1,1,0.6));
gc.fillRect(0,0,width,height);
}
/**
* @param isHover set the hover attribute of the block
*/
public void setHovering(boolean isHover) {
hover = isHover;
paint();
}
/**
* Draw a circle in the center of the block
*/
private void drawCircle() {
GraphicsContext gc = this.getGraphicsContext2D();
gc.setFill(Color.color(1,1,1,0.4));
gc.fillOval(this.width/4,this.height/4,this.width/2,this.height/2);
}
/**
* set the center attribute to the block
*/
public void setCenter() {
this.center = true;
this.paint();
}
/**
* Get the column of this block
* @return column number
*/
public int getX() {
return x;
}
/**
* Get the row of this block
* @return row number
*/
public int getY() {
return y;
}
/**
* Get the current value held by this block, representing it's colour
* @return value
*/
public int getValue() {
return this.value.get();
}
/**
* Bind the value of this block to another property. Used to link the visual block to a corresponding block in the Grid.
* @param input property to bind the value to
*/
public void bind(ObservableValue<? extends Number> input) {
value.bind(input);
}
/**
* Start a fadeOut animation when lines are cleared
*/
public void clearAction() {
fadeoutTimer = new FadeoutTimer();
fadeoutTimer.start();
}
/**
* Paint the style if the piece can't be placed
*/
public void cantPlace() {
GraphicsContext gc = getGraphicsContext2D();
gc.setFill(Color.color(1,0,0,0.4));
gc.fillRect(0,0,width,height);
}
public class FadeoutTimer extends AnimationTimer {
double opacity = 1;
@Override
public void handle(long l) {
fadeOut();
}
/**
* fadeOut Animation.
* fadeOut Colour: Purple
*/
private void fadeOut() {
paintEmpty();
opacity -= 0.05;
if (opacity <= 0) {
stop();
fadeoutTimer = null;
} else {
GraphicsContext gc = getGraphicsContext2D();
gc.setFill(Color.color(0.5,0,0.5,opacity));
gc.fillRect(0,0,getWidth(),getHeight());
}
}
}
public boolean isCanBePlaced(boolean bool) {
return canBePlaced = bool;
}
}
|
3e0714ee69ef3733f497b8e8bd6957922725e40f | 478 | java | Java | 1-Java Syntax/Level 3/20. Plan to conquer the world/Solution.java | Enummethod/CodeGymTasks | ed2aa3dc6843d085670ec8c184bc907e71524a21 | [
"MIT"
] | null | null | null | 1-Java Syntax/Level 3/20. Plan to conquer the world/Solution.java | Enummethod/CodeGymTasks | ed2aa3dc6843d085670ec8c184bc907e71524a21 | [
"MIT"
] | null | null | null | 1-Java Syntax/Level 3/20. Plan to conquer the world/Solution.java | Enummethod/CodeGymTasks | ed2aa3dc6843d085670ec8c184bc907e71524a21 | [
"MIT"
] | null | null | null | 22.761905 | 98 | 0.66318 | 2,999 | package com.codegym.task.task03.task0318;
/*
Plan to conquer the world
*/
// Mustafa YAŞAR
import java.io.*;
public class Solution {
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String years = reader.readLine();
String name = reader.readLine();
System.out.println(name + " will take over the world in " + years + " years. Mwa-ha-ha!");
}
}
|
3e0715230b9311895cdd4b3286f596309f748a8c | 1,193 | java | Java | vaadin-date-picker-flow-parent/vaadin-date-picker-flow-integration-tests/src/test/java/com/vaadin/flow/component/datepicker/DatePickerInAGridHeaderIT.java | tarekoraby/vaadin-flow-components | 57a7f997f8614e4329817a423ae6f22d9fec8fec | [
"Apache-2.0"
] | null | null | null | vaadin-date-picker-flow-parent/vaadin-date-picker-flow-integration-tests/src/test/java/com/vaadin/flow/component/datepicker/DatePickerInAGridHeaderIT.java | tarekoraby/vaadin-flow-components | 57a7f997f8614e4329817a423ae6f22d9fec8fec | [
"Apache-2.0"
] | null | null | null | vaadin-date-picker-flow-parent/vaadin-date-picker-flow-integration-tests/src/test/java/com/vaadin/flow/component/datepicker/DatePickerInAGridHeaderIT.java | tarekoraby/vaadin-flow-components | 57a7f997f8614e4329817a423ae6f22d9fec8fec | [
"Apache-2.0"
] | null | null | null | 31.394737 | 80 | 0.73596 | 3,000 | /*
* Copyright 2000-2017 Vaadin Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.vaadin.flow.component.datepicker;
import org.junit.Test;
import org.openqa.selenium.By;
import com.vaadin.tests.AbstractComponentIT;
import com.vaadin.flow.testutil.TestPath;
@TestPath("vaadin-date-picker/date-picker-in-a-grid-header")
public class DatePickerInAGridHeaderIT extends AbstractComponentIT {
/**
* Test for https://github.com/vaadin/vaadin-date-picker-flow/issues/100
*/
@Test
public void openPage_datePickerIsRendereredWithoutErrors() {
open();
waitForElementPresent(By.id("date-picker"));
checkLogsForErrors();
}
}
|
3e0715562ccfdb24fd1473a8189413ed9d510111 | 288 | java | Java | src/main/java/pl/jp/analyzer/analysis/Post.java | jpodeszwik/xml-analyzer | d01b83cbfd962dbfe84ff4c2a533f97a438e63a2 | [
"MIT"
] | null | null | null | src/main/java/pl/jp/analyzer/analysis/Post.java | jpodeszwik/xml-analyzer | d01b83cbfd962dbfe84ff4c2a533f97a438e63a2 | [
"MIT"
] | null | null | null | src/main/java/pl/jp/analyzer/analysis/Post.java | jpodeszwik/xml-analyzer | d01b83cbfd962dbfe84ff4c2a533f97a438e63a2 | [
"MIT"
] | null | null | null | 16 | 34 | 0.729167 | 3,001 | package pl.jp.analyzer.analysis;
import java.time.OffsetDateTime;
import javax.annotation.Nullable;
import org.immutables.value.Value;
@Value.Immutable
interface Post {
int id();
int score();
OffsetDateTime creationDate();
@Nullable
Integer acceptedAnswerId();
}
|
3e07160ea30a696b1f76afdde0adbe3909ae8f40 | 2,759 | java | Java | core/src/main/java/hudson/console/HyperlinkNote.java | bharath12b5/jenkinsss | 4da864376e4fa59a211d5e81dd7d2052c5245406 | [
"MIT"
] | 15 | 2015-03-04T20:19:23.000Z | 2021-08-05T07:13:40.000Z | core/src/main/java/hudson/console/HyperlinkNote.java | bharath12b5/jenkinsss | 4da864376e4fa59a211d5e81dd7d2052c5245406 | [
"MIT"
] | 2 | 2021-02-03T19:30:28.000Z | 2022-03-02T07:14:30.000Z | core/src/main/java/hudson/console/HyperlinkNote.java | bharath12b5/jenkinsss | 4da864376e4fa59a211d5e81dd7d2052c5245406 | [
"MIT"
] | 14 | 2015-02-11T04:29:14.000Z | 2021-05-02T07:06:29.000Z | 34.4875 | 89 | 0.696629 | 3,002 | /*
* The MIT License
*
* Copyright (c) 2010-2011, CloudBees, Inc.
*
* 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 hudson.console;
import hudson.Extension;
import hudson.MarkupText;
import hudson.model.Hudson;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Turns a text into a hyperlink by specifying the URL separately.
*
* @author Kohsuke Kawaguchi
* @since 1.362
*/
public class HyperlinkNote extends ConsoleNote {
/**
* If this starts with '/', it's interpreted as a path within the context path.
*/
private final String url;
private final int length;
public HyperlinkNote(String url, int length) {
this.url = url;
this.length = length;
}
@Override
public ConsoleAnnotator annotate(Object context, MarkupText text, int charPos) {
String url = this.url;
if (url.startsWith("/"))
url = Hudson.getInstance().getRootUrl()+url.substring(1);
text.addHyperlink(charPos,charPos+length,url);
return null;
}
public static String encodeTo(String url, String text) {
try {
return new HyperlinkNote(url,text.length()).encode()+text;
} catch (IOException e) {
// impossible, but don't make this a fatal problem
LOGGER.log(Level.WARNING, "Failed to serialize "+HyperlinkNote.class,e);
return text;
}
}
@Extension
public static final class DescriptorImpl extends ConsoleAnnotationDescriptor {
public String getDisplayName() {
return "Hyperlinks";
}
}
private static final Logger LOGGER = Logger.getLogger(HyperlinkNote.class.getName());
}
|
3e0718be56ced7d558fa9924ffe33d41178a4b9f | 424 | java | Java | blufilibrary/src/main/java/blufi/espressif/response/BlufiVersionResponse.java | peachhuang/Talkypen | 07e84274eeccb3a8d54841fb84bcfe34fe9bbc1e | [
"Apache-2.0"
] | null | null | null | blufilibrary/src/main/java/blufi/espressif/response/BlufiVersionResponse.java | peachhuang/Talkypen | 07e84274eeccb3a8d54841fb84bcfe34fe9bbc1e | [
"Apache-2.0"
] | null | null | null | blufilibrary/src/main/java/blufi/espressif/response/BlufiVersionResponse.java | peachhuang/Talkypen | 07e84274eeccb3a8d54841fb84bcfe34fe9bbc1e | [
"Apache-2.0"
] | null | null | null | 24.941176 | 93 | 0.679245 | 3,003 | package blufi.espressif.response;
import java.util.Locale;
public class BlufiVersionResponse {
private int[] mVersionValues = {0, 0};
public void setVersionValues(int bigVer, int smallVer) {
mVersionValues[0] = bigVer;
mVersionValues[1] = smallVer;
}
public String getVersionString() {
return String.format(Locale.ENGLISH, "V%d.%d", mVersionValues[0], mVersionValues[1]);
}
}
|
3e071c913107208b6bf2fdf8a2cffc3d8d26c15e | 5,563 | java | Java | api/src/main/java/ca/bc/gov/educ/api/ruleengine/rule/MinElectiveCreditsRule.java | bcgov/EDUC-RULE-ENGINE-API | 9fee974394d3534bc9e76c62bea383e07e0f04a1 | [
"Apache-2.0"
] | null | null | null | api/src/main/java/ca/bc/gov/educ/api/ruleengine/rule/MinElectiveCreditsRule.java | bcgov/EDUC-RULE-ENGINE-API | 9fee974394d3534bc9e76c62bea383e07e0f04a1 | [
"Apache-2.0"
] | 27 | 2020-04-17T19:37:04.000Z | 2022-02-23T18:21:30.000Z | api/src/main/java/ca/bc/gov/educ/api/ruleengine/rule/MinElectiveCreditsRule.java | bcgov/EDUC-RULE-ENGINE-API | 9fee974394d3534bc9e76c62bea383e07e0f04a1 | [
"Apache-2.0"
] | null | null | null | 40.311594 | 166 | 0.75373 | 3,004 | package ca.bc.gov.educ.api.ruleengine.rule;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import ca.bc.gov.educ.api.ruleengine.dto.ProgramRequirement;
import ca.bc.gov.educ.api.ruleengine.dto.GradRequirement;
import ca.bc.gov.educ.api.ruleengine.dto.RuleData;
import ca.bc.gov.educ.api.ruleengine.dto.RuleProcessorData;
import ca.bc.gov.educ.api.ruleengine.dto.StudentCourse;
import ca.bc.gov.educ.api.ruleengine.util.RuleProcessorRuleUtils;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@Component
@NoArgsConstructor
@AllArgsConstructor
public class MinElectiveCreditsRule implements Rule {
private static Logger logger = LoggerFactory.getLogger(MinElectiveCreditsRule.class);
@Autowired
private RuleProcessorData ruleProcessorData;
public RuleData fire() {
int totalCredits = 0;
int requiredCredits = 0;
logger.debug("Min Elective Credits Rule");
if (ruleProcessorData.getStudentCourses() == null || ruleProcessorData.getStudentCourses().size() == 0) {
logger.warn("!!!Empty list sent to Min Elective Credits Rule for processing");
return ruleProcessorData;
}
List<StudentCourse> studentCourses = RuleProcessorRuleUtils
.getUniqueStudentCourses(ruleProcessorData.getStudentCourses(), ruleProcessorData.isProjected());
logger.debug("Unique Courses: " + studentCourses.size());
List<ProgramRequirement> gradProgramRules = ruleProcessorData
.getGradProgramRules().stream().filter(gpr -> "MCE".compareTo(gpr.getProgramRequirementCode().getRequirementTypeCode().getReqTypeCode()) == 0
&& "Y".compareTo(gpr.getProgramRequirementCode().getActiveRequirement()) == 0 && "C".compareTo(gpr.getProgramRequirementCode().getRequirementCategory()) == 0)
.collect(Collectors.toList());
logger.debug(gradProgramRules.toString());
for (ProgramRequirement gradProgramRule : gradProgramRules) {
requiredCredits = Integer.parseInt(gradProgramRule.getProgramRequirementCode().getRequiredCredits().trim()); // list
List<StudentCourse> tempStudentCourseList = null;
if (gradProgramRule.getProgramRequirementCode().getRequiredLevel() == null
|| gradProgramRule.getProgramRequirementCode().getRequiredLevel().trim().compareTo("") == 0) {
tempStudentCourseList = studentCourses.stream().filter(sc -> !sc.isUsedInMatchRule()).collect(Collectors.toList());
} else {
tempStudentCourseList = studentCourses.stream()
.filter(sc -> !sc.isUsedInMatchRule()
&& sc.getCourseLevel().compareTo(gradProgramRule.getProgramRequirementCode().getRequiredLevel().trim()) == 0)
.collect(Collectors.toList());
}
for (StudentCourse sc : tempStudentCourseList) {
if (totalCredits + sc.getCredits() <= requiredCredits) {
totalCredits += sc.getCredits();
sc.setCreditsUsedForGrad(sc.getCredits());
} else {
int extraCredits = totalCredits + sc.getCredits() - requiredCredits;
totalCredits = requiredCredits;
sc.setCreditsUsedForGrad(sc.getCredits() - extraCredits);
}
if (sc.getGradReqMet().length() > 0) {
sc.setGradReqMet(sc.getGradReqMet() + ", " + gradProgramRule.getProgramRequirementCode().getProReqCode());
sc.setGradReqMetDetail(sc.getGradReqMetDetail() + ", " + gradProgramRule.getProgramRequirementCode().getProReqCode() + " - "
+ gradProgramRule.getProgramRequirementCode().getLabel());
} else {
sc.setGradReqMet(gradProgramRule.getProgramRequirementCode().getProReqCode());
sc.setGradReqMetDetail(
gradProgramRule.getProgramRequirementCode().getProReqCode() + " - " + gradProgramRule.getProgramRequirementCode().getLabel());
}
sc.setUsed(true);
if (totalCredits == requiredCredits) {
break;
}
}
if (totalCredits >= requiredCredits) {
logger.info(gradProgramRule.getProgramRequirementCode().getLabel() + " Passed");
gradProgramRule.getProgramRequirementCode().setPassed(true);
List<GradRequirement> reqsMet = ruleProcessorData.getRequirementsMet();
if (reqsMet == null)
reqsMet = new ArrayList<>();
reqsMet.add(new GradRequirement(gradProgramRule.getProgramRequirementCode().getProReqCode(), gradProgramRule.getProgramRequirementCode().getLabel()));
ruleProcessorData.setRequirementsMet(reqsMet);
logger.debug("Min Elective Credits Rule: Total-" + totalCredits + " Required-" + requiredCredits);
} else {
logger.info(gradProgramRule.getProgramRequirementCode().getDescription() + " Failed!");
ruleProcessorData.setGraduated(false);
List<GradRequirement> nonGradReasons = ruleProcessorData.getNonGradReasons();
if (nonGradReasons == null)
nonGradReasons = new ArrayList<>();
nonGradReasons.add(new GradRequirement(gradProgramRule.getProgramRequirementCode().getProReqCode(), gradProgramRule.getProgramRequirementCode().getNotMetDesc()));
ruleProcessorData.setNonGradReasons(nonGradReasons);
}
logger.info("Min Elective Credits -> Required:" + requiredCredits + " Has:" + totalCredits);
requiredCredits = 0;
totalCredits = 0;
}
ruleProcessorData.getStudentCourses().addAll(ruleProcessorData.getExcludedCourses());
return ruleProcessorData;
}
@Override
public void setInputData(RuleData inputData) {
ruleProcessorData = (RuleProcessorData) inputData;
logger.info("MinElectiveCreditsRule: Rule Processor Data set.");
}
}
|
3e071cc145a47433ca74c6bf938590c5b2332f11 | 557 | java | Java | src/main/java/com/smartNodeProtocol/core/service/user/repositories/impl/mock/DummyMockRepositoryImpl.java | samarthgupta3/snop-coredev | e976472cda7875021d1b2c426fba8aa3e208bff1 | [
"MIT"
] | null | null | null | src/main/java/com/smartNodeProtocol/core/service/user/repositories/impl/mock/DummyMockRepositoryImpl.java | samarthgupta3/snop-coredev | e976472cda7875021d1b2c426fba8aa3e208bff1 | [
"MIT"
] | null | null | null | src/main/java/com/smartNodeProtocol/core/service/user/repositories/impl/mock/DummyMockRepositoryImpl.java | samarthgupta3/snop-coredev | e976472cda7875021d1b2c426fba8aa3e208bff1 | [
"MIT"
] | null | null | null | 29.315789 | 101 | 0.737882 | 3,005 | package com.smartNodeProtocol.core.service.user.repositories.impl.mock;
import com.smartNodeProtocol.core.dao.model.data.user.User;
import com.smartNodeProtocol.core.service.user.repositories.intf.DummyRepository;
/**
* Created by Samarth on 06-10-2017.
*/
public class DummyMockRepositoryImpl extends GenericMockRepository<User> implements DummyRepository {
@Override
public User getDefaultUser() {
User user = new User();
user.setFirstName("JonFromREST");
user.setLastName("DoeFromREST");
return user;
}
}
|
3e071d121d637eade27a4b2f21839d755fd02b0a | 2,195 | java | Java | Project1/project1/src/main/java/com/sahfer/itisjapo/project1/view/ViewMenu.java | ItIsJAPO/Sahfer---Test | 8ae4ad52330923f37201970a6e896e8d07d958a8 | [
"MIT"
] | null | null | null | Project1/project1/src/main/java/com/sahfer/itisjapo/project1/view/ViewMenu.java | ItIsJAPO/Sahfer---Test | 8ae4ad52330923f37201970a6e896e8d07d958a8 | [
"MIT"
] | null | null | null | Project1/project1/src/main/java/com/sahfer/itisjapo/project1/view/ViewMenu.java | ItIsJAPO/Sahfer---Test | 8ae4ad52330923f37201970a6e896e8d07d958a8 | [
"MIT"
] | null | null | null | 24.943182 | 61 | 0.700228 | 3,006 | package com.sahfer.itisjapo.project1.view;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class ViewMenu {
private JFrame frmHpVentas;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ViewMenu window = new ViewMenu();
window.frmHpVentas.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public ViewMenu() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frmHpVentas = new JFrame();
frmHpVentas.setTitle("HP - Ventas");
frmHpVentas.setBounds(100, 100, 257, 188);
frmHpVentas.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmHpVentas.getContentPane().setLayout(null);
JButton btnAltas = new JButton("Altas");
btnAltas.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
ViewAltas altas=new ViewAltas();
altas.setVisible(true);
}
});
btnAltas.setBounds(59, 11, 126, 23);
frmHpVentas.getContentPane().add(btnAltas);
JButton btnBajas = new JButton("Bajas");
btnBajas.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ViewBaja bajas=new ViewBaja();
bajas.setVisible(true);
}
});
btnBajas.setBounds(59, 45, 126, 23);
frmHpVentas.getContentPane().add(btnBajas);
JButton btnConsultas = new JButton("Consultas");
btnConsultas.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ViewConsulta con=new ViewConsulta();
con.setVisible(true);
}
});
btnConsultas.setBounds(59, 79, 126, 23);
frmHpVentas.getContentPane().add(btnConsultas);
JButton btnLibre = new JButton("Libre");
btnLibre.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new ViewPerzonalidado().setVisible(true);
}
});
btnLibre.setBounds(59, 113, 126, 23);
frmHpVentas.getContentPane().add(btnLibre);
}
}
|
3e071d68cc22acac22ad5001f7698567cdff2924 | 1,275 | java | Java | core-java-modules/core-java-security/src/main/java/com/baeldung/sasl/ServerCallbackHandler.java | eas5/tutorials | 4b460a9e25f6f0b0292e98144add0ce631a9e05e | [
"MIT"
] | 32,544 | 2015-01-02T16:59:22.000Z | 2022-03-31T21:04:05.000Z | core-java-modules/core-java-security/src/main/java/com/baeldung/sasl/ServerCallbackHandler.java | eas5/tutorials | 4b460a9e25f6f0b0292e98144add0ce631a9e05e | [
"MIT"
] | 1,577 | 2015-02-21T17:47:03.000Z | 2022-03-31T14:25:58.000Z | core-java-modules/core-java-security/src/main/java/com/baeldung/sasl/ServerCallbackHandler.java | eas5/tutorials | 4b460a9e25f6f0b0292e98144add0ce631a9e05e | [
"MIT"
] | 55,853 | 2015-01-01T07:52:09.000Z | 2022-03-31T21:08:15.000Z | 37.5 | 89 | 0.667451 | 3,007 | package com.baeldung.sasl;
import java.io.IOException;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.callback.NameCallback;
import javax.security.auth.callback.PasswordCallback;
import javax.security.auth.callback.UnsupportedCallbackException;
import javax.security.sasl.AuthorizeCallback;
import javax.security.sasl.RealmCallback;
public class ServerCallbackHandler implements CallbackHandler {
@Override
public void handle(Callback[] cbs) throws IOException, UnsupportedCallbackException {
for (Callback cb : cbs) {
if (cb instanceof AuthorizeCallback) {
AuthorizeCallback ac = (AuthorizeCallback) cb;
ac.setAuthorized(true);
} else if (cb instanceof NameCallback) {
NameCallback nc = (NameCallback) cb;
nc.setName("username");
} else if (cb instanceof PasswordCallback) {
PasswordCallback pc = (PasswordCallback) cb;
pc.setPassword("password".toCharArray());
} else if (cb instanceof RealmCallback) {
RealmCallback rc = (RealmCallback) cb;
rc.setText("myServer");
}
}
}
} |
3e071ded8f20f7f441b5598566333f90efd37748 | 2,441 | java | Java | java-client/src/main/java/io/fluxcapacitor/javaclient/persisting/keyvalue/client/KeyValueClient.java | flux-capacitor-io/flux-capacitor-client | eb017e9020dce687684e242f893a3d69cde53bf6 | [
"Apache-2.0"
] | 10 | 2017-09-29T19:22:11.000Z | 2022-01-21T14:17:22.000Z | java-client/src/main/java/io/fluxcapacitor/javaclient/persisting/keyvalue/client/KeyValueClient.java | flux-capacitor-io/flux-capacitor-client | eb017e9020dce687684e242f893a3d69cde53bf6 | [
"Apache-2.0"
] | 1 | 2017-09-29T19:21:25.000Z | 2017-09-29T20:40:13.000Z | java-client/src/main/java/io/fluxcapacitor/javaclient/persisting/keyvalue/client/KeyValueClient.java | flux-capacitor-io/flux-capacitor-client | eb017e9020dce687684e242f893a3d69cde53bf6 | [
"Apache-2.0"
] | 4 | 2018-10-19T11:30:37.000Z | 2022-03-10T23:35:39.000Z | 36.432836 | 116 | 0.702171 | 3,008 | /*
* Copyright (c) 2016-2020 Flux Capacitor.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.fluxcapacitor.javaclient.persisting.keyvalue.client;
import io.fluxcapacitor.common.Awaitable;
import io.fluxcapacitor.common.Guarantee;
import io.fluxcapacitor.common.api.Data;
import java.util.concurrent.CompletableFuture;
/**
* Represents a service to store and retrieve a piece of serialized data by key.
*/
public interface KeyValueClient extends AutoCloseable {
/**
* Adds or replaces the given value in the key value store.
*
* @param key The key associated with this value
* @param value The value to store
* @param guarantee The guarantee for storing
* @return a handle that enables clients to wait until the value was sent or stored depending on the guarantee
*/
Awaitable putValue(String key, Data<byte[]> value, Guarantee guarantee);
/**
* Adds the given value in the key value store if the key is not already mapped to a value.
*
* @param key The key associated with this value
* @param value The value to store
* @return a handle that enables clients to wait until the value was sent or stored depending on the guarantee
*/
CompletableFuture<Boolean> putValueIfAbsent(String key, Data<byte[]> value);
/**
* Returns the {@link Data} object associated with the given key. Returns {@code null} if there is no associated
* value.
*
* @param key The key associated with the value
* @return the value for the given key or null
*/
Data<byte[]> getValue(String key);
/**
* Deletes the value associated with the given key.
*
* @param key The key associated with this value
* @return a handle that enables clients to wait until the command was safely sent to the store
*/
Awaitable deleteValue(String key);
@Override
void close();
}
|
3e071e55515adb0da9ddbb96343ed34049fdc974 | 1,682 | java | Java | src/main/java/l2f/gameserver/model/entity/events/fightclubmanager/FightClubTeam.java | Arodev76/L2Advanced | 12625a32ea7114b9d1d1ac0238da8422d714fc17 | [
"MIT"
] | 7 | 2018-02-05T10:28:56.000Z | 2020-08-06T06:35:54.000Z | src/main/java/l2f/gameserver/model/entity/events/fightclubmanager/FightClubTeam.java | Kryspo/L2jRamsheart | 98c39d754f5aba1806f92acc9e8e63b3b827be49 | [
"MIT"
] | 3 | 2020-02-26T06:49:17.000Z | 2020-03-05T05:11:05.000Z | src/main/java/l2f/gameserver/model/entity/events/fightclubmanager/FightClubTeam.java | Kryspo/L2jRamsheart | 98c39d754f5aba1806f92acc9e8e63b3b827be49 | [
"MIT"
] | 12 | 2018-02-12T20:58:07.000Z | 2020-06-07T02:44:42.000Z | 15.431193 | 60 | 0.699762 | 3,009 | package l2f.gameserver.model.entity.events.fightclubmanager;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import l2f.gameserver.utils.Location;
public class FightClubTeam implements Serializable
{
public static enum TEAM_NAMES {
Red(0x162ee1),
Blue(0xb53e41),
Green(0x3eb541),
Yellow(0x2efdff),
Gray(0x808080),
Orange(0x0087f9),
Black(0x161616),
White(0xffffff),
Violet(0xba2785),
Cyan(0xe3e136),
Pink(0xde6def);
public int _nameColor;
private TEAM_NAMES(int nameColor)
{
_nameColor = nameColor;
}
}
private int _index;
private String _name;
private List<FightClubPlayer> _players = new ArrayList<>();
private Location _spawnLoc;
private int _score;
public FightClubTeam(int index)
{
_index = index;
chooseName();
}
public int getIndex()
{
return _index;
}
public String getName()
{
return _name;
}
public void setName(String name)
{
_name = name;
}
public String chooseName()
{
_name = TEAM_NAMES.values()[_index-1].toString();
return _name;
}
public int getNickColor()
{
return TEAM_NAMES.values()[_index-1]._nameColor;
}
public List<FightClubPlayer> getPlayers()
{
return _players;
}
public void addPlayer(FightClubPlayer player)
{
_players.add(player);
}
public void removePlayer(FightClubPlayer player)
{
_players.remove(player);
}
public void setSpawnLoc(Location loc)
{
_spawnLoc = loc;
}
public Location getSpawnLoc()
{
return _spawnLoc;
}
public void setScore(int newScore)
{
_score = newScore;
}
public void incScore(int by)
{
_score += by;
}
public int getScore()
{
return _score;
}
}
|
3e071ebf4d430546ba7ba6ec15205fed5f884c6b | 686 | java | Java | Exam/src/Method/ex10.java | kasin78/JAVA-Study | 156d8f31aac7fc55efdc6feb58d21d3c8448c524 | [
"MIT"
] | null | null | null | Exam/src/Method/ex10.java | kasin78/JAVA-Study | 156d8f31aac7fc55efdc6feb58d21d3c8448c524 | [
"MIT"
] | null | null | null | Exam/src/Method/ex10.java | kasin78/JAVA-Study | 156d8f31aac7fc55efdc6feb58d21d3c8448c524 | [
"MIT"
] | null | null | null | 17.15 | 63 | 0.542274 | 3,010 | package Method;
public class ex10 {
public static void main(String[] args) {
// 변수 생성
double w = 81.6;
double t = 1.76;
// BMI 계산
double bmi = calculate(w, t);
// 결과 출력
System.out.printf("BMI : %.2f(%.1fkg), %.2fm)\n", bmi, w, t);
System.out.printf("결과 : %s입니다.", result(bmi));
}
private static double calculate(double w, double t) {
double bmi = w / (t*t);
return bmi;
}
public static String result(double bmi) {
String result = "";
if (bmi >= 30) {
result = "비만";
}
else if (bmi >= 25 && bmi < 30) {
result = "과체중";
}
else if (bmi >= 18.5 && bmi < 25) {
result = "정상";
}
else {
result = "저체중";
}
return result;
}
}
|
3e071f22a8eda4510f6f91ce5a66043f31b1f532 | 319 | java | Java | src/main/java/org/acme/Main.java | engilyin/quarkus-spring-dto | d58fe686a98283ae784cd6b6a6e902a60cb7b6f1 | [
"MIT"
] | null | null | null | src/main/java/org/acme/Main.java | engilyin/quarkus-spring-dto | d58fe686a98283ae784cd6b6a6e902a60cb7b6f1 | [
"MIT"
] | null | null | null | src/main/java/org/acme/Main.java | engilyin/quarkus-spring-dto | d58fe686a98283ae784cd6b6a6e902a60cb7b6f1 | [
"MIT"
] | null | null | null | 18.764706 | 50 | 0.68652 | 3,011 | package org.acme;
import io.quarkus.runtime.Quarkus;
import io.quarkus.runtime.annotations.QuarkusMain;
import lombok.extern.slf4j.Slf4j;
@QuarkusMain
@Slf4j
public class Main {
public static void main(String ... args) {
log.info("Starting Spring Data demo...");
Quarkus.run(args);
}
}
|
3e071fe732e37bbc8edd79b289f4e1eab97f90ee | 6,544 | java | Java | src/main/java/net/glaso/ca/business/group/controller/GroupController.java | ehdvudee/certGenerator | f4145a242872bef44aa74309cad11a18c990bc5e | [
"Apache-2.0"
] | 2 | 2019-05-16T02:39:50.000Z | 2019-05-27T00:37:10.000Z | src/main/java/net/glaso/ca/business/group/controller/GroupController.java | ehdvudee/certGenerator | f4145a242872bef44aa74309cad11a18c990bc5e | [
"Apache-2.0"
] | 5 | 2020-03-04T22:47:33.000Z | 2021-12-09T21:12:17.000Z | src/main/java/net/glaso/ca/business/group/controller/GroupController.java | ehdvudee/certGenerator | f4145a242872bef44aa74309cad11a18c990bc5e | [
"Apache-2.0"
] | null | null | null | 33.050505 | 184 | 0.739303 | 3,012 | package net.glaso.ca.business.group.controller;
import net.glaso.ca.business.audit.service.WebAuditService;
import net.glaso.ca.business.common.domain.PageMaker;
import net.glaso.ca.business.common.mvc.controller.CommonController;
import net.glaso.ca.business.group.service.GroupService;
import net.glaso.ca.business.group.vo.UserGroupVo;
import net.glaso.ca.framework.utils.CaUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@RestController
@RequestMapping("/group")
public class GroupController extends CommonController {
private final GroupService service;
private final WebAuditService webAuditService;
@Autowired
public GroupController( GroupService service, WebAuditService webAuditService ) {
this.service = service;
this.webAuditService = webAuditService;
}
@SuppressWarnings("unchecked")
@GetMapping("")
public <T>T listOrPage( HttpServletRequest request ) throws IllegalArgumentException {
if ( request.getParameterMap().isEmpty() ) {
return (T) page( request );
} else {
return (T) showGroupList( request );
}
}
private ModelAndView page( HttpServletRequest request ) {
ModelAndView mv = new ModelAndView();
mv.setViewName( "group/view");
webAuditService.insertAudit( request );
return mv;
}
private ResponseEntity<?> showGroupList( HttpServletRequest request ) throws IllegalArgumentException {
ResponseEntity<?> entity;
Map<String, Object> entities = new HashMap<>();
int page = request.getParameter( "page" ) != null ? Integer.parseInt( request.getParameter( "page" ) ) : 10;
PageMaker pageMaker = super.setPaging( page );
List<Map<String, Object>> list = service.showGroupList( pageMaker.getCri() );
int listCnt = service.showGroupListCnt();
entities = super.commonListing( entities, list, listCnt, pageMaker );
entities.put( "status", "success" );
entity = new ResponseEntity<>(entities, HttpStatus.OK);
webAuditService.insertAudit( request );
return entity;
}
@PostMapping("")
public ResponseEntity<?> registerGroup( HttpServletRequest request ) {
ResponseEntity<?> entity;
Map<String, Object> entities = new HashMap<>();
service.registerGroup( request );
entities.put( "redirect", "/group" );
entities.put( "status", "success" );
entity = new ResponseEntity<>(entities, HttpStatus.OK);
webAuditService.insertAudit( request );
return entity;
}
@GetMapping("{groupId}/user")
public ResponseEntity<?> showUserList( @PathVariable("groupId") int groupId, HttpServletRequest request ) throws IllegalArgumentException, IllegalAccessException {
String oper = request.getParameter( "oper" );
if ( oper != null && oper.equals( "requested" ) ) {
return showAppliedUserList( groupId, request );
} else if ( oper != null && oper.equals( "registered" ) ) {
return showRegisteredUserList( groupId, request );
} else {
throw new IllegalArgumentException( "operation is null." );
}
}
private ResponseEntity<?> showAppliedUserList( int groupId, HttpServletRequest request ) throws IllegalArgumentException {
ResponseEntity<?> entity;
Map<String, Object> entities = new HashMap<>();
int page = request.getParameter( "page" ) != null ? Integer.parseInt( request.getParameter( "page" ) ) : 10;
PageMaker pageMaker = super.setPaging( page );
List<Map<String, Object>> list = service.showUserGroupApplyList( pageMaker.getCri(), groupId );
int listCnt = service.showUserGroupApplyListCnt( groupId );
entities = super.commonListing( entities, list, listCnt, pageMaker );
entities.put( "status", "success" );
entity = new ResponseEntity<>(entities, HttpStatus.OK);
webAuditService.insertAudit( request );
return entity;
}
private ResponseEntity<?> showRegisteredUserList( int groupId, HttpServletRequest request ) throws IllegalArgumentException, IllegalAccessException {
ResponseEntity<?> entity;
Map<String, Object> entities = new HashMap<>();
List<Map<String, Object>> voListMap = new ArrayList<>();
for ( UserGroupVo vo : service.showUserList( groupId ) ) {
voListMap.add( CaUtils.voToMap( vo ) );
}
entities.put( "data", voListMap );
entities.put( "status", "success" );
entity = new ResponseEntity<>(entities, HttpStatus.OK);
webAuditService.insertAudit( request );
return entity;
}
@PostMapping("{groupId}/user/{userId}")
public ResponseEntity<?> registerAppliedUser( @PathVariable("groupId") int groupId, @PathVariable("userId") String userId, HttpServletRequest request ) throws IllegalAccessException {
ResponseEntity<?> entity;
Map<String, Object> entities = new HashMap<>();
service.approveUserToJoinGroup( request, groupId, userId );
entities.put( "status", "success" );
entity = new ResponseEntity<>( entities, HttpStatus.OK );
webAuditService.insertAudit( request );
return entity;
}
@PostMapping("{groupId}/user")
public ResponseEntity<?> addUserToGroup( @PathVariable("groupId") int groupId, HttpServletRequest request ) {
ResponseEntity<?> entity;
Map<String, Object> entities = new HashMap<>();
this.service.addUserToGroup( request, groupId );
entities.put( "status", "success" );
entity = new ResponseEntity<>(entities, HttpStatus.OK);
webAuditService.insertAudit( request );
return entity;
}
// 덜 완성 view 단
@DeleteMapping("{groupId}/user/{userId}")
public ResponseEntity<?> removeUserToGroup( @PathVariable("groupId") int groupId, @PathVariable("userId") String userId, HttpServletRequest request ) {
ResponseEntity<?> entity;
Map<String, Object> entities = new HashMap<>();
this.service.removeUserToGroup( groupId, userId );
entities.put( "status", "success" );
entity = new ResponseEntity<>(entities, HttpStatus.OK);
webAuditService.insertAudit( request );
return entity;
}
@PostMapping("{groupId}/solution")
public ResponseEntity<?> applyGroupSolution( @PathVariable("groupId") int groupId, HttpServletRequest request ) {
ResponseEntity<?> entity;
Map<String, Object> entities = new HashMap<>();
service.applyGroupSolution( request, groupId );
entities.put( "status", "success" );
entity = new ResponseEntity<>(entities, HttpStatus.OK);
webAuditService.insertAudit( request );
return entity;
}
}
|
3e07200b82cf0171da5cf4be49cdb0f51ece68ab | 35 | java | Java | plug-ins/helios/org.eclipse.jdt.ui.tests.refactoring/resources/RenameType/test46/out/C.java | TheRakeshPurohit/CodingSpectator | badd6efaaa8d187983d11c94012da747dda0c85a | [
"NCSA"
] | 5 | 2015-01-20T10:33:20.000Z | 2021-05-11T06:56:51.000Z | plug-ins/helios/org.eclipse.jdt.ui.tests.refactoring/resources/RenameType/test46/out/C.java | TheRakeshPurohit/CodingSpectator | badd6efaaa8d187983d11c94012da747dda0c85a | [
"NCSA"
] | null | null | null | plug-ins/helios/org.eclipse.jdt.ui.tests.refactoring/resources/RenameType/test46/out/C.java | TheRakeshPurohit/CodingSpectator | badd6efaaa8d187983d11c94012da747dda0c85a | [
"NCSA"
] | 7 | 2015-02-13T10:21:04.000Z | 2019-05-08T06:04:40.000Z | 11.666667 | 11 | 0.657143 | 3,013 | package p1;
import p.B;
class C{}; |
3e07213b41f2e2c92d52745f97aeda76e7108367 | 814 | java | Java | Workspace/org.aieonf.browsersupport/src/org/aieonf/browsersupport/service/ActiveLinkData.java | condast/AieonF | 7c096a63b0c2b0eb6c43a34e011e6b2ad7d678f8 | [
"Apache-2.0"
] | null | null | null | Workspace/org.aieonf.browsersupport/src/org/aieonf/browsersupport/service/ActiveLinkData.java | condast/AieonF | 7c096a63b0c2b0eb6c43a34e011e6b2ad7d678f8 | [
"Apache-2.0"
] | null | null | null | Workspace/org.aieonf.browsersupport/src/org/aieonf/browsersupport/service/ActiveLinkData.java | condast/AieonF | 7c096a63b0c2b0eb6c43a34e011e6b2ad7d678f8 | [
"Apache-2.0"
] | null | null | null | 16.958333 | 93 | 0.72973 | 3,014 | package org.aieonf.browsersupport.service;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;
import org.aieonf.commons.net.IWebResourceProvider;
public class ActiveLinkData implements IWebResourceProvider
{
private String provider;
private URL url;
private Date date;
public ActiveLinkData( String provider, URL url, Date date )
{
this.provider = provider;
this.url = url;
this.date = date;
}
public ActiveLinkData( String provider, String url, Date date ) throws MalformedURLException
{
this.provider = provider;
this.url = new URL( url );
this.date =date;
}
@Override
public String getProvider()
{
return this.provider;
}
@Override
public URL getURL()
{
return this.url;
}
@Override
public Date getDate()
{
return this.date;
}
}
|
3e0721ba87d3961d576e7cfe9b8997017ee86145 | 6,369 | java | Java | src/main/java/io/connectedhealth_idaas/eventbuilder/dataobjects/clinical/hl7/BPX.java | RedHat-Healthcare/Event-Builder | 291f6806bf77218ddbce37e81fa2fce6fa668789 | [
"Apache-2.0"
] | null | null | null | src/main/java/io/connectedhealth_idaas/eventbuilder/dataobjects/clinical/hl7/BPX.java | RedHat-Healthcare/Event-Builder | 291f6806bf77218ddbce37e81fa2fce6fa668789 | [
"Apache-2.0"
] | 1 | 2021-07-15T14:24:27.000Z | 2021-07-21T19:35:03.000Z | src/main/java/io/connectedhealth_idaas/eventbuilder/dataobjects/clinical/hl7/BPX.java | RedHat-Healthcare/Event-Builder | 291f6806bf77218ddbce37e81fa2fce6fa668789 | [
"Apache-2.0"
] | 2 | 2021-09-08T19:43:43.000Z | 2022-03-29T16:38:30.000Z | 31.686567 | 104 | 0.753493 | 3,015 | package io.connectedhealth_idaas.eventbuilder.dataobjects.clinical.hl7;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
public class BPX {
private String BPX_1_SetIDBPX;
private String BPX_2_BPDispenseStatus;
private String BPX_3_BPStatus;
private String BPX_4_BPDateTimeofStatus;
private String BPX_5_BCDonationID;
private String BPX_6_BCComponent;
private String BPX_7_BCDonationTypeIntendedUse;
private String BPX_8_CPCommercialProduct;
private String BPX_9_CPManufacturer;
private String BPX_10_CPLotNumber;
private String BPX_11_BPBloodGroup;
private String BPX_12_BCSpecialTesting;
private String BPX_13_BPExpirationDateTime;
private String BPX_14_BPQuantity;
private String BPX_15_BPAmount;
private String BPX_16_BPUnits;
private String BPX_17_BPUniqueID;
private String BPX_18_BPActualDispensedToLocation;
private String BPX_19_BPActualDispensedToAddress;
private String BPX_20_BPDispensedtoReceiver;
private String BPX_21_BPDispensingIndividual;
public String getBPX_1_SetIDBPX() {
return this.BPX_1_SetIDBPX;
}
public void setBPX_1_SetIDBPX(final String BPX_1_SetIDBPX) {
this.BPX_1_SetIDBPX = BPX_1_SetIDBPX;
}
public String getBPX_2_BPDispenseStatus() {
return this.BPX_2_BPDispenseStatus;
}
public void setBPX_2_BPDispenseStatus(final String BPX_2_BPDispenseStatus) {
this.BPX_2_BPDispenseStatus = BPX_2_BPDispenseStatus;
}
public String getBPX_3_BPStatus() {
return this.BPX_3_BPStatus;
}
public void setBPX_3_BPStatus(final String BPX_3_BPStatus) {
this.BPX_3_BPStatus = BPX_3_BPStatus;
}
public String getBPX_4_BPDateTimeofStatus() {
return this.BPX_4_BPDateTimeofStatus;
}
public void setBPX_4_BPDateTimeofStatus(final String BPX_4_BPDateTimeofStatus) {
this.BPX_4_BPDateTimeofStatus = BPX_4_BPDateTimeofStatus;
}
public String getBPX_5_BCDonationID() {
return this.BPX_5_BCDonationID;
}
public void setBPX_5_BCDonationID(final String BPX_5_BCDonationID) {
this.BPX_5_BCDonationID = BPX_5_BCDonationID;
}
public String getBPX_6_BCComponent() {
return this.BPX_6_BCComponent;
}
public void setBPX_6_BCComponent(final String BPX_6_BCComponent) {
this.BPX_6_BCComponent = BPX_6_BCComponent;
}
public String getBPX_7_BCDonationTypeIntendedUse() {
return this.BPX_7_BCDonationTypeIntendedUse;
}
public void setBPX_7_BCDonationTypeIntendedUse(final String BPX_7_BCDonationTypeIntendedUse) {
this.BPX_7_BCDonationTypeIntendedUse = BPX_7_BCDonationTypeIntendedUse;
}
public String getBPX_8_CPCommercialProduct() {
return this.BPX_8_CPCommercialProduct;
}
public void setBPX_8_CPCommercialProduct(final String BPX_8_CPCommercialProduct) {
this.BPX_8_CPCommercialProduct = BPX_8_CPCommercialProduct;
}
public String getBPX_9_CPManufacturer() {
return this.BPX_9_CPManufacturer;
}
public void setBPX_9_CPManufacturer(final String BPX_9_CPManufacturer) {
this.BPX_9_CPManufacturer = BPX_9_CPManufacturer;
}
public String getBPX_10_CPLotNumber() {
return this.BPX_10_CPLotNumber;
}
public void setBPX_10_CPLotNumber(final String BPX_10_CPLotNumber) {
this.BPX_10_CPLotNumber = BPX_10_CPLotNumber;
}
public String getBPX_11_BPBloodGroup() {
return this.BPX_11_BPBloodGroup;
}
public void setBPX_11_BPBloodGroup(final String BPX_11_BPBloodGroup) {
this.BPX_11_BPBloodGroup = BPX_11_BPBloodGroup;
}
public String getBPX_12_BCSpecialTesting() {
return this.BPX_12_BCSpecialTesting;
}
public void setBPX_12_BCSpecialTesting(final String BPX_12_BCSpecialTesting) {
this.BPX_12_BCSpecialTesting = BPX_12_BCSpecialTesting;
}
public String getBPX_13_BPExpirationDateTime() {
return this.BPX_13_BPExpirationDateTime;
}
public void setBPX_13_BPExpirationDateTime(final String BPX_13_BPExpirationDateTime) {
this.BPX_13_BPExpirationDateTime = BPX_13_BPExpirationDateTime;
}
public String getBPX_14_BPQuantity() {
return this.BPX_14_BPQuantity;
}
public void setBPX_14_BPQuantity(final String BPX_14_BPQuantity) {
this.BPX_14_BPQuantity = BPX_14_BPQuantity;
}
public String getBPX_15_BPAmount() {
return this.BPX_15_BPAmount;
}
public void setBPX_15_BPAmount(final String BPX_15_BPAmount) {
this.BPX_15_BPAmount = BPX_15_BPAmount;
}
public String getBPX_16_BPUnits() {
return this.BPX_16_BPUnits;
}
public void setBPX_16_BPUnits(final String BPX_16_BPUnits) {
this.BPX_16_BPUnits = BPX_16_BPUnits;
}
public String getBPX_17_BPUniqueID() {
return this.BPX_17_BPUniqueID;
}
public void setBPX_17_BPUniqueID(final String BPX_17_BPUniqueID) {
this.BPX_17_BPUniqueID = BPX_17_BPUniqueID;
}
public String getBPX_18_BPActualDispensedToLocation() {
return this.BPX_18_BPActualDispensedToLocation;
}
public void setBPX_18_BPActualDispensedToLocation(final String BPX_18_BPActualDispensedToLocation) {
this.BPX_18_BPActualDispensedToLocation = BPX_18_BPActualDispensedToLocation;
}
public String getBPX_19_BPActualDispensedToAddress() {
return this.BPX_19_BPActualDispensedToAddress;
}
public void setBPX_19_BPActualDispensedToAddress(final String BPX_19_BPActualDispensedToAddress) {
this.BPX_19_BPActualDispensedToAddress = BPX_19_BPActualDispensedToAddress;
}
public String getBPX_20_BPDispensedtoReceiver() {
return this.BPX_20_BPDispensedtoReceiver;
}
public void setBPX_20_BPDispensedtoReceiver(final String BPX_20_BPDispensedtoReceiver) {
this.BPX_20_BPDispensedtoReceiver = BPX_20_BPDispensedtoReceiver;
}
public String getBPX_21_BPDispensingIndividual() {
return this.BPX_21_BPDispensingIndividual;
}
public void setBPX_21_BPDispensingIndividual(final String BPX_21_BPDispensingIndividual) {
this.BPX_21_BPDispensingIndividual = BPX_21_BPDispensingIndividual;
}
public String toString() {
return ReflectionToStringBuilder.toString(this);
}
}
|
3e07235b3c84a36cf5b1ad811456497e50f78104 | 2,046 | java | Java | genie-integration/src/main/java/org/ekstep/genieresolvers/group/SetCurrentGroupTask.java | swayangjit/sunbird-android-sdk | 0bd54f6f6db069bb99bdbb7c2fbdfaf1a9bd8e28 | [
"MIT"
] | 3 | 2019-03-01T16:33:43.000Z | 2020-10-10T13:30:33.000Z | genie-integration/src/main/java/org/ekstep/genieresolvers/group/SetCurrentGroupTask.java | swayangjit/sunbird-android-sdk | 0bd54f6f6db069bb99bdbb7c2fbdfaf1a9bd8e28 | [
"MIT"
] | null | null | null | genie-integration/src/main/java/org/ekstep/genieresolvers/group/SetCurrentGroupTask.java | swayangjit/sunbird-android-sdk | 0bd54f6f6db069bb99bdbb7c2fbdfaf1a9bd8e28 | [
"MIT"
] | 5 | 2018-10-08T10:02:33.000Z | 2020-02-20T12:55:39.000Z | 28.416667 | 89 | 0.664712 | 3,016 | package org.ekstep.genieresolvers.group;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import org.ekstep.genieresolvers.BaseTask;
import org.ekstep.genieresolvers.util.Constants;
import org.ekstep.genieservices.commons.bean.GenieResponse;
import org.ekstep.genieservices.commons.utils.GsonUtil;
import java.util.Map;
/**
* Created on 20/7/18.
* shriharsh
*/
public class SetCurrentGroupTask extends BaseTask {
private final String TAG = SetCurrentGroupTask.class.getSimpleName();
private String appQualifier;
private String gid;
public SetCurrentGroupTask(Context context, String appQualifier, String gid) {
super(context);
this.appQualifier = appQualifier;
this.gid = gid;
}
@Override
protected String getLogTag() {
return SetCurrentGroupTask.class.getSimpleName();
}
@Override
protected GenieResponse<Map> execute() {
Cursor cursor = contentResolver.query(getUri(), null, gid, null, null);
if (cursor == null || cursor.getCount() == 0) {
return getErrorResponse(Constants.PROCESSING_ERROR, getErrorMessage(), TAG);
}
return getResponse(cursor);
}
private GenieResponse<Map> getResponse(Cursor cursor) {
GenieResponse<Map> mapData = null;
if (cursor != null && cursor.moveToFirst()) {
do {
mapData = readCursor(cursor);
} while (cursor.moveToNext());
cursor.close();
}
return mapData;
}
private GenieResponse<Map> readCursor(Cursor cursor) {
String serverData = cursor.getString(0);
GenieResponse<Map> response = GsonUtil.fromJson(serverData, GenieResponse.class);
return response;
}
@Override
protected String getErrorMessage() {
return "Could not set user!";
}
private Uri getUri() {
String authority = String.format("content://%s.groups/setGroup", appQualifier);
return Uri.parse(authority);
}
}
|
3e07238b2176664aae55a6d156857bae6851fd61 | 1,429 | java | Java | spring-boot-starter/core-spring-boot-starter/src/main/java/love/forte/simbot/spring/autoconfigure/properties/SimbotCoreConfigurationProperties.java | 58563528/simpler-robot | ad8efda7936559edf8e7bd00f46ad08719a28c6d | [
"Apache-2.0"
] | 259 | 2020-09-25T01:31:18.000Z | 2022-03-31T02:06:34.000Z | spring-boot-starter/core-spring-boot-starter/src/main/java/love/forte/simbot/spring/autoconfigure/properties/SimbotCoreConfigurationProperties.java | 58563528/simpler-robot | ad8efda7936559edf8e7bd00f46ad08719a28c6d | [
"Apache-2.0"
] | 186 | 2020-11-19T15:17:17.000Z | 2022-03-09T02:07:42.000Z | spring-boot-starter/core-spring-boot-starter/src/main/java/love/forte/simbot/spring/autoconfigure/properties/SimbotCoreConfigurationProperties.java | 58563528/simpler-robot | ad8efda7936559edf8e7bd00f46ad08719a28c6d | [
"Apache-2.0"
] | 37 | 2020-10-09T06:47:06.000Z | 2022-03-31T02:00:35.000Z | 21.373134 | 75 | 0.694134 | 3,017 | /*
*
* * Copyright (c) 2021. ForteScarlet All rights reserved.
* * Project simple-robot
* * File MiraiAvatar.kt
* *
* * You can contact the author through the following channels:
* * github https://github.com/ForteScarlet
* * gitee https://gitee.com/ForteScarlet
* * email kenaa@example.com
* * QQ 1149159218
*
*/
package love.forte.simbot.spring.autoconfigure.properties;
import love.forte.simbot.bot.BotResourceType;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* 不被实际使用的配置类,主要用于生成metadata并使得Springboot提供配置文件的快速提示。
*
* 对照了core的具体配置内容进行的配置。
*
* @author <a href="https://github.com/ForteScarlet"> ForteScarlet </a>
*/
@SuppressWarnings("ConfigurationProperties")
@Component
@ConfigurationProperties(prefix = "simbot.core")
@lombok.Getter
@lombok.Setter
public class SimbotCoreConfigurationProperties {
/**
* 建议使用 simbot-bots/*.bot 下文件进行bot注册。
* 参考文档:https://www.yuque.com/simpler-robot/simpler-robot-doc/fk6o3e
*/
@Deprecated
private List<String> bots = null;
/**
* bot资源扫描时所使用的加载类型。
*
*/
private BotResourceType botResourceType;
/**
* 指定要启动的bots。在 .bots中通过 "action_name" 属性进行配置。
*/
private String actionBots;
/**
* 可进行指定的包扫描路径。如果不指定则为启动器所在路径。
*/
private List<String> scanPackage;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.