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
|
---|---|---|---|---|---|
cd60749b5a05470395b4c455a74b7cc5bebf2442 | 12,904 | package com.pogeyan.swagger.helpers;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.chemistry.opencmis.client.api.CmisObject;
import org.apache.chemistry.opencmis.client.api.Document;
import org.apache.chemistry.opencmis.client.api.Folder;
import org.apache.chemistry.opencmis.client.api.ItemIterable;
import org.apache.chemistry.opencmis.client.api.ObjectType;
import org.apache.chemistry.opencmis.client.api.OperationContext;
import org.apache.chemistry.opencmis.client.api.Session;
import org.apache.chemistry.opencmis.client.runtime.OperationContextImpl;
import org.apache.chemistry.opencmis.commons.PropertyIds;
import org.apache.chemistry.opencmis.commons.data.ContentStream;
import org.apache.chemistry.opencmis.commons.definitions.TypeDefinition;
import org.apache.chemistry.opencmis.commons.enums.BaseTypeId;
import org.apache.chemistry.opencmis.commons.enums.DateTimeFormat;
import org.apache.chemistry.opencmis.commons.impl.JSONConverter;
import org.apache.chemistry.opencmis.commons.impl.json.JSONArray;
import org.apache.chemistry.opencmis.commons.impl.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.pogeyan.swagger.api.utils.SwaggerHelpers;
public class SwaggerGetHelpers {
private static final Logger LOG = LoggerFactory.getLogger(SwaggerGetHelpers.class);
public static Map<String, ObjectType> typeMap;
@SuppressWarnings("unused")
public static JSONObject invokeGetTypeDefMethod(String repositoryId, String typeId, String userName,
String password, boolean includeRelationship) throws Exception {
Session session = SwaggerHelpers.getSession(repositoryId, userName, password);
JSONObject json = new JSONObject();
JSONArray jsonArray = new JSONArray();
ObjectType typeDefinitionObject = SwaggerHelpers.getTypeDefinition(session, typeId);
JSONObject object = JSONConverter.convert(typeDefinitionObject, DateTimeFormat.SIMPLE);
if (includeRelationship) {
LOG.debug("class name: {}, method name: {}, repositoryId: {}, for type: {}", "SwaggerGetHelpers",
"invokeGetTypeDefMethod", repositoryId, typeId);
ItemIterable<CmisObject> relationType = getRelationshipType(session, typeId);
getRelationshipChild(session, relationType, object);
}
return object;
}
private static JSONObject getRelationshipChild(Session session, ItemIterable<CmisObject> relationType,
JSONObject mainObject) throws Exception {
JSONArray jsonArray = new JSONArray();
if (relationType != null) {
for (CmisObject types : relationType) {
JSONObject childObject = new JSONObject();
Map<String, Object> propMap = SwaggerHelpers.compileProperties(types, session);
TypeDefinition typeDefinition = SwaggerHelpers.getTypeDefinition(session,
propMap.get("target_table").toString());
JSONObject object = JSONConverter.convert(typeDefinition, DateTimeFormat.SIMPLE);
propMap.forEach((k, v) -> {
if (!k.equalsIgnoreCase(PropertyIds.BASE_TYPE_ID) && !k.equalsIgnoreCase(PropertyIds.OBJECT_TYPE_ID)
&& !k.equalsIgnoreCase(PropertyIds.OBJECT_ID)) {
object.put(k, v);
}
});
ItemIterable<CmisObject> relationInnerChildType = getRelationshipType(session, typeDefinition.getId());
if (relationInnerChildType != null) {
getRelationshipChild(session, relationInnerChildType, object);
}
childObject.put(typeDefinition.getId(), object);
jsonArray.add(childObject);
}
}
mainObject.put("relations", jsonArray);
return mainObject;
}
public static ContentStream invokeDownloadMethod(String repositoryId, String typeId, String objectId,
String userName, String password) throws Exception {
Session session = SwaggerHelpers.getSession(repositoryId, userName, password);
ObjectType typeDefinitionObject = SwaggerHelpers.getTypeDefinition(session, typeId);
String typeIdName = SwaggerHelpers.getIdName(typeDefinitionObject);
String customObjectId = null;
LOG.debug("class name: {}, method name: {}, repositoryId: {}, typeId: {}, objectId: {}", "SwaggerGetHelpers",
"invokeDownloadMethod", repositoryId, typeId, objectId);
if (SwaggerHelpers.customTypeHasFolder()) {
customObjectId = typeDefinitionObject.isBaseType() ? objectId
: typeId + "::" + typeIdName + "::" + objectId;
} else {
customObjectId = objectId;
}
ContentStream stream = ((Document) session.getObject(customObjectId)).getContentStream(customObjectId);
return stream;
}
/**
* @param repositoryId the property repositoryId is identifier for the
* repository.
* @param type the property type is used to get particular type
* definition.
* @param skipCount the property skipCount is used to how many objects user
* want to skip.
* @param maxItems the property maxItems is used to how many objects want
* per page.
* @param userName the property userName is used to login the particular
* repository.
* @param password the property password is used to login the particular
* repository.
* @return list of ObjectData
* @throws Exception
*/
public static JSONObject invokeGetAllMethod(String repositoryId, String type, String parentId, String skipCount,
String maxItems, String userName, String password, String filter, String orderBy,
boolean includeRelationship) throws Exception {
JSONObject json = new JSONObject();
JSONArray arrayJson = new JSONArray();
ItemIterable<CmisObject> children = null;
Session session = SwaggerHelpers.getSession(repositoryId, userName, password);
ObjectType typeDefinitionObject = session.getTypeDefinition(type);
OperationContext context = new OperationContextImpl();
if (maxItems != null) {
context.setMaxItemsPerPage(Integer.parseInt(maxItems));
}
if (filter != null) {
if (filter.contains("*")) {
filter = filter.replace("*", typeDefinitionObject.getPropertyDefinitions().values().stream()
.map(a -> a.getId()).collect(Collectors.joining(",")));
} else {
filter = PropertyIds.NAME + "," + filter;
}
context.setFilterString(filter);
}
if (orderBy != null) {
context.setOrderBy(orderBy);
}
if (typeDefinitionObject != null && typeDefinitionObject.isBaseType()) {
if (parentId != null) {
Folder object = (Folder) session.getObject(parentId);
json.put(object.getName(), object);
children = object.getChildren(context);
} else {
if (!type.equalsIgnoreCase(BaseTypeId.CMIS_FOLDER.value())
&& !type.equalsIgnoreCase(BaseTypeId.CMIS_DOCUMENT.value())
&& !type.equalsIgnoreCase(BaseTypeId.CMIS_RELATIONSHIP.value())
&& !type.equalsIgnoreCase(BaseTypeId.CMIS_ITEM.value())
&& !type.equalsIgnoreCase(BaseTypeId.CMIS_SECONDARY.value())) {
Folder typeFolder = (Folder) session.getObjectByPath("/" + type);
parentId = typeFolder.getId();
if (parentId != null) {
json.put(typeFolder.getName(), typeFolder);
children = typeFolder.getChildren(context);
}
} else {
children = session.getRootFolder().getChildren(context);
}
}
if (skipCount != null) {
children = children.skipTo(Integer.parseInt(skipCount));
}
} else {
if (parentId != null) {
Folder object = (Folder) session.getObject(parentId);
children = object.getChildren(context);
} else {
children = ((Folder) session.getObjectByPath("/" + typeDefinitionObject.getId())).getChildren(context);
}
if (skipCount != null) {
children = children.skipTo(Integer.parseInt(skipCount));
}
}
for (CmisObject child : children.getPage()) {
if (includeRelationship) {
LOG.debug("class name: {}, method name: {}, repositoryId: {}, Fetching RelationshipType for type: {}",
"SwaggerGetHelpers", "invokeGetAllMethod", repositoryId, type);
ArrayList<Object> relationData = SwaggerHelpers.getDescendantsForRelationObjects(userName, password,
repositoryId, child.getId());
Map<String, Object> data = SwaggerGetHelpers.formRelationData(session, relationData);
json.putAll(data);
} else {
Map<String, Object> propmap = SwaggerHelpers.compileProperties(child, session);
arrayJson.add(propmap);
}
}
if (arrayJson.size() > 0) {
json.put(type, arrayJson);
}
return json;
}
/**
* @param repositoryId the property repositoryId is identifier for the
* repository.
* @param typeId the property typeId of an object-type specified in the
* repository.
* @param parentId the property parentId is used to get the object-type�s
* immediate parent type.
* @param input the property input is used to get all request parameters.
* @param userName the property userName is used to login the particular
* repository.
* @param password the property password is used to login the particular
* repository.
* @return response object
* @throws Exception
*/
public static Map<String, Object> invokeGetMethod(String repositoryId, String typeId, String objectId,
String userName, String password, String filter) throws Exception {
Session session = SwaggerHelpers.getSession(repositoryId, userName, password);
ObjectType typeDefinitionObject = SwaggerHelpers.getTypeDefinition(session, typeId);
String typeIdName = SwaggerHelpers.getIdName(typeDefinitionObject);
String customId = null;
if (SwaggerHelpers.customTypeHasFolder()) {
customId = typeDefinitionObject.isBaseType() ? objectId : typeId + "::" + typeIdName + "::" + objectId;
} else {
customId = objectId;
}
OperationContext context = new OperationContextImpl();
if (filter != null) {
context.setFilterString(filter);
}
LOG.debug("class name: {}, method name: {}, repositoryId: {}, type: {}, ObjectId: {}", "SwaggerGetHelpers",
"invokeGetMethod", repositoryId, typeId, objectId);
CmisObject object = session.getObject(customId, context);
if (object != null && typeDefinitionObject.getId().equals(object.getType().getId())) {
Map<String, Object> propMap = SwaggerHelpers.compileProperties(object, session);
return propMap;
} else {
throw new Exception("Type Missmatch");
}
}
@SuppressWarnings("unchecked")
public static Map<String, Object> formRelationData(Session session, ArrayList<Object> relationData) {
Map<String, Object> relMap = new LinkedHashMap<String, Object>();
if (relationData != null) {
relationData.forEach(relationObj -> {
JSONObject childJson = new JSONObject();
LinkedHashMap<Object, Object> relationObjectMap = (LinkedHashMap<Object, Object>) relationObj;
LinkedHashMap<Object, Object> getRelationshipData = (LinkedHashMap<Object, Object>) relationObjectMap
.get("object");
LinkedHashMap<Object, Object> getRelationshipObjectData = (LinkedHashMap<Object, Object>) getRelationshipData
.get("object");
Map<String, Object> succintProps = (Map<String, Object>) getRelationshipObjectData
.get("succinctProperties");
childJson.putAll(succintProps);
String relId = succintProps.get(PropertyIds.OBJECT_ID).toString();
ArrayList<JSONObject> list = relMap.get(relId) != null ? (ArrayList<JSONObject>) relMap.get(relId)
: new ArrayList<>();
ArrayList<Object> childrenRelationData = (ArrayList<Object>) relationObjectMap.get("children");
if (childrenRelationData != null) {
childJson.put("relation", formRelationData(session, childrenRelationData));
}
list.add(childJson);
relMap.put(relId, list);
});
}
return relMap;
}
public static ItemIterable<CmisObject> getRelationshipType(Session session, String typeId) {
ObjectType relationshipType = session.getTypeDefinition(SwaggerHelpers.CMIS_EXT_RELATIONMD);
if (relationshipType != null) {
Folder relationObject = (Folder) session.getObjectByPath("/" + relationshipType.getId());
if (relationObject != null) {
OperationContext context = new OperationContextImpl();
context.setFilterString(
"target_table,source_table,source_column,target_column,copper_relationType,source_table eq "
+ typeId);
ItemIterable<CmisObject> relationDescendants = relationObject.getChildren(context);
return relationDescendants;
}
}
return null;
}
public static JSONObject fetchAllTypes(String repositoryId, String userName, String password) throws Exception {
JSONObject typeDefinition = new JSONObject();
Session session = SwaggerHelpers.getSession(repositoryId, userName, password);
SwaggerHelpers.getAllTypes(session);
typeDefinition.putAll(SwaggerHelpers.getTypeMap().entrySet().stream().collect(Collectors
.toMap(key -> key.getKey(), value -> JSONConverter.convert(value.getValue(), DateTimeFormat.SIMPLE))));
return typeDefinition;
}
}
| 44.343643 | 113 | 0.727914 |
ac10a56ae78746c0d905f02b7750f939a47718e2 | 490 | package uk.nhs.cdss.model.enums;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import uk.nhs.cdss.constants.Systems;
@Getter
@RequiredArgsConstructor
public enum IdentifierType implements Concept {
SDS("SDS user id", "https://fhir.nhs.uk/Id/sds-user-id"),
SDSR("SDS role", "https://fhir.nhs.uk/Id/sds-role-profile-id"),
OC("ODS organisation code", Systems.ODS);
private final String value = name();
private final String display;
private final String system;
}
| 27.222222 | 65 | 0.74898 |
deb450ad427c0a2c2ffecae6713c0d2501c25a13 | 1,151 | package com.javaweb.queue.activemq;
import org.apache.activemq.command.ActiveMQMapMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.jms.MapMessage;
import javax.jms.Queue;
import javax.jms.Topic;
/**
* 短信消息生产者
*/
@Component
public class ActiveMQSmsSend {
// 注入JmsMessagingTemplate
@Autowired
private JmsMessagingTemplate jmsMessagingTemplate;
@Autowired
private Queue queue;
@Autowired
private Topic topic;
// /**
// * 使用ActiveMQ Server 服务
// * 每隔30秒发送一次消息,将消息放入队列
// */
// @Scheduled(fixedDelay = 3000)
// public void sendSms() {
// try {
//
// MapMessage mapMessage = new ActiveMQMapMessage();
// mapMessage.setString("info", "你还在睡觉");
// this.jmsMessagingTemplate.convertAndSend(this.queue, mapMessage);
//
// } catch (Exception e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
}
| 23.979167 | 79 | 0.675065 |
8493128489ff8770115d8f60d961ef78dd296c36 | 1,334 | package g_ISPandDIP.Exercises.BoatRacingSimulator.engines;
import g_ISPandDIP.Exercises.BoatRacingSimulator.contracts.CommandHandler;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Engine implements Runnable {
private static final String TERMINATE_COMMAND = "End";
private CommandHandler commandHandler;
private BufferedReader reader;
public Engine(CommandHandler commandHandler) {
this.commandHandler = commandHandler;
this.reader = new BufferedReader(new InputStreamReader(System.in));
}
@Override
public void run() {
StringBuilder output = new StringBuilder();
while (true) {
try {
String input = reader.readLine();
if (TERMINATE_COMMAND.equals(input)) {
break;
}
String[] arguments = input.split("\\\\");
String commandResult = this.commandHandler.executeCommand(arguments);
output.append(commandResult).append(System.lineSeparator());
} catch (Exception exception) {
output.append(exception.getMessage()).append(System.lineSeparator());
}
}
if (output.length() > 0) {
System.out.println(output.toString().trim());
}
}
}
| 30.318182 | 85 | 0.625937 |
2da1b680398f3d997b24536b794cd79f80d07024 | 603 | package juanf846.javaSimpleCLI.annotations;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import juanf846.javaSimpleCLI.Shell;
/**
* Un metodo anotado con {@link Help} será invocado cuando el usuario escriba
* <code>help nombreComando</code> en el shell, este metodo debe devolver un
* String el cual se imprime en el shell.
*
* @see Shell#addCommand(Object)
* @author juanf846
*
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD })
public @interface Help {
} | 27.409091 | 77 | 0.774461 |
ca85cfdc89345a505cf295ff3a028be337218211 | 954 | package com.lib.bridge.core.implement;
import com.lib.bridge.core.LibResponse;
/**
* 请求返回数据基类
*
* Created by jimmy on 2017/7/15.
*/
public class LibBaseResponse implements LibResponse {
public static final int STATUS_CODE_SUCCESS = 0;
/** 请求结果状态码 */
private int statusCode;
/** 请求结果数据 */
private Object data;
public LibBaseResponse() {
}
public LibBaseResponse(Object data) {
this(STATUS_CODE_SUCCESS, data);
}
public LibBaseResponse(int statusCode, Object data) {
this.statusCode = statusCode;
this.data = data;
}
@Override
public void setStatusCode(int statusCode) {
this.statusCode = statusCode;
}
@Override
public int getStatusCode() {
return this.statusCode;
}
@Override
public void setData(Object data) {
this.data = data;
}
@Override
public Object getData() {
return this.data;
}
}
| 18 | 57 | 0.626834 |
f0d996b79bee1fe86bb6310b3d476670a36a00b7 | 48,004 | /*
Syntax is distributed under the Revised, or 3-clause BSD license
===============================================================================
Copyright (c) 1985, 2012, 2016, Jaime Garza
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
===============================================================================
*/
package me.jaimegarza.syntax.generator;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Stack;
import me.jaimegarza.syntax.EmbeddedCodeProcessor;
import me.jaimegarza.syntax.Lexer;
import me.jaimegarza.syntax.env.Environment;
import me.jaimegarza.syntax.exception.ParsingException;
import me.jaimegarza.syntax.graph.SvgRenderer;
import me.jaimegarza.syntax.model.graph.Dfa;
import me.jaimegarza.syntax.model.parser.Associativity;
import me.jaimegarza.syntax.model.parser.ErrorToken;
import me.jaimegarza.syntax.model.parser.NonTerminal;
import me.jaimegarza.syntax.model.parser.Rule;
import me.jaimegarza.syntax.model.parser.RuleItem;
import me.jaimegarza.syntax.model.parser.Symbol;
import me.jaimegarza.syntax.model.parser.Terminal;
import me.jaimegarza.syntax.model.parser.TokenGroup;
import me.jaimegarza.syntax.model.parser.Type;
import me.jaimegarza.syntax.util.FormattingPrintStream;
import me.jaimegarza.syntax.util.PathUtils;
/**
* This class contains the "non-parser" code, or supporting code for the syntax
* parser.<p>
*
* This is done so that the CodeParser can be generated from a syntaxt file
*
* @author jgarza
*
*/
public abstract class AbstractCodeParser extends AbstractPhase implements Lexer, EmbeddedCodeProcessor {
private static final String DEFAULT_LEXER_MODE = "default";
protected static final String DISTINGUISHED_SYMBOL_NAME = "$start";
private static final int GRAPH_WIDTH = 200;
private static final int GRAPH_HEIGH = 200;
protected Stack<Character> inputChars = new Stack<Character>();
protected boolean bActionDone = false;
protected int currentRuleIndex;
protected Type currentType;
protected int markers = 0;
protected boolean isCurlyBrace;
protected boolean isEqual;
protected boolean isRegexSlash;
protected boolean isError;
protected int tokenNumber;
protected String currentNonTerminalName;
protected boolean mustClose;
protected boolean finalActions;
protected boolean isErrorToken;
protected Associativity ruleAssociativity;
protected int rulePrecedence;
protected int tokenActionCount;
protected int actLine;
protected boolean isFirstToken = true;
protected int numberOfErrorTokens;
public char currentChar;
public String recognized;
/**
* Default Constructor
* @param environment is the syntax environment
*/
public AbstractCodeParser(Environment environment) {
super(environment);
}
/**
* Declare a token
* @param id is the short name of the token
* @param isErrorToken specifies if this token was declared with %error
* @param associativity defines if a token is defined with %left, %right, etc.
* @param precedence is the numeric precedence of the token
* @param type is the type of the non-terminal
* @param tokenNumber is the number of the token, or its value
* @param fullName is the fullname, if given, of the token
* @return true if OK
*/
protected Terminal declareOneTerminal(String id, boolean isErrorToken, Associativity associativity, int precedence, Type type, int tokenNumber, String fullName) {
Terminal terminal = runtimeData.findTerminalByName(id);
if (terminal == null) {
terminal = isErrorToken ? new ErrorToken(id) : new Terminal(id);
runtimeData.getTerminals().add(terminal);
}
terminal.setCount(terminal.getCount() - 1);
if (associativity != Associativity.NONE) {
if (terminal.getAssociativity() != Associativity.NONE) {
environment.error(-1, "Reassigning precedence/associativity for token \'%s\'.", terminal.getName());
return null;
}
terminal.setPrecedence(precedence);
terminal.setAssociativity(associativity);
}
if (type != null) {
terminal.setType(type);
type.addUsage(terminal);
}
if (tokenNumber >= 0) {
if (terminal.getToken() != -1 && terminal.getToken() != tokenNumber) {
environment.error(-1, "Warning: Token \'%s\' already has a value.", terminal.getName());
}
for (Terminal t : runtimeData.getTerminals()) {
if (t != terminal && t.getToken() == tokenNumber) {
environment.error(-1, "Warning: Token number %d already used on token \'%s\'.",
tokenNumber, t.getName());
return null;
}
}
terminal.setToken(tokenNumber);
}
if (fullName != "" && fullName != null) {
terminal.setFullName(fullName);
}
//if ($4 != null) {
// SetEndToken($4, terminal.getName());
//}
return terminal;
}
/**
* Declare one non terminal in the symbol table
* @param typeName the desired type
* @param name the name of the symbol
* @return true if OK
*/
protected boolean declareOneNonTerminal(String typeName, String name) {
if (runtimeData.findTerminalByName(name) != null) {
environment.error(-1, "Token \'%s\' cannot appear on a %%type clause.", name);
return false;
}
NonTerminal nonTerminal = runtimeData.findNonTerminalByName(name);
if (nonTerminal == null) {
nonTerminal = new NonTerminal(name);
runtimeData.getNonTerminals().add(nonTerminal);
} else {
nonTerminal.setCount(nonTerminal.getCount() - 1);
}
Type type = new Type(typeName);
if (runtimeData.getTypes().contains(type)) {
type = runtimeData.getTypes().get(runtimeData.getTypes().indexOf(type));
} else {
runtimeData.getTypes().add(type);
}
type.addUsage(nonTerminal);
nonTerminal.setType(type);
return true;
}
/**
* Declare one given type
* @param typeName the desired type
* @return true if OK
*/
protected boolean declareOneType(String typeName) {
Type type = runtimeData.findType(typeName);
if (type != null) {
environment.error(-1, "Type \'%s\' already declared.", typeName);
return false;
}
type = new Type(typeName);
runtimeData.getTypes().add(type);
return true;
}
/**
* Adds one rule item to the current list of items
* @param symbolName the name of the symbol being used
* @param value the integer value of the symbol
* @param mustClose whether this token must close
* @return true if OK
*/
public boolean declareOneItem(String symbolName, int value, boolean mustClose) {
if (isFirstToken) {
rulePrecedence = 0;
ruleAssociativity = Associativity.NONE;
isFirstToken = false;
}
if (bActionDone) {
Rule stx = newEmptyRule();
String rootName = "$code-fragment-" + (runtimeData.codeRule++);
NonTerminal codeFragment = new NonTerminal(rootName);
codeFragment.setCodeFragment(true);
runtimeData.getNonTerminals().add(codeFragment);
stx.setLeftHand(codeFragment);
codeFragment.setCount(codeFragment.getCount() + 1);
codeFragment.setPrecedence(1); /* used as non terminal */
newItem(codeFragment);
//stx.getItems().add(item);
bActionDone = false;
}
Symbol symbol;
NonTerminal nonTerminal = runtimeData.findNonTerminalByName(symbolName);
if (nonTerminal == null) {
Terminal terminal = runtimeData.findTerminalByName(symbolName);
if (terminal != null) {
rulePrecedence = terminal.getPrecedence();
ruleAssociativity = terminal.getAssociativity();
symbol = terminal;
} else {
if (mustClose && value >= 0) {
terminal = new Terminal(symbolName);
runtimeData.getTerminals().add(terminal);
if (value >= 0) {
for (Terminal cual : runtimeData.getTerminals()) {
if (cual != terminal && cual.getToken() == value) {
environment.error(-1, "Warning: Token number %d already used on token \'%s\'.",
value, cual.getName());
return false;
}
}
terminal.setToken(value);
}
symbol = terminal;
} else {
nonTerminal = new NonTerminal(symbolName);
runtimeData.getNonTerminals().add(nonTerminal);
nonTerminal.setCount(nonTerminal.getCount() + 1);
symbol = nonTerminal;
}
}
} else {
symbol = nonTerminal;
}
newItem(symbol);
return true;
}
/**
* group a list of tokens
* @param tokens the list of tokens
* @param groupName the name of the group
* @param displayName the display name of the group
* @return true if OK
*/
public boolean groupTokens(List<String> tokens, String groupName, String displayName) {
List<Terminal> terminals = new LinkedList<Terminal>();
for (String tokenName : tokens) {
Terminal terminal = runtimeData.findTerminalByName(tokenName);
if (terminal == null) {
environment.error(-1, "The token " + tokenName + " has not been defined. Grouping cannot proceed.");
return false;
}
terminals.add(terminal);
}
TokenGroup group = new TokenGroup(terminals, groupName, displayName);
runtimeData.getErrorGroups().add(group);
return true;
}
/**
* A %prec was given, and as such I need to load its context globally
* @param tokenName is the name of the token given in the %prec
* @return true on success
*/
public boolean computeAssociativityAndPrecedence(String tokenName) {
NonTerminal nonTerminal = runtimeData.findNonTerminalByName(tokenName);
if (nonTerminal == null) {
Terminal terminal = runtimeData.findTerminalByName(tokenName);
if (terminal == null) {
environment.error(-1, "Warning: token \'%s\' not declared.", tokenName);
return false;
} else {
rulePrecedence = terminal.getPrecedence();
ruleAssociativity = terminal.getAssociativity();
}
} else {
environment.error(-1, "Warning: token \'%s\' not declared as token, but as a non-terminal.", tokenName);
return false;
}
return true;
}
/**
* Change the display name of a non terminal
* @param name is the short name of the non terminal
* @param fullName is its full name
* @return true if OK
*/
protected boolean nameOneNonTerminal(String name, String fullName) {
if (runtimeData.findTerminalByName(name) != null) {
environment.error(-1, "Token \'%s\' cannot appear on a %%name clause.", name);
return false;
}
NonTerminal nonTerminal = runtimeData.findNonTerminalByName(name);
if (nonTerminal == null) {
nonTerminal = new NonTerminal(name);
runtimeData.getNonTerminals().add(nonTerminal);
} else {
nonTerminal.setCount(nonTerminal.getCount() - 1);
}
nonTerminal.setFullName(fullName);
return true;
}
/**
* This routine places the non terminal left hand of a rule
* @param name is the non terminal's name
* @return true if OK
*/
protected boolean setLeftHandOfLastRule(String name) {
if (runtimeData.findTerminalByName(name) != null) {
environment.error(-1, "The token \'%s\' cannot appear to the right of a rule.", name);
return false;
}
NonTerminal nonTerminal = runtimeData.findNonTerminalByName(name);
if (nonTerminal == null) {
nonTerminal = new NonTerminal(name);
runtimeData.getNonTerminals().add(nonTerminal);
} else {
nonTerminal.setCount(nonTerminal.getCount() - 1);
}
nonTerminal.setPrecedence(1); /* usado como no terminal */
for (int i = currentRuleIndex; i < runtimeData.getRules().size(); i++) {
Rule rule = runtimeData.getRules().get(i);
if (rule.getLeftHand() == null) {
rule.setLeftHand(nonTerminal);
}
}
bActionDone = false;
return true;
}
/**
* Use the character stream to decode one character from octal<p>
* for instance '\017'
* @return the octal entered character
*/
protected char decodeOctal() {
int iCount = 3;
char c2 = 0;
while (iCount != 0) {
c2 *= 8;
if (currentChar >= '0' && currentChar <= '7') {
c2 += currentChar - '0';
getNextCharacter();
} else if (currentChar == '\0') {
return c2;
} else {
break;
}
iCount--;
}
return c2;
}
/**
* Use the character stream to decode a control char<p>
* \a - \z
* @return the control char
*/
protected char decodeControlChar() {
char c2;
getNextCharacter();
if (currentChar == '\0') {
return '\0';
}
if (currentChar >= 'a' && currentChar <= 'z') {
c2 = currentChar;
getNextCharacter();
return (char) (c2 - ('a' - 1));
} else if (currentChar >= 'A' && currentChar <= 'Z') {
c2 = currentChar;
getNextCharacter();
return (char) (c2 - ('A' - 1));
} else {
return 'c' - 'a';
}
}
/**
* Use the character stream to decode a character entered with hex codes<P>
* for instance \x1f
* @return the character
*/
protected char decodeHex() {
int iCount = 2;
char c2 = 0;
getNextCharacter();
while (iCount != 0) {
c2 *= 16;
if (currentChar >= '0' && currentChar <= '9') {
c2 += currentChar - '0';
} else if (currentChar >= 'a' && currentChar <= 'f') {
c2 += 10 + (currentChar - 'a');
} else if (currentChar >= 'A' && currentChar <= 'F') {
c2 += 10 + (currentChar - 'A');
} else if (currentChar == '\0') {
return '\0';
} else {
return 'x' - 'a';
}
iCount--;
}
return c2;
}
/**
* Use the character stream to decode the next escaped character
* (i.e. hex, octal, control)
* @return the encoded character
*/
protected char decodeEscape() {
char c2;
switch (currentChar) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
return decodeOctal();
case 'a':
getNextCharacter();
return 7;
case 'b':
getNextCharacter();
return '\b';
case 'c':
getNextCharacter();
return decodeControlChar();
case 'e':
getNextCharacter();
return '\\';
case 'f':
getNextCharacter();
return '\f';
case 'n':
getNextCharacter();
return '\n';
case 'r':
getNextCharacter();
return '\r';
case 't':
getNextCharacter();
return '\t';
case 'v':
getNextCharacter();
return 11;
case 'x':
getNextCharacter();
return decodeHex();
default:
c2 = currentChar;
getNextCharacter();
return c2;
}
}
@Override
/**
* Get the next character. It can go to the stack of chars as needed
* @return the next character
*/
public char getNextCharacter() {
if (inputChars.size() > 0) {
currentChar = inputChars.pop();
if (currentChar == '\n') {
runtimeData.lineNumber++;
runtimeData.columnNumber = 0;
}
runtimeData.columnNumber++;
return currentChar;
}
// Get one char from stream
try {
int rc = environment.source.read();
currentChar = (char) rc;
// EOF?
if (rc == -1) {
currentChar = 0;
}
} catch (IOException e) {
currentChar = 0;
}
if (currentChar == -1 || currentChar == 0) {
return 0;
}
// EOL?
if (currentChar == '\n') {
runtimeData.lineNumber++;
runtimeData.columnNumber = 0;
}
// CTRL-Z? <-- suspect code
if (currentChar == 26) {
return 0;
}
runtimeData.columnNumber++;
return currentChar;
}
@Override
public void ungetChar(char c) {
inputChars.push(c);
if (c == '\n') {
runtimeData.lineNumber--;
}
}
@Override
public char getCurrentCharacter() {
return currentChar;
}
/****************************EMBEDDED CODE PROCESSOR **************************/
public Type getTypeFromStream(Lexer lexer) {
Type type;
String s2;
s2 = runtimeData.currentStringValue;
lexer.getNormalSymbol();
type = runtimeData.findType(runtimeData.currentStringValue);
if (type == null) {
environment.error(-1, "Warning: cannot find type '%s'. It will be declared", runtimeData.currentStringValue);
type = new Type(runtimeData.currentStringValue);
runtimeData.getTypes().add(type);
}
runtimeData.currentStringValue = s2;
return type;
}
/**
* Return the item with the given index, or null
* @param index is the offset into the rules, zero based
* @return the rule item
*/
private RuleItem getCurrentRuleItem(int index) {
RuleItem item= null;
if (runtimeData.currentRuleItems != null && index < runtimeData.currentRuleItems.size()) {
item = runtimeData.currentRuleItems.get(index);
}
return item;
}
/**
* $Letter was detected. The idea is to transform such occurrences into $$ or $digit
* occurrences by looking at the symbol whose name is given by the identifier.<p>
*
* When two rule items have the same symbol, a disambiguating index like $Symbol[1],
* $Symbol[2], etc. can be used. The Left hand symbol is only used when non indexed;
*
* @param lexer the element that will give me the lexical logic
* @param elementCount the number of elements in the rule
* @param nonTerminalId the non terminal id for the rule
* @param type the type of the element
* @return true if everything is OK
*/
public boolean generateDollarLetter(Lexer lexer, int elementCount, Type type, String nonTerminalId) {
String id = "";
while (Character.isJavaIdentifierPart(currentChar) ) {
id += currentChar;
lexer.getNextCharacter();
}
int index = -1;
if (currentChar == '[') {
lexer.getNextCharacter();
index = getDollarTextIndexFromStream();
if (index == -2) {
return false;
}
}
Symbol element = getSymbolWithName(id);
if (element == null) {
environment.error(-1, "element " + id + " not found.");
return false;
}
// check to see if this is the symbol of the rule. No indexing for $$
if (runtimeData.findNonTerminalByName(nonTerminalId).equals(element) && index == -1) {
lexer.ungetChar(currentChar);
return generateDollarDollar(lexer, elementCount, nonTerminalId, element.getType());
}
// in the rules now. Locate the rule with the symbol obtained before.
int itemIndex = 1;
int elementIndex = 0;
for (RuleItem item : runtimeData.currentRuleItems) {
if (item.getSymbol().equals(element)) {
elementIndex ++;
if (index == -1 || index == elementIndex) {
break;
}
}
itemIndex++;
}
if (itemIndex > runtimeData.currentRuleItems.size()) {
environment.error(-1, "Element " + id + " was not used in the rules.");
return false;
}
// redirect to the $digit routine by placing elements on the stack.
String s = Integer.toString(itemIndex);
ungetChar(currentChar);
for (int i = s.length()-1; i >= 0; i--) {
lexer.ungetChar(s.charAt(i));
}
lexer.getNextCharacter();
return generateDollarNumber(lexer, elementCount, type == null ? element.getType() : type, 1);
}
/**
* Obtain a symbol, either terminal or non terminal, with the given name.
* @param name the name of the symbol
* @return the symbol
*/
protected Symbol getSymbolWithName(String name) {
Symbol element = runtimeData.findNonTerminalByName(name);
if (element == null) {
element = runtimeData.findTerminalByName(name);
}
return element;
}
/**
* Find the $Letter[<digits>] digits. If <digits> start with
* a zero, octal radix is assumed.
* @return the index.
*/
protected int getDollarTextIndexFromStream() {
int index;
while (currentChar == ' ') {
getNextCharacter();
}
index = 0;
int base;
if (currentChar == '0') {
base = 8;
} else {
base = 10;
}
while (Character.isDigit(currentChar)) {
index = index * base + currentChar - '0';
getNextCharacter();
}
while (currentChar == ' ') {
getNextCharacter();
}
if (currentChar != ']') {
environment.error(-1, "Unfinished index detected.");
return -2;
}
getNextCharacter();
return index;
}
/**
* $1, $2, $-3, etc detected. Proceed with the code generation
*
* @param lexer the element that will give me the lexical logic
* @param elementCount the number of elements in the rule
* @param type the type of the element
* @param sign, 1 for possitive, -1 for negative
* @return true if everything is OK
*/
public boolean generateDollarNumber(Lexer lexer, int elementCount, Type type, int sign) {
int num;
int base;
num = 0;
if (currentChar == '0') {
base = 8;
} else {
base = 10;
}
while (Character.isDigit(currentChar)) {
num = num * base + currentChar - '0';
lexer.getNextCharacter();
}
num = num * sign - elementCount;
if (num > 0) {
environment.error(-1, "Incorrect value of \'$%d\'. Bigger than the number of elements.", num + elementCount);
return false;
}
if (num == 0) {
environment.output.printFragment("stxstack", "");
} else {
environment.output.printFragment("stxstack", String.format("%+d", num));
}
if (runtimeData.getTypes().size() != 0) {
if (num + elementCount <= 0 && type == null) {
environment.error(-1, "Cannot determine the type for \'$%d\'.", num + elementCount);
return false;
}
if (type == null) {
int ruleIndex = 0;
RuleItem rule = getCurrentRuleItem(0);
for (int i = 1; i < num + elementCount && rule != null; i++) {
rule = getCurrentRuleItem(++ruleIndex);
}
if (rule != null) {
Terminal terminal = runtimeData.findTerminalByName(rule.getSymbol().getName());
if (terminal != null) {
terminal.setCount(terminal.getCount() - 1);
type = terminal.getType();
} else {
NonTerminal nonTerminal = runtimeData.findNonTerminalByName(rule.getSymbol().getName());
if (nonTerminal != null) {
nonTerminal.setCount(nonTerminal.getCount() - 1);
type = nonTerminal.getType();
}
}
}
} else if (type == Type.NullType) {
type = null;
}
if (type != null) {
environment.output.printf(".%s", type.getName());
}
}
return true;
}
/**
* $$ detected. Proceed with the code generation
*
* @param lexer the element that will give me the lexical logic
* @param elementCount the number of elements in the rule
* @param nonTerminalId the non terminal id for the rule
* @param type the type of the element
* @return true if everything is OK
* */
public boolean generateDollarDollar(Lexer lexer, int elementCount, String nonTerminalId, Type type) {
if (elementCount == 1) {
environment.output.printFragment("stxstack", "");
} else if (elementCount != 0) {
environment.output.printFragment("stxstack", "-" + Integer.toString(elementCount - 1));
} else {
environment.output.printFragment("stxstack", "+1");
}
if (runtimeData.getTypes().size() != 0) {
if (type == null) {
NonTerminal idp = runtimeData.findNonTerminalByName(nonTerminalId);
if (idp != null) {
idp.setCount(idp.getCount() - 1);
type = idp.getType();
}
} else if (type == Type.NullType) {
type = null;
}
if (type != null) {
environment.output.printf(".%s", type.getName());
}
}
lexer.getNextCharacter();
return true;
}
public boolean generateConstant(Lexer lexer, char characterType) {
environment.output.print(currentChar);
while ((lexer.getNextCharacter()) != characterType) {
if (currentChar == '\0') {
environment.error(-1, "Statement ' .. ' or \" .. \" not ended.");
return false;
}
if (currentChar == '\n') {
environment.error(-1, "End of line reached on string literal.");
return false;
}
if (currentChar == '\\') {
environment.output.print(currentChar);
lexer.getNextCharacter();
}
environment.output.print(currentChar);
}
return true;
}
public boolean skipAndOutputCompositeComment(Lexer lexer, char secondaryCharacter, char characterToFind) {
boolean bBreak;
environment.output.print(currentChar);
lexer.getNextCharacter();
bBreak = false;
while (!bBreak) {
if (currentChar == '\0') {
environment.error(-1, "Unfinished comment.");
return false;
}
while (currentChar == secondaryCharacter) {
environment.output.print(currentChar);
if ((lexer.getNextCharacter()) == characterToFind) {
bBreak = true;
}
}
environment.output.print(currentChar);
lexer.getNextCharacter();
}
return true;
}
/**
* A statement for code generation was found. Finish it.
*/
protected void generateCaseEnd() {
environment.language.generateCaseEnd();
}
/**
* Output the case for a given rule
* @param ruleNumber is the rule number to be emitted in the case statement
* @param comment is the comment
* @return for indentation purposes the column where the case ended
*/
protected int generateCaseStatement(int ruleNumber, String comment) {
return environment.language.generateCaseStart(ruleNumber, Integer.toString(ruleNumber + 1), comment);
}
/**
* Output the top of the rules if needed
*/
protected void generateCodeGeneratorHeader() {
if (runtimeData.ruleActionCount == 0) {
environment.language.generateCodeGeneratorHeader();
}
}
/**
* copy action until the next ';' or '}' that actually closes
* @param lexerMode is the mode of the lexer
* @param token is the token related to the generation. Used in $t
* @return true if OK
*/
protected boolean generateLexerCode(String lexerMode, Terminal token) {
FormattingPrintStream output = environment.getLexerModePrintStream(lexerMode);
environment.language.generateLexerCode(output, lexerMode, this, token, 0);
tokenActionCount++;
return true;
}
/**
* Produce the if statement that will match the regex symbol and the default return code
* @param dfaNode is the index of the dfa vertex
* @param token is the token related to the generation. Used in $t
* @return true if successful
*/
protected boolean generateDefaultRegexCode(int dfaNode, Terminal token) {
FormattingPrintStream output = environment.getLexerModePrintStream("default");
environment.language.generateRegexMatch(output, dfaNode);
environment.language.generateRegexReturn(output, token);
environment.language.generateRegexEnd(output);
tokenActionCount++;
return true;
}
/**
* Produce the if statement that will match the regex symbol and include additional code
* @param lexerMode is the mode of the scanner
* @param dfaNode is the index of the dfa vertex
* @param token is the token related to the generation. Used in $t
* @return true if successful
*/
protected boolean generateRegexCode(String lexerMode, int dfaNode, Terminal token) {
FormattingPrintStream output = environment.getLexerModePrintStream(lexerMode);
environment.language.generateRegexMatch(output, dfaNode);
environment.language.generateLexerCode(output, lexerMode, this, token, 1);
environment.language.generateRegexEnd(output);
tokenActionCount++;
return true;
}
/**
* Generate the ending portion of the code generation
*/
protected void generateCodeGeneratorFooter() {
if (runtimeData.ruleActionCount != 0) {
environment.language.generateCodeGeneratorFooter();
} else {
environment.language.generateVoidCodeGenerator();
}
}
/**
* Generate the bottom of the lexer
*/
protected void generateLexerFooter() {
if (tokenActionCount != 0) {
if (environment.lexerModes.get(DEFAULT_LEXER_MODE) == null) {
environment.getLexerModePrintStream(DEFAULT_LEXER_MODE);
}
List<String> modes = new ArrayList<String>(environment.lexerModes.keySet().size());
modes.addAll(environment.lexerModes.keySet());
Collections.sort(modes);
int index = 0;
if (modes.size() > 0) {
for (String mode: modes) {
environment.language.generateLexerModeDefinition(mode, index++);
}
}
environment.language.generateLexerHeader(modes);
if (modes.size() > 1) {
index = 0;
for (String mode: modes) {
environment.language.generateLexerModeCase(mode, index++);
}
}
environment.language.generateLexerFooter();
if (modes.size() > 1) {
for (String mode: modes) {
FormattingPrintStream stream = environment.lexerModes.get(mode);
String lexerCode = stream.getWriter().toString();
environment.language.emitLine(runtimeData.lineNumber + 1);
environment.language.generateLexerModeHeader(mode);
environment.output.print(lexerCode);
environment.output.println();
environment.language.generateLexerModeFooter(mode);
}
}
}
}
/**
* During a declaration, emit the accompanying code
* @return true if OK
*/
protected boolean generateDeclaration() {
while (Character.isWhitespace(currentChar)) {
getNextCharacter();
}
environment.language.emitLine(runtimeData.lineNumber);
while (currentChar != '\0') {
if (currentChar == '\\') {
if ((getNextCharacter()) == '}') {
getNextCharacter();
return true;
} else {
environment.output.print('\\');
}
} else if (currentChar == '%') {
if ((getNextCharacter()) == '}') {
getNextCharacter();
return true;
} else {
environment.output.print('%');
}
} else if (currentChar == '$') {
getNextCharacter();
if (currentChar == '$') {
getNextCharacter();
switch (currentChar) {
case 'b':
getNextCharacter();
environment.output.print(PathUtils.getFileNameNoExtension(environment.getOutputFile().getAbsolutePath()));
break;
case 'n':
getNextCharacter();
environment.output.print(PathUtils.getFileName(environment.getOutputFile().getAbsolutePath()));
break;
case 'f':
getNextCharacter();
environment.output.print(environment.getOutputFile().getAbsolutePath());
break;
case 'e':
getNextCharacter();
environment.output.print(PathUtils.getFileExtension(environment.getOutputFile().getAbsolutePath()));
break;
case 'p':
getNextCharacter();
environment.output.print(PathUtils.getFilePath(environment.getOutputFile().getAbsolutePath()));
break;
default:
environment.output.print("$$");
}
} else {
environment.output.print('$');
}
}
environment.output.print(currentChar);
getNextCharacter();
}
environment.error(-1, "End of file before \'\\}\' or \'%%}\'.");
return false;
}
/**
* For yacc compatibility this is called the union, but it is
* really a structure
* @return true if OK
*/
protected boolean generateStructure() {
environment.language.emitLine(runtimeData.lineNumber);
runtimeData.setStackTypeDefined(true);
return environment.language.generateStructure(this);
}
/**
* new rule item with the given symbol
* @param elem is the symbol associated to the rule
* @return the new rule item
*/
protected RuleItem newItem(Symbol elem) {
RuleItem item;
item = new RuleItem(elem);
if (runtimeData.currentRuleItems == null) {
runtimeData.currentRuleItems = new LinkedList<RuleItem>();
}
runtimeData.currentRuleItems.add(item);
return item;
}
/**
* new rule with no elements
* @return the new rule
*/
protected Rule newEmptyRule() {
Rule rule;
rule = new Rule(0, actLine, 0, null);
runtimeData.getRules().add(rule);
return rule;
}
/**
* new rule with the currently recognized items
* @return a new rule
*/
protected Rule newRule() {
Rule rule;
rule = new Rule(0, actLine, rulePrecedence, null);
if (runtimeData.currentRuleItems != null) {
rule.getItems().addAll(runtimeData.currentRuleItems);
for (RuleItem item : runtimeData.currentRuleItems) {
item.setRule(rule);
}
runtimeData.currentRuleItems = null;
}
runtimeData.getRules().add(rule);
rulePrecedence = 0;
ruleAssociativity = Associativity.NONE;
return rule;
}
/**
* Starting rule. Add it at the top.
*
* @param root is the root symbol
* @return the new rule
*/
protected Rule newRootRule(NonTerminal root) {
Rule rule;
rule = new Rule(0, actLine, rulePrecedence, root);
if (runtimeData.currentRuleItems != null) {
rule.getItems().addAll(runtimeData.currentRuleItems);
for (RuleItem item : runtimeData.currentRuleItems) {
item.setRule(rule);
}
runtimeData.currentRuleItems = null;
}
runtimeData.getRules().add(0, rule);
rulePrecedence = 0;
ruleAssociativity = Associativity.NONE;
return rule;
}
/**
* Check non terminals whose precedence is zero, and make them terminals.
*/
protected void reviewDeclarations() {
for (int i = 0; i < runtimeData.getNonTerminals().size(); ) {
NonTerminal nonTerminal = runtimeData.getNonTerminals().get(i);
if (nonTerminal.getPrecedence() == 0) {
environment.error(-1, "Warning: token \'%s\' not declared.", nonTerminal.getName());
runtimeData.getTerminals().add(new Terminal(nonTerminal));
runtimeData.getNonTerminals().remove(nonTerminal);
} else {
i++;
}
}
}
/**
* Find out my root symbol
*/
protected void computeRootSymbol() {
runtimeData.setRoot(null);
boolean bError = false;
for (NonTerminal nonTerminal : runtimeData.getNonTerminals()) {
if (nonTerminal.getCount() == 0) {
if (runtimeData.getRoot() == null) {
runtimeData.setRoot(nonTerminal);
} else {
bError = true;
runtimeData.setRoot(null);
break;
}
}
}
if (runtimeData.getStart() != null) { // Was it given with %start ?
for (NonTerminal nonTerminal : runtimeData.getNonTerminals()) {
if (nonTerminal.getCount() == 0 && !nonTerminal.equals(runtimeData.getStart())) {
Rule stx = locateRuleWithId(nonTerminal.getId());
environment.error(lineNumber(stx), "Warning: Symbol \'%s\' not used.", nonTerminal.getName());
}
}
} else {
if (runtimeData.getRoot() != null) {
Rule stx = locateRuleWithId(runtimeData.getRoot().getId());
environment.error(lineNumber(stx), "Assumed \'%s\' as distinguished symbol.", runtimeData.getRoot().getName());
runtimeData.setStart(runtimeData.getRoot());
} else if (bError) {
for (NonTerminal id : runtimeData.getNonTerminals()) {
if (id.getCount() == 0) {
Rule stx = locateRuleWithId(id.getId());
environment.error(lineNumber(stx), "Warning: Symbol \'%s\' not used.", id.getName());
}
}
environment.error(-1, "Distinguished symbol cannot be determined. Use %%start.");
return;
} else {
environment.error(-1, "The distinguished symbol does not exist.");
return;
}
}
boolean found = false;
for (NonTerminal nonTerminal : runtimeData.getNonTerminals()) {
if (nonTerminal.getName().equals(DISTINGUISHED_SYMBOL_NAME)) {
runtimeData.setRoot(nonTerminal);
found = true;
break;
}
}
if (!found) {
NonTerminal root = new NonTerminal(DISTINGUISHED_SYMBOL_NAME);
runtimeData.getNonTerminals().add(root);
runtimeData.setRoot(root);
}
newItem(runtimeData.getStart());
newRootRule(runtimeData.getRoot());
}
/**
* The recovery table deals with tokens that can be used to recognize
* syntax context and can recover from errors.
*/
protected void generateTopRecoveryTable() {
numberOfErrorTokens = 0;
for (Terminal id : runtimeData.getTerminals()) {
if (id instanceof ErrorToken) {
numberOfErrorTokens++;
}
}
environment.language.generateRecoveryTableHeader(numberOfErrorTokens);
}
/**
* Assign ids, numbers, and print them.
*/
protected void finalizeSymbols() {
environment.reportWriter.subHeading("Terminal Symbols");
environment.reportWriter.tableHead("symbols",
right("ID"), left("Name"), left("Full Name"), right("Value"),
left("Err"), right("Refs"), right("Prec"), left("Assc"), left("Type"));
int recoveries = 0;
int terminals = 0;
for (Terminal id : runtimeData.getTerminals()) {
// Look for the default token for a non assigned terminal symbol
if (id.getToken() == -1) {
int tok_num = 1;
for (tok_num = Short.MAX_VALUE+1 ;; tok_num++) {
Terminal cual = runtimeData.findTerminalByToken(tok_num);
if (cual == null) {
break;
}
}
id.setToken(tok_num);
}
id.setId(terminals++);
environment.reportWriter.tableRow(right(id.getId()), left(id.getName()), left(id.getFullName()),
right(id.getToken()), left(id instanceof ErrorToken ? "Yes" : "No "),
right(id.getCount()), right(id.getPrecedence()), left(id.getAssociativity().displayName()),
left(id.getType() != null ? id.getType().getName() : ""));
if (id instanceof ErrorToken) {
int recoveryToken = id.getToken();
++recoveries;
environment.language.generateErrorToken(recoveryToken, (ErrorToken) id, recoveries >= numberOfErrorTokens);
}
}
environment.language.generateTokensHeader(terminals);
int i = 1;
for (Terminal id : runtimeData.getTerminals()) {
environment.language.generateToken(id, i == terminals);
i++;
}
i = 1;
environment.reportWriter.tableEnd();
environment.reportWriter.subHeading("Non Terminal Symbols");
environment.reportWriter.tableHead("symbols",
right("ID"), left("Name"), left("FullName"), right("Refs"), left("Type"));
int noterminals = 0;
for (NonTerminal id : runtimeData.getNonTerminals()) {
id.setId(noterminals + terminals);
environment.reportWriter.tableRow(
right(id.getId()), left(id.getName()), left(id.getFullName()),
right(id.getCount()), left(id.getType() != null ? id.getType().getName() : ""));
noterminals++;
id.setFirst(null);
id.setFollow(null);
}
environment.reportWriter.tableEnd();
environment.reportWriter.subHeading("Types");
environment.reportWriter.tableHead("symbols", left("Name"), left("Used By"));
for (Type type : runtimeData.getTypes()) {
String s = "<ul>";
for (Symbol symbol : type.getUsedBy()) {
s += "<li>" + symbol + "</li>\n";
}
s += "</ul>";
environment.reportWriter.tableRow(left(type.getName()), left(s));
}
environment.reportWriter.tableEnd();
environment.reportWriter.subHeading("Error Groups");
environment.reportWriter.tableHead("symbols", left("Name"),
left("Display Name"), left("Symbols"));
for (TokenGroup errorGroup : runtimeData.getErrorGroups()) {
String s = "<ul>";
for (Terminal symbol : errorGroup.getTokens()) {
s += "<li>" + symbol.toString() + "</li>";
}
s += "</ul>";
environment.reportWriter.tableRow(left(errorGroup.getName()),
left(errorGroup.getDisplayName()), left(s));
}
environment.reportWriter.tableEnd();
environment.reportWriter.subHeading("Lexer Modes");
environment.reportWriter.tableHead("lexermodes", left("Name"), left("Routine"));
for (String lexerMode : environment.getLexerModes().keySet()) {
environment.reportWriter.tableRow(left(lexerMode), left(environment.language.getLexerModeRoutine(lexerMode)));
}
environment.reportWriter.tableEnd();
environment.reportWriter.subHeading("Regular Expressions");
environment.reportWriter.tableHead("lexermodes", left("Expression"), left("Graph"));
for (Dfa graph : runtimeData.getRegularExpressions()) {
SvgRenderer renderer = new SvgRenderer();
graph.layout(GRAPH_WIDTH, GRAPH_HEIGH);
String image = renderer.render(graph, GRAPH_WIDTH, GRAPH_HEIGH);
environment.reportWriter.tableRow(left("/"+graph.getRegex()+"/<br/>" + graph.toHtmlString()), left(image));
}
environment.reportWriter.tableEnd();
}
/**
* set rule numbers and print
*/
protected void finalizeRules() {
environment.reportWriter.subHeading("Grammar");
environment.reportWriter.tableHead("rules", right("Prec"), right("Rule"), left("Grammar"));
int i = 0;
for (Rule stx : runtimeData.getRules()) {
stx.setRulenum(i);
String s = stx.getLeftHand().getName() + " ⇒ ";
for (RuleItem itm : stx.getItems()) {
s += itm.getSymbol().getName() + ' ';
}
environment.reportWriter.tableRow(right(stx.getPrecedence()), right(i), left(s));
i = i + 1;
}
environment.reportWriter.tableEnd();
}
/**
* token definitions are declared as static or #define
*/
protected void generateTokenDefinitions() {
environment.language.generateTokenDefinitions();
}
/**
* Locate a rule whose left hand if is the given id
* @param id is the id of the non terminal on the left hand side
* @return the rule, or null if not found
*/
protected Rule locateRuleWithId(int id) {
Rule rule = null;
for (int i = 0; i < runtimeData.getRules().size(); i++) {
rule = runtimeData.getRules().get(i);
if (id == rule.getLeftHandId()) {
break;
}
}
return rule;
}
/**
* @param rule is the rule's line number
* @return the line number of a given rule
*/
protected int lineNumber(Rule rule) {
return rule != null ? rule.getLineNumber() - 1 : -1;
}
/**
* Found a rule action. Copy it to the output stream as-is
* @param ruleNumber the rule index
* @param elementCount the elements in the rule
* @param nonTerminalName the left hand symbol of the rule
* @return true if OK
*/
protected boolean ruleAction(int ruleNumber, int elementCount, String nonTerminalName) {
generateCodeGeneratorHeader();
String ruleLabel = "";
if (runtimeData.currentRuleItems != null) {
for (RuleItem item : runtimeData.currentRuleItems) {
ruleLabel = ruleLabel + " " + item.getSymbol().getName();
}
}
generateCaseStatement(ruleNumber, "" + (ruleNumber+1) + ". " + nonTerminalName + " -> " + ruleLabel);
while (currentChar == ' ') {
getNextCharacter();
}
if (!environment.language.generateRuleCode(this, this, elementCount, nonTerminalName, runtimeData.columnNumber-2)) {
return false;
}
generateCaseEnd();
runtimeData.ruleActionCount++;
return true;
}
protected boolean declareStart(String id) {
if (runtimeData.getStart() != null) {
environment.error(-1, "Distinguished symbol \'%s\' declared more than once.", runtimeData.getStart().getName());
return false;
}
Terminal terminal = runtimeData.findTerminalByName(id);
if (terminal == null) {
NonTerminal nonTerminal = runtimeData.findNonTerminalByName(id);
if (nonTerminal == null) {
nonTerminal = new NonTerminal(id);
runtimeData.getNonTerminals().add(nonTerminal);
}
nonTerminal.setCount(nonTerminal.getCount() - 1);
runtimeData.setStart(nonTerminal);
} else {
environment.error(-1, "Distinguished symbol \'%s\' previously declared as token.", id);
return false;
}
return true;
}
public abstract void execute() throws ParsingException;
public abstract void dumpTokens() throws ParsingException;
}
| 33.522346 | 165 | 0.609512 |
819ad13b41142f7b715e07ad5aae9342b9d7bc85 | 710 | package org.chronos.chronosphere.api.exceptions;
public class ResourceIsAlreadyClosedException extends ChronoSphereException {
public ResourceIsAlreadyClosedException() {
super();
}
protected ResourceIsAlreadyClosedException(final String message, final Throwable cause,
final boolean enableSuppression, final boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public ResourceIsAlreadyClosedException(final String message, final Throwable cause) {
super(message, cause);
}
public ResourceIsAlreadyClosedException(final String message) {
super(message);
}
public ResourceIsAlreadyClosedException(final Throwable cause) {
super(cause);
}
}
| 26.296296 | 88 | 0.805634 |
b5ccb2654c9210c3ed4995d5c45561460b2218c6 | 28,465 | package hex.gbm;
import static water.util.ModelUtils.getPrediction;
import static water.util.Utils.div;
import hex.ConfusionMatrix;
import hex.VarImp;
import hex.VarImp.VarImpRI;
import hex.gbm.DTree.DecidedNode;
import hex.gbm.DTree.LeafNode;
import hex.gbm.DTree.Split;
import hex.gbm.DTree.TreeModel.TreeStats;
import hex.gbm.DTree.UndecidedNode;
import water.*;
import water.api.DocGen;
import water.api.GBMProgressPage;
import water.api.ParamImportance;
import water.fvec.Chunk;
import water.fvec.Frame;
import water.util.*;
import water.util.Log.Tag.Sys;
import java.util.Arrays;
// Gradient Boosted Trees
//
// Based on "Elements of Statistical Learning, Second Edition, page 387"
public class GBM extends SharedTreeModelBuilder<GBM.GBMModel> {
static final int API_WEAVER = 1; // This file has auto-gen'd doc & json fields
static public DocGen.FieldDoc[] DOC_FIELDS; // Initialized from Auto-Gen code.
@API(help = "Distribution for computing loss function. AUTO selects gaussian for continuous and multinomial for categorical response", filter = Default.class, json=true, importance=ParamImportance.CRITICAL)
public Family family = Family.AUTO;
@API(help = "Learning rate, from 0. to 1.0", filter = Default.class, dmin=0, dmax=1, json=true, importance=ParamImportance.SECONDARY)
public double learn_rate = 0.1;
@API(help = "Grid search parallelism", filter = Default.class, lmax = 4, gridable=false, importance=ParamImportance.SECONDARY)
public int grid_parallelism = 1;
@API(help = "Seed for the random number generator - only for balancing classes (autogenerated)", filter = Default.class)
long seed = -1; // To follow R-semantics, each call of GBM with imbalance should provide different seed. -1 means seed autogeneration
/** Distribution functions */
// Note: AUTO will select gaussian for continuous, and multinomial for categorical response
// TODO: Replace with drop-down that displays different distributions depending on cont/cat response
public enum Family {
AUTO, bernoulli
}
/** Sum of variable empirical improvement in squared-error. The value is not scaled! */
private transient float[/*nfeatures*/] _improvPerVar;
public static class GBMModel extends DTree.TreeModel {
static final int API_WEAVER = 1; // This file has auto-gen'd doc & json fields
static public DocGen.FieldDoc[] DOC_FIELDS; // Initialized from Auto-Gen code.
@API(help = "Model parameters", json = true)
final private GBM parameters;
@Override public final GBM get_params() { return parameters; }
@Override public final Request2 job() { return get_params(); }
@API(help = "Learning rate, from 0. to 1.0") final double learn_rate;
@API(help = "Distribution for computing loss function. AUTO selects gaussian for continuous and multinomial for categorical response")
final Family family;
public GBMModel(GBM job, Key key, Key dataKey, Key testKey, String names[], String domains[][], String[] cmDomain, int ntrees, int max_depth, int min_rows, int nbins, double learn_rate, Family family) {
super(key,dataKey,testKey,names,domains,cmDomain,ntrees,max_depth,min_rows,nbins);
this.parameters = job;
this.learn_rate = learn_rate;
this.family = family;
}
public GBMModel(GBMModel prior, DTree[] trees, double err, ConfusionMatrix cm, TreeStats tstats) {
super(prior, trees, err, cm, tstats);
this.parameters = prior.parameters;
this.learn_rate = prior.learn_rate;
this.family = prior.family;
}
public GBMModel(GBMModel prior, DTree[] trees, TreeStats tstats) {
super(prior, trees, tstats);
this.parameters = prior.parameters;
this.learn_rate = prior.learn_rate;
this.family = prior.family;
}
public GBMModel(GBMModel prior, double err, ConfusionMatrix cm, VarImp varimp, water.api.AUC validAUC) {
super(prior, err, cm, varimp, validAUC);
this.parameters = prior.parameters;
this.learn_rate = prior.learn_rate;
this.family = prior.family;
}
@Override protected TreeModelType getTreeModelType() { return TreeModelType.GBM; }
@Override protected float[] score0(double[] data, float[] preds) {
float[] p = super.score0(data, preds); // These are f_k(x) in Algorithm 10.4
if(family == Family.bernoulli) {
p[2] = 1.0f/(float)(1f+Math.exp(-p[1]));
p[1] = 1f-p[2];
p[0] = getPrediction(p, data);
return p;
}
if (nclasses()>1) { // classification
// Because we call Math.exp, we have to be numerically stable or else
// we get Infinities, and then shortly NaN's. Rescale the data so the
// largest value is +/-1 and the other values are smaller.
// See notes here: http://www.hongliangjie.com/2011/01/07/logsum/
float maxval=Float.NEGATIVE_INFINITY;
float dsum=0;
if (nclasses()==2) p[2] = - p[1];
// Find a max
for( int k=1; k<p.length; k++) maxval = Math.max(maxval,p[k]);
assert !Float.isInfinite(maxval) : "Something is wrong with GBM trees since returned prediction is " + Arrays.toString(p);
for(int k=1; k<p.length;k++)
dsum+=(p[k]=(float)Math.exp(p[k]-maxval));
div(p,dsum);
p[0] = getPrediction(p, data);
} else { // regression
// do nothing for regression
}
return p;
}
@Override protected void generateModelDescription(StringBuilder sb) {
DocGen.HTML.paragraph(sb,"Learn rate: "+learn_rate);
}
@Override protected void toJavaUnifyPreds(SB bodyCtxSB) {
if(family == Family.bernoulli) {
bodyCtxSB.i().p("// Compute Probabilities for Bernoulli 0-1 classifier").nl();
bodyCtxSB.i().p("preds[2] = 1.0f/(float)(1f+Math.exp(-preds[1]))").nl();
bodyCtxSB.i().p("preds[1] = 1f-preds[2]").nl();
}
else if (isClassifier()) {
bodyCtxSB.i().p("// Compute Probabilities for classifier (scale via http://www.hongliangjie.com/2011/01/07/logsum/)").nl();
bodyCtxSB.i().p("float dsum = 0, maxval = Float.NEGATIVE_INFINITY;").nl();
if (nclasses()==2) {
bodyCtxSB.i().p("preds[2] = -preds[1];").nl();
}
bodyCtxSB.i().p("for(int i=1; i<preds.length; i++) maxval = Math.max(maxval, preds[i]);").nl();
bodyCtxSB.i().p("for(int i=1; i<preds.length; i++) dsum += (preds[i]=(float) Math.exp(preds[i] - maxval));").nl();
bodyCtxSB.i().p("for(int i=1; i<preds.length; i++) preds[i] = preds[i] / dsum;").nl();
}
}
}
public Frame score( Frame fr ) { return ((GBMModel)UKV.get(dest())).score(fr); }
@Override protected Log.Tag.Sys logTag() { return Sys.GBM__; }
@Override protected GBMModel makeModel(Key outputKey, Key dataKey, Key testKey, String[] names, String[][] domains, String[] cmDomain) {
return new GBMModel(this, outputKey, dataKey, testKey, names, domains, cmDomain, ntrees, max_depth, min_rows, nbins, learn_rate, family);
}
@Override protected GBMModel makeModel( GBMModel model, double err, ConfusionMatrix cm, VarImp varimp, water.api.AUC validAUC) {
return new GBMModel(model, err, cm, varimp, validAUC);
}
@Override protected GBMModel makeModel(GBMModel model, DTree[] ktrees, TreeStats tstats) {
return new GBMModel(model, ktrees, tstats);
}
public GBM() { description = "Distributed GBM"; importance = true; }
/** Return the query link to this page */
public static String link(Key k, String content) {
RString rs = new RString("<a href='/2/GBM.query?source=%$key'>%content</a>");
rs.replace("key", k.toString());
rs.replace("content", content);
return rs.toString();
}
@Override protected void execImpl() {
logStart();
buildModel(seed);
}
@Override public int gridParallelism() {
return grid_parallelism;
}
@Override protected Response redirect() {
return GBMProgressPage.redirect(this, self(), dest());
}
@Override protected void initAlgo( GBMModel initialModel) {
// Initialize gbm-specific data structures
if (importance) _improvPerVar = new float[initialModel.nfeatures()];
// assert (family != Family.bernoulli) || (_nclass == 2) : "Bernoulli requires the response to be a 2-class categorical";
if(family == Family.bernoulli && _nclass != 2)
throw new IllegalArgumentException("Bernoulli requires the response to be a 2-class categorical");
}
@Override protected void initWorkFrame(GBMModel initialModel, Frame fr) {
if (classification) initialModel.setModelClassDistribution(new MRUtils.ClassDist(response).doAll(response).rel_dist());
// Tag out rows missing the response column
new ExcludeNAResponse().doAll(fr);
// Initialize working response based on given loss function
if (_nclass == 1) { /* regression */
// Initial value is mean(y)
final float mean = (float) fr.vec(initialModel.responseName()).mean();
new MRTask2() {
@Override public void map(Chunk[] chks) {
Chunk tr = chk_tree(chks, 0); // there is only one tree for regression
for (int i=0; i<tr._len; i++) tr.set0(i, mean);
}
}.doAll(fr);
} else if(family == Family.bernoulli) {
// Initial value is log( mean(y)/(1-mean(y)) )
final float mean = (float) fr.vec(initialModel.responseName()).mean();
final float init = (float) Math.log(mean/(1.0f-mean));
new MRTask2() {
@Override public void map(Chunk[] chks) {
Chunk tr = chk_tree(chks, 0); // only the tree for y = 0 is used
for (int i=0; i<tr._len; i++) tr.set0(i, init);
}
}.doAll(fr);
} else { /* multinomial */ // TODO: we should use bernoulli distribution
/* Preserve 0s in working columns */
}
}
// ==========================================================================
// Compute a GBM tree.
// Start by splitting all the data according to some criteria (minimize
// variance at the leaves). Record on each row which split it goes to, and
// assign a split number to it (for next pass). On *this* pass, use the
// split-number to build a per-split histogram, with a per-histogram-bucket
// variance.
@Override protected GBMModel buildModel( GBMModel model, final Frame fr, String names[], String domains[][], Timer t_build ) {
// Build trees until we hit the limit
int tid;
DTree[] ktrees = null; // Trees
TreeStats tstats = new TreeStats(); // Tree stats
for( tid=0; tid<ntrees; tid++) {
// During first iteration model contains 0 trees, then 0-trees, then 1-tree,...
// BUT if validation is not specified model does not participate in voting
// but on-the-fly computed data are used
model = doScoring(model, fr, ktrees, tid, tstats, false, false, false);
// ESL2, page 387
// Step 2a: Compute prediction (prob distribution) from prior tree results:
// Work <== f(Tree)
new ComputeProb().doAll(fr);
// ESL2, page 387
// Step 2b i: Compute residuals from the prediction (probability distribution)
// Work <== f(Work)
new ComputeRes().doAll(fr);
// ESL2, page 387, Step 2b ii, iii, iv
Timer kb_timer = new Timer();
ktrees = buildNextKTrees(fr);
Log.info(Sys.GBM__, (tid+1) + ". tree was built in " + kb_timer.toString());
if( !Job.isRunning(self()) ) break; // If canceled during building, do not bulkscore
// Check latest predictions
tstats.updateBy(ktrees);
}
// Final scoring
model = doScoring(model, fr, ktrees, tid, tstats, true, false, false);
return model;
}
// --------------------------------------------------------------------------
// Tag out rows missing the response column
class ExcludeNAResponse extends MRTask2<ExcludeNAResponse> {
@Override public void map( Chunk chks[] ) {
Chunk ys = chk_resp(chks);
for( int row=0; row<ys._len; row++ )
if( ys.isNA0(row) )
for( int t=0; t<_nclass; t++ )
chk_nids(chks,t).set0(row,-1);
}
}
// --------------------------------------------------------------------------
// Compute Prediction from prior tree results.
// Classification (multinomial): Probability Distribution of loglikelyhoods
// Prob_k = exp(Work_k)/sum_all_K exp(Work_k)
// Classification (bernoulli): Probability of y = 1 given logit link function
// Prob_0 = 1/(1 + exp(Work)), Prob_1 = 1/(1 + exp(-Work))
// Regression: Just prior tree results
// Work <== f(Tree)
class ComputeProb extends MRTask2<ComputeProb> {
@Override public void map( Chunk chks[] ) {
Chunk ys = chk_resp(chks);
if( family == Family.bernoulli ) {
Chunk tr = chk_tree(chks,0);
Chunk wk = chk_work(chks,0);
for( int row = 0; row < ys._len; row++)
// wk.set0(row, 1.0f/(1f+Math.exp(-tr.at0(row))) ); // Prob_1
wk.set0(row, 1.0f/(1f+Math.exp(tr.at0(row))) ); // Prob_0
} else if( _nclass > 1 ) { // Classification
float fs[] = new float[_nclass+1];
for( int row=0; row<ys._len; row++ ) {
float sum = score1(chks,fs,row);
if( Float.isInfinite(sum) ) // Overflow (happens for constant responses)
for( int k=0; k<_nclass; k++ )
chk_work(chks,k).set0(row,Float.isInfinite(fs[k+1])?1.0f:0.0f);
else
for( int k=0; k<_nclass; k++ ) // Save as a probability distribution
chk_work(chks,k).set0(row,fs[k+1]/sum);
}
} else { // Regression
Chunk tr = chk_tree(chks,0); // Prior tree sums
Chunk wk = chk_work(chks,0); // Predictions
for( int row=0; row<ys._len; row++ )
wk.set0(row,(float)tr.at0(row));
}
}
}
// Read the 'tree' columns, do model-specific math and put the results in the
// fs[] array, and return the sum. Dividing any fs[] element by the sum
// turns the results into a probability distribution.
@Override protected float score1( Chunk chks[], float fs[/*nclass*/], int row ) {
if(family == Family.bernoulli) {
fs[1] = 1.0f/(float)(1f+Math.exp(chk_tree(chks,0).at0(row)));
fs[2] = 1f-fs[1];
return fs[1]+fs[2];
}
if( _nclass == 1 ) // Classification?
return (float)chk_tree(chks,0).at0(row); // Regression.
if( _nclass == 2 ) { // The Boolean Optimization
// This optimization assumes the 2nd tree of a 2-class system is the
// inverse of the first. Fill in the missing tree
fs[1] = (float)Math.exp(chk_tree(chks,0).at0(row));
fs[2] = 1.0f/fs[1]; // exp(-d) === 1/d
return fs[1]+fs[2];
}
float sum=0;
for( int k=0; k<_nclass; k++ ) // Sum across of likelyhoods
sum+=(fs[k+1]=(float)Math.exp(chk_tree(chks,k).at0(row)));
return sum;
}
// --------------------------------------------------------------------------
// Compute Residuals from Actuals
// Work <== f(Work)
class ComputeRes extends MRTask2<ComputeRes> {
@Override public void map( Chunk chks[] ) {
Chunk ys = chk_resp(chks);
if(family == Family.bernoulli) {
for(int row = 0; row < ys._len; row++) {
if( ys.isNA0(row) ) continue;
int y = (int)ys.at80(row); // zero-based response variable
Chunk wk = chk_work(chks,0);
// wk.set0(row, y-(float)wk.at0(row)); // wk.at0(row) is Prob_1
wk.set0(row, y-1f+(float)wk.at0(row)); // wk.at0(row) is Prob_0
}
} else if( _nclass > 1 ) { // Classification
for( int row=0; row<ys._len; row++ ) {
if( ys.isNA0(row) ) continue;
int y = (int)ys.at80(row); // zero-based response variable
// Actual is '1' for class 'y' and '0' for all other classes
for( int k=0; k<_nclass; k++ ) {
if( _distribution[k] != 0 ) {
Chunk wk = chk_work(chks,k);
wk.set0(row, (y==k?1f:0f)-(float)wk.at0(row) );
}
}
}
} else { // Regression
Chunk wk = chk_work(chks,0); // Prediction==>Residuals
for( int row=0; row<ys._len; row++ )
wk.set0(row, (float)(ys.at0(row)-wk.at0(row)) );
}
}
}
// --------------------------------------------------------------------------
// Build the next k-trees, which is trying to correct the residual error from
// the prior trees. From LSE2, page 387. Step 2b ii, iii.
private DTree[] buildNextKTrees(Frame fr) {
// We're going to build K (nclass) trees - each focused on correcting
// errors for a single class.
final DTree[] ktrees = new DTree[_nclass];
// Initial set of histograms. All trees; one leaf per tree (the root
// leaf); all columns
DHistogram hcs[][][] = new DHistogram[_nclass][1/*just root leaf*/][_ncols];
for( int k=0; k<_nclass; k++ ) {
// Initially setup as-if an empty-split had just happened
if( _distribution == null || _distribution[k] != 0 ) {
// The Boolean Optimization
// This optimization assumes the 2nd tree of a 2-class system is the
// inverse of the first. This is false for DRF (and true for GBM) -
// DRF picks a random different set of columns for the 2nd tree.
if( k==1 && _nclass==2 ) continue;
ktrees[k] = new DTree(fr._names,_ncols,(char)nbins,(char)_nclass,min_rows);
new GBMUndecidedNode(ktrees[k],-1,DHistogram.initialHist(fr,_ncols,nbins,hcs[k][0],false) ); // The "root" node
}
}
int[] leafs = new int[_nclass]; // Define a "working set" of leaf splits, from here to tree._len
// ----
// ESL2, page 387. Step 2b ii.
// One Big Loop till the ktrees are of proper depth.
// Adds a layer to the trees each pass.
int depth=0;
for( ; depth<max_depth; depth++ ) {
if( !Job.isRunning(self()) ) return null;
hcs = buildLayer(fr, ktrees, leafs, hcs, false, false);
// If we did not make any new splits, then the tree is split-to-death
if( hcs == null ) break;
}
// Each tree bottomed-out in a DecidedNode; go 1 more level and insert
// LeafNodes to hold predictions.
for( int k=0; k<_nclass; k++ ) {
DTree tree = ktrees[k];
if( tree == null ) continue;
int leaf = leafs[k] = tree.len();
for( int nid=0; nid<leaf; nid++ ) {
if( tree.node(nid) instanceof DecidedNode ) {
DecidedNode dn = tree.decided(nid);
for( int i=0; i<dn._nids.length; i++ ) {
int cnid = dn._nids[i];
if( cnid == -1 || // Bottomed out (predictors or responses known constant)
tree.node(cnid) instanceof UndecidedNode || // Or chopped off for depth
(tree.node(cnid) instanceof DecidedNode && // Or not possible to split
((DecidedNode)tree.node(cnid))._split.col()==-1) )
dn._nids[i] = new GBMLeafNode(tree,nid).nid(); // Mark a leaf here
}
// Handle the trivial non-splitting tree
if( nid==0 && dn._split.col() == -1 )
new GBMLeafNode(tree,-1,0);
}
}
} // -- k-trees are done
// ----
// ESL2, page 387. Step 2b iii. Compute the gammas, and store them back
// into the tree leaves. Includes learn_rate.
// For classification (bernoulli):
// gamma_i = sum res_i / sum p_i*(1 - p_i) where p_i = y_i - res_i
// For classification (multinomial):
// gamma_i_k = (nclass-1)/nclass * (sum res_i / sum (|res_i|*(1-|res_i|)))
// For regression (gaussian):
// gamma_i = sum res_i / count(res_i)
GammaPass gp = new GammaPass(ktrees,leafs).doAll(fr);
double m1class = _nclass > 1 && family != Family.bernoulli ? (double)(_nclass-1)/_nclass : 1.0; // K-1/K for multinomial
for( int k=0; k<_nclass; k++ ) {
final DTree tree = ktrees[k];
if( tree == null ) continue;
for( int i=0; i<tree._len-leafs[k]; i++ ) {
double g = gp._gss[k][i] == 0 // Constant response?
? (gp._rss[k][i]==0?0:1000) // Cap (exponential) learn, instead of dealing with Inf
: learn_rate*m1class*gp._rss[k][i]/gp._gss[k][i];
assert !Double.isNaN(g);
((LeafNode)tree.node(leafs[k]+i))._pred = g;
}
}
// ----
// ESL2, page 387. Step 2b iv. Cache the sum of all the trees, plus the
// new tree, in the 'tree' columns. Also, zap the NIDs for next pass.
// Tree <== f(Tree)
// Nids <== 0
new MRTask2() {
@Override public void map( Chunk chks[] ) {
// For all tree/klasses
for( int k=0; k<_nclass; k++ ) {
final DTree tree = ktrees[k];
if( tree == null ) continue;
final Chunk nids = chk_nids(chks,k);
final Chunk ct = chk_tree(chks,k);
for( int row=0; row<nids._len; row++ ) {
int nid = (int)nids.at80(row);
if( nid < 0 ) continue;
ct.set0(row, (float)(ct.at0(row) + ((LeafNode)tree.node(nid))._pred));
nids.set0(row,0);
}
}
}
}.doAll(fr);
// Collect leaves stats
for (int i=0; i<ktrees.length; i++)
if( ktrees[i] != null )
ktrees[i].leaves = ktrees[i].len() - leafs[i];
// DEBUG: Print the generated K trees
// printGenerateTrees(ktrees);
return ktrees;
}
// ---
// ESL2, page 387. Step 2b iii.
// Nids <== f(Nids)
private class GammaPass extends MRTask2<GammaPass> {
final DTree _trees[]; // Read-only, shared (except at the histograms in the Nodes)
final int _leafs[]; // Number of active leaves (per tree)
// Per leaf: sum(res);
double _rss[/*tree/klass*/][/*tree-relative node-id*/];
// Per leaf: multinomial: sum(|res|*1-|res|), gaussian: sum(1), bernoulli: sum((y-res)*(1-y+res))
double _gss[/*tree/klass*/][/*tree-relative node-id*/];
GammaPass(DTree trees[], int leafs[]) { _leafs=leafs; _trees=trees; }
@Override public void map( Chunk[] chks ) {
_gss = new double[_nclass][];
_rss = new double[_nclass][];
final Chunk resp = chk_resp(chks); // Response for this frame
// For all tree/klasses
for( int k=0; k<_nclass; k++ ) {
final DTree tree = _trees[k];
final int leaf = _leafs[k];
if( tree == null ) continue; // Empty class is ignored
// A leaf-biased array of all active Tree leaves.
final double gs[] = _gss[k] = new double[tree._len-leaf];
final double rs[] = _rss[k] = new double[tree._len-leaf];
final Chunk nids = chk_nids(chks,k); // Node-ids for this tree/class
final Chunk ress = chk_work(chks,k); // Residuals for this tree/class
// If we have all constant responses, then we do not split even the
// root and the residuals should be zero.
if( tree.root() instanceof LeafNode ) continue;
for( int row=0; row<nids._len; row++ ) { // For all rows
int nid = (int)nids.at80(row); // Get Node to decide from
if( nid < 0 ) continue; // Missing response
if( tree.node(nid) instanceof UndecidedNode ) // If we bottomed out the tree
nid = tree.node(nid)._pid; // Then take parent's decision
DecidedNode dn = tree.decided(nid); // Must have a decision point
if( dn._split._col == -1 ) // Unable to decide?
dn = tree.decided(nid = dn._pid); // Then take parent's decision
int leafnid = dn.ns(chks,row); // Decide down to a leafnode
assert leaf <= leafnid && leafnid < tree._len;
assert tree.node(leafnid) instanceof LeafNode;
// Note: I can which leaf/region I end up in, but I do not care for
// the prediction presented by the tree. For GBM, we compute the
// sum-of-residuals (and sum/abs/mult residuals) for all rows in the
// leaf, and get our prediction from that.
nids.set0(row,leafnid);
assert !ress.isNA0(row);
// Compute numerator (rs) and denominator (gs) of gamma
double res = ress.at0(row);
double ares = Math.abs(res);
if(family == Family.bernoulli) {
double prob = resp.at0(row) - res;
gs[leafnid-leaf] += prob*(1-prob);
} else
gs[leafnid-leaf] += _nclass > 1 ? ares*(1-ares) : 1;
rs[leafnid-leaf] += res;
}
}
}
@Override public void reduce( GammaPass gp ) {
Utils.add(_gss,gp._gss);
Utils.add(_rss,gp._rss);
}
}
@Override protected DecidedNode makeDecided( UndecidedNode udn, DHistogram hs[] ) {
return new GBMDecidedNode(udn,hs);
}
// ---
// GBM DTree decision node: same as the normal DecidedNode, but
// specifies a decision algorithm given complete histograms on all
// columns. GBM algo: find the lowest error amongst *all* columns.
static class GBMDecidedNode extends DecidedNode {
GBMDecidedNode( UndecidedNode n, DHistogram[] hs ) { super(n,hs); }
@Override public UndecidedNode makeUndecidedNode(DHistogram[] hs ) {
return new GBMUndecidedNode(_tree,_nid,hs);
}
// Find the column with the best split (lowest score). Unlike RF, GBM
// scores on all columns and selects splits on all columns.
@Override public DTree.Split bestCol( UndecidedNode u, DHistogram[] hs ) {
DTree.Split best = new DTree.Split(-1,-1,false,Double.MAX_VALUE,Double.MAX_VALUE,0L,0L,0,0);
if( hs == null ) return best;
for( int i=0; i<hs.length; i++ ) {
if( hs[i]==null || hs[i].nbins() <= 1 ) continue;
DTree.Split s = hs[i].scoreMSE(i);
if( s == null ) continue;
if( best == null || s.se() < best.se() ) best = s;
if( s.se() <= 0 ) break; // No point in looking further!
}
return best;
}
}
// ---
// GBM DTree undecided node: same as the normal UndecidedNode, but specifies
// a list of columns to score on now, and then decide over later.
// GBM algo: use all columns
static class GBMUndecidedNode extends UndecidedNode {
GBMUndecidedNode( DTree tree, int pid, DHistogram hs[] ) { super(tree,pid,hs); }
// Randomly select mtry columns to 'score' in following pass over the data.
// In GBM, we use all columns (as opposed to RF, which uses a random subset).
@Override public int[] scoreCols( DHistogram[] hs ) { return null; }
}
// ---
static class GBMLeafNode extends LeafNode {
GBMLeafNode( DTree tree, int pid ) { super(tree,pid); }
GBMLeafNode( DTree tree, int pid, int nid ) { super(tree,pid,nid); }
// Insert just the predictions: a single byte/short if we are predicting a
// single class, or else the full distribution.
@Override protected AutoBuffer compress(AutoBuffer ab) { assert !Double.isNaN(_pred); return ab.put4f((float)_pred); }
@Override protected int size() { return 4; }
}
/** Compute relative variable importance for GBM model.
*
* See (45), (35) formulas in Friedman: Greedy Function Approximation: A Gradient boosting machine.
* Algo used here can be used for computation individual importance of features per output class. */
@Override protected VarImp doVarImpCalc(GBMModel model, DTree[] ktrees, int tid, Frame validationFrame, boolean scale) {
assert model.ntrees()-1 == tid : "varimp computation expect model with already serialized trees: tid="+tid;
// Iterates over k-tree
for (DTree t : ktrees) { // Iterate over trees
if (t!=null) {
for (int n = 0; n< t.len()-t.leaves; n++)
if (t.node(n) instanceof DecidedNode) { // it is split node
Split split = t.decided(n)._split;
if (split.col()!=-1) // Skip impossible splits ~ leafs
_improvPerVar[split.col()] += split.improvement(); // least squares improvement
}
}
}
// Compute variable importance for all trees in model
float[] varimp = new float[model.nfeatures()];
int ntreesTotal = model.ntrees() * model.nclasses();
int maxVar = 0;
for (int var=0; var<_improvPerVar.length; var++) {
varimp[var] = _improvPerVar[var] / ntreesTotal;
if (varimp[var] > varimp[maxVar]) maxVar = var;
}
// GBM scale varimp to scale 0..100
if (scale) {
float maxVal = varimp[maxVar];
for (int var=0; var<varimp.length; var++) varimp[var] /= maxVal;
}
return new VarImpRI(varimp);
}
}
| 44.476563 | 208 | 0.610434 |
90d5ee2ff6b237ae56ee1edb89785cf3e814b459 | 10,890 | /*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInspection.varScopeCanBeNarrowed;
import com.intellij.codeInspection.InspectionsBundle;
import com.intellij.codeInspection.LocalQuickFix;
import com.intellij.codeInspection.ProblemDescriptor;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.WriteAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.ScrollType;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.IJSwingUtilities;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.NotNullFunction;
import com.siyeh.ig.psiutils.CommentTracker;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
/**
* refactored from {@link FieldCanBeLocalInspection}
*
* @author Danila Ponomarenko
*/
public abstract class BaseConvertToLocalQuickFix<V extends PsiVariable> implements LocalQuickFix {
protected static final Logger LOG = Logger.getInstance(BaseConvertToLocalQuickFix.class);
@Override
@NotNull
public final String getFamilyName() {
return InspectionsBundle.message("inspection.convert.to.local.quickfix");
}
@Override
public final void applyFix(@NotNull Project project, @NotNull ProblemDescriptor descriptor) {
final V variable = getVariable(descriptor);
if (variable == null || !variable.isValid()) return; //weird. should not get here when field becomes invalid
final PsiFile myFile = variable.getContainingFile();
try {
final PsiElement newDeclaration = moveDeclaration(project, variable);
if (newDeclaration == null) return;
positionCaretToDeclaration(project, myFile, newDeclaration);
}
catch (IncorrectOperationException e) {
LOG.error(e);
}
}
@Nullable
protected abstract V getVariable(@NotNull ProblemDescriptor descriptor);
protected static void positionCaretToDeclaration(@NotNull Project project, @NotNull PsiFile psiFile, @NotNull PsiElement declaration) {
final Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor();
if (editor != null && (IJSwingUtilities.hasFocus(editor.getComponent()) || ApplicationManager.getApplication().isUnitTestMode())) {
final PsiFile openedFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
if (openedFile == psiFile) {
editor.getCaretModel().moveToOffset(declaration.getTextOffset());
editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
}
}
}
protected void beforeDelete(@NotNull Project project, @NotNull V variable, @NotNull PsiElement newDeclaration) {
}
@Nullable
protected PsiElement moveDeclaration(@NotNull Project project, @NotNull V variable) {
final Collection<PsiReference> references = ReferencesSearch.search(variable).findAll();
if (references.isEmpty()) return null;
return moveDeclaration(project, variable, references, true);
}
protected PsiElement moveDeclaration(Project project, V variable, final Collection<? extends PsiReference> references, boolean delete) {
final PsiCodeBlock anchorBlock = findAnchorBlock(references);
if (anchorBlock == null) return null; //was assert, but need to fix the case when obsolete inspection highlighting is left
final PsiElement firstElement = getLowestOffsetElement(references);
final String localName = suggestLocalName(project, variable, anchorBlock);
final PsiElement anchor = getAnchorElement(anchorBlock, firstElement);
final PsiAssignmentExpression anchorAssignmentExpression = searchAssignmentExpression(anchor);
if (anchorAssignmentExpression != null && isVariableAssignment(anchorAssignmentExpression, variable)) {
final Set<PsiReference> refsSet = new HashSet<>(references);
refsSet.remove(anchorAssignmentExpression.getLExpression());
return applyChanges(
project,
localName,
anchorAssignmentExpression.getRExpression(),
variable,
refsSet,
delete,
declaration -> new CommentTracker().replaceAndRestoreComments(anchor, declaration)
);
}
return applyChanges(
project,
localName,
variable.getInitializer(),
variable,
references,
delete,
declaration -> {
PsiElement parent = anchorBlock.getParent();
if (parent instanceof PsiSwitchStatement) {
PsiElement switchContainer = parent.getParent();
return switchContainer.addBefore(declaration, parent);
}
return anchorBlock.addBefore(declaration, anchor);
}
);
}
protected PsiElement applyChanges(@NotNull final Project project,
@NotNull final String localName,
@Nullable final PsiExpression initializer,
@NotNull final V variable,
@NotNull final Collection<? extends PsiReference> references,
final boolean delete, @NotNull final NotNullFunction<? super PsiDeclarationStatement, ? extends PsiElement> action) {
final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(project);
return WriteAction.compute(() -> {
final PsiElement newDeclaration = moveDeclaration(elementFactory, localName, variable, initializer, action, references);
if (delete) {
deleteSourceVariable(project, variable, newDeclaration);
}
return newDeclaration;
});
}
protected void deleteSourceVariable(@NotNull Project project, @NotNull V variable, PsiElement newDeclaration) {
CommentTracker tracker = new CommentTracker();
beforeDelete(project, variable, newDeclaration);
variable.normalizeDeclaration();
tracker.delete(variable);
tracker.insertCommentsBefore(newDeclaration);
}
protected PsiElement moveDeclaration(PsiElementFactory elementFactory,
String localName,
V variable,
PsiExpression initializer,
NotNullFunction<? super PsiDeclarationStatement, ? extends PsiElement> action,
Collection<? extends PsiReference> references) {
final PsiDeclarationStatement declaration = elementFactory.createVariableDeclarationStatement(localName, variable.getType(), initializer);
if (references.stream()
.map(PsiReference::getElement)
.anyMatch(element -> element instanceof PsiExpression &&
PsiUtil.isAccessedForWriting((PsiExpression)element))) {
PsiUtil.setModifierProperty((PsiLocalVariable)declaration.getDeclaredElements()[0], PsiModifier.FINAL, false);
}
final PsiElement newDeclaration = action.fun(declaration);
retargetReferences(elementFactory, localName, references);
return newDeclaration;
}
@Nullable
private static PsiAssignmentExpression searchAssignmentExpression(@Nullable PsiElement anchor) {
if (!(anchor instanceof PsiExpressionStatement)) {
return null;
}
final PsiExpression anchorExpression = ((PsiExpressionStatement)anchor).getExpression();
if (!(anchorExpression instanceof PsiAssignmentExpression)) {
return null;
}
return (PsiAssignmentExpression)anchorExpression;
}
private static boolean isVariableAssignment(@NotNull PsiAssignmentExpression expression, @NotNull PsiVariable variable) {
if (expression.getOperationTokenType() != JavaTokenType.EQ) {
return false;
}
if (!(expression.getLExpression() instanceof PsiReferenceExpression)) {
return false;
}
final PsiReferenceExpression leftExpression = (PsiReferenceExpression)expression.getLExpression();
return leftExpression.isReferenceTo(variable);
}
@NotNull
protected abstract String suggestLocalName(@NotNull Project project, @NotNull V variable, @NotNull PsiCodeBlock scope);
private static void retargetReferences(PsiElementFactory elementFactory, String localName, Collection<? extends PsiReference> refs)
throws IncorrectOperationException {
final PsiReferenceExpression refExpr = (PsiReferenceExpression)elementFactory.createExpressionFromText(localName, null);
for (PsiReference ref : refs) {
if (ref instanceof PsiReferenceExpression) {
((PsiReferenceExpression)ref).replace(refExpr);
}
}
}
@Nullable
private static PsiElement getAnchorElement(PsiCodeBlock anchorBlock, @NotNull PsiElement firstElement) {
PsiElement element = firstElement;
while (element != null && element.getParent() != anchorBlock) {
element = element.getParent();
}
return element;
}
@Nullable
private static PsiElement getLowestOffsetElement(@NotNull Collection<? extends PsiReference> refs) {
PsiElement firstElement = null;
for (PsiReference reference : refs) {
final PsiElement element = reference.getElement();
if (!(element instanceof PsiReferenceExpression)) continue;
if (firstElement == null || firstElement.getTextRange().getStartOffset() > element.getTextRange().getStartOffset()) {
firstElement = element;
}
}
return firstElement;
}
private static PsiCodeBlock findAnchorBlock(final Collection<? extends PsiReference> refs) {
PsiCodeBlock result = null;
for (PsiReference psiReference : refs) {
final PsiElement element = psiReference.getElement();
PsiCodeBlock block = PsiTreeUtil.getParentOfType(element, PsiCodeBlock.class);
if (result == null || block == null) {
result = block;
}
else {
final PsiElement commonParent = PsiTreeUtil.findCommonParent(result, block);
result = PsiTreeUtil.getParentOfType(commonParent, PsiCodeBlock.class, false);
}
}
return result;
}
}
| 41.09434 | 153 | 0.721671 |
7ddb7cca560857c2195483ea0b7c93546060bd47 | 3,083 | /*
*
* Copyright 2008-2021 Kinotic and 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
*
* https://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.kinotic.structures.api.domain;
import java.io.Serializable;
public class Trait implements Serializable {
private String id = null;
private String name = null;
private String describeTrait = null;
private String schema = null;
private String esSchema = null;
private long created = 0;
private boolean required = false; // should the GUI require a field to be filled out when looking at the item
private Long updated;
private boolean modifiable = true; // should this field be modifiable outside the system
private boolean unique = false; // should be a unique field in the index, so no others should exist
private boolean operational = false; // field that says we do not really add to the schema but provide some type of process
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescribeTrait() {
return describeTrait;
}
public void setDescribeTrait(String describeTrait) {
this.describeTrait = describeTrait;
}
public String getSchema() {
return schema;
}
public void setSchema(String schema) {
this.schema = schema;
}
public String getEsSchema() {
return esSchema;
}
public void setEsSchema(String esSchema) {
this.esSchema = esSchema;
}
public long getCreated() {
return created;
}
public void setCreated(long created) {
this.created = created;
}
public boolean isRequired() {
return required;
}
public void setRequired(boolean required) {
this.required = required;
}
public Long getUpdated() {
return updated;
}
public void setUpdated(Long updated) {
this.updated = updated;
}
public boolean isModifiable() {
return modifiable;
}
public void setModifiable(boolean modifiable) {
this.modifiable = modifiable;
}
public boolean isUnique() {
return unique;
}
public void setUnique(boolean unique) {
this.unique = unique;
}
public boolean isOperational() {
return operational;
}
public void setOperational(boolean operational) {
this.operational = operational;
}
}
| 24.664 | 127 | 0.656503 |
1b0f06bf8975c6c0c4c853bbb282abe38740cee0 | 779 | package mekanism.common.content.boiler;
import mekanism.api.Coord4D;
import mekanism.common.base.MultiblockFluidTank;
import mekanism.common.content.tank.SynchronizedTankData.ValveData;
import mekanism.common.tile.TileEntityBoilerCasing;
public abstract class BoilerTank extends MultiblockFluidTank<TileEntityBoilerCasing> {
public BoilerTank(TileEntityBoilerCasing tileEntity) {
super(tileEntity);
}
@Override
protected void updateValveData() {
if (multiblock.structure != null) {
Coord4D coord4D = Coord4D.get(multiblock);
for (ValveData data : multiblock.structure.valves) {
if (coord4D.equals(data.location)) {
data.onTransfer();
}
}
}
}
} | 31.16 | 86 | 0.672657 |
ce19912f69a3193eb2cd29d3ebc523cd673db404 | 367 | package com.baeldung.algorithms.mercator;
public class SphericalMercator extends Mercator {
@Override
double xAxisProjection(double input) {
return Math.toRadians(input) * RADIUS_MAJOR;
}
@Override
double yAxisProjection(double input) {
return Math.log(Math.tan(Math.PI / 4 + Math.toRadians(input) / 2)) * RADIUS_MAJOR;
}
}
| 24.466667 | 90 | 0.689373 |
619cd02f513224356b81e489841c2bdbdf183d06 | 874 | package com.github.thethingyee.parkourplugin.SubCore.listeners;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.inventory.ItemStack;
public class deltethis implements Listener {
@EventHandler
public void breakEvent(BlockBreakEvent e) {
Location blockloc = new Location(e.getPlayer().getWorld(), 0, 47, 0);
if(e.getBlock().getLocation().equals(blockloc)) {
if(!(e.getBlock().getType() == Material.LEAVES)) {
for(ItemStack is : e.getBlock().getDrops()) {
e.getPlayer().getWorld().dropItemNaturally(blockloc, is);
}
e.setCancelled(true);
e.getBlock().setType(Material.LEAVES);
}
}
}
}
| 33.615385 | 77 | 0.641876 |
1e376445bb9f7bf6a927974a2bebc35d4e98d8ee | 1,007 | package util;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.MessageType;
import com.intellij.openapi.ui.popup.Balloon;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.wm.StatusBar;
import com.intellij.openapi.wm.WindowManager;
import com.intellij.ui.awt.RelativePoint;
/**
* Created by gisinfo on 2016/12/30.
*/
public class Util {
/**
* Display simple notification of given type
*
* @param project project
* @param type type
* @param text text
*/
public static void showNotification(Project project, MessageType type, String text) {
StatusBar statusBar = WindowManager.getInstance().getStatusBar(project);
JBPopupFactory.getInstance()
.createHtmlTextBalloonBuilder(text, type, null)
.setFadeoutTime(3000)
.createBalloon()
.show(RelativePoint.getCenterOf(statusBar.getComponent()), Balloon.Position.below);
}
}
| 31.46875 | 99 | 0.692155 |
4c895facc9d68ea58ba9aa13de342f19bcf23e83 | 6,581 | /**
* Copyright 2012 The PlayN 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 playn.tests.core;
import java.nio.ByteBuffer;
import playn.core.ImageLayer;
import playn.core.Keyboard;
import playn.core.Net;
import playn.core.Platform;
import playn.core.util.Callback;
import static playn.core.PlayN.*;
public class NetTest extends Test {
private ImageLayer output;
private String lastPostURL;
private Net.WebSocket _websock;
@Override
public String getName() {
return "NetTest";
}
@Override
public String getDescription() {
return "Tests network support.";
}
@Override
public void init() {
output = graphics().createImageLayer();
graphics().rootLayer().addAt(output, 10, 60);
displayText("HTTP response shown here.");
float x = 10;
x = addButton("Google", new Runnable() {
public void run () {
loadURL("http://www.google.com/");
}
}, x, 10);
x = addButton("Enter URL", new Runnable() {
public void run () {
getText("Enter URL:", new TextCB() {
@Override protected void gotText (String url) {
loadURL(url);
}
});
}
}, x, 10);
x = addButton("Post Test", new Runnable() {
public void run () {
getText("Enter POST body:", new TextCB() {
@Override protected void gotText(String data) {
Net.Builder b = net().req("http://www.posttestserver.com/post.php").setPayload(data);
// don't add the header on HTML because it causes CORS freakoutery
if (platformType() != Platform.Type.HTML) {
b.addHeader("playn-test", "we love to test!");
}
b.execute(new Callback<Net.Response>() {
public void onSuccess (Net.Response rsp) {
String[] lines = rsp.payloadString().split("[\r\n]+");
String urlPre = "View it at ";
for (String line : lines) {
System.err.println(line + " " + line.startsWith(urlPre) + " " + urlPre);
if (line.startsWith(urlPre)) {
lastPostURL = line.substring(urlPre.length());
break;
}
}
displayResult(rsp);
}
public void onFailure (Throwable cause) {
displayText(cause.toString());
}
});
}
});
}
}, x, 10);
x = addButton("Fetch Posted Body", new Runnable() {
public void run () {
if (lastPostURL == null) displayText("Click 'Post Test' to post some data first.");
else net().req(lastPostURL).execute(displayer);
}
}, x, 10);
x = addButton("WS Connect", new Runnable() {
public void run () {
if (_websock != null) displayText("Already connected.");
_websock = net().createWebSocket("ws://echo.websocket.org", new Net.WebSocket.Listener() {
public void onOpen() {
displayText("WebSocket connected.");
}
public void onTextMessage(String msg) {
displayText("Got WebSocket message: " + msg);
}
public void onDataMessage(ByteBuffer msg) {
displayText("Got WebSocket data message: " + msg.limit());
}
public void onClose() {
displayText("WebSocket closed.");
_websock = null;
}
public void onError(String reason) {
displayText("Got WebSocket error: " + reason);
_websock = null;
}
});
displayText("WebSocket connection started.");
}
}, x, 10);
x = addButton("WS Send", new Runnable() {
public void run () {
if (_websock == null) displayText("WebSocket not open.");
else getText("Enter message:", new TextCB() {
@Override protected void gotText(String msg) {
if (_websock == null) displayText("WebSocket disappeared.");
else {
_websock.send(msg);
displayText("WebSocket sent: " + msg);
}
}
});
}
}, x, 10);
x = addButton("WS Close", new Runnable() {
public void run () {
if (_websock == null) displayText("WebSocket not open.");
else _websock.close();
}
}, x, 10);
}
protected void getText (String label, TextCB callback) {
keyboard().getText(Keyboard.TextType.DEFAULT, label, "", callback);
}
protected void loadURL (String url) {
displayText("Loading: " + url);
try {
net().req(url).execute(displayer);
} catch (Exception e) {
displayText(e.toString());
}
}
protected void displayResult (Net.Response rsp) {
StringBuilder buf = new StringBuilder();
buf.append("Response code: ").append(rsp.responseCode());
buf.append("\n\nHeaders:\n");
for (String header : rsp.headerNames()) {
buf.append(header).append(":");
int vv = 0;
for (String value : rsp.headers(header)) {
if (vv++ > 0) buf.append(",");
buf.append(" ").append(value);
}
buf.append("\n");
}
buf.append("\nBody:\n");
String payload = rsp.payloadString();
if (payload.length() > 1024) payload = payload.substring(0, 1024) + "...";
buf.append(payload);
displayText(buf.toString());
}
protected void displayText (String text) {
output.setImage(formatText(TEXT_FMT.withWrapWidth(graphics().width()-20), text, false));
}
private Callback<Net.Response> displayer = new Callback<Net.Response>() {
public void onSuccess (Net.Response rsp) {
displayResult(rsp);
}
public void onFailure (Throwable cause) {
displayText(cause.toString());
}
};
private abstract class TextCB implements Callback<String> {
public void onSuccess(String text) {
if (text != null && text.length() > 0) gotText(text);
}
public void onFailure (Throwable cause) {
displayText(cause.toString());
}
protected abstract void gotText(String text);
}
}
| 31.488038 | 98 | 0.580307 |
c0a6a0943db8fae992350511debc76990bde4be4 | 160 | package org.deplabs.entity.cart.order;
import org.marketlive.entity.cart.order.IOrderPayment;
public interface IOrderPaymentAffirm extends IOrderPayment {
}
| 20 | 60 | 0.83125 |
d3fbff1e29c6f0539a8899dc864072889b8b35aa | 1,853 | package net.disy.biggis.opensensemap.model;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Sensor {
private static final String ID = "_id";
private static final String SENSOR_TYPE = "sensorType";
private static final String TITLE = "title";
private static final String UNIT = "unit";
private static final String LAST_MEASUREMENT = "lastMeasurement";
private String title;
private String unit;
private String sensorType;
private String id;
private Measurement lastMeasurement;
private Map<String, Object> other = new HashMap<>();
@JsonProperty(TITLE)
public String getTitle() {
return title;
}
@JsonProperty(TITLE)
public void setTitle(String title) {
this.title = title;
}
@JsonProperty(UNIT)
public String getUnit() {
return unit;
}
@JsonProperty(UNIT)
public void setUnit(String unit) {
this.unit = unit;
}
@JsonProperty(SENSOR_TYPE)
public String getSensorType() {
return sensorType;
}
@JsonProperty(SENSOR_TYPE)
public void setSensorType(String sensorType) {
this.sensorType = sensorType;
}
@JsonProperty(ID)
public String getId() {
return id;
}
@JsonProperty(ID)
public void setId(String id) {
this.id = id;
}
@JsonProperty(LAST_MEASUREMENT)
public Measurement getLastMeasurement() {
return lastMeasurement;
}
@JsonProperty(LAST_MEASUREMENT)
public void setLastMeasurement(Measurement lastMeasurement) {
this.lastMeasurement = lastMeasurement;
}
@JsonAnyGetter
public Map<String, Object> getOther() {
return other;
}
@JsonAnySetter
public void setOther(String name, Object value) {
other.put(name, value);
}
}
| 21.546512 | 67 | 0.721533 |
696265ee1039ab3b2acc5f0cf3cf6061bdb49314 | 1,727 | package ix.idg.controllers;
import java.util.*;
import play.*;
import play.db.ebean.*;
import play.data.*;
import play.mvc.*;
import ix.core.NamedResource;
import ix.idg.models.Gene;
import ix.core.controllers.EntityFactory;
@NamedResource(name="genes",type=Gene.class)
public class GeneFactory extends EntityFactory {
static final public Model.Finder<Long, Gene> finder =
new Model.Finder(Long.class, Gene.class);
public static Gene getGene (Long id) {
return getEntity (id, finder);
}
public static Result count () {
return count (finder);
}
public static Result page (int top, int skip) {
return page (top, skip, null);
}
public static Result page (int top, int skip, String filter) {
return page (top, skip, filter, finder);
}
public static Result edits (Long id) {
return edits (id, Gene.class);
}
public static Result get (Long id, String expand) {
return get (id, expand, finder);
}
public static Result field (Long id, String path) {
return field (id, path, finder);
}
public static Result create () {
return create (Gene.class, finder);
}
public static Result delete (Long id) {
return delete (id, finder);
}
public static Result update (Long id, String field) {
return update (id, field, Gene.class, finder);
}
public static Gene registerIfAbsent (String name) {
List<Gene> genes = finder.where().eq("name", name).findList();
if (genes.isEmpty()) {
Gene g = new Gene ();
g.name = name;
g.save();
return g;
}
return genes.iterator().next();
}
}
| 25.776119 | 70 | 0.609728 |
b83830e1c28025600d5485600d50c1cc92f9742e | 3,842 | /*
* 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.flink.statefun.e2e.sanity;
import org.apache.flink.statefun.e2e.sanity.generated.VerificationMessages;
import org.apache.flink.statefun.sdk.Address;
import org.apache.flink.statefun.sdk.Context;
import org.apache.flink.statefun.sdk.FunctionType;
import org.apache.flink.statefun.sdk.annotations.Persisted;
import org.apache.flink.statefun.sdk.match.MatchBinder;
import org.apache.flink.statefun.sdk.match.StatefulMatchFunction;
import org.apache.flink.statefun.sdk.state.PersistedValue;
/**
* Simple stateful function that performs actions according to the command received.
*
* <ul>
* <li>{@link VerificationMessages.Noop} command: does not do anything.
* <li>{@link VerificationMessages.Send} command: sends a specified command to another function.
* <li>{@link VerificationMessages.Modify} command: increments state value by a specified amount,
* and then reflects the new state value to an egress as a {@link
* VerificationMessages.StateSnapshot} message.
* </ul>
*/
public final class FnCommandResolver extends StatefulMatchFunction {
/** Represents the {@link FunctionType} that this function is bound to. */
private final int fnTypeIndex;
FnCommandResolver(int fnTypeIndex) {
this.fnTypeIndex = fnTypeIndex;
}
@Persisted
private final PersistedValue<Integer> state = PersistedValue.of("state", Integer.class);
@Override
public void configure(MatchBinder binder) {
binder
.predicate(
VerificationMessages.Command.class, VerificationMessages.Command::hasNoop, this::noop)
.predicate(
VerificationMessages.Command.class, VerificationMessages.Command::hasSend, this::send)
.predicate(
VerificationMessages.Command.class,
VerificationMessages.Command::hasModify,
this::modify);
}
private void send(Context context, VerificationMessages.Command command) {
for (VerificationMessages.Command send : command.getSend().getCommandToSendList()) {
Address to = Utils.toSdkAddress(send.getTarget());
context.send(to, send);
}
}
private void modify(Context context, VerificationMessages.Command command) {
VerificationMessages.Modify modify = command.getModify();
final int nextState =
state.updateAndGet(old -> old == null ? modify.getDelta() : old + modify.getDelta());
// reflect state changes to egress
final VerificationMessages.FnAddress self = selfFnAddress(context);
final VerificationMessages.StateSnapshot result =
VerificationMessages.StateSnapshot.newBuilder().setFrom(self).setState(nextState).build();
context.send(Constants.STATE_SNAPSHOT_EGRESS_ID, result);
}
@SuppressWarnings("unused")
private void noop(Context context, Object ignored) {
// nothing to do
}
private VerificationMessages.FnAddress selfFnAddress(Context context) {
return VerificationMessages.FnAddress.newBuilder()
.setType(fnTypeIndex)
.setId(context.self().id())
.build();
}
}
| 38.808081 | 99 | 0.738938 |
e026f3761f1254713133a142e52bef63efa41917 | 7,805 | /*
* Kubernetes
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: release-1.17
*
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package io.kubernetes.client.openapi.models;
import java.util.Objects;
import java.util.Arrays;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.annotations.SerializedName;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import io.kubernetes.client.openapi.models.V1VolumeNodeResources;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
* CSINodeDriver holds information about the specification of one CSI driver installed on a node
*/
@ApiModel(description = "CSINodeDriver holds information about the specification of one CSI driver installed on a node")
@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen", date = "2020-06-19T10:47:33.387Z[Etc/UTC]")
public class V1CSINodeDriver {
public static final String SERIALIZED_NAME_ALLOCATABLE = "allocatable";
@SerializedName(SERIALIZED_NAME_ALLOCATABLE)
private V1VolumeNodeResources allocatable;
public static final String SERIALIZED_NAME_NAME = "name";
@SerializedName(SERIALIZED_NAME_NAME)
private String name;
public static final String SERIALIZED_NAME_NODE_I_D = "nodeID";
@SerializedName(SERIALIZED_NAME_NODE_I_D)
private String nodeID;
public static final String SERIALIZED_NAME_TOPOLOGY_KEYS = "topologyKeys";
@SerializedName(SERIALIZED_NAME_TOPOLOGY_KEYS)
private List<String> topologyKeys = null;
public V1CSINodeDriver allocatable(V1VolumeNodeResources allocatable) {
this.allocatable = allocatable;
return this;
}
/**
* Get allocatable
* @return allocatable
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
public V1VolumeNodeResources getAllocatable() {
return allocatable;
}
public void setAllocatable(V1VolumeNodeResources allocatable) {
this.allocatable = allocatable;
}
public V1CSINodeDriver name(String name) {
this.name = name;
return this;
}
/**
* This is the name of the CSI driver that this object refers to. This MUST be the same name returned by the CSI GetPluginName() call for that driver.
* @return name
**/
@ApiModelProperty(required = true, value = "This is the name of the CSI driver that this object refers to. This MUST be the same name returned by the CSI GetPluginName() call for that driver.")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public V1CSINodeDriver nodeID(String nodeID) {
this.nodeID = nodeID;
return this;
}
/**
* nodeID of the node from the driver point of view. This field enables Kubernetes to communicate with storage systems that do not share the same nomenclature for nodes. For example, Kubernetes may refer to a given node as \"node1\", but the storage system may refer to the same node as \"nodeA\". When Kubernetes issues a command to the storage system to attach a volume to a specific node, it can use this field to refer to the node name using the ID that the storage system will understand, e.g. \"nodeA\" instead of \"node1\". This field is required.
* @return nodeID
**/
@ApiModelProperty(required = true, value = "nodeID of the node from the driver point of view. This field enables Kubernetes to communicate with storage systems that do not share the same nomenclature for nodes. For example, Kubernetes may refer to a given node as \"node1\", but the storage system may refer to the same node as \"nodeA\". When Kubernetes issues a command to the storage system to attach a volume to a specific node, it can use this field to refer to the node name using the ID that the storage system will understand, e.g. \"nodeA\" instead of \"node1\". This field is required.")
public String getNodeID() {
return nodeID;
}
public void setNodeID(String nodeID) {
this.nodeID = nodeID;
}
public V1CSINodeDriver topologyKeys(List<String> topologyKeys) {
this.topologyKeys = topologyKeys;
return this;
}
public V1CSINodeDriver addTopologyKeysItem(String topologyKeysItem) {
if (this.topologyKeys == null) {
this.topologyKeys = new ArrayList<String>();
}
this.topologyKeys.add(topologyKeysItem);
return this;
}
/**
* topologyKeys is the list of keys supported by the driver. When a driver is initialized on a cluster, it provides a set of topology keys that it understands (e.g. \"company.com/zone\", \"company.com/region\"). When a driver is initialized on a node, it provides the same topology keys along with values. Kubelet will expose these topology keys as labels on its own node object. When Kubernetes does topology aware provisioning, it can use this list to determine which labels it should retrieve from the node object and pass back to the driver. It is possible for different nodes to use different topology keys. This can be empty if driver does not support topology.
* @return topologyKeys
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "topologyKeys is the list of keys supported by the driver. When a driver is initialized on a cluster, it provides a set of topology keys that it understands (e.g. \"company.com/zone\", \"company.com/region\"). When a driver is initialized on a node, it provides the same topology keys along with values. Kubelet will expose these topology keys as labels on its own node object. When Kubernetes does topology aware provisioning, it can use this list to determine which labels it should retrieve from the node object and pass back to the driver. It is possible for different nodes to use different topology keys. This can be empty if driver does not support topology.")
public List<String> getTopologyKeys() {
return topologyKeys;
}
public void setTopologyKeys(List<String> topologyKeys) {
this.topologyKeys = topologyKeys;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
V1CSINodeDriver v1CSINodeDriver = (V1CSINodeDriver) o;
return Objects.equals(this.allocatable, v1CSINodeDriver.allocatable) &&
Objects.equals(this.name, v1CSINodeDriver.name) &&
Objects.equals(this.nodeID, v1CSINodeDriver.nodeID) &&
Objects.equals(this.topologyKeys, v1CSINodeDriver.topologyKeys);
}
@Override
public int hashCode() {
return Objects.hash(allocatable, name, nodeID, topologyKeys);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class V1CSINodeDriver {\n");
sb.append(" allocatable: ").append(toIndentedString(allocatable)).append("\n");
sb.append(" name: ").append(toIndentedString(name)).append("\n");
sb.append(" nodeID: ").append(toIndentedString(nodeID)).append("\n");
sb.append(" topologyKeys: ").append(toIndentedString(topologyKeys)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| 39.619289 | 695 | 0.734401 |
71ac4a40941654835d8f00a4cf49fa38d69699de | 1,752 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package erp.mcfg.data;
import java.util.HashMap;
import sa.lib.SLibUtils;
/**
* SCfgParamValues permite obtener valores individuales desde un valor de parámetro de configuración de SIIE (cfg_params).
* Los valores individuales vienen en duplas de valores separados entre sí mediante punto y coma en el formato key=value.
* @author Sergio Flores
*/
public class SCfgParamValues {
protected final String msParamValue;
protected final HashMap<String, String> moKeyValuesMap;
public SCfgParamValues(final String paramValue) {
msParamValue = paramValue;
moKeyValuesMap = new HashMap<>();
if (msParamValue != null && !msParamValue.isEmpty()) {
String[] keyValues = SLibUtils.textExplode(msParamValue, ";");
for (String keyValue : keyValues) {
String[] keyAndValue = SLibUtils.textExplode(keyValue, "=");
moKeyValuesMap.put(keyAndValue[0], keyAndValue[1]);
}
}
}
/**
* Obtener el valor de parámetro de configuración de SIIE (cfg_params) original.
* @return
*/
public String getParamValue() {
return msParamValue;
}
/**
* Obtener el valor individual correspondiente a la clave proporcionada.
* @param key La clave correspondiente al valor individual deseado.
* @return El valor individual deseado. Si la clave proporcionada no existe, devuelve <code>null</code>.
*/
public String getKeyValue(final String key) {
return moKeyValuesMap.get(key);
}
}
| 34.352941 | 122 | 0.669521 |
adc7d771d449e890ef2786c57ab390662fcf0c48 | 4,219 | package com.jlkj.project.ws.domain;
import java.util.Date;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.jlkj.framework.aspectj.lang.annotation.Excel;
import com.jlkj.framework.web.domain.BaseEntity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.springframework.format.annotation.DateTimeFormat;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
/**
* 项目里程碑计划 对象 t_ws_project_milestoneplan
*
* @author pyy
* @date 2020-06-09
*/
@ApiModel("项目里程碑计划实体")
public class WsProjectMilestoneplan extends BaseEntity
{
private static final long serialVersionUID = 1L;
/** 主键 */
@ApiModelProperty("主键")
private Integer id;
/** 项目ID */
@NotNull(message = "项目id能为空")
@ApiModelProperty(value = "项目ID", required = true)
@Excel(name = "项目ID")
private Integer projectId;
/** 里程碑名称 */
@NotBlank(message = "里程碑名称不能为空")
@ApiModelProperty(value = "里程碑名称", required = true)
@Excel(name = "里程碑名称")
private String milepostName;
/** 里程碑排序 */
@ApiModelProperty("里程碑排序")
@Excel(name = "里程碑排序")
private Integer milepostSort;
/** 里程碑时间 */
@ApiModelProperty("里程碑时间 格式 yyyy-MM-dd")
@JsonFormat(pattern="yyyy-MM-dd")
@Excel(name = "里程碑时间", width = 30, dateFormat = "yyyy-MM-dd")
private Date milepostDate;
/** 创建人 */
@ApiModelProperty("创建人")
@Excel(name = "创建人")
private Integer createdBy;
/** 创建时间 */
@ApiModelProperty("创建时间 格式 yyyy-MM-dd")
@JsonFormat(pattern = "yyyy-MM-dd")
@Excel(name = "创建时间", width = 30, dateFormat = "yyyy-MM-dd")
private Date createdTime;
/** 更新人 */
@ApiModelProperty("更新人")
@Excel(name = "更新人")
private Integer updatedBy;
/** 更新时间 */
@ApiModelProperty("更新时间 格式 yyyy-MM-dd")
@JsonFormat(pattern = "yyyy-MM-dd")
@Excel(name = "更新时间", width = 30, dateFormat = "yyyy-MM-dd")
private Date updatedTime;
public void setId(Integer id)
{
this.id = id;
}
public Integer getId()
{
return id;
}
public void setProjectId(Integer projectId)
{
this.projectId = projectId;
}
public Integer getProjectId()
{
return projectId;
}
public String getMilepostName() {
return milepostName;
}
public void setMilepostName(String milepostName) {
this.milepostName = milepostName;
}
public Integer getMilepostSort() {
return milepostSort;
}
public void setMilepostSort(Integer milepostSort) {
this.milepostSort = milepostSort;
}
public void setMilepostDate(Date milepostDate) {
this.milepostDate = milepostDate;
}
public Date getMilepostDate()
{
return milepostDate;
}
public void setCreatedBy(Integer createdBy)
{
this.createdBy = createdBy;
}
public Integer getCreatedBy()
{
return createdBy;
}
public void setCreatedTime(Date createdTime)
{
this.createdTime = createdTime;
}
public Date getCreatedTime()
{
return createdTime;
}
public void setUpdatedBy(Integer updatedBy)
{
this.updatedBy = updatedBy;
}
public Integer getUpdatedBy()
{
return updatedBy;
}
public void setUpdatedTime(Date updatedTime)
{
this.updatedTime = updatedTime;
}
public Date getUpdatedTime()
{
return updatedTime;
}
@Override
public String toString() {
return new ToStringBuilder(this, ToStringStyle.MULTI_LINE_STYLE)
.append("id", getId())
.append("projectId", getProjectId())
.append("milepostName", getMilepostName())
.append("milepostSort", getMilepostSort())
.append("milepostDate", getMilepostDate())
.append("createdBy", getCreatedBy())
.append("createdTime", getCreatedTime())
.append("updatedBy", getUpdatedBy())
.append("updatedTime", getUpdatedTime())
.toString();
}
}
| 24.672515 | 72 | 0.63854 |
e31645abba3e3a3f39feee4af7a90ca5a9d46e3e | 6,534 | /*
* Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
* Copyright 2011 The ZAP Development Team
*
* 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.zaproxy.zap.extension.anticsrf;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.configuration.ConversionException;
import org.apache.commons.configuration.HierarchicalConfiguration;
import org.apache.log4j.Logger;
import org.parosproxy.paros.common.AbstractParam;
import org.zaproxy.zap.extension.api.ZapApiIgnore;
public class AntiCsrfParam extends AbstractParam {
private static final Logger logger = Logger.getLogger(AntiCsrfParam.class);
private static final String ANTI_CSRF_BASE_KEY = "anticsrf";
private static final String ALL_TOKENS_KEY = ANTI_CSRF_BASE_KEY + ".tokens.token";
private static final String TOKEN_NAME_KEY = "name";
private static final String TOKEN_ENABLED_KEY = "enabled";
private static final String CONFIRM_REMOVE_TOKEN_KEY =
ANTI_CSRF_BASE_KEY + ".confirmRemoveToken";
private static final String[] DEFAULT_TOKENS_NAMES = {
"anticsrf",
"CSRFToken",
"__RequestVerificationToken",
"csrfmiddlewaretoken",
"authenticity_token",
"OWASP_CSRFTOKEN",
"anoncsrf",
"csrf_token",
"_csrf",
"_csrfSecret"
};
private List<AntiCsrfParamToken> tokens = null;
private List<String> enabledTokensNames = null;
private boolean confirmRemoveToken = true;
public AntiCsrfParam() {}
@Override
protected void parse() {
try {
List<HierarchicalConfiguration> fields =
((HierarchicalConfiguration) getConfig()).configurationsAt(ALL_TOKENS_KEY);
this.tokens = new ArrayList<>(fields.size());
enabledTokensNames = new ArrayList<>(fields.size());
List<String> tempTokensNames = new ArrayList<>(fields.size());
for (HierarchicalConfiguration sub : fields) {
String name = sub.getString(TOKEN_NAME_KEY, "");
if (!"".equals(name) && !tempTokensNames.contains(name)) {
boolean enabled = sub.getBoolean(TOKEN_ENABLED_KEY, true);
this.tokens.add(new AntiCsrfParamToken(name, enabled));
tempTokensNames.add(name);
if (enabled) {
enabledTokensNames.add(name);
}
}
}
} catch (ConversionException e) {
logger.error("Error while loading anti CSRF tokens: " + e.getMessage(), e);
this.tokens = new ArrayList<>(DEFAULT_TOKENS_NAMES.length);
this.enabledTokensNames = new ArrayList<>(DEFAULT_TOKENS_NAMES.length);
}
if (this.tokens.size() == 0) {
for (String tokenName : DEFAULT_TOKENS_NAMES) {
this.tokens.add(new AntiCsrfParamToken(tokenName));
this.enabledTokensNames.add(tokenName);
}
}
this.confirmRemoveToken = getBoolean(CONFIRM_REMOVE_TOKEN_KEY, true);
}
@ZapApiIgnore
public List<AntiCsrfParamToken> getTokens() {
return tokens;
}
@ZapApiIgnore
public void setTokens(List<AntiCsrfParamToken> tokens) {
this.tokens = new ArrayList<>(tokens);
((HierarchicalConfiguration) getConfig()).clearTree(ALL_TOKENS_KEY);
ArrayList<String> enabledTokens = new ArrayList<>(tokens.size());
for (int i = 0, size = tokens.size(); i < size; ++i) {
String elementBaseKey = ALL_TOKENS_KEY + "(" + i + ").";
AntiCsrfParamToken token = tokens.get(i);
getConfig().setProperty(elementBaseKey + TOKEN_NAME_KEY, token.getName());
getConfig().setProperty(elementBaseKey + TOKEN_ENABLED_KEY, token.isEnabled());
if (token.isEnabled()) {
enabledTokens.add(token.getName());
}
}
enabledTokens.trimToSize();
this.enabledTokensNames = enabledTokens;
}
/**
* Adds a new token with the given {@code name}, enabled by default.
*
* <p>The call to this method has no effect if the given {@code name} is null or empty, or a
* token with the given name already exist.
*
* @param name the name of the token that will be added
*/
public void addToken(String name) {
if (name == null || name.isEmpty()) {
return;
}
if (tokens.stream().noneMatch(token -> name.equals(token.getName()))) {
this.tokens.add(new AntiCsrfParamToken(name));
this.enabledTokensNames.add(name);
}
}
/**
* Removes the token with the given {@code name}.
*
* <p>The call to this method has no effect if the given {@code name} is null or empty, or a
* token with the given {@code name} does not exist.
*
* @param name the name of the token that will be removed
*/
public void removeToken(String name) {
if (name == null || name.isEmpty()) {
return;
}
for (Iterator<AntiCsrfParamToken> it = tokens.iterator(); it.hasNext(); ) {
AntiCsrfParamToken token = it.next();
if (name.equals(token.getName())) {
it.remove();
if (token.isEnabled()) {
this.enabledTokensNames.remove(name);
}
break;
}
}
}
@ZapApiIgnore
public List<String> getTokensNames() {
return enabledTokensNames;
}
@ZapApiIgnore
public boolean isConfirmRemoveToken() {
return this.confirmRemoveToken;
}
@ZapApiIgnore
public void setConfirmRemoveToken(boolean confirmRemove) {
this.confirmRemoveToken = confirmRemove;
getConfig().setProperty(CONFIRM_REMOVE_TOKEN_KEY, confirmRemoveToken);
}
}
| 34.755319 | 96 | 0.628252 |
c55697ae398a093d31166fbe637a1c3b7757438f | 389 | package com.dasher.osugdx.assets;
import com.badlogic.gdx.assets.AssetDescriptor;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import org.jetbrains.annotations.NotNull;
public class FontHolder extends AssetHolder<BitmapFont> {
public AssetDescriptor<BitmapFont> aller;
public FontHolder(@NotNull AssetPaths assetPaths) {
super(assetPaths.fontsPath.path());
}
}
| 25.933333 | 57 | 0.77635 |
d7d728f68fe8265e9148275c5c23c6c5ada172ca | 970 | package com.adai.opensource.config;
/**
* @author zhouchengpei
* date 2019/12/11 11:06
* description 统一配置
*/
public class ParentConfig {
/**
* 创建 controller、service、dao、mapper的基本名字
* 假如 BASE_NAME = OperationLog 那么相应的Controller、Service、Dao、Mapper如下
* Controller: OperationLogController
* Service: IOperationLogService
* imp: OperationLogServiceImpl
* Dao: OperationLogDao
* Mapper: OperationLogMapper
*/
static String BASE_NAME = "Student";
/**
* 基本的路径
*/
public static String BASE_LOCATION = "F:\\JavaCode\\Idea\\Study\\Temp\\src\\main\\";
/**
* 基本的包名 注意 该值要和BASE_DIRECTORY_PATH一一对应
*/
static String BASE_PACKAGE_NAME = "com.adai";
/**
* 基本的路径名 注意 该值要和BASE_PACKAGE_NAME一一对应
*/
public static String BASE_DIRECTORY_PATH = "com\\adai\\";
/**
* 作者的姓名 生成的entity 需要一些注释
*/
public static String AUTHOR = "zhouchengpei";
}
| 23.095238 | 88 | 0.63299 |
2f255c57c1bf6abe8849bacb4c44052777f0268c | 14,891 | package com.google.common.base;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.regex.Pattern;
import org.checkerframework.checker.nullness.compatqual.NullableDecl;
public final class Predicates {
enum ObjectPredicate implements Predicate<Object> {
ALWAYS_TRUE {
public boolean apply(@NullableDecl Object obj) {
return true;
}
public String toString() {
return "Predicates.alwaysTrue()";
}
},
ALWAYS_FALSE {
public boolean apply(@NullableDecl Object obj) {
return false;
}
public String toString() {
return "Predicates.alwaysFalse()";
}
},
IS_NULL {
public boolean apply(@NullableDecl Object obj) {
return obj == null;
}
public String toString() {
return "Predicates.isNull()";
}
},
NOT_NULL {
public boolean apply(@NullableDecl Object obj) {
return obj != null;
}
public String toString() {
return "Predicates.notNull()";
}
};
/* access modifiers changed from: package-private */
public <T> Predicate<T> withNarrowedType() {
return this;
}
}
private Predicates() {
}
public static <T> Predicate<T> alwaysTrue() {
return ObjectPredicate.ALWAYS_TRUE.withNarrowedType();
}
public static <T> Predicate<T> alwaysFalse() {
return ObjectPredicate.ALWAYS_FALSE.withNarrowedType();
}
public static <T> Predicate<T> isNull() {
return ObjectPredicate.IS_NULL.withNarrowedType();
}
public static <T> Predicate<T> notNull() {
return ObjectPredicate.NOT_NULL.withNarrowedType();
}
public static <T> Predicate<T> not(Predicate<T> predicate) {
return new NotPredicate(predicate);
}
public static <T> Predicate<T> and(Iterable<? extends Predicate<? super T>> iterable) {
return new AndPredicate(defensiveCopy(iterable));
}
@SafeVarargs
public static <T> Predicate<T> and(Predicate<? super T>... predicateArr) {
return new AndPredicate(defensiveCopy((T[]) predicateArr));
}
public static <T> Predicate<T> and(Predicate<? super T> predicate, Predicate<? super T> predicate2) {
return new AndPredicate(asList((Predicate) Preconditions.checkNotNull(predicate), (Predicate) Preconditions.checkNotNull(predicate2)));
}
public static <T> Predicate<T> or(Iterable<? extends Predicate<? super T>> iterable) {
return new OrPredicate(defensiveCopy(iterable));
}
@SafeVarargs
public static <T> Predicate<T> or(Predicate<? super T>... predicateArr) {
return new OrPredicate(defensiveCopy((T[]) predicateArr));
}
public static <T> Predicate<T> or(Predicate<? super T> predicate, Predicate<? super T> predicate2) {
return new OrPredicate(asList((Predicate) Preconditions.checkNotNull(predicate), (Predicate) Preconditions.checkNotNull(predicate2)));
}
public static <T> Predicate<T> equalTo(@NullableDecl T t) {
return t == null ? isNull() : new IsEqualToPredicate(t);
}
public static Predicate<Object> instanceOf(Class<?> cls) {
return new InstanceOfPredicate(cls);
}
public static Predicate<Class<?>> subtypeOf(Class<?> cls) {
return new SubtypeOfPredicate(cls);
}
public static <T> Predicate<T> in(Collection<? extends T> collection) {
return new InPredicate(collection);
}
public static <A, B> Predicate<A> compose(Predicate<B> predicate, Function<A, ? extends B> function) {
return new CompositionPredicate(predicate, function);
}
public static Predicate<CharSequence> containsPattern(String str) {
return new ContainsPatternFromStringPredicate(str);
}
public static Predicate<CharSequence> contains(Pattern pattern) {
return new ContainsPatternPredicate(new JdkPattern(pattern));
}
private static class NotPredicate<T> implements Predicate<T>, Serializable {
private static final long serialVersionUID = 0;
final Predicate<T> predicate;
NotPredicate(Predicate<T> predicate2) {
this.predicate = (Predicate) Preconditions.checkNotNull(predicate2);
}
public boolean apply(@NullableDecl T t) {
return !this.predicate.apply(t);
}
public int hashCode() {
return ~this.predicate.hashCode();
}
public boolean equals(@NullableDecl Object obj) {
if (obj instanceof NotPredicate) {
return this.predicate.equals(((NotPredicate) obj).predicate);
}
return false;
}
public String toString() {
return "Predicates.not(" + this.predicate + ")";
}
}
private static class AndPredicate<T> implements Predicate<T>, Serializable {
private static final long serialVersionUID = 0;
private final List<? extends Predicate<? super T>> components;
private AndPredicate(List<? extends Predicate<? super T>> list) {
this.components = list;
}
public boolean apply(@NullableDecl T t) {
for (int i = 0; i < this.components.size(); i++) {
if (!((Predicate) this.components.get(i)).apply(t)) {
return false;
}
}
return true;
}
public int hashCode() {
return this.components.hashCode() + 306654252;
}
public boolean equals(@NullableDecl Object obj) {
if (obj instanceof AndPredicate) {
return this.components.equals(((AndPredicate) obj).components);
}
return false;
}
public String toString() {
return Predicates.toStringHelper("and", this.components);
}
}
private static class OrPredicate<T> implements Predicate<T>, Serializable {
private static final long serialVersionUID = 0;
private final List<? extends Predicate<? super T>> components;
private OrPredicate(List<? extends Predicate<? super T>> list) {
this.components = list;
}
public boolean apply(@NullableDecl T t) {
for (int i = 0; i < this.components.size(); i++) {
if (((Predicate) this.components.get(i)).apply(t)) {
return true;
}
}
return false;
}
public int hashCode() {
return this.components.hashCode() + 87855567;
}
public boolean equals(@NullableDecl Object obj) {
if (obj instanceof OrPredicate) {
return this.components.equals(((OrPredicate) obj).components);
}
return false;
}
public String toString() {
return Predicates.toStringHelper("or", this.components);
}
}
/* access modifiers changed from: private */
public static String toStringHelper(String str, Iterable<?> iterable) {
StringBuilder sb = new StringBuilder("Predicates.");
sb.append(str);
sb.append('(');
boolean z = true;
for (Object next : iterable) {
if (!z) {
sb.append(',');
}
sb.append(next);
z = false;
}
sb.append(')');
return sb.toString();
}
private static class IsEqualToPredicate<T> implements Predicate<T>, Serializable {
private static final long serialVersionUID = 0;
private final T target;
private IsEqualToPredicate(T t) {
this.target = t;
}
public boolean apply(T t) {
return this.target.equals(t);
}
public int hashCode() {
return this.target.hashCode();
}
public boolean equals(@NullableDecl Object obj) {
if (obj instanceof IsEqualToPredicate) {
return this.target.equals(((IsEqualToPredicate) obj).target);
}
return false;
}
public String toString() {
return "Predicates.equalTo(" + this.target + ")";
}
}
private static class InstanceOfPredicate implements Predicate<Object>, Serializable {
private static final long serialVersionUID = 0;
private final Class<?> clazz;
private InstanceOfPredicate(Class<?> cls) {
this.clazz = (Class) Preconditions.checkNotNull(cls);
}
public boolean apply(@NullableDecl Object obj) {
return this.clazz.isInstance(obj);
}
public int hashCode() {
return this.clazz.hashCode();
}
public boolean equals(@NullableDecl Object obj) {
if (!(obj instanceof InstanceOfPredicate) || this.clazz != ((InstanceOfPredicate) obj).clazz) {
return false;
}
return true;
}
public String toString() {
return "Predicates.instanceOf(" + this.clazz.getName() + ")";
}
}
private static class SubtypeOfPredicate implements Predicate<Class<?>>, Serializable {
private static final long serialVersionUID = 0;
private final Class<?> clazz;
private SubtypeOfPredicate(Class<?> cls) {
this.clazz = (Class) Preconditions.checkNotNull(cls);
}
public boolean apply(Class<?> cls) {
return this.clazz.isAssignableFrom(cls);
}
public int hashCode() {
return this.clazz.hashCode();
}
public boolean equals(@NullableDecl Object obj) {
if (!(obj instanceof SubtypeOfPredicate) || this.clazz != ((SubtypeOfPredicate) obj).clazz) {
return false;
}
return true;
}
public String toString() {
return "Predicates.subtypeOf(" + this.clazz.getName() + ")";
}
}
private static class InPredicate<T> implements Predicate<T>, Serializable {
private static final long serialVersionUID = 0;
private final Collection<?> target;
private InPredicate(Collection<?> collection) {
this.target = (Collection) Preconditions.checkNotNull(collection);
}
public boolean apply(@NullableDecl T t) {
try {
return this.target.contains(t);
} catch (ClassCastException | NullPointerException unused) {
return false;
}
}
public boolean equals(@NullableDecl Object obj) {
if (obj instanceof InPredicate) {
return this.target.equals(((InPredicate) obj).target);
}
return false;
}
public int hashCode() {
return this.target.hashCode();
}
public String toString() {
return "Predicates.in(" + this.target + ")";
}
}
private static class CompositionPredicate<A, B> implements Predicate<A>, Serializable {
private static final long serialVersionUID = 0;
final Function<A, ? extends B> f;
final Predicate<B> p;
private CompositionPredicate(Predicate<B> predicate, Function<A, ? extends B> function) {
this.p = (Predicate) Preconditions.checkNotNull(predicate);
this.f = (Function) Preconditions.checkNotNull(function);
}
public boolean apply(@NullableDecl A a) {
return this.p.apply(this.f.apply(a));
}
public boolean equals(@NullableDecl Object obj) {
if (!(obj instanceof CompositionPredicate)) {
return false;
}
CompositionPredicate compositionPredicate = (CompositionPredicate) obj;
if (!this.f.equals(compositionPredicate.f) || !this.p.equals(compositionPredicate.p)) {
return false;
}
return true;
}
public int hashCode() {
return this.f.hashCode() ^ this.p.hashCode();
}
public String toString() {
return this.p + "(" + this.f + ")";
}
}
private static class ContainsPatternPredicate implements Predicate<CharSequence>, Serializable {
private static final long serialVersionUID = 0;
final CommonPattern pattern;
ContainsPatternPredicate(CommonPattern commonPattern) {
this.pattern = (CommonPattern) Preconditions.checkNotNull(commonPattern);
}
public boolean apply(CharSequence charSequence) {
return this.pattern.matcher(charSequence).find();
}
public int hashCode() {
return Objects.hashCode(this.pattern.pattern(), Integer.valueOf(this.pattern.flags()));
}
public boolean equals(@NullableDecl Object obj) {
if (!(obj instanceof ContainsPatternPredicate)) {
return false;
}
ContainsPatternPredicate containsPatternPredicate = (ContainsPatternPredicate) obj;
if (!Objects.equal(this.pattern.pattern(), containsPatternPredicate.pattern.pattern()) || this.pattern.flags() != containsPatternPredicate.pattern.flags()) {
return false;
}
return true;
}
public String toString() {
String toStringHelper = MoreObjects.toStringHelper((Object) this.pattern).add("pattern", (Object) this.pattern.pattern()).add("pattern.flags", this.pattern.flags()).toString();
return "Predicates.contains(" + toStringHelper + ")";
}
}
private static class ContainsPatternFromStringPredicate extends ContainsPatternPredicate {
private static final long serialVersionUID = 0;
ContainsPatternFromStringPredicate(String str) {
super(Platform.compilePattern(str));
}
public String toString() {
return "Predicates.containsPattern(" + this.pattern.pattern() + ")";
}
}
private static <T> List<Predicate<? super T>> asList(Predicate<? super T> predicate, Predicate<? super T> predicate2) {
return Arrays.asList(new Predicate[]{predicate, predicate2});
}
private static <T> List<T> defensiveCopy(T... tArr) {
return defensiveCopy(Arrays.asList(tArr));
}
static <T> List<T> defensiveCopy(Iterable<T> iterable) {
ArrayList arrayList = new ArrayList();
for (T checkNotNull : iterable) {
arrayList.add(Preconditions.checkNotNull(checkNotNull));
}
return arrayList;
}
}
| 32.655702 | 188 | 0.590625 |
fcd9518df617950640a0d07b0c56a368c98696f5 | 2,610 | package arkanoid.shapes.special;
import arkanoid.shapes.Sprite;
import biuoop.DrawSurface;
import java.awt.Color;
/**
* @author Tommy Zaft
* <p>
* Drawing of a Among-us character
* (some may say amogus).
*/
public class Amongus implements Sprite {
private static final Color RED = new Color(195, 17, 17);
private static final Color EYES = new Color(153, 204, 205);
private static final Color OUTER_EYES = new Color(86, 141, 141);
private final int x;
private final int y;
private final int width;
private final int height;
private final Color bodyColor;
/**
* constructor.
*
* @param x x
* @param y y
* @param bodyColor the bodyColor
*/
public Amongus(int x, int y, Color bodyColor) {
this.x = x;
this.y = y;
this.width = 80;
this.height = 60;
this.bodyColor = bodyColor;
}
/**
* default constructor.
*
* @param x x
* @param y y
*/
public Amongus(int x, int y) {
this(x, y, RED);
}
@Override
public void drawOn(DrawSurface d) {
// backpack
d.setColor(bodyColor);
d.fillOval(x - 20, y - height + 5, width / 2, height);
// body
d.fillCircle(x + width / 2, y - height, width / 2);
d.fillOval(x, y - height / 4, width, height / 2);
d.fillRectangle(x, y - height, width, height);
final int legsY = y - height + 53 + 45 * height / 100;
// right leg
drawLeg(d, legsY, x);
// left leg
final int leftLegX = x + width - width / 3;
drawLeg(d, legsY, leftLegX);
// eyes
d.setColor(OUTER_EYES);
d.fillOval(x + 20, y - height - 20, 75 * width / 100, height / 2);
d.setColor(EYES);
d.fillOval(x + 25, y - height - 20, 68 * width / 100, height / 2 - 5);
}
/**
* draw a leg.
*
* @param d DrawSurface
* @param legsY legY
* @param legX legX
*/
private void drawLeg(DrawSurface d, int legsY, int legX) {
d.setColor(bodyColor);
d.fillRectangle(legX, y - height + 60, width / 3, 45 * height / 100);
d.fillOval(legX, legsY, width / 3, height / 4);
d.fillRectangle(legX, y - height + 60, width / 3, 45 * height / 100);
d.fillOval(legX, y - height + 53, width / 3, height / 4);
}
/**
* get width of building.
*
* @return get width of building.
*/
public int getWidth() {
return width;
}
@Override
public void timePassed() {
//nothing
}
}
| 24.857143 | 78 | 0.542146 |
3d51e2afee586d880f2dd58e94029c6e2dc8fcaa | 2,212 | package array;
import java.util.*;
/**
* @Author czgggggggg
* @Date 2021/8/21
* @Description
*/
public class Array500 {
public static void main(String[] args) {
// String[] words1 = {"Hello","Alaska","Dad","Peace"};
// String[] words1 = {"omk"};
String[] words1 = {"adsdf","sfd"};
String[] results1 = findWords(words1);
for(String result1 : results1){
System.out.print(result1 + " ");
}
System.out.println();
}
public static String[] findWords(String[] words) {
Character[] chars1 = {'Q', 'q', 'W', 'w', 'E', 'e', 'R', 'r', 'T', 't', 'Y', 'y', 'U', 'u', 'I', 'i', 'O', 'o', 'P', 'p'};
Character[] chars2 = {'A', 'a', 'S', 's', 'D', 'd', 'F', 'f', 'G', 'g', 'H', 'h', 'J', 'j', 'K', 'k', 'L', 'l'};
Character[] chars3 = {'Z', 'z', 'X', 'x', 'C', 'c', 'V', 'v', 'B', 'b', 'N', 'n', 'M', 'm'};
HashSet<Character> set1 = new HashSet<>();
HashSet<Character> set2 = new HashSet<>();
HashSet<Character> set3 = new HashSet<>();
set1.addAll(Arrays.asList(chars1));
set2.addAll(Arrays.asList(chars2));
set3.addAll(Arrays.asList(chars3));
List<String> list = new ArrayList<>();
for (int i = 0; i < words.length; i++) {
int tag1 = 0, tag2 = 0, tag3 = 0;
for (int j = 0; j < words[i].length(); j++) {
if (set1.contains(words[i].charAt(j))) {
tag1 = 1;
} else if (set2.contains(words[i].charAt(j))) {
tag2 = 1;
} else if (set3.contains(words[i].charAt(j))) {
tag3 = 1;
}
}
int count = 0;
if (tag1 == 1)
count++;
if (tag2 == 1)
count++;
if (tag3 == 1)
count++;
if (count == 1) {
list.add(words[i]);
}
}
String[] strings = new String[list.size()];
int i = 0;
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
strings[i++] = iterator.next();
}
return strings;
}
}
| 34.5625 | 130 | 0.43264 |
a4e0ef60fe9ec291168b626622e42a39bd5e0f0d | 1,079 | // Copyright (c) 2003-2014, Jodd Team (jodd.org). All Rights Reserved.
package jodd.decora;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
/**
* Special <code>HttpServletRequestWrapper</code> allows filtering of the HTTP headers.
*/
public class DecoraRequestWrapper extends HttpServletRequestWrapper {
public DecoraRequestWrapper(HttpServletRequest httpServletRequest) {
super(httpServletRequest);
}
/**
* Returns <code>null</code> for excluded HTTP headers.
*/
@Override
public String getHeader(String header) {
if (isExcluded(header)) {
return null;
}
return super.getHeader(header);
}
/**
* Returns <code>-1</code> for excluded HTTP headers.
*/
@Override
public long getDateHeader(String header) {
if (isExcluded(header)) {
return -1;
}
return super.getDateHeader(header);
}
/**
* Checks if header name is excluded.
*/
protected boolean isExcluded(String header) {
return "If-Modified-Since".equalsIgnoreCase(header);
}
} | 23.456522 | 88 | 0.698795 |
cfc0a3eed4d59137982c4c75bf95e1d5846c99e3 | 674 | package com.example.mybatis.demomybatis.dao;
import com.example.mybatis.demomybatis.entity.UserEntity;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
/**
* @author dhb
* 这里目前先不加@Mapper注解,等以后看Spring和Mybatis结合的时候再加,现在是纯原生
* @date 2019/11/14 9:43
*/
@Mapper
public interface UserMapper {
/**
* 添加User
* @param entity entity
*/
void addUser(@Param("entity") UserEntity entity);
/**
* 查询User
* @return userEntity
*/
UserEntity getUser();
/**
* 根据ID更新
* @param id userId
* @return boolean
*/
boolean updateUserById(@Param("id") Integer id);
}
| 19.823529 | 57 | 0.642433 |
df46430c27e68f653a4895bb344f6b9ae57f6283 | 616 |
// CloudListUiHandlers.java --
//
// CloudListUiHandlers.java is part of ElectricCommander.
//
// Copyright (c) 2005-2011 Electric Cloud, Inc.
// All rights reserved.
//
package ecplugins.EC_CloudManager.client.view;
import com.gwtplatform.mvp.client.UiHandlers;
import ecplugins.EC_CloudManager.client.model.PlanDetails;
public interface PlanListUiHandlers
extends UiHandlers
{
//~ Methods ----------------------------------------------------------------
void refreshList();
void showDeleteDialog(PlanDetails cloud);
void showCopyDialog(PlanDetails cloud);
void configure();
}
| 20.533333 | 80 | 0.663961 |
10a6354a5bacd5893bd5ca872df67ef502811067 | 870 | package org.bspb.smartbirds.pro.db;
import android.provider.BaseColumns;
import net.simonvt.schematic.annotation.AutoIncrement;
import net.simonvt.schematic.annotation.DataType;
import net.simonvt.schematic.annotation.PrimaryKey;
import static net.simonvt.schematic.annotation.DataType.Type.BLOB;
import static net.simonvt.schematic.annotation.DataType.Type.INTEGER;
import static net.simonvt.schematic.annotation.DataType.Type.REAL;
import static net.simonvt.schematic.annotation.DataType.Type.TEXT;
/**
* Created by groupsky on 27.01.17.
*/
public interface LocationColumns {
@DataType(INTEGER)
@PrimaryKey
@AutoIncrement
String _ID = BaseColumns._ID;
@DataType(REAL)
String LAT = "lat";
@DataType(REAL)
String LON = "lon";
@DataType(BLOB)
String DATA = "data";
// calculated
String DISTANCE = "distance";
}
| 23.513514 | 69 | 0.747126 |
b58ef7b75472cd7481f25d1b5b520ebe83bc79b0 | 6,641 | /*
* Copyright 2014-present IVK JSC. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.broker.itest.jms.connection;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestName;
import com.broker.itest.provider.ProviderLoader;
import com.broker.itest.testcase.QueueConnectionTestCase;
/**
* Test connections.
*
* See JMS specifications, 4.3.5 Closing a Connection
*
*/
public class ConnectionTest extends QueueConnectionTestCase {
@Rule
public TestName name = new TestName();
@Override
public String getTestName() {
return name.getMethodName();
}
/**
* Test that invoking the <code>acknowledge()</code> method of a received message from a closed connection's session
* must throw an <code>IllegalStateException</code>.
*/
@Test
public void testAcknowledge() {
try {
receiverConnection.stop();
//need close previous session
receiverSession.close();
receiverSession = receiverConnection.createQueueSession(false, Session.CLIENT_ACKNOWLEDGE);
receiver = receiverSession.createReceiver(receiverQueue);
receiverConnection.start();
Message message = senderSession.createMessage();
sender.send(message);
Message m = receiver.receive(ProviderLoader.TIMEOUT);
receiverConnection.close();
m.acknowledge();
fail("4.3.5 Invoking the acknowledge method of a received message from a closed " + "connection's session must throw a [javax.jms.]IllegalStateException.\n");
} catch (javax.jms.IllegalStateException e) {
} catch (JMSException e) {
fail("4.3.5 Invoking the acknowledge method of a received message from a closed " + "connection's session must throw a [javax.jms.]IllegalStateException, not a " + e);
} catch (java.lang.IllegalStateException e) {
fail("4.3.5 Invoking the acknowledge method of a received message from a closed " + "connection's session must throw an [javax.jms.]IllegalStateException "
+ "[not a java.lang.IllegalStateException]");
}
}
/**
* Test that an attempt to use a <code>Connection</code> which has been closed throws a
* <code>javax.jms.IllegalStateException</code>.
*/
@Test
public void testUseClosedConnection() {
try {
senderConnection.close();
senderConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
fail("Should raise a javax.jms.IllegalStateException");
} catch (javax.jms.IllegalStateException e) {
} catch (JMSException e) {
fail("Should raise a javax.jms.IllegalStateException, not a " + e);
} catch (java.lang.IllegalStateException e) {
fail("Should raise a javax.jms.IllegalStateException, not a java.lang.IllegalStateException");
}
}
/**
* Test session creation without using parameters
*/
@Test
public void testSessionCreation() {
try {
senderConnection.start();
javax.jms.Session session = senderConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
assertTrue("Sesssion is created", (session != null));
} catch (JMSException e) {
fail("Unable to create session without parameters " + e);
}
}
/**
* Test session creation without using parameters
*/
@Test
public void testSessionCreationSessionMode() {
try {
senderConnection.start();
javax.jms.Session session = senderConnection.createSession(true, Session.SESSION_TRANSACTED);
assertTrue("Sesssion is created", (session != null));
assertTrue("Sesssion transacted is true", (session.getTransacted() == true));
} catch (JMSException e) {
fail("Unable to create session with session mode as parameter " + e);
}
}
/**
* Test that a <code>MessageProducer</code> can send messages while a <code>Connection</code> is stopped.
*/
@Test
public void testMessageSentWhenConnectionClosed() {
try {
senderConnection.stop();
Message message = senderSession.createTextMessage();
sender.send(message);
Message m = receiver.receive(ProviderLoader.TIMEOUT);
assertTrue(m != null);
} catch (JMSException e) {
fail(e.getMessage());
}
}
/**
* Test that closing a closed connectiondoes not throw an exception.
*/
@Test
public void testCloseClosedConnection() {
try {
// senderConnection is already started
// we close it once
senderConnection.close();
// we close it a second time
senderConnection.close();
} catch (Exception e) {
fail("4.3.5 Closing a closed connection must not throw an exception.\n");
}
}
/**
* Test that starting a started connection is ignored
*/
@Test
public void testStartStartedConnection() {
try {
// senderConnection is already started
// start it again should be ignored
senderConnection.start();
} catch (JMSException e) {
fail(e.getMessage());
}
}
/**
* Test that stopping a stopped connection is ignored
*/
@Test
public void testStopStoppedConnection() {
try {
// senderConnection is started
// we stop it once
senderConnection.stop();
// stopping it a second time is ignored
senderConnection.stop();
} catch (JMSException e) {
fail(e.getMessage());
}
}
/**
* Test that delivery of message is stopped if the message consumer connection is stopped
*/
@Test
public void testStopConsumerConnection() {
try {
receiverConnection.stop();
receiver.setMessageListener(new MessageListener() {
@Override
public void onMessage(Message m) {
try {
fail("The message must not be received, the consumer connection is stopped");
assertEquals("test", ((TextMessage) m).getText());
} catch (JMSException e) {
fail(e.getMessage());
}
}
});
TextMessage message = senderSession.createTextMessage();
message.setText("test");
sender.send(message);
synchronized (this) {
try {
wait(1000);
} catch (Exception e) {
fail(e.getMessage());
}
}
} catch (JMSException e) {
fail(e.getMessage());
}
}
}
| 29.127193 | 170 | 0.71164 |
bd5f3acd49e399ab3b7f262cc580efd1b0c04694 | 750 | class Solution {
public int countArrangement(int N) {
final String filled = "x".repeat(N + 1);
StringBuilder sb = new StringBuilder(filled);
Map<String, Integer> memo = new HashMap<>();
return dfs(N, 1, sb, memo);
}
private int dfs(int N, int num, StringBuilder sb, Map<String, Integer> memo) {
if (num == N + 1)
return 1;
final String filled = sb.toString();
if (memo.containsKey(filled))
return memo.get(filled);
int count = 0;
for (int i = 1; i <= N; ++i)
if (sb.charAt(i) == 'x' && (num % i == 0 || i % num == 0)) {
sb.setCharAt(i, 'o');
count += dfs(N, num + 1, sb, memo);
sb.setCharAt(i, 'x');
}
memo.put(filled, count);
return count;
}
}
| 25 | 80 | 0.545333 |
51b58d946b2410e05273c305e4c5a5d95574d5c4 | 578 |
import java.util.Arrays;
import java.util.Scanner;
import java.io.IOException;
import java.lang.reflect.Array;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int testes = input.nextInt();
int dividida = 100;
int q = 0;
int soma = 0;
for (int i = 0; i < testes; i++) {
q = input.nextInt();
dividida = dividida / q;
soma = soma + q - 1;
}
System.out.println(soma);
input.close();
System.exit(0);
}
}
| 24.083333 | 47 | 0.536332 |
a26208b44d8f45b19c4ec9cacdb1a7d974f17371 | 1,002 | package net.alenzen.a2l;
import java.io.IOException;
import java.util.List;
public class CalibrationMethod implements IA2LWriteable {
private String name;
private long version;
// optional parameters
private List<CalibrationHandle> calibrationHandle;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getVersion() {
return version;
}
public void setVersion(long version) {
this.version = version;
}
public List<CalibrationHandle> getCalibrationHandle() {
return calibrationHandle;
}
public void setCalibrationHandles(List<CalibrationHandle> calibrationHandle) {
this.calibrationHandle = calibrationHandle;
}
@Override
public void writeTo(A2LWriter writer) throws IOException {
writer.writelnBeginSpaced("CALIBRATION_METHOD", A2LWriter.toA2LString(name), Long.toString(version));
writer.indent();
writer.write(calibrationHandle);
writer.dedent();
writer.writelnEnd("CALIBRATION_METHOD");
}
}
| 20.875 | 103 | 0.763473 |
4bf08f4039b8a78d882023d3df0b65529132e7c0 | 1,569 | /*
* (C) Copyright IBM Corp. 2020.
*
* 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.ibm.cloud.platform_services.open_service_broker.v1.model;
import com.ibm.cloud.sdk.core.service.model.GenericModel;
/**
* Accepted - MUST be returned if the service instance provisioning is in progress. This triggers the IBM Cloud platform
* to poll the Service Instance `last_operation` Endpoint for operation status. Note that a re-sent `PUT` request MUST
* return a `202 Accepted`, not a `200 OK`, if the service instance is not yet fully provisioned.
*/
public class Resp2079874Root extends GenericModel {
protected String operation;
/**
* Gets the operation.
*
* For asynchronous responses, service brokers MAY return an identifier representing the operation. The value of this
* field MUST be provided by the platform with requests to the Last Operation endpoint in a URL encoded query
* parameter. If present, MUST be a non-empty string.
*
* @return the operation
*/
public String getOperation() {
return operation;
}
}
| 39.225 | 120 | 0.74761 |
401251b96e5f0cc21d9632de8e670573049d7e17 | 3,972 | package com.mateuslima.mvvmpartedois.ui.books;
import android.app.Application;
import android.os.AsyncTask;
import android.util.Log;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import com.mateuslima.mvvmpartedois.data.db.FavoriteDatabase;
import com.mateuslima.mvvmpartedois.data.db.dao.FavoriteDao;
import com.mateuslima.mvvmpartedois.data.db.model.Favorite;
import com.mateuslima.mvvmpartedois.util.Resource;
import com.mateuslima.mvvmpartedois.data.network.ApiServices;
import com.mateuslima.mvvmpartedois.data.network.response.BooksResponse;
import com.mateuslima.mvvmpartedois.data.network.result.BooksResult;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class BooksRepository {
private MutableLiveData<Resource<List<BooksResponse>>> responseList = new MutableLiveData<>();
private LiveData<List<Favorite>> favoriteList;
private FavoriteDao favoriteDao;
private Application application;
public BooksRepository(Application application) {
this.application = application;
FavoriteDatabase database = FavoriteDatabase.getInstance(application);
favoriteDao = database.favoriteDao();
favoriteList = favoriteDao.getAllFavorites();
}
public void pesquisarLivro(String pesquisa){
responseList.setValue(Resource.<List<BooksResponse>>loading());
ApiServices.getInstance().getLivros(pesquisa)
.enqueue(new Callback<BooksResult>() {
@Override
public void onResponse(Call<BooksResult> call, Response<BooksResult> response) {
if (response.isSuccessful()){
if (favoriteList.getValue() != null) {
for (Favorite favorite : favoriteList.getValue()) {
for (BooksResponse livro : response.body().getBooksResponseList()) {
if (favorite.getBookId().equals(livro.getId()))
livro.setFavorite(true);
}
}
}
responseList.postValue(Resource.sucess(response.body().getBooksResponseList()));
}else{
Log.i("INFO","erro "+response.code());
}
}
@Override
public void onFailure(Call<BooksResult> call, Throwable t) {
responseList.setValue(Resource.<List<BooksResponse>>erro(t.getMessage(), null));
}
});
}
public void insertFavorite(Favorite favorite){
new FavoriteAsyncTask(favoriteDao, "insert").execute(favorite);
}
public void deleteFavorite(Favorite favorite){
new FavoriteAsyncTask(favoriteDao, "delete").execute(favorite);
}
public LiveData<Resource<List<BooksResponse>>> getResponseList() {
return responseList;
}
public LiveData<List<Favorite>> getFavoriteList() {
return favoriteList;
}
private static class FavoriteAsyncTask extends AsyncTask<Favorite, Void, Void>{
private FavoriteDao favoriteDao;
private String option;
public FavoriteAsyncTask(FavoriteDao favoriteDao, String option) {
this.favoriteDao = favoriteDao;
this.option = option;
}
@Override
protected Void doInBackground(Favorite... favorites) {
switch (option){
case "insert":
favoriteDao.insert(favorites[0]);
break;
case "delete":
favoriteDao.delete(favorites[0]);
break;
default:
break;
}
return null;
}
}
}
| 35.464286 | 108 | 0.599698 |
a9b17a60e668eef42dccedccf884a07e82c1753b | 872 | package com.totvslabs.mdm.client.ui.events;
import java.util.Date;
import com.totvslabs.mdm.client.util.ProcessTypeEnum;
public class SendDataFluigDataDoneEvent {
private Date when;
private String jsonData;
private ProcessTypeEnum processTypeEnum;
public SendDataFluigDataDoneEvent(ProcessTypeEnum processTypeEnum, String string) {
super();
this.when = new Date();
this.jsonData = string;
this.processTypeEnum = processTypeEnum;
}
public ProcessTypeEnum getProcessTypeEnum() {
return processTypeEnum;
}
public void setProcessTypeEnum(ProcessTypeEnum processTypeEnum) {
this.processTypeEnum = processTypeEnum;
}
public Date getWhen() {
return when;
}
public void setWhen(Date when) {
this.when = when;
}
public String getJsonData() {
return jsonData;
}
public void setJsonData(String jsonData) {
this.jsonData = jsonData;
}
}
| 20.27907 | 84 | 0.761468 |
7a7e1fef9414b9b6c1e89bbbe6df163a4764060f | 1,057 | package io.github.walterinkitchen.formula;
import io.github.walterinkitchen.formula.token.Operand;
import javax.validation.constraints.NotNull;
import java.util.Deque;
import java.util.LinkedList;
/**
* Operand Stack
*
* @author walter
* @date 2022/3/12
**/
public class OperandStack {
private final Deque<Operand> stack = new LinkedList<>();
/**
* push one operand into stack
*
* @param operand operand
*/
public void push(@NotNull Operand operand) {
this.stack.addFirst(operand);
}
/**
* pop one operand from stack
*
* @return operand or null
*/
public Operand pop() {
return stack.pollFirst();
}
/**
* stack size
*
* @return size
*/
public int size() {
return stack.size();
}
/**
* check if stack empty
*
* @return true if empty
*/
public boolean isEmpty() {
return stack.isEmpty();
}
/**
* clear stack
*/
public void clear() {
stack.clear();
}
}
| 17.327869 | 60 | 0.566698 |
9d5938c057fcbacee644085fca56a0f4b112f7c4 | 3,498 | package com.dataart.steps;
import org.junit.Assert;
import org.openqa.selenium.support.ui.ExpectedConditions;
import com.dataart.pages.LoginPage;
import com.dataart.utils.Vars;
import net.thucydides.core.annotations.Step;
import net.thucydides.core.annotations.StepGroup;
import net.thucydides.core.steps.ScenarioSteps;
public class UserLoginSteps extends ScenarioSteps {
LoginPage loginPage;
@Step
public void is_on_the_login_page() {
loginPage.open();
loginPage.waitFor(ExpectedConditions.visibilityOf(loginPage.userNameTextField));
}
@Step
public void enter(String userName, String password) {
loginPage.waitFor(ExpectedConditions.visibilityOf(loginPage.userNameTextField));
loginPage.typeInto(loginPage.userNameTextField, userName);
loginPage.typeInto(loginPage.passwordTextField, password);
}
@Step
public void click_login_button() {
loginPage.waitFor(ExpectedConditions.visibilityOf(loginPage.loginButton));
loginPage.clickOn(loginPage.loginButton);
loginPage.waitForWithRefresh();
}
@Step
public void click_logout_link() {
waitABit(2000);
loginPage.waitForWithRefresh();
loginPage.clickOn(loginPage.logOut);
}
@Step
public void should_see_a_page_title(String message) {
loginPage.waitForTitleToAppear(message);
Assert.assertEquals(message,loginPage.getPageTitle());
}
@Step
public void should_see_invalid_flash_message(String message) {
Assert.assertEquals(message,loginPage.getInvalidFlashMessage());
}
@Step
public void click_on_the_Register_now_link() {
loginPage.clickOnRegisterLink();
}
@Step
public void click_on_the_swich_language_button_and_choose(String language) {
loginPage.chooseLanguage(language);
waitABit(2000);
}
@Step
public void user_should_see_the_header(String header) {
Assert.assertEquals(loginPage.getHearer(), header);
}
@Step
public void user_clicks_on_DA_link() {
loginPage.dataartLinkClick();
}
@Step
public void user_clicks_on_GitHub_link() {
loginPage.waitFor(ExpectedConditions.elementToBeClickable(loginPage.githubLink));
loginPage.githubLinkClick();
}
@Step
public void user_clicks_on_Twitter_link() {
loginPage.twitterLinkClick();
}
@Step
public void verify_DA_page() {
loginPage.goToNewWindow();
loginPage.waitForTitleToAppear(LoginPage.DA_PAGE_TITLE);
Assert.assertEquals(LoginPage.DA_PAGE_TITLE,loginPage.getPageTitle());
}
@Step
public void verify_GitHub_page() {
loginPage.goToNewWindow();
//waitABit(5000);
loginPage.waitForTitleToAppear(LoginPage.GITHUB_PAGE_TITLE);
Assert.assertEquals(LoginPage.GITHUB_PAGE_TITLE,loginPage.getPageTitle());
}
@Step
public void verify_Twitter_page() {
loginPage.goToNewWindow();
waitABit(5000);
//loginPage.waitForTitleToAppear(LoginPage.TWITTER_PAGE_TITLE);
//Assert.assertEquals(LoginPage.TWITTER_PAGE_TITLE,loginPage.getPageTitle());
Assert.assertEquals(Vars.TWITER_PAGE_URL,loginPage.getPageUrl());
}
@Step
public void verify_project_email() {
Assert.assertEquals(LoginPage.MAILTO_LINK_TEXT,loginPage.getEmailLinkTest());
}
@Step
public void the_user_click_on_the_forget_password_link(){
loginPage.clickOnForgetLink();
}
@StepGroup
public void the_user_is_signed_in_with(String userName, String password){
is_on_the_login_page();
enter(userName,password);
click_login_button();
}
@Step
public void user_go_to_user_profile(){
loginPage.clickOn(loginPage.profileLink);
waitABit(500);
}
}
| 23.32 | 83 | 0.777587 |
11567df12c55ef990f21d25bddb4acfeed8e3d20 | 1,534 | package com.yjq.data.admin.model.dto.request;
import com.yjq.data.admin.common.Constant;
import lombok.Data;
import org.hibernate.validator.constraints.Range;
import javax.validation.constraints.NotNull;
/**
* @author [email protected]
* @date 2019-05-06
*/
public class AlarmHistoryRequestDTO extends PageRequestDTO {
/**
* 数据库下标
*/
private Integer tableSuffix;
/**
* 应用id
*/
@NotNull
private Integer appId;
/**
* 告警规则 1.慢查询 2.错误
*/
private Integer alarmRule;
@NotNull
@Range(min = 1)
private Integer page;
@NotNull
@Range(min = 1)
private Integer limit;
public Integer getAppId() {
return appId;
}
public void setAppId(Integer appId) {
this.appId = appId;
this.tableSuffix = appId % Constant.ALARM_HISTORY_TABLE_SPLIT_SIZE;
}
public Integer getAlarmRule() {
return alarmRule;
}
public void setAlarmRule(Integer alarmRule) {
this.alarmRule = alarmRule;
}
public Integer getTableSuffix() {
return tableSuffix;
}
public void setTableSuffix(Integer tableSuffix) {
this.tableSuffix = tableSuffix;
}
public Integer getPage() {
return page;
}
public void setPage(Integer page) {
this.setPageNum(page);
this.page = page;
}
public Integer getLimit() {
return limit;
}
public void setLimit(Integer limit) {
this.setPageSize(limit);
this.limit = limit;
}
}
| 18.707317 | 75 | 0.618644 |
042aca8610eb6e1629902cf2c0947c484789701d | 3,221 | package com.a7space.commons.utils;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/*
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.PropertyFilter;*/
public class JsonIgnoreFieldUtils {//implements PropertyFilter {
private static Logger logger = LoggerFactory.getLogger(JsonIgnoreFieldUtils.class);
/**
* 忽略的属性名称
*/
private String[] fields;
/**
* 是否忽略集合
*/
private boolean ignoreColl = false;
/**
* 空参构造方法<br/>
* 默认不忽略集合
*/
public JsonIgnoreFieldUtils() {
// empty
}
/**
* 构造方法
* @param fields 忽略属性名称数组
*/
public JsonIgnoreFieldUtils(String[] fields) {
this.fields = fields;
}
/**
* 构造方法
* @param ignoreColl 是否忽略集合
* @param fields 忽略属性名称数组
*/
public JsonIgnoreFieldUtils(boolean ignoreColl, String[] fields) {
this.fields = fields;
this.ignoreColl = ignoreColl;
}
/**
* 构造方法
* @param ignoreColl 是否忽略集合
*/
public JsonIgnoreFieldUtils(boolean ignoreColl) {
this.ignoreColl = ignoreColl;
}
public boolean apply(Object source, String name, Object value) {
Field declaredField = null;
//忽略值为null的属性
if(value == null)
return true;
//剔除自定义属性,获取属性声明类型
try {
declaredField = source.getClass().getDeclaredField(name);
} catch (NoSuchFieldException e) {
//logger.debug("没有找到属性{}", name);
}
// 忽略集合
if (declaredField != null) {
if(ignoreColl) {
if(declaredField.getType() == Collection.class
|| declaredField.getType() == Set.class) {
return true;
}
}
}
// 忽略设定的属性
if(fields != null && fields.length > 0) {
if(juge(fields,name)) {
return true;
} else {
return false;
}
}
return false;
}
/**
* 过滤忽略的属性
* @param s
* @param s2
* @return
*/
public boolean juge(String[] s,String s2){
boolean b = false;
for(String sl : s){
if(s2.equals(sl)){
b=true;
}
}
return b;
}
public String[] getFields() {
return fields;
}
/**
* 设置忽略的属性
* @param fields
*/
public void setFields(String[] fields) {
this.fields = fields;
}
public boolean isIgnoreColl() {
return ignoreColl;
}
/**
* 设置是否忽略集合类
* @param ignoreColl
*/
public void setIgnoreColl(boolean ignoreColl) {
this.ignoreColl = ignoreColl;
}
/* JsonConfig config = new JsonConfig();
JsonIgnoreFieldUtils ji=new JsonIgnoreFieldUtils();
ji.setIgnoreColl(true);
ji.setFields(new String[]{});
config.setJsonPropertyFilter(ji);
JSONArray jsonarray = JSONArray.fromObject(json,config);*/
} | 23.172662 | 87 | 0.535858 |
b04d2bdff90b0da7cbcbae0dea0b7b9ea7a610a2 | 1,397 | package beans;
import beans.services.DataService;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.inject.Inject;
import org.jboss.logging.Logger;
/**
* A bean that is responsible of listening to certain destination for incoming messages
* from the Processing Server
*/
@MessageDriven(name = "DataMDB", activationConfig = {
@ActivationConfigProperty(propertyName = "destinationLookup", propertyValue = PathConstants.DATABASE_QUEUE),
@ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"),
@ActivationConfigProperty(propertyName = "connectionParameters", propertyValue = "host="+ PathConstants.REMOTE_SERVER_IP+";port="+ PathConstants.REMOTE_SERVER_JMS_PORT),
@ActivationConfigProperty(propertyName = "connectorClassName", propertyValue = "org.apache.activemq.artemis.core.remoting.impl.netty.NettyConnectorFactory")
})
public class DataMDB extends MessageBean {
private static final Logger logger = Logger.getLogger(DataMDB.class.getName());
@Inject
private DataService dataService;
/**
* This mehods implements the messageRecievd function
* @param message
* @return String to respond to the Processing Server
*/
@Override
protected String messageReceived(String message){
return dataService.saveDataToDB(message);
}
}
| 35.820513 | 177 | 0.756621 |
e5601156bb53b656d231f90f8da8f46401c409b2 | 2,064 | package yatzi;
import yatzi.categories.*;
import java.util.List;
public class YatzyScorer {
private static final int DICE_SET_SIZE = 5;
private final List<Integer> diceList;
public YatzyScorer(List<Integer> diceList) {
// I added a validation here because in old code, the methods have (d1,d2,d3,d4,d5) arguments
// I don't like methods with so many arguments, but here they had the benefit to indicate to caller the number of expected dices
validateDiceList(diceList);
this.diceList = diceList;
}
private void validateDiceList(List<Integer> diceList) {
if (diceList.size() != DICE_SET_SIZE) {
throw new IllegalArgumentException(String.format("A complete dice set is %s dices", DICE_SET_SIZE));
}
}
public int chance() {
return score(new Chance());
}
public int yatzy() {
return score(new Yatzi());
}
public int ones() {
return score(new Matches(1));
}
public int twos() {
return score(new Matches(2));
}
public int threes() {
return score(new Matches(3));
}
public int fours() {
return score(new Matches(4));
}
public int fives() {
return score(new Matches(5));
}
public int sixes() {
return score(new Matches(6));
}
public int onePair() {
return score(new ManyOfAKind(Combinations.PAIR));
}
public int twoPairs() {
return score(new TwoPairs());
}
public int threeOfAKind() {
return score(new ManyOfAKind(Combinations.THREE_OF_A_KIND));
}
public int fourOfAKind() {
return score(new ManyOfAKind(Combinations.FOUR_OF_A_KIND));
}
public int smallStraight() {
return score(new SmallStraight());
}
public int largeStraight() {
return score(new LargeStraight());
}
public int fullHouse() {
return score(new FullHouse());
}
private Integer score(Category category) {
return category.score(diceList);
}
}
| 22.434783 | 136 | 0.614341 |
136f8c054ed192b378f13a0ba695b8f0602d32df | 3,677 | package org.endeavourhealth.core.database.dal.datasharingmanager.models;
import com.fasterxml.jackson.annotation.JsonInclude;
import java.sql.Date;
@JsonInclude(JsonInclude.Include.NON_NULL)
public class JsonDataSharingSummary {
private String uuid = null;
private String name = null;
private String description = null;
private String purpose = null;
private Short natureOfInformationId = null;
private String schedule2Condition = null;
private String benefitToSharing = null;
private String overviewOfDataItems = null;
private Short formatTypeId = null;
private Short dataSubjectTypeId = null;
private String natureOfPersonsAccessingData = null;
private Short reviewCycleId = null;
private Date reviewDate = null;
private Date startDate = null;
private String evidenceOfAgreement = null;
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getPurpose() {
return purpose;
}
public void setPurpose(String purpose) {
this.purpose = purpose;
}
public Short getNatureOfInformationId() {
return natureOfInformationId;
}
public void setNatureOfInformationId(Short natureOfInformationId) {
this.natureOfInformationId = natureOfInformationId;
}
public String getSchedule2Condition() {
return schedule2Condition;
}
public void setSchedule2Condition(String schedule2Condition) {
this.schedule2Condition = schedule2Condition;
}
public String getBenefitToSharing() {
return benefitToSharing;
}
public void setBenefitToSharing(String benefitToSharing) {
this.benefitToSharing = benefitToSharing;
}
public String getOverviewOfDataItems() {
return overviewOfDataItems;
}
public void setOverviewOfDataItems(String overviewOfDataItems) {
this.overviewOfDataItems = overviewOfDataItems;
}
public Short getFormatTypeId() {
return formatTypeId;
}
public void setFormatTypeId(Short formatTypeId) {
this.formatTypeId = formatTypeId;
}
public Short getDataSubjectTypeId() {
return dataSubjectTypeId;
}
public void setDataSubjectTypeId(Short dataSubjectTypeId) {
this.dataSubjectTypeId = dataSubjectTypeId;
}
public String getNatureOfPersonsAccessingData() {
return natureOfPersonsAccessingData;
}
public void setNatureOfPersonsAccessingData(String natureOfPersonsAccessingData) {
this.natureOfPersonsAccessingData = natureOfPersonsAccessingData;
}
public Short getReviewCycleId() {
return reviewCycleId;
}
public void setReviewCycleId(Short reviewCycleId) {
this.reviewCycleId = reviewCycleId;
}
public Date getReviewDate() {
return reviewDate;
}
public void setReviewDate(Date reviewDate) {
this.reviewDate = reviewDate;
}
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public String getEvidenceOfAgreement() {
return evidenceOfAgreement;
}
public void setEvidenceOfAgreement(String evidenceOfAgreement) {
this.evidenceOfAgreement = evidenceOfAgreement;
}
}
| 25.184932 | 86 | 0.691868 |
9cb65200d277f8eb8d1c4a9fb9c31ac4a59b8607 | 3,255 | /*
* Copyright (c) 2016 咖枯 <[email protected] | [email protected]>
*
* 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.kaku.colorfulnews.mvp.presenter.impl;
import com.kaku.colorfulnews.mvp.entity.NewsSummary;
import com.kaku.colorfulnews.common.LoadNewsType;
import com.kaku.colorfulnews.mvp.interactor.NewsListInteractor;
import com.kaku.colorfulnews.mvp.interactor.impl.NewsListInteractorImpl;
import com.kaku.colorfulnews.listener.RequestCallBack;
import com.kaku.colorfulnews.mvp.presenter.NewsListPresenter;
import com.kaku.colorfulnews.mvp.presenter.base.BasePresenterImpl;
import com.kaku.colorfulnews.mvp.view.NewsListView;
import java.util.List;
import javax.inject.Inject;
/**
* @author 咖枯
* @version 1.0 2016/5/19
*/
public class NewsListPresenterImpl extends BasePresenterImpl<NewsListView, List<NewsSummary>>
implements NewsListPresenter, RequestCallBack<List<NewsSummary>> {
private NewsListInteractor<List<NewsSummary>> mNewsListInteractor;
private String mNewsType;
private String mNewsId;
private int mStartPage;
private boolean misFirstLoad;
private boolean mIsRefresh = true;
@Inject
public NewsListPresenterImpl(NewsListInteractorImpl newsListInteractor) {
mNewsListInteractor = newsListInteractor;
}
@Override
public void onCreate() {
if (mView != null) {
loadNewsData();
}
}
@Override
public void beforeRequest() {
if (!misFirstLoad) {
mView.showProgress();
}
}
@Override
public void onError(String errorMsg) {
super.onError(errorMsg);
if (mView != null) {
int loadType = mIsRefresh ? LoadNewsType.TYPE_REFRESH_ERROR : LoadNewsType.TYPE_LOAD_MORE_ERROR;
mView.setNewsList(null, loadType);
}
}
@Override
public void success(List<NewsSummary> items) {
misFirstLoad = true;
if (items != null) {
mStartPage += 20;
}
int loadType = mIsRefresh ? LoadNewsType.TYPE_REFRESH_SUCCESS : LoadNewsType.TYPE_LOAD_MORE_SUCCESS;
if (mView != null) {
mView.setNewsList(items, loadType);
mView.hideProgress();
}
}
@Override
public void setNewsTypeAndId(String newsType, String newsId) {
mNewsType = newsType;
mNewsId = newsId;
}
@Override
public void refreshData() {
mStartPage = 0;
mIsRefresh = true;
loadNewsData();
}
@Override
public void loadMore() {
mIsRefresh = false;
loadNewsData();
}
private void loadNewsData() {
mSubscription = mNewsListInteractor.loadNews(this, mNewsType, mNewsId, mStartPage);
}
}
| 29.0625 | 108 | 0.683871 |
b6a6ce889552f938dffbbf00da5521eae3da69fe | 666 | package families.dao;
import java.util.List;
import families.Father;
/**
* Interface for a DAO class containing data methods implementation for a Father class
*/
public interface IFatherDAO {
/**
* Returns a list with Father objects containing all Father entities stored in DB
*/
List<Father> getAllFathers();
/**
* Returns a Father object containing a Father's data stored in DB with a given id
*/
Father getFatherById(int fatherId);
/**
* Stores in DB the data from a given Father object.
*/
void addFather(Father father);
/**
* Checks if a father with a given id exists in DB
*/
boolean fatherExists(int fatherId);
}
| 21.483871 | 87 | 0.6997 |
62ec01107fdfb266ade5314329ebe00b0c7dd438 | 1,617 | package com.wuwenxu.codecamp.base.question;
/**
* @Title: QuestionTest1
* @Description:
* @Version:1.0.0
* @author pancm
* @date 2017年7月21日
*/
public class QuestionTest1 {
/**
* @param args
*/
public static void main(String[] args) {
/*
* 在一个二维数组中,每一行都按照从左到右递增的顺序排序, 每一列都按照从上到下递增的顺序排序。请完成一个函数,
* 输入这样的一个二维数组和一个整数,判断数组中是否含有该整数。
*/
int target = 4;
int target1 = 5;
int target2 = 6;
int[][] array = { { 1, 2, 3, 4 }, { 1, 2, 3, 4, 5 } };
System.out.println(Find(target, array));
System.out.println(Find(target1, array));
System.out.println(Find(target2, array));
System.out.println(Find2(target, array));
System.out.println(Find2(target1, array));
System.out.println(Find2(target2, array));
}
/**
* 方法一:最笨的方法,利用双重循环找到
*
* @param target
* @param array
* @return
*/
public static boolean Find(int target, int[][] array) {
for (int[] i : array) {
for (int j : i) {
if (j == target) {
return true;
}
}
}
return false;
}
/**
* 方法二: 最优解法。 思路:首先我们选择从左下角开始搜寻, (为什么不从左上角开始搜寻,左上角向右和向下都是递增,那么对于一个点,
* 对于向右和向下会产生一个岔路;如果我们选择从左下脚开始搜寻的话, 如果大于就向右,如果小于就向下)。
*
* @param target
* @param array
* @return
*/
public static boolean Find2(int target, int[][] array) {
int len = array.length - 1; // 得出二维数组的列长度
int i = 0;
while ((len > 0) && (i < array[0].length)) {
if (array[len][i] > target) { // 如果左下角的数值大于要找的数字,则向右,否则向下
len--;
} else if (array[len][i] < target) {
i++;
} else {
return true;
}
}
return false;
}
}
| 20.730769 | 70 | 0.572665 |
275f044217b30de784df7222ff91a08b5e614713 | 2,819 | package com.aidex.common.utils;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
public class NumberUtils extends org.apache.commons.lang3.math.NumberUtils {
/**
* 提供精确的减法运算。
* @param v1 被减数
* @param v2 减数
* @return 两个参数的差
*/
public static double sub(double v1, double v2) {
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.subtract(b2).doubleValue();
}
/**
* 提供精确的加法运算。
* @param v1 被加数
* @param v2 加数
* @return 两个参数的和
*/
public static double add(double v1, double v2) {
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.add(b2).doubleValue();
}
/**
* 提供精确的乘法运算。
* @param v1 被乘数
* @param v2 乘数
* @return 两个参数的积
*/
public static double mul(double v1, double v2) {
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.multiply(b2).doubleValue();
}
/**
* 提供(相对)精确的除法运算,当发生除不尽的情况时,精确到 小数点以后10位,以后的数字四舍五入。
* @param v1 被除数
* @param v2 除数
* @return 两个参数的商
*/
public static double div(double v1, double v2) {
return div(v1, v2, 10);
}
/**
* 提供(相对)精确的除法运算。当发生除不尽的情况时,由scale参数指 定精度,以后的数字四舍五入。
* @param v1 被除数
* @param v2 除数
* @param scale 表示表示需要精确到小数点以后几位。
* @return 两个参数的商
*/
public static double div(double v1, double v2, int scale) {
if (scale < 0) {
throw new IllegalArgumentException("The scale must be a positive integer or zero");
}
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.divide(b2, scale, RoundingMode.HALF_UP).doubleValue();
}
/**
* 格式化双精度,保留两个小数
* @return
*/
public static String formatDouble(Double b) {
BigDecimal bg = new BigDecimal(b);
return bg.setScale(2, RoundingMode.HALF_UP).toString();
}
/**
* 百分比计算
* @return
*/
public static String formatScale(double one, long total) {
BigDecimal bg = new BigDecimal(one * 100 / total);
return bg.setScale(0, RoundingMode.HALF_UP).toString();
}
/**
* 格式化数值类型
* @param data
* @param pattern
*/
public static String formatNumber(Object data, String pattern) {
if (data == null){
return StringUtils.EMPTY;
}
if (data instanceof String){
if (StringUtils.isBlank((String)data)){
return StringUtils.EMPTY;
}else{
data = ObjectUtils.toDouble(data);
}
}
DecimalFormat df = null;
if (pattern == null) {
df = new DecimalFormat();
} else {
df = new DecimalFormat(pattern);
}
return df.format(data);
}
/**
* 获取下一个排序号
* @param order
* @return
*/
public static int nextOrder(Integer order){
if(order == null){
order = 0;
}
return order / 10 * 10 + 10;
}
}
| 22.19685 | 86 | 0.665484 |
8ce832c4b43f4633250984757fb4f950ff7420bb | 5,300 | package sg.com.temasys.skylink.sdk.sampleapp.multivideos;
import android.content.Intent;
import android.support.v4.app.Fragment;
import org.webrtc.SurfaceViewRenderer;
import java.util.List;
import sg.com.temasys.skylink.sdk.rtc.SkylinkMedia;
import sg.com.temasys.skylink.sdk.sampleapp.BaseService;
import sg.com.temasys.skylink.sdk.sampleapp.BaseView;
import sg.com.temasys.skylink.sdk.sampleapp.service.model.SkylinkPeer;
/**
* Created by muoi.pham on 20/07/18.
* This interface is responsible for specify behaviors of View, Presenter, Service
*/
public interface MultiVideosContract {
interface View extends BaseView<Presenter> {
/**
* Get instance of the fragment for processing runtime permission
*/
Fragment getInstance();
/**
* Update UI into connected state
*/
void updateUIConnected(String roomId);
/**
* Update UI into disconnected state
*/
void updateUIDisconnected();
/**
* Update UI when remote peer join the room
*/
void updateUIRemotePeerConnected(SkylinkPeer newPeer, int index);
/**
* Update UI details when peers are in room
*/
void updateUIRemotePeerDisconnected(int peerIndex, List<SkylinkPeer> peersList);
/**
* Update UI details when need to add local video view
*/
void updateUIAddLocalMediaView(SurfaceViewRenderer videoView, SkylinkMedia.MediaType mediaType);
/**
* Update UI details when need to add remote video view
*/
void updateUIAddRemoteMediaView(int peerIndex, SkylinkMedia.MediaType mediaType, SurfaceViewRenderer remoteView);
/**
* Update UI details when need to remove remote video view
*/
void updateUIRemoveRemotePeer(int viewIndex);
/**
* Show or hide button stop screen sharing on UI
*/
void updateUIShowButtonStopScreenSharing();
}
interface Presenter {
/**
* process runtime audio/camera permission results
*/
void processPermissionsResult(int requestCode, String[] permissions, int[] grantResults);
/**
* process the permission for screen sharing
*/
void processActivityResult(int requestCode, int resultCode, Intent data);
/**
* Start local audio
*/
void processStartAudio();
/**
* Start local video base on the default video device setting
*/
void processStartVideo();
/**
* Start local screen video view
*/
void processStartScreenShare();
/**
* Start second video view
*/
void processStartSecondVideoView();
void processStartLocalMediaIfConfigAllow();
void processStopScreenShare();
/**
* process data to display on view at initiative connection
*/
void processConnectedLayout();
/**
* process resuming the app state when view resumed
*/
void processResumeState();
/**
* process pausing the app state when view paused
*/
void processPauseState();
/**
* process disconnecting/closing the app when view exited
*/
void processExit();
/**
* process switching camera to front/back camera
*/
void processSwitchCamera();
/**
* process starting recording function
*/
void processStartRecording();
/**
* process stopping recording function
*/
void processStopRecording();
/**
* process get info about local input video resolution from SDK
*/
void processGetInputVideoResolution();
/**
* process get info about local sent video resolution from SDK
*/
void processGetSentVideoResolution(int peerIndex);
/**
* process get info about remote received video resolution from SDK
*/
void processGetReceivedVideoResolution(int peerIndex);
/**
* process toggling stats from WebRTC lib
*/
void processToggleWebrtcStats(int peerIndex);
/**
* process getting info about transfer speed through network
*/
void processGetTransferSpeeds(int peerIndex, SkylinkMedia.MediaType mediaType, boolean forSending);
/**
* process refresh the connection to remote peer
*/
void processRefreshConnection(int peerIndex, boolean iceRestart);
/**
* process getting total number of peers in the current room
*/
int processGetTotalInRoom();
/**
* process getting remote video view from specific peer
*/
List<SurfaceViewRenderer> processGetVideoViewByIndex(int index);
/**
* Get specific peer at index
*/
SkylinkPeer processGetPeerByIndex(int index);
/**
* Get the stats state of specific remote video view
*/
Boolean processGetWebRtcStatsState(int peerIndex);
}
interface Service extends BaseService<Presenter> {
}
}
| 26.633166 | 121 | 0.608868 |
a9d7485d1c97135d637770667776128f9cd88c5a | 3,795 | /*
* Copyright 2004-2009 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.compass.gps.impl;
import java.util.Properties;
import junit.framework.TestCase;
import org.compass.core.Compass;
import org.compass.core.CompassSession;
import org.compass.core.CompassTransaction;
import org.compass.core.config.CompassConfiguration;
import org.compass.core.config.CompassEnvironment;
import org.compass.core.lucene.LuceneEnvironment;
import org.compass.gps.device.MockIndexGpsDevice;
import org.compass.gps.device.MockIndexGpsDeviceObject;
/**
* @author kimchy
*/
public class SingleCompassGpsIndexTests extends TestCase {
private Compass compass;
private SingleCompassGps compassGps;
private MockIndexGpsDevice device;
public void testSimpleIndex() {
CompassConfiguration conf = new CompassConfiguration();
conf.setSetting(CompassEnvironment.CONNECTION, "target/test-index");
conf.addClass(MockIndexGpsDeviceObject.class);
conf.getSettings().setBooleanSetting(CompassEnvironment.DEBUG, true);
compass = conf.buildCompass();
device = new MockIndexGpsDevice();
device.setName("test");
compassGps = new SingleCompassGps(compass);
compassGps.addGpsDevice(device);
compassGps.start();
compass.getSearchEngineIndexManager().deleteIndex();
compass.getSearchEngineIndexManager().createIndex();
assertNoObjects();
device.add(new Long(1), "testvalue");
compassGps.index();
assertExists(new Long(1));
compassGps.stop();
compass.close();
}
public void testWithPropertiesForSingleComopassGps() {
CompassConfiguration conf = new CompassConfiguration();
conf.setSetting(CompassEnvironment.CONNECTION, "target/test-index");
conf.addClass(MockIndexGpsDeviceObject.class);
conf.getSettings().setBooleanSetting(CompassEnvironment.DEBUG, true);
compass = conf.buildCompass();
compass.getSearchEngineIndexManager().deleteIndex();
compass.getSearchEngineIndexManager().createIndex();
device = new MockIndexGpsDevice();
device.setName("test");
compassGps = new SingleCompassGps(compass);
compassGps.addGpsDevice(device);
Properties props = new Properties();
props.setProperty(LuceneEnvironment.SearchEngineIndex.MAX_BUFFERED_DOCS, "100");
compassGps.setIndexSettings(props);
compassGps.start();
assertNoObjects();
device.add(new Long(1), "testvalue");
compassGps.index();
assertExists(new Long(1));
compassGps.stop();
compass.close();
}
private void assertExists(Long id) {
CompassSession session = compass.openSession();
CompassTransaction tr = session.beginTransaction();
session.load(MockIndexGpsDeviceObject.class, id);
tr.commit();
session.close();
}
private void assertNoObjects() {
CompassSession session = compass.openSession();
CompassTransaction tr = session.beginTransaction();
assertEquals(0, session.queryBuilder().matchAll().hits().length());
tr.commit();
session.close();
}
}
| 33.289474 | 88 | 0.69697 |
5cdb0b6861e4d3deea0946b41246bad8ff1e9ef9 | 583 | package ai.datagym.application.labelIteration.models.change.update;
import ai.datagym.application.labelIteration.entity.geometry.SimplePointPojo;
public class PointChangeUpdateBindingModel extends LcEntryChangeUpdateBindingModel {
private SimplePointPojo point;
public SimplePointPojo getPoint() {
return point;
}
public void setPoint(SimplePointPojo point) {
this.point = point;
}
@Override
public String toString() {
return "PointChangeCreateBindingModel{" +
"point=" + point +
'}';
}
}
| 24.291667 | 84 | 0.682676 |
b21d82e3930c48dd0e3c81131efe55fbe27e2f13 | 1,702 | package org.iupac.fairdata.sample;
import org.iupac.fairdata.common.IFDConst;
import org.iupac.fairdata.core.IFDReference;
import org.iupac.fairdata.core.IFDRepresentableObject;
import org.iupac.fairdata.core.IFDRepresentation;
/**
* An IFDSample represents a physical sample that optionally has one or the
* other or both of associated IFDStructureCollection and
* IFDDataObjectCollection. It may also have a representation.
*
* It is expected to hold numerous IFDProperty values that describe the sample.
*
* Multiple IFDStructures would indicate a mixture or, perhaps, an ambiguity
* (which would be distinguished by its properties or subclass) Multiple
* IFDDataObjects indicate multiple experiments all relating to this particular
* sample.
*
* Since IFDSample can exist with no structures and/or no data and/or no
* representations, it can be considered a starting "holder class" that can be
* added to during the process of sample analysis, before any structure is known
* or any spectroscopy is carried out, for example.
*
*
* @author hansonr
*
*/
@SuppressWarnings("serial")
public class IFDSample extends IFDRepresentableObject<IFDSampleRepresentation> {
private static String propertyPrefix = IFDConst.concat(IFDConst.IFD_PROPERTY_FLAG, IFDConst.IFD_SAMPLE_FLAG);
@Override
protected String getPropertyPrefix() {
return propertyPrefix;
}
public IFDSample() {
super(null, null);
setProperties(propertyPrefix, null);
}
@Override
protected IFDRepresentation newRepresentation(IFDReference ifdReference, Object object, long len, String type,
String subtype) {
return new IFDSampleRepresentation(ifdReference, object, len, type, subtype);
}
}
| 33.372549 | 111 | 0.783784 |
375555b1eb5f4a43f0706be29c84bd499fdc0cd5 | 351 | package de.vta.vtalauncher.exception;
public class VtaLogicException extends vtaException {
public VtaLogicException(String message) {
super(message);
}
public VtaLogicException(Throwable cause) {
super(cause);
}
public VtaLogicException(String message, Throwable cause) {
super(message, cause);
}
}
| 21.9375 | 63 | 0.68661 |
60370944ea411d8dbdc3b1619a0dfa11f2d4dbda | 1,078 | package com.reason.lang.ocaml;
import com.reason.lang.core.psi.PsiVal;
import com.reason.lang.core.psi.impl.PsiLowerIdentifier;
import com.reason.lang.core.psi.impl.PsiScopedExpr;
import com.reason.lang.core.psi.impl.PsiValImpl;
public class ValParsingTest extends OclParsingTestCase {
public void test_qualifiedName() {
PsiVal e = first(valExpressions(parseCode("val x : int")));
assertEquals("Dummy.x", e.getQualifiedName());
assertFalse(e.isFunction());
}
public void test_name() {
PsiVal e = first(valExpressions(parseCode("val x : int")));
assertInstanceOf(((PsiValImpl) e).getNameIdentifier(), PsiLowerIdentifier.class);
assertEquals("x", e.getName());
}
public void test_specialName() {
PsiVal e = first(valExpressions(parseCode("val (>>=) : 'a -> 'a t")));
assertInstanceOf(((PsiValImpl) e).getNameIdentifier(), PsiScopedExpr.class);
assertEquals("(>>=)", e.getName());
}
public void test_function() {
PsiVal e = first(valExpressions(parseCode("val x : 'a -> 'a t")));
assertTrue(e.isFunction());
}
}
| 29.944444 | 85 | 0.694805 |
522b1bbeacbbb7a8e2e707629c2b81b7e29b4d45 | 957 | package com.example.shmulik.control;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import com.example.shmulik.myjavaproject.R;
/**
* Created by reuvenp on 6/24/2016.
*/
public class AddBookWebView extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_add_book_webview,container,false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
WebView webView = (WebView) getView().findViewById(R.id.add_book_wv);
if (webView != null)
webView.loadUrl("http://plevinsk.vlab.jct.ac.il/form/addBook.html");
}
}
| 30.870968 | 103 | 0.742947 |
2c59c829873b9845d296fc0eb9350f261b506584 | 458 | /*-------------------*
| Rodrigo CavanhaMan |
| URI 2172 |
| Evento |
*--------------------*/
import java.util.Locale;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int X, M;
X = sc.nextInt();
M = sc.nextInt();
while(X!=0 && M!=0){
int EXP = X*M;
System.out.println(EXP);
X = sc.nextInt();
M = sc.nextInt();
}
sc.close();
}
} | 17.615385 | 41 | 0.504367 |
81dd237b7f3300be06eb770bbf24118f6ade5f9c | 4,746 | package com.andreistraut.gaps.datamodel.graph;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
public class DirectedWeightedGraphStaticTest {
private final int RUN_LIMIT_SMALL = 10000;
private final int NUMBER_OF_NODES_SMALL = 5;
private final int NUMBER_OF_EDGES_SMALL = 10;
private final int RUN_LIMIT_MEDIUM = 500;
private final int NUMBER_OF_NODES_MEDIUM = 100;
private final int NUMBER_OF_EDGES_MEDIUM = 500;
private final int RUN_LIMIT_LARGE = 10;
private final int NUMBER_OF_NODES_LARGE = 1000;
private final int NUMBER_OF_EDGES_LARGE = 3000;
public DirectedWeightedGraphStaticTest() {
}
@BeforeClass
public static void setUpClass() {
Logger.getLogger(DirectedWeightedGraphStaticTest.class.getName()).log(Level.INFO,
"{0} TEST: Graph Static Generation",
DirectedWeightedGraphStaticTest.class.toString());
}
@Test
public void testInitNodes() {
DirectedWeightedGraphStatic graph = new DirectedWeightedGraphStatic(10, 30);
ArrayList<Node> nodes = graph.initNodes();
Assert.assertTrue(nodes.size() == 10);
Assert.assertTrue(graph.getNodes().size() == 10);
Assert.assertTrue(graph.vertexSet().size() == 10);
}
@Test
public void testGraphGenerationSmallGraph() {
for (int i = 0; i < RUN_LIMIT_SMALL; i++) {
DirectedWeightedGraphStatic first = new DirectedWeightedGraphStatic(
this.NUMBER_OF_NODES_SMALL, this.NUMBER_OF_EDGES_SMALL);
DirectedWeightedGraphStatic second = new DirectedWeightedGraphStatic(
this.NUMBER_OF_NODES_SMALL, this.NUMBER_OF_EDGES_SMALL);
first.initNodes();
second.initNodes();
ArrayList<DirectedWeightedEdge> firstEdges = first.initEdges();
ArrayList<DirectedWeightedEdge> secondEdges = second.initEdges();
Assert.assertTrue(first.equals(second));
Assert.assertTrue(firstEdges.equals(secondEdges));
}
}
@Test
public void testGraphGenerationMediumGraph() {
for (int i = 0; i < RUN_LIMIT_MEDIUM; i++) {
DirectedWeightedGraphStatic first = new DirectedWeightedGraphStatic(
this.NUMBER_OF_NODES_MEDIUM, this.NUMBER_OF_EDGES_MEDIUM);
DirectedWeightedGraphStatic second = new DirectedWeightedGraphStatic(
this.NUMBER_OF_NODES_MEDIUM, this.NUMBER_OF_EDGES_MEDIUM);
first.initNodes();
second.initNodes();
ArrayList<DirectedWeightedEdge> firstEdges = first.initEdges();
ArrayList<DirectedWeightedEdge> secondEdges = second.initEdges();
Assert.assertTrue(first.equals(second));
Assert.assertTrue(firstEdges.equals(secondEdges));
}
}
@Test
public void testGraphGenerationLargeGraph() {
for (int i = 0; i < RUN_LIMIT_LARGE; i++) {
DirectedWeightedGraphStatic first = new DirectedWeightedGraphStatic(
this.NUMBER_OF_NODES_LARGE, this.NUMBER_OF_EDGES_LARGE);
DirectedWeightedGraphStatic second = new DirectedWeightedGraphStatic(
this.NUMBER_OF_NODES_LARGE, this.NUMBER_OF_EDGES_LARGE);
first.initNodes();
second.initNodes();
ArrayList<DirectedWeightedEdge> firstEdges = first.initEdges();
ArrayList<DirectedWeightedEdge> secondEdges = second.initEdges();
Assert.assertTrue(first.equals(second));
Assert.assertTrue(firstEdges.equals(secondEdges));
}
}
@Test
public void testGraphGenerationLargeGraphSpecialFailedTest() {
/**
* Test a special case in which graph generation would hang up in GUI for a static graph
* with these specific parameters
*/
for (int i = 0; i < RUN_LIMIT_LARGE; i++) {
DirectedWeightedGraphStatic first = new DirectedWeightedGraphStatic(
100, 500);
first.minimumEdgeWeight = 1;
first.maximumEdgeWeight = 1000;
DirectedWeightedGraphStatic second = new DirectedWeightedGraphStatic(
100, 500);
second.minimumEdgeWeight = 1;
second.maximumEdgeWeight = 1000;
first.initNodes();
second.initNodes();
ArrayList<DirectedWeightedEdge> firstEdges = first.initEdges();
ArrayList<DirectedWeightedEdge> secondEdges = second.initEdges();
Assert.assertTrue(first.equals(second));
Assert.assertTrue(firstEdges.equals(secondEdges));
}
}
}
| 36.790698 | 89 | 0.663506 |
ad1268f563183e003aef1b2838b1ef9f03da4a28 | 10,760 | /*
* 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.asterix.lang.sqlpp.rewrites.visitor;
import org.apache.asterix.common.exceptions.CompilationException;
import org.apache.asterix.lang.common.base.AbstractClause;
import org.apache.asterix.lang.common.base.Expression;
import org.apache.asterix.lang.common.base.ILangExpression;
import org.apache.asterix.lang.common.clause.GroupbyClause;
import org.apache.asterix.lang.common.clause.LetClause;
import org.apache.asterix.lang.common.clause.LimitClause;
import org.apache.asterix.lang.common.clause.OrderbyClause;
import org.apache.asterix.lang.common.expression.GbyVariableExpressionPair;
import org.apache.asterix.lang.common.expression.VariableExpr;
import org.apache.asterix.lang.common.rewrites.LangRewritingContext;
import org.apache.asterix.lang.common.struct.Identifier;
import org.apache.asterix.lang.sqlpp.clause.FromClause;
import org.apache.asterix.lang.sqlpp.clause.HavingClause;
import org.apache.asterix.lang.sqlpp.clause.SelectBlock;
import org.apache.asterix.lang.sqlpp.clause.SelectClause;
import org.apache.asterix.lang.sqlpp.expression.SelectExpression;
import org.apache.asterix.lang.sqlpp.util.SqlppRewriteUtil;
import org.apache.asterix.lang.sqlpp.util.SqlppVariableUtil;
import org.apache.asterix.lang.sqlpp.visitor.base.AbstractSqlppExpressionScopingVisitor;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* An AST pre-processor to rewrite group-by sugar queries, which does the following transformations:
* 1. Rewrite the argument expression of an aggregation function into a subquery
* 2. Turn a SQL-92 aggregate function into a SQL++ core aggregate function when performing 1.
* <p>
* <p>
* For example, this visitor turns the following query:
* <pre>
* FROM Employee e
* JOIN Incentive i ON e.job_category = i.job_category
* JOIN SuperStars s ON e.id = s.id
* GROUP BY e.department_id AS deptId
* GROUP AS eis(e AS e, i AS i, s AS s)
* SELECT deptId as deptId, SUM(e.salary + i.bonus) AS star_cost;
* </pre>
* into the following core-version query:
* <pre>
* FROM Employee e
* JOIN Incentive i ON e.job_category = i.job_category
* JOIN SuperStars s ON e.id = s.id
* GROUP BY e.department_id AS deptId
* GROUP AS eis(e AS e, i AS i, s AS s)
* SELECT ELEMENT {
* 'deptId': deptId,
* 'star_cost': array_sum( (FROM eis AS p SELECT ELEMENT p.e.salary + p.i.bonus) )
* };
* </pre>
* where <code>SUM(e.salary + i.bonus)</code>
* is turned into <code>array_sum( (FROM eis AS p SELECT ELEMENT p.e.salary + p.i.bonus) )</code>
*/
public class SqlppGroupByAggregationSugarVisitor extends AbstractSqlppExpressionScopingVisitor {
public SqlppGroupByAggregationSugarVisitor(LangRewritingContext context) {
super(context);
}
@Override
public Expression visit(SelectBlock selectBlock, ILangExpression arg) throws CompilationException {
// Traverses the select block in the order of "from", "let/where"s, "group by", "let/having"s and "select".
FromClause fromClause = selectBlock.getFromClause();
if (selectBlock.hasFromClause()) {
fromClause.accept(this, arg);
}
if (selectBlock.hasLetWhereClauses()) {
for (AbstractClause letWhereClause : selectBlock.getLetWhereList()) {
letWhereClause.accept(this, arg);
}
}
if (selectBlock.hasGroupbyClause()) {
Set<VariableExpr> visibleVarsPreGroupByScope = scopeChecker.getCurrentScope().getLiveVariables();
GroupbyClause groupbyClause = selectBlock.getGroupbyClause();
groupbyClause.accept(this, arg);
Collection<VariableExpr> visibleVarsInCurrentScope = SqlppVariableUtil.getBindingVariables(groupbyClause);
VariableExpr groupVar = groupbyClause.getGroupVar();
Map<Expression, Identifier> groupFieldVars = getGroupFieldVariables(groupbyClause);
Collection<VariableExpr> freeVariables = new HashSet<>();
Collection<VariableExpr> freeVariablesInGbyLets = new HashSet<>();
if (selectBlock.hasLetHavingClausesAfterGroupby()) {
for (AbstractClause letHavingClause : selectBlock.getLetHavingListAfterGroupby()) {
letHavingClause.accept(this, arg);
// Rewrites each let/having clause after the group-by.
rewriteExpressionUsingGroupVariable(groupVar, groupFieldVars, letHavingClause,
visibleVarsPreGroupByScope);
switch (letHavingClause.getClauseType()) {
case LET_CLAUSE:
LetClause letClause = (LetClause) letHavingClause;
Collection<VariableExpr> freeVariablesInClause =
SqlppVariableUtil.getFreeVariables(letClause.getBindingExpr());
freeVariablesInClause.removeAll(visibleVarsInCurrentScope);
freeVariablesInGbyLets.addAll(freeVariablesInClause);
visibleVarsInCurrentScope.add(letClause.getVarExpr());
break;
case HAVING_CLAUSE:
freeVariables.addAll(SqlppVariableUtil.getFreeVariables(letHavingClause));
break;
default:
throw new IllegalStateException(String.valueOf(letHavingClause.getClauseType()));
}
}
}
SelectExpression parentSelectExpression = (SelectExpression) arg;
// We cannot rewrite ORDER BY and LIMIT if it's a SET operation query.
if (!parentSelectExpression.getSelectSetOperation().hasRightInputs()) {
if (parentSelectExpression.hasOrderby()) {
// Rewrites the ORDER BY clause.
OrderbyClause orderbyClause = parentSelectExpression.getOrderbyClause();
orderbyClause.accept(this, arg);
rewriteExpressionUsingGroupVariable(groupVar, groupFieldVars, orderbyClause,
visibleVarsPreGroupByScope);
freeVariables.addAll(SqlppVariableUtil.getFreeVariables(orderbyClause));
}
if (parentSelectExpression.hasLimit()) {
// Rewrites the LIMIT clause.
LimitClause limitClause = parentSelectExpression.getLimitClause();
limitClause.accept(this, arg);
rewriteExpressionUsingGroupVariable(groupVar, groupFieldVars, limitClause,
visibleVarsPreGroupByScope);
freeVariables.addAll(SqlppVariableUtil.getFreeVariables(limitClause));
}
}
// Visits the select clause.
SelectClause selectClause = selectBlock.getSelectClause();
selectClause.accept(this, arg);
// Rewrites the select clause.
rewriteExpressionUsingGroupVariable(groupVar, groupFieldVars, selectClause, visibleVarsPreGroupByScope);
freeVariables.addAll(SqlppVariableUtil.getFreeVariables(selectClause));
freeVariables.removeAll(visibleVarsInCurrentScope);
// Gets the final free variables.
freeVariables.addAll(freeVariablesInGbyLets);
freeVariables.removeIf(SqlppVariableUtil::isExternalVariableReference);
// Gets outer scope variables.
Collection<VariableExpr> decorVars = scopeChecker.getCurrentScope().getLiveVariables();
decorVars.removeAll(visibleVarsInCurrentScope);
// Only retains used free variables.
if (!decorVars.containsAll(freeVariables)) {
throw new IllegalStateException(decorVars + ":" + freeVariables);
}
decorVars.retainAll(freeVariables);
if (!decorVars.isEmpty()) {
// Adds necessary decoration variables for the GROUP BY.
// NOTE: we need to include outer binding variables so as they can be evaluated before
// the GROUP BY instead of being inlined as part of nested pipepline. The current optimzier
// is not able to optimize the latter case. The following query is such an example:
// asterixdb/asterix-app/src/test/resources/runtimets/queries_sqlpp/dapd/q2-11
List<GbyVariableExpressionPair> decorList = new ArrayList<>();
if (groupbyClause.hasDecorList()) {
decorList.addAll(groupbyClause.getDecorPairList());
}
for (VariableExpr var : decorVars) {
decorList.add(new GbyVariableExpressionPair((VariableExpr) SqlppRewriteUtil.deepCopy(var),
(Expression) SqlppRewriteUtil.deepCopy(var)));
}
groupbyClause.setDecorPairList(decorList);
}
} else {
selectBlock.getSelectClause().accept(this, arg);
}
return null;
}
private Map<Expression, Identifier> getGroupFieldVariables(GroupbyClause groupbyClause) {
return groupbyClause.hasGroupFieldList()
? SqlppVariableUtil.createFieldVariableMap(groupbyClause.getGroupFieldList()) : Collections.emptyMap();
}
// Applying sugar rewriting for group-by.
private void rewriteExpressionUsingGroupVariable(VariableExpr groupVar, Map<Expression, Identifier> fieldVars,
ILangExpression expr, Set<VariableExpr> outerScopeVariables) throws CompilationException {
Sql92AggregateFunctionVisitor visitor =
new Sql92AggregateFunctionVisitor(context, groupVar, fieldVars, outerScopeVariables);
expr.accept(visitor, null);
}
}
| 50.754717 | 119 | 0.67277 |
0eb33ac1ef0d49748c0cb1b04a1e1e3bcd0f1819 | 1,526 | package com.softicar.platform.common.core.constant.container.field;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Objects;
public class ConstantContainerField<T> implements IConstantContainerField<T> {
private final Class<?> containerClass;
private final Class<T> expectedFieldType;
private final Field field;
public ConstantContainerField(Class<?> containerClass, Class<T> expectedFieldType, Field field) {
this.containerClass = Objects.requireNonNull(containerClass);
this.expectedFieldType = Objects.requireNonNull(expectedFieldType);
this.field = Objects.requireNonNull(field);
}
@Override
public Class<?> getContainerClass() {
return containerClass;
}
@Override
public String getName() {
return field.getName();
}
@Override
public Class<?> getType() {
return field.getType();
}
@Override
public T getValue() {
try {
return expectedFieldType.cast(getFieldValueAsObject());
} catch (IllegalAccessException exception) {
throw new RuntimeException(exception);
}
}
@Override
public boolean isPublic() {
return Modifier.isPublic(field.getModifiers());
}
@Override
public boolean isStatic() {
return Modifier.isStatic(field.getModifiers());
}
@Override
public boolean isFinal() {
return Modifier.isFinal(field.getModifiers());
}
private Object getFieldValueAsObject() throws IllegalAccessException {
field.setAccessible(true);
if (isStatic()) {
return field.get(null);
} else {
return null;
}
}
}
| 20.078947 | 98 | 0.742464 |
e83565a329534feec37de3088722268c6b5eeb0a | 4,528 | /*******************************************************************************
* Copyright 2016 Geoscience Australia
*
* 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 au.gov.ga.earthsci.worldwind.common.render;
import gov.nasa.worldwind.avlist.AVKey;
import gov.nasa.worldwind.geom.Position;
import gov.nasa.worldwind.geom.Vec4;
import gov.nasa.worldwind.layers.Layer;
import gov.nasa.worldwind.pick.PickedObject;
import gov.nasa.worldwind.render.DrawContext;
import gov.nasa.worldwind.render.markers.Marker;
import gov.nasa.worldwind.render.markers.MarkerAttributes;
import gov.nasa.worldwind.render.markers.MarkerRenderer;
import java.util.Iterator;
import javax.media.opengl.GL2;
/**
* {@link MarkerRenderer} that supports picking of subsurface markers.
*
* @author Michael de Hoog
*/
public class DeepPickingMarkerRenderer extends MarkerRenderer
{
private boolean oldDeepPicking;
private boolean drawImmediately;
private MarkerAttributes previousAttributes;
@Override
protected boolean intersectsFrustum(DrawContext dc, Vec4 point, double radius)
{
//use the same test for drawing and picking (see superclass' method)
return dc.getView().getFrustumInModelCoordinates().contains(point);
}
@Override
protected void begin(DrawContext dc)
{
if (dc.isPickingMode())
{
oldDeepPicking = dc.isDeepPickingEnabled();
dc.setDeepPickingEnabled(true);
}
super.begin(dc);
}
@Override
protected void end(DrawContext dc)
{
super.end(dc);
if (dc.isPickingMode())
{
dc.setDeepPickingEnabled(oldDeepPicking);
}
}
public boolean isDrawImmediately()
{
return drawImmediately;
}
public void setDrawImmediately(boolean drawImmediately)
{
this.drawImmediately = drawImmediately;
}
@Override
protected void draw(final DrawContext dc, Iterable<Marker> markers)
{
if (isDrawImmediately())
{
drawImmediately(dc, markers);
}
else
{
super.draw(dc, markers);
}
}
protected void drawImmediately(DrawContext dc, Iterable<Marker> markers)
{
Layer parentLayer = dc.getCurrentLayer();
try
{
begin(dc);
Iterator<Marker> markerIterator = markers.iterator();
for (int index = 0; markerIterator.hasNext(); index++)
{
Marker marker = markerIterator.next();
Position pos = marker.getPosition();
Vec4 point = this.computeSurfacePoint(dc, pos);
double radius = this.computeMarkerRadius(dc, point, marker);
if (!intersectsFrustum(dc, point, radius))
{
continue;
}
drawMarker(dc, index, marker, point, radius);
}
}
finally
{
end(dc);
if (dc.isPickingMode())
{
this.pickSupport.resolvePick(dc, dc.getPickPoint(), parentLayer); // Also clears the pick list.
}
}
}
/*
* Same as superclass' method (copied because private)
*/
private void drawMarker(DrawContext dc, int index, Marker marker, Vec4 point, double radius)
{
// This method is called from OrderedMarker's render and pick methods. We don't perform culling here, because
// the marker has already been culled against the appropriate frustum prior adding OrderedMarker to the draw
// context.
if (dc.isPickingMode())
{
java.awt.Color color = dc.getUniquePickColor();
int colorCode = color.getRGB();
PickedObject po = new PickedObject(colorCode, marker, marker.getPosition(), false);
po.setValue(AVKey.PICKED_OBJECT_ID, index);
if (this.isEnablePickSizeReturn())
{
po.setValue(AVKey.PICKED_OBJECT_SIZE, 2 * radius);
}
this.pickSupport.addPickableObject(po);
GL2 gl = dc.getGL().getGL2(); // GL initialization checks for GL2 compatibility.
gl.glColor3ub((byte) color.getRed(), (byte) color.getGreen(), (byte) color.getBlue());
}
MarkerAttributes attrs = marker.getAttributes();
if (attrs != this.previousAttributes) // equality is intentional to avoid constant equals() calls
{
attrs.apply(dc);
this.previousAttributes = attrs;
}
marker.render(dc, point, radius);
}
}
| 28.477987 | 111 | 0.702959 |
336e77798e5ce6161a4fc7c0a388d6b996fe1c5f | 1,580 | package seedu.address.model.recipe;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static seedu.address.testutil.Assert.assertThrows;
import org.junit.jupiter.api.Test;
public class ProductQuantityTest {
@Test
public void constructor_null_throwsNullPointerException() {
assertThrows(NullPointerException.class, () -> new ProductQuantity(null));
}
@Test
public void constructor_invalidProductQuantity_throwsIllegalArgumentException() {
String invalidQuantity = "-1";
assertThrows(IllegalArgumentException.class, () -> new ProductQuantity(invalidQuantity));
}
/**
* Tests for valid quantity. Only non-negative integers are allowed.
*/
@Test
public void isValidProductQuantity() {
assertTrue(ProductQuantity.isValidQuantity("123"));
assertTrue(ProductQuantity.isValidQuantity("0"));
assertFalse(ProductQuantity.isValidQuantity("1 2"));
assertFalse(ProductQuantity.isValidQuantity("-2"));
assertFalse(ProductQuantity.isValidQuantity("1.2"));
assertFalse(ProductQuantity.isValidQuantity("a"));
}
/**
* Test for equality between quantities.
*/
@Test
public void equals() {
assertEquals(new ProductQuantity("1"), new ProductQuantity("1"));
assertNotEquals(new ProductQuantity("1"), new ProductQuantity("2"));
}
}
| 35.111111 | 97 | 0.718987 |
6a6f354170b931b4f231ffc9115be165dc496d22 | 7,403 | package options;
import java.io.*;
import java.util.Vector;
import javax.microedition.rms.*;
import mts.TransSched;
import ObjModel.Bus;
import ObjModel.BusStop;
import ObjModel.FilterDef;
public class OptionsStoreManager
{
final static int SETTINGS_SLOT_COMMON = 1;
final static int SETTINGS_SLOT_KEYS = 2;
public static void ReadSettings()
{
boolean hasErrors = false;
try
{
RecordStore sett = RecordStore.openRecordStore("settings", true);
try
{
byte[] rec = sett.getRecord(SETTINGS_SLOT_COMMON);
ByteArrayInputStream bais = new ByteArrayInputStream(rec);
DataInputStream dis = new DataInputStream(bais);
Options.defWindowSize = dis.readShort();
Options.defWindowShift = dis.readShort();
Options.defWindowSizeStep = dis.readShort();
Options.defWindowShiftStep = dis.readShort();
// was: startup screen
dis.readByte();
Options.fontSize = dis.readInt();
Options.fontFace = dis.readInt();
Options.fontStyle = dis.readInt();
Options.scrollSize = dis.readInt();
Options.fullScreen = dis.readBoolean();
Options.showExitCommand = dis.readBoolean();
Options.showHelpCommand = dis.readBoolean();
Options.showAboutCommand = dis.readBoolean();
Options.showStopsListOnStartup = dis.readBoolean();
Options.lineSpacing = dis.readByte();
Options.textColor = dis.readInt();
Options.favoritesColor = dis.readInt();
}
catch(InvalidRecordIDException ex)
{
hasErrors = true;
// System.out.println("sett:" + ex.toString());
}
catch(IOException ex)
{
hasErrors = true;
// System.out.println(ex.toString());
}
try
{
byte[] rec = sett.getRecord(SETTINGS_SLOT_KEYS);
ByteArrayInputStream bais = new ByteArrayInputStream(rec);
DataInputStream dis = new DataInputStream(bais);
short keysCount = dis.readShort();
for (int i = 0; i < keysCount; i++)
{
int keyHash = dis.readInt();
int cmdId = dis.readShort();
CmdDef cmd = CmdDef.getCmd(cmdId);
if(cmd != null)
cmd.setKeyHash(keyHash);
}
}
catch(Exception ex)
{
hasErrors = true;
}
sett.closeRecordStore();
}
catch(RecordStoreException ex)
{
// System.out.println(ex.toString());
hasErrors = true;
}
if(hasErrors)
SaveSettings();
}
public static void SaveSettings()
{
try
{
RecordStore sett = RecordStore.openRecordStore("settings", true);
try
{
ByteArrayOutputStream baos = new ByteArrayOutputStream(100);
DataOutputStream dos = new DataOutputStream(baos);
dos.writeShort(Options.defWindowSize);
dos.writeShort(Options.defWindowShift);
dos.writeShort(Options.defWindowSizeStep);
dos.writeShort(Options.defWindowShiftStep);
dos.writeByte(0);
dos.writeInt(Options.fontSize);
dos.writeInt(Options.fontFace);
dos.writeInt(Options.fontStyle);
dos.writeInt(Options.scrollSize);
dos.writeBoolean(Options.fullScreen);
dos.writeBoolean(Options.showExitCommand);
dos.writeBoolean(Options.showHelpCommand);
dos.writeBoolean(Options.showAboutCommand);
dos.writeBoolean(Options.showStopsListOnStartup);
dos.writeByte(Options.lineSpacing);
dos.writeInt(Options.textColor);
dos.writeInt(Options.favoritesColor);
dos.flush();
byte[] rec = baos.toByteArray();
if(sett.getNumRecords() == 0)
sett.addRecord(rec, 0, rec.length);
else
sett.setRecord(SETTINGS_SLOT_COMMON, rec, 0, rec.length);
}
catch(InvalidRecordIDException ex)
{
//System.out.println(ex.toString());
}
// save key settings
try
{
ByteArrayOutputStream baos = new ByteArrayOutputStream(100);
DataOutputStream dos = new DataOutputStream(baos);
CmdDef[] all = CmdDef.getAllCommands();
dos.writeShort(all.length);
for (int i = 0; i < all.length; i++)
{
dos.writeInt(all[i].getKeyHash());
dos.writeShort(all[i].id);
}
dos.flush();
byte[] rec = baos.toByteArray();
if(sett.getNumRecords() == 1)
sett.addRecord(rec, 0, rec.length);
else
sett.setRecord(SETTINGS_SLOT_KEYS, rec, 0, rec.length);
}
catch(InvalidRecordIDException ex)
{
//System.out.println(ex.toString());
}
sett.closeRecordStore();
}
catch(Exception ex)
{
//System.out.println(ex.toString());
}
}
public static FilterDef[] LoadCustomFilterDefinitions()
{
FilterDef[] ret = new FilterDef[0];
try{
RecordStore filters = RecordStore.openRecordStore("filters", true);
Vector v = new Vector(filters.getNumRecords());
for (int i = 0; i < filters.getNumRecords(); i++)
{
try{
int recId = i + 1;
byte[] rec = filters.getRecord(recId);
ByteArrayInputStream bais = new ByteArrayInputStream(rec);
DataInputStream dis = new DataInputStream(bais);
FilterDef fd = readFilterDef(dis);
fd.recordId = recId;
v.addElement(fd);
}
catch(Exception e)
{
}
}
ret = new FilterDef[v.size()];
v.copyInto(ret);
}
catch(RecordStoreNotOpenException e)
{
}
catch(RecordStoreException e)
{
}
return ret;
}
public static FilterDef readFilterDef(DataInput dis) throws IOException
{
FilterDef fd = new FilterDef();
fd.name = dis.readUTF();
int transportCount = dis.readShort();
if(transportCount > 0)
{
fd.transport = new Bus[transportCount];
for (int j = 0; j < transportCount; j++)
{
int id = dis.readShort();
fd.transport[j] = (Bus)TransSched.id2transport.get(new Integer(id));
}
}
int stopsCount = dis.readShort();
if(stopsCount > 0)
{
fd.stops = new BusStop[stopsCount];
for (int j = 0; j < stopsCount; j++)
{
int id = dis.readShort();
fd.stops[j] = (BusStop)TransSched.id2stop.get(new Integer(id));
}
}
return fd;
}
public static void saveCustomFilterDefinitions(FilterDef fd)
{
try{
RecordStore filters = RecordStore.openRecordStore("filters", true);
ByteArrayOutputStream baos = new ByteArrayOutputStream(100);
DataOutputStream dos = new DataOutputStream(baos);
dos.writeUTF(fd.name);
if(fd.transport == null)
{
dos.writeShort(0);
}
else
{
dos.writeShort(fd.transport.length);
for (int i = 0; i < fd.transport.length; i++)
{
dos.writeShort(fd.transport[i].id);
}
}
if(fd.stops == null)
{
dos.writeShort(0);
}
else
{
dos.writeShort(fd.stops.length);
for (int i = 0; i < fd.stops.length; i++)
{
dos.writeShort(fd.stops[i].id);
}
}
dos.flush();
byte[] rec = baos.toByteArray();
if(fd.recordId == -1)
fd.recordId = filters.addRecord(rec, 0, rec.length);
else
filters.setRecord(fd.recordId, rec, 0, rec.length);
}
catch(Exception e)
{
}
}
public static void deleteCustomFilterDefinitions(FilterDef fd)
{
try{
RecordStore filters = RecordStore.openRecordStore("filters", true);
filters.deleteRecord(fd.recordId);
fd.recordId = -1;
}
catch(Exception e)
{
}
}
}
| 22.919505 | 73 | 0.623801 |
14783bd7426e491638ea879071350fad0fb75728 | 773 | /*
* Copyright (C) 2020 Intel Corporation. All rights reserved.
* SPDX-License-Identifier: Apache-2.0
*/
package com.intel.iot.ams.service;
import com.intel.iot.ams.entity.Product;
import com.intel.iot.ams.repository.ProductDao;
import com.intel.iot.ams.repository.hibernate.ProductDaoImpl;
public class ProductService extends BaseService<Integer, Product> {
private ProductDao productDao;
public ProductService() {
productDao = new ProductDaoImpl();
super.setDao(productDao);
}
public Product findByUUID(String uuid) {
return productDao.findByUUID(uuid);
}
public void removeByUUID(String uuid) {
productDao.removeByUUID(uuid);
return;
}
public Product findByName(String name) {
return productDao.findByName(name);
}
}
| 20.891892 | 67 | 0.739974 |
54940979a4552d4bcd42cde18d07d9428e9feaca | 14,730 | /*
*AVISO LEGAL
© Copyright
*Este programa esta protegido por la ley de derechos de autor.
*La reproduccion o distribucion ilicita de este programa o de cualquiera de
*sus partes esta penado por la ley con severas sanciones civiles y penales,
*y seran objeto de todas las sanciones legales que correspondan.
*Su contenido no puede copiarse para fines comerciales o de otras,
*ni puede mostrarse, incluso en una version modificada, en otros sitios Web.
Solo esta permitido colocar hipervinculos al sitio web.
*/
package com.bydan.erp.activosfijos.presentation.web.jsf.sessionbean;
import java.util.Set;
import java.util.HashSet;
import java.util.ArrayList;
import java.util.Date;
import java.io.Serializable;
import com.bydan.framework.erp.util.Constantes;
import com.bydan.erp.activosfijos.business.entity.*;
@SuppressWarnings("unused")
public class SubGrupoActivoFijoSessionBean extends SubGrupoActivoFijoSessionBeanAdditional {
private static final long serialVersionUID = 1L;
protected Boolean isPermiteNavegacionHaciaForeignKeyDesdeSubGrupoActivoFijo;
protected Boolean isPermiteRecargarInformacion;
protected String sNombrePaginaNavegacionHaciaForeignKeyDesdeSubGrupoActivoFijo;
protected Boolean isBusquedaDesdeForeignKeySesionForeignKeySubGrupoActivoFijo;
protected Long lIdSubGrupoActivoFijoActualForeignKey;
protected Long lIdSubGrupoActivoFijoActualForeignKeyParaPosibleAtras;
protected Boolean isBusquedaDesdeForeignKeySesionForeignKeySubGrupoActivoFijoParaPosibleAtras;
protected String sUltimaBusquedaSubGrupoActivoFijo;
protected String sServletGenerarHtmlReporte;
protected Integer iNumeroPaginacion;
protected Integer iNumeroPaginacionPagina;
protected String sPathNavegacionActual="";
protected Boolean isPaginaPopup=false;
protected String sStyleDivArbol="";
protected String sStyleDivContent="";
protected String sStyleDivOpcionesBanner="";
protected String sStyleDivExpandirColapsar="";
protected String sFuncionBusquedaRapida="";
Boolean isBusquedaDesdeForeignKeySesionEmpresa;
Long lidEmpresaActual;
Boolean isBusquedaDesdeForeignKeySesionDetalleGrupoActivoFijo;
Long lidDetalleGrupoActivoFijoActual;
private Long id;
private Long id_empresa;
private Long id_detalle_grupo_activo_fijo;
protected Boolean conGuardarRelaciones=false;
protected Boolean estaModoGuardarRelaciones=false;
protected Boolean esGuardarRelacionado=false;
protected Boolean estaModoBusqueda=false;
protected Boolean noMantenimiento=false;
protected SubGrupoActivoFijoSessionBeanAdditional subgrupoactivofijoSessionBeanAdditional=null;
public SubGrupoActivoFijoSessionBeanAdditional getSubGrupoActivoFijoSessionBeanAdditional() {
return this.subgrupoactivofijoSessionBeanAdditional;
}
public void setSubGrupoActivoFijoSessionBeanAdditional(SubGrupoActivoFijoSessionBeanAdditional subgrupoactivofijoSessionBeanAdditional) {
try {
this.subgrupoactivofijoSessionBeanAdditional=subgrupoactivofijoSessionBeanAdditional;
} catch(Exception e) {
;
}
}
public SubGrupoActivoFijoSessionBean () {
this.inicializarSubGrupoActivoFijoSessionBean();
}
public void inicializarSubGrupoActivoFijoSessionBean () {
this.isPermiteNavegacionHaciaForeignKeyDesdeSubGrupoActivoFijo=false;
this.isPermiteRecargarInformacion=false;
this.sNombrePaginaNavegacionHaciaForeignKeyDesdeSubGrupoActivoFijo="";
this.isBusquedaDesdeForeignKeySesionForeignKeySubGrupoActivoFijo=false;
this.lIdSubGrupoActivoFijoActualForeignKey=0L;
this.lIdSubGrupoActivoFijoActualForeignKeyParaPosibleAtras=0L;
this.isBusquedaDesdeForeignKeySesionForeignKeySubGrupoActivoFijoParaPosibleAtras=false;
this.sUltimaBusquedaSubGrupoActivoFijo ="";
this.sServletGenerarHtmlReporte="";
this.iNumeroPaginacion=10;
this.iNumeroPaginacionPagina=0;
this.sPathNavegacionActual="";
this.sFuncionBusquedaRapida="";
this.sStyleDivArbol="display:table-row;width:20%;height:800px;visibility:visible";
this.sStyleDivContent="height:600px;width:80%";
this.sStyleDivOpcionesBanner="display:table-row";
this.sStyleDivExpandirColapsar="display:table-row";
this.isPaginaPopup=false;
this.estaModoGuardarRelaciones=true;
this.conGuardarRelaciones=false;
this.esGuardarRelacionado=false;
this.estaModoBusqueda=false;
this.noMantenimiento=false;
isBusquedaDesdeForeignKeySesionEmpresa=false;
lidEmpresaActual=0L;
isBusquedaDesdeForeignKeySesionDetalleGrupoActivoFijo=false;
lidDetalleGrupoActivoFijoActual=0L;
this.id_empresa=-1L;
this.id_detalle_grupo_activo_fijo=-1L;
}
public void setPaginaPopupVariables(Boolean isPopupVariables) {
if(isPopupVariables) {
if(!this.isPaginaPopup) {
this.sStyleDivArbol="display:none;width:0px;height:0px;visibility:hidden";
this.sStyleDivContent="height:800px;width:100%";;
this.sStyleDivOpcionesBanner="display:none";
this.sStyleDivExpandirColapsar="display:none";
this.isPaginaPopup=true;
}
} else {
if(this.isPaginaPopup) {
this.sStyleDivArbol="display:table-row;width:15%;height:600px;visibility:visible;overflow:auto;";
this.sStyleDivContent="height:600px;width:80%";
this.sStyleDivOpcionesBanner="display:table-row";
this.sStyleDivExpandirColapsar="display:table-row";
this.isPaginaPopup=false;
}
}
}
public Boolean getisPermiteNavegacionHaciaForeignKeyDesdeSubGrupoActivoFijo() {
return this.isPermiteNavegacionHaciaForeignKeyDesdeSubGrupoActivoFijo;
}
public void setisPermiteNavegacionHaciaForeignKeyDesdeSubGrupoActivoFijo(
Boolean isPermiteNavegacionHaciaForeignKeyDesdeSubGrupoActivoFijo) {
this.isPermiteNavegacionHaciaForeignKeyDesdeSubGrupoActivoFijo= isPermiteNavegacionHaciaForeignKeyDesdeSubGrupoActivoFijo;
}
public Boolean getisPermiteRecargarInformacion() {
return this.isPermiteRecargarInformacion;
}
public void setisPermiteRecargarInformacion(
Boolean isPermiteRecargarInformacion) {
this.isPermiteRecargarInformacion=isPermiteRecargarInformacion;
}
public String getsNombrePaginaNavegacionHaciaForeignKeyDesdeSubGrupoActivoFijo() {
return this.sNombrePaginaNavegacionHaciaForeignKeyDesdeSubGrupoActivoFijo;
}
public void setsNombrePaginaNavegacionHaciaForeignKeyDesdeSubGrupoActivoFijo(String sNombrePaginaNavegacionHaciaForeignKeyDesdeSubGrupoActivoFijo) {
this.sNombrePaginaNavegacionHaciaForeignKeyDesdeSubGrupoActivoFijo = sNombrePaginaNavegacionHaciaForeignKeyDesdeSubGrupoActivoFijo;
}
public Boolean getisBusquedaDesdeForeignKeySesionForeignKeySubGrupoActivoFijo() {
return isBusquedaDesdeForeignKeySesionForeignKeySubGrupoActivoFijo;
}
public void setisBusquedaDesdeForeignKeySesionForeignKeySubGrupoActivoFijo(
Boolean isBusquedaDesdeForeignKeySesionForeignKeySubGrupoActivoFijo) {
this.isBusquedaDesdeForeignKeySesionForeignKeySubGrupoActivoFijo= isBusquedaDesdeForeignKeySesionForeignKeySubGrupoActivoFijo;
}
public Long getlIdSubGrupoActivoFijoActualForeignKey() {
return lIdSubGrupoActivoFijoActualForeignKey;
}
public void setlIdSubGrupoActivoFijoActualForeignKey(
Long lIdSubGrupoActivoFijoActualForeignKey) {
this.lIdSubGrupoActivoFijoActualForeignKey = lIdSubGrupoActivoFijoActualForeignKey;
}
public Long getlIdSubGrupoActivoFijoActualForeignKeyParaPosibleAtras() {
return lIdSubGrupoActivoFijoActualForeignKeyParaPosibleAtras;
}
public void setlIdSubGrupoActivoFijoActualForeignKeyParaPosibleAtras(
Long lIdSubGrupoActivoFijoActualForeignKeyParaPosibleAtras) {
this.lIdSubGrupoActivoFijoActualForeignKeyParaPosibleAtras = lIdSubGrupoActivoFijoActualForeignKeyParaPosibleAtras;
}
public Boolean getisBusquedaDesdeForeignKeySesionForeignKeySubGrupoActivoFijoParaPosibleAtras() {
return isBusquedaDesdeForeignKeySesionForeignKeySubGrupoActivoFijoParaPosibleAtras;
}
public void setisBusquedaDesdeForeignKeySesionForeignKeySubGrupoActivoFijoParaPosibleAtras(
Boolean isBusquedaDesdeForeignKeySesionForeignKeySubGrupoActivoFijoParaPosibleAtras) {
this.isBusquedaDesdeForeignKeySesionForeignKeySubGrupoActivoFijoParaPosibleAtras = isBusquedaDesdeForeignKeySesionForeignKeySubGrupoActivoFijoParaPosibleAtras;
}
public String getsUltimaBusquedaSubGrupoActivoFijo() {
return sUltimaBusquedaSubGrupoActivoFijo;
}
public void setsUltimaBusquedaSubGrupoActivoFijo(String sUltimaBusquedaSubGrupoActivoFijo) {
this.sUltimaBusquedaSubGrupoActivoFijo = sUltimaBusquedaSubGrupoActivoFijo;
}
public String getsServletGenerarHtmlReporte() {
return sServletGenerarHtmlReporte;
}
public void setsServletGenerarHtmlReporte(String sServletGenerarHtmlReporte) {
this.sServletGenerarHtmlReporte = sServletGenerarHtmlReporte;
}
public Integer getiNumeroPaginacion() {
return iNumeroPaginacion;
}
public void setiNumeroPaginacion(Integer iNumeroPaginacion) {
this.iNumeroPaginacion= iNumeroPaginacion;
}
public Integer getiNumeroPaginacionPagina() {
return iNumeroPaginacionPagina;
}
public void setiNumeroPaginacionPagina(Integer iNumeroPaginacionPagina) {
this.iNumeroPaginacionPagina= iNumeroPaginacionPagina;
}
public String getsPathNavegacionActual() {
return this.sPathNavegacionActual;
}
public void setsPathNavegacionActual(String sPathNavegacionActual) {
this.sPathNavegacionActual = sPathNavegacionActual;
}
public Boolean getisPaginaPopup() {
return this.isPaginaPopup;
}
public void setisPaginaPopup(Boolean isPaginaPopup) {
this.isPaginaPopup = isPaginaPopup;
}
public String getsStyleDivArbol() {
return this.sStyleDivArbol;
}
public void setsStyleDivArbol(String sStyleDivArbol) {
this.sStyleDivArbol = sStyleDivArbol;
}
public String getsStyleDivContent() {
return this.sStyleDivContent;
}
public void setsStyleDivContent(String sStyleDivContent) {
this.sStyleDivContent = sStyleDivContent;
}
public String getsStyleDivOpcionesBanner() {
return this.sStyleDivOpcionesBanner;
}
public void setsStyleDivOpcionesBanner(String sStyleDivOpcionesBanner) {
this.sStyleDivOpcionesBanner = sStyleDivOpcionesBanner;
}
public String getsStyleDivExpandirColapsar() {
return this.sStyleDivExpandirColapsar;
}
public void setsStyleDivExpandirColapsar(String sStyleDivExpandirColapsar) {
this.sStyleDivExpandirColapsar = sStyleDivExpandirColapsar;
}
public String getsFuncionBusquedaRapida() {
return this.sFuncionBusquedaRapida;
}
public void setsFuncionBusquedaRapida(String sFuncionBusquedaRapida) {
this.sFuncionBusquedaRapida = sFuncionBusquedaRapida;
}
public Boolean getConGuardarRelaciones() {
return this.conGuardarRelaciones;
}
public void setConGuardarRelaciones(Boolean conGuardarRelaciones) {
this.conGuardarRelaciones = conGuardarRelaciones;
}
public Boolean getEstaModoGuardarRelaciones() {
return this.estaModoGuardarRelaciones;
}
public void setEstaModoGuardarRelaciones(Boolean estaModoGuardarRelaciones) {
this.estaModoGuardarRelaciones = estaModoGuardarRelaciones;
}
public Boolean getEsGuardarRelacionado() {
return this.esGuardarRelacionado;
}
public void setEsGuardarRelacionado(Boolean esGuardarRelacionado) {
this.esGuardarRelacionado = esGuardarRelacionado;
}
public Boolean getEstaModoBusqueda() {
return this.estaModoBusqueda;
}
public void setEstaModoBusqueda(Boolean estaModoBusqueda) {
this.estaModoBusqueda = estaModoBusqueda;
}
public Boolean getNoMantenimiento() {
return this.noMantenimiento;
}
public void setNoMantenimiento(Boolean noMantenimiento) {
this.noMantenimiento = noMantenimiento;
}
public Long getid() {
return this.id;
}
public Long getid_empresa() {
return this.id_empresa;
}
public Long getid_detalle_grupo_activo_fijo() {
return this.id_detalle_grupo_activo_fijo;
}
public void setid(Long newid)throws Exception
{
try {
if(this.id!=newid) {
if(newid==null) {
//newid=0L;
if(Constantes.ISDEVELOPING) {
System.out.println("SubGrupoActivoFijo:Valor nulo no permitido en columna id");
}
}
this.id=newid;
}
} catch(Exception e) {
throw e;
}
}
public void setid_empresa(Long newid_empresa)throws Exception
{
try {
if(this.id_empresa!=newid_empresa) {
if(newid_empresa==null) {
//newid_empresa=-1L;
if(Constantes.ISDEVELOPING) {
System.out.println("SubGrupoActivoFijo:Valor nulo no permitido en columna id_empresa");
}
}
this.id_empresa=newid_empresa;
}
} catch(Exception e) {
throw e;
}
}
public void setid_detalle_grupo_activo_fijo(Long newid_detalle_grupo_activo_fijo)throws Exception
{
try {
if(this.id_detalle_grupo_activo_fijo!=newid_detalle_grupo_activo_fijo) {
if(newid_detalle_grupo_activo_fijo==null) {
//newid_detalle_grupo_activo_fijo=-1L;
if(Constantes.ISDEVELOPING) {
System.out.println("SubGrupoActivoFijo:Valor nulo no permitido en columna id_detalle_grupo_activo_fijo");
}
}
this.id_detalle_grupo_activo_fijo=newid_detalle_grupo_activo_fijo;
}
} catch(Exception e) {
throw e;
}
}
public Boolean getisBusquedaDesdeForeignKeySesionEmpresa() {
return isBusquedaDesdeForeignKeySesionEmpresa;
}
public void setisBusquedaDesdeForeignKeySesionEmpresa(
Boolean isBusquedaDesdeForeignKeySesionEmpresa) {
this.isBusquedaDesdeForeignKeySesionEmpresa = isBusquedaDesdeForeignKeySesionEmpresa;
}
public Long getlidEmpresaActual() {
return lidEmpresaActual;
}
public void setlidEmpresaActual(Long lidEmpresaActual) {
this.lidEmpresaActual = lidEmpresaActual;
}
public Boolean getisBusquedaDesdeForeignKeySesionDetalleGrupoActivoFijo() {
return isBusquedaDesdeForeignKeySesionDetalleGrupoActivoFijo;
}
public void setisBusquedaDesdeForeignKeySesionDetalleGrupoActivoFijo(
Boolean isBusquedaDesdeForeignKeySesionDetalleGrupoActivoFijo) {
this.isBusquedaDesdeForeignKeySesionDetalleGrupoActivoFijo = isBusquedaDesdeForeignKeySesionDetalleGrupoActivoFijo;
}
public Long getlidDetalleGrupoActivoFijoActual() {
return lidDetalleGrupoActivoFijoActual;
}
public void setlidDetalleGrupoActivoFijoActual(Long lidDetalleGrupoActivoFijoActual) {
this.lidDetalleGrupoActivoFijoActual = lidDetalleGrupoActivoFijoActual;
}
}
| 32.231947 | 162 | 0.794976 |
3ee0102c453f28a73474f35b11c468132f8a7201 | 19,010 | /*
* Copyright 2015 Jeff Hain
*
* 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 net.jadecy.graph;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.TreeSet;
import junit.framework.TestCase;
import net.jadecy.graph.GraphTestsUtilz.CycleGraphGenerator;
import net.jadecy.graph.GraphTestsUtilz.DisconnectedGraphGenerator;
import net.jadecy.graph.GraphTestsUtilz.InterfaceGraphGenerator;
import net.jadecy.graph.GraphTestsUtilz.RakeCycleGraphGenerator;
import net.jadecy.graph.GraphTestsUtilz.RandomGraphGenerator;
import net.jadecy.graph.GraphTestsUtilz.Vertex;
public class OneShortestPathComputerTest extends TestCase {
//--------------------------------------------------------------------------
// CONFIGURATION
//--------------------------------------------------------------------------
private static final boolean DEBUG = false;
private static final boolean USE_RANDOM_SEED = false;
private static final long SEED = USE_RANDOM_SEED ? new Random().nextLong() : 123456789L;
static {
if (USE_RANDOM_SEED) {
System.out.println("SEED = " + SEED);
}
}
//--------------------------------------------------------------------------
// PRIVATE CLASSES
//--------------------------------------------------------------------------
private static class MyVertexCollProcessor implements InterfaceVertexCollProcessor {
static final Integer BEGIN = 1;
static final Integer PROCESS = 2;
static final Integer END = 3;
final ArrayList<InterfaceVertex> list = new ArrayList<InterfaceVertex>();
final TreeSet<InterfaceVertex> set = new TreeSet<InterfaceVertex>();
final ArrayList<Integer> callList = new ArrayList<Integer>();
public MyVertexCollProcessor() {
}
@Override
public String toString() {
return "[\nlist = " + this.list + ",\nset = " + this.set + ",\ncallList = " + this.callList + "]";
}
@Override
public void processCollBegin() {
assertTrue((this.callList.size() == 0) || (this.getLastCall() == END));
this.callList.add(BEGIN);
}
@Override
public void processCollVertex(InterfaceVertex vertex) {
assertTrue((this.getLastCall() == BEGIN) || (this.getLastCall() == PROCESS));
this.callList.add(PROCESS);
{
this.list.add(vertex);
}
{
// Checking that vertex is always different from others.
final boolean didAdd = this.set.add(vertex);
if (!didAdd) {
if (DEBUG) {
System.out.println("duplicate " + vertex + " in " + this.list);
}
}
assertTrue(didAdd);
}
}
@Override
public boolean processCollEnd() {
assertTrue(this.getLastCall() == PROCESS);
this.callList.add(END);
// Returned boolean must have no effect since there is
// at most one call.
return (this.list.size() & 1) != 0;
}
Integer getFirstCall() {
return this.callList.get(0);
}
Integer getLastCall() {
return this.callList.get(this.callList.size()-1);
}
}
//--------------------------------------------------------------------------
// PUBLIC METHODS
//--------------------------------------------------------------------------
/*
* Special cases.
*/
public void test_computeOneShortestPath_exceptions() {
final Set<InterfaceVertex> beginVertexSet = GraphTestsUtilz.asHashSet();
final Set<InterfaceVertex> endVertexSet = GraphTestsUtilz.asHashSet();
final MyVertexCollProcessor processor = new MyVertexCollProcessor();
try {
OneShortestPathComputer.computeOneShortestPath(
null,
endVertexSet,
processor);
assertTrue(false);
} catch (NullPointerException e) {
// ok
}
try {
OneShortestPathComputer.computeOneShortestPath(
beginVertexSet,
null,
processor);
assertTrue(false);
} catch (NullPointerException e) {
// ok
}
try {
OneShortestPathComputer.computeOneShortestPath(
beginVertexSet,
endVertexSet,
null);
assertTrue(false);
} catch (NullPointerException e) {
// ok
}
}
public void test_computeOneShortestPath_noPath() {
final Vertex v1 = new Vertex(1);
final Vertex v2 = new Vertex(2);
GraphTestsUtilz.ensurePath(v1, v2);
for (boolean emptyBegin : new boolean[]{false,true}) {
for (boolean emptyEnd : new boolean[]{false,true}) {
final Set<InterfaceVertex> beginVertexSet = emptyBegin ? GraphTestsUtilz.asHashSet() : GraphTestsUtilz.asHashSet(v2);
final Set<InterfaceVertex> endVertexSet = emptyEnd ? GraphTestsUtilz.asHashSet() : GraphTestsUtilz.asHashSet(v1);
if (DEBUG) {
System.out.println("beginVertexSet = " + beginVertexSet);
System.out.println("endVertexSet = " + endVertexSet);
}
final MyVertexCollProcessor processor = new MyVertexCollProcessor();
OneShortestPathComputer.computeOneShortestPath(
beginVertexSet,
endVertexSet,
processor);
if (DEBUG) {
System.out.println("processor = " + processor);
}
assertEquals(0, processor.callList.size());
}
}
}
public void test_computeOneShortestPath_beginAndBeginOverlap() {
final int size = 3;
final DisconnectedGraphGenerator gg = new DisconnectedGraphGenerator(
SEED,
size);
final List<InterfaceVertex> graph = gg.newGraph();
GraphTestsUtilz.ensurePathFromIndexes(graph, 0, 1);
GraphTestsUtilz.ensurePathFromIndexes(graph, 1, 0);
GraphTestsUtilz.ensurePathFromIndexes(graph, 0, 2);
GraphTestsUtilz.ensurePathFromIndexes(graph, 2, 0);
final Set<InterfaceVertex> beginVertexSet = GraphTestsUtilz.asSetFromIndexes(graph, 0, 1);
final Set<InterfaceVertex> endVertexSet = GraphTestsUtilz.asSetFromIndexes(graph, 0, 2);
final MyVertexCollProcessor processor = new MyVertexCollProcessor();
OneShortestPathComputer.computeOneShortestPath(
beginVertexSet,
endVertexSet,
processor);
if (DEBUG) {
System.out.println("processor = " + processor);
}
final ArrayList<InterfaceVertex> actualList = processor.list;
final List<InterfaceVertex> expectedList = GraphTestsUtilz.asListFromIndexes(graph, 0);
assertEquals(expectedList.size() + 2, processor.callList.size());
assertEquals(MyVertexCollProcessor.BEGIN, processor.getFirstCall());
assertEquals(MyVertexCollProcessor.END, processor.getLastCall());
assertEquals(expectedList, actualList);
}
/*
* General.
*/
public void test_computeOneShortestPath_general() {
/*
* Graph (k = vertex of index k, whatever its id).
* 0 <-> 2 --> 4 --> 6
* ^ ^
* \ /
* \ /
* \ /
* \ v
* 1 --> 3 --> 5 --> 7
*
* Computing path from 3 to 6.
*/
final DisconnectedGraphGenerator gg = new DisconnectedGraphGenerator(SEED, 8);
final List<InterfaceVertex> graph = gg.newGraph();
GraphTestsUtilz.ensurePathFromIndexes(graph, 0, 2, 4, 6);
GraphTestsUtilz.ensurePathFromIndexes(graph, 1, 3, 5, 7);
GraphTestsUtilz.ensurePathFromIndexes(graph, 2, 0);
GraphTestsUtilz.ensurePathFromIndexes(graph, 5, 2);
GraphTestsUtilz.ensurePathFromIndexes(graph, 5, 6);
GraphTestsUtilz.ensurePathFromIndexes(graph, 6, 5);
final Set<InterfaceVertex> beginVertexSet = GraphTestsUtilz.asHashSet(graph.get(3));
final Set<InterfaceVertex> endVertexSet = GraphTestsUtilz.asHashSet(graph.get(6));
final MyVertexCollProcessor processor = new MyVertexCollProcessor();
OneShortestPathComputer.computeOneShortestPath(
beginVertexSet,
endVertexSet,
processor);
if (DEBUG) {
System.out.println("processor = " + processor);
}
final ArrayList<InterfaceVertex> actualList = processor.list;
final List<InterfaceVertex> expectedList = GraphTestsUtilz.asListFromIndexes(graph, 3, 5, 6);
assertEquals(expectedList.size() + 2, processor.callList.size());
assertEquals(MyVertexCollProcessor.BEGIN, processor.getFirstCall());
assertEquals(MyVertexCollProcessor.END, processor.getLastCall());
assertEquals(expectedList, actualList);
}
/*
* Sturdiness.
*/
public void test_computeOneShortestPath_sturdiness() {
final Random random = new Random(SEED);
for (int i = 0; i < 10*1000; i++) {
final int maxSize = 9;
final RandomGraphGenerator gg = new RandomGraphGenerator(
random.nextLong(),
maxSize);
this.test_computeOneShortestPath_againstNaive(
random,
gg);
}
}
public void test_computeOneShortestPath_noStackOverflowError() {
final Random random = new Random(SEED);
final int size = GraphTestsUtilz.LARGER_THAN_CALL_STACK;
for (int k = 0; k < 2; k++) {
if (DEBUG) {
System.out.println("k = " + k);
}
final InterfaceGraphGenerator gg;
if (k == 0) {
gg = new CycleGraphGenerator(
random.nextLong(),
size);
} else {
gg = new RakeCycleGraphGenerator(
random.nextLong(),
size);
}
final List<InterfaceVertex> graph = gg.newGraph();
final InterfaceVertex beginVertex = graph.get(0);
final InterfaceVertex endVertex = graph.get(size-1);
final Set<InterfaceVertex> beginVertexSet = GraphTestsUtilz.asHashSet(beginVertex);
final Set<InterfaceVertex> endVertexSet = GraphTestsUtilz.asHashSet(endVertex);
final MyVertexCollProcessor processor = new MyVertexCollProcessor();
OneShortestPathComputer.computeOneShortestPath(
beginVertexSet,
endVertexSet,
processor);
if (k == 0) {
assertEquals(size + 2, processor.callList.size());
} else {
assertEquals(2 + 2, processor.callList.size());
}
assertEquals(MyVertexCollProcessor.BEGIN, processor.getFirstCall());
assertEquals(MyVertexCollProcessor.END, processor.getLastCall());
}
}
/*
* Determinism.
*/
/**
* Checks that vertices hash codes have no effect on the result,
* i.e. that ordered sets or maps are used where needed.
*/
public void test_computeOneShortestPath_determinism() {
final Random seedGenerator = new Random(SEED);
for (int k = 0; k < 100; k++) {
List<InterfaceVertex> firstResult = null;
final long currentSeed = seedGenerator.nextLong();
for (int i = 0; i < 10; i++) {
// In this loop, always generating the same graph,
// but with (typically) different hash codes for vertices.
final Random random = new Random(currentSeed);
final int maxSize = 1 + random.nextInt(5);
final RandomGraphGenerator gg = new RandomGraphGenerator(
random.nextLong(),
maxSize);
final List<InterfaceVertex> graph = gg.newGraph();
final HashSet<InterfaceVertex> beginVertexSet = new HashSet<InterfaceVertex>();
final HashSet<InterfaceVertex> endVertexSet = new HashSet<InterfaceVertex>();
for (InterfaceVertex v : graph) {
if (random.nextDouble() < 0.1) {
beginVertexSet.add(v);
endVertexSet.add(v);
} else if (random.nextDouble() < 0.4) {
beginVertexSet.add(v);
} else if (random.nextDouble() < 0.6) {
endVertexSet.add(v);
}
}
final MyVertexCollProcessor processor = new MyVertexCollProcessor();
OneShortestPathComputer.computeOneShortestPath(
beginVertexSet,
endVertexSet,
processor);
final List<InterfaceVertex> result = processor.list;
if (firstResult == null) {
firstResult = result;
if (DEBUG) {
System.out.println("firstResult = " + firstResult);
}
} else {
// Can't compare instances because vertices are from different graphs.
assertEquals(firstResult.toString(), result.toString());
}
}
}
}
//--------------------------------------------------------------------------
// PRIVATE METHODS
//--------------------------------------------------------------------------
private void test_computeOneShortestPath_againstNaive(
Random random,
InterfaceGraphGenerator gg) {
final List<InterfaceVertex> graph = gg.newGraph();
if (DEBUG) {
GraphTestsUtilz.printGraph(graph);
}
final Set<InterfaceVertex> beginVertexSet;
if ((graph.size() == 0) || (random.nextDouble() < 0.1)) {
beginVertexSet = GraphTestsUtilz.asHashSet();
} else {
final InterfaceVertex beginVertex1 = graph.get(0);
final InterfaceVertex beginVertex2 = graph.get(graph.size()/8);
beginVertexSet = GraphTestsUtilz.asHashSet(beginVertex1, beginVertex2);
}
final Set<InterfaceVertex> endVertexSet;
if ((graph.size() == 0) || (random.nextDouble() < 0.1)) {
endVertexSet = GraphTestsUtilz.asHashSet();
} else {
final InterfaceVertex beginVertex3 = graph.get(graph.size()/4);
final InterfaceVertex beginVertex4 = graph.get(graph.size()/2);
endVertexSet = GraphTestsUtilz.asHashSet(beginVertex3, beginVertex4);
}
final int beginVertexSetHC = beginVertexSet.hashCode();
final int endVertexSetHC = endVertexSet.hashCode();
if (DEBUG) {
System.out.println("beginVertexSet = " + beginVertexSet);
System.out.println("endVertexSet = " + endVertexSet);
}
if (DEBUG) {
System.out.println("NaiveOneShortestPathComputer.computeOneShortestPath(...)...");
}
final int expectedShortestPathLength;
{
final MyVertexCollProcessor processor = new MyVertexCollProcessor();
NaiveOneShortestPathComputer.computeOneShortestPath(
beginVertexSet,
endVertexSet,
processor);
// Inputs not modified.
assertEquals(beginVertexSetHC, beginVertexSet.hashCode());
assertEquals(endVertexSetHC, endVertexSet.hashCode());
if (processor.callList.size() != 0) {
assertEquals(MyVertexCollProcessor.BEGIN, processor.getFirstCall());
assertEquals(MyVertexCollProcessor.END, processor.getLastCall());
}
// Length = number of edges = number of vertices - 1.
// If -1 means no shortest path.
expectedShortestPathLength = processor.list.size() - 1;
if (DEBUG) {
System.out.println("possible shortest path = " + processor.list);
System.out.println("expected shortest path length = " + expectedShortestPathLength);
}
GraphTestsUtilz.checkPathExists(processor.list);
}
if (DEBUG) {
System.out.println("OneShortestPathComputer.computeOneShortestPath((...)...");
}
final int actualShortestPathLength;
{
final MyVertexCollProcessor processor = new MyVertexCollProcessor();
OneShortestPathComputer.computeOneShortestPath(
beginVertexSet,
endVertexSet,
processor);
// Inputs not modified.
assertEquals(beginVertexSetHC, beginVertexSet.hashCode());
assertEquals(endVertexSetHC, endVertexSet.hashCode());
if (processor.callList.size() != 0) {
assertEquals(MyVertexCollProcessor.BEGIN, processor.getFirstCall());
assertEquals(MyVertexCollProcessor.END, processor.getLastCall());
}
actualShortestPathLength = processor.list.size() - 1;
if (DEBUG) {
System.out.println("actual shortest path = " + processor.list);
System.out.println("actual shortest path length = " + actualShortestPathLength);
}
GraphTestsUtilz.checkPathExists(processor.list);
}
assertEquals(expectedShortestPathLength, actualShortestPathLength);
}
}
| 37.495069 | 133 | 0.550552 |
467eecabedf231ed167344981b433542a878c183 | 837 | package com.hartwig.pipeline.alignment.bwa;
import java.util.List;
import com.google.common.collect.Lists;
import com.hartwig.pipeline.execution.vm.Bash;
import com.hartwig.pipeline.execution.vm.SambambaCommand;
import org.jetbrains.annotations.NotNull;
class SambambaMarkdupCommand extends SambambaCommand {
SambambaMarkdupCommand(final List<String> inputBamPaths, final String outputBamPath) {
super(arguments(inputBamPaths, outputBamPath));
}
@NotNull
private static String[] arguments(final List<String> inputBamPaths, final String outputBamPath) {
List<String> arguments = Lists.newArrayList("markdup", "-t", Bash.allCpus(), "--overflow-list-size=45000000");
arguments.addAll(inputBamPaths);
arguments.add(outputBamPath);
return arguments.toArray(new String[0]);
}
} | 34.875 | 118 | 0.749104 |
6bb750d3cdd34b8cbeadde3de1c51569ce053eda | 3,171 | package com.jxd.archiveapp;
import android.app.Activity;
import android.content.Intent;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import com.avast.android.dialogs.fragment.ProgressDialogFragment;
import com.jxd.archiveapp.bean.CloseEvent;
import com.jxd.archiveapp.utils.NetworkUtil;
import java.io.Serializable;
public class BaseActivity extends AppCompatActivity {
protected static final String NULL_NETWORK = "无网络或当前网络不可用!";
ProgressDialogFragment _progressDialog=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void showActivity(Activity aty, Class clazz){
Intent i = new Intent(aty, clazz);
aty.startActivity(i);
}
public void showActivity(Activity aty , Class clazz , String key , Serializable serialize ){
Intent i = new Intent(aty, clazz);
i.putExtra(key, serialize);
aty.startActivity(i);
}
public void skipActivity(Activity aty, Class clazz){
Intent i = new Intent(aty, clazz);
aty.startActivity(i);
aty.finish();
}
public void skipActivity(Activity aty , Intent intent){
aty.startActivity(intent);
aty.finish();
}
public void skipActivity( Activity aty , Class clazz , String key , Serializable serialize ){
Intent i = new Intent(aty , clazz);
i.putExtra(key, serialize);
aty.startActivity(i);
aty.finish();
}
public void showActivity(Activity aty, Intent i){
aty.startActivity(i);
}
/**
*
* @return
*/
protected boolean canConnect(){
//网络访问前先检测网络是否可用
if(!NetworkUtil.isConnect(BaseActivity.this)){
Snackbar.make( this.getWindow().getDecorView() , NULL_NETWORK , Snackbar.LENGTH_LONG).setAction("Action", null).show();
//ToastUtils.showLongToast(this, NULL_NETWORK);
return false;
}
return true;
}
/**
* 关闭 事件
* @param event
*/
public void onEventMainThread( CloseEvent event) {
this.finish();
}
protected boolean showProgressDialog( String title , String message ){
if( BaseActivity.this.isFinishing() ) return true;
//网络访问前先检测网络是否可用
if(canConnect()==false){
return false;
}
if( _progressDialog !=null ) {
_progressDialog.dismiss();
_progressDialog=null;
}
ProgressDialogFragment.ProgressDialogBuilder builder = ProgressDialogFragment.createBuilder(this, getSupportFragmentManager())
.setTitle(title)
.setMessage( message )
//.setCancelable(false)
.setCancelableOnTouchOutside(false);
_progressDialog = (ProgressDialogFragment) builder.show();
return true;
}
protected void closeProgressDialog(){
if( BaseActivity.this.isFinishing() )return;
if(_progressDialog!=null){
_progressDialog.dismiss();
_progressDialog=null;
}
}
}
| 29.091743 | 134 | 0.6386 |
baa3a036ab7efe9c53d5d9d6f941a07d6b407152 | 1,011 | package com.example.rh.ec.main.personal.order;
import android.view.View;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.SimpleClickListener;
import com.example.rh.core.fragment.BaseAppFragment;
/**
* @author RH
* @date 2018/11/12
*/
public class OrderListClickListener extends SimpleClickListener {
private final BaseAppFragment fragment;
public OrderListClickListener(BaseAppFragment fragment) {
this.fragment = fragment;
}
@Override
public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
fragment.getSupportDelegate().start(new OrderCommentFragment());
}
@Override
public void onItemLongClick(BaseQuickAdapter adapter, View view, int position) {
}
@Override
public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
}
@Override
public void onItemChildLongClick(BaseQuickAdapter adapter, View view, int position) {
}
}
| 24.658537 | 89 | 0.74184 |
96ce1ca320d063713083be949b08101779f4f948 | 4,795 | /*
* Copyright 2016 Crown Copyright
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.gov.gchq.gaffer.graphql.definitions;
import graphql.schema.GraphQLInterfaceType;
import graphql.schema.GraphQLObjectType;
import org.apache.log4j.Logger;
import uk.gov.gchq.gaffer.data.element.Element;
import uk.gov.gchq.gaffer.graphql.GrafferQLException;
import uk.gov.gchq.gaffer.store.schema.Schema;
import uk.gov.gchq.gaffer.store.schema.SchemaElementDefinition;
import uk.gov.gchq.gaffer.store.schema.TypeDefinition;
import java.util.Map;
import static graphql.schema.GraphQLFieldDefinition.newFieldDefinition;
import static graphql.schema.GraphQLObjectType.newObject;
/**
* General form of a GraphQL type builder based on a Gaffer Element definitions.
*/
public abstract class ElementTypeGQLBuilder<
E extends Element,
S extends SchemaElementDefinition,
B extends ElementTypeGQLBuilder<E, S, B>> {
private static final Logger LOGGER = Logger.getLogger(ElementTypeGQLBuilder.class);
protected abstract GraphQLInterfaceType getInterfaceType();
protected abstract void contribute(final GraphQLObjectType.Builder builder);
protected abstract void addToQuery(final GraphQLObjectType type,
final GraphQLObjectType.Builder queryTypeBuilder);
public abstract B self();
private Map<String, GraphQLObjectType> dataObjectTypes;
private String name;
private S elementDefinition;
private Schema schema;
private GraphQLObjectType.Builder queryTypeBuilder;
public B dataObjectTypes(final Map<String, GraphQLObjectType> dataObjectTypes) {
this.dataObjectTypes = dataObjectTypes;
return self();
}
public B name(final String name) {
this.name = name;
return self();
}
public B elementDefinition(final S elementDefinition) {
this.elementDefinition = elementDefinition;
return self();
}
public B schema(final Schema schema) {
this.schema = schema;
return self();
}
public B queryTypeBuilder(final GraphQLObjectType.Builder queryTypeBuilder) {
this.queryTypeBuilder = queryTypeBuilder;
return self();
}
protected Map<String, GraphQLObjectType> getDataObjectTypes() {
return dataObjectTypes;
}
protected String getName() {
return name;
}
protected S getElementDefinition() {
return elementDefinition;
}
protected Schema getSchema() {
return schema;
}
public GraphQLObjectType build() throws GrafferQLException {
if (null == this.dataObjectTypes) {
throw new GrafferQLException("dataObjectTypes given to data type builder is null");
}
if (null == this.name) {
throw new GrafferQLException("name given to data type builder is null");
}
if (null == this.schema) {
throw new GrafferQLException("schema given to data type builder is null");
}
if (null == this.elementDefinition) {
throw new GrafferQLException("elementDefinition given to data type builder is null");
}
if (null == this.queryTypeBuilder) {
throw new GrafferQLException("queryTypeBuilder given to data type builder is null");
}
// Create a builder
final GraphQLObjectType.Builder builder = newObject()
.name(name)
.withInterface(getInterfaceType());
for (final String propName : elementDefinition.getProperties()) {
final String propTypeName = elementDefinition.getPropertyTypeName(propName);
GraphQLObjectType propObjectType = dataObjectTypes.get(propTypeName);
final TypeDefinition prop = elementDefinition.getPropertyTypeDef(propName);
LOGGER.debug("Property " + propName + " - " + propTypeName + " - " + prop);
builder
.field(newFieldDefinition()
.name(propName)
.type(propObjectType)
.build());
}
contribute(builder);
final GraphQLObjectType type = builder.build();
addToQuery(type, queryTypeBuilder);
return type;
}
}
| 35.518519 | 97 | 0.676538 |
729a189ac2d007408b247dc13aa3296077f42605 | 6,296 | /*
* Asset Share Commons
*
* Copyright (C) 2019 Adobe
*
* 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.adobe.aem.commons.assetshare.content.renditions.impl;
import com.adobe.aem.commons.assetshare.content.AssetModel;
import com.adobe.aem.commons.assetshare.content.AssetResolver;
import com.adobe.aem.commons.assetshare.content.impl.AssetModelImpl;
import com.adobe.aem.commons.assetshare.content.properties.ComputedProperties;
import com.adobe.aem.commons.assetshare.content.properties.impl.ComputedPropertiesImpl;
import com.adobe.aem.commons.assetshare.content.renditions.AssetRenditionParameters;
import com.adobe.aem.commons.assetshare.content.renditions.AssetRenditions;
import com.adobe.aem.commons.assetshare.util.ExpressionEvaluator;
import com.adobe.aem.commons.assetshare.util.impl.ExpressionEvaluatorImpl;
import com.day.cq.dam.commons.util.DamUtil;
import io.wcm.testing.mock.aem.junit.AemContext;
import org.apache.sling.commons.mime.MimeTypeService;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.util.HashMap;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
@RunWith(MockitoJUnitRunner.class)
public class AssetRenditionsImplTest {
@Rule
public AemContext ctx = new AemContext();
@Mock
private MimeTypeService mimeTypeService;
private AssetModel testAssetModel;
@Before
public void setUp() throws Exception {
ctx.load().json(getClass().getResourceAsStream("AssetRenditionsImplTest.json"), "/content/dam");
ctx.currentResource("/content/dam/test.png");
final AssetResolver assetResolver = mock(AssetResolver.class);
doReturn(DamUtil.resolveToAsset(ctx.resourceResolver().getResource("/content/dam/test.png"))).when(assetResolver).resolveAsset(ctx.request());
ctx.registerService(AssetResolver.class, assetResolver);
ctx.registerService(mimeTypeService);
ctx.registerService(ExpressionEvaluator.class, new ExpressionEvaluatorImpl());
ctx.registerService(ComputedProperties.class, new ComputedPropertiesImpl());
ctx.addModelsForClasses(AssetModelImpl.class);
ctx.registerInjectActivateService(new AssetRenditionsImpl());
testAssetModel = ctx.request().adaptTo(AssetModel.class);
}
@Test
public void getUrl() {
final String expected = "/content/dam/test.png.renditions/test-rendition/asset.rendition";
final AssetRenditions assetRenditions = ctx.getService(AssetRenditions.class);
final AssetRenditionParameters params = new AssetRenditionParameters(testAssetModel, "test-rendition", false);
final AssetModel assetModel = ctx.request().adaptTo(AssetModel.class);
String actual = assetRenditions.getUrl(ctx.request(), assetModel, params);
assertEquals(expected, actual);
}
@Test
public void getUrl_AsDownload() {
final String expected = "/content/dam/test.png.renditions/test-rendition/download/asset.rendition";
final AssetRenditions assetRenditions = ctx.getService(AssetRenditions.class);
final AssetRenditionParameters params = new AssetRenditionParameters(testAssetModel, "test-rendition", true);
final AssetModel assetModel = ctx.request().adaptTo(AssetModel.class);
String actual = assetRenditions.getUrl(ctx.request(), assetModel, params);
assertEquals(expected, actual);
}
@Test
public void getOptions() {
final Map<String, String> params = new HashMap<>();
params.put("foo", "foo value");
params.put("foo_bar", "foo_bar value");
params.put("foo-bar", "foo-bar value");
final Map<String, String> expected = new HashMap<>();
expected.put("Foo", "foo");
expected.put("Foo bar", "foo_bar");
expected.put("Foo-bar", "foo-bar");
final AssetRenditions assetRenditions = ctx.getService(AssetRenditions.class);
final Map<String, String> actual = assetRenditions.getOptions(params);
assertEquals(expected, actual);
}
@Test
public void evaluateExpression() {
final String expression = "${asset.path}.test-selector.${asset.extension}?filename=${asset.name}&rendition=${rendition.name}";
final String expected = "/content/dam/test.png.test-selector.png?filename=test.png&rendition=test-rendition";
final AssetRenditions assetRenditions = ctx.getService(AssetRenditions.class);
ctx.requestPathInfo().setResourcePath("/content/dam/test.png");
ctx.requestPathInfo().setExtension("renditions");
ctx.requestPathInfo().setSuffix("/test-rendition/asset.rendition");
String actual = assetRenditions.evaluateExpression(ctx.request(), expression);
assertEquals(expected, actual);
}
@Test
public void evaluateExpression_ForDynamicMediaVariables() {
final String expression = "${dm.domain}is/image/${dm.file}?folder=${dm.folder}&name=${dm.name}&id=${dm.id}&api=${dm.api-server}";
final String expected = "http://test.scene7.com/is/image/testing/test_1?folder=testing&name=test_1&id=x|1234&api=https://test.api.scene7.com";
final AssetRenditions assetRenditions = ctx.getService(AssetRenditions.class);
ctx.requestPathInfo().setResourcePath("/content/dam/test.png");
ctx.requestPathInfo().setExtension("renditions");
ctx.requestPathInfo().setSuffix("/test-rendition/asset.rendition");
String actual = assetRenditions.evaluateExpression(ctx.request(), expression);
assertEquals(expected, actual);
}
} | 41.150327 | 150 | 0.731576 |
2df35194096a859b54c57b05881eb4aae7ee31d4 | 1,649 | package com.uniz.admin.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import com.uniz.admin.domain.Criteria;
import com.uniz.admin.domain.Uniz;
import com.uniz.admin.domain.UnizLayer;
public interface UnizMapper {
public List<Uniz> getListWithPaging(Criteria cri, Long unizSn);
public int unizInsert(Uniz uniz);
public int selectUniz(@Param("unizTypeSn")int unizTypeSn, @Param("unizKeyword")String unizKeyword);
public int unizUpdate(Uniz uniz);
public int unizDelete(Uniz uniz);
public int getCountByUniz(Long unizSn);
public List<Uniz> unizList2();
public List<UnizLayer> unizLayerList();
public int unizLayerDelete(UnizLayer unizLayer);
public int unizLayerUpdate(UnizLayer unizLayer);
public int unizLayerInsert(UnizLayer unizLayer);
public int unizLayerCheck(UnizLayer unizLayer);
public List<Uniz> unizNotLayerList();
public int getCountUnizKeyWord(String keyWord);
public int unizKeyWordInsert(@Param("searchUnizType") int searchUnizType, @Param("keyWord")String keyWord);
public int unizKeyWordsInsert(@Param("searchUnizType") List<Integer> searchUnizType, @Param("keyWord")String keyWord);
public int titleVideoUnizListInsert(@Param("videoSN")int videoSN, @Param("unizSN")Long unizSN);
public int titleVideoUnizListInsertAllKeyword(int videoSn, @Param("splitKeyWord")List<String> splitKeyWord, @Param("UnizTypeSN")int unizTypeSN);
public Long getUnizsnForKeyword(@Param("UnizTypeSN")int UnizTypeSN, @Param("UnizKeyWord")String UnizKeyWord);
public int getUnizCount();
public List<Uniz> getPagingUniz(@Param("start")int start,@Param("length") int length);
}
| 29.981818 | 145 | 0.783505 |
aca5a7b157222a02ad7aa7d096fe669f17d5edec | 1,098 | package server.pojo;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
public class OnlineManage{
public OnlineManage() {
}
public static List<UsersBuffer> onlineUsers = new ArrayList<UsersBuffer>();
public static List<GameRoom>Rooms = new ArrayList<GameRoom>();
public static UsersBuffer getUserBufferByUserName(String username){
for (int i = 0; i < OnlineManage.onlineUsers.size(); i++) {
if(OnlineManage.onlineUsers.get(i).getUser().getUserName().equals(username)){
return OnlineManage.onlineUsers.get(i);
}
}
return null;
}
public static int getRoomsByUserName(String username){
AtomicInteger i = new AtomicInteger();
Rooms.forEach(room->{
if(room.getUserBuffer1().getUser().getUserName().equals(username)){
i.set(1);
if(room.getUserBuffer2() != null){
i.set(2);
}
}else if(room.getUserBuffer2()!=null && room.getUserBuffer2().getUser().getUserName().equals(username)){
i.set(1);
if(room.getUserBuffer1() != null){
i.set(2);
}
}
});
return i.get();
}
}
| 23.869565 | 107 | 0.686703 |
9d1c4162d381afba64c73b20679f4c4bc7926286 | 4,438 | package org.algorithmdb.datastructures.map;
import java.util.Stack;
import java.util.concurrent.ArrayBlockingQueue;
public class BinarySearchTreeMap<K extends Comparable , V> implements OrderedMap<K, V>{
Node root;
private class Node<K, V> {
K key;
V value;
Node leftNode;
Node rightNode;
public Node(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() {
return key;
}
public void setKey(K key) {
this.key = key;
}
public V getValue() {
return value;
}
public void setValue(V value) {
this.value = value;
}
public Node getLeftNode() {
return leftNode;
}
public void setLeftNode(Node leftNode) {
this.leftNode = leftNode;
}
public Node getRightNode() {
return rightNode;
}
public void setRightNode(Node rightNode) {
this.rightNode = rightNode;
}
}
@Override
public void put(K key, V value) {
root = put (key, value, root, null);
}
public Node put(K key, V value,Node tempRoot, Integer i) {
if (tempRoot == null) {
return new Node(key, value);
}
int cmp = key.compareTo((K) tempRoot.getKey());
if (cmp < 0) {
tempRoot.leftNode = put(key, value, tempRoot.getLeftNode(), null);
} else if (cmp > 0) {
tempRoot.rightNode = put(key,value, tempRoot.getRightNode(), null);
}
return tempRoot;
}
@Override
public V get(K key) {
return get(key, root);
}
public V get(K key, Node node) {
if (node == null) {
return null;
}
int cmp = key.compareTo((K) node.getKey());
if (cmp <0) {
return (V) get(key, node.getLeftNode());
} else if (cmp > 0) {
return (V) get(key, node.getRightNode());
}
return (V) node.getValue();
}
@Override
public boolean contains(K key) {
// TODO Auto-generated method stub
return false;
}
@Override
public void delete(K key) {
// TODO Auto-generated method stub
}
@Override
public int size() {
// TODO Auto-generated method stub
return 0;
}
public void inorderTraversal(Node node) {
if (node != null) {
//Process the Node here. I am just printing the value
System.out.println(node.key);
inorderTraversal(node.leftNode);
inorderTraversal(node.rightNode);
}
}
public void inorderTraversalNonRecursive(Node node) {
if (node != null) {
Stack<Node> stack = new Stack<>();
while(true) {
while (node != null) {
//Process the Node here. I am just printing the value
System.out.println(node.key);
stack.push(node);
node = node.leftNode;
}
if(stack.isEmpty()) {
break;
}
Node temp = stack.pop();
node = temp.rightNode;
}
return;
}
}
public void levelOrderTraversal(Node node) {
if (node == null) {
return;
}
ArrayBlockingQueue<Node> queue = new ArrayBlockingQueue<>(10);
queue.offer(node);
while(!queue.isEmpty()) {
Node temp = queue.poll();
System.out.println(temp.getKey());
if (temp.leftNode != null) {
queue.offer(temp.leftNode);
}
if(temp.rightNode != null) {
queue.offer(temp.rightNode);
}
}
}
/**
* This method is to find the maximum key and return it.
* Right most node is the maximum key.
* @return Maximum key
*/
public K findMaxKey() {
return this.findMaxKey(root);
}
private K findMaxKey(Node node) {
if (node.getRightNode() == null) {
return (K)node.getKey();
}
return (K) findMaxKey(node.getRightNode());
}
public K searchInBinaryTree(K key) {
return this.searchInBinaryTree(root, key);
}
public K searchInBinaryTree(Node node, K key) {
if (node == null) {
return null;
}
if (key.compareTo((K)node.key) == 0) {
return key;
}
if (node.getLeftNode() != null) {
return (K) searchInBinaryTree(node.getLeftNode(), key);
}
if (node.getRightNode() != null) {
return (K) searchInBinaryTree(node.getRightNode(), key);
}
return null;
}
public static void main(String...args) {
BinarySearchTreeMap<Integer, String> tree = new BinarySearchTreeMap<>();
tree.put(5, "Arunan");
tree.put(7, "Ramanathan");
tree.put(3, "Pavalakkodi");
tree.put(1, "abinaya");
tree.put(4, "Idhaya");
tree.put(11, "kamatchi");
tree.put(6, "ezhil");
System.out.println("inserted");
System.out.println(tree.findMaxKey());
System.out.println(tree.searchInBinaryTree(4));
//System.out.println("get 1: "+ tree.get(1));
//System.out.println("get 7: "+ tree.get(7));
//System.out.println("get 11: "+ tree.get(11));
}
}
| 21.543689 | 87 | 0.635872 |
b5a17cc434a636eb8ca10bf34efdf38f430629fa | 15,695 | package com.aliyun.svideo.base.widget.beauty.seekbar;
import android.content.Context;
import android.graphics.drawable.GradientDrawable;
import android.os.Build;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import androidx.annotation.IdRes;
import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import com.aliyun.svideo.base.R;
/**
* created by ZhuangGuangquan on 2017/9/9
* <p>
* Version : 2.0
* Date: 2017/12/10
* New Feature: indicator stay always.
*/
public class Indicator {
private final Context mContext;
private final IndicatorSeekBar mSeekBar;
private final int mWindowWidth;
private int[] mLocation = new int[2];
private ArrowView mIndicatorArrow;
private TextView mIndicatorText;
private PopupWindow mIndicator;
private View mIndicatorView;
private LinearLayout mTopContentView;
private int mGap;
private BuilderParams p;
public Indicator(Context context, IndicatorSeekBar seekBar, BuilderParams p) {
this.mContext = context;
this.mSeekBar = seekBar;
this.p = p;
initIndicator();
mWindowWidth = getWindowWidth();
mGap = IndicatorUtils.dp2px(mContext, 2);
}
public void setGap(int dp) {
Log.e("Test", dp + "...." + mGap);
mGap = IndicatorUtils.dp2px(mContext, dp);
}
void initIndicator() {
if (p.mIndicatorType == IndicatorType.CUSTOM) {
if (p.mIndicatorCustomView != null) {
mIndicatorView = p.mIndicatorCustomView;
//for the custom indicator view, if progress need to show when seeking ,
// need a TextView to show progress and this textView 's identify must be progress;
int progressTextViewId = mContext.getResources().getIdentifier("isb_progress", "id", mContext.getApplicationContext().getPackageName());
if (progressTextViewId > 0) {
View view = mIndicatorView.findViewById(progressTextViewId);
if (view != null) {
if (view instanceof TextView) {
//progressText
mIndicatorText = (TextView) view;
mIndicatorText.setText(String.valueOf(mSeekBar.getProgress()));
mIndicatorText.setTextSize(IndicatorUtils.px2sp(mContext, p.mIndicatorTextSize));
mIndicatorText.setTextColor(p.mIndicatorTextColor);
} else {
throw new ClassCastException("the view identified by isb_progress in indicator custom layout can not be cast to TextView");
}
}
}
}
} else {
if (IndicatorType.CIRCULAR_BUBBLE == p.mIndicatorType) {
mIndicatorView = new CircleBubbleView(p, checkHolderText());
((CircleBubbleView) mIndicatorView).setProgress(String.valueOf(mSeekBar.getProgress()));
} else {
mIndicatorView = View.inflate(mContext, R.layout.aliyun_isb_indicator, null);
//container
mTopContentView = (LinearLayout) mIndicatorView.findViewById(R.id.indicator_container);
//arrow
mIndicatorArrow = (ArrowView) mIndicatorView.findViewById(R.id.indicator_arrow);
mIndicatorArrow.setColor(p.mIndicatorColor);
//progressText
mIndicatorText = (TextView) mIndicatorView.findViewById(R.id.isb_progress);
mIndicatorText.setText(String.valueOf(mSeekBar.getProgress()));
mIndicatorText.setTextSize(IndicatorUtils.px2sp(mContext, p.mIndicatorTextSize));
mIndicatorText.setTextColor(p.mIndicatorTextColor);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
mTopContentView.setBackground(getGradientDrawable());
} else {
mTopContentView.setBackgroundDrawable(getGradientDrawable());
}
//custom top content view
if (p.mIndicatorCustomTopContentView != null) {
//for the custom indicator top content view, if progress need to show when seeking ,
//need a TextView to show progress and this textView 's identify must be progress;
int progressTextViewId = mContext.getResources().getIdentifier("isb_progress", "id", mContext.getApplicationContext().getPackageName());
View topContentView = p.mIndicatorCustomTopContentView;
if (progressTextViewId > 0) {
View tv = topContentView.findViewById(progressTextViewId);
if (tv != null) {
setIndicatorTopContentView(topContentView, progressTextViewId);
} else {
setIndicatorTopContentView(topContentView);
}
} else {
setIndicatorTopContentView(topContentView);
}
}
}
}
if (mIndicatorView != null) {
mIndicatorView.measure(0, 0);
mIndicator = new PopupWindow(mIndicatorView, WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT, false);
}
}
String checkHolderText() {
if (p.mSeekBarType == IndicatorSeekBarType.CONTINUOUS || p.mSeekBarType == IndicatorSeekBarType.CONTINUOUS_TEXTS_ENDS) {
String maxString = String.valueOf(p.mMax);
String minString = String.valueOf(p.mMin);
return maxString.getBytes().length > minString.getBytes().length ? maxString : minString;
} else {
if (p.mTextArray != null) {
String maxLengthText = "j";
for (CharSequence c : p.mTextArray) {
if (c.length() > maxLengthText.length()) {
maxLengthText = c + "";
}
}
return maxLengthText;
}
}
return "100";
}
@NonNull
private GradientDrawable getGradientDrawable() {
GradientDrawable tvDrawable;
if (p.mIndicatorType == IndicatorType.RECTANGLE_ROUNDED_CORNER) {
tvDrawable = (GradientDrawable) mContext.getResources().getDrawable(R.drawable.isb_indicator_square_corners);
} else {
tvDrawable = (GradientDrawable) mContext.getResources().getDrawable(R.drawable.isb_indicator_rounded_corners);
}
tvDrawable.setColor(p.mIndicatorColor);
return tvDrawable;
}
private int getWindowWidth() {
WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
if (wm != null) {
return wm.getDefaultDisplay().getWidth();
}
return 0;
}
private int getIndicatorScreenX() {
mSeekBar.getLocationOnScreen(mLocation);
return mLocation[0];
}
private void adjustArrow(float touchX) {
if (p.mIndicatorType == IndicatorType.CUSTOM || p.mIndicatorType == IndicatorType.CIRCULAR_BUBBLE) {
return;
}
int indicatorScreenX = getIndicatorScreenX();
if (indicatorScreenX + touchX < mIndicator.getContentView().getMeasuredWidth() / 2) {
setMargin(-(int) (mIndicator.getContentView().getMeasuredWidth() / 2 - indicatorScreenX - touchX), -1, -1, -1);
} else if (mWindowWidth - indicatorScreenX - touchX < mIndicator.getContentView().getMeasuredWidth() / 2) {
setMargin((int) (mIndicator.getContentView().getMeasuredWidth() / 2 - (mWindowWidth - indicatorScreenX - touchX)), -1, -1, -1);
} else {
setMargin(0, 0, 0, 0);
}
}
private void setMargin(int left, int top, int right, int bottom) {
if (mIndicatorArrow == null) {
return;
}
if (mIndicatorArrow.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
ViewGroup.MarginLayoutParams layoutParams = (ViewGroup.MarginLayoutParams) mIndicatorArrow.getLayoutParams();
layoutParams.setMargins(left == -1 ? layoutParams.leftMargin : left, top == -1 ? layoutParams.topMargin : top, right == -1 ? layoutParams.rightMargin : right, bottom == -1 ? layoutParams.bottomMargin : bottom);
mIndicatorArrow.requestLayout();
}
}
/**
* call this to update indicator's location. if SeekBar is covered ,the indicator will dismiss auto and would show after the SeekBar showing completed.
*/
public void update() {
if (!mSeekBar.isEnabled() || !(mSeekBar.getVisibility() == View.VISIBLE)) {
return;
}
if (mSeekBar.isCover()) {
this.forceHide();
} else {
if (mSeekBar.getVisibility() == View.VISIBLE) {
if (this.isShowing()) {
this.update(mSeekBar.getTouchX());
} else {
this.show(mSeekBar.getTouchX());
}
}
}
}
/**
* update the indicator position
*
* @param touchX the x location you touch without padding left.
*/
void update(float touchX) {
if (!mSeekBar.isEnabled() || !(mSeekBar.getVisibility() == View.VISIBLE)) {
return;
}
if (mIndicatorView instanceof CircleBubbleView) {
((CircleBubbleView) mIndicatorView).setProgress(mSeekBar.getProgressString());
} else if (mIndicatorText != null) {
mIndicatorText.setText(mSeekBar.getProgressString());
mIndicator.getContentView().measure(0, 0);
}
mIndicator.update(mSeekBar, (int) (touchX - mIndicator.getContentView().getMeasuredWidth() / 2), -(mSeekBar.getMeasuredHeight() + mIndicator.getContentView().getMeasuredHeight() - mSeekBar.getPaddingTop() + mGap), -1, -1);
adjustArrow(touchX);
}
/**
* call this to show indicator
*/
public void show() {
if (!mSeekBar.isEnabled() || !(mSeekBar.getVisibility() == View.VISIBLE)) {
return;
}
if (!this.isShowing() && !mSeekBar.isCover()) {
this.show(mSeekBar.getTouchX());
}
}
/**
* call this method to show the indicator.
*
* @param touchX the x location you touch without padding left.
*/
void show(float touchX) {
if (mIndicator.isShowing() || !mSeekBar.isEnabled() || !(mSeekBar.getVisibility() == View.VISIBLE)) {
return;
}
if (mIndicatorView instanceof CircleBubbleView) {
((CircleBubbleView) mIndicatorView).setProgress(mSeekBar.getProgressString());
} else if (mIndicatorText != null) {
mIndicatorText.setText(mSeekBar.getProgressString());
mIndicator.getContentView().measure(0, 0);
}
mIndicator.showAsDropDown(mSeekBar, (int) (touchX - mIndicator.getContentView().getMeasuredWidth() / 2f), -(mSeekBar.getMeasuredHeight() + mIndicator.getContentView().getMeasuredHeight() - mSeekBar.getPaddingTop() + mGap));
adjustArrow(touchX);
}
/**
* call this method hide the indicator
*/
public void hide() {
if (mIndicator.isShowing()) {
if (!p.mIndicatorStay) {
mIndicator.dismiss();
}
}
}
/**
* call this method to hide the indicator ignore indicator stay always.
*/
public void forceHide() {
if (mIndicator.isShowing()) {
mIndicator.dismiss();
}
}
/**
* set the View to the indicator top container, not influence indicator arrow ;
* if indicator type is custom , this method will be not work.
*
* @param topContentView the view is inside the indicator TOP part, not influence indicator arrow;
*/
public void setIndicatorTopContentView(@NonNull View topContentView) {
mTopContentView.removeAllViews();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
topContentView.setBackground(getGradientDrawable());
} else {
topContentView.setBackgroundDrawable(getGradientDrawable());
}
mTopContentView.addView(topContentView);
}
/**
* set the View to the indicator top container, not influence indicator arrow ;
* if indicator type is custom , this method will be not work.
*
* @param topContentLayoutId the view id for indicator TOP part, not influence indicator arrow;
*/
public void setIndicatorTopContentLayout(@LayoutRes int topContentLayoutId) {
mTopContentView.removeAllViews();
View topContentView = View.inflate(mContext, topContentLayoutId, null);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
topContentView.setBackground(getGradientDrawable());
} else {
topContentView.setBackgroundDrawable(getGradientDrawable());
}
mTopContentView.addView(topContentView);
}
/**
* get the indicator content view.
*
* @return the view which is inside indicator.
*/
public View getmContentView() {
return mIndicator.getContentView();
}
/**
* set the View to the indicator top container, and show the changing progress in indicator when seek;
* not influence indicator arrow;
* * if indicator type is custom , this method will be not work.
*
* @param topContentView the view is inside the indicator TOP part, not influence indicator arrow;
* @param progressTextViewId the id can be find in @param topContentView, and it is a TextView id.
*/
public void setIndicatorTopContentView(@NonNull View topContentView, @IdRes int progressTextViewId) {
View tv = topContentView.findViewById(progressTextViewId);
if (tv == null) {
throw new IllegalArgumentException(" can not find the TextView in indicator topContentView by id: " + progressTextViewId);
}
if (!(tv instanceof TextView)) {
throw new ClassCastException(" the view identified by progressTextViewId can not be cast to TextView. ");
}
mIndicatorText = (TextView) tv;
mTopContentView.removeAllViews();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
topContentView.setBackground(getGradientDrawable());
} else {
topContentView.setBackgroundDrawable(getGradientDrawable());
}
mTopContentView.addView(topContentView);
}
/**
* check the indicator is showing or not .
*
* @return true is showing.
*/
public boolean isShowing() {
return mIndicator.isShowing();
}
/**
* call this method to replace the current indicator with a new indicator view , indicator arrow will be replace ,too.
*
* @param customIndicatorView a new view for indicator.
*/
public void setCustomIndicator(@NonNull View customIndicatorView) {
mIndicator.setContentView(customIndicatorView);
}
/**
* the text view to show the progress in indicator , must can be found in indicator root view.
*
* @param view a text view can be found in indicator root view
*/
public void setProgressTextView(@NonNull TextView view) {
mIndicatorText = view;
}
} | 41.302632 | 231 | 0.617012 |
aaa75d44fc39415eed3d22d56a30d7c517451efd | 729 | package sh.pancake.spellbox.api.observer;
import java.util.Map;
/*
* Created on Sat Jan 09 2021
*
* Copyright (c) storycraft. Licensed under the MIT Licence.
*/
public class MapValueObserver<K, T> implements IValueObserver<T> {
private Map<K, T> map;
private K key;
private T lastValue;
public MapValueObserver(Map<K, T> map, K key) {
this.map = map;
this.key = key;
this.lastValue = null;
this.update();
}
@Override
public T getLastValue() {
return lastValue;
}
@Override
public T getCurrentValue() {
return map.get(key);
}
@Override
public void update() {
this.lastValue = getCurrentValue();
}
}
| 17.357143 | 66 | 0.59808 |
d6bed35ed2cf98da7834eee22e34fd407c0c6534 | 404 | package no.nav.foreldrepenger.behandlingslager.behandling.inntektarbeidytelse;
import javax.persistence.Entity;
import no.nav.foreldrepenger.behandlingslager.kodeverk.Kodeliste;
@Entity(name = "YtelseType")
public class YtelseType extends Kodeliste {
YtelseType(String kode, String discriminator) {
super(kode, discriminator);
}
public YtelseType() {
//hibernate
}
}
| 22.444444 | 78 | 0.742574 |
1cab19d29a0e37830e29971cb42ee89d4a746965 | 3,532 | package com.test.printers;
import com.test.cases.AbstractInstrumentationTest;
import com.test.cases.SafeCaller;
import com.test.cases.util.ForkProcessBuilder;
import com.ulyp.core.CallRecord;
import com.ulyp.core.printers.IdentityObjectRepresentation;
import com.ulyp.core.printers.NullObjectRepresentation;
import com.ulyp.core.printers.NumberObjectRepresentation;
import com.ulyp.core.printers.StringObjectRepresentation;
import org.junit.Test;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
public class ObjectInstrumentationTest extends AbstractInstrumentationTest {
@Test
public void shouldPrintObjects() {
CallRecord root = runForkWithUi(
new ForkProcessBuilder()
.setMainClassName(ObjectTestCases.class)
.setMethodToRecord("acceptsTwoObjects")
);
assertThat(root.getArgs(), hasSize(2));
assertThat(root.getArgs().get(0), instanceOf(IdentityObjectRepresentation.class));
assertThat(root.getArgs().get(1), instanceOf(IdentityObjectRepresentation.class));
}
@Test
public void shouldChooseValidPrinterForJavaLangObjectAtRuntime() {
CallRecord root = runForkWithUi(
new ForkProcessBuilder()
.setMainClassName(ObjectTestCases.class)
.setMethodToRecord("acceptsTwoObjects2")
);
assertThat(root.getArgs(), hasSize(2));
assertThat(root.getArgs().get(0), instanceOf(StringObjectRepresentation.class));
assertThat(root.getArgs().get(1), instanceOf(NumberObjectRepresentation.class));
}
@Test
public void shouldPrintNullArguments() {
CallRecord root = runForkWithUi(
new ForkProcessBuilder()
.setMainClassName(ObjectTestCases.class)
.setMethodToRecord("acceptsTwoNulls")
);
assertThat(root.getArgs(), hasSize(2));
assertThat(root.getArgs().get(0), instanceOf(NullObjectRepresentation.class));
assertThat(root.getArgs().get(1), instanceOf(NullObjectRepresentation.class));
}
public static class ObjectTestCases {
private static volatile Object store0;
private static volatile Object store1;
private static volatile Object store2;
private static volatile Object store3;
public static void main(String[] args) {
SafeCaller.call(() -> new ObjectTestCases().acceptsTwoObjects(new Object(), new Object()));
SafeCaller.call(() -> new ObjectTestCases().acceptsTwoObjects2("asdasd", 34));
SafeCaller.call(() -> new ObjectTestCases().acceptsTwoObjects3(new ObjectTestCases.X(), new ObjectTestCases.Y()));
SafeCaller.call(() -> new ObjectTestCases().acceptsTwoNulls(null, null));
}
public void acceptsTwoObjects(Object o1, Object o2) {
store0 = o1;
store1 = o2;
}
public void acceptsTwoObjects2(Object o1, Object o2) {
store0 = o1;
store1 = o2;
}
public void acceptsTwoObjects3(Object o1, Object o2) {
store0 = o1;
store1 = o2;
}
public void acceptsTwoNulls(Object o1, Object o2) {
store0 = o1;
store1 = o2;
}
private static class X {
}
private static class Y {
public String toString() {
return "Y{}";
}
}
}
}
| 34.970297 | 126 | 0.638165 |
e9cc55ecd4db457e721a9c62748707da14f1d6be | 1,771 | package com.bytezone.dm3270.display;
import com.bytezone.dm3270.attributes.ColorAttribute;
import java.awt.Color;
public class ScreenContext {
public static final ScreenContext DEFAULT_CONTEXT = new ScreenContext(ColorAttribute.COLORS[0],
ColorAttribute.COLORS[8], (byte) 0, false, false);
public final Color foregroundColor;
public final Color backgroundColor;
public final byte highlight;
public final boolean highIntensity;
public final boolean isGraphic;
public ScreenContext(Color foregroundColor, Color backgroundColor, byte highlight,
boolean highIntensity, boolean isGraphic) {
this.foregroundColor = foregroundColor;
this.backgroundColor = backgroundColor;
this.highlight = highlight;
this.highIntensity = highIntensity;
this.isGraphic = isGraphic;
}
public ScreenContext withBackgroundColor(Color color) {
return new ScreenContext(foregroundColor, color, highlight, highIntensity, isGraphic);
}
public ScreenContext withHighlight(byte highlight) {
return new ScreenContext(foregroundColor, backgroundColor, highlight, highIntensity,
isGraphic);
}
public ScreenContext withForeground(Color color) {
return new ScreenContext(color, backgroundColor, highlight, highIntensity, isGraphic);
}
public ScreenContext withGraphic(boolean isGraphic) {
return new ScreenContext(foregroundColor, backgroundColor, highlight, highIntensity,
isGraphic);
}
@Override
public String toString() {
return String.format("[Fg:%-10s Bg:%-10s In:%s Hl:%02X]",
ColorAttribute.getName(foregroundColor),
ColorAttribute.getName(backgroundColor),
(highIntensity ? 'x' : ' '), highlight);
}
public boolean isGraphic() {
return isGraphic;
}
}
| 31.625 | 97 | 0.746471 |
56a9afa1a9cd6aea641db21ee74231e101db9e10 | 2,610 | package problems;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.*;
import static problems.BinaryTreeLevelOrderTraversal.*;
public class BinaryTreeLevelOrderTraversalTest {
@Test
public void emptyTreeShouldBeEmptyListOfLists() {
List<List<Integer>> expected = new ArrayList<>();
assertEquals(expected, levelOrder(null));
}
@Test
public void singleValueTreeShouldBeSingleValueListOfLists() {
TreeNode root = new TreeNode(0);
List<List<Integer>> expected = new ArrayList<>();
List<Integer> first = new ArrayList<>();
first.add(0);
expected.add(first);
assertEquals(expected, levelOrder(root));
}
@Test
public void multiLevelBalancedTreeShouldBeMultipleListsOfLists() {
TreeNode root = new TreeNode(0);
TreeNode left = new TreeNode(1);
TreeNode right = new TreeNode(2);
TreeNode leftLeft = new TreeNode(3);
TreeNode leftRight = new TreeNode(4);
TreeNode rightLeft = new TreeNode(5);
TreeNode rightRight = new TreeNode(6);
root.left = left;
root.right = right;
right.left = rightLeft;
right.right = rightRight;
left.left = leftLeft;
left.right = leftRight;
List<List<Integer>> expected = new ArrayList<>();
List<Integer> first = new ArrayList<>();
List<Integer> second = new ArrayList<>();
List<Integer> third = new ArrayList<>();
first.add(0);
second.add(1);
second.add(2);
third.add(3);
third.add(4);
third.add(5);
third.add(6);
expected.add(first);
expected.add(second);
expected.add(third);
assertEquals(expected, levelOrder(root));
}
@Test
public void unbalancedTreeShouldBeMultipleListsOfLists() {
TreeNode root = new TreeNode(0);
TreeNode left = new TreeNode(1);
TreeNode leftLeft = new TreeNode(3);
TreeNode leftRight = new TreeNode(4);
root.left = left;
left.left = leftLeft;
left.right = leftRight;
List<List<Integer>> expected = new ArrayList<>();
List<Integer> first = new ArrayList<>();
List<Integer> second = new ArrayList<>();
List<Integer> third = new ArrayList<>();
first.add(0);
second.add(1);
third.add(3);
third.add(4);
expected.add(first);
expected.add(second);
expected.add(third);
assertEquals(expected, levelOrder(root));
}
} | 27.765957 | 70 | 0.605364 |
f44979c2315dd7afd82e3aec5f13ed85311da1cd | 4,628 | package de.borisskert.spring.springvalidationexample;
import org.json.JSONObject;
import org.junit.jupiter.api.Test;
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.http.MediaType;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.web.servlet.MockMvc;
import java.util.regex.Pattern;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.matchesRegex;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest
@AutoConfigureMockMvc
@ActiveProfiles("IT")
class UserEndpointTest {
public static final Pattern UUID_REGEX = Pattern.compile("^([a-f0-9]{8}(-[a-f0-9]{4}){4}[a-f0-9]{8})$");
@Autowired
private MockMvc mvc;
@Test
public void shouldCreateUser() throws Exception {
JSONObject requestBody = new JSONObject()
.put("name", "username")
.put("email", "[email protected]");
mvc.perform(post("/users")
.contentType(MediaType.APPLICATION_JSON)
.content(requestBody.toString()))
.andExpect(status().isOk())
.andExpect(jsonPath("name", equalTo("username")))
.andExpect(jsonPath("email", equalTo("[email protected]")))
.andExpect(jsonPath("id", matchesRegex(UUID_REGEX)))
;
}
@Test
public void shouldNotAcceptEmptyBody() throws Exception {
mvc.perform(post("/users")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().is4xxClientError())
;
}
@Test
public void shouldNotAcceptMissingEmail() throws Exception {
JSONObject requestBody = new JSONObject()
.put("name", "my name");
mvc.perform(post("/users")
.contentType(MediaType.APPLICATION_JSON)
.content(requestBody.toString()))
.andExpect(status().is4xxClientError())
;
}
@Test
public void shouldNotAcceptEmptyEmail() throws Exception {
JSONObject requestBody = new JSONObject()
.put("name", "my name")
.put("email", "");
mvc.perform(post("/users")
.contentType(MediaType.APPLICATION_JSON)
.content(requestBody.toString()))
.andExpect(status().is4xxClientError())
;
}
@Test
public void shouldNotAcceptEmptyName() throws Exception {
JSONObject requestBody = new JSONObject()
.put("name", "")
.put("email", "[email protected]");
mvc.perform(post("/users")
.contentType(MediaType.APPLICATION_JSON)
.content(requestBody.toString()))
.andExpect(status().is4xxClientError())
;
}
@Test
public void shouldNotAcceptMissingName() throws Exception {
JSONObject requestBody = new JSONObject()
.put("email", "[email protected]");
mvc.perform(post("/users")
.contentType(MediaType.APPLICATION_JSON)
.content(requestBody.toString()))
.andExpect(status().is4xxClientError())
;
}
@Test
public void shouldNotAcceptInvalidName() throws Exception {
JSONObject requestBody = new JSONObject()
.put("name", "user5name")
.put("email", "[email protected]");
mvc.perform(post("/users")
.contentType(MediaType.APPLICATION_JSON)
.content(requestBody.toString()))
.andExpect(status().is4xxClientError())
;
}
@Test
public void shouldNotAcceptOccupiedUsername() throws Exception {
JSONObject requestBody = new JSONObject()
.put("name", "occupied")
.put("email", "[email protected]");
mvc.perform(post("/users")
.contentType(MediaType.APPLICATION_JSON)
.content(requestBody.toString()))
.andExpect(status().isOk())
;
mvc.perform(post("/users")
.contentType(MediaType.APPLICATION_JSON)
.content(requestBody.toString()))
.andExpect(status().is4xxClientError())
;
}
}
| 34.281481 | 108 | 0.613656 |
c9a9a7d9024a8cb69e0e3a672117fd9daf25dc96 | 973 | package com.ceiba.pagos.administracion.servicio.testdatabuilder;
import com.ceiba.pagos.administracion.comando.ComandoPagosAdministracion;
import com.ceiba.pagos.administracion.modelo.dto.DtoConsultarSaldoPagosAdministracion;
public class ConsultarSaldoPagosAdministracionTestDataBuilder {
private String codigoInmueble;
private Integer mes;
public ConsultarSaldoPagosAdministracionTestDataBuilder() {
codigoInmueble = "QA18";
mes = 2;
}
public ConsultarSaldoPagosAdministracionTestDataBuilder conCodigoInmueble(String codigoInmueble) {
this.codigoInmueble = codigoInmueble;
return this;
}
public ConsultarSaldoPagosAdministracionTestDataBuilder conMes(Integer mes) {
this.mes = mes;
return this;
}
public DtoConsultarSaldoPagosAdministracion build() {
return new DtoConsultarSaldoPagosAdministracion(
codigoInmueble,
mes
);
}
}
| 28.617647 | 102 | 0.731757 |
fce07901be5024b2c1a6c0cb9f4abfd9649086be | 2,531 | /*
* Copyright 2011-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
*
* https://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.neo4j.repository;
import java.util.List;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Sort;
import org.springframework.data.repository.NoRepositoryBean;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.QueryByExampleExecutor;
/**
* Neo4j specific {@link org.springframework.data.repository.Repository} interface.
*
* @author Michael J. Simons
* @author Ján Šúr
* @param <T> type of the domain class to map
* @param <ID> identifier type in the domain class
* @since 6.0
*/
@NoRepositoryBean
public interface Neo4jRepository<T, ID> extends PagingAndSortingRepository<T, ID>, QueryByExampleExecutor<T> {
/*
* (non-Javadoc)
* @see org.springframework.data.repository.CrudRepository#saveAll(java.lang.Iterable)
*/
@Override
<S extends T> List<S> saveAll(Iterable<S> entities);
/*
* (non-Javadoc)
* @see org.springframework.data.repository.CrudRepository#findAll()
*/
@Override
List<T> findAll();
/*
* (non-Javadoc)
* @see org.springframework.data.repository.CrudRepository#findAllById(java.lang.Iterable)
*/
@Override
List<T> findAllById(Iterable<ID> iterable);
/*
* (non-Javadoc)
* @see org.springframework.data.repository.PagingAndSortingRepository#findAll(org.springframework.data.domain.Sort)
*/
@Override
List<T> findAll(Sort sort);
/*
* (non-Javadoc)
* @see org.springframework.data.repository.query.QueryByExampleExecutor#findAll(org.springframework.data.domain.Example)
*/
@Override
<S extends T> List<S> findAll(Example<S> example);
/*
* (non-Javadoc)
* @see org.springframework.data.repository.query.QueryByExampleExecutor#findAll(org.springframework.data.domain.Example, org.springframework.data.domain.Sort)
*/
@Override
<S extends T> List<S> findAll(Example<S> example, Sort sort);
}
| 31.6375 | 160 | 0.751877 |
f991eae48d396c6e4681c3b9cf2f62259c42814f | 2,570 | /*
* Board
*
* Max Rossmannek
*/
package monopoly;
import java.io.FileReader;
import java.io.BufferedReader;
import java.util.ArrayList;
public class Board {
private char[][] board; // board 2d-array
private int rows; // number of rows on board
private int cols; // number of columns on board
private String boardFile; // name of file the board is saved in
public Board(String filename) {
boardFile = filename;
try {
FileReader inFile = new FileReader(boardFile);
BufferedReader reader = new BufferedReader(inFile);
char[] tmp = reader.readLine().toCharArray();
cols = tmp.length;
rows=1;
while (reader.readLine() != null) {
rows++;
}
reader.close();
inFile.close();
board = new char[rows][cols];
} catch (Exception e) {
System.err.println(e);
}
}
public void setupBoard() {
try {
FileReader inFile = new FileReader(boardFile);
BufferedReader reader = new BufferedReader(inFile);
int i=0;
while (i<rows) {
char[] tmp = reader.readLine().toCharArray();
for (int j=0; j<cols; ++j) {
board[i][j] = tmp[j];
}
i++;
}
reader.close();
inFile.close();
} catch (Exception e) {
System.err.println(e);
}
}
public void printBoard() {
System.out.println();
for (int m=0; m<rows; ++m) {
for (int n=0; n<cols; ++n) {
System.out.print(board[m][n]);
}
System.out.println();
}
}
public void placePlayer(Player pl, ArrayList<Field> fields) {
int pos = pl.getPosition();
Field field = fields.get(pos);
int[] coords = field.getCoordinates();
int count = field.getPlayerCount();
switch (count) {
case 0:
board[coords[0]][coords[1]] = pl.getName().charAt(0);
break;
default:
board[coords[0]][coords[1]] = 'X';
}
field.increasePlayerCount();
// System.out.println("Placing player "+pl.get_name()+" on field "+field.get_name()+" (#players: "+field.get_player_count()+")");
}
public void removePlayer(Player pl, ArrayList<Field> fields) {
int pos = pl.getPosition();
Field field = fields.get(pos);
int[] coords = field.getCoordinates();
int count = field.getPlayerCount();
switch (count) {
case 0:
System.err.println("There appears to be no player on this field:");
return;
case 1:
board[coords[0]][coords[1]] = ' ';
field.decreasePlayerCount();
break;
default:
field.decreasePlayerCount();
}
// System.out.println("Removing player "+pl.get_name()+" from field "+field.get_name()+" (#players: "+field.get_player_count()+")");
}
}
| 19.469697 | 135 | 0.625292 |
2154ae9095fc31119542c75e801e91e8bb4a91e2 | 5,779 | package com.skytala.eCommerce.domain.product.relations.costComponent.control.calc;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.google.common.base.Splitter;
import com.skytala.eCommerce.domain.product.relations.costComponent.command.calc.AddCostComponentCalc;
import com.skytala.eCommerce.domain.product.relations.costComponent.command.calc.DeleteCostComponentCalc;
import com.skytala.eCommerce.domain.product.relations.costComponent.command.calc.UpdateCostComponentCalc;
import com.skytala.eCommerce.domain.product.relations.costComponent.event.calc.CostComponentCalcAdded;
import com.skytala.eCommerce.domain.product.relations.costComponent.event.calc.CostComponentCalcDeleted;
import com.skytala.eCommerce.domain.product.relations.costComponent.event.calc.CostComponentCalcFound;
import com.skytala.eCommerce.domain.product.relations.costComponent.event.calc.CostComponentCalcUpdated;
import com.skytala.eCommerce.domain.product.relations.costComponent.mapper.calc.CostComponentCalcMapper;
import com.skytala.eCommerce.domain.product.relations.costComponent.model.calc.CostComponentCalc;
import com.skytala.eCommerce.domain.product.relations.costComponent.query.calc.FindCostComponentCalcsBy;
import com.skytala.eCommerce.framework.exceptions.RecordNotFoundException;
import com.skytala.eCommerce.framework.pubsub.Scheduler;
import static com.skytala.eCommerce.framework.pubsub.ResponseUtil.*;
@RestController
@RequestMapping("/product/costComponent/costComponentCalcs")
public class CostComponentCalcController {
private static Map<String, RequestMethod> validRequests = new HashMap<>();
public CostComponentCalcController() {
validRequests.put("find", RequestMethod.GET);
validRequests.put("add", RequestMethod.POST);
validRequests.put("update", RequestMethod.PUT);
validRequests.put("removeById", RequestMethod.DELETE);
}
/**
*
* @param allRequestParams
* all params by which you want to find a CostComponentCalc
* @return a List with the CostComponentCalcs
* @throws Exception
*/
@GetMapping("/find")
public ResponseEntity<List<CostComponentCalc>> findCostComponentCalcsBy(@RequestParam(required = false) Map<String, String> allRequestParams) throws Exception {
FindCostComponentCalcsBy query = new FindCostComponentCalcsBy(allRequestParams);
if (allRequestParams == null) {
query.setFilter(new HashMap<>());
}
List<CostComponentCalc> costComponentCalcs =((CostComponentCalcFound) Scheduler.execute(query).data()).getCostComponentCalcs();
return ResponseEntity.ok().body(costComponentCalcs);
}
/**
* creates a new CostComponentCalc entry in the ofbiz database
*
* @param costComponentCalcToBeAdded
* the CostComponentCalc thats to be added
* @return true on success; false on fail
*/
@RequestMapping(method = RequestMethod.POST, value = "/add", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<CostComponentCalc> createCostComponentCalc(@RequestBody CostComponentCalc costComponentCalcToBeAdded) throws Exception {
AddCostComponentCalc command = new AddCostComponentCalc(costComponentCalcToBeAdded);
CostComponentCalc costComponentCalc = ((CostComponentCalcAdded) Scheduler.execute(command).data()).getAddedCostComponentCalc();
if (costComponentCalc != null)
return successful(costComponentCalc);
else
return conflict(null);
}
/**
* Updates the CostComponentCalc with the specific Id
*
* @param costComponentCalcToBeUpdated
* the CostComponentCalc thats to be updated
* @return true on success, false on fail
* @throws Exception
*/
@RequestMapping(method = RequestMethod.PUT, value = "/{costComponentCalcId}", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<String> updateCostComponentCalc(@RequestBody CostComponentCalc costComponentCalcToBeUpdated,
@PathVariable String costComponentCalcId) throws Exception {
costComponentCalcToBeUpdated.setCostComponentCalcId(costComponentCalcId);
UpdateCostComponentCalc command = new UpdateCostComponentCalc(costComponentCalcToBeUpdated);
try {
if(((CostComponentCalcUpdated) Scheduler.execute(command).data()).isSuccess())
return noContent();
} catch (RecordNotFoundException e) {
return notFound();
}
return conflict();
}
@GetMapping("/{costComponentCalcId}")
public ResponseEntity<CostComponentCalc> findById(@PathVariable String costComponentCalcId) throws Exception {
HashMap<String, String> requestParams = new HashMap<String, String>();
requestParams.put("costComponentCalcId", costComponentCalcId);
try {
List<CostComponentCalc> foundCostComponentCalc = findCostComponentCalcsBy(requestParams).getBody();
if(foundCostComponentCalc.size()==1){ return successful(foundCostComponentCalc.get(0));
}else{
return notFound();
}
} catch (RecordNotFoundException e) {
return notFound();
}
}
@DeleteMapping("/{costComponentCalcId}")
public ResponseEntity<String> deleteCostComponentCalcByIdUpdated(@PathVariable String costComponentCalcId) throws Exception {
DeleteCostComponentCalc command = new DeleteCostComponentCalc(costComponentCalcId);
try {
if (((CostComponentCalcDeleted) Scheduler.execute(command).data()).isSuccess())
return noContent();
} catch (RecordNotFoundException e) {
return notFound();
}
return conflict();
}
}
| 38.785235 | 161 | 0.796678 |
6421efbfea8c474285483266eb40a8a087f5f488 | 225 | package org.thehustletech.kafka;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class WsSpringbootKafkaApplicationTests {
@Test
void contextLoads() {}
}
| 18.75 | 60 | 0.804444 |
47ec853fe3bc66d86518a36a76fd3f389f76a5cb | 538 | package com.learn.thread.exercise2;
/**
* Date: Tuesday, 3/16/21
* Time: 11:24 AM
* Author: Hung.Pham
*/
public class RunExercise2 {
public static void main(String[] args) throws InterruptedException {
ThreadOne threadOne = new ThreadOne(2);
ThreadTwo threadTwo = new ThreadTwo(2);
// Start thread One
threadOne.start();
// Thread main wait for thread One to die
threadOne.join();
// Thread Two start after thread One has died
threadTwo.start();
}
}
| 22.416667 | 72 | 0.6171 |
520b782fa3fe957030c50b84d410578449ad9be1 | 2,586 | package utils;
public class arrayEnteros {
/**
* Introduce un valor en una posición de un array de enteros, desplazando el
* valor existente y todos los que hay acontinuacion a la derecha, no se
* borra nungún valor.
*
* @param array Array de enteros original
* @param pos Posicion donde hacer la insercion
* @param v Valor a inertar
* @return Nuevo array de enteros con el valor insertado, ahora su medida se
* ha incrementado en uno, Si hay un error se evalua a null
*/
public int[] insertar(int[] array, int pos, int v) {
if ((pos >= 0) && (pos < array.length)) {
int[] nuevoArray = new int[array.length + 1];
copiarNPosiciones(array, nuevoArray, pos);
nuevoArray[pos] = v;
for (int i = pos; i < array.length; i++) {
nuevoArray[i + 1] = array[i];
}
return nuevoArray;
} else {
return null;
}
}
/**
* Borra un valor en una posición de un array de enteros, desplazando los
* valores, sobre la posición eliminada, hacia la izquierda.
*
* @param array Array de enteros original
* @param pos Posición a borrar
* @return Nuevo array de enteros con el valor eliminado. Ahora su medida se
* ha reducido en uno. Si hay un error se evalua a null.
*/
public int[] borrar(int[] array, int pos) {
if ((pos >= 0) && (pos < array.length)) {
int[] nouArray = new int[array.length - 1];
copiarNPosiciones(array, nouArray, pos);
for (int i = pos + 1; i < array.length; i++) {
nouArray[i - 1] = array[i];
}
return nouArray;
} else {
return null;
}
}
/**
* Dados dos vectores de enteros, copia los N primeros valores de el origen, a
* la destinacion, comenzando por la posicion 0.
*
* @param origen Array de origen
* @param desti Array de destino
* @param n Numero de valors a copiar
*/
public void copiarNPosiciones(int[] origen, int[] desti, int n) {
for (int i = 0; i < n; i++) {
desti[i] = origen[i];
}
}
/**
* Recibe un array y printea su contenido formateado.
*
* @param array recibe un array
*/
public void mostrarArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.printf("%3d", array[i]);
}
}
}
| 32.325 | 83 | 0.535189 |
5f99e0b7501c4fec5a3413b610384c72a9d94b57 | 321 | package com.marklalor.monopolysim.game.display;
import java.awt.image.BufferedImage;
public class DisplayHQ extends Display
{
@Override
public void draw()
{
// TODO draw on HQ graphics;
}
@Override
protected BufferedImage createImage()
{
return new BufferedImage(600, 400, BufferedImage.TYPE_INT_RGB);
}
}
| 16.894737 | 65 | 0.753894 |
d912300beb78116de77af6b56e4cd97bebd29d99 | 4,196 | package hu.unideb.inf.notebookservice.service.impl;
import hu.unideb.inf.notebookservice.commons.exeptions.AlreadyExistsException;
import hu.unideb.inf.notebookservice.commons.exeptions.NotFoundException;
import hu.unideb.inf.notebookservice.commons.request.ModificationRequest;
import hu.unideb.inf.notebookservice.persistence.entity.ModificationEntity;
import hu.unideb.inf.notebookservice.persistence.repository.ModificationRepository;
import hu.unideb.inf.notebookservice.service.converter.modification.ModificationEntityListToModificationListConverter;
import hu.unideb.inf.notebookservice.service.converter.modification.ModificationEntityToModificationConverter;
import hu.unideb.inf.notebookservice.service.converter.modification.ModificationRequestToModificationConverter;
import hu.unideb.inf.notebookservice.service.converter.modification.ModificationToModificationEntityConverter;
import hu.unideb.inf.notebookservice.service.domain.Modification;
import hu.unideb.inf.notebookservice.service.interfaces.ModificationService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
import static hu.unideb.inf.notebookservice.commons.error.ErrorTemplate.ALREADY_EXISTS_EXCEPTION;
import static hu.unideb.inf.notebookservice.commons.error.ErrorTemplate.ID_NOT_FOUND_EXCEPTION;
@Slf4j
@Service
@RequiredArgsConstructor
public class ModificationServiceImpl implements ModificationService {
private final ModificationEntityToModificationConverter toDomain;
private final ModificationToModificationEntityConverter toEntity;
private final ModificationRequestToModificationConverter fromRequest;
private final ModificationEntityListToModificationListConverter toDomainList;
private final ModificationRepository repository;
@Override
public Modification save(ModificationRequest modificationRequest) {
Optional<ModificationEntity> entity = repository.findByName(modificationRequest.getName());
if (entity.isPresent()) {
throw new AlreadyExistsException(String.format(ALREADY_EXISTS_EXCEPTION, modificationRequest.getName()));
}
log.info(">> Converting Request >> [modificationRequest:{}]", modificationRequest);
Modification modification = fromRequest.convert(modificationRequest);
log.info(">> Converting Domain >> [modification:{}]", modification);
ModificationEntity converted = toEntity.convert(modification);
log.info(">> Saving Entity >> [converted:{}]", converted);
return toDomain.convert(repository.save(converted));
}
@Override
public Modification update(Long id, ModificationRequest modification) {
findById(id);
Modification newModification = fromRequest.convert(id, modification);
log.info(">> Converting Domain >> [newModification:{}]", newModification);
ModificationEntity converted = toEntity.convert(newModification);
log.info(">> Saving Entity >> [converted:{}]", converted);
ModificationEntity saved = repository.save(converted);
log.info(">> Response >> [saved:{}]", saved);
return toDomain.convert(saved);
}
@Override
public Modification findById(Long id) {
log.info(">> Searching in Database >> [id:{}]", id);
Optional<ModificationEntity> foundModification = repository.findById(id);
log.info(">> Converting to Domain >> [foundModification:{}]", foundModification);
Modification convertedModification = toDomain.convert(
foundModification.orElseThrow(
() -> new NotFoundException(
String.format(ID_NOT_FOUND_EXCEPTION, id))));
log.info(">> Response >> [convertedModification:{}]", convertedModification);
return convertedModification;
}
@Override
public List<Modification> findAll() {
log.info(">> Finding all Brand <<");
List<ModificationEntity> entityList = repository.findAll();
log.info(">> Converting all to Domain <<");
return toDomainList.convert(entityList);
}
}
| 45.11828 | 118 | 0.753813 |
3a412d2fa54da8631e0b893a6c6522d4f2effe17 | 2,864 | import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class C3063467A4Conf {
public static java.util.Scanner xbox = new java.util.Scanner(System.in);
public static synchronized void main(String[] variable) {
HJoystick nokia;
java.lang.String opinions;
int septentrionAssistance;
int southwesterlyOpinion;
nokia = null;
opinions = "";
septentrionAssistance = -1;
southwesterlyOpinion = -1;
if (variable.length > 0) {
for (java.lang.String fh : variable) {
opinions = fh;
}
try {
java.lang.String northwesterlyPurch;
java.util.regex.Pattern northwardNormal;
java.util.regex.Matcher northwestwardVerifier;
java.lang.String southwardExperiment;
java.util.regex.Pattern southwesterlyConvention;
java.util.regex.Matcher southwestVariable;
opinions = "./out/production/c3063467A2P1/" + opinions;
opinions = readerInitiate(opinions, StandardCharsets.UTF_8);
northwesterlyPurch = "N=(?<North>[\\d]+)";
northwardNormal = java.util.regex.Pattern.compile(northwesterlyPurch);
northwestwardVerifier = northwardNormal.matcher(opinions);
while (northwestwardVerifier.find()) {
septentrionAssistance = java.lang.Integer.parseInt(northwestwardVerifier.group("North"));
}
southwardExperiment = "S=(?<South>[\\d]+)";
southwesterlyConvention = java.util.regex.Pattern.compile(southwardExperiment);
southwestVariable = southwesterlyConvention.matcher(opinions);
while (southwestVariable.find()) {
southwesterlyOpinion = java.lang.Integer.parseInt(southwestVariable.group("South"));
}
} catch (java.io.IOException appointed) {
System.out.println("");
}
}
while (septentrionAssistance < 0 || southwesterlyOpinion < 0) {
System.out.println("Oops some of those input values were invalid, lets try again.");
System.out.println("Enter the number of North Island Farmers to initialize:");
septentrionAssistance = xbox.nextInt();
System.out.println("Enter the number of South Island Farmers to initialize:");
southwesterlyOpinion = xbox.nextInt();
}
nokia = new HJoystick(septentrionAssistance, southwesterlyOpinion);
System.out.println("main: Start main");
nokia.commencing();
}
public static synchronized java.lang.String readerInitiate(
java.lang.String routes, java.nio.charset.Charset crypto) throws IOException {
byte[] interlaced = java.nio.file.Files.readAllBytes(java.nio.file.Paths.get(routes));
return new java.lang.String(interlaced, crypto);
}
}
| 38.702703 | 99 | 0.699022 |
b8430ab04526cb949e955f5aa96a7c83048b4662 | 17,131 | package eu.daiad.web.mapreduce;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import java.util.regex.Pattern;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IOUtils;
/**
* Submits a map reduce job to a Hadoop YARN cluster.
*/
public class RunJar {
/**
* Logger instance for writing events using the configured logging API.
*/
private static final Log logger = LogFactory.getLog(RunJar.class);
/**
* Environment specific temporary directory.
*/
private static final String PROPERTY_TMP_DIRECTORY = "java.io.tmpdir";
/**
* Pattern for matching files in JAR archive.
*/
private static final Pattern MATCH_ANY = Pattern.compile(".*");
/**
* Ensures that a key exists in the properties.
*
* @param properties the properties to check.
* @param key the key to find.
* @param message error message.
* @return true if the value is not null or empty.
* @throws Exception if no value is assigned to the given key.
*/
private boolean ensureParameter(Map<String, String> properties, String key, String message) throws Exception {
return ensureParameter(properties, key, message, true);
}
/**
* Ensures that a key exists in the properties.
*
* @param properties the properties to check.
* @param key the key to find.
* @param message error message.
* @param throwException throw an exception if the parameter does not exist.
* @return true if the value is not null or empty.
* @throws Exception if no value is assigned to the given key.
*/
private boolean ensureParameter(Map<String, String> properties, String key, String message, boolean throwException) throws Exception {
if (!properties.containsKey(key)) {
if (throwException) {
throw new Exception(String.format("%s. Parameter: %s", message, key));
}
return false;
}
if (StringUtils.isBlank(properties.get(key))) {
if (throwException) {
throw new Exception(String.format("%s. Parameter: %s", message, key));
}
return false;
}
return true;
}
/**
* Executes a map reduce job from an external jar file.
*
* @param properties properties to add to the job configuration.
* @throws Throwable if the job execution fails.
*/
public void run(Map<String, String> properties) throws Throwable {
ensureParameter(properties, EnumJobMapReduceParameter.JOB_NAME.getValue(), "Job name is not set");
ensureParameter(properties, EnumJobMapReduceParameter.JAR_NAME.getValue(), "JAR is not set");
// Get JAR file
String jarFilename = properties.get(EnumJobMapReduceParameter.JAR_NAME.getValue());
File file = new File(jarFilename);
if (!file.exists() || !file.isFile()) {
throw new Exception(String.format("Not a valid JAR: %s", file.getCanonicalPath()));
}
JarFile jarFile;
try {
jarFile = new JarFile(jarFilename);
} catch (IOException io) {
throw new IOException(String.format("Error opening job jar: %s", jarFilename)).initCause(io);
}
// Select Main class
String mainClassName = null;
Manifest manifest = jarFile.getManifest();
if (manifest != null) {
mainClassName = manifest.getMainAttributes().getValue("Main-Class");
}
jarFile.close();
if (mainClassName == null) {
ensureParameter(properties, EnumJobMapReduceParameter.MAIN_CLASS_NAME.getValue(), "Main Class is not set");
mainClassName = properties.get(EnumJobMapReduceParameter.MAIN_CLASS_NAME.getValue());
}
mainClassName = mainClassName.replaceAll("/", ".");
// Create working directory
String tmpDirPath = properties.get(EnumJobMapReduceParameter.LOCAL_TMP_PATH.getValue());
if (StringUtils.isBlank(tmpDirPath)) {
tmpDirPath = System.getProperty(PROPERTY_TMP_DIRECTORY);
}
File tmpDir = new File(tmpDirPath);
ensureDirectory(tmpDir);
final File workDir;
try {
workDir = File.createTempFile("yarn-mapreduce-", "", tmpDir);
} catch (IOException ioe) {
throw new Exception(String.format("Error creating temp dir in java.io.tmpdir %s due to %s.", tmpDir, ioe.getMessage()));
}
if (!workDir.delete()) {
throw new Exception("Delete failed for " + workDir);
}
ensureDirectory(workDir);
// Extract all files to the working directory
unJar(file, workDir);
// Get external libraries directory
File libDir = null;
if (ensureParameter(properties, EnumJobMapReduceParameter.LOCAL_LIB_PATH.getValue(), "Lib path is not set", false)) {
libDir = new File(properties.get(EnumJobMapReduceParameter.LOCAL_LIB_PATH.getValue()));
ensureDirectory(libDir);
}
// Copy job files
copyLocalFilesToHdfs(properties);
// Create class loader and submit job
final ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
URLClassLoader loader = null;
Class<?> mainClass = null;
Method main = null;
try {
// Set arguments
List<String> arguments = new ArrayList<>();
for (String key : properties.keySet()) {
switch (EnumJobMapReduceParameter.fromString(key)) {
case JAR_NAME:
// Ignore JAR file name
break;
case MAIN_CLASS_NAME:
// Ignore Main Class name
break;
default:
arguments.add(key + "=" + properties.get(key));
break;
}
}
// Initialize class loader and execute application
loader = createClassLoader(file, libDir, workDir);
Thread.currentThread().setContextClassLoader(loader);
logCommand(jarFilename, mainClassName, arguments);
// Invoke job
mainClass = Class.forName(mainClassName, true, loader);
main = mainClass.getMethod("main", new Class[] { Array.newInstance(String.class, 0).getClass() });
main.invoke(null, new Object[] { arguments.toArray(new String[0]) });
} catch (InvocationTargetException e) {
throw e.getTargetException();
} finally {
// Reset class loader
Thread.currentThread().setContextClassLoader(originalClassLoader);
// Delete temporary files and release resources
FileUtils.deleteQuietly(workDir);
main = null;
mainClass = null;
if (loader != null) {
loader.close();
}
loader = null;
Runtime.getRuntime().gc();
}
// TODO : Cleanup working directory (both local and HDFS one)
}
/**
* Extract JAR file.
*
* @param jarFile the jar file.
* @param toDir the path where to extract files.
* @throws IOException if an I/O exception occurs.
*/
private void unJar(File jarFile, File toDir) throws IOException {
unJar(jarFile, toDir, MATCH_ANY);
}
/**
* Extract JAR file.
*
* @param jarFile the jar file.
* @param toDir the path where to extract files.
* @param unpackRegex pattern for selecting files to extract.
* @throws IOException if an I/O exception occurs.
*/
private void unJar(File jarFile, File toDir, Pattern unpackRegex) throws IOException {
JarFile jar = new JarFile(jarFile);
try {
Enumeration<JarEntry> entries = jar.entries();
while (entries.hasMoreElements()) {
final JarEntry entry = entries.nextElement();
if (!entry.isDirectory() && unpackRegex.matcher(entry.getName()).matches()) {
InputStream in = jar.getInputStream(entry);
try {
File file = new File(toDir, entry.getName());
ensureDirectory(file.getParentFile());
OutputStream out = new FileOutputStream(file);
try {
IOUtils.copyBytes(in, out, 8192);
} finally {
out.close();
}
} finally {
in.close();
}
}
}
} finally {
jar.close();
}
}
/**
* Creates a directory.
*
* @param dir the directory to create.
* @throws IOException if an I/O exception occurs.
*/
private void ensureDirectory(File dir) throws IOException {
if (!dir.mkdirs() && !dir.isDirectory()) {
throw new IOException("Mkdirs failed to create " + dir.toString());
}
}
/**
* Creates a class loader. The application jar as well as the contents of
* the working directory are added to the classpath. If external libraries
* are declared, they are copied to the working directory and added to the
* classpath too.
*
* @param file the job jar file.
* @param libDir the local path with external jar files to add to the
* classpath.
* @param workDir the currently working directory.
* @return the initialized {@link ClassLoader}.
*
* @throws MalformedURLException if a path is malformed.
* @throws IOException if an I/O operation fails.
*/
private URLClassLoader createClassLoader(File file, final File libDir, final File workDir) throws MalformedURLException, IOException {
List<URL> classPath = new ArrayList<URL>();
classPath.add(file.toURI().toURL());
classPath.add(new File(workDir + "/").toURI().toURL());
classPath.add(new File(workDir, "classes/").toURI().toURL());
if (libDir != null) {
transferJarsToWorkingDir(libDir, new File(workDir, "lib"));
File[] libs = new File(workDir, "lib").listFiles();
if (libs != null) {
for (int i = 0; i < libs.length; i++) {
classPath.add(libs[i].toURI().toURL());
}
}
}
return new URLClassLoader(classPath.toArray(new URL[0]));
}
/**
* Copies the contents of a directory to another one.
*
* @param source the source directory.
* @param target the target directory.
* @throws IOException if an I/O exception occurs.
*/
private void transferJarsToWorkingDir(File source, File target) throws IOException {
try {
FileUtils.copyDirectory(source, target);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Copies local files to a temporary HDFS path. Two sets of files are
* optionally copied (a) files that are available at HDFS and (b) files that
* are available at HDFS but also cached on every YARN node and accessible
* using symbolic links.
*
* the job configuration properties.
* @throws IOException if an I/O exception occurs.
*/
private void copyLocalFilesToHdfs(Map<String, String> properties) throws IOException {
// Create random base path
String basePath = Paths.get(properties.get(EnumJobMapReduceParameter.HDFS_TMP_PATH.getValue()),
RandomStringUtils.randomAlphanumeric(8)).toString();
// Update temporary HDFS path
properties.put(EnumJobMapReduceParameter.HDFS_TMP_PATH.getValue(), basePath);
// Copy files to HDFS. These files are accessible from HDFS.
String localFilePath = properties.get(EnumJobMapReduceParameter.LOCAL_FILE_PATH.getValue());
String hdfsFilePath = properties.get(EnumJobMapReduceParameter.HDFS_FILE_PATH.getValue());
if (StringUtils.isBlank(hdfsFilePath)) {
hdfsFilePath = Paths.get(basePath, "files").toString();
}
copyFilesToHdfs(properties, localFilePath, hdfsFilePath);
// Update parameter of the HDFS path in order to include the random base path.
properties.put(EnumJobMapReduceParameter.HDFS_FILE_PATH.getValue(), hdfsFilePath);
// Copy files from cache to HDFS. These files will be accessible locally on every YARN node.
String localCachePath = properties.get(EnumJobMapReduceParameter.LOCAL_CACHE_PATH.getValue());
String hdfsCachePath = properties.get(EnumJobMapReduceParameter.HDFS_CACHE_PATH.getValue());
if (StringUtils.isBlank(hdfsCachePath)) {
hdfsCachePath = Paths.get(basePath, "cache").toString();
}
copyFilesToHdfs(properties, localCachePath, hdfsCachePath);
// Update parameter of the HDFS path in order to include the random base path.
properties.put(EnumJobMapReduceParameter.HDFS_CACHE_PATH.getValue(), hdfsCachePath);
}
private void copyFilesToHdfs(Map<String, String> properties, String source, String target) throws IOException {
if (!StringUtils.isBlank(source)) {
Set<File> files = collectFilesFromLocalDir(source);
if (!files.isEmpty()) {
System.err.println(String.format("Copying [%d] files from local dir [%s] to HDFS dir [%s] at [%s]",
files.size(),
source,
target,
properties.get(EnumHadoopParameter.HDFS_PATH.getValue())));
Configuration conf = new Configuration();
conf.set(EnumHadoopParameter.HDFS_PATH.getValue(), properties.get(EnumHadoopParameter.HDFS_PATH.getValue()));
FileSystem hdfsFileSystem = FileSystem.get(conf);
for (File file : files) {
Path localJarPath = new Path(file.toURI());
Path hdfsJarPath = new Path(target, file.getName());
hdfsFileSystem.copyFromLocalFile(false, true, localJarPath, hdfsJarPath);
}
}
}
}
/**
* Returns a set of all files in the given path.
*
* @param localPath the local path.
* @return a set of files.
* @throws IllegalArgumentException if {@code localPath} does not exist.
*/
private Set<File> collectFilesFromLocalDir(String localPath) throws IllegalArgumentException {
File path = new File(localPath);
if (!path.isDirectory()) {
throw new IllegalArgumentException(String.format("Path points to file, not directory: %s", localPath));
}
Set<File> files = new HashSet<File>();
for (File file : path.listFiles()) {
if (file.exists() && !file.isDirectory()) {
files.add(file);
}
}
return files;
}
/**
* Logs the command alternative for executing the job from the command line.
*
* @param jar the MapReduce job jar.
* @param main the main class to initialize.
* @param arguments the arguments to use.
*/
private void logCommand(String jar, String main, List<String> arguments) {
StringBuilder text = new StringBuilder();
text.append(String.format("bin/hadoop jar %s \\", jar));
text.append(System.lineSeparator());
text.append(String.format("%s \\", main));
text.append(System.lineSeparator());
if (!arguments.isEmpty()) {
for (int index = 0, count = arguments.size() - 1; index < count; index++) {
text.append(String.format("\"%s\" \\", arguments.get(index)));
text.append(System.lineSeparator());
}
text.append(String.format("%s", arguments.get(arguments.size() - 1)));
}
logger.info(text.toString());
}
}
| 37.485777 | 138 | 0.606094 |
b5dea5b50444439743481ee1c90eaad13ed8f5ca | 8,347 | package no.sb1.troxy.record.v2;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import no.sb1.troxy.http.common.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A templated Response, used for creating a Response to the client.
* @deprecated Use v3 instead
*/
@Deprecated
public class ResponseTemplate extends Response {
/**
* Logger for this class.
*/
private static final Logger log = LoggerFactory.getLogger(ResponseTemplate.class);
/**
* A regular expression used to escape characters that can be mistaken as the character used to denote a variable.
*/
private static final Pattern ESCAPE_VARIABLE_PREFIX_PATTERN = Pattern.compile("(\\$)");
/**
* The original response for this ResponseTemplate.
* This is the response from the server when first creating a recording.
* This value should under normal circumstances never be modified.
*/
private Response originalResponse;
/**
* A list of static text and variables used for the code field.
*/
private List<Entry> code;
/**
* A list of static text and variables used for the header field.
*/
private List<Entry> header;
/**
* A list of static text and variables used for the content field.
*/
private List<Entry> content;
/**
* Empty constructor, needed to create a ResponseTemplate object from a serialized (XML) state.
*/
public ResponseTemplate() {
}
/**
* Constructor that creates a ResponseTemplate from a Response by escaping characters used to denote a variable.
* @param response The Response to create this ResponseTemplate from.
*/
public ResponseTemplate(Response response) {
setOriginalResponse(response);
setCode(escape(response.getCode()));
setHeader(escape(response.getHeader()));
setContent(escape(response.getContent()));
}
/**
* Create a Response from this template.
* @param variables Map of keys and values to be inserted into the response.
* @return A Response from this template.
*/
public Response createResponse(Map<String, Matcher> variables) {
if (code == null) {
code = createArray(getCode());
header = createArray(getHeader());
content = createArray(getContent());
}
Response response = new Response();
response.setCode(createString(code, variables));
response.setHeader(createString(header, variables));
response.setContent(createString(content, variables));
return response;
}
/**
* Get the original response.
* @return The original response.
*/
public Response getOriginalResponse() {
return originalResponse;
}
/**
* Set the original response.
* @param originalResponse The original response.
*/
public void setOriginalResponse(Response originalResponse) {
this.originalResponse = originalResponse;
}
/**
* Escape characters that may be mistaken as a variable.
* @param text The text to be escaped.
* @return An escaped version of the given text.
*/
public static String escape(String text) {
if (text == null)
return null;
return ESCAPE_VARIABLE_PREFIX_PATTERN.matcher(text).replaceAll("$1$1");
}
/**
* Helper method to split up a templated text into a list of static text and variables.
* @param text The templated text.
* @return An array of static text and variables.
*/
private List<Entry> createArray(String text) {
List<Entry> entries = new ArrayList<>();
int index = 0;
int previousIndex = 0;
boolean detectVariable = false;
log.debug("Creating Entry array from text: {}", text);
while ((index = text.indexOf('$', index)) >= 0) {
int charCount = 1;
while (++index < text.length() && text.charAt(index) == '$')
++charCount;
if (charCount % 2 == 0) {
/* escaped character */
continue;
}
index -= detectVariable ? charCount : 1;
Entry entry = new Entry(detectVariable, text.substring(previousIndex, index));
log.debug("Adding {} to array: {}", entry.isVariable() ? "variable" : "static text", entry.getText());
entries.add(entry);
detectVariable = !detectVariable;
previousIndex = ++index;
}
Entry entry = new Entry(false, text.substring(previousIndex));
log.debug("Adding {} to array: {}", entry.isVariable() ? "variable" : "static text", entry.getText());
entries.add(entry);
return entries;
}
/**
* Helper method to build up code, header or content.
* @param entries The entries to build this String from.
* @param variables The variables to insert into the String.
* @return A String for code, header or content where variables are replaced by values.
*/
private String createString(List<Entry> entries, Map<String, Matcher> variables) {
StringBuilder sb = new StringBuilder();
log.debug("Building String from Entry array");
for (Entry entry : entries) {
String text = null;
if (entry.isVariable()) {
String variable = entry.getText();
int colonIndex = variable.indexOf(':');
if (colonIndex > 0) {
/* field specified */
text = getVariable(variables.get(variable.substring(0, colonIndex).toUpperCase()), variable.substring(colonIndex + 1));
} else {
/* field not specified, have to go through all */
for (String key : variables.keySet()) {
text = getVariable(variables.get(key.toUpperCase()), variable);
if (text != null)
break;
}
}
log.info("Inserting value for variable \"{}\": {}", variable, text);
} else {
text = entry.getText();
log.debug("Inserting static text: {}", text);
}
sb.append(text);
}
return sb.toString();
}
/**
* Get value of variable from matcher.
* @param matcher Matcher to retrieve variable value from.
* @param variable Name (or index) of variable value to retrieve.
* @return Value of variable, or null if not found.
*/
private String getVariable(Matcher matcher, String variable) {
if (matcher == null)
return null;
try {
return matcher.group(variable);
} catch (Exception e) {
/* may be integer instead of named group */
try {
return matcher.group(Integer.parseInt(variable));
} catch (Exception e2) {
/* apparently not, fall though and return null */
}
}
return null;
}
/**
* An Entry is either static text or a variable.
* When the variable is set then the text is the key used to find the value of the variable.
*/
private class Entry {
/**
* Whether this Entry is a variable.
*/
private boolean variable;
/**
* Either static text or the key for the variable.
*/
private String text;
/**
* Default constructor, sets both values.
* @param variable Whether the entry is a variable.
* @param text Static text of key for variable.
*/
public Entry(boolean variable, String text) {
this.variable = variable;
this.text = variable ? text : text.replace("$$", "$");
}
/**
* Getter for variable.
* @return Returns true if Entry is variable, false otherwise.
*/
public boolean isVariable() {
return variable;
}
/**
* Getter for text.
* @return The static text or the key for the variable.
*/
public String getText() {
return text;
}
}
}
| 35.071429 | 139 | 0.587037 |
67ad6c32a17c17cc10f2549ec29b2f5735e72da7 | 629 | package com.jyg.gameserver.queue;
/**
* created by jiayaoguang at 2018年5月26日
*/
class Data {
private final long squenceId;
private long timeMills;
private Object content;
public Data() {
squenceId = 0L;
timeMills = System.currentTimeMillis();
}
public Object getContent() {
return content;
}
public void setContent(Object content) {
this.content = content;
}
public long getTimeMills() {
return timeMills;
}
public void init(Object content) {
this.content = content;
this.timeMills = System.currentTimeMillis();
}
public void clean() {
this.content = null;
this.timeMills = -1;
}
}
| 15.725 | 46 | 0.691574 |
ea0ea06633b54c68943da122be22e0a1021bafb1 | 443 | /**
* An app built in JavaFX to graphically simulate the Three-Body Problem in classical mechanics.
*/
module threebodysimulation {
requires javafx.controls;
requires javafx.fxml;
requires commons.math3;
requires commons.csv;
requires java.desktop;
requires org.kordamp.ikonli.javafx;
requires org.kordamp.ikonli.material;
opens stl.threebodysimulation to javafx.fxml;
exports stl.threebodysimulation;
} | 27.6875 | 96 | 0.744921 |
39e5db2e21e239a8ac15ed41658f30aa11b167c2 | 3,301 | /*
* Maintained by brightSPARK Labs.
* www.brightsparklabs.com
*
* Refer to LICENSE at repository root for license details.
*/
package com.brightsparklabs.asanti.decoder.builtin;
import static com.google.common.base.Preconditions.*;
import com.brightsparklabs.asanti.common.DecodeExceptions;
import com.brightsparklabs.asanti.common.OperationResult;
import com.brightsparklabs.asanti.decoder.AsnByteDecoder;
import com.brightsparklabs.asanti.exception.DecodeException;
import com.brightsparklabs.asanti.model.data.AsantiAsnData;
import com.brightsparklabs.asanti.schema.AsnBuiltinType;
import com.brightsparklabs.asanti.validator.AsnByteValidator;
import com.brightsparklabs.asanti.validator.builtin.EnumeratedValidator;
import com.brightsparklabs.asanti.validator.failure.ByteValidationFailure;
import com.brightsparklabs.asanti.validator.failure.DecodedTagValidationFailure;
import com.google.common.collect.ImmutableSet;
/**
* Decoder for data of type {@link AsnBuiltinType#Enumerated}
*
* @author brightSPARK Labs
*/
public class EnumeratedDecoder extends AbstractBuiltinTypeDecoder<String> {
// -------------------------------------------------------------------------
// INSTANCE VARIABLES
// -------------------------------------------------------------------------
/** singleton instance */
private static EnumeratedDecoder instance;
// -------------------------------------------------------------------------
// CONSTRUCTION
// -------------------------------------------------------------------------
/**
* Default constructor.
*
* <p>This is private, use {@link #getInstance()} to obtain an instance
*/
private EnumeratedDecoder() {}
/**
* Returns a singleton instance of this class
*
* @return a singleton instance of this class
*/
public static EnumeratedDecoder getInstance() {
if (instance == null) {
instance = new EnumeratedDecoder();
}
return instance;
}
// -------------------------------------------------------------------------
// IMPLEMENTATION: AbstractBuiltinTypeDecoder
// -------------------------------------------------------------------------
@Override
public String decode(final byte[] bytes) throws DecodeException {
final ImmutableSet<ByteValidationFailure> failures =
AsnByteValidator.validateAsEnumerated(bytes);
DecodeExceptions.throwIfHasFailures(failures);
return AsnByteDecoder.decodeAsInteger(bytes).toString();
}
@Override
public String decode(final String tag, final AsantiAsnData asnData) throws DecodeException {
checkNotNull(tag);
checkNotNull(asnData);
final OperationResult<String, ImmutableSet<DecodedTagValidationFailure>> result =
EnumeratedValidator.getInstance().validateAndDecode(tag, asnData);
if (!result.wasSuccessful()) {
DecodeExceptions.throwIfHasFailures(
result.getFailureReason().orElse(ImmutableSet.of()));
}
return result.getOutput();
}
@Override
public String decodeAsString(final String tag, final AsantiAsnData asnData)
throws DecodeException {
return decode(tag, asnData);
}
}
| 35.494624 | 96 | 0.615874 |
76410135f1e9c4e90e78b123a45f68b294fafe86 | 3,244 | /*******************************************************************************
* Copyright 2017 The MITRE Corporation
* and the MIT Internet Trust Consortium
*
* 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.mitre.openid.connect.service.impl;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mitre.openid.connect.model.WhitelistedSite;
import org.mitre.openid.connect.repository.WhitelistedSiteRepository;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
/**
* @author wkim
*
*/
@RunWith(MockitoJUnitRunner.class)
public class TestDefaultWhitelistedSiteService {
@Mock
private WhitelistedSiteRepository repository;
@InjectMocks
private DefaultWhitelistedSiteService service;
@Before
public void prepare() {
Mockito.reset(repository);
}
@Test(expected = IllegalArgumentException.class)
public void saveNew_notNullId() {
WhitelistedSite site = Mockito.mock(WhitelistedSite.class);
Mockito.when(site.getId()).thenReturn(12345L); // arbitrary long value
service.saveNew(site);
}
@Test
public void saveNew_success() {
WhitelistedSite site = Mockito.mock(WhitelistedSite.class);
Mockito.when(site.getId()).thenReturn(null);
service.saveNew(site);
Mockito.verify(repository).save(site);
}
@Test
public void update_nullSites() {
WhitelistedSite oldSite = Mockito.mock(WhitelistedSite.class);
WhitelistedSite newSite = Mockito.mock(WhitelistedSite.class);
// old client null
try {
service.update(null, newSite);
fail("Old site input is null. Expected a IllegalArgumentException.");
} catch (IllegalArgumentException e) {
assertThat(e, is(notNullValue()));
}
// new client null
try {
service.update(oldSite, null);
fail("New site input is null. Expected a IllegalArgumentException.");
} catch (IllegalArgumentException e) {
assertThat(e, is(notNullValue()));
}
// both clients null
try {
service.update(null, null);
fail("Both site inputs are null. Expected a IllegalArgumentException.");
} catch (IllegalArgumentException e) {
assertThat(e, is(notNullValue()));
}
}
@Test
public void update_success() {
WhitelistedSite oldSite = Mockito.mock(WhitelistedSite.class);
WhitelistedSite newSite = Mockito.mock(WhitelistedSite.class);
service.update(oldSite, newSite);
Mockito.verify(repository).update(oldSite, newSite);
}
}
| 28.45614 | 81 | 0.717324 |
0abf0f308ba05ce329388c90fa068514f890fff4 | 786 | package ru.roborox.itunesconnect.api.analytics.model;
import java.util.Arrays;
import java.util.List;
public class ApiList<T> {
private int size;
private List<T> results;
public ApiList() {
}
public ApiList(int size, T... results) {
this.size = size;
this.results = Arrays.asList(results);
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public List<T> getResults() {
return results;
}
public void setResults(List<T> results) {
this.results = results;
}
@Override
public String toString() {
if (results != null) {
return results.toString();
} else {
return "[]";
}
}
}
| 18.27907 | 53 | 0.55598 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.