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
0747a4953df75ef8b5959086afb14b1654aed637
4,898
package com.orhanobut.android.swipemenu; import android.content.Context; import android.opengl.GLES20; import android.opengl.Matrix; import javax.microedition.khronos.opengles.GL10; /** * Created by limon on 08.03.2014. */ public class TextureRenderer extends MyRenderer { public TextureRenderer(Context context) { super(context); } @Override protected void init() { float length = 0.5f; float squareVertices[] = { -length, -length, 0.0f, // V0 - bottom left -length, length, 0.0f, // V1 - top left length, -length, 0.0f, // V2 - bottom right length, length, 0.0f // V3 - top right }; // Mapping coordinates for the vertices float texture[] = { 0.0f, 1.0f, // top left (V2) 0.0f, 0.0f, // bottom left (V1) 1.0f, 1.0f, // top right (V4) 1.0f, 0.0f // bottom right (V3) }; short[] squareDrawOrder = { 0, 1, 2, // front face 2, 1, 3, }; float[] color = { 1f, 0.0f, 0.0f, 1.0f }; String vertexShader2 = RawResourceReader.readTextFileFromRawResource( getContext(), R.raw.vertex_shader_texture); String fragmentShader2 = RawResourceReader.readTextFileFromRawResource( getContext(), R.raw.fragment_shader_texture); Square s1 = new Square(squareVertices, texture, squareDrawOrder, vertexShader2, fragmentShader2); s1.setColor(color); s1.textureDataHandle = TextureHelper.loadTexture(getContext(), R.drawable.pg_capital); s1.setZ(-2.0f); s1.theta = MainCircle.FRONT; Square s2 = new Square(squareVertices, texture, squareDrawOrder, vertexShader2, fragmentShader2); s2.setColor(color); s2.setZ(2.0f); s2.textureDataHandle = TextureHelper.loadTexture(getContext(), R.drawable.pg_noncapital); s2.theta = MainCircle.BACK; Square s3 = new Square(squareVertices, texture, squareDrawOrder, vertexShader2, fragmentShader2); s3.setColor(color); s3.setX(-2.0f); s3.textureDataHandle = TextureHelper.loadTexture(getContext(), R.drawable.pg_number); s3.theta = MainCircle.RIGHT; Square s4 = new Square(squareVertices, texture, squareDrawOrder, vertexShader2, fragmentShader2); s4.setColor(color); s4.setX(2.0f); s4.textureDataHandle = TextureHelper.loadTexture(getContext(), R.drawable.pg_game); s4.theta = MainCircle.LEFT; getSquares()[0] = s3; // BACK getSquares()[1] = s4; // RIGHT getSquares()[2] = s2; // LEFT getSquares()[3] = s1; // FRONT length = 3.5f; float offset = 1.0f; float[] background = { -length, 0.0f, -length * offset, // v0 -length, 0.0f, length * offset, // v1 length, 0.0f, -length * offset, // v2 length, 0.0f, length * offset // v3 }; setBackGround(new Square(background, texture, squareDrawOrder, vertexShader2, fragmentShader2)); getBackGround().setColor(color); getBackGround().setY(-0.5f); getBackGround().textureDataHandle = TextureHelper.loadTexture(getContext(), R.drawable.floor); length = 3.9f; float depth = 1.0f; float[] backgroundBack = { -length, -length, depth, // v0 -length, length, depth, // v1 length, -length, depth, // v2 length, length, depth // v3 }; setBackgroundBack(new Square(backgroundBack, texture, squareDrawOrder, vertexShader2, fragmentShader2)); getBackgroundBack().setColor(color); getBackgroundBack().textureDataHandle = TextureHelper.loadTexture( getContext(), R.drawable.bg_back_b); } @Override public void onDrawFrame(GL10 gl) { GLES20.glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Calculate the projection and view transformation Matrix.multiplyMM(getTempMatrix(), 0, getPMatrix(), 0, getVMatrix(), 0); if (isRotating()) { update(); } else { setBuzzControl(getBuzzControl()+1); jump(); } refreshModelMatrices(); try { Thread.sleep(VELOCITY); } catch (InterruptedException e) { e.printStackTrace(); } getBackgroundBack().drawWithTexture(); getBackGround().drawWithTexture(); for (int i : getDrawOrder()) { getSquares()[i].drawWithTexture(); } setLoaded(true); } }
32.437086
83
0.5588
9af23c90c9c7bd97cc4079950e1c8c03da924fab
3,958
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package controller; import bean.UniteEnseignement; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import main.Main; /** * * @author ATH */ public class UniteEnseignementController { private final Connection connection; private PreparedStatement preparedStatement; private ResultSet resultSet; public UniteEnseignementController(Connection connection) { this.connection = connection; } public UniteEnseignementController() { this.connection = Main.getConnection(); } public void addUniteEnseignement(String sigle, String nom){ try { String req = "INSERT INTO unite_enseignements (sigle, nom) VALUES (?, ?) "; preparedStatement = connection.prepareStatement(req); preparedStatement.setString(1, sigle); preparedStatement.setString(2, nom); preparedStatement.executeUpdate(); } catch (SQLException ex) { Logger.getLogger(UniteEnseignementController.class.getName()).log(Level.SEVERE, null, ex); } } public void updateUniteEnseignement(int id, String sigle, String nom){ try { String req = "UPDATE unite_enseignements SET sigle = ?, nom = ? WHERE id = ? "; preparedStatement = connection.prepareStatement(req); preparedStatement.setString(1, sigle); preparedStatement.setString(2, nom); preparedStatement.setInt(3, id); preparedStatement.executeUpdate(); } catch (SQLException ex) { Logger.getLogger(UniteEnseignementController.class.getName()).log(Level.SEVERE, null, ex); } } public void removeUniteEnseignement(int id){ try { String req = "DELETE FROM unite_enseignements WHERE id = ? "; preparedStatement = connection.prepareStatement(req); preparedStatement.setInt(1, id); preparedStatement.executeUpdate(); } catch (SQLException ex) { Logger.getLogger(UniteEnseignementController.class.getName()).log(Level.SEVERE, null, ex); } } public UniteEnseignement getUniteEnseignement(int id_unite_enseignement){ try { String req = "SELECT * FROM unite_enseignements WHERE id = ? "; preparedStatement = connection.prepareStatement(req); preparedStatement.setInt(1, id_unite_enseignement); preparedStatement.execute(); resultSet = preparedStatement.getResultSet(); if(resultSet.next()){ return new UniteEnseignement(resultSet.getInt("id"), resultSet.getString("sigle"), resultSet.getString("nom")); } } catch (SQLException ex) { Logger.getLogger(UniteEnseignementController.class.getName()).log(Level.SEVERE, null, ex); } return null; } public ArrayList<UniteEnseignement> getUniteEnseignements(){ try { ArrayList<UniteEnseignement> list = new ArrayList<>(); String req = "SELECT * FROM unite_enseignements "; preparedStatement = connection.prepareStatement(req); preparedStatement.execute(); resultSet = preparedStatement.getResultSet(); while(resultSet.next()){ list.add(new UniteEnseignement(resultSet.getInt("id"), resultSet.getString("sigle"), resultSet.getString("nom"))); } return list; } catch (SQLException ex) { Logger.getLogger(UniteEnseignementController.class.getName()).log(Level.SEVERE, null, ex); } return null; } }
39.979798
130
0.651844
641fb835e7d79f31285a4fc728fbe1d21f9bacd0
3,245
/* * Copyright 2021 Alfresco Software, 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 org.alfresco.extension_inspector.inventory.output; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import org.alfresco.extension_inspector.model.InventoryReport; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.util.StringUtils; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; public class JSONInventoryOutput implements InventoryOutput { private static final Logger logger = LoggerFactory.getLogger(JSONInventoryOutput.class); private static final OutputType type = OutputType.JSON; private static final ObjectMapper objectMapper = new ObjectMapper(); static { objectMapper.enable(SerializationFeature.INDENT_OUTPUT); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); } private Path outputPath; public JSONInventoryOutput(String warPath, String outputPath) { this.outputPath = getNormalizedPath(warPath, outputPath); } @Override public void generateOutput(InventoryReport report) { File reportFile = outputPath.toFile(); try { FileUtils.touch(outputPath.toFile()); objectMapper.writeValue(reportFile, report); if (logger.isInfoEnabled()) { logger.info("Inventory report generated - " + reportFile.getAbsolutePath()); } } catch (IOException e) { logger.error("Failed writing report to file " + reportFile.getAbsolutePath(), e); } } private Path getNormalizedPath(String warPath, String outputPath) { if (outputPath == null) { outputPath = ""; } outputPath = outputPath.trim(); Path path = Paths.get(outputPath); if (StringUtils.isEmpty(outputPath) || FilenameUtils.getExtension(outputPath).isEmpty()) { //use default inventory report name - <alfresco-war-name>.inventory.json String warFileName = FilenameUtils.getBaseName(warPath); String defaultPath = defaultPath(warFileName, type); path = path.resolve(defaultPath); } if (logger.isDebugEnabled()) { logger.debug("Output file - " + path); } return path; } public Path getOutputPath() { return outputPath; } }
30.613208
93
0.678891
df78fc186b5a4280633715cc3ba90f4e65c92cf8
5,235
package com.devicehive.model.wrappers; /* * #%L * DeviceHive Java Server Common business logic * %% * Copyright (C) 2016 DataArt * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import com.devicehive.json.strategies.JsonPolicyDef; import com.devicehive.model.HiveEntity; import com.devicehive.model.JsonStringWrapper; import com.google.gson.annotations.SerializedName; import java.util.Date; import java.util.Optional; import static com.devicehive.json.strategies.JsonPolicyDef.Policy.*; /** * Created by tatyana on 2/12/15. */ public class DeviceCommandWrapper implements HiveEntity { private static final long serialVersionUID = 1179387574631106725L; @SerializedName("command") @JsonPolicyDef({COMMAND_FROM_CLIENT, COMMAND_TO_DEVICE, COMMAND_UPDATE_TO_CLIENT, COMMAND_UPDATE_FROM_DEVICE, POST_COMMAND_TO_DEVICE, COMMAND_LISTED}) private String command; @SerializedName("timestamp") @JsonPolicyDef({COMMAND_FROM_CLIENT, COMMAND_TO_DEVICE, COMMAND_UPDATE_TO_CLIENT, COMMAND_UPDATE_FROM_DEVICE, POST_COMMAND_TO_DEVICE, COMMAND_LISTED}) private Date timestamp; @SerializedName("parameters") @JsonPolicyDef({COMMAND_FROM_CLIENT, COMMAND_TO_DEVICE, COMMAND_UPDATE_TO_CLIENT, COMMAND_UPDATE_FROM_DEVICE, POST_COMMAND_TO_DEVICE, COMMAND_LISTED}) private JsonStringWrapper parameters; @SerializedName("lifetime") @JsonPolicyDef({COMMAND_FROM_CLIENT, COMMAND_TO_DEVICE, COMMAND_UPDATE_TO_CLIENT, COMMAND_UPDATE_FROM_DEVICE, COMMAND_LISTED}) private Integer lifetime; @SerializedName("status") @JsonPolicyDef({COMMAND_FROM_CLIENT, COMMAND_TO_DEVICE, COMMAND_UPDATE_TO_CLIENT, COMMAND_UPDATE_FROM_DEVICE, POST_COMMAND_TO_DEVICE, COMMAND_LISTED}) private String status; @SerializedName("result") @JsonPolicyDef({COMMAND_FROM_CLIENT, COMMAND_TO_DEVICE, COMMAND_UPDATE_TO_CLIENT, COMMAND_UPDATE_FROM_DEVICE, POST_COMMAND_TO_DEVICE, COMMAND_LISTED}) private JsonStringWrapper result; public Optional<String> getCommand() { return Optional.ofNullable(command); } public void setCommand(String command) { this.command = command; } public Optional<Date> getTimestamp() { return Optional.ofNullable(timestamp); } public void setTimestamp(Date timestamp) { this.timestamp = timestamp; } public Optional<JsonStringWrapper> getParameters() { return Optional.ofNullable(parameters); } public void setParameters(JsonStringWrapper parameters) { this.parameters = parameters; } public Optional<Integer> getLifetime() { return Optional.ofNullable(lifetime); } public void setLifetime(Integer lifetime) { this.lifetime = lifetime; } public Optional<String> getStatus() { return Optional.ofNullable(status); } public void setStatus(String status) { this.status = status; } public Optional<JsonStringWrapper> getResult() { return Optional.ofNullable(result); } public void setResult(JsonStringWrapper result) { this.result = result; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DeviceCommandWrapper that = (DeviceCommandWrapper) o; if (command != null ? !command.equals(that.command) : that.command != null) return false; if (lifetime != null ? !lifetime.equals(that.lifetime) : that.lifetime != null) return false; if (parameters != null ? !parameters.equals(that.parameters) : that.parameters != null) return false; if (result != null ? !result.equals(that.result) : that.result != null) return false; if (status != null ? !status.equals(that.status) : that.status != null) return false; return true; } @Override public int hashCode() { int result1 = command != null ? command.hashCode() : 0; result1 = 31 * result1 + (parameters != null ? parameters.hashCode() : 0); result1 = 31 * result1 + (lifetime != null ? lifetime.hashCode() : 0); result1 = 31 * result1 + (status != null ? status.hashCode() : 0); result1 = 31 * result1 + (result != null ? result.hashCode() : 0); return result1; } @Override public String toString() { return "DeviceCommandWrapper{" + "command='" + command + '\'' + ", parameters=" + parameters + ", lifetime=" + lifetime + ", status='" + status + '\'' + ", result=" + result + '}'; } }
33.993506
113
0.678128
74442280a932261ded4690726b5b8eb3074a44ce
527
package ofouro.code.graphql.demo.model; import lombok.*; import javax.persistence.*; import java.time.ZonedDateTime; @Entity @Data @RequiredArgsConstructor @AllArgsConstructor @NoArgsConstructor @EqualsAndHashCode(callSuper = false) public class Comment extends BaseEntity { @NonNull @Column(columnDefinition = "TEXT") private String comment; private ZonedDateTime createdOn; private String author; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "talk_id") private Talk talk; }
17.566667
41
0.745731
79edec08f19ebc6bafc573418bd3a83caee1c806
1,863
package br.ufes.inf.ontoumlplugin.model; import com.vp.plugin.model.IStereotype; import com.vp.plugin.model.IProject; import com.vp.plugin.model.IModelElement; import com.vp.plugin.model.factory.IModelElementFactory; public enum OntoUMLClassType { KIND("Kind"), COLLECTIVE("Collective"), QUANTITY("Quantity"), SUBKIND("SubKind"), ROLE("Role"), PHASE("Phase"), ROLEMIXIN("RoleMixin"), CATEGORY("Category"), MIXIN("Mixin"), RELATOR("Relator"), MODE("Mode"), QUALITY("Quality"), DATA_TYPE("DataType"), PERCEIVABLE_QUALITY("PerceivableQuality"), NON_PERCEIVABLE_QUALITY("NonPerceivableQuality"), NOMINAL_QUALITY("NominalQuality"), ENUMERATION("enumeration"), PRIMITIVE_TYPE("primitive"); private String text; OntoUMLClassType(String text){ this.text = text; } public String getText(){ return text; } public static OntoUMLClassType fromString(String text) { for (OntoUMLClassType b : OntoUMLClassType.values()) { if (b.text.equalsIgnoreCase(text)) { return b; } } return SUBKIND; } public static IStereotype getStereotypeFromString(IProject project, String text){ IModelElement[] stereotypes = project.toModelElementArray(IModelElementFactory.MODEL_TYPE_STEREOTYPE); for(IModelElement e : stereotypes){ IStereotype s = (IStereotype) e; if(s.getBaseType().equals(IModelElementFactory.MODEL_TYPE_CLASS) && s.getName().equalsIgnoreCase(text)){ return s; } } return null; } public static boolean doesProjectHaveStereotype(IProject project, String text) { IModelElement[] stereotypes = project.toModelElementArray(IModelElementFactory.MODEL_TYPE_STEREOTYPE); for(IModelElement e : stereotypes){ IStereotype s = (IStereotype) e; if(s.getBaseType().equals(IModelElementFactory.MODEL_TYPE_CLASS) && s.getName().equalsIgnoreCase(text)){ return true; } } return false; } }
32.12069
142
0.745035
3293c5fedeceea00281302d969e2f08cd766e61e
5,932
package com.sap.mlt.xliff12.impl.persistence; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.xml.XMLConstants; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.OutputKeys; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMResult; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; import javax.xml.validation.Validator; import org.w3c.dom.Document; import org.xml.sax.SAXException; import com.sap.mlt.xliff12.api.element.toplevel.Xliff; import com.sap.mlt.xliff12.api.exception.SerializationException; import com.sap.mlt.xliff12.api.persistence.XliffSerializer; import com.sap.mlt.xliff12.impl.schema.Schemas; import com.sap.mlt.xliff12.impl.util.Assert; public final class XliffSerializerImpl implements XliffSerializer { private static final XliffSerializerImpl INSTANCE = new XliffSerializerImpl(); public static XliffSerializerImpl getInstance() { return INSTANCE; } private XliffSerializerImpl() { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); factory.setSchema(Schemas.getXLIFF12TransitionalSchema()); try { factory.setFeature("http://xml.org/sax/features/external-general-entities", false); factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); builder = factory.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new IllegalStateException( "There is an internal problem with the XML-parser configuration.", e); } Schema schema = Schemas.getXLIFF12TransitionalSchema(); validator = schema.newValidator(); final InputStream resourceAsStream = getClass().getResourceAsStream("pretty_print_indent.xsl"); try { Source prettyPrintIndentTemplate = new StreamSource(resourceAsStream); final TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); transformerFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); prettyPrintIndentTransformer = transformerFactory .newTransformer(prettyPrintIndentTemplate); prettyPrintIndentTransformer.setOutputProperty(OutputKeys.INDENT, "no"); nullTransformer = transformerFactory.newTransformer(); nullTransformer.setOutputProperty(OutputKeys.INDENT, "no"); } catch (TransformerConfigurationException e) { throw new IllegalStateException( "There is an internal problem with the XML configuration.", e); } finally { try { resourceAsStream.close(); } catch (IOException e) { // ignore IOException during close } } } private DocumentBuilder builder; private Validator validator; private Transformer nullTransformer; private Transformer prettyPrintIndentTransformer; public void serialize(Xliff xliff, File file) throws SerializationException { serialize(xliff, file, ""); } public void serialize(Xliff xliff, File file, String indentation) throws SerializationException { Assert.notNull(xliff, "xliff"); Assert.notNull(file, "file"); FileOutputStream os = null; try { os = new FileOutputStream(file); serialize(xliff, os, indentation); os.close(); os = null; } catch (IOException e) { throw new SerializationException(e); } finally { if (os != null) { try { os.close(); } catch (IOException e) { // $JL-EXC$ } } } } public void serialize(Xliff xliff, OutputStream os) throws SerializationException { serialize(xliff, os, ""); } public synchronized void serialize(Xliff xliff, OutputStream os, String indentation) throws SerializationException { Assert.notNull(xliff, "xliff"); Assert.notNull(os, "os"); Assert.notNull(indentation, "indentation"); int il = indentation.length(); for (int i = 0; i < il; ++i) { char ch = indentation.charAt(i); if ((ch != ' ') && (ch != '\t')) { throw new IllegalArgumentException( "The parameter 'indentation' must contain spaces and tabulators only"); } } Document document = builder.newDocument(); document.appendChild(xliff.asXmlNode(document)); // We will do a "null"-transform first to avoid issues with missing // attribute-prefixes DOMSource domSource = new DOMSource(document); DOMResult domResult = new DOMResult(); try { nullTransformer.transform(domSource, domResult); } catch (TransformerException e) { throw new SerializationException("Could not write the XLIFF", e); } // Now we will perform the actual transformation on the "clean" DOM domSource = new DOMSource(domResult.getNode()); // Check if the DOM is valid according to the schema try { validator.validate(domSource); } catch (SAXException e) { throw new SerializationException( "The passed XLIFF file is invalid. Check underlying exception for details.", e); } catch (IOException e) { // $JL-EXC$ } StreamResult streamResult = new StreamResult(os); try { prettyPrintIndentTransformer.setParameter("indentsequence", indentation); prettyPrintIndentTransformer.transform(domSource, streamResult); } catch (TransformerException e) { throw new SerializationException("Could not write the XLIFF", e); } } }
33.325843
98
0.731457
c830c7bf604b75e8c2536a2719d86060061307f1
727
package org.infinispan.client.rest; import java.util.concurrent.CompletionStage; /** * @author Tristan Tarrant &lt;[email protected]&gt; * @since 10.0 **/ public interface RestServerClient { CompletionStage<RestResponse> configuration(); CompletionStage<RestResponse> stop(); CompletionStage<RestResponse> threads(); CompletionStage<RestResponse> info(); CompletionStage<RestResponse> memory(); CompletionStage<RestResponse> env(); CompletionStage<RestResponse> ignoreCache(String cacheManagerName, String cacheName); CompletionStage<RestResponse> unIgnoreCache(String cacheManagerName, String cacheName); CompletionStage<RestResponse> listIgnoredCaches(String cacheManagerName); }
25.964286
90
0.782669
770a1e2296db812467969ed80af2095cf189d745
3,881
/* * The MIT License (MIT) * Copyright (c) 2011-2014 Turenai Project * * 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 jp.mydns.turenar.twclient.init.tree; import java.util.AbstractList; import java.util.Arrays; import java.util.NoSuchElementException; import java.util.RandomAccess; /** * List which contains TreeInitInfo. * * <p> * This class should be called as follow statement. * </p> * <p> * Phase Init: You should call {@link #add(TreeInitInfoBase)}. If you want to retrieve next info to init, * You can call {@link #rebuild()} and {@link #next()} * </p> * <p> * Phase UnInit: You can call {@link #prev()}. You must not call {@link #add(TreeInitInfoBase)} and {@link #next()}. * {@link #rebuild()} have no effect. * </p> * * @author Turenar (snswinhaiku dot lo at gmail dot com) */ /*package*/ class TreeInfoList extends AbstractList<TreeInitInfoBase> implements RandomAccess { private TreeInitInfoBase[] objects; private int tableSize; private int size; private int finishedIndex; /** * make instance */ public TreeInfoList() { tableSize = 16; objects = new TreeInitInfoBase[tableSize]; } @Override public boolean add(TreeInitInfoBase treeInitInfo) { if (tableSize == 0) { throw new IllegalStateException(); // prev called } if (contains(treeInitInfo)) { return false; } if (size >= tableSize) { TreeInitInfoBase[] oldTable = objects; objects = new TreeInitInfoBase[tableSize <<= 1]; System.arraycopy(oldTable, 0, objects, 0, size); } objects[size++] = treeInitInfo; return true; } @Override public TreeInitInfoBase get(int index) { if (tableSize == 0) { throw new IllegalStateException(); } else if (index < 0 || index >= size) { throw new NoSuchElementException(); } return objects[index]; } /** * get next info to init which all dependencies are resolved. * * @return info or null */ public TreeInitInfoBase next() { if (finishedIndex >= size) { return null; } TreeInitInfoBase next = get(finishedIndex); if (next.isAllDependenciesResolved()) { finishedIndex++; return next; } else { return null; } } /** * next work index * * @return next index */ public int nowIndex() { return finishedIndex; } /** * get info to uninit * * @return info or null */ public TreeInitInfoBase prev() { if (finishedIndex <= 0) { return null; } tableSize = 0; return objects[--finishedIndex]; } /** * sort all info which doesn't not retrieved. This function affects {@link #next()} but {@link #prev()} */ public void rebuild() { for (int i = finishedIndex; i < size; i++) { objects[i].update(); } Arrays.sort(objects, finishedIndex, size); } @Override public int size() { return size; } /** * revert next() */ public void unnext() { --finishedIndex; } }
26.04698
116
0.686936
52ac9b49c85738f78f54dfb83a18997004a4261f
1,020
package com.dreamcc.orm.dataobject; import com.baomidou.mybatisplus.annotation.FieldFill; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import lombok.Data; import java.io.Serializable; import java.util.Date; /** * @author cloud-cc * @ClassName ProfilePO * @Description 模板数据库存储类 * @date 2021/12/1 09:11 * @Version 1.0 */ @Data @TableName("vms_iot_profile") public class ProfileDO implements Serializable { /** * id */ @TableId private Long id; /** * 模板名称 */ private String name; /** * 是否可用 */ private Integer enable; /** * 描述 */ private String description; /** * 创建时间 */ @TableField(fill = FieldFill.INSERT) private Date createTime; /** * 更新时间 */ @TableField(fill = FieldFill.INSERT_UPDATE) private Date updateTime; /** * 逻辑删除符 */ private Integer deleted; }
18.545455
54
0.640196
d8c03742b189a4c311092d732acb0c0ba4706225
3,042
package org.datazup.expression; import java.util.*; /** * Created by admin@datazup on 3/14/16. */ public class Parameters { private String functionSeparator; private final List<Operator> operators = new ArrayList(); private final List<Function> functions = new ArrayList(); private final List<Constant> constants = new ArrayList(); private final Map<String, String> translations = new HashMap(); private final List<BracketPair> expressionBrackets = new ArrayList(); private final List<BracketPair> functionBrackets = new ArrayList(); public Parameters() { this.setFunctionArgumentSeparator(','); } public Collection<Operator> getOperators() { return this.operators; } public Collection<Function> getFunctions() { return this.functions; } public Collection<Constant> getConstants() { return this.constants; } public Collection<BracketPair> getExpressionBrackets() { return this.expressionBrackets; } public Collection<BracketPair> getFunctionBrackets() { return this.functionBrackets; } public void addOperators(Collection<Operator> operators) { this.operators.addAll(operators); } public void add(Operator operator) { this.operators.add(operator); } public void addFunctions(Collection<Function> functions) { this.functions.addAll(functions); } public void add(Function function) { this.functions.add(function); } public void addConstants(Collection<Constant> constants) { this.constants.addAll(constants); } public void add(Constant constant) { this.constants.add(constant); } public void addExpressionBracket(BracketPair pair) { this.expressionBrackets.add(pair); } public void addExpressionBrackets(Collection<BracketPair> brackets) { this.expressionBrackets.addAll(brackets); } public void addFunctionBracket(BracketPair pair) { this.functionBrackets.add(pair); } public void addFunctionBrackets(Collection<BracketPair> brackets) { this.functionBrackets.addAll(brackets); } public void setTranslation(Function function, String translatedName) { this.setTranslation(function.getName(), translatedName); } public void setTranslation(Constant constant, String translatedName) { this.setTranslation(constant.getName(), translatedName); } private void setTranslation(String name, String translatedName) { this.translations.put(name, translatedName); } public String getTranslation(String originalName) { String translation = (String)this.translations.get(originalName); return translation == null?originalName:translation; } public void setFunctionArgumentSeparator(char separator) { this.functionSeparator = new String(new char[]{separator}); } public String getFunctionArgumentSeparator() { return this.functionSeparator; } }
28.429907
74
0.693951
f2b4ecc333357454625206cac76e5b8b77292734
417
package dev7.id.sidausappspublic.Server; import dev7.id.sidausappspublic.Model.User; import retrofit2.Call; import retrofit2.http.Field; import retrofit2.http.FormUrlEncoded; import retrofit2.http.Headers; import retrofit2.http.POST; public interface UserInterface { @FormUrlEncoded @POST("api_token_auth/") Call<User> login (@Field("username") String username, @Field("password") String password); }
24.529412
94
0.776978
fb68210665f65697690c4c6b5ae60273ba11ccf2
1,306
package com.videolibrary.metadata; /** * Created with Android Studio. * Title:LiveTypeConstans * Description: * Copyright:Copyright (c) 2016 * Company:quanyan * Author:赵晓坡 * Date:9/13/16 * Time:18:58 * Version 1.1.0 */ public class LiveTypeConstants { /** * 达人创建直播 */ public static final String CREATE_LIVE = "CREATE_LIVE"; /** * 正在直播 */ public static final String LIVE_ING = "START_LIVE"; /** * 直播正在关闭 */ public static final String CLOSING_LIVE = "CLOSING_LIVE"; /** * 结束直播 */ public static final String LIVE_OVER = "END_LIVE"; /** * 直播在回放状态 */ public static final String LIVE_REPLAY = "REPLAY_LIVE"; /** * 无效直播,一定时间内未推流 */ public static final String LIVE_INVALID = "INVALID_LIVE"; /** * 直播记录状态 删除 */ public static final String DELETE_LIVE = "DELETE_LIVE"; /** * 直播记录状态 下架 */ public static final String OFF_SHELVE_LIVE = "OFF_SHELVE_LIVE"; /** * 直播记录状态 正常 */ public static final String NORMAL_LIVE = "NORMAL_LIVE"; public static final String FOLLOW_STATE_SUCCESS = "FOLLOW_SUCCESS"; public static final String FOLLOW_STATE_FAILED = "FOLLOW_FAILED"; public static final String FOLLOW_STATE_ALREADY = "HAS_FOLLOW"; }
21.766667
71
0.630168
31b24b8345218e1e00f47029ef3574848e780131
508
package webshop.products; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import com.fasterxml.jackson.annotation.JsonProperty; import io.dropwizard.Configuration; public class ServiceConfiguration extends Configuration { @NotNull @Min(1) private long defaultCategoryId = 1; @JsonProperty public void setDefaultCategoryId(long id) { this.defaultCategoryId = id; } @JsonProperty public long getDefaultCategoryId() { return this.defaultCategoryId; } }
19.538462
57
0.797244
2c9fc9d562f3562a7ff29c5b863f7fbdece8b285
729
package control; /* * While loops whit "labeled break" and "labeled continue" * */ public class LabeledWhile { public static void main(String [] args) { int i = 0; outer: while(true) { System.out.println("Outer while loop"); while(true) { i ++; System.out.println("i = " + i); if (i == 1) { System.out.println("continue"); continue; } if (i == 3) { System.out.println("continue outer"); continue outer; } if( i == 5) { System.out.println("break"); break; } if( i == 7) { System.out.println("break outer"); break outer; } } } } }
16.568182
59
0.466392
85fb092cfd59908eb43e0f13c225d63a0555d854
4,553
package com.ontologycentral.ldspider.any23; import java.net.URISyntaxException; import java.util.logging.Logger; import org.apache.any23.extractor.ExtractionContext; import org.apache.any23.writer.TripleHandler; import org.apache.any23.writer.TripleHandlerException; import org.openrdf.model.BNode; import org.openrdf.model.Literal; import org.openrdf.model.Resource; import org.openrdf.model.URI; import org.openrdf.model.Value; import org.semanticweb.yars.nx.Node; import org.semanticweb.yars.nx.parser.Callback; import org.semanticweb.yars.nx.util.NxUtil; /** * @author Tobias Kaefer */ public class CallbackNQuadTripleHandler implements TripleHandler { Logger _log = Logger.getLogger(CallbackNQuadTripleHandler.class.getName()); private Callback _cb; public CallbackNQuadTripleHandler(Callback callback) { _cb = callback; } /** * Receive triple in openrdf's classes, convert it to NxParser's classes * and process it in the callback. */ public void receiveTriple(Resource arg0, URI arg1, Value arg2, URI arg3, ExtractionContext arg4) throws TripleHandlerException { Node subj = null, pred = null, obj = null; org.semanticweb.yars.nx.Resource cont = null; cont = convert(arg4.getDocumentURI()); if (arg0 instanceof URI) subj = convert((URI) arg0); else if (arg0 instanceof BNode) subj = convert((BNode) arg0, cont); pred = convert(arg1); if (arg2 instanceof URI) obj = convert((URI) arg2); else if (arg2 instanceof Literal) obj = convert((Literal) arg2); else if (arg2 instanceof BNode) obj = convert((BNode) arg2, cont); Node[] nx = { subj, pred, obj, cont }; for (Node n : nx) if (n == null) { throw new TripleHandlerException( "Error while receiving triple: " + arg0.stringValue() + " " + arg1.stringValue() + " " + arg2.stringValue() + " " + arg3.stringValue() + " . Context was: " + arg4.getDocumentURI() + " . Dropping statement."); } _cb.processStatement(nx); } private org.semanticweb.yars.nx.Resource convert(org.openrdf.model.URI arg0) throws TripleHandlerException { java.net.URI uri; org.semanticweb.yars.nx.Resource res; try { uri = new java.net.URI(arg0.stringValue()); res = new org.semanticweb.yars.nx.Resource( NxUtil.escapeForNx(new java.net.URI(uri.getScheme(), uri .getAuthority(), uri.getPath(), uri.getQuery(), uri .getFragment()).toString())); } catch (URISyntaxException e) { res = new org.semanticweb.yars.nx.Resource(NxUtil.escapeForNx(arg0 .stringValue())); } return res; } /** * Converting a BNode. Context required for NxParser's BNode creation code. * * @param arg0 * the BNode in openrdf type hierarchy * @param context * the context in which the BNode has been encountered. * @return the BNode in NxParser's terms */ private org.semanticweb.yars.nx.BNode convert(BNode arg0, org.semanticweb.yars.nx.Resource context) throws TripleHandlerException { return org.semanticweb.yars.nx.BNode.createBNode(context.toN3() .substring(1, context.toN3().length() - 1), arg0.stringValue()); } private org.semanticweb.yars.nx.Literal convert(Literal arg0) throws TripleHandlerException{ String value = NxUtil.escapeForNx(arg0.getLabel()); String language = null; org.semanticweb.yars.nx.Resource datatype = null; if (arg0.getDatatype() != null) datatype = convert(arg0.getDatatype()); language = arg0.getLanguage(); try { return new org.semanticweb.yars.nx.Literal(value, language, datatype); } catch (IllegalArgumentException e) { _log.warning("Something fishy in the following Literal: " + arg0 + " Exception caught: " + e.getMessage()); return null; } } @Override public void close() throws TripleHandlerException { ; } @Override public void closeContext(ExtractionContext arg0) throws TripleHandlerException { ; } @Override public void endDocument(URI arg0) throws TripleHandlerException { ; } @Override public void openContext(ExtractionContext arg0) throws TripleHandlerException { ; } @Override public void receiveNamespace(String arg0, String arg1, ExtractionContext arg2) throws TripleHandlerException { ; } @Override public void setContentLength(long arg0) { ; } @Override public void startDocument(URI arg0) throws TripleHandlerException { ; } }
28.63522
94
0.686141
fc4b02d04fb0d5471af8f4aa18f43562294cf59b
6,773
/* * Copyright 2010-2013 Ning, Inc. * * Ning 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.killbill.billing.entitlement.engine.core; import java.util.UUID; import org.killbill.billing.entitlement.api.BlockingStateType; import org.killbill.notificationq.api.NotificationEvent; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; public class BlockingTransitionNotificationKey implements NotificationEvent { private final UUID blockingStateId; private final UUID blockableId; private final BlockingStateType blockingType; private final Boolean isTransitionToBlockedBilling; private final Boolean isTransitionToUnblockedBilling; private final Boolean isTransitionToBlockedEntitlement; private final Boolean isTransitionToUnblockedEntitlement; @JsonCreator public BlockingTransitionNotificationKey(@JsonProperty("blockingStateId") final UUID blockingStateId, @JsonProperty("blockableId") final UUID blockableId, @JsonProperty("type") final BlockingStateType blockingType, @JsonProperty("isTransitionToBlockedBilling") final Boolean isTransitionToBlockedBilling, @JsonProperty("isTransitionToUnblockedBilling") final Boolean isTransitionToUnblockedBilling, @JsonProperty("isTransitionToBlockedEntitlement") final Boolean isTransitionToBlockedEntitlement, @JsonProperty("isTransitionToUnblockedEntitlement") final Boolean isTransitionToUnblockedEntitlement) { this.blockingStateId = blockingStateId; this.blockableId = blockableId; this.blockingType = blockingType; this.isTransitionToBlockedBilling = isTransitionToBlockedBilling; this.isTransitionToUnblockedBilling = isTransitionToUnblockedBilling; this.isTransitionToBlockedEntitlement = isTransitionToBlockedEntitlement; this.isTransitionToUnblockedEntitlement = isTransitionToUnblockedEntitlement; } public UUID getBlockingStateId() { return blockingStateId; } public UUID getBlockableId() { return blockableId; } public BlockingStateType getBlockingType() { return blockingType; } @JsonProperty("isTransitionToBlockedBilling") public Boolean isTransitionedToBlockedBilling() { return isTransitionToBlockedBilling; } @JsonProperty("isTransitionToUnblockedBilling") public Boolean isTransitionedToUnblockedBilling() { return isTransitionToUnblockedBilling; } @JsonProperty("isTransitionToBlockedEntitlement") public Boolean isTransitionedToBlockedEntitlement() { return isTransitionToBlockedEntitlement; } @JsonProperty("isTransitionToUnblockedEntitlement") public Boolean isTransitionToUnblockedEntitlement() { return isTransitionToUnblockedEntitlement; } @Override public String toString() { final StringBuilder sb = new StringBuilder("BlockingTransitionNotificationKey{"); sb.append("blockingStateId=").append(blockingStateId); sb.append(", blockableId=").append(blockableId); sb.append(", blockingType=").append(blockingType); sb.append(", isTransitionToBlockedBilling=").append(isTransitionToBlockedBilling); sb.append(", isTransitionToUnblockedBilling=").append(isTransitionToUnblockedBilling); sb.append(", isTransitionToBlockedEntitlement=").append(isTransitionToBlockedEntitlement); sb.append(", isTransitionToUnblockedEntitlement=").append(isTransitionToUnblockedEntitlement); sb.append('}'); return sb.toString(); } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final BlockingTransitionNotificationKey that = (BlockingTransitionNotificationKey) o; if (blockingStateId != null ? !blockingStateId.equals(that.blockingStateId) : that.blockingStateId != null) { return false; } if (blockableId != null ? !blockableId.equals(that.blockableId) : that.blockableId != null) { return false; } if (blockingType != that.blockingType) { return false; } if (isTransitionToBlockedBilling != null ? !isTransitionToBlockedBilling.equals(that.isTransitionToBlockedBilling) : that.isTransitionToBlockedBilling != null) { return false; } if (isTransitionToBlockedEntitlement != null ? !isTransitionToBlockedEntitlement.equals(that.isTransitionToBlockedEntitlement) : that.isTransitionToBlockedEntitlement != null) { return false; } if (isTransitionToUnblockedBilling != null ? !isTransitionToUnblockedBilling.equals(that.isTransitionToUnblockedBilling) : that.isTransitionToUnblockedBilling != null) { return false; } if (isTransitionToUnblockedEntitlement != null ? !isTransitionToUnblockedEntitlement.equals(that.isTransitionToUnblockedEntitlement) : that.isTransitionToUnblockedEntitlement != null) { return false; } return true; } @Override public int hashCode() { int result = blockingStateId != null ? blockingStateId.hashCode() : 0; result = 31 * result + (blockableId != null ? blockableId.hashCode() : 0); result = 31 * result + (blockingType != null ? blockingType.hashCode() : 0); result = 31 * result + (isTransitionToBlockedBilling != null ? isTransitionToBlockedBilling.hashCode() : 0); result = 31 * result + (isTransitionToUnblockedBilling != null ? isTransitionToUnblockedBilling.hashCode() : 0); result = 31 * result + (isTransitionToBlockedEntitlement != null ? isTransitionToBlockedEntitlement.hashCode() : 0); result = 31 * result + (isTransitionToUnblockedEntitlement != null ? isTransitionToUnblockedEntitlement.hashCode() : 0); return result; } }
45.456376
193
0.700281
ff4daa89cea17a424d0a1876934489e3bee44d2e
274
package us.fjj.spring.learning.conditionalannotationusage.test3; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; @Configuration @Import({BeanConfig1.class, BeanConfig2.class}) public class MainConfig3 { }
27.4
64
0.843066
4f5c4c9a8e26d2d6acba270c7d41291f11f6d63a
481
package com.darkyen.nbtapi.nbt; /** * */ public final class NBTDouble extends NBTBase { public final double value; public NBTDouble(double value) { this.value = value; } @Override public String toString() { return getClass().getSimpleName() + "[" + value + "]"; } @Override public boolean equals(Object obj) { return obj.getClass() == getClass() && this.value == ((com.darkyen.nbtapi.nbt.NBTDouble) obj).value; } }
20.913043
108
0.609148
fb20aa4d3aca1df71a6e6a4245f043d055831d15
404
package org.prebid.server.bidder.model; import io.vertx.core.MultiMap; import io.vertx.core.http.HttpMethod; import lombok.AllArgsConstructor; import lombok.Value; /** * Packages together the fields needed to make an http request. */ @AllArgsConstructor(staticName = "of") @Value public class AdapterHttpRequest<T> { HttpMethod method; String uri; T payload; MultiMap headers; }
16.833333
63
0.740099
8739638d3db7e01cf3ee203aef6e781857258221
2,882
/* * Copyright 2008/2011 Mohawk College of Applied Arts and Technology * * 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. * * User: Jaspinder Singh * Date: 06-28-2011 */ package org.marc.everest.datatypes; import org.marc.everest.interfaces.IEnumeratedVocabulary; /** * Identifies how an address can be used. */ public enum PostalAddressUse implements IEnumeratedVocabulary { /** * A communication address at a home, attempted contacts for business purposes. */ HomeAddress("H", null), /** * The primary home to reach a person after business hours. */ PrimaryHome("HP", null), /** * A vacation home. */ VacationHome("HV", null), /** * An office address. */ WorkPlace("WP", null), /** * Indicates a work place address or a telecommunication address. */ Direct("DIR", null), /** * Indicates a work place address or telecommunication address that is a standard. */ Public("PUB", null), /** * A flag indicating that the address is bad. */ BadAddress("BAD", null), /** * Used primarily to visit an address. */ PhysicalVisit("PHYS", null), /** * Used to send mail. */ PostalAddress("PST", null), /** * A temporary address may be good for visit or mailing. */ TemporaryAddress("TMP", null), /** * Alphabetic transcription. */ Alphabetic("ABC", null), /** * Address as understood by the datacentre. */ Ideographic("IDE", null), /** * Syllabic translation of the address. */ Syllabic("SYL", null), /** * An address spelled according to the soundex algorithm. */ Soundex("SNDX", null), /** The address as understood by the datacentre. */ Phonetic("PHON", null); /** * Instantiates a new postal address use. * * @param code the code * @param codeSystem the code system */ private PostalAddressUse(String code, String codeSystem) { CODE = code; CODE_SYSTEM = codeSystem; } /** * Code. */ private final String CODE; /** * Code System. */ private final String CODE_SYSTEM; /** * Gets the code. * * @return the string */ public String getCode() { return CODE; } /** * Gets the code system. * * @return the code system */ public String getCodeSystem() { return CODE_SYSTEM; } /** * Represent as a string */ @Override public String toString() { return this.getCode(); } }
18.474359
83
0.655448
5bf028204c1a64d1f741f1c59cc1633d2ead7d73
54
package test.bank; public class NationalBankTest { }
10.8
31
0.777778
0e9c26307f74d55bbe412539492a371fb63b8b98
14,291
package com.logicartisan.common.core.thread; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicBoolean; /** * */ class SharedThreadPoolImpl implements ScheduledExecutor { private static final Logger LOG = LoggerFactory.getLogger( SharedThreadPool.class ); private static final long THREAD_CACHE_TIME = Long.getLong( "common.sharedthreadpool.cache_time", 60000 ).longValue(); private static final long LONG_TASK_ALERT_TIME_NANOS = TimeUnit.MILLISECONDS.toNanos( Long.getLong( "common.sharedthreadpool.long_task_notify_ms", 60000 ).longValue() ); // To handle scheduling but still use just a caching thread pool (i.e., unbounded // growth, etc.), a single thread pool is used for scheduling. That pool simply starts // a task in the main thread pool so they always return immediately. private final ScheduledThreadPoolExecutor schedule_executor; private final ExecutorService main_executor; SharedThreadPoolImpl() { schedule_executor = new ScheduledThreadPoolExecutor( 1, new NamingThreadFactory( "SharedThreadPool Scheduler" ) ); // No queue, no max size, cache for specified time // // This executor has two real customizations: // 1) The thread creator creates threads that are instances of NameStoringThread // 2) After execution is complete, the "restoreOriginalName" method is called // on the NameStoringThread instances. // This allows tasks to change the name of their thread (for easier debugging) // and the name of the thread will automatically be reset when the test is // complete. main_executor = new ThreadPoolExecutor( 0, Integer.MAX_VALUE, THREAD_CACHE_TIME, TimeUnit.MILLISECONDS, new SynchronousQueue<>(), new STPTrackerThreadFactory( "SharedThreadPool Worker-" ) ) { @Override protected void beforeExecute( Thread t, Runnable r ) { ( ( STPTrackerThread ) t ).recordTaskStartTime(); super.beforeExecute( t, r ); } @Override protected void afterExecute( Runnable r, @Nullable Throwable t ) { STPTrackerThread thread = ( STPTrackerThread ) Thread.currentThread(); long duration = System.nanoTime() - thread.getTaskStartTime(); // Restore the name to the calling thread (which is the one that executed // the task. String custom_name = thread.restoreOriginalName(); // Alert of long-running tasks if ( LONG_TASK_ALERT_TIME_NANOS > 0 && duration >= LONG_TASK_ALERT_TIME_NANOS ) { LOG.info( "The following task ran long ({} ms) on the " + "SharedThreadPool{}: {}", TimeUnit.NANOSECONDS.toMillis( duration ), custom_name == null ? "" : " (thread name was \"" + custom_name + "\")", r ); } // Ensure exceptions are noted if the runnable was wrapped in a Future. // See ThreadPoolExecutor.afterExecute docs for the origin of this code. if ( t == null && r instanceof Future<?> && ( ( Future<?> ) r ).isDone() ) { try { ( ( Future<?> ) r ).get(); } catch ( CancellationException ce ) { t = ce; } catch ( ExecutionException ee ) { t = ee.getCause(); } catch ( InterruptedException ie ) { // ignore/reset Thread.currentThread().interrupt(); } } if ( t != null ) { LOG.warn( "The following task encountered an uncaught exception on " + "the SharedThreadPool{} after running for {} ms: {}", custom_name == null ? "" : " (thread name was \"" + custom_name + "\")", TimeUnit.NANOSECONDS.toMillis( duration ), r, t ); } super.afterExecute( r, t ); } }; } /** * See {@link Executor#execute(Runnable)}. */ public void execute( @Nonnull Runnable command ) { LOG.trace( "Execute: {}", command ); main_executor.submit( command ); } /** * See {@link ScheduledExecutorService#schedule(Callable, long, TimeUnit)} */ public <V> ScheduledFuture<V> schedule( Callable<V> callable, long delay, TimeUnit unit ) { if ( LOG.isTraceEnabled() ) { LOG.trace( "Schedule: {} at delay={} {}", callable, Long.valueOf( delay ), unit ); } HandoffScheduledFuture<V> handoff_future = new HandoffScheduledFuture<>(); Callable<V> wrapper = new HandoffCallable<>( callable, handoff_future, main_executor ); ScheduledFuture<V> schedule_future = schedule_executor.schedule( wrapper, delay, unit ); handoff_future.init( schedule_future ); return handoff_future; } /** * See {@link ScheduledExecutorService#schedule(Runnable, long, TimeUnit)} */ @SuppressWarnings( { "unchecked" } ) public ScheduledFuture<?> schedule( Runnable command, long delay, TimeUnit unit ) { if ( LOG.isTraceEnabled() ) { LOG.trace( "Schedule: {} at delay={} {}", command, Long.valueOf( delay ), unit ); } HandoffScheduledFuture<?> handoff_future = new HandoffScheduledFuture<Void>(); Runnable wrapper = new HandoffRunnable( command, handoff_future, main_executor ); ScheduledFuture schedule_future = schedule_executor.schedule( wrapper, delay, unit ); handoff_future.init( schedule_future ); return handoff_future; } /** * See {@link ScheduledExecutorService#scheduleAtFixedRate(Runnable, long, long, TimeUnit)} */ @SuppressWarnings( { "unchecked" } ) public ScheduledFuture<?> scheduleAtFixedRate( Runnable command, long initialDelay, long period, TimeUnit unit ) { if ( LOG.isTraceEnabled() ) { LOG.trace( "Schedule at fixed rate: {} at initialDelay={} period={} {}", command, Long.valueOf( initialDelay ), Long.valueOf( period ), unit ); } HandoffScheduledFuture<?> handoff_future = new HandoffScheduledFuture<Void>(); Runnable wrapper = new PreventConcurrentRunHandoffRunnable( command, handoff_future, main_executor ); ScheduledFuture schedule_future = schedule_executor.scheduleAtFixedRate( wrapper, initialDelay, period, unit ); handoff_future.init( schedule_future ); return handoff_future; } /** * See {@link ScheduledExecutorService#scheduleWithFixedDelay(Runnable, long, long, TimeUnit)} */ @SuppressWarnings( { "unchecked" } ) public ScheduledFuture<?> scheduleWithFixedDelay( Runnable command, long initialDelay, long delay, TimeUnit unit ) { if ( LOG.isTraceEnabled() ) { LOG.trace( "Schedule with fixed delay: {} at initialDelay={} delay={} {}", command, Long.valueOf( initialDelay ), Long.valueOf( delay ), unit ); } // NOTE: since the scheduled execution service is disconnected from the actual // running of the task, this method is a bit trickier to implement. When the // task is finished running, it needs to be re-scheduled for one-time // execution. RescheduleWrapperRunnable reschedule_wrapper = new RescheduleWrapperRunnable( command, delay, unit, schedule_executor ); HandoffScheduledFuture<?> handoff_future = new HandoffScheduledFuture<Void>(); HandoffRunnable wrapper = new HandoffRunnable( reschedule_wrapper, handoff_future, main_executor ); reschedule_wrapper.initHandoffRunnable( wrapper, handoff_future ); ScheduledFuture schedule_future = schedule_executor.schedule( wrapper, initialDelay, unit ); handoff_future.init( schedule_future ); return handoff_future; } private static class RescheduleWrapperRunnable implements Runnable { private final Runnable delegate; private final long delay; private final TimeUnit unit; private final ScheduledThreadPoolExecutor schedule_executor; private HandoffRunnable handoff_runnable; private HandoffScheduledFuture<?> handoff_future; RescheduleWrapperRunnable( Runnable delegate, long delay, TimeUnit unit, ScheduledThreadPoolExecutor schedule_executor ) { this.delegate = delegate; this.delay = delay; this.unit = unit; this.schedule_executor = schedule_executor; } void initHandoffRunnable( HandoffRunnable handoff_runnable, HandoffScheduledFuture<?> handoff_future ) { this.handoff_runnable = handoff_runnable; this.handoff_future = handoff_future; } @Override public void run() { delegate.run(); // Don't reschedule if cancelled if ( handoff_future.isCancelled() ) return; ScheduledFuture future = schedule_executor.schedule( handoff_runnable, delay, unit ); //noinspection unchecked handoff_future.init( future ); } } private static class HandoffRunnable implements Runnable { final Runnable delegate; private final HandoffScheduledFuture<?> handoff_future; private final ExecutorService main_executor; HandoffRunnable( Runnable delegate, HandoffScheduledFuture<?> handoff_future, ExecutorService main_executor ) { this.delegate = delegate; this.handoff_future = handoff_future; this.main_executor = main_executor; } @SuppressWarnings( { "unchecked" } ) @Override public void run() { Future inner_future = main_executor.submit( delegate ); handoff_future.setDirectExecutionDelegate( inner_future ); } } private static class HandoffCallable<V> implements Callable<V> { private final Callable<V> delegate; private final HandoffScheduledFuture<V> handoff_future; private final ExecutorService main_executor; HandoffCallable( Callable<V> delegate, HandoffScheduledFuture<V> handoff_future, ExecutorService main_executor ) { this.delegate = delegate; this.handoff_future = handoff_future; this.main_executor = main_executor; } @Override public V call() throws Exception { Future<V> inner_future = main_executor.submit( delegate ); handoff_future.setDirectExecutionDelegate( inner_future ); // Return immediately, this value doesn't matter return null; } } private static class HandoffScheduledFuture<V> implements ScheduledFuture<V> { private ScheduledFuture<V> scheduled_delegate; private ObjectSlot<Future<V>> direct_execution_delegate; HandoffScheduledFuture() { this.direct_execution_delegate = new ObjectSlot<>(); } void init( ScheduledFuture<V> scheduled_delegate ) { ScheduledFuture<V> previous_delegate = this.scheduled_delegate; this.scheduled_delegate = scheduled_delegate; // Make sure the previous task wasn't already canceled. if ( previous_delegate != null && previous_delegate.isCancelled() ) { scheduled_delegate.cancel( false ); } } void setDirectExecutionDelegate( Future<V> direct_execution_delegate ) { this.direct_execution_delegate.set( direct_execution_delegate ); } @Override public long getDelay( @Nonnull TimeUnit unit ) { return scheduled_delegate.getDelay( unit ); } @Override public int compareTo( @Nonnull Delayed o ) { return scheduled_delegate.compareTo( o ); } @Override public boolean cancel( boolean mayInterruptIfRunning ) { boolean canceled = scheduled_delegate.cancel( mayInterruptIfRunning ); Future<V> direct_future = direct_execution_delegate.get(); if ( direct_future != null ) { canceled |= direct_future.cancel( mayInterruptIfRunning ); } return canceled; } @Override public boolean isCancelled() { Future<V> direct_future = direct_execution_delegate.get(); if ( direct_future == null ) return scheduled_delegate.isCancelled(); else return direct_future.isCancelled(); } @Override public boolean isDone() { Future<V> direct_future = direct_execution_delegate.get(); return direct_future != null && direct_future.isDone(); } @Override public V get() throws InterruptedException, ExecutionException { Future<V> direct_future = direct_execution_delegate.waitForValue(); return direct_future.get(); } @Override public V get( long timeout, @Nonnull TimeUnit unit ) throws InterruptedException, ExecutionException, TimeoutException { long start = System.nanoTime(); Future<V> direct_future = direct_execution_delegate.waitForValue( unit.toMillis( timeout ) ); long spent = Math.min( 0, System.nanoTime() - start ); long remaining = unit.toNanos( timeout ) - spent; if ( remaining <= 0 ) return direct_future.get( 0, unit ); else return direct_future.get( remaining, TimeUnit.NANOSECONDS ); } } /** * Stores relevant information such as an "original" thread name and task start time. */ private class STPTrackerThread extends Thread { private final String original_name; private volatile long task_start_time; STPTrackerThread( Runnable target, String name ) { super( target, name ); this.original_name = name; } /** * @return The name associate with the thread before it was restored, if it * was different from the original. If the name was unchanged from * the original, null will be returned. */ @Nullable String restoreOriginalName() { String name = getName(); setName( original_name ); if ( original_name.equals( name ) ) return null; else return name; } void recordTaskStartTime() { task_start_time = System.nanoTime(); } long getTaskStartTime() { return task_start_time; } } private class STPTrackerThreadFactory extends NamingThreadFactory { STPTrackerThreadFactory( String name_prefix ) { super( name_prefix, true ); } @Override protected Thread createThread( Runnable r, String name ) { return new STPTrackerThread( r, name ); } } private class PreventConcurrentRunHandoffRunnable extends HandoffRunnable { PreventConcurrentRunHandoffRunnable( Runnable delegate, HandoffScheduledFuture<?> handoff_future, ExecutorService main_executor ) { super( new TrackingRunnableWrapper( delegate ), handoff_future, main_executor ); } @Override public void run() { TrackingRunnableWrapper wrapper = ( TrackingRunnableWrapper ) delegate; boolean currently_running = wrapper.running.get(); if ( currently_running ) return; super.run(); } } private class TrackingRunnableWrapper implements Runnable { final AtomicBoolean running = new AtomicBoolean( false ); private final Runnable delegate; TrackingRunnableWrapper( Runnable delegate ) { this.delegate = delegate; } @Override public void run() { running.set( true ); try { delegate.run(); } finally { running.set( false ); } } } }
29.587992
95
0.717305
73dd8a365e7fb0f9a96fe1816f4f6fb1f54e6ffe
1,886
import java.util.Scanner; public class DivisionDemoSecondVersion { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); try { System.out.println("Enter numerator:"); int numerator = keyboard.nextInt(); System.out.println("Enter denominator:"); int denominator = keyboard.nextInt(); double quotient = safeDivide(numerator, denominator); System.out.println(numerator + "/" + denominator + " = " + quotient); } catch(DivisionByZeroException e) { System.out.println(e.getMessage( )); secondChance( ); } System.out.println("End of program."); } public static double safeDivide(int top, int bottom) throws DivisionByZeroException { if (bottom == 0) throw new DivisionByZeroException( ); return top/(double)bottom; } public static void secondChance( ) { Scanner keyboard = new Scanner(System.in); try { System.out.println("Enter numerator:"); int numerator = keyboard.nextInt(); System.out.println("Enter denominator:"); int denominator = keyboard.nextInt(); double quotient = safeDivide(numerator, denominator); System.out.println(numerator + "/" + denominator + " = " + quotient); } catch(DivisionByZeroException e) { System.out.println("I cannot do division by zero."); System.out.println("Aborting program."); System.exit(0); } } }
28.575758
65
0.497349
7ebfa7deea6e097a25fd61c73c0b80b71fce9271
775
class Sort{ public static void bubble(int[] arr){ int n = arr.length; int temp; boolean no_swap; for(int i=0; i<n; i++){ no_swap = true; for(int j=0; j<n; j++){ if(arr[i] < arr[j]){ temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; no_swap = false; } } if(no_swap) break; } System.out.println("Sorted array is "); for(int i=0; i<n; i++){ System.out.print(arr[i] + "\t"); } } } public class Demo{ public static void main(String []args){ int[] a = {2,5,3,1,8,0,61,23,15,-5}; Sort.bubble(a); } }
24.21875
47
0.381935
18eea80ac1a520607d7b06fef1d789dc791e3684
8,282
package com.bridgefy.samples.twitter; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.appcompat.widget.Toolbar; import android.text.InputFilter; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import android.widget.ToggleButton; import com.bridgefy.samples.twitter.entities.Tweet; import com.bridgefy.sdk.client.Bridgefy; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; import static com.bridgefy.samples.twitter.IntroActivity.INTENT_USERNAME; public class TimelineActivity extends AppCompatActivity implements TweetManager.TweetListener { private String TAG = "TimelineActivity"; private String username; @BindView(R.id.txtTweet) EditText txtMessage; @BindView(R.id.gatewaySwitch) ToggleButton gatewaySwitch; TweetManager tweetManager; TweetsRecyclerViewAdapter tweetsAdapter = new TweetsRecyclerViewAdapter(new ArrayList<>()); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_timeline); ButterKnife.bind(this); // recover our username and set the maximum tweet size username = getIntent().getStringExtra(INTENT_USERNAME); txtMessage.setFilters(new InputFilter[] { new InputFilter.LengthFilter(138 - username.length()) }); // Configure the Toolbar Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); gatewaySwitch.setChecked(true); // configure the recyclerview RecyclerView tweetsRecyclerView = findViewById(R.id.tweet_list); LinearLayoutManager mLinearLayoutManager = new LinearLayoutManager(this); mLinearLayoutManager.setReverseLayout(true); tweetsRecyclerView.setLayoutManager(mLinearLayoutManager); tweetsRecyclerView.setAdapter(tweetsAdapter); // Set the Bridgefy MessageListener Log.d(TAG, "Setting new State and Message Listeners"); Bridgefy.setMessageListener(tweetManager = new TweetManager(username, this)); // register the connected receiver registerReceiver(wifiReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)); } @Override protected void onDestroy() { unregisterReceiver(wifiReceiver); if (isFinishing()) { try { Bridgefy.stop(); } catch (IllegalStateException ise) { ise.printStackTrace(); } } super.onDestroy(); } /** * ACTION AND INTERFACE METHODS */ @OnClick(R.id.gatewaySwitch) public void onGatewaySwitched(ToggleButton gatewaySwitch) { Log.i(TAG, "Internet relaying toggled: " + gatewaySwitch.isChecked()); tweetManager.setGateway(gatewaySwitch.isChecked()); if (gatewaySwitch.isChecked()) flushTweets(); } @OnClick(R.id.gatewayHelp) public void onGatewayHelpTap(View v) { Toast.makeText(this, "Toggle this switch if you want this device to act as a Twitter gateway", Toast.LENGTH_LONG).show(); } @OnClick({R.id.btnSubmit}) public void onSubmitTweet(View v) { // get the tweet and push it to the views String messageString = txtMessage.getText().toString(); if (messageString.trim().length() > 0) { // create the Tweet object to send Tweet tweet = new Tweet(messageString, username); // update the views txtMessage.setText(""); tweetsAdapter.addTweet(tweet); // send the tweet tweetManager.postTweet(tweet); } } @Override public void onTweetReceived(Tweet tweet) { tweetsAdapter.addTweet(tweet); } @Override public void onTweetPosted(Tweet tweet) { tweetsAdapter.refreshTweetView(tweet); } public void flushTweets() { if (tweetsAdapter != null) { for (Tweet tweet : tweetsAdapter.tweets) { if (!tweet.isPosted()) tweetManager.postTweet(tweet); } } } private BroadcastReceiver wifiReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) { Log.i(TAG, "Connected!"); flushTweets(); } else { Log.e(TAG, "No Connectivity!"); } } }; /** * RECYCLER VIEW CLASSES */ class TweetsRecyclerViewAdapter extends RecyclerView.Adapter<TweetsRecyclerViewAdapter.TweetViewHolder> { private List<Tweet> tweets; TweetsRecyclerViewAdapter(List<Tweet> tweets) { this.tweets = tweets; } @Override public int getItemCount() { return tweets.size(); } void addTweet(Tweet tweet) { if (!tweets.contains(tweet)) { tweets.add(0, tweet); notifyDataSetChanged(); } } void refreshTweetView(Tweet tweet) { for (int i = 0; i < tweets.size(); i++) { Tweet t = tweets.get(i); if (t.getId().equals(tweet.getId())) { tweets.set(i, tweet); notifyItemChanged(i); return; } } } @Override public TweetViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) { return new TweetViewHolder(LayoutInflater .from(viewGroup.getContext()) .inflate((R.layout.tweet_row), viewGroup, false)); } @Override public void onBindViewHolder(final TweetViewHolder tweetViewHolder, int position) { tweetViewHolder.setTweet(tweets.get(position)); } class TweetViewHolder extends RecyclerView.ViewHolder { Tweet tweet; @BindView(R.id.txtTweet) TextView txtTweet; @BindView(R.id.txtTweetDate) TextView txtTweetDate; @BindView(R.id.txtTweetSender) TextView txtTweetSender; @BindView(R.id.imgTweetIcon) ImageView imgTweetIcon; TweetViewHolder(View view) { super(view); ButterKnife.bind(this, view); } void setTweet(Tweet tweet) { this.tweet = tweet; txtTweet.setText(tweet.getContent()); txtTweetSender.setText("#" + tweet.getSender()); txtTweetDate.setText(getRelativeDate(tweet.getDate())); imgTweetIcon.setImageDrawable(getDrawable( tweet.isPosted() ? R.drawable.tweet_online : R.drawable.tweet_mesh)); } private String getRelativeDate(long datesent) { long relativeDate = System.currentTimeMillis()/1000 - datesent; if (relativeDate > 0) { if (relativeDate < 60) return relativeDate + "s"; if (relativeDate < 60*60) return relativeDate/60 + "m"; if (relativeDate < 60*60*24) return relativeDate/(60*24) + "hr"; if (relativeDate < 60*60*24*7) return relativeDate/(60*24*7) + " days"; else return relativeDate + "w"; } else { return "0s"; } } } } }
32.478431
129
0.610118
1bd6914cb655d50253805f08d0246072f425e5c8
4,953
package me.uniodex.uniofactions.listeners; import com.gamingmesh.jobs.api.JobsExpGainEvent; import com.gamingmesh.jobs.api.JobsPrePaymentEvent; import com.gamingmesh.jobs.container.Job; import me.uniodex.uniocustomitems.CustomItems; import me.uniodex.uniocustomitems.managers.ItemManager; import me.uniodex.uniofactions.UnioFactions; import me.uniodex.uniofactions.utils.Utils; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.block.Block; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.entity.PlayerDeathEvent; import org.bukkit.event.player.PlayerQuitEvent; import org.bukkit.inventory.ItemStack; import java.util.Random; public class JobsListeners implements Listener { private UnioFactions plugin; public JobsListeners(UnioFactions plugin) { this.plugin = plugin; Bukkit.getPluginManager().registerEvents(this, plugin); } private double getPayment(Player player, Job job, double amount) { if (!job.getName().equalsIgnoreCase("Madenci")) return amount; double newAmount = amount; Block lastBrokenBlock = plugin.getJobsManager().getLastBrokenBlock(player); if (lastBrokenBlock == null || !plugin.getJobsManager().isLocationInMine(lastBrokenBlock.getLocation())) { return 0; } ItemStack item = player.getInventory().getItemInMainHand(); if (CustomItems.instance.itemManager.isItemNamed(item)) { if (CustomItems.instance.itemManager.getItem(ItemManager.Items.vaghlodarKazmasi).getItemMeta().getDisplayName().equals(item.getItemMeta().getDisplayName())) { newAmount = (amount / 5.2D); } else if (CustomItems.instance.itemManager.getItem(ItemManager.Items.karaBuyuluVaghlodarKazmasi).getItemMeta().getDisplayName().equals(item.getItemMeta().getDisplayName())) { newAmount = (amount / 4); } else if (CustomItems.instance.itemManager.getItem(ItemManager.Items.buyuluAlanKazmasi).getItemMeta().getDisplayName().equals(item.getItemMeta().getDisplayName())) { newAmount = (amount / 40.4D); } } if (Utils.isLocationInArea(lastBrokenBlock.getLocation(), plugin.getConfig().getString("mineNames.vip"))) { if (player.hasPermission("uniofactions.rank.vip+")) { newAmount *= 1.75; } else { newAmount *= 1.5; } } else if (Utils.isLocationInArea(lastBrokenBlock.getLocation(), plugin.getConfig().getString("mineNames.uvip"))) { newAmount *= 2; } else if (Utils.isLocationInArea(lastBrokenBlock.getLocation(), plugin.getConfig().getString("mineNames.uvip+"))) { newAmount *= 2.25; } return newAmount; } @EventHandler(ignoreCancelled = true) public void onPayment(JobsPrePaymentEvent event) { if (event.getPlayer().getPlayer() == null) return; Player player = event.getPlayer().getPlayer(); if (player == null || event.getJob() == null) return; if (!event.getJob().getName().equalsIgnoreCase("Madenci")) return; double amount = getPayment(player, event.getJob(), event.getAmount()); event.setAmount(amount); } @EventHandler(ignoreCancelled = true) public void onPayment(JobsExpGainEvent event) { if (event.getPlayer().getPlayer() == null) return; Player player = event.getPlayer().getPlayer(); double amount = getPayment(player, event.getJob(), event.getExp()); event.setExp(amount); } @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onBreak(BlockBreakEvent event) { Player player = event.getPlayer(); Block block = event.getBlock(); plugin.getJobsManager().addBrokenBlock(player, block); } @EventHandler public void onQuit(PlayerQuitEvent event) { plugin.getJobsManager().clearPlayerData(event.getPlayer()); } @EventHandler public void onDeath(PlayerDeathEvent event) { if (event.getEntity().getKiller() == null) return; Player victim = event.getEntity(); Player killer = event.getEntity().getKiller(); Location location = event.getEntity().getLocation(); if (plugin.getJobsManager().isPlayerInJob(killer.getName(), "Kelle_Avcısı")) { int chance = Math.round(20 + (plugin.getJobsManager().getJobLevel(killer.getName(), "Kelle_Avcısı") / 10)); int maxChance = 200; int val = new Random().nextInt(maxChance) + 1; if (val <= chance) { Bukkit.getScheduler().runTask(plugin, () -> location.getWorld().dropItemNaturally(location, plugin.getSkullManager().getSkull(victim.getName()))); } } } }
40.933884
187
0.675954
10e7203c20819173c2455f9687d8f203a282d1aa
5,554
package eu.okaeri.configs.schema; import eu.okaeri.configs.OkaeriConfig; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NonNull; import java.lang.reflect.*; import java.util.*; import java.util.stream.Collectors; @Data @AllArgsConstructor public class GenericsDeclaration { private static final Map<String, Class<?>> PRIMITIVES = new HashMap<>(); private static final Map<Class<?>, Class<?>> PRIMITIVE_TO_WRAPPER = new HashMap<>(); private static final Set<Class<?>> PRIMITIVE_WRAPPERS = new HashSet<>(); public static boolean isUnboxedCompatibleWithBoxed(@NonNull Class<?> unboxedClazz, @NonNull Class<?> boxedClazz) { Class<?> primitiveWrapper = PRIMITIVE_TO_WRAPPER.get(unboxedClazz); return primitiveWrapper == boxedClazz; } public static boolean doBoxTypesMatch(@NonNull Class<?> clazz1, @NonNull Class<?> clazz2) { return isUnboxedCompatibleWithBoxed(clazz1, clazz2) || isUnboxedCompatibleWithBoxed(clazz2, clazz1); } static { PRIMITIVES.put(boolean.class.getName(), boolean.class); PRIMITIVES.put(byte.class.getName(), byte.class); PRIMITIVES.put(char.class.getName(), char.class); PRIMITIVES.put(double.class.getName(), double.class); PRIMITIVES.put(float.class.getName(), float.class); PRIMITIVES.put(int.class.getName(), int.class); PRIMITIVES.put(long.class.getName(), long.class); PRIMITIVES.put(short.class.getName(), short.class); PRIMITIVE_TO_WRAPPER.put(boolean.class, Boolean.class); PRIMITIVE_TO_WRAPPER.put(byte.class, Byte.class); PRIMITIVE_TO_WRAPPER.put(char.class, Character.class); PRIMITIVE_TO_WRAPPER.put(double.class, Double.class); PRIMITIVE_TO_WRAPPER.put(float.class, Float.class); PRIMITIVE_TO_WRAPPER.put(int.class, Integer.class); PRIMITIVE_TO_WRAPPER.put(long.class, Long.class); PRIMITIVE_TO_WRAPPER.put(short.class, Short.class); PRIMITIVE_WRAPPERS.add(Boolean.class); PRIMITIVE_WRAPPERS.add(Byte.class); PRIMITIVE_WRAPPERS.add(Character.class); PRIMITIVE_WRAPPERS.add(Double.class); PRIMITIVE_WRAPPERS.add(Float.class); PRIMITIVE_WRAPPERS.add(Integer.class); PRIMITIVE_WRAPPERS.add(Long.class); PRIMITIVE_WRAPPERS.add(Short.class); } public static GenericsDeclaration of(@NonNull Object type, @NonNull List<Object> subtypes) { Class<?> finalType = (type instanceof Class<?>) ? (Class<?>) type : type.getClass(); GenericsDeclaration declaration = new GenericsDeclaration(finalType); declaration.setSubtype(subtypes.stream().map(GenericsDeclaration::of).collect(Collectors.toList())); return declaration; } public static GenericsDeclaration of(Object object) { if (object == null) { return null; } if (object instanceof Class) { return new GenericsDeclaration((Class<?>) object); } if (object instanceof Type) { return from((Type) object); } return new GenericsDeclaration(object.getClass()); } private static GenericsDeclaration from(Type type) { if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; Type rawType = parameterizedType.getRawType(); Type[] actualTypeArguments = parameterizedType.getActualTypeArguments(); if (rawType instanceof Class<?>) { GenericsDeclaration declaration = new GenericsDeclaration((Class<?>) rawType); declaration.setSubtype(Arrays.stream(actualTypeArguments) .map(GenericsDeclaration::of) .filter(Objects::nonNull) .collect(Collectors.toList())); return declaration; } } throw new IllegalArgumentException("cannot process type: " + type + " [" + type.getClass() + "]"); } private GenericsDeclaration(Class<?> type) { this.type = type; this.isEnum = type.isEnum(); } private Class<?> type; private List<GenericsDeclaration> subtype; private boolean isEnum; public GenericsDeclaration getSubtypeAtOrNull(int index) { return (this.subtype == null) ? null : ((index >= this.subtype.size()) ? null : this.subtype.get(index)); } public Class<?> wrap() { return PRIMITIVE_TO_WRAPPER.get(this.type); } @SuppressWarnings("UnnecessaryUnboxing") public Object unwrapValue(Object object) { if (object instanceof Boolean) return ((Boolean) object).booleanValue(); if (object instanceof Byte) return ((Byte) object).byteValue(); if (object instanceof Character) return ((Character) object).charValue(); if (object instanceof Double) return ((Double) object).doubleValue(); if (object instanceof Float) return ((Float) object).floatValue(); if (object instanceof Integer) return ((Integer) object).intValue(); if (object instanceof Long) return ((Long) object).longValue(); if (object instanceof Short) return ((Short) object).shortValue(); return object; } public boolean isPrimitive() { return this.type.isPrimitive(); } public boolean isPrimitiveWrapper() { return PRIMITIVE_WRAPPERS.contains(this.type); } public boolean isConfig() { return OkaeriConfig.class.isAssignableFrom(this.type); } }
38.839161
118
0.664206
1438bf9b07e5171838c8f91c5117b85d39b39c9b
2,505
package jetbrains.mps.kotlin.textGen; /*Generated by MPS */ import jetbrains.mps.text.rt.TextGenDescriptorBase; import jetbrains.mps.text.rt.TextGenContext; import jetbrains.mps.text.impl.TextGenSupport; import jetbrains.mps.lang.smodel.generator.smodelAdapter.SLinkOperations; import jetbrains.mps.internal.collections.runtime.ListSequence; import org.jetbrains.mps.openapi.model.SNode; import jetbrains.mps.internal.collections.runtime.Sequence; import org.jetbrains.mps.openapi.language.SContainmentLink; import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory; public class ForStatement_TextGen extends TextGenDescriptorBase { @Override public void generateText(final TextGenContext ctx) { final TextGenSupport tgs = new TextGenSupport(ctx); if ((SLinkOperations.getTarget(ctx.getPrimaryInput(), LINKS.label$EneV) != null)) { tgs.appendNode(SLinkOperations.getTarget(ctx.getPrimaryInput(), LINKS.label$EneV)); } tgs.append("for ("); KotlinTextGen.annotations(ctx.getPrimaryInput(), false, ctx); if (ListSequence.fromList(SLinkOperations.getChildren(ctx.getPrimaryInput(), LINKS.variables$_81g)).count() > 1) { tgs.append("("); } { Iterable<SNode> collection = SLinkOperations.getChildren(ctx.getPrimaryInput(), LINKS.variables$_81g); final SNode lastItem = Sequence.fromIterable(collection).last(); for (SNode item : collection) { tgs.appendNode(item); if (item != lastItem) { tgs.append(", "); } } } if (ListSequence.fromList(SLinkOperations.getChildren(ctx.getPrimaryInput(), LINKS.variables$_81g)).count() > 1) { tgs.append(")"); } tgs.append(" in "); tgs.appendNode(SLinkOperations.getTarget(ctx.getPrimaryInput(), LINKS.in$_8gh)); tgs.append(") "); KotlinTextGen.controlStructureStatements(ctx.getPrimaryInput(), ctx); } private static final class LINKS { /*package*/ static final SContainmentLink label$EneV = MetaAdapterFactory.getContainmentLink(0x6b3888c1980244d8L, 0x8baff8e6c33ed689L, 0x631027d1c446692eL, 0x631027d1c446692fL, "label"); /*package*/ static final SContainmentLink variables$_81g = MetaAdapterFactory.getContainmentLink(0x6b3888c1980244d8L, 0x8baff8e6c33ed689L, 0x28bef6d7551af425L, 0x28bef6d7551af707L, "variables"); /*package*/ static final SContainmentLink in$_8gh = MetaAdapterFactory.getContainmentLink(0x6b3888c1980244d8L, 0x8baff8e6c33ed689L, 0x28bef6d7551af425L, 0x28bef6d7551af708L, "in"); } }
46.388889
198
0.754092
c6902e9f8793b0108ca88bf4096b198c1a312cfa
3,803
import java.io.Serializable; //------------------------------------------------------------------ //Nome: Matheus Fernando vieira Pinto - //Classe Posicao responsavel por representar uma posicao em um - //tabuleiro - //------------------------------------------------------------------ public class Posicao implements Serializable{ //----------------------------------------Atributos-------------------------------------------------- private char coluna; //representa a coluna de uma posicao private int linha; //representa a linha de uma posicao private char cor; //representa a cor de uma posicao private Peca peca; //aramazena a peca que ira ocupar a posicao private boolean estaOcupada; //armazena o status da posicao se ela esta ocupada ou nao //--------------------------------------------------------------------------------------------------- //------------------------------------Metodo Construtor---------------------------------------------- /*inicializa os atributos de uma determinada posicao com os valores fornecidos como parametro. Gera uma excecao caso a cor fornecida seja diferente de B ou P, se a linha e colunas fornecidas estiverem fora dos limites de um tabuleiro de xadrez*/ public Posicao(char cor, int linha, char coluna, Peca p) throws Exception{ //lança uma excecao caso a cor fornecida seja invalida if(cor != 'B' && cor != 'P') throw new Exception("Cor da posicão inválida"); //lança uma excecao caso a linha nao esteja no intervalo [1, 8] if(linha < 1 || linha > 8) throw new JogoExcecoes("Linha fornecida não está no intervalo [1, 8] considerado válido"); //lanca uma excecao caso a coluna nao esteja no intervalo [a, h] if(coluna < 'a' || coluna > 'h') throw new JogoExcecoes("Coluna fornecida não está no intervalo [a, h] considerado válido"); this.cor = cor; //inicializa o atributo cor com o valor fornecido como parametro this.linha = linha; //inicializa o atributo linha com o valor fornecido como parametro this.coluna = coluna; //inicializa o atributo coluna com o valor fornecido como parametro this.setPeca(p);; //adiciona uma peça a posicao } //--------------------------------------------------------------------------------------------------- //------------------------------------Metodos gets e sets-------------------------------------------- //retorna a cor de uma posicao public char getCor() { return this.cor; } //retorna a coluna na qual a posicao esta ocupada public char getColuna() { return this.coluna; } //retorna a linha na qual a posicao esta localizada public int getLinha() { return this.linha; } //retorna o status da posicao verdadeiro para ocupada e falso caso contrario public boolean getEstaOcupada() { return this.estaOcupada; } //modifica o status da posicao, indicando se ela esta ocupada ou nao public void setEstaOcupada(boolean capturada) { this.estaOcupada = capturada; } //insere uma peca na posicao public void setPeca(Peca p) { this.peca = p; if(p == null) this.setEstaOcupada(false); else this.setEstaOcupada(true); } //retorna uma referencia para um objeto do tipo peca que ocupa uma determinada posicao ou o valor null caso ela esteja vazia. public Peca getPeca() { return this.peca; } //--------------------------------------------------------------------------------------------------- }
46.950617
130
0.517486
1ffe4497730f487412c92c8553b33b0fd5fc2f9d
2,106
package com.vimukti.accounter.web.client.ui.settings; import com.google.gwt.core.client.GWT; import com.google.gwt.core.client.RunAsyncCallback; import com.google.gwt.resources.client.ImageResource; import com.vimukti.accounter.web.client.Global; import com.vimukti.accounter.web.client.core.ClientMeasurement; import com.vimukti.accounter.web.client.ui.Accounter; import com.vimukti.accounter.web.client.ui.MainFinanceWindow; import com.vimukti.accounter.web.client.ui.core.Action; public class AddMeasurementAction extends Action<ClientMeasurement> { public AddMeasurementAction() { super(); this.catagory = messages.inventory(); } @Override public void run() { runAysnc(data, isDependent); } private void runAysnc(final Object data, final Boolean isDependent) { GWT.runAsync(new RunAsyncCallback() { public void onSuccess() { AddMeasurementView view = new AddMeasurementView(); MainFinanceWindow.getViewManager().showView(view, data, isDependent, AddMeasurementAction.this); } public void onFailure(Throwable e) { Accounter.showError(Global.get().messages() .unableToshowtheview()); } }); // AccounterAsync.createAsync(new CreateViewAsyncCallback() { // // @Override // public void onCreated() { // AddMeasurementView view = new AddMeasurementView(); // MainFinanceWindow.getViewManager().showView(view, data, // isDependent, AddMeasurementAction.this); // // } // }); } @Override public ImageResource getBigImage() { // TODO Auto-generated method stub return null; } @Override public ImageResource getSmallImage() { // TODO Auto-generated method stub return null; } // @Override // public ParentCanvas getView() { // // TODO Auto-generated method stub // return null; // } @Override public String getHistoryToken() { return "addMeasurement"; } @Override public String getHelpToken() { return "add-measurement"; } @Override public String getText() { return messages.addMeasurementName(); } }
23.931818
71
0.70038
41408e42e829353d9455cd1fd0593ee752459b64
3,802
/** * Copyright 1&1 Internet AG, https://github.com/1and1/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.oneandone.sushi.util; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; public class Base64Test { @Test public void encode() { assertEquals("AQ==", new String(run(true, new byte[] { 1 }))); } @Test public void decode() { byte[] result; result = run(false, "AQ==".getBytes()); assertEquals(1, result.length); assertEquals((byte) 1, result[0]); } @Test public void lengthZeros() { int i; byte[] data; for (i = 0; i < 255; i++) { data = new byte[i]; // initialized to zeros check(data); } } @Test public void lengthNumbers() { byte[] data; for (int i = 0; i < 255; i++) { data = new byte[i]; // initialized to zeros for (int j = 0; j < i; j++) { data[j] = (byte) j; } check(data); } } @Test public void one() { int b; for (b = Byte.MIN_VALUE; b <= Byte.MAX_VALUE; b++) { check(new byte[] { (byte) b }); } } @Test public void complex() { check("sch??ne schei??e".getBytes()); } @Test public void string() { Base64 encoder; Base64 decoder; StringBuilder builder; String normal; String encoded; builder = new StringBuilder(); encoder = new Base64(true); decoder = new Base64(false); for (char c = 0; c < 257; c++) { normal = builder.toString(); encoded = encoder.run(normal); assertEquals(normal, decoder.run(encoded)); builder.append(c); } } private void check(byte[] orig) { byte[] encoded; byte[] cmp; encoded = run(true, orig); assertEq(org.apache.commons.codec.binary.Base64.encodeBase64(orig), encoded); assertEquals((int) Base64.encodedLength(orig.length), encoded.length); cmp = run(false, encoded); assertEq(org.apache.commons.codec.binary.Base64.decodeBase64(encoded), cmp); assertEquals((int) Base64.encodedLength(orig.length), encoded.length); assertEquals(orig.length, cmp.length); assertEquals(new String(orig), new String(cmp)); } private void assertEq(byte[] expected, byte[] found) { assertEquals(expected.length, found.length); for (int i = 0; i < expected.length; i++) { assertEquals("idx " + i, expected[i], found[i]); } } private static byte[] run(boolean encoder, byte[] src) { Base64 base64; ByteArrayOutputStream stream; base64 = new Base64(encoder); stream = new ByteArrayOutputStream(); try { base64.run(new ByteArrayInputStream(src), stream); } catch (IOException e) { fail(e.getMessage()); } return stream.toByteArray(); } }
27.751825
85
0.568385
47571741a503d1dd66c42de818cad0146c849374
3,389
package rocks.inspectit.ui.rcp.handlers; import java.util.HashMap; import java.util.Map; import org.eclipse.core.commands.AbstractHandler; import org.eclipse.core.commands.ExecutionEvent; import org.eclipse.core.commands.ExecutionException; import org.eclipse.core.commands.IHandler; import org.eclipse.ui.IEditorPart; import org.eclipse.ui.IWorkbenchWindow; import org.eclipse.ui.commands.ICommandService; import org.eclipse.ui.commands.IElementUpdater; import org.eclipse.ui.handlers.HandlerUtil; import org.eclipse.ui.menus.UIElement; import org.eclipse.ui.services.IServiceScopes; import rocks.inspectit.ui.rcp.editor.preferences.IPreferencePanel; import rocks.inspectit.ui.rcp.editor.root.AbstractRootEditor; /** * Handler for the maximize/minimize the active sub-view. At the same time this Handler implements * the {@link IElementUpdater} interface so that we can manually update the checked state of the UI * elements that are bounded to the {@value #COMMAND_ID} command. * * @author Ivan Senic * */ public class MaximizeActiveViewHandler extends AbstractHandler implements IHandler, IElementUpdater { /** * Command id. */ public static final String COMMAND_ID = "rocks.inspectit.ui.rcp.commands.maximizeActiveView"; /** * Preference panel id parameter needed for this command. */ public static final String PREFERENCE_PANEL_ID_PARAMETER = COMMAND_ID + ".preferencePanelId"; /** * {@inheritDoc} */ @Override public Object execute(ExecutionEvent event) throws ExecutionException { IEditorPart editorPart = HandlerUtil.getActiveEditor(event); if (editorPart instanceof AbstractRootEditor) { AbstractRootEditor abstractRootEditor = (AbstractRootEditor) editorPart; if (abstractRootEditor.canMaximizeActiveSubView()) { abstractRootEditor.maximizeActiveSubView(); } else if (abstractRootEditor.canMinimizeActiveSubView()) { abstractRootEditor.minimizeActiveSubView(); } } // after the maximized/minimized is executed we need to refresh the UI elements bounded to // the command, so that checked state of that elements is updated ICommandService commandService = (ICommandService) HandlerUtil.getActiveWorkbenchWindow(event).getService(ICommandService.class); Map<Object, Object> filter = new HashMap<>(); filter.put(IServiceScopes.WINDOW_SCOPE, HandlerUtil.getActiveWorkbenchWindow(event)); commandService.refreshElements(event.getCommand().getId(), filter); return null; } /** * {@inheritDoc} */ @SuppressWarnings("rawtypes") @Override public void updateElement(UIElement element, Map parameters) { // we'll only update the element that is bounded to the preference panel in the active // sub-view IWorkbenchWindow workbenchWindow = (IWorkbenchWindow) parameters.get("org.eclipse.ui.IWorkbenchWindow"); String preferencePanelId = (String) parameters.get(PREFERENCE_PANEL_ID_PARAMETER); if ((null != workbenchWindow) && (null != preferencePanelId)) { IEditorPart editorPart = workbenchWindow.getActivePage().getActiveEditor(); if (editorPart instanceof AbstractRootEditor) { AbstractRootEditor abstractRootEditor = (AbstractRootEditor) editorPart; IPreferencePanel preferencePanel = abstractRootEditor.getPreferencePanel(); if (preferencePanelId.equals(preferencePanel.getId())) { element.setChecked(!abstractRootEditor.canMaximizeActiveSubView()); } } } } }
38.954023
131
0.782532
643c9896ee3704c2ec6d913897cf5f1a2301ce98
4,468
package icetone.examples; import com.jme3.app.SimpleApplication; import com.jme3.math.FastMath; import com.jme3.renderer.RenderManager; import com.jme3.renderer.ViewPort; import com.jme3.scene.control.AbstractControl; import icetone.controls.containers.Panel; import icetone.controls.extras.Indicator; import icetone.controls.extras.Indicator.DisplayMode; import icetone.controls.text.Label; import icetone.core.ElementContainer; import icetone.core.Orientation; import icetone.core.Screen; import icetone.core.layout.mig.MigLayout; import icetone.effects.Interpolation; /** * This example shows some examples of usage of the {@link Indicator} control, a * 'Progress Bar' type component. */ public class IndicatorExample extends SimpleApplication { public static void main(String[] args) { IndicatorExample app = new IndicatorExample(); app.start(); } @Override public void simpleInitApp() { /* * We are only using a single screen, so just initialise it (and you * don't need to provide the screen instance to each control). * * It is passed to the buildExample method in this way to help * ExampleRunner so this example can be run from there and as a * standalone JME application */ buildExample(new Screen(this)); } protected void buildExample(ElementContainer<?, ?> container) { /* * A Horizontal Indicator displaying percentages in the normal direction */ Indicator indicator1 = new Indicator().setDisplayMode(DisplayMode.percentages).setMaxValue(100) .setCurrentValue(75); indicator1.addControl(new UpdateControl()); Panel panel1 = new Panel(new MigLayout("fill, wrap 1", "[grow]", "[][]")); panel1.setPosition(100, 100); panel1.addElement(indicator1, "growx"); panel1.addElement(new Label("Horizontal, Percentages, Forward"), "ax 50%"); /* * A Horizontal Indicator displaying the value in the reverse direction */ Indicator indicator2 = new Indicator().setMaxValue(100).setDisplayMode(DisplayMode.value).setCurrentValue(75) .setReverseDirection(true); indicator2.addControl(new UpdateControl()); Panel panel2 = new Panel(new MigLayout("fill, wrap 1", "[grow]", "[][]")); panel2.addElement(indicator2, "growx"); panel2.addElement(new Label("Horizontal, Valuue, Reverse"), "ax 50%"); panel2.setPosition(200, 200); /* * A Vertical Indicator displaying custom text in the forward direction */ Indicator indicator3 = new Indicator() { @Override protected void refactorText() { getOverlayElement().setText(String.format("Custom text %.3f", getCurrentPercentage())); super.refactorText(); } }.setMaxValue(100).setDisplayMode(DisplayMode.none).setCurrentValue(75); indicator3.addControl(new UpdateControl()); Panel panel3 = new Panel(new MigLayout("fill, wrap 1", "[]", "[grow][]")); panel3.addElement(indicator3, "growx, ax 50%"); panel3.addElement(new Label("Vertical,Custom,Forward"), "ax 50%"); panel3.setPosition(300, 300); /* * A Vertical Indicator displaying nothing with animation (jumps every 2 * seconds) */ Indicator indicator4 = new Indicator().setOrientation(Orientation.VERTICAL).setDisplayMode(DisplayMode.none) .setMaxValue(100).setCurrentValue(75).setAnimationTime(0.5f).setInterpolation(Interpolation.bounce); indicator4.addControl(new AbstractControl() { /* This control updates the bar to a random value every 2 seconds */ float t = 0; @Override protected void controlUpdate(float tpf) { t += tpf; if (t > 2) { t = 0; indicator4.setCurrentValue(FastMath.nextRandomFloat() * indicator4.getMaxValue()); } } @Override protected void controlRender(RenderManager rm, ViewPort vp) { } }); Panel panel4 = new Panel(new MigLayout("fill, wrap 1", "[]", "[:260:,grow][]")); panel4.setPosition(400, 400); panel4.addElement(indicator4, "growy, ax 50%"); panel4.addElement(new Label("Vertical,Animation"), "ax 50%"); // Build the screen container.showElement(panel1); container.showElement(panel2); container.showElement(panel3); container.showElement(panel4); } class UpdateControl extends AbstractControl { @Override protected void controlUpdate(float tpf) { Indicator i = (Indicator) spatial; i.setCurrentValue(i.getCurrentValue() + tpf); if (i.getCurrentValue() >= i.getMaxValue()) { i.setCurrentValue(0); } } @Override protected void controlRender(RenderManager rm, ViewPort vp) { } } }
31.244755
111
0.720904
6791a08367c4655914f2fff78d1161788948402d
5,822
/*****************************************************************************\ * AtlasRef * * AtlasRef is a class that figures out which page in a number of atlases * given an R.A. and Dec. It also supports the Rukl lunar atlas * given a lunar latitude and longitude. * * Based in part on C code from project pluto (www.projectpluto.com) * \*****************************************************************************/ package com.mhuss.AstroLib; /** * AtlasRef is a class that figures out which page in a number of atlases * best show the given RA and Dec. * <P> * It also supports the Rukl lunar atlas given a lunar latitude and longitude. */ public class AtlasRef { /** * This function returns the page number in the Millennium Star Atlas * that best shows the location specified. * * @param ra Right ascension in decimal hours * @param dec Declination in decimal degrees * * @return The appropriate Millenium Atlas page */ public static int millenniumAtlasPage( double ra, double dec ) { int page; if( dec >= 87.) /* polar cap pages */ page = ( ra < 4. || ra > 16. ? 2 : 1); else if( dec <= -87.) /* polar cap pages */ page = ( ra < 4. || ra > 16. ? 516 : 515); else { int gore = (int)( ra / 8.), zone = (int)(( 93. - dec) / 6.); double remains = Math.ceil( ra / 8.) * 8. - ra; final int per_zone[] = { 2, 4, 8, 10, 12, 14, 16, 20, 20, 22, 22, 24, 24, 24, 24, 24, 24, 24, 24, 24, 22, 22, 20, 20, 16, 14, 12, 10, 8, 4, 2 }; page = (int)( remains * (double)per_zone[zone] / 8.) + 1 + gore * 516; while( 0 != zone-- ) page += per_zone[zone]; } return page; } /** * This function returns the page number in Sky Atlas 2000 * page that best shows the location specified. * * @param ra Right ascension in decimal hours * @param dec Declination in decimal degrees * * @return The appropriate Sky Atlas 2000 page */ public static int skyAtlasPage( double ra, double dec ) { int page; if( Math.abs( dec ) < 18.5 ) /* between -18.5 and 18.5 */ { page = 9 + (int)( ra / 3. + 5. / 6. ); if( page == 9 ) page = 17; } else if( Math.abs( dec ) < 52. ) /* between 18.5 and 52, N and S */ { page = 4 + (int)( ra / 4. ); if( dec < 0. ) page += 14; } else /* above 52, N and S */ { page = 1 + (int)( ra / 8. ); if( dec < 0. ) page += 23; } return page; } /** * This function returns the page number in Uranometria that * best shows the location specified. * * @param ra Right ascension in decimal hours * @param dec Declination in decimal degrees * @param fix472 True to swap charts 472 and 473 (needed in original * edition) * * @return The appropriate Uranometria page */ public static int uranometriaPage( double ra, double dec, boolean fix472 ) { final int decLimits[] = { -900, -845, -725, -610, -500, -390, -280, -170, -55, 55, 170, 280, 390, 500, 610, 725, 845, 900 }; final int nDivides[] = { 2, 12, 20, 24, 30, 36, 45, 45, 45, 45, 45, 36, 30, 24, 20, 12, 2 }; int divide, startValue = 472; for( divide = 0; (double)decLimits[divide + 1] < dec * 10.; divide++ ) startValue -= (int)nDivides[divide + 1]; double angle = ra * (int)nDivides[divide] / 24.; if( nDivides[divide] >= 20 ) angle += .5; else if( nDivides[divide] == 12 ) angle += 5. / 12.; int page = (int)angle % nDivides[divide] + startValue; if( page >= 472 && fix472 ) /* charts 472 and 473 are "flipped" */ page = (472 + 473) - page; return page; } /** * This function returns the page number in the original edition of * Uranometria that best shows the location specified. * * @param ra Right ascension in decimal hours * @param dec Declination in decimal degrees * * @return The appropriate Uranometria page */ public static int uranometriaPage( double ra, double dec ) { return uranometriaPage( ra, dec, true ); } /** * This function returns the page number in Rukl that best shows the * lunar location specified. Returns a String to accomodate Rukl's * roman numeral libration pages. * * @param lon lunar longitude * @param lat lunar latitude * * @return The appropriate Rukl page */ public static String ruklPage( double lon, double lat ) { double x = Math.cos( lat ) * Math.cos( lon ); double y = Math.cos( lat ) * Math.sin( lon ); double z = Math.sin( lat ); int page = -1, ix = (int)( y * 5.5 + 5.5), iy = (int)( 4. - 4. * z); final int page_starts[] = { -1, 7, 17, 28, 39, 50, 60, 68 }; //strcpy( buff, "Rukl "); StringBuffer buff = new StringBuffer( "Rukl " ); if( x > 0. ) { if( iy <= 1 || iy >= 6) { if( 0 == ix ) ix = 1; else if( 10 == ix ) ix = 9; } if( 0 == iy || 7 == iy ) if( 1 == ix ) ix = 2; else if( 9 == ix ) ix = 8; page = ix + page_starts[iy]; buff.append( page ); } /* Allow a basically eight-degree libration zone. This */ /* isn't _perfect_, but it's "not bad" either. */ if( x < Math.PI * 8. / 180. && x > -Math.PI * 8. / 180.) { int zone_no = (int)( Math.atan2( z, y) * 4. / Math.PI + 4.); String librationZonePages[] = { "VII", "VI", "V", "IV", "III", "II", "I", "VIII" }; if( page > -1) buff.append( '/' ); buff.append( librationZonePages[zone_no] ); } return ( -1 == page ) ? "" : buff.toString(); } } // end class AtlasRef
28.4
79
0.53023
4ded891540505b2fda875248815074a9efe92725
7,331
package ca.dieterlunn.android.pizza.fragments; import android.app.Activity; import android.app.Fragment; import android.content.Context; import android.content.SharedPreferences; import android.content.res.Configuration; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; import java.util.List; import ca.dieterlunn.android.pizza.NavigationItem; import ca.dieterlunn.android.pizza.R; import ca.dieterlunn.android.pizza.adapters.NavigationDrawerAdapter; import ca.dieterlunn.android.pizza.callbacks.NavigationDrawerCallbacks; public class NavigationDrawerFragment extends Fragment implements NavigationDrawerCallbacks { private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned"; private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position"; private static final String PREFERENCES_FILE = "pizza_settings"; private RecyclerView mDrawer; private NavigationDrawerCallbacks mCallbacks; private View mFragmentContainerView; private DrawerLayout mDrawerLayout; private ActionBarDrawerToggle mDrawerToggle; private boolean mUserLearnedDrawer; private boolean mFromSavedInstance; private int mCurrentPosition; @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_navigation_drawer, container, false); mDrawer = (RecyclerView) view.findViewById(R.id.drawerView); LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity()); layoutManager.setOrientation(LinearLayoutManager.VERTICAL); mDrawer.setLayoutManager(layoutManager); mDrawer.setHasFixedSize(true); final List<NavigationItem> navigationItems = getMenu(); NavigationDrawerAdapter adapter = new NavigationDrawerAdapter(navigationItems, "Dieter Lunn", "[email protected]", R.drawable.avatar); adapter.setNavigationDrawerCallbacks(this); mDrawer.setAdapter(adapter); selectItem(mCurrentPosition); return view; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mUserLearnedDrawer = Boolean.valueOf(readSharedSetting(getActivity(), PREF_USER_LEARNED_DRAWER, "false")); if (savedInstanceState != null) { mCurrentPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION); mFromSavedInstance = true; } } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mCallbacks = (NavigationDrawerCallbacks) activity; } catch (ClassCastException e) { throw new ClassCastException("Activity must implement NavigationDrawerCallbacks"); } } @Override public void onDetach() { super.onDetach(); mCallbacks = null; } public ActionBarDrawerToggle getDrawerToggle() { return mDrawerToggle; } public void setDrawerToggle(ActionBarDrawerToggle drawerToggle) { mDrawerToggle = drawerToggle; } public DrawerLayout getDrawerLayout() { return mDrawerLayout; } public void setDrawerLayout(DrawerLayout drawerLayout) { mDrawerLayout = drawerLayout; } public void setup(int fragmentId, DrawerLayout drawerLayout, Toolbar toolbar) { mFragmentContainerView = getActivity().findViewById(fragmentId); mDrawerLayout = drawerLayout; mDrawerToggle = new ActionBarDrawerToggle(getActivity(), mDrawerLayout, toolbar, R.string.drawer_open, R.string.drawer_closed) { @Override public void onDrawerClosed(View drawerView) { super.onDrawerClosed(drawerView); if (!isAdded()) return; getActivity().invalidateOptionsMenu(); } @Override public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); if (!isAdded()) return; if (!mUserLearnedDrawer) { mUserLearnedDrawer = true; saveSharedSetting(getActivity(), PREF_USER_LEARNED_DRAWER, "true"); } getActivity().invalidateOptionsMenu(); } }; if (!mUserLearnedDrawer && !mFromSavedInstance) { mDrawerLayout.openDrawer(mFragmentContainerView); } mDrawerLayout.post(new Runnable() { @Override public void run() { mDrawerToggle.syncState(); } }); mDrawerLayout.setDrawerListener(mDrawerToggle); } public void openDrawer() { mDrawerLayout.openDrawer(mFragmentContainerView); } public void closeDrawer() { mDrawerLayout.closeDrawer(mFragmentContainerView); } private void selectItem(int position) { mCurrentPosition = position; if (mDrawerLayout != null) { mDrawerLayout.closeDrawer(mFragmentContainerView); } if (mCallbacks != null) { mCallbacks.onNavigationDrawerItemSelected(position); } ((NavigationDrawerAdapter) mDrawer.getAdapter()).selectPosition(position); } public boolean isDrawerOpen() { return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView); } @Override public void onNavigationDrawerItemSelected(int position) { selectItem(position); } @Override public void onConfigurationChanged(Configuration configuration) { super.onConfigurationChanged(configuration); mDrawerToggle.onConfigurationChanged(configuration); } @Override public void onSaveInstanceState(Bundle state) { super.onSaveInstanceState(state); state.putInt(STATE_SELECTED_POSITION, mCurrentPosition); } public static void saveSharedSetting(Context context, String settingName, String value) { SharedPreferences preferences = context.getSharedPreferences(PREFERENCES_FILE, Context.MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); editor.putString(settingName, value); editor.apply(); } public static String readSharedSetting(Context context, String settingName, String defaultValue) { SharedPreferences preferences = context.getSharedPreferences(PREFERENCES_FILE, Context.MODE_PRIVATE); return preferences.getString(settingName, defaultValue); } public List<NavigationItem> getMenu() { List<NavigationItem> items = new ArrayList<>(); items.add(new NavigationItem("Orders", getResources().getDrawable(R.drawable.abc_ic_search_api_mtrl_alpha))); items.add(new NavigationItem("Settings", getResources().getDrawable(R.drawable.abc_ic_search_api_mtrl_alpha))); return items; } }
33.939815
145
0.703315
b0a809c12dfce007be9d5af533a23653180c8461
35,842
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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 ANYDa * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.index.mapper; import org.apache.lucene.document.Field; import org.apache.lucene.document.DoubleRangeField; import org.apache.lucene.document.FloatRangeField; import org.apache.lucene.document.IntRangeField; import org.apache.lucene.document.LongRangeField; import org.apache.lucene.document.StoredField; import org.apache.lucene.index.IndexOptions; import org.apache.lucene.index.IndexableField; import org.apache.lucene.search.BoostQuery; import org.apache.lucene.search.Query; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.NumericUtils; import org.elasticsearch.common.Explicit; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.geo.ShapeRelation; import org.elasticsearch.common.joda.DateMathParser; import org.elasticsearch.common.joda.FormatDateTimeFormatter; import org.elasticsearch.common.settings.Setting; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.LocaleUtils; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.index.mapper.NumberFieldMapper.NumberType; import org.elasticsearch.index.query.QueryShardContext; import org.joda.time.DateTimeZone; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Objects; import static org.elasticsearch.index.mapper.TypeParsers.parseDateTimeFormatter; import static org.elasticsearch.index.query.RangeQueryBuilder.GT_FIELD; import static org.elasticsearch.index.query.RangeQueryBuilder.GTE_FIELD; import static org.elasticsearch.index.query.RangeQueryBuilder.LT_FIELD; import static org.elasticsearch.index.query.RangeQueryBuilder.LTE_FIELD; /** A {@link FieldMapper} for indexing numeric and date ranges, and creating queries */ public class RangeFieldMapper extends FieldMapper { public static final boolean DEFAULT_INCLUDE_UPPER = true; public static final boolean DEFAULT_INCLUDE_LOWER = true; public static class Defaults { public static final Explicit<Boolean> COERCE = new Explicit<>(true, false); } // this is private since it has a different default static final Setting<Boolean> COERCE_SETTING = Setting.boolSetting("index.mapping.coerce", true, Setting.Property.IndexScope); public static class Builder extends FieldMapper.Builder<Builder, RangeFieldMapper> { private Boolean coerce; private Locale locale; public Builder(String name, RangeType type) { super(name, new RangeFieldType(type), new RangeFieldType(type)); builder = this; locale = Locale.ROOT; } @Override public RangeFieldType fieldType() { return (RangeFieldType)fieldType; } @Override public Builder docValues(boolean docValues) { if (docValues == true) { throw new IllegalArgumentException("field [" + name + "] does not currently support " + TypeParsers.DOC_VALUES); } return super.docValues(docValues); } public Builder coerce(boolean coerce) { this.coerce = coerce; return builder; } protected Explicit<Boolean> coerce(BuilderContext context) { if (coerce != null) { return new Explicit<>(coerce, true); } if (context.indexSettings() != null) { return new Explicit<>(COERCE_SETTING.get(context.indexSettings()), false); } return Defaults.COERCE; } public Builder dateTimeFormatter(FormatDateTimeFormatter dateTimeFormatter) { fieldType().setDateTimeFormatter(dateTimeFormatter); return this; } @Override public Builder nullValue(Object nullValue) { throw new IllegalArgumentException("Field [" + name() + "] does not support null value."); } public void locale(Locale locale) { this.locale = locale; } @Override protected void setupFieldType(BuilderContext context) { super.setupFieldType(context); FormatDateTimeFormatter dateTimeFormatter = fieldType().dateTimeFormatter; if (fieldType().rangeType == RangeType.DATE) { if (!locale.equals(dateTimeFormatter.locale())) { fieldType().setDateTimeFormatter(new FormatDateTimeFormatter(dateTimeFormatter.format(), dateTimeFormatter.parser(), dateTimeFormatter.printer(), locale)); } } else if (dateTimeFormatter != null) { throw new IllegalArgumentException("field [" + name() + "] of type [" + fieldType().rangeType + "] should not define a dateTimeFormatter unless it is a " + RangeType.DATE + " type"); } } @Override public RangeFieldMapper build(BuilderContext context) { setupFieldType(context); return new RangeFieldMapper(name, fieldType, defaultFieldType, coerce(context), includeInAll, context.indexSettings(), multiFieldsBuilder.build(this, context), copyTo); } } public static class TypeParser implements Mapper.TypeParser { final RangeType type; public TypeParser(RangeType type) { this.type = type; } @Override public Mapper.Builder<?,?> parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException { Builder builder = new Builder(name, type); TypeParsers.parseField(builder, name, node, parserContext); for (Iterator<Map.Entry<String, Object>> iterator = node.entrySet().iterator(); iterator.hasNext();) { Map.Entry<String, Object> entry = iterator.next(); String propName = entry.getKey(); Object propNode = entry.getValue(); if (propName.equals("null_value")) { throw new MapperParsingException("Property [null_value] is not supported for [" + this.type.name + "] field types."); } else if (propName.equals("coerce")) { builder.coerce(TypeParsers.nodeBooleanValue("coerce", propNode, parserContext)); iterator.remove(); } else if (propName.equals("locale")) { builder.locale(LocaleUtils.parse(propNode.toString())); iterator.remove(); } else if (propName.equals("format")) { builder.dateTimeFormatter(parseDateTimeFormatter(propNode)); iterator.remove(); } else if (TypeParsers.parseMultiField(builder, name, parserContext, propName, propNode)) { iterator.remove(); } } return builder; } } public static final class RangeFieldType extends MappedFieldType { protected RangeType rangeType; protected FormatDateTimeFormatter dateTimeFormatter; protected DateMathParser dateMathParser; public RangeFieldType(RangeType type) { super(); this.rangeType = Objects.requireNonNull(type); setTokenized(false); setHasDocValues(false); setOmitNorms(true); if (rangeType == RangeType.DATE) { setDateTimeFormatter(DateFieldMapper.DEFAULT_DATE_TIME_FORMATTER); } } public RangeFieldType(RangeFieldType other) { super(other); this.rangeType = other.rangeType; if (other.dateTimeFormatter() != null) { setDateTimeFormatter(other.dateTimeFormatter); } } @Override public MappedFieldType clone() { return new RangeFieldType(this); } @Override public boolean equals(Object o) { if (!super.equals(o)) return false; RangeFieldType that = (RangeFieldType) o; return Objects.equals(rangeType, that.rangeType) && (rangeType == RangeType.DATE) ? Objects.equals(dateTimeFormatter.format(), that.dateTimeFormatter.format()) && Objects.equals(dateTimeFormatter.locale(), that.dateTimeFormatter.locale()) : dateTimeFormatter == null && that.dateTimeFormatter == null; } @Override public int hashCode() { return (dateTimeFormatter == null) ? Objects.hash(super.hashCode(), rangeType) : Objects.hash(super.hashCode(), rangeType, dateTimeFormatter.format(), dateTimeFormatter.locale()); } @Override public String typeName() { return rangeType.name; } @Override public void checkCompatibility(MappedFieldType fieldType, List<String> conflicts, boolean strict) { super.checkCompatibility(fieldType, conflicts, strict); if (strict) { RangeFieldType other = (RangeFieldType)fieldType; if (this.rangeType != other.rangeType) { conflicts.add("mapper [" + name() + "] is attempting to update from type [" + rangeType.name + "] to incompatible type [" + other.rangeType.name + "]."); } if (this.rangeType == RangeType.DATE) { if (Objects.equals(dateTimeFormatter().format(), other.dateTimeFormatter().format()) == false) { conflicts.add("mapper [" + name() + "] is used by multiple types. Set update_all_types to true to update [format] across all types."); } if (Objects.equals(dateTimeFormatter().locale(), other.dateTimeFormatter().locale()) == false) { conflicts.add("mapper [" + name() + "] is used by multiple types. Set update_all_types to true to update [locale] across all types."); } } } } public FormatDateTimeFormatter dateTimeFormatter() { return dateTimeFormatter; } public void setDateTimeFormatter(FormatDateTimeFormatter dateTimeFormatter) { checkIfFrozen(); this.dateTimeFormatter = dateTimeFormatter; this.dateMathParser = new DateMathParser(dateTimeFormatter); } protected DateMathParser dateMathParser() { return dateMathParser; } @Override public Query termQuery(Object value, QueryShardContext context) { Query query = rangeQuery(value, value, true, true, context); if (boost() != 1f) { query = new BoostQuery(query, boost()); } return query; } @Override public Query rangeQuery(Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, QueryShardContext context) { return rangeQuery(lowerTerm, upperTerm, includeLower, includeUpper, ShapeRelation.INTERSECTS, context); } public Query rangeQuery(Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, ShapeRelation relation, QueryShardContext context) { failIfNotIndexed(); return rangeQuery(lowerTerm, upperTerm, includeLower, includeUpper, relation, null, dateMathParser, context); } public Query rangeQuery(Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, ShapeRelation relation, DateTimeZone timeZone, DateMathParser parser, QueryShardContext context) { return rangeType.rangeQuery(name(), lowerTerm, upperTerm, includeLower, includeUpper, relation, timeZone, parser, context); } } private Boolean includeInAll; private Explicit<Boolean> coerce; private RangeFieldMapper( String simpleName, MappedFieldType fieldType, MappedFieldType defaultFieldType, Explicit<Boolean> coerce, Boolean includeInAll, Settings indexSettings, MultiFields multiFields, CopyTo copyTo) { super(simpleName, fieldType, defaultFieldType, indexSettings, multiFields, copyTo); this.coerce = coerce; this.includeInAll = includeInAll; } @Override public RangeFieldType fieldType() { return (RangeFieldType) super.fieldType(); } @Override protected String contentType() { return fieldType.typeName(); } @Override protected RangeFieldMapper clone() { return (RangeFieldMapper) super.clone(); } @Override protected void parseCreateField(ParseContext context, List<IndexableField> fields) throws IOException { final boolean includeInAll = context.includeInAll(this.includeInAll, this); Range range; if (context.externalValueSet()) { range = context.parseExternalValue(Range.class); } else { XContentParser parser = context.parser(); if (parser.currentToken() == XContentParser.Token.START_OBJECT) { RangeFieldType fieldType = fieldType(); RangeType rangeType = fieldType.rangeType; String fieldName = null; Number from = rangeType.minValue(); Number to = rangeType.maxValue(); boolean includeFrom = DEFAULT_INCLUDE_LOWER; boolean includeTo = DEFAULT_INCLUDE_UPPER; XContentParser.Token token; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { fieldName = parser.currentName(); } else { if (fieldName.equals(GT_FIELD.getPreferredName())) { includeFrom = false; if (parser.currentToken() != XContentParser.Token.VALUE_NULL) { from = rangeType.parseFrom(fieldType, parser, coerce.value(), includeFrom); } } else if (fieldName.equals(GTE_FIELD.getPreferredName())) { includeFrom = true; if (parser.currentToken() != XContentParser.Token.VALUE_NULL) { from = rangeType.parseFrom(fieldType, parser, coerce.value(), includeFrom); } } else if (fieldName.equals(LT_FIELD.getPreferredName())) { includeTo = false; if (parser.currentToken() != XContentParser.Token.VALUE_NULL) { to = rangeType.parseTo(fieldType, parser, coerce.value(), includeTo); } } else if (fieldName.equals(LTE_FIELD.getPreferredName())) { includeTo = true; if (parser.currentToken() != XContentParser.Token.VALUE_NULL) { to = rangeType.parseTo(fieldType, parser, coerce.value(), includeTo); } } else { throw new MapperParsingException("error parsing field [" + name() + "], with unknown parameter [" + fieldName + "]"); } } } range = new Range(rangeType, from, to, includeFrom, includeTo); } else { throw new MapperParsingException("error parsing field [" + name() + "], expected an object but got " + parser.currentName()); } } if (includeInAll) { context.allEntries().addText(fieldType.name(), range.toString(), fieldType.boost()); } boolean indexed = fieldType.indexOptions() != IndexOptions.NONE; boolean docValued = fieldType.hasDocValues(); boolean stored = fieldType.stored(); fields.addAll(fieldType().rangeType.createFields(name(), range, indexed, docValued, stored)); } @Override protected void doMerge(Mapper mergeWith, boolean updateAllTypes) { super.doMerge(mergeWith, updateAllTypes); RangeFieldMapper other = (RangeFieldMapper) mergeWith; this.includeInAll = other.includeInAll; if (other.coerce.explicit()) { this.coerce = other.coerce; } } @Override protected void doXContentBody(XContentBuilder builder, boolean includeDefaults, Params params) throws IOException { super.doXContentBody(builder, includeDefaults, params); if (includeDefaults || (fieldType().dateTimeFormatter() != null && fieldType().dateTimeFormatter().format().equals(DateFieldMapper.DEFAULT_DATE_TIME_FORMATTER.format()) == false)) { builder.field("format", fieldType().dateTimeFormatter().format()); } if (includeDefaults || (fieldType().dateTimeFormatter() != null && fieldType().dateTimeFormatter().locale() != Locale.ROOT)) { builder.field("locale", fieldType().dateTimeFormatter().locale()); } if (includeDefaults || coerce.explicit()) { builder.field("coerce", coerce.value()); } if (includeInAll != null) { builder.field("include_in_all", includeInAll); } else if (includeDefaults) { builder.field("include_in_all", false); } } /** Enum defining the type of range */ public enum RangeType { DATE("date_range", NumberType.LONG) { @Override public Field getRangeField(String name, Range r) { return new LongRangeField(name, new long[] {r.from.longValue()}, new long[] {r.to.longValue()}); } private Number parse(DateMathParser dateMathParser, String dateStr) { return dateMathParser.parse(dateStr, () -> {throw new IllegalArgumentException("now is not used at indexing time");}); } @Override public Number parseFrom(RangeFieldType fieldType, XContentParser parser, boolean coerce, boolean included) throws IOException { Number value = parse(fieldType.dateMathParser, parser.text()); return included ? value : nextUp(value); } @Override public Number parseTo(RangeFieldType fieldType, XContentParser parser, boolean coerce, boolean included) throws IOException{ Number value = parse(fieldType.dateMathParser, parser.text()); return included ? value : nextDown(value); } @Override public Long minValue() { return Long.MIN_VALUE; } @Override public Long maxValue() { return Long.MAX_VALUE; } @Override public Number nextUp(Number value) { return LONG.nextUp(value); } @Override public Number nextDown(Number value) { return LONG.nextDown(value); } @Override public byte[] getBytes(Range r) { return LONG.getBytes(r); } @Override public Query rangeQuery(String field, Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, ShapeRelation relation, @Nullable DateTimeZone timeZone, @Nullable DateMathParser parser, QueryShardContext context) { DateTimeZone zone = (timeZone == null) ? DateTimeZone.UTC : timeZone; DateMathParser dateMathParser = (parser == null) ? new DateMathParser(DateFieldMapper.DEFAULT_DATE_TIME_FORMATTER) : parser; Long low = lowerTerm == null ? Long.MIN_VALUE : dateMathParser.parse(lowerTerm instanceof BytesRef ? ((BytesRef) lowerTerm).utf8ToString() : lowerTerm.toString(), context::nowInMillis, false, zone); Long high = upperTerm == null ? Long.MAX_VALUE : dateMathParser.parse(upperTerm instanceof BytesRef ? ((BytesRef) upperTerm).utf8ToString() : upperTerm.toString(), context::nowInMillis, false, zone); return super.rangeQuery(field, low, high, includeLower, includeUpper, relation, zone, dateMathParser, context); } @Override public Query withinQuery(String field, Number from, Number to, boolean includeLower, boolean includeUpper) { return LONG.withinQuery(field, from, to, includeLower, includeUpper); } @Override public Query containsQuery(String field, Number from, Number to, boolean includeLower, boolean includeUpper) { return LONG.containsQuery(field, from, to, includeLower, includeUpper); } @Override public Query intersectsQuery(String field, Number from, Number to, boolean includeLower, boolean includeUpper) { return LONG.intersectsQuery(field, from, to, includeLower, includeUpper); } }, // todo support half_float FLOAT("float_range", NumberType.FLOAT) { @Override public Float minValue() { return Float.NEGATIVE_INFINITY; } @Override public Float maxValue() { return Float.POSITIVE_INFINITY; } @Override public Float nextUp(Number value) { return Math.nextUp(value.floatValue()); } @Override public Float nextDown(Number value) { return Math.nextDown(value.floatValue()); } @Override public Field getRangeField(String name, Range r) { return new FloatRangeField(name, new float[] {r.from.floatValue()}, new float[] {r.to.floatValue()}); } @Override public byte[] getBytes(Range r) { byte[] b = new byte[Float.BYTES*2]; NumericUtils.intToSortableBytes(NumericUtils.floatToSortableInt(r.from.floatValue()), b, 0); NumericUtils.intToSortableBytes(NumericUtils.floatToSortableInt(r.to.floatValue()), b, Float.BYTES); return b; } @Override public Query withinQuery(String field, Number from, Number to, boolean includeFrom, boolean includeTo) { return FloatRangeField.newWithinQuery(field, new float[] {includeFrom ? (Float)from : Math.nextUp((Float)from)}, new float[] {includeTo ? (Float)to : Math.nextDown((Float)to)}); } @Override public Query containsQuery(String field, Number from, Number to, boolean includeFrom, boolean includeTo) { return FloatRangeField.newContainsQuery(field, new float[] {includeFrom ? (Float)from : Math.nextUp((Float)from)}, new float[] {includeTo ? (Float)to : Math.nextDown((Float)to)}); } @Override public Query intersectsQuery(String field, Number from, Number to, boolean includeFrom, boolean includeTo) { return FloatRangeField.newIntersectsQuery(field, new float[] {includeFrom ? (Float)from : Math.nextUp((Float)from)}, new float[] {includeTo ? (Float)to : Math.nextDown((Float)to)}); } }, DOUBLE("double_range", NumberType.DOUBLE) { @Override public Double minValue() { return Double.NEGATIVE_INFINITY; } @Override public Double maxValue() { return Double.POSITIVE_INFINITY; } @Override public Double nextUp(Number value) { return Math.nextUp(value.doubleValue()); } @Override public Double nextDown(Number value) { return Math.nextDown(value.doubleValue()); } @Override public Field getRangeField(String name, Range r) { return new DoubleRangeField(name, new double[] {r.from.doubleValue()}, new double[] {r.to.doubleValue()}); } @Override public byte[] getBytes(Range r) { byte[] b = new byte[Double.BYTES*2]; NumericUtils.longToSortableBytes(NumericUtils.doubleToSortableLong(r.from.doubleValue()), b, 0); NumericUtils.longToSortableBytes(NumericUtils.doubleToSortableLong(r.to.doubleValue()), b, Double.BYTES); return b; } @Override public Query withinQuery(String field, Number from, Number to, boolean includeFrom, boolean includeTo) { return DoubleRangeField.newWithinQuery(field, new double[] {includeFrom ? (Double)from : Math.nextUp((Double)from)}, new double[] {includeTo ? (Double)to : Math.nextDown((Double)to)}); } @Override public Query containsQuery(String field, Number from, Number to, boolean includeFrom, boolean includeTo) { return DoubleRangeField.newContainsQuery(field, new double[] {includeFrom ? (Double)from : Math.nextUp((Double)from)}, new double[] {includeTo ? (Double)to : Math.nextDown((Double)to)}); } @Override public Query intersectsQuery(String field, Number from, Number to, boolean includeFrom, boolean includeTo) { return DoubleRangeField.newIntersectsQuery(field, new double[] {includeFrom ? (Double)from : Math.nextUp((Double)from)}, new double[] {includeTo ? (Double)to : Math.nextDown((Double)to)}); } }, // todo add BYTE support // todo add SHORT support INTEGER("integer_range", NumberType.INTEGER) { @Override public Integer minValue() { return Integer.MIN_VALUE; } @Override public Integer maxValue() { return Integer.MAX_VALUE; } @Override public Integer nextUp(Number value) { return value.intValue() + 1; } @Override public Integer nextDown(Number value) { return value.intValue() - 1; } @Override public Field getRangeField(String name, Range r) { return new IntRangeField(name, new int[] {r.from.intValue()}, new int[] {r.to.intValue()}); } @Override public byte[] getBytes(Range r) { byte[] b = new byte[Integer.BYTES*2]; NumericUtils.intToSortableBytes(r.from.intValue(), b, 0); NumericUtils.intToSortableBytes(r.to.intValue(), b, Integer.BYTES); return b; } @Override public Query withinQuery(String field, Number from, Number to, boolean includeFrom, boolean includeTo) { return IntRangeField.newWithinQuery(field, new int[] {(Integer)from + (includeFrom ? 0 : 1)}, new int[] {(Integer)to - (includeTo ? 0 : 1)}); } @Override public Query containsQuery(String field, Number from, Number to, boolean includeFrom, boolean includeTo) { return IntRangeField.newContainsQuery(field, new int[] {(Integer)from + (includeFrom ? 0 : 1)}, new int[] {(Integer)to - (includeTo ? 0 : 1)}); } @Override public Query intersectsQuery(String field, Number from, Number to, boolean includeFrom, boolean includeTo) { return IntRangeField.newIntersectsQuery(field, new int[] {(Integer)from + (includeFrom ? 0 : 1)}, new int[] {(Integer)to - (includeTo ? 0 : 1)}); } }, LONG("long_range", NumberType.LONG) { @Override public Long minValue() { return Long.MIN_VALUE; } @Override public Long maxValue() { return Long.MAX_VALUE; } @Override public Long nextUp(Number value) { return value.longValue() + 1; } @Override public Long nextDown(Number value) { return value.longValue() - 1; } @Override public Field getRangeField(String name, Range r) { return new LongRangeField(name, new long[] {r.from.longValue()}, new long[] {r.to.longValue()}); } @Override public byte[] getBytes(Range r) { byte[] b = new byte[Long.BYTES*2]; long from = r.from == null ? Long.MIN_VALUE : r.from.longValue(); long to = r.to == null ? Long.MAX_VALUE : r.to.longValue(); NumericUtils.longToSortableBytes(from, b, 0); NumericUtils.longToSortableBytes(to, b, Long.BYTES); return b; } @Override public Query withinQuery(String field, Number from, Number to, boolean includeFrom, boolean includeTo) { return LongRangeField.newWithinQuery(field, new long[] {(Long)from + (includeFrom ? 0 : 1)}, new long[] {(Long)to - (includeTo ? 0 : 1)}); } @Override public Query containsQuery(String field, Number from, Number to, boolean includeFrom, boolean includeTo) { return LongRangeField.newContainsQuery(field, new long[] {(Long)from + (includeFrom ? 0 : 1)}, new long[] {(Long)to - (includeTo ? 0 : 1)}); } @Override public Query intersectsQuery(String field, Number from, Number to, boolean includeFrom, boolean includeTo) { return LongRangeField.newIntersectsQuery(field, new long[] {(Long)from + (includeFrom ? 0 : 1)}, new long[] {(Long)to - (includeTo ? 0 : 1)}); } }; RangeType(String name, NumberType type) { this.name = name; this.numberType = type; } /** Get the associated type name. */ public final String typeName() { return name; } protected abstract byte[] getBytes(Range range); public abstract Field getRangeField(String name, Range range); public List<IndexableField> createFields(String name, Range range, boolean indexed, boolean docValued, boolean stored) { assert range != null : "range cannot be null when creating fields"; List<IndexableField> fields = new ArrayList<>(); if (indexed) { fields.add(getRangeField(name, range)); } // todo add docValues ranges once aggregations are supported if (stored) { fields.add(new StoredField(name, range.toString())); } return fields; } /** parses from value. rounds according to included flag */ public Number parseFrom(RangeFieldType fieldType, XContentParser parser, boolean coerce, boolean included) throws IOException { Number value = numberType.parse(parser, coerce); return included ? value : nextUp(value); } /** parses to value. rounds according to included flag */ public Number parseTo(RangeFieldType fieldType, XContentParser parser, boolean coerce, boolean included) throws IOException { Number value = numberType.parse(parser, coerce); return included ? value : nextDown(value); } public abstract Number minValue(); public abstract Number maxValue(); public abstract Number nextUp(Number value); public abstract Number nextDown(Number value); public abstract Query withinQuery(String field, Number from, Number to, boolean includeFrom, boolean includeTo); public abstract Query containsQuery(String field, Number from, Number to, boolean includeFrom, boolean includeTo); public abstract Query intersectsQuery(String field, Number from, Number to, boolean includeFrom, boolean includeTo); public Query rangeQuery(String field, Object from, Object to, boolean includeFrom, boolean includeTo, ShapeRelation relation, @Nullable DateTimeZone timeZone, @Nullable DateMathParser dateMathParser, QueryShardContext context) { Number lower = from == null ? minValue() : numberType.parse(from, false); Number upper = to == null ? maxValue() : numberType.parse(to, false); if (relation == ShapeRelation.WITHIN) { return withinQuery(field, lower, upper, includeFrom, includeTo); } else if (relation == ShapeRelation.CONTAINS) { return containsQuery(field, lower, upper, includeFrom, includeTo); } return intersectsQuery(field, lower, upper, includeFrom, includeTo); } public final String name; private final NumberType numberType; } /** Class defining a range */ public static class Range { RangeType type; private Number from; private Number to; private boolean includeFrom; private boolean includeTo; public Range(RangeType type, Number from, Number to, boolean includeFrom, boolean includeTo) { this.type = type; this.from = from; this.to = to; this.includeFrom = includeFrom; this.includeTo = includeTo; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(includeFrom ? '[' : '('); sb.append(includeFrom || from.equals(type.minValue()) ? from : type.nextDown(from)); sb.append(':'); sb.append(includeTo || to.equals(type.maxValue()) ? to : type.nextUp(to)); sb.append(includeTo ? ']' : ')'); return sb.toString(); } } }
46.3674
135
0.591066
57e6dff628dd1056adffe8c1ae94a09842a5d06f
1,087
package com.darian.BaTJ_face_Question._03_integerSwap; import java.lang.reflect.Field; /** * <br> * <br>Darian **/ public class IntegerProxySwap { public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException { // 装箱操作 Integer a = 1, b = 2; System.out.println("before:a = " + a + ",b = " + b); swap(a, b); System.out.println("after:a = " + a + ",b = " + b); } public static void swap(Integer i1, Integer i2) throws NoSuchFieldException, IllegalAccessException { Field field = Integer.class.getDeclaredField("value"); // 可以绕过检查 field.setAccessible(true); int tmp = i1.intValue(); // Integer tmp = new Integer(i1.intValue()); // field.set(i1, i2.intValue()); // 涉及到了装箱 i1 -> Integer.valueOf(i2.intValue()).intValue(); // field.set(i2, tmp); // i2 -> Integer.valuof(tmp).intValue(); field.setInt(i1, i2.intValue()); field.setInt(i2, tmp); System.out.println("tmp:" + tmp + ",_tmp:" + Integer.valueOf(tmp)); } }
35.064516
105
0.594296
c56d4d2b457906381bd3e513d025b7eec7429828
385
package io.gridgo.config.test; import io.gridgo.core.GridgoContext; import io.gridgo.core.Processor; import io.gridgo.core.support.RoutingContext; import io.gridgo.framework.support.Registry; public class TestProcessor implements Processor { public TestProcessor(Registry registry) { } @Override public void process(RoutingContext rc, GridgoContext gc) { } }
20.263158
62
0.763636
3a06dbd9d949790b125d6c9acda266c77c22a486
709
package top.imdtf.multi.thread.chapter2.page65; /** * 0 * * 1 * @Author: deng.tengfei * 2 * @email: [email protected] * 3 * @Date: 2021/8/3 22:23 */ public class Page65SyncLockIn1 { public static void main(String[] args) { new MyThread().start(); } } class Service { public synchronized void service1() { System.out.println("service1"); service2(); } public synchronized void service2() { System.out.println("service2"); service3(); } public synchronized void service3() { System.out.println("service3"); } } class MyThread extends Thread { @Override public void run() { new Service().service1(); } }
19.162162
47
0.590973
f69483567ccf7b9fd72161ac7e95256dfbe42753
3,892
package sjcorbett.boggle; import java.util.ArrayList; import java.util.Collections; import java.util.Deque; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Set; import com.google.common.collect.ImmutableList; import com.google.common.collect.Sets; import sjcorbett.trie.Trie; public class Boggler { private final Trie trie; public Boggler(Trie trie) { this.trie = trie; } public Iterable<GridWord> solve(char[][] grid) { return solve(new Grid(grid)); } public Iterable<GridWord> solve(Grid grid) { Set<GridWord> words = Sets.newHashSet(); for (int i = 0; i < grid.grid.length; i++) { char[] row = grid.grid[i]; for (int j = 0; j < row.length; j++) { words.addAll(solveFrom(grid, i, j)); } } return words; } public Set<GridWord> solveFrom(Grid grid, int x, int y) { GridReference startingPoint = new GridReference(x, y); Trie.Node currentNode = trie.getRootNode(); if (currentNode == null) return Collections.emptySet(); Set<GridWord> words = Sets.newHashSet(); StringBuilder currentWord = new StringBuilder(); Deque<Trie.Node> nodes = new LinkedList<>(); Deque<Deque<GridReference>> path = new LinkedList<>(); nodes.add(currentNode); path.add(new LinkedList<>(ImmutableList.of(startingPoint))); // Head of head of path is the next grid reference to examine. while (!path.isEmpty()) { Deque<GridReference> head = path.peek(); // if the head is empty then remove it and roll back a letter. if (head.isEmpty()) { path.pop(); if (!path.isEmpty()) { path.peek().pop(); currentWord.deleteCharAt(currentWord.length() - 1); } nodes.pop(); } else { // Otherwise, there's a new grid reference to check. GridReference ref = head.peek(); char nextLetter = grid.letterAt(ref); // if the current node has no child with the next letter then there's no point continuing. pop the current head. Trie.Node child = nodes.peek().getChild(nextLetter); if (child == null) { head.pop(); } else { nodes.push(child); currentWord.append(nextLetter); // Does this character make a word? if (child.isTerminal()) { words.add(new GridWord(currentWord.toString(), currentPath(path))); } // Investigate all of the surrounding nodes that aren't on the current path. Deque<GridReference> nextSteps = new LinkedList<>(); for (GridReference candidate : grid.surrounding(ref)) { if (!hasAlreadyVisited(candidate, path)) { nextSteps.push(candidate); } } path.push(nextSteps); } } } return words; } private boolean hasAlreadyVisited(GridReference reference, Deque<Deque<GridReference>> path) { for (Deque<GridReference> previous : path) { if (previous.peek().equals(reference)) { return true; } } return false; } private List<GridReference> currentPath(Deque<Deque<GridReference>> path) { List<GridReference> route = new ArrayList<>(path.size()); Iterator<Deque<GridReference>> it = path.descendingIterator(); while (it.hasNext()) { route.add(it.next().peek()); } return route; } }
34.140351
128
0.545735
ea6adedadc7d4048abc74b9148588962029f9428
4,271
package org.fluentlenium.adapter.cucumber; import org.fluentlenium.adapter.DefaultFluentControlContainer; import org.fluentlenium.adapter.FluentAdapter; import org.fluentlenium.adapter.FluentControlContainer; import org.fluentlenium.adapter.SharedMutator; import org.fluentlenium.core.annotation.Page; import org.fluentlenium.core.components.ComponentsManager; import org.fluentlenium.core.inject.DefaultContainerInstantiator; import org.fluentlenium.core.inject.FluentInjector; import java.util.Arrays; import static java.util.Objects.isNull; import static java.util.Objects.nonNull; /** * Container class for {@link FluentCucumberTest}. * <p> * It uses Sinlgeton pattern based on enum to makes sure that all Cucumber steps */ public enum FluentTestContainer { /** * Instance of FluentTestContainer. */ FLUENT_TEST; private ThreadLocal<FluentAdapter> fluentAdapter; private ThreadLocal<FluentControlContainer> controlContainer; private ThreadLocal<SharedMutator> sharedMutator; private ThreadLocal<FluentInjector> injector; private static Class<?> configClass; FluentTestContainer() { fluentAdapter = new ThreadLocal<>(); controlContainer = new ThreadLocal<>(); sharedMutator = new ThreadLocal<>(); injector = new ThreadLocal<>(); } /** * Returns single instance of adapter across all Cucumber steps. * * @return instance of fluent adapter */ public FluentAdapter instance() { if (isNull(fluentAdapter.get())) { controlContainer.set(new DefaultFluentControlContainer()); sharedMutator.set(new FluentCucumberSharedMutator()); if (nonNull(configClass)) { fluentAdapter.set(new FluentCucumberTest(controlContainer.get(), configClass, sharedMutator.get())); } else { fluentAdapter.set(new FluentCucumberTest(controlContainer.get(), sharedMutator.get())); } injector.set(new FluentInjector(fluentAdapter.get(), null, new ComponentsManager(fluentAdapter.get()), new DefaultContainerInstantiator(fluentAdapter.get()))); } return fluentAdapter.get(); } /** * Reset instance of FluentAdapter stored in container. */ public void reset() { sharedMutator.remove(); controlContainer.remove(); injector.remove(); configClass = null; fluentAdapter.remove(); } /** * Provide control container across different classes. * * @return control container instance. */ protected FluentControlContainer getControlContainer() { if (fluentAdapter.get() == null) { instance(); } return controlContainer.get(); } /** * Sets config class - needed to enable annotation configuration. * * @param clazz class annotated with @RunWith(FluentCucumber.class) */ public static void setConfigClass(Class clazz) { configClass = clazz; } /** * Returns used inside container SharedMutator * * @return SharedMutator instance */ protected SharedMutator getSharedMutator() { return sharedMutator.get(); } /** * Injector used in FluentObjectFactory for creating instances * * @return fluent injector without loaded full FluentControl context */ public FluentInjector injector() { return injector.get(); } /** * Creating new instances of pages. * * @param obj container obj which contains pages to initialize */ public void instantiatePages(Object obj) { Arrays.stream(obj.getClass().getDeclaredFields()) .filter(field -> field.isAnnotationPresent(Page.class)) .forEach(field -> { try { Object instance = injector.get().newInstance(field.getType()); field.setAccessible(true); field.set(obj, instance); field.setAccessible(false); } catch (IllegalAccessException e) { e.printStackTrace(); } }); } }
31.404412
116
0.636619
57898a4125dbb1b00477bc80b9ed53e78bd9ee22
252
package io.starteos.jeos.net.request; public class BlockHeaderStateRequest extends BaseRequest { private String block_num_or_id; public BlockHeaderStateRequest(String block_num_or_id) { this.block_num_or_id = block_num_or_id; } }
25.2
60
0.77381
2a146ace290109e15e2e54e5dc19f83807ed61f3
2,083
package mrghastien.thermocraft.common.capabilities.heat.transport.networks; import mrghastien.thermocraft.common.capabilities.heat.transport.cables.Cable; import mrghastien.thermocraft.util.MathUtils; import net.minecraft.core.BlockPos; import net.minecraft.world.level.Level; import java.util.Map; public class HeatConductorNetwork extends HeatNetwork { HeatConductorNetwork(long id, Level world) { super(id, world); } @Override public boolean contains(BlockPos pos) { return cables.containsKey(pos); } @Override protected void pushEnergyOut() { for (Map.Entry<BlockPos, TransferPoint> e : nodes.entrySet()) { TransferPoint point = e.getValue(); if(point.getGlobalType().canExtract()) e.getValue().pushEnergyOut(MathUtils.clampedMap(distanceToNearestAcceptor(e.getKey()), 100d, 1600d, 1d, 0.1d)); } } @Override public HeatNetworkHandler.HeatNetworkType type() { return HeatNetworkHandler.HeatNetworkType.CONDUCTOR; } @Override public int size() { return cables.size(); } @Override boolean canMerge(HeatNetwork other) { return other.type() == type(); } @Override protected void refresh() { refreshMap.forEach(this::refreshTransferPoint); refreshMap.clear(); } @Override public void requestRefresh(BlockPos pos, Cable cable) { if(!world.isClientSide() && contains(pos)) { needsRefresh = true; refreshMap.put(pos, cable); } } private int distanceToNearestAcceptor(BlockPos pos) { int nearest = Integer.MAX_VALUE; for (Map.Entry<BlockPos, TransferPoint> entry : nodes.entrySet()) { BlockPos p = entry.getKey(); TransferPoint n = entry.getValue(); if (p != pos && n.getGlobalType().canReceive()) { int dist = (int) p.distSqr(pos); if (dist < nearest) nearest = dist; } } return nearest; } }
28.534247
127
0.62314
6363837835466baa0236b1490fd37ab59e63470c
4,385
/* * Copyright (C) 2010,2011 ECOSUR, Andrew Waterman and Max Pimm * * Licensed under the Academic Free License v. 3.0. * http://www.opensource.org/licenses/afl-3.0.php */ /** * GentePlayer extends GridRegistrant to provide several Pente specific methods * for use by the Pente rule set. * * @author [email protected] */ package mx.ecosur.multigame.gente.entity; import javax.persistence.*; import mx.ecosur.multigame.grid.util.BeadString; import mx.ecosur.multigame.grid.entity.GridRegistrant; import mx.ecosur.multigame.grid.Color; import mx.ecosur.multigame.grid.entity.GridPlayer; import org.apache.commons.lang.builder.HashCodeBuilder; import java.util.HashSet; import java.util.Set; @Entity public class GentePlayer extends GridPlayer { private static final long serialVersionUID = -7540174337729169503L; private int points; private Set<Tria> trias; private Set<Tessera> tesseras; private GentePlayer partner; public GentePlayer () { super (); points = 0; partner = null; } /** * @param player * @param color */ public GentePlayer(GridRegistrant player, Color color) { super (player, color); } public void addTria(BeadString string) throws Exception { Tria t = new Tria(); t.setCells(string.getBeads()); getTrias().add(t); } public void addTessera (BeadString string) { Tessera t = new Tessera(); t.setCells(string.getBeads()); getTesseras().add(t); } public boolean containsString (BeadString comparison) { boolean ret = false; if (comparison.size() == 3) { if (trias != null) { Tria comp = new Tria(); try { comp.setCells(comparison.getBeads()); for (Tria t : trias) { ret = t.equals(comp); if (ret) break; } } catch (Exception e) { e.printStackTrace(); } } } else if (comparison.size() == 4) { if (tesseras != null) { Tessera comp = new Tessera(); comp.setCells(comparison.getBeads()); for (Tessera t : tesseras) { ret = comp.equals(t); if (ret) break; } } } return ret; } @OneToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE}, fetch=FetchType.EAGER) public GentePlayer getPartner() { return partner; } public void setPartner(GentePlayer partner) { this.partner = partner; } public int getPoints() { return points; } public void setPoints(int points) { this.points = points; } @OneToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE}, fetch=FetchType.EAGER) public Set<Tessera> getTesseras() { if (tesseras == null) tesseras = new HashSet<Tessera>(); return tesseras; } public void setTesseras(Set<Tessera> tesseras) { this.tesseras = tesseras; } @OneToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE}, fetch=FetchType.EAGER) public Set<Tria> getTrias() { if (trias == null) trias = new HashSet<Tria>(); return trias; } public void setTrias(Set<Tria> trias) { this.trias = trias; } @Override protected Object clone() throws CloneNotSupportedException { GentePlayer ret = new GentePlayer (); ret.setId(getId()); ret.points = points; ret.tesseras = tesseras; ret.trias = trias; ret.setColor(getColor()); ret.setName(getName()); ret.setTurn(isTurn()); ret.points = points; return ret; } @Override public boolean equals(Object obj) { boolean ret = false; if (obj instanceof GentePlayer) { GentePlayer comp = (GentePlayer) obj; if (comp.getName().equals(this.getName())) ret = true; } return ret; } @Override public int hashCode() { return new HashCodeBuilder().append(getId()).append(getName()).append(points).append(getColor()).toHashCode(); } }
26.10119
118
0.567845
b85e78749bc6e2906ed3f04dcc2e6173cf445360
3,420
/** * Copyright 2013-2019 the original author or authors from the Jeddict project (https://jeddict.github.io/). * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package io.github.jeddict.jsonb.spec; import static io.github.jeddict.jcode.util.AttributeType.CALENDAR; import static io.github.jeddict.jcode.util.AttributeType.DATE; import static io.github.jeddict.jcode.util.AttributeType.DURATION; import static io.github.jeddict.jcode.util.AttributeType.GREGORIAN_CALENDAR; import static io.github.jeddict.jcode.util.AttributeType.INSTANT; import static io.github.jeddict.jcode.util.AttributeType.LOCAL_DATE; import static io.github.jeddict.jcode.util.AttributeType.LOCAL_DATE_TIME; import static io.github.jeddict.jcode.util.AttributeType.LOCAL_TIME; import static io.github.jeddict.jcode.util.AttributeType.OFFSET_DATE_TIME; import static io.github.jeddict.jcode.util.AttributeType.OFFSET_TIME; import static io.github.jeddict.jcode.util.AttributeType.PERIOD; import static io.github.jeddict.jcode.util.AttributeType.SIMPLE_TIME_ZONE; import static io.github.jeddict.jcode.util.AttributeType.TIME_ZONE; import static io.github.jeddict.jcode.util.AttributeType.ZONED_DATE_TIME; import static io.github.jeddict.jcode.util.AttributeType.ZONE_ID; import static io.github.jeddict.jcode.util.AttributeType.ZONE_OFFSET; import io.github.jeddict.jpa.spec.validator.JsonbDateFormatValidator; import io.github.jeddict.source.AnnotatedMember; import io.github.jeddict.source.AnnotationExplorer; import java.util.Arrays; import java.util.HashSet; import java.util.Optional; import java.util.Set; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; /** * * @author jGauravGupta */ @XmlJavaTypeAdapter(value = JsonbDateFormatValidator.class) public class JsonbDateFormat extends JsonbFormat { private static final Set<String> SUPPORTED_TYPE = new HashSet<>(Arrays.asList(DATE,CALENDAR,GREGORIAN_CALENDAR,TIME_ZONE ,SIMPLE_TIME_ZONE, INSTANT,DURATION,PERIOD,LOCAL_DATE,LOCAL_TIME,LOCAL_DATE_TIME, ZONED_DATE_TIME,ZONE_ID,ZONE_OFFSET,OFFSET_DATE_TIME,OFFSET_TIME)); @Override public boolean isSupportedFormat(String type) { return SUPPORTED_TYPE.contains(type); } public static JsonbDateFormat load(AnnotatedMember member) { JsonbDateFormat jsonbDateFormat = null; Optional<AnnotationExplorer> annotationOpt = member.getAnnotation(javax.json.bind.annotation.JsonbDateFormat.class); if (annotationOpt.isPresent()) { AnnotationExplorer annotation = annotationOpt.get(); jsonbDateFormat = new JsonbDateFormat(); annotation.getString("value").ifPresent(jsonbDateFormat::setValue); annotation.getString("locale").ifPresent(jsonbDateFormat::setLocale); } return jsonbDateFormat; } }
46.849315
144
0.765789
7a332e56cc10553ae9d90d19408fb82048703440
1,141
package in.succinct.beckn.registry.db.model.onboarding; import com.venky.swf.db.Database; import com.venky.swf.db.annotations.column.UNIQUE_KEY; import com.venky.swf.db.annotations.column.indexing.Index; import com.venky.swf.db.annotations.model.HAS_DESCRIPTION_FIELD; import com.venky.swf.db.annotations.model.MENU; import com.venky.swf.db.model.Model; import java.util.List; @HAS_DESCRIPTION_FIELD("PARTICIPANT_ID") @MENU("Admin") public interface NetworkParticipant extends Model { @UNIQUE_KEY @Index public String getParticipantId(); public void setParticipantId(String id); public List<Attachment> getAttachments(); public List<NetworkRole> getNetworkRoles(); public List<ParticipantKey> getParticipantKeys(); public static NetworkParticipant find(String particpantId){ NetworkParticipant participant = Database.getTable(NetworkParticipant.class).newRecord(); participant.setParticipantId(particpantId); participant = Database.getTable(NetworkParticipant.class).getRefreshed(participant); return participant; } @Index public Long getCreatorUserId(); }
31.694444
97
0.7695
410cf125531c87f7b84b832192b86c47a70d4af5
5,082
/*- * #%L * Elastic APM Java agent * %% * Copyright (C) 2018 - 2020 Elastic and contributors * %% * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. 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. * #L% */ package co.elastic.apm.api; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.lang.invoke.MethodHandle; public abstract class AbstractSpanImpl implements Span { @Nonnull // co.elastic.apm.agent.impl.transaction.Span protected final Object span; AbstractSpanImpl(@Nonnull Object span) { this.span = span; } @Nonnull @Override public Span createSpan() { Object span = doCreateSpan(); return span != null ? new SpanImpl(span) : NoopSpan.INSTANCE; } @Nonnull @Override public Span startSpan(String type, @Nullable String subtype, @Nullable String action) { Object span = doCreateSpan(); if (span != null) { doSetTypes(span, type, subtype, action); return new SpanImpl(span); } return NoopSpan.INSTANCE; } @Nonnull @Override public Span startSpan() { Object span = doCreateSpan(); return span != null ? new SpanImpl(span) : NoopSpan.INSTANCE; } public void doSetStartTimestamp(long epochMicros) { // co.elastic.apm.agent.plugin.api.AbstractSpanInstrumentation$SetStartTimestampInstrumentation } private Object doCreateSpan() { // co.elastic.apm.agent.plugin.api.AbstractSpanInstrumentation$DoCreateSpanInstrumentation.doCreateSpan return null; } void doSetName(String name) { // co.elastic.apm.agent.plugin.api.AbstractSpanInstrumentation$SetNameInstrumentation.doSetName } void doSetType(String type) { // co.elastic.apm.agent.plugin.api.AbstractSpanInstrumentation$SetTypeInstrumentation.doSetType } private void doSetTypes(Object span, String type, @Nullable String subtype, @Nullable String action) { // co.elastic.apm.agent.plugin.api.AbstractSpanInstrumentation$SetTypesInstrumentation.doSetType } // keep for backwards compatibility reasons @Deprecated void doAddTag(String key, String value) { // co.elastic.apm.agent.plugin.api.AbstractSpanInstrumentation$AddStringLabelInstrumentation } void doAddStringLabel(String key, String value) { // co.elastic.apm.agent.plugin.api.AbstractSpanInstrumentation$AddStringLabelInstrumentation } void doAddNumberLabel(String key, Number value) { // co.elastic.apm.agent.plugin.api.AbstractSpanInstrumentation$AddNumberTagInstrumentation } void doAddBooleanLabel(String key, Boolean value) { // co.elastic.apm.agent.plugin.api.AbstractSpanInstrumentation$AddBooleanTagInstrumentation } @Override public void end() { // co.elastic.apm.agent.plugin.api.AbstractSpanInstrumentation$EndInstrumentation } @Override public void end(long epochMicros) { // co.elastic.apm.agent.plugin.api.AbstractSpanInstrumentation$EndWithTimestampInstrumentation } @Override public String captureException(Throwable throwable) { // co.elastic.apm.agent.plugin.api.AbstractSpanInstrumentation.CaptureExceptionInstrumentation return ""; } @Nonnull @Override public String getId() { // co.elastic.apm.agent.plugin.api.AbstractSpanInstrumentation.GetIdInstrumentation return ""; } @Nonnull @Override public String getTraceId() { // co.elastic.apm.agent.plugin.api.AbstractSpanInstrumentation.GetTraceIdInstrumentation return ""; } @Override public Scope activate() { // co.elastic.apm.agent.plugin.api.AbstractSpanInstrumentation.ActivateInstrumentation return new ScopeImpl(span); } @Override public boolean isSampled() { // co.elastic.apm.agent.plugin.api.AbstractSpanInstrumentation.IsSampledInstrumentation return false; } @Override public void injectTraceHeaders(HeaderInjector headerInjector) { doInjectTraceHeaders(ApiMethodHandles.ADD_HEADER, headerInjector); } private void doInjectTraceHeaders(MethodHandle addHeader, HeaderInjector headerInjector) { // co.elastic.apm.agent.plugin.api.AbstractSpanInstrumentation.InjectTraceHeadersInstrumentation } }
32.787097
111
0.710547
94d4138639cc145314eab66df601e1b0328435d7
9,228
package com.psychowood.henkaku; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.Inet4Address; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.List; import java.util.Map; import fi.iki.elonen.NanoHTTPD; public class HenkakuWebServer extends NanoHTTPD { private static final String TAG = "HNKWebServer"; private static final String INDEX_HTML = "index.html"; private static final String STAGE1_PATH = "stage1/"; private static final String PAYLOAD_JS = STAGE1_PATH + "payload.js"; private static final String LOADER_BIN = "loader.rop.bin"; private static final String STAGE2_PATH = "stage2/"; private static final String EXPLOIT_BIN = "exploit.rop.bin"; private static final String PKG_PREFIX_PATH = "host/pkg"; private static final String LAST_FILE = "pkg/sce_sys/livearea/contents/template.xml"; private static int PORT = 8357; private WebServerHandler handler; public static void main(String[] argv) throws IOException { if (argv.length < 1) { System.out.println("Usage for serving files: java HenkakuWebServer path-to-asset-directory [port]"); System.out.println(" with path-to-asset-directory the directory containing all the needed files"); System.exit(-2); } final String assetDir = argv[0]; if (argv.length > 1) { try { PORT = Integer.parseInt(argv[1]); } catch (NumberFormatException e) { System.out.println("Invalid port number " + argv[1]); } } WebServerHandler serverHandler = new HenkakuWebServer.WebServerHandler() { @Override public InputStream openResource(String resourceName) throws IOException { return new FileInputStream(assetDir + resourceName); } @Override public void receivedRequest(final NanoHTTPD.IHTTPSession session) { System.out.println(session.getUri()); } @Override public void log(String tag, String s) { System.out.println(s); } @Override public void log(String tag, String s, Exception ex) { System.out.println(s); ex.printStackTrace(); } @Override public void done() { System.out.println("======================"); System.out.println("======= ENJOY! ======="); System.out.println("======================"); } }; HenkakuWebServer server = new HenkakuWebServer(serverHandler); server.start(PORT,false); final List<InetAddress> addresses = getLocalIpV4Addresses(); for (InetAddress inetAddress : addresses) { System.out.println("running at http://"+ inetAddress.getHostAddress() + ":" + server.getCurrentPort()); } } private HenkakuWebServer() { super(PORT); } public HenkakuWebServer(WebServerHandler handler) { super(PORT); this.handler = handler; } @Override public Response serve(IHTTPSession session) { handler.log(TAG, "Request: " + session.getUri()); Map<String, String> headers = session.getHeaders(); InputStream resInputStream = null; String resPath = INDEX_HTML; String resMimeType = MIME_HTML; try { handler.receivedRequest(session); if (session.getUri().length() > 1) { resPath = session.getUri().substring(1); resMimeType = NanoHTTPD.getMimeTypeForFile(resPath); } if (resPath.startsWith(STAGE1_PATH)) { //Stage1 if (resPath.endsWith(PAYLOAD_JS)) { String stage2Url = "http://" + headers.get("host") + "/" + STAGE2_PATH; /* Stage1 PAYLOAD_JS is generated as - LOADER_BIN - Write exploit URL - Preprocess as JS and serve to client */ InputStream loaderInputStream = handler.openResource(LOADER_BIN); ByteArrayOutputStream stage1ToProcess = new ByteArrayOutputStream(); HENprocess.writePkgUrl( loaderInputStream, stage1ToProcess, stage2Url ); ByteArrayOutputStream stage1Processed = new ByteArrayOutputStream(); HENprocess.preprocess( new ByteArrayInputStream(stage1ToProcess.toByteArray()), stage1Processed, true ); resInputStream = new ByteArrayInputStream(stage1Processed.toByteArray()); } else { // EXPLOIT_HTML and everything else will be served as is resInputStream = handler.openResource(resPath); } } else if (resPath.startsWith(STAGE2_PATH)){ //Stage2 int num_args = 7; Map<String,String> args = new HashMap<>(); final Map<String, List<String>> params = session.getParameters(); for (int i = 1; i <= num_args; ++i) { final String param = "a" + i; final List<String> val = params.get(param); if (val != null || val.size() > 0) { args.put(param,val.get(0)); } } InputStream exploitInputStream = handler.openResource(EXPLOIT_BIN); ByteArrayOutputStream stage2ToProcess = new ByteArrayOutputStream(); HENprocess.preprocess( exploitInputStream, stage2ToProcess, false ); String packageUrl = "http://" + headers.get("host") + "/" + PKG_PREFIX_PATH; ByteArrayOutputStream stage2Processed = new ByteArrayOutputStream(); HENprocess.writePkgUrl( new ByteArrayInputStream(stage2ToProcess.toByteArray()), stage2Processed, packageUrl ); byte[] payload = stage2Processed.toByteArray(); byte[] out = HENprocess.patchExploit(payload,args); resInputStream = new ByteArrayInputStream(out); } else { //Static resources (site & pkg) resInputStream = handler.openResource(resPath); } } catch (IOException ioe) { resInputStream = null; handler.log(TAG,"Error serving files",ioe); } catch (Exception ioe) { resInputStream = null; handler.log(TAG,"Error processing files",ioe); } handler.log(TAG,"Serving: " + resPath); if (resInputStream != null) { if (resPath.endsWith(LAST_FILE)) { new Thread(new Runnable() { @Override public void run() { handler.done(); } }).start(); } return NanoHTTPD.newChunkedResponse(Response.Status.OK, resMimeType, resInputStream); } else { final String html = "<html><head><head><body><h1>Sorry, something went wrong</h1><p></p></body></html>"; return NanoHTTPD.newFixedLengthResponse(Response.Status.NOT_FOUND, MIME_HTML, html); } } public static List<InetAddress> getLocalIpV4Addresses() throws SocketException { List<InetAddress> addresses = new ArrayList<>(); for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) { NetworkInterface intf = en.nextElement(); for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) { InetAddress inetAddress = enumIpAddr.nextElement(); if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) { addresses.add(inetAddress); } } } return addresses; } public int getCurrentPort() { return PORT; } public interface WebServerHandler { public InputStream openResource(String resourceName) throws IOException; public void receivedRequest(IHTTPSession session); public void log(String tag, String s); public void log(String tag, String s, Exception ex); public void done(); } }
36.330709
116
0.551907
f774d5564375337af12ebea9403a4aaaa7c777fb
3,553
/* * Copyright 2014-2016 Fukurou Mishiranu * * 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.mishiranu.dashchan.content.async; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import chan.content.ChanConfiguration; import chan.content.ChanPerformer; import chan.content.ExtensionException; import chan.content.InvalidResponseException; import chan.content.model.ThreadSummary; import chan.http.HttpException; import chan.http.HttpHolder; import chan.util.CommonUtils; import com.mishiranu.dashchan.content.model.ErrorItem; public class ReadThreadSummariesTask extends HttpHolderTask<Void, Void, ThreadSummary[]> { private final String chanName; private final String boardName; private final int pageNumber; private final int type; private final Callback callback; private ErrorItem errorItem; public interface Callback { public void onReadThreadSummariesSuccess(ThreadSummary[] threadSummaries, int pageNumber); public void onReadThreadSummariesFail(ErrorItem errorItem); } public ReadThreadSummariesTask(String chanName, String boardName, int pageNumber, int type, Callback callback) { this.chanName = chanName; this.boardName = boardName; this.pageNumber = pageNumber; this.type = type; this.callback = callback; } @Override protected ThreadSummary[] doInBackground(HttpHolder holder, Void... params) { try { ChanPerformer performer = ChanPerformer.get(chanName); ChanPerformer.ReadThreadSummariesResult result = performer.safe().onReadThreadSummaries(new ChanPerformer .ReadThreadSummariesData(boardName, pageNumber, type, holder)); ThreadSummary[] threadSummaries = result != null ? result.threadSummaries : null; return threadSummaries != null && threadSummaries.length > 0 ? threadSummaries : null; } catch (ExtensionException | HttpException | InvalidResponseException e) { errorItem = e.getErrorItemAndHandle(); return null; } finally { ChanConfiguration.get(chanName).commit(); } } @Override public void onPostExecute(ThreadSummary[] threadSummaries) { if (errorItem == null) { callback.onReadThreadSummariesSuccess(threadSummaries, pageNumber); } else { callback.onReadThreadSummariesFail(errorItem); } } public static ThreadSummary[] concatenate(ThreadSummary[] threadSummaries1, ThreadSummary[] threadSummaries2) { ArrayList<ThreadSummary> threadSummaries = new ArrayList<>(); if (threadSummaries1 != null) { Collections.addAll(threadSummaries, threadSummaries1); } HashSet<String> identifiers = new HashSet<>(); for (ThreadSummary threadSummary : threadSummaries) { identifiers.add(threadSummary.getBoardName() + '/' + threadSummary.getThreadNumber()); } if (threadSummaries2 != null) { for (ThreadSummary threadSummary : threadSummaries2) { if (!identifiers.contains(threadSummary.getBoardName() + '/' + threadSummary.getThreadNumber())) { threadSummaries.add(threadSummary); } } } return CommonUtils.toArray(threadSummaries, ThreadSummary.class); } }
35.888889
113
0.769209
742f14f9a04088abcf8c08d9e32c31bf0b56a595
5,402
/* * Copyright (c) 2012, 2017, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.javafx.tk.quantum; import com.sun.glass.ui.ClipboardAssistance; import com.sun.javafx.embed.EmbeddedSceneDSInterface; import com.sun.javafx.embed.HostDragStartListener; import com.sun.javafx.embed.EmbeddedSceneDTInterface; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicReference; import com.sun.javafx.tk.TKClipboard; import com.sun.javafx.tk.Toolkit; import javafx.application.Platform; import javafx.scene.input.TransferMode; final class EmbeddedSceneDnD { private final GlassSceneDnDEventHandler dndHandler; private HostDragStartListener dragStartListener; private EmbeddedSceneDSInterface fxDragSource; private EmbeddedSceneDTInterface fxDropTarget; private Thread hostThread; public EmbeddedSceneDnD(final GlassScene scene) { this.dndHandler = new GlassSceneDnDEventHandler(scene); } private void startDrag() { assert Platform.isFxApplicationThread(); assert fxDragSource != null; dragStartListener.dragStarted(fxDragSource, TransferMode.COPY); } private void setHostThread() { if (hostThread == null) { hostThread = Thread.currentThread(); } } public boolean isHostThread() { return (Thread.currentThread() == hostThread); } public void onDragSourceReleased(final EmbeddedSceneDSInterface ds) { assert fxDragSource == ds; fxDragSource = null; Toolkit.getToolkit().exitNestedEventLoop(this, null); } public void onDropTargetReleased(final EmbeddedSceneDTInterface dt) { fxDropTarget = null; } /* * This is a helper method to execute code on FX event thread. It * can be implemented using AWT nested event loop, however it just * blocks the current thread. This is done by intention, because * we need to handle Swing events one by one. If we enter a nested * event loop, various weird side-effects are observed, e.g. * dragOver() in SwingDnD is executed before dragEnter() is finished */ <T> T executeOnFXThread(final Callable<T> r) { // When running under SWT, the main thread is the FX thread // so execute the callable right away (return null on failure) if (Platform.isFxApplicationThread()) { try { return r.call(); } catch (Exception z) { // ignore } return null; } final AtomicReference<T> result = new AtomicReference<>(); final CountDownLatch l = new CountDownLatch(1); Platform.runLater(() -> { try { result.set(r.call()); } catch (Exception z) { // ignore } finally { l.countDown(); } }); try { l.await(); } catch (Exception z) { // ignore } return result.get(); } // Should be called from Scene.DnDGesture.createDragboard only! public TKClipboard createDragboard(boolean isDragSource) { assert Platform.isFxApplicationThread(); assert fxDragSource == null; assert isDragSource; ClipboardAssistance assistant = new ClipboardAssistance("DND-Embedded") { @Override public void flush() { super.flush(); startDrag(); // notify host Toolkit.getToolkit().enterNestedEventLoop(EmbeddedSceneDnD.this); // block current thread } }; fxDragSource = new EmbeddedSceneDS(this, assistant, dndHandler); return QuantumClipboard.getDragboardInstance(assistant, isDragSource); } public void setDragStartListener(HostDragStartListener l) { setHostThread(); dragStartListener = l; } public EmbeddedSceneDTInterface createDropTarget() { setHostThread(); return executeOnFXThread(() -> { assert fxDropTarget == null; fxDropTarget = new EmbeddedSceneDT(EmbeddedSceneDnD.this, dndHandler); return fxDropTarget; }); } }
33.141104
105
0.666235
3a0ec6de3a6d2772331ea83f4774f7948c731f66
1,167
package arithmetic; import java.util.ArrayList; import java.util.List; /** *@Description: 将所有在listB中存在,但listA中不存在的字符串,存放到A中(重复的也算) *@Author:Ryan *@Date:2018/1/29 23:36 */ public class ListMerge { /** * 将所有在listB中存在,但listA中不存在的字符串,存放到A中 */ public static List<String> comList(List<String> listA, List<String> listB){ int sizeA = listA.size(); int sizeB = listB.size(); for (int j=0;j<sizeB;j++){ boolean flag = true; for (int i = 0;i<sizeA;i++){ if ((listB.get(j).equals(listA.get(i)))){ flag = false; } } if (flag==true){ listA.add(listB.get(j)); } } return listA; } public static void main(String[] args) { List<String> a = new ArrayList<>(); List<String> b = new ArrayList<>(); for (int i = 1;i<11;i++){ a.add(String.valueOf(i)); b.add(String.valueOf(i+2)); } List<String> c = comList(a,b); for (int i = 0;i<c.size();i++){ System.out.println(c.get(i)); } } }
22.018868
79
0.491003
043374c1336a7cddc4b02e2169c566ee155a6e06
3,888
/* * Copyright 2016-2018 Talsma ICT * * 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 nl.talsmasoftware.umldoclet.html; import net.sourceforge.plantuml.FileFormat; import nl.talsmasoftware.umldoclet.configuration.Configuration; import nl.talsmasoftware.umldoclet.util.FileUtils; import java.io.File; import java.io.IOException; import java.nio.file.FileVisitResult; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.SimpleFileVisitor; import java.nio.file.attribute.BasicFileAttributes; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.regex.Pattern; import static java.util.Collections.unmodifiableCollection; import static java.util.Collections.unmodifiableList; import static java.util.stream.Collectors.toList; /** * Collects all generated diagram files from the output directory. * * @author Sjoerd Talsma */ final class DiagramCollector extends SimpleFileVisitor<Path> { private static final Pattern PACKAGE_DIAGRAM_PATTERN = Pattern.compile("package.[a-z]+$"); private final File basedir; private final Optional<File> imagesDirectory; private final List<String> diagramExtensions; private final ThreadLocal<Collection<UmlDiagram>> collected = ThreadLocal.withInitial(ArrayList::new); DiagramCollector(Configuration config) { this.basedir = new File(config.destinationDirectory()); this.diagramExtensions = unmodifiableList(config.images().formats().stream() .map(FileFormat::getFileSuffix) .map(String::toLowerCase) .map(format -> format.startsWith(".") ? format : "." + format) .collect(toList())); this.imagesDirectory = config.images().directory() .map(imagesDir -> new File(config.destinationDirectory(), imagesDir)); } /** * Collects all generated diagram files by walking the specified path. * * @return The collected diagrams * @throws IOException In case there were I/O errors walking the path */ Collection<UmlDiagram> collectDiagrams() throws IOException { if (diagramExtensions.isEmpty()) return Collections.emptySet(); try { Files.walkFileTree(imagesDirectory.orElse(basedir).toPath(), this); return unmodifiableCollection(collected.get()); } finally { collected.remove(); } } @Override public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException { if (attrs.isRegularFile() && FileUtils.hasExtension(path, diagramExtensions.get(0))) { createDiagramInstance(path).ifPresent(collected.get()::add); } return super.visitFile(path, attrs); } private boolean isPackageDiagram(File diagramFile) { return PACKAGE_DIAGRAM_PATTERN.matcher(diagramFile.getName()).find(); } private Optional<UmlDiagram> createDiagramInstance(Path diagramPath) { File diagramFile = diagramPath.normalize().toFile(); if (isPackageDiagram(diagramFile)) { return Optional.of(new UmlPackageDiagram(basedir, diagramFile, imagesDirectory.isPresent())); } return Optional.of(new UmlClassDiagram(basedir, diagramFile, imagesDirectory.isPresent())); } }
38.49505
106
0.716049
39f999f85363700f23ae0f6019af7b82ecc3a442
1,170
//package org.loed.framework.common.web.mvc.freemarker; // //import freemarker.template.Configuration; //import freemarker.template.TemplateException; // //import java.io.IOException; // ///** // * @author Thomason // * @version 1.0 // * @since 2016/9/19 15:22 // */ // //public class FreeMarkerConfigurer extends org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer { // private boolean localizedLookup = false; // private boolean whitespaceStripping = true; // private String defaultEncoding = "utf-8"; // // @Override // protected void postProcessConfiguration(Configuration config) throws IOException, TemplateException { // config.setLocalizedLookup(localizedLookup); // config.setWhitespaceStripping(whitespaceStripping); // config.setDefaultEncoding(defaultEncoding); // } // // public void setLocalizedLookup(boolean localizedLookup) { // this.localizedLookup = localizedLookup; // } // // public void setWhitespaceStripping(boolean whitespaceStripping) { // this.whitespaceStripping = whitespaceStripping; // } // // @Override // public void setDefaultEncoding(String defaultEncoding) { // this.defaultEncoding = defaultEncoding; // } //}
30
114
0.757265
96b392f800845d49f6073f69333e04b8f0658dbf
1,491
/** * Copyright (C) 2014 Karlsruhe Institute of Technology * * 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. */ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edu.kit.dama.mdm.dataorganization.entity.core; import edu.kit.dama.commons.types.ILFN; /** * The IFileNode represents an abstraction of the file-proxy. Besides the * properties inherited from {@link IDataOrganizationNode} it has a * logicalFileName property which is an unique identifier used to identify * StorageVirtualisationService layer file and for example retrieve its content * as a bitstream. * * @author pasic */ public interface IFileNode extends IDataOrganizationNode { /** * Gets the logical file name. * * @return logical file name */ ILFN getLogicalFileName(); /** * Sets the logical file name. * * @param logicalFileName The logical file name. */ void setLogicalFileName(ILFN logicalFileName); }
30.428571
79
0.731724
672f0f47b0f6d27e382650caa428aae2676f9a6d
5,599
/*! ****************************************************************************** * * Hop : The Hop Orchestration Platform * * Copyright (C) 2002-2017 by Hitachi Vantara : http://www.pentaho.com * http://www.project-hop.org * ******************************************************************************* * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ package org.apache.hop.workflow.actions.msgboxinfo; import org.apache.hop.core.ICheckResult; import org.apache.hop.core.Const; import org.apache.hop.core.Result; import org.apache.hop.core.annotations.Action; import org.apache.hop.core.exception.HopXmlException; import org.apache.hop.core.gui.GuiFactory; import org.apache.hop.core.gui.IThreadDialogs; import org.apache.hop.core.variables.IVariables; import org.apache.hop.core.xml.XmlHandler; import org.apache.hop.workflow.WorkflowMeta; import org.apache.hop.workflow.action.IAction; import org.apache.hop.workflow.action.ActionBase; import org.apache.hop.workflow.action.validator.ActionValidatorUtils; import org.apache.hop.metadata.api.IHopMetadataProvider; import org.w3c.dom.Node; import java.util.List; /** * Action type to display a message box. * * @author Samatar * @since 12-02-2007 */ @Action( id = "MSGBOX_INFO", i18nPackageName = "org.apache.hop.workflow.actions.msgboxinfo", name = "ActionMsgBoxInfo.Name", description = "ActionMsgBoxInfo.Description", image = "MsgBoxInfo.svg", categoryDescription = "i18n:org.apache.hop.workflow:ActionCategory.Category.Utility", documentationUrl = "https://hop.apache.org/manual/latest/plugins/actions/msgboxinfo.html" ) public class ActionMsgBoxInfo extends ActionBase implements Cloneable, IAction { private String bodymessage; private String titremessage; public ActionMsgBoxInfo( String n, String scr ) { super( n, "" ); bodymessage = null; titremessage = null; } public ActionMsgBoxInfo() { this( "", "" ); } public Object clone() { ActionMsgBoxInfo je = (ActionMsgBoxInfo) super.clone(); return je; } public String getXml() { StringBuilder retval = new StringBuilder( 50 ); retval.append( super.getXml() ); retval.append( " " ).append( XmlHandler.addTagValue( "bodymessage", bodymessage ) ); retval.append( " " ).append( XmlHandler.addTagValue( "titremessage", titremessage ) ); return retval.toString(); } public void loadXml( Node entrynode, IHopMetadataProvider metadataProvider ) throws HopXmlException { try { super.loadXml( entrynode ); bodymessage = XmlHandler.getTagValue( entrynode, "bodymessage" ); titremessage = XmlHandler.getTagValue( entrynode, "titremessage" ); } catch ( Exception e ) { throw new HopXmlException( "Unable to load action of type 'Msgbox Info' from XML node", e ); } } /** * Display the Message Box. */ public boolean evaluate( Result result ) { try { // default to ok // Try to display MSGBOX boolean response = true; IThreadDialogs dialogs = GuiFactory.getThreadDialogs(); if ( dialogs != null ) { response = dialogs.threadMessageBox( getRealBodyMessage() + Const.CR, getRealTitleMessage(), true, Const.INFO ); } return response; } catch ( Exception e ) { result.setNrErrors( 1 ); logError( "Couldn't display message box: " + e.toString() ); return false; } } /** * Execute this action and return the result. In this case it means, just set the result boolean in the Result * class. * * @param prev_result The result of the previous execution * @return The Result of the execution. */ public Result execute( Result prevResult, int nr ) { prevResult.setResult( evaluate( prevResult ) ); return prevResult; } public boolean resetErrorsBeforeExecution() { // we should be able to evaluate the errors in // the previous action. return false; } public boolean evaluates() { return true; } public boolean isUnconditional() { return false; } public String getRealTitleMessage() { return environmentSubstitute( getTitleMessage() ); } public String getRealBodyMessage() { return environmentSubstitute( getBodyMessage() ); } public String getTitleMessage() { if ( titremessage == null ) { titremessage = ""; } return titremessage; } public String getBodyMessage() { if ( bodymessage == null ) { bodymessage = ""; } return bodymessage; } public void setBodyMessage( String s ) { bodymessage = s; } public void setTitleMessage( String s ) { titremessage = s; } @Override public void check( List<ICheckResult> remarks, WorkflowMeta workflowMeta, IVariables variables, IHopMetadataProvider metadataProvider ) { ActionValidatorUtils.addOkRemark( this, "bodyMessage", remarks ); ActionValidatorUtils.addOkRemark( this, "titleMessage", remarks ); } }
28.712821
112
0.66244
3f866f33655539acbf2787f1f86c8086d5062047
2,468
package com.tom.protobuf.handler; import com.tom.protobuf.UserInfo; import io.netty.channel.ChannelHandler; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.ChannelInboundHandlerAdapter; import io.netty.handler.timeout.IdleState; import io.netty.handler.timeout.IdleStateEvent; import io.netty.util.ReferenceCountUtil; /** * @author WangTao */ @ChannelHandler.Sharable public class NettyProtobufServerHanlder extends ChannelInboundHandlerAdapter { private static int idle_count = 0; @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { System.out.printf("连接客户端%s\n",ctx.channel().remoteAddress()); UserInfo.UserMsg userMsg = UserInfo.UserMsg.newBuilder().setId(1) .setName("tom").setAge(22).build(); ctx.writeAndFlush(userMsg); } /** * 心跳检测 * @param ctx * @param evt * @throws Exception */ @Override public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { if (evt instanceof IdleStateEvent){ IdleStateEvent event = (IdleStateEvent)evt; // 如果读通道处于空闲状态,说明没有接收到心跳命令 if (IdleState.READER_IDLE.equals(event.state())) { System.out.println("已经5秒没有接收到客户端的信息了"); if (idle_count > 1) { System.out.println("关闭这个不活跃的channel"); ctx.channel().close(); } idle_count++; } }else { super.userEventTriggered(ctx,evt); } } @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { try { if (msg instanceof UserInfo.UserMsg) { UserInfo.UserMsg userState = (UserInfo.UserMsg) msg; if (userState.getState() == 1) { System.out.println("客户端业务处理成功!"); } else if(userState.getState() == 2){ System.out.println("接受到客户端发送的心跳!"); }else{ System.out.println("未知命令!"); } } else { System.out.println("未知数据--->!" + msg); } }finally { ReferenceCountUtil.release(msg); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { cause.printStackTrace(); ctx.close(); } }
28.697674
94
0.593598
3bda15cb0bb78c7cd3d0db49d579f5ce9ed086ca
792
package kr.gaulim.lib.string; public class Nvl { // private static final String TAG = Nvl.class.getSimpleName(); private Nvl() { } /** * <p>null을 빈 문자열로 바꾼다.</p> * * @param str 문자열 * * @return null이 제거된 문자열 */ public static String null2zero(final String str) { if ( ( null == str ) || "null".equalsIgnoreCase(str) ) return ""; else return str; } /** * <p>null을 빈 문자열로 바꾼다.</p> * * @param obj 문자열로 변환 가능한 객체 * * @return null이 제거된 문자열 */ public static String null2zero(final Object obj) { if ( null == obj ) return ""; else return null2zero(obj.toString()); } // End of Nvl.class } // End of Nvl.java
16.163265
64
0.496212
ba0663beb01f317993364687d84b9e99999788e4
481
package io.github.dunwu.tool.lang; import io.github.dunwu.tool.date.DateTime; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; public class DictTest { @Test public void dictTest() { Dict dict = Dict.create() .set("key1", 1)//int .set("key2", 1000L)//long .set("key3", DateTime.now());//Date Long v2 = dict.getLong("key2"); Assertions.assertEquals(Long.valueOf(1000L), v2); } }
22.904762
57
0.611227
becfb074f5b4b99541ff999d2cbf5a1d74c51e32
684
package entidad; public class Cliente { // atributos private String nombre; private String direccion; // constructores public Cliente() { } public Cliente(String nombre, String direccion) { super(); this.nombre = nombre; this.direccion = direccion; } // getters y setters public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getDireccion() { return direccion; } public void setDireccion(String direccion) { this.direccion = direccion; } @Override public String toString() { return "Cliente [\n\tnombre=" + nombre + ",\n\tdireccion=" + direccion + "\n]"; } }
15.2
72
0.672515
1cf947789c1122a12cc8df21588ccd868606b78b
9,740
package org.synyx.urlaubsverwaltung.account.service; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.synyx.urlaubsverwaltung.account.domain.Account; import org.synyx.urlaubsverwaltung.person.Person; import org.synyx.urlaubsverwaltung.testdatacreator.TestDataCreator; import java.math.BigDecimal; import java.time.LocalDate; import java.util.Optional; import static java.math.BigDecimal.ONE; import static java.math.BigDecimal.TEN; import static java.math.BigDecimal.ZERO; import static java.time.Month.DECEMBER; import static java.time.Month.JANUARY; import static java.time.Month.OCTOBER; import static org.assertj.core.api.Java6Assertions.assertThat; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class AccountInteractionServiceImplTest { private AccountInteractionServiceImpl sut; @Mock private AccountService accountService; @Mock private VacationDaysService vacationDaysService; private Person person; @Before public void setup() { sut = new AccountInteractionServiceImpl(accountService, vacationDaysService); person = TestDataCreator.createPerson("horscht"); } @Test public void testUpdateRemainingVacationDays() { LocalDate startDate = LocalDate.of(2012, JANUARY, 1); LocalDate endDate = LocalDate.of(2012, DECEMBER, 31); Account account2012 = new Account(person, startDate, endDate, BigDecimal.valueOf(30), BigDecimal.valueOf(5), ZERO, null); Account account2013 = new Account(person, startDate.withYear(2013), endDate.withYear(2013), BigDecimal.valueOf(30), BigDecimal.valueOf(3), ZERO, "comment1"); Account account2014 = new Account(person, startDate.withYear(2014), endDate.withYear(2014), BigDecimal.valueOf(30), BigDecimal.valueOf(8), ZERO, "comment2"); when(accountService.getHolidaysAccount(2012, person)).thenReturn(Optional.of(account2012)); when(accountService.getHolidaysAccount(2013, person)).thenReturn(Optional.of(account2013)); when(accountService.getHolidaysAccount(2014, person)).thenReturn(Optional.of(account2014)); when(accountService.getHolidaysAccount(2015, person)).thenReturn(Optional.empty()); when(vacationDaysService.calculateTotalLeftVacationDays(account2012)).thenReturn(BigDecimal.valueOf(6)); when(vacationDaysService.calculateTotalLeftVacationDays(account2013)).thenReturn(BigDecimal.valueOf(2)); sut.updateRemainingVacationDays(2012, person); verify(vacationDaysService).calculateTotalLeftVacationDays(account2012); verify(vacationDaysService).calculateTotalLeftVacationDays(account2013); verify(vacationDaysService, never()).calculateTotalLeftVacationDays(account2014); verify(accountService, never()).save(account2012); verify(accountService).save(account2013); verify(accountService).save(account2014); Assert.assertEquals("Wrong number of remaining vacation days for 2012", BigDecimal.valueOf(5), account2012.getRemainingVacationDays()); Assert.assertEquals("Wrong number of remaining vacation days for 2013", BigDecimal.valueOf(6), account2013.getRemainingVacationDays()); Assert.assertEquals("Wrong number of remaining vacation days for 2014", BigDecimal.valueOf(2), account2014.getRemainingVacationDays()); Assert.assertEquals("Wrong comment", null, account2012.getComment()); Assert.assertEquals("Wrong comment", "comment1", account2013.getComment()); Assert.assertEquals("Wrong comment", "comment2", account2014.getComment()); } @Test public void ensureCreatesNewHolidaysAccountIfNotExistsYet() { int year = 2014; int nextYear = 2015; LocalDate startDate = LocalDate.of(year, JANUARY, 1); LocalDate endDate = LocalDate.of(year, OCTOBER, 31); BigDecimal leftDays = BigDecimal.ONE; Account referenceHolidaysAccount = new Account(person, startDate, endDate, BigDecimal.valueOf(30), BigDecimal.valueOf(8), BigDecimal.valueOf(4), "comment"); when(accountService.getHolidaysAccount(nextYear, person)).thenReturn(Optional.empty()); when(vacationDaysService.calculateTotalLeftVacationDays(referenceHolidaysAccount)).thenReturn(leftDays); Account createdHolidaysAccount = sut.autoCreateOrUpdateNextYearsHolidaysAccount(referenceHolidaysAccount); Assert.assertNotNull("Should not be null", createdHolidaysAccount); Assert.assertEquals("Wrong person", person, createdHolidaysAccount.getPerson()); Assert.assertEquals("Wrong number of annual vacation days", referenceHolidaysAccount.getAnnualVacationDays(), createdHolidaysAccount.getAnnualVacationDays()); Assert.assertEquals("Wrong number of remaining vacation days", leftDays, createdHolidaysAccount.getRemainingVacationDays()); Assert.assertEquals("Wrong number of not expiring remaining vacation days", ZERO, createdHolidaysAccount.getRemainingVacationDaysNotExpiring()); Assert.assertEquals("Wrong validity start date", LocalDate.of(nextYear, 1, 1), createdHolidaysAccount.getValidFrom()); Assert.assertEquals("Wrong validity end date", LocalDate.of(nextYear, 12, 31), createdHolidaysAccount.getValidTo()); verify(accountService).save(createdHolidaysAccount); verify(vacationDaysService).calculateTotalLeftVacationDays(referenceHolidaysAccount); verify(accountService, times(2)).getHolidaysAccount(nextYear, person); } @Test public void ensureUpdatesRemainingVacationDaysOfHolidaysAccountIfAlreadyExists() { int year = 2014; int nextYear = 2015; LocalDate startDate = LocalDate.of(year, JANUARY, 1); LocalDate endDate = LocalDate.of(year, OCTOBER, 31); BigDecimal leftDays = BigDecimal.valueOf(7); Account referenceAccount = new Account(person, startDate, endDate, BigDecimal.valueOf(30), BigDecimal.valueOf(8), BigDecimal.valueOf(4), "comment"); Account nextYearAccount = new Account(person, LocalDate.of(nextYear, 1, 1), LocalDate.of( nextYear, 10, 31), BigDecimal.valueOf(28), ZERO, ZERO, "comment"); when(accountService.getHolidaysAccount(nextYear, person)).thenReturn(Optional.of(nextYearAccount)); when(vacationDaysService.calculateTotalLeftVacationDays(referenceAccount)).thenReturn(leftDays); Account account = sut.autoCreateOrUpdateNextYearsHolidaysAccount(referenceAccount); Assert.assertNotNull("Should not be null", account); Assert.assertEquals("Wrong person", person, account.getPerson()); Assert.assertEquals("Wrong number of annual vacation days", nextYearAccount.getAnnualVacationDays(), account.getAnnualVacationDays()); Assert.assertEquals("Wrong number of remaining vacation days", leftDays, account.getRemainingVacationDays()); Assert.assertEquals("Wrong number of not expiring remaining vacation days", ZERO, account.getRemainingVacationDaysNotExpiring()); Assert.assertEquals("Wrong validity start date", nextYearAccount.getValidFrom(), account.getValidFrom()); Assert.assertEquals("Wrong validity end date", nextYearAccount.getValidTo(), account.getValidTo()); verify(accountService).save(account); verify(vacationDaysService).calculateTotalLeftVacationDays(referenceAccount); verify(accountService).getHolidaysAccount(nextYear, person); } @Test public void createHolidaysAccount() { LocalDate validFrom = LocalDate.of(2014, JANUARY, 1); LocalDate validTo = LocalDate.of(2014, DECEMBER, 31); when(accountService.getHolidaysAccount(2014, person)).thenReturn(Optional.empty()); Account expectedAccount = sut.updateOrCreateHolidaysAccount(person, validFrom, validTo, TEN, ONE, ZERO, TEN, "comment"); assertThat(expectedAccount.getPerson()).isEqualTo(person); assertThat(expectedAccount.getAnnualVacationDays()).isEqualTo(TEN); assertThat(expectedAccount.getVacationDays()).isEqualTo(ONE); assertThat(expectedAccount.getRemainingVacationDays()).isSameAs(ZERO); assertThat(expectedAccount.getRemainingVacationDaysNotExpiring()).isEqualTo(TEN); verify(accountService).save(expectedAccount); } @Test public void updateHolidaysAccount() { LocalDate validFrom = LocalDate.of(2014, JANUARY, 1); LocalDate validTo = LocalDate.of(2014, DECEMBER, 31); Account account = new Account(person, validFrom, validTo, TEN, TEN, TEN, "comment"); when(accountService.getHolidaysAccount(2014, person)).thenReturn(Optional.of(account)); Account expectedAccount = sut.updateOrCreateHolidaysAccount(person, validFrom, validTo, ONE, ONE, ONE, ONE, "new comment"); assertThat(expectedAccount.getPerson()).isEqualTo(person); assertThat(expectedAccount.getAnnualVacationDays()).isEqualTo(ONE); assertThat(expectedAccount.getVacationDays()).isEqualTo(ONE); assertThat(expectedAccount.getRemainingVacationDays()).isSameAs(ONE); assertThat(expectedAccount.getRemainingVacationDaysNotExpiring()).isEqualTo(ONE); verify(accountService).save(expectedAccount); } }
46.380952
131
0.732341
9ceae9a4d9fc0be4251000abf53bc924f13f7774
3,762
/******************************************************************************* * Copyright 2013-2019 Qaprosoft (http://www.qaprosoft.com). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package com.qaprosoft.zafira.service.util; import com.qaprosoft.zafira.models.push.events.EventMessage; import com.qaprosoft.zafira.service.integration.tool.impl.MessageBrokerService; import org.springframework.amqp.AmqpException; import org.springframework.amqp.core.Message; import org.springframework.amqp.core.MessagePostProcessor; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.context.annotation.Lazy; import org.springframework.stereotype.Component; @Component public class EventPushService<T extends EventMessage> { private static final String EXCHANGE_NAME = "events"; private static final String SUPPLIER_QUEUE_NAME_HEADER = "SUPPLIER_QUEUE"; private final RabbitTemplate rabbitTemplate; private final MessageBrokerService messageBrokerService; public EventPushService(RabbitTemplate rabbitTemplate, @Lazy MessageBrokerService messageBrokerService) { this.rabbitTemplate = rabbitTemplate; this.messageBrokerService = messageBrokerService; } public enum Type { SETTINGS("settings"), ZFR_CALLBACKS("zfr_callbacks"), ZBR_EVENTS("zbr_events"), TENANCIES("tenancies"); private final String routingKey; Type(String routingKey) { this.routingKey = routingKey; } public String getRoutingKey() { return routingKey; } } public boolean convertAndSend(Type type, T eventMessage) { return convertAndSend(type, eventMessage, setSupplierQueueNameHeader()); } public boolean convertAndSend(Type type, T eventMessage, String headerName, String headerValue) { return convertAndSend(type, eventMessage, message -> { message.getMessageProperties().setHeader(headerName, headerValue); return message; }); } private boolean convertAndSend(Type type, T eventMessage, MessagePostProcessor messagePostProcessor) { try { rabbitTemplate.convertAndSend(EXCHANGE_NAME, type.getRoutingKey(), eventMessage, messagePostProcessor); return true; } catch (AmqpException e) { return false; } } private MessagePostProcessor setSupplierQueueNameHeader() { return message -> { message.getMessageProperties().getHeaders().putIfAbsent(SUPPLIER_QUEUE_NAME_HEADER, messageBrokerService.getSettingQueueName()); return message; }; } public boolean isSettingQueueConsumer(Message message) { return messageBrokerService.getSettingQueueName().equals(getSupplierQueueNameHeader(message)); } private String getSupplierQueueNameHeader(Message message) { Object supplier = message.getMessageProperties().getHeaders().get(SUPPLIER_QUEUE_NAME_HEADER); return supplier != null ? message.getMessageProperties().getHeaders().get(SUPPLIER_QUEUE_NAME_HEADER).toString() : null; } }
38.387755
140
0.691919
d33eb68c6e2c4132884b4ac6b67e614d04923043
5,009
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) annotate safe package android.support.constraint.solver.widgets; // Referenced classes of package android.support.constraint.solver.widgets: // ConstraintWidget public static final class ConstraintWidget$DimensionBehaviour extends Enum { public static ConstraintWidget$DimensionBehaviour valueOf(String s) { return (ConstraintWidget$DimensionBehaviour)Enum.valueOf(android/support/constraint/solver/widgets/ConstraintWidget$DimensionBehaviour, s); // 0 0:ldc1 #2 <Class ConstraintWidget$DimensionBehaviour> // 1 2:aload_0 // 2 3:invokestatic #43 <Method Enum Enum.valueOf(Class, String)> // 3 6:checkcast #2 <Class ConstraintWidget$DimensionBehaviour> // 4 9:areturn } public static ConstraintWidget$DimensionBehaviour[] values() { return (ConstraintWidget$DimensionBehaviour[])((ConstraintWidget$DimensionBehaviour []) ($VALUES)).clone(); // 0 0:getstatic #35 <Field ConstraintWidget$DimensionBehaviour[] $VALUES> // 1 3:invokevirtual #50 <Method Object _5B_Landroid.support.constraint.solver.widgets.ConstraintWidget$DimensionBehaviour_3B_.clone()> // 2 6:checkcast #46 <Class ConstraintWidget$DimensionBehaviour[]> // 3 9:areturn } private static final ConstraintWidget$DimensionBehaviour $VALUES[]; public static final ConstraintWidget$DimensionBehaviour FIXED; public static final ConstraintWidget$DimensionBehaviour MATCH_CONSTRAINT; public static final ConstraintWidget$DimensionBehaviour MATCH_PARENT; public static final ConstraintWidget$DimensionBehaviour WRAP_CONTENT; static { FIXED = new ConstraintWidget$DimensionBehaviour("FIXED", 0); // 0 0:new #2 <Class ConstraintWidget$DimensionBehaviour> // 1 3:dup // 2 4:ldc1 #18 <String "FIXED"> // 3 6:iconst_0 // 4 7:invokespecial #22 <Method void ConstraintWidget$DimensionBehaviour(String, int)> // 5 10:putstatic #24 <Field ConstraintWidget$DimensionBehaviour FIXED> WRAP_CONTENT = new ConstraintWidget$DimensionBehaviour("WRAP_CONTENT", 1); // 6 13:new #2 <Class ConstraintWidget$DimensionBehaviour> // 7 16:dup // 8 17:ldc1 #25 <String "WRAP_CONTENT"> // 9 19:iconst_1 // 10 20:invokespecial #22 <Method void ConstraintWidget$DimensionBehaviour(String, int)> // 11 23:putstatic #27 <Field ConstraintWidget$DimensionBehaviour WRAP_CONTENT> MATCH_CONSTRAINT = new ConstraintWidget$DimensionBehaviour("MATCH_CONSTRAINT", 2); // 12 26:new #2 <Class ConstraintWidget$DimensionBehaviour> // 13 29:dup // 14 30:ldc1 #28 <String "MATCH_CONSTRAINT"> // 15 32:iconst_2 // 16 33:invokespecial #22 <Method void ConstraintWidget$DimensionBehaviour(String, int)> // 17 36:putstatic #30 <Field ConstraintWidget$DimensionBehaviour MATCH_CONSTRAINT> MATCH_PARENT = new ConstraintWidget$DimensionBehaviour("MATCH_PARENT", 3); // 18 39:new #2 <Class ConstraintWidget$DimensionBehaviour> // 19 42:dup // 20 43:ldc1 #31 <String "MATCH_PARENT"> // 21 45:iconst_3 // 22 46:invokespecial #22 <Method void ConstraintWidget$DimensionBehaviour(String, int)> // 23 49:putstatic #33 <Field ConstraintWidget$DimensionBehaviour MATCH_PARENT> $VALUES = (new ConstraintWidget$DimensionBehaviour[] { FIXED, WRAP_CONTENT, MATCH_CONSTRAINT, MATCH_PARENT }); // 24 52:iconst_4 // 25 53:anewarray ConstraintWidget$DimensionBehaviour[] // 26 56:dup // 27 57:iconst_0 // 28 58:getstatic #24 <Field ConstraintWidget$DimensionBehaviour FIXED> // 29 61:aastore // 30 62:dup // 31 63:iconst_1 // 32 64:getstatic #27 <Field ConstraintWidget$DimensionBehaviour WRAP_CONTENT> // 33 67:aastore // 34 68:dup // 35 69:iconst_2 // 36 70:getstatic #30 <Field ConstraintWidget$DimensionBehaviour MATCH_CONSTRAINT> // 37 73:aastore // 38 74:dup // 39 75:iconst_3 // 40 76:getstatic #33 <Field ConstraintWidget$DimensionBehaviour MATCH_PARENT> // 41 79:aastore // 42 80:putstatic #35 <Field ConstraintWidget$DimensionBehaviour[] $VALUES> //* 43 83:return } private ConstraintWidget$DimensionBehaviour(String s, int i) { super(s, i); // 0 0:aload_0 // 1 1:aload_1 // 2 2:iload_2 // 3 3:invokespecial #37 <Method void Enum(String, int)> // 4 6:return } }
48.163462
145
0.643242
751ef4343a9e278235de800d2bae274d34e9b4c4
609
/* * 爱组搭 http://aizuda.com 低代码组件化开发平台 * ------------------------------------------ * 受知识产权保护,请勿删除版权申明 */ package com.aizuda.limiter.exception; /** * 分布式锁异常 * <p> * 尊重知识产权,CV 请保留版权,爱组搭 http://aizuda.com 出品 * * @author zhongjiahua * @since 2021-12-04 */ public class DistributedLockException extends RuntimeException { public DistributedLockException(Throwable cause) { super(cause); } public DistributedLockException(String message) { super(message); } public DistributedLockException(String message, Throwable cause) { super(message, cause); } }
20.3
70
0.627258
d672521ad0f801bbfac1e8329cf11e1d8327a308
1,890
/** * Copyright 2010 OpenConcept Systems,Inc. All rights reserved. */ package com.ocs.indaba.action; import com.ocs.indaba.common.Constants; import com.ocs.indaba.service.JournalVersionService; import com.ocs.util.StringUtils; import com.ocs.indaba.vo.JournalVersionView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.springframework.beans.factory.annotation.Autowired; /** * * @author Jeff Jiang */ public class JournalContentVersionAction extends BaseAction { private static final Logger logger = Logger.getLogger(JournalContentVersionAction.class); private static final String ATTR_JOURNAL_CONTENT_VERSION = "journalContentVersion"; private JournalVersionService jouralVersionService = null; @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { // Pre-process the request (from the super class) preprocess(mapping, request, response); int contentVersionId = StringUtils.str2int(request.getParameter(PARAM_CONTENT_VERSION_ID), Constants.INVALID_INT_ID); JournalVersionView journalContentVersion = jouralVersionService.getJournalContentVersion(contentVersionId); request.setAttribute(ATTR_JOURNAL_CONTENT_VERSION, journalContentVersion); request.setAttribute("attachments", journalContentVersion.getJournalAttachmentVersions()); return mapping.findForward(FWD_SUCCESS); } @Autowired public void setJournalVersionService(JournalVersionService jouralVersionService) { this.jouralVersionService = jouralVersionService; } }
38.571429
125
0.786772
79ebed30439cb687d42f2135dc907b014ca57df7
6,550
package com.example.ori.jnidemo.utils; import android.os.Handler; import android.util.Log; import com.example.ori.jnidemo.bean.ActionMessageEvent; import com.example.ori.jnidemo.bean.MessageEvent; import com.example.ori.jnidemo.bean.Order; import com.example.ori.jnidemo.bean.OrderValidate; import com.example.ori.jnidemo.constant.ComConstant; import com.example.ori.jnidemo.utils.serial_port.SerialHelper; import org.greenrobot.eventbus.EventBus; import java.io.IOException; /** * @author: hblolj * @date: 2018/12/24 9:30 * @description: */ public class OrderUtils { private static final String TAG = OrderUtils.class.getSimpleName(); public static void retrySendOrder(SerialHelper comHelper, OrderValidate validate, Handler myHandler){ validate.setRetryCount(validate.getRetryCount() + 1); SerialHelper.waitReplys.put(validate.getWaitReceiverOrder().getOrderContent(), validate); Log.d(TAG, "第" + validate.getRetryCount() + "次指令发送,指令内容: " + validate.getSendOrder().getOrderContent()); try { comHelper.sendHex(validate.getSendOrder(), validate.getWaitReceiverOrder().getOrderContent(), myHandler); } catch (IOException | InterruptedException e) { e.printStackTrace(); // 数据发送异常,移除存储的校验对象 SerialHelper.waitReplys.remove(validate.getWaitReceiverOrder().getOrderContent()); EventBus.getDefault().post(new MessageEvent("消息发送异常!", MessageEvent.MESSAGE_TYPE_NOTICE)); } } public static void sendOrder(SerialHelper comHelper, String targetAddress, String actionCode, String param, Handler myHandler, Integer retryCount){ Boolean empty = StringUtil.isEmpty(param); Order sendOrder = new Order(ComConstant.ANDROID_ADDRESS, targetAddress, actionCode, empty ? Order.DEFAULT_ORDER_PARAM : param); Order replyOrder = new Order(targetAddress, ComConstant.ANDROID_ADDRESS, actionCode, empty ? Order.DEFAULT_ORDER_PARAM : param); SerialHelper.waitReplys.put(replyOrder.getOrderContent(), new OrderValidate(sendOrder, replyOrder, retryCount)); Log.d(TAG, "第" + retryCount + "次指令发送,指令内容: " + sendOrder.getOrderContent()); try { comHelper.sendHex(sendOrder, replyOrder.getOrderContent(), myHandler); } catch (IOException | InterruptedException e) { e.printStackTrace(); // 数据发送异常,移除存储的校验对象 SerialHelper.waitReplys.remove(replyOrder.getOrderContent()); EventBus.getDefault().post(new MessageEvent("消息发送异常!", MessageEvent.MESSAGE_TYPE_NOTICE)); } } public static void sendOrder(SerialHelper comHelper, ActionMessageEvent event, Handler myHandler){ Boolean empty = StringUtil.isEmpty(event.getParam()); Order sendOrder = new Order(ComConstant.ANDROID_ADDRESS, event.getTargetAddress(), event.getActionCode(), empty ? Order.DEFAULT_ORDER_PARAM : event.getParam()); Order replyOrder = new Order(event.getTargetAddress(), ComConstant.ANDROID_ADDRESS, event.getActionCode(), empty ? Order.DEFAULT_ORDER_PARAM : event.getParam()); SerialHelper.waitReplys.put(replyOrder.getOrderContent(), new OrderValidate(sendOrder, replyOrder, event.getRetryCount())); Log.d(TAG, "第" + event.getRetryCount() + "次指令发送,指令内容: " + sendOrder.getOrderContent()); try { comHelper.sendHex(sendOrder, replyOrder.getOrderContent(), myHandler); } catch (IOException | InterruptedException e) { e.printStackTrace(); // 数据发送异常,移除存储的校验对象 SerialHelper.waitReplys.remove(replyOrder.getOrderContent()); EventBus.getDefault().post(new MessageEvent("消息发送异常!", MessageEvent.MESSAGE_TYPE_NOTICE)); } } public static void sendNeedResponseOrder(SerialHelper comHelper, String targetAddress, String actionCode, String param, Handler myHandler, Integer retryCount){ Boolean empty = StringUtil.isEmpty(param); Order sendOrder = new Order(ComConstant.ANDROID_ADDRESS, targetAddress, actionCode, empty ? Order.DEFAULT_ORDER_PARAM : param); Order replyOrder = new Order(targetAddress, ComConstant.ANDROID_ADDRESS, actionCode, empty ? Order.DEFAULT_ORDER_PARAM : param); // 操作码 转 10进制 + 1,然后转回 16进制 String resultAction = CommonUtil.hexAdd(actionCode, 1); String key = targetAddress + resultAction; SerialHelper.waitReplys.put(replyOrder.getOrderContent(), new OrderValidate(sendOrder, replyOrder, retryCount)); SerialHelper.waitResults.put(key, sendOrder); Log.d(TAG, "第" + retryCount + "次指令发送,指令内容: " + sendOrder.getOrderContent()); try { comHelper.sendHex(sendOrder, replyOrder.getOrderContent(), myHandler); } catch (IOException | InterruptedException e) { e.printStackTrace(); // 数据发送异常,移除存储的校验对象 SerialHelper.waitReplys.remove(replyOrder.getOrderContent()); SerialHelper.waitResults.remove(key); EventBus.getDefault().post(new MessageEvent("消息发送异常!", MessageEvent.MESSAGE_TYPE_NOTICE)); } } public static void sendNeedResponseOrder(SerialHelper comHelper, ActionMessageEvent event, Handler myHandler){ Boolean empty = StringUtil.isEmpty(event.getParam()); Order sendOrder = new Order(ComConstant.ANDROID_ADDRESS, event.getTargetAddress(), event.getActionCode(), empty ? Order.DEFAULT_ORDER_PARAM : event.getParam()); Order replyOrder = new Order(event.getTargetAddress(), ComConstant.ANDROID_ADDRESS, event.getActionCode(), empty ? Order.DEFAULT_ORDER_PARAM : event.getParam()); // 操作码 转 10进制 + 1,然后转回 16进制 String resultAction = CommonUtil.hexAdd(event.getActionCode(), 1); String key = event.getTargetAddress() + resultAction; SerialHelper.waitReplys.put(replyOrder.getOrderContent(), new OrderValidate(sendOrder, replyOrder, event.getRetryCount())); SerialHelper.waitResults.put(key, sendOrder); Log.d(TAG, "第" + event.getRetryCount() + "次指令发送,指令内容: " + sendOrder.getOrderContent()); try { comHelper.sendHex(sendOrder, replyOrder.getOrderContent(), myHandler); } catch (IOException | InterruptedException e) { e.printStackTrace(); // 数据发送异常,移除存储的校验对象 SerialHelper.waitReplys.remove(replyOrder.getOrderContent()); SerialHelper.waitResults.remove(key); EventBus.getDefault().post(new MessageEvent("消息发送异常!", MessageEvent.MESSAGE_TYPE_NOTICE)); } } }
51.171875
169
0.706107
7f4be97ee7572eb810f3201da3152d5c61c5fad7
1,553
package org.whyisthisnecessary.eps.economy; import org.bukkit.entity.Player; public interface Economy { /**Changes the specified player's balance. * * @param playername The player affected * @param amount The amount changed. Can be negative. * @return Returns the amount the player has after. */ public Integer changeBalance(String playername, Integer amount); /**Changes the specified player's balance. * * @param player The player affected * @param amount The amount changed. Can be negative. * @return Returns the amount the player has after. */ public Integer changeBalance(Player player, Integer amount); /**Sets the specified player's balance. * * @param playername The player affected * @param value The amount to be set to. * @return Returns the balance the player has after. */ public Integer setBalance(String playername, Integer value); /**Sets the specified player's balance. * * @param player The player affected * @param value The amount to be set to. * @return Returns the balance the player has after. */ public Integer setBalance(Player player, Integer value); /**Returns the balance of the specified player. * * @param player The player to get from * @return Returns the balance of the specified player. */ public Integer getBalance(Player player); /**Returns the balance of the specified player. * * @param playername The player to get from * @return Returns the balance of the specified player. */ public Integer getBalance(String playername); }
29.301887
65
0.725692
6b0e3ba00d932291c4b6a46c4efa0a3af0257b4e
3,011
/* * Copyright (C) 2017-2019 Dremio Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dremio.exec.planner.sql.parser; import java.util.List; import org.apache.calcite.sql.SqlCall; import org.apache.calcite.sql.SqlIdentifier; import org.apache.calcite.sql.SqlKind; import org.apache.calcite.sql.SqlLiteral; import org.apache.calcite.sql.SqlNode; import org.apache.calcite.sql.SqlOperator; import org.apache.calcite.sql.SqlSpecialOperator; import org.apache.calcite.sql.SqlWriter; import org.apache.calcite.sql.parser.SqlParserPos; import org.apache.calcite.util.ImmutableNullableList; import com.dremio.service.namespace.NamespaceKey; /** * SQL node tree for <code>ALTER TABLE table_identifier <ENABLE|DISABLE> APPROXIMATE STATS</code> */ public class SqlSetApprox extends SqlSystemCall { public static final SqlSpecialOperator OPERATOR = new SqlSpecialOperator("ENABLE_APPROXIMATE_STATS", SqlKind.OTHER) { @Override public SqlCall createCall(SqlLiteral functionQualifier, SqlParserPos pos, SqlNode... operands) { return new SqlSetApprox(pos, (SqlIdentifier) operands[0], (SqlLiteral) operands[1]); } }; private SqlIdentifier table; private SqlLiteral enable; /** Creates a SqlSetApprox. */ public SqlSetApprox(SqlParserPos pos, SqlIdentifier table, SqlLiteral enable) { super(pos); this.table = table; this.enable = enable; } @Override public void unparse(SqlWriter writer, int leftPrec, int rightPrec) { writer.keyword("ALTER"); writer.keyword("TABLE"); table.unparse(writer, leftPrec, rightPrec); if((Boolean) enable.getValue()) { writer.keyword("ENABLE"); } else { writer.keyword("DISABLE"); } writer.keyword("APPROXIMATE"); writer.keyword("STATS"); } @Override public void setOperand(int i, SqlNode operand) { switch (i) { case 0: table = (SqlIdentifier) operand; break; case 1: enable = (SqlLiteral) operand; break; default: throw new AssertionError(i); } } public boolean isEnable() { return (Boolean) enable.getValue(); } public NamespaceKey getPath() { return new NamespaceKey(table.names); } @Override public SqlOperator getOperator() { return OPERATOR; } @Override public List<SqlNode> getOperandList() { return ImmutableNullableList.<SqlNode>of(table, enable); } public SqlIdentifier getTable() { return table; } }
28.951923
97
0.709731
072eeb1e2f588cd4c9e52042da5288a99f1724b7
1,009
package com.aaa.javatest.fragment_test; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import androidx.appcompat.app.AppCompatActivity; import com.aaa.javatest.R; import com.aaa.javatest.fragment_test.FirstActivity; public class SecondActivity extends AppCompatActivity { private static final String TAG = "MainActivity"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); } public void jumpA(View view) { Intent intent = new Intent(this, FirstActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); Util.setFragStr("A"); startActivity(intent); } public void jumpB(View view) { Intent intent = new Intent(this, FirstActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); Util.setFragStr("B"); startActivity(intent); } }
28.027778
62
0.717542
e5184fe15581b60807632582575f3eefd897367c
2,195
package org.apache.commons.jcs.yajcache.lang.annotation; /* * 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. */ /** * Copyright Types. * * @author Hanson Char */ // @CopyRightApache // http://www.netbeans.org/issues/show_bug.cgi?id=53704 public enum CopyRightType { APACHE { @Override public String toString() { return "\n" + "/* ========================================================================\n" + " * Copyright 2005 The Apache Software Foundation\n" + " *\n" + " * Licensed under the Apache License, Version 2.0 (the \"License\");\n" + " * you may not use this file except in compliance with the License.\n" + " * You may obtain a copy of the License at\n" + " *\n" + " * http://www.apache.org/licenses/LICENSE-2.0\n" + " *\n" + " * Unless required by applicable law or agreed to in writing, software\n" + " * distributed under the License is distributed on an \"AS IS\" BASIS,\n" + " * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n" + " * See the License for the specific language governing permissions and\n" + " * limitations under the License.\n" + " * ========================================================================\n" + " */\n" ; } }; }
41.415094
93
0.582232
026237ce5f0e4ec42450bea222fdcd70d32984d0
443
package com.synaodev.automobile.car; import java.util.ArrayList; import java.util.List; public class Car { private List<CarPart> parts; public Car() { parts = new ArrayList<CarPart>(); parts.add(new Engine(40, 8)); parts.add(new FuelTank(60, 590)); parts.add(new Seats(50, 6)); parts.add(new Wheels(70, "Michelin")); parts.add(new Windows(80, true)); } public void run() { for (CarPart p : parts) { p.status(); } } }
20.136364
40
0.659142
1e2f82d458a5ae211006281ddc59420467328975
1,412
/** * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * <p> * Copyright (C) 2017 - 2017 Evgenii Lartcev (https://github.com/Evegen55/) and contributors * <p> * 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. * <p> * 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. * * @author Evgenii Lartcev * @created on 12/13/2017 */ package controllers.openvc; public enum RecognizingTypeOfDetection { write_video, face, plates_rus, edges, pedestrian }
54.307692
120
0.765581
0778cab7ca2f288b449a18b623f9fbdf037b5686
360
package org.beetl.ext.fn; import org.beetl.core.Context; import org.beetl.core.Function; import org.beetl.core.misc.ClassSearch; /** * 获取当前模板信息 * var a = meta.resource(); * @author xiandafu * */ public class ResourceFunction implements Function { @Override public Object call(Object[] paras, Context ctx) { return ctx.getResourceId(); } }
15.652174
51
0.705556
cc0cae2aea63886607dfbd223f576efde38d3d42
1,445
/* * Copyright 2013 The Sculptor Project Team, including 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.sculptor.examples.library.media.repositoryimpl; import org.sculptor.examples.library.media.domain.Library; import org.sculptor.examples.library.media.domain.LibraryRepository; import org.sculptor.framework.errorhandling.ValidationException; import org.springframework.stereotype.Repository; /** * Repository for Library */ @Repository("libraryRepository") public class LibraryRepositoryImpl extends LibraryRepositoryBase implements LibraryRepository { @Override public Library save(Library entity) { if (entity.getName().equals("err")) { throw new RuntimeException("SimulatedRuntimeException"); } if (entity.getName().equals("validation")) { throw new ValidationException("foo", "Simulated validation exception"); } return super.save(entity); } }
33.604651
95
0.764706
2390e61a5aabb143efd063e7a24736c118977e7a
1,120
/* * Copyright 2021 EPAM Systems. * * 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.epam.digital.data.platform.reportexporter.exception; import java.util.UUID; import javax.validation.constraints.NotBlank; public class MockEntity { private UUID entityId; @NotBlank private String excerptType; public UUID getEntityId() { return entityId; } public void setEntityId(UUID entityId) { this.entityId = entityId; } public String getExcerptType() { return excerptType; } public void setExcerptType(String excerptType) { this.excerptType = excerptType; } }
25.454545
75
0.735714
0fddbdd46abcb37b0bc021931f0cae4af82957f3
6,794
package org.firstinspires.ftc.teamcode.autonomous.step; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.DcMotorSimple; import com.qualcomm.robotcore.hardware.NormalizedColorSensor; import com.qualcomm.robotcore.hardware.Servo; import com.qualcomm.robotcore.util.ElapsedTime; import org.firstinspires.ftc.teamcode.ColorSensor; import org.firstinspires.ftc.teamcode.ManipulationManager; import org.firstinspires.ftc.teamcode.MovementManager; import org.firstinspires.ftc.teamcode.TelemetryManager; import org.firstinspires.ftc.teamcode.auxillary.PaulMath; import org.firstinspires.ftc.teamcode.data.RobotState; @Autonomous(group = "Step") public class FullLeft extends LinearOpMode { MovementManager driver; ManipulationManager hands; ElapsedTime runtime = new ElapsedTime(); ColorSensor sensor; ColorSensor sensorDown; boolean driveStarted; DcMotor fl; DcMotor fr; DcMotor bl; DcMotor br; TelemetryManager logger; private long delayRunTime; private ElapsedTime timer; private boolean delaying = false; public void wait(int delay) { if(!delaying) { timer = new ElapsedTime(); } while(timer.milliseconds() <= delay && opModeIsActive()) {} delaying = false; } @Override public void runOpMode() { telemetry.addData("Status", "Initialized"); telemetry.update(); driver = new MovementManager(hardwareMap.get(DcMotor.class, "fl"), hardwareMap.get(DcMotor.class, "fr"), hardwareMap.get(DcMotor.class, "bl"), hardwareMap.get(DcMotor.class, "br")); hands = new ManipulationManager( hardwareMap.get(Servo.class, "sev"), hardwareMap.get(DcMotor.class, "lift"), hardwareMap.get(Servo.class, "sideGrab"), hardwareMap.get(Servo.class, "sideLift"), hardwareMap.get(Servo.class, "foundationGrabber"), hardwareMap.get(Servo.class, "dropper") ); driver.resetAllEncoders(); driver.frontLeft.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); driver.frontRight.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); driver.backRight.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); driver.backLeft.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); hands.sideLift.setPosition(0); sensor = new ColorSensor(hardwareMap.get(NormalizedColorSensor.class, "sensor")); sensorDown = new ColorSensor(hardwareMap.get(NormalizedColorSensor.class, "sensorDown")); // Wait for the game to start (driver presses PLAY) waitForStart(); //Step 1: Drive sideways to the row of blocks driver.driveWhileHorizontal(0.5f, PaulMath.encoderDistance(21), this); wait(10); //Step 2: scan along the line for a SkyStone(tm) double msStart = System.currentTimeMillis(); driver.driveVertical(0.5f, 1f, this); while(!(sensor.isSkystone() || (System.currentTimeMillis() - msStart) > 1500) && opModeIsActive()) {} driver.resetAllEncoders(); driver.driveAuto(0,0,0,0); //branching fallback path-- if(!sensor.isSkystone()) { //Step 3 (fallback) go back and try again -only retries once msStart = System.currentTimeMillis(); driver.driveRaw(1, -1, -1, 1); while(!(sensorDown.isBled() || (System.currentTimeMillis() - msStart) > 1000) && opModeIsActive()) {} //Step 4 (fallback stop) driver.driveAuto(0f, 0f, 0f,0f); wait(10); stop(); } /*5*/ //TODO: Grabber code DOWN hands.setSideLiftPosition(1); wait(100); /*6*/ //TODO: Grabber code GRAB hands.setSideGrabberPosition(1); wait(100); /*7*/ //TODO: Grabber code UP hands.setSideLiftPosition(0.7); wait(100); //8 Drive back a bit so we don't disturb the other SkyStone(tm)s driver.driveWhileHorizontal(0.5f, -4f, this); wait(20); //9 Go to the other side of the blue/red line driver.driveVertical(0.5f, -PaulMath.encoderDistance(72), this); //10 while(!(sensor.isBled() || (System.currentTimeMillis() - msStart) > 3000) && opModeIsActive()) {} driver.resetAllEncoders(); driver.driveAuto(0,0,0,0); //branching fallback path-- go forward until we see the line if(!sensor.isBled()) { //fallback stop driver.driveAuto(0f, 0f, 0f,0f); wait(10); stop(); } wait(10); /*10*/ //TODO: Grabber code DOWN hands.setSideLiftPosition(1); wait(100); /*11*/ //TODO: Grabber code RELEASE hands.setSideGrabberPosition(0); wait(100); /*12*/ //TODO: Grabber code UP hands.setSideLiftPosition(0); wait(100); //13: move backwards to other SkyStone(tm) msStart = System.currentTimeMillis(); driver.driveVertical(0.5f, -PaulMath.encoderDistance(72), this); while(!(sensor.isSkystone() || (System.currentTimeMillis() - msStart) > 3000) && opModeIsActive()) {} driver.resetAllEncoders(); driver.driveAuto(0,0,0,0); //branching fallback path-- go forward until we see the line if(!sensor.isSkystone()) { //Step 14 (fallback) go forward until we detect the line msStart = System.currentTimeMillis(); driver.driveRaw(1, -1, -1, 1); while(!(sensorDown.isBled() || (System.currentTimeMillis() - msStart) > 2000) && opModeIsActive()) {} //Step 15 (fallback stop) driver.driveAuto(0f, 0f, 0f,0f); wait(10); stop(); } //13 Go to the other side of the blue/red line driver.driveVertical(0.5f, 10f, this); while(!(sensor.isBled() || (System.currentTimeMillis() - msStart) > 3000) && opModeIsActive()) {} driver.resetAllEncoders(); //branching fallback path-- go forward until we see the line if(!sensor.isBled()) { //fallback stop driver.driveAuto(0f, 0f, 0f,0f); wait(10); stop(); } /*14*/ //TODO: Grabber code DOWN hands.setSideLiftPosition(1); wait(10); /*15*/ //TODO: Grabber code RELEASE hands.setSideGrabberPosition(0); wait(10); /*16*/ //TODO: Grabber code UP hands.setSideLiftPosition(0); wait(10); } }
34.48731
113
0.618634
defeac208b6db724d46ab31af578988f3bee3aa9
340
package io.github.uetoyo.patterns.specification; import io.github.uetoyo.patterns.specification.protocols.Immutable; /** * The specification without any component. * * @param <T> The type of entity for which the specification is defined. */ @Immutable abstract class NullaryCompositeSpecification<T> implements Specification<T> { }
24.285714
77
0.782353
6f0498bab5bd1b4ecee6a7ce84d6645cf8a134d5
1,087
package org.gradoop.demo.server.pojo.enums; public class SamplingType { public enum Type { PAGE_RANK, EDGE, LIMITED_DEGREE_VERTEX, NON_UNIFORM_VERTEX, VERTEX_EDGE, VERTEX_NEIGHBORHOOD, VERTEX } private Type type; public SamplingType(String typeString) { switch (typeString) { case "page_rank": this.type = Type.PAGE_RANK; break; case "edge": this.type = Type.EDGE; break; case "limited_degree_vertex": this.type = Type.LIMITED_DEGREE_VERTEX; break; case "non_uniform_vertex": this.type = Type.NON_UNIFORM_VERTEX; break; case "vertex_edge": this.type = Type.VERTEX_EDGE; break; case "vertex_neighborhood": this.type = Type.VERTEX_NEIGHBORHOOD; break; case "vertex": this.type = Type.VERTEX; break; default: throw new IllegalArgumentException( "Sampling type '" + typeString + "' was not recognized."); } } public Type getType() { return this.type; } }
22.183673
68
0.604416
74b9166ac8fef67319e80ba04d34e7fbe356b26b
7,099
package mekanism.generators.client; import java.util.Map; import java.util.function.Function; import mekanism.client.ClientRegistrationUtil; import mekanism.client.render.item.ItemLayerWrapper; import mekanism.generators.client.gui.GuiBioGenerator; import mekanism.generators.client.gui.GuiGasGenerator; import mekanism.generators.client.gui.GuiHeatGenerator; import mekanism.generators.client.gui.GuiIndustrialTurbine; import mekanism.generators.client.gui.GuiReactorController; import mekanism.generators.client.gui.GuiReactorFuel; import mekanism.generators.client.gui.GuiReactorHeat; import mekanism.generators.client.gui.GuiReactorLogicAdapter; import mekanism.generators.client.gui.GuiReactorStats; import mekanism.generators.client.gui.GuiSolarGenerator; import mekanism.generators.client.gui.GuiTurbineStats; import mekanism.generators.client.gui.GuiWindGenerator; import mekanism.generators.client.render.RenderAdvancedSolarGenerator; import mekanism.generators.client.render.RenderBioGenerator; import mekanism.generators.client.render.RenderGasGenerator; import mekanism.generators.client.render.RenderHeatGenerator; import mekanism.generators.client.render.RenderIndustrialTurbine; import mekanism.generators.client.render.RenderReactor; import mekanism.generators.client.render.RenderTurbineRotor; import mekanism.generators.client.render.RenderWindGenerator; import mekanism.generators.client.render.item.RenderAdvancedSolarGeneratorItem; import mekanism.generators.client.render.item.RenderBioGeneratorItem; import mekanism.generators.client.render.item.RenderGasGeneratorItem; import mekanism.generators.client.render.item.RenderHeatGeneratorItem; import mekanism.generators.client.render.item.RenderWindGeneratorItem; import mekanism.generators.common.MekanismGenerators; import mekanism.generators.common.registries.GeneratorsBlocks; import mekanism.generators.common.registries.GeneratorsContainerTypes; import mekanism.generators.common.registries.GeneratorsTileEntityTypes; import net.minecraft.client.renderer.RenderType; import net.minecraft.client.renderer.model.IBakedModel; import net.minecraft.client.renderer.model.ModelResourceLocation; import net.minecraft.inventory.container.ContainerType; import net.minecraft.util.ResourceLocation; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.client.event.ModelBakeEvent; import net.minecraftforge.client.event.TextureStitchEvent; import net.minecraftforge.event.RegistryEvent; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent; @Mod.EventBusSubscriber(modid = MekanismGenerators.MODID, value = Dist.CLIENT, bus = Mod.EventBusSubscriber.Bus.MOD) public class GeneratorsClientRegistration { @SubscribeEvent public static void init(FMLClientSetupEvent event) { ClientRegistrationUtil.bindTileEntityRenderer(GeneratorsTileEntityTypes.ADVANCED_SOLAR_GENERATOR, RenderAdvancedSolarGenerator::new); ClientRegistrationUtil.bindTileEntityRenderer(GeneratorsTileEntityTypes.BIO_GENERATOR, RenderBioGenerator::new); ClientRegistrationUtil.bindTileEntityRenderer(GeneratorsTileEntityTypes.GAS_BURNING_GENERATOR, RenderGasGenerator::new); ClientRegistrationUtil.bindTileEntityRenderer(GeneratorsTileEntityTypes.HEAT_GENERATOR, RenderHeatGenerator::new); ClientRegistrationUtil.bindTileEntityRenderer(GeneratorsTileEntityTypes.REACTOR_CONTROLLER, RenderReactor::new); ClientRegistrationUtil.bindTileEntityRenderer(GeneratorsTileEntityTypes.TURBINE_CASING, RenderIndustrialTurbine::new); ClientRegistrationUtil.bindTileEntityRenderer(GeneratorsTileEntityTypes.TURBINE_ROTOR, RenderTurbineRotor::new); ClientRegistrationUtil.bindTileEntityRenderer(GeneratorsTileEntityTypes.TURBINE_VALVE, RenderIndustrialTurbine::new); ClientRegistrationUtil.bindTileEntityRenderer(GeneratorsTileEntityTypes.TURBINE_VENT, RenderIndustrialTurbine::new); ClientRegistrationUtil.bindTileEntityRenderer(GeneratorsTileEntityTypes.WIND_GENERATOR, RenderWindGenerator::new); //Block render layers ClientRegistrationUtil.setRenderLayer(RenderType.func_228645_f_(), GeneratorsBlocks.LASER_FOCUS_MATRIX, GeneratorsBlocks.REACTOR_GLASS); } @SubscribeEvent public static void registerContainers(RegistryEvent.Register<ContainerType<?>> event) { ClientRegistrationUtil.registerScreen(GeneratorsContainerTypes.BIO_GENERATOR, GuiBioGenerator::new); ClientRegistrationUtil.registerScreen(GeneratorsContainerTypes.GAS_BURNING_GENERATOR, GuiGasGenerator::new); ClientRegistrationUtil.registerScreen(GeneratorsContainerTypes.HEAT_GENERATOR, GuiHeatGenerator::new); ClientRegistrationUtil.registerScreen(GeneratorsContainerTypes.INDUSTRIAL_TURBINE, GuiIndustrialTurbine::new); ClientRegistrationUtil.registerScreen(GeneratorsContainerTypes.REACTOR_CONTROLLER, GuiReactorController::new); ClientRegistrationUtil.registerScreen(GeneratorsContainerTypes.REACTOR_FUEL, GuiReactorFuel::new); ClientRegistrationUtil.registerScreen(GeneratorsContainerTypes.REACTOR_HEAT, GuiReactorHeat::new); ClientRegistrationUtil.registerScreen(GeneratorsContainerTypes.REACTOR_LOGIC_ADAPTER, GuiReactorLogicAdapter::new); ClientRegistrationUtil.registerScreen(GeneratorsContainerTypes.REACTOR_STATS, GuiReactorStats::new); ClientRegistrationUtil.registerScreen(GeneratorsContainerTypes.SOLAR_GENERATOR, GuiSolarGenerator::new); ClientRegistrationUtil.registerScreen(GeneratorsContainerTypes.TURBINE_STATS, GuiTurbineStats::new); ClientRegistrationUtil.registerScreen(GeneratorsContainerTypes.WIND_GENERATOR, GuiWindGenerator::new); } @SubscribeEvent public static void onModelBake(ModelBakeEvent event) { Map<ResourceLocation, IBakedModel> modelRegistry = event.getModelRegistry(); registerItemStackModel(modelRegistry, "heat_generator", model -> RenderHeatGeneratorItem.model = model); registerItemStackModel(modelRegistry, "bio_generator", model -> RenderBioGeneratorItem.model = model); registerItemStackModel(modelRegistry, "wind_generator", model -> RenderWindGeneratorItem.model = model); registerItemStackModel(modelRegistry, "gas_burning_generator", model -> RenderGasGeneratorItem.model = model); registerItemStackModel(modelRegistry, "advanced_solar_generator", model -> RenderAdvancedSolarGeneratorItem.model = model); } private static void registerItemStackModel(Map<ResourceLocation, IBakedModel> modelRegistry, String type, Function<ItemLayerWrapper, IBakedModel> setModel) { ModelResourceLocation resourceLocation = ClientRegistrationUtil.getInventoryMRL(MekanismGenerators::rl, type); modelRegistry.put(resourceLocation, setModel.apply(new ItemLayerWrapper(modelRegistry.get(resourceLocation)))); } @SubscribeEvent public static void onStitch(TextureStitchEvent.Pre event) { RenderBioGenerator.resetCachedModels(); } }
68.92233
161
0.839977
13385885173e5d59d2ffcc63b3fe18d140bbe384
2,566
package com.wontlost.alert; import com.vaadin.flow.component.button.Button; import com.vaadin.flow.component.dependency.JsModule; import com.vaadin.flow.component.notification.Notification; import com.vaadin.flow.component.orderedlayout.FlexComponent; import com.vaadin.flow.component.orderedlayout.VerticalLayout; import com.vaadin.flow.component.page.Viewport; import com.vaadin.flow.router.PageTitle; import com.vaadin.flow.router.Route; import com.wontlost.sweetalert2.Config; import com.wontlost.sweetalert2.SweetAlert2Vaadin; import static com.wontlost.ckeditor.utils.Constant.PAGE_DEMO_ALERT; import static com.wontlost.ckeditor.utils.Constant.PAGE_DEMO_ZXING; /** * @author Ryan Pang * @date 4/15/2021 */ @JsModule("./styles/shared-styles.js") @Viewport("width=device-width, minimum-scale=1, initial-scale=1, user-scalable=yes, viewport-fit=cover") @Route(value = PAGE_DEMO_ALERT) @PageTitle("SweetAlert2") public class SweetAlert2View extends VerticalLayout { public SweetAlert2View(){ Button openAlert = new Button("Open Alert"); openAlert.addClickListener(buttonClickEvent -> { Config config = new Config(); config.setTitle("Error!!!"); config.setText("Something went wrong."); config.setIcon("error"); config.setShowCancelButton(true); config.setShowCloseButton(true); config.setFooter("<a href>Why do I have this issue?</a>"); SweetAlert2Vaadin sweetAlert2Vaadin = new SweetAlert2Vaadin(config); sweetAlert2Vaadin.open(); sweetAlert2Vaadin.addConfirmListener(e->{ Notification.show("Confirmed!"); System.out.println("confirm result : "+e.getSource().getSweetAlert2Result()); }); sweetAlert2Vaadin.addCancelListener(e->{ Notification.show("Cancelled!"); System.out.println("cancel result : "+e.getSource().getSweetAlert2Result()); }); sweetAlert2Vaadin.addCloseListener(e->{ Notification.show("Closed!"); System.out.println("close result : "+e.getSource().getSweetAlert2Result()); }); sweetAlert2Vaadin.addDenyListener(e->{ Notification.show("Denied!"); System.out.println("deny result : "+e.getSource().getSweetAlert2Result()); }); }); add(openAlert); setAlignItems(FlexComponent.Alignment.CENTER); } }
41.387097
105
0.652377
5306a4feee142cd0440f68c5ba2bdd8c4e73aeee
1,205
package com.charlyghislain.authenticator.domain.domain.secondary; import javax.validation.constraints.NotNull; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class ApplicationAuthenticatorAuthorizationHealth implements Serializable { @NotNull private String applicationName; private boolean reachable; private boolean authorizationHealthy; @NotNull private List<String> errors = new ArrayList<>(); public boolean isReachable() { return reachable; } public void setReachable(boolean reachable) { this.reachable = reachable; } public boolean isAuthorizationHealthy() { return authorizationHealthy; } public void setAuthorizationHealthy(boolean authorizationHealthy) { this.authorizationHealthy = authorizationHealthy; } public List<String> getErrors() { return errors; } public void setErrors(List<String> errors) { this.errors = errors; } public String getApplicationName() { return applicationName; } public void setApplicationName(String applicationName) { this.applicationName = applicationName; } }
24.591837
82
0.712033
afbbd269c72d713ecf92695594e1152a9d9e801e
396
package pl.plh.app.employment.service; import org.springframework.data.repository.CrudRepository; public class PersistServiceValidator { private PersistServiceValidator() { } static <E> void checkIdExists(CrudRepository<E, Long> repo, Long id, Class entityClass) { if (!repo.existsById(id)) { throw new NoSuchObjectException(entityClass, id); } } }
26.4
93
0.699495
fa9ecf5a1536042d960223d7ef6374d16170830a
4,187
package at.ac.tuwien.ifs.parser; import at.ac.tuwien.ifs.api.SimilarityApiMock; import org.apache.lucene.index.Term; import org.apache.lucene.search.BooleanQuery; import org.apache.lucene.search.Query; import org.apache.solr.common.params.ModifiableSolrParams; import org.apache.solr.search.QParser; import org.apache.solr.search.SyntaxError; import org.apache.solr.util.AbstractSolrTestCase; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import at.ac.tuwien.ifs.query.AugmentedTermQuery; import at.ac.tuwien.ifs.query.TermWeightTuple; /** * Unit tests, that check the correct "query string" -> "lucene augmented query" behavior * of the <code>{@link SimilarityParser}</code> */ public class SimilarityParserTest extends AbstractSolrTestCase { private static ModifiableSolrParams mockCorrectParams; @BeforeClass public static void beforeTests() throws Exception { // This is relative to the current working directory // when running the tests with intellij the current working directory is: the main Extensions folder // THIS could/will break test runs with other working directories ! // - resource folder has to be set explicitly, otherwise the base class takes the relative "solr/collection1" // and will not find it ... initCore("solrconfig.xml", "schema.xml", "src\\test\\resources\\"); mockCorrectParams = new ModifiableSolrParams(); mockCorrectParams.add("api:type","mock"); mockCorrectParams.add("query:method","GT"); mockCorrectParams.add("df","text"); mockCorrectParams.add("defType","similarityApiParser"); } @Test(expected = RuntimeException.class) public void test_missingParamsCompletely() throws SyntaxError { // arrange ModifiableSolrParams emptyParams = new ModifiableSolrParams(); // act - expect: exception QParser parser = new SimilarityParser("query",new ModifiableSolrParams(), emptyParams, req("query")); } @Test(expected = RuntimeException.class) public void test_missingParamsUrl() throws SyntaxError { // arrange ModifiableSolrParams params = new ModifiableSolrParams(); params.add("api:type","real"); // but missing api:url //act QParser parser = new SimilarityParser("query",new ModifiableSolrParams(),params,req("query")); } @Test public void test_singleTerm() throws SyntaxError { // arrange QParser parser = new SimilarityParser("first",new ModifiableSolrParams(),mockCorrectParams,req("first")); // act Query luceneQuery = parser.parse(); // assert AugmentedTermQuery expected = new AugmentedTermQuery( AugmentedTermQuery.ModelMethod.Generalized, new Term("text", "first"), new TermWeightTuple[]{SimilarityApiMock.similarTerm("text")} ); Assert.assertEquals(expected, luceneQuery); } @Test public void test_twoTerm() throws SyntaxError { // arrange QParser parser = new SimilarityParser("first second",new ModifiableSolrParams(),mockCorrectParams,req("first second")); // act Query luceneQuery = parser.parse(); // assert Assert.assertEquals(BooleanQuery.class, luceneQuery.getClass()); BooleanQuery realQuery = (BooleanQuery)luceneQuery; Assert.assertEquals(2,realQuery.clauses().size()); // first AugmentedTermQuery expected1 = new AugmentedTermQuery( AugmentedTermQuery.ModelMethod.Generalized, new Term("text", "first"), new TermWeightTuple[]{SimilarityApiMock.similarTerm("text")} ); Assert.assertEquals(expected1,realQuery.clauses().get(0).getQuery()); //second AugmentedTermQuery expected2 = new AugmentedTermQuery( AugmentedTermQuery.ModelMethod.Generalized, new Term("text", "second"), new TermWeightTuple[]{SimilarityApiMock.similarTerm("text")} ); Assert.assertEquals(expected2,realQuery.clauses().get(1).getQuery()); } }
36.408696
127
0.679245
186d77f82cfd7e96e6561898e09c932f4cbcc165
3,753
package com.changgou.order.controller; import com.changgou.entity.Result; import com.changgou.entity.StatusCode; import com.changgou.order.pojo.ReturnOrder; import com.changgou.order.service.ReturnOrderService; import com.github.pagehelper.PageInfo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; /**** * @Author:admin * @Description: * @Date 2019/6/14 0:18 *****/ @RestController @RequestMapping("/returnOrder") @CrossOrigin public class ReturnOrderController { @Autowired private ReturnOrderService returnOrderService; /*** * ReturnOrder分页条件搜索实现 * @param returnOrder * @param page * @param size * @return */ @PostMapping(value = "/search/{page}/{size}" ) public Result<PageInfo> findPage(@RequestBody(required = false) ReturnOrder returnOrder, @PathVariable int page, @PathVariable int size){ //调用ReturnOrderService实现分页条件查询ReturnOrder PageInfo<ReturnOrder> pageInfo = returnOrderService.findPage(returnOrder, page, size); return new Result(true, StatusCode.OK,"查询成功",pageInfo); } /*** * ReturnOrder分页搜索实现 * @param page:当前页 * @param size:每页显示多少条 * @return */ @GetMapping(value = "/search/{page}/{size}" ) public Result<PageInfo> findPage(@PathVariable int page, @PathVariable int size){ //调用ReturnOrderService实现分页查询ReturnOrder PageInfo<ReturnOrder> pageInfo = returnOrderService.findPage(page, size); return new Result<PageInfo>(true,StatusCode.OK,"查询成功",pageInfo); } /*** * 多条件搜索品牌数据 * @param returnOrder * @return */ @PostMapping(value = "/search" ) public Result<List<ReturnOrder>> findList(@RequestBody(required = false) ReturnOrder returnOrder){ //调用ReturnOrderService实现条件查询ReturnOrder List<ReturnOrder> list = returnOrderService.findList(returnOrder); return new Result<List<ReturnOrder>>(true,StatusCode.OK,"查询成功",list); } /*** * 根据ID删除品牌数据 * @param id * @return */ @DeleteMapping(value = "/{id}" ) public Result delete(@PathVariable Long id){ //调用ReturnOrderService实现根据主键删除 returnOrderService.delete(id); return new Result(true,StatusCode.OK,"删除成功"); } /*** * 修改ReturnOrder数据 * @param returnOrder * @param id * @return */ @PutMapping(value="/{id}") public Result update(@RequestBody ReturnOrder returnOrder,@PathVariable Long id){ //设置主键值 returnOrder.setId(id); //调用ReturnOrderService实现修改ReturnOrder returnOrderService.update(returnOrder); return new Result(true,StatusCode.OK,"修改成功"); } /*** * 新增ReturnOrder数据 * @param returnOrder * @return */ @PostMapping public Result add(@RequestBody ReturnOrder returnOrder){ //调用ReturnOrderService实现添加ReturnOrder returnOrderService.add(returnOrder); return new Result(true,StatusCode.OK,"添加成功"); } /*** * 根据ID查询ReturnOrder数据 * @param id * @return */ @GetMapping("/{id}") public Result<ReturnOrder> findById(@PathVariable Long id){ //调用ReturnOrderService实现根据主键查询ReturnOrder ReturnOrder returnOrder = returnOrderService.findById(id); return new Result<ReturnOrder>(true,StatusCode.OK,"查询成功",returnOrder); } /*** * 查询ReturnOrder全部数据 * @return */ @GetMapping public Result<List<ReturnOrder>> findAll(){ //调用ReturnOrderService实现查询所有ReturnOrder List<ReturnOrder> list = returnOrderService.findAll(); return new Result<List<ReturnOrder>>(true, StatusCode.OK,"查询成功",list) ; } }
29.320313
144
0.664002
dd07a655f07eb7cb99adbb95707bfac17d042843
306
package com.cloud.springcloud.configservice.service; import com.cloud.springcloud.entities.entity.Adver; import com.baomidou.mybatisplus.extension.service.IService; /** * <p> * 广告信息 服务类 * </p> * * @author wangcheng * @since 2021-04-19 */ public interface AdverService extends IService<Adver> { }
18
59
0.738562
7fe136c67afd8aa859da917f3e93f17cfde1cb80
2,441
package io.hefuyi.listener.dataloader; import android.content.ContentResolver; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.provider.MediaStore; import java.util.ArrayList; import java.util.List; import io.hefuyi.listener.mvp.model.Song; import io.hefuyi.listener.util.PreferencesUtility; import rx.Observable; import rx.Subscriber; /** * Created by hefuyi on 2016/11/4. */ public class ArtistSongLoader { public static Observable<List<Song>> getSongsForArtist(final Context context, final long artistID) { return Observable.create(new Observable.OnSubscribe<List<Song>>() { @Override public void call(Subscriber<? super List<Song>> subscriber) { Cursor cursor = makeArtistSongCursor(context, artistID); List<Song> songsList = new ArrayList<Song>(); if ((cursor != null) && (cursor.moveToFirst())) do { long id = cursor.getLong(0); String title = cursor.getString(1); String artist = cursor.getString(2); String album = cursor.getString(3); int duration = cursor.getInt(4); int trackNumber = cursor.getInt(5); long albumId = cursor.getInt(6); long artistId = artistID; songsList.add(new Song(id, albumId, artistId, title, artist, album, duration, trackNumber)); } while (cursor.moveToNext()); if (cursor != null){ cursor.close(); cursor = null; } subscriber.onNext(songsList); subscriber.onCompleted(); } }); } private static Cursor makeArtistSongCursor(Context context, long artistID) { ContentResolver contentResolver = context.getContentResolver(); final String artistSongSortOrder = PreferencesUtility.getInstance(context).getArtistSongSortOrder(); Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; String string = "is_music=1 AND title != '' AND artist_id=" + artistID; return contentResolver.query(uri, new String[]{"_id", "title", "artist", "album", "duration", "track", "album_id"}, string, null, artistSongSortOrder); } }
39.370968
159
0.597706
d75f694a3b78627067449257bc4c891d09217e8b
2,144
import java.awt.*; import java.awt.event.*; public class StringRequest extends Dialog { BorderLayout borderLayout1 = new BorderLayout(); Label label1 = new Label(); Panel panel1 = new Panel(); Panel panel2 = new Panel(); Button button1 = new Button(); BorderLayout borderLayout2 = new BorderLayout(); Button button2 = new Button(); TextField textField1 = null; String result = null; public StringRequest(Frame parent, String msg, String def, boolean question) { super(parent, true); try { this.setSize(new Dimension(209, 114)); this.setTitle("Aardappel Request:"); setBackground(SystemColor.control); label1.setText(msg); panel2.setLayout(borderLayout2); button1.setLabel("Ok"); button2.setLabel("Cancel"); this.setLayout(borderLayout1); this.add(label1, BorderLayout.NORTH); this.add(panel1, BorderLayout.SOUTH); this.add(panel2, BorderLayout.SOUTH); panel2.add(button1, BorderLayout.WEST); button1.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { quit(1); } }); if (question) panel2.add(button2, BorderLayout.EAST); button2.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { quit(0); } }); this.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { quit(0); } }); if (def != null) { textField1 = new TextField(def); this.add(textField1, BorderLayout.CENTER); textField1.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent e) { quit(1); } }); } this.pack(); this.setLocation(200, 200); this.show(); } catch (Exception e) { e.printStackTrace(); } } void quit(int n) { if (n == 1) result = (textField1 == null) ? "" : textField1.getText(); this.dispose(); } }
29.777778
80
0.58722
5fb05896952c673306dd9be568f4de16c39bc923
629
package p005cm.aptoide.p006pt.search.view; import p005cm.aptoide.p006pt.presenter.View.LifecycleEvent; import p026rx.p027b.C0132p; /* renamed from: cm.aptoide.pt.search.view.Tc */ /* compiled from: lambda */ public final /* synthetic */ class C4759Tc implements C0132p { /* renamed from: a */ private final /* synthetic */ SearchSuggestionsPresenter f8393a; public /* synthetic */ C4759Tc(SearchSuggestionsPresenter searchSuggestionsPresenter) { this.f8393a = searchSuggestionsPresenter; } public final Object call(Object obj) { return this.f8393a.mo16381f((LifecycleEvent) obj); } }
29.952381
91
0.72655
6cc3cb2cf83c94f9b234091dcbb31c22b860aec4
2,404
package com.dtstack.chunjun.connector.api; import com.dtstack.chunjun.connector.pgwal.conf.PGWalConf; import com.dtstack.chunjun.connector.pgwal.converter.PGWalColumnConverter; import com.dtstack.chunjun.connector.pgwal.listener.PgWalListener; import com.dtstack.chunjun.connector.pgwal.util.ChangeLog; import com.dtstack.chunjun.connector.pgwal.util.PgDecoder; import com.dtstack.chunjun.element.ErrorMsgRowData; import org.apache.flink.table.data.RowData; import com.google.common.collect.Lists; import com.google.gson.Gson; import org.apache.commons.lang3.StringUtils; import org.postgresql.jdbc.PgConnection; import org.postgresql.replication.PGReplicationStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Map; public class PGDataProcessor implements DataProcessor<RowData> { private static final Logger LOG = LoggerFactory.getLogger(PgWalListener.class); private static Gson gson = new Gson(); private PGWalConf conf; private PgConnection conn; private PGReplicationStream stream; private PgDecoder decoder; private PGWalColumnConverter converter; private ByteBuffer buffer; private volatile boolean running; public PGDataProcessor(Map<String, Object> param) { LOG.info("PgWalListener start running....."); } @Override public List<RowData> process(ServiceProcessor.Context context) throws Exception { assert context.contains("data"); ChangeLog changeLog = decoder.decode(context.get("data", ByteBuffer.class)); if (StringUtils.isBlank(changeLog.getId())) { return new ArrayList<>(); } String type = changeLog.getType().name().toLowerCase(); if (!conf.getCat().contains(type)) { return new ArrayList<>(); } if (!conf.getSimpleTables().contains(changeLog.getTable())) { return new ArrayList<>(); } LOG.trace("table = {}", gson.toJson(changeLog)); LinkedList<RowData> rowData = converter.toInternal(changeLog); return rowData; } @Override public boolean moreData() { return true; } @Override public List<RowData> processException(Exception e) { return Lists.newArrayList(new ErrorMsgRowData(e.getMessage())); } }
32.486486
85
0.72005
e4b3ee3a9afb9d120c4fc8ed413d8374cf87816b
332
package by.tc.task05.service.validator; import by.tc.task05.entity.HotelForm; import by.tc.task05.service.exception.ServiceException; /** * Interface that contains methods validating input associated with hotel's * actions */ public interface HotelValidator { void validateHotelForm(HotelForm form) throws ServiceException; }
25.538462
75
0.804217
2205e75d46f2d230bab1f4f511d5f9c90aeffb89
5,649
/* * Copyright 2014 TWO SIGMA OPEN SOURCE, LLC * * 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.twosigma.beakerx.chart.treemap; import com.twosigma.beakerx.chart.Chart; import com.twosigma.beakerx.chart.ChartToJson; import com.twosigma.beakerx.chart.treemap.util.ColorProvider; import com.twosigma.beakerx.chart.treemap.util.IToolTipBuilder; import com.twosigma.beakerx.chart.treemap.util.RandomColorProvider; import net.sf.jtreemap.swing.TreeMapNode; import static com.twosigma.beakerx.widget.BeakerxPlot.MODEL_NAME_VALUE; import static com.twosigma.beakerx.widget.BeakerxPlot.VIEW_NAME_VALUE; public class TreeMap extends Chart { public static final int ROWS_LIMIT = 1_000; // root of the tree private TreeMapNode root = null; // color provider private ColorProvider colorProvider = null; private IToolTipBuilder toolTipBuilder = null; /** * If mode is specified, sets the layout algorithm. If mode is not specified, returns the current layout * algorithm, which defaults to "squarify". The following modes are supported: * <p> * squarify - rectangular subdivision; squareness controlled via the target ratio. * slice - horizontal subdivision. * dice - vertical subdivision. * slice-dice - alternating between horizontal and vertical subdivision. */ private Mode mode; /** * If ratio is specified, sets the layout ratio. If ratio is not specified, returns the current layout * ratio, which defaults to .5 * (1 + Math.sqrt(5)) */ private Double ratio; /** * If sticky is specified, sets whether or not the treemap layout is "sticky": a sticky treemap * layout will preserve the relative arrangement of nodes across transitions. The allocation of nodes * into squarified horizontal and vertical rows is persisted across updates by storing a z attribute * on the last element in each row; this allows nodes to be resized smoothly, without shuffling or * occlusion that would impede perception of changing values. Note, however, that this results in a * suboptimal layout for one of the two states. If sticky is not specified, returns whether the * treemap layout is sticky. * Implementation note: sticky treemaps cache the array of nodes internally; therefore, * it is not possible to reuse the same layout instance on multiple datasets. To reset the * cached state when switching datasets with a sticky layout, call sticky(true) again. Since * version 1.25.0, hierarchy layouts no longer copy the input data by default on each invocation, * so it may be possible to eliminate caching and make the layout fully stateless. */ private Boolean sticky; /** * If round is specified, sets whether or not the treemap layout will round to exact pixel boundaries. * This can be nice to avoid antialiasing artifacts in SVG. If round is not specified, returns whether * the treemap will be rounded. */ private Boolean round; //determine value accessor for chart private ValueAccessor valueAccessor = ValueAccessor.VALUE; public TreeMap(final TreeMapNode root) { this(); setRoot(root); } public TreeMap() { super(); openComm(); setColorProvider(new RandomColorProvider()); setShowLegend(false); } /** * get the root. * * @return the root */ public TreeMapNode getRoot() { return root; } /** * set the new root. * * @param newRoot the new root to set */ public void setRoot(final TreeMapNode newRoot) { root = newRoot; } public Mode getMode() { return mode; } public void setMode(Mode mode) { this.mode = mode; sendModelUpdate(ChartToJson.serializeTreeMapMode(this.mode)); } public Double getRatio() { return ratio; } public void setRatio(Double ratio) { this.ratio = ratio; sendModelUpdate(ChartToJson.serializeTreeMapRatio(this.ratio)); } public Boolean getSticky() { return sticky; } public void setSticky(Boolean sticky) { this.sticky = sticky; sendModelUpdate(ChartToJson.serializeTreeMapSticky(this.sticky)); } public Boolean getRound() { return round; } public void setRound(Boolean round) { this.round = round; sendModelUpdate(ChartToJson.serializeTreeMapRound(this.round)); } public ValueAccessor getValueAccessor() { return valueAccessor; } public void setValueAccessor(ValueAccessor valueAccessor) { this.valueAccessor = valueAccessor; sendModelUpdate(ChartToJson.serializeTreeMapValueAccessor(this.valueAccessor)); } public void setColorProvider(final ColorProvider newColorProvider) { colorProvider = newColorProvider; } public ColorProvider getColorProvider() { return colorProvider; } public IToolTipBuilder getToolTipBuilder() { return toolTipBuilder; } public void setToolTipBuilder(IToolTipBuilder toolTipBuilder) { this.toolTipBuilder = toolTipBuilder; sendModelUpdate(); } @Override public String getModelNameValue() { return MODEL_NAME_VALUE; } @Override public String getViewNameValue() { return VIEW_NAME_VALUE; } }
29.731579
106
0.730041
8f1885c31aa3b25ba6e608b34e3ad63685700298
6,491
package systemtests; //@@author chernghann import static seedu.address.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import static seedu.address.logic.commands.CommandTestUtil.EVENT_ADDRESS_A_DESC; import static seedu.address.logic.commands.CommandTestUtil.EVENT_ADDRESS_B_DESC; import static seedu.address.logic.commands.CommandTestUtil.EVENT_DATE_A_DESC; import static seedu.address.logic.commands.CommandTestUtil.EVENT_DATE_B_DESC; import static seedu.address.logic.commands.CommandTestUtil.EVENT_NAME_A_DESC; import static seedu.address.logic.commands.CommandTestUtil.EVENT_NAME_B_DESC; import static seedu.address.logic.commands.CommandTestUtil.INVALID_ADDRESS_DESC; import static seedu.address.logic.commands.CommandTestUtil.INVALID_DATE_DESC; import static seedu.address.logic.commands.CommandTestUtil.INVALID_NAME_DESC; import static seedu.address.logic.commands.CommandTestUtil.VALID_EVENT_A_ADDRESS; import static seedu.address.logic.commands.CommandTestUtil.VALID_EVENT_A_DATE; import static seedu.address.logic.commands.CommandTestUtil.VALID_EVENT_A_NAME; import static seedu.address.logic.commands.CommandTestUtil.VALID_EVENT_B_ADDRESS; import static seedu.address.logic.commands.CommandTestUtil.VALID_EVENT_B_DATE; import static seedu.address.logic.commands.CommandTestUtil.VALID_EVENT_B_NAME; import static seedu.address.testutil.TypicalEvents.EVENT_A; import org.junit.Test; import seedu.address.logic.commands.AddEventCommand; import seedu.address.model.Model; import seedu.address.model.event.Date; import seedu.address.model.event.EventName; import seedu.address.model.event.ReadOnlyEvent; import seedu.address.model.event.exceptions.DuplicateEventException; import seedu.address.model.person.Address; import seedu.address.testutil.EventBuilder; public class AddEventCommandSystemTest extends AddressBookSystemTest { @Test public void add() throws Exception { Model model = getModel(); executeCommand("events"); ReadOnlyEvent toAdd = EVENT_A; String command = " " + AddEventCommand.COMMAND_WORD + " " + EVENT_NAME_A_DESC + " " + EVENT_DATE_A_DESC + " " + EVENT_ADDRESS_A_DESC + " "; assertCommandSuccess(command, toAdd); /* Case: add an event with all fields same as another event in the address book except name -> added */ toAdd = new EventBuilder().withName(VALID_EVENT_B_NAME).withDate(VALID_EVENT_A_DATE) .withAddress(VALID_EVENT_A_ADDRESS).build(); command = AddEventCommand.COMMAND_WORD + EVENT_NAME_B_DESC + EVENT_DATE_A_DESC + EVENT_ADDRESS_A_DESC; assertCommandSuccess(command, toAdd); /* Case: add an event with all fields same as another event in the address book except date -> added */ toAdd = new EventBuilder().withName(VALID_EVENT_A_NAME).withDate(VALID_EVENT_B_DATE) .withAddress(VALID_EVENT_A_ADDRESS).build(); command = AddEventCommand.COMMAND_WORD + EVENT_NAME_A_DESC + EVENT_DATE_B_DESC + EVENT_ADDRESS_A_DESC; assertCommandSuccess(command, toAdd); /* Case: add an event with all fields same as another event in the address book except address -> added */ toAdd = new EventBuilder().withName(VALID_EVENT_A_NAME).withDate(VALID_EVENT_A_DATE) .withAddress(VALID_EVENT_B_ADDRESS).build(); command = AddEventCommand.COMMAND_WORD + EVENT_NAME_A_DESC + EVENT_DATE_A_DESC + EVENT_ADDRESS_B_DESC; assertCommandSuccess(command, toAdd); /* Case: missing name -> rejected */ command = AddEventCommand.COMMAND_WORD + EVENT_DATE_A_DESC + EVENT_ADDRESS_A_DESC; assertCommandFailure(command, String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddEventCommand.MESSAGE_USAGE)); /* Case: missing date -> rejected */ command = AddEventCommand.COMMAND_WORD + EVENT_NAME_A_DESC + EVENT_ADDRESS_A_DESC; assertCommandFailure(command, String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddEventCommand.MESSAGE_USAGE)); /* Case: missing date -> rejected */ command = AddEventCommand.COMMAND_WORD + EVENT_NAME_A_DESC + EVENT_DATE_A_DESC; assertCommandFailure(command, String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddEventCommand.MESSAGE_USAGE)); /* Case: invalid name -> rejected */ command = AddEventCommand.COMMAND_WORD + INVALID_NAME_DESC + EVENT_DATE_A_DESC + EVENT_ADDRESS_A_DESC; assertCommandFailure(command, EventName.MESSAGE_EVENT_NAME_CONSTRAINTS); /* Case: invalid date -> rejected */ command = AddEventCommand.COMMAND_WORD + EVENT_NAME_A_DESC + INVALID_DATE_DESC + EVENT_ADDRESS_A_DESC; assertCommandFailure(command, Date.MESSAGE_DATE_CONSTRAINTS); /* Case: invalid date -> rejected */ command = AddEventCommand.COMMAND_WORD + EVENT_NAME_A_DESC + EVENT_DATE_A_DESC + INVALID_ADDRESS_DESC; assertCommandFailure(command, Address.MESSAGE_ADDRESS_CONSTRAINTS); } /** * Performs the same verification as {@code assertCommandSuccess(ReadOnlyPerson)} except that the result * display box displays {@code expectedResultMessage} and the model related components equal to * {@code expectedModel}. Executes {@code command} instead. */ private void assertCommandSuccess(String command, ReadOnlyEvent toAdd) { Model expectedModel = getModel(); try { expectedModel.addEvent(toAdd); } catch (DuplicateEventException dee) { throw new IllegalArgumentException("toAdd already exists in the model."); } executeCommand(command); } /** * Executes {@code command} and verifies that the command box displays {@code command}, the result display * box displays {@code expectedResultMessage} and the model related components equal to the current model. * These verifications are done by * {@code AddressBookSystemTest#assertApplicationDisplaysExpected(String, String, Model)}.<br> * Also verifies that the browser url, selected card and status bar remain unchanged, and the command box has the * error style. * @see AddressBookSystemTest#assertApplicationDisplaysExpected(String, String, Model) */ private void assertCommandFailure(String command, String expectedResultMessage) { executeCommand(command); assertEventDisplaysExpected(command, expectedResultMessage); assertCommandBoxShowsErrorStyle(); assertStatusBarUnchanged(); } }
52.346774
117
0.758589
b010a11e8c09b3a52ff7ec6cfacaee2d38d9a633
884
package com.kolyadko_polovtseva.book_maze.service; import com.kolyadko_polovtseva.book_maze.dto.SearchQueryDto; import com.kolyadko_polovtseva.book_maze.entity.Book; import com.kolyadko_polovtseva.book_maze.entity.Category; import com.kolyadko_polovtseva.book_maze.entity.LibraryBook; import java.util.List; import java.util.Set; /** * Created by nadez on 12/3/2016. */ public interface BookService { Integer RESERVE_PERIOD = 10; List<Book> findByCategory(Category category); Set<Book> findByCategory(Integer categoryId); Book find(Integer bookId); LibraryBook findLibraryBook(Integer bookId); LibraryBook findLibraryBook(Book book); Book findBookByCategoryIdAndBookId(Integer categoryId, Integer bookId); void save(Book book); List<Book> findAll(); Iterable<Book> search(SearchQueryDto query); void deleteById(Integer id); }
24.555556
75
0.771493
9b05cdf85efa15670542775c2ba4f9770d605c1b
10,371
package intextbooks; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Arrays; import java.util.Calendar; import java.util.List; import org.apache.commons.io.FileUtils; import intextbooks.Configuration; import intextbooks.SystemLogger; import intextbooks.content.ContentManager; import intextbooks.content.models.BookStatus; import intextbooks.exceptions.BookWithoutPageNumbersException; import intextbooks.exceptions.EarlyInterruptionException; import intextbooks.exceptions.NoIndexException; import intextbooks.exceptions.NotPDFFileException; import intextbooks.exceptions.TOCNotFoundException; import intextbooks.ontologie.LanguageEnum; import intextbooks.persistence.Persistence; import intextbooks.tools.utility.MD5Utils; public class TextbookProcessor { List<String> allowedExtensions = Arrays.asList("pdf"); ContentManager cm; String path; String id; LanguageEnum lang; boolean processReadingLabels; boolean linkWithDBpedia; String dbpediaCat; boolean linkToExternalGlossary; boolean splitTextbook; String senderEmail; String fullFileName; String fileName; String fileExtension; String filePath; String checksum; /** * Constructs a object that can be used to process a textbook to create its knowledge model * * @param path path to the PDF file of the textbook * @param lang language of the textbook, use the LanguageEnum * @param processReadingLabels true to find the reading labels of the the index terms * @param linkWithDBpedia true to link the index terms to DBpedia resources * @param dbpediaCat DBpedia category of the textbook * @param linkToExternalGlossary true to link tho an external glossary * @param splitTextbook true to split the textbook in PDF segments and TXT files * @param senderEmail email of the user who is creating the kwowledge model * @throws IOException * @throws FileNotFoundException * @throws NotPDFFileException */ public TextbookProcessor(String path, LanguageEnum lang, boolean processReadingLabels, boolean linkWithDBpedia, String dbpediaCat, boolean linkToExternalGlossary, boolean splitTextbook, String senderEmail) throws IOException, FileNotFoundException, NotPDFFileException { cm = ContentManager.getInstance(); this.path = path; this.lang = lang; this.processReadingLabels = processReadingLabels; this.linkWithDBpedia = linkWithDBpedia; this.linkToExternalGlossary = linkToExternalGlossary; this.splitTextbook = splitTextbook; this.senderEmail = senderEmail; this.dbpediaCat = dbpediaCat; //check if the file exists File file = new File(this.path); if(file.exists() && !file.isDirectory()) { //get the filename and extention of textbook int posLastBreak = path.lastIndexOf('/'); this.fullFileName = path.substring(posLastBreak+1); int posLastPeriod = this.fullFileName.lastIndexOf('.'); this.fileName = this.fullFileName.substring(0, posLastPeriod); this.fileExtension = this.fullFileName.substring(posLastPeriod+1); //check the extension of the file if(this.allowedExtensions.contains(this.fileExtension.toLowerCase())){ //create a new full file name using the date Calendar calendar = Calendar.getInstance(); java.util.Date now = calendar.getTime(); this.fullFileName = this.fileName + now.getTime() + "." + this.fileExtension; //copy the file into the folder for the repository this.filePath = Configuration.getInstance().getContentFolder()+this.fullFileName; try { FileUtils.copyFile(new File(path), new File(filePath)); } catch (IOException e) { throw new IOException ("There was an error copying the textbook file into the textbooks repository"); } this.checksum = MD5Utils.getCheckum(filePath); } else { throw new NotPDFFileException ("Textbook file should be a PDF file"); } } else { throw new FileNotFoundException ("Textbook file does not exists"); } } public void createTextbook() { this.id = cm.createBook(fullFileName, lang, fileName, checksum, "book", null, senderEmail); } public BookStatus processTextbook() throws NullPointerException, TOCNotFoundException, BookWithoutPageNumbersException, NoIndexException { return this.cm.processBook(id, fullFileName, lang, fileName, false, "book", null, processReadingLabels, linkWithDBpedia, dbpediaCat, linkToExternalGlossary, splitTextbook, senderEmail); } public String getBookId() { return this.id; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public LanguageEnum getLang() { return lang; } public void setLang(LanguageEnum lang) { this.lang = lang; } public boolean isProcessReadingLabels() { return processReadingLabels; } public void setProcessReadingLabels(boolean processReadingLabels) { this.processReadingLabels = processReadingLabels; } public boolean isLinkWithDBpedia() { return linkWithDBpedia; } public void setLinkWithDBpedia(boolean linkWithDBpedia) { this.linkWithDBpedia = linkWithDBpedia; } public boolean isLinkToExternalGlossary() { return linkToExternalGlossary; } public void setLinkToExternalGlossary(boolean linkToExternalGlossary) { this.linkToExternalGlossary = linkToExternalGlossary; } public boolean isSplitTextbook() { return splitTextbook; } public void setSplitTextbook(boolean splitTextbook) { this.splitTextbook = splitTextbook; } public String getSenderEmail() { return senderEmail; } public void setSenderEmail(String senderEmail) { this.senderEmail = senderEmail; } public String getFullFileName() { return fullFileName; } public void setFullFileName(String fullFileName) { this.fullFileName = fullFileName; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public String getFileExtension() { return fileExtension; } public void setFileExtension(String fileExtension) { this.fileExtension = fileExtension; } public String getFilePath() { return filePath; } public void setFilePath(String filePath) { this.filePath = filePath; } public String getChecksum() { return checksum; } public void setChecksum(String checksum) { this.checksum = checksum; } /** * Static method to process a textbook to create its knowledge model * * @param path path to the PDF file of the textbook * @param lang language of the textbook, use the LanguageEnum * @param processReadingLabels true to find the reading labels of the the index terms * @param linkWithDBpedia true to link the index terms to DBpedia resources * @param dbpediaCat DBpedia category of the textbook * @param linkToExternalGlossary true to link tho an external glossary * @param splitTextbook true to split the textbook in PDF segments and TXT files * @param senderEmail email of the user who is creating the knowledge model * @throws IOException * @throws FileNotFoundException * @throws NotPDFFileException */ public static void processFullTextbook(String path, LanguageEnum lang, boolean processReadingLabels, boolean linkWithDBpedia, String dbpediaCat, boolean linkToExternalGlossary, boolean splitTextbook, String senderEmail) { try { TextbookProcessor tbProcessor = new TextbookProcessor(path, lang, processReadingLabels, linkWithDBpedia, dbpediaCat, linkToExternalGlossary, splitTextbook, senderEmail); tbProcessor.createTextbook(); try { BookStatus bs = tbProcessor.processTextbook(); if(bs == BookStatus.Processed){ Persistence.getInstance().updateBookStatus(tbProcessor.getBookId(), bs); SystemLogger.getInstance().log("RESULT: The textbook was successfully processed and the models are stored in the corresponding folder."); } else { Persistence.getInstance().updateBookStatus(tbProcessor.getBookId(), bs); SystemLogger.getInstance().log("RESULT: The textbook was processed and the models are stored in the corresponding folder, but there was an error and the Enriched Model or part of it was not created succesfully. "); } } catch (NullPointerException e) { Persistence.getInstance().updateBookStatus(tbProcessor.getBookId(), BookStatus.Error); SystemLogger.getInstance().log("RESULT: The textbook was not finished processing due to an unknown error."); throw e; } catch (TOCNotFoundException e) { Persistence.getInstance().updateBookStatus(tbProcessor.getBookId(), BookStatus.TOCNotFound); SystemLogger.getInstance().log(e.getLocalizedMessage()); SystemLogger.getInstance().log("RESULT: The textbook was not finished processing because the textbook does not contain a Table of Contents."); } catch (BookWithoutPageNumbersException e) { Persistence.getInstance().updateBookStatus(tbProcessor.getBookId(), BookStatus.BookWithoutPageNumbers); SystemLogger.getInstance().log(e.getLocalizedMessage()); SystemLogger.getInstance().log("RESULT: The textbook was not finished processing because the textbook does not contain page numbers."); } catch (NoIndexException e) { Persistence.getInstance().updateBookStatus(tbProcessor.getBookId(), BookStatus.NoIndex); SystemLogger.getInstance().log(e.getLocalizedMessage()); SystemLogger.getInstance().log("RESULT: The textbook was not finished processing because the textbook does not contain an Index."); } } catch (FileNotFoundException e) { SystemLogger.getInstance().log(e.getLocalizedMessage()); SystemLogger.getInstance().log("RESULT: The textbook could not be processed because the pdf file does not exist."); } catch (IOException e) { SystemLogger.getInstance().log(e.getLocalizedMessage()); SystemLogger.getInstance().log("RESULT: The textbook could not be processed due to an I/O error."); } catch (NotPDFFileException e) { SystemLogger.getInstance().log(e.getLocalizedMessage()); SystemLogger.getInstance().log("RESULT: The textbook could not be processed because the file is not in PDF format."); } } public static void main(String args[]) { // ///home/alpiz001/Desktop/Walpole_Probability_and_Statistics.pdf TextbookProcessor.processFullTextbook("/home/alpiz001/Documents/INTERLINGUA_BOOKS/EduHintOVD/BRICKS-GEO-11-bwt.pdf", LanguageEnum.ENGLISH, false, false, null, false, false, "[email protected]"); } }
37.305755
271
0.766175
36fe773d63e9376476cf07387e0cde933129739a
3,730
/* * Copyright 2016 Ratha Long * * 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 nz.co.testamation.common.mail; import nz.co.testamation.testcommon.fixture.SomeFixture; import nz.co.testamation.testcommon.template.MockitoTestTemplate; import org.junit.Test; import javax.mail.BodyPart; import javax.mail.Multipart; import static org.hamcrest.Matchers.startsWith; public class MultipartMessageFactoryImplTest { abstract class Template extends MockitoTestTemplate { String textBody = SomeFixture.someString(); String htmlBody = SomeFixture.someString(); Email email = mock( Email.class ); AttachmentBodyPartFactory attachmentBodyPartFactory = mock( AttachmentBodyPartFactory.class ); EmailAttachment attachment1 = mock( EmailAttachment.class ); EmailAttachment attachment2 = mock( EmailAttachment.class ); BodyPart bodyPart1 = mock( BodyPart.class ); BodyPart bodyPart2 = mock( BodyPart.class ); } @Test public void happyDay() throws Exception { new Template() { Multipart actual; @Override protected void given() throws Exception { given( email.getHtmlBody() ).thenReturn( htmlBody ); given( email.getTextBody() ).thenReturn( textBody ); given( email.getAttachments() ).thenReturn( new EmailAttachment[]{attachment1, attachment2} ); given( attachmentBodyPartFactory.create( attachment1 ) ).thenReturn( bodyPart1 ); given( attachmentBodyPartFactory.create( attachment2 ) ).thenReturn( bodyPart2 ); } @Override protected void when() throws Exception { actual = new MultipartMessageFactoryImpl( attachmentBodyPartFactory ).create( email ); } @Override protected void then() throws Exception { assertThat( actual.getContentType(), startsWith( "multipart/alternative" ) ); assertThat( actual.getBodyPart( 0 ).getContent(), equalTo( textBody ) ); assertThat( actual.getBodyPart( 1 ).getContent(), equalTo( htmlBody ) ); assertThat( actual.getBodyPart( 2 ), equalTo( bodyPart1 ) ); assertThat( actual.getBodyPart( 3 ), equalTo( bodyPart2 ) ); } }.run(); } @Test public void createCorrectlyIfNoHtmlContent() throws Exception { new Template() { Multipart actual; @Override protected void given() throws Exception { given( email.getHtmlBody() ).thenReturn( null ); given( email.getTextBody() ).thenReturn( textBody ); } @Override protected void when() throws Exception { actual = new MultipartMessageFactoryImpl( attachmentBodyPartFactory ).create( email ); } @Override protected void then() throws Exception { assertThat( actual.getContentType(), startsWith( "multipart/mixed" ) ); assertThat( actual.getBodyPart( 0 ).getContent(), equalTo( textBody ) ); } }.run(); } }
35.188679
110
0.637265
3452b1b1ba6c835dbb18501dd04dd9faf49ac600
18,800
package org.codelogger.utils; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import org.codelogger.utils.exceptions.DateException; import org.codelogger.utils.lang.DatePeriod; /** * A useful tools to handle dates, likes get date from string, date format, get * date back, calculate date between, get first/last day of month, get * year/month/week/day/hour/minute/second and so on... * * @author DengDefei */ public class DateUtils { public static final int SUNDAY = 1; public static final int MONDAY = 2; public static final int TUESDAY = 3; public static final int WEDNESDAY = 4; public static final int THURSDAY = 5; public static final int FRIDAY = 6; public static final int SATURDAY = 7; public static final int JANUARY = 1; public static final int FEBRUARY = 2; public static final int MARCH = 3; public static final int APRIL = 4; public static final int MAY = 5; public static final int JUNE = 6; public static final int JULY = 7; public static final int AUGUST = 8; public static final int SEPTEMBER = 9; public static final int OCTOBER = 10; public static final int NOVEMBER = 11; public static final int DECEMBER = 12; private static final String DEFAULT_DATE_SIMPLE_PATTERN = "yyyy-MM-dd"; private static final String DEFAULT_DATETIME_24HOUR_PATTERN = "yyyy-MM-dd HH:mm:ss"; private static final ThreadLocal<SimpleDateFormat> simpleDateFormatCache = new ThreadLocal<SimpleDateFormat>(); private static final ThreadLocal<Calendar> calendarCache = new ThreadLocal<Calendar>(); private DateUtils() { } /** * The date format pattern is "yyyy-MM-dd HH:mm:ss", so you must put data like * this: '2012-12-21 00:00:00' * * @param dateString date string to be handled. * @return a new Date object by given date string. * @throws DateException */ public static Date getDateFromString(final String dateString) { return getDateFromString(dateString, DEFAULT_DATETIME_24HOUR_PATTERN); } /** * Get data from data string using the given pattern and the default date * format symbols for the default locale. * * @param dateString date string to be handled. * @param pattern pattern to be formated. * @return a new Date object by given date string and pattern. * @throws DateException */ public static Date getDateFromString(final String dateString, final String pattern) { try { SimpleDateFormat df = buildDateFormat(pattern); return df.parse(dateString); } catch (ParseException e) { throw new DateException(String.format("Could not parse %s with pattern %s.", dateString, pattern), e); } } /** * Format date by given pattern. * * @param date date to be handled. * @param pattern pattern use to handle given date. * @return a string object of format date by given pattern. */ public static String getDateFormat(final Date date, final String pattern) { SimpleDateFormat simpleDateFormat = buildDateFormat(pattern); return simpleDateFormat.format(date); } /** * Format date from given date string and date pattern by format pattern.<br> * <p> * e.g:<br> * date: '2012-12-21 13:14:20'<br> * datePattern: 'yyyy-MM-dd'<br> * formatPattern: 'yyyy-MM-dd 23:59:59'<br> * result: "2012-12-21 23:59:59" * </p> * * @param date date string to be handled. * @param datePattern pattern to handle date string to date object. * @param formatPattern pattern use to format given date. * @return format date from given date string and date pattern by format * pattern. * @throws DateException */ public static String getDateFormat(final String date, final String datePattern, final String formatPattern) { Date parsedDate = getDateFromString(date, datePattern); SimpleDateFormat simpleDateFormat = buildDateFormat(formatPattern); return simpleDateFormat.format(parsedDate); } /** * Get specify seconds back form given date. * * @param secondsBack how many second want to be back. * @param date date to be handled. * @return a new Date object. */ public static Date getDateOfSecondsBack(final int secondsBack, final Date date) { return dateBack(Calendar.SECOND, secondsBack, date); } /** * Get specify minutes back form given date. * * @param minutesBack how many minutes want to be back. * @param date date to be handled. * @return a new Date object. */ public static Date getDateOfMinutesBack(final int minutesBack, final Date date) { return dateBack(Calendar.MINUTE, minutesBack, date); } /** * Get specify hours back form given date. * * @param hoursBack how many hours want to be back. * @param date date to be handled. * @return a new Date object. */ public static Date getDateOfHoursBack(final int hoursBack, final Date date) { return dateBack(Calendar.HOUR_OF_DAY, hoursBack, date); } /** * Get specify days back from given date. * * @param daysBack how many days want to be back. * @param date date to be handled. * @return a new Date object. */ public static Date getDateOfDaysBack(final int daysBack, final Date date) { return dateBack(Calendar.DAY_OF_MONTH, daysBack, date); } /** * Get specify weeks back from given date. * * @param weeksBack how many weeks want to be back. * @param date date to be handled. * @return a new Date object. */ public static Date getDateOfWeeksBack(final int weeksBack, final Date date) { return dateBack(Calendar.WEEK_OF_MONTH, weeksBack, date); } /** * Get specify months back from given date. * * @param monthsBack how many months want to be back. * @param date date to be handled. * @return a new Date object. */ public static Date getDateOfMonthsBack(final int monthsBack, final Date date) { return dateBack(Calendar.MONTH, monthsBack, date); } /** * Get specify years back from given date. * * @param yearsBack how many years want to be back. * @param date date to be handled. * @return a new Date object. */ public static Date getDateOfYearsBack(final int yearsBack, final Date date) { return dateBack(Calendar.YEAR, yearsBack, date); } /** * Get the second within the minute by given date.<br> * E.g.: at 10:04:15.250 PM the SECOND is 15. * * @param date date to be handled. * @return second within the minute by given date. */ public static int getSecondOfMinute(final Date date) { return getNumberOfGranularity(Calendar.SECOND, date); } /** * Get the minute within the hour by given date.<br> * E.g.: at 10:04:15.250 PM the MINUTE is 4. * * @param date date to be handled. * @return minute within the hour by given date. */ public static int getMinuteOfHour(final Date date) { return getNumberOfGranularity(Calendar.MINUTE, date); } /** * Get the hour of the day by given date. HOUR_OF_DAY is used for the 24-hour * clock(0-23).<br> * E.g.: at 10:04:15.250 PM the HOUR_OF_DAY is 22. * * @param date date to be handled. * @return the hour of the day by given date. */ public static int getHourOfDay(final Date date) { return getNumberOfGranularity(Calendar.HOUR_OF_DAY, date); } /** * Get the day of the week by given date. This field takes values SUNDAY = 1, * MONDAY = 2, TUESDAY = 3, WEDNESDAY = 4, THURSDAY = 5, FRIDAY = 6, and * SATURDAY = 7. * * @param date date to be handled. * @return the day of the week by given date. */ public static int getDayOfWeek(final Date date) { int dayOfWeek = getNumberOfGranularity(Calendar.DAY_OF_WEEK, date); return dayOfWeek; } /** * Get the day of the month by given date. The first day of the month has * value 1. * * @param date date to be handled. * @return the day of the month by given date. */ public static int getDayOfMonth(final Date date) { return getNumberOfGranularity(Calendar.DAY_OF_MONTH, date); } /** * Get the day number within the year by given date. The first day of the year * has value 1. * * @param date date to be handled. * @return the day number within the year by given date. */ public static int getDayOfYear(final Date date) { return getNumberOfGranularity(Calendar.DAY_OF_YEAR, date); } /** * Get the week of the month by given date. The first week of the month has * value 1. * * @param date date to be handled. * @return the week of the month by given date. */ public static int getWeekOfMonth(final Date date) { return getNumberOfGranularity(Calendar.WEEK_OF_MONTH, date); } /** * Get the week number within the year by given date. The first week of the * year, the first week of the year value is 1. Subclasses define the value of * WEEK_OF_YEAR for days before the first week of the year. * * @param date date to be handled. * @return the week number within the year by given date. */ public static int getWeekOfYear(final Date date) { return getNumberOfGranularity(Calendar.WEEK_OF_YEAR, date); } /** * Get the month of year by given date. This is a calendar-specific value. The * first month of the year in the calendars is JANUARY which is 1; the last * depends on the number of months in a year. * * @param date date to be handled. * @return the month of year by given date. */ public static int getMonthOfYear(final Date date) { return getNumberOfGranularity(Calendar.MONTH, date) + 1; } /** * Get the year by given date. * * @param date date to be handled. * @return the year by given date. */ public static int getYear(final Date date) { return getNumberOfGranularity(Calendar.YEAR, date); } /** * Return true when if the given date is the first day of the month; false * otherwise. * * @param date date to be tested. * @return true when if the given date is the first day of the month; false * otherwise. */ public static boolean isFirstDayOfTheMonth(final Date date) { return getDayOfMonth(date) == 1; } /** * Return true if the given date is the last day of the month; false * otherwise. * * @param date date to be tested. * @return true if the given date is the last day of the month; false * otherwise. */ public static boolean isLastDayOfTheMonth(final Date date) { Date dateOfMonthsBack = getDateOfMonthsBack(-1, date); int dayOfMonth = getDayOfMonth(dateOfMonthsBack); Date dateOfDaysBack = getDateOfDaysBack(dayOfMonth, dateOfMonthsBack); return dateOfDaysBack.equals(date); } /** * Return current system date. * * @return a new date object which date is current system date. */ public static Date getCurrentDate() { return new Date(); } /** * Allocates a Date object and initializes it to represent the specified * number of milliseconds since the standard base time known as "the epoch", * namely January 1, 1970, 00:00:00 GMT. * * @param times number of milliseconds. * @return a Date object and initializes it to represent the specified number * of milliseconds since the standard base time known as "the epoch", * namely January 1, 1970, 00:00:00 GMT. */ public static Date BuildDate(final long times) { return new Date(times); } /** * Get how many seconds between two date. * * @param date1 date to be tested. * @param date2 date to be tested. * @return how many seconds between two date. */ public static long subSeconds(final Date date1, final Date date2) { return subTime(date1, date2, DatePeriod.SECOND); } /** * Get how many minutes between two date. * * @param date1 date to be tested. * @param date2 date to be tested. * @return how many minutes between two date. */ public static long subMinutes(final Date date1, final Date date2) { return subTime(date1, date2, DatePeriod.MINUTE); } /** * Get how many hours between two date. * * @param date1 date to be tested. * @param date2 date to be tested. * @return how many hours between two date. */ public static long subHours(final Date date1, final Date date2) { return subTime(date1, date2, DatePeriod.HOUR); } /** * Get how many days between two date, the date pattern is 'yyyy-MM-dd'. * * @param dateString1 date string to be tested. * @param dateString2 date string to be tested. * @return how many days between two date. * @throws DateException */ public static long subDays(final String dateString1, final String dateString2) { Date date1 = getDateFromString(dateString1, DEFAULT_DATE_SIMPLE_PATTERN); Date date2 = getDateFromString(dateString2, DEFAULT_DATE_SIMPLE_PATTERN); return subDays(date1, date2); } /** * Get how many days between two date. * * @param date1 date to be tested. * @param date2 date to be tested. * @return how many days between two date. */ public static long subDays(final Date date1, final Date date2) { return subTime(date1, date2, DatePeriod.DAY); } /** * Get how many months between two date, the date pattern is 'yyyy-MM-dd'. * * @param dateString1 date string to be tested. * @param dateString2 date string to be tested. * @return how many months between two date. * @throws DateException */ public static long subMonths(final String dateString1, final String dateString2) { Date date1 = getDateFromString(dateString1, DEFAULT_DATE_SIMPLE_PATTERN); Date date2 = getDateFromString(dateString2, DEFAULT_DATE_SIMPLE_PATTERN); return subMonths(date1, date2); } /** * Get how many months between two date. * * @param date1 date to be tested. * @param date2 date to be tested. * @return how many months between two date. */ public static long subMonths(final Date date1, final Date date2) { Calendar calendar1 = buildCalendar(date1); int monthOfDate1 = calendar1.get(Calendar.MONTH); int yearOfDate1 = calendar1.get(Calendar.YEAR); Calendar calendar2 = buildCalendar(date2); int monthOfDate2 = calendar2.get(Calendar.MONTH); int yearOfDate2 = calendar2.get(Calendar.YEAR); int subMonth = Math.abs(monthOfDate1 - monthOfDate2); int subYear = Math.abs(yearOfDate1 - yearOfDate2); return subYear * 12 + subMonth; } /** * Get how many years between two date, the date pattern is 'yyyy-MM-dd'. * * @param dateString1 date string to be tested. * @param dateString2 date string to be tested. * @return how many years between two date. * @throws DateException */ public static long subYears(final String dateString1, final String dateString2) { Date date1 = getDateFromString(dateString1, DEFAULT_DATE_SIMPLE_PATTERN); Date date2 = getDateFromString(dateString2, DEFAULT_DATE_SIMPLE_PATTERN); return subMonths(date1, date2); } /** * Get how many years between two date. * * @param date1 date to be tested. * @param date2 date to be tested. * @return how many years between two date. */ public static long subYears(final Date date1, final Date date2) { return Math.abs(getYear(date1) - getYear(date2)); } /** * Returns the beginning of the given day. <br/> * e.g: '2012-12-21 21:21:21' => '2012-12-21 00:00:00' * * @param date date to be handled. * @return a new date is beginning of the given day. * @throws DateException */ public static Date formatToStartOfDay(final Date date) { try { SimpleDateFormat dateFormat = buildDateFormat(DEFAULT_DATE_SIMPLE_PATTERN); String formattedDate = dateFormat.format(date); return dateFormat.parse(formattedDate); } catch (ParseException pe) { throw new DateException("Unparseable date specified.", pe); } } /** * Returns the beginning of the given day. <br/> * e.g: '2012-12-21 21:21:21' => '2012-12-21 23:59:59' * * @param date date to be handled. * @return a new date is ending of the given day. * @throws DateException */ public static Date formatToEndOfDay(final Date date) { return getDateOfSecondsBack(1, getDateOfDaysBack(-1, formatToStartOfDay(date))); } /** * Get a SimpleDateFormat object by given pattern. * * @param pattern date format pattern. * @return a SimpleDateFormat object by given pattern. */ private static SimpleDateFormat buildDateFormat(final String pattern) { SimpleDateFormat simpleDateFormat = simpleDateFormatCache.get(); if (simpleDateFormat == null) { simpleDateFormat = new SimpleDateFormat(); simpleDateFormatCache.set(simpleDateFormat); } simpleDateFormat.applyPattern(pattern); return simpleDateFormat; } /** * Gets a calendar using the default time zone and locale. The Calendar * returned is based on the current time in the default time zone with the * default locale. * * @return a Calendar object. */ private static Calendar buildCalendar() { Calendar calendar = calendarCache.get(); if (calendar == null) { calendar = GregorianCalendar.getInstance(); calendarCache.set(calendar); } return calendar; } /** * Gets a calendar using the default time zone and locale. The Calendar * returned is based on the given time in the default time zone with the * default locale. * * @return a Calendar object use given date. */ private static Calendar buildCalendar(final Date date) { Calendar calendar = buildCalendar(); calendar.setTime(date); return calendar; } private static long subTime(final Date date1, final Date date2, final long granularity) { long time1 = date1.getTime(); long time = date2.getTime(); long subTime = Math.abs(time1 - time); return subTime / granularity; } private static int getNumberOfGranularity(final int granularity, final Date date) { Calendar calendar = buildCalendar(date); return calendar.get(granularity); } private static long getTimeBackInMillis(final int granularity, final int numberToBack, final Date date) { Calendar calendar = buildCalendar(date); calendar.add(granularity, -numberToBack); long timeBackInMillis = calendar.getTimeInMillis(); return timeBackInMillis; } private static Date dateBack(final int granularity, final int numberToBack, final Date date) { long timeBackInMillis = getTimeBackInMillis(granularity, numberToBack, date); return BuildDate(timeBackInMillis); } }
29.467085
113
0.686436
eaa91438aab8f8e0c7b2d468f13f5e28e7fc9fb7
4,537
/* * Copyright © 2021 ProStore * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.arenadata.dtm.query.execution.plugin.adb.check; import io.arenadata.dtm.common.model.ddl.Entity; import io.arenadata.dtm.query.execution.plugin.adb.check.factory.impl.AdbCheckDataQueryFactory; import io.arenadata.dtm.query.execution.plugin.adb.check.service.AdbCheckDataService; import io.arenadata.dtm.query.execution.plugin.adb.query.service.impl.AdbQueryExecutor; import io.arenadata.dtm.query.execution.plugin.api.check.CheckDataByCountRequest; import io.arenadata.dtm.query.execution.plugin.api.check.CheckDataByHashInt32Request; import io.vertx.core.Future; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.HashMap; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.Mockito.*; class AdbCheckDataServiceTest { private final static Long RESULT = 1L; private final AdbQueryExecutor adbQueryExecutor = mock(AdbQueryExecutor.class); private final AdbCheckDataService adbCheckDataService = new AdbCheckDataService( new AdbCheckDataQueryFactory(), adbQueryExecutor); @BeforeEach void setUp() { when(adbQueryExecutor.executeUpdate(any())).thenReturn(Future.succeededFuture()); } @Test void testCheckByHash() { HashMap<String, Object> result = new HashMap<>(); result.put("hash_sum", RESULT); when(adbQueryExecutor.execute(any(), any())) .thenReturn(Future.succeededFuture(Collections.singletonList(result))); CheckDataByHashInt32Request request = CheckDataByHashInt32Request.builder() .cnFrom(1L) .cnTo(2L) .columns(Collections.emptySet()) .entity(Entity.builder() .fields(Collections.emptyList()) .build()) .build(); adbCheckDataService.checkDataByHashInt32(request) .onComplete(ar -> { assertTrue(ar.succeeded()); assertEquals(RESULT, ar.result()); verify(adbQueryExecutor, times(1)).execute(any(), any()); }); } @Test void testCheckByHashNullResult() { HashMap<String, Object> result = new HashMap<>(); result.put("hash_sum", null); when(adbQueryExecutor.execute(any(), any())) .thenReturn(Future.succeededFuture(Collections.singletonList(result))); CheckDataByHashInt32Request request = CheckDataByHashInt32Request.builder() .cnFrom(1L) .cnTo(2L) .columns(Collections.emptySet()) .entity(Entity.builder() .fields(Collections.emptyList()) .build()) .build(); adbCheckDataService.checkDataByHashInt32(request) .onComplete(ar -> { assertTrue(ar.succeeded()); assertEquals(0L, ar.result()); verify(adbQueryExecutor, times(1)).execute(any(), any()); }); } @Test void testCheckByCount() { HashMap<String, Object> result = new HashMap<>(); result.put("cnt", RESULT); when(adbQueryExecutor.execute(any(), any())) .thenReturn(Future.succeededFuture(Collections.singletonList(result))); CheckDataByCountRequest request = CheckDataByCountRequest.builder() .cnFrom(1L) .cnTo(2L) .entity(Entity.builder().build()) .build(); adbCheckDataService.checkDataByCount(request) .onComplete(ar -> { assertTrue(ar.succeeded()); assertEquals(RESULT, ar.result()); verify(adbQueryExecutor, times(1)).execute(any(), any()); }); } }
40.508929
95
0.635222
293d0abc9030844c092d69bfd1ca3d8f443102b0
4,086
/******************************************************************************* * Copyright 2012 University of Southern California * * 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. * * This code was developed by the Information Integration Group as part * of the Karma project at the Information Sciences Institute of the * University of Southern California. For more information, publications, * and related projects, please see: http://www.isi.edu/integration ******************************************************************************/ package edu.isi.karma.rep; import java.util.HashMap; import java.util.Map; import org.json.JSONObject; public class ColumnMetadata { private Map<String, Integer> columnPreferredLengths; // private Map<String, COLUMN_TYPE> columnTypes; // private Map<String, List<String>> invalidNodeIds; private Map<String, JSONObject> columnHistogramData; private Map<String, String> columnPythonTransform; private Map<String, String> columnPreviousCommandId; private Map<String, String> columnDerivedFrom; private Map<String, DataStructure> columnDataStructure; private Map<String, Boolean> columnOnError; public ColumnMetadata() { super(); this.columnPreferredLengths = new HashMap<String, Integer>(); // this.columnTypes = new HashMap<String, ColumnMetadata.COLUMN_TYPE>(); // this.invalidNodeIds = new HashMap<String, List<String>>(); this.columnHistogramData = new HashMap<String, JSONObject>(); this.columnPythonTransform = new HashMap<String, String>(); this.columnPreviousCommandId = new HashMap<String, String>(); this.columnDerivedFrom = new HashMap<String, String>(); this.columnDataStructure = new HashMap<String, DataStructure>(); this.columnOnError = new HashMap<String, Boolean>(); } public enum DataStructure { PRIMITIVE, COLLECTION, OBJECT } public enum COLUMN_TYPE { String, Long, Double, Date, URI, HTML } public void addColumnPreferredLength(String hNodeId, int preferredLength) { columnPreferredLengths.put(hNodeId, preferredLength); } public Integer getColumnPreferredLength(String hNodeId) { return columnPreferredLengths.get(hNodeId); } public JSONObject getColumnHistogramData(String hNodeId) { return columnHistogramData.get(hNodeId); } public void addColumnHistogramData(String hNodeId, JSONObject data) { columnHistogramData.put(hNodeId, data); } public void addColumnOnError(String hNodeId, Boolean onError) { columnOnError.put(hNodeId, onError); } public Boolean getColumnOnError(String hNodeId) { return columnOnError.get(hNodeId); } public String getColumnPython(String hNodeId) { return columnPythonTransform.get(hNodeId); } public String getColumnPreviousCommandId(String hNodeId) { return columnPreviousCommandId.get(hNodeId); } public String getColumnDerivedFrom(String hNodeId) { return columnDerivedFrom.get(hNodeId); } public DataStructure getColumnDataStructure(String hNodeId) { return columnDataStructure.get(hNodeId); } public void addColumnPythonTransformation(String hNodeId, String pythonTransform) { columnPythonTransform.put(hNodeId, pythonTransform); } public void addPreviousCommandId(String hNodeId, String commandId) { columnPreviousCommandId.put(hNodeId, commandId); } public void addColumnDerivedFrom(String hNodeId, String sourceHNodeId) { columnDerivedFrom.put(hNodeId, sourceHNodeId); } public void addColumnDataStructure(String hNodeId, DataStructure dataStructure) { columnDataStructure.put(hNodeId, dataStructure); } }
32.951613
82
0.738864
a4e26cbc00257a4fe96a1c196808a42c2947670c
481
package vkbootstrap; import java.util.ArrayList; import java.util.List; // For advanced device queue setup public class VkbCustomQueueDescription { public VkbCustomQueueDescription(int index, int count, List<Float> priorities) { this.index = index; this.count = count; this.priorities.addAll(priorities); assert(count == priorities.size()); } public int index = 0; public int count = 0; public final List<Float> priorities = new ArrayList<>(); }
30.0625
84
0.713098
896ae3ef27ba003b1da54d65abbeae99b532f150
479
package org.prvn.lab.functionalinterfaces; import org.prvn.lab.data.Person; import org.prvn.lab.data.PersonDatabase; import java.util.List; import java.util.function.Supplier; public class WorkingWithSupplier { //Supplier returns something static Supplier<List<Person>> personSupplier = ()-> PersonDatabase.getPersonList(); public static void main(String[] args) { // final List<Person> people = personSupplier.get(); System.out.println(people); } }
26.611111
87
0.73904