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 |
|---|---|---|---|---|---|
9202ca686af04415ed8cd7797fe4e1316648bd52 | 5,131 | /*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*/
package com.microsoft.azure.maven.auth;
import com.microsoft.azure.maven.exception.MavenDecryptException;
import com.microsoft.azure.maven.model.MavenAuthConfiguration;
import com.microsoft.azure.toolkit.lib.auth.exception.InvalidConfigurationException;
import org.apache.commons.lang3.StringUtils;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.settings.Server;
import org.apache.maven.settings.building.SettingsProblem;
import org.apache.maven.settings.crypto.DefaultSettingsDecryptionRequest;
import org.apache.maven.settings.crypto.SettingsDecrypter;
import org.apache.maven.settings.crypto.SettingsDecryptionRequest;
import org.apache.maven.settings.crypto.SettingsDecryptionResult;
import org.codehaus.plexus.util.xml.Xpp3Dom;
import java.util.Objects;
public class MavenSettingHelper {
/**
* Build maven auth configuration from serverId.
*
* @param session the maven session
* @param settingsDecrypter the decrypter
* @param serverId the server id
* @return the auth configuration
* @throws MavenDecryptException when there are errors decrypting maven generated password
* @throws InvalidConfigurationException where are any illegal configurations
*/
public static MavenAuthConfiguration buildAuthConfigurationByServerId(MavenSession session, SettingsDecrypter settingsDecrypter, String serverId)
throws InvalidConfigurationException, MavenDecryptException {
if (StringUtils.isBlank(serverId)) {
throw new IllegalArgumentException("Parameter 'serverId' cannot be null or empty.");
}
final Server server = session.getSettings().getServer(serverId);
if (server == null) {
throw new InvalidConfigurationException(String.format("serverId '%s' cannot be found in maven settings.xml.", serverId));
}
final MavenAuthConfiguration configurationFromServer = new MavenAuthConfiguration();
final Xpp3Dom configuration = (Xpp3Dom) server.getConfiguration();
configurationFromServer.setServerId(serverId);
if (configuration == null) {
return configurationFromServer;
}
configurationFromServer.setTenant(getPropertyValue(configuration, "tenant"));
configurationFromServer.setClient(getPropertyValue(configuration, "client"));
final String rawKey = getPropertyValue(configuration, "key");
configurationFromServer.setKey(isPropertyEncrypted(rawKey) ? decryptMavenSettingProperty(settingsDecrypter, "key", rawKey) : rawKey);
configurationFromServer.setCertificate(getPropertyValue(configuration, "certificate"));
final String rawCertificatePassword = getPropertyValue(configuration, "certificatePassword");
configurationFromServer.setCertificatePassword(isPropertyEncrypted(rawCertificatePassword) ?
decryptMavenSettingProperty(settingsDecrypter, "certificatePassword", rawCertificatePassword) :
rawCertificatePassword);
configurationFromServer.setEnvironment(getPropertyValue(configuration, "environment"));
configurationFromServer.setServerId(serverId);
return configurationFromServer;
}
/**
* Get string value from server configuration section in settings.xml.
*
* @param configuration the <code>Xpp3Dom</code> object representing the configuration in <server>.
* @param property the property name
* @return String value if property exists; otherwise, return null.
*/
private static String getPropertyValue(final Xpp3Dom configuration, final String property) {
final Xpp3Dom node = configuration.getChild(property);
return Objects.isNull(node) ? null : node.getValue();
}
private static boolean isPropertyEncrypted(String value) {
return value != null && value.startsWith("{") && value.endsWith("}");
}
private static String decryptMavenSettingProperty(SettingsDecrypter settingsDecrypter, String propertyName, String value) throws MavenDecryptException {
final Server server = new Server();
server.setPassword(value);
final SettingsDecryptionRequest request = new DefaultSettingsDecryptionRequest(server);
final SettingsDecryptionResult result = settingsDecrypter.decrypt(request);
for (final SettingsProblem problem : result.getProblems()) {
if (problem.getSeverity() == SettingsProblem.Severity.ERROR || problem.getSeverity() == SettingsProblem.Severity.FATAL) {
// for java 8+, it is ok to use operator '+' for string concatenation
throw new MavenDecryptException(String.format("Unable to decrypt property(%s), value(%s) from maven settings.xml due to error: %s",
propertyName, value, problem));
}
}
return result.getServer().getPassword();
}
private MavenSettingHelper() {
}
}
| 52.357143 | 156 | 0.732606 |
dca1b90d5aa584ae55d5f1c36b0347e00f63fafc | 3,489 | package prefuse.controls;
import java.awt.Cursor;
import java.awt.event.MouseEvent;
import java.awt.geom.Point2D;
import java.util.Iterator;
import javax.swing.SwingUtilities;
import prefuse.Display;
import prefuse.visual.NodeItem;
import prefuse.visual.VisualItem;
/**
* Control that changes the location of a whole subtree when dragged on screen.
* This is similar to the {@link DragControl DragControl} class, except that it
* moves the entire visible subtree rooted at an item, rather than just the
* item itself.
*
* @author <a href="http://jheer.org">jeffrey heer</a>
*/
public class SubtreeDragControl extends ControlAdapter {
private Point2D down = new Point2D.Double();
private Point2D tmp = new Point2D.Double();
private boolean wasFixed;
/**
* Creates a new subtree drag control that issues repaint requests as an
* item is dragged.
*/
public SubtreeDragControl() {
}
/**
* @see prefuse.controls.Control#itemEntered(prefuse.visual.VisualItem, java.awt.event.MouseEvent)
*/
public void itemEntered(VisualItem item, MouseEvent e) {
if ( !(item instanceof NodeItem) ) return;
Display d = (Display)e.getSource();
d.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
}
/**
* @see prefuse.controls.Control#itemExited(prefuse.visual.VisualItem, java.awt.event.MouseEvent)
*/
public void itemExited(VisualItem item, MouseEvent e) {
if ( !(item instanceof NodeItem) ) return;
Display d = (Display)e.getSource();
d.setCursor(Cursor.getDefaultCursor());
}
/**
* @see prefuse.controls.Control#itemPressed(prefuse.visual.VisualItem, java.awt.event.MouseEvent)
*/
public void itemPressed(VisualItem item, MouseEvent e) {
if (!SwingUtilities.isLeftMouseButton(e)) return;
if ( !(item instanceof NodeItem) ) return;
Display d = (Display)e.getComponent();
down = d.getAbsoluteCoordinate(e.getPoint(), down);
wasFixed = item.isFixed();
item.setFixed(true);
}
/**
* @see prefuse.controls.Control#itemReleased(prefuse.visual.VisualItem, java.awt.event.MouseEvent)
*/
public void itemReleased(VisualItem item, MouseEvent e) {
if (!SwingUtilities.isLeftMouseButton(e)) return;
if ( !(item instanceof NodeItem) ) return;
item.setFixed(wasFixed);
}
/**
* @see prefuse.controls.Control#itemDragged(prefuse.visual.VisualItem, java.awt.event.MouseEvent)
*/
public void itemDragged(VisualItem item, MouseEvent e) {
if (!SwingUtilities.isLeftMouseButton(e)) return;
if ( !(item instanceof NodeItem) ) return;
Display d = (Display)e.getComponent();
tmp = d.getAbsoluteCoordinate(e.getPoint(), tmp);
double dx = tmp.getX()-down.getX();
double dy = tmp.getY()-down.getY();
updateLocations((NodeItem)item, dx, dy);
down.setLocation(tmp);
item.getVisualization().repaint();
}
private void updateLocations(NodeItem n, double dx, double dy) {
double x = n.getX(), y = n.getY();
n.setStartX(x); n.setStartY(y);
x += dx; y += dy;
n.setX(x); n.setY(y);
n.setEndX(x); n.setEndY(y);
Iterator children = n.children();
while ( children.hasNext() )
updateLocations((NodeItem)children.next(), dx, dy);
}
} // end of class SubtreeDragControl
| 33.873786 | 103 | 0.650616 |
92a3c5c44ef445b0a257e7fa5ac720427f266927 | 1,056 | package com.wisdom.acm.szxm.form.sysscore;
import lombok.Data;
import org.hibernate.validator.constraints.Range;
import javax.validation.constraints.NotBlank;
import java.math.BigDecimal;
/**
* Author:wqd
* Date:2020-01-02 14:00
* Description:<描述>
*/
@Data
public class ObjectTemplateAddForm {
/**
* 考核项名称
*/
@NotBlank(message = "考核项名称不能为空")
private String checkTitle;
/**
* 主项最大分
*/
@Range(max = 100, min = 0, message = "主项最大分需在0-100之间")
private Integer maxScore;
/**
* 主项最小分
*/
@Range(max = 100, min = 0, message = "主项最小分需在0-100之间")
private Integer minScore;
/**
* 考核项编码(每一项的编码)
*/
@NotBlank(message = "考核项编码不能为空")
private String itemCode;
/**
* 考核主项(主项0,细项1)
*/
@NotBlank(message = "是否为考核主项不能为空")
private String mainItem;
/**
* 细项所属考核项id 为细项时 该数据不能为空
*/
private Integer checkItemId;
/**
* 扣分标准
*/
@Range(max = 100, min = 0, message = "扣分标准需在0-100之间")
private BigDecimal deductionStandard;
}
| 18.857143 | 58 | 0.604167 |
5609f3b7b36619ea3af7401e5c2ee4272e935e27 | 4,374 | package gov.nih.nci.ncicb.cadsr.common.persistence.dao.jdbc;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import org.springframework.jdbc.object.MappingSqlQuery;
import gov.nih.nci.ncicb.cadsr.common.dto.DataElementTransferObject;
import gov.nih.nci.ncicb.cadsr.common.dto.QuestionTransferObject;
import gov.nih.nci.ncicb.cadsr.common.dto.ValueDomainV2TransferObject;
import gov.nih.nci.ncicb.cadsr.common.resource.Question;
public class JDBCModuleQuestionsDAO
{
public JDBCModuleQuestionsDAO() {
super();
// TODO Auto-generated constructor stub
}
class QuestionsInAModuleQuery extends MappingSqlQuery
{
public void _setSql(String idSeq)
{
super.setSql((new StringBuilder()).append("SELECT a.*, b.EDITABLE_IND, b.QC_ID, c.RULE, d.PREFERRED_NAME as DE_SHORT_NAME, d.PREFERRED_DEFINITION as DE_PREFERRED_DEFINITION, "
+ "d.CREATED_BY as DE_CREATED_BY, b.DATE_CREATED as QUESTION_DATE_CREATED, b.DATE_MODIFIED as QUESTION_DATE_MODIFIED, e.NAME as DE_CONTEXT_NAME "
+ "FROM SBREXT.FB_QUESTIONS_VIEW a, CABIO31_QUESTIONS_VIEW b, COMPLEX_DATA_ELEMENTS_VIEW c, SBR.DATA_ELEMENTS_VIEW d, SBR.CONTEXTS_VIEW e where a.MODULE_IDSEQ = '")
.append(idSeq).append("' and a.ques_idseq=b.QC_IDSEQ and b.DE_IDSEQ = c.P_DE_IDSEQ(+) and b.de_idseq = d.de_idseq(+) and d.CONTE_IDSEQ = e.CONTE_IDSEQ(+)").toString());
}
protected Object mapRow(ResultSet rs, int rownum)
throws SQLException
{
Question question = new QuestionTransferObject();
question.setQuesIdseq(rs.getString("QUES_IDSEQ"));
question.setLongName(rs.getString("LONG_NAME"));
question.setDisplayOrder(rs.getInt("DISPLAY_ORDER"));
question.setAslName(rs.getString("WORKFLOW"));
question.setPreferredDefinition(rs.getString("DEFINITION"));
question.setMandatory("Yes".equalsIgnoreCase(rs.getString("MANDATORY_IND")));
question.setPublicId(rs.getInt("QC_ID"));
question.setVersion(new Float(rs.getFloat("VERSION")));
question.setDateCreated(rs.getTimestamp("QUESTION_DATE_CREATED"));
question.setDateModified(rs.getTimestamp("QUESTION_DATE_MODIFIED"));
String editableInd = rs.getString("EDITABLE_IND");
boolean editable = editableInd == null || editableInd.trim().equals("") || editableInd.equalsIgnoreCase("Yes");
question.setEditable(editable);
String derivRule = rs.getString("RULE");
if(derivRule != null && !derivRule.trim().equals(""))
question.setDeDerived(true);
else
question.setDeDerived(false);
String deIdSeq = rs.getString("DE_IDSEQ");
if(deIdSeq != null)
{
DataElementTransferObject dataElementTransferObject = new DataElementTransferObject();
dataElementTransferObject.setDeIdseq(deIdSeq);
dataElementTransferObject.setLongCDEName(rs.getString(15));
dataElementTransferObject.setVersion(new Float(rs.getFloat(16)));
dataElementTransferObject.setLongName(rs.getString(17));
dataElementTransferObject.setCDEId(Integer.toString(rs.getInt(18)));
dataElementTransferObject.setAslName(rs.getString("DE_WORKFLOW"));
dataElementTransferObject.setPreferredName(rs.getString("DE_SHORT_NAME"));
dataElementTransferObject.setPreferredDefinition(rs.getString("DE_PREFERRED_DEFINITION"));
dataElementTransferObject.setCreatedBy(rs.getString("DE_CREATED_BY"));
dataElementTransferObject.setContextName(rs.getString("DE_CONTEXT_NAME"));
question.setDataElement(dataElementTransferObject);
ValueDomainV2TransferObject valueDomainV2TransferObject = new ValueDomainV2TransferObject();
valueDomainV2TransferObject.setVdIdseq(rs.getString(19));
dataElementTransferObject.setValueDomain(valueDomainV2TransferObject);
}
return question;
}
QuestionsInAModuleQuery()
{
super();
}
}
public Collection getQuestionsInAModuleV2(String moduleId)
{
QuestionsInAModuleQuery query = new QuestionsInAModuleQuery();
try {
javax.naming.Context ic = new InitialContext();
DataSource ds = (DataSource) ic.lookup("java:comp/env/jdbc/FormBuilderDS");
query.setDataSource(ds);
} catch (NamingException e) {
System.out.println("Error in fetching DataSource: ");
e.printStackTrace();
}
query._setSql(moduleId);
return query.execute();
}
}
| 42.466019 | 178 | 0.763832 |
2da093c87558a6cb1e40509331083f55d025a859 | 33,622 | /*
* MIT LICENSE
* Copyright 2000-2021 Simplified Logic, Inc
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions: The above copyright
* notice and this permission notice shall be included in all copies or
* substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS",
* WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
* TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
* CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.simplifiedlogic.nitro.jshell.json.help;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.simplifiedlogic.nitro.jlink.DataUtils;
import com.simplifiedlogic.nitro.jlink.data.DimDetailData;
import com.simplifiedlogic.nitro.jlink.data.DimToleranceData;
import com.simplifiedlogic.nitro.jshell.json.request.JLDimensionRequestParams;
import com.simplifiedlogic.nitro.jshell.json.response.JLDimensionResponseParams;
import com.simplifiedlogic.nitro.jshell.json.template.FunctionArgument;
import com.simplifiedlogic.nitro.jshell.json.template.FunctionExample;
import com.simplifiedlogic.nitro.jshell.json.template.FunctionObject;
import com.simplifiedlogic.nitro.jshell.json.template.FunctionReturn;
import com.simplifiedlogic.nitro.jshell.json.template.FunctionSpec;
import com.simplifiedlogic.nitro.jshell.json.template.FunctionTemplate;
/**
* Generate help doc for "dimension" functions
*
* @author Adam Andrews
*
*/
public class JLJsonDimensionHelp extends JLJsonCommandHelp implements JLDimensionRequestParams, JLDimensionResponseParams {
public static final String OBJ_DIM_DATA = "DimData";
public static final String OBJ_DIM_DETAIL_DATA = "DimDetailData";
public static final String OBJ_DIM_SELECT_DATA = "DimSelectData";
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jshell.json.help.JLJsonCommandHelp#getCommand()
*/
public String getCommand() {
return COMMAND;
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jshell.json.help.JLJsonCommandHelp#getHelp()
*/
public List<FunctionTemplate> getHelp() {
List<FunctionTemplate> list = new ArrayList<FunctionTemplate>();
list.add(helpCopy());
list.add(helpList());
list.add(helpListDetail());
list.add(helpSet());
list.add(helpSetText());
list.add(helpShow());
list.add(helpUserSelect());
return list;
}
/* (non-Javadoc)
* @see com.simplifiedlogic.nitro.jshell.json.help.JLJsonCommandHelp#getHelpObjects()
*/
public List<FunctionObject> getHelpObjects() {
List<FunctionObject> list = new ArrayList<FunctionObject>();
list.add(helpDimData());
list.add(helpDimDetailData());
list.add(helpDimSelectData());
return list;
}
private FunctionTemplate helpSet() {
FunctionTemplate template = new FunctionTemplate(COMMAND, FUNC_SET);
FunctionSpec spec = template.getSpec();
spec.setFunctionDescription("Set a dimension value");
spec.addFootnote("One reason to encode values is if the value contains special characters, such as Creo symbols.");
spec.addFootnote("You may be able to avoid Base64-encoding symbols by using Unicode for the binary characters, for example including \\u0001#\\u0002 in the "+PARAM_VALUE+" to insert a plus/minus symbol.");
FunctionArgument arg;
arg = new FunctionArgument(PARAM_MODEL, FunctionSpec.TYPE_STRING);
arg.setDescription("File name");
arg.setDefaultValue("The currently active model");
spec.addArgument(arg);
arg = new FunctionArgument(PARAM_NAME, FunctionSpec.TYPE_STRING);
arg.setDescription("Dimension name");
arg.setRequired(true);
spec.addArgument(arg);
arg = new FunctionArgument(PARAM_VALUE, FunctionSpec.TYPE_DEPEND);
arg.setDescription("Dimension value");
arg.setDefaultValue("Clears the dimension value if missing");
spec.addArgument(arg);
arg = new FunctionArgument(PARAM_ENCODED, FunctionSpec.TYPE_BOOL);
arg.setDescription("Whether the value is Base64-encoded");
arg.setDefaultValue("false");
spec.addArgument(arg);
FunctionExample ex;
ex = new FunctionExample();
ex.addInput(PARAM_MODEL, "box.prt");
ex.addInput(PARAM_NAME, "d3");
ex.addInput(PARAM_VALUE, 32.0);
ex.addInput(PARAM_ENCODED, false);
template.addExample(ex);
ex = new FunctionExample();
ex.addInput(PARAM_NAME, "RADIUS");
ex.addInput(PARAM_VALUE, 2.5);
ex.addInput(PARAM_ENCODED, false);
template.addExample(ex);
ex = new FunctionExample();
ex.addInput(PARAM_NAME, "ANGLE");
ex.addInput(PARAM_VALUE, "MzAgASQCCg==");
ex.addInput(PARAM_ENCODED, true);
template.addExample(ex);
return template;
}
private FunctionTemplate helpSetText() {
FunctionTemplate template = new FunctionTemplate(COMMAND, FUNC_SET_TEXT);
FunctionSpec spec = template.getSpec();
spec.setFunctionDescription("Set dimension text");
spec.addFootnote("If the text contains Creo Symbols or other non-ASCII text, you must Base64-encode the "+PARAM_TEXT+" and set "+PARAM_ENCODED+" to true.");
spec.addFootnote("You may be able to avoid Base64-encoding symbols by using Unicode for the binary characters, for example including \\u0001#\\u0002 in the "+PARAM_TEXT+" to insert a plus/minus symbol.");
spec.addFootnote("Embed newlines in the "+PARAM_TEXT+" for line breaks");
spec.addFootnote("Since J-Link does not support setting the Prefix or Suffix, you will need to include those in the "+PARAM_TEXT+" value if you need them.");
FunctionArgument arg;
arg = new FunctionArgument(PARAM_MODEL, FunctionSpec.TYPE_STRING);
arg.setDescription("File name");
arg.setDefaultValue("The currently active model");
spec.addArgument(arg);
arg = new FunctionArgument(PARAM_NAME, FunctionSpec.TYPE_STRING);
arg.setDescription("Dimension name");
arg.setRequired(true);
spec.addArgument(arg);
arg = new FunctionArgument(PARAM_TEXT, FunctionSpec.TYPE_DEPEND);
arg.setDescription("Dimension text");
arg.setDefaultValue("Sets the dimension's text to @D if missing");
spec.addArgument(arg);
arg = new FunctionArgument(PARAM_ENCODED, FunctionSpec.TYPE_BOOL);
arg.setDescription("Whether the text value is Base64-encoded");
arg.setDefaultValue("false");
spec.addArgument(arg);
FunctionExample ex;
ex = new FunctionExample();
ex.addInput(PARAM_MODEL, "box.prt");
ex.addInput(PARAM_NAME, "d3");
ex.addInput(PARAM_TEXT, "@D rad");
ex.addInput(PARAM_ENCODED, false);
template.addExample(ex);
ex = new FunctionExample();
ex.addInput(PARAM_NAME, "RADIUS");
ex.addInput(PARAM_TEXT, "(@D)\nAS SHOWN");
ex.addInput(PARAM_ENCODED, false);
template.addExample(ex);
ex = new FunctionExample();
ex.addInput(PARAM_NAME, "ANGLE");
byte[] enc = DataUtils.encodeBase64("@D \001$\002");
ex.addInput(PARAM_TEXT, new String(enc));
ex.addInput(PARAM_ENCODED, true);
template.addExample(ex);
ex = new FunctionExample();
ex.addInput(PARAM_NAME, "ANGLE");
ex.addInput(PARAM_TEXT, "@D \u0001$\u0002");
ex.addInput(PARAM_ENCODED, false);
template.addExample(ex);
return template;
}
private FunctionTemplate helpCopy() {
FunctionTemplate template = new FunctionTemplate(COMMAND, FUNC_COPY);
FunctionSpec spec = template.getSpec();
spec.setFunctionDescription("Copy dimension to another in the same model or another model");
FunctionArgument arg;
arg = new FunctionArgument(PARAM_MODEL, FunctionSpec.TYPE_STRING);
arg.setDescription("Source model");
arg.setDefaultValue("The currently active model");
spec.addArgument(arg);
arg = new FunctionArgument(PARAM_NAME, FunctionSpec.TYPE_STRING);
arg.setDescription("Dimension name to copy");
arg.setRequired(true);
spec.addArgument(arg);
arg = new FunctionArgument(PARAM_TONAME, FunctionSpec.TYPE_STRING);
arg.setDescription("Destination dimension; the dimension must already exist");
arg.setRequired(true);
spec.addArgument(arg);
arg = new FunctionArgument(PARAM_TOMODEL, FunctionSpec.TYPE_STRING);
arg.setDescription("Destination model");
arg.setDefaultValue("The source model");
spec.addArgument(arg);
FunctionExample ex;
ex = new FunctionExample();
ex.addInput(PARAM_MODEL, "box.prt");
ex.addInput(PARAM_NAME, "d2");
ex.addInput(PARAM_TONAME, "d3");
template.addExample(ex);
ex = new FunctionExample();
ex.addInput(PARAM_MODEL, "box_flat.prt");
ex.addInput(PARAM_NAME, "RADIUS");
ex.addInput(PARAM_TOMODEL, "box.prt");
template.addExample(ex);
ex = new FunctionExample();
ex.addInput(PARAM_NAME, "RADIUS");
ex.addInput(PARAM_TOMODEL, "box.prt");
template.addExample(ex);
return template;
}
private FunctionTemplate helpList() {
FunctionTemplate template = new FunctionTemplate(COMMAND, FUNC_LIST);
FunctionSpec spec = template.getSpec();
spec.setFunctionDescription("Get a list of dimensions from a model");
spec.addFootnote("If "+PARAM_SELECT+" is true, then the current selection in Creo will be cleared even if no items are found.");
FunctionArgument arg;
FunctionReturn ret;
arg = new FunctionArgument(PARAM_MODEL, FunctionSpec.TYPE_STRING);
arg.setDescription("File name");
arg.setDefaultValue("The currently active model");
spec.addArgument(arg);
arg = new FunctionArgument(PARAM_NAME, FunctionSpec.TYPE_STRING);
arg.setDescription("Dimension name; only used if " + PARAM_NAMES + " is not given");
arg.setWildcards(true);
// arg.setDefaultValue("The " + PARAM_NAMES + " parameter is used; if both are empty, then all dimensions are listed");
spec.addArgument(arg);
arg = new FunctionArgument(PARAM_NAMES, FunctionSpec.TYPE_ARRAY, FunctionSpec.TYPE_STRING);
arg.setDescription("List of dimension names");
arg.setDefaultValue("The " + PARAM_NAME + " parameter is used; if both are empty, then all dimensions are listed");
spec.addArgument(arg);
arg = new FunctionArgument(PARAM_DIM_TYPE, FunctionSpec.TYPE_STRING);
arg.setDescription("Dimension type filter");
arg.setValidValues(new String[] {
DimDetailData.TYPE_LINEAR,
DimDetailData.TYPE_RADIAL,
DimDetailData.TYPE_DIAMETER,
DimDetailData.TYPE_ANGULAR
});
arg.setDefaultValue("no filter");
spec.addArgument(arg);
arg = new FunctionArgument(PARAM_ENCODED, FunctionSpec.TYPE_BOOL);
arg.setDescription("Whether to return the values Base64-encoded");
arg.setDefaultValue("false");
spec.addArgument(arg);
arg = new FunctionArgument(PARAM_SELECT, FunctionSpec.TYPE_BOOL);
arg.setDescription("If true, the dimensions that are found will be selected in Creo");
arg.setDefaultValue("false");
spec.addArgument(arg);
ret = new FunctionReturn(OUTPUT_DIMLIST, FunctionSpec.TYPE_OBJARRAY, OBJ_DIM_DATA);
ret.setDescription("List of dimension information");
spec.addReturn(ret);
FunctionExample ex;
ex = new FunctionExample();
ex.addInput(PARAM_MODEL, "box.prt");
ex.addInput(PARAM_NAME, "d*1");
Map<String, Object> rec;
List<Map<String, Object>> params = new ArrayList<Map<String, Object>>();
rec = new OrderedMap<String, Object>();
params.add(rec);
rec.put(OUTPUT_NAME, "d1");
rec.put(OUTPUT_VALUE, 32.5);
rec.put(OUTPUT_ENCODED, false);
rec.put(OUTPUT_DWG_DIM, false);
rec = new OrderedMap<String, Object>();
params.add(rec);
rec.put(OUTPUT_NAME, "d11");
rec.put(OUTPUT_VALUE, 5.0);
rec.put(OUTPUT_ENCODED, false);
rec.put(OUTPUT_DWG_DIM, false);
ex.addOutput(OUTPUT_DIMLIST, params);
template.addExample(ex);
ex = new FunctionExample();
ex.addInput(PARAM_NAMES, new String[] {"d1","RADIUS","ANGLE"});
params = new ArrayList<Map<String, Object>>();
rec = new OrderedMap<String, Object>();
params.add(rec);
rec.put(OUTPUT_NAME, "ANGLE");
rec.put(OUTPUT_VALUE, "MzAgASQCCg==");
rec.put(OUTPUT_ENCODED, true);
rec.put(OUTPUT_DWG_DIM, false);
rec = new OrderedMap<String, Object>();
params.add(rec);
rec.put(OUTPUT_NAME, "d1");
rec.put(OUTPUT_VALUE, 32.5);
rec.put(OUTPUT_ENCODED, false);
rec.put(OUTPUT_DWG_DIM, false);
rec = new OrderedMap<String, Object>();
params.add(rec);
rec.put(OUTPUT_NAME, "RADIUS");
rec.put(OUTPUT_VALUE, 2.5);
rec.put(OUTPUT_ENCODED, false);
rec.put(OUTPUT_DWG_DIM, false);
ex.addOutput(OUTPUT_DIMLIST, params);
template.addExample(ex);
ex = new FunctionExample();
ex.addInput(PARAM_MODEL, "box.prt");
ex.addInput(PARAM_NAME, "d1");
ex.addInput(PARAM_ENCODED, true);
params = new ArrayList<Map<String, Object>>();
rec = new OrderedMap<String, Object>();
params.add(rec);
rec.put(OUTPUT_NAME, "d1");
rec.put(OUTPUT_VALUE, "MzIuNQ==");
rec.put(OUTPUT_ENCODED, true);
rec.put(OUTPUT_DWG_DIM, false);
ex.addOutput(OUTPUT_DIMLIST, params);
template.addExample(ex);
ex = new FunctionExample();
ex.addInput(PARAM_MODEL, "box.prt");
ex.addInput(PARAM_DIM_TYPE, DimDetailData.TYPE_LINEAR);
params = new ArrayList<Map<String, Object>>();
rec = new OrderedMap<String, Object>();
params.add(rec);
rec.put(OUTPUT_NAME, "d1");
rec.put(OUTPUT_VALUE, 32.5);
rec.put(OUTPUT_ENCODED, false);
rec.put(OUTPUT_DWG_DIM, false);
ex.addOutput(OUTPUT_DIMLIST, params);
template.addExample(ex);
ex = new FunctionExample();
ex.addInput(PARAM_MODEL, "box.drw");
ex.addInput(PARAM_NAME, "d*1");
params = new ArrayList<Map<String, Object>>();
rec = new OrderedMap<String, Object>();
params.add(rec);
rec.put(OUTPUT_NAME, "d1");
rec.put(OUTPUT_VALUE, 32.5);
rec.put(OUTPUT_ENCODED, false);
rec.put(OUTPUT_DWG_DIM, false);
rec = new OrderedMap<String, Object>();
params.add(rec);
rec.put(OUTPUT_NAME, "d11");
rec.put(OUTPUT_VALUE, 5.0);
rec.put(OUTPUT_ENCODED, false);
rec.put(OUTPUT_DWG_DIM, false);
rec = new OrderedMap<String, Object>();
params.add(rec);
rec.put(OUTPUT_NAME, "ad11");
rec.put(OUTPUT_VALUE, 32.0);
rec.put(OUTPUT_ENCODED, false);
rec.put(OUTPUT_DWG_DIM, true);
ex.addOutput(OUTPUT_DIMLIST, params);
template.addExample(ex);
return template;
}
private FunctionTemplate helpListDetail() {
FunctionTemplate template = new FunctionTemplate(COMMAND, FUNC_LIST_DETAIL);
FunctionSpec spec = template.getSpec();
spec.setFunctionDescription("Get a list of dimension details from a model");
spec.addFootnote("If "+PARAM_SELECT+" is true, then the current selection in Creo will be cleared even if no items are found.");
spec.addFootnote("See the documentation for "+"object"+" : "+OBJ_DIM_DETAIL_DATA+" to find out which values are returned for drawings vs models.");
FunctionArgument arg;
FunctionReturn ret;
arg = new FunctionArgument(PARAM_MODEL, FunctionSpec.TYPE_STRING);
arg.setDescription("File name");
arg.setDefaultValue("The currently active model");
spec.addArgument(arg);
arg = new FunctionArgument(PARAM_NAME, FunctionSpec.TYPE_STRING);
arg.setDescription("Dimension name; only used if " + PARAM_NAMES + " is not given");
arg.setWildcards(true);
// arg.setDefaultValue("The " + PARAM_NAMES + " parameter is used; if both are empty, then all dimensions are listed");
spec.addArgument(arg);
arg = new FunctionArgument(PARAM_NAMES, FunctionSpec.TYPE_ARRAY, FunctionSpec.TYPE_STRING);
arg.setDescription("List of dimension names");
arg.setDefaultValue("The " + PARAM_NAME + " parameter is used; if both are empty, then all dimensions are listed");
spec.addArgument(arg);
arg = new FunctionArgument(PARAM_DIM_TYPE, FunctionSpec.TYPE_STRING);
arg.setDescription("Dimension type filter");
arg.setValidValues(new String[] {
DimDetailData.TYPE_LINEAR,
DimDetailData.TYPE_RADIAL,
DimDetailData.TYPE_DIAMETER,
DimDetailData.TYPE_ANGULAR
});
arg.setDefaultValue("no filter");
spec.addArgument(arg);
arg = new FunctionArgument(PARAM_ENCODED, FunctionSpec.TYPE_BOOL);
arg.setDescription("Whether to return the values Base64-encoded");
arg.setDefaultValue("false");
spec.addArgument(arg);
arg = new FunctionArgument(PARAM_SELECT, FunctionSpec.TYPE_BOOL);
arg.setDescription("If true, the dimensions that are found will be selected in Creo");
arg.setDefaultValue("false");
spec.addArgument(arg);
ret = new FunctionReturn(OUTPUT_DIMLIST, FunctionSpec.TYPE_OBJARRAY, OBJ_DIM_DETAIL_DATA);
ret.setDescription("List of dimension information");
spec.addReturn(ret);
FunctionExample ex;
ex = new FunctionExample();
ex.addInput(PARAM_MODEL, "box.prt");
ex.addInput(PARAM_NAME, "d*1");
Map<String, Object> rec;
List<Map<String, Object>> params = new ArrayList<Map<String, Object>>();
// record 1
rec = new OrderedMap<String, Object>();
params.add(rec);
rec.put(OUTPUT_NAME, "d21");
rec.put(OUTPUT_VALUE, 32.5);
rec.put(OUTPUT_ENCODED, false);
rec.put(OUTPUT_DWG_DIM, false);
rec.put(OUTPUT_DIM_TYPE, DimDetailData.TYPE_LINEAR);
rec.put(OUTPUT_TEXT, new String[] {"{0:@D}\n"});
// record 2
rec = new OrderedMap<String, Object>();
params.add(rec);
rec.put(OUTPUT_NAME, "d31");
rec.put(OUTPUT_VALUE, 5.0);
rec.put(OUTPUT_ENCODED, false);
rec.put(OUTPUT_DWG_DIM, false);
rec.put(OUTPUT_DIM_TYPE, DimDetailData.TYPE_LINEAR);
rec.put(OUTPUT_TEXT, new String[] {"{0:@D}\n"});
ex.addOutput(OUTPUT_DIMLIST, params);
template.addExample(ex);
ex = new FunctionExample();
ex.addInput(PARAM_MODEL, "box.drw");
ex.addInput(PARAM_NAME, "d*1");
params = new ArrayList<Map<String, Object>>();
// record 1
rec = new OrderedMap<String, Object>();
params.add(rec);
rec.put(OUTPUT_NAME, "d1");
rec.put(OUTPUT_VALUE, 32.5);
rec.put(OUTPUT_ENCODED, false);
rec.put(OUTPUT_DWG_DIM, false);
rec.put(OUTPUT_SHEET, 1);
rec.put(OUTPUT_VIEW_NAME, "main_view");
rec.put(OUTPUT_DIM_TYPE, DimDetailData.TYPE_LINEAR);
rec.put(OUTPUT_TEXT, new String[] {"{0:@D}\n"});
rec.put(OUTPUT_LOCATION, JLJsonFileHelp.writePoint(100.0, 50.0, 0.0));
rec.put(OUTPUT_TOLERANCE_TYPE, DimToleranceData.TYPE_PLUS_MINUS);
rec.put(OUTPUT_TOL_PLUS, 0.75);
rec.put(OUTPUT_TOL_MINUS, 1.0);
// record 2
rec = new OrderedMap<String, Object>();
params.add(rec);
rec.put(OUTPUT_NAME, "d11");
rec.put(OUTPUT_VALUE, 5.0);
rec.put(OUTPUT_ENCODED, false);
rec.put(OUTPUT_DWG_DIM, false);
rec.put(OUTPUT_SHEET, 1);
rec.put(OUTPUT_VIEW_NAME, "main_view");
rec.put(OUTPUT_DIM_TYPE, DimDetailData.TYPE_LINEAR);
rec.put(OUTPUT_TEXT, new String[] {"{0:@D}\n"});
rec.put(OUTPUT_LOCATION, JLJsonFileHelp.writePoint(5.0, 7.5, 0.0));
ex.addOutput(OUTPUT_DIMLIST, params);
template.addExample(ex);
ex = new FunctionExample();
ex.addInput(PARAM_NAMES, new String[] {"d1","RADIUS","ANGLE"});
params = new ArrayList<Map<String, Object>>();
// record 1
rec = new OrderedMap<String, Object>();
params.add(rec);
rec.put(OUTPUT_NAME, "ANGLE");
rec.put(OUTPUT_VALUE, "MzAgASQCCg==");
rec.put(OUTPUT_ENCODED, true);
rec.put(OUTPUT_DWG_DIM, false);
rec.put(OUTPUT_SHEET, 2);
rec.put(OUTPUT_VIEW_NAME, "hole_view");
rec.put(OUTPUT_DIM_TYPE, DimDetailData.TYPE_ANGULAR);
rec.put(OUTPUT_TEXT, new String[] {"{0:@D}\n"});
rec.put(OUTPUT_LOCATION, JLJsonFileHelp.writePoint(16.0, 3.0, 0.0));
// record 2
rec = new OrderedMap<String, Object>();
params.add(rec);
rec.put(OUTPUT_NAME, "d1");
rec.put(OUTPUT_VALUE, 32.5);
rec.put(OUTPUT_ENCODED, false);
rec.put(OUTPUT_DWG_DIM, false);
rec.put(OUTPUT_SHEET, 1);
rec.put(OUTPUT_VIEW_NAME, "main_view");
rec.put(OUTPUT_DIM_TYPE, DimDetailData.TYPE_LINEAR);
rec.put(OUTPUT_TEXT, new String[] {"{0:@D}\n"});
rec.put(OUTPUT_LOCATION, JLJsonFileHelp.writePoint(100.0, 50.0, 0.0));
rec.put(OUTPUT_TOLERANCE_TYPE, DimToleranceData.TYPE_PLUS_MINUS);
rec.put(OUTPUT_TOL_PLUS, 0.75);
rec.put(OUTPUT_TOL_MINUS, 1.0);
// record 3
rec = new OrderedMap<String, Object>();
params.add(rec);
rec.put(OUTPUT_NAME, "RADIUS");
rec.put(OUTPUT_VALUE, 2.5);
rec.put(OUTPUT_ENCODED, false);
rec.put(OUTPUT_DWG_DIM, false);
rec.put(OUTPUT_SHEET, 2);
rec.put(OUTPUT_VIEW_NAME, "hole_view");
rec.put(OUTPUT_DIM_TYPE, DimDetailData.TYPE_RADIAL);
rec.put(OUTPUT_TEXT, new String[] {"{0:@D}\n"});
rec.put(OUTPUT_LOCATION, JLJsonFileHelp.writePoint(12.32, 4.25, 0.0));
ex.addOutput(OUTPUT_DIMLIST, params);
template.addExample(ex);
ex = new FunctionExample();
ex.addInput(PARAM_MODEL, "box.drw");
ex.addInput(PARAM_NAME, "d1");
ex.addInput(PARAM_ENCODED, true);
params = new ArrayList<Map<String, Object>>();
// record 1
rec = new OrderedMap<String, Object>();
params.add(rec);
rec.put(OUTPUT_NAME, "d1");
rec.put(OUTPUT_VALUE, "MzIuNQ==");
rec.put(OUTPUT_ENCODED, true);
rec.put(OUTPUT_DWG_DIM, false);
rec.put(OUTPUT_SHEET, 1);
rec.put(OUTPUT_VIEW_NAME, "main_view");
rec.put(OUTPUT_DIM_TYPE, DimDetailData.TYPE_LINEAR);
rec.put(OUTPUT_TEXT, new String[] {"{0:@D}\n"});
rec.put(OUTPUT_LOCATION, JLJsonFileHelp.writePoint(100.0, 50.0, 0.0));
rec.put(OUTPUT_TOLERANCE_TYPE, DimToleranceData.TYPE_PLUS_MINUS);
rec.put(OUTPUT_TOL_PLUS, 0.75);
rec.put(OUTPUT_TOL_MINUS, 1.0);
ex.addOutput(OUTPUT_DIMLIST, params);
template.addExample(ex);
ex = new FunctionExample();
ex.addInput(PARAM_MODEL, "box.drw");
ex.addInput(PARAM_DIM_TYPE, DimDetailData.TYPE_LINEAR);
params = new ArrayList<Map<String, Object>>();
// record 1
rec = new OrderedMap<String, Object>();
params.add(rec);
rec.put(OUTPUT_NAME, "d1");
rec.put(OUTPUT_VALUE, 32.5);
rec.put(OUTPUT_ENCODED, false);
rec.put(OUTPUT_DWG_DIM, false);
rec.put(OUTPUT_SHEET, 1);
rec.put(OUTPUT_VIEW_NAME, "main_view");
rec.put(OUTPUT_DIM_TYPE, DimDetailData.TYPE_LINEAR);
rec.put(OUTPUT_TEXT, new String[] {"{0:@D}\n"});
rec.put(OUTPUT_LOCATION, JLJsonFileHelp.writePoint(100.0, 50.0, 0.0));
rec.put(OUTPUT_TOLERANCE_TYPE, DimToleranceData.TYPE_PLUS_MINUS);
rec.put(OUTPUT_TOL_PLUS, 0.75);
rec.put(OUTPUT_TOL_MINUS, 1.0);
ex.addOutput(OUTPUT_DIMLIST, params);
template.addExample(ex);
return template;
}
private FunctionObject helpDimData() {
FunctionObject obj = new FunctionObject(OBJ_DIM_DATA);
obj.setDescription("Information about a Creo dimension");
FunctionArgument arg;
arg = new FunctionArgument(OUTPUT_NAME, FunctionSpec.TYPE_STRING);
arg.setDescription("Dimension name");
obj.add(arg);
arg = new FunctionArgument(OUTPUT_VALUE, FunctionSpec.TYPE_DEPEND);
arg.setDescription("Dimension value");
obj.add(arg);
arg = new FunctionArgument(OUTPUT_ENCODED, FunctionSpec.TYPE_BOOL);
arg.setDescription("Value is Base64-encoded");
arg.setDefaultValue("false");
obj.add(arg);
arg = new FunctionArgument(OUTPUT_DWG_DIM, FunctionSpec.TYPE_BOOL);
arg.setDescription("Whether dimension is a drawing dimension rather than a model dimension");
arg.setDefaultValue("false");
obj.add(arg);
return obj;
}
private FunctionObject helpDimSelectData() {
FunctionObject obj = helpDimData();
obj.setObjectName(OBJ_DIM_SELECT_DATA);
obj.setDescription("Information about a dimension that the user has selected");
FunctionArgument arg;
arg = new FunctionArgument(PARAM_MODEL, FunctionSpec.TYPE_STRING);
arg.setDescription("Model name that owns the dimension");
obj.add(arg);
arg = new FunctionArgument(PARAM_RELATION_ID, FunctionSpec.TYPE_INTEGER);
arg.setDescription("Relation ID for the dimension's model");
obj.add(arg);
return obj;
}
private FunctionObject helpDimDetailData() {
FunctionObject obj = helpDimData();
obj.setObjectName(OBJ_DIM_DETAIL_DATA);
obj.setDescription("More detailed information about a Creo dimension");
obj.addFootnote("If dimension is not a drawing dimension, then only "+OUTPUT_NAME+", "+OUTPUT_VALUE+", "+OUTPUT_ENCODED+", "+OUTPUT_DIM_TYPE+", and "+OUTPUT_TEXT+" will be returned.");
obj.addFootnote(OUTPUT_TOL_LOWER_LIMIT + " and " + OUTPUT_TOL_UPPER_LIMIT + " are only set when " + OUTPUT_TOLERANCE_TYPE + "=" + DimToleranceData.TYPE_LIMITS);
obj.addFootnote(OUTPUT_TOL_PLUS + " and " + OUTPUT_TOL_MINUS + " are only set when " + OUTPUT_TOLERANCE_TYPE + "=" + DimToleranceData.TYPE_PLUS_MINUS);
obj.addFootnote(OUTPUT_TOL_SYMMETRIC_VALUE + " is only set when " + OUTPUT_TOLERANCE_TYPE + "=" + DimToleranceData.TYPE_SYMMETRIC + " or " + DimToleranceData.TYPE_SYM_SUPERSCRIPT);
obj.addFootnote(OUTPUT_TOL_TABLE_NAME + ", " + OUTPUT_TOL_TABLE_COLUMN + " and " + OUTPUT_TOL_TABLE_TYPE + " are only set when " + OUTPUT_TOLERANCE_TYPE + "=" + DimToleranceData.TYPE_ISODIN);
FunctionArgument arg;
arg = new FunctionArgument(OUTPUT_DIM_TYPE, FunctionSpec.TYPE_STRING);
arg.setDescription("Dimension type");
arg.setValidValues(new String[] {
DimDetailData.TYPE_LINEAR,
DimDetailData.TYPE_RADIAL,
DimDetailData.TYPE_DIAMETER,
DimDetailData.TYPE_ANGULAR
});
obj.add(arg);
arg = new FunctionArgument(OUTPUT_TEXT, FunctionSpec.TYPE_ARRAY, FunctionSpec.TYPE_STRING);
arg.setDescription("Dimension raw text");
obj.add(arg);
arg = new FunctionArgument(OUTPUT_SHEET, FunctionSpec.TYPE_INTEGER);
arg.setDescription("Sheet number");
obj.add(arg);
arg = new FunctionArgument(OUTPUT_VIEW_NAME, FunctionSpec.TYPE_STRING);
arg.setDescription("View name");
obj.add(arg);
arg = new FunctionArgument(OUTPUT_LOCATION, FunctionSpec.TYPE_OBJECT, JLJsonFileHelp.OBJ_POINT);
arg.setDescription("Coordinates of the dimension in drawing units");
obj.add(arg);
arg = new FunctionArgument(OUTPUT_TOLERANCE_TYPE, FunctionSpec.TYPE_STRING);
arg.setDescription("Tolerance type, if any");
arg.setValidValues(new String[] {
DimToleranceData.TYPE_LIMITS,
DimToleranceData.TYPE_PLUS_MINUS,
DimToleranceData.TYPE_SYMMETRIC,
DimToleranceData.TYPE_SYM_SUPERSCRIPT,
DimToleranceData.TYPE_ISODIN
});
obj.add(arg);
arg = new FunctionArgument(OUTPUT_TOL_LOWER_LIMIT, FunctionSpec.TYPE_DOUBLE);
arg.setDescription("Tolerance Lower Limit");
obj.add(arg);
arg = new FunctionArgument(OUTPUT_TOL_UPPER_LIMIT, FunctionSpec.TYPE_DOUBLE);
arg.setDescription("Tolerance Upper Limit");
obj.add(arg);
arg = new FunctionArgument(OUTPUT_TOL_PLUS, FunctionSpec.TYPE_DOUBLE);
arg.setDescription("Tolerance Plus Value");
obj.add(arg);
arg = new FunctionArgument(OUTPUT_TOL_MINUS, FunctionSpec.TYPE_DOUBLE);
arg.setDescription("Tolerance Minus Value");
obj.add(arg);
arg = new FunctionArgument(OUTPUT_TOL_SYMMETRIC_VALUE, FunctionSpec.TYPE_DOUBLE);
arg.setDescription("Tolerance Symmetric Value");
obj.add(arg);
arg = new FunctionArgument(OUTPUT_TOL_TABLE_NAME, FunctionSpec.TYPE_STRING);
arg.setDescription("Tolerance Table Name");
obj.add(arg);
arg = new FunctionArgument(OUTPUT_TOL_TABLE_COLUMN, FunctionSpec.TYPE_INTEGER);
arg.setDescription("Tolerance Table Column");
obj.add(arg);
arg = new FunctionArgument(OUTPUT_TOL_TABLE_TYPE, FunctionSpec.TYPE_STRING);
arg.setDescription("Tolerance Table Type");
arg.setValidValues(new String[] {
DimToleranceData.TABLE_GENERAL,
DimToleranceData.TABLE_BROKEN_EDGE,
DimToleranceData.TABLE_SHAFTS,
DimToleranceData.TABLE_HOLES
});
obj.add(arg);
return obj;
}
private FunctionTemplate helpShow() {
FunctionTemplate template = new FunctionTemplate(COMMAND, FUNC_SHOW);
FunctionSpec spec = template.getSpec();
spec.setFunctionDescription("Display or hide a dimension in Creo");
spec.addFootnote("You can show a dimension on a specific occurrence of a part in an assembly, but if you hide a dimension it will be hidden on all occurrences of the component.");
FunctionArgument arg;
arg = new FunctionArgument(PARAM_MODEL, FunctionSpec.TYPE_STRING);
arg.setDescription("File name containing the dimension");
arg.setDefaultValue("The currently active model");
spec.addArgument(arg);
arg = new FunctionArgument(PARAM_ASSEMBLY, FunctionSpec.TYPE_STRING);
arg.setDescription("Assembly name; only used if " + PARAM_PATH + " is given");
arg.setDefaultValue("The currently active model");
spec.addArgument(arg);
arg = new FunctionArgument(PARAM_NAME, FunctionSpec.TYPE_STRING);
arg.setDescription("Dimension name");
arg.setRequired(true);
spec.addArgument(arg);
arg = new FunctionArgument(PARAM_PATH, FunctionSpec.TYPE_ARRAY, FunctionSpec.TYPE_INTEGER);
arg.setDescription("Path to occurrence of the model within the assembly; the dimension will only be shown for that occurrence");
arg.setDefaultValue("All occurrences of the component are affected");
spec.addArgument(arg);
arg = new FunctionArgument(PARAM_SHOW, FunctionSpec.TYPE_BOOL);
arg.setDescription("Whether to show (or hide) the dimension");
arg.setDefaultValue("true (show)");
spec.addArgument(arg);
FunctionExample ex;
ex = new FunctionExample();
ex.addInput(PARAM_MODEL, "box.prt");
ex.addInput(PARAM_NAME, "d3");
ex.addInput(PARAM_SHOW, true);
template.addExample(ex);
ex = new FunctionExample();
ex.addInput(PARAM_MODEL, "bolt.prt");
ex.addInput(PARAM_ASSEMBLY, "engine.asm");
ex.addInput(PARAM_NAME, "d5");
ex.addInput(PARAM_PATH, new int[] {51, 12});
ex.addInput(PARAM_SHOW, true);
template.addExample(ex);
ex = new FunctionExample();
ex.addInput(PARAM_NAME, "d1");
ex.addInput(PARAM_SHOW, false);
template.addExample(ex);
return template;
}
private FunctionTemplate helpUserSelect() {
FunctionTemplate template = new FunctionTemplate(COMMAND, FUNC_USER_SELECT);
FunctionSpec spec = template.getSpec();
spec.setFunctionDescription("Prompt the user to select one or more dimensions, and return their selections");
FunctionArgument arg;
FunctionReturn ret;
arg = new FunctionArgument(PARAM_MODEL, FunctionSpec.TYPE_STRING);
arg.setDescription("File name");
arg.setDefaultValue("The currently active model");
spec.addArgument(arg);
arg = new FunctionArgument(PARAM_MAX, FunctionSpec.TYPE_INTEGER);
arg.setDescription("The maximum number of dimensions that the user can select");
arg.setDefaultValue("1");
spec.addArgument(arg);
ret = new FunctionReturn(OUTPUT_DIMLIST, FunctionSpec.TYPE_OBJARRAY, OBJ_DIM_SELECT_DATA);
ret.setDescription("List of selected dimension information");
spec.addReturn(ret);
FunctionExample ex;
ex = new FunctionExample();
ex.addInput(PARAM_MODEL, "box.prt");
Map<String, Object> rec;
List<Map<String, Object>> params = new ArrayList<Map<String, Object>>();
rec = new OrderedMap<String, Object>();
params.add(rec);
rec.put(OUTPUT_NAME, "d1");
rec.put(OUTPUT_VALUE, 32.5);
rec.put(OUTPUT_ENCODED, false);
rec.put(PARAM_MODEL, "box.prt");
rec.put(PARAM_RELATION_ID, 23);
ex.addOutput(OUTPUT_DIMLIST, params);
template.addExample(ex);
ex = new FunctionExample();
ex.addInput(PARAM_MODEL, "box.prt");
ex.addInput(PARAM_MAX, 2);
params = new ArrayList<Map<String, Object>>();
rec = new OrderedMap<String, Object>();
params.add(rec);
rec.put(OUTPUT_NAME, "ANGLE");
rec.put(OUTPUT_VALUE, "MzAgASQCCg==");
rec.put(OUTPUT_ENCODED, true);
rec.put(PARAM_MODEL, "box.prt");
rec.put(PARAM_RELATION_ID, 145);
rec = new OrderedMap<String, Object>();
params.add(rec);
rec.put(OUTPUT_NAME, "d1");
rec.put(OUTPUT_VALUE, 32.5);
rec.put(OUTPUT_ENCODED, false);
rec.put(PARAM_MODEL, "box.prt");
rec.put(PARAM_RELATION_ID, 23);
ex.addOutput(OUTPUT_DIMLIST, params);
template.addExample(ex);
return template;
}
}
| 39.555294 | 211 | 0.698382 |
50156564159cd987f39869144562f675fb7c26ba | 19,343 | /*
* 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.netbeans.modules.test.refactoring;
import java.awt.*;
import java.awt.event.KeyEvent;
import javax.swing.*;
import junit.framework.Test;
import org.netbeans.jellytools.EditorOperator;
import org.netbeans.jellytools.JellyTestCase;
import org.netbeans.jemmy.EventTool;
import org.netbeans.modules.test.refactoring.actions.*;
import org.netbeans.modules.test.refactoring.operators.*;
import org.netbeans.modules.test.refactoring.operators.ErrorOperator;
/**
@author (stanislav.sazonov@oracle.com)
*/
public class EncapsulateFieldTest extends ModifyingRefactoring {
private enum currentTest { testSimple_A_A,
testSimple_A_B,
testSimple_A_C,
testSimple_A_D,
testSimple_A_E,
testSimple_A_F,
testSimple_A_G,
testSimple_A_H,
testSimple_A_I,
testSimple_A_J,
testSimple_A_K,
testSimple_A_L,
testSimple_A_M,
testSimple_A_N,
testSimple_A_O,
testSimple_A_P,
testSimple_A_Q,
testSimple_A_R,
testSimple_A_S,
testSimple_A_T,
testSimple_A_U,
testSimple_A_V,
testSimple_A_W,
testSimple_A_X,
testSimple_A_Y,
testSimple_A_Z,
testSimple_B_A,
nothing
};
public EncapsulateFieldTest(String name){
super(name);
}
public static Test suite(){
return JellyTestCase.emptyConfiguration().
addTest(RenameTest.class, "testSimple_A_A").
addTest(RenameTest.class, "testSimple_A_B").
addTest(RenameTest.class, "testSimple_A_C").
addTest(RenameTest.class, "testSimple_A_D").
addTest(RenameTest.class, "testSimple_A_E").
addTest(RenameTest.class, "testSimple_A_F").
addTest(RenameTest.class, "testSimple_A_G").
addTest(RenameTest.class, "testSimple_A_H").
addTest(RenameTest.class, "testSimple_A_I").
addTest(RenameTest.class, "testSimple_A_J").
addTest(RenameTest.class, "testSimple_A_K").
addTest(RenameTest.class, "testSimple_A_L").
addTest(RenameTest.class, "testSimple_A_M").
addTest(RenameTest.class, "testSimple_A_N").
addTest(RenameTest.class, "testSimple_A_O").
addTest(RenameTest.class, "testSimple_A_P").
addTest(RenameTest.class, "testSimple_A_Q").
addTest(RenameTest.class, "testSimple_A_R").
addTest(RenameTest.class, "testSimple_A_S").
addTest(RenameTest.class, "testSimple_A_T").
addTest(RenameTest.class, "testSimple_A_U").
addTest(RenameTest.class, "testSimple_A_V").
addTest(RenameTest.class, "testSimple_A_W").
addTest(RenameTest.class, "testSimple_A_X").
addTest(RenameTest.class, "testSimple_A_Y").
addTest(RenameTest.class, "testSimple_A_Z").
addTest(RenameTest.class, "testSimple_B_A").
suite();
}
public void testSimple_A_A(){
performIntroduvceMethod(currentTest.testSimple_A_A);
}
public void testSimple_A_B(){
performIntroduvceMethod(currentTest.testSimple_A_B);
}
public void testSimple_A_C(){
performIntroduvceMethod(currentTest.testSimple_A_C);
}
public void testSimple_A_D(){
performIntroduvceMethod(currentTest.testSimple_A_D);
}
public void testSimple_A_E(){
performIntroduvceMethod(currentTest.testSimple_A_E);
}
public void testSimple_A_F(){
performIntroduvceMethod(currentTest.testSimple_A_F);
}
public void testSimple_A_G(){
performIntroduvceMethod(currentTest.testSimple_A_G);
}
public void testSimple_A_H(){
performIntroduvceMethod(currentTest.testSimple_A_H);
}
public void testSimple_A_I(){
performIntroduvceMethod(currentTest.testSimple_A_I);
}
public void testSimple_A_J(){
performIntroduvceMethod(currentTest.testSimple_A_J);
}
public void testSimple_A_K(){
performIntroduvceMethod(currentTest.testSimple_A_K);
}
public void testSimple_A_L(){
performIntroduvceMethod(currentTest.testSimple_A_L);
}
public void testSimple_A_M(){
performIntroduvceMethod(currentTest.testSimple_A_M);
}
public void testSimple_A_N(){
performIntroduvceMethod(currentTest.testSimple_A_N);
}
public void testSimple_A_O(){
performIntroduvceMethod(currentTest.testSimple_A_O);
}
public void testSimple_A_P(){
performIntroduvceMethod(currentTest.testSimple_A_P);
}
public void testSimple_A_Q(){
performIntroduvceMethod(currentTest.testSimple_A_Q);
}
public void testSimple_A_R(){
performIntroduvceMethod(currentTest.testSimple_A_R);
}
public void testSimple_A_S(){
performIntroduvceMethod(currentTest.testSimple_A_S);
}
public void testSimple_A_T(){
performIntroduvceMethod(currentTest.testSimple_A_T);
}
public void testSimple_A_U(){
performIntroduvceMethod(currentTest.testSimple_A_U);
}
public void testSimple_A_V(){
performIntroduvceMethod(currentTest.testSimple_A_V);
}
public void testSimple_A_W(){
performIntroduvceMethod(currentTest.testSimple_A_W);
}
public void testSimple_A_X(){
performIntroduvceMethod(currentTest.testSimple_A_X);
}
public void testSimple_A_Y(){
performIntroduvceMethod(currentTest.testSimple_A_Y);
}
public void testSimple_A_Z(){
performIntroduvceMethod(currentTest.testSimple_A_Z);
}
public void testSimple_B_A(){
performIntroduvceMethod(currentTest.testSimple_B_A);
}
private void performIntroduvceMethod(currentTest c){
EncapsulateFieldOperator efo = null;
ErrorOperator eo = null;
String report = "";
boolean debugMode = false;
EditorOperator editor;
// open source file
String curClass = "";
switch(c){
case testSimple_A_A: curClass = "Class_A_A"; break;
case testSimple_A_B: curClass = "Class_A_B"; break;
case testSimple_A_C: curClass = "Class_A_C"; break;
case testSimple_A_D: curClass = "Class_A_D"; break;
case testSimple_A_E: curClass = "Class_A_E"; break;
case testSimple_A_F: curClass = "Class_A_F"; break;
case testSimple_A_G: curClass = "Class_A_G"; break;
case testSimple_A_H: curClass = "Class_A_H"; break;
case testSimple_A_I: curClass = "Class_A_I"; break;
case testSimple_A_J: curClass = "Class_A_J"; break;
case testSimple_A_K: curClass = "Class_A_K"; break;
case testSimple_A_L: curClass = "Class_A_L"; break;
case testSimple_A_M: curClass = "Class_A_M"; break;
case testSimple_A_N: curClass = "Class_A_N"; break;
case testSimple_A_O: curClass = "Class_A_O"; break;
case testSimple_A_P: curClass = "Class_A_P"; break;
case testSimple_A_Q: curClass = "Class_A_Q"; break;
case testSimple_A_R: curClass = "Class_A_R"; break;
case testSimple_A_S: curClass = "Class_A_S"; break;
case testSimple_A_T: curClass = "Class_A_T"; break;
case testSimple_A_U: curClass = "Class_A_U"; break;
case testSimple_A_V: curClass = "Class_A_V"; break;
case testSimple_A_W: curClass = "Class_A_W"; break;
case testSimple_A_X: curClass = "Class_A_X"; break;
case testSimple_A_Y: curClass = "Class_A_Y"; break;
case testSimple_A_Z: curClass = "Class_A_Z"; break;
case testSimple_B_A: curClass = "Class_B_A"; break;
}
// open source file
switch(c){
default:
openSourceFile("encapsulateField", curClass);
editor = new EditorOperator(curClass + ".java");
break;
}
if(debugMode) new EventTool().waitNoEvent(2000);
// put carret on position
switch(c){
case testSimple_A_A:
case testSimple_A_B:
case testSimple_A_C:
case testSimple_A_D:
case testSimple_A_E:
case testSimple_A_F:
editor.setCaretPosition(6, 1);
editor.select(6, 21, 26);
break;
case testSimple_A_G:
case testSimple_A_H:
case testSimple_A_I:
editor.setCaretPosition(52, 1);
editor.select(52, 73, 78);
break;
case testSimple_A_J:
case testSimple_A_K:
case testSimple_A_L:
editor.setCaretPosition(57, 1);
editor.select(57, 73, 78);
break;
case testSimple_A_M:
case testSimple_A_N:
case testSimple_A_O:
case testSimple_A_P:
case testSimple_A_Q:
case testSimple_A_R:
case testSimple_A_S:
case testSimple_A_T:
case testSimple_A_U:
case testSimple_A_V:
case testSimple_A_W:
case testSimple_A_X:
case testSimple_A_Y:
case testSimple_A_Z:
case testSimple_B_A:
editor.setCaretPosition(52, 1);
editor.select(52, 73, 78);
break;
}
if(debugMode) new EventTool().waitNoEvent(1000);
// call Reafctor > Introduce parameter
switch(c){
default:
new EncapsulateFieldAction().performPopup(editor);
break;
}
// catch Introduce method dialog
switch(c){
case nothing: break;
default:
efo = new EncapsulateFieldOperator();
break;
}
new EventTool().waitNoEvent(500);
// Insert Point
switch(c){
case testSimple_A_G:
case testSimple_A_H:
case testSimple_A_I:
efo.setValueAt(0, 1, true);
efo.setValueAt(0, 3, true);
break;
case testSimple_A_J:
case testSimple_A_K:
case testSimple_A_L:
efo.setValueAt(0, 1, true);
efo.setValueAt(0, 3, true);
// efo.setValueAt(0, 2, "setF1");
// efo.setValueAt(0, 3, "getF1");
efo.setValueAt(2, 1, true);
efo.setValueAt(2, 3, true);
// efo.setValueAt(2, 2, "setF3");
// efo.setValueAt(2, 3, "getF3");
efo.setValueAt(3, 1, true);
efo.setValueAt(3, 3, true);
// efo.setValueAt(0, 2, "setF4");
// efo.setValueAt(0, 3, "getF4");
break;
case testSimple_A_M:
case testSimple_A_N:
case testSimple_A_O:
case testSimple_A_P:
case testSimple_A_Q:
case testSimple_A_R:
case testSimple_A_S:
case testSimple_A_T:
break;
}
new EventTool().waitNoEvent(500);
switch(c){
case testSimple_A_A: efo.setInsertPoint("Default"); break;
case testSimple_A_B: efo.setInsertPoint("First Method"); break;
case testSimple_A_C: efo.setInsertPoint("Last Method"); break;
case testSimple_A_D: efo.setInsertPoint("After m1(int field1) : void"); break;
case testSimple_A_E: efo.setInsertPoint("After Class_A_E(int f)"); break;
case testSimple_A_F: efo.setInsertPoint("After m2() : void"); break;
default:
efo.setInsertPoint("Default");
break;
}
new EventTool().waitNoEvent(500);
// Sort By
switch(c){
case testSimple_A_G: efo.setSortBy("Getter/Setter pairs"); break;
case testSimple_A_H: efo.setSortBy("Getters then Setters"); break;
case testSimple_A_I: efo.setSortBy("Method names"); break;
default:
efo.setSortBy("Getter/Setter pairs");
break;
}
new EventTool().waitNoEvent(500);
// Javadoc
switch(c){
case testSimple_A_J: efo.setJavadoc("Copy from field"); break;
case testSimple_A_K: efo.setJavadoc("Create default comments"); break;
case testSimple_A_L: efo.setJavadoc("None"); break;
default:
efo.setJavadoc("None");
break;
}
new EventTool().waitNoEvent(500);
// Accessors fields visibility
switch(c){
case testSimple_A_M: efo.setFieldsVisibility("<default>"); break;
case testSimple_A_N: efo.setFieldsVisibility("private"); break;
case testSimple_A_O: efo.setFieldsVisibility("protected"); break;
case testSimple_A_P: efo.setFieldsVisibility("public"); break;
default:
efo.setFieldsVisibility("private");
break;
}
// Accessors visibility
switch(c){
case testSimple_A_Q: efo.setAccessorsVisibility("<default>"); break;
case testSimple_A_R: efo.setAccessorsVisibility("private"); break;
case testSimple_A_S: efo.setAccessorsVisibility("protected"); break;
case testSimple_A_T: efo.setAccessorsVisibility("public"); break;
default:
efo.setAccessorsVisibility("public");
break;
}
// Use Accessors Even When Field Is Accessible
switch(c){
case testSimple_A_U:
efo.setUseAccessorsEvenWhenFieldIsAccessible(false);
break;
default:
efo.setUseAccessorsEvenWhenFieldIsAccessible(true);
break;
}
// Generate Property ChangeS upport
switch(c){
case testSimple_A_V:
case testSimple_A_W:
efo.setGeneratePropertyChangeSupport(true);
new EventTool().waitNoEvent(500);
break;
default:
efo.setGeneratePropertyChangeSupport(false);
break;
}
// Select {All, None, Getters, Setters}
switch(c){
case testSimple_A_Y:
efo.selectNone();
new EventTool().waitNoEvent(500);
efo.selectGetters();
break;
case testSimple_A_Z:
efo.selectNone();
new EventTool().waitNoEvent(500);
efo.selectSetters();
break;
case testSimple_B_A:
efo.selectNone();
new EventTool().waitNoEvent(500);
efo.selectAll();
break;
default:
break;
}
// Generate Vetoable Change Support
switch(c){
case testSimple_A_W:
efo.setGenerateVetoableChangeSupport(true);
break;
case nothing:
efo.setGenerateVetoableChangeSupport(false);
break;
}
if(debugMode) new EventTool().waitNoEvent(2000);
switch(c){
case testSimple_A_X:
efo.cancel();
break;
default:
efo.refactor();
break;
}
if(debugMode) new EventTool().waitNoEvent(3000);
// add report to editor, which causes test is failed
if(!report.equals("")){
editor.setCaretPosition(1, 1);
editor.insert(report);
editor.pushKey(KeyEvent.VK_ENTER);
}
if(debugMode) new EventTool().waitNoEvent(2000);
new EventTool().waitNoEvent(1000); // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// evalue result and discard changes
ref(editor.getText());
editor.closeDiscard();
}
public void browse(Component cmp) {
System.out.println(cmp.getClass().getName());
if(cmp instanceof Container) {
Component[] components = ((Container)cmp).getComponents();
for (Component component : components) {
browse(component);
}
}
}
}
| 37.413926 | 97 | 0.52846 |
6c2446c50f781c3dd8199163d010f78ed7532e0b | 618 | package cn.wyu.Dao;
import cn.wyu.Domain.Resource;
import cn.wyu.bean.PageInfo;
import java.util.List;
public interface ResourceDao {
/**
* 插入操作
* @param Resource
*/
int insert(Resource resource);
/**
* 根据id查询数据
* @param id
* @return
*/
Resource queryById(int id);
/**
* 查询所有数据
* @return
*/
List<Resource> queryAll();
/**
* 根据id删除对应的行
* @param id
*/
int deleteById(int id);
/**
* 修改数据
*/
void modify(int id);
PageInfo queryByAll(Integer currentPage);
int updateByRe(Resource resource);
}
| 15.073171 | 45 | 0.555016 |
da62566c538b62df70f4b61f2b7072a6d44fff7e | 5,160 | package nc.block.storage;
import java.util.ArrayList;
import nc.tile.storage.TileStorage;
import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IIconRegister;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ChatComponentText;
import net.minecraft.util.EnumChatFormatting;
import net.minecraft.util.IIcon;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import com.google.common.collect.Lists;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
public abstract class BlockEnergyStorage extends BlockContainer {
@SideOnly(Side.CLIENT)
public IIcon blockIcon1;
@SideOnly(Side.CLIENT)
public IIcon blockIcon2;
@SideOnly(Side.CLIENT)
public IIcon iconTop;
@SideOnly(Side.CLIENT)
public IIcon iconTop1;
@SideOnly(Side.CLIENT)
public IIcon iconTop2;
public String name;
public BlockEnergyStorage(String nam) {
super(Material.iron);
name = nam;
}
public int damageDropped(int par1) {
return par1;
}
@SideOnly(Side.CLIENT)
public void registerBlockIcons(IIconRegister iconRegister) {
blockIcon = iconRegister.registerIcon("nc:storage/" + name + "/" + "sideIn");
blockIcon1 = iconRegister.registerIcon("nc:storage/" + name + "/" + "sideOut");
blockIcon2 = iconRegister.registerIcon("nc:storage/" + name + "/" + "sideDisabled");
iconTop = iconRegister.registerIcon("nc:storage/" + name + "/" + "topIn");
iconTop1 = iconRegister.registerIcon("nc:storage/" + name + "/" + "topOut");
iconTop2 = iconRegister.registerIcon("nc:storage/" + name + "/" + "topDisabled");
}
@SideOnly(Side.CLIENT)
public IIcon getIcon(IBlockAccess access, int x, int y, int z, int side) {
TileEntity te = access.getTileEntity(x, y, z);
if (te instanceof TileStorage) {
TileStorage t = (TileStorage) access.getTileEntity(x, y, z);
if (side <= 1) {
return t.sideMode[side] == 0 ? iconTop : (t.sideMode[side] == 1 ? iconTop1 : iconTop2);
} else {
return t.sideMode[side] == 0 ? blockIcon : (t.sideMode[side] == 1 ? blockIcon1 : blockIcon2);
}
}
return side <= 1 ? iconTop : blockIcon;
}
@SideOnly(Side.CLIENT)
public IIcon getIcon(int side, int metadata) {
return side <= 1 ? iconTop : blockIcon;
}
public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int side, float hitX, float hitY, float hitZ) {
if (player != null) {
if (world.getTileEntity(x, y, z) instanceof TileStorage) {
TileStorage te = (TileStorage) world.getTileEntity(x, y, z);
if (world.isRemote) {
if (player.isSneaking()) player.addChatMessage(new ChatComponentText(EnumChatFormatting.WHITE + "Energy Stored: " + te.storage.getEnergyStored() + " / " + te.storage.getMaxEnergyStored() + " RF"));
else player.addChatMessage(new ChatComponentText(EnumChatFormatting.WHITE + "Mode: " + (te.sideMode[side] == 0 ? "Output" : (te.sideMode[side] == 1 ? "Disabled" : "Input"))));
}
if (!player.isSneaking()) te.incrSide(side);
}
}
return true;
}
public final ArrayList<ItemStack> getDrops(World world, int x, int y, int z, int metadata, int fortune) {
return Lists.newArrayList(getDataDrop(world, x, y, z, world.getTileEntity(x, y, z) != null ? world.getTileEntity(x, y, z) : null));
}
public ItemStack getPickBlock(MovingObjectPosition target, World world, int x, int y, int z, EntityPlayer player) {
return getDataDrop(world, x, y, z, world.getTileEntity(x, y, z) != null ? world.getTileEntity(x, y, z) : null);
}
public ItemStack getDataDrop(World world, int x, int y, int z, TileEntity t) {
ItemStack itemStack = new ItemStack(this, 1);
processDrop(world, x, y, z, t, itemStack);
return itemStack;
}
protected void processDrop(World world, int x, int y, int z, TileEntity t, ItemStack drop) {
NBTTagCompound tag = new NBTTagCompound();
if(t != null && t instanceof TileStorage) { // THE ISSUE IS HERE - WHY IS THE TILE NULL?
((TileStorage) t).writeNBT(tag);
}
drop.setTagCompound(tag);
}
public void harvestBlock(World world, EntityPlayer player, int x, int y, int z, int meta) {
super.harvestBlock(world, player, x, y, z, meta);
world.setBlockToAir(x, y, z);
}
public boolean removedByPlayer(World world, EntityPlayer player, int x, int y, int z, boolean willHarvest) {
if (willHarvest) return true;
return super.removedByPlayer(world, player, x, y, z, willHarvest);
}
public void onBlockPlacedBy(World world, int x, int y, int z, EntityLivingBase player, ItemStack stack) {
super.onBlockPlacedBy(world, x, y, z, player, stack);
world.setBlockMetadataWithNotify(x, y, z, 0, 2);
TileStorage t = (TileStorage) world.getTileEntity(x, y, z);
if(t == null) {
return;
}
if(stack.stackTagCompound != null) {
t.readNBT(stack.stackTagCompound);
}
if(world.isRemote) {
return;
}
world.markBlockForUpdate(x, y, z);
}
}
| 36.595745 | 202 | 0.712597 |
cbf96e9ee6a9aed194d2eca7ff0b5d2ab667492d | 1,556 | /*
* Copyright 2004-2011 H2 Group.
* Copyright 2011 James Moger.
*
* 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.iciql.test.models;
import java.util.Arrays;
import java.util.List;
import com.iciql.Iciql.IQColumn;
import com.iciql.Iciql.IQTable;
/**
* A table containing product data.
*/
@IQTable(create = false)
public class ProductNoCreateTable {
@SuppressWarnings("unused")
@IQColumn(name = "id")
private Integer productId;
@SuppressWarnings("unused")
@IQColumn(name = "name")
private String productName;
public ProductNoCreateTable() {
// public constructor
}
private ProductNoCreateTable(int productId, String productName) {
this.productId = productId;
this.productName = productName;
}
private static ProductNoCreateTable create(int productId, String productName) {
return new ProductNoCreateTable(productId, productName);
}
public static List<ProductNoCreateTable> getList() {
ProductNoCreateTable[] list = { create(1, "Chai"), create(2, "Chang") };
return Arrays.asList(list);
}
}
| 25.933333 | 80 | 0.74036 |
ff954486622d2f65a0f319db8610a67268025077 | 512 | package com.tngtech.flink.connector.email.imap;
import static org.assertj.core.api.Assertions.assertThat;
import com.tngtech.flink.connector.email.testing.TestBase;
import org.apache.flink.table.catalog.Catalog;
import org.junit.Test;
public class ImapCatalogTest extends TestBase {
@Test
public void testListTables() throws Exception {
final Catalog catalog = createImapCatalog("local");
assertThat(catalog.listTables(catalog.getDefaultDatabase())).containsExactly("INBOX");
}
}
| 30.117647 | 94 | 0.767578 |
651d516ede08b87218da7f1818b85e5796078c53 | 131 | package com.xthena.api.form;
import java.util.List;
public interface FormConnector {
List<FormDTO> getAll(String scopeId);
}
| 16.375 | 41 | 0.755725 |
e714e5a7c249fdedb08d79f70861086a91f2c7df | 55,507 | // The MIT License (MIT)
//
// Copyright (c) 2017 Smart&Soft
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
package com.smartnsoft.droid4me.download;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import android.view.View;
import com.smartnsoft.droid4me.download.BasisDownloadInstructions.InputStreamDownloadInstructor;
import com.smartnsoft.droid4me.download.DownloadContracts.Bitmapable;
import com.smartnsoft.droid4me.download.DownloadContracts.Handlerable;
import com.smartnsoft.droid4me.download.DownloadContracts.Viewable;
import com.smartnsoft.droid4me.download.DownloadInstructions.BitmapableGif;
/**
* An implementation of the {@link CoreBitmapDownloader} class, which is independent from the Android platform.
* <p>
* <p>
* This implementation relies on two internal threads pools, which are shared among all {@link CoreBitmapDownloader} instances. The tunable parameters
* are:
* </p>
* <ul>
* <li>{@link #setPreThreadPoolSize(int)},</li>
* <li>{@link #setDownloadThreadPoolSize(int)}.</li>
* </ul>
*
* @author Édouard Mercier
* @since 2009.02.19
*/
public class BasisBitmapDownloader<BitmapClass extends Bitmapable, ViewClass extends Viewable, HandlerClass extends Handlerable>
extends CoreBitmapDownloader<BitmapClass, ViewClass, HandlerClass>
{
/**
* Indicates to the command how it should handle the {@link BasisBitmapDownloader.BasisCommand#executeEnd()} method.
*/
private enum NextResult
{
/**
* The next workflow execution has failed being registered.
*/
Failed,
/**
* The next workflow execution has properly been registered.
*/
Success,
/**
* The workflow should stop.
*/
Stop,
}
/**
* Indicates to the {@link BasisBitmapDownloader.PreCommand} what it should do eventually.
*
* @since 2011.09.02
*/
private enum FinalState
{
/**
* The bitmap is taken from the local resources, and the command is over.
*/
Local,
/**
* The bitmap was already in the memory cache, and the command is over.
*/
InCache,
/**
* The bitmap imageUid is {@code null}, there is no temporary bitmap, and the command is over.
*/
NullUriNoTemporary,
/**
* The bitmap imageUid is {@code null}, there is a temporary bitmap, and the command is over.
*/
NullUriTemporary,
/**
* The bitmap needs to be downloaded, and a download-command will be triggered.
*/
NotInCache
}
/**
* Contains extra information about a {@link BasisBitmapDownloader} instance internal state.
*
* @since 2013.12.18
*/
public static class BasisAnalyticsData
extends CoreAnalyticsData
{
public final int commandsCount;
public final int prioritiesPreStackSize;
public final int prioritiesStackSize;
public final int prioritiesDownloadStackSize;
public final int inProgressDownloadsSize;
protected BasisAnalyticsData(int bitmapsCount, int cleanUpsCount, int outOfMemoryOccurences, int commandsCount,
int prioritiesPreStackSize, int prioritiesStackSize, int prioritiesDownloadStackSize,
int inProgressDownloadsSize)
{
super(bitmapsCount, cleanUpsCount, outOfMemoryOccurences);
this.commandsCount = commandsCount;
this.prioritiesPreStackSize = prioritiesPreStackSize;
this.prioritiesStackSize = prioritiesStackSize;
this.prioritiesDownloadStackSize = prioritiesDownloadStackSize;
this.inProgressDownloadsSize = inProgressDownloadsSize;
}
}
/**
* The default number of authorized threads available in the "pre" threads pool.
*
* @see #setPreThreadPoolSize(int)
*/
public final static int PRE_THREAD_POOL_DEFAULT_SIZE = 3;
/**
* The default number of authorized threads available in the "download" threads pool.
*
* @see #setDownloadThreadPoolSize(int)
*/
public final static int DOWNLOAD_THREAD_POOL_DEFAULT_SIZE = 4;
/**
* When creating the {@link BasisBitmapDownloader#PRE_THREAD_POOL}, the number of {@link ThreadPoolExecutor#setCorePoolSize(int) core threads}.
*/
private static int PRE_THREAD_POOL_SIZE = BasisBitmapDownloader.PRE_THREAD_POOL_DEFAULT_SIZE;
/**
* The threads pool responsible for executing the pre-commands.
*/
private static ThreadPoolExecutor PRE_THREAD_POOL;
/**
* When creating the {@link BasisBitmapDownloader#DOWNLOAD_THREAD_POOL}, the number of {@link ThreadPoolExecutor#setCorePoolSize(int) core threads}.
*/
private static int DOWNLOAD_THREAD_POOL_SIZE = BasisBitmapDownloader.DOWNLOAD_THREAD_POOL_DEFAULT_SIZE;
/**
* The threads pool responsible for executing the download commands.
*/
private static ThreadPoolExecutor DOWNLOAD_THREAD_POOL;
/**
* The counter of all commands, which is incremented by one on every new command, so as to be able to determine their creation order.
*/
private static int commandOrdinalCount = -1;
/**
* The internal unique identifier of a command.
*/
private static int commandIdCount = -1;
/**
* Resets the BitmapDownloader, so that the commands count is reset to {@code 0} and so that the internal worker thread are purged.
*/
public static void reset()
{
if (log.isInfoEnabled())
{
log.info("Resetting the BitmapDownloader");
}
BasisBitmapDownloader.commandOrdinalCount = -1;
BasisBitmapDownloader.commandIdCount = -1;
if (BasisBitmapDownloader.PRE_THREAD_POOL != null)
{
BasisBitmapDownloader.PRE_THREAD_POOL.purge();
// BasisBitmapDownloader.PRE_THREAD_POOL = null;
}
if (BasisBitmapDownloader.DOWNLOAD_THREAD_POOL != null)
{
BasisBitmapDownloader.DOWNLOAD_THREAD_POOL.purge();
// BasisBitmapDownloader.DOWNLOAD_THREAD_POOL = null;
}
BasisBitmapDownloader.ANALYTICS_LISTENER = null;
}
/**
* Enables to tune how many threads at most will be available in the "pre" threads pool.
*
* @param poolSize the maximum of threads will created for handling incoming commands ; defaults to {@link #PRE_THREAD_POOL_DEFAULT_SIZE}
* @throws IllegalStateException if the this method is invoked while the threads pool has already been created, because the Android {@link ThreadPoolExecutor}
* implementation does not support properly changing this parameter dynamically
*/
public static void setPreThreadPoolSize(int poolSize)
{
if (BasisBitmapDownloader.PRE_THREAD_POOL != null)
{
throw new IllegalStateException("Cannot set the pre-threads pool core size while the threads pool has already been created!");
}
BasisBitmapDownloader.PRE_THREAD_POOL_SIZE = poolSize;
}
/**
* Enables to tune how many threads at most will be available in the "download" threads pool.
*
* @param poolSize the maximum of threads will created for handling incoming commands ; defaults to {@link #DOWNLOAD_THREAD_POOL_DEFAULT_SIZE}
* @throws IllegalStateException if the this method is invoked while the threads pool has already been created, because the Android {@link ThreadPoolExecutor}
* implementation does not support properly changing this parameter dynamically
*/
public static void setDownloadThreadPoolSize(int poolSize)
{
if (BasisBitmapDownloader.DOWNLOAD_THREAD_POOL != null)
{
throw new IllegalStateException("Cannot set the pre-threads pool core size while the threads pool has already been created!");
}
BasisBitmapDownloader.DOWNLOAD_THREAD_POOL_SIZE = poolSize;
}
private static synchronized void ensurePreThreadPool()
{
if (BasisBitmapDownloader.PRE_THREAD_POOL == null)
{
BasisBitmapDownloader.PRE_THREAD_POOL = new ThreadPoolExecutor(BasisBitmapDownloader.PRE_THREAD_POOL_SIZE, BasisBitmapDownloader.PRE_THREAD_POOL_SIZE, 5l, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new ThreadFactory()
{
private final AtomicInteger threadsCount = new AtomicInteger(0);
public Thread newThread(Runnable runnable)
{
final Thread thread = new Thread(runnable);
thread.setName("droid4me-" + (threadsCount.get() < BasisBitmapDownloader.PRE_THREAD_POOL.getCorePoolSize() ? "core-" : "") + "pre #" + threadsCount.getAndIncrement());
return thread;
}
}, new ThreadPoolExecutor.AbortPolicy());
}
}
private static synchronized void ensureDownloadThreadPool()
{
if (BasisBitmapDownloader.DOWNLOAD_THREAD_POOL == null)
{
BasisBitmapDownloader.DOWNLOAD_THREAD_POOL = new ThreadPoolExecutor(BasisBitmapDownloader.DOWNLOAD_THREAD_POOL_SIZE, BasisBitmapDownloader.DOWNLOAD_THREAD_POOL_SIZE, 5l, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new ThreadFactory()
{
private final AtomicInteger threadsCount = new AtomicInteger(0);
public Thread newThread(Runnable runnable)
{
final Thread thread = new Thread(runnable);
thread.setName("droid4me-" + (threadsCount.get() < BasisBitmapDownloader.DOWNLOAD_THREAD_POOL.getCorePoolSize() ? "core-" : "") + "download #" + threadsCount.getAndIncrement());
return thread;
}
}, new ThreadPoolExecutor.AbortPolicy());
}
}
/**
* A map which handles the priorities of the {@link BasisBitmapDownloader.PreCommand pre-commands}: when a new command for an {@link View} is asked
* for, if a {@link BasisBitmapDownloader.PreCommand} is already stacked for the same view (i.e. present in {@link #prioritiesPreStack stacked}), the old one
* will be discarded.
*/
private final Map<ViewClass, PreCommand> prioritiesPreStack;
/**
* A map which contains all the {@link BasisBitmapDownloader.PreCommand commands} that are currently at the top of the priorities stack. When a new
* command for an {@link View} is asked for, if a {@link BasisBitmapDownloader.PreCommand} is already stacked for the same view (i.e. present in
* {@link BasisBitmapDownloader#prioritiesPreStack stacked}), the old one will be discarded.
*/
private final Map<ViewClass, Integer> prioritiesStack;
/**
* A map which remembers the {@link BasisBitmapDownloader.DownloadBitmapCommand download command} which have been registered. This map allows to
* discard some commands if a new one has been registered for the same {@link View} later on.
*/
private final Map<ViewClass, DownloadBitmapCommand> prioritiesDownloadStack;
private final Set<ViewClass> asynchronousDownloadCommands;
/**
* Contains the URL of the bitmap being currently downloaded. The key is the URL, the value is a {@link DownloadingBitmap} used for the
* synchronization.
*/
private Map<String, DownloadingBitmap> inProgressDownloads;
public BasisBitmapDownloader(int instanceIndex, String name, long maxMemoryInBytes,
long lowLevelMemoryWaterMarkInBytes, boolean useReferences, boolean recycleMap)
{
super(instanceIndex, name, maxMemoryInBytes, lowLevelMemoryWaterMarkInBytes, useReferences, recycleMap);
prioritiesStack = new Hashtable<>();// Collections.synchronizedMap(new IdentityHashMap<ViewClass, Integer>());
prioritiesPreStack = new Hashtable<ViewClass, PreCommand>();// Collections.synchronizedMap(new IdentityHashMap<ViewClass, PreCommand>());
prioritiesDownloadStack = new Hashtable<ViewClass, DownloadBitmapCommand>();// Collections.synchronizedMap(new IdentityHashMap<ViewClass,
// DownloadBitmapCommand>());
inProgressDownloads = new Hashtable<String, DownloadingBitmap>();
asynchronousDownloadCommands = new HashSet<>();
BasisBitmapDownloader.ensurePreThreadPool();
BasisBitmapDownloader.ensureDownloadThreadPool();
}
/**
* {@inheritDoc}
*/
@Override
public final void get(ViewClass view, String bitmapUid, Object imageSpecs, HandlerClass handler,
BasisDownloadInstructions.Instructions<BitmapClass, ViewClass> instructions)
{
if (IS_DEBUG_TRACE && log.isInfoEnabled())
{
log.info("Starting asynchronously a command for the bitmap with uid '" + bitmapUid + "' and " + (view != null ? ("view (id='" + view.getId() + "',hash=" + view.hashCode() + ")") : "with no view") + (imageSpecs == null ? "" : (" and with specs '" + imageSpecs.toString() + "'")));
}
if (isEnabled() == false)
{
return;
}
if (view != null)
{
// We indicate to the potential asynchronous input stream downloads that a new request is now set for the bitmap
asynchronousDownloadCommands.remove(view);
// We remove a previously stacked command for the same view
final PreCommand alreadyStackedCommand = prioritiesPreStack.get(view);
if (alreadyStackedCommand != null)
{
if (IS_DEBUG_TRACE && log.isDebugEnabled())
{
log.debug("Removed an already stacked command corresponding to the view " + ("(id='" + view.getId() + "',hash=" + view.hashCode() + ")") + (alreadyStackedCommand.imageSpecs == null ? "" : (" and with specs '" + alreadyStackedCommand.imageSpecs.toString() + "'")));
}
if (BasisBitmapDownloader.PRE_THREAD_POOL.remove(alreadyStackedCommand) == false)
{
if (IS_DEBUG_TRACE && log.isDebugEnabled())
{
log.debug("The pre-command relative to view " + ("(id='" + view.getId() + "',hash=" + view.hashCode() + ")") + (alreadyStackedCommand.imageSpecs == null ? "" : (" and with specs '" + alreadyStackedCommand.imageSpecs.toString() + "'")) + " could not be removed, because its execution has already started!");
}
}
else
{
// In that case, the command is aborted and is over
instructions.onOver(true, alreadyStackedCommand.view, alreadyStackedCommand.bitmapUid, alreadyStackedCommand.imageSpecs);
}
}
}
final PreCommand command = new PreCommand(++BasisBitmapDownloader.commandIdCount, view, bitmapUid, imageSpecs, handler, instructions);
if (view != null)
{
prioritiesStack.put(view, command.id);
prioritiesPreStack.put(view, command);
dump();
}
BasisBitmapDownloader.PRE_THREAD_POOL.execute(command);
if (IS_DEBUG_TRACE && log.isInfoEnabled())
{
log.info("Pre-command with id " + command.id + " registered regarding the bitmap with uid '" + bitmapUid + "' and " + (view != null ? ("view (id='" + view.getId() + "',hash=" + view.hashCode() + ")") : "with no view") + (imageSpecs == null ? "" : (" and with specs '" + imageSpecs.toString() + "'")));
}
}
/**
* {@inheritDoc}
*/
@Override
public final void get(boolean isPreBlocking, boolean isDownloadBlocking, ViewClass view, String bitmapUid,
Object imageSpecs, HandlerClass handler,
BasisDownloadInstructions.Instructions<BitmapClass, ViewClass> instructions)
{
if (isEnabled() == false)
{
return;
}
if (isPreBlocking == false)
{
get(view, bitmapUid, imageSpecs, handler, instructions);
}
else
{
final PreCommand preCommand = new PreCommand(++BasisBitmapDownloader.commandIdCount, view, bitmapUid, imageSpecs, handler, instructions, true);
if (view != null)
{
prioritiesStack.put(view, preCommand.id);
prioritiesPreStack.put(view, preCommand);
dump();
}
preCommand.executeStart(true, isDownloadBlocking);
}
}
public synchronized void clear()
{
if (log.isInfoEnabled())
{
log.info("Clearing the cache '" + name + "'");
}
if (BasisBitmapDownloader.PRE_THREAD_POOL != null)
{
BasisBitmapDownloader.PRE_THREAD_POOL.getQueue().clear();
}
if (BasisBitmapDownloader.DOWNLOAD_THREAD_POOL != null)
{
BasisBitmapDownloader.DOWNLOAD_THREAD_POOL.getQueue().clear();
}
asynchronousDownloadCommands.clear();
prioritiesStack.clear();
prioritiesPreStack.clear();
prioritiesDownloadStack.clear();
inProgressDownloads.clear();
cache.clear();
dump();
}
@Override
protected void dump()
{
super.dump();
if (IS_DUMP_TRACE && IS_DEBUG_TRACE && log.isDebugEnabled())
{
log.debug("'" + name + "' statistics: " + "prioritiesStack.size()=" + prioritiesStack.size() + " - " + "prioritiesPreStack.size()=" + prioritiesPreStack.size() + " - " + "prioritiesDownloadStack.size()=" + prioritiesDownloadStack.size() + " - " + "inProgressDownloads.size()=" + inProgressDownloads.size());
}
}
@Override
protected CoreAnalyticsData computeAnalyticsData()
{
return new BasisAnalyticsData(cache.size(), cleanUpsCount, outOfMemoryOccurences, BasisBitmapDownloader.commandOrdinalCount, prioritiesPreStack.size(), prioritiesStack.size(), prioritiesDownloadStack.size(), inProgressDownloads.size());
}
/**
* Used for the unitary tests, in order to retrieve and control the internal state of the instance.
*/
public final void getStacks(AtomicInteger prioritiesPreStack, AtomicInteger prioritiesStack,
AtomicInteger prioritiesDownloadStack, AtomicInteger inProgressDownloads,
AtomicInteger asynchronousDownloadCommands)
{
prioritiesPreStack.set(this.prioritiesPreStack.size());
prioritiesStack.set(this.prioritiesStack.size());
prioritiesDownloadStack.set(this.prioritiesDownloadStack.size());
inProgressDownloads.set(this.inProgressDownloads.size());
asynchronousDownloadCommands.set(this.asynchronousDownloadCommands.size());
}
protected DownloadBitmapCommand computeDownloadBitmapCommand(int id, ViewClass view, String url, String bitmapUid,
Object imageSpecs, HandlerClass handler,
BasisDownloadInstructions.Instructions<BitmapClass, ViewClass> instructions)
{
return new DownloadBitmapCommand(id, view, url, bitmapUid, imageSpecs, handler, instructions);
}
private abstract class BasisCommand
implements Runnable, Comparable<BasisCommand>
{
protected final int id;
protected final ViewClass view;
protected final String bitmapUid;
protected final Object imageSpecs;
protected final HandlerClass handler;
protected final BasisDownloadInstructions.Instructions<BitmapClass, ViewClass> instructions;
protected UsedBitmap usedBitmap;
private final int ordinal = ++BasisBitmapDownloader.commandOrdinalCount;
private boolean executeEnd;
public BasisCommand(int id, ViewClass view, String bitmapUid, Object imageSpecs, HandlerClass handler,
BasisDownloadInstructions.Instructions<BitmapClass, ViewClass> instructions)
{
this(id, view, bitmapUid, imageSpecs, handler, instructions, false);
}
public BasisCommand(int id, ViewClass view, String bitmapUid, Object imageSpecs, HandlerClass handler,
BasisDownloadInstructions.Instructions<BitmapClass, ViewClass> instructions, boolean executeEnd)
{
this.id = id;
this.view = view;
this.bitmapUid = bitmapUid;
this.imageSpecs = imageSpecs;
this.handler = handler;
this.instructions = instructions;
this.executeEnd = executeEnd;
}
/**
* Introduced in order to reduce the allocation of a {@link Runnable}, and for an optimization purpose.
*/
public final void run()
{
try
{
if (executeEnd == false)
{
executeEnd = true;
executeStart(false, false);
}
else
{
executeEnd();
}
}
catch (Throwable throwable)
{
if (log.isErrorEnabled())
{
log.error(logCommandId() + "An unhandled exception has been raised during the processing of a command", throwable);
}
// We notify the caller
instructions.onOver(true, view, bitmapUid, imageSpecs);
if (view != null)
{
// In case of an exception, we forget the command
prioritiesStack.remove(view);
prioritiesDownloadStack.remove(view);
prioritiesDownloadStack.remove(view);
}
}
}
public final int compareTo(BasisCommand other)
{
if (ordinal > other.ordinal)
{
return -1;
}
else if (ordinal < other.ordinal)
{
return 1;
}
return 0;
}
public final String logCommandId()
{
return logCommandIdPrefix() + "C(" + id + ") ";
}
protected abstract void executeStart(boolean isFromGuiThread, boolean resumeWorkflowOnSameThread);
/**
* This method will always be executed in the UI thread.
*/
protected abstract void executeEnd();
/**
* @return {@code true} if the command should not execute its next workflow through the {@link BasisCommand#executeEnd()} method
*/
protected abstract boolean executeEndStillRequired();
/**
* Should always be used when the command needs to go to the next workflow by executing it in the GUI thread.
*
* @return {@code true} if the command could be properly posted
*/
protected final NextResult executeNextThroughHandler()
{
if (executeEndStillRequired() == true)
{
return handler.post(this) == true ? NextResult.Success : NextResult.Failed;
}
else
{
return NextResult.Stop;
}
}
/**
* Should always be used when the command needs to go to the next workflow by executing it from the thread.
*/
protected final void executeNext()
{
if (executeEndStillRequired() == true)
{
run();
}
}
protected final boolean wasCommandStackedMeanwhile()
{
final Integer commandId = prioritiesStack.get(view);
final boolean wasOtherCommandBeenStacked = commandId == null || commandId.intValue() != id;
return wasOtherCommandBeenStacked;
}
protected abstract String logCommandIdPrefix();
protected final boolean onBindBitmap(boolean downloaded)
{
try
{
return instructions.onBindBitmap(downloaded, view, usedBitmap.getBitmap(), bitmapUid, imageSpecs) == true;
}
catch (OutOfMemoryError exception)
{
if (log.isWarnEnabled())
{
log.warn(logCommandId() + "Process exceeding available memory", exception);
}
outOfMemoryOccurences++;
cleanUpCache();
throw exception;
}
}
protected final void onBitmapReady(boolean allright, BitmapClass bitmap)
{
try
{
instructions.onBitmapReady(allright, view, bitmap, bitmapUid, imageSpecs);
}
catch (OutOfMemoryError exception)
{
if (log.isWarnEnabled())
{
log.warn(logCommandId() + "Process exceeding available memory", exception);
}
outOfMemoryOccurences++;
cleanUpCache();
}
}
}
// TODO: define a pool of Command objects, so as to minimize GC, if possible
private final class PreCommand
extends BasisCommand
{
/**
* This flag will be used when executing the {@link #run} method the second time.
*/
private BasisBitmapDownloader.FinalState state;
public PreCommand(int id, ViewClass view, String bitmapUid, Object imageSpecs, HandlerClass handler,
BasisDownloadInstructions.Instructions<BitmapClass, ViewClass> instructions)
{
super(id, view, bitmapUid, imageSpecs, handler, instructions);
}
public PreCommand(int id, ViewClass view, String bitmapUid, Object imageSpecs, HandlerClass handler,
BasisDownloadInstructions.Instructions<BitmapClass, ViewClass> instructions, boolean executeEnd)
{
super(id, view, bitmapUid, imageSpecs, handler, instructions, executeEnd);
}
@Override
protected void executeStart(boolean isFromGuiThread, boolean resumeWorkflowOnSameThread)
{
if (IS_DEBUG_TRACE && log.isDebugEnabled())
{
log.debug(logCommandId() + "Starting to handle in thread '" + Thread.currentThread().getName() + "' the pre-command for the bitmap with uid '" + bitmapUid + "'" + (view != null ? " corresponding to the view " + ("(id='" + view.getId() + "',hash=" + view.hashCode() + ")") : "") + (imageSpecs == null ? "" : (" and with specs '" + imageSpecs.toString() + "'")));
}
// The command is removed from the priority stack
if (view != null)
{
prioritiesPreStack.remove(view);
dump();
}
// We set a local bitmap if available
if (setLocalBitmapIfPossible(isFromGuiThread) == true)
{
if (IS_DEBUG_TRACE && log.isDebugEnabled())
{
log.debug(logCommandId() + "Some local availability has been detected for the bitmap with uid '" + bitmapUid + "'" + (view != null ? " corresponding to the view " + ("(id='" + view.getId() + "',hash=" + view.hashCode() + ")") : "") + (imageSpecs == null ? "" : (" and with specs '" + imageSpecs.toString() + "'")));
}
return;
}
// We compute the bitmap URL and proceed
final String url = instructions.computeUrl(bitmapUid, imageSpecs);
// We use a bitmap from the cache if possible
if (setBitmapFromCacheIfPossible(url, isFromGuiThread) == true)
{
if (IS_DEBUG_TRACE && log.isDebugEnabled())
{
log.debug(logCommandId() + "Some caching availability has been detected for the bitmap with uid '" + bitmapUid + "'" + (view != null ? " corresponding to the view " + ("(id='" + view.getId() + "',hash=" + view.hashCode() + ")") : "") + (imageSpecs == null ? "" : (" and with specs '" + imageSpecs.toString() + "'")));
}
return;
}
// We set a temporary bitmap, if available
setTemporaryBitmapIfPossible(isFromGuiThread, url);
// We handle the special case of a null bitmap URL
if (url == null)
{
// We need to do that in the GUI thread!
state = state == FinalState.NotInCache ? FinalState.NullUriTemporary : FinalState.NullUriNoTemporary;
if (isFromGuiThread == false)
{
if (executeNextThroughHandler() == NextResult.Failed)
{
if (log.isWarnEnabled())
{
log.warn(logCommandId() + "Failed to notify the instructions regarding a bitmap with null id from the GUI thread");
}
}
}
else
{
executeNext();
}
// We do not want to go any further, since the URL is null, and the work is completed
return;
}
skipToDownloadCommand(url, resumeWorkflowOnSameThread);
}
/**
* The {@link BasisBitmapDownloader.PreCommand#view} is ensured not to be null when this method is invoked.
*/
@Override
protected void executeEnd()
{
if (IS_DEBUG_TRACE && log.isDebugEnabled())
{
log.debug(logCommandId() + "Running the action in state '" + state + "' for the bitmap with uid '" + bitmapUid + "'");
}
try
{
switch (state)
{
case Local:
instructions.onBindLocalBitmap(view, usedBitmap.getBitmap(), bitmapUid, imageSpecs);
instructions.onBitmapBound(true, view, bitmapUid, imageSpecs);
instructions.onOver(false, view, bitmapUid, imageSpecs);
if (IS_DEBUG_TRACE && log.isDebugEnabled())
{
log.debug(logCommandId() + "Set the local drawable for the bitmap with uid '" + bitmapUid + "'");
}
break;
case InCache:
boolean success = false;
try
{
success = onBindBitmap(false);
}
finally
{
if (success != true)
{
instructions.onBitmapBound(false, view, bitmapUid, imageSpecs);
}
}
if (success != true)
{
instructions.onOver(true, view, bitmapUid, imageSpecs);
return;
}
if (IS_DEBUG_TRACE && log.isDebugEnabled())
{
log.debug(logCommandId() + "Bound the bitmap with uid '" + bitmapUid + "' to the view " + ("(id='" + view.getId() + "',hash=" + view.hashCode() + ")") + (imageSpecs == null ? "" : (" and with specs '" + imageSpecs.toString() + "'")));
}
usedBitmap.forgetBitmap();
usedBitmap.rememberBinding(view);
instructions.onBitmapBound(true, view, bitmapUid, imageSpecs);
instructions.onOver(false, view, bitmapUid, imageSpecs);
if (IS_DEBUG_TRACE && log.isDebugEnabled())
{
log.debug(logCommandId() + "Used the cached bitmap with uid '" + bitmapUid + "'");
}
break;
case NullUriNoTemporary:
instructions.onBitmapBound(false, view, bitmapUid, imageSpecs);
instructions.onOver(false, view, bitmapUid, imageSpecs);
if (IS_DEBUG_TRACE && log.isDebugEnabled())
{
log.debug(logCommandId() + "Did not set any temporary bitmap for a null bitmap id");
}
break;
case NullUriTemporary:
instructions.onBindTemporaryBitmap(view, usedBitmap.getBitmap(), bitmapUid, imageSpecs);
instructions.onBitmapBound(false, view, bitmapUid, imageSpecs);
instructions.onOver(false, view, bitmapUid, imageSpecs);
if (IS_DEBUG_TRACE && log.isDebugEnabled())
{
log.debug(logCommandId() + "Set the temporary bitmap for a null bitmap URL");
}
break;
case NotInCache:
instructions.onBindTemporaryBitmap(view, usedBitmap.getBitmap(), bitmapUid, imageSpecs);
if (IS_DEBUG_TRACE && log.isDebugEnabled())
{
log.debug(logCommandId() + "Set the temporary bitmap with uid '" + bitmapUid + "'");
}
break;
}
}
finally
{
// We clear the priorities stack if the work is over for that command (i.e. no DownloadBitmapCommand is required)
if (state != FinalState.NotInCache && view != null)
{
prioritiesStack.remove(view);
if (IS_DEBUG_TRACE && log.isDebugEnabled())
{
log.debug(logCommandId() + "Removed from the priority stack the view (id='" + view.getId() + "',hash=" + view.hashCode() + ")");
}
dump();
}
}
}
@Override
protected boolean executeEndStillRequired()
{
if (view == null)
{
return true;
}
// We only continue the process (and the temporary or local bitmap view binding) provided there is not already another command bound to be
// processed for the same view
if (state != FinalState.NotInCache && wasCommandStackedMeanwhile() == true)
{
instructions.onOver(true, view, bitmapUid, imageSpecs);
if (log.isDebugEnabled())
{
log.debug(logCommandId() + "The bitmap corresponding to the uid '" + bitmapUid + "' will not be bound to its view, because this bitmap has asked for another bitmap URL in the meantime");
}
return false;
}
return true;
}
@Override
protected String logCommandIdPrefix()
{
return "P";
}
/**
* @return {@code true} if and only if a local bitmap should be used
*/
private boolean setLocalBitmapIfPossible(boolean isFromGuiThread)
{
final BitmapClass bitmap = view == null ? null : instructions.hasLocalBitmap(view, bitmapUid, imageSpecs);
if (bitmap != null)
{
if (view != null)
{
usedBitmap = new UsedBitmap(bitmap, null);
// We need to do that in the GUI thread!
state = FinalState.Local;
if (isFromGuiThread == false)
{
if (executeNextThroughHandler() == NextResult.Failed)
{
if (log.isWarnEnabled())
{
log.warn(logCommandId() + "Failed to apply that local resource for the bitmap with uid '" + bitmapUid + "'");
}
}
}
else
{
executeNext();
}
return true;
}
}
return false;
}
private void setTemporaryBitmapIfPossible(boolean isFromGuiThread, String url)
{
final BitmapClass bitmap = view == null ? null : instructions.hasTemporaryBitmap(view, bitmapUid, imageSpecs);
if (bitmap != null)
{
if (view != null)
{
usedBitmap = new UsedBitmap(bitmap, url);
state = FinalState.NotInCache;
// Beware: we have a special handling in the caller method if the bitmap URL is null!
if (url != null)
{
// We need to do that in the GUI thread!
if (isFromGuiThread == false)
{
if (executeNextThroughHandler() == NextResult.Failed)
{
if (log.isWarnEnabled())
{
log.warn(logCommandId() + "Failed to apply the temporary for the bitmap with uid '" + bitmapUid + "'");
}
}
}
else
{
executeNext();
}
}
}
}
}
private boolean setBitmapFromCacheIfPossible(String url, boolean isFromGuiThread)
{
// There is a special case when the bitmap URL is null
if (url == null)
{
// We do not want to attempt retrieving a cached bitmap corresponding to a null URL
return false;
}
// We check that the bitmap is not already in the cache
final UsedBitmap otherUsedBitmap = getUsedBitmapFromCache(url);
if (otherUsedBitmap != null)
{
usedBitmap = otherUsedBitmap;
usedBitmap.rememberAccessed();
onBitmapReady(true, usedBitmap.getBitmap());
if (view != null)
{
if (IS_DEBUG_TRACE && log.isDebugEnabled())
{
log.debug(logCommandId() + "Re-using the cached bitmap for the URL '" + url + "'");
}
// It is possible that no bitmap exists for that URL
// We need to do that in the GUI thread!
state = FinalState.InCache;
if (isFromGuiThread == false)
{
if (executeNextThroughHandler() == NextResult.Failed)
{
if (log.isWarnEnabled())
{
log.warn(logCommandId() + "Failed to apply that cached bitmap with uid '" + bitmapUid + "' relative to the URL '" + url + "'");
}
}
}
else
{
executeNext();
}
}
else
{
if (IS_DEBUG_TRACE && log.isDebugEnabled())
{
log.debug(logCommandId() + "The bitmap with uid '" + bitmapUid + "' relative to the URL '" + url + "' is null: no need to apply its cached bitmap");
}
}
return true;
}
return false;
}
private void skipToDownloadCommand(final String url, boolean resumeWorkflowOnSameThread)
{
// We want to remove any pending download command for the view
if (view != null)
{
// But we test whether the download is still required
if (wasCommandStackedMeanwhile() == true)
{
if (IS_DEBUG_TRACE && log.isDebugEnabled())
{
log.debug(logCommandId() + "Because another command has been stacked for the same view in the meantime, aborting the command corresponding to the view with uid '" + bitmapUid + "'" + (view != null ? " corresponding to the view " + ("(id='" + view.getId() + "',hash=" + view.hashCode() + ")") : "") + (imageSpecs == null ? "" : (" and with specs '" + imageSpecs.toString() + "'")));
}
instructions.onOver(true, view, bitmapUid, imageSpecs);
return;
}
// We remove a previously stacked command for the same view
final DownloadBitmapCommand alreadyStackedCommand = prioritiesDownloadStack.get(view);
if (alreadyStackedCommand != null)
{
if (IS_DEBUG_TRACE && log.isDebugEnabled())
{
log.debug(logCommandId() + "Removing an already stacked download command corresponding to the view " + ("(id='" + view.getId() + "',hash=" + view.hashCode() + ")") + (imageSpecs == null ? "" : (" and with specs '" + imageSpecs.toString() + "'")));
}
if (BasisBitmapDownloader.DOWNLOAD_THREAD_POOL.remove(alreadyStackedCommand) == false)
{
// This may happen if the download command has already started
}
else
{
instructions.onOver(true, alreadyStackedCommand.view, alreadyStackedCommand.bitmapUid, alreadyStackedCommand.imageSpecs);
}
}
}
// We need to download the bitmap or take it from a local persistence place
// Hence, we stack the bitmap download command
final DownloadBitmapCommand downloadCommand = computeDownloadBitmapCommand(id, view, url, bitmapUid, imageSpecs, handler, instructions);
if (view != null)
{
prioritiesDownloadStack.put(view, downloadCommand);
dump();
}
if (resumeWorkflowOnSameThread == false)
{
BasisBitmapDownloader.DOWNLOAD_THREAD_POOL.execute(downloadCommand);
}
else
{
// In that case, we want the workflow to keep on running from the calling thread
downloadCommand.executeStart(true, false);
}
}
}
protected class DownloadBitmapCommand
extends BasisCommand
implements InputStreamDownloadInstructor
{
protected final String url;
private boolean downloaded;
private boolean inputStreamAsynchronous;
/**
* When not negative, the timestamp corresponding to the time when the underlying bitmap started to be downloaded.
*/
private long downloadStartTimestamp = -1;
public DownloadBitmapCommand(int id, ViewClass view, String url, String bitmapUid, Object imageSpecs,
HandlerClass handler, BasisDownloadInstructions.Instructions<BitmapClass, ViewClass> instructions)
{
super(id, view, bitmapUid, imageSpecs, handler, instructions);
this.url = url;
}
public final void setAsynchronous()
{
inputStreamAsynchronous = true;
}
public final void onDownloaded(InputStream inputStream)
{
try
{
try
{
inputStream = onInputStreamDownloaded(inputStream);
downloaded = true;
}
catch (OutOfMemoryError exception)
{
if (log.isWarnEnabled())
{
log.warn(logCommandId() + "Process exceeding available memory", exception);
}
outOfMemoryOccurences++;
cleanUpCache();
return;
}
// We first check for the input stream
if (inputStream == null)
{
onBitmapReady(false, null);
return;
}
// We attempt to convert the input stream into a bitmap
final BitmapClass bitmap = fromInputStreamToBitmapable(inputStream);
if (bitmap == null)
{
onBitmapReady(false, null);
return;
}
// We put in cache the bitmap
usedBitmap = putInCache(url, bitmap);
onBitmapReady(true, bitmap);
// Indicates whether another command has been set for the view in the meantime
if (view != null && asynchronousDownloadCommands.remove(view) == true)
{
bindBitmap();
}
}
finally
{
try
{
inputStream.close();
}
catch (IOException exception)
{
// Does not really matter
if (log.isErrorEnabled())
{
log.error("Could not close the input stream corresponding to downloaded bitmap corresponding to the image with uid '" + bitmapUid + "'", exception);
}
}
}
}
@Override
protected void executeStart(boolean isFromGuiThread, boolean resumeWorkflowOnSameThread)
{
if (IS_DEBUG_TRACE && log.isDebugEnabled())
{
log.debug(logCommandId() + "Starting to handle in thread '" + Thread.currentThread().getName() + "' the download command for the bitmap with uid '" + bitmapUid + "'" + (view != null ? " corresponding to the view " + ("(id='" + view.getId() + "',hash=" + view.hashCode() + ")") : "") + (imageSpecs == null ? "" : (" and with specs '" + imageSpecs.toString() + "'")));
}
// The command is removed from the priority stack
if (view != null)
{
prioritiesDownloadStack.remove(view);
dump();
}
// We need to check whether the same URL has not been downloaded in the meantime
final UsedBitmap otherUsedBitmap = getUsedBitmapFromCache(url);
if (otherUsedBitmap == null)
{
// If the bitmap is not already in memory, we retrieve it
// But, before that, we check whether the same bitmap would not be currently downloading
final BitmapClass bitmap;
final DownloadingBitmap downloadingBitmap;
synchronized (inProgressDownloads)
{
downloadingBitmap = inProgressDownloads.get(url);
}
if (downloadingBitmap != null)
{
downloadingBitmap.referencesCount++;
if (IS_DEBUG_TRACE && log.isDebugEnabled())
{
log.debug(logCommandId() + "Waiting for the bitmap corresponding to the URL '" + url + "' to be downloaded" + (view != null ? " regarding the view " + ("(id='" + view.getId() + "',hash=" + view.hashCode() + ")") : "") + (imageSpecs == null ? "" : (" and with specs '" + imageSpecs.toString() + "'")));
}
synchronized (downloadingBitmap)
{
// We wait for the other download to complete
bitmap = downloadingBitmap.bitmap;
downloadingBitmap.referencesCount--;
usedBitmap = downloadingBitmap.usedBitmap;
if (downloadingBitmap.referencesCount <= 0)
{
inProgressDownloads.remove(url);
}
}
}
else
{
final DownloadingBitmap newDownloadingBitmap;
synchronized (inProgressDownloads)
{
newDownloadingBitmap = new DownloadingBitmap();
inProgressDownloads.put(url, newDownloadingBitmap);
}
synchronized (newDownloadingBitmap)
{
BitmapClass retrievedBitmap = null;
try
{
retrievedBitmap = retrieveBitmap();
}
catch (Throwable throwable)
{
// We want to make sure that the process resumes if a problem occurred during the retrieval of the bitmap
if (log.isWarnEnabled())
{
log.warn(logCommandId() + "An unattended problem occurred while retrieving the bitmap with uid '" + bitmapUid + "' corresponding to the URL '" + url + "'", throwable);
}
}
bitmap = retrievedBitmap;
if (bitmap != null)
{
// If the bitmap is not null, we cache it immediately
usedBitmap = putInCache(url, bitmap);
newDownloadingBitmap.usedBitmap = usedBitmap;
}
// A minor optimization
if (newDownloadingBitmap.referencesCount <= 0)
{
inProgressDownloads.remove(url);
}
newDownloadingBitmap.bitmap = bitmap;
if (inputStreamAsynchronous == true)
{
return;
}
}
}
if (bitmap == null)
{
// This happens either when the bitmap URL is null, or when the bitmap retrieval failed
if (inputStreamAsynchronous == false)
{
if (url != null && url.length() >= 1)
{
if (log.isWarnEnabled())
{
log.warn(logCommandId() + "The bitmap with uid '" + bitmapUid + "' relative to the URL '" + url + "' is null");
}
}
}
// We let intentionally the 'usedBitmap' null
}
}
else
{
// Otherwise, we reuse it
usedBitmap = otherUsedBitmap;
usedBitmap.rememberAccessed();
}
onBitmapReady(usedBitmap != null && usedBitmap.getBitmap() != null, usedBitmap == null ? null : usedBitmap.getBitmap());
bindBitmap();
}
/**
* The {@link BasisBitmapDownloader.PreCommand#view} is ensured not to be null when this method is invoked.
*/
@Override
protected void executeEnd()
{
try
{
if (usedBitmap != null)
{
boolean success = false;
try
{
success = onBindBitmap(downloaded);
}
finally
{
if (success != true)
{
instructions.onBitmapBound(false, view, bitmapUid, imageSpecs);
}
}
if (success != true)
{
instructions.onOver(true, view, bitmapUid, imageSpecs);
return;
}
if (IS_DEBUG_TRACE && log.isDebugEnabled())
{
log.debug(logCommandId() + "Bound the bitmap with uid '" + bitmapUid + "' to the view " + ("(id='" + view.getId() + "',hash=" + view.hashCode() + ")") + (imageSpecs == null ? "" : (" and with specs '" + imageSpecs.toString() + "'")));
}
usedBitmap.forgetBitmap();
usedBitmap.rememberBinding(view);
}
instructions.onBitmapBound(usedBitmap != null, view, bitmapUid, imageSpecs);
instructions.onOver(false, view, bitmapUid, imageSpecs);
}
finally
{
// We clear the priorities stack because the work is over for that command
{
prioritiesStack.remove(view);
if (IS_DEBUG_TRACE && log.isDebugEnabled())
{
log.debug(logCommandId() + "Removed from the priority stack the view" + (view != null ? " " + ("(id='" + view.getId() + "',hash=" + view.hashCode() + ")") : ""));
}
dump();
}
}
}
@Override
protected boolean executeEndStillRequired()
{
if (view == null)
{
return true;
}
// We only bind the bitmap to the view provided there is not already another command bound to be processed
if (wasCommandStackedMeanwhile() == true)
{
if (IS_DEBUG_TRACE && log.isDebugEnabled())
{
log.debug(logCommandId() + "The bitmap corresponding to the URL '" + url + "' will not be bound to its view" + (view != null ? " " + ("(id='" + view.getId() + "',hash=" + view.hashCode() + ")") : "") + ", because its related view has been requested again in the meantime");
}
instructions.onOver(true, view, bitmapUid, imageSpecs);
return false;
}
return true;
}
@Override
protected String logCommandIdPrefix()
{
return "D";
}
protected InputStream onInputStreamDownloaded(InputStream inputStream)
{
return instructions.onInputStreamDownloaded(bitmapUid, imageSpecs, url, inputStream);
}
/**
* This method assumes that the provided <code>inputStream</code> is not {@code null}.
*
* @param inputStream an input stream corresponding to a bitmap or a gif
* @return {@code null} if the input stream could not be properly converted ; a valid bitmap otherwise
*/
protected BitmapClass fromInputStreamToBitmapable(InputStream inputStream)
{
try
{
final BitmapClass bitmap = instructions.convert(inputStream, bitmapUid, imageSpecs, url);
if (bitmap == null)
{
if (log.isWarnEnabled())
{
log.warn(logCommandId() + "Could not turn properly into a valid bitmap the input stream corresponding to the bitmap with uid '" + bitmapUid + "', related to the URL '" + url + "'");
}
}
return bitmap;
}
catch (OutOfMemoryError exception)
{
if (log.isWarnEnabled())
{
log.warn(logCommandId() + "Cannot decode the downloaded bitmap because it exceeds the allowed memory", exception);
}
outOfMemoryOccurences++;
cleanUpCache();
return null;
}
}
/**
* Is responsible for getting the bitmap, either from the local persisted cache, and if not available from Internet.
*
* @return {@code null}, in particular, if the underlying bitmap URL is null or empty
*/
private final BitmapClass retrieveBitmap()
{
final InputStream inputStream;
try
{
inputStream = fetchInputStream();
}
catch (IOException exception)
{
if (log.isWarnEnabled())
{
log.warn(logCommandId() + "Could not access to the bitmap with uid '" + bitmapUid + "' relative to the URL '" + url + "'");
}
return null;
}
if (inputStream == null)
{
if (inputStreamAsynchronous == false)
{
if (url != null && url.length() >= 1)
{
if (log.isWarnEnabled())
{
log.warn(logCommandId() + "The input stream used to build the bitmap with uid '" + bitmapUid + "' relative to to the URL '" + url + "' is null");
}
}
}
return null;
}
try
{
final BitmapClass bitmap = fromInputStreamToBitmapable(inputStream);
if (downloadStartTimestamp >= 0)
{
final long stop = System.currentTimeMillis();
if (log.isDebugEnabled())
{
log.debug(logCommandId() + "The thread '" + Thread.currentThread().getName() + "' downloaded and transformed in " + (stop - downloadStartTimestamp) + " ms the bitmap with uid '" + bitmapUid + "' relative to the URL '" + url + "'");
}
}
return bitmap;
}
finally
{
if (inputStream != null)
{
try
{
inputStream.close();
}
catch (IOException exception)
{
// Does not really matter
if (log.isErrorEnabled())
{
log.error("Could not close the input stream corresponding to the image with uid '" + bitmapUid + "'", exception);
}
}
}
}
}
/**
* @return {@code null}, in particular, when either if the URL is null or empty
* @throws IOException if an IO problem occurred while retrieving the bitmap stream
*/
private final InputStream fetchInputStream()
throws IOException
{
{
final InputStream inputStream;
// We do not event attempt to request for the input stream if the bitmap URI is null or empty
if (url != null && url.length() >= 1)
{
try
{
inputStream = instructions.getInputStream(bitmapUid, imageSpecs, url, this);
}
catch (IOException exception)
{
if (log.isWarnEnabled())
{
log.warn(logCommandId() + "Could not get the provided input stream for the bitmap with uid '" + bitmapUid + "' relative to the URL '" + url + "'", exception);
}
// In that case, we consider that the input stream custom download was a failure
throw exception;
}
}
else
{
return null;
}
if (inputStream != null)
{
if (IS_DEBUG_TRACE && log.isDebugEnabled())
{
log.debug(logCommandId() + "Using the provided input stream corresponding to the URL '" + url + "'");
}
return inputStream;
}
}
// We determine whether the input stream has turned asynchronous
if (inputStreamAsynchronous == true)
{
asynchronousDownloadCommands.add(view);
return null;
}
try
{
return downloadInputStream();
}
catch (OutOfMemoryError exception)
{
if (log.isWarnEnabled())
{
log.warn(logCommandId() + "Process exceeding available memory", exception);
}
outOfMemoryOccurences++;
cleanUpCache();
return null;
}
}
/**
* Is responsible for actually downloading the input stream corresponding to the bitmap.
*
* @return the input stream corresponding to the bitmap ; should not return {@code null} but throw an exception instead when the input stream
* cannot be downloaded in case of download attempt error, and {@code null} if no Internet connectivity is available
* @throws IOException if a problem occurred during the download
*/
private InputStream downloadInputStream()
throws IOException
{
downloadStartTimestamp = System.currentTimeMillis();
if (isConnected() == false)
{
return null;
}
final InputStream inputStream = instructions.downloadInputStream(bitmapUid, imageSpecs, url);
final InputStream downloadedInputStream = onInputStreamDownloaded(inputStream);
downloaded = true;
return downloadedInputStream;
}
/**
* The method will do nothing if the {@link #view} is {@code null}.
*/
private final void bindBitmap()
{
// We need to bind the bitmap to the view in the GUI thread!
if (view != null)
{
if (executeNextThroughHandler() == NextResult.Failed)
{
if (log.isWarnEnabled())
{
log.warn(logCommandId() + "Failed to apply the downloaded bitmap for the bitmap with uid '" + bitmapUid + "' relative to the URL '" + url + "'");
}
}
}
}
}
/**
* An internal class used when donwloading a bitmap.
*/
private final class DownloadingBitmap
{
private BitmapClass bitmap;
private int referencesCount;
private UsedBitmap usedBitmap;
}
}
| 36.043506 | 393 | 0.623579 |
4f0c8cda58aad67ef7d5fd2625d14f964e329acb | 628 | package com.sequenceiq.cloudbreak.service.secret.vault;
public class VaultConfigException extends RuntimeException {
public VaultConfigException() {
}
public VaultConfigException(String message) {
super(message);
}
public VaultConfigException(String message, Throwable cause) {
super(message, cause);
}
public VaultConfigException(Throwable cause) {
super(cause);
}
public VaultConfigException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
| 26.166667 | 121 | 0.721338 |
62cf7188560503757bbf08aaa232f6d0ae5fb4df | 1,028 | package com.rozvi14.facialrecognition;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
public class MyMessagingService extends FirebaseMessagingService {
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
showNotification(remoteMessage.getNotification().getTitle(),remoteMessage.getNotification().getBody());
}
public void showNotification(String title, String message){
NotificationCompat.Builder builder = new NotificationCompat.Builder(this,"my-channel")
.setContentTitle(title)
.setSmallIcon(R.drawable.logo)
.setAutoCancel(true)
.setContentText(message);
NotificationManagerCompat manager = NotificationManagerCompat.from(this);
manager.notify(999,builder.build());
}
}
| 38.074074 | 111 | 0.741245 |
451482b6d593aeed06d9b935ba5e7f0dc26032f5 | 3,965 | package com.smt.kata.code;
import java.util.*;
/****************************************************************************
* <b>Title</b>: MorseCodeTranslator.java
* <b>Project</b>: SMT-Kata
* <b>Description: </b> Morse Code converter. Take any phrase and convert it to
* its morse code equivelant and decode a morse code phrase back to english. In morse
* code, spaces separate the letters and " / " separates words
* <b>Copyright:</b> Copyright (c) 2021
* <b>Company:</b> Silicon Mountain Technologies
*
* @author James Camire
* @version 3.0
* @since Mar 15, 2021
* @updates:
****************************************************************************/
public class MorseCodeTranslator {
Map<String,String> morse;
/**
*
*/
public MorseCodeTranslator() {
super();
Map<String, String> morse = new HashMap<String, String>();
morse.put("A", ".-");
morse.put("B", "-...");
morse.put("C", "-.-.");
morse.put("D", "-..");
morse.put("E", ".");
morse.put("F", "..-.");
morse.put("G", "--.");
morse.put("H", "....");
morse.put("I", "..");
morse.put("J", ".---");
morse.put("K", "-.-");
morse.put("L", ".-..");
morse.put("M", "--");
morse.put("N", "-.");
morse.put("O", "---");
morse.put("P", ".--.");
morse.put("Q", "--.-");
morse.put("R", ".-.");
morse.put("S", "...");
morse.put("T", "-");
morse.put("U", "..-");
morse.put("V", "...-");
morse.put("W", ".--");
morse.put("X", "-..-");
morse.put("Y", "-.--");
morse.put("Z", "--..");
morse.put("1", ".----");
morse.put("2", "..---");
morse.put("3", "...--");
morse.put("4", "....-");
morse.put("5", ".....");
morse.put("6", "-....");
morse.put("7", "--...");
morse.put("8", "---..");
morse.put("9", "----.");
morse.put("0", "-----");
this.morse = morse;
}
/**
* Converts a phrase or word into morse code
* @param phrase any set of characters or numbers
* @return Morse code as a space delimited document
*/
public String encode(String phrase) {
if(phrase == null || phrase.length() == 0) return "";
String output = "";
String[] words = phrase.split(" ");
for(int x = 0; x < words.length; x++) {
char[] letters = words[x].toCharArray();
for(int y = 0; y < letters.length; y++) {
String val = this.morse.get(letters[y] + "");
if(val != null) {
output += val;
if(y != letters.length - 1) output += " ";
}
}
if(x != words.length - 1) output += " / ";
}
return output;
}
/**
* Decodes a morse code encoded phrase
* @param encodedPhrase Uses spaces as the letter delimiter and / as the word delimiter
* @return English phrase decoded form the morse code snippet
*/
public String decode(String encodedPhrase) {
if(encodedPhrase == null || encodedPhrase.length() == 0) return "";
String output = "";
String[] words = encodedPhrase.split(" / ");
for(int x = 0; x < words.length; x++) {
String[] letters = words[x].split(" ");
for(int y = 0; y < letters.length; y++) {
String xx = getKeyByValue(letters[y]);
if(xx != null) output += xx;
}
if(x != words.length - 1) output += " ";
}
return output;
}
public String getKeyByValue(String value) {
for (Entry<String, String> entry : this.morse.entrySet()) {
if (value.equals(entry.getValue())) return entry.getKey();
}
return null;
}
}
| 32.5 | 91 | 0.44111 |
260cc91ed32269e1652c4deec241b60e73326b04 | 5,908 | package fishmaple.utils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import fishmaple.thirdPart.baiduWebWorm.BaiduSearchObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.client.RestTemplate;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;
public class HttpClientUtil {
static Logger logger = LoggerFactory.getLogger(HttpClient.class);
public static Map<String,String> getHttpreturnMap(String urlStr) throws IOException {
URL url = new URL(urlStr);//爬取的网址
URLConnection urlconn = url.openConnection();
InputStream in=urlconn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
StringBuffer sb = new StringBuffer();
String s;
while((s=reader.readLine()) != null){
sb.append(s+"\n");
}
reader.close();
Map map=JSON.parseObject(sb.toString());
return map;
}
public static void pushBlog(String id){
try {
Thread.sleep(4000);
RestTemplate restTemplate = new RestTemplate();
org.springframework.http.HttpEntity<String> formEntity = new org.springframework.http.HttpEntity<String>("https://www.fishmaple.cn/blog/d?bid=" + id);
String a = restTemplate.postForObject("http://data.zz.baidu.com/urls?site=www.fishmaple.cn&token=-",
formEntity, String.class);
System.out.println("推送" + a + id);
}catch (Exception e){
e.printStackTrace();
pushBlog(id);
}
}
/**
* post请求(用于请求json格式的参数)
* @param url
* @param params
* @return
*/
public static String doPost(String url, String params) throws Exception {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);// 创建httpPost
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-Type", "application/json");
String charSet = "UTF-8";
StringEntity entity = new StringEntity(params, charSet);
httpPost.setEntity(entity);
CloseableHttpResponse response = null;
try {
response = httpclient.execute(httpPost);
StatusLine status = response.getStatusLine();
int state = status.getStatusCode();
if (state == HttpStatus.SC_OK) {
HttpEntity responseEntity = response.getEntity();
String jsonString = EntityUtils.toString(responseEntity);
return jsonString;
}
else{
logger.error("请求返回:"+state+"("+url+")");
}
}
finally {
if (response != null) {
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public static String post(String strURL, String params) {
try {
// 创建连接
URL url = new URL(strURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
// 设置请求方式
connection.setRequestMethod("POST");
// 设置接收数据的格式
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
connection.connect();
// utf-8编码
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
out.append(params);
out.flush();
out.close();
// 读取响应 获取长度
int length = (int) connection.getContentLength();
InputStream is = connection.getInputStream();
if (length != -1) {
byte[] data = new byte[length];
byte[] temp = new byte[512];
int readLen = 0;
int destPos = 0;
while ((readLen = is.read(temp)) > 0) {
System.arraycopy(temp, 0, data, destPos, readLen);
destPos += readLen;
}
// utf-8编码
String result = new String(data, "UTF-8");
return result;
}
} catch (IOException e) {
e.printStackTrace();
}
return "error";
}
public static String getHttpreturnStr(String urlStr) throws IOException {
URL url = new URL(urlStr);//爬取的网址
URLConnection urlconn = url.openConnection();
InputStream in=urlconn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
StringBuffer sb = new StringBuffer();
String s;
while((s=reader.readLine()) != null){
sb.append(s+"\n");
}
reader.close();
return sb.toString();
}
}
| 35.590361 | 162 | 0.590386 |
3c0f5c5beab4a8e680ad340ebcdd9b20ad28bd80 | 372 | package com.goodworkalan.manifold;
// TODO Document.
public class Close implements Runnable {
// TODO Document.
private final Conversation conversation;
// TODO Document.
public Close(Conversation conversation) {
this.conversation = conversation;
}
// TODO Document.
public void run() {
conversation.session.close();
}
}
| 20.666667 | 45 | 0.666667 |
84c7114cb4d480a74e9217938ff4619078e723df | 2,396 | /*
* Copyright (C) 2009 The Android Open Source Project
*
* 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.
*/
public class Main {
static public void main(String[] args) {
try {
PublicAccess.accessStaticField();
System.err.println("ERROR: call 1 not expected to succeed");
} catch (VerifyError ve) {
// dalvik
System.out.println("Got expected failure 1");
} catch (IllegalAccessError iae) {
// reference
System.out.println("Got expected failure 1");
}
try {
PublicAccess.accessStaticMethod();
System.err.println("ERROR: call 2 not expected to succeed");
} catch (IllegalAccessError iae) {
// reference
System.out.println("Got expected failure 2");
}
try {
PublicAccess.accessInstanceField();
System.err.println("ERROR: call 3 not expected to succeed");
} catch (VerifyError ve) {
// dalvik
System.out.println("Got expected failure 3");
} catch (IllegalAccessError iae) {
// reference
System.out.println("Got expected failure 3");
}
try {
PublicAccess.accessInstanceMethod();
System.err.println("ERROR: call 4 not expected to succeed");
} catch (IllegalAccessError iae) {
// reference
System.out.println("Got expected failure 4");
}
try {
CheckInstanceof.main(new Object());
System.err.println("ERROR: call 5 not expected to succeed");
} catch (VerifyError ve) {
// dalvik
System.out.println("Got expected failure 5");
} catch (IllegalAccessError iae) {
// reference
System.out.println("Got expected failure 5");
}
}
}
| 34.724638 | 75 | 0.594324 |
6485739c59acdd857ff6bf09d4b4567af87b82e4 | 36,996 | package org.basex.qt3ts.op;
import org.basex.tests.bxapi.*;
import org.basex.tests.qt3ts.*;
/**
* Tests for the gYearMonth-equal() function.
*
* @author BaseX Team 2005-15, BSD License
* @author Leo Woerteler
*/
@SuppressWarnings("all")
public class OpGYearMonthEqual extends QT3TestSet {
/**
*
* *******************************************************
* Test: K-gYearMonthEQ-1
* Written by: Frans Englich
* Date: 2007-11-22T11:31:21+01:00
* Purpose: Simple test of 'eq' for xs:gYearMonth, returning positive.
* *******************************************************
* .
*/
@org.junit.Test
public void kGYearMonthEQ1() {
final XQuery query = new XQuery(
"xs:gYearMonth(\"2001-01 \") eq xs:gYearMonth(\"2001-01\")",
ctx);
try {
result = new QT3Result(query.value());
} catch(final Throwable trw) {
result = new QT3Result(trw);
} finally {
query.close();
}
test(
assertBoolean(true)
);
}
/**
*
* *******************************************************
* Test: K-gYearMonthEQ-2
* Written by: Frans Englich
* Date: 2007-11-22T11:31:21+01:00
* Purpose: Simple test of 'eq' for xs:gYearMonth.
* *******************************************************
* .
*/
@org.junit.Test
public void kGYearMonthEQ2() {
final XQuery query = new XQuery(
"not(xs:gYearMonth(\"2001-03\") eq xs:gYearMonth(\"2000-03\"))",
ctx);
try {
result = new QT3Result(query.value());
} catch(final Throwable trw) {
result = new QT3Result(trw);
} finally {
query.close();
}
test(
assertBoolean(true)
);
}
/**
*
* *******************************************************
* Test: K-gYearMonthEQ-3
* Written by: Frans Englich
* Date: 2007-11-22T11:31:21+01:00
* Purpose: Simple test of 'ne' for xs:gYearMonth.
* *******************************************************
* .
*/
@org.junit.Test
public void kGYearMonthEQ3() {
final XQuery query = new XQuery(
"xs:gYearMonth(\"2001-12\") ne xs:gYearMonth(\"2001-11\")",
ctx);
try {
result = new QT3Result(query.value());
} catch(final Throwable trw) {
result = new QT3Result(trw);
} finally {
query.close();
}
test(
assertBoolean(true)
);
}
/**
*
* *******************************************************
* Test: K-gYearMonthEQ-4
* Written by: Frans Englich
* Date: 2007-11-22T11:31:21+01:00
* Purpose: Simple test of 'ne' for xs:gYearMonth.
* *******************************************************
* .
*/
@org.junit.Test
public void kGYearMonthEQ4() {
final XQuery query = new XQuery(
"not(xs:gYearMonth(\"1995-11\") ne xs:gYearMonth(\"1995-11\"))",
ctx);
try {
result = new QT3Result(query.value());
} catch(final Throwable trw) {
result = new QT3Result(trw);
} finally {
query.close();
}
test(
assertBoolean(true)
);
}
/**
*
* *******************************************************
* Test: K-gYearMonthEQ-5
* Written by: Frans Englich
* Date: 2007-11-22T11:31:21+01:00
* Purpose: Test that zone offset -00:00 is equal to Z, in xs:gYearMonth.
* *******************************************************
* .
*/
@org.junit.Test
public void kGYearMonthEQ5() {
final XQuery query = new XQuery(
"xs:gYearMonth(\"1999-01-00:00\") eq xs:gYearMonth(\"1999-01Z\")",
ctx);
try {
result = new QT3Result(query.value());
} catch(final Throwable trw) {
result = new QT3Result(trw);
} finally {
query.close();
}
test(
assertBoolean(true)
);
}
/**
*
* *******************************************************
* Test: K-gYearMonthEQ-6
* Written by: Frans Englich
* Date: 2007-11-22T11:31:21+01:00
* Purpose: Test that zone offset +00:00 is equal to Z, in xs:gYearMonth.
* *******************************************************
* .
*/
@org.junit.Test
public void kGYearMonthEQ6() {
final XQuery query = new XQuery(
"xs:gYearMonth(\"1999-01+00:00\") eq xs:gYearMonth(\"1999-01Z\")",
ctx);
try {
result = new QT3Result(query.value());
} catch(final Throwable trw) {
result = new QT3Result(trw);
} finally {
query.close();
}
test(
assertBoolean(true)
);
}
/**
*
* *******************************************************
* Test: K-gYearMonthEQ-7
* Written by: Frans Englich
* Date: 2007-11-22T11:31:21+01:00
* Purpose: Test that zone offset Z is equal to Z, in xs:gYearMonth.
* *******************************************************
* .
*/
@org.junit.Test
public void kGYearMonthEQ7() {
final XQuery query = new XQuery(
"xs:gYearMonth(\"1999-01Z\") eq xs:gYearMonth(\"1999-01Z\")",
ctx);
try {
result = new QT3Result(query.value());
} catch(final Throwable trw) {
result = new QT3Result(trw);
} finally {
query.close();
}
test(
assertBoolean(true)
);
}
/**
*
* *******************************************************
* Test: K-gYearMonthEQ-8
* Written by: Frans Englich
* Date: 2007-11-22T11:31:21+01:00
* Purpose: Test that zone offset -00:00 is equal to +00:00, in xs:gYearMonth.
* *******************************************************
* .
*/
@org.junit.Test
public void kGYearMonthEQ8() {
final XQuery query = new XQuery(
"xs:gYearMonth(\"1999-01-00:00\") eq xs:gYearMonth(\"1999-01+00:00\")",
ctx);
try {
result = new QT3Result(query.value());
} catch(final Throwable trw) {
result = new QT3Result(trw);
} finally {
query.close();
}
test(
assertBoolean(true)
);
}
/**
* test comparison of gYearMonth .
*/
@org.junit.Test
public void cbclGYearMonthEqual001() {
final XQuery query = new XQuery(
"declare function local:gYearMonth($year as xs:integer) { xs:gYearMonth(concat(string(2000 + $year), \"-01\")) }; not(local:gYearMonth(7) eq xs:gYearMonth(\"2008-01\"))",
ctx);
try {
result = new QT3Result(query.value());
} catch(final Throwable trw) {
result = new QT3Result(trw);
} finally {
query.close();
}
test(
assertBoolean(true)
);
}
/**
* test comparison of gYearMonth .
*/
@org.junit.Test
public void cbclGYearMonthEqual002() {
final XQuery query = new XQuery(
"if (implicit-timezone() eq xs:dayTimeDuration('PT9M'))\n" +
" then xs:gYearMonth(\"2008-01\") eq xs:gYearMonth(\"2008-01+09:01\")\n" +
" else xs:gYearMonth(\"2008-01\") eq xs:gYearMonth(\"2008-01+09:00\")",
ctx);
try {
result = new QT3Result(query.value());
} catch(final Throwable trw) {
result = new QT3Result(trw);
} finally {
query.close();
}
test(
assertBoolean(false)
);
}
/**
* test comparison of gYearMonth .
*/
@org.junit.Test
public void cbclGYearMonthEqual003() {
final XQuery query = new XQuery(
"if (implicit-timezone() eq xs:dayTimeDuration('PT9M'))\n" +
" then xs:gYearMonth(\"2008-01+09:01\") eq xs:gYearMonth(\"2008-01\")\n" +
" else xs:gYearMonth(\"2008-01+09:00\") eq xs:gYearMonth(\"2008-01\")",
ctx);
try {
result = new QT3Result(query.value());
} catch(final Throwable trw) {
result = new QT3Result(trw);
} finally {
query.close();
}
test(
assertBoolean(false)
);
}
/**
* test comparison of gYearMonth .
*/
@org.junit.Test
public void cbclGYearMonthEqual004() {
final XQuery query = new XQuery(
"if (implicit-timezone() eq xs:dayTimeDuration('-PT9M'))\n" +
" then xs:gYearMonth(\"2008-01\") eq xs:gYearMonth(\"2008-01-09:01\")\n" +
" else xs:gYearMonth(\"2008-01\") eq xs:gYearMonth(\"2008-01-09:00\")",
ctx);
try {
result = new QT3Result(query.value());
} catch(final Throwable trw) {
result = new QT3Result(trw);
} finally {
query.close();
}
test(
assertBoolean(false)
);
}
/**
* test comparison of gYearMonth .
*/
@org.junit.Test
public void cbclGYearMonthEqual005() {
final XQuery query = new XQuery(
"if (implicit-timezone() eq xs:dayTimeDuration('-PT9M'))\n" +
" then xs:gYearMonth(\"2008-01-09:01\") eq xs:gYearMonth(\"2008-01\")\n" +
" else xs:gYearMonth(\"2008-01-09:00\") eq xs:gYearMonth(\"2008-01\")",
ctx);
try {
result = new QT3Result(query.value());
} catch(final Throwable trw) {
result = new QT3Result(trw);
} finally {
query.close();
}
test(
assertBoolean(false)
);
}
/**
* test comparison of gYearMonth .
*/
@org.junit.Test
public void cbclGYearMonthEqual006() {
final XQuery query = new XQuery(
"declare function local:gYearMonth($year as xs:integer) { xs:gYearMonth(concat(string(2000 + $year), \"-01\")) }; not(local:gYearMonth(7) ne xs:gYearMonth(\"2008-01\"))",
ctx);
try {
result = new QT3Result(query.value());
} catch(final Throwable trw) {
result = new QT3Result(trw);
} finally {
query.close();
}
test(
assertBoolean(false)
);
}
/**
* test comparison of gYearMonth .
*/
@org.junit.Test
public void cbclGYearMonthEqual007() {
final XQuery query = new XQuery(
"if (implicit-timezone() eq xs:dayTimeDuration('PT9M'))\n" +
" then xs:gYearMonth(\"2008-01\") ne xs:gYearMonth(\"2008-01+09:01\")\n" +
" else xs:gYearMonth(\"2008-01\") ne xs:gYearMonth(\"2008-01+09:00\")",
ctx);
try {
result = new QT3Result(query.value());
} catch(final Throwable trw) {
result = new QT3Result(trw);
} finally {
query.close();
}
test(
assertBoolean(true)
);
}
/**
* test comparison of gYearMonth .
*/
@org.junit.Test
public void cbclGYearMonthEqual008() {
final XQuery query = new XQuery(
"if (implicit-timezone() eq xs:dayTimeDuration('PT9M'))\n" +
" then xs:gYearMonth(\"2008-01+09:01\") ne xs:gYearMonth(\"2008-01\")\n" +
" else xs:gYearMonth(\"2008-01+09:00\") ne xs:gYearMonth(\"2008-01\")",
ctx);
try {
result = new QT3Result(query.value());
} catch(final Throwable trw) {
result = new QT3Result(trw);
} finally {
query.close();
}
test(
assertBoolean(true)
);
}
/**
* test comparison of gYearMonth .
*/
@org.junit.Test
public void cbclGYearMonthEqual009() {
final XQuery query = new XQuery(
"if (implicit-timezone() eq xs:dayTimeDuration('-PT9M'))\n" +
" then xs:gYearMonth(\"2008-01\") ne xs:gYearMonth(\"2008-01-09:01\")\n" +
" else xs:gYearMonth(\"2008-01\") ne xs:gYearMonth(\"2008-01-09:00\")",
ctx);
try {
result = new QT3Result(query.value());
} catch(final Throwable trw) {
result = new QT3Result(trw);
} finally {
query.close();
}
test(
assertBoolean(true)
);
}
/**
* test comparison of gYearMonth .
*/
@org.junit.Test
public void cbclGYearMonthEqual010() {
final XQuery query = new XQuery(
"if (implicit-timezone() eq xs:dayTimeDuration('-PT9M'))\n" +
" then xs:gYearMonth(\"2008-01-09:01\") ne xs:gYearMonth(\"2008-01\")\n" +
" else xs:gYearMonth(\"2008-01-09:00\") ne xs:gYearMonth(\"2008-01\")",
ctx);
try {
result = new QT3Result(query.value());
} catch(final Throwable trw) {
result = new QT3Result(trw);
} finally {
query.close();
}
test(
assertBoolean(true)
);
}
/**
* test comparison of gYearMonth .
*/
@org.junit.Test
public void cbclGYearMonthEqual011() {
final XQuery query = new XQuery(
"declare function local:gYearMonth($gYearMonth as xs:gYearMonth, $null as xs:boolean) { if ($null) then () else $gYearMonth }; exists(local:gYearMonth(xs:gYearMonth(\"1972-12\"), fn:true()) eq xs:gYearMonth(\"1972-12\"))",
ctx);
try {
result = new QT3Result(query.value());
} catch(final Throwable trw) {
result = new QT3Result(trw);
} finally {
query.close();
}
test(
assertBoolean(false)
);
}
/**
* test comparison of gYearMonth .
*/
@org.junit.Test
public void cbclGYearMonthEqual012() {
final XQuery query = new XQuery(
"declare function local:gYearMonth($gYearMonth as xs:gYearMonth, $null as xs:boolean) { if ($null) then () else $gYearMonth }; local:gYearMonth(xs:gYearMonth(\"1972-12\"), fn:false()) eq xs:gYearMonth(\"1972-12\")",
ctx);
try {
result = new QT3Result(query.value());
} catch(final Throwable trw) {
result = new QT3Result(trw);
} finally {
query.close();
}
test(
assertBoolean(true)
);
}
/**
* test comparison of gYearMonth .
*/
@org.junit.Test
public void cbclGYearMonthEqual013() {
final XQuery query = new XQuery(
"declare function local:gYearMonth($gYearMonth as xs:gYearMonth, $null as xs:boolean) { if ($null) then () else $gYearMonth }; exists(local:gYearMonth(xs:gYearMonth(\"1972-12\"), fn:true()) ne xs:gYearMonth(\"1972-12\"))",
ctx);
try {
result = new QT3Result(query.value());
} catch(final Throwable trw) {
result = new QT3Result(trw);
} finally {
query.close();
}
test(
assertBoolean(false)
);
}
/**
* test comparison of gYearMonth .
*/
@org.junit.Test
public void cbclGYearMonthEqual014() {
final XQuery query = new XQuery(
"declare function local:gYearMonth($gYearMonth as xs:gYearMonth, $null as xs:boolean) { if ($null) then () else $gYearMonth }; local:gYearMonth(xs:gYearMonth(\"1972-12\"), fn:false()) ne xs:gYearMonth(\"1972-12\")",
ctx);
try {
result = new QT3Result(query.value());
} catch(final Throwable trw) {
result = new QT3Result(trw);
} finally {
query.close();
}
test(
assertBoolean(false)
);
}
/**
*
* *******************************************************
* Test: op-gYearMonth-equal2args-1
* Written By: Carmelo Montanez
* Date: Tue Apr 12 16:29:07 GMT-05:00 2005
* Purpose: Evaluates The "op:gYearMonth-equal" operator
* with the arguments set as follows:
* $arg1 = xs:gYearMonth(lower bound)
* $arg2 = xs:gYearMonth(lower bound)
* *******************************************************
* .
*/
@org.junit.Test
public void opGYearMonthEqual2args1() {
final XQuery query = new XQuery(
"xs:gYearMonth(\"1970-01Z\") eq xs:gYearMonth(\"1970-01Z\")",
ctx);
try {
result = new QT3Result(query.value());
} catch(final Throwable trw) {
result = new QT3Result(trw);
} finally {
query.close();
}
test(
assertBoolean(true)
);
}
/**
*
* *******************************************************
* Test: op-gYearMonth-equal2args-10
* Written By: Carmelo Montanez
* Date: Tue Apr 12 16:29:07 GMT-05:00 2005
* Purpose: Evaluates The "op:gYearMonth-equal" operator
* with the arguments set as follows:
* $arg1 = xs:gYearMonth(lower bound)
* $arg2 = xs:gYearMonth(upper bound)
* *******************************************************
* .
*/
@org.junit.Test
public void opGYearMonthEqual2args10() {
final XQuery query = new XQuery(
"xs:gYearMonth(\"1970-01Z\") ne xs:gYearMonth(\"2030-12Z\")",
ctx);
try {
result = new QT3Result(query.value());
} catch(final Throwable trw) {
result = new QT3Result(trw);
} finally {
query.close();
}
test(
assertBoolean(true)
);
}
/**
*
* *******************************************************
* Test: op-gYearMonth-equal2args-2
* Written By: Carmelo Montanez
* Date: Tue Apr 12 16:29:07 GMT-05:00 2005
* Purpose: Evaluates The "op:gYearMonth-equal" operator
* with the arguments set as follows:
* $arg1 = xs:gYearMonth(mid range)
* $arg2 = xs:gYearMonth(lower bound)
* *******************************************************
* .
*/
@org.junit.Test
public void opGYearMonthEqual2args2() {
final XQuery query = new XQuery(
"xs:gYearMonth(\"1984-12Z\") eq xs:gYearMonth(\"1970-01Z\")",
ctx);
try {
result = new QT3Result(query.value());
} catch(final Throwable trw) {
result = new QT3Result(trw);
} finally {
query.close();
}
test(
assertBoolean(false)
);
}
/**
*
* *******************************************************
* Test: op-gYearMonth-equal2args-3
* Written By: Carmelo Montanez
* Date: Tue Apr 12 16:29:07 GMT-05:00 2005
* Purpose: Evaluates The "op:gYearMonth-equal" operator
* with the arguments set as follows:
* $arg1 = xs:gYearMonth(upper bound)
* $arg2 = xs:gYearMonth(lower bound)
* *******************************************************
* .
*/
@org.junit.Test
public void opGYearMonthEqual2args3() {
final XQuery query = new XQuery(
"xs:gYearMonth(\"2030-12Z\") eq xs:gYearMonth(\"1970-01Z\")",
ctx);
try {
result = new QT3Result(query.value());
} catch(final Throwable trw) {
result = new QT3Result(trw);
} finally {
query.close();
}
test(
assertBoolean(false)
);
}
/**
*
* *******************************************************
* Test: op-gYearMonth-equal2args-4
* Written By: Carmelo Montanez
* Date: Tue Apr 12 16:29:07 GMT-05:00 2005
* Purpose: Evaluates The "op:gYearMonth-equal" operator
* with the arguments set as follows:
* $arg1 = xs:gYearMonth(lower bound)
* $arg2 = xs:gYearMonth(mid range)
* *******************************************************
* .
*/
@org.junit.Test
public void opGYearMonthEqual2args4() {
final XQuery query = new XQuery(
"xs:gYearMonth(\"1970-01Z\") eq xs:gYearMonth(\"1984-12Z\")",
ctx);
try {
result = new QT3Result(query.value());
} catch(final Throwable trw) {
result = new QT3Result(trw);
} finally {
query.close();
}
test(
assertBoolean(false)
);
}
/**
*
* *******************************************************
* Test: op-gYearMonth-equal2args-5
* Written By: Carmelo Montanez
* Date: Tue Apr 12 16:29:07 GMT-05:00 2005
* Purpose: Evaluates The "op:gYearMonth-equal" operator
* with the arguments set as follows:
* $arg1 = xs:gYearMonth(lower bound)
* $arg2 = xs:gYearMonth(upper bound)
* *******************************************************
* .
*/
@org.junit.Test
public void opGYearMonthEqual2args5() {
final XQuery query = new XQuery(
"xs:gYearMonth(\"1970-01Z\") eq xs:gYearMonth(\"2030-12Z\")",
ctx);
try {
result = new QT3Result(query.value());
} catch(final Throwable trw) {
result = new QT3Result(trw);
} finally {
query.close();
}
test(
assertBoolean(false)
);
}
/**
*
* *******************************************************
* Test: op-gYearMonth-equal2args-6
* Written By: Carmelo Montanez
* Date: Tue Apr 12 16:29:07 GMT-05:00 2005
* Purpose: Evaluates The "op:gYearMonth-equal" operator
* with the arguments set as follows:
* $arg1 = xs:gYearMonth(lower bound)
* $arg2 = xs:gYearMonth(lower bound)
* *******************************************************
* .
*/
@org.junit.Test
public void opGYearMonthEqual2args6() {
final XQuery query = new XQuery(
"xs:gYearMonth(\"1970-01Z\") ne xs:gYearMonth(\"1970-01Z\")",
ctx);
try {
result = new QT3Result(query.value());
} catch(final Throwable trw) {
result = new QT3Result(trw);
} finally {
query.close();
}
test(
assertBoolean(false)
);
}
/**
*
* *******************************************************
* Test: op-gYearMonth-equal2args-7
* Written By: Carmelo Montanez
* Date: Tue Apr 12 16:29:07 GMT-05:00 2005
* Purpose: Evaluates The "op:gYearMonth-equal" operator
* with the arguments set as follows:
* $arg1 = xs:gYearMonth(mid range)
* $arg2 = xs:gYearMonth(lower bound)
* *******************************************************
* .
*/
@org.junit.Test
public void opGYearMonthEqual2args7() {
final XQuery query = new XQuery(
"xs:gYearMonth(\"1984-12Z\") ne xs:gYearMonth(\"1970-01Z\")",
ctx);
try {
result = new QT3Result(query.value());
} catch(final Throwable trw) {
result = new QT3Result(trw);
} finally {
query.close();
}
test(
assertBoolean(true)
);
}
/**
*
* *******************************************************
* Test: op-gYearMonth-equal2args-8
* Written By: Carmelo Montanez
* Date: Tue Apr 12 16:29:07 GMT-05:00 2005
* Purpose: Evaluates The "op:gYearMonth-equal" operator
* with the arguments set as follows:
* $arg1 = xs:gYearMonth(upper bound)
* $arg2 = xs:gYearMonth(lower bound)
* *******************************************************
* .
*/
@org.junit.Test
public void opGYearMonthEqual2args8() {
final XQuery query = new XQuery(
"xs:gYearMonth(\"2030-12Z\") ne xs:gYearMonth(\"1970-01Z\")",
ctx);
try {
result = new QT3Result(query.value());
} catch(final Throwable trw) {
result = new QT3Result(trw);
} finally {
query.close();
}
test(
assertBoolean(true)
);
}
/**
*
* *******************************************************
* Test: op-gYearMonth-equal2args-9
* Written By: Carmelo Montanez
* Date: Tue Apr 12 16:29:07 GMT-05:00 2005
* Purpose: Evaluates The "op:gYearMonth-equal" operator
* with the arguments set as follows:
* $arg1 = xs:gYearMonth(lower bound)
* $arg2 = xs:gYearMonth(mid range)
* *******************************************************
* .
*/
@org.junit.Test
public void opGYearMonthEqual2args9() {
final XQuery query = new XQuery(
"xs:gYearMonth(\"1970-01Z\") ne xs:gYearMonth(\"1984-12Z\")",
ctx);
try {
result = new QT3Result(query.value());
} catch(final Throwable trw) {
result = new QT3Result(trw);
} finally {
query.close();
}
test(
assertBoolean(true)
);
}
/**
*
* *******************************************************
* Test: op-gYearMonth-equal-1
* Written By: Carmelo Montanez
* Date: June 13, 2005
* Purpose: Evaluates The "gYearMonth-equal" function
* As per example 1 (for this function)of the F&O specs
* *******************************************************
* .
*/
@org.junit.Test
public void opGYearMonthEqualNew1() {
final XQuery query = new XQuery(
"(xs:gYearMonth(\"1976-02-05:00\") eq xs:gYearMonth(\"1976-03Z\"))",
ctx);
try {
result = new QT3Result(query.value());
} catch(final Throwable trw) {
result = new QT3Result(trw);
} finally {
query.close();
}
test(
assertBoolean(false)
);
}
/**
*
* *******************************************************
* Test: op-gYearMonth-equal-10
* Written By: Carmelo Montanez
* Date: June 13, 2005
* Purpose: Evaluates The "gYearMonth-equal" function used
* together with "or" expression (ne operator).
* *******************************************************
* .
*/
@org.junit.Test
public void opGYearMonthEqualNew10() {
final XQuery query = new XQuery(
"(xs:gYearMonth(\"1976-01Z\") ne xs:gYearMonth(\"1976-02Z\")) or (xs:gYearMonth(\"1980-03Z\") ne xs:gYearMonth(\"1980-04Z\"))",
ctx);
try {
result = new QT3Result(query.value());
} catch(final Throwable trw) {
result = new QT3Result(trw);
} finally {
query.close();
}
test(
assertBoolean(true)
);
}
/**
*
* *******************************************************
* Test: op-gYearMonth-equal-11
* Written By: Carmelo Montanez
* Date: June 13, 2005
* Purpose: Evaluates The "gYearMonth-equal" function used
* together with "fn:true"/or expression (eq operator).
* *******************************************************
* .
*/
@org.junit.Test
public void opGYearMonthEqualNew11() {
final XQuery query = new XQuery(
"(xs:gYearMonth(\"1980-05Z\") eq xs:gYearMonth(\"1980-05Z\")) or (fn:true())",
ctx);
try {
result = new QT3Result(query.value());
} catch(final Throwable trw) {
result = new QT3Result(trw);
} finally {
query.close();
}
test(
assertBoolean(true)
);
}
/**
*
* *******************************************************
* Test: op-gYearMonth-equal-12
* Written By: Carmelo Montanez
* Date: June 13, 2005
* Purpose: Evaluates The "gYearMonth-equal" function used
* together with "fn:true"/or expression (ne operator).
* *******************************************************
* .
*/
@org.junit.Test
public void opGYearMonthEqualNew12() {
final XQuery query = new XQuery(
"(xs:gYearMonth(\"2000-06Z\") ne xs:gYearMonth(\"2000-07Z\")) or (fn:true())",
ctx);
try {
result = new QT3Result(query.value());
} catch(final Throwable trw) {
result = new QT3Result(trw);
} finally {
query.close();
}
test(
assertBoolean(true)
);
}
/**
*
* *******************************************************
* Test: op-gYearMonth-equal-13
* Written By: Carmelo Montanez
* Date: June 13, 2005
* Purpose: Evaluates The "gYearMonth-equal" function used
* together with "fn:false"/or expression (eq operator).
* *******************************************************
* .
*/
@org.junit.Test
public void opGYearMonthEqualNew13() {
final XQuery query = new XQuery(
"(xs:gYearMonth(\"1980-09Z\") eq xs:gYearMonth(\"1980-09Z\")) or (fn:false())",
ctx);
try {
result = new QT3Result(query.value());
} catch(final Throwable trw) {
result = new QT3Result(trw);
} finally {
query.close();
}
test(
assertBoolean(true)
);
}
/**
*
* *******************************************************
* Test: op-gYearMonth-equal-14
* Written By: Carmelo Montanez
* Date: June 13, 2005
* Purpose: Evaluates The "gYearMonth-equal" function used
* together with "fn:false"/or expression (ne operator).
* *******************************************************
* .
*/
@org.junit.Test
public void opGYearMonthEqualNew14() {
final XQuery query = new XQuery(
"(xs:gYearMonth(\"1980-03Z\") ne xs:gYearMonth(\"1980-03Z\")) or (fn:false())",
ctx);
try {
result = new QT3Result(query.value());
} catch(final Throwable trw) {
result = new QT3Result(trw);
} finally {
query.close();
}
test(
assertBoolean(false)
);
}
/**
*
* *******************************************************
* Test: op-gYearMonth-equal-2
* Written By: Carmelo Montanez
* Date: June 13, 2005
* Purpose: Evaluates The "gYearMonth-equal" function
* As per example 2 (for this function) of the F&O specs
* *******************************************************
* .
*/
@org.junit.Test
public void opGYearMonthEqualNew2() {
final XQuery query = new XQuery(
"(xs:gYearMonth(\"1976-03-05:00\") eq xs:gYearMonth(\"1976-03Z\"))",
ctx);
try {
result = new QT3Result(query.value());
} catch(final Throwable trw) {
result = new QT3Result(trw);
} finally {
query.close();
}
test(
assertBoolean(false)
);
}
/**
*
* *******************************************************
* Test: op-gYearMonth-equal-3
* Written By: Carmelo Montanez
* Date: June 13, 2005
* Purpose: Evaluates The "gYearMonth-equal" function that
* return true and used together with fn:not (eq operator)
* *******************************************************
* .
*/
@org.junit.Test
public void opGYearMonthEqualNew3() {
final XQuery query = new XQuery(
"fn:not((xs:gYearMonth(\"1995-02Z\") eq xs:gYearMonth(\"1995-02Z\")))",
ctx);
try {
result = new QT3Result(query.value());
} catch(final Throwable trw) {
result = new QT3Result(trw);
} finally {
query.close();
}
test(
assertBoolean(false)
);
}
/**
*
* *******************************************************
* Test: op-gYearMonth-equal-4
* Written By: Carmelo Montanez
* Date: June 13, 2005
* Purpose: Evaluates The "gYearMonth-equal" function that
* return true and used together with fn:not (le operator)
* *******************************************************
* .
*/
@org.junit.Test
public void opGYearMonthEqualNew4() {
final XQuery query = new XQuery(
"fn:not(xs:gYearMonth(\"2005-02Z\") ne xs:gYearMonth(\"2006-03Z\"))",
ctx);
try {
result = new QT3Result(query.value());
} catch(final Throwable trw) {
result = new QT3Result(trw);
} finally {
query.close();
}
test(
assertBoolean(false)
);
}
/**
*
* *******************************************************
* Test: op-gYearMonth-equal-5
* Written By: Carmelo Montanez
* Date: June 13, 2005
* Purpose: Evaluates The "gYearMonth-equal" function that
* return false and used together with fn:not (eq operator)
* *******************************************************
* .
*/
@org.junit.Test
public void opGYearMonthEqualNew5() {
final XQuery query = new XQuery(
"fn:not(xs:gYearMonth(\"2000-01Z\") eq xs:gYearMonth(\"2001-04Z\"))",
ctx);
try {
result = new QT3Result(query.value());
} catch(final Throwable trw) {
result = new QT3Result(trw);
} finally {
query.close();
}
test(
assertBoolean(true)
);
}
/**
*
* *******************************************************
* Test: op-gYearMonth-equal-6
* Written By: Carmelo Montanez
* Date: June 13, 2005
* Purpose: Evaluates The "gYearMonth-equal" function that
* return false and used together with fn:not(ne operator)
* *******************************************************
* .
*/
@org.junit.Test
public void opGYearMonthEqualNew6() {
final XQuery query = new XQuery(
"fn:not(xs:gYearMonth(\"2005-01Z\") ne xs:gYearMonth(\"2005-01Z\"))",
ctx);
try {
result = new QT3Result(query.value());
} catch(final Throwable trw) {
result = new QT3Result(trw);
} finally {
query.close();
}
test(
assertBoolean(true)
);
}
/**
*
* *******************************************************
* Test: op-gYearMonth-equal-7
* Written By: Carmelo Montanez
* Date: June 13, 2005
* Purpose: Evaluates The "gYearMonth-equal" function used
* together with "and" expression (eq operator).
* *******************************************************
* .
*/
@org.junit.Test
public void opGYearMonthEqualNew7() {
final XQuery query = new XQuery(
"(xs:gYearMonth(\"2000-02Z\") eq xs:gYearMonth(\"2000-03Z\")) and (xs:gYearMonth(\"2001-01Z\") eq xs:gYearMonth(\"2001-01Z\"))",
ctx);
try {
result = new QT3Result(query.value());
} catch(final Throwable trw) {
result = new QT3Result(trw);
} finally {
query.close();
}
test(
assertBoolean(false)
);
}
/**
*
* *******************************************************
* Test: op-gYearMonth-equal-8
* Written By: Carmelo Montanez
* Date: June 13, 2005
* Purpose: Evaluates The "gYearMonth-equal" function used
* together with "and" expression (ne operator).
* *******************************************************
* .
*/
@org.junit.Test
public void opGYearMonthEqualNew8() {
final XQuery query = new XQuery(
"(xs:gYearMonth(\"2000-01Z\") ne xs:gYearMonth(\"2000-01Z\")) and (xs:gYearMonth(\"1975-01Z\") ne xs:gYearMonth(\"1975-03Z\"))",
ctx);
try {
result = new QT3Result(query.value());
} catch(final Throwable trw) {
result = new QT3Result(trw);
} finally {
query.close();
}
test(
assertBoolean(false)
);
}
/**
*
* *******************************************************
* Test: op-gYearMonth-equal-9
* Written By: Carmelo Montanez
* Date: June 13, 2005
* Purpose: Evaluates The "gYearMonth-equal" function used
* together with "or" expression (eq operator).
* *******************************************************
* .
*/
@org.junit.Test
public void opGYearMonthEqualNew9() {
final XQuery query = new XQuery(
"(xs:gYearMonth(\"2000-01Z\") eq xs:gYearMonth(\"2000-03Z\")) or (xs:gYearMonth(\"1976-06Z\") eq xs:gYearMonth(\"1976-06Z\"))",
ctx);
try {
result = new QT3Result(query.value());
} catch(final Throwable trw) {
result = new QT3Result(trw);
} finally {
query.close();
}
test(
assertBoolean(true)
);
}
}
| 30.349467 | 228 | 0.470375 |
53a9edcf4ce6502ef5b7074809817775efbdc9d4 | 3,067 | /*
* Copyright 2018 tweerlei Wruck + Buchmeier GbR - http://www.tweerlei.de/
*
* 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 de.tweerlei.spring.web.service.impl;
import java.util.Locale;
import java.util.TimeZone;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.context.Theme;
import org.springframework.ui.context.ThemeSource;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.ThemeResolver;
import de.tweerlei.spring.web.handler.TimeZoneResolver;
import de.tweerlei.spring.web.service.RequestSettingsService;
/**
* Default impl.
*
* @author Robert Wruck
*/
//@Service("requestSettingsService")
public class RequestSettingsServiceImpl implements RequestSettingsService
{
private final LocaleResolver localeResolver;
private final ThemeResolver themeResolver;
private final ThemeSource themeSource;
private final TimeZoneResolver timeZoneResolver;
/**
* Constructor
* @param localeResolver LocaleResolver
* @param themeResolver ThemeResolver
* @param timeZoneResolver TimeZoneResolver
* @param themeSource ThemeSource
*/
@Autowired
public RequestSettingsServiceImpl(LocaleResolver localeResolver, ThemeResolver themeResolver,
TimeZoneResolver timeZoneResolver, ThemeSource themeSource)
{
this.localeResolver = localeResolver;
this.themeResolver = themeResolver;
this.themeSource = themeSource;
this.timeZoneResolver = timeZoneResolver;
}
public Locale getLocale(HttpServletRequest request)
{
return (localeResolver.resolveLocale(request));
}
public String getThemeName(HttpServletRequest request)
{
return (themeResolver.resolveThemeName(request));
}
public Theme getTheme(HttpServletRequest request)
{
return (themeSource.getTheme(getThemeName(request)));
}
public TimeZone getTimeZone(HttpServletRequest request)
{
return (timeZoneResolver.resolveTimeZone(request));
}
public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale)
{
localeResolver.setLocale(request, response, locale);
}
public void setThemeName(HttpServletRequest request, HttpServletResponse response, String themeName)
{
themeResolver.setThemeName(request, response, themeName);
}
public void setTimeZone(HttpServletRequest request, HttpServletResponse response, TimeZone timeZone)
{
timeZoneResolver.setTimeZone(request, response, timeZone);
}
}
| 31.295918 | 101 | 0.789697 |
07321a4dc50157f155c943971a7d4948ab5c957d | 215 | package io.agrest.cayenne.qualifier;
import io.agrest.base.protocol.Exp;
import org.apache.cayenne.exp.Expression;
/**
* @since 3.3
*/
public interface IQualifierParser {
Expression parse(Exp qualifier);
}
| 16.538462 | 41 | 0.744186 |
10c9465b5b5b53c42cdb3ed906a2581252672b69 | 456 | import java.util.*;
/* 852. Peak Index in a Mountain Array */
public class Solution {
public int peakIndexInMountainArray(int[] arr) {
int left = 0;
int right = arr.length - 1;
while (left < right) {
int mid = left + (right - left) / 2;
if (arr[mid] < arr[mid + 1]) {
left = mid + 1;
} else {
right = mid;
}
}
return left;
}
}
| 24 | 52 | 0.449561 |
5283abfaac182aa68ef921f6a548b9bab47a7a1c | 361 | package org.codeforamerica.shiba.output.pdf;
import static org.apache.pdfbox.cos.COSName.YES;
import lombok.AllArgsConstructor;
import lombok.Value;
@Value
@AllArgsConstructor
public class BinaryPdfField implements PdfField {
String name;
String value;
public BinaryPdfField(String name) {
this.name = name;
this.value = YES.getName();
}
}
| 18.05 | 49 | 0.756233 |
2b46ee3ac73bd22b97c528dfbb266e14c79f02ba | 1,699 | package top.murphypen.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import top.murphypen.domain.DemoObj;
import javax.servlet.http.HttpServletRequest;
@Controller
@RequestMapping("/anno")
public class AnnoController {
@RequestMapping(produces = "text/plain;charset=UTF-8")
public @ResponseBody
String index(HttpServletRequest request) {
return "url:" + request.getRequestURI() + " can access";
}
@RequestMapping(value = "/pathvar/{str}", produces = "text/plain;charset=UTF-8")
public @ResponseBody
String demoPathVar(@PathVariable String str, HttpServletRequest request) {
return "url:" + request.getRequestURI() + " can access,str:" + str;
}
@RequestMapping(value = "/requestParam", produces = "text/plain;charset=UTF-8")
public @ResponseBody
String passRequestParam(Long id, HttpServletRequest request) {
return "url:" + request.getRequestURI() + " can access,id:" + id;
}
@RequestMapping(value = "/obj", produces = "application/json;charset=UTF-8")
public @ResponseBody
String passObj(DemoObj obj, HttpServletRequest request) {
return "url:" + request.getRequestURI() + " can access,obj.id:"
+ obj.getId() + " obj.name:" + obj.getName();
}
@RequestMapping(value = {"/name1", "/name2"}, produces = "text/plain;charset=UTF-8")
public @ResponseBody
String remove(HttpServletRequest request) {
return "url:" + request.getRequestURI() + " can access";
}
}
| 36.934783 | 88 | 0.698058 |
e9bd8c021994577f1f36f38eed629542ec9043a3 | 3,366 | package kripke;
import expressions.*;
import java.util.*;
import java.util.stream.Collectors;
public class World {
private List<World> children;
private Set<Variable> forcedVariables;
private Map<Expression, Boolean> forcedExpression;
public World() {
children = new ArrayList<>();
forcedVariables = new HashSet<>();
forcedExpression = new HashMap<>();
}
public World(int num, List<Variable> list) {
children = new ArrayList<>();
forcedVariables = new HashSet<>();
forcedExpression = new HashMap<>();
for (int i = 0; i < list.size(); i++) {
if ((num & (1 << i)) != 0) {
forcedVariables.add(list.get(i));
}
}
}
public void toStringQuick(StringBuilder sb, int depth) {
for (int i = 0; i < depth; i++) {
sb.append(' ');
}
sb.append('*');
boolean flag = false;
for (Variable variable : forcedVariables) {
if (flag) sb.append(", ");
sb.append(variable);
flag = true;
}
sb.append('\n');
for (World w : children) {
w.toStringQuick(sb, depth + 1);
}
}
public boolean isForced(Expression expression) {
// if (forcedExpression.containsKey(expression)) return forcedExpression.get(expression);
boolean ans;
if (expression instanceof And) {
ans = isForced(((And) expression).left) && isForced(((And) expression).right);
} else if (expression instanceof Or) {
ans = isForced(((Or) expression).left) || isForced(((Or) expression).right);
} else if (expression instanceof Not) {
ans = true;
Queue<World> worlds = new ArrayDeque<>();
worlds.add(this);
while (!worlds.isEmpty()) {
World w = worlds.poll();
if (w.isForced(((Not) expression).getExpr())) {
ans = false;
break;
}
worlds.addAll(w.children.stream().collect(Collectors.toList()));
}
} else if (expression instanceof Entailment) {
ans = true;
Queue<World> worlds = new ArrayDeque<>();
worlds.add(this);
while (!worlds.isEmpty()) {
World w = worlds.poll();
if (w.isForced(((Entailment) expression).left) && !w.isForced(((Entailment) expression).right)) {
ans = false;
break;
}
worlds.addAll(w.children.stream().collect(Collectors.toList()));
}
} else if (expression instanceof Variable) {
ans = forcedVariables.contains(expression);
} else {
throw new IllegalStateException();
}
// forcedExpression.put(expression, ans);
return ans;
}
public void addChild(World child) {
children.add(child);
}
private void addForcedVariable(Variable var) {
forcedVariables.add(var);
}
public World copy() {
World ret = new World();
for (Variable var : forcedVariables) {
ret.addForcedVariable(var);
}
for (World child : children) {
ret.addChild(child.copy());
}
return ret;
}
} | 32.057143 | 113 | 0.523767 |
04552899b625998821b48549f0da96fef9f64326 | 375 | import java.util.ArrayList;
public class Arrays {
public static void main(String[] args) {
ArrayList<String> food = new ArrayList<String>();
food.add("Pizza");
food.add("Ivan");
food.set(1, "Hello There");
for (int i = 0;i < food.size(); i++){
System.out.println(food.get(i));
}
}
}
| 19.736842 | 58 | 0.506667 |
cdf3211660448e1892141efa110ea0af985f8980 | 2,015 | package hr.fer.zemris.jcms.web.actions.data;
import hr.fer.zemris.jcms.beans.ext.MPUserState;
import hr.fer.zemris.jcms.beans.ext.MPViewBean;
import hr.fer.zemris.jcms.model.Group;
import hr.fer.zemris.jcms.model.UserGroup;
import hr.fer.zemris.jcms.service.has.HasParent;
import hr.fer.zemris.jcms.web.actions.data.support.IMessageLogger;
import java.util.List;
public class MPViewData extends BaseCourseInstance implements HasParent {
private Group parent;
private boolean active;
private MPUserState userState;
private String now;
private List<UserGroup> userGroups;
private List<Group> allGroups;
private String courseInstanceID;
private Long parentID;
private MPViewBean bean = new MPViewBean();
public MPViewData(IMessageLogger messageLogger) {
super(messageLogger);
}
public String getCourseInstanceID() {
return courseInstanceID;
}
public void setCourseInstanceID(String courseInstanceID) {
this.courseInstanceID = courseInstanceID;
}
public Long getParentID() {
return parentID;
}
public void setParentID(Long parentID) {
this.parentID = parentID;
}
public MPViewBean getBean() {
return bean;
}
public void setBean(MPViewBean bean) {
this.bean = bean;
}
public Group getParent() {
return parent;
}
public void setParent(Group parent) {
this.parent = parent;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public MPUserState getUserState() {
return userState;
}
public void setUserState(MPUserState userState) {
this.userState = userState;
}
public String getNow() {
return now;
}
public void setNow(String now) {
this.now = now;
}
public List<UserGroup> getUserGroups() {
return userGroups;
}
public void setUserGroups(List<UserGroup> userGroups) {
this.userGroups = userGroups;
}
public List<Group> getAllGroups() {
return allGroups;
}
public void setAllGroups(List<Group> allGroups) {
this.allGroups = allGroups;
}
}
| 22.142857 | 73 | 0.741439 |
283903e2b8e08b5a2c448ecf8cf2726099009334 | 2,191 | package cn.snaildev.zuul.gateway.filter;
import cn.snaildev.zuul.gateway.util.NetUtils;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
/**
* @author: Ming.Zhao
* @create: 2019-04-08 17:22
**/
@Slf4j
public class CollectFilter extends ZuulFilter {
@Autowired
private ThreadPoolTaskExecutor filterExecutor;
@Override
public String filterType() {
return "pre";
}
@Override
public int filterOrder() {
return 10;
}
public boolean shouldFilter() {
RequestContext ctx = RequestContext.getCurrentContext();
return ctx.getRouteHost() == null && ctx.get("serviceId") != null && ctx.sendZuulResponse();
}
public Object run() throws ZuulException {
RequestContext ctx = RequestContext.getCurrentContext();
String uri = ctx.getRequest().getRequestURI();
String method = ctx.getRequest().getMethod();
String ip = NetUtils.getIpAddress(ctx.getRequest());
String queryString = ctx.getRequest().getQueryString();
String body = charReader(ctx.getRequest());
AsyncCollect(ip + "\t" + method + "\t" + uri + "\t" + queryString + "\t" + body);
return null;
}
private void AsyncCollect(final String msg) {
filterExecutor.execute(new Runnable() {
public void run() {
log.info(msg);
}
});
}
private String charReader(HttpServletRequest request) {
try {
BufferedReader br = request.getReader();
StringBuilder sb = new StringBuilder();
String str;
while ((str = br.readLine()) != null) {
sb.append(str);
}
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
| 28.828947 | 100 | 0.635783 |
303aa13721c88941e5dfc866a5a6f1d83a5616a9 | 4,951 | package com.essam.chatapp.ui.verification;
import android.app.Activity;
import android.util.Log;
import androidx.annotation.NonNull;
import com.essam.chatapp.firebase.data.FirebaseManager;
import com.essam.chatapp.firebase.fcm.FcmUtils;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.FirebaseException;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.PhoneAuthCredential;
import com.google.firebase.auth.PhoneAuthOptions;
import com.google.firebase.auth.PhoneAuthProvider;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.ValueEventListener;
import java.util.concurrent.TimeUnit;
public class VerificationPresenter implements VerificationContract.Presenter {
private VerificationContract.View mView;
private FirebaseManager mFirebaseManager;
private static final String TAG = VerificationPresenter.class.getSimpleName();
public VerificationPresenter(VerificationContract.View view) {
mView = view;
mFirebaseManager = FirebaseManager.getInstance();
}
@Override
public void getVerificationCode(String phoneNumber) {
// this call back basically overrides three methods
// 1- onVerificationCompleted : this means verification automatically done and no need to enter verify code
// 2- onCodeSent : returns a string verification code to users phone number so we have to
// compare this code with the code that entered by user
//check automatically for credentials
PhoneAuthProvider.OnVerificationStateChangedCallbacks loginPhoneCallBack =
new PhoneAuthProvider.OnVerificationStateChangedCallbacks() {
@Override
public void onVerificationCompleted(@NonNull PhoneAuthCredential phoneAuthCredential) {
//check automatically for credentials
signInWithPhoneCredential(phoneAuthCredential);
}
@Override
public void onVerificationFailed(@NonNull FirebaseException e) {
Log.e(TAG, "onVerificationFailed: " + e.toString());
mView.onVerifyPhoneNumberFailed();
}
@Override
public void onCodeSent(@NonNull String code, @NonNull PhoneAuthProvider.ForceResendingToken forceResendingToken) {
super.onCodeSent(code, forceResendingToken);
mView.onVerificationCodeSent(code);
}
};
PhoneAuthOptions phoneAuthOptions = PhoneAuthOptions.newBuilder()
.setPhoneNumber(phoneNumber) // Phone number to verify
.setTimeout(60L, TimeUnit.SECONDS) // Timeout and unit
.setActivity((Activity) mView) // Activity (for callback binding)
.setCallbacks(loginPhoneCallBack)
.build();
PhoneAuthProvider.verifyPhoneNumber(phoneAuthOptions);
}
@Override
public void signInWithPhoneCredential(PhoneAuthCredential phoneAuthCredential) {
mFirebaseManager.getFirebaseAuth().signInWithCredential(phoneAuthCredential)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Tell firebase manager that user has been successfully logged in
mFirebaseManager.updateUserAuthState(FirebaseManager.UserAuthState.LOGGED_IN);
// check if this is a new user or already registered user
checkIfUserExistInDataBase();
// update view
mView.onLoginSuccess();
}
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
mView.onInvalidVerificationCode();
}
});
}
private void checkIfUserExistInDataBase() {
mFirebaseManager.checkIfUserExistInDataBase(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if (!dataSnapshot.exists()) {
// If not found in database >> just push new user with basic info [Uid, phone]
addNewUserToDatabase();
}
FcmUtils.initFcm();
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
private void addNewUserToDatabase() {
mFirebaseManager.addNewUserToDataBase();
}
@Override
public void detachView(){
mView = null;
}
}
| 39.608 | 126 | 0.661079 |
d9dd23a75f15841bc9d35ad471f1056e8cdbec33 | 462 | package lychi;
public final class Version {
public static final String VERSION = "20180207";
public static final String COMMIT = "fe2ea2a";
public static final String USER = "tyler";
public static final String TIMESTAMP = "02/07/2018 at 17:57:34 EST";
private Version () {}
public static void main (String[] argv) {
System.out.println("LyChI Version: commit="+COMMIT+" version="+VERSION+" timestamp="+TIMESTAMP+" user="+USER);
}
}
| 38.5 | 116 | 0.683983 |
9dd6ff9d8b277794d6764431d203326f0c7afade | 5,816 | /*
* 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.aliyuncs.cloudapi.model.v20160714;
import java.util.List;
import com.aliyuncs.AcsResponse;
import com.aliyuncs.cloudapi.transform.v20160714.DescribeApiStageResponseUnmarshaller;
import com.aliyuncs.transform.UnmarshallerContext;
/**
* @author auto create
* @version
*/
public class DescribeApiStageResponse extends AcsResponse {
private String requestId;
private String groupId;
private String stageId;
private String stageName;
private String description;
private String createdTime;
private String modifiedTime;
private List<VariableItem> variables;
public String getRequestId() {
return this.requestId;
}
public void setRequestId(String requestId) {
this.requestId = requestId;
}
public String getGroupId() {
return this.groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
public String getStageId() {
return this.stageId;
}
public void setStageId(String stageId) {
this.stageId = stageId;
}
public String getStageName() {
return this.stageName;
}
public void setStageName(String stageName) {
this.stageName = stageName;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
public String getCreatedTime() {
return this.createdTime;
}
public void setCreatedTime(String createdTime) {
this.createdTime = createdTime;
}
public String getModifiedTime() {
return this.modifiedTime;
}
public void setModifiedTime(String modifiedTime) {
this.modifiedTime = modifiedTime;
}
public List<VariableItem> getVariables() {
return this.variables;
}
public void setVariables(List<VariableItem> variables) {
this.variables = variables;
}
public static class VariableItem {
private String variableName;
private String variableValue;
private Boolean supportRoute;
private StageRouteModel stageRouteModel;
public String getVariableName() {
return this.variableName;
}
public void setVariableName(String variableName) {
this.variableName = variableName;
}
public String getVariableValue() {
return this.variableValue;
}
public void setVariableValue(String variableValue) {
this.variableValue = variableValue;
}
public Boolean getSupportRoute() {
return this.supportRoute;
}
public void setSupportRoute(Boolean supportRoute) {
this.supportRoute = supportRoute;
}
public StageRouteModel getStageRouteModel() {
return this.stageRouteModel;
}
public void setStageRouteModel(StageRouteModel stageRouteModel) {
this.stageRouteModel = stageRouteModel;
}
public static class StageRouteModel {
private String parameterCatalog;
private String serviceParameterName;
private String location;
private String parameterType;
private String routeMatchSymbol;
private List<RouteRuleItem> routeRules;
public String getParameterCatalog() {
return this.parameterCatalog;
}
public void setParameterCatalog(String parameterCatalog) {
this.parameterCatalog = parameterCatalog;
}
public String getServiceParameterName() {
return this.serviceParameterName;
}
public void setServiceParameterName(String serviceParameterName) {
this.serviceParameterName = serviceParameterName;
}
public String getLocation() {
return this.location;
}
public void setLocation(String location) {
this.location = location;
}
public String getParameterType() {
return this.parameterType;
}
public void setParameterType(String parameterType) {
this.parameterType = parameterType;
}
public String getRouteMatchSymbol() {
return this.routeMatchSymbol;
}
public void setRouteMatchSymbol(String routeMatchSymbol) {
this.routeMatchSymbol = routeMatchSymbol;
}
public List<RouteRuleItem> getRouteRules() {
return this.routeRules;
}
public void setRouteRules(List<RouteRuleItem> routeRules) {
this.routeRules = routeRules;
}
public static class RouteRuleItem {
private Long maxValue;
private Long minValue;
private String conditionValue;
private String resultValue;
public Long getMaxValue() {
return this.maxValue;
}
public void setMaxValue(Long maxValue) {
this.maxValue = maxValue;
}
public Long getMinValue() {
return this.minValue;
}
public void setMinValue(Long minValue) {
this.minValue = minValue;
}
public String getConditionValue() {
return this.conditionValue;
}
public void setConditionValue(String conditionValue) {
this.conditionValue = conditionValue;
}
public String getResultValue() {
return this.resultValue;
}
public void setResultValue(String resultValue) {
this.resultValue = resultValue;
}
}
}
}
@Override
public DescribeApiStageResponse getInstance(UnmarshallerContext context) {
return DescribeApiStageResponseUnmarshaller.unmarshall(this, context);
}
}
| 22.198473 | 86 | 0.706843 |
4e77d8d219fde6e12abc8528a68639fc270819dd | 5,470 | package dev.anhcraft.craftkit.internal.tasks;
import dev.anhcraft.craftkit.events.ArmorChangeEvent;
import dev.anhcraft.craftkit.events.ArmorEquipEvent;
import dev.anhcraft.craftkit.events.ArmorUnequipEvent;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.inventory.EquipmentSlot;
import org.bukkit.inventory.ItemStack;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
public class ArmorHandleTask implements Runnable {
public static final Map<UUID, Map<EquipmentSlot, ItemStack>> data = new HashMap<>();
@Override
public void run() {
for(Player p : Bukkit.getOnlinePlayers()){
ItemStack h = p.getInventory().getHelmet();
ItemStack c = p.getInventory().getChestplate();
ItemStack l = p.getInventory().getLeggings();
ItemStack b = p.getInventory().getBoots();
Map<EquipmentSlot, ItemStack> x = data.get(p.getUniqueId());
if(x != null){
ItemStack oh = x.get(EquipmentSlot.HEAD);
if(oh == null){
if(h != null){
ArmorEquipEvent e = new ArmorEquipEvent(p, h, EquipmentSlot.HEAD);
Bukkit.getPluginManager().callEvent(e);
x.put(EquipmentSlot.HEAD, h);
}
} else {
if(h == null){
ArmorUnequipEvent e = new ArmorUnequipEvent(p, oh, EquipmentSlot.HEAD);
Bukkit.getPluginManager().callEvent(e);
x.put(EquipmentSlot.HEAD, null);
} else if(!oh.equals(h)){
ArmorChangeEvent e = new ArmorChangeEvent(p, oh, h, EquipmentSlot.HEAD);
Bukkit.getPluginManager().callEvent(e);
x.put(EquipmentSlot.HEAD, h);
}
}
ItemStack oc = x.get(EquipmentSlot.CHEST);
if(oc == null){
if(c != null){
ArmorEquipEvent e = new ArmorEquipEvent(p, c, EquipmentSlot.CHEST);
Bukkit.getPluginManager().callEvent(e);
x.put(EquipmentSlot.CHEST, c);
}
} else {
if(c == null){
ArmorUnequipEvent e = new ArmorUnequipEvent(p, oc, EquipmentSlot.CHEST);
Bukkit.getPluginManager().callEvent(e);
x.put(EquipmentSlot.CHEST, null);
} else if(!oc.equals(c)){
ArmorChangeEvent e = new ArmorChangeEvent(p, oc, c, EquipmentSlot.CHEST);
Bukkit.getPluginManager().callEvent(e);
x.put(EquipmentSlot.CHEST, c);
}
}
ItemStack ol = x.get(EquipmentSlot.LEGS);
if(ol == null){
if(l != null){
ArmorEquipEvent e = new ArmorEquipEvent(p, l, EquipmentSlot.LEGS);
Bukkit.getPluginManager().callEvent(e);
x.put(EquipmentSlot.LEGS, l);
}
} else {
if(l == null){
ArmorUnequipEvent e = new ArmorUnequipEvent(p, ol, EquipmentSlot.LEGS);
Bukkit.getPluginManager().callEvent(e);
x.put(EquipmentSlot.LEGS, null);
} else if(!ol.equals(l)){
ArmorChangeEvent e = new ArmorChangeEvent(p, ol, l, EquipmentSlot.LEGS);
Bukkit.getPluginManager().callEvent(e);
x.put(EquipmentSlot.LEGS, l);
}
}
ItemStack ob = x.get(EquipmentSlot.FEET);
if(ob == null){
if(b != null){
ArmorEquipEvent e = new ArmorEquipEvent(p, b, EquipmentSlot.FEET);
Bukkit.getPluginManager().callEvent(e);
x.put(EquipmentSlot.FEET, b);
}
} else {
if(b == null){
ArmorUnequipEvent e = new ArmorUnequipEvent(p, ob, EquipmentSlot.FEET);
Bukkit.getPluginManager().callEvent(e);
x.put(EquipmentSlot.FEET, null);
} else if(!ob.equals(b)){
ArmorChangeEvent e = new ArmorChangeEvent(p, ob, b, EquipmentSlot.FEET);
Bukkit.getPluginManager().callEvent(e);
x.put(EquipmentSlot.FEET, b);
}
}
} else {
x = new HashMap<>();
x.put(EquipmentSlot.HEAD, h);
x.put(EquipmentSlot.CHEST, c);
x.put(EquipmentSlot.LEGS, l);
x.put(EquipmentSlot.FEET, b);
Set<EquipmentSlot> set = x.keySet();
for(EquipmentSlot r : set){
ItemStack v = x.get(r);
if(v != null) {
ArmorEquipEvent e = new ArmorEquipEvent(p, v, r);
Bukkit.getPluginManager().callEvent(e);
}
}
}
data.put(p.getUniqueId(), x);
}
}
} | 44.836066 | 97 | 0.476782 |
7634468f1426357347762a949d5b06f999d937e5 | 876 | package com.example.gdrivepasswordvault;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import android.app.Activity;
import android.widget.TextView;
import android.widget.Toast;
public class Logger {
private static TextView statusBar;
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
private static Activity activity;
public static void setup(Activity act, TextView bar){
statusBar = bar;
activity = act;
}
public static void log(String s, boolean toast){
activity.runOnUiThread(() -> {
if(toast){
Toast.makeText(activity.getApplicationContext(), s, Toast.LENGTH_SHORT).show();
}
statusBar.append(String.format("%s::\t%s\n",dateFormat.format(new Date()), s));
});
}
}
| 28.258065 | 104 | 0.671233 |
ef82e726a527f57ea199ffe018a2dfcf4ca75509 | 9,238 | /*
* Copyright 2015 Adaptris Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.adaptris.core.interceptor;
import static com.adaptris.core.runtime.AdapterComponentMBean.ADAPTER_PREFIX;
import static com.adaptris.core.runtime.AdapterComponentMBean.CHANNEL_PREFIX;
import static com.adaptris.core.runtime.AdapterComponentMBean.ID_PREFIX;
import static com.adaptris.core.runtime.AdapterComponentMBean.JMX_ADAPTER_TYPE;
import static com.adaptris.core.runtime.AdapterComponentMBean.JMX_METRICS_TYPE;
import static com.adaptris.core.runtime.AdapterComponentMBean.JMX_WORKFLOW_TYPE;
import static com.adaptris.core.runtime.AdapterComponentMBean.WORKFLOW_PREFIX;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.management.JMX;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.adaptris.core.Adapter;
import com.adaptris.core.Channel;
import com.adaptris.core.CoreException;
import com.adaptris.core.SerializableAdaptrisMessage;
import com.adaptris.core.StandardWorkflow;
import com.adaptris.core.WorkflowInterceptor;
import com.adaptris.core.runtime.AdapterManager;
import com.adaptris.core.runtime.BaseComponentMBean;
import com.adaptris.core.runtime.ChildRuntimeInfoComponent;
import com.adaptris.core.runtime.WorkflowManagerMBean;
import com.adaptris.core.util.JmxHelper;
import com.adaptris.util.GuidGenerator;
public abstract class StatisticsMBeanCase extends com.adaptris.interlok.junit.scaffolding.BaseCase {
protected static final String DEFAULT_INTERCEPTOR_NAME = "MMI";
protected static final GuidGenerator GUID = new GuidGenerator();
protected MBeanServer mBeanServer;
protected List<ObjectName> registeredObjects;
@Before
public void setUp() throws Exception {
mBeanServer = JmxHelper.findMBeanServer();
registeredObjects = new ArrayList<ObjectName>();
}
@After
public void tearDown() throws Exception {
for (ObjectName bean : registeredObjects) {
if (mBeanServer.isRegistered(bean)) {
mBeanServer.unregisterMBean(bean);
log.trace(bean + " unregistered");
}
}
}
@Test
public void testRegistration() throws Exception {
String adapterName = this.getClass().getSimpleName() + "." + getName();
Adapter adapter = createAdapter(adapterName);
AdapterManager am = new AdapterManager(adapter);
try {
start(adapter);
am.registerMBean();
}
finally {
am.unregisterMBean();
stop(adapter);
}
}
@Test
public void testStandardGetters() throws Exception {
String adapterName = this.getClass().getSimpleName() + "." + getName();
Adapter adapter = createAdapter(adapterName);
AdapterManager am = new AdapterManager(adapter);
try {
start(adapter);
am.registerMBean();
Collection<BaseComponentMBean> children = am.getAllDescendants();
for (BaseComponentMBean bean : children) {
assertNotNull(bean.createObjectName());
if (bean instanceof ChildRuntimeInfoComponent) {
assertNotNull(((ChildRuntimeInfoComponent) bean).getParentId());
assertNotNull(((ChildRuntimeInfoComponent) bean).getParentObjectName());
assertNotNull(((ChildRuntimeInfoComponent) bean).getParentRuntimeInfoComponent());
}
}
}
finally {
stop(adapter);
am.unregisterMBean();
}
}
@Test
public void testGet_NoTimeslicesAvailable() throws Exception {
String adapterName = this.getClass().getSimpleName() + "." + getName();
Adapter adapter = createAdapter(adapterName);
List<BaseComponentMBean> mBeans = createJmxManagers(adapter);
try {
start(adapter);
register(mBeans);
ObjectName workflowObj = createWorkflowObjectName(adapterName);
ObjectName metricsObj = createMetricsObjectName(adapterName);
MetricsMBean stats = JMX.newMBeanProxy(mBeanServer, metricsObj, MetricsMBean.class);
WorkflowManagerMBean workflow = JMX.newMBeanProxy(mBeanServer, workflowObj, WorkflowManagerMBean.class);
assertEquals(0, stats.getNumberOfTimeSlices());
}
finally {
stop(adapter);
}
}
@Test
public void testGetTimesliceDuration() throws Exception {
String adapterName = this.getClass().getSimpleName() + "." + getName();
Adapter adapter = createAdapter(adapterName);
List<BaseComponentMBean> mBeans = createJmxManagers(adapter);
try {
start(adapter);
register(mBeans);
ObjectName workflowObj = createWorkflowObjectName(adapterName);
ObjectName metricsObj = createMetricsObjectName(adapterName);
MetricsMBean stats = JMX.newMBeanProxy(mBeanServer, metricsObj, MetricsMBean.class);
WorkflowManagerMBean workflow = JMX.newMBeanProxy(mBeanServer, workflowObj, WorkflowManagerMBean.class);
assertEquals(10, stats.getTimeSliceDurationSeconds());
}
finally {
stop(adapter);
}
}
protected Adapter createAdapter(String uid) throws CoreException {
return createAdapter(uid, 1, 1);
}
protected Adapter createSingleChannelAdapter(String uid, WorkflowInterceptor... interceptors) throws CoreException {
Adapter adapter = new Adapter();
adapter.setUniqueId(uid);
adapter.getChannelList().add(createSingleWorkflowChannel("channel1", interceptors));
return adapter;
}
protected Adapter createAdapter(String uid, int channels, int workflows) throws CoreException {
Adapter adapter = new Adapter();
adapter.setUniqueId(uid);
for (int i = 0; i < channels; i++) {
adapter.getChannelList().add(createChannel("channel" + (i + 1), workflows));
}
return adapter;
}
protected ObjectName createAdapterObjectName(String uid) throws Exception {
return ObjectName.getInstance(JMX_ADAPTER_TYPE + ID_PREFIX + uid);
}
protected ObjectName createMetricsObjectName(String uid) throws Exception {
return ObjectName.getInstance(JMX_METRICS_TYPE + ADAPTER_PREFIX + uid + CHANNEL_PREFIX + "channel1" + WORKFLOW_PREFIX
+ "workflow1" + ID_PREFIX + DEFAULT_INTERCEPTOR_NAME);
}
protected ObjectName createMetricsObjectName(String uid, String metricsId) throws Exception {
return ObjectName.getInstance(JMX_METRICS_TYPE + ADAPTER_PREFIX + uid + CHANNEL_PREFIX + "channel1" + WORKFLOW_PREFIX
+ "workflow1" + ID_PREFIX + metricsId);
}
protected ObjectName createWorkflowObjectName(String uid) throws Exception {
return ObjectName.getInstance(JMX_WORKFLOW_TYPE + ADAPTER_PREFIX + uid + CHANNEL_PREFIX + "channel1" + ID_PREFIX + "workflow1");
}
protected Channel createChannel(String uid, int workflows) throws CoreException {
Channel c = new Channel();
c.setUniqueId(uid);
for (int i = 0; i < workflows; i++) {
c.getWorkflowList().add(createWorkflow("workflow" + (i + 1)));
}
return c;
}
protected Channel createSingleWorkflowChannel(String uid, WorkflowInterceptor... interceptors) throws CoreException {
Channel c = new Channel();
c.setUniqueId(uid);
c.getWorkflowList().add(createWorkflow("workflow1", interceptors));
return c;
}
protected Channel createChannel(String uid) throws CoreException {
return createChannel(uid, 0);
}
protected StandardWorkflow createWorkflow(String uid) throws CoreException
{
WorkflowInterceptorImpl interceptor = createInterceptor();
interceptor.setUniqueId(DEFAULT_INTERCEPTOR_NAME);
return createWorkflow(uid, interceptor);
}
protected static StandardWorkflow createWorkflow(String uid, WorkflowInterceptor... interceptors)
throws CoreException {
StandardWorkflow wf = new StandardWorkflow();
wf.setUniqueId(uid);
for (WorkflowInterceptor wi : interceptors) {
wf.addInterceptor(wi);
}
return wf;
}
protected void register(Collection<BaseComponentMBean> mBeans) throws Exception {
for (BaseComponentMBean bean : mBeans) {
ObjectName name = bean.createObjectName();
registeredObjects.add(name);
mBeanServer.registerMBean(bean, name);
log.trace("MBean [" + bean + "] registered");
}
}
protected List<BaseComponentMBean> createJmxManagers(Adapter adapter) throws Exception {
List<BaseComponentMBean> result = new ArrayList<BaseComponentMBean>();
AdapterManager am = new AdapterManager(adapter);
result.add(am);
result.addAll(am.getAllDescendants());
return result;
}
protected abstract SerializableAdaptrisMessage createMessageForInjection(String payload);
protected abstract WorkflowInterceptorImpl createInterceptor();
}
| 36.65873 | 132 | 0.741935 |
35ccab548416f295cb6561dc2613c4472e2aee43 | 4,250 | /*
*
*
* Copyright 2018 Symphony Communication Services, LLC.
*
* Licensed to The Symphony Software Foundation (SSF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.symphony.oss.fugue.naming;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.annotation.Nonnull;
import com.symphony.oss.commons.fault.CodingFault;
/**
* Base class for names.
*
* @author Bruce Skingle
*
*/
public class Name
{
public static final String SEPARATOR = "-";
private final String name_;
private final String sha1Name_;
private final String md5Name_;
/**
* Base class for Names.
*
* Construct via a NameFactory.
*
* The name may not be <code>null</code>. Any optional additional non-null suffix components will be
* appended to the final name each with the standard separator.
*
* @param name The name
* @param additional Zero or more optional suffix elements.
*/
protected Name(@Nonnull String name, Object ...additional)
{
if(name == null)
throw new NullPointerException("name may not be null");
StringBuilder b = new StringBuilder(name);
if(additional != null)
{
for(Object s : additional)
{
if(s != null)
{
b.append(SEPARATOR);
b.append(s);
}
}
}
name_ = b.toString();
try
{
byte[] hash = MessageDigest.getInstance("SHA-1").digest(name_.getBytes(StandardCharsets.UTF_8));
sha1Name_ = Base62.encodeToString(hash);
hash = MessageDigest.getInstance("MD5").digest(name_.getBytes(StandardCharsets.UTF_8));
md5Name_ = Base62.encodeToString(hash);
}
catch(NoSuchAlgorithmException e)
{
throw new CodingFault(e); // "Can't happen"
}
}
/**
* Return a new name based on the current name with the given elements appended.
*
* @param name An element to append to the current Name.
*
* @return a new name based on the current name with the given elements appended.
*/
public Name append(@Nonnull String name)
{
return new Name(name_, name);
}
@Override
public String toString()
{
return name_;
}
/**
* Returns a short name of at most the given length.
*
* If the full name is short enough it is returned. Otherwise if maxLen is 27 or more the
* Base62 encoded SHA-1 hash of the name is returned, otherwise if maxLen is 22 or more the
* Base62 encoded MD5 hash of the name is returned.
*
* Base62 encoding uses only [a-zA-Z0-9], names are constructed from a series of elements
* separated by hyphens so as long as a long name has more than one element, the Base62
* encoded short versions cannot clash with unencoded names.
*
* @param maxLen The maximum length of the name.
*
* @return the short name.
*/
public String getShortName(int maxLen)
{
if(name_.length() <= maxLen)
return name_;
if(sha1Name_.length() <= maxLen)
return sha1Name_;
if(md5Name_.length() <= maxLen)
return md5Name_;
throw new IllegalArgumentException(md5Name_.length() + " is the shortest abbreviated name.");
}
@Override
public int hashCode()
{
return name_.hashCode();
}
@Override
public boolean equals(Object obj)
{
if(obj != null && getClass().equals(obj.getClass()))
return name_.equals(((Name)obj).toString());
else
return false;
}
}
| 26.898734 | 102 | 0.666588 |
b6273ad9c7a45c0d058e02c7b61219969b5dd150 | 2,662 | package com.vladsch.flexmark.parser;
import com.vladsch.flexmark.util.ast.Document;
import com.vladsch.flexmark.util.ast.Node;
import com.vladsch.flexmark.ast.Text;
import com.vladsch.flexmark.ast.util.Parsing;
import com.vladsch.flexmark.parser.core.delimiter.Bracket;
import com.vladsch.flexmark.parser.core.delimiter.Delimiter;
import com.vladsch.flexmark.parser.block.CharacterNodeFactory;
import com.vladsch.flexmark.util.sequence.BasedSequence;
import java.util.BitSet;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Parser for inline content (text, links, emphasized text, etc).
* <p><em>This interface is not intended to be implemented by clients.</em></p>
*/
public interface InlineParser {
void initializeDocument(Parsing parsing, Document document);
void finalizeDocument(Document document);
/**
* @param input the content to parse as inline
* @param node the node to append resulting nodes to (as children)
*/
void parse(BasedSequence input, Node node);
BasedSequence getInput();
int getIndex();
void setIndex(int index);
Delimiter getLastDelimiter();
Bracket getLastBracket();
Document getDocument();
InlineParserOptions getOptions();
Parsing getParsing();
Node getBlock();
List<Node> parseCustom(BasedSequence input, Node node, BitSet customCharacters, Map<Character, CharacterNodeFactory> nodeFactoryMap);
void mergeTextNodes(Node fromNode, Node toNode);
void mergeIfNeeded(Text first, Text last);
void moveNodes(Node fromNode, Node toNode);
void appendText(BasedSequence text, int beginIndex, int endIndex);
void appendNode(Node node);
// In some cases, we don't want the text to be appended to an existing node, we need it separate
Text appendSeparateText(BasedSequence text);
boolean flushTextNode();
BasedSequence match(Pattern re);
BasedSequence[] matchWithGroups(Pattern re);
Matcher matcher(Pattern re);
char peek();
char peek(int ahead);
boolean spnl();
boolean nonIndentSp();
boolean sp();
boolean spnlUrl();
BasedSequence toEOL();
boolean parseNewline();
BasedSequence parseLinkDestination();
BasedSequence parseLinkTitle();
int parseLinkLabel();
boolean parseAutolink();
boolean parseHtmlInline();
boolean parseEntity();
void processDelimiters(Delimiter stackBottom);
void removeDelimitersBetween(Delimiter opener, Delimiter closer);
void removeDelimiterAndNode(Delimiter delim);
void removeDelimiterKeepNode(Delimiter delim);
void removeDelimiter(Delimiter delim);
}
| 35.972973 | 137 | 0.743802 |
9fcac15f0d8a775e0095f2ff1a4d9e4cedbb1d97 | 1,405 | /*
* Copyright 2010 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.openehealth.ipf.platform.camel.ihe.hl7v3.pcc1;
import org.openehealth.ipf.commons.ihe.hl7v3.pcc1.Pcc1PortType;
import org.openehealth.ipf.platform.camel.ihe.hl7v3.Hl7v3ContinuationAwareEndpoint;
import org.openehealth.ipf.platform.camel.ihe.hl7v3.Hl7v3ContinuationAwareWebService;
// The main purpose of this class is to add "implements Pcc1PortType"
// to the class Hl7v3ContinuationAwareWebService, as required by CXF.
/**
* Continuation-Aware service implementation for the IHE PCC-1 transaction (QED).
* @author Dmytro Rud
*/
public class Pcc1ContinuationAwareService
extends Hl7v3ContinuationAwareWebService
implements Pcc1PortType {
public Pcc1ContinuationAwareService(Hl7v3ContinuationAwareEndpoint endpoint) {
super(endpoint);
}
}
| 39.027778 | 85 | 0.77153 |
78755a3cbeea2c2d3f07fc5890e28f15721c8fb6 | 23,984 | package com.droiuby.client.core;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.StringReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.JDOMParseException;
import org.jdom2.input.SAXBuilder;
import org.jruby.Ruby;
import org.jruby.embed.EmbedEvalUnit;
import org.jruby.embed.EvalFailedException;
import org.jruby.embed.ParseFailedException;
import org.jruby.embed.ScriptingContainer;
import org.jruby.runtime.builtin.IRubyObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import com.droiuby.application.bootstrap.DroiubyApp;
import com.droiuby.application.bootstrap.DroiubyBootstrap;
import com.droiuby.client.core.builder.ActivityBuilder;
import com.droiuby.client.core.console.WebConsole;
import com.droiuby.client.core.listeners.OnPageRefreshListener;
import com.droiuby.client.core.postprocessor.CssPreloadParser;
import com.droiuby.client.core.postprocessor.ScriptPreparser;
import com.droiuby.client.core.utils.OnWebConsoleReady;
import com.droiuby.client.core.utils.Utils;
import com.droiuby.launcher.Options;
class PageRefreshTask extends AsyncTask<Void, Void, PageAsset> {
Activity currentActivity;
ExecutionBundle bundle;
OnPageRefreshListener listener;
int refreshType;
public static final int FULL_ACTIVITY_REFRESH = 0;
public static final int QUICK_ACTIVITY_REFRESH = 1;
public PageRefreshTask(Activity currentActivity, ExecutionBundle bundle,
OnPageRefreshListener listener, int refreshType) {
this.currentActivity = currentActivity;
this.bundle = bundle;
this.refreshType = refreshType;
this.listener = listener;
}
@Override
protected PageAsset doInBackground(Void... params) {
DroiubyApp application = bundle.getPayload().getActiveApp();
DroiubyLauncher.downloadAssets(currentActivity, bundle.getPayload()
.getActiveApp(), bundle);
PageAsset page = DroiubyLauncher.loadPage(currentActivity, bundle,
application.getMainUrl(), Utils.HTTP_GET);
return page;
}
@Override
protected void onPostExecute(PageAsset result) {
super.onPostExecute(result);
if (refreshType == PageRefreshTask.FULL_ACTIVITY_REFRESH) {
currentActivity.finish();
DroiubyLauncher.startNewActivity(currentActivity, result);
} else {
DroiubyLauncher
.runController(currentActivity, bundle, result, true);
}
if (listener != null) {
listener.onRefreshComplete(result);
}
}
}
public class DroiubyLauncher extends AsyncTask<Void, Void, PageAsset> {
Context context;
String url;
Class<?> activityClass;
Options options;
protected DroiubyLauncher(Context context, String url,
Class<?> activityClass, Options options) {
this.context = context;
this.url = url;
this.activityClass = activityClass;
this.options = options;
}
public static void launch(Context context, String url, Options options) {
launch(context, url, null, options);
}
public static void launch(Context context, String url) {
launch(context, url, null, new Options());
}
public static void launch(Context context, String url,
Class<?> activityClass, Options options) {
try {
if (activityClass == null) {
activityClass = getDefaultActivityClass(context);
}
DroiubyLauncher launcher = new DroiubyLauncher(context, url,
activityClass, options);
launcher.execute();
} catch (ClassNotFoundException e) {
e.printStackTrace();
return;
}
}
public static Class<?> getDefaultActivityClass(Context context)
throws ClassNotFoundException {
Class<?> activityClass;
String packageName = context.getApplicationContext().getPackageName();
activityClass = Class.forName(packageName
+ ".activities.DroiubyActivity");
return activityClass;
}
private DroiubyApp download(String url) throws FileNotFoundException,
IOException {
String responseBody = null;
Log.d(DroiubyLauncher.class.toString(), "loading " + url);
String extraction_path;
DroiubyApp app = new DroiubyApp();
if (url.startsWith("asset:") && url.endsWith(".zip")) {
String asset_path = url.substring(6);
extraction_path = Utils.processArchive(context, url, context
.getAssets().open(asset_path), options.isOverwrite());
url = "file://" + extraction_path + File.separator
+ "config.droiuby";
} else {
String extraction_target = Utils.getAppExtractionTarget(url,
context);
File dir = new File(extraction_target);
if (dir.exists()) {
Log.d(Utils.class.toString(), "removing existing directory.");
FileUtils.deleteDirectory(dir);
}
dir.mkdirs();
app.setWorkingDirectory(extraction_target);
}
if (url.startsWith("file://") || url.indexOf("asset:") != -1) {
responseBody = Utils.loadAsset(context, url);
} else {
responseBody = Utils.query(url, context, null);
}
if (responseBody != null) {
Log.d(DroiubyLauncher.class.toString(), responseBody);
SAXBuilder sax = new SAXBuilder();
Document doc;
try {
doc = sax.build(new StringReader(responseBody));
Element rootElem = doc.getRootElement();
String appName = rootElem.getChild("name").getText();
String appDescription = rootElem.getChild("description")
.getText();
String baseUrl = rootElem.getChildText("base_url");
String mainActivity = rootElem.getChildText("main");
String framework = rootElem.getChildText("framework");
if (baseUrl == null || baseUrl.equals("")) {
if (url.startsWith("file://")) {
baseUrl = extractBasePath(url);
app.setWorkingDirectory(Utils.stripProtocol(baseUrl));
} else {
URL aURL = new URL(url);
String adjusted_path = aURL.getPath();
adjusted_path = extractBasePath(adjusted_path);
baseUrl = aURL.getProtocol() + "://" + aURL.getHost()
+ ":" + aURL.getPort() + adjusted_path;
}
}
app.setDescription(appDescription);
app.setName(appName);
app.setBaseUrl(baseUrl);
app.setMainUrl(mainActivity);
app.setFramework(framework);
app.setLaunchUrl(url);
app.setInitiallOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
String orientation = rootElem.getChildText("orientation");
if (orientation != null) {
if (orientation.equals("landscape")) {
app.setInitiallOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
} else if (orientation.equals("portrait")
|| orientation.equals("vertical")) {
app.setInitiallOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} else if (orientation.equals("sensor_landscape")) {
app.setInitiallOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
} else if (orientation.equals("sensor_portrait")) {
app.setInitiallOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);
} else if (orientation.equals("auto")) {
app.setInitiallOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
} else {
app.setInitiallOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
}
}
if (rootElem.getChild("assets") != null) {
List<Element> assets = rootElem.getChild("assets")
.getChildren("resource");
for (Element asset : assets) {
String asset_name = asset.getAttributeValue("name");
String asset_type = asset.getAttributeValue("type");
Log.d("APP DOWNLOADER", "loading asset " + asset_name
+ ".");
int type_int = DroiubyApp.ASSET_TYPE_SCRIPT;
if (asset_type.equals("script")) {
type_int = DroiubyApp.ASSET_TYPE_SCRIPT;
} else if (asset_type.equals("css")) {
type_int = DroiubyApp.ASSET_TYPE_CSS;
} else if (asset_type.equals("lib")) {
type_int = DroiubyApp.ASSET_TYPE_LIB;
} else if (asset_type.equals("font")
|| asset_type.equals("typeface")) {
type_int = DroiubyApp.ASSET_TYPE_TYPEFACE;
} else if (asset_type.equals("binary")
|| asset_type.equals("file")) {
type_int = DroiubyApp.ASSET_TYPE_BINARY;
} else if (asset_type.equals("vendor")) {
type_int = DroiubyApp.ASSET_TYPE_VENDOR;
}
app.addAsset(asset_name, type_int);
}
}
return app;
} catch (JDOMException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected PageAsset doInBackground(Void... params) {
DroiubyApp application = null;
try {
application = download(url);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (application != null) {
ExecutionBundleFactory factory = ExecutionBundleFactory
.getInstance(DroiubyBootstrap.classLoader);
ExecutionBundle executionBundle = factory.getNewScriptingContainer(
context, application.getBaseUrl(), options.isNewRuntime());
if (options.isRootBundle()) {
Log.d(this.getClass().toString(),
"Setting instance as root bundle");
executionBundle.setRootBundle(options.isRootBundle());
}
if (options.getConsole() != null) {
options.getConsole().setBundle(executionBundle);
}
executionBundle.getPayload().setDroiubyApp(application);
addPath(application.getWorkingDirectory(), executionBundle);
downloadAssets(context, application, executionBundle);
return loadPage(context, executionBundle, application.getMainUrl(),
Utils.HTTP_GET);
}
return null;
}
private void addPath(String path, ExecutionBundle executionBundle) {
Log.d(this.getClass().toString(), "Adding " + path + " to load path");
List<String> loadPaths = new ArrayList<String>();
loadPaths.add(path);
Ruby runtime = executionBundle.getPayload().getContainer()
.getProvider().getRuntime();
runtime.getLoadService().addPaths(loadPaths);
}
@Override
protected void onPostExecute(PageAsset result) {
super.onPostExecute(result);
if (result == null) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setMessage("Unable to download access app at " + url)
.setCancelable(true).create();
} else {
if (options.isNewActivity()) {
startNewActivity(context, activityClass, result);
}
if (options.isCloseParentActivity() && context instanceof Activity) {
((Activity) context).finish();
}
}
}
public static void startNewActivity(Context context, PageAsset result) {
try {
startNewActivity(context,
DroiubyLauncher.getDefaultActivityClass(context), result);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static void startNewActivity(Context context,
Class<?> activityClass, PageAsset result) {
Intent intent = new Intent(context, activityClass);
intent.putExtra("bundle", result.getBundle().getName());
intent.putExtra("pageUrl", result.getUrl());
context.startActivity(intent);
}
public static PageAsset loadPage(Context context, ExecutionBundle bundle,
String pageUrl, int method) {
PageAsset page = new PageAsset();
DroiubyApp app = bundle.getPayload().getActiveApp();
page.setBundle(bundle);
page.setUrl(pageUrl);
bundle.addPageAsset(pageUrl, page);
String responseBody;
String controllerIdentifier = null;
String controllerClass = null;
String baseUrl = app.getBaseUrl();
ScriptingContainer scriptingContainer = bundle.getContainer();
if (pageUrl.endsWith(".xml")) {
SAXBuilder sax = new SAXBuilder();
Document mainActivityDocument = null;
try {
responseBody = (String) Utils.loadAppAsset(app, context,
pageUrl, Utils.ASSET_TYPE_TEXT, method);
if (responseBody == null) {
responseBody = "<activity><t>Problem loading url "
+ pageUrl + "</t></activity>";
}
if (mainActivityDocument == null) {
mainActivityDocument = sax.build(new StringReader(
responseBody));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
responseBody = "<activity><t>Unable to open file " + pageUrl
+ "</t></activity>";
try {
mainActivityDocument = sax.build(new StringReader(
responseBody));
} catch (JDOMException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
} catch (JDOMParseException e) {
e.printStackTrace();
responseBody = "<activity><t>" + e.getMessage()
+ "</t></activity>";
try {
mainActivityDocument = sax.build(new StringReader(
responseBody));
} catch (JDOMException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
} catch (JDOMException e) {
e.printStackTrace();
}
controllerIdentifier = mainActivityDocument.getRootElement()
.getAttributeValue("controller");
ActivityBuilder builder = new ActivityBuilder(mainActivityDocument,
null, baseUrl);
page.setBuilder(builder);
ArrayList<Object> resultBundle = builder.preload(context, bundle);
page.setAssets(resultBundle);
} else if (pageUrl.endsWith(".rb")) {
controllerIdentifier = pageUrl;
ActivityBuilder builder = new ActivityBuilder(null,
null, baseUrl);
page.setBuilder(builder);
}
if (controllerIdentifier != null) {
String csplit[] = org.apache.commons.lang3.StringUtils.split(
controllerIdentifier, "#");
if (csplit.length == 2) {
if (!csplit[1].trim().equals("")) {
controllerClass = csplit[1];
}
if (!csplit[0].trim().equals("")) {
Log.d("Activity loader", "loading controller file "
+ baseUrl + csplit[0]);
downloadScript(context, bundle, page, app,
scriptingContainer, csplit[0]);
}
} else {
downloadScript(context, bundle, page, app, scriptingContainer,
controllerIdentifier);
String pathComponents[] = StringUtils.split(
controllerIdentifier, "/");
controllerClass = StringUtils.replace(
pathComponents[pathComponents.length - 1], ".rb", "");
}
}
page.setControllerClass(controllerClass);
scriptingContainer.put("$container_payload", bundle.getPayload());
try {
scriptingContainer.runScriptlet("$framework.before_activity_setup");
} catch (Exception e) {
e.printStackTrace();
}
return page;
}
private static void downloadScript(Context context, ExecutionBundle bundle,
PageAsset page, DroiubyApp app,
ScriptingContainer scriptingContainer, String scriptUrl) {
String controller_content = null;
try {
controller_content = (String) Utils.loadAppAsset(app, context,
scriptUrl, Utils.ASSET_TYPE_TEXT, Utils.HTTP_GET);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
long start = System.currentTimeMillis();
try {
page.setPreParsedScript(Utils.preParseRuby(scriptingContainer,
controller_content));
} catch (ParseFailedException e) {
e.printStackTrace();
bundle.addError(e.getMessage());
}
long elapsed = System.currentTimeMillis() - start;
Log.d(DroiubyLauncher.class.toString(),
"controller preparse: elapsed time = " + elapsed + "ms");
}
public static Boolean downloadAssets(Context context, DroiubyApp app,
ExecutionBundle executionBundle) {
ScriptingContainer scriptingContainer = executionBundle.getPayload()
.getContainer();
if (!executionBundle.isLibraryInitialized()) {
ArrayList<Object> resultBundle = new ArrayList<Object>();
HashMap<String, Integer> asset_map = app.getAssets();
if (app.getAssets().size() > 0) {
ExecutorService thread_pool = Executors
.newFixedThreadPool(Runtime.getRuntime()
.availableProcessors() + 1);
for (String asset_name : app.getAssets().keySet()) {
int asset_type = asset_map.get(asset_name);
int download_type = Utils.ASSET_TYPE_TEXT;
AssetDownloadCompleteListener listener = null;
if (asset_type == DroiubyApp.ASSET_TYPE_SCRIPT) {
listener = new ScriptPreparser();
} else if (asset_type == DroiubyApp.ASSET_TYPE_CSS) {
listener = new CssPreloadParser();
} else if (asset_type == DroiubyApp.ASSET_TYPE_VENDOR) {
List<String> loadPaths = new ArrayList<String>();
String path = Utils.stripProtocol(app.getBaseUrl())
+ asset_name;
File fpath = new File(path);
if (fpath.exists() && fpath.isDirectory()) {
for (File file : fpath.listFiles()) {
if (file.isDirectory()) {
String vendorPath;
try {
vendorPath = file.getCanonicalPath()
+ File.separator + "lib";
File libDir = new File(vendorPath);
if (libDir.exists()) {
Log.d(DroiubyLauncher.class
.toString(),
"Adding vendor path "
+ vendorPath);
loadPaths.add(vendorPath);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
scriptingContainer.getProvider().getRuntime()
.getLoadService().addPaths(loadPaths);
} else if (asset_type == DroiubyApp.ASSET_TYPE_LIB) {
List<String> loadPaths = new ArrayList<String>();
String path = Utils.stripProtocol(app.getBaseUrl())
+ asset_name;
Log.d(DroiubyLauncher.class.toString(),
"examine lib at " + path);
File fpath = new File(path);
if (fpath.isDirectory()) {
Log.d(DroiubyLauncher.class.toString(), "Adding "
+ path + " to load paths.");
loadPaths.add(path);
scriptingContainer.getProvider().getRuntime()
.getLoadService().addPaths(loadPaths);
}
continue;
} else if (asset_type == DroiubyApp.ASSET_TYPE_BINARY) {
download_type = Utils.ASSET_TYPE_BINARY;
} else if (asset_type == DroiubyApp.ASSET_TYPE_TYPEFACE) {
download_type = Utils.ASSET_TYPE_TYPEFACE;
}
Log.d(DroiubyLauncher.class.toString(), "downloading "
+ asset_name + " ...");
AssetDownloadWorker worker = new AssetDownloadWorker(
context, app, executionBundle, asset_name,
download_type, resultBundle, listener,
Utils.HTTP_GET);
thread_pool.execute(worker);
}
thread_pool.shutdown();
try {
thread_pool.awaitTermination(240, TimeUnit.SECONDS);
for (Object elem : resultBundle) {
Log.d(DroiubyLauncher.class.toString(),
"executing asset");
if (elem instanceof EmbedEvalUnit) {
((EmbedEvalUnit) elem).run();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Log.d(DroiubyLauncher.class.toString(), "initializing framework");
try {
scriptingContainer.runScriptlet("require '"
+ app.getFramework() + "/" + app.getFramework() + "'");
executionBundle.setLibraryInitialized(true);
} catch (Exception e) {
e.printStackTrace();
executionBundle.addError(e.getMessage());
}
}
return true;
}
private static String extractBasePath(String adjusted_path) {
int pos = 0;
while ((adjusted_path.indexOf("/", pos)) != -1) {
pos = adjusted_path.indexOf("/", pos) + 1;
}
adjusted_path = adjusted_path.substring(0, pos);
return adjusted_path;
}
public static IRubyObject runController(Activity activity,
ExecutionBundle bundle, PageAsset page, boolean refresh) {
bundle.getPayload().setCurrentActivity(activity);
bundle.getPayload().setCurrentPage(page);
EmbedEvalUnit preParsedScript = page.getPreParsedScript();
ScriptingContainer scriptingContainer = bundle.getContainer();
long start = System.currentTimeMillis();
IRubyObject instance = null;
try {
if (preParsedScript != null) {
preParsedScript.run();
long elapsed = System.currentTimeMillis() - start;
Log.d(DroiubyLauncher.class.toString(),
"Preparse started. elapsed " + elapsed);
start = System.currentTimeMillis();
}
scriptingContainer.runScriptlet("$framework.preload");
if (preParsedScript != null) {
Log.d(DroiubyLauncher.class.toString(),
"class = " + page.getControllerClass());
instance = (IRubyObject) scriptingContainer
.runScriptlet("$framework.script('"
+ page.getControllerClass() + "',"
+ (refresh ? "true" : "false") + ")");
bundle.setCurrentController(instance);
}
return instance;
} catch (EvalFailedException e) {
e.printStackTrace();
bundle.addError(e.getMessage());
Log.e(DroiubyLauncher.class.toString(), e.getMessage());
} catch (RuntimeException e) {
e.printStackTrace();
bundle.addError(e.getMessage());
Log.e(DroiubyLauncher.class.toString(), e.getMessage());
} catch (Exception e) {
e.printStackTrace();
bundle.addError(e.getMessage());
Log.e(DroiubyLauncher.class.toString(), e.getMessage());
} finally {
long elapsed = System.currentTimeMillis() - start;
Log.d(DroiubyLauncher.class.toString(),
"run Controller: elapsed time = " + elapsed + "ms");
}
return null;
}
public static void refresh(Activity currentActivity,
ExecutionBundle bundle, OnPageRefreshListener listener) {
PageRefreshTask refreshTask = new PageRefreshTask(currentActivity,
bundle, listener, PageRefreshTask.QUICK_ACTIVITY_REFRESH);
refreshTask.execute();
}
public static IRubyObject runController(Activity activity,
String bundleName, String pageUrl, boolean refresh) {
ExecutionBundle bundle = ExecutionBundleFactory.getBundle(bundleName);
PageAsset page = bundle.getPage(pageUrl);
return runController(activity, bundle, page, refresh);
}
public static void setPage(Activity activity, String bundleName,
String pageUrl) {
ExecutionBundle bundle = ExecutionBundleFactory.getBundle(bundleName);
PageAsset page = bundle.getPage(pageUrl);
setPage(activity, bundle, page);
}
public static void setPage(Activity activity, ExecutionBundle bundle,
PageAsset page) {
long start = System.currentTimeMillis();
bundle.getPayload().setExecutionBundle(bundle);
bundle.getPayload().setCurrentPage(page);
bundle.getPayload().setActivityBuilder(page.getBuilder());
bundle.setCurrentUrl(page.getUrl());
ActivityBuilder builder = page.getBuilder();
if (builder != null) {
Log.d(DroiubyLauncher.class.toString(),
"parsing and preparing views....");
builder.setCurrentActivity(activity);
View preparedViews = builder.prepare(bundle);
long elapsed = System.currentTimeMillis() - start;
Log.d(DroiubyLauncher.class.toString(),
"prepare activity: elapsed time = " + elapsed + "ms");
View view = builder.setPreparedView(preparedViews);
// apply CSS
builder.applyStyle(view, page.getAssets());
Log.d(DroiubyLauncher.class.toString(),
"build activity: elapsed time = " + elapsed + "ms");
}
}
public static void setupConsole(ExecutionBundle executionBundle,
OnWebConsoleReady listener) {
String web_public_loc;
Log.d(DroiubyLauncher.class.toString(), "Loading WebConsole...");
try {
web_public_loc = executionBundle.getPayload().getCurrentActivity()
.getCacheDir().getCanonicalPath()
+ "/www";
File webroot = new File(web_public_loc);
webroot.mkdirs();
WebConsole console = WebConsole
.getInstance(4000, webroot, listener);
Log.d(DroiubyLauncher.class.toString(),
"Setting current bundle ...");
console.setBundle(executionBundle);
console.setActivity(executionBundle.getPayload()
.getCurrentActivity());
} catch (IOException e) {
e.printStackTrace();
}
}
}
| 32.193289 | 83 | 0.700634 |
ee9887d774be195ff93626ecdc7ba7e8aae47701 | 68 | package com.google.android.gms.base;
public final class C1517R {
}
| 13.6 | 36 | 0.764706 |
dc95db5c3b11ac578e51682bdd544c0d6cafa247 | 9,473 | package mmt;
import java.io.Serializable;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.time.Duration;
/** A customer of the TrainCompany, has Itineraries
*
* @see Itinerary
* @see TrainCompany
*/
public class Passenger implements Serializable, Comparable {
/** The superclass for the type of the passenger */
public abstract class PassengerType implements Serializable {
/** Serial number for serialization. */
private static final long serialVersionUID = 20178079L;
/** The list of the passenger itineraries */
protected List<Itinerary> _itineraries;
/** The total cost of all the itineraries */
protected double _totalPaid;
/**
* The constructor of types
*
* @param itineraries the list of itineraries already traveled
* @param paid the total cost of all the itineraries
*/
public PassengerType(List<Itinerary> itineraries, double paid) {
_itineraries = itineraries;
_totalPaid = paid;
}
/**
* Gets the discount rate the passenger has
*
* @return a double with the discount rate
*/
public abstract double getDiscountRate();
/**
* Adds an itinerary, updates the total cost, and eventually updates
* the type of the passenger
*
* @param itinerary the itinerary to travel
*/
public void addItinerary(Itinerary itinerary) {
_totalPaid += itinerary.getBaseCost()*(1 - getDiscountRate());
_itineraries.add(itinerary);
}
/**
* Gets how many itineraries the passenger has
*
* @return the number of itineraries
*/
public int getNumberOfItineraries() {
return _itineraries.size();
}
/**
* Gets how much the passenger has paid
*
* @return the amount of money the passenger paid for all
* the itineraries
*/
public double getTotalPaid() {
return _totalPaid;
}
/**
* Gets all itineraries the passenger has
*
* @return an read-only list of itineraries
*/
public List<Itinerary> getItineraries() {
return Collections.unmodifiableList(_itineraries);
}
/**
* Helper method to calculate the value of the last n itineraries
* @param n the number of itineraries to consider
* @return the price of the last n itineraries, or all itineraries, if n is too big
*/
protected double calculatePriceLastItineraries(int n) {
double res = 0;
int last = _itineraries.size();
int first = (last - n > 0) ? last-n : 0;
for(Itinerary i : _itineraries.subList(first, last)) {
res += i.getBaseCost();
}
return res;
}
}
/** The basic passenger type */
public class NormalType extends PassengerType {
public NormalType(List<Itinerary> i, double p) {
super(i,p);
}
/**
* The concrete implementation of buying an itinerary for this
* type of passenger.
*
* @see PassengerType#addItinerary(Itinerary)
*/
@Override
public void addItinerary(Itinerary i) {
super.addItinerary(i);
double last10iter = calculatePriceLastItineraries(10);
if(last10iter > 2500) {
Passenger.this._type = new SpecialType(_itineraries,_totalPaid);
} else if(last10iter > 250) {
Passenger.this._type = new FrequentType(_itineraries, _totalPaid);
}
}
/**
* Gets the discount rate the passenger has
*
* @return 0.0, in this type (no discount)
* @see PassengerType#getDiscountRate()
*/
public double getDiscountRate() { return 0; }
/**
* Gets a string representation of the passenger category Normal
*
* @return "NORMAL", in this type
*/
@Override
public String toString() { return "NORMAL"; }
}
/** The frequent passenger type */
public class FrequentType extends PassengerType {
public FrequentType(List<Itinerary> i, double p) {
super(i,p);
}
/**
* The concrete implementation of buying an itinerary for this
* type of passenger.
*
* @see PassengerType#addItinerary(Itinerary)
*/
@Override
public void addItinerary(Itinerary i) {
super.addItinerary(i);
double last10iter = calculatePriceLastItineraries(10);
if(last10iter > 2500) {
Passenger.this._type = new SpecialType(_itineraries, _totalPaid);
} else if(last10iter <= 250) {
Passenger.this._type = new NormalType(_itineraries, _totalPaid);
}
}
/**
* Gets the discount rate the passenger has
*
* @return 0.15, in this type (15% of discount)
* @see PassengerType#getDiscountRate()
*/
public double getDiscountRate() { return 0.15; }
/**
* Gets a string representation of the passenger category Frequente
*
* @return "FREQUENTE", in this type
*/
@Override
public String toString() { return "FREQUENTE"; }
}
/** The special passenger type */
public class SpecialType extends PassengerType {
public SpecialType(List<Itinerary> i, double p) {
super(i,p);
}
/**
* The concrete implementation of buying an itinerary for this
* type of passenger.
*
* @see PassengerType#addItinerary(Itinerary)
*/
@Override
public void addItinerary(Itinerary i) {
super.addItinerary(i);
double last10iter = calculatePriceLastItineraries(10);
if(last10iter <= 2500) {
// Passenger.this._type = new FrequentType(_itineraries, _totalPaid);
// } else if(last10iter <= 250) {
Passenger.this._type = new NormalType(_itineraries, _totalPaid);
}
}
/**
* Gets the discount rate the passenger has
*
* @return 0.5, in this type (50% of discount)
* @see PassengerType#getDiscountRate()
*/
public double getDiscountRate() { return 0.5; }
/**
* Gets a string representation of the passenger category Especial
*
* @return "ESPECIAL", in this type
*/
@Override
public String toString() { return "ESPECIAL"; }
}
/** Serial number for serialization. */
private static final long serialVersionUID = 20178079L;
/** The passenger name */
private String _name;
/** The passenger id */
private int _passengerId;
/** The total time the Passenger has traveled */
protected Duration _timeTraveled;
/** The type of passenger
* @see Passenger.PassengerType
*/
private PassengerType _type;
/**
* Creates a new Passenger, of the normal type
*
* @param name the name for the new passenger
* @param id the numeric id attributed to passenger
*/
public Passenger(String name, int id) {
_name = name;
_passengerId = id;
_timeTraveled = Duration.ZERO;
_type = new NormalType(new ArrayList<Itinerary>(), 0);
}
/**
* Gets the name
*
* @return the name of the passenger
*/
public String getName() {
return _name;
}
/** Changes the name of this passenger
*
* @param newName the new name of the passenger
*/
public void setName(String newName) {
_name = newName;
}
/**
* Gets the numeric id given to the passenger
*
* @return the numeric id of the passenger;
*/
public int getId() {
return _passengerId;
}
/**
* Gets the discount rate the passenger has
*
* @return a double with the discount rate
* @see Passenger.PassengerType#getDiscountRate()
*/
public double getDiscountRate() {
return _type.getDiscountRate();
}
/**
* Adds an itinerary to the passenger
*
* @param i the itinerary to add
* @see Passenger.PassengerType#addItinerary(Itinerary)
*/
public void addItinerary(Itinerary i) {
_type.addItinerary(i);
_timeTraveled=_timeTraveled.plus(i.calculateTravelTime());
}
/**
* Gets how many itineraries the passenger has
*
* @return the number of itineraries
* @see Passenger.PassengerType#getNumberOfItineraries()
*/
public int getNumberOfItineraries() {
return _type.getNumberOfItineraries();
}
/**
* Gets how much the passenger has paid
*
* @return the amount of money the passenger paid for all
* the itineraries
* @see Passenger.PassengerType#getTotalPaid()
*/
public double getTotalPaid() {
return _type.getTotalPaid();
}
/**
* Gets all itineraries the passenger has
*
* @return an read-only list of itineraries
* @see Passenger.PassengerType#getItineraries()
*/
public List<Itinerary> getItineraries() {
return _type.getItineraries();
}
/**
* Returns all itineraries the passenger has, in string representation
*
* @return the string representation of all the itineraries the
* passenger has, with a header with name and id of the passenger;
* an empty string if the passenger has no itineraries
* @see Itinerary
*/
public String showItineraries() {
String res = new String();
if(getNumberOfItineraries() > 0) {
res += String.format("== Passageiro %d: %s ==\n",
_passengerId, _name);
List<Itinerary> itineraries = new ArrayList<>(getItineraries());
itineraries.sort(null);
for(int i = 0; i < getNumberOfItineraries(); ++i)
res += itineraries.get(i).toString(i+1);
}
return res;
}
/**
* Compares 2 passengers by id
*
* @return the diference between ids
*/
@Override
public int compareTo(Object o) throws ClassCastException, NullPointerException {
Passenger p = (Passenger) o;
return _passengerId - p._passengerId;
}
/**
* Gets the string representation of the passenger
*
* @return the textual representation of the passenger
*/
@Override
public String toString() {
return String.format("%d|%s|%s|%d|%.02f|%02d:%02d\n", _passengerId, _name,
_type.toString(), getNumberOfItineraries(), getTotalPaid(),
_timeTraveled.toHours(), _timeTraveled.toMinutes() % 60);
}
}
| 24.478036 | 85 | 0.679405 |
df89653464f3c9b925425fb3b96a7eeaa2867efb | 2,701 | /*
* Copyright 2011 DTO Solutions, Inc. (http://dtosolutions.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* NodeProcessorService.java
*
* User: Greg Schueler <a href="mailto:greg@dtosolutions.com">greg@dtosolutions.com</a>
* Created: 3/21/11 4:06 PM
*
*/
package com.dtolabs.rundeck.core.execution.dispatch;
import com.dtolabs.rundeck.core.common.*;
import com.dtolabs.rundeck.core.execution.ExecutionContext;
import com.dtolabs.rundeck.core.plugins.BaseProviderRegistryService;
import com.dtolabs.rundeck.core.execution.service.ExecutionServiceException;
import com.dtolabs.rundeck.core.plugins.configuration.ConfigurationException;
import com.dtolabs.rundeck.core.resources.FileResourceModelSource;
import com.dtolabs.rundeck.core.resources.ResourceModelSourceException;
import com.dtolabs.rundeck.plugins.ServiceNameConstants;
/**
* NodeProcessorService is ...
*
* @author Greg Schueler <a href="mailto:greg@dtosolutions.com">greg@dtosolutions.com</a>
*/
public class NodeDispatcherService extends BaseProviderRegistryService<NodeDispatcher>{
private static final String SERVICE_NAME = ServiceNameConstants.NodeDispatcher;
public NodeDispatcherService(Framework framework) {
super(framework);
registry.put("parallel", ParallelNodeDispatcher.class);
registry.put("sequential", SequentialNodeDispatcher.class);
}
public NodeDispatcher getNodeDispatcher(ExecutionContext context) throws ExecutionServiceException {
if (context.getThreadCount() > 1 && context.getNodes().getNodeNames().size() > 1) {
return providerOfType("parallel");
}else{
return providerOfType("sequential");
}
}
public static NodeDispatcherService getInstanceForFramework(Framework framework) {
if (null == framework.getService(SERVICE_NAME)) {
final NodeDispatcherService service = new NodeDispatcherService(framework);
framework.setService(SERVICE_NAME, service);
return service;
}
return (NodeDispatcherService) framework.getService(SERVICE_NAME);
}
public String getName() {
return SERVICE_NAME;
}
}
| 37.513889 | 105 | 0.739726 |
564bb37040709e4445489bb8ab4f98e9d847e6ce | 1,895 | package com.vato.app;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;
/**
* The State class is the abstract class for all states that a raft node may be in.
*/
public abstract class State {
Node context;
int currentTerm;
public State(Node context){
this.context = context;
currentTerm = 0;
}
/**
* This method is called when the heartbeat timeout for the node has elapsed.
*/
public abstract void heartbeatElapsed();
/**
* This method is called when the node receives a request vote message.
* @param request The Request Vote message.
* @return The response for the vote request
*/
public RequestVoteResponse rcvRequestVote(RequestVote request)
throws NotImplementedException{
throw new NotImplementedException();
}
/**
* This method is called when a response for a request for vote is received.
* @param response The response of a previously sent vote request message.
*/
public void rcvRequestVoteResponse(RequestVoteResponse response)
throws NotImplementedException{
throw new NotImplementedException();
}
/**
* This method is called when a leader sends an append entries message here.
* @param request The append entries message.
* @return A response to the append entrees message.
*/
public Response rcvAppendEntries(AppendEntries request)
throws NotImplementedException{
throw new NotImplementedException();
}
/**
* This message is called when a leader is sent an append entries response (maybe put this in leader only?)
* @param response The append entries response message.
*/
public void rcvAppendEntriesResponse(Response response)
throws NotImplementedException{
throw new NotImplementedException();
}
}
| 31.583333 | 111 | 0.685488 |
8ad81add2c03feef9408969baf9f3e8926286ff9 | 2,493 | package ru.heroes.modeselector.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import ru.heroes.modeselector.model.Game;
import ru.heroes.modeselector.model.Race;
import ru.heroes.modeselector.service.GamesService;
import java.util.HashMap;
import java.util.Map;
@Controller
public class GamesController {
@Autowired
private GamesService gamesService;
@GetMapping(value = "/games")
public String getGames(Model model) {
model.addAttribute("activeGames", gamesService.getActiveGames());
return "games";
}
@GetMapping(value = "/games/{id}")
public String lobby(@PathVariable String id, Model model) {
Game game = gamesService.getGame(id);
model.addAttribute("game", game);
model.addAttribute("races", gamesService.generate(game.getMode()));
return "lobby";
}
@PostMapping(value = "/games/{id}")
public String setResult(@PathVariable String id, @ModelAttribute("winner") String winner) {
gamesService.getGame(id).setWinner(winner);
return "redirect:/games";
}
@PostMapping(value = "/create-game")
public String createGame(@ModelAttribute("newGame") Game game) {
gamesService.addGame(game);
return "redirect:/games";
}
@GetMapping(value = "games/{id}/select/{race}")
public String select(@PathVariable String id, @PathVariable Race race, Model model) {
String name = SecurityContextHolder.getContext().getAuthentication().getName();
gamesService.getGame(id).getPositions().put(name, race);
return "redirect:/main/" + id;
}
@GetMapping(value = "/main/{id}")
public String mainTable(@PathVariable String id, Model model) {
Map<String, Race> positions = gamesService.getGame(id).getPositions();
positions.forEach(model::addAttribute);
return "main_table";
}
@GetMapping(value = "/reset")
public String reset(){
gamesService.getActiveGames().forEach(game -> game.setPositions(new HashMap<>()));
return "redirect:/games";
}
}
| 35.614286 | 95 | 0.708785 |
a7ce8c6189e63e863e89b2dec4e4482ca4131ee9 | 444 | package com.nekose.officemanage.usermanagement.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@RestController
@RequestMapping("/v1/users")
public class UserManagementController {
@GetMapping()
public String getUsers() {
return "dummy";
}
}
| 24.666667 | 62 | 0.804054 |
83a1500249503e39c32e9ea17f44c252d3fbd9f7 | 412 | /*
*
*/
package net.community.chest.javaagent.dumper.ui;
import net.community.chest.javaagent.dumper.ui.data.SelectiblePackageInfo;
/**
* <P>Copyright as per GPLv2</P>
* @author Lyor G.
* @since Aug 14, 2011 12:18:48 PM
*
*/
interface SelectiblePackageInfoHandler {
void processSelectiblePackageInfo (SelectiblePackageInfo pkgInfo);
void doneLoadingDumperData (DumperDataLoaderThread loader);
}
| 22.888889 | 74 | 0.752427 |
72bf42d4b70187775262ed3be1f1b5ea6bec8fcd | 1,634 | /*
* Copyright 2013 Foundation4GWT
*
* 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.wfairclough.foundation4gwt.client.ui.resources;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.HeadElement;
import com.google.gwt.dom.client.ScriptElement;
/**
* Methods to inject JavaScript code into the document header.
*
* @since 2.0.4.0
*
* @author Carlos Alexandro Becker
*/
public class JavaScriptInjector extends AbstractInjector {
/**
* Injects the JavaScript code into a
* {@code <script type="text/javascript">...</script>} element in the
* document header.
*
* @param javascript
* the JavaScript code
*/
public static void inject(String javascript) {
HeadElement head = getHead();
ScriptElement element = createScriptElement();
element.setText(javascript);
head.appendChild(element);
}
private static ScriptElement createScriptElement() {
ScriptElement script = Document.get().createScriptElement();
script.setAttribute("type", "text/javascript");
script.setAttribute("charset", "UTF-8");
return script;
}
}
| 30.259259 | 76 | 0.72399 |
22ca327349890c196b214c06c7e885fe8d5738d1 | 904 | public class Filme {
private String nome;
private FilmeEstado estado;
public Filme() {
this.estado = FilmeEstadoNaoAssistido.getInstance();
}
public void setEstado(FilmeEstado estado) {
this.estado = estado;
}
public String marcarAssistido() {
return estado.marcarAssistido(this);
}
public String marcarNaoAssistido() {
return estado.marcarNaoAssistido(this);
}
public String marcarAssistindo() {
return estado.marcarAssistindo(this);
}
public String marcarInterrompido() {
return estado.marcarInterrompido(this);
}
public String getNomeEstado() {
return estado.getEstado();
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public FilmeEstado getEstado() {
return estado;
}
}
| 19.652174 | 60 | 0.621681 |
a47a30e452c6bcae57f8eade7ca3e2e77b435977 | 2,164 | /*
* smart-doc https://github.com/shalousun/smart-doc
*
* Copyright (C) 2018-2022 smart-doc
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.smartdoc.gradle.plugin;
import com.smartdoc.gradle.constant.GlobalConstants;
import com.smartdoc.gradle.constant.TaskConstants;
import com.smartdoc.gradle.extension.SmartDocPluginExtension;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.Task;
import org.gradle.api.plugins.JavaPlugin;
/**
* @author yu 2020/2/16.
*/
public class SmartDocPlugin implements Plugin<Project> {
@Override
public void apply(Project project) {
project.getPluginManager().apply(JavaPlugin.class);
Task javaCompileTask = project.getTasks().getByName(JavaPlugin.COMPILE_JAVA_TASK_NAME);
TaskConstants.taskMap.forEach((taskName, taskClass) ->
this.createTask(project, taskName, taskClass, javaCompileTask));
// extend project-model to get our settings/configuration via nice configuration
project.getExtensions().create(GlobalConstants.EXTENSION_NAME, SmartDocPluginExtension.class);
}
private <T extends Task> void createTask(Project project, String taskName, Class<T> taskClass, Task javaCompileTask) {
T t = project.getTasks().create(taskName, taskClass);
t.setGroup(GlobalConstants.TASK_GROUP);
t.dependsOn(javaCompileTask);
}
}
| 38.642857 | 122 | 0.744917 |
c76a10cc8cfbfc23bff76c7bb491fa38060827fe | 1,857 | // WARNING: This file is autogenerated. DO NOT EDIT!
// Generated 2020-08-29 20:45:22 +0200
package jnr.constants.platform.solaris;
public enum SocketMessage implements jnr.constants.Constant {
MSG_DONTWAIT(0x80L),
MSG_OOB(0x1L),
MSG_PEEK(0x2L),
MSG_DONTROUTE(0x4L),
MSG_EOR(0x8L),
MSG_TRUNC(0x20L),
MSG_CTRUNC(0x10L),
MSG_WAITALL(0x40L),
// MSG_PROXY not defined
// MSG_FIN not defined
// MSG_SYN not defined
// MSG_CONFIRM not defined
// MSG_RST not defined
// MSG_ERRQUEUE not defined
MSG_NOSIGNAL(0x200L);
// MSG_MORE not defined
// MSG_FASTOPEN not defined
// MSG_EOF not defined
// MSG_FLUSH not defined
// MSG_HOLD not defined
// MSG_SEND not defined
// MSG_HAVEMORE not defined
// MSG_RCVMORE not defined
// MSG_COMPAT not defined
private final long value;
private SocketMessage(long value) { this.value = value; }
public static final long MIN_VALUE = 0x1L;
public static final long MAX_VALUE = 0x200L;
static final class StringTable {
public static final java.util.Map<SocketMessage, String> descriptions = generateTable();
public static final java.util.Map<SocketMessage, String> generateTable() {
java.util.Map<SocketMessage, String> map = new java.util.EnumMap<SocketMessage, String>(SocketMessage.class);
map.put(MSG_DONTWAIT, "MSG_DONTWAIT");
map.put(MSG_OOB, "MSG_OOB");
map.put(MSG_PEEK, "MSG_PEEK");
map.put(MSG_DONTROUTE, "MSG_DONTROUTE");
map.put(MSG_EOR, "MSG_EOR");
map.put(MSG_TRUNC, "MSG_TRUNC");
map.put(MSG_CTRUNC, "MSG_CTRUNC");
map.put(MSG_WAITALL, "MSG_WAITALL");
map.put(MSG_NOSIGNAL, "MSG_NOSIGNAL");
return map;
}
}
public final String toString() { return StringTable.descriptions.get(this); }
public final int value() { return (int) value; }
public final int intValue() { return (int) value; }
public final long longValue() { return value; }
public final boolean defined() { return true; }
}
| 33.160714 | 113 | 0.750673 |
d516fcb11815ce99d02d1b29aeee2b4c841cca01 | 628 | package vdsMain.tool;
import bitcoin.UInt256;
import vdsMain.transaction.CHash256;
//bqu
public class Hash {
public static UInt256 m10362a(byte[] bArr) {
return m10363a(bArr, 0, bArr.length);
}
/* renamed from: a */
public static UInt256 m10363a(byte[] bArr, int i, int i2) {
byte[] bArr2 = new byte[1];
UInt256 uInt256 = new UInt256();
CHash256 jVar = new CHash256();
if (bArr == null || i2 < 1) {
jVar.writeAllBytes(bArr2);
} else {
jVar.mo44126a(bArr, i, i2);
}
jVar.Finalize(uInt256);
return uInt256;
}
}
| 24.153846 | 63 | 0.571656 |
404b6082afdd41e5abdfe5cad8310a28e4884988 | 660 | package com.nice.mqtt.thread.pool;
import java.util.concurrent.Callable;
/**
* @Author hzdz163@163.com
* @Description CallableTemplate
* @Date 17:03 2020/9/24
* @Param
* @return
**/
public abstract class CallableTemplate<V> implements Callable<V> {
/**
* 前置处理
*/
public void beforeProcess() {
}
/**
* 处理业务逻辑
*
* @return
*/
public abstract V process() throws Exception;
/**
* 后置处理
*/
public void afterProcess() {
}
@Override
public V call() throws Exception {
beforeProcess();
V result = process();
afterProcess();
return result;
}
}
| 16.5 | 66 | 0.566667 |
11e9cc213266a267e0556a68f515b02996224f4f | 850 | package com.springboot.chapter6.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import com.springboot.chapter6.dao.UserDao;
import com.springboot.chapter6.pojo.User;
import com.springboot.chapter6.service.UserService;
/**** imports ****/
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao = null;
@Override
@Transactional(isolation = Isolation.READ_COMMITTED, timeout = 1)
public int insertUser(User user) {
return userDao.insertUser(user);
}
@Override
@Transactional(isolation = Isolation.READ_COMMITTED, timeout = 1)
public User getUser(Long id) {
return userDao.getUser(id);
}
} | 28.333333 | 66 | 0.8 |
0f89905a6d423ed9e9c415b57a208e970b8e8cf1 | 3,650 | /**
* Copyright (c) 2015 Mark S. Kolich
* http://mark.koli.ch
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
package com.kolich.blog.components;
import com.kolich.blog.ApplicationConfig;
import com.kolich.blog.exceptions.ContentNotFoundException;
import com.kolich.common.functional.either.Either;
import curacao.annotations.Component;
import curacao.components.ComponentDestroyable;
import curacao.entities.AppendableCuracaoEntity;
import com.kolich.http.HttpClient4ClosureBuilder;
import com.kolich.http.helpers.StringClosures.StringOrNullClosure;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.CloseableHttpClient;
import java.io.Reader;
import java.io.StringReader;
import java.io.Writer;
import static com.google.common.base.Charsets.UTF_8;
import static com.google.common.net.MediaType.JSON_UTF_8;
import static javax.servlet.http.HttpServletResponse.SC_OK;
import static org.apache.commons.io.IOUtils.copyLarge;
@Component
public class TwitterFeedHttpClient implements ComponentDestroyable {
private static final String twitterFeedUrl__ = ApplicationConfig.getTwitterFeedUrl();
private static final String UTF_8_STRING = UTF_8.toString();
public static final class TwitterFeed extends AppendableCuracaoEntity {
private static final String JSON_UTF_8_TYPE = JSON_UTF_8.toString();
private final String jsonString_;
public TwitterFeed(final String jsonString) {
jsonString_ = jsonString;
}
@Override
public final void toWriter(final Writer writer) throws Exception {
try (final Reader reader = new StringReader(jsonString_)) {
copyLarge(reader, writer);
}
}
@Override
public final int getStatus() {
return SC_OK;
}
@Override
public final String getContentType() {
return JSON_UTF_8_TYPE;
}
}
private final HttpClient httpClient_;
public TwitterFeedHttpClient() {
httpClient_ = HttpClient4ClosureBuilder.Factory.getNewInstanceWithProxySelector();
}
public final TwitterFeed getTweets() {
final Either<Void,String> feed = new StringOrNullClosure(httpClient_, UTF_8_STRING){}.get(twitterFeedUrl__);
if (!feed.success()) {
throw new ContentNotFoundException("Failed to load Twitter feed from URL: " + twitterFeedUrl__);
}
return new TwitterFeed(feed.right());
}
@Override
public final void destroy() throws Exception {
((CloseableHttpClient) httpClient_).close();
}
}
| 34.761905 | 116 | 0.732055 |
b01f22a65e38919ac71341fe1778b9f7c06d74cd | 8,378 | package com.tuling.tim.common.data.construct;
import org.junit.Assert;
import org.junit.Test;
import java.util.List;
public class TrieTreeTest {
@Test
public void insert() throws Exception {
TrieTree trieTree = new TrieTree();
trieTree.insert("abc");
trieTree.insert("abcd");
}
@Test
public void all() throws Exception {
TrieTree trieTree = new TrieTree();
trieTree.insert("ABC");
trieTree.insert("abC");
List<String> all = trieTree.all();
String result = "";
for (String s : all) {
result += s + ",";
System.out.println(s);
}
Assert.assertTrue("ABC,abC,".equals(result));
}
@Test
public void all2() throws Exception {
TrieTree trieTree = new TrieTree();
trieTree.insert("abc");
trieTree.insert("abC");
List<String> all = trieTree.all();
String result = "";
for (String s : all) {
result += s + ",";
System.out.println(s);
}
//Assert.assertTrue("ABC,abC,".equals(result));
}
@Test
public void prefixSea() throws Exception {
TrieTree trieTree = new TrieTree();
trieTree.insert("java");
trieTree.insert("jsf");
trieTree.insert("jsp");
trieTree.insert("javascript");
trieTree.insert("php");
String result = "";
List<String> ab = trieTree.prefixSearch("jav");
for (String s : ab) {
result += s + ",";
System.out.println(s);
}
Assert.assertTrue(result.equals("java,javascript,"));
}
@Test
public void prefixSea2() throws Exception {
TrieTree trieTree = new TrieTree();
trieTree.insert("java");
trieTree.insert("jsf");
trieTree.insert("jsp");
trieTree.insert("javascript");
trieTree.insert("php");
String result = "";
List<String> ab = trieTree.prefixSearch("j");
for (String s : ab) {
result += s + ",";
System.out.println(s);
}
Assert.assertTrue(result.equals("java,javascript,jsf,jsp,"));
}
@Test
public void prefixSea3() throws Exception {
TrieTree trieTree = new TrieTree();
trieTree.insert("java");
trieTree.insert("jsf");
trieTree.insert("jsp");
trieTree.insert("javascript");
trieTree.insert("php");
String result = "";
List<String> ab = trieTree.prefixSearch("js");
for (String s : ab) {
result += s + ",";
System.out.println(s);
}
Assert.assertTrue(result.equals("jsf,jsp,"));
}
@Test
public void prefixSea4() throws Exception {
TrieTree trieTree = new TrieTree();
trieTree.insert("java");
trieTree.insert("jsf");
trieTree.insert("jsp");
trieTree.insert("javascript");
trieTree.insert("php");
String result = "";
List<String> ab = trieTree.prefixSearch("jav");
for (String s : ab) {
result += s + ",";
System.out.println(s);
}
Assert.assertTrue(result.equals("java,javascript,"));
}
@Test
public void prefixSea5() throws Exception {
TrieTree trieTree = new TrieTree();
trieTree.insert("java");
trieTree.insert("jsf");
trieTree.insert("jsp");
trieTree.insert("javascript");
trieTree.insert("php");
String result = "";
List<String> ab = trieTree.prefixSearch("js");
for (String s : ab) {
result += s + ",";
System.out.println(s);
}
Assert.assertTrue(result.equals("jsf,jsp,"));
}
@Test
public void prefixSearch() throws Exception {
TrieTree trieTree = new TrieTree();
trieTree.insert("abc");
trieTree.insert("abd");
trieTree.insert("ABe");
List<String> ab = trieTree.prefixSearch("AB");
for (String s : ab) {
System.out.println(s);
}
System.out.println("========");
//char[] chars = new char[3] ;
//for (int i = 0; i < 3; i++) {
// int a = 97 + i ;
// chars[i] = (char) a ;
//}
//
//String s = String.valueOf(chars);
//System.out.println(s);
}
@Test
public void prefixSearch2() throws Exception {
TrieTree trieTree = new TrieTree();
trieTree.insert("Cde");
trieTree.insert("CDa");
trieTree.insert("ABe");
List<String> ab = trieTree.prefixSearch("AC");
for (String s : ab) {
System.out.println(s);
}
Assert.assertTrue(ab.size() == 0);
}
@Test
public void prefixSearch3() throws Exception {
TrieTree trieTree = new TrieTree();
trieTree.insert("Cde");
trieTree.insert("CDa");
trieTree.insert("ABe");
List<String> ab = trieTree.prefixSearch("CD");
for (String s : ab) {
System.out.println(s);
}
Assert.assertTrue(ab.size() == 1);
}
@Test
public void prefixSearch4() throws Exception {
TrieTree trieTree = new TrieTree();
trieTree.insert("Cde");
trieTree.insert("CDa");
trieTree.insert("ABe");
List<String> ab = trieTree.prefixSearch("Cd");
String result = "";
for (String s : ab) {
result += s + ",";
System.out.println(s);
}
Assert.assertTrue(result.equals("Cde,"));
}
@Test
public void prefixSearch44() throws Exception {
TrieTree trieTree = new TrieTree();
trieTree.insert("a");
trieTree.insert("b");
trieTree.insert("c");
trieTree.insert("d");
trieTree.insert("e");
trieTree.insert("f");
trieTree.insert("g");
trieTree.insert("h");
}
@Test
public void prefixSearch5() throws Exception {
TrieTree trieTree = new TrieTree();
trieTree.insert("Cde");
trieTree.insert("CDa");
trieTree.insert("ABe");
trieTree.insert("CDfff");
trieTree.insert("Cdfff");
List<String> ab = trieTree.prefixSearch("Cd");
String result = "";
for (String s : ab) {
result += s + ",";
System.out.println(s);
}
Assert.assertTrue(result.equals("Cde,Cdfff,"));
}
@Test
public void prefixSearch6() throws Exception {
TrieTree trieTree = new TrieTree();
trieTree.insert("Cde");
trieTree.insert("CDa");
trieTree.insert("ABe");
trieTree.insert("CDfff");
trieTree.insert("Cdfff");
List<String> ab = trieTree.prefixSearch("CD");
String result = "";
for (String s : ab) {
result += s + ",";
System.out.println(s);
}
Assert.assertTrue(result.equals("CDa,CDfff,"));
}
@Test
public void prefixSearch7() throws Exception {
TrieTree trieTree = new TrieTree();
trieTree.insert("Cde");
trieTree.insert("CDa");
trieTree.insert("ABe");
trieTree.insert("CDfff");
trieTree.insert("Cdfff");
List<String> ab = trieTree.prefixSearch("");
String result = "";
for (String s : ab) {
result += s + ",";
System.out.println(s);
}
Assert.assertTrue(result.equals(""));
}
@Test
public void prefixSearch8() throws Exception {
TrieTree trieTree = new TrieTree();
List<String> ab = trieTree.prefixSearch("");
String result = "";
for (String s : ab) {
result += s + ",";
System.out.println(s);
}
Assert.assertTrue(result.equals(""));
}
@Test
public void prefixSearch9() throws Exception {
TrieTree trieTree = new TrieTree();
trieTree.insert("Cde");
trieTree.insert("CDa");
trieTree.insert("ABe");
trieTree.insert("CDfff");
trieTree.insert("Cdfff");
List<String> ab = trieTree.prefixSearch("CDFD");
String result = "";
for (String s : ab) {
result += s + ",";
System.out.println(s);
}
Assert.assertTrue(result.equals(""));
}
} | 26.345912 | 69 | 0.525901 |
bfb3835186e8f02052ece6aeb35e544f872173ba | 4,640 | /************************************************************************
* Menu.java is part of Titanium4j Desktop 1.2 Copyright 2012 Emitrom LLC
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use obj 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.emitrom.ti4j.desktop.client.ui;
import com.emitrom.ti4j.core.client.Function;
import com.emitrom.ti4j.core.client.ProxyObject;
import com.google.gwt.core.client.JavaScriptObject;
public class Menu extends ProxyObject {
public Menu() {
jsObj = creatPeer();
}
protected Menu(JavaScriptObject obj) {
jsObj = obj;
}
public native MenuItem addCheckItem(String label)/*-{
var obj = this.@com.emitrom.ti4j.core.client.ProxyObject::getJsObj()();
var peer = obj.addCheckItem(label);
return @com.emitrom.ti4j.desktop.client.ui.MenuItem::new(Lcom/google/gwt/core/client/JavaScriptObject;)(peer);
}-*/;
public native MenuItem addCheckItem(String label, Function listener)/*-{
var obj = this.@com.emitrom.ti4j.core.client.ProxyObject::getJsObj()();
var peer = obj.addCheckItem(label, function() {
listener.@com.emitrom.ti4j.core.client.Function::execute()();
});
return @com.emitrom.ti4j.desktop.client.ui.MenuItem::new(Lcom/google/gwt/core/client/JavaScriptObject;)(peer);
}-*/;
public native MenuItem addItem(String label)/*-{
var obj = this.@com.emitrom.ti4j.core.client.ProxyObject::getJsObj()();
var peer = obj.addItem(label);
return @com.emitrom.ti4j.desktop.client.ui.MenuItem::new(Lcom/google/gwt/core/client/JavaScriptObject;)(peer);
}-*/;
public native MenuItem addItem(String label, Function listener)/*-{
var obj = this.@com.emitrom.ti4j.core.client.ProxyObject::getJsObj()();
var peer = obj.addItem(label, function() {
listener.@com.emitrom.ti4j.core.client.Function::execute()();
});
return @com.emitrom.ti4j.desktop.client.ui.MenuItem::new(Lcom/google/gwt/core/client/JavaScriptObject;)(peer);
}-*/;
public native MenuItem addItem(String label, Function listener, String iconURL)/*-{
var obj = this.@com.emitrom.ti4j.core.client.ProxyObject::getJsObj()();
var peer = obj.addItem(label, function() {
listener.@com.emitrom.ti4j.core.client.Function::execute()();
}, iconURL);
return @com.emitrom.ti4j.desktop.client.ui.MenuItem::new(Lcom/google/gwt/core/client/JavaScriptObject;)(peer);
}-*/;
public native MenuItem addSeparatorItem()/*-{
var obj = this.@com.emitrom.ti4j.core.client.ProxyObject::getJsObj()();
var peer = obj.addSeparatorItem();
return @com.emitrom.ti4j.desktop.client.ui.MenuItem::new(Lcom/google/gwt/core/client/JavaScriptObject;)(peer);
}-*/;
public native String appendItem(Menu item)/*-{
var obj = this.@com.emitrom.ti4j.core.client.ProxyObject::getJsObj()();
return obj
.appendItem(item.@com.emitrom.ti4j.core.client.ProxyObject::getJsObj()());
}-*/;
public native String clear()/*-{
var obj = this.@com.emitrom.ti4j.core.client.ProxyObject::getJsObj()();
return obj.clear();
}-*/;
public native MenuItem getItemAt(int index)/*-{
var obj = this.@com.emitrom.ti4j.core.client.ProxyObject::getJsObj()();
var peer = obj.getItemAt(index);
return @com.emitrom.ti4j.desktop.client.ui.MenuItem::new(Lcom/google/gwt/core/client/JavaScriptObject;)(peer);
}-*/;
public native int getLength()/*-{
var obj = this.@com.emitrom.ti4j.core.client.ProxyObject::getJsObj()();
return obj.getLength();
}-*/;
public native String insterItemAt(MenuItem item, int index)/*-{
var obj = this.@com.emitrom.ti4j.core.client.ProxyObject::getJsObj()();
return obj.insterItemAt(
item.@com.emitrom.ti4j.core.client.ProxyObject::getJsObj()(),
index);
}-*/;
public native String removeItemAt(int index)/*-{
var obj = this.@com.emitrom.ti4j.core.client.ProxyObject::getJsObj()();
return obj.removeItemAt(index);
}-*/;
private native JavaScriptObject creatPeer()/*-{
return Ti.UI.createMenu();
}-*/;
}
| 41.061947 | 113 | 0.665948 |
dc57b215ad5024e87c20e0601a3556f006045825 | 1,803 | /*
* The contents of this file are subject to the terms
* of the Common Development and Distribution License
* (the "License"). You may not use this file except
* in compliance with the License.
*
* You can obtain a copy of the license at
* glassfish/bootstrap/legal/CDDLv1.0.txt or
* https://glassfish.dev.java.net/public/CDDLv1.0.html.
* See the License for the specific language governing
* permissions and limitations under the License.
*
* When distributing Covered Code, include this CDDL
* HEADER in each file and include the License file at
* glassfish/bootstrap/legal/CDDLv1.0.txt. If applicable,
* add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your
* own identifying information: Portions Copyright [yyyy]
* [name of copyright owner]
*/
/*
* @(#)ProtocolException.java 1.7 05/08/29
*
* Copyright 1997-2005 Sun Microsystems, Inc. All Rights Reserved.
*/
package com.sun.mail.iap;
/**
* @author John Mani
*/
public class ProtocolException extends Exception {
protected transient Response response = null;
private static final long serialVersionUID = -4360500807971797439L;
/**
* Constructs a ProtocolException with no detail message.
*/
public ProtocolException() {
super();
}
/**
* Constructs a ProtocolException with the specified detail message.
* @param s the detail message
*/
public ProtocolException(String s) {
super(s);
}
/**
* Constructs a ProtocolException with the specified Response object.
*/
public ProtocolException(Response r) {
super(r.toString());
response = r;
}
/**
* Return the offending Response object.
*/
public Response getResponse() {
return response;
}
}
| 26.130435 | 73 | 0.689407 |
37e5ae3a02cd463295b6ec881a327151b97cb1eb | 11,172 | package com.benny.openlauncher.viewutil;
import android.app.WallpaperManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.view.DragEvent;
import android.view.View;
import android.widget.Toast;
import com.afollestad.materialdialogs.MaterialDialog;
import com.benny.openlauncher.R;
import com.benny.openlauncher.activity.Home;
import com.benny.openlauncher.model.Item;
import com.benny.openlauncher.util.AppManager;
import com.benny.openlauncher.util.LauncherAction;
import com.benny.openlauncher.util.Tool;
import com.mikepenz.fastadapter.FastAdapter;
import com.mikepenz.fastadapter.IAdapter;
import com.mikepenz.fastadapter.commons.adapters.FastItemAdapter;
import net.qiujuer.genius.blur.StackBlur;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class DialogHelper {
public static void editItemDialog(String title, String defaultText, Context c, final onItemEditListener listener) {
MaterialDialog.Builder builder = new MaterialDialog.Builder(c);
builder.title(title)
.positiveText(R.string.ok)
.negativeText(R.string.cancel)
.input(null, defaultText, new MaterialDialog.InputCallback() {
@Override
public void onInput(@NonNull MaterialDialog dialog, CharSequence input) {
listener.itemLabel(input.toString());
}
}).show();
}
public static void alertDialog(Context context, String title, String msg) {
MaterialDialog.Builder builder = new MaterialDialog.Builder(context);
builder.title(title)
.content(msg)
.positiveText(R.string.ok)
.show();
}
public static void addActionItemDialog(final Context context, MaterialDialog.ListCallback callback) {
MaterialDialog.Builder builder = new MaterialDialog.Builder(context);
builder.title(R.string.desktop_action)
.items(R.array.entries__desktop_actions)
.itemsCallback(callback)
.show();
}
public static void selectAppDialog(final Context context, final OnAppSelectedListener onAppSelectedListener) {
MaterialDialog.Builder builder = new MaterialDialog.Builder(context);
FastItemAdapter<IconLabelItem> fastItemAdapter = new FastItemAdapter<>();
builder.title(R.string.select_app)
.adapter(fastItemAdapter, new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false))
.negativeText(R.string.cancel);
final MaterialDialog dialog = builder.build();
List<IconLabelItem> items = new ArrayList<>();
final List<AppManager.App> apps = AppManager.getInstance(context).getApps();
int size = Tool.dp2px(46, context);
int sizePad = Tool.dp2px(8, context);
for (int i = 0; i < apps.size(); i++) {
items.add(new IconLabelItem(context, apps.get(i).icon, apps.get(i).label, null, sizePad, size));
}
fastItemAdapter.set(items);
fastItemAdapter.withOnClickListener(new FastAdapter.OnClickListener<IconLabelItem>() {
@Override
public boolean onClick(View v, IAdapter<IconLabelItem> adapter, IconLabelItem item, int position) {
if (onAppSelectedListener != null) {
onAppSelectedListener.onAppSelected(apps.get(position));
}
dialog.dismiss();
return true;
}
});
dialog.show();
}
public static void selectActionDialog(final Context context, int titleId, LauncherAction.ActionItem selected, final int id, final OnActionSelectedListener onActionSelectedListener) {
new MaterialDialog.Builder(context)
.title(context.getString(titleId))
.negativeText(R.string.cancel)
.items(R.array.entries__gestures)
.itemsCallbackSingleChoice(LauncherAction.getActionItemIndex(selected) + 1, new MaterialDialog.ListCallbackSingleChoice() {
@Override
public boolean onSelection(MaterialDialog dialog, View itemView, int which, CharSequence text) {
LauncherAction.ActionItem item = null;
if (which > 0) {
item = LauncherAction.getActionItem(which - 1);
if (item != null && item.action == LauncherAction.Action.LaunchApp) {
final LauncherAction.ActionItem finalItem = item;
selectAppDialog(context, new OnAppSelectedListener() {
@Override
public void onAppSelected(AppManager.App app) {
finalItem.extraData = Tool.getStartAppIntent(app);
onActionSelectedListener.onActionSelected(finalItem);
Home.launcher.db.setGesture(id, finalItem);
}
});
} else if (onActionSelectedListener != null) {
onActionSelectedListener.onActionSelected(item);
Home.launcher.db.setGesture(id, item);
}
} else {
Home.launcher.db.deleteGesture(id);
}
return true;
}
}).show();
}
public static void setWallpaperDialog(final Context context) {
new MaterialDialog.Builder(context)
.title(R.string.wallpaper)
.iconRes(R.drawable.ic_photo_black_24dp)
.items(R.array.entries__wallpaper_options)
.itemsCallback(new MaterialDialog.ListCallback() {
@Override
public void onSelection(MaterialDialog dialog, View itemView, int position, CharSequence text) {
switch (position) {
case 0:
Intent intent = new Intent(Intent.ACTION_SET_WALLPAPER);
context.startActivity(Intent.createChooser(intent, context.getString(R.string.wallpaper_pick)));
break;
case 1:
try {
WallpaperManager.getInstance(context).setBitmap(StackBlur.blur(Tool.drawableToBitmap(context.getWallpaper()), 10, false));
} catch (Exception e) {
Tool.toast(context, context.getString(R.string.wallpaper_unable_to_blur));
}
break;
}
}
}).show();
}
public static void deletePackageDialog(Context context, DragEvent dragEvent) {
Intent intent = dragEvent.getClipData().getItemAt(0).getIntent();
intent.setExtrasClassLoader(Item.class.getClassLoader());
Item item = intent.getParcelableExtra("mDragData");
if (item.type == Item.Type.APP) {
try {
Uri packageURI = Uri.parse("package:" + item.intent.getComponent().getPackageName());
Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);
context.startActivity(uninstallIntent);
} catch (Exception e) {
}
}
}
public static void backupDialog(final Context context) {
new MaterialDialog.Builder(context)
.title(R.string.pref_title__backup)
.positiveText(R.string.cancel)
.items(R.array.entries__backup_options)
.itemsCallback(new MaterialDialog.ListCallback() {
@Override
public void onSelection(MaterialDialog dialog, View itemView, int item, CharSequence text) {
PackageManager m = context.getPackageManager();
String s = context.getPackageName();
if (context.getResources().getStringArray(R.array.entries__backup_options)[item].equals(context.getResources().getString(R.string.dialog__backup_app_settings__backup))) {
File directory = new File(Environment.getExternalStorageDirectory() + "/OpenLauncher/");
if (!directory.exists()) {
directory.mkdir();
}
try {
PackageInfo p = m.getPackageInfo(s, 0);
s = p.applicationInfo.dataDir;
Tool.copy(context, s + "/databases/home.db", directory + "/home.db");
Tool.copy(context, s + "/shared_prefs/app.xml", directory + "/app.xml");
Toast.makeText(context, R.string.dialog__backup_app_settings__success, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(context, R.string.dialog__backup_app_settings__error, Toast.LENGTH_SHORT).show();
}
}
if (context.getResources().getStringArray(R.array.entries__backup_options)[item].equals(context.getResources().getString(R.string.dialog__backup_app_settings__restore))) {
File directory = new File(Environment.getExternalStorageDirectory() + "/OpenLauncher/");
try {
PackageInfo p = m.getPackageInfo(s, 0);
s = p.applicationInfo.dataDir;
Tool.copy(context, directory + "/home.db", s + "/databases/home.db");
Tool.copy(context, directory + "/app.xml", s + "/shared_prefs/app.xml");
Toast.makeText(context, R.string.dialog__backup_app_settings__success, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(context, R.string.dialog__backup_app_settings__error, Toast.LENGTH_SHORT).show();
}
System.exit(1);
}
}
}).show();
}
public interface OnAppSelectedListener {
void onAppSelected(AppManager.App app);
}
public interface OnActionSelectedListener {
void onActionSelected(LauncherAction.ActionItem item);
}
public interface onItemEditListener {
void itemLabel(String label);
}
}
| 50.781818 | 195 | 0.571608 |
acad1b385cddd01b23098bb816046807d7897851 | 3,279 | /*******************************************************************************
* Copyright (c) 2018 Robert Koszewski
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*******************************************************************************/
package com.robertkoszewski.dsce.emulator.utils;
import java.awt.AWTException;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* Java Robot Screen Capture based Screen Grabber
* @author Robert Koszewski
*/
public class RobotScreenGrabber extends Thread implements ScreenGrabber {
private boolean hasFrame = false;
private BufferedImage screen;
// Locks
private ReentrantReadWriteLock rwLock = new ReentrantReadWriteLock();
private ReentrantLock screenLock = new ReentrantLock();
@Override
public synchronized void start() {
super.start();
}
@Override
public void run() {
super.run();
Robot robot;
try {
robot = new Robot();
Toolkit toolkit = Toolkit.getDefaultToolkit();
Rectangle screenRectangle;
while(!isInterrupted()) {
screenRectangle = new Rectangle(toolkit.getScreenSize());
screen = robot.createScreenCapture(screenRectangle); // Seems that what takes most of the time is storing the buffered image. Maybe multithread two Robot instances?
synchronized(screenLock) {
screenLock.notifyAll();
}
rwLock.writeLock().lock();
hasFrame = true;
rwLock.writeLock().unlock();
}
} catch (AWTException e) {
e.printStackTrace();
}
}
public boolean hasFrame() {
rwLock.readLock().lock();
boolean retHasFrame = hasFrame;
rwLock.readLock().unlock();
return retHasFrame;
}
public BufferedImage getFrame() {
rwLock.readLock().lock();
if(!hasFrame) {
// Wait for frame
synchronized(screenLock){
try {
screenLock.wait();
} catch (InterruptedException e) {
rwLock.readLock().unlock();
return null;
}
}
}
rwLock.readLock().unlock();
BufferedImage tscreen = screen;
rwLock.writeLock().lock();
hasFrame = false;
rwLock.writeLock().unlock();
return tscreen;
}
}
| 29.017699 | 168 | 0.689235 |
7c9c4264bd62f88d392eda04a044ba8d06a6751e | 1,664 | /* Copyright (c) The m-m-m Team, Licensed under the Apache License, Version 2.0
* http://www.apache.org/licenses/LICENSE-2.0 */
package net.sf.mmm.code.base.loader;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import net.sf.mmm.code.api.language.JavaLanguage;
/**
* Base implementation of {@link BaseSourceCodeProvider} for a source-code directory in the filesystem.
*
* @author Joerg Hohwiller (hohwille at users.sourceforge.net)
* @since 1.0.0
*/
public class BaseSourceCodeProviderDirectory extends BaseSourceCodeProvider {
private String sourceDirectory;
/**
* The constructor.
*
* @param sourceFolder the {@link File} pointing to the top-level source-code folder (where the root/default package
* is located).
*/
public BaseSourceCodeProviderDirectory(File sourceFolder) {
this(sourceFolder, JavaLanguage.TYPE_EXTENSION_JAVA);
}
/**
* The constructor.
*
* @param sourceFolder the {@link File} pointing to the top-level source-code folder (where the root/default package
* is located).
* @param typeExtension the {@link #getTypeExtension() type extension}.
*/
public BaseSourceCodeProviderDirectory(File sourceFolder, String typeExtension) {
super(typeExtension);
assert (sourceFolder.isDirectory());
this.sourceDirectory = sourceFolder.getAbsolutePath();
}
@Override
protected Path getPath(String path) {
return Paths.get(this.sourceDirectory, path);
}
@Override
public void close() {
this.sourceDirectory = null;
}
@Override
protected boolean isClosed() {
return (this.sourceDirectory == null);
}
}
| 25.6 | 118 | 0.714543 |
d5c97edddaadabde64231079321c7b71ca98b3ce | 541 | class Solution {
public List<Integer> minimizeWaitTime(int[] tasks) {
final Comparator<Integer> cmp = (i,j) -> {
final int cmpDuration = Integer.compare(tasks[i], tasks[j]);
if (cmpDuration != 0) return cmpDuration;
return Integer.compare(i,j);
};
final PriorityQueue<Integer> pq = new PriorityQueue<>(cmp);
for (int i = 0; i < tasks.length; i++)
pq.offer(i);
final List<Integer> res = new ArrayList<>();
while (!pq.isEmpty()) {
res.add(pq.poll()+1);
}
return res;
}
}
| 27.05 | 66 | 0.593346 |
2bad48854e0e4edc12287c34c7f3c7d6a07b9538 | 1,467 | package net.minecraft.server;
import com.google.common.collect.Sets;
import java.util.Arrays;
import java.util.Set;
public enum EnumDirection8 {
NORTH(new EnumDirection[]{EnumDirection.NORTH}), NORTH_EAST(new EnumDirection[]{EnumDirection.NORTH, EnumDirection.EAST}), EAST(new EnumDirection[]{EnumDirection.EAST}), SOUTH_EAST(new EnumDirection[]{EnumDirection.SOUTH, EnumDirection.EAST}), SOUTH(new EnumDirection[]{EnumDirection.SOUTH}), SOUTH_WEST(new EnumDirection[]{EnumDirection.SOUTH, EnumDirection.WEST}), WEST(new EnumDirection[]{EnumDirection.WEST}), NORTH_WEST(new EnumDirection[]{EnumDirection.NORTH, EnumDirection.WEST});
private static final int i = 1 << EnumDirection8.NORTH_WEST.ordinal();
private static final int j = 1 << EnumDirection8.WEST.ordinal();
private static final int k = 1 << EnumDirection8.SOUTH_WEST.ordinal();
private static final int l = 1 << EnumDirection8.SOUTH.ordinal();
private static final int m = 1 << EnumDirection8.SOUTH_EAST.ordinal();
private static final int n = 1 << EnumDirection8.EAST.ordinal();
private static final int o = 1 << EnumDirection8.NORTH_EAST.ordinal();
private static final int p = 1 << EnumDirection8.NORTH.ordinal();
private final Set<EnumDirection> q;
private EnumDirection8(EnumDirection... aenumdirection) {
this.q = Sets.immutableEnumSet(Arrays.asList(aenumdirection));
}
public Set<EnumDirection> a() {
return this.q;
}
}
| 50.586207 | 491 | 0.740286 |
402c3608946dd80eea1bffaaa3f4c8f846ceb744 | 9,908 | package lsedit;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;
import java.util.Enumeration;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellRenderer;
import javax.swing.event.TableModelListener;
// This is the class which maps to the data being presented/updated to lsedit variables
class MyTableModel extends AbstractTableModel {
Ta m_ta;
Vector m_classes;
int m_cnt_spanning;
private void restart1()
{
RelationClass[] containsClasses = m_ta.getContainsClasses();
Vector classes = m_classes;
Enumeration en;
RelationClass rc;
int i;
classes.clear();
for (i = 0; i < containsClasses.length; ++i) {
classes.add(containsClasses[i]);
}
m_cnt_spanning = i;
for (en = m_ta.enumRelationClassesInOrder(); en.hasMoreElements(); ) {
rc = (RelationClass) en.nextElement();
if (!classes.contains(rc)) {
classes.add(rc);
} } }
public void restart()
{
restart1();
fireTableDataChanged();
}
public MyTableModel(Ta ta)
{
m_ta = ta;
m_classes = new Vector();
restart1();
}
public void clearSpanningClasses()
{
// Used to signal should return null
m_cnt_spanning = 0;
}
public Vector getClasses()
{
return m_classes;
}
public int getCntSpanning()
{
return m_cnt_spanning;
}
public int getRowCount()
{
return (m_classes.size());
}
public int getColumnCount()
{
return(1);
}
public String getColumnName(int col)
{
return(null);
}
public Object getValueAt(int row, int col)
{
if (row < m_classes.size()) {
RelationClass rc = (RelationClass) m_classes.elementAt(row);
return(rc.getRelationLabel());
}
return "";
}
public boolean isCellEditable(int row, int col)
{
return(false);
}
public void setValueAt(Object value, int row, int col)
{
}
public void forceNotEmpty()
{
if (m_cnt_spanning == 0) {
Object rc = m_ta.getRelationBaseClass();
m_classes.remove(rc);
m_classes.insertElementAt(rc, 0);
m_cnt_spanning = 1;
} }
public void add(int[] rows)
{
Object rc;
int i, row;
boolean ret = false;
for (i = 0; i < rows.length; ++i) {
row = rows[i];
if (m_cnt_spanning <= row) {
rc = m_classes.elementAt(row);
m_classes.remove(row);
m_classes.insertElementAt(rc, m_cnt_spanning);
++m_cnt_spanning;
ret = true;
} }
if (ret) {
fireTableDataChanged();
}
}
public void remove(int[] rows)
{
Object rc;
int i, row, at;
boolean ret = false;
at = m_classes.size()-1;
for (i = rows.length; --i >= 0; ) {
row = rows[i];
if (row < m_cnt_spanning) {
rc = m_classes.elementAt(row);
m_classes.remove(row);
m_classes.insertElementAt(rc, at);
--at;
--m_cnt_spanning;
ret = true;
} }
forceNotEmpty();
if (ret) {
fireTableDataChanged();
} }
public void up(int[] rows)
{
Object rc;
int i, row;
boolean ret = false;
for (i = 0; i < rows.length; ++i) {
row = rows[i];
if (m_cnt_spanning == row) {
++m_cnt_spanning;
ret = true;
} else if (row > 0) {
rc = m_classes.elementAt(row);
m_classes.remove(row);
m_classes.insertElementAt(rc, row-1);
ret = true;
} }
if (ret) {
fireTableDataChanged();
} }
public void down(int[] rows)
{
Object rc;
int i, row;
boolean ret = false;
for (i = rows.length; --i >= 0; ) {
row = rows[i];
if (row == m_cnt_spanning-1) {
--m_cnt_spanning;
ret = true;
} else if (row < m_classes.size()-1) {
rc = m_classes.elementAt(row);
m_classes.remove(row);
m_classes.insertElementAt(rc, row+1);
ret = true;
} }
forceNotEmpty();
if (ret) {
fireTableDataChanged();
} }
}
// This is the class which decides how the table is drawn and edited
class MyJTable extends JTable implements TableModelListener {
public MyJTable(AbstractTableModel tableModel)
{
super(tableModel);
//drag and drop
setTableHeader(null);
// setFillsViewportHeight(false);
tableModel.addTableModelListener(this);
}
// Overload how cells are rendered
public TableCellRenderer getCellRenderer(int row, int column)
{
MyTableModel model = (MyTableModel) getModel();
Vector classes = model.getClasses();
TableCellRenderer ret;
Color foreground;
ret = super.getCellRenderer(row, column);
if (row < classes.size()) {
if (row < model.getCntSpanning()) {
foreground = Color.blue;
} else {
foreground = Color.black;
}
((JLabel) ret).setForeground(foreground);
}
return(ret);
}
}
public class SpanningClasses extends JDialog implements ActionListener { //Class definition
static protected final int BUTTON_ADD = 0;
static protected final int BUTTON_REMOVE = 1;
static protected final int BUTTON_UP = 2;
static protected final int BUTTON_DOWN = 3;
static protected final int BUTTON_OK = 4;
static protected final int BUTTON_CANCEL = 5;
static protected final int BUTTON_RESTART = 6;
static protected final int BUTTON_HELP = 7;
protected final static String[] m_button_titles =
{
"Add",
"Remove",
"Up",
"Down",
"Ok",
"Cancel",
"Restart",
"Help",
};
private LandscapeEditorCore m_ls;
private Diagram m_diagram;
private MyTableModel m_model;
private MyJTable m_table;
private JButton[] m_buttons;
protected SpanningClasses(JFrame frame, Diagram diagram)
{
super(frame, "Choose Spanning Classes",true); //false if non-modal
Container contentPane;
JScrollPane scrollPane;
JPanel panel;
JButton button;
Font font, bold;
int i;
m_diagram = diagram;
m_ls = diagram.getLs();
font = FontCache.getDialogFont();
bold = font.deriveFont(Font.BOLD);
// setSize(438,369);
contentPane = getContentPane();
contentPane.setLayout(new BorderLayout());
setForeground(ColorCache.get(0,0,0));
setBackground(ColorCache.get(192,192,192));
setFont(font);
MyTableModel tableModel;
MyJTable table;
m_model = tableModel = new MyTableModel(diagram);
m_table = table = new MyJTable(tableModel);
table.setFont(font);
FontMetrics fm = getFontMetrics(font);
table.setRowHeight(fm.getHeight() + 4);
table.setVisible(true);
scrollPane = new JScrollPane(table);
scrollPane.setVisible(true);
contentPane.add(scrollPane, BorderLayout.CENTER);
// --------------
// Use a FlowLayout to center the button and give it margins.
JPanel bottomPanel = new JPanel();
GridLayout gridLayout = new GridLayout(2,4);
gridLayout.setVgap(0);
bottomPanel.setLayout(gridLayout);
m_buttons = new JButton[m_button_titles.length];
for (i = 0; i < m_button_titles.length; ++i) {
m_buttons[i] = button = new JButton(m_button_titles[i]);
button.setFont(bold);
button.addActionListener(this);
bottomPanel.add(button);
}
contentPane.add(bottomPanel, BorderLayout.SOUTH);
pack();
setVisible(true);
table.removeEditor();
}
public RelationClass[] getSpanningClasses()
{
int cnt = m_model.getCntSpanning();
RelationClass[] ret = null;
if (cnt > 0) {
Vector classes = m_model.getClasses();
int i;
ret = new RelationClass[cnt];
for (i = 0; i < cnt; ++i) {
ret[i] = (RelationClass) classes.elementAt(i);
} }
return ret;
}
// ActionListener interface
public void actionPerformed(ActionEvent ev)
{
Object source = ev.getSource();
int state, i;
state = -1;
for (i = 0; i < m_button_titles.length; ++i) {
if (source == m_buttons[i]) {
state = i;
break;
} }
switch (state) {
case BUTTON_ADD:
m_model.add(m_table.getSelectedRows());
return;
case BUTTON_REMOVE:
m_model.remove(m_table.getSelectedRows());
return;
case BUTTON_UP:
m_model.up(m_table.getSelectedRows());
return;
case BUTTON_DOWN:
m_model.down(m_table.getSelectedRows());
return;
case BUTTON_CANCEL:
m_model.clearSpanningClasses();
case BUTTON_OK:
break;
case BUTTON_RESTART:
m_model.restart();
return;
case BUTTON_HELP:
JOptionPane.showMessageDialog(m_ls.getFrame(),
"Blue relation classes in the order shown will be used to form a new spanning\n" +
"tree. Earlier named classes will be preferred for this purpose over later\n" +
"named classes. Use [add] to add to the end of the set of selected spanning\n" +
"classes, [remove] to remove from this set, and [up] and [down] to reorder items\n" +
"in the list of spanning classes. Multiple items may be selected by each of these\n" +
"operations."
, "Help", JOptionPane.OK_OPTION);
default:
return;
}
setVisible(false);
return;
}
public static RelationClass[] getSpanningClasses(LandscapeEditorCore ls)
{
SpanningClasses spanningClasses = new SpanningClasses(ls.getFrame(), ls.getDiagram());
RelationClass[] classes = spanningClasses.getSpanningClasses();
spanningClasses.dispose();
return classes;
}
}
| 23.590476 | 94 | 0.639584 |
58823eca22cbf51511dd64699c0dbbd5a581e875 | 819 | package br.com.zup.casadocodigo.cadastrolivro.listLivro;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import br.com.zup.casadocodigo.cadastrolivro.LivroRepository;
@RestController
@RequestMapping("/livros")
public class ListaLivroController {
@Autowired
LivroRepository repository;
@GetMapping
public ResponseEntity<List<LivroResposta>>lista(){
List<LivroResposta> list = repository.findbuscarLivrosSQL();
return new ResponseEntity<List<LivroResposta>>(list, HttpStatus.OK);
}
}
| 28.241379 | 70 | 0.822955 |
a5b5c912398fb215aafbf72858246e7cbffe7fd9 | 6,051 | package protobuf.lang.resolve;
import static protobuf.lang.psi.PbPsiEnums.ReferenceKind;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiNamedElement;
import consulo.psi.PsiPackage;
import protobuf.lang.psi.api.PbFile;
import protobuf.lang.psi.api.block.PbBlock;
import protobuf.lang.psi.api.declaration.PbEnumDef;
import protobuf.lang.psi.api.declaration.PbExtendDef;
import protobuf.lang.psi.api.declaration.PbFieldDef;
import protobuf.lang.psi.api.declaration.PbGroupDef;
import protobuf.lang.psi.api.declaration.PbMessageDef;
import protobuf.lang.psi.api.reference.PbRef;
import protobuf.lang.psi.utils.PbPsiUtil;
/**
* @author Nikolay Matveev
* Date: Mar 29, 2010
*/
public abstract class PbResolveUtil
{
private final static Logger LOG = Logger.getInstance(PbResolveUtil.class.getName());
public static PsiElement resolveInScope(final PsiElement scope, final PbRef ref)
{
ReferenceKind kind = ref.getRefKind();
String refName = ref.getReferenceName();
if(refName == null)
{
return null;
}
if(scope instanceof PsiPackage)
{
switch(kind)
{
case FILE:
case PACKAGE:
{
}
case MESSAGE_OR_GROUP_FIELD:
{
assert false;
}
break;
case MESSAGE_OR_GROUP:
case MESSAGE_OR_ENUM_OR_GROUP:
case EXTEND_FIELD:
{
//get imported files by package name and invoke this function for this files
PbFile containingFile = (PbFile) ref.getContainingFile();
if(PbPsiUtil.isSamePackage(containingFile, (PsiPackage) scope))
{
PsiElement resolveResult = resolveInScope(containingFile, ref);
if(resolveResult != null)
{
return resolveResult;
}
}
PbFile[] importedFiles = PbPsiUtil.getImportedFilesByPackageName(containingFile, ((PsiPackage) scope).getQualifiedName());
for(PbFile importedFile : importedFiles)
{
PsiElement resolveResult = resolveInScope(importedFile, ref);
if(resolveResult != null)
{
return resolveResult;
}
}
}
break;
case MESSAGE_OR_PACKAGE_OR_GROUP:
{
PbFile containingFile = (PbFile) ref.getContainingFile();
//resolve in subpackages scope
//alg: find subpackage and then find it in subpackages
PsiPackage subPackage = resolveInSubPackagesScope((PsiPackage) scope, refName);
if(subPackage != null)
{
//f(subPackage, thisFile) -> boolean
//true if this subPackage in visible scope either false
if(PbPsiUtil.isVisibleSubPackage(subPackage, containingFile))
{
return subPackage;
}
}
//resolve in containing file
if(PbPsiUtil.isSamePackage(containingFile, (PsiPackage) scope))
{
PsiElement resolveResult = resolveInScope(containingFile, ref);
if(resolveResult != null)
{
return resolveResult;
}
}
//resolve in imported files scope
PbFile[] importedFiles = PbPsiUtil.getImportedFilesByPackageName(containingFile, ((PsiPackage) scope).getQualifiedName());
for(PbFile importedFile : importedFiles)
{
PsiElement resolveResult = resolveInScope(importedFile, ref);
if(resolveResult != null)
{
return resolveResult;
}
}
}
break;
}
}
else if(scope instanceof PbBlock || scope instanceof PbFile)
{
switch(kind)
{
case FILE:
case PACKAGE:
{
assert false;
}
case MESSAGE_OR_PACKAGE_OR_GROUP:
case MESSAGE_OR_GROUP:
{
PsiElement[] children = scope.getChildren();
for(PsiElement child : children)
{
if(child instanceof PbMessageDef || (!(scope instanceof PbFile) && child instanceof PbGroupDef))
{
if(refName.equals(((PsiNamedElement) child).getName()))
{
return child;
}
}
}
//LOG.info(refName + " : MESSAGE_OR_PACKAGE_OR_GROUP not resolved in " + (scope instanceof PbFile ? "PbFile" : ("PbBlock: " + ((PbBlock) scope).getParent().getText())));
}
break;
case MESSAGE_OR_ENUM_OR_GROUP:
{
PsiElement[] children = scope.getChildren();
for(PsiElement child : children)
{
if(child instanceof PbMessageDef || child instanceof PbEnumDef || child instanceof PbGroupDef)
{
if(refName.equals(((PsiNamedElement) child).getName()))
{
return child;
}
}
}
}
break;
case EXTEND_FIELD:
{
PsiElement[] children = scope.getChildren();
for(PsiElement child : children)
{
if(child instanceof PbExtendDef)
{
PbBlock extendBlock = ((PbExtendDef) child).getBlock();
if(extendBlock == null)
{
return null;
}
PsiElement[] extendChildren = extendBlock.getChildren();
for(PsiElement extendChild : extendChildren)
{
if(extendChild instanceof PbFieldDef && refName.equals(((PbFieldDef) extendChild).getName()))
{
return extendChild;
}
else if(extendChild instanceof PbGroupDef && refName.equals(((PbGroupDef) extendChild).getFieldName()))
{
return extendChild;
}
}
}
}
}
break;
case MESSAGE_OR_GROUP_FIELD:
{
if(scope instanceof PbFile)
{
assert false;
}
PsiElement[] children = scope.getChildren();
for(PsiElement child : children)
{
if(child instanceof PbFieldDef)
{
if(refName.equals(((PsiNamedElement) child).getName()))
{
return child;
}
}
else if(child instanceof PbGroupDef && refName.equals(((PbGroupDef) child).getFieldName()))
{
return child;
}
}
}
break;
}
}
return null;
}
public static PsiPackage resolveInSubPackagesScope(final PsiPackage parentPackage, String refName)
{
PsiPackage[] subPackages = parentPackage.getSubPackages();
for(PsiPackage subPackage : subPackages)
{
if(subPackage.getName().equals(refName))
{
return subPackage;
}
}
return null;
}
}
| 27.013393 | 174 | 0.65328 |
1ae1a8dfcef760271c1b824e3090c94d3267ba10 | 2,555 | package ru.job4j.task;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* Game class.
* @author agavrikov
* @since 28.08.2017
* @version 1
*/
public class Game {
/**
* Board.
*/
private final Board board;
/**
* Victory.
*/
private final Victory victory;
/**
* Constructor.
* @param board Board
* @param victory Victory
*/
public Game(Board board, Victory victory) {
this.board = board;
this.victory = victory;
}
/**
* method for start game.
*/
public void startGame() {
boolean gameEnd = false;
SimpleMark player1 = new SimpleMark('x');
SimpleMark player2 = new SimpleMark('o');
SimpleMark currentPlayer = player1;
try (BufferedReader bf = new BufferedReader(new InputStreamReader(System.in))) {
while (!gameEnd) {
System.out.println(String.format("Now move player wirh char %s", currentPlayer.view));
SimpleField[][] fields = this.board.fields();
for (int i = 0; i < fields.length; i++) {
for (int j = 0; j < fields[i].length; j++) {
System.out.print(fields[i][j].mark.view);
}
System.out.println();
}
System.out.println("Enter number of row:");
int coordR = Integer.parseInt(bf.readLine());
System.out.println("Enter number of column:");
int coordC = Integer.parseInt(bf.readLine());
if (board.hasMoves()) {
board.move(currentPlayer, coordR, coordC);
} else {
gameEnd = true;
}
if (victory.playerIsWin(board, coordR, coordC)) {
System.out.println(String.format("Player with char %s winner.", currentPlayer.view));
gameEnd = true;
} else {
if (currentPlayer == player1) {
currentPlayer = player2;
} else {
currentPlayer = player1;
}
}
}
} catch (IOException e) {
e.getStackTrace();
}
}
/**
* Point of start.
* @param args params
*/
public static void main(String[] args) {
Game game = new Game(new SmallBoard(), new SimpleVictory());
game.startGame();
}
}
| 29.034091 | 105 | 0.496673 |
859baf0ce5feb5ad26e77d97bfb1a4ddb7c153b0 | 7,643 | package org.kohsuke.github;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.util.Objects;
import java.util.logging.Logger;
import javax.annotation.Nonnull;
/**
* A GitHub API Rate Limit Checker called before each request.
*
* <p>
* GitHub allots a certain number of requests to each user or application per period of time. The number of requests
* remaining and the time when the number will be reset is returned in the response header and can also be requested
* using {@link GitHub#getRateLimit()}. The "requests per interval" is referred to as the "rate limit".
* </p>
* <p>
* Different parts of the GitHub API have separate rate limits, but most of REST API uses {@link RateLimitTarget#CORE}.
* Checking your rate limit using {@link GitHub#getRateLimit()} does not effect your rate limit. GitHub prefers that
* clients stop before exceeding their rate limit rather than stopping after they exceed it.
* </p>
* <p>
* This class provides the infrastructure for calling the appropriate {@link RateLimitChecker} before each request and
* retrying than call many times as needed. Each {@link RateLimitChecker} decides whether to wait and for how long. This
* allows for a wide range of {@link RateLimitChecker} implementations, including complex throttling strategies and
* polling.
* </p>
*/
class GitHubRateLimitChecker {
@Nonnull
private final RateLimitChecker core;
@Nonnull
private final RateLimitChecker search;
@Nonnull
private final RateLimitChecker graphql;
@Nonnull
private final RateLimitChecker integrationManifest;
private static final Logger LOGGER = Logger.getLogger(GitHubRateLimitChecker.class.getName());
GitHubRateLimitChecker() {
this(RateLimitChecker.NONE, RateLimitChecker.NONE, RateLimitChecker.NONE, RateLimitChecker.NONE);
}
GitHubRateLimitChecker(@Nonnull RateLimitChecker core,
@Nonnull RateLimitChecker search,
@Nonnull RateLimitChecker graphql,
@Nonnull RateLimitChecker integrationManifest) {
this.core = Objects.requireNonNull(core);
this.search = Objects.requireNonNull(search);
this.graphql = Objects.requireNonNull(graphql);
this.integrationManifest = Objects.requireNonNull(integrationManifest);
}
/**
* Constructs a new {@link GitHubRateLimitChecker} with a new checker for a particular target.
*
* Only one {@link RateLimitChecker} is allowed per target.
*
* @param checker
* the {@link RateLimitChecker} to apply.
* @param rateLimitTarget
* the {@link RateLimitTarget} for this checker. If {@link RateLimitTarget#NONE}, checker will be ignored
* and no change will be made.
* @return a new {@link GitHubRateLimitChecker}
*/
GitHubRateLimitChecker with(@Nonnull RateLimitChecker checker, @Nonnull RateLimitTarget rateLimitTarget) {
return new GitHubRateLimitChecker(rateLimitTarget == RateLimitTarget.CORE ? checker : core,
rateLimitTarget == RateLimitTarget.SEARCH ? checker : search,
rateLimitTarget == RateLimitTarget.GRAPHQL ? checker : graphql,
rateLimitTarget == RateLimitTarget.INTEGRATION_MANIFEST ? checker : integrationManifest);
}
/**
* Checks whether there is sufficient requests remaining within this client's rate limit quota to make the current
* request.
* <p>
* This method does not do the actual check. Instead it selects the appropriate {@link RateLimitChecker} and
* {@link GHRateLimit.Record} for the current request's {@link RateLimitTarget}. It then calls
* {@link RateLimitChecker#checkRateLimit(GHRateLimit.Record, long)}.
* </p>
* <p>
* It is up to {@link RateLimitChecker#checkRateLimit(GHRateLimit.Record, long)} to which decide if the rate limit
* has been exceeded. If it has, {@link RateLimitChecker#checkRateLimit(GHRateLimit.Record, long)} will sleep for as
* long is it chooses and then return {@code true}. If not, that method will return {@code false}.
* </p>
* <p>
* As long as {@link RateLimitChecker#checkRateLimit(GHRateLimit.Record, long)} returns {@code true}, this method
* will request updated rate limit information and call
* {@link RateLimitChecker#checkRateLimit(GHRateLimit.Record, long)} again. This looping allows different
* {@link RateLimitChecker} implementations to apply any number of strategies to controlling the speed at which
* requests are made.
* </p>
* <p>
* When the {@link RateLimitChecker} returns {@code false} this method will return and the request processing will
* continue.
* </p>
* <p>
* If the {@link RateLimitChecker} for this the current request's urlPath is {@link RateLimitChecker#NONE} the rate
* limit is not checked.
* </p>
*
* @param client
* the {@link GitHubClient} to check
* @param rateLimitTarget
* the {@link RateLimitTarget} to check against
* @throws IOException
* if there is an I/O error
*/
void checkRateLimit(GitHubClient client, @Nonnull RateLimitTarget rateLimitTarget) throws IOException {
RateLimitChecker guard = selectChecker(rateLimitTarget);
if (guard == RateLimitChecker.NONE) {
return;
}
// For the first rate limit, accept the current limit if a valid one is already present.
GHRateLimit rateLimit = client.rateLimit(rateLimitTarget);
GHRateLimit.Record rateLimitRecord = rateLimit.getRecord(rateLimitTarget);
long waitCount = 0;
try {
while (guard.checkRateLimit(rateLimitRecord, waitCount)) {
waitCount++;
// When rate limit is exceeded, sleep for one additional second beyond when the
// called {@link RateLimitChecker} sleeps.
// Reset time is only accurate to the second, so adding a one second buffer for safety is a good idea.
// This also keeps polling clients from querying too often.
Thread.sleep(1000);
// After the first wait, always request a new rate limit from the server.
rateLimit = client.getRateLimit(rateLimitTarget);
rateLimitRecord = rateLimit.getRecord(rateLimitTarget);
}
} catch (InterruptedException e) {
throw (IOException) new InterruptedIOException(e.getMessage()).initCause(e);
}
}
/**
* Gets the appropriate {@link RateLimitChecker} for a particular target.
*
* Analogous with {@link GHRateLimit#getRecord(RateLimitTarget)}.
*
* @param rateLimitTarget
* the rate limit to check
* @return the {@link RateLimitChecker} for a particular target
*/
@Nonnull
private RateLimitChecker selectChecker(@Nonnull RateLimitTarget rateLimitTarget) {
if (rateLimitTarget == RateLimitTarget.NONE) {
return RateLimitChecker.NONE;
} else if (rateLimitTarget == RateLimitTarget.CORE) {
return core;
} else if (rateLimitTarget == RateLimitTarget.SEARCH) {
return search;
} else if (rateLimitTarget == RateLimitTarget.GRAPHQL) {
return graphql;
} else if (rateLimitTarget == RateLimitTarget.INTEGRATION_MANIFEST) {
return integrationManifest;
} else {
throw new IllegalArgumentException("Unknown rate limit target: " + rateLimitTarget.toString());
}
}
}
| 44.958824 | 120 | 0.679445 |
13dc23ee81a73bb763e26b926a535b33f55e676e | 2,577 | package de.unigoe.informatik.swe.kcast.expression;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import de.unigoe.informatik.swe.krm.KnowledgeComponent;
/**
* Represents a sizeof operator that is applied to an expression<br /><br />
* Syntax: <code>sizeof</code> <em>expression</em> [<a href="cppreference.com">cppreference.com</a>]
* @author Ella Albrecht
*
*/
public class MySizeOfExpression extends MySizeOf{
/**
* Expression describing the object of which the size is determined
*/
private MyExpression expression;
/* The KCs defined for the size of expression element on different levels */
private static final Set<KnowledgeComponent> kcs0 = new HashSet<KnowledgeComponent>(Arrays.asList(KnowledgeComponent.EXPRESSION));
private static final Set<KnowledgeComponent> kcs1 = new HashSet<KnowledgeComponent>(Arrays.asList(KnowledgeComponent.SIZE_OF));
private static final Set<KnowledgeComponent> kcs2 = new HashSet<KnowledgeComponent>(Arrays.asList(KnowledgeComponent.SIZE_OF_EXPRESSION));
private static final Set<KnowledgeComponent> kcs3 = new HashSet<KnowledgeComponent>();
/**
* Creates a new size of expression operator
* @param expression Expression describing the object of which the size is determined
*/
public MySizeOfExpression(MyExpression expression) {
this.expression = expression;
}
/**
*
* @return Expression describing the object of which the size is determined
*/
public MyExpression getExpression() {
return expression;
}
/**
*
* @param expression Expression describing the object of which the size is determined
*/
public void setExpression(MyExpression expression) {
this.expression = expression;
}
@Override
public boolean isSizeOfType() {
return false;
}
@Override
public boolean isSizeOfExpression() {
return true;
}
@Override
public Set<KnowledgeComponent> getKCs(int level) {
Set<KnowledgeComponent> kcs = new HashSet<KnowledgeComponent>();
kcs.addAll(kcs0);
if (level > 0) {
kcs.addAll(kcs1);
if (level > 1) {
kcs.addAll(kcs2);
if (level > 2) {
kcs.addAll(kcs3);
}
}
}
kcs.addAll(expression.getKCs(level));
return kcs;
}
@Override
public boolean equals(Object o) {
if (o instanceof MySizeOfExpression) {
MySizeOfExpression expr = (MySizeOfExpression) o;
return (expression.equals(expr.getExpression()));
}
return false;
}
@Override
public String toString() {
String text = "SIZE OF EXPRESSION\n";
text += "Expression: " + expression.toString() + "\n";
return text;
}
}
| 26.295918 | 139 | 0.727202 |
0c4acf36952f50f558a844654365f7690d65aa54 | 2,602 | /*
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.forscience.whistlepunk;
import android.util.Log;
import com.google.android.apps.forscience.javalib.MaybeConsumer;
import io.reactivex.CompletableObserver;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
/**
* MaybeConsumer that logs an stacktrace on failure, which is sufficient for many situations
* in which failure is not expected.
*
* @param <T>
*/
public abstract class LoggingConsumer<T> implements MaybeConsumer<T> {
public static <T> LoggingConsumer<T> expectSuccess(String tag, String operation) {
return new LoggingConsumer<T>(tag, operation) {
@Override
public void success(T value) {
// do nothing
};
};
}
private final String mTag;
private final String mOperation;
public LoggingConsumer(String tag, String operation) {
mTag = tag;
mOperation = operation;
}
@Override
public void fail(Exception e) {
complain(e, mTag, mOperation);
}
public static void complain(Throwable e, String tag, String operation) {
// TODO: allow non-ERROR log levels
if (Log.isLoggable(tag, Log.ERROR)) {
Log.e(tag, "Failed: " + operation, e);
}
}
/**
* Returns a Consumer that logs a failure, if any, the way that LoggingConsumer does.
*/
public static Consumer<? super Throwable> complain(String tag, String operation) {
return e -> complain(e, tag, operation);
}
public static CompletableObserver observe(String tag, String operation) {
return new CompletableObserver() {
@Override
public void onSubscribe(Disposable d) {
}
@Override
public void onComplete() {
}
@Override
public void onError(Throwable e) {
complain(e, tag, operation);
}
};
}
}
| 28.911111 | 92 | 0.646042 |
962b6fdcee1e94afc328a988e8f8e15cb2830a67 | 680 | package me.yamakaja.rpgpets.api.event;
import me.yamakaja.rpgpets.api.entity.PetDescriptor;
import org.bukkit.event.Event;
import org.bukkit.event.HandlerList;
/**
* Created by Yamakaja on 12.06.17.
*/
public class PetLevelUpEvent extends Event {
private static final HandlerList handlerList = new HandlerList();
private PetDescriptor pet;
public PetLevelUpEvent(PetDescriptor pet) {
this.pet = pet;
}
public static HandlerList getHandlerList() {
return handlerList;
}
@Override
public HandlerList getHandlers() {
return handlerList;
}
public PetDescriptor getPetDescriptor() {
return pet;
}
}
| 20.606061 | 69 | 0.692647 |
3cc873e7497fa483ce27a9b0fd9c0ba540b027ae | 2,285 | package com.bhaptics.bhapticsandroid.adapters;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import com.bhaptics.bhapticsandroid.App;
import com.bhaptics.bhapticsandroid.R;
import com.bhaptics.bhapticsandroid.models.TactFile;
import com.bhaptics.bhapticsandroid.utils.FileUtils;
import com.bhaptics.bhapticsmanger.SdkRequestHandler;
import java.util.List;
public class TactFileListAdapter extends BaseAdapter {
private LayoutInflater inflater;
private int layout;
private List<TactFile> files;
private SdkRequestHandler sdkRequestHandler;
public TactFileListAdapter(Activity context, String tacFileFolder) {
this.inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.layout = R.layout.list_item_tact_file;
files = FileUtils.listFile(context, tacFileFolder);
sdkRequestHandler = App.getHandler(context);
for (TactFile file : files) {
sdkRequestHandler.register(file.getFileName(), file.getContent());
}
}
@Override
public int getCount() {
return files.size();
}
@Override
public Object getItem(int position) {
return files.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
final TactFile tactFile = files.get(position);
if(convertView==null){
convertView=inflater.inflate(layout,parent,false);
Button playButton = convertView.findViewById(R.id.play_button);
playButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sdkRequestHandler.submitRegistered(tactFile.getFileName(), tactFile.getFileName(), 1f, 1f, 0, 0);
}
});
}
TextView deviceName = convertView.findViewById(R.id.file_name);
deviceName.setText(tactFile.getFileName());
return convertView;
}
}
| 30.466667 | 117 | 0.696718 |
95e98cd4e8c4851a32ad308c1f6d8c16bf757e60 | 197 | package DungeonCrawler.GameObject;
import DungeonCrawler.GameData;
//Game objects that require a regular update.
public interface Update {
void update(GameData gamedata, double deltaTime);
}
| 21.888889 | 53 | 0.796954 |
9a19fe27a4da4c1e8e0709ba4986056efbbdd9be | 269 | package io.github.adobe.sign.core.workflow;
public class SignWorkflowException extends Exception {
public SignWorkflowException(String msg) {
super(msg);
}
public SignWorkflowException(String msg, Throwable t) {
super(msg, t);
}
}
| 22.416667 | 59 | 0.680297 |
1a73aa18f1f703f27469c7715c25bcf2a1f47741 | 32,459 | /**
* PercolatorSQTDataUploadService.java
* @author Vagisha Sharma
* Dec 11, 2008
* @version 1.0
*/
package org.yeastrc.ms.service.sqtfile;
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.log4j.Logger;
import org.yeastrc.ms.dao.DAOFactory;
import org.yeastrc.ms.dao.analysis.MsRunSearchAnalysisDAO;
import org.yeastrc.ms.dao.analysis.MsSearchAnalysisDAO;
import org.yeastrc.ms.dao.analysis.percolator.PercolatorParamsDAO;
import org.yeastrc.ms.dao.analysis.percolator.PercolatorResultDAO;
import org.yeastrc.ms.dao.run.MsScanDAO;
import org.yeastrc.ms.dao.search.MsRunSearchDAO;
import org.yeastrc.ms.dao.search.MsSearchDAO;
import org.yeastrc.ms.dao.search.MsSearchResultDAO;
import org.yeastrc.ms.domain.analysis.impl.RunSearchAnalysisBean;
import org.yeastrc.ms.domain.analysis.impl.SearchAnalysisBean;
import org.yeastrc.ms.domain.analysis.percolator.PercolatorResultDataWId;
import org.yeastrc.ms.domain.analysis.percolator.PercolatorResultIn;
import org.yeastrc.ms.domain.analysis.percolator.PercolatorSearchScan;
import org.yeastrc.ms.domain.analysis.percolator.impl.PercolatorParamBean;
import org.yeastrc.ms.domain.analysis.percolator.impl.PercolatorResultDataBean;
import org.yeastrc.ms.domain.search.MsResidueModificationIn;
import org.yeastrc.ms.domain.search.MsRunSearch;
import org.yeastrc.ms.domain.search.MsSearch;
import org.yeastrc.ms.domain.search.MsSearchResult;
import org.yeastrc.ms.domain.search.MsTerminalModificationIn;
import org.yeastrc.ms.domain.search.Program;
import org.yeastrc.ms.domain.search.SearchFileFormat;
import org.yeastrc.ms.domain.search.sqtfile.SQTHeaderItem;
import org.yeastrc.ms.domain.search.sqtfile.SQTRunSearchIn;
import org.yeastrc.ms.parser.DataProviderException;
import org.yeastrc.ms.parser.sqtFile.SQTFileReader;
import org.yeastrc.ms.parser.sqtFile.SQTHeader;
import org.yeastrc.ms.parser.sqtFile.percolator.PercolatorSQTFileReader;
import org.yeastrc.ms.service.AnalysisDataUploadService;
import org.yeastrc.ms.service.UploadException;
import org.yeastrc.ms.service.UploadException.ERROR_CODE;
import org.yeastrc.ms.service.percolator.stats.PercolatorFilteredPsmStatsSaver;
import org.yeastrc.ms.service.percolator.stats.PercolatorFilteredSpectraStatsSaver;
/**
*
*/
public class PercolatorSQTDataUploadService implements AnalysisDataUploadService {
private static final Logger log = Logger.getLogger(PercolatorSQTDataUploadService.class);
private final MsSearchResultDAO resultDao;
private final MsSearchAnalysisDAO analysisDao;
private final MsRunSearchDAO runSearchDao;
private final PercolatorParamsDAO paramDao;
private final MsSearchDAO searchDao;
private final MsRunSearchAnalysisDAO runSearchAnalysisDao;
private final PercolatorResultDAO percResultDao;
private static final int BUF_SIZE = 1000;
private List<? extends MsResidueModificationIn> dynaResidueMods;
private List<? extends MsTerminalModificationIn> dynaTermMods;
// these are the things we will cache and do bulk-inserts
private List<PercolatorResultDataWId> percolatorResultDataList; // percolator scores
private Set<Integer> uploadedResultIds;
private int numAnalysisUploaded = 0;
// This is information we will get from the SQT files and then update the entries in the msPostSearchAnalysis
private String programVersion = "uninit";
private Map<String, String> params;
private int analysisId = 0;
private String comments;
private int numResultsNotFound = 0;
private int searchId;
private String dataDirectory;
private StringBuilder preUploadCheckMsg;
private boolean preUploadCheckDone = false;
private List<String> filenames;
private List<String> searchDataFileNames;
private Program searchProgram;
public PercolatorSQTDataUploadService() {
this.percolatorResultDataList = new ArrayList<PercolatorResultDataWId>(BUF_SIZE);
this.dynaResidueMods = new ArrayList<MsResidueModificationIn>();
this.dynaTermMods = new ArrayList<MsTerminalModificationIn>();
this.params = new HashMap<String, String>();
uploadedResultIds = new HashSet<Integer>();
filenames = new ArrayList<String>();
DAOFactory daoFactory = DAOFactory.instance();
this.analysisDao = daoFactory.getMsSearchAnalysisDAO();
this.runSearchDao = daoFactory.getMsRunSearchDAO();
this.paramDao = daoFactory.getPercoltorParamsDAO();
this.searchDao = daoFactory.getMsSearchDAO();
this.runSearchAnalysisDao = daoFactory.getMsRunSearchAnalysisDAO();
this.resultDao = daoFactory.getMsSearchResultDAO();
this.percResultDao = daoFactory.getPercolatorResultDAO();
}
void reset() {
//analysisId = 0;
numAnalysisUploaded = 0;
resetCaches();
programVersion = "uninit";
dynaResidueMods.clear();
dynaTermMods.clear();
params.clear();
}
// called before uploading each sqt file and in the reset() method.
void resetCaches() {
percolatorResultDataList.clear();
numResultsNotFound = 0;
uploadedResultIds.clear();
}
private void updateProgramVersion(int analysisId, String programVersion) {
try {
analysisDao.updateAnalysisProgramVersion(analysisId, programVersion);
}
catch(RuntimeException e) {
log.warn("Error updating program version for analysisID: "+analysisId, e);
}
}
@Override
public void upload() throws UploadException {
reset();// reset all caches etc.
if(!preUploadCheckDone) {
if(!preUploadCheckPassed()) {
UploadException ex = new UploadException(ERROR_CODE.PREUPLOAD_CHECK_FALIED);
ex.appendErrorMessage(this.getPreUploadCheckMsg());
ex.appendErrorMessage("\n\t!!!PERCOLATOR ANALYSIS WILL NOT BE UPLOADED\n");
throw ex;
}
}
Map<String,Integer> runSearchIdMap;
try {
runSearchIdMap = createRunSearchIdMap();
}
catch(UploadException e) {
e.appendErrorMessage("\n\t!!!PERCOLATOR ANALYSIS WILL NOT BE UPLOADED\n");
throw e;
}
// create a new entry in the msSearchAnalysis table
try {
if(analysisId == 0)
analysisId = saveTopLevelAnalysis();
}
catch (UploadException e) {
e.appendErrorMessage("\n\t!!!PERCOLATOR ANALYSIS WILL NOT BE UPLOADED\n");
throw e;
}
// get the modifications used for this search. Will be used for parsing the peptide sequence
getSearchModifications(searchId);
// now upload the individual sqt files
for (String file: filenames) {
String filePath = dataDirectory+File.separator+file;
// if the file does not exist skip over to the next
if (!(new File(filePath).exists()))
continue;
Integer runSearchId = runSearchIdMap.get(file);
if (runSearchId == null) {
UploadException ex = new UploadException(ERROR_CODE.NO_RUNSEARCHID_FOR_ANALYSIS_FILE);
ex.appendErrorMessage("\n\tDELETING PERCOLATOR ANALYSIS...ID: "+analysisId+"\n");
deleteAnalysis(analysisId);
numAnalysisUploaded = 0;
throw ex;
}
resetCaches();
try {
uploadSqtFile(filePath, runSearchId, searchProgram);
numAnalysisUploaded++;
log.info("Number of results not found: "+numResultsNotFound);
}
catch (UploadException ex) {
ex.appendErrorMessage("\n\tDELETING PERCOLATOR ANALYSIS...ID: "+analysisId+"\n");
deleteAnalysis(analysisId);
numAnalysisUploaded = 0;
throw ex;
}
}
// if no sqt files were uploaded delete the top level search analysis
if (numAnalysisUploaded == 0) {
UploadException ex = new UploadException(ERROR_CODE.NO_PERC_ANALYSIS_UPLOADED);
ex.appendErrorMessage("\n\tDELETING PERCOLATOR ANALYSIS...ID: "+analysisId+"\n");
deleteAnalysis(analysisId);
numAnalysisUploaded = 0;
throw ex;
}
// Update the "analysisProgramVersion" in the msSearchAnalysis table
if (this.programVersion != null && this.programVersion != "uninit") {
updateProgramVersion(analysisId, programVersion);
}
// Add the Percolator parameters
try {
addPercolatorParams(params, analysisId);
}
catch(UploadException e) {
e.appendErrorMessage("\n\tDELETING PERCOLATOR ANALYSIS...ID: "+analysisId+"\n");
log.error(e.getMessage(), e);
deleteAnalysis(analysisId);
numAnalysisUploaded = 0;
throw e;
}
// Finally, save the filtered results stats
try {
PercolatorFilteredPsmStatsSaver psmStatsSaver = PercolatorFilteredPsmStatsSaver.getInstance();
psmStatsSaver.save(analysisId, 0.01);
PercolatorFilteredSpectraStatsSaver spectraStatsSaver = PercolatorFilteredSpectraStatsSaver.getInstance();
spectraStatsSaver.save(analysisId, 0.01);
}
catch(Exception e) {
log.error("Error saving filtered stats for analysisID: "+analysisId, e);
}
}
public List<Integer> getUploadedAnalysisIds() {
List<Integer> analysisIds = new ArrayList<Integer>();
analysisIds.add(analysisId);
return analysisIds;
}
public void setAnalysisId(int analysisId) {
this.analysisId = analysisId;
}
public void setComments(String comments) {
this.comments = comments;
}
private Map<String, Integer> createRunSearchIdMap() throws UploadException {
Map<String, Integer> runSearchIdMap = new HashMap<String, Integer>(filenames.size()*2);
for(String file: filenames) {
String filenoext = removeFileExtension(file);
int runSearchId = runSearchDao.loadIdForSearchAndFileName(searchId, filenoext);
if(runSearchId == 0) {
UploadException ex = new UploadException(ERROR_CODE.NO_RUNSEARCHID_FOR_ANALYSIS_FILE);
ex.appendErrorMessage("File: "+filenoext);
ex.appendErrorMessage("; SearchID: "+searchId);
throw ex;
}
runSearchIdMap.put(file, runSearchId);
}
return runSearchIdMap;
}
private void addPercolatorParams(Map<String, String> params, int analysisId) throws UploadException {
for (String name: params.keySet()) {
String val = params.get(name);
PercolatorParamBean param = new PercolatorParamBean();
param.setParamName(name);
param.setParamValue(val);
try {
paramDao.saveParam(param, analysisId);
}
catch(RuntimeException e) {
UploadException ex = new UploadException(ERROR_CODE.RUNTIME_SQT_ERROR, e);
ex.appendErrorMessage("Exception saving Percolator param (name: "+name+", value: "+val+")");
throw ex;
}
}
}
private void getSearchModifications(int searchId) {
MsSearch search = searchDao.loadSearch(searchId);
this.dynaResidueMods = search.getDynamicResidueMods();
this.dynaTermMods = search.getDynamicTerminalMods();
}
private int saveTopLevelAnalysis() throws UploadException {
SearchAnalysisBean analysis = new SearchAnalysisBean();
// analysis.setSearchId(searchId);
analysis.setAnalysisProgram(Program.PERCOLATOR);
analysis.setComments(comments);
try {
return analysisDao.save(analysis);
}
catch(RuntimeException e) {
UploadException ex = new UploadException(ERROR_CODE.RUNTIME_SQT_ERROR, e);
ex.setErrorMessage(e.getMessage());
throw ex;
}
}
private void uploadSqtFile(String filePath, int runSearchId, Program searchProgram) throws UploadException {
log.info("BEGIN PERCOLATOR SQT FILE UPLOAD: "+(new File(filePath).getName())+"; RUN_SEARCH_ID: "+runSearchId);
long startTime = System.currentTimeMillis();
PercolatorSQTFileReader provider = new PercolatorSQTFileReader();
try {
provider.open(filePath, searchProgram);
provider.setDynamicResidueMods(this.dynaResidueMods);
provider.setDynamicTerminalMods(this.dynaTermMods);
}
catch (DataProviderException e) {
provider.close();
UploadException ex = new UploadException(ERROR_CODE.READ_ERROR_SQT, e);
ex.setFile(filePath);
ex.setErrorMessage(e.getMessage()+"\n\t!!!PERCOLATOR SQT FILE WILL NOT BE UPLOADED!!!");
throw ex;
}
try {
uploadPercolatorSqtFile(provider, runSearchId);
}
catch (UploadException ex) {
ex.setFile(filePath);
ex.appendErrorMessage("\n\t!!!PERCOLATOR SQT FILE WILL NOT BE UPLOADED!!!");
throw ex;
}
catch (RuntimeException e) { // most likely due to SQL exception
UploadException ex = new UploadException(ERROR_CODE.RUNTIME_SQT_ERROR, e);
ex.setFile(filePath);
ex.setErrorMessage(e.getMessage()+"\n\t!!!PERCOLATOR SQT FILE WILL NOT BE UPLOADED!!!");
throw ex;
}
finally {provider.close();}
long endTime = System.currentTimeMillis();
log.info("END PERCOLATOR SQT FILE UPLOAD: "+provider.getFileName()+"; RUN_SEARCH_ID: "+runSearchId+ " in "+(endTime - startTime)/(1000L)+"seconds\n");
}
// parse and upload a sqt file
private void uploadPercolatorSqtFile(PercolatorSQTFileReader provider, int runSearchId) throws UploadException {
int runSearchAnalysisId = 0;
try {
runSearchAnalysisId = uploadRunSearchAnalysis(provider, analysisId, runSearchId);
log.info("Extracted info from Percolator sqt file header: "+provider.getFileName());
log.info("Uploaded top-level info for sqt file. runSearchAnalysisId: "+runSearchAnalysisId);
}
catch(DataProviderException e) {
UploadException ex = new UploadException(ERROR_CODE.INVALID_SQT_HEADER, e);
ex.setErrorMessage(e.getMessage());
throw ex;
}
// get the runID. Will be needed later to get the scan number
int runId = getRunIdForRunSearch(runSearchId);
if(runId == 0) {
UploadException ex = new UploadException(ERROR_CODE.NO_RUNID_FOR_SQT);
ex.setErrorMessage("No runID found for runSearchID: "+runSearchId);
throw ex;
}
// upload the search results for each scan + charge combination
int numResults = 0;
while (provider.hasNextSearchScan()) {
PercolatorSearchScan scan = null;
try {
scan = provider.getNextSearchScan();
}
catch (DataProviderException e) {
UploadException ex = new UploadException(ERROR_CODE.INVALID_SQT_SCAN);
ex.setErrorMessage(e.getMessage());
throw ex;
}
// Data from MacCoss Lab can have duplicate results for the same scan
// and charge. When uploading the sequest results the "observed mass" for
// a search scan is matched with the Z lines of the MS2 file. The scan
// is uploaded only if the charge and mass match a Z line for the scan in the MS2 file.
// Before uploading the Percolator results for this search scan make
// sure that the observed mass is the same as the observed mass
// for the uploaded sequest search scan. If not, ignore this scan
int scanId = getScanId(runId, scan.getScanNumber());
int numMatches = resultDao.numResultsForRunSearchScanChargeMass(runSearchId, scanId, scan.getCharge(), scan.getObservedMass());
if(numMatches == 0) {
String msg = "No matching results found with runSearchId: "+runSearchId+
"; scanId: "+scanId+"; charge: "+scan.getCharge()+
"; mass: "+scan.getObservedMass();
// log.error(msg);
UploadException ex = new UploadException(ERROR_CODE.NO_MATCHING_SEARCH_SCAN);
ex.setErrorMessage(msg);
throw ex;
}
else {
// save all the search results for this scan
for (PercolatorResultIn result: scan.getScanResults()) {
boolean uploaded = uploadSearchResult(result, runSearchAnalysisId, runSearchId, scanId);
if(uploaded) numResults++;
}
}
}
flush(); // save any cached data
log.info("Uploaded Percolator SQT file: "+provider.getFileName()+", with "+numResults+" results.");
}
private int getRunIdForRunSearch(int runSearchId) {
MsRunSearch rs = runSearchDao.loadRunSearch(runSearchId);
if(rs != null)
return rs.getRunId();
else
return 0;
}
// EXTRACT INFO FROM PERCOLATOR SQT HEADER AND save an entry in the MsRunSearchAnalysis table
private final int uploadRunSearchAnalysis(PercolatorSQTFileReader provider, int analysisId, int runSearchId)
throws DataProviderException {
SQTRunSearchIn search = provider.getSearchHeader();
if (search instanceof SQTHeader) {
SQTHeader header = (SQTHeader)search;
// SEARCH PROGRAM VERSION IN THE SQT FILE
// this is the first time we are assigning a value to program version
if ("uninit".equals(programVersion))
this.programVersion = header.getSearchEngineVersion();
// make sure the SQTGeneratorVersion value is same in all sqt headers
if (programVersion == null) {
if (header.getSearchEngineVersion() != null)
throw new DataProviderException("Value of Percolator version is not the same in all SQT files.");
}
else if (!programVersion.equals(header.getSearchEngineVersion())) {
throw new DataProviderException("Value of Percolator version is not the same in all SQT files.");
}
Map<String, String> sqtParams = PercolatorSQTFileReader.getPercolatorParams(header);
// get the Percolator parameters
for(String param: sqtParams.keySet()) {
String pval = params.get(param);
if(pval == null)
params.put(param, sqtParams.get(param));
else {
if(!pval.equals(sqtParams.get(param))) {
throw new DataProviderException("Parameter \""+param+"\" values do not match");
}
}
}
}
// save the run search analysis and return the database id
RunSearchAnalysisBean rsa = new RunSearchAnalysisBean();
rsa.setAnalysisFileFormat(SearchFileFormat.SQT_PERC);
rsa.setAnalysisId(analysisId);
rsa.setRunSearchId(runSearchId);
return runSearchAnalysisDao.save(rsa);
}
private boolean uploadSearchResult(PercolatorResultIn result, int rsAnalysisId, int runSearchId, int scanId) throws UploadException {
MsSearchResult searchResult = null;
try {
List<MsSearchResult> matchingResults = resultDao.loadResultForSearchScanChargePeptide(runSearchId, scanId,
result.getCharge(),
result.getResultPeptide().getPeptideSequence());
if(matchingResults.size() == 1)
searchResult = matchingResults.get(0);
else if(matchingResults.size() > 1) { // this can happen if
// 1. scan searched with same charge but different M+H (due to Bullseye) results in same peptide match
// 2. we have the same sequence with different mods (TODO will this ever happen??)
// check for 1. first
int numMatching = 0;
for(MsSearchResult res: matchingResults) {
// log.info("My mass: "+result.getObservedMass()+". Looking at: "+res.getObservedMass());
if(result.getObservedMass().doubleValue() == res.getObservedMass().doubleValue()) {
searchResult = res;
numMatching++;
}
}
// If we still have multiple matches check for 2.
if(numMatching > 1) {
numMatching = 0;
String myPeptide = result.getResultPeptide().getModifiedPeptidePS();
for(MsSearchResult res: matchingResults) {
// If this does not have the same observed mass as our result skip it
if(result.getObservedMass().doubleValue() != res.getObservedMass().doubleValue())
continue;
if(myPeptide.equals(res.getResultPeptide().getModifiedPeptidePS())) {
searchResult = res;
numMatching++;
}
}
}
// If we still don't have a definite match
if(numMatching > 1) {
UploadException ex = new UploadException(ERROR_CODE.MULTI_MATCHING_SEARCH_RESULT);
ex.setErrorMessage("Multiple matching search results were found for runSearchId: "+runSearchId+
" scanId: "+scanId+"; charge: "+result.getCharge()+"; mass: "+result.getObservedMass()+
"; peptide: "+result.getResultPeptide().getPeptideSequence()+
"; modified peptide: "+result.getResultPeptide().getModifiedPeptidePS());
throw ex;
}
}
}
catch(RuntimeException e) {
UploadException ex = new UploadException(ERROR_CODE.RUNTIME_SQT_ERROR, e);
ex.setErrorMessage(e.getMessage());
throw ex;
}
if(searchResult == null) {
numResultsNotFound++;
UploadException ex = new UploadException(ERROR_CODE.NO_MATCHING_SEARCH_RESULT);
ex.setErrorMessage("No matching search result was found for runSearchId: "+runSearchId+
" scanId: "+scanId+"; charge: "+result.getCharge()+"; mass: "+result.getObservedMass()+
"; peptide: "+result.getResultPeptide().getPeptideSequence()+
"; modified peptide: "+result.getResultPeptide().getModifiedPeptidePS());
throw ex;
//log.warn(ex.getErrorMessage());
//return false;
}
// upload the Percolator specific information for this result.
return uploadPercolatorResultData(result, rsAnalysisId, searchResult.getId());
}
private boolean uploadPercolatorResultData(PercolatorResultIn resultData, int rsAnalysisId, int searchResultId) {
// upload the Percolator specific result information if the cache has enough entries
if (percolatorResultDataList.size() >= BUF_SIZE) {
uploadPercolatorResultBuffer();
}
// TODO THIS IS TEMP TILL I SORT OUT THE DUPLICATE RESULTS IN PERCOLATOR SQT FILES
if(uploadedResultIds.contains(searchResultId))
return false;
uploadedResultIds.add(searchResultId);
// add the Percolator specific information for this result to the cache
PercolatorResultDataBean res = new PercolatorResultDataBean();
res.setRunSearchAnalysisId(rsAnalysisId);
res.setSearchResultId(searchResultId);
res.setPredictedRetentionTime(resultData.getPredictedRetentionTime());
res.setDiscriminantScore(resultData.getDiscriminantScore());
res.setPosteriorErrorProbability(resultData.getPosteriorErrorProbability());
res.setQvalue(resultData.getQvalue());
percolatorResultDataList.add(res);
return true;
}
private void uploadPercolatorResultBuffer() {
percResultDao.saveAllPercolatorResultData(percolatorResultDataList);
percolatorResultDataList.clear();
}
private void flush() {
if (percolatorResultDataList.size() > 0) {
uploadPercolatorResultBuffer();
}
}
static int getScanId(int runId, int scanNumber) throws UploadException {
MsScanDAO scanDao = DAOFactory.instance().getMsScanDAO();
int scanId = scanDao.loadScanIdForScanNumRun(scanNumber, runId);
if (scanId == 0) {
UploadException ex = new UploadException(ERROR_CODE.NO_SCANID_FOR_SCAN);
ex.setErrorMessage("No scanId found for scan number: "+scanNumber+" and runId: "+runId);
throw ex;
}
return scanId;
}
public void deleteAnalysis(int analysisId) {
if (analysisId == 0)
return;
log.info("Deleting analysis ID: "+analysisId);
analysisDao.delete(analysisId);
}
@Override
public void setSearchId(int searchId) {
this.searchId = searchId;
}
@Override
public void setDirectory(String directory) {
this.dataDirectory = directory;
}
@Override
public void setRemoteDirectory(String remoteDirectory) {
throw new UnsupportedOperationException();
}
@Override
public void setRemoteServer(String remoteServer) {
throw new UnsupportedOperationException();
}
@Override
public String getPreUploadCheckMsg() {
return preUploadCheckMsg.toString();
}
private void appendToMsg(String msg) {
this.preUploadCheckMsg.append(msg+"\n");
}
@Override
public boolean preUploadCheckPassed() {
preUploadCheckMsg = new StringBuilder();
// checks for
// 1. valid data directory
File dir = new File(dataDirectory);
if(!dir.exists()) {
appendToMsg("Data directory does not exist: "+dataDirectory);
return false;
}
if(!dir.isDirectory()) {
appendToMsg(dataDirectory+" is not a directory");
return false;
}
// 2. valid and supported analysis data format
// 3. consistent data format
File[] files = dir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
String name_uc = name.toLowerCase();
return name_uc.endsWith(".sqt");
}});
for (int i = 0; i < files.length; i++) {
filenames.add(files[i].getName());
}
// make sure all files are of the same type
for (String file: filenames) {
String sqtFile = dataDirectory+File.separator+file;
SearchFileFormat myType = SQTFileReader.getSearchFileType(sqtFile);
if (myType == null) {
appendToMsg("Cannot determine SQT type for file: "+file);
return false;
}
if(myType != getAnalysisFileFormat()) {
appendToMsg("Unsupported SQT type for uploader. Expected: "+getAnalysisFileFormat()+"; Found: "+myType+". File: "+file);
return false;
}
}
// 4. If we know the search data file names that will be uploaded match them with up with the analysis SQT files
// and make sure there is a raw data file for each SQT file
if(searchDataFileNames != null) {
for(String file:filenames) {
// String filenoext = removeFileExtension(file);
if(!searchDataFileNames.contains(file)) {
appendToMsg("No corresponding search data file found for: "+file);
return false;
}
}
}
preUploadCheckDone = true;
return true;
}
private String removeFileExtension(String file) {
int idx = file.lastIndexOf(".sqt");
if(idx == -1)
idx = file.lastIndexOf(".SQT");
if(idx != -1)
return file.substring(0, idx);
else
return file;
}
@Override
public String getUploadSummary() {
return "\tAnalysis file format: "+getAnalysisFileFormat()+
"\n\t#Analysis files in Directory: "+filenames.size()+"; #Uploaded: "+numAnalysisUploaded;
}
@Override
public SearchFileFormat getAnalysisFileFormat() {
return SearchFileFormat.SQT_PERC;
}
@Override
public void setSearchProgram(Program searchProgram) {
this.searchProgram = searchProgram;
}
@Override
public void setSearchDataFileNames(List<String> searchDataFileNames) {
this.searchDataFileNames = searchDataFileNames;
}
public int getMaxPsmRank() {
for (String file: filenames) {
String filePath = dataDirectory+File.separator+file;
// if the file does not exist skip over to the next
if (!(new File(filePath).exists()))
continue;
PercolatorSQTFileReader provider = new PercolatorSQTFileReader();
try {
provider.open(filePath, searchProgram);
}
catch (DataProviderException e) {
provider.close();
log.error("Error opening PercolatorSQTFileReader", e);
return Integer.MAX_VALUE;
}
try {
SQTRunSearchIn search = provider.getSearchHeader();
if (search instanceof SQTHeader) {
SQTHeader header = (SQTHeader)search;
for(SQTHeaderItem h: header.getHeaders()) {
if(h.getName().equalsIgnoreCase("percolator")) {
String cmdline = h.getValue();
String[] tokens = cmdline.split("\\s+");
for(int i = 0; i < tokens.length; i++) {
String val = tokens[i];
if(val.startsWith("-m")) {
int rank = Integer.parseInt(tokens[++i]);
return rank;
}
}
}
}
// If we are here it means we did not find the -m flag in the percolator command-line
// This means percolator will only use the top hit for each scan+charge combination
return 1;
}
}
catch (DataProviderException e) {
log.error("Error reading percolator SQT file", e);
return Integer.MAX_VALUE;
}
finally {provider.close();}
}
log.warn("Could not read percolator command-line to determine value of -m argument. "+
"ALL sequest results will be uploaded.");
return Integer.MAX_VALUE;
}
}
| 40.523096 | 158 | 0.606118 |
626901c31ebca5713c1d7d31479203f21fb98aa1 | 116 | /**
* 哲学家就餐问题
*/
package com.zc.concurrency_program_design.concurrency_program_design.dining_philosophers_problem; | 29 | 97 | 0.844828 |
72a87a1fa6cb7727158c5d6ea9fa67a247d8fc7d | 4,444 | /*
* Licensed to STRATIO (C) under one or more contributor license agreements.
* See the NOTICE file distributed with this work for additional information
* regarding copyright ownership. The STRATIO (C) licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.stratio.cassandra.lucene.search.condition;
import com.spatial4j.core.context.jts.JtsSpatialContext;
import com.spatial4j.core.shape.jts.JtsGeometry;
import com.stratio.cassandra.lucene.IndexException;
import com.stratio.cassandra.lucene.common.GeoTransformation;
import com.stratio.cassandra.lucene.schema.mapping.GeoShapeMapper;
import com.stratio.cassandra.lucene.util.GeospatialUtilsJTS;
import com.stratio.cassandra.lucene.util.JsonSerializer;
import org.junit.Test;
import java.io.IOException;
import static com.stratio.cassandra.lucene.common.GeoTransformation.Difference;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNotNull;
/**
* Unit tests for {@link GeoTransformation.Difference}.
*
* @author Andres de la Pena {@literal <adelapena@stratio.com>}
*/
public class GeoTransformationDifferenceTest extends AbstractConditionTest {
private static final JtsSpatialContext CONTEXT = GeoShapeMapper.SPATIAL_CONTEXT;
private static JtsGeometry geometry(String string) {
return GeospatialUtilsJTS.geometryFromWKT(CONTEXT, string);
}
@Test
public void testDifferenceTransformation() {
String shape1 = "POLYGON((-30 30, -30 0, 30 0, 30 30, -30 30))";
String shape2 = "POLYGON((-20 20, -20 0, 20 0, 20 20, -20 20))";
String difference = "POLYGON ((-20 0, -30 0, -30 30, 30 30, 30 0, 20 0, 20 20, -20 20, -20 0))";
GeoTransformation transformation = new Difference(shape2);
JtsGeometry geometry = geometry(shape1);
JtsGeometry transformedGeometry = transformation.apply(geometry, GeoShapeCondition.CONTEXT);
assertEquals("Failed applied DifferenceTransformation", difference, transformedGeometry.toString());
}
@Test(expected = IndexException.class)
public void testDifferenceTransformationWithNullShape() {
String shape1 = "POLYGON((-30 30, -30 0, 30 0, 30 30, -30 30))";
GeoTransformation transformation = new Difference(null);
JtsGeometry geometry = geometry(shape1);
transformation.apply(geometry, GeoShapeCondition.CONTEXT);
}
@Test(expected = IndexException.class)
public void testDifferenceTransformationWithEmptyShape() {
String shape1 = "POLYGON((-30 30, -30 0, 30 0, 30 30, -30 30))";
GeoTransformation transformation = new Difference("");
JtsGeometry geometry = geometry(shape1);
transformation.apply(geometry, GeoShapeCondition.CONTEXT);
}
@Test(expected = IndexException.class)
public void testDifferenceTransformationWithWrongShape() {
String shape1 = "POLYGON((-30 30, -30 0, 30 0, 30 30, -30 30))";
GeoTransformation transformation = new Difference("POLYGON((-30 0, 30 0, 30 -30, -30 -30))");
JtsGeometry geometry = geometry(shape1);
transformation.apply(geometry, GeoShapeCondition.CONTEXT);
}
@Test
public void testDifferenceTransformationToString() {
String shape1 = "POLYGON((-30 30, -30 0, 30 0, 30 30, -30 30))";
GeoTransformation transformation = new Difference(shape1);
assertEquals("Difference{other=POLYGON((-30 30, -30 0, 30 0, 30 30, -30 30))}", transformation.toString());
}
@Test
public void testDifferenceTransformationParsing() throws IOException {
String json = "{type:\"difference\",shape:\"LINESTRING(2 28, 30 3)\"}";
Difference difference = JsonSerializer.fromString(json, Difference.class);
assertNotNull("JSON serialization is wrong", difference);
assertEquals("JSON serialization is wrong", "LINESTRING(2 28, 30 3)", difference.other);
}
}
| 43.145631 | 115 | 0.719847 |
482ecf68f4cac61402e8a08898cef64c5c1d25d4 | 578 | package noppes.npcs.enchants;
import noppes.npcs.items.ItemGun;
import noppes.npcs.items.ItemStaff;
public class EnchantConfusion extends EnchantInterface {
public EnchantConfusion() {
super(3, ItemStaff.class, ItemGun.class);
setName("confusion");
}
@Override
public int getMinEnchantability(int par1) {
return 12 + (par1 - 1) * 20;
}
@Override
public int getMaxEnchantability(int par1) {
return this.getMinEnchantability(par1) + 25;
}
@Override
public int getMaxLevel() {
return 2;
}
}
| 20.642857 | 56 | 0.652249 |
f49f79308fd80df0665a6de26b075416745fe2be | 2,722 | /* ==========================================
* JGraphT : a free Java graph-theory library
* ==========================================
*
* Project Info: http://jgrapht.sourceforge.net/
* Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh)
*
* (C) Copyright 2003-2008, by Barak Naveh and Contributors.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the Free Software Foundation,
* Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*/
/* ---------------------
* GraphChangeEvent.java
* ---------------------
* (C) Copyright 2003-2008, by Barak Naveh and Contributors.
*
* Original Author: Barak Naveh
* Contributor(s): -
*
* $Id: GraphChangeEvent.java 645 2008-09-30 19:44:48Z perfecthash $
*
* Changes
* -------
* 10-Aug-2003 : Initial revision (BN);
*
*/
package org.jgrapht.event;
import java.util.*;
/**
* An event which indicates that a graph has changed. This class is a root for
* graph change events.
*
* @author Barak Naveh
* @since Aug 10, 2003
*/
public class GraphChangeEvent
extends EventObject
{
//~ Static fields/initializers ---------------------------------------------
private static final long serialVersionUID = 3834592106026382391L;
//~ Instance fields --------------------------------------------------------
/**
* The type of graph change this event indicates.
*/
protected int type;
//~ Constructors -----------------------------------------------------------
/**
* Creates a new graph change event.
*
* @param eventSource the source of the event.
* @param type the type of event.
*/
public GraphChangeEvent(Object eventSource, int type)
{
super(eventSource);
this.type = type;
}
//~ Methods ----------------------------------------------------------------
/**
* Returns the event type.
*
* @return the event type.
*/
public int getType()
{
return type;
}
}
// End GraphChangeEvent.java
| 28.957447 | 81 | 0.557311 |
d6dbf54d8f4bdb8c381e476ad8e3cbe758334561 | 5,293 | package com.ulyp.core;
import com.google.protobuf.ByteString;
import org.agrona.ExpandableDirectByteBuffer;
import org.agrona.MutableDirectBuffer;
import org.agrona.concurrent.UnsafeBuffer;
import org.agrona.sbe.MessageDecoderFlyweight;
import org.agrona.sbe.MessageEncoderFlyweight;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.NoSuchElementException;
import java.util.function.Consumer;
import java.util.function.Supplier;
/**
* Off-heap list which stores all data flat in memory using SBE.
* Both SBE encoder and decoder must be specified in descendant classes
*/
public abstract class AbstractBinaryEncodedList<Encoder extends MessageEncoderFlyweight, Decoder extends MessageDecoderFlyweight> implements Iterable<Decoder> {
private static final int LIST_HEADER_LENGTH = 2 * Integer.BYTES;
private static final int RECORD_HEADER_LENGTH = 2 * Integer.BYTES;
private Encoder encoder;
private Decoder decoder;
private Supplier<Decoder> decoderSupplier;
protected final MutableDirectBuffer buffer;
public AbstractBinaryEncodedList() {
buffer = new ExpandableDirectByteBuffer(64 * 1024);
setSize(0);
setLength(0);
initEncoder();
}
public AbstractBinaryEncodedList(ByteString bytes) {
buffer = new UnsafeBuffer(bytes.asReadOnlyByteBuffer());
initEncoder();
}
public ByteString toByteString() {
int bytesCount = length() + LIST_HEADER_LENGTH;
ByteString.Output output = ByteString.newOutput(bytesCount);
for (int i = 0; i < bytesCount; i++) {
output.write(buffer.getByte(i));
}
return output.toByteString();
}
@SuppressWarnings("unchecked")
private void initEncoder() {
ParameterizedType parameterizedSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
Type[] genericTypes = parameterizedSuperclass.getActualTypeArguments();
try {
encoder = (Encoder) Class.forName(genericTypes[0].getTypeName()).newInstance();
decoderSupplier = () -> {
try {
return (Decoder) Class.forName(genericTypes[1].getTypeName()).newInstance();
} catch (Exception e) {
throw new RuntimeException(e);
}
};
decoder = decoderSupplier.get();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
protected void add(Consumer<Encoder> writer) {
int recordHeaderAddr = length() + LIST_HEADER_LENGTH;
int recordAddr = recordHeaderAddr + RECORD_HEADER_LENGTH;
encoder.wrap(buffer, recordAddr);
writer.accept(encoder);
buffer.putInt(recordHeaderAddr, encoder.encodedLength());
buffer.putInt(recordHeaderAddr + Integer.BYTES, encoder.sbeBlockLength());
addLength(RECORD_HEADER_LENGTH + encoder.encodedLength());
incSize();
}
public int size() {
return buffer.getInt(0);
}
protected void incSize() {
setSize(size() + 1);
}
private void setSize(int value) {
buffer.putInt(0, value);
}
public int length() {
return buffer.getInt(4);
}
private void setLength(int value) {
buffer.putInt(4, value);
}
private void addLength(int delta) {
setLength(length() + delta);
}
@Override
public AddressableItemIterator<Decoder> iterator() {
return new ZeroCopyIterator();
}
public AddressableItemIterator<Decoder> copyingIterator() {
return new CopyingIterator();
}
private class ZeroCopyIterator implements AddressableItemIterator<Decoder> {
private int addr = LIST_HEADER_LENGTH;
@Override
public boolean hasNext() {
return addr < length() && buffer.getInt(addr) > 0;
}
@Override
public Decoder next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
int encodedLength = buffer.getInt(addr);
int blockLength = buffer.getInt(addr + Integer.BYTES);
decoder.wrap(buffer, addr + RECORD_HEADER_LENGTH, blockLength, 0);
addr += RECORD_HEADER_LENGTH + encodedLength;
return decoder;
}
@Override
public long address() {
return addr;
}
}
private class CopyingIterator implements AddressableItemIterator<Decoder> {
private int addr = LIST_HEADER_LENGTH;
@Override
public boolean hasNext() {
return addr < length() && buffer.getInt(addr) > 0;
}
@Override
public Decoder next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
int encodedLength = buffer.getInt(addr);
int blockLength = buffer.getInt(addr + Integer.BYTES);
Decoder decoder = decoderSupplier.get();
decoder.wrap(buffer, addr + RECORD_HEADER_LENGTH, blockLength, 0);
addr += RECORD_HEADER_LENGTH + encodedLength;
return decoder;
}
@Override
public long address() {
return addr;
}
}
}
| 30.245714 | 160 | 0.631022 |
e579620445eb9a82c93ffe7ce59c4c825f2acfe8 | 2,098 | package org.cempaka.cyclone.managed;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import io.dropwizard.lifecycle.Managed;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.cempaka.cyclone.beans.NodeStatus;
import org.cempaka.cyclone.configurations.ClusterConfiguration;
import org.cempaka.cyclone.services.NodeStatusService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Singleton
public class HeartbeatManaged implements Managed
{
private final static Logger LOG = LoggerFactory.getLogger(HeartbeatManaged.class);
private final ScheduledExecutorService executorService;
private final NodeStatusService nodeStatusService;
private final ClusterConfiguration clusterConfiguration;
@Inject
public HeartbeatManaged(final NodeStatusService nodeStatusService,
final ClusterConfiguration clusterConfiguration)
{
this.nodeStatusService = checkNotNull(nodeStatusService);
this.clusterConfiguration = checkNotNull(clusterConfiguration);
this.executorService = Executors.newSingleThreadScheduledExecutor(new ThreadFactoryBuilder()
.setNameFormat("HeartbeatManaged-%d")
.build());
}
@Override
public void start()
{
executorService.scheduleWithFixedDelay(() -> {
try {
nodeStatusService.updateStatus(NodeStatus.UP);
} catch (Exception e) {
LOG.error("Failed on sending heartbeat.", e);
}
}, 0, clusterConfiguration.getHeartbeatInterval(), TimeUnit.SECONDS);
}
@Override
public void stop() throws Exception
{
executorService.shutdown();
executorService.awaitTermination(clusterConfiguration.getHeartbeatManagedAwaitInterval(),
TimeUnit.SECONDS);
nodeStatusService.updateStatus(NodeStatus.DOWN);
}
}
| 35.559322 | 100 | 0.736416 |
fe0baf336d977b6325c7d53d2dd0dbae3879653f | 542 | package springfive.cms.domain.models;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.Data;
import org.hibernate.annotations.GenericGenerator;
/**
* @author claudioed on 28/10/17. Project cms
*/
@Data
@Entity
@Table(name = "system_user")
public class User {
@Id
@GeneratedValue(generator = "system-uuid")
@GenericGenerator(name = "system-uuid", strategy = "uuid")
String id;
String identity;
String name;
Role role;
}
| 18.066667 | 60 | 0.743542 |
f864525d9c2dbe853831dd85880cf6fcc9e50419 | 1,022 | package com.caleb.algorithm.leetcode;
import com.caleb.algorithm.offerdemo.ListNode;
/**
* @author:Caleb
* @Date :2021-08-14 23:18:55
*
* 反转链表II
*
* 给你单链表的头指针 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置
* right 的链表节点,返回 反转后的链表 。
*
*/
public class ReverseBetween92 {
public ListNode reverseBetween(ListNode head, int left, int right) {
ListNode prev = new ListNode(-1);
prev.next = head;
ListNode after;
ListNode node = head;
ListNode leftNode;
ListNode rightNode;
int pos = 1;
while (left != pos) {
node = node.next;
prev = prev.next;
pos++;
}
leftNode = node;
while (right != pos) {
node = node.next;
pos++;
}
rightNode = node;
after = node.next;
prev.next = null;
rightNode.next = null;
while (leftNode != null) {
ListNode temp = leftNode.next;
leftNode.next = after;
after = leftNode;
leftNode = temp;
}
prev.next = rightNode;
if (left == 1) {
return prev.next;
} else {
return head;
}
}
} | 18.925926 | 78 | 0.620352 |
0017075f0a244205c5776cb7a718091aacc1b899 | 2,715 | package com.qp.net;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class FileDownload {
private static FileDownload instance;
private OkHttpClient mOkHttpClient;
private FileDownload() {
mOkHttpClient = new OkHttpClient();
}
public static FileDownload getInstance() {
if (instance == null) {
synchronized (FileDownload.class) {
if (instance == null) {
instance = new FileDownload();
}
}
}
return instance;
}
public void download(String url, String filePathName, final OnDownloadListener listener) {
Request request = new Request.Builder().url(url).build();
mOkHttpClient.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
listener.onDownloadFailed();
}
@Override
public void onResponse(Call call, Response response) throws IOException {
InputStream is = null;
byte[] buf = new byte[2048];
int len = 0;
FileOutputStream fos = null;
try {
is = response.body().byteStream();
long total = response.body().contentLength();
File file = new File(filePathName);
fos = new FileOutputStream(file);
long sum = 0;
while ((len = is.read(buf)) != -1) {
fos.write(buf, 0, len);
sum += len;
int progress = (int) (sum * 1.0f / total * 100);
listener.onDownloading(progress);
}
fos.flush();
listener.onDownloadSuccess();
} catch (Exception e) {
listener.onDownloadFailed();
} finally {
try {
if (is != null)
is.close();
} catch (IOException e) {
}
try {
if (fos != null)
fos.close();
} catch (IOException e) {
}
}
}
});
}
public interface OnDownloadListener {
void onDownloadSuccess();
void onDownloading(int progress);
void onDownloadFailed();
}
}
| 32.321429 | 94 | 0.483241 |
899365f0b141305f364fae0c90a40cf8355974fe | 3,094 | package com.felhr.usbserial;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import java.util.Arrays;
@RunWith(JUnit4.class)
public class FTDISerialDeviceTest {
@Test
public void adaptEmptyByteArray() {
byte[] onlyHeaders = {1, 2};
byte[] adapted = FTDISerialDevice.adaptArray(onlyHeaders);
Assert.assertEquals("Should be empty", 0, adapted.length);
byte[] adaptAgain = FTDISerialDevice.adaptArray(onlyHeaders);
Assert.assertSame("Should be the same instance of empty array", adapted, adaptAgain);
}
@Test
public void withHeaders() {
byte[] withHeaders = {1, 2, 3, 4, 5, 6};
byte[] wanted = {3,4,5,6};
Assert.assertArrayEquals(wanted, FTDISerialDevice.adaptArray(withHeaders));
}
@Test
public void fullWithHeaders() {
byte[] withHeaders = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64};
byte[] wanted = Arrays.copyOfRange(withHeaders, 2, 64);
Assert.assertArrayEquals(wanted, FTDISerialDevice.adaptArray(withHeaders));
}
@Test
public void testMultipleFull() {
byte[] withHeaders = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64, 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64};
byte[] wanted = {3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64, 3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64};
Assert.assertArrayEquals(wanted, FTDISerialDevice.adaptArray(withHeaders));
}
@Test
public void testMultiplePartial() {
byte[] withHeaders = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64, 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62};
byte[] wanted = {3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64, 3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62};
Assert.assertArrayEquals(wanted, FTDISerialDevice.adaptArray(withHeaders));
}
}
| 61.88 | 398 | 0.654169 |
8d887be1ffbe58a7d4cf4c723064eb86bdadacfb | 2,442 | /*
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.wiki.plugin;
import org.apache.wiki.api.core.Context;
import org.apache.wiki.api.exceptions.PluginException;
import org.apache.wiki.api.plugin.Plugin;
import org.apache.wiki.preferences.Preferences;
import org.apache.wiki.preferences.Preferences.TimeFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.ResourceBundle;
/**
* Just displays the current date and time.
* The time format is exactly like in the java.text.SimpleDateFormat class.
*
* <p>Parameters : </p>
* NONE
* @since 1.7.8
* @see java.text.SimpleDateFormat
*/
public class CurrentTimePlugin implements Plugin {
// private static Logger log = LogManager.getLogger( CurrentTimePlugin.class );
/**
* {@inheritDoc}
*/
@Override
public String execute( final Context context, final Map< String, String > params ) throws PluginException {
final String formatString = params.get( "format" );
try {
final SimpleDateFormat fmt;
if( formatString != null ) {
fmt = new SimpleDateFormat( formatString );
} else {
fmt = Preferences.getDateFormat( context, TimeFormat.DATETIME );
}
final Date d = new Date(); // Now.
return fmt.format( d );
} catch( final IllegalArgumentException e ) {
final ResourceBundle rb = Preferences.getBundle( context, Plugin.CORE_PLUGINS_RESOURCEBUNDLE );
throw new PluginException( rb.getString( "currenttimeplugin.badformat" ) + e.getMessage() );
}
}
}
| 34.885714 | 111 | 0.68878 |
9f8cf3178b5f7d5c439d8b7dc5ba24abf9bdf7e3 | 2,320 | /*
* 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.scavi.de.gw2imp.dagger2.module;
import android.content.Context;
import android.support.annotation.NonNull;
import com.scavi.de.gw2imp.preferences.IPreferenceAccess;
import com.scavi.de.gw2imp.model.SplashModel;
import com.scavi.de.gw2imp.presenter.SplashPresenter;
import com.scavi.de.gw2imp.ui.view.ISplashView;
import javax.annotation.Nonnull;
import javax.annotation.ParametersAreNonnullByDefault;
import dagger.Module;
import dagger.Provides;
@Module
@ParametersAreNonnullByDefault
public class SplashModule {
private final ISplashView mView;
/**
* Constructor
*
* @param view the view for the splash screen
*/
public SplashModule(final ISplashView view) {
this.mView = view;
}
/**
* @return the view of the splash screen
*/
@Provides
@Nonnull
public ISplashView provideView() {
return mView;
}
/**
* @param model the model of the MVP pattern in the context of the splash screen
* @return the presenter of the MVP pattern in the context of the splash screen
*/
@Provides
@NonNull
public SplashPresenter providePresenter(final SplashModel model) {
return new SplashPresenter(mView, model);
}
/**
* @param context the context to global information about the application environment
* @param preferenceAccess access to the shared preferences of this application
* @return the model of the MVP pattern in the context of the splash screen
*/
@Provides
@NonNull
public SplashModel provideModel(final Context context,
final IPreferenceAccess preferenceAccess) {
return new SplashModel(context, preferenceAccess);
}
}
| 30.526316 | 98 | 0.707328 |
c9131b22048d1cfe7fd0e306fa73081e75da7485 | 5,620 | /*
* Copyright 2011-2021 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.query;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import org.apiguardian.api.API;
import org.neo4j.cypherdsl.core.Condition;
import org.neo4j.cypherdsl.core.Conditions;
import org.neo4j.cypherdsl.core.Cypher;
import org.neo4j.cypherdsl.core.Expression;
import org.neo4j.cypherdsl.core.PatternElement;
import org.neo4j.cypherdsl.core.SortItem;
import org.neo4j.cypherdsl.core.Statement;
import org.neo4j.cypherdsl.core.StatementBuilder;
import org.springframework.data.neo4j.core.mapping.CypherGenerator;
import org.springframework.data.neo4j.core.mapping.NodeDescription;
import org.springframework.lang.Nullable;
/**
* Collects the parts of a Cypher query to be handed over to the Cypher generator.
*
* @author Gerrit Meier
* @since 6.0.4
*/
@API(status = API.Status.INTERNAL, since = "6.0.4")
public final class QueryFragments {
private List<PatternElement> matchOn = new ArrayList<>();
private Condition condition;
private List<Expression> returnExpressions = new ArrayList<>();
private SortItem[] orderBy;
private Number limit;
private Long skip;
private ReturnTuple returnTuple;
private boolean scalarValueReturn = false;
private boolean renderConstantsAsParameters = false;
public void addMatchOn(PatternElement match) {
this.matchOn.add(match);
}
public void setMatchOn(List<PatternElement> match) {
this.matchOn = match;
}
public List<PatternElement> getMatchOn() {
return matchOn;
}
public void setCondition(@Nullable Condition condition) {
this.condition = Optional.ofNullable(condition).orElse(Conditions.noCondition());
}
public Condition getCondition() {
return condition;
}
public void setReturnExpressions(Expression[] expression) {
this.returnExpressions = Arrays.asList(expression);
}
public void setReturnExpression(Expression returnExpression, boolean isScalarValue) {
this.returnExpressions = Collections.singletonList(returnExpression);
this.scalarValueReturn = isScalarValue;
}
public boolean includeField(String fieldName) {
return this.returnTuple == null || this.returnTuple.includedProperties.isEmpty()
|| this.returnTuple.includedProperties.contains(fieldName);
}
public void setOrderBy(SortItem[] orderBy) {
this.orderBy = orderBy;
}
public void setLimit(Number limit) {
this.limit = limit;
}
public void setSkip(Long skip) {
this.skip = skip;
}
public void setReturnBasedOn(NodeDescription<?> nodeDescription, List<String> includedProperties,
boolean isDistinct) {
this.returnTuple = new ReturnTuple(nodeDescription, includedProperties, isDistinct);
}
public ReturnTuple getReturnTuple() {
return returnTuple;
}
public boolean isScalarValueReturn() {
return scalarValueReturn;
}
public boolean isRenderConstantsAsParameters() {
return renderConstantsAsParameters;
}
public void setRenderConstantsAsParameters(boolean renderConstantsAsParameters) {
this.renderConstantsAsParameters = renderConstantsAsParameters;
}
public Statement toStatement() {
StatementBuilder.OngoingReadingWithoutWhere match = null;
for (PatternElement patternElement : matchOn) {
if (match == null) {
match = Cypher.match(matchOn.get(0));
} else {
match = match.match(patternElement);
}
}
StatementBuilder.OngoingReadingWithWhere matchWithWhere = match.where(condition);
StatementBuilder.OngoingReadingAndReturn returnPart = isDistinctReturn()
? matchWithWhere.returningDistinct(getReturnExpressions())
: matchWithWhere.returning(getReturnExpressions());
Statement statement = returnPart
.orderBy(getOrderBy())
.skip(skip)
.limit(limit).build();
statement.setRenderConstantsAsParameters(renderConstantsAsParameters);
return statement;
}
private Expression[] getReturnExpressions() {
return returnExpressions.size() > 0
? returnExpressions.toArray(new Expression[] {})
: CypherGenerator.INSTANCE.createReturnStatementForMatch(getReturnTuple().nodeDescription,
this::includeField);
}
private boolean isDistinctReturn() {
return returnExpressions.isEmpty() && getReturnTuple().isDistinct;
}
public SortItem[] getOrderBy() {
return orderBy != null ? orderBy : new SortItem[] {};
}
public Number getLimit() {
return limit;
}
public Long getSkip() {
return skip;
}
/**
* Describes which fields of an entity needs to get returned.
*/
final static class ReturnTuple {
final NodeDescription<?> nodeDescription;
final Set<String> includedProperties;
final boolean isDistinct;
private ReturnTuple(NodeDescription<?> nodeDescription, List<String> includedProperties, boolean isDistinct) {
this.nodeDescription = nodeDescription;
this.includedProperties =
includedProperties == null ? Collections.emptySet() : new HashSet<>(includedProperties);
this.isDistinct = isDistinct;
}
}
}
| 29.578947 | 112 | 0.764769 |
ac3416322e60caecadbcf16e79e1e945cc333fef | 1,603 | package com.cskaoyan.controller;
import com.cskaoyan.bean.BaseRespVo;
import com.cskaoyan.service.StatUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
@RestController
@RequestMapping("admin/stat")
public class StatController {
@Autowired
StatUserService statUserService;
@GetMapping("/user")
/**
* 显示用户统计
*/
public BaseRespVo queryStatUserMsg(){
BaseRespVo<Object> baseRespVo = new BaseRespVo<>();
Map map = statUserService.queryStatUserMsg();
System.out.println("这里是"+map.get("rows"));
if(map==null){
baseRespVo.setErrmsg("系统有误");
baseRespVo.setData(map);
baseRespVo.setErrno(10000);
return baseRespVo;
}
baseRespVo.setErrmsg("成功");
baseRespVo.setData(map);
baseRespVo.setErrno(0);
return baseRespVo;
}
@GetMapping("/goods")
public BaseRespVo queryStatGoodsMsg(){
BaseRespVo<Object> baseRespVo = new BaseRespVo<>();
Map map = statUserService.queryStatGoodsMsg();
if(map==null){
baseRespVo.setErrmsg("系统有误");
baseRespVo.setData(map);
baseRespVo.setErrno(10000);
return baseRespVo;
}
baseRespVo.setErrmsg("成功");
baseRespVo.setData(map);
baseRespVo.setErrno(0);
return baseRespVo;
}
}
| 28.625 | 62 | 0.653774 |
acfad5619b36fa53778dba73c50a9f1c62990e53 | 1,116 | package org.loser.cache;
import static com.loserico.commons.jackson.JacksonUtils.toJson;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import com.loserico.commons.jackson.JacksonUtils;
import com.loserico.commons.resource.PropertyReader;
public class PropertyReaderTest {
@Test
public void testStrList() {
PropertyReader propertyReader = new PropertyReader("centre-virtual-account");
List<String> centres20190101 = propertyReader.getStrList("virtual.account.20190101");
System.out.println(toJson(centres20190101));
}
@Test
public void testGetLocalDate() {
PropertyReader propertyReader = new PropertyReader("centre-virtual-account");
LocalDate localDate = propertyReader.getLocalDate("virtual.account.since");
System.out.println(localDate);
}
@Test
public void testGetMap() {
PropertyReader propertyReader = new PropertyReader("centre-virtual-account");
Map<String, String> accountMap = propertyReader.getMap("company.accounts");
System.out.println(JacksonUtils.toPrettyJson(accountMap));
}
}
| 30.162162 | 88 | 0.760753 |
07c24852db8a9c10c2655f8400674e8871d73193 | 2,213 | /*
* Copyright (c) 2018, Fitzyy. All Rights Reserved.
*/
package me.fitzyy.tool.datetime;
import org.joda.time.DateTime;
import java.util.Date;
/**
* <p> </p>
*
* <p> Created At 2018-02-14 13:57 </p>
*
* @author FitzYang
* @version 1.0
* @since JDK 1.8
*/
public class TimeUtil {
private TimeUtil() {
}
/**
* 获取当前时间 单位:s
*
* @return 当前时间
*/
public static int unixTime() {
return (int) (System.currentTimeMillis() / 1000);
}
/**
* 通过以s为单位的当前时间返回日期
*
* @param unix 以s为单位的时间
* @return unix对应的日期
*/
public static Date dateTime(int unix) {
return new Date(unix * 1000L);
}
/**
* 通过日期返回对应的时间 单位s
*
* @param date 日期
* @return 对应的以s为单位的时间
*/
public static int unixTime(Date date) {
return date == null ? 0 : (int) (date.getTime() / 1000);
}
/**
* 通过日期返回对应的时间 单位s
*
* @param dateTime 日期
* @return 对应的以s为单位的时间
*/
public static int unixTime(DateTime dateTime) {
return dateTime == null ? 0 : (int) (dateTime.getMillis() / 1000);
}
/**
* 获取某个时间的 一天 的开始时间和结束时间
*
* @param time 时间
* @return 开始和结束时间 unixTime
*/
public static int[] dayOfMinMaxUnitTime(DateTime time) {
final DateTime.Property millisOfDay = time.millisOfDay();
final DateTime maximumValue = millisOfDay.withMaximumValue();
final DateTime minimumValue = millisOfDay.withMinimumValue();
return new int[]{unixTime(minimumValue), unixTime(maximumValue)};
}
/**
* 获取某个时间的 所在月份的 的开始时间和结束时间
*
* @param month 月
* @return 开始和结束时间 unixTime
*/
public static int[] monthOfMinMaxUnitTime(DateTime month) {
final DateTime.Property monthOfYear = month.monthOfYear();
final DateTime maximumValue = monthOfYear.withMaximumValue();
final DateTime minimumValue = monthOfYear.withMinimumValue();
return new int[]{unixTime(minimumValue), unixTime(maximumValue)};
}
/**
* 获取长整型当前时间 单位:s
*
* @return 以s为单位的长整型当前时间
*/
public static long unixTimeLong() {
return (System.currentTimeMillis() / 1000);
}
}
| 22.353535 | 74 | 0.592408 |
99007773b49344f64879246a3fa9293ca21bb380 | 11,653 | package com.pgmmers.radar.service.impl.model;
import com.alibaba.fastjson.JSON;
import com.pgmmers.radar.dal.bean.DataListQuery;
import com.pgmmers.radar.dal.bean.DataListRecordQuery;
import com.pgmmers.radar.dal.model.DataListDal;
import com.pgmmers.radar.dal.model.ModelDal;
import com.pgmmers.radar.service.cache.CacheService;
import com.pgmmers.radar.service.cache.SubscribeHandle;
import com.pgmmers.radar.service.common.CommonResult;
import com.pgmmers.radar.service.model.DataListsService;
import com.pgmmers.radar.vo.model.DataListMetaVO;
import com.pgmmers.radar.vo.model.DataListRecordVO;
import com.pgmmers.radar.vo.model.DataListsVO;
import com.pgmmers.radar.vo.model.ModelVO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class DataListsServiceImpl implements DataListsService, SubscribeHandle {
public static Logger logger = LoggerFactory.getLogger(DataListsServiceImpl.class);
@Autowired
private DataListDal dataListDal;
@Autowired
private CacheService cacheService;
@Autowired
private ModelDal modelDal;
private static Map<Long, Map<String, Object>> dataListRecordCacheMap = new HashMap<>();
@Override
public List<DataListsVO> listDataLists(Long modelId, Integer status) {
return dataListDal.listDataLists(modelId, status);
}
@Override
public List<DataListRecordVO> listDataListRecords(Long dataListId) {
return dataListDal.listDataRecord(dataListId);
}
@Override
public DataListsVO get(Long id) {
return dataListDal.get(id);
}
@Override
public CommonResult list(Long modelId) {
CommonResult result = new CommonResult();
result.setSuccess(true);
result.getData().put("list", dataListDal.list(modelId));
return result;
}
@Override
public CommonResult query(DataListQuery query) {
CommonResult result = new CommonResult();
result.setSuccess(true);
result.getData().put("page", dataListDal.query(query));
return result;
}
@Override
public CommonResult save(DataListsVO dataList) {
CommonResult result = new CommonResult();
int count = dataListDal.save(dataList);
if (count > 0) {
if(StringUtils.isEmpty(dataList.getName())){
dataList.setName("dataList_"+dataList.getId());
dataListDal.save(dataList);
}
result.getData().put("id", dataList.getId());
result.setSuccess(true);
// 通知更新
dataList.setOpt("new");
cacheService.publishDataList(dataList);
}
return result;
}
@Override
public CommonResult delete(Long[] id) {
CommonResult result = new CommonResult();
DataListsVO dataList = dataListDal.get(id[0]);
int count = dataListDal.delete(id);
if (count > 0) {
result.setSuccess(true);
// 通知更新
dataList.setOpt("delete");
cacheService.publishDataList(dataList);
}
return result;
}
@Override
public DataListMetaVO getMeta(Long id) {
return dataListDal.getMeta(id);
}
@Override
public CommonResult listMeta(Long dataListId) {
CommonResult result = new CommonResult();
result.setSuccess(true);
result.getData().put("list", dataListDal.listDataMeta(dataListId));
return result;
}
@Override
public CommonResult saveMeta(List<DataListMetaVO> listDataListMeta) {
// 现有数据转为map
Map<Long, DataListMetaVO> metaMap = new HashMap<Long, DataListMetaVO>();
Long dataListId = listDataListMeta.get(0).getDataListId();
List<DataListMetaVO> listMetaVO = dataListDal.listDataMeta(dataListId);
for (DataListMetaVO metaVO : listMetaVO) {
metaMap.put(metaVO.getId(), metaVO);
}
// 遍历更新
for (DataListMetaVO dataListMeta : listDataListMeta) {
if (metaMap.containsKey(dataListMeta.getId())) {
metaMap.remove(dataListMeta.getId());
}
dataListDal.saveMeta(dataListMeta);
if(StringUtils.isEmpty(dataListMeta.getFieldName())){
dataListMeta.setFieldName("dataListMeta_"+dataListMeta.getId());
dataListDal.saveMeta(dataListMeta);
}
}
// 移除未提交的记录
List<Long> listId = new ArrayList<Long>();
listId.addAll(metaMap.keySet());
if (listId.size() > 0) {
deleteMeta(listId);
}
// meta改变,清除Record数据
dataListDal.deleteRecord(dataListId);
CommonResult result = new CommonResult();
result.setSuccess(true);
return result;
}
@Override
public CommonResult deleteMeta(List<Long> listId) {
CommonResult result = new CommonResult();
int count = dataListDal.deleteMeta(listId);
if (count > 0) {
result.setSuccess(true);
// 通知更新 TODO
}
return result;
}
@Override
public DataListRecordVO getRecord(Long id) {
return dataListDal.getRecord(id);
}
@Override
public CommonResult queryRecord(DataListRecordQuery query) {
CommonResult result = new CommonResult();
result.setSuccess(true);
result.getData().put("page", dataListDal.queryRecord(query));
return result;
}
@Override
public CommonResult saveRecord(DataListRecordVO dataListRecord) {
CommonResult result = new CommonResult();
int count = dataListDal.saveRecord(dataListRecord);
if (count > 0) {
result.getData().put("id", dataListRecord.getId());
result.setSuccess(true);
// 通知更新
DataListsVO dataListVO = dataListDal.get(dataListRecord.getDataListId());
dataListRecord.setModelId(dataListVO.getModelId());
dataListRecord.setOpt("update");
cacheService.publishDataListRecord(dataListRecord);
}
return result;
}
@Override
public CommonResult deleteRecord(Long[] id) {
CommonResult result = new CommonResult();
DataListRecordVO record = dataListDal.getRecord(id[0]);
int count = dataListDal.deleteRecord(id);
if (count > 0) {
result.setSuccess(true);
// 通知更新
DataListsVO dataListVO = dataListDal.get(record.getDataListId());
record.setModelId(dataListVO.getModelId());
record.setOpt("delete");
cacheService.publishDataListRecord(record);
}
return result;
}
@Override
public void onMessage(String channel, String message) {
logger.info("data list sub:{}", message);
DataListsVO dataListsVO = JSON.parseObject(message, DataListsVO.class);
Map<String, Object> listRecordMap = dataListRecordCacheMap.get(dataListsVO.getModelId());
if (dataListsVO.getOpt().equals("delete")) {
listRecordMap.remove(dataListsVO.getName());
} else if (dataListsVO.getOpt().equals("new")) {
Map<String, String> recordsMap = new HashMap<>();
listRecordMap.put(dataListsVO.getName(), recordsMap);
}
}
@PostConstruct
public void init() {
cacheService.subscribeDataList(this);
new Thread(() ->{
List<ModelVO> modelList = modelDal.listModel(null);
// 加载系统数据名单列表
Map<String, Object> sysDataListMap = new HashMap<>();
List<DataListsVO> sysList = dataListDal.listDataLists(0L, null);
for (DataListsVO dataListVO : sysList) {
Map<String, String> dataListRecords = new HashMap<String, String>();
// record list
List<DataListRecordVO> recordVOList = dataListDal.listDataRecord(dataListVO.getId());
if (recordVOList != null) {
for (DataListRecordVO record : recordVOList) {
dataListRecords.put(record.getDataRecord(), "");
}
}
sysDataListMap.put(dataListVO.getName(), dataListRecords);
}
for (ModelVO model : modelList) {
Map<String, Object> dataListMap = new HashMap<>();
// datalist list
List<DataListsVO> dataLists = dataListDal.listDataLists(model.getId(), null);
if (dataLists != null) {
for (DataListsVO dataListVO : dataLists) {
Map<String, String> dataListRecords = new HashMap<>();
// record list
List<DataListRecordVO> recordVOList = dataListDal.listDataRecord(dataListVO.getId());
if (recordVOList != null) {
for (DataListRecordVO record : recordVOList) {
dataListRecords.put(record.getDataRecord(), "");
}
}
dataListMap.put(dataListVO.getName(), dataListRecords);
}
}
// add sys data list
dataListMap.putAll(sysDataListMap);
dataListRecordCacheMap.put(model.getId(), dataListMap);
}
logger.info("data list has loaded.");
}).start();
}
public Map<String, Object> getDataListMap(Long modelId) {
Map<String, Object> listMap = dataListRecordCacheMap.get(modelId);
return listMap;
}
@Override
public CommonResult batchImportData(List<DataListsVO> list, Long modelId) {
CommonResult result = new CommonResult();
for (DataListsVO data : list) {
data.setStatus(1);
data.setName("");
data.setModelId(modelId);
int count = dataListDal.save(data);
if (count > 0) {
if(StringUtils.isEmpty(data.getName())){
data.setName("dataList_"+data.getId());
dataListDal.save(data);
}
// 通知更新
data.setOpt("new");
cacheService.publishDataList(data);
}
}
result.setSuccess(true);
result.setMsg("导入成功");
return result;
}
@Override
public CommonResult batchImportDataRecord(List<DataListRecordVO> list, Long dataListId) {
CommonResult result = new CommonResult();
for (DataListRecordVO dataListRecord : list) {
dataListRecord.setDataListId(dataListId);
int count = dataListDal.saveRecord(dataListRecord);
if (count > 0) {
// 通知更新
DataListsVO dataListVO = dataListDal.get(dataListRecord.getDataListId());
dataListRecord.setModelId(dataListVO.getModelId());
dataListRecord.setOpt("update");
cacheService.publishDataListRecord(dataListRecord);
}
}
result.setSuccess(true);
result.setMsg("导入成功");
return result;
}
}
| 35.966049 | 113 | 0.5977 |
7dec6c078ea43e3e7309640c958de467d1ee8924 | 846 | package org.modelcatalogue.spreadsheet.api;
/**
* Created by ladin on 03.03.17.
*/
public interface PageSettingsProvider {
Keywords.Orientation getPortrait();
Keywords.Orientation getLandscape();
Keywords.Fit getWidth();
Keywords.Fit getHeight();
Keywords.To getTo();
Keywords.Paper getLetter();
Keywords.Paper getLetterSmall();
Keywords.Paper getTabloid();
Keywords.Paper getLedger();
Keywords.Paper getLegal();
Keywords.Paper getStatement();
Keywords.Paper getExecutive();
Keywords.Paper getA3();
Keywords.Paper getA4();
Keywords.Paper getA4Small();
Keywords.Paper getA5();
Keywords.Paper getB4();
Keywords.Paper getB5();
Keywords.Paper getFolio();
Keywords.Paper getQuarto();
Keywords.Paper getStandard10x14();
Keywords.Paper getStandard11x17();
}
| 24.882353 | 43 | 0.696217 |
9291f842580350da5cbdd2e1da355e862ec59c5c | 7,215 | package us.kbase.genbank;
import us.kbase.auth.AuthService;
import us.kbase.auth.AuthToken;
import us.kbase.auth.AuthUser;
import us.kbase.auth.TokenFormatException;
import us.kbase.common.service.Tuple11;
import us.kbase.common.service.UObject;
import us.kbase.common.service.UnauthorizedException;
import us.kbase.kbasegenomes.ContigSet;
import us.kbase.kbasegenomes.Genome;
import us.kbase.workspace.*;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
/**
* Created by Marcin Joachimiak
* User: marcin
* Date: 11/3/14
* Time: 3:22 PM
*/
public class ConvertGBK {
String wshttp = null;
String ws = null;
boolean isTest = false;
/**
* @param args
* @throws Exception
*/
public ConvertGBK(String[] args) throws Exception {
File indir = new File(args[0]);
if (args.length == 3) {
ws = args[1];
wshttp = args[2];
}
parseAllInDir(new int[]{1}, indir, new ObjectStorage() {
@Override
public List<Tuple11<Long, String, String, String, Long, String, Long, String, String, Long, Map<String, String>>> saveObjects(
String authToken, SaveObjectsParams params) throws Exception {
//validateObject(validator, params.getObjects().get(0).getName(),
// params.getObjects().get(0).getData(), params.getObjects().get(0).getType());
return null;
}
@Override
public List<ObjectData> getObjects(String authToken,
List<ObjectIdentity> objectIds) throws Exception {
throw new IllegalStateException("Unsupported method");
}
}, ws, wshttp, isTest);
}
/**
* @param pos
* @param dir
* @param wc
* @throws Exception
*/
public static void parseAllInDir(int[] pos, File dir, ObjectStorage wc, String wsname, String http, boolean isTestThis) throws Exception {
List<File> files = new ArrayList<File>();
for (File f : dir.listFiles()) {
if (f.isDirectory()) {
parseAllInDir(pos, f, wc, wsname, http, isTestThis);
} else if (f.getName().endsWith(".gbk")) {
files.add(f);
System.out.println("Added " + f);
}
}
if (files.size() > 0)
parseGenome(pos, dir, files, wsname, http, isTestThis);
}
/**
* @param pos
* @param dir
* @param gbkFiles
* @throws Exception
*/
public static void parseGenome(int[] pos, File dir, List<File> gbkFiles, String wsname, String http, boolean isTestThis) throws Exception {
System.out.println("[" + (pos[0]++) + "] " + dir.getName());
long time = System.currentTimeMillis();
ArrayList ar = GbkUploader.uploadGbk(gbkFiles, wsname, dir.getName(), true);
Genome genome = (Genome) ar.get(2);
final String outpath = genome.getId() + ".jsonp";
try {
PrintWriter out = new PrintWriter(new FileWriter(outpath));
out.print(UObject.transformObjectToString(genome));
out.close();
System.out.println(" wrote: " + outpath);
} catch (IOException e) {
System.err.println("Error creating or writing file " + outpath);
System.err.println("IOException: " + e.getMessage());
}
ContigSet contigSet = (ContigSet) ar.get(4);
final String contigId = genome.getId() + "_ContigSet";
final String outpath2 = contigId + ".jsonp";
try {
PrintWriter out = new PrintWriter(new FileWriter(outpath2));
out.print(UObject.transformObjectToString(contigSet));
out.close();
System.out.println(" wrote: " + outpath2);
} catch (IOException e) {
System.err.println("Error creating or writing file " + outpath2);
System.err.println("IOException: " + e.getMessage());
}
if (wsname != null) {
/*ar.add(ws);
ar.add(id);
ar.add(genome);
ar.add(contigSetId);
ar.add(contigSet);
ar.add(meta);*/
String genomeid = (String) ar.get(1);
//String token = (String) ar.get(2);
String contigSetId = (String) ar.get(3);
Map<String, String> meta = (Map<String, String>) ar.get(5);
String user = System.getProperty("test.user");
String pwd = System.getProperty("test.pwd");
String kbtok = System.getenv("KB_AUTH_TOKEN");
System.out.println(http);
try {
WorkspaceClient wc = null;
if (isTestThis) {
AuthToken at = ((AuthUser) AuthService.login(user, pwd)).getToken();
wc = new WorkspaceClient(new URL(http), at);
} else {
wc = new WorkspaceClient(new URL(http), new AuthToken(kbtok));
}
wc.setAuthAllowedForHttp(true);
wc.saveObjects(new SaveObjectsParams().withWorkspace(wsname)
.withObjects(Arrays.asList(new ObjectSaveData().withName(contigSetId)
.withType("KBaseGenomes.ContigSet").withData(new UObject(contigSet)))));
wc.saveObjects(new SaveObjectsParams().withWorkspace(wsname)
.withObjects(Arrays.asList(new ObjectSaveData().withName(genomeid).withMeta(meta)
.withType("KBaseGenomes.Genome").withData(new UObject(genome)))));
} catch (UnauthorizedException e) {
System.err.println("WS UnauthorizedException");
System.err.print(e.getMessage());
System.err.print(e.getStackTrace());
e.printStackTrace();
} catch (IOException e) {
System.err.println("WS IOException");
System.err.print(e.getMessage());
System.err.print(e.getStackTrace());
e.printStackTrace();
} catch (TokenFormatException e) {
System.err.println("WS TokenFormatException");
System.err.print(e.getMessage());
System.err.print(e.getStackTrace());
e.printStackTrace();
}
}
/*TODO add SHOCK upload? */
System.out.println(" time: " + (System.currentTimeMillis() - time) + " ms");
}
/**
* @param args
*/
public final static void main(String[] args) {
if (args.length == 1 || args.length == 3) {
try {
ConvertGBK clt = new ConvertGBK(args);
} catch (Exception e) {
e.printStackTrace();
}
} else {
System.out.println("usage: java us.kbase.genbank.ConvertGBK <dir or dir of dirs with GenBank .gbk files> <ws name> <ws url>");// <convert y/n> <save y/n>");
}
}
}
| 34.521531 | 168 | 0.559529 |
57ef2e99298ce578f963f60d47964d4a3ca17a1f | 840 | package com.github.nekolr.util;
import java.lang.reflect.Field;
public class BeanUtils {
/**
* 设置字段的值
*
* @param obj 实体对象
* @param field 字段
* @param value 值
*/
public static void setFieldValue(Object obj, Field field, Object value) {
try {
field.setAccessible(true);
field.set(obj, value);
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
/**
* 获取字段的值
*
* @param obj 实体对象
* @param field 字段
* @return 字段的值
*/
public static Object getFieldValue(Object obj, Field field) {
try {
field.setAccessible(true);
return field.get(obj);
} catch (IllegalAccessException e) {
e.printStackTrace();
return null;
}
}
}
| 21 | 77 | 0.527381 |
2d78296d2df6688e47355d4b53e995846a7e685c | 2,040 | /*
* Copyright 2016-2018 ISP RAS (http://www.ispras.ru)
*
* 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 ru.ispras.microtesk.translator.nml.analysis;
import ru.ispras.microtesk.translator.TranslatorHandler;
import ru.ispras.microtesk.translator.nml.ir.Ir;
import ru.ispras.microtesk.translator.nml.ir.IrVisitorDefault;
import ru.ispras.microtesk.translator.nml.ir.IrWalker;
import ru.ispras.microtesk.translator.nml.ir.primitive.Attribute;
import ru.ispras.microtesk.translator.nml.ir.primitive.Primitive;
import ru.ispras.microtesk.translator.nml.ir.primitive.PrimitiveAnd;
public final class ReferenceDetector implements TranslatorHandler<Ir> {
@Override
public void processIr(final Ir ir) {
final IrWalker walker = new IrWalker(ir);
walker.visit(new Visitor(), IrWalker.Direction.LINEAR);
}
private static final class Visitor extends IrVisitorDefault {
@Override
public void onResourcesBegin() {
setStatus(Status.SKIP);
}
@Override
public void onResourcesEnd() {
setStatus(Status.OK);
}
@Override
public void onArgumentBegin(
final PrimitiveAnd andRule,
final String argName,
final Primitive argType) {
argType.addParentReference(andRule, argName);
}
@Override
public void onAttributeBegin(final PrimitiveAnd andRule, final Attribute attr) {
setStatus(Status.SKIP);
}
@Override
public void onAttributeEnd(final PrimitiveAnd andRule, final Attribute attr) {
setStatus(Status.OK);
}
}
}
| 32.903226 | 100 | 0.740196 |
646686da99ca8b848ec532b8e5f5700f205f99c7 | 5,094 | /*
* Copyright 2020 The Netty Project
*
* The Netty Project 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:
*
* 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 io.netty.incubator.codec.http3;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.channel.socket.ChannelInputShutdownEvent;
import io.netty.util.ReferenceCountUtil;
import io.netty.util.internal.ObjectUtil;
import static io.netty.incubator.codec.http3.Http3CodecUtils.closeOnFailure;
final class Http3ControlStreamOutboundHandler
extends Http3FrameTypeDuplexValidationHandler<Http3ControlStreamFrame> {
private final boolean server;
private final Http3SettingsFrame localSettings;
private final ChannelHandler codec;
private Long sentMaxPushId;
private Long sendGoAwayId;
Http3ControlStreamOutboundHandler(boolean server, Http3SettingsFrame localSettings, ChannelHandler codec) {
super(Http3ControlStreamFrame.class);
this.server = server;
this.localSettings = ObjectUtil.checkNotNull(localSettings, "localSettings");
this.codec = ObjectUtil.checkNotNull(codec, "codec");
}
/**
* Returns the local settings that were sent on the control stream.
*
* @return the local {@link Http3SettingsFrame}.
*/
Http3SettingsFrame localSettings() {
return localSettings;
}
/**
* Returns the last id that was sent in a MAX_PUSH_ID frame or {@code null} if none was sent yet.
*
* @return the id.
*/
Long sentMaxPushId() {
return sentMaxPushId;
}
@Override
public void channelActive(ChannelHandlerContext ctx) {
// We need to write 0x00 into the stream before doing anything else.
// See https://tools.ietf.org/html/draft-ietf-quic-http-32#section-6.2.1
// Just allocate 8 bytes which would be the max needed.
ByteBuf buffer = ctx.alloc().buffer(8);
Http3CodecUtils.writeVariableLengthInteger(buffer, Http3CodecUtils.HTTP3_CONTROL_STREAM_TYPE);
ctx.write(buffer);
// Add the encoder and decoder in the pipeline so we can handle Http3Frames. This needs to happen after
// we did write the type via a ByteBuf.
ctx.pipeline().addFirst(codec);
// If writing of the local settings fails let's just teardown the connection.
closeOnFailure(ctx.writeAndFlush(DefaultHttp3SettingsFrame.copyOf(localSettings)));
ctx.fireChannelActive();
}
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
if (evt instanceof ChannelInputShutdownEvent) {
// See https://tools.ietf.org/html/draft-ietf-quic-http-32#section-6.2.1
Http3CodecUtils.criticalStreamClosed(ctx);
}
ctx.fireUserEventTriggered(evt);
}
@Override
public void channelInactive(ChannelHandlerContext ctx) {
// See https://tools.ietf.org/html/draft-ietf-quic-http-32#section-6.2.1
Http3CodecUtils.criticalStreamClosed(ctx);
ctx.fireChannelInactive();
}
@Override
void write(ChannelHandlerContext ctx, Http3ControlStreamFrame msg, ChannelPromise promise) {
if (msg instanceof Http3MaxPushIdFrame) {
sentMaxPushId = ((Http3MaxPushIdFrame) msg).id();
}
if (msg instanceof Http3GoAwayFrame) {
Http3GoAwayFrame goAwayFrame = (Http3GoAwayFrame) msg;
if (server) {
// See https://tools.ietf.org/html/draft-ietf-quic-http-32#section-5.2
long id = goAwayFrame.id();
if (id % 4 != 0) {
ReferenceCountUtil.release(msg);
promise.setFailure(new Http3Exception(Http3ErrorCode.H3_ID_ERROR,
"GOAWAY id not valid : " + id));
return;
}
if (sendGoAwayId != null && id > sendGoAwayId) {
ReferenceCountUtil.release(msg);
promise.setFailure(new Http3Exception(Http3ErrorCode.H3_ID_ERROR,
"GOAWAY id is bigger then the last sent: " + id + " > " + sendGoAwayId));
return;
}
sendGoAwayId = id;
} else {
// TODO: Add logic for the client side as well.
}
}
ctx.write(msg, promise);
}
@Override
public boolean isSharable() {
// This handle keeps state so we cant reuse it.
return false;
}
}
| 39.184615 | 111 | 0.659992 |
1cdce66f0ad30d16574d96c679f1ebc7b8792439 | 694 | package com.julianfm.wvctf.api.dto;
import java.util.Date;
import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import com.julianfm.wvctf.model.entity.Product;
import com.julianfm.wvctf.model.entity.Users;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class OrderDTO {
private Long id;
@Valid
private UserDTO users;
@Valid
private ProductDTO product;
private Date orderDate;
@Max(value = 100, message = "A order cannot have more than 100 products")
private int count;
}
| 18.756757 | 77 | 0.772334 |
4a157e9650b9927158ba0dcf0ec5522786e1b31e | 2,422 | /*
* 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.table.temptable.rpc;
import org.apache.flink.table.temptable.TableService;
/**
* Defined the message type and bytes of the message type for TableService RPC.
*/
public class TableServiceMessage {
/**
* Indicates this is a {@link TableService} getPartitions request.
*/
public static final byte GET_PARTITIONS = 1;
/**
* Indicates this is a {@link TableService} read request.
*/
public static final byte READ = 2;
/**
* Indicates this is a {@link TableService} write request.
*/
public static final byte WRITE = 3;
/**
* Indicates this is a {@link TableService} initialize partition request.
*/
public static final byte INITIALIZE_PARTITION = 4;
/**
* The bytes of GET_PARTITIONS.
*/
public static final byte[] GET_PARTITIONS_BYTES = new byte[] {1};
/**
* The bytes of READ.
*/
public static final byte[] READ_BYTES = new byte[] {2};
/**
* The bytes of WRITE.
*/
public static final byte[] WRITE_BYTES = new byte[] {3};
/**
* The bytes of INITIALIZE_PARTITION.
*/
public static final byte[] INITIALIZE_PARTITION_BYTES = new byte[] {4};
/**
* Indicates this is a successful request.
*/
public static final byte SUCCESS = 0;
/**
* Indicates this is a failed request.
*/
public static final byte FAILURE = 1;
/**
* The number of bytes of SUCCESS / FAILURE.
*/
public static final int RESPONSE_STATUS_LENGTH = 1;
/**
* The bytes of SUCCESS.
*/
public static final byte[] SUCCESS_BYTES = new byte[] { 0 };
/**
* The bytes of FAILURE.
*/
public static final byte[] FAILURE_BYTES = new byte[] { 1 };
}
| 25.765957 | 79 | 0.698183 |
58175cdff11b66d51e52be07c986de2effda7853 | 3,408 | /*******************************************************************************
*
* Copyright FUJITSU LIMITED 2018
*
* Creation Date: 13.07.2010
*
*******************************************************************************/
package org.oscm.domobjects;
import java.math.BigDecimal;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.ManyToOne;
/**
* The domain object for a stepped price.
*
* It can be attached to price models (depending on the users per subscription),
* priced events (depending on the amount of events), priced parameters
* (depending on the number of users or the parameters numeric value) and priced
* options (depending on the number of users).
*
* @author weiser
*
*/
@Entity
public class SteppedPrice extends DomainObjectWithHistory<SteppedPriceData> {
private static final long serialVersionUID = -6554156861562109586L;
@ManyToOne(optional = true, fetch = FetchType.LAZY)
private PriceModel priceModel;
@ManyToOne(optional = true, fetch = FetchType.LAZY)
private PricedEvent pricedEvent;
@ManyToOne(optional = true, fetch = FetchType.LAZY)
private PricedParameter pricedParameter;
public SteppedPrice() {
setDataContainer(new SteppedPriceData());
}
public PriceModel getPriceModel() {
return priceModel;
}
public void setPriceModel(PriceModel priceModel) {
this.priceModel = priceModel;
}
public PricedEvent getPricedEvent() {
return pricedEvent;
}
public void setPricedEvent(PricedEvent pricedEvent) {
this.pricedEvent = pricedEvent;
}
public PricedParameter getPricedParameter() {
return pricedParameter;
}
public void setPricedParameter(PricedParameter pricedParameter) {
this.pricedParameter = pricedParameter;
}
public Long getLimit() {
return dataContainer.getLimit();
}
public void setLimit(Long limit) {
this.dataContainer.setLimit(limit);
}
public BigDecimal getPrice() {
return dataContainer.getPrice();
}
public void setPrice(BigDecimal price) {
this.dataContainer.setPrice(price);
}
public BigDecimal getAdditionalPrice() {
return dataContainer.getAdditionalPrice();
}
public void setAdditionalPrice(BigDecimal additionalPrice) {
this.dataContainer.setAdditionalPrice(additionalPrice);
}
public long getFreeEntityCount() {
return dataContainer.getFreeEntityCount();
}
public void setFreeEntityCount(long freeEntityCount) {
this.dataContainer.setFreeEntityCount(freeEntityCount);
}
/**
* Copies this stepped price. The reference to the parent element has to be
* set after copying.
*
* @return the copy of this
*/
public SteppedPrice copy() {
SteppedPrice sp = new SteppedPrice();
sp.setAdditionalPrice(getAdditionalPrice());
sp.setFreeEntityCount(getFreeEntityCount());
sp.setLimit(getLimit());
sp.setPrice(getPrice());
return sp;
}
}
| 29.128205 | 83 | 0.598298 |
20b5d4d97df206b88c3673358acbafb80dcfaf51 | 5,539 | package com.tersesystems.proxyjsse.builder;
import com.tersesystems.proxyjsse.keystore.TrustStore;
import java.security.*;
import java.security.cert.CertPathParameters;
import java.util.function.Supplier;
import javax.net.ssl.CertPathTrustManagerParameters;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509ExtendedTrustManager;
import org.slieb.throwables.SupplierWithThrowable;
public class TrustManagerBuilder {
private TrustManagerBuilder() {}
public interface BuilderFinal {
X509ExtendedTrustManager build() throws Exception;
}
public interface TrustManagerFactoryStage {
ParametersStage withAlgorithm(String algorithm);
ParametersStage withAlgorithmAndProvider(String algorithm, String provider);
ParametersStage withDefaultAlgorithm();
}
static class TrustManagerFactoryStageImpl implements TrustManagerFactoryStage {
@Override
public ParametersStage withAlgorithm(String algorithm) {
return new ParametersStageImpl(() -> TrustManagerFactory.getInstance(algorithm));
}
@Override
public ParametersStage withAlgorithmAndProvider(String algorithm, String provider) {
return new ParametersStageImpl(() -> TrustManagerFactory.getInstance(algorithm, provider));
}
@Override
public ParametersStage withDefaultAlgorithm() {
return new ParametersStageImpl(
() -> TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()));
}
}
public interface ParametersStage {
BuilderFinal withKeyStore(KeyStore keyStore);
BuilderFinal withKeyStore(SupplierWithThrowable<KeyStore, Exception> keyStoreSupplier);
BuilderFinal withTrustStore(TrustStore trustStore);
BuilderFinal withTrustStore(Supplier<TrustStore> trustStore);
BuilderFinal withDefaultKeystore();
BuilderFinal withCertPathParameters(CertPathParameters parameters);
BuilderFinal withCertPathParameters(
SupplierWithThrowable<CertPathParameters, Exception> params);
}
static class ParametersStageImpl implements ParametersStage {
private final SupplierWithThrowable<TrustManagerFactory, GeneralSecurityException>
trustManagerFactory;
ParametersStageImpl(
SupplierWithThrowable<TrustManagerFactory, GeneralSecurityException> trustManagerFactory) {
this.trustManagerFactory = trustManagerFactory;
}
@Override
public BuilderFinal withKeyStore(KeyStore keyStore) {
return new BuilderFinalKeyStoreImpl(trustManagerFactory, () -> keyStore);
}
@Override
public BuilderFinal withKeyStore(SupplierWithThrowable<KeyStore, Exception> keyStoreSupplier) {
return new BuilderFinalKeyStoreImpl(trustManagerFactory, keyStoreSupplier);
}
@Override
public BuilderFinal withTrustStore(TrustStore trustStore) {
return new BuilderFinalKeyStoreImpl(trustManagerFactory, trustStore::keyStore);
}
@Override
public BuilderFinal withTrustStore(Supplier<TrustStore> trustStore) {
return new BuilderFinalKeyStoreImpl(trustManagerFactory, () -> trustStore.get().keyStore());
}
@Override
public BuilderFinal withCertPathParameters(CertPathParameters params) {
return new BuilderFinalParametersImpl(trustManagerFactory, () -> params);
}
@Override
public BuilderFinal withCertPathParameters(
SupplierWithThrowable<CertPathParameters, Exception> params) {
return new BuilderFinalParametersImpl(trustManagerFactory, params);
}
@Override
public BuilderFinal withDefaultKeystore() {
return new BuilderFinalKeyStoreImpl(
trustManagerFactory, () -> KeyStoreBuilder.defaultTrustManagerStore().build());
}
}
static class BuilderFinalKeyStoreImpl implements BuilderFinal {
private final SupplierWithThrowable<KeyStore, Exception> keyStore;
private final SupplierWithThrowable<TrustManagerFactory, GeneralSecurityException>
trustManagerFactory;
BuilderFinalKeyStoreImpl(
SupplierWithThrowable<TrustManagerFactory, GeneralSecurityException> tmf,
SupplierWithThrowable<KeyStore, Exception> keyStore) {
this.trustManagerFactory = tmf;
this.keyStore = keyStore;
}
public X509ExtendedTrustManager build() throws Exception {
TrustManagerFactory tmf = trustManagerFactory.getWithThrowable();
tmf.init(keyStore.getWithThrowable());
return (X509ExtendedTrustManager) tmf.getTrustManagers()[0];
}
}
// FIXME SunX509 trust manager does not use trust manager parameters
// FIXME only PKIX uses CertPathTrustManagerParameters
static class BuilderFinalParametersImpl implements BuilderFinal {
private final SupplierWithThrowable<CertPathParameters, Exception> parameters;
private final SupplierWithThrowable<TrustManagerFactory, GeneralSecurityException>
trustManagerFactory;
BuilderFinalParametersImpl(
SupplierWithThrowable<TrustManagerFactory, GeneralSecurityException> tmf,
SupplierWithThrowable<CertPathParameters, Exception> parameters) {
this.trustManagerFactory = tmf;
this.parameters = parameters;
}
@Override
public X509ExtendedTrustManager build() throws Exception {
TrustManagerFactory tmf = trustManagerFactory.getWithThrowable();
tmf.init(new CertPathTrustManagerParameters(parameters.getWithThrowable()));
return (X509ExtendedTrustManager) tmf.getTrustManagers()[0];
}
}
public static TrustManagerFactoryStage builder() {
return new TrustManagerFactoryStageImpl();
}
}
| 35.280255 | 99 | 0.772161 |
f090e0fcbec1caa5caa5b3778ae3f68d30afd636 | 62 | package classifyx.ui.admin;
public class AdminController {
}
| 12.4 | 30 | 0.790323 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.