hexsha
stringlengths 40
40
| size
int64 8
1.04M
| content
stringlengths 8
1.04M
| avg_line_length
float64 2.24
100
| max_line_length
int64 4
1k
| alphanum_fraction
float64 0.25
0.97
|
---|---|---|---|---|---|
0df35c2cfa1afdc90f41c60051f69e2c60b85e96 | 372 | package xyz.a00000.blog.bean.dto;
import lombok.Data;
import lombok.ToString;
import java.io.Serializable;
import java.util.Date;
@Data
@ToString
public class RegisterParams implements Serializable {
private String username;
private String password;
private String token;
private String email;
private String message;
private Date birthday;
}
| 17.714286 | 53 | 0.755376 |
588869d1d1ffc4fffe191e0b5910bba13e21e9e0 | 6,274 | /*
* Copyright 2008-2009 MOPAS(Ministry of Public Administration and Security).
*
* 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.egovframe.rte.itl.integration.metadata;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.atomic.AtomicBoolean;
import org.egovframe.rte.itl.integration.util.Validatable;
import org.springframework.util.StringUtils;
/**
* 전자정부 연계 서비스 메타 데이터 중 '시스템'를 나타내는 구현 클래스
* <p>
* <b>NOTE:</b> 전자정부 연계 서비스 메타 데이터 중 '시스템'를 나타내는 class이다.
* </p>
*
* @author 실행환경 개발팀 심상호
* @since 2009.06.01
* @version 1.0
* <pre>
* 개정이력(Modification Information)
*
* 수정일 수정자 수정내용
* ----------------------------------------------
* 2009.06.01 심상호 최초 생성
* </pre>
*/
public class SystemDefinition implements Validatable {
/** key */
private String key;
/** 기관 */
private OrganizationDefinition organization;
/** 시스템 ID */
private String id;
/** 시스템명 */
private String name;
/** 표준 여부 */
private boolean standard;
/** 소속 서비스 */
private Map<String, ServiceDefinition> services = new HashMap<String, ServiceDefinition>();
/** valid */
private boolean valid = false;
/** statucChanged flag */
private AtomicBoolean statusChanged = new AtomicBoolean(false);
/**
* Default Constructor
*/
public SystemDefinition() {
super();
}
/**
* Constructor
*
* @param key
* key
* @param organization
* 기관
* @param id
* 시스템 ID
* @param name
* 시스템명
* @param standard
* 표준 여부
*/
public SystemDefinition(String key, OrganizationDefinition organization,
String id, String name, boolean standard) {
super();
this.key = key;
this.organization = organization;
this.id = id;
this.name = name;
this.standard = standard;
this.statusChanged.set(true);
}
/**
* Constructor
*
* @param key
* key
* @param organization
* 기관
* @param id
* 시스템 ID
* @param name
* 시스템명
* @param standard
* 표준 여부
* @param services
* 소속 서비스
*/
public SystemDefinition(String key, OrganizationDefinition organization,
String id, String name, boolean standard,
Map<String, ServiceDefinition> services) {
super();
this.key = key;
this.organization = organization;
this.id = id;
this.name = name;
this.standard = standard;
this.services = services;
this.statusChanged.set(true);
}
/**
* Key
*
* @return the key
*/
public String getKey() {
return key;
}
/**
* Key
*
* @param key
* the key to set
*/
public void setKey(String key) {
this.key = key;
this.statusChanged.set(true);
}
/**
* 기관
*
* @return the organization
*/
public OrganizationDefinition getOrganization() {
return organization;
}
/**
* 기관
*
* @param organization
* the organization to set
*/
public void setOrganization(OrganizationDefinition organization) {
this.organization = organization;
this.statusChanged.set(true);
}
/**
* 시스템 Id
*
* @return the id
*/
public String getId() {
return id;
}
/**
* 시스템 Id
*
* @param id
* the id to set
*/
public void setId(String id) {
this.id = id;
this.statusChanged.set(true);
}
/**
* 시스템 명
*
* @return the name
*/
public String getName() {
return name;
}
/**
* 시스템 명
*
* @param name
* the name to set
*/
public void setName(String name) {
this.name = name;
this.statusChanged.set(true);
}
/**
* 표준 여부
*
* @return the standard
*/
public boolean isStandard() {
return standard;
}
/**
* 표준 여부
*
* @param standard
* the standard to set
*/
public void setStandard(boolean standard) {
this.standard = standard;
// this.statusChanged.set(true);
}
/**
* 소속서비스
*
* @return the services
*/
public Map<String, ServiceDefinition> getServices() {
return services;
}
/**
* 소속서비스
*
* @param services
* the services to set
*/
public void setServices(Map<String, ServiceDefinition> services) {
this.services = services;
this.statusChanged.set(true);
}
public ServiceDefinition getServiceDefinition(String serviceId) {
return services.get(serviceId);
}
public boolean isValid() {
if (statusChanged.getAndSet(false)) {
valid = (StringUtils.hasText(key) && organization != null
&& StringUtils.hasText(id) && StringUtils.hasText(name) && services != null);
if (organization != null) {
valid = valid && organization.isValid();
}
if (services != null) {
for (ServiceDefinition service : services.values()) {
valid = valid && service.isValid();
}
}
}
return valid;
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer();
sb.append(this.getClass().getName()).append(" {").append("\n\tkey = ")
.append(StringUtils.quote(key));
if (organization == null) {
sb.append("\n\torganization = null");
} else {
sb.append("\n\torganization.id = ").append(
StringUtils.quote(organization.getId()));
}
sb.append("\n\tid = ").append(StringUtils.quote(id))
.append("\n\tname = ").append(StringUtils.quote(name))
.append("\n\tstandard = ").append(standard);
if (services == null) {
sb.append("\n\tservices = null");
} else {
sb.append("\n\tservices = {");
for (Entry<String, ServiceDefinition> entry : services.entrySet()) {
sb.append("\n\t\t<key = ")
.append(StringUtils.quote(entry.getKey()))
.append(", value = ")
.append(entry.getValue() == null ? "" : "\n")
.append(entry.getValue()).append(">");
}
sb.append("\n\t}");
}
sb.append("\n}");
return sb.toString();
}
}
| 20.706271 | 92 | 0.617947 |
a61bde7508f2a4ed04d7e57bd7d3d7f23083c1ec | 2,828 | package org.unique.web.core;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.unique.web.handler.Handler;
import org.unique.web.util.WebUtil;
/**
* mvc core filter
*/
@WebFilter(urlPatterns = {"/*"},
asyncSupported = true,
initParams = {@WebInitParam(name="configPath",value="config.properties")})
public class Dispatcher implements Filter {
private Logger logger = Logger.getLogger(Dispatcher.class);
private static Unique unique = Unique.single();
private static boolean isInit = false;
private static Handler handler;
private int contextPathLength;
/**
* init
*/
public void init(FilterConfig config) {
if(!isInit){
// config path
Const.CONFIG_PATH = config.getInitParameter("configPath");
ActionContext.single().setActionContext(config.getServletContext());
// init web
isInit = unique.init();
handler = unique.getHandler();
String contextPath = config.getServletContext().getContextPath();
contextPathLength = (contextPath == null || "/".equals(contextPath) ? 0 : contextPath.length());
logger.info("unique web init finish!");
}
}
/**
* doFilter
*
* @author:rex
*/
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
String target = request.getRequestURI().replaceFirst(request.getContextPath(), "");
target = WebUtil.getRelativePath(request, "");
if (contextPathLength != 0) {
target = request.getRequestURI().substring(contextPathLength);
}
if(target.endsWith(Const.URL_EXT)){
target = target.substring(0, target.indexOf(Const.URL_EXT));
}
// set reqest and response
ActionContext.single().setActionContext(request, response);
if (!handler.handle(target, request, response)) {
chain.doFilter(request, response);
}
}
/**
* destroy
*/
public void destroy() {
if (null != unique) {
unique = null;
}
if (null != handler) {
handler = null;
}
}
}
| 27.72549 | 123 | 0.640028 |
47d8f4511f7dd9464f502d64cf516a12d5b1398d | 442 | package com.novbank.ndp.kernel.exception;
/**
* A transaction was not found in the transaction registry
*
* Created by CaoKe on 2015/5/13.
*/
public class TransactionMissingException extends RepositoryRuntimeException {
private static final long serialVersionUID = 2139084821001303830L;
/**
*
* @param s the exception message
*/
public TransactionMissingException(final String s) {
super(s);
}
}
| 22.1 | 77 | 0.701357 |
57f4b1d8fc249046ad00c44a0477d15b4f9e6145 | 999 | package section_12;
import typeinfo.pets.Pet;
import typeinfo.pets.Pets;
import java.util.AbstractCollection;
import java.util.Iterator;
/**
* @Author ZhangGJ
* @Date 2019/05/29
*/
public class CollectionSequence extends AbstractCollection<Pet> {
private Pet[] pets = Pets.createArray(8);
public int size() {
return pets.length;
}
public Iterator<Pet> iterator() {
return new Iterator<Pet>() {
private int index = 0;
public boolean hasNext() {
return index < pets.length;
}
public Pet next() {
return pets[index++];
}
public void remove() { // Not implemented
throw new UnsupportedOperationException();
}
};
}
public static void main(String[] args) {
CollectionSequence c = new CollectionSequence();
InterfaceVsIterator.display(c);
InterfaceVsIterator.display(c.iterator());
}
}
| 22.704545 | 65 | 0.584585 |
9e9d8621776d2444424198420c36b628520ccb11 | 319 | package com.ctrip.framework.apollo.common.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
/**
* 实体对
*
* @author Jason Song([email protected])
*/
@Data
@AllArgsConstructor
public class EntityPair<E> {
/**
* 第一个实体
*/
private E firstEntity;
/**
* 第二个实体
*/
private E secondEntity;
}
| 13.291667 | 49 | 0.667712 |
884fc0b9b134c5dfa938248797bd354062ff3318 | 2,278 | package telran.aop.document;
import java.time.LocalDateTime;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
@AllArgsConstructor
@Data
@NoArgsConstructor
@EqualsAndHashCode
@Document(collection="log")
public class ResDoc {
@Id
LocalDateTime date;
String className;
String methodName;
Long timeResponse;
String result;
String exception;
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ResDoc other = (ResDoc) obj;
if (className == null) {
if (other.className != null)
return false;
} else if (!className.equals(other.className))
return false;
if (date == null) {
if (other.date != null)
return false;
} else if (!date.equals(other.date))
return false;
if (exception == null) {
if (other.exception != null)
return false;
} else if (!exception.equals(other.exception))
return false;
if (methodName == null) {
if (other.methodName != null)
return false;
} else if (!methodName.equals(other.methodName))
return false;
if (result == null) {
if (other.result != null)
return false;
} else if (!result.equals(other.result))
return false;
if (timeResponse == null) {
if (other.timeResponse != null)
return false;
} else if (!timeResponse.equals(other.timeResponse))
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((className == null) ? 0 : className.hashCode());
result = prime * result + ((date == null) ? 0 : date.hashCode());
result = prime * result + ((exception == null) ? 0 : exception.hashCode());
result = prime * result + ((methodName == null) ? 0 : methodName.hashCode());
result = prime * result + ((this.result == null) ? 0 : this.result.hashCode());
result = prime * result + ((timeResponse == null) ? 0 : timeResponse.hashCode());
return result;
}
}
| 24.494624 | 84 | 0.640474 |
146c25864a6770c18c037b1f67cfeb8c963d5f31 | 805 | // Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
package team3176.robot.commands.Shooter;
import edu.wpi.first.wpilibj2.command.InstantCommand;
import team3176.robot.subsystems.Flywheel;
import team3176.robot.subsystems.Vision;
public class FlywheelVisionSet extends InstantCommand {
private Flywheel m_Flywheel = Flywheel.getInstance();
private Vision m_Vision = Vision.getInstance();
public FlywheelVisionSet() {
addRequirements(m_Flywheel);
}
@Override
public void initialize() {
int visionTicksPer100MS = 100; //m_Vision.getBestFlywheelTicksPer100MS(); //TODO: ADD VISION
m_Flywheel.spinMotors(visionTicksPer100MS);
}
}
| 32.2 | 96 | 0.776398 |
431e2be2718b2609fb0af6d6c54fbeccb447e1db | 1,995 | package co.com.devmont.javatestingcourse.movies.data;
import co.com.devmont.javatestingcourse.movies.model.Genre;
import co.com.devmont.javatestingcourse.movies.model.Movie;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import java.util.Collection;
import java.util.List;
public class MovieRepositoryJdbcImpl implements MovieRepository {
private JdbcTemplate jdbcTemplate;
public MovieRepositoryJdbcImpl(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
@Override
public Movie findById(long id) {
Object[] args = {id};
return jdbcTemplate.queryForObject("select * from movies where id = ?", args, movieMapper);
}
@Override
public List<Movie> findByName(String name) {
Object[] args = {"%" + name.toLowerCase() + "%"};
return jdbcTemplate.query("select * from movies where lower(name) like ?", args, movieMapper);
}
@Override
public List<Movie> findByDirector(String director) {
Object[] args = {"%" + director.toLowerCase() + "%"};
return jdbcTemplate.query("select * from movies where lower(director) like ?", args, movieMapper);
}
@Override
public Collection<Movie> findAll() {
return jdbcTemplate.query("select * from movies", movieMapper);
}
@Override
public void saveOrUpdate(Movie movie) {
jdbcTemplate.update(
"insert into movies(name, minutes, genre, director) values(?, ?, ?, ?)",
movie.getName(),
movie.getMinutes(),
movie.getGenre().toString(),
movie.getDirector()
);
}
private static RowMapper<Movie> movieMapper = (resultSet, i) -> new Movie(
resultSet.getInt("id"),
resultSet.getString("name"),
resultSet.getInt("minutes"),
Genre.valueOf(resultSet.getString("genre")),
resultSet.getString("name")
);
}
| 32.704918 | 106 | 0.64411 |
30793316e1a9cc777f17eeca67795ee9e7d73061 | 18,738 | /*
* Copyright 2005-2020 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.openwms.common.transport;
import org.ameba.integration.jpa.ApplicationEntity;
import org.openwms.common.location.LocationType;
import org.springframework.util.Assert;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
/**
* A TransportUnitType is a type of a certain {@code TransportUnit}. Typically to store characteristic attributes of {@code TransportUnit}s,
* such as the length, the height, or the weight of {@code TransportUnit}s. It is possible to group and characterize {@code TransportUnit}s.
*
* @author Heiko Scherrer
* @GlossaryTerm
* @see TransportUnit
*/
@Entity
@Table(name = "COM_TRANSPORT_UNIT_TYPE", uniqueConstraints = @UniqueConstraint(name = "UC_TUT_TYPE", columnNames = "C_TYPE"))
public class TransportUnitType extends ApplicationEntity implements Serializable {
/** Unique natural key. */
@Column(name = "C_TYPE", nullable = false)
@OrderBy
private String type;
/** Description for this type. */
@Column(name = "C_DESCRIPTION")
private String description = DEF_TYPE_DESCRIPTION;
/** Default description of the {@code TransportUnitType}. Default {@value}. */
public static final String DEF_TYPE_DESCRIPTION = "--";
/** Length of the {@code TransportUnitType}. */
@Column(name = "C_LENGTH")
private int length = DEF_LENGTH;
/** Default value of {@link #length}. */
public static final int DEF_LENGTH = 0;
/** Width of the {@code TransportUnitType}. */
@Column(name = "C_WIDTH")
private int width = DEF_WIDTH;
/** Default value of {@link #width}. */
public static final int DEF_WIDTH = 0;
/** Height of the {@code TransportUnitType}. */
@Column(name = "C_HEIGHT")
private int height = DEF_HEIGHT;
/** Default value of {@link #height}. */
public static final int DEF_HEIGHT = 0;
/** Tare weight of the {@code TransportUnitType}. */
@Column(name = "C_WEIGHT_TARE", scale = 3)
private BigDecimal weightTare;
/** Maximum allowed weight of the {@code TransportUnitType}. */
@Column(name = "C_WEIGHT_MAX", scale = 3)
private BigDecimal weightMax;
/** Effective weight of the {@code TransportUnitType}'s payload. */
@Column(name = "C_PAYLOAD", scale = 3)
private BigDecimal payload;
/**
* Characteristic used to hold specific compatibility attributes.<br /> Example:<br /> 'isn't compatible with...' or 'is compatible with
* ...' or 'type owns another type ...'
*/
@Column(name = "C_COMPATIBILITY")
private String compatibility;
/*~ ------------------- collection mapping ------------------- */
/** A collection of all {@link TransportUnit}s belonging to this type. */
@OneToMany(mappedBy = "transportUnitType")
private Set<TransportUnit> transportUnits = new HashSet<>();
/** Describes other {@code TransportUnitType}s and how many of these may be stacked on the {@code TransportUnitType}. */
@OneToMany(mappedBy = "baseTransportUnitType", cascade = {CascadeType.ALL})
private Set<TypeStackingRule> typeStackingRules = new HashSet<>();
/** A Set of {@link TypePlacingRule}s store all possible {@code LocationType} s of the {@code TransportUnitType}. */
@OneToMany(mappedBy = "transportUnitType", cascade = {CascadeType.PERSIST, CascadeType.MERGE}, orphanRemoval = true)
@OrderBy("privilegeLevel")
private Set<TypePlacingRule> typePlacingRules = new HashSet<>();
/*~ ----------------------------- constructors ------------------- */
/** Dear JPA... */
protected TransportUnitType() { }
/**
* Create a new {@code TransportUnitType}.
*
* @param type Unique name
*/
public TransportUnitType(String type) {
Assert.hasText(type, "Type must not be null when creating a TransportUnitType");
this.type = type;
}
private TransportUnitType(Builder builder) {
this.type = builder.type;
setDescription(builder.description);
setLength(builder.length);
setWidth(builder.width);
setHeight(builder.height);
setWeightTare(builder.weightTare);
setWeightMax(builder.weightMax);
setPayload(builder.payload);
setCompatibility(builder.compatibility);
setTransportUnits(builder.transportUnits);
setTypeStackingRules(builder.typeStackingRules);
setTypePlacingRules(builder.typePlacingRules);
}
/**
* Create a TransportUnitType with the corresponding builder.
*
* @param type The business key
* @return The builder instance
*/
public static Builder newBuilder(String type) {
return new Builder(type);
}
/*~ ----------------------------- methods ------------------- */
/**
* Factory method to create a new TransportUnitType.
*
* @param type The business key
* @return The instance
*/
public static TransportUnitType of(String type) {
return new TransportUnitType(type);
}
/**
* Returns the type of the {@code TransportUnitType}.
*
* @return The type
*/
public String getType() {
return this.type;
}
/**
* Returns the width of the {@code TransportUnitType}.
*
* @return The width
*/
public int getWidth() {
return this.width;
}
/**
* Set the width of the {@code TransportUnitType}.
*
* @param width The width to set
*/
public void setWidth(int width) {
this.width = width;
}
/**
* Returns the height of the {@code TransportUnitType}.
*
* @return The height
*/
public int getHeight() {
return this.height;
}
/**
* Set the height of the {@code TransportUnitType}.
*
* @param height The height to set
*/
public void setHeight(int height) {
this.height = height;
}
/**
* Get the length of the {@code TransportUnitType}.
*
* @return The length
*/
public int getLength() {
return this.length;
}
/**
* Set the length of the {@code TransportUnitType}.
*
* @param length The length to set
*/
public void setLength(int length) {
this.length = length;
}
/**
* Returns the description of the {@code TransportUnitType}.
*
* @return The description text
*/
public String getDescription() {
return this.description;
}
/**
* Set the description for the {@code TransportUnitType}.
*
* @param description The description to set
*/
public void setDescription(String description) {
this.description = description;
}
/**
* Returns the payload of the {@code TransportUnitType}.
*
* @return The payload
*/
public BigDecimal getPayload() {
return this.payload;
}
/**
* Set the payload of the {@code TransportUnitType}.
*
* @param payload The payload to set
*/
public void setPayload(BigDecimal payload) {
this.payload = payload;
}
/**
* Returns the compatibility of the {@code TransportUnitType}.
*
* @return The compatibility
*/
public String getCompatibility() {
return this.compatibility;
}
/**
* Set the compatibility of the {@code TransportUnitType}.
*
* @param compatibility The compatibility to set
*/
public void setCompatibility(String compatibility) {
this.compatibility = compatibility;
}
/**
* Returns a Set of all {@link TransportUnit}s belonging to the {@code TransportUnitType}.
*
* @return A Set of all {@link TransportUnit}s belonging to the {@code TransportUnitType}
*/
public Set<TransportUnit> getTransportUnits() {
return this.transportUnits;
}
/**
* Assign a Set of {@link TransportUnit}s to the {@code TransportUnitType}. Already existing {@link TransportUnit}s will be removed.
*
* @param transportUnits A Set of {@link TransportUnit}s.
*/
private void setTransportUnits(Set<TransportUnit> transportUnits) {
this.transportUnits = transportUnits;
}
/**
* Add a rule to the {@code TransportUnitType}. A {@link TypePlacingRule} determines what {@code TransportUnitType}s can be placed on
* which locations.
*
* @param typePlacingRule The rule to set
* @return {@literal true} when the rule was added gracefully, otherwise {@literal false}
*/
public boolean addTypePlacingRule(TypePlacingRule typePlacingRule) {
Assert.notNull(typePlacingRule, "typePlacingRule to add is null, this: " + this);
return typePlacingRules.add(typePlacingRule);
}
/**
* Remove a {@link TypePlacingRule} from the collection or rules.
*
* @param typePlacingRule The rule to be removed
* @return {@literal true} when the rule was removed gracefully, otherwise {@literal false}
*/
public boolean removeTypePlacingRule(TypePlacingRule typePlacingRule) {
Assert.notNull(typePlacingRule, "typePlacingRule to remove is null, this: " + this);
return typePlacingRules.remove(typePlacingRule);
}
/**
* Remove a {@link TypePlacingRule} from the collection or rules.
*
* @param locationType All TypePlacingRules of this LocationType are going to be removed
*/
public void removeTypePlacingRules(LocationType locationType) {
Assert.notNull(locationType, "locationType to remove is null, this: " + this);
List<TypePlacingRule> toRemove = typePlacingRules
.stream()
.filter(tpr -> tpr.getAllowedLocationType().getType().equals(locationType.getType()))
.collect(Collectors.toList());
typePlacingRules.removeAll(toRemove);
}
/**
* Returns all {@link TypePlacingRule}s belonging to the {@code TransportUnitType}.
*
* @return A Set of all placing rules
*/
public Set<TypePlacingRule> getTypePlacingRules() {
return Collections.unmodifiableSet(this.typePlacingRules);
}
/**
* Assign a Set of {@link TypePlacingRule}s to the {@code TransportUnitType}. Already existing {@link TypePlacingRule}s will be
* removed.
*
* @param typePlacingRules The rules to set
*/
private void setTypePlacingRules(Set<TypePlacingRule> typePlacingRules) {
this.typePlacingRules = typePlacingRules;
}
/**
* Returns a Set of all {@link TypeStackingRule}s. A {@link TypeStackingRule} determines which other {@code TransportUnitType}s can be
* placed on the {@code TransportUnitType}.
*
* @return A Set of all stacking rules
*/
public Set<TypeStackingRule> getTypeStackingRules() {
return this.typeStackingRules;
}
/**
* Assign a Set of {@link TypeStackingRule}s. A {@link TypeStackingRule} determines which {@code TransportUnitType}s can be placed on
* the {@code TransportUnitType}. Already existing {@link TypeStackingRule} s will be removed.
*
* @param typeStackingRules The rules to set
*/
private void setTypeStackingRules(Set<TypeStackingRule> typeStackingRules) {
this.typeStackingRules = typeStackingRules;
}
/**
* Get the weightTare.
*
* @return The weightTare.
*/
public BigDecimal getWeightTare() {
return weightTare;
}
/**
* Set the weightTare.
*
* @param weightTare The weightTare to set.
*/
public void setWeightTare(BigDecimal weightTare) {
this.weightTare = weightTare;
}
/**
* Get the weightMax.
*
* @return The weightMax.
*/
public BigDecimal getWeightMax() {
return weightMax;
}
/**
* Set the weightMax.
*
* @param weightMax The weightMax to set.
*/
public void setWeightMax(BigDecimal weightMax) {
this.weightMax = weightMax;
}
/**
* Returns the type.
*
* @return as String
* @see Object#toString()
*/
@Override
public String toString() {
return this.type;
}
/**
* {@inheritDoc}
*/
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TransportUnitType that = (TransportUnitType) o;
return Objects.equals(type, that.type);
}
/**
* {@inheritDoc}
*/
@Override
public int hashCode() {
return Objects.hash(type);
}
/**
* {@code TransportUnitType} builder static inner class.
*/
public static final class Builder {
private String type;
private String description;
private int length;
private int width;
private int height;
private BigDecimal weightTare;
private BigDecimal weightMax;
private BigDecimal payload;
private String compatibility;
private Set<TransportUnit> transportUnits;
private Set<TypeStackingRule> typeStackingRules;
private Set<TypePlacingRule> typePlacingRules;
private Builder(String type) {
this.type = type;
}
/**
* Sets the {@code description} and returns a reference to this Builder so that the methods can be chained together.
*
* @param val the {@code description} to set
* @return a reference to this Builder
*/
public Builder description(String val) {
description = val;
return this;
}
/**
* Sets the {@code length} and returns a reference to this Builder so that the methods can be chained together.
*
* @param val the {@code length} to set
* @return a reference to this Builder
*/
public Builder length(int val) {
length = val;
return this;
}
/**
* Sets the {@code width} and returns a reference to this Builder so that the methods can be chained together.
*
* @param val the {@code width} to set
* @return a reference to this Builder
*/
public Builder width(int val) {
width = val;
return this;
}
/**
* Sets the {@code height} and returns a reference to this Builder so that the methods can be chained together.
*
* @param val the {@code height} to set
* @return a reference to this Builder
*/
public Builder height(int val) {
height = val;
return this;
}
/**
* Sets the {@code weightTare} and returns a reference to this Builder so that the methods can be chained together.
*
* @param val the {@code weightTare} to set
* @return a reference to this Builder
*/
public Builder weightTare(BigDecimal val) {
weightTare = val;
return this;
}
/**
* Sets the {@code weightMax} and returns a reference to this Builder so that the methods can be chained together.
*
* @param val the {@code weightMax} to set
* @return a reference to this Builder
*/
public Builder weightMax(BigDecimal val) {
weightMax = val;
return this;
}
/**
* Sets the {@code payload} and returns a reference to this Builder so that the methods can be chained together.
*
* @param val the {@code payload} to set
* @return a reference to this Builder
*/
public Builder payload(BigDecimal val) {
payload = val;
return this;
}
/**
* Sets the {@code compatibility} and returns a reference to this Builder so that the methods can be chained together.
*
* @param val the {@code compatibility} to set
* @return a reference to this Builder
*/
public Builder compatibility(String val) {
compatibility = val;
return this;
}
/**
* Sets the {@code transportUnits} and returns a reference to this Builder so that the methods can be chained together.
*
* @param val the {@code transportUnits} to set
* @return a reference to this Builder
*/
public Builder transportUnits(Set<TransportUnit> val) {
transportUnits = val;
return this;
}
/**
* Sets the {@code typeStackingRules} and returns a reference to this Builder so that the methods can be chained together.
*
* @param val the {@code typeStackingRules} to set
* @return a reference to this Builder
*/
public Builder typeStackingRules(Set<TypeStackingRule> val) {
typeStackingRules = val;
return this;
}
/**
* Sets the {@code typePlacingRules} and returns a reference to this Builder so that the methods can be chained together.
*
* @param val the {@code typePlacingRules} to set
* @return a reference to this Builder
*/
public Builder typePlacingRules(Set<TypePlacingRule> val) {
typePlacingRules = val;
return this;
}
/**
* Returns a {@code TransportUnitType} built from the parameters previously set.
*
* @return a {@code TransportUnitType} built with parameters of this {@code TransportUnitType.Builder}
*/
public TransportUnitType build() {
return new TransportUnitType(this);
}
}
}
| 31.598651 | 140 | 0.621945 |
0cc1bdcd722ab4afb7e351099d32995168ee2894 | 3,323 | /*
* 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.logging.log4j.core.async;
import com.lmax.disruptor.LifecycleAware;
import com.lmax.disruptor.Sequence;
import com.lmax.disruptor.SequenceReportingEventHandler;
/**
* This event handler gets passed messages from the RingBuffer as they become
* available. Processing of these messages is done in a separate thread,
* controlled by the {@code Executor} passed to the {@code Disruptor}
* constructor.
*/
public class RingBufferLogEventHandler implements
SequenceReportingEventHandler<RingBufferLogEvent>, LifecycleAware {
private static final int NOTIFY_PROGRESS_THRESHOLD = 50;
private Sequence sequenceCallback;
private int counter;
private long threadId = -1;
@Override
public void setSequenceCallback(final Sequence sequenceCallback) {
this.sequenceCallback = sequenceCallback;
}
@Override
public void onEvent(final RingBufferLogEvent event, final long sequence,
final boolean endOfBatch) throws Exception {
try {
// RingBufferLogEvents are populated by an EventTranslator. If an exception is thrown during event
// translation, the event may not be fully populated, but Disruptor requires that the associated sequence
// still be published since a slot has already been claimed in the ring buffer. Ignore any such unpopulated
// events. The exception that occurred during translation will have already been propagated.
if (event.isPopulated()) {
event.execute(endOfBatch);
}
}
finally {
event.clear();
// notify the BatchEventProcessor that the sequence has progressed.
// Without this callback the sequence would not be progressed
// until the batch has completely finished.
notifyCallback(sequence);
}
}
private void notifyCallback(final long sequence) {
if (++counter > NOTIFY_PROGRESS_THRESHOLD) {
sequenceCallback.set(sequence);
counter = 0;
}
}
/**
* Returns the thread ID of the background consumer thread, or {@code -1} if the background thread has not started
* yet.
* @return the thread ID of the background consumer thread, or {@code -1}
*/
public long getThreadId() {
return threadId;
}
@Override
public void onStart() {
threadId = Thread.currentThread().getId();
}
@Override
public void onShutdown() {
}
}
| 37.761364 | 119 | 0.692748 |
4af6fc11604757d748b6c5195c9ff1f85e824ec6 | 676 | package nl.nikhef.jgridstart.gui.util;
import javax.swing.JButton;
import nl.nikhef.xhtmlrenderer.swing.ITemplatePanel;
import nl.nikhef.xhtmlrenderer.swing.ITemplatePanelTest;
import nl.nikhef.xhtmlrenderer.swing.TemplatePanelGuitest;
public class TemplateButtonPanelGuitest extends TemplatePanelGuitest {
@Override
protected ITemplatePanel createPanel() {
return new TemplateButtonPanel();
}
public static void main(String[] args) throws Exception {
TemplateButtonPanel panel = new TemplateButtonPanel();
panel.addButton(new JButton("dummy"), false);
panel.addButton(new JButton("dfldummy"), true);
ITemplatePanelTest.main(panel, args);
}
}
| 30.727273 | 70 | 0.782544 |
a5d86f65b2c51f32062059a9f760b173501be7c2 | 1,107 | package com.skeqi.finance.mapper.endhandle;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.skeqi.finance.domain.endhandle.withholding.TGlWithholdingScheme;
import com.skeqi.common.core.mybatisplus.core.BaseMapperPlus;
import com.skeqi.common.core.mybatisplus.cache.MybatisPlusRedisCache;
import com.skeqi.finance.pojo.bo.endhandle.TGlWithholdingSchemeQueryBo;
import com.skeqi.finance.pojo.vo.endhandle.TGlWithholdingSchemeVo;
import org.apache.ibatis.annotations.CacheNamespace;
import org.apache.ibatis.annotations.Param;
/**
* 凭证预提Mapper接口
*
* @author toms
* @date 2021-07-27
*/
// 如使需切换数据源 请勿使用缓存 会造成数据不一致现象
@CacheNamespace(implementation = MybatisPlusRedisCache.class, eviction = MybatisPlusRedisCache.class)
public interface TGlWithholdingSchemeMapper extends BaseMapperPlus<TGlWithholdingScheme> {
IPage<TGlWithholdingSchemeVo> queryPageList(Page<TGlWithholdingSchemeQueryBo> userPage, @Param("bo") TGlWithholdingSchemeQueryBo bo);
TGlWithholdingSchemeVo getInfo(@Param("fSchemeId") Integer fSchemeId);
}
| 41 | 134 | 0.837398 |
76f1667b53e4bfbf1ff83480dfbe50fdece61cce | 1,060 | package org.cocos2dx.cpp.drawingcoloring.activity;
import android.Manifest;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import org.cocos2dx.cpp.drawingcoloring.core.Const;
import org.cocos2dx.cpp.drawingcoloring.view.ViewDrawingColoring;
public class DrawingActivity extends DrawingColoringActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 99);
setMode(ViewDrawingColoring.MODE.DRAWING);
setBGColor(mPreference.getConfig(Const.PARAM_BG_COLOR_INDEX, 0), false);
setPenColor(mPreference.getConfig(Const.PARAM_PEN_COLOR_INDEX_IN_DRAWING, 1), false);
mbNeedSave = mPreference.getConfig(Const.PARAM_NEED_SAVE_IN_DRAWING, false);
checkSaveButton();
}
@Override
protected void onPause() {
super.onPause();
mPreference.setConfig(Const.PARAM_NEED_SAVE_IN_DRAWING, mbNeedSave);
}
}
| 35.333333 | 110 | 0.762264 |
f61886091943391a6f687c3c0e6620c8d3af6481 | 1,700 | package com.cavecat.bo;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import org.springframework.dao.DataAccessException;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.util.HtmlUtils;
import com.cavecat.dao.BoardDAO;
import com.cavecat.model.Board;
@Service
public class BoardBO {
private final BoardDAO boardDAO;
public BoardBO(BoardDAO boardDAO) {
this.boardDAO = boardDAO;
}
@Transactional
public Board getBoard(Long sequence) throws DataAccessException {
Optional<Board> rawBoard = boardDAO.findOne(Example.of(new Board(sequence)));
rawBoard.ifPresent(board -> {
board.setReadCount(board.getReadCount() + 1);
board.setTitle(HtmlUtils.htmlEscape(board.getTitle(), "utf-8"));
boardDAO.save(board);
board.setText(HtmlUtils.htmlEscape(board.getText()));
});
return rawBoard.orElseGet(Board::new);
}
@Transactional(readOnly = true)
public List<Board> getBoardes() throws DataAccessException {
return boardDAO.findAll(Sort.by(Sort.Direction.DESC, "sequence"));
}
@Transactional
public Long addBoard(Board board) throws DataAccessException {
board.setRegisteredDate(new Date());
board = boardDAO.save(board);
return board.getSequence();
}
@Transactional
public void modifyBoard(Board board) throws DataAccessException {
boardDAO.save(board);
}
@Transactional
public void removeBoard(Long sequence) throws DataAccessException {
boardDAO.delete(new Board(sequence));
}
}
| 27.419355 | 81 | 0.750588 |
08bc60d62ea8cc3409b216634e286c29a1f20723 | 1,249 | package io.github.mattthomson.depijp.tap;
import com.google.common.base.Charsets;
import com.google.common.io.Files;
import io.github.mattthomson.depijp.DePijpSink;
import io.github.mattthomson.depijp.DePijpSource;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.util.List;
import static io.github.mattthomson.depijp.tap.DePijpTapTestUtil.readFromSource;
import static io.github.mattthomson.depijp.tap.DePijpTapTestUtil.writeToSink;
import static org.assertj.core.api.Assertions.assertThat;
public class TextLineDePijpTapTest {
@Test
public void shouldReadLinesFromFile() {
DePijpSource<String> tap = new TextLineDePijpTap("src/test/resources/values.txt");
assertThat(readFromSource(tap)).containsExactly("one", "two", "three");
}
@Test
public void shouldWriteLinesToFile() throws IOException {
File outputFile = File.createTempFile("output", "txt");
outputFile.deleteOnExit();
DePijpSink<String> tap = new TextLineDePijpTap(outputFile.getPath());
writeToSink(tap, "one", "two", "three");
List<String> result = Files.readLines(outputFile, Charsets.UTF_8);
assertThat(result).containsExactly("one", "two", "three");
}
} | 35.685714 | 90 | 0.738991 |
c9f3bf6b5df0dec3094dec4130508937a52239fc | 2,252 | package com.eme22.bolo.commands.admin;
import com.eme22.bolo.Bot;
import com.eme22.bolo.commands.AdminCommand;
import com.jagrosh.jdautilities.command.CommandEvent;
import net.dv8tion.jda.api.entities.Message;
import net.dv8tion.jda.api.events.interaction.SlashCommandEvent;
import net.dv8tion.jda.api.interactions.commands.OptionType;
import net.dv8tion.jda.api.interactions.commands.build.OptionData;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
public class ClearMessagesCmd extends AdminCommand {
public ClearMessagesCmd(Bot bot)
{
this.name = "clear";
this.help = "limpia los mensajes especificados";
this.arguments = "<2 - 100>";
this.aliases = bot.getConfig().getAliases(this.name);
this.options = Collections.singletonList(new OptionData(OptionType.INTEGER, "mensajes", "numero entre 2 al 100").setMinValue(2).setMaxValue(100).setRequired(true));
}
@Override
protected void execute(SlashCommandEvent event) {
int values = Integer.parseInt(event.getOption("mensajes").getAsString());
List<Message> messages = event.getChannel().getHistory().retrievePast(values).complete();
event.getTextChannel().deleteMessages(messages).queue();
event.reply(getClient().getSuccess() +" " + values + " mensajes borrados!").setEphemeral(true).queue();
}
@Override
protected void execute(CommandEvent event) {
try {
int values = Integer.parseInt(event.getArgs());
if (values < 1 || values > 100) {
event.replyError("El valor tiene que ser entre 1 y 100!");
return;
}
//event.getMessage().delete();
List<Message> messages = event.getChannel().getHistory().retrievePast(values+1).complete();
event.getTextChannel().deleteMessages(messages).queue();
event.getChannel().sendMessage( event.getClient().getSuccess() +" " + values + " mensajes borrados!").queue(m ->
m.delete().queueAfter(5, TimeUnit.SECONDS));
} catch (NumberFormatException ex) {
event.replyError("Escribe un numero entre 1 y 100");
}
}
}
| 40.214286 | 172 | 0.671847 |
e3ef6ae9147882f1b002d4d23cf50493a8be1663 | 3,352 | package com.xhe.common.redis.config;
import cn.hutool.core.date.DatePattern;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import com.xhe.lynx.common.core.jackjson.JavaTimeModule;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import java.time.ZoneId;
import java.util.Locale;
import java.util.TimeZone;
/**
* @Classname RedisConfig
* @Description redis template配置
* @Date 2020/3/4 9:50
* @Created by xhe
*/
@EnableConfigurationProperties({RedisProperties.class})
@Configuration
public class RedisAutoConfigure {
/**
* RedisTemplate配置
* @param factory
*/
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(factory);
RedisSerializer<String> stringSerializer = new StringRedisSerializer();
//使用Jackson序列化
Jackson2JsonRedisSerializer<Object> redisObjectSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
ObjectMapper objectMapper = builder.locale(Locale.CHINA)
.timeZone(TimeZone.getTimeZone(ZoneId.systemDefault()))
.simpleDateFormat(DatePattern.NORM_DATETIME_PATTERN)
.modules(new JavaTimeModule())
.build();
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
//将类名称序列化到json串中,去掉会导致得出来的的是LinkedHashMap对象,直接转换实体对象会失败
objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
//已弃用
//objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
//设置输入时忽略JSON字符串中存在而Java对象实际没有的属性
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
redisObjectSerializer.setObjectMapper(objectMapper);
redisTemplate.setKeySerializer(stringSerializer);
redisTemplate.setHashKeySerializer(stringSerializer);
redisTemplate.setValueSerializer(redisObjectSerializer);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}
| 45.917808 | 146 | 0.790573 |
9de8c13a00216d25a84f444a24aa0ab53cb6e9b9 | 1,803 | package io.quarkus.mongodb.panache.deployment;
import io.quarkus.mongodb.panache.PanacheMongoEntity;
import io.quarkus.mongodb.panache.PanacheMongoEntityBase;
import io.quarkus.mongodb.panache.PanacheMongoRepository;
import io.quarkus.mongodb.panache.PanacheMongoRepositoryBase;
import io.quarkus.mongodb.panache.PanacheQuery;
import io.quarkus.mongodb.panache.PanacheUpdate;
import io.quarkus.mongodb.panache.runtime.MongoOperations;
public class ImperativeTypeBundle implements TypeBundle {
@Override
public ByteCodeType entity() {
return new ByteCodeType(PanacheMongoEntity.class);
}
@Override
public ByteCodeType entityBase() {
return new ByteCodeType(PanacheMongoEntityBase.class);
}
@Override
public ByteCodeType entityBaseCompanion() {
throw new UnsupportedOperationException("Companions are not supported in Java.");
}
@Override
public ByteCodeType entityCompanion() {
throw new UnsupportedOperationException("Companions are not supported in Java.");
}
@Override
public ByteCodeType entityCompanionBase() {
throw new UnsupportedOperationException("Companions are not supported in Java.");
}
@Override
public ByteCodeType operations() {
return new ByteCodeType(MongoOperations.class);
}
@Override
public ByteCodeType queryType() {
return new ByteCodeType(PanacheQuery.class);
}
@Override
public ByteCodeType repository() {
return new ByteCodeType(PanacheMongoRepository.class);
}
@Override
public ByteCodeType repositoryBase() {
return new ByteCodeType(PanacheMongoRepositoryBase.class);
}
@Override
public ByteCodeType updateType() {
return new ByteCodeType(PanacheUpdate.class);
}
}
| 29.080645 | 89 | 0.734886 |
c323242c3a15f23e5a339ee0f70220cc618e57e6 | 138 | package com.ynhenc.comm.registry;
import com.ynhenc.comm.ArrayListEx;
public class ArrayListRegiItem extends ArrayListEx<RegiItem> {
}
| 17.25 | 62 | 0.811594 |
669e0dbc63011c87176b540d4f5ec654cdc7f4ff | 318 | package ru.mihkopylov.myspb.dao;
import lombok.NonNull;
import org.springframework.data.jpa.repository.JpaRepository;
import ru.mihkopylov.myspb.model.User;
import java.util.Optional;
public interface UserDao extends JpaRepository<User, Long> {
@NonNull
Optional<User> findByLogin(@NonNull String login);
}
| 24.461538 | 61 | 0.792453 |
5993232e6c7decb546bcae2fa64bf3b51c9e9116 | 1,235 | package problems;
import java.util.HashSet;
import java.util.Set;
import datastructures.SinglyLinkedList;
import datastructures.SinglyLinkedList.Node;
/**
* Cracking the Coding Interview - Data Structures 2 Linked Lists 2.1 Write code
* to remove duplicates from an unsorted linked list.
*
* @author Ajinkya Patil
*/
public class RemoveDuplFromLinkedList {
public static void removeDuplicates(SinglyLinkedList list) {
Node current = list.head;
Node prev = list.head;
Set<Integer> box = new HashSet<Integer>();
while (current != null) {
if (box.contains(current.data)) {
prev.next = current.next;
current = current.next;
} else {
box.add(current.data);
prev = current;
current = current.next;
}
}
}
public static void main(String[] args) {
SinglyLinkedList list = new SinglyLinkedList();
Node prev = null;
for (int i = 0; i < args.length; i++) {
Node node = new Node(Integer.parseInt(args[i]));
if (i == 0) {
list.head = node;
prev = list.head;
continue;
}
prev.next = node;
prev = node;
}
removeDuplicates(list);
Node current = list.head;
while (current != null) {
System.out.print(current.data + " ");
current = current.next;
}
}
}
| 23.301887 | 80 | 0.664777 |
4271c5f469a0d2e51d26223244ab5aa42969cab1 | 20,851 | package com.leidos.glidepath.ead;
import com.leidos.glidepath.appcommon.Constants;
import com.leidos.glidepath.appcommon.utils.GlidepathApplicationContext;
import com.leidos.glidepath.asd.Location;
import com.leidos.glidepath.asd.map.MapMessage;
import com.leidos.glidepath.dvi.AppConfig;
import com.leidos.glidepath.logger.Logger;
import com.leidos.glidepath.logger.LoggerManager;
import java.util.Vector;
// This class represents the geometry of a single road intersection and the position of the vehicle relative to it. It is
// constructed from a MAP message. Given a vehicle position, it will attempt to determine which lane the vehicle is driving on
// (aka the associated lane). There are situations where such an association may be impossible, such as the indicated
// vehicle position is nowhere near any of the defined lanes.
public class Intersection {
/**
* Constructs the Intersection object
* @param perfCheck - should we respect the timeouts established for acceptable performance? (turn off for testing)
*/
public Intersection(boolean perfCheck) {
AppConfig config = GlidepathApplicationContext.getInstance().getAppConfig();
assert(config != null);
cteThreshold_ = Integer.valueOf(config.getProperty("ead.cte.threshold"));
respectTimeouts_ = perfCheck;
allInitialized_ = false;
laneIndex_ = -1;
laneDtsb_ = Integer.MAX_VALUE;
cte_ = Integer.MAX_VALUE;
prevLaneApproach_ = false;
prevLaneIndex_ = -1;
prevDtsb_ = Integer.MAX_VALUE;
lastApproachDtsb_ = 0;
firstEgressDtsb_ = 0;
map_ = null;
laneGeo_ = null;
stopBoxWidth_ = 0.0;
}
/**
* mapMsg intersection ID != to stored ID || mapMsg content version != previously stored : exception
* pre-processing complete : do nothing
* pre-processing incomplete : continue constructing geometry pre-processing
*
* Note: the pre-processing could take a long time, but this method must return in less than one Glidepath timestep, so
* there is a mechanism to break it up into multiple chunks that can be done in sequential calls. Keep calling
* this method until it returns true before using any of the other methods.
*
* @param mapMsg - a valid MAP message retrieved from the ASD device that describes the intersection
* @return true if pre-processing is complete, false if additional pre-processing of this intersection is needed
*/
public boolean initialize(MapMessage mapMsg) throws Exception {
//if some initialization remains to be done then
if(!allInitialized_) {
long startTime = System.currentTimeMillis();
long timeElapsed = 0;
//if incoming message is different from previously analyzed one then throw an exception (mapMsg is guaranteed to be non-null)
if (map_ != null && (mapMsg.intersectionId() != map_.intersectionId() || mapMsg.getContentVersion() != map_.getContentVersion())) {
log_.errorf("INTR", "Attempting to use a different mapMsg: intersection %d, content ver %d", mapMsg.intersectionId(), mapMsg.getContentVersion());
throw new Exception("Intersection.initialize() was passed a mapMsg different from the one originally passed to this object.");
}
//store the MAP message
map_ = mapMsg;
//set up the array for each lane
int numLanes = mapMsg.numLanes();
if (laneGeo_ == null) {
laneGeo_ = new LaneGeometry[numLanes];
for (int j = 0; j < numLanes; ++j) {
laneGeo_[j] = null;
}
}
//loop through each lane in the MAP message while there is time available to work it
for (int i = 0; i < numLanes && timeElapsed < TIME_BUDGET; ++i) {
//if a geometry hasn't already been constructed for this lane then
if (laneGeo_[i] == null) {
//create the lane geometry from the current lane in the MAP message
laneGeo_[i] = new LaneGeometry(mapMsg.getRefPoint(), mapMsg.getLane(i));
//log_.debugf("INTR", "Geometry initialized for lane index %d", i);
//if this is the final geometry to be created then
if (i == numLanes - 1) {
//indicate initialization complete
allInitialized_ = true;
}else {
if (respectTimeouts_) {
timeElapsed = System.currentTimeMillis() - startTime;
}else {
timeElapsed = 0;
}
}
}
} //end loop on lanes
//if all lanes have been computed then
if (allInitialized_) {
//find the largest distance between any pair of stop bars (node 0 of each lane)
for (int i = 0; i < numLanes - 1; ++i) {
CartesianPoint2D sb1 = laneGeo_[i].getStopBar();
for (int j = i + 1; j < numLanes; ++j) {
CartesianPoint2D sb2 = laneGeo_[j].getStopBar();
double dist = 0.01*sb1.distanceFrom(sb2);
if (dist > stopBoxWidth_) {
stopBoxWidth_ = dist;
}
}
}
}
log_.infof("INTR", "End of initialize. allInitialized = %b; exec time = %d ms, stopBoxWidth = %.2f",
allInitialized_, System.currentTimeMillis()-startTime, stopBoxWidth_);
} //endif some initialization is needed
return allInitialized_;
}
/**
* intersection initialized : determine which lane(s) the vehicle is associated with and its position relative to that lane
* intersection not initialized : false
*
* @param vehicleLat in degrees
* @param vehicleLon in degrees
* @return true if vehicle is successfully associated with a single lane; false if not
*/
public boolean computeGeometry(double vehicleLat, double vehicleLon) {
boolean success = false;
//if intersection not fully initialized then return false
if (!allInitialized_) return false;
Location vehicle = new Location(vehicleLat, vehicleLon);
class Candidate {
public int index;
public boolean approach;
public int dtsb; //this is simply dist to the stop bar of THIS lane, not necessarily of the lane we approached the intersection on
public int cte;
}
Vector<Candidate> candidateLanes = new Vector<Candidate>();
Candidate prevLane = new Candidate();
prevLane.index = prevLaneIndex_;
prevLane.approach = prevLaneApproach_;
Candidate chosenLane = null;
// ----- initial screening for candidate lanes that we might be close to - see if we're in any bounding boxes
// Caution: if the bounding box thresholds are too small relative to the size of the intersection, there
// may be a no-man's land near the center of the stop box that is not in any of the lanes' bounding boxes!
// This would fail the first screen and no DTSB would be calculated.
//loop on all lanes
for (int i = 0; i < map_.numLanes(); ++i) {
//if the vehicle is in this lane's bounding box then
if (laneGeo_[i].inBoundingBox(vehicle)) {
//get DTSB & CTE relative to this lane
Candidate cand = new Candidate();
cand.dtsb = laneGeo_[i].dtsb(vehicle);
cand.cte = laneGeo_[i].cte(vehicle);
//record the lane index & type as a candidate
cand.index = i;
cand.approach = map_.getLane(i).isApproach();
candidateLanes.add(cand);
}
}
log_.debugf("INTR", "computeGeometry: initial screening found %d candidate lanes", candidateLanes.size());
// ----- for all candidates found above let's spend the time to see if our cross-track error (lateral distance to lane centerline)
// ----- is small enough to call this "our" lane in a variety of possible situations
//if at least one candidate lane was identified then
if (candidateLanes.size() > 0) {
//if only one candidate lane was identified then
if (candidateLanes.size() == 1) {
//if it is the same lane as used previously or (this lane is egress and previous was approach) then
if (candidateLanes.get(0).index == prevLane.index ||
(!candidateLanes.get(0).approach && prevLane.approach)) {
//store it and indicate success
chosenLane = candidateLanes.get(0);
success = true;
//else (it's a different lane and no egress transition is in the works)
}else {
//if its CTE is within the acceptable threshold then indicate success
if (candidateLanes.get(0).cte < cteThreshold_) {
chosenLane = candidateLanes.get(0);
success = true;
}
}
//else (multiple candidates were identified)
}else {
//if vehicle is approaching the intersection then
if (prevDtsb_ >= 0) {
//if we are close to the stop bar then
if (prevDtsb_ < Constants.THRESHOLD_DIST && prevLane.index >= 0) {
//use the same lane as previous time step (too many lanes near the stop box to try sorting them out)
chosenLane = prevLane;
chosenLane.cte = laneGeo_[chosenLane.index].cte(vehicle);
chosenLane.dtsb = laneGeo_[chosenLane.index].dtsb(vehicle);
//else
}else {
//choose the approach lane with the smallest CTE
int smallestCte = Integer.MAX_VALUE;
for (int j = 0; j < candidateLanes.size(); ++j) {
Candidate c = candidateLanes.get(j);
if (c.approach && c.cte < smallestCte) {
chosenLane = c;
smallestCte = c.cte;
}
}
}
/*****
if (chosenLane == null) {
log_.debugf("INTR", "approaching: prevDtsb = %d, no lane chosen.", prevDtsb_);
}else {
log_.debugf("INTR", "approaching: prevDtsb = %d, chose lane index %d", prevDtsb_, chosenLane.index);
}
*****/
//else (beyond stop bar - in intersection or we are already departing)
}else {
//if we are sufficiently downtrack of the stop bar (same as uptrack closeness threshold) then
if (prevDtsb_ < -Constants.THRESHOLD_DIST) {
//choose the egress lane with the smallest CTE
int smallestCte = Integer.MAX_VALUE;
for (int j = 0; j < candidateLanes.size(); ++j) {
Candidate c = candidateLanes.get(j);
if (!c.approach && c.cte < smallestCte) {
chosenLane = c;
smallestCte = c.cte;
}
}
//else if the previous time step was associated with an approach lane then
}else if (prevLane.index >= 0 && map_.getLane(prevLane.index).isApproach()){
//stay on lane from prev time step
chosenLane = prevLane;
chosenLane.cte = laneGeo_[chosenLane.index].cte(vehicle);
chosenLane.dtsb = laneGeo_[chosenLane.index].dtsb(vehicle);
}
if (chosenLane == null) {
log_.debugf("INTR", "beyond stop bar: prevDtsb = %d, no lane chosen.", prevDtsb_);
}else {
log_.debugf("INTR", "beyond stop bar: prevDtsb = %d, chose lane index %d", prevDtsb_, chosenLane.index);
}
} //endif vehicle is approaching
//if CTE of the chosen lane is less than the threshold distance then indicate success
if (chosenLane != null && chosenLane.cte < cteThreshold_) {
success = true;
}
} //endif multiple candidates found
log_.debugf("INTR", "computeGeometry: detailed screening complete with success = %b, prevDtsb_ = %d, prev index = %d", success, prevDtsb_, prevLane.index);
// ----- final polish - make sure that the candidate lane we identified passes a final sanity check
//if we found a candidate then
if (success) { //guarantees chosenLane is defined
//if the candidate is an egress lane then
if (!chosenLane.approach) {
//we were previously on an approach then
if (prevLane.approach) {
//store the previous DTSB and current lane's DTSB permanently as the baseline
// (since DTSB on egress will still have to get more negative)
lastApproachDtsb_ = laneGeo_[prevLane.index].dtsb(vehicle);
firstEgressDtsb_ = chosenLane.dtsb;
log_.infof("INTR", "///// Changing from approach to egress at lane (index %d) DTSB = %d cm", chosenLane.index, chosenLane.dtsb);
}
//else (approach lane)
}else {
//if the candidate's DTSB is way different from the DTSB used in the previous time step then
int diff = prevDtsb_ - chosenLane.dtsb;
if (prevLane.index >= 0 && (diff < -20 || diff > LARGE_MOVEMENT)) { //allow for drift in position signal or slow time step processing
//if the candidate is different from the lane used in the previous time step then
if (chosenLane.index != prevLane.index) {
//if the previously used lane is still in the candidate list then
boolean found = false;
for (int j = 0; j < candidateLanes.size(); ++j) {
if (candidateLanes.get(j).index == prevLane.index) {
found = true;
log_.debugf("INTR", "computeGeometry: DTSB jumped by %d cm; switched from lane %d to %d", diff, chosenLane.index, prevLane.index);
break;
}
}
if (found) {
//indicate that this previously used one is our candidate
chosenLane.index = prevLane.index;
//if its CTE > threshold distance then
if (laneGeo_[chosenLane.index].cte(vehicle) > cteThreshold_) {
//indicate failure
success = false;
log_.debugf("INTR", "computeGeometry failed. DTSB jumped by %d cm, but prev lane (%d) had large CTE", diff, chosenLane.index);
}
//else
}else {
//indicate failure
success = false;
log_.debugf("INTR", "computeGeometry failed. DTSB jumped by %d cm, so reverted to prev lane (%d)", diff, chosenLane.index);
}
//else (candidate lane is same as the previous lane)
}else {
//indicate failure
success = false;
log_.debugf("INTR", "computeGeometry failed. Chose same lane (%d) but DTSB jumped by %d cm", chosenLane.index, diff);
}
} //endif DTSB is way different
} //endif approach lane
} //endif found a candidate
} //endif at least one candidate found
//if no lanes found but we are wandering around in the stop box then
if (!success && prevDtsb_ < 0 && prevLane.approach) {
//stay with the one who brung ya (previous approach lane)
chosenLane = prevLane;
chosenLane.cte = laneGeo_[chosenLane.index].cte(vehicle);
chosenLane.dtsb = laneGeo_[chosenLane.index].dtsb(vehicle);
success = true;
log_.info("INTR", "computeGeometry: in stop box, no other lanes available so staying with approach lane.");
}
//at this point if no lane was successfully chosen then chosenLane.index will be -1 (no need to do anything here)
//store the new values for use in other methods and for this method in the next time step
if (success) {
laneIndex_ = chosenLane.index;
laneDtsb_ = chosenLane.dtsb;
cte_ = chosenLane.cte;
prevLaneIndex_ = chosenLane.index;
prevLaneApproach_ = chosenLane.index >= 0 ? map_.getLane(chosenLane.index).isApproach() : false;
log_.infof("INTR", "computeGeometry succeeded. lane index = %d, lane ID = %d, laneDtsb = %d cm, CTE = %d cm",
laneIndex_, laneId(), laneDtsb_, cte_);
}else {
laneIndex_ = -1;
laneDtsb_ = Integer.MAX_VALUE;
cte_ = Integer.MAX_VALUE;
prevLaneIndex_ = -1;
prevLaneApproach_ = false;
log_.warn("INTR", "computeGeometry - could not associate the vehicle to a lane.");
}
//compute the DTSB - need to do this here so we'll have it for comparison in the next call to this method
computeDtsb();
return success;
}
/**
* vehicle has a single associated lane : ID of the associated lane
* no single lane can be associated to the vehicle position : -1
*
* Note: this is the ID of the lane (as specified in the MAP message), and not necessarily its storage index
*/
public int laneId() {
if (laneIndex_ >= 0) {
return map_.getLane(laneIndex_).id();
}
return -1;
}
/**
* vehicle has a single associated lane : distance to the approach lane's stop bar in meters
* no single lane can be associated to the vehicle position : a very large number
*
* Note: distance to stop bar is positive if vehicle is associated with an approach lane and the intersection has not
* been reached. It will be negative if associated lane is egress, or if associated lane is approach but the vehicle
* has crossed the stop bar (is in the intersection box).
*/
public double dtsb() {
//convert the stored value to meters
return 0.01*(double)prevDtsb_;
}
/**
* vehicle has a single associated lane : cross-track error in cm
* no single lane can be associated to the vehicle position : a very large number
*
* Note: cte is always positive, represents the lateral distance from the vehicle to the nearest line segment of
* the associated lane. If the lane type is approach and dtsb < 0, then the line segment adjacent to the stop bar
* will be extended through the intersection to determine cte.
*/
public int cte() {
return cte_;
}
/**
* num lanes > 1 : greatest distance between any two lane stop bars, meters
* num lanes <= 1 : 0
*/
public double stopBoxWidth() {
return stopBoxWidth_;
}
//////////////////
// member elements
//////////////////
//A note about distance to stop bar (DTSB) as used in this class:
//Every lane has a stop bar, defined by its node 0. If the vehicle is associated with that lane, then it has a laneDtsb_, which is the
//distance from the vehicle along the segments of that lane to its stop bar. On approach to the intersection this is simply the DTSB
//for the whole scenario. It gets tricky when we pass that stop bar and proceed through the intersection (through the stop box) and
//on to the egress lane, however. Once we cross that approach lane stop bar the DTSB for the scenario needs to be negative, and continue
//to grow to more negative values as the vehicle proceeds farther downtrack from that approach stop bar. Eventually, the vehicle will
//associate with an egress lane. Its distance to that stop bar will at first be small (positive), then grow as we drive farther away from
//the stop box. Just using this new lane's DTSB clearly is not what we want for the scenario's DTSB, which needs to become larger negative.
//Therefore, at the point of transition between the approach lane and the egress lane (probably somewhere in the stop box), we store the
//lastApproachDtsb_ and the firstEgressDtsb_ to allow proper math in the computation of the scenario's overall DTSB from that point on.
/**
* vehicle has a single associated lane : stores distance to the approach lane's stop bar in cm
* no single lane can be associated to the vehicle position : stores a very large number
*/
private void computeDtsb() {
int result;
//if we are associated with a lane then
if (laneIndex_ >= 0) {
//if it's an approach lane then
if (prevLaneApproach_) {
//use its DTSB
result = laneDtsb_;
//else
}else {
//result = approach baseline - (reported DTSB - egress baseline)
result = lastApproachDtsb_ - (laneDtsb_ - firstEgressDtsb_);
}
//else
}else {
//set it to a very large (positive) number
result = Integer.MAX_VALUE;
}
//store the DTSB as the previous time step's value for the next time step's call to computeGeometry()
prevDtsb_ = result;
}
private boolean allInitialized_; //has the initialization for the whole intersection been completed?
private boolean respectTimeouts_; //will we be respecting the timeout limits?
private int laneIndex_; //storage vector index of the associated lane
private int laneDtsb_; //vehicle's distance to stop bar of the currently associated lane, cm
private int cte_; //vehicle's current cross-track error, cm
private int cteThreshold_; //threshold beyond which a CTE is considered bogus, cm
private int prevLaneIndex_; //index (not ID) of the lane successfully associated on prev time step; -1 if none
private boolean prevLaneApproach_; //was the associated lane in the previous time step an approach lane?
private int prevDtsb_; //route DTSB from the previous time step, cm
private int lastApproachDtsb_; //DTSB on the final time step that we were associated with the approach lane
private int firstEgressDtsb_; //DTSB on the first time step that we were associated with the egress lane
private MapMessage map_; //the latest MAP message that we've seen
private LaneGeometry[] laneGeo_; //array of geometries for each lane specified in the MAP message
private double stopBoxWidth_; //farthest distance between any two lanes' stop bars, m
//private static final int LARGE_MOVEMENT = 2000; //allows for testing sporadic locations without having to march the vehicle down the route
private static final int LARGE_MOVEMENT = (int)(60.0/Constants.MPS_TO_MPH * 100.0 * 0.2); //unrealistically large distance to travel in one time step, cm
//60 MPH, 100 cm/m, 0.2 sec time step
private static final long TIME_BUDGET = 20; //time budget allowed to spend on initializing the geometry in a single time step, ms
private static Logger log_ = (Logger)LoggerManager.getLogger(Intersection.class);
}
| 43.896842 | 158 | 0.685818 |
f87852b94925a392b6eb7cbdafb974f24ece72fd | 2,968 | package com.indianeagle.internal.util;
import com.indianeagle.internal.constants.StringConstants;
import com.indianeagle.internal.dto.Employee;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.html.simpleparser.HTMLWorker;
import com.itextpdf.text.pdf.PdfWriter;
import org.apache.commons.lang.StringUtils;
import org.thymeleaf.TemplateEngine;
import java.io.OutputStream;
import java.io.StringReader;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* The util class for paySlip generation
* User: anish
* Date: 3/26/14
* Time: 10:06 PM
*/
public class PaySlipPdfUtils {
/**
* The method to generate the pdf document from vm file
* @param templateEngine
* @param arrayOutputStream
* @param templateLocation
* @param dataObjects
*/
public static void generatePaySlipPdf(TemplateEngine templateEngine, OutputStream arrayOutputStream, String templateLocation, Object... dataObjects){
List<Element> elementList = null;
Document document = new Document(PageSize.A4.rotate(), 20, 20, 50, 50);
try {
/* PDF Write copy every Element added to this Document will be written to the outputStream. */
PdfWriter writer = PdfWriter.getInstance(document, arrayOutputStream);
Employee employee = null;
for (Object data : dataObjects) {
if(data instanceof Employee){
employee = (Employee)data;
}
}
if(null != employee){
writer.setEncryption(employee.getEmpId().getBytes(), employee.getEmpId().getBytes(), PdfWriter.AllowPrinting, PdfWriter.ENCRYPTION_AES_128);
writer.createXmpMetadata();
}
document.open();
Map<String, Object> dataMap = new HashMap<String, Object>();
dataMap.put(DateFormatter.class.getSimpleName(), DateFormatter.class);
dataMap.put(DateUtils.class.getSimpleName(), DateUtils.class);
dataMap.put(StringConstants.class.getSimpleName(), StringConstants.class);
dataMap.put(BigDecimal.class.getSimpleName(), BigDecimal.class);
dataMap.put("hrMailId", StringConstants.HR_MAIL_ID);
dataMap.put("companyName", StringConstants.COMPANY_NAME);
for (Object data : dataObjects) {
dataMap.put(StringUtils.uncapitalize(data.getClass().getSimpleName()), data);
}
String htmlFileContent = MailContentBuilder.build(templateEngine, templateLocation, dataMap);
elementList = HTMLWorker.parseToList(new StringReader(htmlFileContent), null);
for (Element element : elementList) {
document.add(element);
}
document.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
| 40.108108 | 156 | 0.665094 |
1e101f1cc502f03e601bf81afe3b5422bbde05aa | 238 | package com.github.football.dto.club.response;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
@Getter
@AllArgsConstructor
public class CheckClubNameResponse {
private Boolean isDuplicate;
}
| 19.833333 | 46 | 0.827731 |
5e17e6ce266f8ba2c185b9bed25bb3c1cccca182 | 316 | package com.example.pontoacesso.repository;
import com.example.pontoacesso.model.JornadaTrabalho;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface JornadaTrabalhoRepository extends JpaRepository<JornadaTrabalho, Long> {
}
| 31.6 | 89 | 0.860759 |
43688dfa5b155da566312f0dd22920cd3c82b629 | 14,497 | /*
* Copyright 2012 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.springframework.data.solr.repository.query;
import java.lang.reflect.Method;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.springframework.data.domain.Sort;
import org.springframework.data.mapping.context.MappingContext;
import org.springframework.data.repository.core.RepositoryMetadata;
import org.springframework.data.repository.query.parser.PartTree;
import org.springframework.data.solr.core.geo.Distance;
import org.springframework.data.solr.core.geo.GeoLocation;
import org.springframework.data.solr.core.mapping.SimpleSolrMappingContext;
import org.springframework.data.solr.core.mapping.SolrPersistentProperty;
import org.springframework.data.solr.core.query.Criteria;
import org.springframework.data.solr.core.query.Query;
import org.springframework.data.solr.repository.ProductBean;
/**
* @author Christoph Strobl
*/
@RunWith(MockitoJUnitRunner.class)
public class SolrQueryCreatorTest {
@Mock
private RepositoryMetadata metadataMock;
@Mock
private SolrEntityInformationCreator entityInformationCreatorMock;
private MappingContext<?, SolrPersistentProperty> mappingContext;
@Before
public void setUp() {
mappingContext = new SimpleSolrMappingContext();
}
@Test
public void testCreateFindBySingleCriteria() throws NoSuchMethodException, SecurityException {
Method method = SampleRepository.class.getMethod("findByPopularity", Integer.class);
PartTree partTree = new PartTree(method.getName(), method.getReturnType());
SolrQueryMethod queryMethod = new SolrQueryMethod(method, metadataMock, entityInformationCreatorMock);
SolrQueryCreator creator = new SolrQueryCreator(partTree, new SolrParametersParameterAccessor(queryMethod,
new Object[] { 100 }), mappingContext);
Query query = creator.createQuery();
Criteria criteria = query.getCriteria();
Assert.assertEquals("popularity:100", criteria.getQueryString());
}
@Test
public void testCreateFindByNotCriteria() throws NoSuchMethodException, SecurityException {
Method method = SampleRepository.class.getMethod("findByPopularityIsNot", Integer.class);
PartTree partTree = new PartTree(method.getName(), method.getReturnType());
SolrQueryMethod queryMethod = new SolrQueryMethod(method, metadataMock, entityInformationCreatorMock);
SolrQueryCreator creator = new SolrQueryCreator(partTree, new SolrParametersParameterAccessor(queryMethod,
new Object[] { 100 }), mappingContext);
Query query = creator.createQuery();
Criteria criteria = query.getCriteria();
Assert.assertEquals("popularity:-100", criteria.getQueryString());
}
@Test
public void testCreateFindByAndQuery() throws NoSuchMethodException, SecurityException {
Method method = SampleRepository.class.getMethod("findByPopularityAndPrice", Integer.class, Float.class);
PartTree partTree = new PartTree(method.getName(), method.getReturnType());
SolrQueryMethod queryMethod = new SolrQueryMethod(method, metadataMock, entityInformationCreatorMock);
SolrQueryCreator creator = new SolrQueryCreator(partTree, new SolrParametersParameterAccessor(queryMethod,
new Object[] { 100, 200f }), mappingContext);
Query query = creator.createQuery();
Criteria criteria = query.getCriteria();
Assert.assertEquals("popularity:100 AND price:200.0", criteria.getQueryString());
}
@Test
public void testCreateFindByOrQuery() throws NoSuchMethodException, SecurityException {
Method method = SampleRepository.class.getMethod("findByPopularityOrPrice", Integer.class, Float.class);
PartTree partTree = new PartTree(method.getName(), method.getReturnType());
SolrQueryMethod queryMethod = new SolrQueryMethod(method, metadataMock, entityInformationCreatorMock);
SolrQueryCreator creator = new SolrQueryCreator(partTree, new SolrParametersParameterAccessor(queryMethod,
new Object[] { 100, 200f }), mappingContext);
Query query = creator.createQuery();
Criteria criteria = query.getCriteria();
Assert.assertEquals("popularity:100 OR price:200.0", criteria.getQueryString());
}
@Test
public void testCreateQueryWithTrueClause() throws NoSuchMethodException, SecurityException {
Method method = SampleRepository.class.getMethod("findByAvailableTrue");
PartTree partTree = new PartTree(method.getName(), method.getReturnType());
SolrQueryMethod queryMethod = new SolrQueryMethod(method, metadataMock, entityInformationCreatorMock);
SolrQueryCreator creator = new SolrQueryCreator(partTree, new SolrParametersParameterAccessor(queryMethod,
new Object[] {}), mappingContext);
Query query = creator.createQuery();
Criteria criteria = query.getCriteria();
Assert.assertEquals("inStock:true", criteria.getQueryString());
}
@Test
public void testCreateQueryWithFalseClause() throws NoSuchMethodException, SecurityException {
Method method = SampleRepository.class.getMethod("findByAvailableFalse");
PartTree partTree = new PartTree(method.getName(), method.getReturnType());
SolrQueryMethod queryMethod = new SolrQueryMethod(method, metadataMock, entityInformationCreatorMock);
SolrQueryCreator creator = new SolrQueryCreator(partTree, new SolrParametersParameterAccessor(queryMethod,
new Object[] {}), mappingContext);
Query query = creator.createQuery();
Criteria criteria = query.getCriteria();
Assert.assertEquals("inStock:false", criteria.getQueryString());
}
@Test
public void testCreateQueryWithStartsWithClause() throws NoSuchMethodException, SecurityException {
Method method = SampleRepository.class.getMethod("findByTitleStartingWith", String.class);
PartTree partTree = new PartTree(method.getName(), method.getReturnType());
SolrQueryMethod queryMethod = new SolrQueryMethod(method, metadataMock, entityInformationCreatorMock);
SolrQueryCreator creator = new SolrQueryCreator(partTree, new SolrParametersParameterAccessor(queryMethod,
new Object[] { "j73x73r" }), mappingContext);
Query query = creator.createQuery();
Criteria criteria = query.getCriteria();
Assert.assertEquals("title:j73x73r*", criteria.getQueryString());
}
@Test
public void testCreateQueryWithEndingWithClause() throws NoSuchMethodException, SecurityException {
Method method = SampleRepository.class.getMethod("findByTitleEndingWith", String.class);
PartTree partTree = new PartTree(method.getName(), method.getReturnType());
SolrQueryMethod queryMethod = new SolrQueryMethod(method, metadataMock, entityInformationCreatorMock);
SolrQueryCreator creator = new SolrQueryCreator(partTree, new SolrParametersParameterAccessor(queryMethod,
new Object[] { "christoph" }), mappingContext);
Query query = creator.createQuery();
Criteria criteria = query.getCriteria();
Assert.assertEquals("title:*christoph", criteria.getQueryString());
}
@Test
public void testCreateQueryWithContainingClause() throws NoSuchMethodException, SecurityException {
Method method = SampleRepository.class.getMethod("findByTitleContaining", String.class);
PartTree partTree = new PartTree(method.getName(), method.getReturnType());
SolrQueryMethod queryMethod = new SolrQueryMethod(method, metadataMock, entityInformationCreatorMock);
SolrQueryCreator creator = new SolrQueryCreator(partTree, new SolrParametersParameterAccessor(queryMethod,
new Object[] { "solr" }), mappingContext);
Query query = creator.createQuery();
Criteria criteria = query.getCriteria();
Assert.assertEquals("title:*solr*", criteria.getQueryString());
}
@Test
public void testCreateQueryWithRegexClause() throws NoSuchMethodException, SecurityException {
Method method = SampleRepository.class.getMethod("findByTitleRegex", String.class);
PartTree partTree = new PartTree(method.getName(), method.getReturnType());
SolrQueryMethod queryMethod = new SolrQueryMethod(method, metadataMock, entityInformationCreatorMock);
SolrQueryCreator creator = new SolrQueryCreator(partTree, new SolrParametersParameterAccessor(queryMethod,
new Object[] { "(\\+ \\*)" }), mappingContext);
Query query = creator.createQuery();
Criteria criteria = query.getCriteria();
Assert.assertEquals("title:(\\+ \\*)", criteria.getQueryString());
}
@Test
public void testCreateQueryWithBetweenClause() throws NoSuchMethodException, SecurityException {
Method method = SampleRepository.class.getMethod("findByPopularityBetween", Integer.class, Integer.class);
PartTree partTree = new PartTree(method.getName(), method.getReturnType());
SolrQueryMethod queryMethod = new SolrQueryMethod(method, metadataMock, entityInformationCreatorMock);
SolrQueryCreator creator = new SolrQueryCreator(partTree, new SolrParametersParameterAccessor(queryMethod,
new Object[] { 100, 200 }), mappingContext);
Query query = creator.createQuery();
Criteria criteria = query.getCriteria();
Assert.assertEquals("popularity:[100 TO 200]", criteria.getQueryString());
}
@Test
public void testCreateQueryWithLessThanClause() throws NoSuchMethodException, SecurityException {
Method method = SampleRepository.class.getMethod("findByPriceLessThan", Float.class);
PartTree partTree = new PartTree(method.getName(), method.getReturnType());
SolrQueryMethod queryMethod = new SolrQueryMethod(method, metadataMock, entityInformationCreatorMock);
SolrQueryCreator creator = new SolrQueryCreator(partTree, new SolrParametersParameterAccessor(queryMethod,
new Object[] { 100f }), mappingContext);
Query query = creator.createQuery();
Criteria criteria = query.getCriteria();
Assert.assertEquals("price:[* TO 100.0]", criteria.getQueryString());
}
@Test
public void testCreateQueryWithGreaterThanClause() throws NoSuchMethodException, SecurityException {
Method method = SampleRepository.class.getMethod("findByPriceGreaterThan", Float.class);
PartTree partTree = new PartTree(method.getName(), method.getReturnType());
SolrQueryMethod queryMethod = new SolrQueryMethod(method, metadataMock, entityInformationCreatorMock);
SolrQueryCreator creator = new SolrQueryCreator(partTree, new SolrParametersParameterAccessor(queryMethod,
new Object[] { 10f }), mappingContext);
Query query = creator.createQuery();
Criteria criteria = query.getCriteria();
Assert.assertEquals("price:[10.0 TO *]", criteria.getQueryString());
}
@Test
public void testCreateQueryWithInClause() throws NoSuchMethodException, SecurityException {
Method method = SampleRepository.class.getMethod("findByPopularityIn", Integer[].class);
PartTree partTree = new PartTree(method.getName(), method.getReturnType());
SolrQueryMethod queryMethod = new SolrQueryMethod(method, metadataMock, entityInformationCreatorMock);
SolrQueryCreator creator = new SolrQueryCreator(partTree, new SolrParametersParameterAccessor(queryMethod,
new Object[] { new Object[] { 1, 2, 3 } }), mappingContext);
Query query = creator.createQuery();
Criteria criteria = query.getCriteria();
Assert.assertEquals("popularity:(1 2 3)", criteria.getQueryString());
}
@Test
public void testCreateQueryWithNear() throws NoSuchMethodException, SecurityException {
Method method = SampleRepository.class.getMethod("findByLocationNear", GeoLocation.class, Distance.class);
PartTree partTree = new PartTree(method.getName(), method.getReturnType());
SolrQueryMethod queryMethod = new SolrQueryMethod(method, metadataMock, entityInformationCreatorMock);
SolrQueryCreator creator = new SolrQueryCreator(partTree, new SolrParametersParameterAccessor(queryMethod,
new Object[] { new GeoLocation(48.303056, 14.290556), new Distance(5) }), mappingContext);
Query query = creator.createQuery();
Criteria criteria = query.getCriteria();
Assert.assertEquals("{!geofilt pt=48.303056,14.290556 sfield=location d=5.0}", criteria.getQueryString());
}
@Test
public void testCreateQueryWithSortDesc() throws NoSuchMethodException, SecurityException {
Method method = SampleRepository.class.getMethod("findByPopularityOrderByTitleDesc", Integer.class);
PartTree partTree = new PartTree(method.getName(), method.getReturnType());
SolrQueryMethod queryMethod = new SolrQueryMethod(method, metadataMock, entityInformationCreatorMock);
SolrQueryCreator creator = new SolrQueryCreator(partTree, new SolrParametersParameterAccessor(queryMethod,
new Object[] { 1 }), mappingContext);
Query query = creator.createQuery();
Assert.assertNotNull(query.getSort());
Assert.assertEquals(Sort.Direction.DESC, query.getSort().getOrderFor("title").getDirection());
}
private interface SampleRepository {
ProductBean findByPopularity(Integer popularity);
ProductBean findByPopularityIsNot(Integer popularity);
ProductBean findByPopularityAndPrice(Integer popularity, Float price);
ProductBean findByPopularityOrPrice(Integer popularity, Float price);
ProductBean findByAvailableTrue();
ProductBean findByAvailableFalse();
ProductBean findByTitleStartingWith(String prefix);
ProductBean findByTitleEndingWith(String postfix);
ProductBean findByTitleContaining(String fragment);
ProductBean findByTitleRegex(String expression);
ProductBean findByPopularityBetween(Integer lower, Integer upper);
ProductBean findByPriceLessThan(Float price);
ProductBean findByPriceGreaterThan(Float price);
ProductBean findByPopularityIn(Integer... values);
ProductBean findByPopularityOrderByTitleDesc(Integer popularity);
ProductBean findByLocationNear(GeoLocation location, Distance distance);
}
}
| 43.665663 | 109 | 0.775057 |
da76149adc8d10a37eb3f95c33a8501657d1b43c | 3,626 | package model;
public enum AminoAcid {
ALANINE("Alanine", "ALA", 'A', 71.03711 + 18.010565),
CYSTEINE("Cysteine", "CYS", 'C', 103.00919 + 18.010565),
ASPARTIC_ACID("Aspartic acid", "ASP", 'D', 115.02694 + 18.010565),
GLUTAMIC_ACID("Glutamic acid", "GLN", 'E', 129.04259 + 18.010565),
PHENYLALANINE("Phenylalanine", "PHE", 'F', 147.06841 + 18.010565),
GLYCINE("Glycine", "GLY", 'G', 57.02146 + 18.010565),
HISTIDINE("Histidine", "HIS", 'H', 137.05891 + 18.010565),
ISOLEUCINE("Isoleucine", "ILE", 'I', 113.08406 + 18.010565),
LYSINE("Lysine", "LYS", 'K', 128.09496 + 18.010565),
LEUCINE("Leucine", "LEU", 'L', 113.08406 + 18.010565),
METHIONINE("Methionine", "MET", 'M', 131.04049 + 18.010565),
ASPARAGINE("Asparagine", "ASN", 'N', 114.04293 + 18.010565),
PYRROLYSINE("Pyrrolysine", "PYL", 'O', 237.14773 + 18.010565),
PROLINE("Proline", "PRO", 'P', 97.05276 + 18.010565),
GLUTAMINE("Glutamine", "GLU", 'Q', 128.05858 + 18.010565),
ARGININE("Arginine", "ARG", 'R', 156.10111 + 18.010565),
SERINE("Serine", "SER", 'S', 87.03203 + 18.010565),
THREONINE("Threonine", "THR", 'T', 101.04768 + 18.010565),
SELENOCYTEINE("Selenocysteine", "SEC", 'U', 150.95364 + 18.010565),
VALINE("Valine", "VAL", 'V', 99.06841 + 18.010565),
TRYPTOPHAN("Tryptophan", "TRP", 'W', 186.07931 + 18.010565),
TYROSINE("Tyrosine", "TYR", 'Y', 163.06333 + 18.010565),
UNKNOWN("Unknown", "XXX", 'X', 0.0);
private String fullName;
private String threeLetter;
private char oneLetter;
private double mass;
private AminoAcid(String f, String t, char o,
double mass) {
this.fullName = f;
this.threeLetter = t;
this.oneLetter = o;
this.mass = mass;
}
public String getFullName() {
return this.fullName;
}
public String getThreeLetterCode() {
return this.threeLetter;
}
public char getOneLetterCode() {
return this.oneLetter;
}
public double getMass() {
return this.mass;
}
public static AminoAcid fromFullName(String s) {
s = s.toUpperCase().replaceAll("\\ ", "").replaceAll("_", "");
for (AminoAcid amac : AminoAcid.values()) {
String amac_compare = amac.fullName.toUpperCase();
amac_compare = amac_compare.replaceAll("\\ ", "");
amac_compare = amac_compare.replaceAll("_", "");
if (amac_compare.equals(s)) {
return amac;
}
}
return AminoAcid.UNKNOWN;
}
public static AminoAcid fromThreeLetter(String s) {
s = s.toUpperCase().replaceAll("\\ ", "").replaceAll("_", "");
for (AminoAcid amac : AminoAcid.values()) {
String amac_compare = amac.threeLetter.toUpperCase();
amac_compare = amac_compare.replaceAll("\\ ", "");
amac_compare = amac_compare.replaceAll("_", "");
if (amac_compare.equals(s)) {
return amac;
}
}
return AminoAcid.UNKNOWN;
}
public static AminoAcid fromOneLetter(char c) {
for (AminoAcid amac : AminoAcid.values()) {
if (amac.oneLetter == c) {
return amac;
}
}
return AminoAcid.UNKNOWN;
}
public static Double calculatePeptideMass(String sequence) {
Double mass = 18.010565;
for (char c : sequence.toCharArray()) {
mass += AminoAcid.fromOneLetter(c).mass - 18.010565;
}
return mass;
}
// public static AminoAcid getRandomAminoAcid() {
// AminoAcid aa_return = AminoAcid.UNKNOWN;
// Random rnd = new Random();
// int random_int = rnd.nextInt(10000);
// double p = random_int / 10000.0;
// double prev = 0.0;
// for (AminoAcid aa : AminoAcid.values()) {
// if (!aa.equals(AminoAcid.UNKNOWN)) {
// if ((p >= prev) && (p < aa.occ_cumulative)) {
// aa_return = aa;
// break;
// }
// prev = aa.occ_cumulative;
// }
// }
// return aa_return;
// }
} | 29.721311 | 68 | 0.641754 |
015aa642651c289076b3ba890c890eec97b52ec0 | 5,801 | /*
*************************************************************************
* The contents of this file are subject to the Openbravo Public License
* Version 1.1 (the "License"), being the Mozilla Public License
* Version 1.1 with a permitted attribution clause; you may not use this
* file except in compliance with the License. You may obtain a copy of
* the License at http://www.openbravo.com/legal/license.html
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
* The Original Code is Openbravo ERP.
* The Initial Developer of the Original Code is Openbravo SLU
* All portions are Copyright (C) 2010-2014 Openbravo SLU
* All Rights Reserved.
* Contributor(s): ______________________________________.
************************************************************************
*/
package org.openbravo.userinterface.selectors.test;
import static org.junit.Assert.assertEquals;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import org.apache.log4j.Logger;
import org.junit.Before;
import org.junit.Test;
import org.openbravo.client.application.OBBindings;
import org.openbravo.dal.core.OBContext;
import org.openbravo.test.base.OBBaseTest;
/**
* Tests the current API exposed to JavaScript expression through OBBindings class
*
* @author iperdomo
*/
public class ExpressionsTest extends OBBaseTest {
private ScriptEngineManager manager;
private ScriptEngine engine;
private Object result = null;
private Logger log = Logger.getLogger(ExpressionsTest.class);
private HashMap<String, String> expr = new HashMap<String, String>();
/**
* This before method is named setUpEt() to avoid overwriting the super
* setUp method that is invoke automatically before this one.
*/
@Before
public void setUpEt() throws Exception {
// Everything runs as System Admin user
setSystemAdministratorContext();
manager = new ScriptEngineManager();
engine = manager.getEngineByName("js");
engine.put("OB", new OBBindings(OBContext.getOBContext()));
// Initialize expressions
expr.put("Get current user's name", "OB.getContext().getUser().name");
expr.put("Get current language", "OB.getContext().getLanguage().language");
expr.put("Format today's date", "OB.formatDate(new Date(), 'yyyy-MM-dd')");
expr.put("Get current client id", "OB.getContext().getCurrentClient().id");
expr.put("Parse date with fixed format", "OB.parseDate('1979-04-24','yyyy-MM-dd')");
expr.put("Format a parsed date",
"OB.formatDate(OB.parseDate('1979-04-24', 'yyyy-MM-dd'), 'MM-dd-yyyy')");
expr.put("Filter by vendor/customer", "if(OB.isSalesTransaction()===null){'';}"
+ "else if(OB.isSalesTransaction()==true){'e.customer = true';}"
+ "else{'e.vendor = true';}");
expr.put("Complex expression from Java",
"OB.getFilterExpression('org.openbravo.userinterface.selectors.test.SampleFilterExpression');");
}
@Test
public void testUserName() {
final String s = expr.get("Get current user's name");
try {
result = engine.eval(s);
} catch (Exception e) {
log.error("Error evaluating expression: " + s, e);
}
assertEquals(result.toString(), OBContext.getOBContext().getUser().getName());
}
@Test
public void testLanguage() {
final String s = expr.get("Get current language");
try {
result = engine.eval(s);
} catch (Exception e) {
log.error("Error evaluating expression: " + s, e);
}
assertEquals(result.toString(), OBContext.getOBContext().getLanguage().getLanguage());
}
@Test
public void testFormatDate() {
final String s = expr.get("Format today's date");
final SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
try {
result = engine.eval(s);
} catch (Exception e) {
log.error("Error evaluating expression: " + s, e);
}
assertEquals(df.format(Calendar.getInstance().getTime()), result);
}
@Test
public void testCurrentClientId() {
final String s = expr.get("Get current client id");
try {
result = engine.eval(s);
} catch (Exception e) {
log.error("Error evaluating expression: " + s, e);
}
assertEquals(OBContext.getOBContext().getCurrentClient().getId(), result);
}
@Test
public void testParseDate() {
final String s = expr.get("Parse date with fixed format");
final SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
try {
result = engine.eval(s);
assertEquals(df.parse("1979-04-24"), result);
} catch (Exception e) {
log.error("Error evaluating expression: " + s, e);
}
}
@Test
public void testFormatParsedDate() {
final String s = expr.get("Format a parsed date");
try {
result = engine.eval(s);
assertEquals("04-24-1979", result);
} catch (Exception e) {
log.error("Error evaluating expression: " + s, e);
}
}
@Test
public void testCustomerVendorFilter() {
final String s = expr.get("Filter by vendor/customer");
try {
result = engine.eval(s);
} catch (Exception e) {
log.error("Error evaluating expression: " + s, e);
}
assertEquals("", result);
}
@Test
public void testGetFilterExpression() {
final String s = expr.get("Complex expression from Java");
try {
result = engine.eval(s);
} catch (Exception e) {
log.error("Error evaluating expression: " + s, e);
}
assertEquals("This is a complex expression", result);
}
}
| 32.774011 | 104 | 0.658852 |
13721feb6aed690a4d556b89624bdafdd4104b2b | 1,177 | /*
* This file is part of java2c. It is subject to the licence terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/raphaelcohn/java2c/master/COPYRIGHT. No part of compilerUser, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file.
* Copyright © 2014-2015 The developers of java2c. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/raphaelcohn/java2c/master/COPYRIGHT.
*/
package com.java2c.model.other;
import org.jetbrains.annotations.NotNull;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Target({CONSTRUCTOR, METHOD, FIELD})
@Retention(RUNTIME)
public @interface CCodeTemplate
{
@NotNull String[] value();
@NotNull String[] includes() default {};
@NotNull String Scalar = "(@value@)";
}
| 42.035714 | 381 | 0.794393 |
d13d42f42c9e4cff688514f264fb29aaf58e3b98 | 100 | package com.base.basepedo.callback;
public interface StepCallBack {
void Step(int stepNum);
}
| 14.285714 | 35 | 0.75 |
f89a89b58a6385cf778f1329311651dddad1278b | 9,070 | package uk.gov.ida.notification;
import engineering.reliability.gds.metrics.bundle.PrometheusBundle;
import io.dropwizard.Application;
import io.dropwizard.configuration.EnvironmentVariableSubstitutor;
import io.dropwizard.configuration.SubstitutingSourceProvider;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import io.dropwizard.views.ViewBundle;
import net.shibboleth.utilities.java.support.security.SecureRandomIdentifierGenerationStrategy;
import org.eclipse.jetty.server.session.SessionHandler;
import org.glassfish.hk2.utilities.binding.AbstractBinder;
import uk.gov.ida.dropwizard.logstash.LogstashBundle;
import uk.gov.ida.notification.configuration.RedisServiceConfiguration;
import uk.gov.ida.notification.exceptions.mappers.ErrorPageExceptionMapper;
import uk.gov.ida.notification.exceptions.mappers.ErrorPageRedirectResponseValidationExceptionMapper;
import uk.gov.ida.notification.exceptions.mappers.ExceptionToSamlErrorResponseMapper;
import uk.gov.ida.notification.exceptions.mappers.GenericExceptionMapper;
import uk.gov.ida.notification.exceptions.mappers.MissingMetadataExceptionMapper;
import uk.gov.ida.notification.healthcheck.ProxyNodeHealthCheck;
import uk.gov.ida.notification.proxy.EidasSamlParserProxy;
import uk.gov.ida.notification.proxy.TranslatorProxy;
import uk.gov.ida.notification.resources.AssetsResource;
import uk.gov.ida.notification.resources.EidasAuthnRequestResource;
import uk.gov.ida.notification.resources.HubResponseResource;
import uk.gov.ida.notification.session.storage.InMemoryStorage;
import uk.gov.ida.notification.session.storage.RedisStorage;
import uk.gov.ida.notification.session.storage.SessionStore;
import uk.gov.ida.notification.shared.Urls;
import uk.gov.ida.notification.shared.istio.IstioHeaderMapperFilter;
import uk.gov.ida.notification.shared.istio.IstioHeaderStorage;
import uk.gov.ida.notification.shared.logging.ProxyNodeLoggingFilter;
import uk.gov.ida.notification.shared.metadata.MetadataPublishingBundle;
import uk.gov.ida.notification.shared.proxy.VerifyServiceProviderProxy;
import javax.servlet.DispatcherType;
import java.net.URI;
import java.util.EnumSet;
public class GatewayApplication extends Application<GatewayConfiguration> {
@SuppressWarnings("WeakerAccess") // Needed for DropwizardAppRules
public GatewayApplication() {
}
public static void main(final String[] args) throws Exception {
if (args == null || args.length == 0) {
String configFile = System.getenv("CONFIG_FILE");
if (configFile == null) {
throw new RuntimeException("CONFIG_FILE environment variable should be set with path to configuration file");
}
new GatewayApplication().run("server", configFile);
} else {
new GatewayApplication().run(args);
}
}
@Override
public String getName() {
return "EidasProxyNode";
}
@Override
public void initialize(final Bootstrap<GatewayConfiguration> bootstrap) {
// Needed to correctly interpolate environment variables in config file
bootstrap.setConfigurationSourceProvider(
new SubstitutingSourceProvider(bootstrap.getConfigurationSourceProvider(),
new EnvironmentVariableSubstitutor(false)
)
);
bootstrap.addBundle(new ViewBundle<>());
bootstrap.addBundle(new LogstashBundle());
bootstrap.addBundle(new MetadataPublishingBundle<>(GatewayConfiguration::getMetadataPublishingConfiguration));
bootstrap.addBundle(new PrometheusBundle());
}
@Override
public void run(final GatewayConfiguration configuration, final Environment environment) {
final ProxyNodeHealthCheck proxyNodeHealthCheck = new ProxyNodeHealthCheck("gateway");
environment.healthChecks().register(proxyNodeHealthCheck.getName(), proxyNodeHealthCheck);
final RedisServiceConfiguration redisService = configuration.getRedisService();
final SessionStore sessionStorage = redisService.isLocal() ?
new InMemoryStorage() : new RedisStorage(redisService);
final SamlFormViewBuilder samlFormViewBuilder = new SamlFormViewBuilder();
final TranslatorProxy translatorProxy = configuration
.getTranslatorServiceConfiguration()
.buildTranslatorProxy(environment);
registerProviders(environment);
registerResources(configuration, environment, samlFormViewBuilder, translatorProxy, sessionStorage);
registerExceptionMappers(environment, samlFormViewBuilder, translatorProxy, sessionStorage, configuration.getErrorPageRedirectUrl());
registerInjections(environment);
}
private void registerProviders(Environment environment) {
SessionHandler sessionHandler = new SessionHandler();
sessionHandler.setSessionCookie("gateway-session");
environment.servlets().setSessionHandler(sessionHandler);
setRequestServletFilter(environment);
setResponseServletFilter(environment);
environment.jersey().register(IstioHeaderMapperFilter.class);
environment.jersey().register(ProxyNodeLoggingFilter.class);
}
private void setRequestServletFilter(Environment environment) {
JourneyIdGeneratingServletFilter requestFilter = new JourneyIdGeneratingServletFilter(new SecureRandomIdentifierGenerationStrategy());
environment.servlets()
.addFilter(requestFilter.getClass().getSimpleName(), requestFilter)
.addMappingForUrlPatterns(
EnumSet.of(DispatcherType.REQUEST),
true,
Urls.GatewayUrls.GATEWAY_ROOT + Urls.GatewayUrls.GATEWAY_EIDAS_AUTHN_REQUEST_POST_PATH,
Urls.GatewayUrls.GATEWAY_ROOT + Urls.GatewayUrls.GATEWAY_EIDAS_AUTHN_REQUEST_REDIRECT_PATH);
}
private void setResponseServletFilter(Environment environment) {
InvalidateSessionServletFilter invalidateSessionServletFilter = new InvalidateSessionServletFilter();
environment.servlets()
.addFilter(invalidateSessionServletFilter.getClass().getSimpleName(), invalidateSessionServletFilter)
.addMappingForUrlPatterns(
EnumSet.of(DispatcherType.REQUEST),
true,
Urls.GatewayUrls.GATEWAY_HUB_RESPONSE_RESOURCE);
JourneyIdHubResponseServletFilter responseFilter = new JourneyIdHubResponseServletFilter();
environment.servlets()
.addFilter(responseFilter.getClass().getSimpleName(), responseFilter)
.addMappingForUrlPatterns(
EnumSet.of(DispatcherType.REQUEST),
true,
Urls.GatewayUrls.GATEWAY_HUB_RESPONSE_RESOURCE);
}
private void registerExceptionMappers(
Environment environment,
SamlFormViewBuilder samlFormViewBuilder,
TranslatorProxy translatorProxy,
SessionStore sessionStore,
URI errorPageRedirectUrl) {
environment.jersey().register(new MissingMetadataExceptionMapper());
environment.jersey().register(new ExceptionToSamlErrorResponseMapper(samlFormViewBuilder, translatorProxy, sessionStore));
environment.jersey().register(new ErrorPageExceptionMapper(errorPageRedirectUrl));
environment.jersey().register(new ErrorPageRedirectResponseValidationExceptionMapper(errorPageRedirectUrl));
environment.jersey().register(new GenericExceptionMapper(errorPageRedirectUrl));
}
private void registerResources(
GatewayConfiguration configuration,
Environment environment,
SamlFormViewBuilder samlFormViewBuilder,
TranslatorProxy translatorProxy,
SessionStore sessionStorage) {
EidasSamlParserProxy espProxy = configuration
.getEidasSamlParserServiceConfiguration()
.buildEidasSamlParserService(environment);
VerifyServiceProviderProxy vspProxy = configuration
.getVerifyServiceProviderConfiguration()
.buildVerifyServiceProviderProxy(environment);
environment.lifecycle().manage(sessionStorage);
environment.jersey().register(AssetsResource.class);
environment.jersey().register(new EidasAuthnRequestResource(
espProxy,
vspProxy,
samlFormViewBuilder,
sessionStorage));
environment.jersey().register(new HubResponseResource(
samlFormViewBuilder,
translatorProxy,
sessionStorage
));
}
private void registerInjections(Environment environment) {
environment.jersey().register(new AbstractBinder() {
@Override
protected void configure() {
bindAsContract(IstioHeaderStorage.class);
}
});
}
}
| 46.040609 | 142 | 0.727012 |
3a4730683c299fc5c0fcb53671478da2dc74e6f1 | 1,437 | package com.xceptance.common.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
/**
* Utility class that provides convenient methods regarding ordinary java objects.
*
* @author Jörg Werner (Xceptance Software Technologies GmbH)
*/
public final class ObjectUtils
{
/**
* Default constructor. Declared private to prevent external instantiation.
*/
private ObjectUtils()
{
}
/**
* Creates a deep copy of the passed object. For this method to work, the object to be cloned and all contained
* objects must be serializable.
*
* @param o
* the object to clone
* @return the clone
* @throws Exception
* if an error occurred, especially if the object is not serializable
*/
public static Object cloneObject(final Object o) throws Exception
{
// stream the object to a byte buffer
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final ObjectOutputStream out = new ObjectOutputStream(baos);
out.writeObject(o);
out.flush();
// reconstruct the object from the byte buffer
final ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
final ObjectInputStream in = new ObjectInputStream(bais);
return in.readObject();
}
}
| 29.9375 | 115 | 0.680585 |
a36876beaad6db4afef1a916ff24e14e29d4a36b | 3,605 | package AST;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.io.File;
import java.util.*;
import beaver.*;
import java.util.ArrayList;
import java.util.zip.*;
import java.io.*;
import java.util.Stack;
import java.util.regex.Pattern;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.Transformer;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Element;
import org.w3c.dom.Document;
import java.util.HashMap;
import java.util.Map.Entry;
import javax.xml.transform.TransformerException;
import javax.xml.parsers.ParserConfigurationException;
import java.util.Collection;
/**
* @ast node
* @declaredat java.ast:110
*/
public abstract class AssignMultiplicativeExpr extends AssignExpr implements Cloneable {
/**
* @apilvl low-level
*/
public void flushCache() {
super.flushCache();
}
/**
* @apilvl internal
*/
public void flushCollectionCache() {
super.flushCollectionCache();
}
/**
* @apilvl internal
*/
@SuppressWarnings({"unchecked", "cast"})
public AssignMultiplicativeExpr clone() throws CloneNotSupportedException {
AssignMultiplicativeExpr node = (AssignMultiplicativeExpr)super.clone();
node.in$Circle(false);
node.is$Final(false);
return node;
}
/**
* @ast method
* @aspect TypeCheck
* @declaredat D:\zhh\JastAddJ\Java1.4Frontend\TypeCheck.jrag:64
*/
public void typeCheck() {
if(sourceType().isBoolean()||getDest().type().isBoolean())
error("Multiplicative operators do not operate on boolean types");
super.typeCheck();
}
/**
* @ast method
* @declaredat java.ast:1
*/
public AssignMultiplicativeExpr() {
super();
}
/**
* @ast method
* @declaredat java.ast:7
*/
public AssignMultiplicativeExpr(Expr p0, Expr p1) {
setChild(p0, 0);
setChild(p1, 1);
}
/**
* @apilvl low-level
* @ast method
* @declaredat java.ast:14
*/
protected int numChildren() {
return 2;
}
/**
* @apilvl internal
* @ast method
* @declaredat java.ast:20
*/
public boolean mayHaveRewrite() {
return false;
}
/**
* Setter for Dest
* @apilvl high-level
* @ast method
* @declaredat java.ast:5
*/
public void setDest(Expr node) {
setChild(node, 0);
}
/**
* Getter for Dest
* @apilvl high-level
* @ast method
* @declaredat java.ast:12
*/
public Expr getDest() {
return (Expr)getChild(0);
}
/**
* @apilvl low-level
* @ast method
* @declaredat java.ast:18
*/
public Expr getDestNoTransform() {
return (Expr)getChildNoTransform(0);
}
/**
* Setter for Source
* @apilvl high-level
* @ast method
* @declaredat java.ast:5
*/
public void setSource(Expr node) {
setChild(node, 1);
}
/**
* Getter for Source
* @apilvl high-level
* @ast method
* @declaredat java.ast:12
*/
public Expr getSource() {
return (Expr)getChild(1);
}
/**
* @apilvl low-level
* @ast method
* @declaredat java.ast:18
*/
public Expr getSourceNoTransform() {
return (Expr)getChildNoTransform(1);
}
/**
* @apilvl internal
*/
public ASTNode rewriteTo() {
return super.rewriteTo();
}
}
| 22.253086 | 89 | 0.665187 |
a75e3793bac0cdba8778cbee4e4e5c2430404f64 | 56,329 | package pk.ajneb97.managers;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.ClickType;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemFlag;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.LeatherArmorMeta;
import net.md_5.bungee.api.ChatColor;
import pk.ajneb97.KitEditando;
import pk.ajneb97.PlayerKits;
import pk.ajneb97.otros.Utilidades;
public class InventarioEditar implements Listener{
private PlayerKits plugin;
public InventarioEditar(PlayerKits plugin) {
this.plugin = plugin;
}
@SuppressWarnings("deprecation")
public static void crearInventario(Player jugador,String kit,PlayerKits plugin) {
FileConfiguration kits = plugin.getKits();
Inventory inv = Bukkit.createInventory(null, 45, ChatColor.translateAlternateColorCodes('&', "&9Editing Kit"));
ItemStack item = new ItemStack(Material.DROPPER);
ItemMeta meta = item.getItemMeta();
meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&eSet &6&lSlot"));
List<String> lore = new ArrayList<String>();
lore.add(ChatColor.translateAlternateColorCodes('&', "&7Click to define the position of the display"));
lore.add(ChatColor.translateAlternateColorCodes('&', "&7item of this kit in the Inventory."));
lore.add(ChatColor.translateAlternateColorCodes('&', ""));
String slot = "none";
if(kits.contains("Kits."+kit+".slot")) {
slot = kits.getString("Kits."+kit+".slot");
}
lore.add(ChatColor.translateAlternateColorCodes('&', "&7Current Slot: &a"+slot));
meta.setLore(lore);
item.setItemMeta(meta);
inv.setItem(10, item);
item = new ItemStack(Material.GHAST_TEAR);
meta = item.getItemMeta();
meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&eSet &6&lCooldown"));
lore = new ArrayList<String>();
lore.add(ChatColor.translateAlternateColorCodes('&', "&7Click to define the cooldown of"));
lore.add(ChatColor.translateAlternateColorCodes('&', "&7the kit."));
lore.add(ChatColor.translateAlternateColorCodes('&', ""));
int cooldown = 0;
if(kits.contains("Kits."+kit+".cooldown")) {
cooldown = Integer.valueOf(kits.getString("Kits."+kit+".cooldown"));
}
lore.add(ChatColor.translateAlternateColorCodes('&', "&7Current Cooldown: &a"+cooldown+"(s)"));
meta.setLore(lore);
item.setItemMeta(meta);
inv.setItem(11, item);
item = new ItemStack(Material.REDSTONE_BLOCK);
meta = item.getItemMeta();
meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&eSet &6&lPermission"));
lore = new ArrayList<String>();
lore.add(ChatColor.translateAlternateColorCodes('&', "&7Click to define the permission of"));
lore.add(ChatColor.translateAlternateColorCodes('&', "&7the kit."));
lore.add(ChatColor.translateAlternateColorCodes('&', ""));
String permission = "none";
if(kits.contains("Kits."+kit+".permission")) {
permission = kits.getString("Kits."+kit+".permission");
}
lore.add(ChatColor.translateAlternateColorCodes('&', "&7Current Permission: &a"+permission));
meta.setLore(lore);
item.setItemMeta(meta);
inv.setItem(12, item);
String firstJoin = "false";
if(kits.contains("Kits."+kit+".first_join")) {
firstJoin = kits.getString("Kits."+kit+".first_join");
}
if(firstJoin.equals("true")) {
if(!Utilidades.isLegacy()) {
item = new ItemStack(Material.LIME_DYE);
}else {
item = new ItemStack(Material.valueOf("INK_SACK"),1,(short) 10);
}
}else {
if(!Utilidades.isLegacy()) {
item = new ItemStack(Material.GRAY_DYE);
}else {
item = new ItemStack(Material.valueOf("INK_SACK"),1,(short) 8);
}
}
meta = item.getItemMeta();
meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&eSet &6&lFirst Join"));
lore = new ArrayList<String>();
lore.add(ChatColor.translateAlternateColorCodes('&', "&7Click to define if players should"));
lore.add(ChatColor.translateAlternateColorCodes('&', "&7receive this kit when they join for"));
lore.add(ChatColor.translateAlternateColorCodes('&', "&7the first time."));
lore.add(ChatColor.translateAlternateColorCodes('&', ""));
lore.add(ChatColor.translateAlternateColorCodes('&', "&7Current Status: &a"+firstJoin));
meta.setLore(lore);
item.setItemMeta(meta);
inv.setItem(19, item);
String oneTime = "false";
if(kits.contains("Kits."+kit+".one_time")) {
oneTime = kits.getString("Kits."+kit+".one_time");
}
if(oneTime.equals("true")) {
if(!Utilidades.isLegacy()) {
item = new ItemStack(Material.LIME_DYE);
}else {
item = new ItemStack(Material.valueOf("INK_SACK"),1,(short) 10);
}
}else {
if(!Utilidades.isLegacy()) {
item = new ItemStack(Material.GRAY_DYE);
}else {
item = new ItemStack(Material.valueOf("INK_SACK"),1,(short) 8);
}
}
meta = item.getItemMeta();
meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&eSet &6&lOne Time"));
lore = new ArrayList<String>();
lore.add(ChatColor.translateAlternateColorCodes('&', "&7Click to define if players should"));
lore.add(ChatColor.translateAlternateColorCodes('&', "&7claim this kit just one time."));
lore.add(ChatColor.translateAlternateColorCodes('&', ""));
lore.add(ChatColor.translateAlternateColorCodes('&', "&7Current Status: &a"+oneTime));
meta.setLore(lore);
item.setItemMeta(meta);
inv.setItem(20, item);
String autoArmor = "false";
if(kits.contains("Kits."+kit+".auto_armor")) {
autoArmor = kits.getString("Kits."+kit+".auto_armor");
}
if(autoArmor.equals("true")) {
if(!Utilidades.isLegacy()) {
item = new ItemStack(Material.LIME_DYE);
}else {
item = new ItemStack(Material.valueOf("INK_SACK"),1,(short) 10);
}
}else {
if(!Utilidades.isLegacy()) {
item = new ItemStack(Material.GRAY_DYE);
}else {
item = new ItemStack(Material.valueOf("INK_SACK"),1,(short) 8);
}
}
meta = item.getItemMeta();
meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&eSet &6&lAuto Armor"));
lore = new ArrayList<String>();
lore.add(ChatColor.translateAlternateColorCodes('&', "&7Click to set if kit armor should"));
lore.add(ChatColor.translateAlternateColorCodes('&', "&7be equipped automatically when"));
lore.add(ChatColor.translateAlternateColorCodes('&', "&7claiming the kit."));
lore.add(ChatColor.translateAlternateColorCodes('&', ""));
lore.add(ChatColor.translateAlternateColorCodes('&', "&7Current Status: &a"+autoArmor));
meta.setLore(lore);
item.setItemMeta(meta);
inv.setItem(28, item);
item = new ItemStack(Material.BEACON);
meta = item.getItemMeta();
meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&eSet &6&lNo Buy Item"));
lore = new ArrayList<String>();
lore.add(ChatColor.translateAlternateColorCodes('&', "&7Click to edit the kit display item when"));
lore.add(ChatColor.translateAlternateColorCodes('&', "&7player has not buyed it."));
meta.setLore(lore);
item.setItemMeta(meta);
inv.setItem(41, item);
item = new ItemStack(Material.BARRIER);
meta = item.getItemMeta();
meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&eSet &6&lNo Permission Item"));
lore = new ArrayList<String>();
lore.add(ChatColor.translateAlternateColorCodes('&', "&7Click to edit the kit display item when"));
lore.add(ChatColor.translateAlternateColorCodes('&', "&7player doesn't have permissions to claim"));
lore.add(ChatColor.translateAlternateColorCodes('&', "&7the kit."));
meta.setLore(lore);
item.setItemMeta(meta);
inv.setItem(40, item);
item = new ItemStack(Material.IRON_SWORD);
meta = item.getItemMeta();
meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&eSet &6&lDisplay Item"));
lore = new ArrayList<String>();
lore.add(ChatColor.translateAlternateColorCodes('&', "&7Click to edit the kit display item."));
meta.setLore(lore);
meta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES);
item.setItemMeta(meta);
inv.setItem(39, item);
List<String> items = new ArrayList<String>();
FileConfiguration config = plugin.getConfig();
if(kits.contains("Kits."+kit+".Items")) {
for(String n : kits.getConfigurationSection("Kits."+kit+".Items").getKeys(false)) {
String path = "Kits."+kit+".Items."+n;
ItemStack itemN = KitManager.getItem(kits, path, config, jugador);
items.add("x"+itemN.getAmount()+" "+itemN.getType());
}
}
item = new ItemStack(Material.DIAMOND);
meta = item.getItemMeta();
meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&eSet &6&lKit Items"));
lore = new ArrayList<String>();
lore.add(ChatColor.translateAlternateColorCodes('&', "&7Click to edit the kit items."));
lore.add(ChatColor.translateAlternateColorCodes('&', ""));
lore.add(ChatColor.translateAlternateColorCodes('&', "&7Current Items:"));
for(int i=0;i<items.size();i++) {
lore.add(ChatColor.translateAlternateColorCodes('&', "&8- &a")+items.get(i));
}
meta.setLore(lore);
item.setItemMeta(meta);
inv.setItem(14, item);
List<String> comandos = new ArrayList<String>();
if(kits.contains("Kits."+kit+".Commands")) {
comandos = kits.getStringList("Kits."+kit+".Commands");
}
item = new ItemStack(Material.IRON_INGOT);
meta = item.getItemMeta();
meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&eSet &6&lKit Commands"));
lore = new ArrayList<String>();
lore.add(ChatColor.translateAlternateColorCodes('&', "&7Click to edit which commands should"));
lore.add(ChatColor.translateAlternateColorCodes('&', "&7the kit execute to the player when"));
lore.add(ChatColor.translateAlternateColorCodes('&', "&7receiving it."));
lore.add(ChatColor.translateAlternateColorCodes('&', ""));
lore.add(ChatColor.translateAlternateColorCodes('&', "&7Current Commands:"));
if(comandos.isEmpty()) {
lore.add(ChatColor.translateAlternateColorCodes('&', "&cNONE"));
}else {
for(int i=0;i<comandos.size();i++) {
lore.add(ChatColor.translateAlternateColorCodes('&', "&8- &a")+comandos.get(i));
}
}
meta.setLore(lore);
item.setItemMeta(meta);
inv.setItem(15, item);
item = new ItemStack(Material.PAPER);
meta = item.getItemMeta();
meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&eSet &6&lPrice"));
lore = new ArrayList<String>();
lore.add(ChatColor.translateAlternateColorCodes('&', "&7Click to define the price of"));
lore.add(ChatColor.translateAlternateColorCodes('&', "&7the kit."));
lore.add(ChatColor.translateAlternateColorCodes('&', ""));
String price = "none";
if(kits.contains("Kits."+kit+".price")) {
price = kits.getString("Kits."+kit+".price");
}
lore.add(ChatColor.translateAlternateColorCodes('&', "&7Current Price: &a"+price));
meta.setLore(lore);
item.setItemMeta(meta);
inv.setItem(23, item);
item = new ItemStack(Material.ENDER_PEARL);
meta = item.getItemMeta();
meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&eSet &6&lPage"));
lore = new ArrayList<String>();
lore.add(ChatColor.translateAlternateColorCodes('&', "&7Click to define the page of the of"));
lore.add(ChatColor.translateAlternateColorCodes('&', "&7this kit in the Inventory."));
lore.add(ChatColor.translateAlternateColorCodes('&', ""));
String page = "1";
if(kits.contains("Kits."+kit+".page")) {
page = kits.getString("Kits."+kit+".page");
}
lore.add(ChatColor.translateAlternateColorCodes('&', "&7Current Page: &a"+page));
meta.setLore(lore);
item.setItemMeta(meta);
inv.setItem(16, item);
String oneTimeBuy = "false";
if(kits.contains("Kits."+kit+".one_time_buy")) {
oneTimeBuy = kits.getString("Kits."+kit+".one_time_buy");
}
if(oneTimeBuy.equals("true")) {
if(!Utilidades.isLegacy()) {
item = new ItemStack(Material.LIME_DYE);
}else {
item = new ItemStack(Material.valueOf("INK_SACK"),1,(short) 10);
}
}else {
if(!Utilidades.isLegacy()) {
item = new ItemStack(Material.GRAY_DYE);
}else {
item = new ItemStack(Material.valueOf("INK_SACK"),1,(short) 8);
}
}
meta = item.getItemMeta();
meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&eSet &6&lOne Time Buy"));
lore = new ArrayList<String>();
lore.add(ChatColor.translateAlternateColorCodes('&', "&7Click to set if the kit should be"));
lore.add(ChatColor.translateAlternateColorCodes('&', "&7buyed just one time. This option"));
lore.add(ChatColor.translateAlternateColorCodes('&', "&7requires a price for the kit."));
lore.add(ChatColor.translateAlternateColorCodes('&', ""));
lore.add(ChatColor.translateAlternateColorCodes('&', "&7Current Status: &a"+oneTimeBuy));
meta.setLore(lore);
item.setItemMeta(meta);
inv.setItem(21, item);
jugador.openInventory(inv);
plugin.setKitEditando(new KitEditando(jugador,kit,""));
}
@SuppressWarnings("deprecation")
public static void crearInventarioItems(Player jugador,String kit,PlayerKits plugin) {
FileConfiguration kits = plugin.getKits();
// FileConfiguration config = plugin.getConfig();
// int slots = Integer.valueOf(config.getString("Config.previewInventorySize"));
Inventory inv = Bukkit.createInventory(null, 54, ChatColor.translateAlternateColorCodes('&', "&9Editing Kit Items"));
ItemStack item = new ItemStack(Material.ARROW);
ItemMeta meta = item.getItemMeta();
meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&7Go Back"));
item.setItemMeta(meta);
inv.setItem(45, item);
item = new ItemStack(Material.EMERALD);
meta = item.getItemMeta();
meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&aSave Items"));
List<String> lore = new ArrayList<String>();
lore.add(ChatColor.translateAlternateColorCodes('&', "&7If you made any changes in this inventory"));
lore.add(ChatColor.translateAlternateColorCodes('&', "&7it is very important to click this item"));
lore.add(ChatColor.translateAlternateColorCodes('&', "&7before closing it or going back."));
meta.setLore(lore);
item.setItemMeta(meta);
inv.setItem(53, item);
if(!Utilidades.isLegacy()) {
item = new ItemStack(Material.GRAY_STAINED_GLASS_PANE);
}else {
item = new ItemStack(Material.valueOf("STAINED_GLASS_PANE"),1,(short) 8);
}
meta = item.getItemMeta();
meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', " "));
item.setItemMeta(meta);
for(int i=46;i<=52;i++) {
inv.setItem(i, item);
}
if(!Bukkit.getVersion().contains("1.8")) {
item = new ItemStack(Material.BOOK);
meta = item.getItemMeta();
meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&aInformation"));
lore = new ArrayList<String>();
lore.add(ChatColor.translateAlternateColorCodes('&', "&7If you want to set an item on the offhand"));
lore.add(ChatColor.translateAlternateColorCodes('&', "&7just right click it."));
meta.setLore(lore);
item.setItemMeta(meta);
inv.setItem(49, item);
}
int slot = 0;
if(kits.contains("Kits."+kit+".Items")) {
for(String n : kits.getConfigurationSection("Kits."+kit+".Items").getKeys(false)) {
String path = "Kits."+kit+".Items."+n;
item = KitManager.getItem(kits, path, plugin.getConfig(), jugador);
List<String> loreOffhand = new ArrayList<String>();
ItemMeta metaNuevo = item.getItemMeta();
if(!Bukkit.getVersion().contains("1.8") && kits.contains(path+".offhand") && kits.getString(path+".offhand").equals("true")) {
loreOffhand.add(ChatColor.translateAlternateColorCodes('&', " "));
loreOffhand.add(ChatColor.translateAlternateColorCodes('&', "&8[&cRight Click to remove from OFFHAND&8]"));
}
if(!loreOffhand.isEmpty()) {
if(metaNuevo.hasLore()) {
List<String> loreNuevo = meta.getLore();
loreNuevo.addAll(loreOffhand);
metaNuevo.setLore(loreNuevo);
}else {
metaNuevo.setLore(loreOffhand);
}
item.setItemMeta(metaNuevo);
}
if(kits.contains(path+".preview_slot")) {
inv.setItem(Integer.valueOf(kits.getString(path+".preview_slot")), item);
}else {
inv.setItem(slot, item);
slot++;
}
}
}
jugador.openInventory(inv);
plugin.setKitEditando(new KitEditando(jugador,kit,""));
}
@EventHandler
public void clickInventarioItems(InventoryClickEvent event){
String pathInventory = ChatColor.translateAlternateColorCodes('&', "&9Editing Kit Items");
String pathInventoryM = ChatColor.stripColor(pathInventory);
if(ChatColor.stripColor(event.getView().getTitle()).equals(pathInventoryM)){
if((event.getSlotType() == null)){
event.setCancelled(true);
return;
}else{
final Player jugador = (Player) event.getWhoClicked();
int slot = event.getSlot();
if(event.getClickedInventory() != null && event.getClickedInventory().equals(jugador.getOpenInventory().getTopInventory())) {
final KitEditando kitEditando = plugin.getKitEditando();
FileConfiguration kits = plugin.getKits();
if(kitEditando != null && kitEditando.getJugador().getName().equals(jugador.getName())) {
if(slot == 45) {
event.setCancelled(true);
InventarioEditar.crearInventario(jugador, kitEditando.getKit(), plugin);
}else if(slot == 53) {
//Guardar items
event.setCancelled(true);
kits.set("Kits."+kitEditando.getKit()+".Items", null);
ItemStack[] contents = jugador.getOpenInventory().getTopInventory().getContents();
int c = 1;
FileConfiguration config = plugin.getConfig();
for(int i=0;i<44;i++) {
if(contents[i] != null && !contents[i].getType().equals(Material.AIR)) {
String path = "Kits."+kitEditando.getKit()+".Items."+c;
ItemStack contentsClone = contents[i].clone();
if(!Bukkit.getVersion().contains("1.8")) {
ItemMeta meta = contentsClone.getItemMeta();
List<String> lore = meta.getLore();
if(lore != null && !lore.isEmpty()) {
String ultimaLinea = ChatColor.stripColor(lore.get(lore.size()-1));
if(ultimaLinea.equals("[Right Click to remove from OFFHAND]")) {
lore.remove(lore.size()-1);lore.remove(lore.size()-1);
kits.set(path+".offhand", true);
if(lore.isEmpty()) {
meta.setLore(null);
}else {
meta.setLore(lore);
}
}
contentsClone.setItemMeta(meta);
}
}
KitManager.saveItem(contentsClone, kits, path, config);
kits.set(path+".preview_slot", i);
c++;
}
}
plugin.saveKits();
jugador.sendMessage(ChatColor.translateAlternateColorCodes('&', "&aKit Items saved."));
}else if(slot >= 46 && slot <= 52) {
event.setCancelled(true);
}else if(event.getClick().equals(ClickType.RIGHT)) {
ItemStack item = event.getCurrentItem();
if(item != null && !item.getType().equals(Material.AIR)
&& !Bukkit.getVersion().contains("1.8")) {
event.setCancelled(true);
ItemMeta meta = item.getItemMeta();
List<String> lore = meta.getLore();
if(lore != null) {
String ultimaLinea = ChatColor.stripColor(lore.get(lore.size()-1));
if(ultimaLinea.equals("[Right Click to remove from OFFHAND]")) {
lore.remove(lore.size()-1);lore.remove(lore.size()-1);
if(lore.isEmpty()) {
lore = null;
}
}else {
lore.add(ChatColor.translateAlternateColorCodes('&', " "));
lore.add(ChatColor.translateAlternateColorCodes('&', "&8[&cRight Click to remove from OFFHAND&8]"));
}
}else {
lore = new ArrayList<String>();
lore.add(ChatColor.translateAlternateColorCodes('&', " "));
lore.add(ChatColor.translateAlternateColorCodes('&', "&8[&cRight Click to remove from OFFHAND&8]"));
}
meta.setLore(lore);
item.setItemMeta(meta);
}
}
}
}
}
}
}
@SuppressWarnings("deprecation")
public static void crearInventarioDisplayItem(Player jugador,String kit,PlayerKits plugin,String tipoDisplay) {
//El tipoDisplay puede ser: normal o nopermission
FileConfiguration kits = plugin.getKits();
Inventory inv = Bukkit.createInventory(null, 27, ChatColor.translateAlternateColorCodes('&', "&9Editing Display Item"));
ItemStack item = new ItemStack(Material.ARROW);
ItemMeta meta = item.getItemMeta();
meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&7Go Back"));
item.setItemMeta(meta);
inv.setItem(18, item);
if(!Utilidades.isLegacy()) {
item = new ItemStack(Material.GRAY_STAINED_GLASS_PANE);
}else {
item = new ItemStack(Material.valueOf("STAINED_GLASS_PANE"),1,(short) 8);
}
meta = item.getItemMeta();
meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', " "));
item.setItemMeta(meta);
for(int i=19;i<=26;i++) {
inv.setItem(i, item);
}
for(int i=0;i<=8;i++) {
inv.setItem(i, item);
}
inv.setItem(9, item);inv.setItem(13, item);;inv.setItem(17, item);
if(!Utilidades.isLegacy()) {
item = new ItemStack(Material.PLAYER_HEAD);
}else {
item = new ItemStack(Material.valueOf("SKULL_ITEM"),1,(short) 3);
}
meta = item.getItemMeta();
meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&7Place item here &6>>"));
item.setItemMeta(meta);
item = Utilidades.setSkull(item, "d513d666-0992-42c7-9aa6-e518a83e0b38", "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvMTliZjMyOTJlMTI2YTEwNWI1NGViYTcxM2FhMWIxNTJkNTQxYTFkODkzODgyOWM1NjM2NGQxNzhlZDIyYmYifX19");
inv.setItem(10, item);
if(!Utilidades.isLegacy()) {
item = new ItemStack(Material.PLAYER_HEAD);
}else {
item = new ItemStack(Material.valueOf("SKULL_ITEM"),1,(short) 3);
}
meta = item.getItemMeta();
meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&6<< &7Place item here"));
item.setItemMeta(meta);
item = Utilidades.setSkull(item, "2391d533-ab09-434d-9980-adafde4057a3", "eyJ0ZXh0dXJlcyI6eyJTS0lOIjp7InVybCI6Imh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvYmQ2OWUwNmU1ZGFkZmQ4NGU1ZjNkMWMyMTA2M2YyNTUzYjJmYTk0NWVlMWQ0ZDcxNTJmZGM1NDI1YmMxMmE5In19fQ==");
inv.setItem(12, item);
String name = "none";
if(tipoDisplay.equals("normal")) {
if(kits.contains("Kits."+kit+".display_name")) {
name = kits.getString("Kits."+kit+".display_name");
}
}else {
if(kits.contains("Kits."+kit+"."+tipoDisplay+".display_name")) {
name = kits.getString("Kits."+kit+"."+tipoDisplay+".display_name");
}else {
if(kits.contains("Kits."+kit+".display_name")) {
name = kits.getString("Kits."+kit+".display_name");
}
}
}
item = new ItemStack(Material.NAME_TAG);
meta = item.getItemMeta();
meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&eSet &6&lDisplay Name"));
List<String> lore = new ArrayList<String>();
lore.add(ChatColor.translateAlternateColorCodes('&', "&7Click to define the display item name."));
lore.add(ChatColor.translateAlternateColorCodes('&', ""));
lore.add(ChatColor.translateAlternateColorCodes('&', "&7Current Name: &a"+name));
meta.setLore(lore);
item.setItemMeta(meta);
inv.setItem(14, item);
List<String> displayLore = new ArrayList<String>();
if(tipoDisplay.equals("normal")) {
if(kits.contains("Kits."+kit+".display_lore")) {
displayLore = kits.getStringList("Kits."+kit+".display_lore");
}
}else {
if(kits.contains("Kits."+kit+"."+tipoDisplay+".display_lore")) {
displayLore = kits.getStringList("Kits."+kit+"."+tipoDisplay+".display_lore");
}else {
if(kits.contains("Kits."+kit+".display_lore")) {
displayLore = kits.getStringList("Kits."+kit+".display_lore");
}
}
}
item = new ItemStack(Material.PAPER);
meta = item.getItemMeta();
meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&eSet &6&lDisplay Lore"));
lore = new ArrayList<String>();
lore.add(ChatColor.translateAlternateColorCodes('&', "&7Click to define the display item lore."));
lore.add(ChatColor.translateAlternateColorCodes('&', ""));
lore.add(ChatColor.translateAlternateColorCodes('&', "&7Current Lore:"));
if(displayLore.isEmpty()) {
lore.add(ChatColor.translateAlternateColorCodes('&', "&cNONE"));
}else {
for(int i=0;i<displayLore.size();i++) {
lore.add(ChatColor.translateAlternateColorCodes('&', displayLore.get(i)));
}
}
meta.setLore(lore);
item.setItemMeta(meta);
inv.setItem(15, item);
String glowing = "false";
if(tipoDisplay.equals("normal")) {
if(kits.contains("Kits."+kit+".display_item_glowing")) {
glowing = kits.getString("Kits."+kit+".display_item_glowing");
}
}else {
if(kits.contains("Kits."+kit+"."+tipoDisplay+".display_item_glowing")) {
glowing = kits.getString("Kits."+kit+"."+tipoDisplay+".display_item_glowing");
}
}
if(glowing.equals("true")) {
if(!Utilidades.isLegacy()) {
item = new ItemStack(Material.LIME_DYE);
}else {
item = new ItemStack(Material.valueOf("INK_SACK"),1,(short) 10);
}
}else {
if(!Utilidades.isLegacy()) {
item = new ItemStack(Material.GRAY_DYE);
}else {
item = new ItemStack(Material.valueOf("INK_SACK"),1,(short) 8);
}
}
meta = item.getItemMeta();
meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&eSet &6&lDisplay Item Glowing"));
lore = new ArrayList<String>();
lore.add(ChatColor.translateAlternateColorCodes('&', "&7Click to define if the display item"));
lore.add(ChatColor.translateAlternateColorCodes('&', "&7should display an enchantment."));
lore.add(ChatColor.translateAlternateColorCodes('&', ""));
lore.add(ChatColor.translateAlternateColorCodes('&', "&7Current Status: &a"+glowing));
meta.setLore(lore);
if(glowing.equals("true")) {
meta.addEnchant(Enchantment.PROTECTION_ENVIRONMENTAL, 1, true);
meta.addItemFlags(ItemFlag.HIDE_ENCHANTS);
}
item.setItemMeta(meta);
inv.setItem(16, item);
ItemStack displayItem = null;
if(tipoDisplay.equals("normal")) {
if(kits.contains("Kits."+kit+".display_item")) {
displayItem = Utilidades.getDisplayItem(kits, "Kits."+kit);
}
}else {
if(kits.contains("Kits."+kit+"."+tipoDisplay+".display_item")) {
displayItem = Utilidades.getDisplayItem(kits, "Kits."+kit+"."+tipoDisplay);
}
}
if(displayItem != null) {
meta = displayItem.getItemMeta();
meta.setDisplayName(null);
meta.setLore(null);
displayItem.setItemMeta(meta);
inv.setItem(11, displayItem);
}
jugador.openInventory(inv);
plugin.setKitEditando(new KitEditando(jugador,kit,tipoDisplay));
}
@EventHandler
public void clickInventarioDisplayItem(InventoryClickEvent event){
String pathInventory = ChatColor.translateAlternateColorCodes('&', "&9Editing Display Item");
String pathInventoryM = ChatColor.stripColor(pathInventory);
if(ChatColor.stripColor(event.getView().getTitle()).equals(pathInventoryM)){
if(event.getCursor() == null){
event.setCancelled(true);
return;
}
if((event.getSlotType() == null)){
event.setCancelled(true);
return;
}else{
final Player jugador = (Player) event.getWhoClicked();
int slot = event.getSlot();
if(event.getClickedInventory() != null && event.getClickedInventory().equals(jugador.getOpenInventory().getTopInventory())) {
final KitEditando kitEditando = plugin.getKitEditando();
FileConfiguration kits = plugin.getKits();
if(slot != 11) {
event.setCancelled(true);
if(kitEditando != null && kitEditando.getJugador().getName().equals(jugador.getName())) {
final String tipoDisplay = kitEditando.getTipoDisplay();
if(slot == 18) {
guardarDisplayItem(event.getClickedInventory(),tipoDisplay,kits,kitEditando.getKit());
InventarioEditar.crearInventario(jugador, kitEditando.getKit(), plugin);
}else if(slot == 14) {
//set display name
jugador.closeInventory();
KitEditando kit = new KitEditando(jugador,kitEditando.getKit(),tipoDisplay);
kit.setPaso("display_name");
plugin.setKitEditando(kit);
jugador.sendMessage(ChatColor.translateAlternateColorCodes('&', "&aWrite the display name of the Kit."));
jugador.sendMessage(ChatColor.translateAlternateColorCodes('&', "&8(&7You can use color codes&8)"));
}else if(slot == 16) {
//set glowing
guardarDisplayItem(event.getClickedInventory(),tipoDisplay,kits,kitEditando.getKit());
String path = "";
if(tipoDisplay.equals("normal")) {
path = "Kits."+kitEditando.getKit()+".display_item_glowing";
if(kits.contains("Kits."+kitEditando.getKit()+".display_item_glowing") && kits.getString("Kits."+kitEditando.getKit()+".display_item_glowing").equals("true")) {
kits.set(path, false);
}else {
kits.set(path, true);
}
}else {
path = "Kits."+kitEditando.getKit()+"."+tipoDisplay+".display_item_glowing";
if(kits.contains("Kits."+kitEditando.getKit()+"."+tipoDisplay+".display_item_glowing") && kits.getString("Kits."+kitEditando.getKit()+"."+tipoDisplay+".display_item_glowing").equals("true")) {
kits.set(path, false);
}else {
kits.set(path, true);
}
}
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
InventarioEditar.crearInventarioDisplayItem(jugador, kitEditando.getKit(), plugin, tipoDisplay);
}
}, 3L);
}else if(slot == 15) {
guardarDisplayItem(event.getClickedInventory(),tipoDisplay,kits,kitEditando.getKit());
InventarioEditar.crearInventarioDisplayItemLore(jugador, kitEditando.getKit(), plugin, tipoDisplay);
}
}
}
}
}
}
}
//Guardar display item
public static void guardarDisplayItem(Inventory inv,String tipoDisplay,FileConfiguration kits,String kit) {
ItemStack item = inv.getItem(11);
String path = "";
if(tipoDisplay.equals("normal")) {
path = "Kits."+kit;
}else {
path = "Kits."+kit+"."+tipoDisplay;
}
if(item != null) {
Material id = item.getType();
int datavalue = 0;
if(Utilidades.isLegacy()){
if(id == Material.POTION){
datavalue = item.getDurability();
}else{
datavalue = item.getData().getData();
}
}
kits.set(path+".display_item_skulldata", null);
kits.set(path+".display_item_custom_model_data", null);
if(datavalue != 0) {
kits.set(path+".display_item", item.getType()+":"+datavalue);
}else {
kits.set(path+".display_item", item.getType()+"");
}
kits.set(path+".display_item_leathercolor", null);
if(id.equals(Material.LEATHER_BOOTS) || id.equals(Material.LEATHER_CHESTPLATE)
|| id.equals(Material.LEATHER_HELMET) || id.equals(Material.LEATHER_LEGGINGS)) {
LeatherArmorMeta meta = (LeatherArmorMeta) item.getItemMeta();
kits.set(path+".display_item_leathercolor", meta.getColor().asRGB()+"");
}
if(Utilidades.isNew()){
ItemMeta meta = item.getItemMeta();
if(meta.hasCustomModelData()) {
kits.set(path+".display_item_custom_model_data", meta.getCustomModelData());
}
}
if(!Utilidades.isLegacy()){
if(id == Material.getMaterial("PLAYER_HEAD")){
Utilidades.guardarSkullDisplay(item,kits,path);
}
}else {
if(id == Material.valueOf("SKULL_ITEM") && datavalue == 3){
Utilidades.guardarSkullDisplay(item,kits,path);
}
}
}else {
kits.set(path+".display_item", null);
}
}
@SuppressWarnings("deprecation")
public static void crearInventarioDisplayItemLore(Player jugador,String kit,PlayerKits plugin,String tipoDisplay) {
FileConfiguration kits = plugin.getKits();
Inventory inv = Bukkit.createInventory(null, 54, ChatColor.translateAlternateColorCodes('&', "&9Editing Display Item Lore"));
ItemStack item = new ItemStack(Material.ARROW);
ItemMeta meta = item.getItemMeta();
meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&7Go Back"));
item.setItemMeta(meta);
inv.setItem(45, item);
item = new ItemStack(Material.EMERALD_BLOCK);
meta = item.getItemMeta();
meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&aAdd new Lore Line"));
item.setItemMeta(meta);
inv.setItem(53, item);
if(!Utilidades.isLegacy()) {
item = new ItemStack(Material.GRAY_STAINED_GLASS_PANE);
}else {
item = new ItemStack(Material.valueOf("STAINED_GLASS_PANE"),1,(short) 8);
}
meta = item.getItemMeta();
meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', " "));
item.setItemMeta(meta);
for(int i=46;i<=52;i++) {
inv.setItem(i, item);
}
List<String> lore = new ArrayList<String>();
if(tipoDisplay.equals("normal")) {
if(kits.contains("Kits."+kit+".display_lore")) {
lore = kits.getStringList("Kits."+kit+".display_lore");
}
}else {
if(kits.contains("Kits."+kit+"."+tipoDisplay+".display_lore")) {
lore = kits.getStringList("Kits."+kit+"."+tipoDisplay+".display_lore");
}
}
for(int i=0;i<lore.size();i++) {
item = new ItemStack(Material.PAPER,1);
meta = item.getItemMeta();
meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&9Line &e#"+(i+1)));
List<String> lore2 = new ArrayList<String>();
lore2.add(ChatColor.translateAlternateColorCodes('&', "&7")+lore.get(i));
lore2.add(ChatColor.translateAlternateColorCodes('&', ""));
lore2.add(ChatColor.translateAlternateColorCodes('&', "&8[&cRight Click to remove&8]"));
meta.setLore(lore2);
item.setItemMeta(meta);
inv.setItem(i, item);
}
jugador.openInventory(inv);
plugin.setKitEditando(new KitEditando(jugador,kit,tipoDisplay));
}
@EventHandler
public void clickInventarioDisplayLore(InventoryClickEvent event){
String pathInventory = ChatColor.translateAlternateColorCodes('&', "&9Editing Display Item Lore");
String pathInventoryM = ChatColor.stripColor(pathInventory);
if(ChatColor.stripColor(event.getView().getTitle()).equals(pathInventoryM)){
if(event.getCurrentItem() == null){
event.setCancelled(true);
return;
}
if((event.getSlotType() == null)){
event.setCancelled(true);
return;
}else{
final Player jugador = (Player) event.getWhoClicked();
int slot = event.getSlot();
event.setCancelled(true);
if(event.getClickedInventory().equals(jugador.getOpenInventory().getTopInventory())) {
final KitEditando kitEditando = plugin.getKitEditando();
FileConfiguration kits = plugin.getKits();
if(kitEditando != null && kitEditando.getJugador().getName().equals(jugador.getName())) {
final String tipoDisplay = kitEditando.getTipoDisplay();
if(slot == 45) {
InventarioEditar.crearInventarioDisplayItem(jugador, kitEditando.getKit(), plugin,tipoDisplay);
}else if(slot == 53) {
//Agregar lore
jugador.closeInventory();
KitEditando kit = new KitEditando(jugador,kitEditando.getKit(),tipoDisplay);
kit.setPaso("lore");
plugin.setKitEditando(kit);
jugador.sendMessage(ChatColor.translateAlternateColorCodes('&', "&aWrite the lore line to add."));
jugador.sendMessage(ChatColor.translateAlternateColorCodes('&', "&8(&7Write 'empty' to add an empty line&8)"));
}else if(slot >= 0 && slot <= 44 && event.getClick().equals(ClickType.RIGHT)) {
List<String> lore = new ArrayList<String>();
if(tipoDisplay.equals("normal")) {
if(kits.contains("Kits."+kitEditando.getKit()+".display_lore")) {
lore = kits.getStringList("Kits."+kitEditando.getKit()+".display_lore");
}
}else {
if(kits.contains("Kits."+kitEditando.getKit()+"."+tipoDisplay+".display_lore")) {
lore = kits.getStringList("Kits."+kitEditando.getKit()+"."+tipoDisplay+".display_lore");
}
}
for(int i=0;i<lore.size();i++) {
if(i == slot) {
lore.remove(i);
break;
}
}
if(tipoDisplay.equals("normal")) {
kits.set("Kits."+kitEditando.getKit()+".display_lore", lore);
}else {
kits.set("Kits."+kitEditando.getKit()+"."+tipoDisplay+".display_lore", lore);
}
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
InventarioEditar.crearInventarioDisplayItemLore(jugador, kitEditando.getKit(), plugin, tipoDisplay);
}
}, 3L);
}
}
}
}
}
}
@SuppressWarnings("deprecation")
public static void crearInventarioComandos(Player jugador,String kit,PlayerKits plugin) {
FileConfiguration kits = plugin.getKits();
Inventory inv = Bukkit.createInventory(null, 54, ChatColor.translateAlternateColorCodes('&', "&9Editing Kit Commands"));
ItemStack item = new ItemStack(Material.ARROW);
ItemMeta meta = item.getItemMeta();
meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&7Go Back"));
item.setItemMeta(meta);
inv.setItem(45, item);
item = new ItemStack(Material.EMERALD_BLOCK);
meta = item.getItemMeta();
meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&aAdd new Command"));
item.setItemMeta(meta);
inv.setItem(53, item);
if(!Utilidades.isLegacy()) {
item = new ItemStack(Material.GRAY_STAINED_GLASS_PANE);
}else {
item = new ItemStack(Material.valueOf("STAINED_GLASS_PANE"),1,(short) 8);
}
meta = item.getItemMeta();
meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', " "));
item.setItemMeta(meta);
for(int i=46;i<=52;i++) {
inv.setItem(i, item);
}
List<String> comandos = new ArrayList<String>();
if(kits.contains("Kits."+kit+".Commands")) {
comandos = kits.getStringList("Kits."+kit+".Commands");
}
for(int i=0;i<comandos.size();i++) {
item = new ItemStack(Material.PAPER,1);
meta = item.getItemMeta();
meta.setDisplayName(ChatColor.translateAlternateColorCodes('&', "&9Command &e#"+(i+1)));
List<String> lore = new ArrayList<String>();
lore.add(ChatColor.translateAlternateColorCodes('&', "&7")+comandos.get(i));
lore.add(ChatColor.translateAlternateColorCodes('&', ""));
lore.add(ChatColor.translateAlternateColorCodes('&', "&8[&cRight Click to remove&8]"));
meta.setLore(lore);
item.setItemMeta(meta);
inv.setItem(i, item);
}
jugador.openInventory(inv);
plugin.setKitEditando(new KitEditando(jugador,kit,""));
}
@EventHandler
public void clickInventarioComandos(InventoryClickEvent event){
String pathInventory = ChatColor.translateAlternateColorCodes('&', "&9Editing Kit Commands");
String pathInventoryM = ChatColor.stripColor(pathInventory);
if(ChatColor.stripColor(event.getView().getTitle()).equals(pathInventoryM)){
if(event.getCurrentItem() == null){
event.setCancelled(true);
return;
}
if((event.getSlotType() == null)){
event.setCancelled(true);
return;
}else{
final Player jugador = (Player) event.getWhoClicked();
int slot = event.getSlot();
event.setCancelled(true);
if(event.getClickedInventory().equals(jugador.getOpenInventory().getTopInventory())) {
final KitEditando kitEditando = plugin.getKitEditando();
FileConfiguration kits = plugin.getKits();
if(kitEditando != null && kitEditando.getJugador().getName().equals(jugador.getName())) {
if(slot == 45) {
InventarioEditar.crearInventario(jugador, kitEditando.getKit(), plugin);
}else if(slot == 53) {
//Agregar comando
jugador.closeInventory();
KitEditando kit = new KitEditando(jugador,kitEditando.getKit(),"");
kit.setPaso("comando");
plugin.setKitEditando(kit);
jugador.sendMessage(ChatColor.translateAlternateColorCodes('&', "&aWrite the command to add."));
jugador.sendMessage(ChatColor.translateAlternateColorCodes('&', "&8(&7This command will be executed from console&8)"));
jugador.sendMessage(ChatColor.translateAlternateColorCodes('&', "&8(&7Player variable is: &e%player%&8)"));
jugador.sendMessage(ChatColor.translateAlternateColorCodes('&', "&8(&7Write the command without the '/'&8)"));
}else if(slot >= 0 && slot <= 44 && event.getClick().equals(ClickType.RIGHT)) {
List<String> comandos = new ArrayList<String>();
if(kits.contains("Kits."+kitEditando.getKit()+".Commands")) {
comandos = kits.getStringList("Kits."+kitEditando.getKit()+".Commands");
}
for(int i=0;i<comandos.size();i++) {
if(i == slot) {
comandos.remove(i);
break;
}
}
kits.set("Kits."+kitEditando.getKit()+".Commands", comandos);
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
InventarioEditar.crearInventarioComandos(jugador, kitEditando.getKit(), plugin);
}
}, 3L);
}
}
}
}
}
}
@EventHandler
public void cerrarInventarioDisplay(InventoryCloseEvent event) {
String pathInventory = ChatColor.stripColor(ChatColor.stripColor(ChatColor.translateAlternateColorCodes('&', "&9Editing Display Item")));
Player jugador = (Player)event.getPlayer();
KitEditando kitEditando = plugin.getKitEditando();
if(kitEditando != null && kitEditando.getJugador().getName().equals(jugador.getName())) {
if(ChatColor.stripColor(event.getView().getTitle()).equals(pathInventory)){
InventarioEditar.guardarDisplayItem(event.getView().getTopInventory(), kitEditando.getTipoDisplay(), plugin.getKits(), kitEditando.getKit());
plugin.removerKitEditando();
plugin.saveKits();
}
}
}
@EventHandler
public void cerrarInventario(InventoryCloseEvent event) {
String pathInventory = ChatColor.stripColor(ChatColor.stripColor(ChatColor.translateAlternateColorCodes('&', "&9Editing Kit")));
Player jugador = (Player)event.getPlayer();
KitEditando kitEditando = plugin.getKitEditando();
if(kitEditando != null && kitEditando.getJugador().getName().equals(jugador.getName())) {
if(ChatColor.stripColor(event.getView().getTitle()).startsWith(pathInventory)){
plugin.removerKitEditando();
plugin.saveKits();
}
}
}
@EventHandler
public void alSalir(PlayerQuitEvent event) {
KitEditando kit = plugin.getKitEditando();
Player jugador = event.getPlayer();
if(kit != null && kit.getJugador().getName().equals(jugador.getName())) {
plugin.removerKitEditando();
plugin.saveKits();
}
}
@EventHandler
public void clickInventario(InventoryClickEvent event){
FileConfiguration config = plugin.getConfig();
String pathInventory = ChatColor.translateAlternateColorCodes('&', "&9Editing Kit");
String pathInventoryM = ChatColor.stripColor(pathInventory);
if(ChatColor.stripColor(event.getView().getTitle()).equals(pathInventoryM)){
if(event.getCurrentItem() == null){
event.setCancelled(true);
return;
}
if((event.getSlotType() == null)){
event.setCancelled(true);
return;
}else{
final Player jugador = (Player) event.getWhoClicked();
int slot = event.getSlot();
event.setCancelled(true);
if(event.getClickedInventory().equals(jugador.getOpenInventory().getTopInventory())) {
final KitEditando kitEditando = plugin.getKitEditando();
FileConfiguration kits = plugin.getKits();
if(kitEditando != null && kitEditando.getJugador().getName().equals(jugador.getName())) {
if(slot == 10) {
//set slot
jugador.closeInventory();
KitEditando kit = new KitEditando(jugador,kitEditando.getKit(),"");
kit.setPaso("slot");
plugin.setKitEditando(kit);
int max = Integer.valueOf(config.getString("Config.inventorySize"))-1;
jugador.sendMessage(ChatColor.translateAlternateColorCodes('&', "&aWrite the new slot of the Kit."));
jugador.sendMessage(ChatColor.translateAlternateColorCodes('&', "&8(&7Use a number between 0 and "+max+"&8)"));
jugador.sendMessage(ChatColor.translateAlternateColorCodes('&', "&8(&7Write 'none' to not show the kit&8)"));
}else if(slot == 11) {
//set cooldown
jugador.closeInventory();
KitEditando kit = new KitEditando(jugador,kitEditando.getKit(),"");
kit.setPaso("cooldown");
plugin.setKitEditando(kit);
jugador.sendMessage(ChatColor.translateAlternateColorCodes('&', "&aWrite the cooldown of the Kit."));
}else if(slot == 12) {
//set permission
jugador.closeInventory();
KitEditando kit = new KitEditando(jugador,kitEditando.getKit(),"");
kit.setPaso("permission");
plugin.setKitEditando(kit);
jugador.sendMessage(ChatColor.translateAlternateColorCodes('&', "&aWrite the permission of the Kit."));
jugador.sendMessage(ChatColor.translateAlternateColorCodes('&', "&8(&7Write 'none' to not have a permission&8)"));
}else if(slot == 19) {
//set first join
if(kits.contains("Kits."+kitEditando.getKit()+".first_join") && kits.getString("Kits."+kitEditando.getKit()+".first_join").equals("true")) {
kits.set("Kits."+kitEditando.getKit()+".first_join", false);
}else {
kits.set("Kits."+kitEditando.getKit()+".first_join", true);
}
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
InventarioEditar.crearInventario(jugador, kitEditando.getKit(), plugin);
}
}, 3L);
}else if(slot == 20) {
//set one time
if(kits.contains("Kits."+kitEditando.getKit()+".one_time") && kits.getString("Kits."+kitEditando.getKit()+".one_time").equals("true")) {
kits.set("Kits."+kitEditando.getKit()+".one_time", false);
}else {
kits.set("Kits."+kitEditando.getKit()+".one_time", true);
}
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
InventarioEditar.crearInventario(jugador, kitEditando.getKit(), plugin);
}
}, 3L);
}else if(slot == 28) {
//set auto armor
if(kits.contains("Kits."+kitEditando.getKit()+".auto_armor") && kits.getString("Kits."+kitEditando.getKit()+".auto_armor").equals("true")) {
kits.set("Kits."+kitEditando.getKit()+".auto_armor", false);
}else {
kits.set("Kits."+kitEditando.getKit()+".auto_armor", true);
}
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
InventarioEditar.crearInventario(jugador, kitEditando.getKit(), plugin);
}
}, 3L);
}else if(slot == 15) {
//set commands
InventarioEditar.crearInventarioComandos(jugador, kitEditando.getKit(), plugin);
}else if(slot == 14) {
//set items
InventarioEditar.crearInventarioItems(jugador, kitEditando.getKit(), plugin);
}else if(slot == 23) {
//set price
jugador.closeInventory();
KitEditando kit = new KitEditando(jugador,kitEditando.getKit(),"");
kit.setPaso("price");
plugin.setKitEditando(kit);
jugador.sendMessage(ChatColor.translateAlternateColorCodes('&', "&aWrite the price of the Kit."));
jugador.sendMessage(ChatColor.translateAlternateColorCodes('&', "&8(&7Write 'none' to not have a price&8)"));
}else if(slot == 16) {
//set page
jugador.closeInventory();
KitEditando kit = new KitEditando(jugador,kitEditando.getKit(),"");
kit.setPaso("page");
plugin.setKitEditando(kit);
jugador.sendMessage(ChatColor.translateAlternateColorCodes('&', "&aWrite the new page of the Kit."));
jugador.sendMessage(ChatColor.translateAlternateColorCodes('&', "&8(&7Use a number greater than 0&8)"));
}else if(slot == 21) {
//set one time buy
if(kits.contains("Kits."+kitEditando.getKit()+".one_time_buy") && kits.getString("Kits."+kitEditando.getKit()+".one_time_buy").equals("true")) {
kits.set("Kits."+kitEditando.getKit()+".one_time_buy", false);
}else {
kits.set("Kits."+kitEditando.getKit()+".one_time_buy", true);
}
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
InventarioEditar.crearInventario(jugador, kitEditando.getKit(), plugin);
}
}, 3L);
}
else if(slot == 40) {
InventarioEditar.crearInventarioDisplayItem(jugador, kitEditando.getKit(), plugin, "noPermissionsItem");
}else if(slot == 39) {
InventarioEditar.crearInventarioDisplayItem(jugador, kitEditando.getKit(), plugin, "normal");
}else if(slot == 41) {
InventarioEditar.crearInventarioDisplayItem(jugador, kitEditando.getKit(), plugin, "noBuyItem");
}
}
}
}
}
}
@EventHandler
public void capturarChat(AsyncPlayerChatEvent event) {
final KitEditando kit = plugin.getKitEditando();
final Player jugador = event.getPlayer();
String message = ChatColor.stripColor(event.getMessage());
if(kit != null && kit.getJugador().getName().equals(jugador.getName())) {
FileConfiguration kits = plugin.getKits();
event.setCancelled(true);
FileConfiguration config = plugin.getConfig();
String prefix = ChatColor.translateAlternateColorCodes('&', config.getString("Messages.prefix"));
String paso = kit.getPaso();
if(paso.equals("slot")) {
int max = Integer.valueOf(config.getString("Config.inventorySize"))-1;
try {
int num = Integer.valueOf(message);
if(num >= 0 && num <= max) {
jugador.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', "&aSlot defined to: &e"+num));
kits.set("Kits."+kit.getKit()+".slot", num);
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
InventarioEditar.crearInventario(jugador, kit.getKit(), plugin);
}
}, 3L);
}else {
jugador.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', "&cUse a valid number or write 'none'."));
}
}catch(NumberFormatException e) {
if(message.equalsIgnoreCase("none")) {
jugador.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', "&aSlot defined to: &e"+message));
kits.set("Kits."+kit.getKit()+".slot", null);
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
InventarioEditar.crearInventario(jugador, kit.getKit(), plugin);
}
}, 3L);
}else {
jugador.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', "&cUse a valid number or write 'none'."));
}
}
}else if(paso.equals("page")) {
try {
int num = Integer.valueOf(message);
if(num >= 1) {
jugador.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', "&aPage defined to: &e"+num));
kits.set("Kits."+kit.getKit()+".page", num);
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
InventarioEditar.crearInventario(jugador, kit.getKit(), plugin);
}
}, 3L);
}else {
jugador.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', "&cUse a valid number."));
}
}catch(NumberFormatException e) {
jugador.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', "&cUse a valid number."));
}
}
else if(paso.equals("cooldown")) {
try {
int num = Integer.valueOf(message);
if(num >= 0) {
jugador.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', "&aCooldown defined to: &e"+num));
kits.set("Kits."+kit.getKit()+".cooldown", num);
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
InventarioEditar.crearInventario(jugador, kit.getKit(), plugin);
}
}, 3L);
}else {
jugador.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', "&cUse a valid number."));
}
}catch(NumberFormatException e) {
jugador.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', "&cUse a valid number."));
}
}else if(paso.equals("permission")) {
if(message.equalsIgnoreCase("none")) {
kits.set("Kits."+kit.getKit()+".permission", null);
}else {
kits.set("Kits."+kit.getKit()+".permission", message);
}
jugador.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', "&aPermission defined to: &e"+message));
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
InventarioEditar.crearInventario(jugador, kit.getKit(), plugin);
}
}, 3L);
}else if(paso.equals("comando")) {
List<String> comandos = new ArrayList<String>();
if(kits.contains("Kits."+kit.getKit()+".Commands")) {
comandos = kits.getStringList("Kits."+kit.getKit()+".Commands");
}
comandos.add(message);
kits.set("Kits."+kit.getKit()+".Commands", comandos);
jugador.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', "&aCommand added: &e"+message));
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
InventarioEditar.crearInventarioComandos(jugador, kit.getKit(), plugin);
}
}, 3L);
}else if(paso.equals("price")) {
if(message.equalsIgnoreCase("none")) {
kits.set("Kits."+kit.getKit()+".price", null);
}else {
kits.set("Kits."+kit.getKit()+".price", message);
}
jugador.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', "&aPrice defined to: &e"+message));
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
InventarioEditar.crearInventario(jugador, kit.getKit(), plugin);
}
}, 3L);
}else if(paso.equals("display_name")) {
final String tipoDisplay = kit.getTipoDisplay();
if(tipoDisplay.equals("normal")) {
kits.set("Kits."+kit.getKit()+".display_name", message);
}else {
kits.set("Kits."+kit.getKit()+"."+tipoDisplay+".display_name", message);
}
jugador.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', "&aDisplay Name defined to: &e"+message));
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
InventarioEditar.crearInventarioDisplayItem(jugador, kit.getKit(), plugin, tipoDisplay);
}
}, 3L);
}else if(paso.equals("lore")) {
List<String> lore = new ArrayList<String>();
final String tipoDisplay = kit.getTipoDisplay();
if(tipoDisplay.equals("normal")) {
if(kits.contains("Kits."+kit.getKit()+".display_lore")) {
lore = kits.getStringList("Kits."+kit.getKit()+".display_lore");
}
}else {
if(kits.contains("Kits."+kit.getKit()+"."+tipoDisplay+".display_lore")) {
lore = kits.getStringList("Kits."+kit.getKit()+"."+tipoDisplay+".display_lore");
}
}
if(message.equals("empty")) {
lore.add("");
}else {
lore.add(message);
}
if(tipoDisplay.equals("normal")) {
kits.set("Kits."+kit.getKit()+".display_lore", lore);
}else {
kits.set("Kits."+kit.getKit()+"."+tipoDisplay+".display_lore", lore);
}
jugador.sendMessage(prefix+ChatColor.translateAlternateColorCodes('&', "&aLore line added: &e"+message));
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
InventarioEditar.crearInventarioDisplayItemLore(jugador, kit.getKit(), plugin,tipoDisplay);
}
}, 3L);
}
}
}
}
| 41.116058 | 259 | 0.67301 |
600a3c11a40589b187763f7cb60987293e5585fe | 2,322 | /* ###
* IP: GHIDRA
*
* 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 ghidra.app.decompiler;
import java.util.*;
/**
*
*
* A line of C code. This is an independent grouping
* of C tokens from the statement, vardecl retype groups
*/
public class ClangLine {
private int indent_level;
private ArrayList<ClangToken> tokens;
private int lineNumber;
public ClangLine(int lineNumber, int indent) {
tokens = new ArrayList<>();
indent_level = indent;
this.lineNumber = lineNumber;
}
public String getIndentString() {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < indent_level; i++) {
buffer.append(PrettyPrinter.INDENT_STRING);
}
return buffer.toString();
}
public int getIndent() {
return indent_level;
}
public void addToken(ClangToken tok) {
tokens.add(tok);
tok.setLineParent(this);
}
public ArrayList<ClangToken> getAllTokens() {
return tokens;
}
public int getNumTokens() {
return tokens.size();
}
public int getLineNumber() {
return lineNumber;
}
public ClangToken getToken(int i) {
return tokens.get(i);
}
public String toDebugString(List<ClangToken> calloutTokens) {
return toDebugString(calloutTokens, "[", "]");
}
public String toDebugString(List<ClangToken> calloutTokens, String start, String end) {
if (calloutTokens == null) {
calloutTokens = Collections.emptyList();
}
StringBuilder buffy = new StringBuilder(getLineNumber() + ": ");
for (ClangToken token : tokens) {
boolean isCallout = calloutTokens.contains(token);
if (isCallout) {
buffy.append(start);
}
buffy.append(token.getText());
if (isCallout) {
buffy.append(end);
}
}
return buffy.toString();
}
@Override
public String toString() {
return toDebugString(Collections.emptyList());
}
}
| 22.114286 | 88 | 0.700689 |
c4afb8f77cffd21784917f35dd776dce0bc958db | 674 | package um.si.de4a.resources.vc;
import com.google.gson.annotations.SerializedName;
import java.util.ArrayList;
public class CredentialsAttach {
@SerializedName("lastmod_time")
private String lastmodTime;
private Data data;
public CredentialsAttach(String lastmodTime, Data data) {
this.lastmodTime = lastmodTime;
this.data = data;
}
public String getLastmodTime() {
return lastmodTime;
}
public void setLastmodTime(String lastmodTime) {
this.lastmodTime = lastmodTime;
}
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
}
| 20.424242 | 61 | 0.661721 |
430fa4c3d23022d3ea4308724a4b4b237f2bf4c2 | 722 | package com.zeshanaslam.actionhealth.support;
import io.lumine.mythic.bukkit.BukkitAPIHelper;
import io.lumine.mythic.bukkit.MythicBukkit;
import org.bukkit.Bukkit;
import org.bukkit.entity.Entity;
public class MythicMobsSupport {
private static final MythicBukkit plugin = (MythicBukkit) Bukkit.getServer().getPluginManager().getPlugin("MythicMobs");
public String getMythicName(Entity entity) {
if (plugin == null) {
return null;
}
BukkitAPIHelper bucketApiHelper = plugin.getAPIHelper();
if (bucketApiHelper.isMythicMob(entity)) {
return bucketApiHelper.getMythicMobInstance(entity).getType().getInternalName();
}
return null;
}
}
| 31.391304 | 124 | 0.710526 |
bbfc9ac91d1c27ab10f5461484f6ca83686a3ec2 | 261 | package de.unisiegen.gtitool.core.grammars.cfg;
import de.unisiegen.gtitool.core.grammars.Grammar;
/**
* The interface for context free grammars.
*
* @author Christian Fehler
* @version $Id$
*/
public interface CFG extends Grammar
{
// Do nothing
}
| 15.352941 | 50 | 0.720307 |
b01cdc6d390b8c936b6aae81b59938916477ffb3 | 1,238 | package burlap.behavior.stochasticgames.agents.naiveq.history;
import burlap.oomdp.stochasticgames.agentactions.GroundedSGAgentAction;
/**
* An interface that can turn a grounded action into an integer value
* @author James MacGlashan
*
*/
public interface ActionIdMap {
/**
* Returns an int value corresponding to the input action
* @param gsa the input action
* @return an int value corresponding to the input action
*/
public int getActionId(GroundedSGAgentAction gsa);
/**
* Returns an int value corresponding to the input action name and parameters
* @param actionName the input action name
* @param params the input action parameters
* @return an int value corresponding to the input action name and parameters
*/
public int getActionId(String actionName, String [] params);
/**
* The maximum number of int values for actions
* @return maximum number of int values for actions
*/
public int maxValue();
/**
* Returns a corresponding GroundedSingleAction for a given int value
* @param id the int value indicating which GroundedSingleAction to return.
* @return a corresponding GroundedSingleAction for a given int value
*/
public GroundedSGAgentAction getActionForId(int id);
}
| 30.95 | 78 | 0.756058 |
55bad4ed012fa5e6dd6ce489f741ef8f2c6f4528 | 9,332 | /*
* 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.jackrabbit.vault.packaging;
import java.io.IOException;
import javax.jcr.Node;
import javax.jcr.Property;
import javax.jcr.RepositoryException;
import org.apache.jackrabbit.vault.fs.io.ImportOptions;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.osgi.annotation.versioning.ProviderType;
/**
* Specifies the interface of a vault package stored in the repository.
*/
@ProviderType
public interface JcrPackage extends Comparable<JcrPackage>, AutoCloseable {
/**
* Nodetype name of a package node
*/
String NT_VLT_PACKAGE = "vlt:Package";
/**
* Nodetype name of a definition node
*/
String NT_VLT_PACKAGE_DEFINITION = "vlt:PackageDefinition";
/**
* Nodename of the definition node
*/
String NN_VLT_DEFINITION = "vlt:definition";
/**
* default mime type of a package
*/
String MIME_TYPE = "application/zip";
/**
* Returns the package definition of this package
* @return the package definition or {@code null} if this package is
* not valid.
* @throws RepositoryException if an error occurrs
*/
@Nullable
JcrPackageDefinition getDefinition() throws RepositoryException;
/**
* Checks if the underlying node contains the correct structure.
* @return {@code true} if this package is valid.
*/
boolean isValid();
/**
* Returns the underlying node
* @return the node
*/
@Nullable
Node getNode();
/**
* Checks if this package is sealed. this is the case, if it was not
* modified since it was unwrapped.
* @return {@code true} if this package is sealed.
*/
boolean isSealed();
/**
* Returns the vault package stored in the data of this package
* @return the package
* @throws RepositoryException if an error occurs
* @throws IOException if an I/O error occurs
*/
@NotNull
VaultPackage getPackage() throws RepositoryException, IOException;
/**
* Extracts the package contents to the repository
*
* @param opts import options
* @throws RepositoryException if a repository error during installation occurs.
* @throws PackageException if an error during packaging occurs
* @throws IllegalStateException if the package is not valid.
* @throws IOException if an I/O error occurs
* @since 2.3.14
*/
void extract(@NotNull ImportOptions opts)
throws RepositoryException, PackageException, IOException;
/**
* Installs the package contents to the repository but creates a snapshot if
* necessary.
*
* @param opts import options
* @throws RepositoryException if a repository error during installation occurs.
* @throws PackageException if an error during packaging occurs
* @throws IllegalStateException if the package is not valid.
* @throws IOException if an I/O error occurs
*
* @since 2.3.14
*/
void install(@NotNull ImportOptions opts)
throws RepositoryException, PackageException, IOException;
/**
* Processes this package and extracts all sub packages. No content of this package or its sub packages is extracted
* and not snapshots are taken. If {@link ImportOptions#isNonRecursive()} is {@code true}, then only the direct
* sub packages are extracted. The extraction ensures that the sub packages have a dependency to their parent package.
*
* @param opts import options
* @return the list of subpackages that were extracted
* @throws RepositoryException if a repository error during installation occurs.
* @throws PackageException if an error during packaging occurs
* @throws IllegalStateException if the package is not valid.
* @throws IOException if an I/O error occurs
*
* @since 3.1.32
*/
@NotNull
PackageId[] extractSubpackages(@NotNull ImportOptions opts)
throws RepositoryException, PackageException, IOException;
/**
* Returns the dependencies that are not resolved. If the {@link DependencyHandling} is set to strict, the package
* will not installed if any unresolved dependencies are listed.
* @return the array of unresolved dependencies.
* @throws RepositoryException if an error accessing the repository occurrs
* @since 3.1.32
*/
@NotNull
Dependency[] getUnresolvedDependencies() throws RepositoryException;
/**
* Returns a list of the installed packages that this package depends on.
* @return the array of resolved dependencies
* @throws RepositoryException if an error accessing the repository occurrs
* @since 3.1.32
*/
@NotNull
PackageId[] getResolvedDependencies() throws RepositoryException;
/**
* Creates a snapshot of this package.
*
* @param opts export options
* @param replace if {@code true} any existing snapshot is replaced.
* @return a package that represents the snapshot of this package or {@code null} if it wasn't created.
* @throws RepositoryException if a repository error during installation occurs.
* @throws PackageException if an error during packaging occurs
* @throws IllegalStateException if the package is not valid.
* @throws IOException if an I/O error occurs
*
* @since 2.0
*/
@Nullable
JcrPackage snapshot(@NotNull ExportOptions opts, boolean replace)
throws RepositoryException, PackageException, IOException;
/**
* Returns the snapshot that was taken when installing this package.
* @return the snapshot package or {@code null}
* @throws RepositoryException if an error occurs.
*
* @since 2.0
*/
@Nullable
JcrPackage getSnapshot() throws RepositoryException;
/**
* Reverts the changes of a prior installation of this package.
*
* @param opts import options
* @throws RepositoryException if a repository error during installation occurs.
* @throws PackageException if an error during packaging occurs or if no
* snapshot is available.
* @throws IllegalStateException if the package is not valid.
* @throws PackageException if no snapshot is present and {@link ImportOptions#isStrict()} is {@code true}.
* @throws IOException if an I/O error occurs
*
* @since 2.3.14
*/
void uninstall(@NotNull ImportOptions opts)
throws RepositoryException, PackageException, IOException;
/**
* Checks if the package id is correct in respect to the installation path
* and adjusts it accordingly.
*
* @param autoFix {@code true} to automatically fix the id
* @param autoSave {@code true} to save changes immediately
* @return {@code true} if id is correct.
* @throws RepositoryException if an error occurs.
*
* @since 2.2.18
*
* @deprecated As of 3.1.42, the storage location is implementation details.
*/
@Deprecated
boolean verifyId(boolean autoFix, boolean autoSave) throws RepositoryException;
/**
* Checks if this package is installed.
*
* Note: the default implementation only checks the {@link org.apache.jackrabbit.vault.packaging.JcrPackageDefinition#getLastUnpacked()}
* date. If the package is replaced since it was installed. this method will return {@code false}.
*
* @return {@code true} if this package is installed.
* @throws RepositoryException if an error occurs.
*
* @since 2.4.6
*/
boolean isInstalled() throws RepositoryException;
/**
* Checks if the package has content.
* @return {@code true} if this package doesn't have content
*
* @since 3.1.40
*/
boolean isEmpty();
/**
* Returns the size of the underlying package.
* @return the size in bytes or -1 if not valid.
*/
long getSize();
/**
* Closes this package and destroys all temporary data.
*/
void close();
/**
* Returns the jcr:data property of the package
* @return the jcr:data property
* @throws RepositoryException if an error occurrs
*/
@Nullable
Property getData() throws RepositoryException;
/**
* Returns the definition node or {@code null} if not exists
* @return the definition node.
* @throws RepositoryException if an error occurrs
*/
@Nullable
Node getDefNode() throws RepositoryException;
}
| 34.820896 | 140 | 0.684312 |
05bf90475c5963c84114e4bdc04bd4843c089f9a | 2,035 | /**
* Copyright 1996-2014 FoxBPM ORG.
*
* 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.
*
* @author ych
*/
package org.foxbpm.engine.impl.cmd;
import java.util.ArrayList;
import java.util.List;
import org.foxbpm.engine.identity.GroupDefinition;
import org.foxbpm.engine.impl.entity.GroupEntity;
import org.foxbpm.engine.impl.interceptor.Command;
import org.foxbpm.engine.impl.interceptor.CommandContext;
import org.foxbpm.engine.impl.util.ExceptionUtil;
import org.foxbpm.engine.impl.util.StringUtil;
/**
* 获取组编号下的所有子组(包含自身)
* @author ych
*
*/
public class FindGroupChildrenIncludeByGroupIdCmd implements Command<List<GroupEntity>>{
private String groupType;
private String groupId;
public FindGroupChildrenIncludeByGroupIdCmd(String groupId,String groupType) {
this.groupId = groupId;
this.groupType = groupType;
}
public List<GroupEntity> execute(CommandContext commandContext) {
if(StringUtil.isEmpty(groupType)){
throw ExceptionUtil.getException("10601004");
}
if(StringUtil.isEmpty(groupId)){
throw ExceptionUtil.getException("10601005");
}
List<GroupEntity> groups = new ArrayList<GroupEntity>();
List<GroupDefinition> groupDefinitions = commandContext.getProcessEngineConfigurationImpl().getGroupDefinitions();
for(GroupDefinition groupDefinition : groupDefinitions){
if(groupDefinition.getType().equals(groupType)){
groups = groupDefinition.selectChildrenByGroupId(groupId);
return groups;
}
}
throw ExceptionUtil.getException("10602001");
}
}
| 31.307692 | 116 | 0.764619 |
43dc6b9e5340084749e6a02f3ec3c739c2e42d31 | 1,192 | package me.jinhao.springblog.model;
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Transient;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import org.hibernate.annotations.CreationTimestamp;
import lombok.Data;
@Entity
@Data
public class Comment {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@JsonManagedReference
@ManyToOne(cascade = {CascadeType.MERGE,CascadeType.REFRESH})
private Blog blog;
@Column(nullable = false)
private String email;
@Column(nullable = false)
private String name;
private String website;
@Column(nullable = false)
private String content;
@CreationTimestamp
@Column(updatable = false, nullable = false)
private Date createdTime;
@Transient
private String avatar;
} | 22.923077 | 66 | 0.730705 |
517b164769d1d4f5faad16f0ed5aa10de33995aa | 1,606 | /*
* Copyright (c) 2015 Andrew Coates
*
* 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.datalorax.populace.core.walk.inspector.annotation;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;
/**
* Default annotation inspector for Populace. The inspector obtains annotations of the supplied {@code field}
*
* @author Andrew Coates - 24/03/2015.
*/
public class SimpleAnnotationInspector implements AnnotationInspector {
public static final SimpleAnnotationInspector INSTANCE = new SimpleAnnotationInspector();
@Override
public <T extends Annotation> T getAnnotation(final Field field, final Class<T> type) {
return field.getAnnotation(type);
}
@Override
public <T extends Annotation> T getAnnotation(final Class<T> type, final Method... accessorMethods) {
return Arrays.stream(accessorMethods)
.map(accessor -> accessor.getAnnotation(type))
.filter(annotation -> annotation != null)
.findFirst().orElse(null);
}
}
| 35.688889 | 109 | 0.728518 |
b5dcc8d5c02a92c071ef4efc0462123cf6860788 | 1,276 | package com.blazemeter.jmeter.citrix.clause.strategy.format;
import com.blazemeter.jmeter.citrix.clause.CheckResult;
import com.blazemeter.jmeter.citrix.clause.Clause;
/**
* Provides a check result formatter dedicated to displaying the correspondence
* with the expected value.
*/
public class RegularResultFormatter implements ResultFormatter {
@Override
public String execute(CheckResult result, CheckResult previous, Clause clause, int index) {
String value;
if (result.isSuccessful()) {
if (clause.isUsingRegex()) {
value = "'" + result.getValue() + "' matches the expecting regular expression '"
+ clause.getExpectedValueParametrized() + "'";
} else {
value = "'" + result.getValue() + "' is equals to the expecting value '" +
clause.getExpectedValueParametrized()
+ "'";
}
} else {
if (clause.isUsingRegex()) {
value = "'" + result.getValue() + "' does not match the expecting regular expression '"
+ clause.getExpectedValueParametrized() + "'";
} else {
value = "'" + result.getValue() + "' differs from the expecting value '" +
clause.getExpectedValueParametrized()
+ "'";
}
}
return value;
}
}
| 33.578947 | 95 | 0.634013 |
8c7f32a87599f29bc2517649f8c4f223b169d3fa | 4,053 | package com.googlecode.blaisemath.graph.metrics;
/*
* #%L
* BlaiseGraphTheory
* --
* Copyright (C) 2009 - 2021 Elisha Peterson
* --
* 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%
*/
import com.google.common.annotations.Beta;
import com.google.common.collect.Iterables;
import com.google.common.graph.Graph;
import com.googlecode.blaisemath.graph.GraphNodeMetric;
import com.googlecode.blaisemath.graph.GraphSubsetMetric;
import com.googlecode.blaisemath.graph.GraphUtils;
import java.util.Set;
/**
* Utility class for working with {@link GraphSubsetMetric} instances.
*
* @author Elisha Peterson
*/
@Beta
public class SubsetMetrics {
// utility class
private SubsetMetrics() {
}
/**
* Crete an additive subset metric based on the given node metric. The resulting metric
* adds the computed values for each node in a subset together.
* @param <N> node type
* @param baseMetric base metric
* @return additive metric
*/
public static <N extends Number> GraphSubsetMetric<N> additiveSubsetMetric(GraphNodeMetric<N> baseMetric) {
return new AdditiveSubsetMetric<>(baseMetric);
}
/**
* Create a contractive subset metric based on the given node metric. The resulting metric
* computes a subset metric by first contracting the subset to a point, and then
* using the base metric in that new graph.
* @param <N> node type
* @param baseMetric base metric
* @return contractive metric
*/
public static <N> GraphSubsetMetric<N> contractiveSubsetMetric(GraphNodeMetric<N> baseMetric) {
return new ContractiveSubsetMetric<>(baseMetric);
}
//region INNER CLASSES
@Beta
private static class AdditiveSubsetMetric<T extends Number> implements GraphSubsetMetric<T> {
final GraphNodeMetric<T> baseMetric;
/**
* Constructs with provided base metric.
* @param baseMetric the metric to use for computations on individual nodes.
*/
private AdditiveSubsetMetric(GraphNodeMetric<T> baseMetric) {
this.baseMetric = baseMetric;
}
@Override
public <N> T getValue(Graph<N> graph, Set<N> nodes) {
Double result = 0.0;
Number val = null;
for (N n : nodes) {
val = baseMetric.apply(graph, n);
result += val.doubleValue();
}
if (val instanceof Integer) {
return (T) (Integer) result.intValue();
}
else if (val instanceof Double) {
return (T) result;
}
else if (val instanceof Float) {
return (T) (Float) result.floatValue();
}
return null;
}
}
@Beta
private static class ContractiveSubsetMetric<T> implements GraphSubsetMetric<T> {
final GraphNodeMetric<T> baseMetric;
/**
* Constructs with provided base metric.
* @param baseMetric the metric to use for computations of contracted node
*/
private ContractiveSubsetMetric(GraphNodeMetric<T> baseMetric) {
this.baseMetric = baseMetric;
}
@Override
public <N> T getValue(Graph<N> graph, Set<N> nodes) {
N starNode = Iterables.getFirst(nodes, null);
Graph<N> contracted = GraphUtils.contractedGraph(graph, nodes, starNode);
return baseMetric.apply(contracted, starNode);
}
}
//endregion
}
| 31.913386 | 111 | 0.643967 |
facb7878d38591af7f61f06a159581768035bb89 | 1,857 | package org.sports.hbaseparse.parserUtils;
import java.util.Calendar;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public final class CustomDateTimeParser {
private static int getMonth(String bgMonthString) {
int result;
switch (bgMonthString.toLowerCase()) {
case "януари":
result = 1;
break;
case "февруари":
result = 2;
break;
case "март":
result = 3;
break;
case "април":
result = 4;
break;
case "май":
result = 5;
break;
case "юни":
result = 6;
break;
case "юли":
result = 7;
break;
case "август":
result = 8;
break;
case "септември":
result = 9;
break;
case "октомври":
result = 10;
break;
case "ноември":
result = 11;
break;
case "декември":
result = 12;
break;
default:
throw new IllegalArgumentException("Invalid month string.");
}
return result;
}
/**
* Transforms string encoded date into DateTime format
*
* @param input
* String encoded date in format dd MonthName YYYY | HH:MM
* @return Parsed date and time in proper format
*/
public static Date parse(String input) {
if (input == "") {
return null;
}
String regex = "(\\d+)\\s+(.*)\\s+(\\d+)[|\\s]+(\\d+):(\\d+)";
Pattern pattern = Pattern.compile(regex);
Matcher m = pattern.matcher(input);
if (m.matches()) {
int date = Integer.parseInt(m.group(1));
int month = getMonth(m.group(2)) - 1;
int year = Integer.parseInt(m.group(3));
int hourOfDay = Integer.parseInt(m.group(4));
int minute = Integer.parseInt(m.group(5));
Calendar cal = Calendar.getInstance();
cal.set(year, month, date, hourOfDay, minute, 0);
return cal.getTime();
} else {
throw new IllegalArgumentException(
"Not valid date string format. Must be dd MonthName YYYY | HH:MM.");
}
}
}
| 20.865169 | 73 | 0.628433 |
3c731de92e82cfed0cd08d8c2995587a488b30a0 | 4,951 | package com.dylanvann.fastimage;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.util.Log;
import androidx.annotation.Nullable;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.SizeReadyCallback;
import com.bumptech.glide.request.target.Target;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableArray;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.bridge.WritableNativeMap;
class FastImageViewModule extends ReactContextBaseJavaModule {
private static final String REACT_CLASS = "FastImageView";
FastImageViewModule(ReactApplicationContext reactContext) {
super(reactContext);
}
@Override
public String getName() {
return REACT_CLASS;
}
@ReactMethod
public void preload(final ReadableArray sources, final Promise onSizeDetermined) {
final Activity activity = getCurrentActivity();
if (activity == null) return;
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
final boolean canIssuePromise = sources.size() == 1;
if (!canIssuePromise) {
onSizeDetermined.resolve(null);
}
for (int i = 0; i < sources.size(); i++) {
final ReadableMap source = sources.getMap(i);
final FastImageSource imageSource = FastImageViewConverter.getImageSource(activity, source);
Target<Drawable> target = Glide
.with(activity.getApplicationContext())
// This will make this work for remote and local images. e.g.
// - file:///
// - content://
// - res:/
// - android.resource://
// - data:image/png;base64
.load(
imageSource.isBase64Resource() ? imageSource.getSource() :
imageSource.isResource() ? imageSource.getUri() : imageSource.getGlideUrl()
)
.apply(FastImageViewConverter.getOptions(activity, imageSource, source))
.addListener(new RequestListener<Drawable>() {
@Override
public boolean onLoadFailed(@Nullable GlideException e, Object o, Target<Drawable> target, boolean b) {
if (canIssuePromise) {
onSizeDetermined.reject(e.getMessage());
}
return false;
}
@Override
public boolean onResourceReady(Drawable drawable, Object o, Target<Drawable> target, DataSource dataSource, boolean b) {
if (!canIssuePromise) return false;
final int w = drawable.getIntrinsicWidth();
final int h = drawable.getIntrinsicHeight();
final WritableMap map = new WritableNativeMap();
map.putInt("width", w);
map.putInt("height", h);
onSizeDetermined.resolve(map);
return false;
}
})
.preload();
}
}
});
}
@ReactMethod
public void clearMemoryCache(final Promise promise) {
final Activity activity = getCurrentActivity();
if (activity == null) {
promise.resolve(null);
return;
}
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
Glide.get(activity.getApplicationContext()).clearMemory();
promise.resolve(null);
}
});
}
@ReactMethod
public void clearDiskCache(Promise promise) {
final Activity activity = getCurrentActivity();
if (activity == null) {
promise.resolve(null);
return;
}
Glide.get(activity.getApplicationContext()).clearDiskCache();
promise.resolve(null);
}
}
| 39.608 | 152 | 0.533428 |
5f53f14e484761c6484c752cba400b2445aca963 | 2,106 | // This file is auto-generated, don't edit it. Thanks.
package com.antgroup.antchain.openapi.baasdt.models;
import com.aliyun.tea.*;
public class SetIpOrdergoodsidRequest extends TeaModel {
// OAuth模式下的授权token
@NameInMap("auth_token")
public String authToken;
@NameInMap("product_instance_id")
public String productInstanceId;
// 基础请求参数
@NameInMap("base_request")
@Validation(required = true)
public BaseRequestInfo baseRequest;
// 订单ID
@NameInMap("ip_order_id")
@Validation(required = true)
public String ipOrderId;
// 要绑定的商品信息
@NameInMap("goods_info_list")
@Validation(required = true)
public java.util.List<IPOrderGoods> goodsInfoList;
public static SetIpOrdergoodsidRequest build(java.util.Map<String, ?> map) throws Exception {
SetIpOrdergoodsidRequest self = new SetIpOrdergoodsidRequest();
return TeaModel.build(map, self);
}
public SetIpOrdergoodsidRequest setAuthToken(String authToken) {
this.authToken = authToken;
return this;
}
public String getAuthToken() {
return this.authToken;
}
public SetIpOrdergoodsidRequest setProductInstanceId(String productInstanceId) {
this.productInstanceId = productInstanceId;
return this;
}
public String getProductInstanceId() {
return this.productInstanceId;
}
public SetIpOrdergoodsidRequest setBaseRequest(BaseRequestInfo baseRequest) {
this.baseRequest = baseRequest;
return this;
}
public BaseRequestInfo getBaseRequest() {
return this.baseRequest;
}
public SetIpOrdergoodsidRequest setIpOrderId(String ipOrderId) {
this.ipOrderId = ipOrderId;
return this;
}
public String getIpOrderId() {
return this.ipOrderId;
}
public SetIpOrdergoodsidRequest setGoodsInfoList(java.util.List<IPOrderGoods> goodsInfoList) {
this.goodsInfoList = goodsInfoList;
return this;
}
public java.util.List<IPOrderGoods> getGoodsInfoList() {
return this.goodsInfoList;
}
}
| 28.08 | 98 | 0.695632 |
74489a6a3f43025127283d80bb133e834c4d7418 | 1,587 | package com.figueiras.photocontest.backend.rest.dtos;
import com.figueiras.photocontest.backend.model.entities.Horarios;
import java.util.List;
public class ListaHorariosPorElevador {
private List<Horarios> horariosElevador1;
private List<Horarios> horariosElevador2;
private List<Horarios> horariosElevador3;
private List<Horarios> horariosElevador4;
private List<Horarios> horariosElevador5;
public ListaHorariosPorElevador() {
}
public List<Horarios> getHorariosElevador1() {
return horariosElevador1;
}
public void setHorariosElevador1(List<Horarios> horariosElevador1) {
this.horariosElevador1 = horariosElevador1;
}
public List<Horarios> getHorariosElevador2() {
return horariosElevador2;
}
public void setHorariosElevador2(List<Horarios> horariosElevador2) {
this.horariosElevador2 = horariosElevador2;
}
public List<Horarios> getHorariosElevador3() {
return horariosElevador3;
}
public void setHorariosElevador3(List<Horarios> horariosElevador3) {
this.horariosElevador3 = horariosElevador3;
}
public List<Horarios> getHorariosElevador4() {
return horariosElevador4;
}
public void setHorariosElevador4(List<Horarios> horariosElevador4) {
this.horariosElevador4 = horariosElevador4;
}
public List<Horarios> getHorariosElevador5() {
return horariosElevador5;
}
public void setHorariosElevador5(List<Horarios> horariosElevador5) {
this.horariosElevador5 = horariosElevador5;
}
}
| 27.362069 | 72 | 0.729049 |
44959e781bd68cb239bbf6420c6767378fff7dbc | 2,165 | package com.example.android_thread;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class RunExample extends AppCompatActivity implements View.OnClickListener{
TextView textViewRun, textViewRunResult;
Button buttonRunStart;
ProgressDialog progressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_run_example);
textViewRun = (TextView) findViewById(R.id.textViewRun);
textViewRunResult = (TextView) findViewById(R.id.textViewRunResult);
buttonRunStart = (Button) findViewById(R.id.buttonRunStart);
buttonRunStart.setOnClickListener(this);
}
@Override
public void onClick(View view) {
RunTask();
}
private void RunTask() {
progressDialog = new ProgressDialog(RunExample.this);
progressDialog.setMax(10);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.show();
new Thread(new Runnable() {
@Override
public void run() {
int i = 0;
while (i <= 10) {
int Progress = i;
try {
Thread.sleep(1500);
i++;
} catch (InterruptedException e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
@Override
public void run() {
progressDialog.setProgress(Progress);
}
});
}
runOnUiThread(new Runnable() {
@Override
public void run() {
textViewRunResult.setText("Download Complete");
progressDialog.hide();
}
});
}
}).start();
}
} | 33.307692 | 82 | 0.546882 |
2b09948044d8af50127fef12132d2dfd69dc3767 | 623 | package com.hcl.sql.postgresql.connection;
import java.sql.Connection;
import java.sql.DriverManager;
import com.hcl.sql.postgresql.constants.AppConstants;
public class ConnectionFactory {
public static Connection getConnection() {
Connection conn = null;
try {
Class.forName(AppConstants.DriverClass);
conn = DriverManager.getConnection(AppConstants.JDBCurl, AppConstants.DBUserID, AppConstants.DBPaassword);
} catch (Exception e) {
e.printStackTrace();
System.err.println(e.getClass().getName() + ": " + e.getMessage());
}
System.out.println("Opened database successfully");
return conn;
}
}
| 27.086957 | 109 | 0.751204 |
ab38212a481c28a011fcdef5e54d0de4b64a318c | 6,970 | package dao;
import entity.Sesion;
import java.sql.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class SesionMySQLFactoryDAO implements SesionDAO {
private Connection connection = null;
private Statement stmt = null;
public SesionMySQLFactoryDAO() {
this.connection = new util.Connection().getConnection();
}
@Override
public int insertar(Sesion sesion) throws Exception {
PreparedStatement ps = null;
int last = 0;
try {
ps = this.connection.prepareStatement("INSERT INTO sesion VALUES (NULL, ?,?,?,?,?,?,?)"
, Statement.RETURN_GENERATED_KEYS);
ps.setTimestamp(1, new java.sql.Timestamp(sesion.getFecha_creacion().getTime()));
ps.setTimestamp(2, new java.sql.Timestamp(sesion.getFecha_reunion().getTime()));
ps.setString(3, sesion.getEstado());
ps.setString(4, sesion.getLugar());
ps.setInt(5, sesion.getCodigo_paciente());
ps.setInt(6, sesion.getCodigo_psicologo());
ps.setInt(7, sesion.getDuracion());
ps.executeUpdate();
ResultSet rs = ps.getGeneratedKeys();
if (rs.next()) {
last = rs.getInt(1);
}
} catch (SQLException e) {
e.printStackTrace();
}
return last;
}
@Override
public List<Sesion> listar() throws Exception {
Connection connection = null;
PreparedStatement psmt = null;
ArrayList<Sesion> listado = new ArrayList<Sesion>();
try {
connection = this.connection;
psmt = connection.prepareStatement("SELECT * FROM sesion");
ResultSet rs = psmt.executeQuery();
while (rs.next()) {
Sesion sesion = new Sesion();
sesion.setCodigo_sesion(rs.getInt("codigo_sesion"));
sesion.setFecha_creacion(rs.getTimestamp("fecha_creacion"));
sesion.setFecha_reunion(rs.getTimestamp("fecha_reunion"));
sesion.setEstado(rs.getString("estado"));
sesion.setLugar(rs.getString("lugar"));
sesion.setCodigo_paciente(rs.getInt("codigo_paciente"));
sesion.setCodigo_psicologo(rs.getInt("codigo_psicologo"));
sesion.setDuracion(rs.getInt("duracion"));
listado.add(sesion);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return listado;
}
@Override
public int eliminar(int codigo) throws Exception {
PreparedStatement ps = null;
int valor;
try {
ps = this.connection.prepareStatement("DELETE FROM sesion WHERE codigo_sesion = ?");
ps.setInt(1, codigo);
valor = ps.executeUpdate();
if (valor > 0) {
//el valor se ha eliminado
return valor;
} else return 0;
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
@Override
public List<Sesion> buscar(Sesion sesion) throws Exception {
Connection connection = null;
PreparedStatement ps = null;
ArrayList<Sesion> listado = new ArrayList<Sesion>();
try {
connection = this.connection;
String sql = "SELECT * FROM sesion ";
ArrayList<String> params = new ArrayList<String>();
HashMap<String, String> map = new HashMap<>();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd");
if (sesion.getFecha_creacion() != null) {
map.put("fecha_creacion", df2.format(sesion.getFecha_creacion()) );
}
if (sesion.getFecha_reunion() != null) {
map.put("fecha_reunion", df2.format(sesion.getFecha_reunion()) );
}
if (sesion.getEstado() != null) {
map.put("estado", sesion.getEstado() );
}
if (sesion.getLugar() != null) {
map.put("lugar", sesion.getLugar());
}
if (sesion.getCodigo_paciente() != 0) {
map.put("codigo_paciente", String.valueOf(sesion.getCodigo_paciente()));
}
if (sesion.getCodigo_psicologo() != 0) {
map.put("codigo_psicologo", String.valueOf(sesion.getCodigo_psicologo()));
}
if (sesion.getDuracion() != 0) {
map.put("duracion", String.valueOf(sesion.getDuracion()));
}
for (String param : map.keySet()) {
if(param.contains("codigo")){
params.add(param + " = ?");
}else{
params.add(param + " LIKE ?");
}
}
String[] arrParams = new String[params.size()];
arrParams = params.toArray(arrParams);
if (arrParams.length > 0) {
sql += " WHERE ";
sql += String.join(" AND ", arrParams);
}
sql +=" ORDER BY fecha_reunion ASC";
System.out.printf(sql);
ps = connection.prepareStatement(sql);
if (arrParams.length > 0) {
int index = 1;
for (Map.Entry<String, String> entry : map.entrySet()) {
if(entry.getKey().contains("codigo")){
ps.setString(index, entry.getValue());
}else{
ps.setString(index, "%" + entry.getValue() + "%");
}
index++;
}
}
ResultSet rs = ps.executeQuery();
while (rs.next()) {
Sesion s = new Sesion();
s.setCodigo_sesion(rs.getInt("codigo_sesion"));
s.setFecha_creacion(rs.getTimestamp("fecha_creacion"));
s.setFecha_reunion(rs.getTimestamp("fecha_reunion"));
s.setEstado(rs.getString("estado"));
s.setLugar(rs.getString("lugar"));
s.setCodigo_paciente(rs.getInt("codigo_paciente"));
s.setCodigo_psicologo(rs.getInt("codigo_psicologo"));
s.setDuracion(rs.getInt("duracion"));
listado.add(s);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
return listado;
}
}
}
| 32.877358 | 99 | 0.521234 |
c7e6acb81ef425dae29a4f289a635d020ba39461 | 4,040 | package org.wikipedia.page.database;
import android.content.Context;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.wikipedia.WikipediaApp;
import org.wikipedia.database.Database;
import org.wikipedia.page.notes.Article;
import org.wikipedia.page.notes.Note;
import org.wikipedia.page.notes.database.ArticleNoteDbHelper;
import java.util.ArrayList;
import java.util.List;
import static android.support.test.InstrumentationRegistry.getInstrumentation;
import static junit.framework.Assert.assertNotNull;
import static junit.framework.Assert.assertNotSame;
import static junit.framework.Assert.assertNull;
import static junit.framework.TestCase.assertEquals;
/**
* Created by amawai on 29/03/18.
*/
public class ArticleNoteDbHelperTest {
Context mContext;
Database database;
ArticleNoteDbHelper dbHelper;
Note note;
Article article;
String ARTICLE_TITLE = "Apple";
int UPDATED_SCROLL_STATE = 500;
String NOTE_TITLE = "Note title";
String NOTE_CONTENT = "Note content";
String UPDATED_NOTE_TITLE = "UPDATE title";
String UPDATED_NOTE_CONTENT = "UPDATED content";
@Before
public void setUp(){
mContext = getInstrumentation().getContext();
database = WikipediaApp.getInstance().getDatabase();
dbHelper = ArticleNoteDbHelper.instance();
//Most of the following tests use the article and note that has been created and added to the db here
article = dbHelper.createArticle(ARTICLE_TITLE, 0);
note = dbHelper.createNote(article, NOTE_CONTENT);
article.setNote(note);
}
@Test
public void shouldRetrieveCreateArticle() {
List<Article> articles = dbHelper.getAllArticles();
Article createdArticle = articles.get(0);
assertEquals(articles.size(), 1);
assertEquals(ARTICLE_TITLE, createdArticle.getArticleTitle());
assertEquals(0, createdArticle.getScrollPosition());
}
@Test
public void shouldNotCreateArticleIfArticleExistsAlready() {
//Makes sure that createArticle checks if the article has already been added
assertNull(dbHelper.createArticle(ARTICLE_TITLE,0));
}
@Test
public void shouldUpdateScrollState(){
article.setScroll(UPDATED_SCROLL_STATE);
dbHelper.updateScrollState(article);
int updatedScroll = dbHelper.getScrollOfArticle(article);
assertEquals(UPDATED_SCROLL_STATE, updatedScroll);
}
@Test
public void shouldRetrieveNoteAssociatedToArticle() {
Note addedNote = dbHelper.getNotesFromArticle(article);
assertEquals(NOTE_CONTENT, addedNote.getNoteContent());
}
@Test
public void shouldUpdateNote() {
note.setNoteContent(UPDATED_NOTE_CONTENT);
dbHelper.updateArticleNote(article);
Note updatedNote = dbHelper.getNotesFromArticle(article);
assertEquals(UPDATED_NOTE_CONTENT, updatedNote.getNoteContent());
}
@Test
public void shouldOnlyRetrieveNotesRelatedToSpecificArticle() {
Article otherArticle= dbHelper.createArticle("Not apple", 0);
dbHelper.createNote(otherArticle, "desc1");
//Retrieve and store notes based on article
Note articleNote = dbHelper.getNotesFromArticle(article);
Note otherArticleNote = dbHelper.getNotesFromArticle(otherArticle);
//Ensure that the retrived notes are only associated to one article
assertNotNull(articleNote);
assertNotSame(articleNote, otherArticleNote);
}
@Test
public void shouldDeleteNoteAssociatedToArticle(){
dbHelper.deleteArticleNote(article);
Note articleNote = dbHelper.getNotesFromArticle(article);
//Ensure that the note associated to the article is gone
assertNull(articleNote);
}
@After
public void closeDb(){
//Close and delete the database that was used for testing
database.close();
WikipediaApp.getInstance().deleteDatabase(database.getDatabaseName());
}
}
| 33.114754 | 109 | 0.72203 |
86066a5dba9776bfa9ed7224e33583b747b922e9 | 753 | package com.packtpub.wflydevelopment.chapter3.boundary;
import com.packtpub.wflydevelopment.chapter3.control.TheatreBox;
import com.packtpub.wflydevelopment.chapter3.entity.Seat;
import javax.ejb.EJB;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import java.util.Collection;
@Stateless
@Remote(TheatreInfoRemote.class)
public class TheatreInfo implements TheatreInfoRemote {
@EJB
private TheatreBox box;
@Override
public String printSeatList() {
final Collection<Seat> seats = box.getSeats();
final StringBuilder sb = new StringBuilder();
for (Seat seat : seats) {
sb.append(seat.toString());
sb.append(System.lineSeparator());
}
return sb.toString();
}
}
| 25.965517 | 64 | 0.706507 |
21ff87a4de6925dbdf782cc48ca3cd5df93a0285 | 3,638 | package fluidpirates.fluidpirates_android;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.app.Activity;
import android.content.Intent;
import android.widget.Toast;
import org.json.JSONObject;
import models.Params;
import utils.PostJsonObjectAsync;
public class LoginActivity extends Activity {
// 10.0.2.2 is localhost in the android emulator
private static final String LOGIN_URL = "https://fluidpirates.com/api/sessions";
private static final String REGISTER_URL = "https://fluidpirates.com/api/users";
private static final String TAG = "LoginActivity";
public static final String PREFS_NAME = "FluidPiratesPreferences";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Button loginButton = (Button) findViewById(R.id.login_button); //waiting clic on loginButton
loginButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
sendLoginRequest();
}
});
Button registerButton = (Button) findViewById(R.id.login_register_button); //waiting clic on RegisterButton
registerButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
sendRegisterRequest();
}
});
}
protected void onLoginSuccess() {
Intent intent = new Intent(this, GroupsActivity.class);
startActivity(intent);
}
private void sendLoginRequest() {
Params params = new Params();
params.put("session[email]", ((EditText) findViewById(R.id.login_email_field)).getText().toString());
params.put("session[password]", ((EditText) findViewById(R.id.login_password_field)).getText().toString());
//Ouverture de session
(new FetchToken(this, params)).execute(LOGIN_URL);
}
private void sendRegisterRequest() {
Params params = new Params();
params.put("user[email]", ((EditText) findViewById(R.id.login_email_field)).getText().toString());
params.put("user[password]", ((EditText) findViewById(R.id.login_password_field)).getText().toString());
//Création de session
(new FetchToken(this, params)).execute(REGISTER_URL);
}
private class FetchToken extends PostJsonObjectAsync {
public FetchToken(Context context, Params params) {
super(context, params);
}
@Override
protected void onPostExecute(JSONObject json) { //Utilisation d'une bibliothèque de connexion asynchrone.
try {
Log.d(TAG, json.toString());
String token = json.getString("token");
if (token.length() > 0) {
SharedPreferences.Editor editor = getSharedPreferences(PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("token", json.getString("token"));
editor.commit();
Intent intent = new Intent(LoginActivity.this, GroupsActivity.class);
startActivity(intent);
}
} catch (Exception e) {
Toast.makeText(context, e.getMessage(), Toast.LENGTH_LONG).show();
} finally {
super.onPostExecute(json);
}
}
}
}
| 34.647619 | 115 | 0.646234 |
48286dbefacdec706da6a17434b955f05fc22035 | 579 | package com.tvd12.ezyfox.exception;
import lombok.Getter;
@Getter
public class EzyObjectGetException extends IllegalArgumentException {
private static final long serialVersionUID = -5250894414568092276L;
protected final Object key;
protected final Object value;
protected final Class<?> outType;
public EzyObjectGetException(
Object key, Object value, Class<?> outType, Exception e) {
super("can't transform value: " + value + " of key: " + key + " with outType: " + outType.getName(), e);
this.key = key;
this.value = value;
this.outType = outType;
}
}
| 26.318182 | 106 | 0.728843 |
ae9e98562dd847cae55dbd140b4e6f200bc9e824 | 293 | package org.raku.nqp.io;
import org.raku.nqp.runtime.ThreadContext;
import org.raku.nqp.sixmodel.SixModelObject;
public interface IIOAsyncWritable {
void spurt(ThreadContext tc, SixModelObject Str, SixModelObject data, SixModelObject done,
SixModelObject error);
}
| 29.3 | 94 | 0.750853 |
c911288af15748f9b2fdb3924a5c7b70ec089ebe | 2,547 | /*
* ***************************************************************************
* Copyright 2014-2019 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* ***************************************************************************
*/
package com.spectralogic.ds3cli.views.cli;
import com.bethecoder.ascii_table.ASCIITable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.spectralogic.ds3cli.models.GetObjectVersionsResult;
import com.spectralogic.ds3client.models.S3Object;
import java.util.ArrayList;
import java.util.List;
import static com.spectralogic.ds3cli.util.Constants.DATE_FORMAT;
import static com.spectralogic.ds3cli.util.Guard.nullGuard;
import static com.spectralogic.ds3cli.util.Guard.nullGuardFromDate;
public class GetObjectVersionsView extends TableView<GetObjectVersionsResult> {
private Iterable<S3Object> versions;
@Override
public String render(final GetObjectVersionsResult result) {
versions = result.getResult();
if (versions == null || Iterables.isEmpty(versions)) {
return "Could not find any versions.";
}
initTable(ImmutableList.of("Bucket Id", "Name", "Creation Date", "Latest", "Version Id"));
return ASCIITable.getInstance().getTable(getHeaders(), formatTableContents());
}
@Override
protected String[][] formatTableContents() {
final List<String[]> contents = new ArrayList<>();
for (final S3Object version : versions) {
final String[] arrayEntry = new String[this.columnCount];
arrayEntry[0] = nullGuard(version.getId());
arrayEntry[1] = nullGuard(version.getName());
arrayEntry[2] = nullGuardFromDate(version.getCreationDate(), DATE_FORMAT);
arrayEntry[3] = nullGuard(version.getLatest());
arrayEntry[4] = nullGuard(version.getBucketId());
contents.add(arrayEntry);
}
return contents.toArray(new String[contents.size()][]);
}
}
| 39.184615 | 98 | 0.664311 |
f0b1626c7d183fa20ff12a51f1406e7be1198bdd | 3,319 | package com.wjx.android.wanandroidmvp.presenter.project;
import com.wjx.android.wanandroidmvp.base.presenter.BasePresenter;
import com.wjx.android.wanandroidmvp.bean.db.ProjectClassify;
import com.wjx.android.wanandroidmvp.bean.project.ProjectClassifyData;
import com.wjx.android.wanandroidmvp.contract.project.Contract;
import com.wjx.android.wanandroidmvp.model.ProjectModel;
import java.util.List;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
/**
* Created with Android Studio.
* Description:
*
* @author: Wangjianxian
* @date: 2019/12/27
* Time: 14:57
*/
public class ProjectPresenter extends BasePresenter<Contract.IProjectView> implements Contract.IProjectPresenter {
Contract.IProjectModel iProjectModel;
public ProjectPresenter() {
iProjectModel = new ProjectModel();
}
@Override
public void loadProjectClassify() {
iProjectModel.loadProjectClassify()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<List<ProjectClassify>>() {
@Override
public void onSubscribe(Disposable d) {
mCompositeDisposable.add(d);
}
@Override
public void onNext(List<ProjectClassify> projectClassify) {
if (isViewAttached()) {
getView().onLoadProjectClassify(projectClassify);
getView().onLoadSuccess();
}
}
@Override
public void onError(Throwable e) {
e.printStackTrace();
if (isViewAttached()) {
getView().onLoadFailed();
}
}
@Override
public void onComplete() {
}
});
}
@Override
public void refreshProjectClassify() {
iProjectModel.refreshProjectClassify()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<List<ProjectClassify>>() {
@Override
public void onSubscribe(Disposable d) {
mCompositeDisposable.add(d);
}
@Override
public void onNext(List<ProjectClassify> projectClassify) {
if (isViewAttached()) {
getView().onRefreshProjectClassify(projectClassify);
getView().onLoadSuccess();
}
}
@Override
public void onError(Throwable e) {
e.printStackTrace();
if (isViewAttached()) {
getView().onLoadFailed();
}
}
@Override
public void onComplete() {
}
});
}
}
| 33.525253 | 114 | 0.520337 |
ba5507ce95ac1aa7c9bbf7a511298b814fb8fe02 | 4,043 | /**
* Copyright Microsoft Corporation
*
* 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.microsoft.windowsazure.services.media.implementation;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Date;
import javax.inject.Named;
import javax.management.timer.Timer;
import com.microsoft.windowsazure.core.utils.DateFactory;
import com.microsoft.windowsazure.exception.ServiceException;
import com.microsoft.windowsazure.services.media.MediaConfiguration;
/**
* An OAuth token manager class.
*
*/
public class OAuthTokenManager {
private final DateFactory dateFactory;
private final URI acsBaseUri;
private final String clientId;
private final String clientSecret;
private final OAuthContract contract;
private ActiveToken activeToken;
private final String scope;
/**
* Creates an OAuth token manager instance with specified contract, date
* factory, ACS base URI, client ID, and client secret.
*
* @param contract
* A <code>OAuthContract</code> object instance that represents
* the OAUTH contract.
*
* @param dateFactory
* A <code>DateFactory</code> object instance that represents the
* date factory.
*
* @param oAuthUri
* A <code>String</code> object instance that represents the ACS
* base URI.
*
* @param clientId
* A <code>String</code> object instance that represents the
* client ID.
*
* @param clientSecret
* A <code>String</code> object instance that represents the
* client secret.
* @throws URISyntaxException
*
*/
public OAuthTokenManager(OAuthContract contract, DateFactory dateFactory,
@Named(MediaConfiguration.OAUTH_URI) String oAuthUri,
@Named(MediaConfiguration.OAUTH_CLIENT_ID) String clientId,
@Named(MediaConfiguration.OAUTH_CLIENT_SECRET) String clientSecret,
@Named(MediaConfiguration.OAUTH_SCOPE) String scope)
throws URISyntaxException {
this.contract = contract;
this.dateFactory = dateFactory;
this.acsBaseUri = new URI(oAuthUri);
this.clientId = clientId;
this.clientSecret = clientSecret;
this.scope = scope;
this.activeToken = null;
}
/**
* Gets an OAuth access token with specified media service scope.
*
* @param mediaServiceScope
* A <code>String</code> instance that represents the media
* service scope.
*
* @return String
*
* @throws ServiceException
* @throws URISyntaxException
*/
public String getAccessToken() throws ServiceException, URISyntaxException {
Date now = dateFactory.getDate();
if (this.activeToken == null
|| now.after(this.activeToken.getExpiresUtc())) {
OAuthTokenResponse oAuth2TokenResponse = contract.getAccessToken(
acsBaseUri, clientId, clientSecret, scope);
Date expiresUtc = new Date(now.getTime()
+ oAuth2TokenResponse.getExpiresIn() * Timer.ONE_SECOND / 2);
ActiveToken newToken = new ActiveToken();
newToken.setAccessToken(oAuth2TokenResponse.getAccessToken());
newToken.setExpiresUtc(expiresUtc);
this.activeToken = newToken;
}
return this.activeToken.getAccessToken();
}
}
| 35.778761 | 81 | 0.658917 |
acc3e834d81368c7e46f441fc6fbff31713641ac | 2,974 | /*
* Copyright 2020 Arne Limburg
*
* 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.microjpa;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
import java.lang.reflect.ParameterizedType;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.spi.CDI;
import javax.inject.Inject;
import javax.persistence.PersistenceUnit;
import org.apache.deltaspike.cdise.api.ContextControl;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.microjpa.child.AbstractChildRepository;
import org.microjpa.child.TestChild;
import org.microjpa.parent.AbstractParentRepository;
import org.microjpa.parent.TestParent;
import org.microjpa.relation.AbstractRelationService;
import org.microjpa.relation.Relation;
@PersistenceUnit(unitName = "unknown")
abstract class AbstractPersistenceUnitTest
<S extends AbstractRelationService<P, C>, P extends AbstractParentRepository, C extends AbstractChildRepository> {
@Inject
private ContextControl contextControl;
protected S testService;
protected C testChildRepository;
protected long parentId;
@BeforeEach
public void startCdi() {
contextControl.startContext(RequestScoped.class);
ParameterizedType genericSuperclass = (ParameterizedType)getClass().getGenericSuperclass();
testService = CDI.current().select((Class<S>)genericSuperclass.getActualTypeArguments()[0]).get();
testChildRepository = CDI.current().select((Class<C>)genericSuperclass.getActualTypeArguments()[2]).get();
TestChild testChild = new TestChild(new TestParent());
testService.persist(testChild);
parentId = testChild.getParent().getId();
contextControl.stopContext(RequestScoped.class);
}
@Test
@DisplayName("found parent equals parent of found child (same EntityManager is used)")
void find() {
Relation parentAndChild = testService.findParentAndChild(parentId);
assertSame(parentAndChild.getChild().getParent(), parentAndChild.getParent());
}
@Test
@DisplayName("persist joins to transaction after find")
void persist() {
testService.findParentAndChild(parentId);
testService.persist(new TestChild());
testChildRepository.clear();
assertEquals(2, testChildRepository.findAll().size());
}
}
| 36.268293 | 118 | 0.754539 |
3f5afcd0d55b8851af0f18f58ee6f0a3de67642f | 159 | package org.acme;
import java.util.List;
/**
* BookRepository
*/
public interface BookRepository {
Book save(Book book);
List<Book> listAll();
} | 11.357143 | 33 | 0.666667 |
18d2bf88efae2bbfe8b423ab59612502df35d195 | 1,973 | package cn.lee.leetcode.probolems.g0;
import java.util.ArrayList;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.junit.Assert;
import org.junit.Test;
/**
* @Title: Q68
* @Description: https://leetcode-cn.com/problems/text-justification/
* @author: libo
* @date: 2021/9/9 13:53
* @Version: 1.0
*/
@Slf4j
public class Q68 {
@Test
public void test1() {
Assert.assertArrayEquals(new String[]{"This is an",
"example of text",
"justification. "}, fullJustify(new String[]{"This", "is", "an", "example", "of", "text", "justification."}, 16).toArray());
}
@Test
public void test2() {
Assert.assertArrayEquals(new String[]{"What must be",
"acknowledgment ",
"shall be "}, fullJustify(new String[]{"What", "must", "be", "acknowledgment", "shall", "be"}, 16).toArray());
}
@Test
public void test3() {
Assert.assertArrayEquals(new String[]{
"Science is what we",
"understand well",
"enough to explain to",
"a computer. Art is",
"everything else we",
"do "},
fullJustify(new String[]{"Science", "is", "what", "we", "understand", "well",
"enough", "to", "explain", "to", "a", "computer.", "Art", "is", "everything", "else", "we", "do"},
20).toArray());
}
public List<String> fullJustify(String[] words, int maxWidth) {
List<String> res = new ArrayList<>();
List<String> line = new ArrayList<>();
int width = 0;
for (int i = 0; i < words.length; i++) {
if (maxWidth < (width + words[i].length() + line.size())) {
//最大
StringBuilder sb = new StringBuilder();
String seq = "";
for (String str : line) {
sb.append(seq).append(str);
seq = " ";
}
res.add(sb.toString());
line = new ArrayList<>();
line.add(words[i]);
width = words[i].length();
log.info(sb.toString());
} else {
width += words[i].length();
line.add(words[i]);
}
}
return res;
}
}
| 27.027397 | 129 | 0.580841 |
75e279c03ec17283df9a3771c623cb40a9cf0c82 | 5,197 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.datatorrent.demos.frauddetect;
import java.io.Serializable;
/**
* POJO for BIN Alert related data.
*
* @since 0.9.0
*/
public class MerchantTransaction implements Serializable
{
public enum MerchantType
{
UNDEFINED, BRICK_AND_MORTAR, INTERNET
}
public enum TransactionType
{
UNDEFINED, POS
}
public String ccNum;
public String bankIdNum;
public String fullCcNum;
public Long amount;
public String merchantId;
public Integer terminalId;
public Integer zipCode;
public String country;
public MerchantType merchantType = MerchantType.UNDEFINED;
public TransactionType transactionType = TransactionType.UNDEFINED;
public Long time;
public boolean userGenerated;
public MerchantTransaction()
{
}
@Override
public int hashCode()
{
int key = 0;
if (ccNum != null) {
key |= (1 << 1);
key |= (ccNum.hashCode());
}
if (bankIdNum != null) {
key |= (1 << 2);
key |= (bankIdNum.hashCode());
}
if (amount != null) {
key |= (1 << 6);
key |= (amount << 4);
}
if (merchantId != null) {
key |= (1 << 3);
key |= (merchantId.hashCode());
}
if (terminalId != null) {
key |= (1 << 4);
key |= (terminalId << 2);
}
if (zipCode != null) {
key |= (1 << 5);
key |= (zipCode << 3);
}
if (country != null) {
key |= (1 << 7);
key |= (country.hashCode());
}
if (merchantType != null) {
key |= (1 << 8);
key |= (merchantType.hashCode());
}
if (transactionType != null) {
key |= (1 << 9);
key |= (transactionType.hashCode());
}
if (fullCcNum != null) {
key |= (1 << 10);
key |= (fullCcNum.hashCode());
}
if (time != null) {
key |= (1 << 11);
key |= (time << 2);
}
return key;
}
@Override
public boolean equals(Object obj)
{
if (!(obj instanceof MerchantTransaction)) {
return false;
}
MerchantTransaction mtx = (MerchantTransaction)obj;
return checkStringEqual(this.ccNum, mtx.ccNum)
&& checkStringEqual(this.bankIdNum, mtx.bankIdNum)
&& checkLongEqual(this.amount, mtx.amount)
&& checkStringEqual(this.merchantId, mtx.merchantId)
&& checkIntEqual(this.terminalId, mtx.terminalId)
&& checkIntEqual(this.zipCode, mtx.zipCode)
&& checkStringEqual(this.country, mtx.country)
&& checkIntEqual(this.merchantType.ordinal(), mtx.merchantType.ordinal())
&& checkIntEqual(this.transactionType.ordinal(), mtx.transactionType.ordinal())
&& checkStringEqual(this.fullCcNum, mtx.fullCcNum)
&& checkLongEqual(this.time, mtx.time);
}
private boolean checkIntEqual(Integer a, Integer b)
{
if ((a == null) && (b == null)) {
return true;
}
if ((a != null) && (b != null) && a.intValue() == b.intValue()) {
return true;
}
return false;
}
private boolean checkLongEqual(Long a, Long b)
{
if ((a == null) && (b == null)) {
return true;
}
if ((a != null) && (b != null) && a.longValue() == b.longValue()) {
return true;
}
return false;
}
private boolean checkStringEqual(String a, String b)
{
if ((a == null) && (b == null)) {
return true;
}
if ((a != null) && a.equals(b)) {
return true;
}
return false;
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
if (ccNum != null) {
sb.append("|0:").append(ccNum);
}
if (bankIdNum != null) {
sb.append("|1:").append(bankIdNum);
}
if (fullCcNum != null) {
sb.append("|2:").append(fullCcNum);
}
if (amount != null) {
sb.append("|3:").append(amount);
}
if (merchantId != null) {
sb.append("|4:").append(merchantId);
}
if (terminalId != null) {
sb.append("|5:").append(terminalId);
}
if (zipCode != null) {
sb.append("|6:").append(zipCode);
}
if (country != null) {
sb.append("|7:").append(country);
}
if (merchantType != null) {
sb.append("|8:").append(merchantType);
}
if (transactionType != null) {
sb.append("|9:").append(transactionType);
}
if (time != null) {
sb.append("|10:").append(time);
}
return sb.toString();
}
}
| 25.600985 | 91 | 0.584183 |
e487503b3a9e75026c64d77c2a4f2748e93d38d0 | 1,965 | package com.appgallabs.cloudmlplatform.datascience.model;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Serializable;
import java.util.Objects;
public class Label implements Serializable {
private static Logger logger = LoggerFactory.getLogger(Label.class);
private String value;
private String field;
public Label() {
}
public Label(String value, String field) {
this.value = value;
this.field = field;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getField() {
return field;
}
public void setField(String field) {
this.field = field;
}
public JsonObject toJson(){
JsonObject json = new JsonObject();
if(this.value != null){
json.addProperty("value",this.value);
}
if(this.field != null){
json.addProperty("field",this.field);
}
return json;
}
public static Label parse(String jsonString){
Label label = new Label();
JsonObject json = JsonParser.parseString(jsonString).getAsJsonObject();
if(json.has("value")){
label.value = json.get("value").getAsString();
}
if(json.has("field")){
label.field = json.get("field").getAsString();
}
return label;
}
@Override
public String toString() {
return this.toJson().toString();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Label label = (Label) o;
return value.equals(label.value) && field.equals(label.field);
}
@Override
public int hashCode() {
return Objects.hash(value, field);
}
}
| 22.329545 | 79 | 0.597455 |
30654342c48c9764b3d51a362f1e76f75e085619 | 9,171 | package com.queryflow.accessor.runner;
import com.queryflow.accessor.handler.ResultSetHandler;
import com.queryflow.accessor.interceptor.InterceptorHelper;
import com.queryflow.accessor.interceptor.Interceptors;
import com.queryflow.utils.JdbcUtil;
import com.queryflow.utils.Utils;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class BaseSqlRunner extends AbstractSqlRunner {
@Override
public <T> T query(Connection conn, String sql, List<Object> params, Interceptors interceptors,
ResultSetHandler<T> handler) throws SQLException {
check(conn, sql);
PreparedStatement ps = null;
ResultSet rs = null;
T result = null;
try {
ps = this.prepareStatement(conn, sql, null, interceptors, false);
this.fillStatement(ps, params);
if (!InterceptorHelper.before(interceptors, ps)) {
return null;
}
rs = ps.executeQuery();
InterceptorHelper.after(interceptors, ps);
if (handler != null) {
result = handler.handle(rs);
}
} catch (SQLException e) {
throw new SQLException(buildErrorMessage(e, sql, params), e.getSQLState(), e.getErrorCode());
} finally {
JdbcUtil.close(rs, ps);
}
return result;
}
@Override
public int update(Connection conn, String sql, List<Object> params, Interceptors interceptors) throws SQLException {
check(conn, sql);
PreparedStatement ps = null;
int rows;
try {
ps = this.prepareStatement(conn, sql, null, interceptors, false);
this.fillStatement(ps, params);
if (!InterceptorHelper.before(interceptors, ps)) {
return 0;
}
rows = ps.executeUpdate();
InterceptorHelper.after(interceptors, ps);
} catch (SQLException e) {
throw new SQLException(buildErrorMessage(e, sql, params), e.getSQLState(), e.getErrorCode());
} finally {
JdbcUtil.close(ps);
}
return rows;
}
@Override
public <T> T insertGetKey(Connection conn, String sql, List<Object> params,
String[] keyColumnNames,
Interceptors interceptors,
ResultSetHandler<T> handler) throws SQLException {
check(conn, sql);
PreparedStatement ps = null;
ResultSet rs = null;
T result = null;
try {
ps = this.prepareStatement(conn, sql, keyColumnNames, interceptors, true);
this.fillStatement(ps, params);
if (!InterceptorHelper.before(interceptors, ps)) {
return null;
}
ps.execute();
InterceptorHelper.after(interceptors, ps);
if (handler != null) {
rs = ps.getGeneratedKeys();
result = handler.handle(rs);
}
} catch (SQLException e) {
throw new SQLException(buildErrorMessage(e, sql, params), e.getSQLState(), e.getErrorCode());
} finally {
JdbcUtil.close(rs, ps);
}
return result;
}
@Override
public <T> T batchInsertGetKeys(Connection conn, String sql, List<List<Object>> params,
String[] keyColumnNames,
Interceptors interceptors,
ResultSetHandler<T> handler) throws SQLException {
check(conn, sql);
if (params == null) {
params = new ArrayList<>(0);
}
PreparedStatement ps = null;
ResultSet rs = null;
T result = null;
try {
ps = prepareStatement(conn, sql, keyColumnNames, interceptors, true);
for (int i = 0, len = params.size(); i < len; i++) {
this.fillStatement(ps, params.get(i));
ps.addBatch();
}
if (!InterceptorHelper.before(interceptors, ps)) {
return null;
}
ps.executeBatch();
InterceptorHelper.after(interceptors, ps);
if (handler != null) {
rs = ps.getGeneratedKeys();
result = handler.handle(rs);
}
} catch (SQLException e) {
throw new SQLException(buildErrorMessage(e, sql, null), e.getSQLState(), e.getErrorCode());
} finally {
JdbcUtil.close(rs, ps);
}
return result;
}
@Override
public int[] batch(Connection conn, String sql, List<List<Object>> params, Interceptors interceptors)
throws SQLException {
check(conn, sql);
if (params == null) {
params = new ArrayList<>(0);
}
PreparedStatement ps = null;
int[] rows = new int[0];
try {
ps = this.prepareStatement(conn, sql, null, interceptors, false);
for (int i = 0, len = params.size(); i < len; i++) {
this.fillStatement(ps, params.get(i));
ps.addBatch();
}
if (!InterceptorHelper.before(interceptors, ps)) {
return rows;
}
rows = ps.executeBatch();
InterceptorHelper.after(interceptors, ps);
} catch (SQLException e) {
throw new SQLException(buildErrorMessage(e, sql, null), e.getSQLState(), e.getErrorCode());
} finally {
JdbcUtil.close(ps);
}
return rows;
}
@Override
public int[] batch(Connection conn, List<String> sqls, Interceptors interceptors) throws SQLException {
if (conn == null) {
throw new SQLException("the connection is null");
}
if (sqls == null || sqls.isEmpty()) {
throw new SQLException("sql statements is null");
}
Statement statement = null;
int[] rows = new int[0];
try {
statement = this.statement(conn, interceptors);
if (!InterceptorHelper.before(interceptors, statement)) {
return rows;
}
for (String sql : sqls) {
statement.addBatch(sql);
}
rows = statement.executeBatch();
InterceptorHelper.after(interceptors, statement);
} catch (SQLException e) {
throw new SQLException(buildErrorMessage(e, "", null), e.getSQLState(), e.getErrorCode());
} finally {
JdbcUtil.close(statement);
}
return rows;
}
@Override
public int call(Connection conn, String sql, List<Object> params, Interceptors interceptors) throws SQLException {
check(conn, sql);
CallableStatement cs = null;
int rows = 0;
try {
cs = this.prepareCall(conn, sql, interceptors);
if (!InterceptorHelper.before(interceptors, cs)) {
return rows;
}
this.fillStatement(cs, params);
rows = cs.executeUpdate();
InterceptorHelper.after(interceptors, cs);
this.setOutParameterValue(cs, params);
} catch (SQLException e) {
throw new SQLException(buildErrorMessage(e, sql, params), e.getSQLState(), e.getErrorCode());
} finally {
JdbcUtil.close(cs);
}
return rows;
}
@Override
public <T> T call(Connection conn, String sql, List<Object> params, Interceptors interceptors,
ResultSetHandler<T> handler) throws SQLException {
check(conn, sql);
CallableStatement cs = null;
ResultSet rs = null;
T result = null;
try {
cs = this.prepareCall(conn, sql, interceptors);
this.fillStatement(cs, params);
if (!InterceptorHelper.before(interceptors, cs)) {
return null;
}
cs.execute();
InterceptorHelper.after(interceptors, cs);
rs = cs.getResultSet();
if (handler != null) {
result = handler.handle(rs);
}
} catch (SQLException e) {
throw new SQLException(buildErrorMessage(e, sql, params), e.getSQLState(), e.getErrorCode());
} finally {
JdbcUtil.close(rs, cs);
}
return result;
}
private void check(Connection conn, String sql) throws SQLException {
if (conn == null) {
throw new SQLException("the connection is null");
}
if (Utils.isEmpty(sql)) {
throw new SQLException("sql sql is null");
}
}
private void setOutParameterValue(CallableStatement cs, List<Object> params) throws SQLException {
if (params != null) {
Object param;
for (int i = 0, len = params.size(); i < len; i++) {
param = params.get(i);
if (param instanceof OutParameter) {
((OutParameter) param).setValue(cs, i + 1);
}
}
}
}
}
| 34.738636 | 120 | 0.543779 |
9e0437e7452a0926b1ff75d6cf391d6d7641d43b | 219 | package com.javarush.task.task14.task1410;
/**
* Created by boltenkov on 03.01.2018.
*/
public class Wine extends Drink {
public String getHolidayName()
{
return "День Рождения";
}
}
| 16.846154 | 43 | 0.616438 |
9738e9f78c027fe470922baf6c40f5cd2a27da62 | 1,616 | package br.com.zupacademy.dani.transacao.transacao;
import br.com.zupacademy.dani.transacao.erros.ErroPadronizado;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.stream.Collectors;
@RestController
@RequestMapping("/transacoes")
public class TransacaoController {
@Autowired
private TransacaoRepository transacaoRepository;
@GetMapping("{numero}")
public ResponseEntity<?> buscarTransacoes (@PathVariable String numero,
@PageableDefault(sort = "efetivadaEm", direction = Sort.Direction.DESC, page = 0, size = 10) Pageable paginacao){
Page<Transacao> transacoes = transacaoRepository.findByCartaoNumero(numero, paginacao);
if (transacoes.isEmpty()){
return ResponseEntity.status(HttpStatus.NOT_FOUND)
.body(new ErroPadronizado(List.of("Não foram encontradas transações para este cartão")));
}
return ResponseEntity.ok((transacoes.stream().map(TransacaoResponse::new).collect(Collectors.toList())));
}
}
| 42.526316 | 152 | 0.764233 |
f49a6ba5d07042411a7bea5707defeed9f7c5884 | 1,299 | package pro.chenggang.plugin.springcloud.gateway.response.strategy;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import pro.chenggang.plugin.springcloud.gateway.option.ResponseResult;
import pro.chenggang.plugin.springcloud.gateway.option.SystemResponseInfo;
import pro.chenggang.plugin.springcloud.gateway.response.ExceptionHandlerResult;
/**
* Default ExceptionHandlerStrategy
* @author chenggang
* @date 2019/01/29
*/
@Slf4j
public class DefaultExceptionHandlerStrategy implements ExceptionHandlerStrategy {
@Override
public Class getHandleClass() {
return Throwable.class;
}
@Override
public ExceptionHandlerResult handleException(Throwable throwable) {
ResponseResult<String> responseResult = new ResponseResult<>(SystemResponseInfo.GATEWAY_ERROR,throwable.getMessage());
ExceptionHandlerResult result = new ExceptionHandlerResult(HttpStatus.INTERNAL_SERVER_ERROR, JSON.toJSONString(responseResult));
log.debug("[DefaultExceptionHandlerStrategy]Handle Exception:{},Result:{}",throwable.getMessage(),result);
log.error("[DefaultExceptionHandlerStrategy]Log Exception In Error Level,Exception Message:{}",throwable.getMessage());
return result;
}
}
| 40.59375 | 136 | 0.788299 |
228a9726f1edee50100a5831b18d8a9bbaf2055f | 7,269 | package org.sng.shortener;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jayway.jsonpath.JsonPath;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sng.shortener.controllers.ParamNames;
import org.sng.shortener.json.GetStatisticResponse;
import org.sng.shortener.model.AllowedRedirect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.sng.shortener.controllers.ParamNames.ACCOUNT_ID;
import static org.sng.shortener.controllers.PathMappings.ACCOUNT;
import static org.sng.shortener.controllers.PathMappings.REGISTER;
import static org.sng.shortener.controllers.PathMappings.STATISTIC;
import static org.sng.shortener.services.AccountService.PASSWORD_LENGTH;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
public class ApiControllerTest {
private static final String PASSWORD = "password";
private static final String SUCCESS = "success";
private static final String SHORT_URL = "shortUrl";
private static final String TEST_LONG_URL = "http://ya.ru";
private String newAccountId;
private static long accountCount;
@Autowired
private MockMvc mockMvc;
@Before
public void beforeTest() {
newAccountId = "acc" + accountCount++;
}
@Test
public void open_account() throws Exception {
Assert.assertTrue(createAccountOk(newAccountId).length() >= PASSWORD_LENGTH);
}
@Test
public void register_url() throws Exception {
String pass = createAccountOk(newAccountId);
new URL(shortenOk(newAccountId, pass, TEST_LONG_URL));
}
@Test
public void default_redirect_test() throws Exception {
String pass = createAccountOk(newAccountId);
URL shortUrl = new URL(shortenOk(newAccountId, pass, TEST_LONG_URL));
checkRedirect(TEST_LONG_URL, shortUrl, 302);
}
@Test
public void redirect_301_test() throws Exception {
String pass = createAccountOk(newAccountId);
int redirectType = AllowedRedirect.PERMANENTLY_301.getCode();
URL shortUrl = new URL(shortenOk(newAccountId, pass, TEST_LONG_URL, redirectType));
checkRedirect(TEST_LONG_URL, shortUrl, redirectType);
}
@Test
public void statistics_test() throws Exception {
String pass = createAccountOk(newAccountId);
Map<String, Long> expectedStats = new HashMap<>();
URL shortUrl = new URL(shortenOk(newAccountId, pass, TEST_LONG_URL));
int useRedirectCount = 5;
for (int i = 0; i < useRedirectCount; i++) {
checkRedirect(TEST_LONG_URL, shortUrl);
}
expectedStats.put(TEST_LONG_URL, (long)useRedirectCount);
String anotherLongUrl = "http://google.com";
URL anotherShortUrl = new URL(shortenOk(newAccountId, pass, anotherLongUrl));
checkRedirect(anotherLongUrl, anotherShortUrl);
expectedStats.put(anotherLongUrl, 1L);
Map<String, Long> realStats = fetchStats(newAccountId, pass);
assertThat(realStats.entrySet(), equalTo(expectedStats.entrySet()));
}
private Map<String, Long> fetchStats(String user, String password) throws Exception {
String contentAsString = fetchStatsRequest(user, password)
.andExpect(status().isOk())
.andReturn().getResponse().getContentAsString();
ObjectMapper jackson = new ObjectMapper();
return jackson.readValue(contentAsString, GetStatisticResponse.class);
}
private ResultActions fetchStatsRequest(String user, String password) throws Exception {
return mockMvc.perform(get(STATISTIC + "/" + user)
.with(user(user).password(password)))
.andDo(print());
}
private void checkRedirect(String expectedLocation, URL shortUrl) throws Exception {
checkRedirect(expectedLocation, shortUrl, AllowedRedirect.TEMPORARILY_302.getCode());
}
private void checkRedirect(String expectedLocation, URL shortUrl, int redirectType) throws Exception {
mockMvc.perform(get(shortUrl.toURI()))
.andDo(print())
.andExpect(status().is(redirectType))
.andExpect(header().stringValues("Location", expectedLocation));
}
private ResultActions createAccountPost(String accountId) throws Exception {
return mockMvc.perform(post(ACCOUNT)
.param(ACCOUNT_ID, accountId))
.andDo(print());
}
private String createAccountOk(String accountId) throws Exception {
String contentAsString = createAccountPost(accountId)
.andExpect(status().isOk())
.andExpect(jsonPath(SUCCESS, is(true)))
.andExpect(jsonPath(PASSWORD).exists())
.andReturn().getResponse().getContentAsString();
return JsonPath.parse(contentAsString).read(PASSWORD, String.class);
}
private String shortenOk(String user, String password, String url) throws Exception {
return shortenOk(user, password, url, null);
}
private String shortenOk(String user, String password, String url, Integer redirectType) throws Exception {
String contentAsString = shortenPost(user, password, url, redirectType)
.andExpect(status().isOk())
.andExpect(jsonPath(SHORT_URL).isNotEmpty())
.andReturn().getResponse().getContentAsString();
return JsonPath.parse(contentAsString).read(SHORT_URL, String.class);
}
private ResultActions shortenPost(String user, String password, String url, Integer redirectType) throws Exception {
MockHttpServletRequestBuilder reqBuilder = post(REGISTER).with(user(user).password(password));
if (redirectType != null) {
reqBuilder.param(ParamNames.REDIRECT_TYPE, String.valueOf(redirectType));
}
reqBuilder.param(ParamNames.URL, url);
return mockMvc.perform(reqBuilder).andDo(print());
}
} | 42.261628 | 120 | 0.725684 |
40df8046a44bc3d69e72937db32646d4ac7fbfc7 | 3,539 | package ca.zesty.fleetreporter;
import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.AccessibilityServiceInfo;
import android.content.Intent;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
public class UssdReceiverService extends AccessibilityService {
static final String TAG = "UssdReceiverService";
static final String ACTION_USSD_RECEIVED = "FLEET_REPORTER_USSD_RECEIVED";
static final String EXTRA_USSD_MESSAGE = "ussd_message";
@Override public void onAccessibilityEvent(AccessibilityEvent event) {
Utils u = new Utils(this);
if (!u.getBooleanPref(Prefs.RUNNING)) return;
AccessibilityNodeInfo source = event.getSource();
String eventClass = String.valueOf(event.getClassName());
String sourceClass = String.valueOf(source.getClassName());
switch (event.getEventType()) {
case AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED:
if (sourceClass.endsWith(".TextView")) {
String text = "" + source.getText();
dismissDialog(source);
handleText(text);
}
break;
case AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED:
if (eventClass.endsWith(".AlertDialog") ||
eventClass.endsWith(".UssdAlertActivity")) {
String text = event.getText().isEmpty() ? "" : "" + event.getText().get(0);
dismissDialog(source);
handleText(text);
}
break;
}
}
@Override public void onInterrupt() { }
@Override protected void onServiceConnected() {
super.onServiceConnected();
AccessibilityServiceInfo info = new AccessibilityServiceInfo();
info.flags = AccessibilityServiceInfo.DEFAULT;
info.feedbackType = AccessibilityServiceInfo.FEEDBACK_GENERIC;
info.packageNames = new String[] {"com.android.phone"};
info.eventTypes = AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED |
AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED;
setServiceInfo(info);
}
private void dismissDialog(AccessibilityNodeInfo node) {
String nodeClass = String.valueOf(node.getClassName());
if (nodeClass.endsWith(".FrameLayout")) {
// If this is a text entry popup, there will be two buttons,
// "Cancel" and "Send". If this is a plain message popup, there
// will just be one button, "OK". In both cases, we click the
// first available button to dismiss the popup.
for (int i = 0; i < node.getChildCount(); i++) {
AccessibilityNodeInfo child = node.getChild(i);
if (child != null && String.valueOf(child.getClassName()).endsWith(".Button")) {
child.performAction(AccessibilityNodeInfo.ACTION_CLICK);
break;
}
}
} else {
// These methods of closing the dialog don't work on Samsung, but
// might work on other phones.
performGlobalAction(GLOBAL_ACTION_BACK);
sendBroadcast(new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
}
}
private void handleText(String text) {
Utils.logRemote(TAG, "USSD received: " + text);
sendBroadcast(new Intent(ACTION_USSD_RECEIVED).putExtra(EXTRA_USSD_MESSAGE, text));
}
}
| 44.2375 | 96 | 0.635773 |
8495e0452dd5fda598cda2ecc551ce008a348a9e | 1,169 | package ru.job4j.generic;
import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
public class StoresTest {
@Test
public void whenUseUserStoreThenShowsItsFunctional() {
UserStore users = new UserStore();
User user = new User("123");
User user1 = new User("456");
User user2 = new User("789");
users.add(user);
users.add(user1);
users.add(user2);
assertThat(users.delete(user.getId()), is(true));
assertThat(users.findById("456"), is(user1));
assertThat(users.replace(user2.getId(), new User("834")), is(true));
}
@Test
public void whenUseRoleStoreThenShowsItsFunctional() {
RoleStore roles = new RoleStore();
Role role = new Role("123");
Role role1 = new Role("456");
Role role2 = new Role("789");
roles.add(role);
roles.add(role1);
roles.add(role2);
assertThat(roles.delete(role.getId()), is(true));
assertThat(roles.findById("456"), is(role1));
assertThat(roles.replace(role2.getId(), new Role("834")), is(true));
}
}
| 30.763158 | 76 | 0.613345 |
76c774d07ecfc846d860fde4ef40c98cd3b243e3 | 2,255 | /**
* Copyright (c) 2001-2017 Mathew A. Nelson and Robocode contributors
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://robocode.sourceforge.net/license/epl-v10.html
*/
package robocode;
import net.sf.robocode.peer.IRobotStatics;
import net.sf.robocode.serialization.ISerializableHelper;
import net.sf.robocode.serialization.RbSerializer;
import robocode.robotinterfaces.IBasicEvents;
import robocode.robotinterfaces.IBasicRobot;
import java.awt.*;
import java.nio.ByteBuffer;
/**
* This event is sent to {@link Robot#onWin(WinEvent) onWin()} when your robot
* wins the round in a battle.
*
* @author Mathew A. Nelson (original)
* @author Flemming N. Larsen (contributor)
*/
public final class WinEvent extends Event {
private static final long serialVersionUID = 1L;
private final static int DEFAULT_PRIORITY = 100; // System event -> cannot be changed!
/**
* Called by the game to create a new WinEvent.
*/
public WinEvent() {
super();
}
/**
* {@inheritDoc}
*/
@Override
public final int getPriority() {
return DEFAULT_PRIORITY;
}
/**
* {@inheritDoc}
*/
@Override
final int getDefaultPriority() {
return DEFAULT_PRIORITY;
}
/**
* {@inheritDoc}
*/
@Override
final void dispatch(IBasicRobot robot, IRobotStatics statics, Graphics2D graphics) {
IBasicEvents listener = robot.getBasicEventListener();
if (listener != null) {
listener.onWin(this);
}
}
/**
* {@inheritDoc}
*/
@Override
final boolean isCriticalEvent() {
return true;
}
/**
* {@inheritDoc}
*/
@Override
byte getSerializationType() {
return RbSerializer.WinEvent_TYPE;
}
static ISerializableHelper createHiddenSerializer() {
return new SerializableHelper();
}
private static class SerializableHelper implements ISerializableHelper {
public int sizeOf(RbSerializer serializer, Object object) {
return RbSerializer.SIZEOF_TYPEINFO;
}
public void serialize(RbSerializer serializer, ByteBuffer buffer, Object object) {}
public Object deserialize(RbSerializer serializer, ByteBuffer buffer) {
return new WinEvent();
}
}
}
| 22.777778 | 87 | 0.729933 |
86b44326252064214b731d2d609fa6e79ff51f2c | 11,299 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.mobilenetwork.models;
import com.azure.core.management.Region;
import com.azure.core.management.SystemData;
import com.azure.core.util.Context;
import com.azure.resourcemanager.mobilenetwork.fluent.models.SimPolicyInner;
import java.util.List;
import java.util.Map;
/** An immutable client-side representation of SimPolicy. */
public interface SimPolicy {
/**
* Gets the id property: Fully qualified resource Id for the resource.
*
* @return the id value.
*/
String id();
/**
* Gets the name property: The name of the resource.
*
* @return the name value.
*/
String name();
/**
* Gets the type property: The type of the resource.
*
* @return the type value.
*/
String type();
/**
* Gets the location property: The geo-location where the resource lives.
*
* @return the location value.
*/
String location();
/**
* Gets the tags property: Resource tags.
*
* @return the tags value.
*/
Map<String, String> tags();
/**
* Gets the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information.
*
* @return the systemData value.
*/
SystemData systemData();
/**
* Gets the provisioningState property: The provisioning state of the sim policy resource.
*
* @return the provisioningState value.
*/
ProvisioningState provisioningState();
/**
* Gets the ueAmbr property: Aggregate maximum bit rate across all non-GBR QoS flows of all PDU sessions of a given
* UE. See 3GPP TS23.501 section 5.7.2.6 for a full description of the UE-AMBR.
*
* @return the ueAmbr value.
*/
Ambr ueAmbr();
/**
* Gets the defaultSlice property: The default slice to use if the UE does not explicitly specify it. This slice
* must exist in the `sliceConfigurations` map.
*
* @return the defaultSlice value.
*/
SliceResourceId defaultSlice();
/**
* Gets the rfspIndex property: RAT/Frequency Selection Priority Index, defined in 3GPP TS 36.413. This is an
* optional setting and by default is unspecified.
*
* @return the rfspIndex value.
*/
Integer rfspIndex();
/**
* Gets the registrationTimer property: Interval for the UE periodic registration update procedure, in seconds.
*
* @return the registrationTimer value.
*/
Integer registrationTimer();
/**
* Gets the sliceConfigurations property: The allowed slices and the settings to use for them. The list must not
* contain duplicate items and must contain at least one item.
*
* @return the sliceConfigurations value.
*/
List<SliceConfiguration> sliceConfigurations();
/**
* Gets the region of the resource.
*
* @return the region of the resource.
*/
Region region();
/**
* Gets the name of the resource region.
*
* @return the name of the resource region.
*/
String regionName();
/**
* Gets the inner com.azure.resourcemanager.mobilenetwork.fluent.models.SimPolicyInner object.
*
* @return the inner object.
*/
SimPolicyInner innerModel();
/** The entirety of the SimPolicy definition. */
interface Definition
extends DefinitionStages.Blank,
DefinitionStages.WithLocation,
DefinitionStages.WithParentResource,
DefinitionStages.WithUeAmbr,
DefinitionStages.WithDefaultSlice,
DefinitionStages.WithSliceConfigurations,
DefinitionStages.WithCreate {
}
/** The SimPolicy definition stages. */
interface DefinitionStages {
/** The first stage of the SimPolicy definition. */
interface Blank extends WithLocation {
}
/** The stage of the SimPolicy definition allowing to specify location. */
interface WithLocation {
/**
* Specifies the region for the resource.
*
* @param location The geo-location where the resource lives.
* @return the next definition stage.
*/
WithParentResource withRegion(Region location);
/**
* Specifies the region for the resource.
*
* @param location The geo-location where the resource lives.
* @return the next definition stage.
*/
WithParentResource withRegion(String location);
}
/** The stage of the SimPolicy definition allowing to specify parent resource. */
interface WithParentResource {
/**
* Specifies resourceGroupName, mobileNetworkName.
*
* @param resourceGroupName The name of the resource group. The name is case insensitive.
* @param mobileNetworkName The name of the mobile network.
* @return the next definition stage.
*/
WithUeAmbr withExistingMobileNetwork(String resourceGroupName, String mobileNetworkName);
}
/** The stage of the SimPolicy definition allowing to specify ueAmbr. */
interface WithUeAmbr {
/**
* Specifies the ueAmbr property: Aggregate maximum bit rate across all non-GBR QoS flows of all PDU
* sessions of a given UE. See 3GPP TS23.501 section 5.7.2.6 for a full description of the UE-AMBR..
*
* @param ueAmbr Aggregate maximum bit rate across all non-GBR QoS flows of all PDU sessions of a given UE.
* See 3GPP TS23.501 section 5.7.2.6 for a full description of the UE-AMBR.
* @return the next definition stage.
*/
WithDefaultSlice withUeAmbr(Ambr ueAmbr);
}
/** The stage of the SimPolicy definition allowing to specify defaultSlice. */
interface WithDefaultSlice {
/**
* Specifies the defaultSlice property: The default slice to use if the UE does not explicitly specify it.
* This slice must exist in the `sliceConfigurations` map..
*
* @param defaultSlice The default slice to use if the UE does not explicitly specify it. This slice must
* exist in the `sliceConfigurations` map.
* @return the next definition stage.
*/
WithSliceConfigurations withDefaultSlice(SliceResourceId defaultSlice);
}
/** The stage of the SimPolicy definition allowing to specify sliceConfigurations. */
interface WithSliceConfigurations {
/**
* Specifies the sliceConfigurations property: The allowed slices and the settings to use for them. The list
* must not contain duplicate items and must contain at least one item..
*
* @param sliceConfigurations The allowed slices and the settings to use for them. The list must not contain
* duplicate items and must contain at least one item.
* @return the next definition stage.
*/
WithCreate withSliceConfigurations(List<SliceConfiguration> sliceConfigurations);
}
/**
* The stage of the SimPolicy definition which contains all the minimum required properties for the resource to
* be created, but also allows for any other optional properties to be specified.
*/
interface WithCreate
extends DefinitionStages.WithTags, DefinitionStages.WithRfspIndex, DefinitionStages.WithRegistrationTimer {
/**
* Executes the create request.
*
* @return the created resource.
*/
SimPolicy create();
/**
* Executes the create request.
*
* @param context The context to associate with this operation.
* @return the created resource.
*/
SimPolicy create(Context context);
}
/** The stage of the SimPolicy definition allowing to specify tags. */
interface WithTags {
/**
* Specifies the tags property: Resource tags..
*
* @param tags Resource tags.
* @return the next definition stage.
*/
WithCreate withTags(Map<String, String> tags);
}
/** The stage of the SimPolicy definition allowing to specify rfspIndex. */
interface WithRfspIndex {
/**
* Specifies the rfspIndex property: RAT/Frequency Selection Priority Index, defined in 3GPP TS 36.413. This
* is an optional setting and by default is unspecified..
*
* @param rfspIndex RAT/Frequency Selection Priority Index, defined in 3GPP TS 36.413. This is an optional
* setting and by default is unspecified.
* @return the next definition stage.
*/
WithCreate withRfspIndex(Integer rfspIndex);
}
/** The stage of the SimPolicy definition allowing to specify registrationTimer. */
interface WithRegistrationTimer {
/**
* Specifies the registrationTimer property: Interval for the UE periodic registration update procedure, in
* seconds..
*
* @param registrationTimer Interval for the UE periodic registration update procedure, in seconds.
* @return the next definition stage.
*/
WithCreate withRegistrationTimer(Integer registrationTimer);
}
}
/**
* Begins update for the SimPolicy resource.
*
* @return the stage of resource update.
*/
SimPolicy.Update update();
/** The template for SimPolicy update. */
interface Update extends UpdateStages.WithTags {
/**
* Executes the update request.
*
* @return the updated resource.
*/
SimPolicy apply();
/**
* Executes the update request.
*
* @param context The context to associate with this operation.
* @return the updated resource.
*/
SimPolicy apply(Context context);
}
/** The SimPolicy update stages. */
interface UpdateStages {
/** The stage of the SimPolicy update allowing to specify tags. */
interface WithTags {
/**
* Specifies the tags property: Resource tags..
*
* @param tags Resource tags.
* @return the next definition stage.
*/
Update withTags(Map<String, String> tags);
}
}
/**
* Refreshes the resource to sync with Azure.
*
* @return the refreshed resource.
*/
SimPolicy refresh();
/**
* Refreshes the resource to sync with Azure.
*
* @param context The context to associate with this operation.
* @return the refreshed resource.
*/
SimPolicy refresh(Context context);
}
| 36.214744 | 120 | 0.610674 |
06b6585bbf4d99cc114666e63a6426c0bb6a0cc2 | 327 | package com.songchao.mybilibili.model;
/**
* Author: SongCHao
* Date: 2017/9/18/14:11
* Email: [email protected]
*/
public class DoubleNews {
public String id;
public String title;
public String image;
public String content;
public String source;
public String digest;
public String time;
}
| 18.166667 | 38 | 0.685015 |
522a8034ae723f85e457a0960149e2547f551f2b | 959 | package org.usfirst.frc.team4488.robot.autonomous.actions;
import org.usfirst.frc.team4488.robot.systems.Forklift;
public class InaccurateMoveLift implements Action {
private Forklift lift;
private int startingCycles;
private double startingDoneRange;
private double height;
private int updateCycles = 0;
public InaccurateMoveLift(double height) {
this.height = height;
lift = Forklift.getInstance();
}
@Override
public boolean isFinished() {
return lift.atDesiredPosition() && updateCycles > 3;
}
@Override
public void update() {
updateCycles++;
lift.setHeight(height);
}
@Override
public void done() {
lift.setDoneRange(startingDoneRange);
lift.changeMinDoneCycleCount(startingCycles);
}
@Override
public void start() {
startingCycles = lift.getMinDoneCycleCount();
startingDoneRange = lift.getDoneRange();
lift.setDoneRange(5);
lift.changeMinDoneCycleCount(5);
}
}
| 21.795455 | 58 | 0.722628 |
2a26bcdc6600556450750f405f8eaea6f91751ba | 10,335 | package top.imshan.pdf;
import com.itextpdf.awt.geom.Rectangle2D.Float;
import com.itextpdf.text.*;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.parser.ImageRenderInfo;
import com.itextpdf.text.pdf.parser.PdfReaderContentParser;
import com.itextpdf.text.pdf.parser.RenderListener;
import com.itextpdf.text.pdf.parser.TextRenderInfo;
import com.itextpdf.tool.xml.XMLWorkerFontProvider;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import top.imshan.utils.ImageHelper;
import top.imshan.utils.PdfFooterPager;
import freemarker.template.Configuration;
import freemarker.template.Template;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* PDF生成器
* @author shansb
*/
public class PdfMaker {
/**
* 编码集
*/
private static final String CHARSET = "UTF-8";
/**
* 生产pdf时需要的字体
*/
private static final String FONT = "/simhei.ttf";
/**
* freemarker模板路径
*/
private static final String PATH_PREFIX = "/test/";
/**
* 印章uid颜色
*/
public static final Color MARK_CONTENT_COLOR = Color.RED;
/**
* 107px相当于A4PDF的38mm物理距离,缩放真实大小比例 = 38/210(A4宽)*595(pdf 像素宽度)
*/
public static final float REAL_PIXEL = 107.7f;
/**
* 盖骑缝章,设置页码
* @param infilePath 原PDF路径
* @param outFilePath 输出PDF路径
* @param stampId 章图片id(水印内容)
* @throws IOException
* @throws DocumentException
*/
public void createPageSealPdf(String infilePath, String outFilePath, String stampId)
throws IOException, DocumentException {
PdfReader reader = null;
FileOutputStream fileOutputStream = null;
PdfStamper stamp = null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
//印章序号字体为红色
BufferedImage stampImage = ImageHelper.waterPress(MARK_CONTENT_COLOR, stampId);
try {
reader = new PdfReader(infilePath);// 选择需要印章的pdf
fileOutputStream = new FileOutputStream(outFilePath);
stamp = new PdfStamper(reader, fileOutputStream);// 加完印章后的pdf
Rectangle pageSize = reader.getPageSize(1);// 获得第一页
int nums = reader.getNumberOfPages();
Image[] nImage = ImageHelper.subImages(stampImage, nums);// 生成骑缝章切割图片
float width = pageSize.getWidth();
float height = pageSize.getHeight();
for (int n = 1; n <= nums; n++) {
PdfContentByte over = stamp.getOverContent(n);// 设置在第几页打印印章
Image img = nImage[n - 1];// 选择图片
float percent = REAL_PIXEL /img.getHeight();
// 大于1页才有骑缝章
if (nums > 1) {
//印章缩放到107px
img.scalePercent(percent * 100f);
//计算位置时同样要考虑缩放
float sealX = width - img.getWidth() * percent;
float sealY = height / 2 - img.getHeight() * percent / 2;
img.setAbsolutePosition(sealX,sealY);
over.addImage(img);
}
//最后一页在文章末尾追加印章
if(n == nums){
ImageIO.write(stampImage, "png", out);
Image fullStamp = Image.getInstance(out.toByteArray());
// 默认盖在页面右下2/3处
float fixedX = 0.7f*width-fullStamp.getWidth()*percent/2;
float fixedY = 0.3f*height-fullStamp.getHeight()*percent / 2;
//获取动态高度
List<Float> textRectangles = getKeyWord(nums, reader,"电子印章代码");
if (!textRectangles.isEmpty()) {
fixedY = (float) (textRectangles.get(0).getMaxY());
fixedX = (float) textRectangles.get(0).getMinX();
// 页面高度减去页边距,有文本内容的最大Y轴值
float contentMaxY = height-72f;
//文本高度减去图片高度就是图片能存放的最大Y轴值
float imageMaxY = contentMaxY - fullStamp.getHeight()*percent;
fixedY = fixedY > imageMaxY ? imageMaxY : fixedY;
}
fullStamp.scalePercent(percent*100f);
fullStamp.setAbsolutePosition(fixedX, fixedY);
over.addImage(fullStamp);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stamp != null) {
stamp.close();
}
if (fileOutputStream != null) {
fileOutputStream.close();
}
if (reader != null) {
reader.close();
}
out.close();
}
}
/**
* 获取指定页面的关键词坐标
* @param pageNum 指定页面
* @param reader pdfReader
* @param keyWord 关键字
* @return 坐标列表
*/
private List<Float> getKeyWord(Integer pageNum, PdfReader reader, final String keyWord) {
final List<Float> result = new ArrayList<Float>(1);
PdfReaderContentParser parser = new PdfReaderContentParser(reader);
try {
parser.processContent(pageNum, new RenderListener() {
@Override
public void renderText(TextRenderInfo info) {
//文字处理
//获取的内容很奇怪,连续的单词也可能被分开
String text = info.getText();
if(null != text && text.contains(keyWord)){
result.add(info.getBaseline().getBoundingRectange());
}
}
@Override
public void renderImage(ImageRenderInfo arg0) {
// 图像处理
}
@Override
public void endTextBlock() {
//do nothing
}
@Override
public void beginTextBlock() {
//do nothing
}
});
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
/**
* freemarker渲染html
* @param data 动态填充内容
* @param htmlTmp 模板
* @return 内容string
*/
public String freeMarkerRender(Map<String, Object> data, String htmlTmp) {
// 创建配置实例
Configuration configuration = new Configuration();
// 设置编码
configuration.setDefaultEncoding(CHARSET);
// 模板文件
configuration.setClassForTemplateLoading(PdfMaker.class,
PATH_PREFIX);
Writer out = new StringWriter();
try {
// 获取模板,并设置编码方式
Template template = configuration.getTemplate(htmlTmp);
// 合并数据模型与模板
template.process(data, out); // 将合并后的数据和模板写入到流中,这里使用的字符流
out.flush();
return out.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return null;
}
/**
* 创建pdf,指定了页面大小和页边距
* @param content 字符内容
* @param dest 目标路径
* @param isRotation 是否A4横版
* @throws IOException
*/
public void createPdf(String content, String dest, boolean isRotation) throws IOException {
Document document = null;
PdfWriter writer = null;
FileOutputStream fileOutputStream = null;
ByteArrayInputStream byteArrayInputStream = null;
try {
// step 1
//横版时直接输入大小而不用PageSize.A4.rotate()
//是因为使用rotate会导致读取pdf高宽的时候发生对换,加盖骑缝章错误。
if (isRotation) {
document = new Document(new RectangleReadOnly(842F, 595F));
} else {
document = new Document(PageSize.A4);
}
document.setMargins(90f, 90f, 72f, 72f);//A4默认页边距
// step 2
fileOutputStream = new FileOutputStream(dest);
writer = PdfWriter.getInstance(document, fileOutputStream);
//增加页码
writer.setPageEvent(new PdfFooterPager());
// step 3
document.open();
// step 4 设置字体
XMLWorkerFontProvider fontImp =
new XMLWorkerFontProvider(XMLWorkerFontProvider.DONTLOOKFORFONTS);
fontImp.register(FONT);
byteArrayInputStream = new ByteArrayInputStream(content.getBytes());
XMLWorkerHelper.getInstance()
.parseXHtml(writer, document, byteArrayInputStream, null,
Charset.forName(CHARSET), fontImp);
} catch (Exception e) {
e.printStackTrace();
} finally {
// step 5
if (byteArrayInputStream != null) {
byteArrayInputStream.close();
}
if (document != null) {
document.close();
}
if (fileOutputStream != null) {
fileOutputStream.close();
}
}
}
/**
* 创建横版A4 pdf并添加骑缝章
* @param dataMap 动态内容
* @param templateName 模板
* @param dest 目标路径+目标文件名
* @param isRotation 是否横版A4
* @throws IOException
* @throws DocumentException
*/
public void createPdfWithStamp(Map<String, Object> dataMap, String templateName,String dest, boolean isRotation) throws IOException, DocumentException{
//动态生成文本内容
String content = freeMarkerRender(dataMap, templateName);
if (null == content) {
System.out.print("pdf content is null!");
return;
}
// 无章pdf:临时文件
String destTemp = dest + "temp";
// 创建无章pdf
createPdf(content, destTemp, isRotation);
// 加盖骑缝章
createPageSealPdf(destTemp, dest, (String) dataMap.get("Uid"));
// 删除无章pdf
File tempFile = new File(destTemp);
if(tempFile.exists()){
tempFile.delete();
}
System.out.println("文件地址:"+ dest);
}
}
| 34.221854 | 155 | 0.553459 |
a87997b815d7e513b99455d38f8d47d841c23349 | 4,604 | /*
* Copyright (c) 2010, 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code 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 General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.vm.ci.code;
import jdk.vm.ci.meta.AllocatableValue;
import jdk.vm.ci.meta.ValueKind;
/**
* Represents a compiler spill slot or an outgoing stack-based argument in a method's frame or an
* incoming stack-based argument in a method's {@linkplain #isInCallerFrame() caller's frame}.
*/
public final class StackSlot extends AllocatableValue {
private final int offset;
private final boolean addFrameSize;
/**
* Gets a {@link StackSlot} instance representing a stack slot at a given index holding a value
* of a given kind.
*
* @param kind The kind of the value stored in the stack slot.
* @param offset The offset of the stack slot (in bytes)
* @param addFrameSize Specifies if the offset is relative to the stack pointer, or the
* beginning of the frame (stack pointer + total frame size).
*/
public static StackSlot get(ValueKind<?> kind, int offset, boolean addFrameSize) {
assert addFrameSize || offset >= 0;
return new StackSlot(kind, offset, addFrameSize);
}
/**
* Private constructor to enforce use of {@link #get(ValueKind, int, boolean)} so that a cache
* can be used.
*/
private StackSlot(ValueKind<?> kind, int offset, boolean addFrameSize) {
super(kind);
this.offset = offset;
this.addFrameSize = addFrameSize;
}
/**
* Gets the offset of this stack slot, relative to the stack pointer.
*
* @return The offset of this slot (in bytes).
*/
public int getOffset(int totalFrameSize) {
assert totalFrameSize > 0 || !addFrameSize;
int result = offset + (addFrameSize ? totalFrameSize : 0);
assert result >= 0;
return result;
}
public boolean isInCallerFrame() {
return addFrameSize && offset >= 0;
}
public int getRawOffset() {
return offset;
}
public boolean getRawAddFrameSize() {
return addFrameSize;
}
@Override
public String toString() {
if (!addFrameSize) {
return "out:" + offset + getKindSuffix();
} else if (offset >= 0) {
return "in:" + offset + getKindSuffix();
} else {
return "stack:" + (-offset) + getKindSuffix();
}
}
/**
* Gets this stack slot used to pass an argument from the perspective of a caller.
*/
public StackSlot asOutArg() {
assert offset >= 0;
if (addFrameSize) {
return get(getValueKind(), offset, false);
}
return this;
}
/**
* Gets this stack slot used to pass an argument from the perspective of a callee.
*/
public StackSlot asInArg() {
assert offset >= 0;
if (!addFrameSize) {
return get(getValueKind(), offset, true);
}
return this;
}
@Override
public int hashCode() {
final int prime = 37;
int result = super.hashCode();
result = prime * result + (addFrameSize ? 1231 : 1237);
result = prime * result + offset;
return result;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof StackSlot) {
StackSlot other = (StackSlot) obj;
return super.equals(obj) && addFrameSize == other.addFrameSize && offset == other.offset;
}
return false;
}
}
| 33.362319 | 101 | 0.641182 |
017b934c8546ea83c8223c520b6887ad1a185804 | 1,081 | package com.github.kbreczko.gitproxy.user.controllers;
import com.github.kbreczko.gitproxy.common.properties.GitproxyProperties;
import com.github.kbreczko.gitproxy.user.api.UserApi;
import com.github.kbreczko.gitproxy.user.models.UserDto;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
@AllArgsConstructor
@Slf4j
@RestController
@RequestMapping(value = GitproxyProperties.Mappings.USERS)
public class UserRestController {
private final UserApi userApi;
@GetMapping(value = "/{login}")
public UserDto getUser(@PathVariable String login) {
return userApi.getUser(login)
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "User not found"));
}
}
| 36.033333 | 104 | 0.803885 |
cb9ae3887255525684f7f65f17ec61ddc4bc410c | 1,687 | package io.treefrog.function.tuple;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.platform.runner.JUnitPlatform;
import org.junit.runner.RunWith;
import java.util.concurrent.atomic.AtomicInteger;
import static com.google.common.truth.Truth.assertThat;
import static io.treefrog.function.tuple.Tuple.tuple;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS;
@TestInstance(PER_CLASS)
@RunWith(JUnitPlatform.class)
class Tuple2Test {
@Test
void shouldMap() {
final Tuple2<String, String> tuple = tuple("string1", "string2");
assertThat(tuple.map((v1, v2) -> v1 + v2)).isNotNull();
}
@Test
void shouldTrueCondition() {
final Tuple2<String, String> tuple = tuple("A", "B");
assertThat(tuple.matches((v1, v2) -> v1.equals("A"))).isTrue();
}
@Test
void shouldFlatMap() {
final Tuple2<String, String> tuple = tuple("A", "B");
assertThat(tuple.<Tuple2<String, String>>flatMap((v1, v2) -> tuple("B", "A"))).isNotNull();
}
@Test
void shouldPeekWithResult() {
final Tuple2<Integer, Integer> tuple = tuple(1, 2);
final AtomicInteger result = new AtomicInteger(0);
tuple.peek((v1, v2) -> result.set(v1 + v2));
assertThat(result.get()).isEqualTo(3);
}
@Test
void shouldReturnsAB() {
final Tuple2<String, String> tuple = tuple("A", "B");
assertThat(tuple.<String>then((v1, v2) -> v1 + v2)).isEqualTo("AB");
}
@Test
void shouldThrowException() {
final Tuple2<String, String> tuple = tuple("v1", "v2");
assertThrows(RuntimeException.class, () -> tuple.then(null));
}
}
| 27.209677 | 95 | 0.688797 |
99b413159b58af182e23eb7d95691f142ce2dbdf | 2,320 | package net.simpvp.PathCleaner;
import java.util.HashSet;
import org.bukkit.Chunk;
import org.bukkit.block.Block;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.world.ChunkUnloadEvent;
/**
* Listens for events that indicate that a given region was modified by
* players.
*/
public class InteractListener implements Listener {
private static HashSet<Region> seen_regions = new HashSet<>();
private void add_region(Block block) {
String world = block.getWorld().getName();
int x = block.getX() >> 9;
int z = block.getZ() >> 9;
Region r = new Region(world, x, z);
if (!seen_regions.add(r)) {
return;
}
//PathCleaner.instance.getLogger().info(String.format("Setting safe region %s", r.toString()));
if (!SQLite.insert_safe_region(r)) {
PathCleaner.initialized = false;
seen_regions.remove(r);
PathCleaner.instance.getLogger().severe(String.format("Error saving safe region %s", r.toString()));
}
}
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onPlayerBlockPlace(BlockPlaceEvent event) {
add_region(event.getBlockPlaced());
}
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onPlayerBreakBlock(BlockBreakEvent event) {
add_region(event.getBlock());
}
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onPlayerDeath(PlayerDeathEvent event) {
add_region(event.getEntity().getLocation().getBlock());
}
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=true)
public void onPlayerInteract(PlayerInteractEvent event) {
add_region(event.getClickedBlock());
}
/*
* Removing this trigger, as we can easily compute it later.
@EventHandler(priority=EventPriority.MONITOR, ignoreCancelled=false)
public void onChunkUnload(ChunkUnloadEvent event) {
Chunk c = event.getChunk();
PathCleaner.instance.getLogger().info("Unload time " + c.getInhabitedTime());
if (c.getInhabitedTime() > PathCleaner.inhabited_threshold) {
add_region(c.getBlock(0, 0, 0));
}
}
*/
}
| 30.526316 | 103 | 0.75819 |
1a868bb31241aec967adf534c3a943d9b1cf315f | 1,070 | package Simulation;
import java.util.List;
/**
* Rules for Ant simulation
*/
public class AntRuleSet extends RuleSet {
/**
* Set parameters
* @param parameters
*/
@Override
public void setParameters(double[] parameters) {
super.setParameters(parameters);
}
/**
* Apply the rules
* @param neighbors
* @param cell
* @param grid
* @return
*/
@Override
public State applyRules(List<Cell> neighbors, Cell cell, Grid grid) {
AntCell antCell = (AntCell) cell;
antCell.evaluate((AntGrid) grid);
if (cell.getCurrentState() == AntState.FOOD)
return cell.getCurrentState();
if (cell.getCurrentState() == AntState.HOME)
return cell.getCurrentState();
antCell.diffuse();
if (antCell.hasAnts()) {
if (antCell.hasFoodAnts())
return AntState.ANT_WITH_FOOD;
else
return AntState.ANT_NO_FOOD;
} else {
return AntState.EMPTY;
}
}
}
| 19.454545 | 73 | 0.563551 |
95eb810a1a3748020e502cd8c56e8622b3fa6dd9 | 356 | package com.bangqu.lib.slipload.callback;
public interface IHeaderCallBack {
/**
* 正常状态
*/
void onStateNormal();
/**
* 准备刷新
*/
void onStateReady();
/**
* 正在刷新
*/
void onStateRefreshing();
/**
* 刷新成功
*/
void onStateSuccess();
/**
* 刷新失败
*/
void onStateFail();
} | 12.275862 | 41 | 0.483146 |
f4549f78e0aad5eb882f8445896fbe46289c95c5 | 5,513 | package com.geodatastore.zk;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.junit.Test;
import java.util.ArrayList;
import java.util.concurrent.CountDownLatch;
public class ZKConnectionTest {
private final String zkLocation = "192.168.1.5:2181";
private final int sessionTimeOut = 5000;
/**
* 迭代获取父节点的子节点
* @param parentNodeName
* @param zooKeeper
* @return
*/
public ArrayList<String> iterChildNodeList(String parentNodeName, ZooKeeper zooKeeper){
if(parentNodeName != null && !parentNodeName.equals("")){
try {
ArrayList<String> childNodeList = (ArrayList<String>)zooKeeper.getChildren(parentNodeName, null);
if(childNodeList.size() > 0){
System.out.println("父结点:" + parentNodeName);
for(String childNode : childNodeList){
String childNodePath = "";
if(!parentNodeName.equals("/")){
childNodePath = parentNodeName + "/" + childNode;
}else {
childNodePath = parentNodeName + childNode;
}
System.out.println(parentNodeName + "的子节点:" + childNodePath);
iterChildNodeList(childNodePath, zooKeeper);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
return new ArrayList<String>();
}
@Test
public void zkConnect() {
try {
final CountDownLatch countDownLatch = new CountDownLatch(1);
ZooKeeper zooKeeper = new ZooKeeper(
zkLocation,
sessionTimeOut, new Watcher() {
@Override
public void process(WatchedEvent event) {
if (Event.KeeperState.SyncConnected == event.getState()) {
countDownLatch.countDown();
}
}
});
countDownLatch.await();
System.out.println(zooKeeper.getState());
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
/**
* 获取服务器节点列表
*/
@Test
public void listTest(){
try {
ZooKeeper zooKeeper = new ZooKeeper(zkLocation, sessionTimeOut, null);
String root = "/";
iterChildNodeList(root, zooKeeper);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取指定节点的节点数据
*/
@Test
public void getDataTest(){
try {
ZooKeeper zooKeeper = new ZooKeeper(zkLocation, sessionTimeOut, null);
String path = "/hbase";
String data = new String(zooKeeper.getData(path, null, new Stat()));
System.out.println(data);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 节点创建测试
*/
@Test
public void createTest(){
try{
ZooKeeper zooKeeper = new ZooKeeper(zkLocation, sessionTimeOut,null);
String dataStr = "100";
byte[] data = dataStr.getBytes();
// CreateMode:
//(1)PERSISTENT:持久;(2)PERSISTENT_SEQUENTIAL:持久顺序;(3)EPHEMERAL:临时;(4)EPHEMERAL_SEQUENTIAL:临时顺序。
String res = zooKeeper.create("/zookeeper/testNode", data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
if(res != null && !res.equals("")){
System.out.println("插入节点为:" + res);
String newData = new String(zooKeeper.getData("/zookeeper/testNode", null, new Stat()));
System.out.println("新插入数据为:" + newData);
}else {
System.out.println("创建失败!");
}
}catch (Exception e){
System.out.println(e);
}
}
/**
* 节点数据更新测试
*/
@Test
public void setTest(){
try{
ZooKeeper zooKeeper = new ZooKeeper(zkLocation, sessionTimeOut,null);
// 修改的节点
String path = "/zookeeper/testNode";
// 修改的新数据
byte[] data = new String("man").getBytes();
// 期望更新的版本号
// 从未修改后的话版本号为0,修改成功后版本号递增1
int version = 0;
// 修改之前的节点数据
String beforeData = new String(zooKeeper.getData(path, null, new Stat()));
Stat stat = zooKeeper.setData(path, data, version);
// 修改之后的版本号
int newVersion = stat.getVersion();
// 修改之后的节点数据
String afterData = new String(zooKeeper.getData(path, null, new Stat()));
System.out.println("更新之前数据为:" + beforeData);
System.out.println("更新之后数据为:" + afterData);
System.out.println("更新数据后新版本号为:" + newVersion);
}catch (Exception e){
System.out.println(e);
}
}
/**
* 节点删除测试
*/
@Test
public void deleteTest(){
try{
ZooKeeper zooKeeper = new ZooKeeper(zkLocation, sessionTimeOut,null);
// 删除的节点
String path = "/it1002/grade";
Stat stat = zooKeeper.exists(path, null);
// 删除的节点的版本
int version = stat.getVersion();
// 执行删除
zooKeeper.delete(path, version);
// 删除后列出最新的zk节点结构
listTest();
}catch (Exception e){
System.out.println(e);
}
}
}
| 32.429412 | 123 | 0.520225 |
8f28d6620ee8eb92ccd242977d0583361c75fab9 | 855 | package org.malagu.panda.dbconsole.service;
import java.util.Map;
import org.malagu.panda.dbconsole.model.SqlWrapper;
public interface ISqlWrapperService {
public static final String BEAN_ID = "panda.dbconsole.sqlWrapperService";
/**
* 添加数据浏览器记录sql
*
* @param tableName
* @param map
* @throws Exception
*/
public SqlWrapper getInsertTableSql(String tableName, Map<String, Object> map) throws Exception;
/**
* 更新数据浏览器记录sql
*
* @param tableName
* @param map
* @param oldMap
* @throws Exception
*/
public SqlWrapper getUpdateTableSql(String tableName, Map<String, Object> map, Map<String, Object> oldMap) throws Exception;
/**
* 删除数据浏览器记录sql
*
* @param tableName
* @param oldMap
* @throws Exception
*/
public SqlWrapper getDeleteTableSql(String tableName, Map<String, Object> oldMap) throws Exception;
}
| 22.5 | 125 | 0.725146 |
60cd3674c35082dda20976647fa3ebff8e88cec9 | 1,844 | package jfract4d.jfract.api.user.impl;
import jfract4d.discord.exception.MalformedDiscordIDException;
import jfract4d.discord.util.FormatHelper;
import jfract4d.jfract.api.exception.MalformedIDException;
import jfract4d.jfract.api.user.Role;
import jfract4d.jfract.api.user.User;
/**
* Basic implementation of a user
* @author Antoine Gagnon
*/
public class UserImpl implements User {
/**
* Role of the user
*/
protected Role role;
/**
* ID of the user, 18 char numeric string
*/
protected String id;
public UserImpl(String id, Role role) throws MalformedIDException {
setID(id);
setRole(role);
}
public UserImpl(String id) throws MalformedIDException {
setID(id);
}
/**
* Verify and set the ID
* Override this to set your own rules
* @param discordID
* @throws MalformedDiscordIDException
*/
protected void setID(String discordID) throws MalformedIDException {
this.id = id;
if (!FormatHelper.isValidID(discordID)) {
throw new MalformedIDException(discordID);
}
this.id = discordID;
}
@Override
public void setRole(Role role) {
this.role = role;
}
@Override
public Role getRole() {
return this.role;
}
@Override
public String getID() {
return this.id;
}
@Override
public int compareTo(User o) {
return o.getRole() == null && this.role == null ? 0
: o.getRole() != null && this.role == null ? -1
: o.getRole() == null && this.role != null ? 0
: this.role.compareTo(o.getRole());
}
@Override
public String toString() {
return String.format("%s | Role: %s", getID(), getRole().getName());
}
}
| 23.05 | 78 | 0.594902 |
3d08bbd411da6415f51cde37a98fb9b07f33410b | 521 | package com.lakeel.altla.vision.nearby.presentation.beacon.distance;
import java.util.Locale;
public final class Distance {
private final int txPower;
private final int rssi;
public Distance(int txPower, int rssi) {
this.txPower = txPower;
this.rssi = rssi;
}
public String getMeters() {
double value = Math.pow(10d, ((double) txPower - rssi) / 20.0) / 1000;
// Return distance in meters.
return String.format(Locale.getDefault(), "%.2f", value);
}
}
| 23.681818 | 78 | 0.641075 |
e0fe3f862a01f691aead2eada5cb0eb6d8c24b24 | 160 | package com.google.ads.mediation;
import e.b.a.a;
@Deprecated
public interface c {
void a(MediationBannerAdapter<?, ?> mediationBannerAdapter, a aVar);
}
| 17.777778 | 72 | 0.7375 |
447a7269fb1e2ef9c99593ad0ad788111813e267 | 502 | package cn.qd.peiwen.demo;
import androidx.appcompat.app.AppCompatActivity;
import cn.qd.peiwen.logger.PWLogger;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PWLogger.debug("debug");
PWLogger.warn("warn");
PWLogger.error("error");
PWLogger.crash("dhdhhdhhd");
}
}
| 25.1 | 56 | 0.705179 |
edc5ecad9375965ecc89ad90c764a16460139d04 | 2,037 | import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
public class CardDeckTest {
CardDeck deck;
int cardDeckNumber;
ArrayList<Card> alternateDeck;
String pathToFile;
@Before
public void setUp() {
cardDeckNumber = 12;
deck = new CardDeck(cardDeckNumber);
alternateDeck = new ArrayList<Card>();
}
@Test
public void testGetDeck() {
int testValue = 1;
deck.addCard(new Card(testValue));
alternateDeck.add( alternateDeck.size(), new Card(testValue));
assertEquals(alternateDeck, deck.getDeck());
}
@Test
public void testGetDeckNumber() {
assertEquals(cardDeckNumber, deck.getDeckNumber());
}
@Test
public void testAddCard() {
CardDeck testDeck = new CardDeck(1);
testDeck.addCard(new Card(5));
int testDeckSize = testDeck.getDeck().size();
Card lastCard = testDeck.getDeck().get(testDeckSize-1);
assertEquals(5, lastCard.getValue());
}
@Test
public void testMoveTopCard() {
CardDeck testDeck = new CardDeck(1);
for (int i = 1; i <= 4; i++) {
testDeck.addCard(new Card(i));
}
Card topCard = testDeck.moveTopCard();
assertEquals(1, topCard.getValue());
}
@Test
public void testCreateOutputFile() {
CardDeck testDeck = new CardDeck(1);
pathToFile = String.format(".%1$soutput%1$sdeck%2$s.txt", File.separator, testDeck.getDeckNumber());
testDeck.createOutputFile(pathToFile);
assertTrue(new File(pathToFile).exists());
}
@Test
public void testWriteToFile() {
String stringToWrite = "This is the written string";
assertTrue(deck.writeToFile(stringToWrite));
}
@Test
public void testToString() {
String toString = Arrays.toString(deck.getDeck().toArray());
assertEquals(toString, deck.toString());
}
}
| 26.802632 | 108 | 0.627884 |
0d228c837bc040ee329bf1616aac2718047259fb | 4,068 | /*
* Copyright (c) 2020 Ubique Innovation AG <https://www.ubique.ch>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*
* SPDX-License-Identifier: MPL-2.0
*/
package org.dpppt.android.sdk.internal.crypto;
import android.content.Context;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.dpppt.android.sdk.internal.AppConfigManager;
import org.dpppt.android.sdk.internal.backend.BackendBucketRepository;
import org.dpppt.android.sdk.internal.database.models.Contact;
import org.dpppt.android.sdk.internal.database.models.Handshake;
public class ContactsFactory {
private static final int WINDOW_LENGTH_IN_MINUTES = 5;
private static final int WINDOW_DURATION = WINDOW_LENGTH_IN_MINUTES * 60 * 1000;
public static List<Contact> mergeHandshakesToContacts(Context context, List<Handshake> handshakes) {
HashMap<EphId, List<Handshake>> handshakeMapping = new HashMap<>();
AppConfigManager appConfigManager = AppConfigManager.getInstance(context);
// group handhakes by id
for (Handshake handshake : handshakes) {
if (!handshakeMapping.containsKey(handshake.getEphId())) {
handshakeMapping.put(handshake.getEphId(), new ArrayList<>());
}
handshakeMapping.get(handshake.getEphId()).add(handshake);
}
//filter result to only contain actual contacts in close proximity
List<Contact> contacts = new ArrayList<>();
for (List<Handshake> handshakeList : handshakeMapping.values()) {
int contactCounter = 0;
long ketjuStartDate = 0;
long ketjuEndDate = 0;
List<Double> ketjuMeans = new ArrayList<>();
long startTime = min(handshakeList, (h) -> h.getTimestamp());
ketjuStartDate = startTime;
for (long offset = 0; offset < CryptoModule.MILLISECONDS_PER_EPOCH; offset += WINDOW_DURATION) {
long windowStart = startTime + offset;
long windowEnd = startTime + offset + WINDOW_DURATION;
ketjuEndDate = windowEnd;
Double windowMean = mean(handshakeList, (h) -> h.getTimestamp() >= windowStart && h.getTimestamp() < windowEnd);
if (windowMean != null && windowMean < appConfigManager.getContactAttenuationThreshold()) {
ketjuMeans.add(windowMean);
contactCounter++;
}
}
if (contactCounter > 0) {
int ketjuMinutes = contactCounter * WINDOW_LENGTH_IN_MINUTES;
double ketjuMeanAttenuation = average(ketjuMeans);
double ketjuMeanDistance = Math.pow(10, ketjuMeanAttenuation / 20) / 1000.0;
EphId ephId = handshakeList.get(0).getEphId();
contacts.add(
new Contact(-1, floorTimestampToBucket(handshakeList.get(0).getTimestamp()),
ephId,
contactCounter,
0,
ephId.getKetjuUserPrefix(), ketjuStartDate, ketjuEndDate, ketjuMinutes, ketjuMeanAttenuation, ketjuMeanDistance));
}
}
return contacts;
}
private static Double mean(List<Handshake> handshakes, Condition condition) {
Double valueSum = null;
int count = 0;
for (Handshake handshake : handshakes) {
if (condition.test(handshake)) {
if (valueSum == null) {
valueSum = 0.0;
}
valueSum += handshake.getAttenuation();
count++;
}
}
if (valueSum != null) {
return valueSum / count;
} else {
return null;
}
}
private static double average(List<Double> list) {
Double sum = 0.0;
if(!list.isEmpty()) {
for (Double item: list) {
sum += item;
}
return sum / list.size();
}
return sum;
}
private static <T> Long min(List<T> values, ToLongConverter<T> converter) {
Long min = null;
for (T val : values) {
if (min == null || converter.toLong(val) < min) {
min = converter.toLong(val);
}
}
return min;
}
private interface Condition {
boolean test(Handshake handshake);
}
private interface ToLongConverter<T> {
long toLong(T value);
}
private static long floorTimestampToBucket(long timestamp) {
return timestamp - (timestamp % BackendBucketRepository.BATCH_LENGTH);
}
}
| 29.478261 | 122 | 0.707227 |
ee447c1658025be8d37b8414f5449eee3e3254ea | 3,112 | /*
* Copyright 2018-present KunMinX
*
* 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.kunminx.puremusic.ui.callback;
import androidx.lifecycle.ViewModel;
import com.kunminx.architecture.ui.callback.ProtectedUnPeekLiveData;
import com.kunminx.architecture.ui.callback.UnPeekLiveData;
/**
* TODO tip 1:callback-ViewModel 的职责仅限于在 "跨页面通信" 的场景下,承担 "唯一可信源",
* 所有跨页面的 "状态同步请求" 都交由该可信源在内部决策和处理,并统一分发给所有订阅者页面。
* <p>
* 如果这样说还不理解的话,详见《LiveData 鲜为人知的 身世背景 和 独特使命》中结合实际场合 对"唯一可信源"本质的解析。
* https://xiaozhuanlan.com/topic/0168753249
*
* <p>
* Create by KunMinX at 19/10/16
*/
public class SharedViewModel extends ViewModel {
//TODO tip 2:此处演示通过 UnPeekLiveData 配合 SharedViewModel 来发送 生命周期安全的、
// 确保消息同步一致性和可靠性的 "跨页面" 通知。
//TODO tip 3:并且,在 "页面通信" 的场景下,使用全局 ViewModel,是因为它被封装在 base 页面中,
// 避免页面之外的组件拿到,从而造成不可预期的推送。
// 而且尽可能使用单例或 ViewModel 托管 liveData,这样能利用好 LiveData "读写分离" 的特性
// 来实现 "唯一可信源" 单向数据流的决策和分发,从而避免只读数据被篡改 导致的其他页面拿到脏数据。
// 如果这么说还不理解的话,
// 详见 https://xiaozhuanlan.com/topic/0168753249 和 https://xiaozhuanlan.com/topic/6257931840
private final UnPeekLiveData<Boolean> toCloseSlidePanelIfExpanded = new UnPeekLiveData<>();
private final UnPeekLiveData<Boolean> toCloseActivityIfAllowed = new UnPeekLiveData<>();
private final UnPeekLiveData<Boolean> toOpenOrCloseDrawer = new UnPeekLiveData<>();
//TODO tip 4:可以通过构造器的方式来配置 UnPeekLiveData
// 具体存在有缘和使用方式可详见《LiveData 数据倒灌 背景缘由全貌 独家解析》
// https://xiaozhuanlan.com/topic/6719328450
private final UnPeekLiveData<Boolean> toAddSlideListener =
new UnPeekLiveData.Builder<Boolean>().setAllowNullValue(false).create();
public ProtectedUnPeekLiveData<Boolean> isToAddSlideListener() {
return toAddSlideListener;
}
public ProtectedUnPeekLiveData<Boolean> isToCloseSlidePanelIfExpanded() {
return toCloseSlidePanelIfExpanded;
}
public ProtectedUnPeekLiveData<Boolean> isToCloseActivityIfAllowed() {
return toCloseActivityIfAllowed;
}
public ProtectedUnPeekLiveData<Boolean> isToOpenOrCloseDrawer() {
return toOpenOrCloseDrawer;
}
public void requestToCloseActivityIfAllowed(boolean allow) {
toCloseActivityIfAllowed.setValue(allow);
}
public void requestToOpenOrCloseDrawer(boolean open) {
toOpenOrCloseDrawer.setValue(open);
}
public void requestToCloseSlidePanelIfExpanded(boolean close) {
toCloseSlidePanelIfExpanded.setValue(close);
}
public void requestToAddSlideListener(boolean add) {
toAddSlideListener.setValue(add);
}
}
| 33.462366 | 95 | 0.742931 |
836a4b7264364aef878c29715099a7c233f315c7 | 5,455 | package xworker.swt.actions;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.FileDialog;
import org.eclipse.swt.widgets.Shell;
import org.xmeta.ActionContext;
import org.xmeta.Thing;
import org.xmeta.World;
import org.xmeta.util.UtilData;
import org.xmeta.util.UtilMap;
import org.xmeta.util.UtilString;
import ognl.OgnlException;
import xworker.swt.util.SwtUtils;
import xworker.util.XWorkerUtils;
public class FileDialogActions {
public static Object run(ActionContext actionContext){
Thing self = (Thing) actionContext.get("self");
Shell shell = (Shell) self.doAction("getShell", actionContext);
if(shell == null){
//如果没有使用IDE
shell = (Shell) XWorkerUtils.getIDEShell();
}
int style = SWT.OPEN;
String s = self.getStringBlankAsNull("style");
if("SAVE".equals(s)){
style = SWT.SAVE;
}else if("MULTI".equals(s)){
style = SWT.MULTI;
}
if(SwtUtils.isRWT()) {
ActionContext ac = new ActionContext();
ac.put("parent", shell);
ac.put("thing", self);
ac.put("parentContext", actionContext);
String filePath = self.doAction("getFilterPath", actionContext);
if(filePath == null) {
filePath = ".";
}
ac.put("filePath", filePath);
Thing dialogThing = World.getInstance().getThing("xworker.swt.actions.prototypes.RWTFileDialog");
Shell dialogShell = dialogThing.doAction("create", ac);
dialogShell.setVisible(true);
return null;
}else {
FileDialog dialog = new FileDialog(shell, style);
String fileName = (String) self.doAction("getFileName", actionContext);
String text = (String) self.doAction("getText", actionContext);
String[] filterExtensions = (String[]) self.doAction("getFilterExtensions", actionContext);
Integer filterIndex = (Integer) self.doAction("getFilterIndex", actionContext);
String[] filterNames = (String[]) self.doAction("getFilterNames", actionContext);
String filterPath = (String) self.doAction("getFilterPath", actionContext);
Boolean overwrite = (Boolean) self.doAction("getOverwrite", actionContext);
if(fileName != null){
dialog.setFileName(fileName);
}
if(filterExtensions != null){
dialog.setFilterExtensions(filterExtensions);
}
if(filterIndex != null){
dialog.setFilterIndex(filterIndex);
}
if(filterNames != null){
dialog.setFilterNames(filterNames);
}
if(filterPath != null){
dialog.setFilterPath(filterPath);
}
if(overwrite != null){
dialog.setOverwrite(overwrite);
}
if(text != null){
dialog.setText(text);
}
String f = dialog.open();
if(f != null){
self.doAction("onSelected", actionContext, "fileName", f);
}else{
self.doAction("onUnSelected", actionContext, "fileName", f);
}
return self.doAction("open", actionContext, UtilMap.toMap("fileName", f));
}
}
public static Object open(ActionContext actionContext){
//Thing self = (Thing) actionContext.get("self");
//logger.info(self.getMetadata().getPath() + " open:" + actionContext.get("fileName"));
return actionContext.get("fileName");
}
public static Object getShell(ActionContext actionContext) throws OgnlException{
Thing self = (Thing) actionContext.get("self");
Object obj = UtilData.getData(self, "shell", actionContext);
Shell shell = null;
if(obj instanceof String){
shell = (Shell) actionContext.get((String) obj);
}else if(obj instanceof Shell){
shell = (Shell) obj;
}
if(shell == null){
shell = Display.getCurrent().getActiveShell();
}
if(shell == null){
shell = (Shell) XWorkerUtils.getIDEShell();
}
return shell;
}
public static Object getFileName(ActionContext actionContext){
Thing self = (Thing) actionContext.get("self");
return UtilString.getString(self, "fileName", actionContext);
}
public static Object getText(ActionContext actionContext){
Thing self = (Thing) actionContext.get("self");
return UtilString.getString(self, "text", actionContext);
}
public static Object getFilterExtensions(ActionContext actionContext){
Thing self = (Thing) actionContext.get("self");
String filterExtensions = self.getStringBlankAsNull("filterExtensions");
if(filterExtensions != null){
return filterExtensions.split("[,]");
}else{
return null;
}
}
public static Object getFilterIndex(ActionContext actionContext){
Thing self = (Thing) actionContext.get("self");
if(self.getStringBlankAsNull("filterIndex") != null){
return self.getInt("filterIndex");
}else{
return null;
}
}
public static Object getFilterNames(ActionContext actionContext){
Thing self = (Thing) actionContext.get("self");
String filterExtensions = self.getStringBlankAsNull("filterNames");
if(filterExtensions != null){
return filterExtensions.split("[,]");
}else{
return null;
}
}
public static Object getFilterPath(ActionContext actionContext){
Thing self = (Thing) actionContext.get("self");
return UtilString.getString(self, "filterPath", actionContext);
}
public static Object getOverwrite(ActionContext actionContext){
Thing self = (Thing) actionContext.get("self");
return self.getBoolean("overwrite");
}
}
| 32.088235 | 107 | 0.672777 |
2f3ef2706e3b41a666dff8b7c9a5c540eb76d3f6 | 5,290 | package com.test.basequickadapterlib.head;
import android.content.Context;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.test.basequickadapterlib.BaseAdapterHelper;
import java.util.ArrayList;
/**
* Created by qibin on 2015/11/5.
*/
public abstract class BaseHeadRecyclerAdapter<T> extends RecyclerView.Adapter<BaseAdapterHelper> implements View.OnClickListener {
protected final Context context;
protected final int layoutResId;
public static final int TYPE_HEADER = 0;
public static final int TYPE_NORMAL = 1;
protected ArrayList<T> mDatas = new ArrayList<>();
protected View mHeaderView;
protected int animID;
private OnItemClickListener mOnItemClickListener = null;
/**
* Create a QuickAdapter.
*
* @param context The context.
* @param layoutResId The layout resource id of each item.
*/
public BaseHeadRecyclerAdapter(Context context, int layoutResId) {
this(context, layoutResId, null);
}
/**
* Same as QuickAdapter#QuickAdapter(Context,int) but with
* some initialization data.
*
* @param context The context.
* @param layoutResId The layout resource id of each item.
* @param mDatas A new list is created out of this one to avoid mutable list
*/
public BaseHeadRecyclerAdapter(Context context, int layoutResId, ArrayList<T> mDatas) {
this.mDatas = mDatas == null ? new ArrayList<T>() : mDatas;
this.context = context;
this.layoutResId = layoutResId;
}
public void setAnimID(int animID) {
this.animID = animID;
}
public void setHeaderView(View headerView) {
mHeaderView = headerView;
notifyItemInserted(0);
}
public View getHeaderView() {
return mHeaderView;
}
public void addDatas(ArrayList<T> datas) {
mDatas.addAll(datas);
notifyDataSetChanged();
}
@Override
public int getItemViewType(int position) {
if (mHeaderView == null) return TYPE_NORMAL;
if (position == 0) return TYPE_HEADER;
return TYPE_NORMAL;
}
@Override
public BaseAdapterHelper onCreateViewHolder(ViewGroup parent, final int viewType) {
if (mHeaderView != null && viewType == TYPE_HEADER) return new Holder(mHeaderView);
View view = LayoutInflater.from(parent.getContext()).inflate(layoutResId, parent, false);
view.setOnClickListener(this);
BaseAdapterHelper vh = new BaseAdapterHelper(view);
return vh;
}
@Override
public void onBindViewHolder(BaseAdapterHelper viewHolder, int position) {
if (getItemViewType(position) == TYPE_HEADER) return;
final int pos = getRealPosition(viewHolder);
final T data = mDatas.get(pos);
onBind(viewHolder, pos, position, data);
}
@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
RecyclerView.LayoutManager manager = recyclerView.getLayoutManager();
if (manager instanceof GridLayoutManager) {
final GridLayoutManager gridManager = ((GridLayoutManager) manager);
gridManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
@Override
public int getSpanSize(int position) {
return getItemViewType(position) == TYPE_HEADER
? gridManager.getSpanCount() : 1;
}
});
}
}
@Override
public void onViewAttachedToWindow(BaseAdapterHelper holder) {
super.onViewAttachedToWindow(holder);
ViewGroup.LayoutParams lp = holder.itemView.getLayoutParams();
if (lp != null
&& lp instanceof StaggeredGridLayoutManager.LayoutParams
&& holder.getLayoutPosition() == 0) {
StaggeredGridLayoutManager.LayoutParams p = (StaggeredGridLayoutManager.LayoutParams) lp;
p.setFullSpan(true);
}
}
public int getRealPosition(BaseAdapterHelper holder) {
int position = holder.getLayoutPosition();
return mHeaderView == null ? position : position - 1;
}
@Override
public int getItemCount() {
return mHeaderView == null ? mDatas.size() : mDatas.size() + 1;
}
public abstract void onBind(BaseAdapterHelper viewHolder, int RealPosition, int position, T data);
@Override
public void onClick(View v) {
if (v == null) {
return;
}
if (mOnItemClickListener != null) {
mOnItemClickListener.onItemClick(v, (int) v.getTag());
}
}
public void setOnItemClickListener(OnItemClickListener listener) {
this.mOnItemClickListener = listener;
}
//define interface
public static interface OnItemClickListener {
void onItemClick(View view, int position);
}
public class Holder extends BaseAdapterHelper {
public Holder(View itemView) {
super(itemView);
}
}
}
| 30.228571 | 130 | 0.66087 |
a8aaacaaaa3b11d01b46c5befebb3f6ba1755fae | 1,117 |
public class PrintInitials {
/* This program prints my initials (DJE) in big letters,
where each letter is nine lines tall.
*/
public static void main(String[] args) {
System.out.println();
System.out.println(" ****** ************* **********");
System.out.println(" ** ** ** **");
System.out.println(" ** ** ** **");
System.out.println(" ** ** ** **");
System.out.println(" ** ** ** ********");
System.out.println(" ** ** ** ** **");
System.out.println(" ** ** ** ** **");
System.out.println(" ** ** ** ** **");
System.out.println(" ***** **** **********");
System.out.println();
} // end main()
} // end class
| 48.565217 | 92 | 0.283796 |
f271cb89809e8d63fe2f7ef6b710e1200b42f55a | 410 | package bio.singa.structure.parser.pdb.structures.iterators.sources;
import java.util.Iterator;
import java.util.List;
/**
* @author cl
*/
public interface SourceIterator<SourceContent, ContentType> extends Iterator<SourceContent> {
List<SourceContent> getSources();
ContentType getContent(SourceContent source);
boolean hasChain();
String getChain();
List<String> getChains();
}
| 18.636364 | 93 | 0.739024 |
b91740559136d930dda1c1fc99f5e26df178d75b | 2,941 | /*
* Copyright (C) 2014 Dell, 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.dell.doradus.olap.aggregate.mr;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.dell.doradus.olap.collections.BdLongSet;
import com.dell.doradus.olap.store.CubeSearcher;
import com.dell.doradus.search.aggregate.AggregationGroup;
import com.dell.doradus.search.aggregate.AggregationGroupItem;
public class MFCollectorSet {
private static Logger LOG = LoggerFactory.getLogger("MFCollectorSet");
public MFCollector[] collectors;
public MFCollector commonPartCollector;
public MFCollectorSet(CubeSearcher searcher, List<AggregationGroup> groups, boolean allowCommonPart) {
int commonIndex = 0;
// common parts in groups
if(allowCommonPart) commonIndex = getCommonPart(groups);
if(commonIndex > 0) commonPartCollector = MFCollector.create(searcher, groups.get(0), 0, commonIndex);
collectors = new MFCollector[groups.size()];
for(int i = 0; i < collectors.length; i++) {
collectors[i] = MFCollector.create(searcher, groups.get(i), commonIndex, groups.get(i).items.size());
}
}
public int size() { return collectors.length; }
public void collect(long doc, BdLongSet[] values) {
for(int i = 0; i < collectors.length; i++) {
collectors[i].collect(doc, values[i]);
}
}
// Support for common paths in groups
private int getCommonPart(List<AggregationGroup> groups) {
if(groups.size() < 2) return 0;
for(int i = 0; i < groups.size(); i++) {
if(groups.get(i).filter != null) return 0;
}
int itemsCount = groups.get(0).items.size() - 1;
for(int i = 1; i < groups.size(); i++) {
itemsCount = Math.min(itemsCount, groups.get(i).items.size() - 1);
}
if(itemsCount <= 0) return 0;
int itemIndex = 0;
for(; itemIndex < itemsCount; itemIndex++) {
boolean eq = true;
AggregationGroupItem item = groups.get(0).items.get(itemIndex);
if(item.xlinkContext != null) break;
for(int i = 1; i < groups.size(); i++) {
AggregationGroupItem item2 = groups.get(i).items.get(itemIndex);
if(!item.equals(item2) || item.xlinkContext != null) {
eq = false;
break;
}
}
if(!eq) break;
}
if(itemIndex > 0) {
LOG.info("Found common path for groups: " + itemIndex);
}
return itemIndex;
}
}
| 31.623656 | 105 | 0.675621 |
ffb7b5204df8fd7c762b0fd1d8019fd60d7698aa | 1,149 | public class Solution {
public int[][] generateMatrix(int n) {
int[][] res = new int[n][n];
int rowBegin = 0;
int rowEnd = n-1;
int columnBegin = 0;
int columnEnd = n-1;
int counter = 1;
while(rowBegin <= rowEnd && columnBegin <= columnEnd){
for(int i = columnBegin; i <= columnEnd; i++){
res[rowBegin][i] = counter++;
}
rowBegin++;
for(int i = rowBegin; i <= rowEnd; i++){
res[i][columnEnd] = counter++;
}
columnEnd--;
if(rowBegin <= rowEnd){
for(int i = columnEnd; i >= columnBegin; i--){
res[rowEnd][i] = counter++;
}
}
rowEnd--;
if(columnBegin <= columnEnd){
for(int i = rowEnd; i >= rowBegin; i--){
res[i][columnBegin] = counter++;
}
}
columnBegin++;
}
return res;
}
}
| 26.113636 | 62 | 0.369887 |
31280a498d75ebf39e13eb4f27fcf12fc3a8e54f | 3,025 | /*
* 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.
*/
/**
* @author Dmitry A. Durnev
* @version $Revision$
*/
package org.apache.harmony.awt.wtk;
import java.awt.AWTEvent;
import java.awt.AWTException;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.im.spi.InputMethod;
import java.awt.im.spi.InputMethodContext;
import java.awt.im.spi.InputMethodDescriptor;
import java.lang.Character.Subset;
import java.util.Locale;
/**
* A cross-platform interface for native input
* method sub-system functionality.
*/
public abstract class NativeIM implements InputMethod, InputMethodDescriptor {
protected InputMethodContext imc;
public void activate() {
}
public void deactivate(boolean isTemporary) {
}
public void dispatchEvent(AWTEvent event) {
}
public void dispose() {
}
public void endComposition() {
}
public Object getControlObject() {
return null;
}
public Locale getLocale() {
return null;
}
public void hideWindows() {
}
public boolean isCompositionEnabled() {
return false;
}
public void notifyClientWindowChange(Rectangle bounds) {
}
public void reconvert() {
}
public void removeNotify() {
}
public void setCharacterSubsets(Subset[] subsets) {
}
public void setCompositionEnabled(boolean enable) {
}
public void setInputMethodContext(InputMethodContext context) {
imc = context;
}
public boolean setLocale(Locale locale) {
return false;
}
public Locale[] getAvailableLocales() throws AWTException {
return new Locale[]{Locale.getDefault(), Locale.ENGLISH};
}
public InputMethod createInputMethod() throws Exception {
return this;
}
public String getInputMethodDisplayName(Locale inputLocale,
Locale displayLanguage) {
return "System input methods"; //$NON-NLS-1$
}
public Image getInputMethodIcon(Locale inputLocale) {
return null;
}
public boolean hasDynamicLocaleList() {
return false;
}
public abstract void disableIME();
// public abstract void disableIME(long id);
}
| 23.269231 | 78 | 0.676694 |
Subsets and Splits