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 |
|---|---|---|---|---|---|
24ca0b573a94d7d0ae362408144f68a7aa8c7376 | 9,899 | /*******************************************************************************
* Copyright (C) 2018, OpenRefine contributors
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
package com.google.refine.importers;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.refine.ProjectMetadata;
import com.google.refine.importing.ImportingJob;
import com.google.refine.importing.ImportingUtilities;
import com.google.refine.model.Project;
import com.google.refine.util.JSONUtilities;
import com.google.refine.util.ParsingUtilities;
public class FixedWidthImporter extends TabularImportingParserBase {
public FixedWidthImporter() {
super(false);
}
@Override
public ObjectNode createParserUIInitializationData(
ImportingJob job, List<ObjectNode> fileRecords, String format) {
ObjectNode options = super.createParserUIInitializationData(job, fileRecords, format);
ArrayNode columnWidths = ParsingUtilities.mapper.createArrayNode();
if (fileRecords.size() > 0) {
ObjectNode firstFileRecord = fileRecords.get(0);
String encoding = ImportingUtilities.getEncoding(firstFileRecord);
String location = JSONUtilities.getString(firstFileRecord, "location", null);
if (location != null) {
File file = new File(job.getRawDataDir(), location);
int[] columnWidthsA = guessColumnWidths(file, encoding);
if (columnWidthsA != null) {
for (int w : columnWidthsA) {
JSONUtilities.append(columnWidths, w);
}
}
}
JSONUtilities.safePut(options, "headerLines", 0);
JSONUtilities.safePut(options, "columnWidths", columnWidths);
JSONUtilities.safePut(options, "guessCellValueTypes", false);
}
return options;
}
@Override
public void parseOneFile(
Project project,
ProjectMetadata metadata,
ImportingJob job,
String fileSource,
Reader reader,
int limit,
ObjectNode options,
List<Exception> exceptions
) {
final int[] columnWidths = JSONUtilities.getIntArray(options, "columnWidths");
List<Object> retrievedColumnNames = null;
if (options.has("columnNames")) {
String[] strings = JSONUtilities.getStringArray(options, "columnNames");
if (strings.length > 0) {
retrievedColumnNames = new ArrayList<Object>();
for (String s : strings) {
s = s.trim();
if (!s.isEmpty()) {
retrievedColumnNames.add(s);
}
}
if (retrievedColumnNames.size() > 0) {
JSONUtilities.safePut(options, "headerLines", 1);
} else {
retrievedColumnNames = null;
}
}
}
final List<Object> columnNames = retrievedColumnNames;
final LineNumberReader lnReader = new LineNumberReader(reader);
TableDataReader dataReader = new TableDataReader() {
boolean usedColumnNames = false;
@Override
public List<Object> getNextRowOfCells() throws IOException {
if (columnNames != null && !usedColumnNames) {
usedColumnNames = true;
return columnNames;
} else {
String line = lnReader.readLine();
if (line == null) {
return null;
} else {
return getCells(line, columnWidths);
}
}
}
};
TabularImportingParserBase.readTable(project, job, dataReader, limit, options, exceptions);
}
/**
* Splits the line into columns
* @param line Line to be split
* @param widths array of integers with field sizes
* @return
*/
static private ArrayList<Object> getCells(String line, int[] widths) {
ArrayList<Object> cells = new ArrayList<Object>();
int columnStartCursor = 0;
int columnEndCursor = 0;
for (int width : widths) {
if (columnStartCursor >= line.length()) {
cells.add(null); //FIXME is adding a null cell (to represent no data) OK?
continue;
}
columnEndCursor = columnStartCursor + width;
if (columnEndCursor > line.length()) {
columnEndCursor = line.length();
}
if (columnEndCursor <= columnStartCursor) {
cells.add(null); //FIXME is adding a null cell (to represent no data, or a zero width column) OK?
continue;
}
cells.add(line.substring(columnStartCursor, columnEndCursor));
columnStartCursor = columnEndCursor;
}
// Residual text
if (columnStartCursor < line.length()) {
cells.add(line.substring(columnStartCursor));
}
return cells;
}
static public int[] guessColumnWidths(File file, String encoding) {
try {
InputStream is = new FileInputStream(file);
Reader reader = (encoding != null) ? new InputStreamReader(is, encoding) : new InputStreamReader(is);
LineNumberReader lineNumberReader = new LineNumberReader(reader);
try {
int[] counts = null;
int totalBytes = 0;
int lineCount = 0;
String s;
while (totalBytes < 64 * 1024 &&
lineCount < 100 &&
(s = lineNumberReader.readLine()) != null) {
totalBytes += s.length() + 1; // count the new line character
if (s.length() == 0) {
continue;
}
lineCount++;
if (counts == null) {
counts = new int[s.length()];
for (int c = 0; c < counts.length; c++) {
counts[c] = 0;
}
}
for (int c = 0; c < counts.length && c < s.length(); c++) {
char ch = s.charAt(c);
if (ch == ' ') {
counts[c]++;
}
}
}
if (counts != null && lineCount > 2) {
List<Integer> widths = new ArrayList<Integer>();
int startIndex = 0;
for (int c = 0; c < counts.length; c++) {
int count = counts[c];
if (count == lineCount) {
widths.add(c - startIndex + 1);
startIndex = c + 1;
}
}
for (int i = widths.size() - 2; i >= 0; i--) {
if (widths.get(i) == 1) {
widths.set(i + 1, widths.get(i + 1) + 1);
widths.remove(i);
}
}
int[] widthA = new int[widths.size()];
for (int i = 0; i < widthA.length; i++) {
widthA[i] = widths.get(i);
}
return widthA;
}
} finally {
lineNumberReader.close();
reader.close();
is.close();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
| 39.438247 | 114 | 0.523487 |
87600075bb303b21543deef76f5f1dfa59d6f5a6 | 4,008 | /* =======================================================
Copyright 2020 - ePortfolium - Licensed under the
Educational Community 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.osedu.org/licenses/ECL-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 eportfolium.com.karuta.business.contract;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;
import com.fasterxml.jackson.core.JsonProcessingException;
import eportfolium.com.karuta.document.*;
import eportfolium.com.karuta.model.bean.GroupRights;
import eportfolium.com.karuta.model.bean.Portfolio;
import eportfolium.com.karuta.model.exception.BusinessException;
public interface PortfolioManager extends BaseManager {
int addPortfolioInGroup(UUID portfolioUuid, Long portfolioGroupId, String label);
Long addPortfolioGroup(String groupname, String type, Long parentId);
boolean removePortfolio(UUID portfolioId, Long userId);
boolean removePortfolioFromPortfolioGroups(UUID portfolioId, Long portfolioGroupId);
boolean removePortfolioGroups(Long portfolioGroupId);
String getPortfolio(UUID portfolioId,
Long userId,
Integer cutoff) throws BusinessException, JsonProcessingException;
ByteArrayOutputStream getZippedPortfolio(PortfolioDocument portfolio, String lang, String servletContext) throws IOException;
String getPortfolioByCode(String portfolioCode,
Long userId,
boolean resources) throws BusinessException, JsonProcessingException;
PortfolioGroupDocument getPortfoliosByPortfolioGroup(Long portfolioGroupId);
Long getPortfolioGroupIdFromLabel(String groupLabel);
String getPortfolioGroupList();
PortfolioGroupList getPortfolioGroupListFromPortfolio(UUID portfolioId);
String getPortfolios(long userId, boolean active, boolean count, Boolean specialProject, String portfolioCode);
PortfolioList getPortfolioShared(Long userId);
GroupRights getRightsOnPortfolio(Long userId, UUID portfolioId);
UUID postPortfolioParserights(UUID portfolioId, Long userId) throws JsonProcessingException, BusinessException;
boolean isOwner(Long userId, UUID portfolioId);
/**
* Has rights, whether ownership, or given by someone
*/
boolean hasRights(Long userId, UUID portfolioUuid);
boolean changePortfolioOwner(UUID portfolioId, long newOwner);
void changePortfolioConfiguration(UUID portfolioId, Boolean portfolioActive);
boolean rewritePortfolioContent(PortfolioDocument portfolio, UUID portfolioId, Long userId, Boolean portfolioActive)
throws BusinessException, JsonProcessingException;
String instanciatePortfolio(String portfolioId, String srccode, String tgtcode);
UUID importPortfolio(InputStream fileInputStream, Long id, String servletContext)
throws BusinessException, IOException;
PortfolioList addPortfolio(PortfolioDocument portfolio, long userId, String projectName)
throws BusinessException, JsonProcessingException;
GroupRightInfoList getGroupRightsInfos(UUID portfolioId);
String getRoleByPortfolio(String role, UUID portfolioId);
GroupInfoList getRolesByPortfolio(UUID portfolioId, Long userId);
UUID copyPortfolio(String id, String srccode, String tgtcode, Long userId)
throws BusinessException;
void updateTime(UUID portfolioId);
void updateTimeByNode(UUID nodeId);
List<Portfolio> getPortfolioList(Long userId, boolean active, Boolean specialProject, String portfolioCode);
Long getPortfolioCount(Long userId, boolean active, Boolean specialProject, String portfolioCode);
}
| 37.457944 | 126 | 0.795908 |
4d51dd5d9eb49359cba8cc6cf1b5848c1bcb7973 | 1,518 | package server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import server.tcp.ListenerThread;
import util.Config;
/**
* Server application that creates a TCP socket and waits for messages send by
* client.
*/
public class Server implements Runnable {
private Config config;
private ServerSocket serverSocket;
public Server(Config config) {
this.config = config;
}
@Override
public void run() {
// create and start a new TCP ServerSocket
try {
serverSocket = new ServerSocket(config.getInt("tcp.port"));
// handle incoming connections from client in a separate thread
new ListenerThread(serverSocket).start();
} catch (IOException e) {
throw new RuntimeException("Cannot listen on TCP port.", e);
}
System.out.println("Server is up! Hit <ENTER> to exit!");
// create a reader to read from the console
BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
try {
// read commands from the console
reader.readLine();
} catch (IOException e) {
// IOException from System.in is very very unlikely (or impossible)
// and cannot be handled
}
// close socket and listening thread
close();
}
public void close() {
if (serverSocket != null)
try {
serverSocket.close();
} catch (IOException e) {
// Ignored because we cannot handle it
}
}
public static void main(String[] args) {
new Server(new Config("server")).run();
}
}
| 22.656716 | 78 | 0.702899 |
52235ae24cab59d4a66eff8658692034c4f2a68a | 24,338 | /*
* Constellation - An open source and standard compliant SDI
* http://www.constellation-sdi.org
*
* Copyright 2014 Geomatys.
*
* 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.constellation.map.featureinfo;
import java.awt.*;
import java.io.StringWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.TimeZone;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.measure.Unit;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import org.apache.sis.coverage.SampleDimension;
import org.apache.sis.geometry.GeneralDirectPosition;
import org.apache.sis.measure.MeasurementRange;
import org.apache.sis.storage.DataStoreException;
import org.apache.sis.storage.Resource;
import org.apache.sis.util.logging.Logging;
import org.apache.sis.xml.MarshallerPool;
import org.constellation.api.DataType;
import org.constellation.configuration.AppProperty;
import org.constellation.configuration.Application;
import org.constellation.exception.ConstellationStoreException;
import org.constellation.provider.Data;
import org.constellation.ws.MimeType;
import org.geotoolkit.display.PortrayalException;
import org.geotoolkit.display2d.canvas.RenderingContext2D;
import org.geotoolkit.display2d.primitive.ProjectedCoverage;
import org.geotoolkit.display2d.primitive.ProjectedFeature;
import org.geotoolkit.display2d.primitive.SearchAreaJ2D;
import org.geotoolkit.display2d.service.CanvasDef;
import org.geotoolkit.display2d.service.SceneDef;
import org.geotoolkit.display2d.service.ViewDef;
import org.geotoolkit.feature.FeatureExt;
import org.geotoolkit.geometry.isoonjts.JTSUtils;
import org.geotoolkit.geometry.jts.JTSEnvelope2D;
import org.geotoolkit.internal.jaxb.ObjectFactory;
import org.geotoolkit.map.FeatureMapLayer;
import org.geotoolkit.ows.xml.GetFeatureInfo;
import org.geotoolkit.referencing.ReferencingUtilities;
import org.geotoolkit.util.DateRange;
import org.geotoolkit.util.NamesExt;
import org.locationtech.jts.geom.Geometry;
import org.opengis.feature.AttributeType;
import org.opengis.feature.Feature;
import org.opengis.feature.FeatureType;
import org.opengis.feature.PropertyType;
import org.opengis.geometry.Envelope;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.util.FactoryException;
import org.opengis.util.GenericName;
/**
* A generic FeatureInfoFormat that produce GML output for Features and Coverages.
* Supported mimeTypes are :
* <ul>
* <li>application/vnd.ogc.gml : will return msGMLOutput</li>
* <li>application/gml+xml : will return OGC GML3</li>
* </ul>
*
* @author Quentin Boileau (Geomatys)
*/
public class GMLFeatureInfoFormat extends AbstractTextFeatureInfoFormat {
private static final Logger LOGGER = Logging.getLogger("org.constellation.map.featureinfo");
/**
* GML version flag : 0 for mapserver output
* 1 for GML 3 output
*/
private int mode = 1;
private GetFeatureInfo gfi;
/**
* A Map of namespace / prefix
*/
private final Map<String, String> prefixMap = new HashMap<>();
private static final MarshallerPool pool;
static {
MarshallerPool candidate = null;
try {
final Map<String, Object> properties = new HashMap<>();
properties.put(Marshaller.JAXB_FRAGMENT, true);
properties.put(Marshaller.JAXB_FORMATTED_OUTPUT, false);
candidate = new MarshallerPool(JAXBContext.newInstance(ObjectFactory.class), properties);
} catch (JAXBException ex) {
LOGGER.log(Level.SEVERE, "JAXB Exception while initializing the marshaller pool", ex);
}
pool = candidate;
}
public GMLFeatureInfoFormat() {
prefixMap.put("http://www.opengis.net/gml", "gml");
}
/**
* Return the defined prefix for the specified namespace.
* if it does not already exist a prefix for this namespace,
* a new one will be created on the form: "ns" + prefixMap.size()
*
* @param namespace a attribute or featureType namespace.
*
* @return a prefix used in XML.
*/
private String acquirePrefix(String namespace) {
if (namespace != null && !namespace.isEmpty()) {
String result = prefixMap.get(namespace);
if (result == null) {
result = "ns" + prefixMap.size();
prefixMap.put(namespace,result);
}
return result + ":";
}
return "";
}
/**
* {@inheritDoc}
*/
@Override
protected void nextProjectedCoverage(ProjectedCoverage coverage, RenderingContext2D context, SearchAreaJ2D queryArea) {
final List<Map.Entry<SampleDimension,Object>> results =
FeatureInfoUtilities.getCoverageValues(coverage, context, queryArea);
if (results == null) {
return;
}
final Resource ref = coverage.getLayer().getResource();
final GenericName fullLayerName;
try {
if (ref.getIdentifier().isPresent()) {
fullLayerName = ref.getIdentifier().get().tip();
} else {
throw new RuntimeException("resource identifier not present");
}
} catch (DataStoreException e) {
throw new RuntimeException(e); // TODO
}
String layerName = fullLayerName.tip().toString();
List<String> strs = coverages.get(layerName);
if (strs == null) {
strs = new ArrayList<String>();
coverages.put(layerName, strs);
}
StringBuilder builder = new StringBuilder();
for (final Map.Entry<SampleDimension,Object> entry : results) {
final Object value = entry.getValue();
if (value == null) {
continue;
}
builder.append(value);
}
final String result = builder.toString();
builder = new StringBuilder();
final String endMark = ">\n";
layerName = layerName.replaceAll("\\W", "");
builder.append("\t<").append(layerName).append("_layer").append(endMark)
.append("\t\t<").append(layerName).append("_feature").append(endMark);
final List<Data> layerDetailsList = getLayersDetails();
Data layerPostgrid = null;
for (Data layer : layerDetailsList) {
if (layer.getDataType().equals(DataType.COVERAGE) && layer.getName().equals(fullLayerName)) {
layerPostgrid = layer;
}
}
final Envelope objEnv;
final List<Date> time;
final Double elevation;
if (gfi != null && gfi instanceof org.geotoolkit.wms.xml.GetFeatureInfo) {
org.geotoolkit.wms.xml.GetFeatureInfo wmsGFI = (org.geotoolkit.wms.xml.GetFeatureInfo) gfi;
objEnv = wmsGFI.getEnvelope2D();
time = wmsGFI.getTime();
elevation = wmsGFI.getElevation();
} else {
objEnv = null;
time = null;
elevation = null;
}
if (objEnv != null) {
final CoordinateReferenceSystem crs = objEnv.getCoordinateReferenceSystem();
final GeneralDirectPosition pos = getPixelCoordinates(gfi);
if (pos != null) {
builder.append("\t\t\t<gml:boundedBy>").append("\n");
String crsName;
try {
crsName = ReferencingUtilities.lookupIdentifier(crs, true);
} catch (FactoryException ex) {
LOGGER.log(Level.INFO, ex.getLocalizedMessage(), ex);
crsName = crs.getName().getCode();
}
builder.append("\t\t\t\t<gml:Box srsName=\"").append(crsName).append("\">\n");
builder.append("\t\t\t\t\t<gml:coordinates>");
builder.append(pos.getOrdinate(0)).append(",").append(pos.getOrdinate(1)).append(" ")
.append(pos.getOrdinate(0)).append(",").append(pos.getOrdinate(1));
builder.append("</gml:coordinates>").append("\n");
builder.append("\t\t\t\t</gml:Box>").append("\n");
builder.append("\t\t\t</gml:boundedBy>").append("\n");
builder.append("\t\t\t<x>").append(pos.getOrdinate(0)).append("</x>").append("\n")
.append("\t\t\t<y>").append(pos.getOrdinate(1)).append("</y>").append("\n");
}
}
if (time != null && !time.isEmpty()) {
// TODO : Adapt code to use periods.
builder.append("\t\t\t<time>").append(time.get(time.size()-1)).append("</time>")
.append("\n");
} else {
/*
* Get the date of the last slice in this layer. Don't invoke
* layerPostgrid.getAvailableTimes().last() because getAvailableTimes() is very
* costly. The layerPostgrid.getEnvelope() method is much cheaper, since it can
* leverage the database index.
*/
DateRange dates = null;
if (layerPostgrid != null) {
try {
dates = layerPostgrid.getDateRange();
} catch (ConstellationStoreException ex) {
LOGGER.log(Level.INFO, ex.getLocalizedMessage(), ex);
}
}
if (dates != null && !(dates.isEmpty())) {
if (dates.getMaxValue() != null) {
final DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
df.setTimeZone(TimeZone.getTimeZone("UTC"));
builder.append("\t\t\t<time>").append(df.format(dates.getMaxValue()))
.append("</time>").append("\n");
}
}
}
if (elevation != null) {
builder.append("\t\t\t<elevation>").append(elevation)
.append("</elevation>").append("\n");
} else {
SortedSet<Number> elevs = null;
if (layerPostgrid != null) {
try {
elevs = layerPostgrid.getAvailableElevations();
} catch (ConstellationStoreException ex) {
LOGGER.log(Level.INFO, ex.getLocalizedMessage(), ex);
elevs = null;
}
}
if (elevs != null && !(elevs.isEmpty())) {
builder.append("\t\t\t<elevation>").append(elevs.first().toString())
.append("</elevation>").append("\n");
}
}
if (!results.isEmpty()) {
builder.append("\t\t\t<variable>")
.append(results.get(0).getKey().getName())
.append("</variable>").append("\n");
}
MeasurementRange[] ranges = null;
if (layerPostgrid != null) {
ranges = layerPostgrid.getSampleValueRanges();
}
if (ranges != null && ranges.length > 0) {
final MeasurementRange range = ranges[0];
if (range != null) {
final Unit unit = range.unit();
if (unit != null && !unit.toString().isEmpty()) {
builder.append("\t\t\t<unit>").append(unit.toString())
.append("</unit>").append("\n");
}
}
}
builder.append("\t\t\t<value>").append(result)
.append("</value>").append("\n")
.append("\t\t</").append(layerName).append("_feature").append(endMark)
.append("\t</").append(layerName).append("_layer").append(endMark);
strs.add(builder.toString());
}
/**
* {@inheritDoc}
*/
@Override
protected void nextProjectedFeature(ProjectedFeature graphic, RenderingContext2D context, SearchAreaJ2D queryArea) {
final StringBuilder builder = new StringBuilder();
final FeatureMapLayer layer = graphic.getLayer();
final Feature feature = graphic.getCandidate();
final FeatureType featureType = feature.getType();
String margin = "\t";
if (mode == 0) {
// featureType mark
if (featureType != null) {
final String ftLocal = featureType.getName().tip().toString();
builder.append(margin).append("<").append(encodeXMLMark(ftLocal)).append("_feature").append(">\n");
margin += "\t";
builder.append(margin).append("<ID>").append(encodeXML(FeatureExt.getId(feature).getID())).append("</ID>\n");
XMLFeatureInfoFormat.complexAttributetoXML(builder, feature, margin);
// end featureType mark
margin = margin.substring(1);
builder.append(margin).append("</").append(encodeXMLMark(ftLocal)).append("_feature").append(">\n");
} else {
LOGGER.warning("The feature type is null");
}
} else {
// feature member mark
builder.append(margin).append("<gml:featureMember>\n");
margin += "\t";
// featureType mark
if (featureType != null) {
String ftLocal = featureType.getName().tip().toString();
String ftPrefix = acquirePrefix(NamesExt.getNamespace(featureType.getName()));
builder.append(margin).append('<').append(ftPrefix).append(ftLocal).append(">\n");
margin += "\t";
toGML3(builder, feature, margin);
// end featureType mark
margin = margin.substring(1);
builder.append(margin).append("</").append(ftPrefix).append(ftLocal).append(">\n");
} else {
LOGGER.warning("The feature type is null");
}
// end feature member mark
margin = margin.substring(1);
builder.append(margin).append("</gml:featureMember>\n");
}
final String result = builder.toString();
if (builder.length() > 0) {
final String layerName = layer.getName();
List<String> strs = features.get(layerName);
if (strs == null) {
strs = new ArrayList<>();
features.put(layerName, strs);
}
strs.add(result.substring(0, result.length()));
}
}
private void toGML3(final StringBuilder builder, final Feature complexAtt, String margin) {
for (PropertyType pt : complexAtt.getType().getProperties(true)) {
final GenericName propName = pt.getName();
String pLocal = propName.tip().toString();
if (pLocal.startsWith("@")) {
pLocal = pLocal.substring(1);
}
String pPrefix = acquirePrefix(NamesExt.getNamespace(propName));
if (pt instanceof AttributeType) {
final AttributeType att = (AttributeType) pt;
final Object value = complexAtt.getPropertyValue(((AttributeType) pt).getName().toString());
if (Geometry.class.isAssignableFrom(att.getValueClass())) {
builder.append(margin).append('<').append(pPrefix).append(pLocal).append(">\n");
Marshaller m = null;
try {
m = pool.acquireMarshaller();
StringWriter sw = new StringWriter();
org.opengis.geometry.Geometry gmlGeometry = JTSUtils.toISO((Geometry)value,FeatureExt.getCRS(pt));
ObjectFactory factory = new ObjectFactory();
m.setProperty(Marshaller.JAXB_FRAGMENT, true);
m.marshal(factory.buildAnyGeometry(gmlGeometry), sw);
builder.append(sw.toString());
} catch (JAXBException ex) {
LOGGER.log(Level.WARNING, "JAXB exception while marshalling the geometry", ex);
} finally {
if (m != null) {
pool.recycle(m);
}
}
builder.append("\n");
builder.append(margin).append("</").append(pPrefix).append(pLocal).append(">\n");
} else {
if (value instanceof Feature) {
final Feature complex = (Feature) value;
builder.append(margin).append('<').append(pPrefix).append(pLocal).append(">\n");
margin += "\t";
toGML3(builder, complex, margin);
margin = margin.substring(1);
builder.append(margin).append("</").append(pPrefix).append(pLocal).append(">\n");
} else {
//simple
if (value instanceof List) {
List valueList = (List) value;
if (valueList.isEmpty()) {
builder.append(margin).append('<').append(pLocal).append("/>\n");
} else {
for (Object v : valueList) {
if (v != null) {
final String strValue = encodeXML(value.toString());
builder.append(margin).append('<').append(pLocal).append(">")
.append(strValue)
.append("</").append(pLocal).append(">\n");
} else {
builder.append(margin).append('<').append(pLocal).append("/>\n");
}
}
}
} else if (value != null) {
final String strValue = encodeXML(value.toString());
builder.append(margin).append('<').append(pPrefix).append(pLocal).append('>')
.append(strValue)
.append("</").append(pPrefix).append(pLocal).append(">\n");
} else {
builder.append(margin).append('<').append(pLocal).append("/>\n");
}
}
}
}
}
}
/**
* {@inheritDoc}
*/
@Override
public Object getFeatureInfo(SceneDef sdef, ViewDef vdef, CanvasDef cdef, Rectangle searchArea, GetFeatureInfo getFI) throws PortrayalException {
this.gfi = getFI;
final StringBuilder builder = new StringBuilder();
if (getFI.getInfoFormat().equals(MimeType.APP_GML) &&
Application.getBooleanProperty(AppProperty.CSTL_MAPSERVER_GFI_OUTPUT, true)) {
mode = 0;//msGMLOutput
} else {
mode = 1;//GML3
}
//fill coverages and features maps
getCandidates(sdef, vdef, cdef, searchArea, -1);
if (mode == 0) {
// Map Server GML output
builder.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>").append("\n")
.append("<msGMLOutput xmlns:gml=\"http://www.opengis.net/gml\" ")
.append("xmlns:xlink=\"http://www.w3.org/1999/xlink\" ")
.append("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">")
.append("\n");
} else {
builder.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>").append("\n")
.append("<gml:featureCollection ")
.append("xmlns:xlink=\"http://www.w3.org/1999/xlink\" ")
.append("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ");
for (Map.Entry<String, String> entry: prefixMap.entrySet()) {
builder.append("xmlns:").append(entry.getValue()).append("=\"").append(entry.getKey()).append("\" ");
}
builder.append(">\n");
}
final Map<String, List<String>> values = new HashMap<>();
values.putAll(features);
values.putAll(coverages);
// optimization move this filter to getCandidates
Integer maxValue = getFeatureCount(getFI);
if (maxValue == null) {
maxValue = 1;
}
for (String layerName : values.keySet()) {
if (mode == 0) {
builder.append("<").append(encodeXMLMark(layerName)).append("_layer").append(">\n");
}
int cpt = 0;
for (final String record : values.get(layerName)) {
builder.append(record);
cpt++;
if (cpt >= maxValue) break;
}
if (mode == 0) {
builder.append("</").append(encodeXMLMark(layerName)).append("_layer").append(">\n");
}
}
if (mode == 0) {
builder.append("</msGMLOutput>");
} else {
builder.append("</gml:featureCollection>");
}
features.clear();
coverages.clear();
return builder.toString();
}
/**
* {@inheritDoc}
*/
@Override
public List<String> getSupportedMimeTypes() {
final List<String> mimes = new ArrayList<>();
mimes.add(MimeType.APP_GML);//will return map server GML
mimes.add(MimeType.APP_GML_XML);//will return GML 3
return mimes;
}
/**
* Returns the coordinates of the requested pixel in the image, expressed in the
* {@linkplain CoordinateReferenceSystem crs} defined in the request.
*/
private GeneralDirectPosition getPixelCoordinates(final GetFeatureInfo gfi) {
if (gfi != null) {
JTSEnvelope2D objEnv = new JTSEnvelope2D();
int width = 0;
int height = 0;
int pixelX = 0;
int pixelY = 0;
if(gfi instanceof org.geotoolkit.wms.xml.GetFeatureInfo) {
org.geotoolkit.wms.xml.GetFeatureInfo wmsGFI = (org.geotoolkit.wms.xml.GetFeatureInfo) gfi;
objEnv = new JTSEnvelope2D(wmsGFI.getEnvelope2D());
width = wmsGFI.getSize().width;
height = wmsGFI.getSize().height;
pixelX = wmsGFI.getX();
pixelY = wmsGFI.getY();
} else if (gfi instanceof org.geotoolkit.wmts.xml.v100.GetFeatureInfo) {
org.geotoolkit.wmts.xml.v100.GetFeatureInfo wmtsGFI = (org.geotoolkit.wmts.xml.v100.GetFeatureInfo) gfi;
objEnv = new JTSEnvelope2D(); //gfi.getEnvelope());
width = 0; // gfi.getSize().width;
height = 0; // gfi.getSize().height;
pixelX = wmtsGFI.getI();
pixelY = wmtsGFI.getJ();
}
final double widthEnv = objEnv.getSpan(0);
final double heightEnv = objEnv.getSpan(1);
final double resX = widthEnv / width;
final double resY = -1 * heightEnv / height;
final double geoX = (pixelX + 0.5) * resX + objEnv.getMinimum(0);
final double geoY = (pixelY + 0.5) * resY + objEnv.getMaximum(1);
final GeneralDirectPosition position = new GeneralDirectPosition(geoX, geoY);
position.setCoordinateReferenceSystem(objEnv.getCoordinateReferenceSystem());
return position;
}
return null;
}
}
| 41.250847 | 149 | 0.555674 |
44afd34cfa67ce7950554270c8c4cb85ffe18eeb | 1,138 | package game;
import java.applet.AudioClip;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.paint.Color;
import settings.Configuracoes;
public class Bullet extends GameObj {
private int framesAlive;
private Configuracoes c;
public Bullet(double[] front, double[] shipSpeed, double angle, Configuracoes c) {
super(front[0], front[1], 0, 0, angle, c);
this.framesAlive = 0;
this.c = c;
setSpeedX(c.getBulletSpeed() * cos + shipSpeed[0]);
setSpeedY(c.getBulletSpeed() * sin + shipSpeed[1]);
}
public void draw(GraphicsContext gc, Configuracoes c) {
gc.setFill(Color.WHITE);
gc.fillRect(x-1, y-1, 2, 2);
gc.setFill(Color.BLACK);
move(c);
}
public void move(Configuracoes c) {
x += speedX;
y += speedY;
if (x < 0) x = c.getFrameWidth(); //angulacao que a bala sai
if (x > c.getFrameWidth()) x = 0;
if (y < 0) y = c.getFrameHeight();
if (y > c.getFrameHeight()) y = 0;
framesAlive++;
}
public boolean isDead() {
return framesAlive >= c.getBulletLifespan();
}
public int getAge() {
return framesAlive;
}
} | 23.22449 | 83 | 0.637961 |
6a88684fc2af5ce6c360a7b16799b77d0b6adbad | 8,609 | package com.feeyo.net.nio.ssl;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLEngineResult;
import javax.net.ssl.SSLEngineResult.HandshakeStatus;
import javax.net.ssl.SSLEngineResult.Status;
import javax.net.ssl.SSLException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.feeyo.net.nio.ClosableConnection;
import com.feeyo.net.nio.Connection;
import com.feeyo.net.nio.NIOHandler;
import com.feeyo.net.nio.util.ByteUtil;
/**
*
* SSL/TLS encrypted connection
*
* @author zhuam
*
*/
public class SslConnection extends Connection {
private static Logger LOGGER = LoggerFactory.getLogger( SslConnection.class );
// An empty buffer used during the handshake phase
protected static final ByteBuffer emptyBuffer = ByteBuffer.allocate(0);
//
protected ByteBuffer incomingBuffer;
protected ByteBuffer outgoingBuffer;
protected ByteBuffer appBuffer;
//
protected volatile boolean handshakeComplete = false;
protected SSLEngine sslEngine;
//
private volatile boolean initialized;
//
public SslConnection(SocketChannel socketChannel, SSLContext sslContext) {
super(socketChannel);
//
sslEngine = sslContext.createSSLEngine();
int packetBufferSize = sslEngine.getSession().getPacketBufferSize(); // // SSL引擎默认包大小,16921
int applicationBufferSize = sslEngine.getSession().getApplicationBufferSize();
//
incomingBuffer = ByteBuffer.allocate( packetBufferSize );
outgoingBuffer = ByteBuffer.allocate( packetBufferSize );
outgoingBuffer.position(0);
outgoingBuffer.limit(0);
//
appBuffer = ByteBuffer.allocate( applicationBufferSize );
}
//
@SuppressWarnings({ "rawtypes", "unchecked" })
@Override
public void setHandler(NIOHandler<? extends ClosableConnection> handler) {
this.handler = new SslHandler( handler );
}
@Override
public void close(String reason) {
super.close(reason);
//
if (sslEngine != null)
sslEngine.closeOutbound();
}
//
private void initialize() throws IOException {
//
if ( initialized) {
LOGGER.warn("Ssl I/O conneciton already initialized");
return;
}
//
this.initialized = true;
//
// SSL ServerMode
this.sslEngine.setUseClientMode(false);
//
// Begin handshake
this.sslEngine.beginHandshake();
this.doHandshake();
}
private void doHandshake() throws IOException {
//
HandshakeStatus handshakeStatus = sslEngine.getHandshakeStatus();
//
// Start SSL handshake
while (!handshakeComplete) {
//
// 将缓冲区刷新到网络
if (outgoingBuffer.hasRemaining())
socketChannel.write(outgoingBuffer);
///
//
SSLEngineResult result;
//
switch (handshakeStatus) {
case FINISHED:
handshakeComplete = true;
break;
case NEED_UNWRAP:
//
// Process incoming handshake data
int bytesRead = socketChannel.read(incomingBuffer);
if ( bytesRead == -1) {
close("End stream!");
return;
}
System.out.println("read=" + ByteUtil.dump(incomingBuffer));
//
needIO: while (handshakeStatus == HandshakeStatus.NEED_UNWRAP) {
//
incomingBuffer.flip();
result = doUnwrap(incomingBuffer, appBuffer);
incomingBuffer.compact();
handshakeStatus = result.getHandshakeStatus();
//
switch (result.getStatus()) {
case OK:
switch (handshakeStatus) {
case NOT_HANDSHAKING:
case NEED_TASK:
// run handshake tasks in the current Thread
handshakeStatus = doRunTask();
break;
case FINISHED:
handshakeComplete = true;
break needIO;
default:
break;
}
break;
case BUFFER_UNDERFLOW:
/* we need more data */
break needIO;
case BUFFER_OVERFLOW:
/* resize output buffer */
appBuffer = ByteBuffer.allocateDirect(appBuffer.capacity() * 2);
break;
default:
break;
}
}
//
if (handshakeStatus != HandshakeStatus.NEED_WRAP) {
break;
}
case NEED_WRAP:
// Generate outgoing handshake data
outgoingBuffer.clear();
result = doWrap(emptyBuffer, outgoingBuffer);
outgoingBuffer.flip();
handshakeStatus = result.getHandshakeStatus();
//
switch (result.getStatus()) {
case OK:
if (handshakeStatus == HandshakeStatus.NEED_TASK) {
// run handshake tasks in the current Thread
handshakeStatus = doRunTask();
}
break;
default:
break;
}
break;
default:
break;
}
}
//
incomingBuffer.clear();
}
//
// A works-around for exception handling craziness in Sun/Oracle's SSLEngine
// implementation.
//
// sun.security.pkcs11.wrapper.PKCS11Exception is re-thrown as
// plain RuntimeException in sun.security.ssl.Handshaker#checkThrown
private SSLException convert(final RuntimeException ex) {
Throwable cause = ex.getCause();
if (cause == null) {
cause = ex;
}
return new SSLException(cause);
}
private SSLEngineResult doWrap(final ByteBuffer src, final ByteBuffer dst) throws SSLException {
try {
return this.sslEngine.wrap(src, dst);
} catch (final RuntimeException ex) {
throw convert(ex);
}
}
private SSLEngineResult doUnwrap(final ByteBuffer src, final ByteBuffer dst) throws SSLException {
try {
return this.sslEngine.unwrap(src, dst);
} catch (final RuntimeException ex) {
throw convert(ex);
}
}
private HandshakeStatus doRunTask() throws SSLException {
try {
final Runnable r = this.sslEngine.getDelegatedTask();
if (r != null) {
r.run();
}
return this.sslEngine.getHandshakeStatus();
} catch (final RuntimeException ex) {
throw convert(ex);
}
}
//
public void handleSslWrite(ByteBuffer buffer) throws IOException {
//
if ( outgoingBuffer.hasRemaining() )
socketChannel.write(outgoingBuffer);
//
encryptedData( buffer );
//
if (outgoingBuffer.hasRemaining())
socketChannel.write(outgoingBuffer);
}
//
private void encryptedData(ByteBuffer buffer) throws IOException {
//
outgoingBuffer.clear();
//
SSLEngineResult result = doWrap(buffer, outgoingBuffer);
outgoingBuffer.flip();
//
switch (result.getStatus()) {
case OK:
if ( result.getHandshakeStatus() == HandshakeStatus.NEED_TASK)
doRunTask();
break;
default:
break;
}
}
private void decryptData(byte[] data) throws IOException {
//
incomingBuffer.clear();
if ( incomingBuffer.remaining() < data.length ) {
ByteBuffer newBuffer = ByteBuffer.allocate( incomingBuffer.capacity() * 2);
newBuffer.put( incomingBuffer );
incomingBuffer = newBuffer;
}
incomingBuffer.put( data );
incomingBuffer.flip();
//
// 读
SSLEngineResult result;
do {
//
result = sslEngine.unwrap(incomingBuffer, appBuffer);
incomingBuffer.flip();
//
HandshakeStatus handshakeStatus = result.getHandshakeStatus();
Status status = result.getStatus();
if ( status == Status.BUFFER_UNDERFLOW ) {
appBuffer = ByteBuffer.allocate(appBuffer.capacity() * 2);
//
} else if ( status == Status.OK && handshakeStatus == HandshakeStatus.NEED_TASK ) {
doRunTask();
}
} while ((incomingBuffer.position() != 0) && result.getStatus() != SSLEngineResult.Status.BUFFER_UNDERFLOW);
}
//
private class SslHandler<T extends ClosableConnection> implements NIOHandler<T> {
private NIOHandler<T> delegateHandler;
public SslHandler(NIOHandler<T> handler) {
this.delegateHandler = handler;
}
@Override
public void onConnected(T con) throws IOException {
initialize();
this.delegateHandler.onConnected(con);
}
@Override
public void onConnectFailed(T con, Exception e) {
this.delegateHandler.onConnectFailed(con, e);
}
@Override
public void onClosed(T con, String reason) {
this.delegateHandler.onClosed(con, reason);
}
@Override
public void handleReadEvent(T con, byte[] data) throws IOException {
//
if ( !handshakeComplete ) {
con.close("Unable to complete SSL handshake error!");
return;
}
System.out.println("https xxx: " + ByteUtil.dump( data ) );
//
decryptData(data);
this.delegateHandler.handleReadEvent(con, incomingBuffer.array());
incomingBuffer.clear();
}
}
} | 25.698507 | 110 | 0.664189 |
61f8859a222ddaddb358e7ddd3ed3043942bbd22 | 5,093 | package com.ljmu.andre.snaptools.Networking;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkError;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.google.common.base.MoreObjects;
import com.ljmu.andre.snaptools.Networking.Packets.Packet;
import java.net.UnknownHostException;
import java.util.List;
import javax.net.ssl.SSLException;
import timber.log.Timber;
/**
* This class was created by Andre R M (SID: 701439)
* It and its contents are free to use by all
*/
public class WebResponse {
private final String message;
private final String failedUrl;
private Object result;
private Throwable exception;
private int responseCode = 0;
private int webStatusCode;
WebResponse(Object result, String failedUrl) {
this(result, "SUCCESS", failedUrl);
}
private WebResponse(Object result, String message, String failedUrl) {
this.message = message;
this.result = result;
this.failedUrl = failedUrl;
Timber.d("Web Response [Msg: %s]", message);
}
WebResponse(String message, Throwable exception, String failedUrl) {
this(message, exception, -1, failedUrl);
}
WebResponse(String message, Throwable exception, int errorCode, String failedUrl) {
this.message = message;
this.exception = exception;
this.responseCode = errorCode;
this.failedUrl = failedUrl;
if (exception == null)
return;
if (exception instanceof VolleyError) {
VolleyError volleyError = (VolleyError) exception;
if (volleyError.networkResponse != null) {
webStatusCode = volleyError.networkResponse.statusCode;
}
}
if (isNetworkProblem(exception) || isCronetError(exception)) {
Timber.w(exception, message);
this.exception = null;
if (responseCode == -1 || responseCode == 0)
responseCode = 1;
} else if (isServerProblem(exception)) {
this.exception = transformServerException(exception);
if (responseCode == -1 || responseCode == 0)
responseCode = 2;
}
}
private static boolean isNetworkProblem(Object error) {
return error instanceof NetworkError || error instanceof TimeoutError
|| error instanceof UnknownHostException || error instanceof SSLException;
}
private static boolean isCronetError(Object error) {
String errorClassName = error.getClass().getSimpleName();
return errorClassName.equals("QuicException") ||
errorClassName.equals("UrlRequestException");
}
private static boolean isServerProblem(Object error) {
return (error instanceof ServerError || error instanceof AuthFailureError);
}
private Throwable transformServerException(Throwable exception) {
if (exception instanceof VolleyError) {
VolleyError volleyError = (VolleyError) exception;
if (volleyError.networkResponse != null && volleyError.networkResponse.data != null) {
String str = new String(volleyError.networkResponse.data);
if (str.length() > 1000)
str = "Data exceeds 1000 characters. Probably contains raw HTML";
return new VolleyError(
"Url: " + failedUrl + " | Status: " + volleyError.networkResponse.statusCode
+ " | " + str,
exception
);
}
}
return exception;
}
public <T> T getResult() {
return (T) result;
}
public String getMessage() {
return message;
}
public int getResponseCode() {
return responseCode;
}
public Throwable getException() {
return exception;
}
public int getWebStatusCode() {
return webStatusCode;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.omitNullValues()
.add("message", message)
.add("success", result)
.add("exception", exception)
.add("responseCode", responseCode)
.toString();
}
public interface ServerListResultListener<T> {
void success(List<T> list);
void error(String message, Throwable t, int errorCode);
}
public interface PacketResultListener<T extends Packet> {
void success(String message, T packet);
void error(String message, Throwable t, int errorCode);
}
public interface ObjectResultListener<T> {
void success(String message, T object);
void error(String message, Throwable t, int errorCode);
abstract class ErrorObjectResultListener<T> implements ObjectResultListener<T> {
@Override
public void success(String message, Object object) {
}
}
}
}
| 30.866667 | 100 | 0.624583 |
f02e2694adcf84e5cd0d899cbc9f6d0bf3c6db61 | 1,810 |
package net.eduard.curso.eventos;
import org.bukkit.Bukkit;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.CraftItemEvent;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.inventory.InventoryCloseEvent;
import org.bukkit.event.inventory.InventoryCreativeEvent;
import org.bukkit.event.inventory.InventoryDragEvent;
import org.bukkit.event.inventory.InventoryEvent;
import org.bukkit.event.inventory.InventoryMoveItemEvent;
import org.bukkit.event.inventory.InventoryOpenEvent;
import org.bukkit.event.inventory.InventoryPickupItemEvent;
import org.bukkit.event.player.PlayerItemBreakEvent;
import org.bukkit.event.player.PlayerItemConsumeEvent;
import org.bukkit.event.player.PlayerPickupItemEvent;
public class ListaDeEventosInventario implements Listener {
@EventHandler
public void InventoryCraft(CraftItemEvent e) {
Bukkit.broadcastMessage(e.getEventName());
}
@EventHandler
public void InventoryAbre(InventoryOpenEvent e) {
}
@EventHandler
public void InventoryArrasta(InventoryDragEvent e) {
}
@EventHandler
public void InventoryClica(InventoryClickEvent e) {
}
@EventHandler
public void InventoryConsomeItem(PlayerItemConsumeEvent e) {
}
@EventHandler
public void InventoryCreativo(InventoryCreativeEvent e) {
}
@EventHandler
public void InventoryFecha(InventoryCloseEvent e) {
}
@EventHandler
public void InventoryMecherHotBar(InventoryEvent e) {
}
@EventHandler
public void InventoryMoveItem(InventoryMoveItemEvent e) {
}
@EventHandler
public void InventoryMoveItem(PlayerPickupItemEvent e) {
}
@EventHandler
public void InventoryPegaItem(InventoryPickupItemEvent e) {
}
@EventHandler
public void InventoryQuebraItem(PlayerItemBreakEvent e) {
}
}
| 21.807229 | 61 | 0.816022 |
d90a276f772c4732388d0ae27ae4e4dbddae5a27 | 3,530 | /*
* To the extent possible under law, the ImageJ developers have waived
* all copyright and related or neighboring rights to this tutorial code.
*
* See the CC0 1.0 Universal license for details:
* http://creativecommons.org/publicdomain/zero/1.0/
*/
import net.imagej.Dataset;
import net.imagej.measure.StatisticsService;
import org.scijava.ItemIO;
import org.scijava.command.Command;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;
/**
* A command that computes some statistics of a dataset.
* <p>
* For an even simpler command, see {@link HelloWorld} in this same package!
* </p>
*/
@Plugin(type = Command.class, headless = true,
menuPath = "Analyze>Compute Statistics")
public class ComputeStats implements Command {
@Parameter
private StatisticsService statisticsService;
@Parameter
private Dataset dataset;
@Parameter(type = ItemIO.OUTPUT)
private double arithmeticMean;
@Parameter(type = ItemIO.OUTPUT)
private double geometricMean;
@Parameter(type = ItemIO.OUTPUT)
private double harmonicMean;
@Parameter(type = ItemIO.OUTPUT)
private double maximum;
@Parameter(type = ItemIO.OUTPUT)
private double median;
@Parameter(type = ItemIO.OUTPUT)
private double midpoint;
@Parameter(type = ItemIO.OUTPUT)
private double minimum;
@Parameter(type = ItemIO.OUTPUT)
private double populationKurtosis;
@Parameter(type = ItemIO.OUTPUT)
private double populationKurtosisExcess;
@Parameter(type = ItemIO.OUTPUT)
private double populationSkew;
@Parameter(type = ItemIO.OUTPUT)
private double populationStdDev;
@Parameter(type = ItemIO.OUTPUT)
private double populationVariance;
@Parameter(type = ItemIO.OUTPUT)
private double product;
@Parameter(type = ItemIO.OUTPUT)
private double sampleKurtosis;
@Parameter(type = ItemIO.OUTPUT)
private double sampleKurtosisExcess;
@Parameter(type = ItemIO.OUTPUT)
private double sampleSkew;
@Parameter(type = ItemIO.OUTPUT)
private double sampleStdDev;
@Parameter(type = ItemIO.OUTPUT)
private double sampleVariance;
@Parameter(type = ItemIO.OUTPUT)
private double sum;
@Parameter(type = ItemIO.OUTPUT)
private double sumOfSquaredDeviations;
/**
* Computes some statistics on the input dataset, using ImageJ's built-in
* statistics service.
*/
@Override
public void run() {
arithmeticMean = statisticsService.arithmeticMean(dataset);
geometricMean = statisticsService.geometricMean(dataset);
harmonicMean = statisticsService.harmonicMean(dataset);
maximum = statisticsService.maximum(dataset);
median = statisticsService.median(dataset);
midpoint = statisticsService.midpoint(dataset);
minimum = statisticsService.minimum(dataset);
populationKurtosis = statisticsService.populationKurtosis(dataset);
populationKurtosisExcess =
statisticsService.populationKurtosisExcess(dataset);
populationSkew = statisticsService.populationSkew(dataset);
populationStdDev = statisticsService.populationStdDev(dataset);
populationVariance = statisticsService.populationVariance(dataset);
product = statisticsService.product(dataset);
sampleKurtosis = statisticsService.sampleKurtosis(dataset);
sampleKurtosisExcess = statisticsService.sampleKurtosisExcess(dataset);
sampleSkew = statisticsService.sampleSkew(dataset);
sampleStdDev = statisticsService.sampleStdDev(dataset);
sampleVariance = statisticsService.sampleVariance(dataset);
sum = statisticsService.sum(dataset);
sumOfSquaredDeviations = statisticsService.sumOfSquaredDeviations(dataset);
}
}
| 28.699187 | 77 | 0.783569 |
fdaaf38af328db1484f1d99bec23b1932f6eb428 | 656 | package GetMail.controller.persistence;
import java.util.Base64;
public class Encoder {
private static final Base64.Encoder enc = Base64.getEncoder();
private static final Base64.Decoder dec = Base64.getDecoder();
public String encode(String text){
try{
return enc.encodeToString(text.getBytes());
} catch(Exception e){
e.printStackTrace();
return null;
}
}
public String decode(String text){
try{
return new String(dec.decode(text.getBytes()));
} catch(Exception e){
e.printStackTrace();
return null;
}
}
} | 24.296296 | 66 | 0.591463 |
2f8cf781769ff6dc92916f45f529bc968ef5bf1f | 1,578 | package de.mide.wear.glossar_app;
import android.content.Intent;
import android.os.Bundle;
import android.support.wearable.activity.WearableActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
/**
* Activity zur Darstellung der Erklärung für den ausgewählten Glossar-Begriff.
* <br><br>
*
* This project is licensed under the terms of the BSD 3-Clause License.
*/
public class ErklaerungsActivity extends WearableActivity {
/**
* Lifecycle-Methode.
*
* Holt sich aus Intent, mit dem diese Activity aufgerufen wurde,
* den als Extra mitgegebenen Erklärungs-String, der dann im
* TextView-Element dargestellt wird.
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_erklaerung);
Intent intent = getIntent();
String glossarBegriff = intent.getStringExtra(MainActivity.EXTRA_KEY_BEGRIFF );
String erklaerung = intent.getStringExtra(MainActivity.EXTRA_KEY_ERKLAERUNG);
TextView glossarTextView = findViewById(R.id.begriffTextView);
glossarTextView.setText(glossarBegriff);
TextView erklaerungsTextView = findViewById(R.id.erklaerungTextView);
erklaerungsTextView.setText(erklaerung);
setAmbientEnabled(); // Enables Always-on
}
}
| 30.941176 | 90 | 0.714829 |
8ecc62c5074c7c12c010068078d9e2e6dabab8e7 | 172 | package View.topology;
import java.util.EventListener;
public interface NodeMovedEventListener extends EventListener {
void onNodeMoved(NodeMovedEvent evt);
}
| 21.5 | 64 | 0.784884 |
079058fefc91f2d67d60fdc02fe94a0aa2448470 | 807 | package org.fleet.modules.demo.test.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Select;
import org.fleet.modules.demo.test.entity.FleetOrderTicket;
import java.util.List;
/**
* @Description: 订单机票
* @Author: fleet-team
* @Date: 2019-02-15
* @Version: V1.0
*/
public interface FleetOrderTicketMapper extends BaseMapper<FleetOrderTicket> {
/**
* 通过主表外键批量删除客户
*
* @param mainId
* @return
*/
@Delete("DELETE FROM JEECG_ORDER_TICKET WHERE ORDER_ID = #{mainId}")
public boolean deleteTicketsByMainId(String mainId);
@Select("SELECT * FROM JEECG_ORDER_TICKET WHERE ORDER_ID = #{mainId}")
public List<FleetOrderTicket> selectTicketsByMainId(String mainId);
}
| 26.9 | 78 | 0.732342 |
655be1d78cc42191516f3723ad41f65b34a0bd67 | 6,649 | /*
Copyright [2016] [Taqdir Ali]
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.uclab.imp.cdss.cardiovascular.dao;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import org.uclab.imp.cdss.cardiovascular.datamodel.WellnessConceptsModel;
import org.uclab.imp.cdss.cardiovascular.datamodel.WellnessConceptsRelationships;
/**
* This is Data Access Object implementation class for the rule this DAO implements to
* create, update, retrieve of rule with conditions, conclusions, and situations
* @author Taqdir Ali
* @version 1.0
* @since 2015-08-16
* */
@Repository
public class WellnessConceptsModelDAOImpl implements WellnessConceptsModelDAO {
/**
* This creation of static object of logger for Wellness Concept
*/
private static final Logger logger = LoggerFactory.getLogger(RuleDAOImpl.class);
/**
* This creation of Session for factory
*/
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sf){
this.sessionFactory = sf;
}
/**
* This function is the implementation for add new Wellness Concept
* @param objWellnessConceptsModel
*/
public void addWellnessConcept(WellnessConceptsModel objWellnessConceptsModel) {
try
{
Session session = this.sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.persist(objWellnessConceptsModel);
tx.commit();
session.close();
logger.info("Wellness Concepts Model saved successfully, Wellness Concepts Model Details="+objWellnessConceptsModel);
}
catch(Exception ex )
{
logger.info("Error occurred in wellness concept saving"+ ex.getMessage());
}
}
/**
* This function is the implementation for update existing Wellness Concept
* @param objWellnessConceptsModel
*/
public void updateWellnessConcept(WellnessConceptsModel objWellnessConceptsModel) {
try
{
Session session = this.sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.update(objWellnessConceptsModel);
tx.commit();
session.close();
logger.info("Wellness Concepts Model updated successfully, Wellness Concepts Model Details="+objWellnessConceptsModel);
}
catch(Exception ex )
{
logger.info("Error occurred in wellness concept updating"+ ex.getMessage());
}
}
/**
* This function is the implementation for retrieving all Wellness Concepts in form of list
* @return List of WellnessConceptsModel
*/
@SuppressWarnings("unchecked")
public List<WellnessConceptsModel> listWellnessConceptsModel(String strQuery) {
try
{
Session session = this.sessionFactory.openSession();
@SuppressWarnings("unchecked")
List<WellnessConceptsModel> wellnessConceptsModelList = session.createQuery("from WellnessConceptsModel w Where w.wellnessConceptDescription like '%" + strQuery + "%'").list();
for(WellnessConceptsModel objWellnessConceptsModel : wellnessConceptsModelList){
logger.info("WellnessConceptsModel List::"+objWellnessConceptsModel);
}
session.close();
return wellnessConceptsModelList;
}
catch(Exception ex )
{
logger.info("Error occurred in wellness concept retrieving list"+ ex.getMessage());
return null;
}
}
/**
* This function is the implementation for retrieving all Wellness Concept in form of list by searching key
* @param strKey
* @param strQuery
* @return List of WellnessConceptsRelationships
*/
@SuppressWarnings("unchecked")
public List<WellnessConceptsRelationships> listWellnessConceptsByKey(String strKey, String strQuery) {
try
{
Session session = this.sessionFactory.openSession();
Query query = session.createSQLQuery("{CALL Usp_Get_WellnessConceptsByKey(:key, :query)}").addEntity(WellnessConceptsRelationships.class).setParameter("key", strKey).setParameter("query", strQuery);
List<WellnessConceptsRelationships> wellnessConceptsRelationshipslList = query.list();
for(WellnessConceptsRelationships objWellnessConceptsRelationships : wellnessConceptsRelationshipslList){
logger.info("WellnessConceptsRelationships List::"+objWellnessConceptsRelationships);
}
session.close();
return wellnessConceptsRelationshipslList;
}
catch(Exception ex )
{
logger.info("Error occurred in wellness concept retrieving list"+ ex.getMessage());
return null;
}
}
/**
* This function is the implementation for retrieving a single Wellness Concept by id
* @param id
* @return Object of WellnessConceptsModel
*/
public WellnessConceptsModel getWellnessConceptById(int id) {
try
{
Session session = this.sessionFactory.openSession();
WellnessConceptsModel objWellnessConceptsModel = (WellnessConceptsModel) session.load(WellnessConceptsModel.class, new Integer(id));
logger.info("Wellness Concepts Model loaded successfully, WellnessConceptsModel details="+objWellnessConceptsModel);
session.close();
return objWellnessConceptsModel;
}
catch(Exception ex )
{
logger.info("Error occurred in wellness concept retrieving"+ ex.getMessage());
return null;
}
}
/**
* This function is the implementation for deleting Wellness Concept
* @param id
*/
public void removeWellnessConcept(int id) {
try
{
Session session = this.sessionFactory.openSession();
WellnessConceptsModel objWellnessConceptsModel = (WellnessConceptsModel) session.load(WellnessConceptsModel.class, new Integer(id));
if(null != objWellnessConceptsModel){
session.delete(objWellnessConceptsModel);
}
logger.info("WellnessConceptsModel deleted successfully, Rule details="+objWellnessConceptsModel);
session.close();
}
catch(Exception ex )
{
logger.info("Error occurred in wellness concept deleting"+ ex.getMessage());
}
}
}
| 34.097436 | 201 | 0.737254 |
543bce5e361e7a18de3339d341dbd52a5f0307ba | 645 | package gov.hhs.cms.bluebutton.data.codebook.data;
import org.junit.Assert;
import org.junit.Test;
/**
* Unit tests for {@link CcwCodebookVariable}.
*/
public final class CcwCodebookVariableTest {
/**
* Verifies that {@link CcwCodebookVariable} was generated as expected.
*/
@Test
public void constants() {
Assert.assertTrue(CcwCodebookVariable.values().length > 0);
}
/**
* Verifies that {@link CcwCodebookVariable#getVariable()} works as expected.
*/
@Test
public void getVariable() {
for (CcwCodebookVariable variableEnum : CcwCodebookVariable.values()) {
Assert.assertNotNull(variableEnum.getVariable());
}
}
}
| 23.035714 | 78 | 0.727132 |
cfe64e5737ef16daccd125232f6641afe3df9b7e | 1,988 | /*******************************************************************************
* Copyright 2017 UIA
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package uia.netflow.packet.v1;
public class NFHeaderV1 {
private int version;
private int count;
private int sysUptime;
private int unixSecs;
private int unixNsecs;
public NFHeaderV1() {
this.version = 5;
}
public int getVersion() {
return this.version;
}
public void setVersion(int version) {
this.version = version;
}
public int getCount() {
return this.count;
}
public void setCount(int count) {
this.count = count;
}
public int getSysUptime() {
return this.sysUptime;
}
public void setSysUptime(int sysUptime) {
this.sysUptime = sysUptime;
}
public int getUnixSecs() {
return this.unixSecs;
}
public void setUnixSecs(int unixSecs) {
this.unixSecs = unixSecs;
}
public int getUnixNsecs() {
return this.unixNsecs;
}
public void setUnixNsecs(int unixNsecs) {
this.unixNsecs = unixNsecs;
}
}
| 25.818182 | 81 | 0.615191 |
cf5cce8b5807a0f4fc1dc2e738d5ce127f9e625c | 5,485 | package com.salab.project.kakikana.viewmodel;
import android.app.Application;
import android.graphics.Bitmap;
import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
import com.salab.project.kakikana.model.Question;
import com.salab.project.kakikana.model.QuestionResult;
import com.salab.project.kakikana.model.QuizResult;
import com.salab.project.kakikana.model.UserKana;
import com.salab.project.kakikana.repository.Repository;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class QuizViewModel extends AndroidViewModel {
// constants
private static final String TAG = QuizViewModel.class.getSimpleName();
private static final int numQuestions = 5;
private static final int quizId = 0;
// global variables
private Repository repository;
private MutableLiveData<Boolean> isQuizEnded = new MutableLiveData<>(false);
private MutableLiveData<Integer> quizProgressInPercent = new MutableLiveData<>(0);
private LiveData<List<Question>> questionList;
private MutableLiveData<Question> currentQuestion = new MutableLiveData<>();
private int currentQuestionIndex = 0;
private MutableLiveData<QuestionResult> questionResult = new MutableLiveData<>();
// output
private QuizResult quizResult = new QuizResult();
private Map<String, UserKana> kanaQuizResult = new HashMap<>();
public QuizViewModel(@NonNull Application application) {
super(application);
repository = new Repository(application.getApplicationContext());
questionList = repository.getQuestionList(quizId, numQuestions);
questionList.observeForever(new Observer<List<Question>>() {
@Override
public void onChanged(List<Question> questions) {
// set first question when data ready and it notifies UI to start
if (questions != null && questions.size() != 0){
currentQuestion.setValue(questions.get(currentQuestionIndex));
questionList.removeObserver(this);
}
}
});
}
// response to UI events
public void submitAnswer(Bitmap bitmap, int timeTaken){
// users confirm their answer and start judging their answers
repository.getQuestionResult(currentQuestion, bitmap, timeTaken, questionResult);
}
public void nextQuestion() {
// save previous question result for latter result displaying and uploading
saveResultToOutputs();
updateProgress();
// get a new question or end the quiz
List<Question> questions = questionList.getValue();
if (questions != null){
if (currentQuestionIndex < questions.size() - 1){
currentQuestionIndex++;
currentQuestion.setValue(questions.get(currentQuestionIndex));
} else {
// no more questions. Quiz ends
isQuizEnded.setValue(true);
uploadQuizResult();
}
}
}
public boolean onReportIssueClick() {
QuestionResult questionResultValue = questionResult.getValue();
if (questionResultValue != null){
// every click will swap the flag
questionResultValue.setIssued(!questionResultValue.isIssued());
return questionResultValue.isIssued();
}
return false;
}
private void updateProgress() {
// update current progress in percentage
quizProgressInPercent.setValue(Math.round((float)(currentQuestionIndex+1)/numQuestions*100));
}
private void uploadQuizResult() {
// sync data to server
repository.addQuizResult(quizResult, kanaQuizResult);
}
private void saveResultToOutputs() {
QuestionResult questionResultValue = questionResult.getValue();
if (questionResultValue == null){
return;
}
// save result to quizResult which will be upload to server
quizResult.appendQuestionResult(questionResultValue);
// using map to record by kana result
// it will be used later to update users' kana-base stats
if (!questionResultValue.isIssued()) {
String kanaId = questionResultValue.getQuestionKanaIdString();
UserKana userKana;
if (kanaQuizResult.containsKey(kanaId) && kanaQuizResult.get(kanaId) != null){
userKana = kanaQuizResult.get(kanaId);
} else {
userKana = new UserKana();
}
if (questionResultValue.isCorrect()) {
userKana.addCorrect();
} else {
userKana.addIncorrect();
}
kanaQuizResult.put(kanaId, userKana);
}
}
// getter and setter methods
public LiveData<Integer> getQuizProgressInPercent() {
return quizProgressInPercent;
}
public LiveData<Boolean> getIsQuizEnded() {
return isQuizEnded;
}
public LiveData<List<Question>> getQuestionList() {
return questionList;
}
public LiveData<Question> getCurrentQuestion() {
return currentQuestion;
}
public LiveData<QuestionResult> getQuestionResult() {
return questionResult;
}
public QuizResult getQuizResult() {
return quizResult;
}
}
| 33.042169 | 101 | 0.660893 |
14a89ddb07402a9af2caec543edb3e1eff305427 | 1,288 | /*
* $Id: NewProjectAction.java,v 1.2 2005/09/05 09:08:29 tcurley Exp $
*
* Copyright (C) 2002, Cladonia Ltd. All rights reserved.
*
* This software is the proprietary information of Cladonia Ltd.
* Use is subject to license terms.
*/
package com.cladonia.xngreditor.project.actions;
import java.awt.event.ActionEvent;
import javax.swing.AbstractAction;
import com.cladonia.xngreditor.project.Project;
/**
* An action that can be used to copy information
* in a XML Document.
*
* @version $Revision: 1.2 $, $Date: 2005/09/05 09:08:29 $
* @author Dogsbay
*/
public class NewProjectAction extends AbstractAction {
private static final boolean DEBUG = false;
private Project project = null;
/**
* The constructor for the add action.
*
* @param editor the editor to copy information from.
*/
public NewProjectAction( Project project) {
super( "New Project");
this.project = project;
putValue( MNEMONIC_KEY, new Integer( 'N'));
putValue( SHORT_DESCRIPTION, "Add a Project");
}
/**
* The implementation of the copy action.
*
* @param e the action event.
*/
public void actionPerformed( ActionEvent e) {
boolean isStartup = false;
project.addProject(isStartup);
}
}
| 24.301887 | 70 | 0.668478 |
901942769a3a25c928ea99f38041db9161423fa1 | 7,927 | /*******************************************************************************
* © 2012 Global Retail Information Ltd.
******************************************************************************/
package com.becoblohm.cr.net.models;
import java.io.Serializable;
import java.util.Date;
/**
*/
public class Client implements Serializable {
/**
*
*/
private static final long serialVersionUID = 6438809252376710094L;
// private Long id;
/**
* Field clientType.
*/
private ClientType clientType;
/**
* Field economicActivity.
*/
private EconomicActivity economicActivity;
/**
* Field idNumber.
*/
private String idNumber;
/**
* Field isTaxPayer.
*/
private boolean isTaxPayer;
/**
* Field registerDate.
*/
private Date registerDate;
/**
* Field updateDate.
*/
private Date updateDate;
/**
* Field name.
*/
private String name;
/**
* Field fiscalId.
*/
private String fiscalId;
/**
* Field address.
*/
private String address;
/**
* Field fiscalAddress.
*/
private String fiscalAddress;
/**
* Field phone.
*/
private String phone;
/**
* Field email.
*/
private String email;
/**
* Field bigClient.
*/
private String bigClient;
/**
* Field employeeId.
*/
private long employeeId;
/**
* Field transactionClientId.
*/
protected long transactionClientId = -1;
/**
* Field employeeDiscount.
*/
private boolean employeeDiscount = false;
// TODO Crear campo en la tabla tipocliente y agregar en fromJPA de tipo
// cliente
/**
* Field diplomatic.
*/
private boolean diplomatic = false;
/**
* Field retentionAgent.
*/
private String retentionAgent = "N";
/**
* Field isSinc.
*/
private String isSinc = "N";
/**
* Method getIsSinc.
* @return String
*/
public String getIsSinc() {
return isSinc;
}
/**
* Method setIsSinc.
* @param isSinc String
*/
public void setIsSinc(String isSinc) {
this.isSinc = isSinc;
}
/**
* Constructor for Client.
*/
public Client() {
this.clientType = new ClientType();
// this.exonerationType=new ExonerationType();
}
/**
* Constructor for Client.
* @param name String
* @param idNumber String
* @param address String
* @param phone String
* @param economicActivity EconomicActivity
*/
public Client(String name, String idNumber, String address, String phone, EconomicActivity economicActivity) {
super();
this.name = name;
this.idNumber = idNumber;
this.address = address;
this.phone = phone;
this.economicActivity = economicActivity;
}
/*
* public Long getId() { return id; } public void setId(Long id) { this.id =
* id; }
*/
/**
* Method getClientType.
* @return ClientType
*/
public ClientType getClientType() {
return clientType;
}
/**
* Method setClientType.
* @param clientType ClientType
*/
public void setClientType(ClientType clientType) {
this.clientType = clientType;
}
/**
* Method getEconomicActivity.
* @return EconomicActivity
*/
public EconomicActivity getEconomicActivity() {
return economicActivity;
}
/**
* Method setEconomicActivity.
* @param economicActivity EconomicActivity
*/
public void setEconomicActivity(EconomicActivity economicActivity) {
this.economicActivity = economicActivity;
}
/**
* Method getIdNumber.
* @return String
*/
public String getIdNumber() {
return idNumber;
}
/**
* Method setIdNumber.
* @param idNumber String
*/
public void setIdNumber(String idNumber) {
this.idNumber = idNumber;
}
/*
* Si el cliente es juridico, se usa solo para el registro de clientes
*/
/**
* Method isTaxPayer.
* @return boolean
*/
public boolean isTaxPayer() {
return isTaxPayer;
}
/**
* Method setTaxPayer.
* @param isTaxPayer boolean
*/
public void setTaxPayer(boolean isTaxPayer) {
boolean tmp = this.isTaxPayer;
this.isTaxPayer = isTaxPayer;
}
/**
* Method getRegisterDate.
* @return Date
*/
public Date getRegisterDate() {
return registerDate;
}
/**
* Method setRegisterDate.
* @param registerDate Date
*/
public void setRegisterDate(Date registerDate) {
Date tmp = this.registerDate;
this.registerDate = registerDate;
}
/**
* Method getUpdateDate.
* @return Date
*/
public Date getUpdateDate() {
return updateDate;
}
/**
* Method setUpdateDate.
* @param updateDate Date
*/
public void setUpdateDate(Date updateDate) {
Date tmp = this.updateDate;
this.updateDate = updateDate;
}
/**
* Method getName.
* @return String
*/
public String getName() {
return name;
}
/**
* Method setName.
* @param name String
*/
public void setName(String name) {
String tmp = this.name;
this.name = name;
}
/**
* Method getFiscalId.
* @return String
*/
public String getFiscalId() {
return fiscalId;
}
/**
* Method setFiscalId.
* @param fiscalId String
*/
public void setFiscalId(String fiscalId) {
String tmp = this.fiscalId;
this.fiscalId = fiscalId;
}
/**
* Method getAddress.
* @return String
*/
public String getAddress() {
return address;
}
/**
* Method setAddress.
* @param address String
*/
public void setAddress(String address) {
String tmp = this.address;
this.address = address;
}
/**
* Method getFiscalAddress.
* @return String
*/
public String getFiscalAddress() {
return fiscalAddress;
}
/**
* Method setFiscalAddress.
* @param fiscalAddress String
*/
public void setFiscalAddress(String fiscalAddress) {
String tmp = this.fiscalAddress;
this.fiscalAddress = fiscalAddress;
}
/**
* Method getPhone.
* @return String
*/
public String getPhone() {
return phone;
}
/**
* Method setPhone.
* @param phone String
*/
public void setPhone(String phone) {
String tmp = this.phone;
this.phone = phone;
}
/**
* Method getEmail.
* @return String
*/
public String getEmail() {
return email;
}
/**
* Method setEmail.
* @param email String
*/
public void setEmail(String email) {
String tmp = this.email;
this.email = email;
}
/**
* Method getRetentionAgent.
* @return String
*/
public String getRetentionAgent() {
return retentionAgent;
}
/**
* Method setRetentionAgent.
* @param retentionAgent String
*/
public void setRetentionAgent(String retentionAgent) {
String tmp = this.retentionAgent;
this.retentionAgent = retentionAgent;
}
/**
* Method getEmployeeId.
* @return long
*/
public long getEmployeeId() {
return employeeId;
}
/**
* Method setEmployeeId.
* @param employeeId long
*/
public void setEmployeeId(long employeeId) {
long tmp = this.employeeId;
this.employeeId = employeeId;
}
/**
* Method getTransactionClientId.
* @return long
*/
public long getTransactionClientId() {
return transactionClientId;
}
/**
* Method setTransactionClientId.
* @param transactionClientId long
*/
public void setTransactionClientId(long transactionClientId) {
long tmp = this.transactionClientId;
this.transactionClientId = transactionClientId;
}
/**
* Method isEmployeeDiscount.
* @return boolean
*/
public boolean isEmployeeDiscount() {
return employeeDiscount;
}
/**
* Method setEmployeeDiscount.
* @param employeeDiscount boolean
*/
public void setEmployeeDiscount(boolean employeeDiscount) {
boolean tmp = this.employeeDiscount;
this.employeeDiscount = employeeDiscount;
}
/**
* @param diplomatic
* the diplomatic to set
*/
public void setDiplomatic(boolean diplomatic) {
this.diplomatic = diplomatic;
}
/**
* @return the diplomatic */
public boolean getDiplomatic() {
return diplomatic;
}
/**
* @param bigClient
* the bigClient to set
*/
public void setBigClient(String bigClient) {
this.bigClient = bigClient;
}
/**
* @return the bigClient */
public String getBigClient() {
return bigClient;
}
}
| 17.12095 | 111 | 0.65258 |
7b675baf6915322586ba5f60488cbb48cc995a2c | 187 | package com.concretepage.service;
import org.springframework.stereotype.Service;
@Service
public class MyService1 {
public String getMessage() {
return "Hello World!";
}
}
| 17 | 46 | 0.727273 |
08dca2ad08442cdb9208b7404c960735fd878175 | 7,864 | package com.actionbarsherlock.internal.view.menu;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Resources;
import android.view.KeyEvent;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.SubMenu;
import java.util.ArrayList;
import java.util.List;
public class ActionMenu
implements Menu
{
private Context mContext;
private boolean mIsQwerty;
private ArrayList<ActionMenuItem> mItems;
public ActionMenu(Context paramContext)
{
this.mContext = paramContext;
this.mItems = new ArrayList();
}
private int findItemIndex(int paramInt)
{
ArrayList localArrayList = this.mItems;
int i = localArrayList.size();
for (int j = 0;; j++)
{
if (j >= i) {
j = -1;
}
while (((ActionMenuItem)localArrayList.get(j)).getItemId() == paramInt) {
return j;
}
}
}
private ActionMenuItem findItemWithShortcut(int paramInt, KeyEvent paramKeyEvent)
{
boolean bool = this.mIsQwerty;
ArrayList localArrayList = this.mItems;
int i = localArrayList.size();
int j = 0;
ActionMenuItem localActionMenuItem;
if (j >= i) {
localActionMenuItem = null;
}
label77:
for (;;)
{
return localActionMenuItem;
localActionMenuItem = (ActionMenuItem)localArrayList.get(j);
if (bool) {}
for (int k = localActionMenuItem.getAlphabeticShortcut();; k = localActionMenuItem.getNumericShortcut())
{
if (paramInt == k) {
break label77;
}
j++;
break;
}
}
}
public MenuItem add(int paramInt)
{
return add(0, 0, 0, paramInt);
}
public MenuItem add(int paramInt1, int paramInt2, int paramInt3, int paramInt4)
{
return add(paramInt1, paramInt2, paramInt3, this.mContext.getResources().getString(paramInt4));
}
public MenuItem add(int paramInt1, int paramInt2, int paramInt3, CharSequence paramCharSequence)
{
ActionMenuItem localActionMenuItem = new ActionMenuItem(getContext(), paramInt1, paramInt2, 0, paramInt3, paramCharSequence);
this.mItems.add(paramInt3, localActionMenuItem);
return localActionMenuItem;
}
public MenuItem add(CharSequence paramCharSequence)
{
return add(0, 0, 0, paramCharSequence);
}
public int addIntentOptions(int paramInt1, int paramInt2, int paramInt3, ComponentName paramComponentName, Intent[] paramArrayOfIntent, Intent paramIntent, int paramInt4, MenuItem[] paramArrayOfMenuItem)
{
PackageManager localPackageManager = this.mContext.getPackageManager();
List localList = localPackageManager.queryIntentActivityOptions(paramComponentName, paramArrayOfIntent, paramIntent, 0);
if (localList != null) {}
int j;
for (int i = localList.size();; i = 0)
{
if ((paramInt4 & 0x1) == 0) {
removeGroup(paramInt1);
}
j = 0;
if (j < i) {
break;
}
return i;
}
ResolveInfo localResolveInfo = (ResolveInfo)localList.get(j);
if (localResolveInfo.specificIndex < 0) {}
for (Intent localIntent1 = paramIntent;; localIntent1 = paramArrayOfIntent[localResolveInfo.specificIndex])
{
Intent localIntent2 = new Intent(localIntent1);
localIntent2.setComponent(new ComponentName(localResolveInfo.activityInfo.applicationInfo.packageName, localResolveInfo.activityInfo.name));
MenuItem localMenuItem = add(paramInt1, paramInt2, paramInt3, localResolveInfo.loadLabel(localPackageManager)).setIcon(localResolveInfo.loadIcon(localPackageManager)).setIntent(localIntent2);
if ((paramArrayOfMenuItem != null) && (localResolveInfo.specificIndex >= 0)) {
paramArrayOfMenuItem[localResolveInfo.specificIndex] = localMenuItem;
}
j++;
break;
}
}
public SubMenu addSubMenu(int paramInt)
{
return null;
}
public SubMenu addSubMenu(int paramInt1, int paramInt2, int paramInt3, int paramInt4)
{
return null;
}
public SubMenu addSubMenu(int paramInt1, int paramInt2, int paramInt3, CharSequence paramCharSequence)
{
return null;
}
public SubMenu addSubMenu(CharSequence paramCharSequence)
{
return null;
}
public void clear()
{
this.mItems.clear();
}
public void close() {}
public MenuItem findItem(int paramInt)
{
return (MenuItem)this.mItems.get(findItemIndex(paramInt));
}
public Context getContext()
{
return this.mContext;
}
public MenuItem getItem(int paramInt)
{
return (MenuItem)this.mItems.get(paramInt);
}
public boolean hasVisibleItems()
{
ArrayList localArrayList = this.mItems;
int i = localArrayList.size();
for (int j = 0;; j++)
{
if (j >= i) {
return false;
}
if (((ActionMenuItem)localArrayList.get(j)).isVisible()) {
return true;
}
}
}
public boolean isShortcutKey(int paramInt, KeyEvent paramKeyEvent)
{
return findItemWithShortcut(paramInt, paramKeyEvent) != null;
}
public boolean performIdentifierAction(int paramInt1, int paramInt2)
{
int i = findItemIndex(paramInt1);
if (i < 0) {
return false;
}
return ((ActionMenuItem)this.mItems.get(i)).invoke();
}
public boolean performShortcut(int paramInt1, KeyEvent paramKeyEvent, int paramInt2)
{
ActionMenuItem localActionMenuItem = findItemWithShortcut(paramInt1, paramKeyEvent);
if (localActionMenuItem == null) {
return false;
}
return localActionMenuItem.invoke();
}
public void removeGroup(int paramInt)
{
ArrayList localArrayList = this.mItems;
int i = localArrayList.size();
int j = 0;
for (;;)
{
if (j >= i) {
return;
}
if (((ActionMenuItem)localArrayList.get(j)).getGroupId() == paramInt)
{
localArrayList.remove(j);
i--;
}
else
{
j++;
}
}
}
public void removeItem(int paramInt)
{
this.mItems.remove(findItemIndex(paramInt));
}
public void setGroupCheckable(int paramInt, boolean paramBoolean1, boolean paramBoolean2)
{
ArrayList localArrayList = this.mItems;
int i = localArrayList.size();
for (int j = 0;; j++)
{
if (j >= i) {
return;
}
ActionMenuItem localActionMenuItem = (ActionMenuItem)localArrayList.get(j);
if (localActionMenuItem.getGroupId() == paramInt)
{
localActionMenuItem.setCheckable(paramBoolean1);
localActionMenuItem.setExclusiveCheckable(paramBoolean2);
}
}
}
public void setGroupEnabled(int paramInt, boolean paramBoolean)
{
ArrayList localArrayList = this.mItems;
int i = localArrayList.size();
for (int j = 0;; j++)
{
if (j >= i) {
return;
}
ActionMenuItem localActionMenuItem = (ActionMenuItem)localArrayList.get(j);
if (localActionMenuItem.getGroupId() == paramInt) {
localActionMenuItem.setEnabled(paramBoolean);
}
}
}
public void setGroupVisible(int paramInt, boolean paramBoolean)
{
ArrayList localArrayList = this.mItems;
int i = localArrayList.size();
for (int j = 0;; j++)
{
if (j >= i) {
return;
}
ActionMenuItem localActionMenuItem = (ActionMenuItem)localArrayList.get(j);
if (localActionMenuItem.getGroupId() == paramInt) {
localActionMenuItem.setVisible(paramBoolean);
}
}
}
public void setQwertyMode(boolean paramBoolean)
{
this.mIsQwerty = paramBoolean;
}
public int size()
{
return this.mItems.size();
}
}
| 26.748299 | 205 | 0.666455 |
c0fd35a4220da4c7fc2de0d0c12d87165dd2504c | 5,927 | package com.metalbeetle.koboldpit;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
public class Display {
final GameWorld w;
final int width;
final int height;
int prevMilestone = 50;
Display(GameWorld w, int width, int height) {
this.w = w;
this.width = width;
this.height = height;
}
void draw(Graphics2D g) {
g.setFont(new Font("Courier", Font.PLAIN, 11));
int xOff = 1;
int yOff = g.getFontMetrics().getAscent();
if (w.intro) {
g.setColor(Color.BLACK);
g.fillRect(0, 0, width, height);
g.setColor(Color.RED);
g.drawString("KOBOLD PIT", 20 + xOff, 60 + yOff);
g.drawString("Tales of skull piles and ecological degradation!", 20 + xOff, 80 + yOff);
g.setColor(new Color(0, 71, 171));
g.drawString("k", 20 + xOff, 100 + yOff);
g.setColor(Color.WHITE);
g.drawString(" A kobold. It likes to eat and sit in pits.", 20 + xOff, 100 + yOff);
g.setColor(new Color(250, 250, 245));
g.drawString("r", 20 + xOff, 120 + yOff);
g.setColor(Color.WHITE);
g.drawString(" A rabbit. It's what kobolds eat. When they're not eating each other.", 20 + xOff, 120 + yOff);
g.setColor(new Color(245, 245, 215));
g.drawString("ø", 20 + xOff, 140 + yOff);
g.setColor(Color.WHITE);
g.drawString(" A skull. Kobolds make big piles of them in the center of the pit. Any skull will do.", 20 + xOff, 140 + yOff);
g.setColor(Tile.Type.GRASS.c);
g.fillRect(20, 160, 10, 10);
g.setColor(Color.WHITE);
g.drawString(" Grass. Rabbits like it. Kobolds don't. They much prefer...", 20 + xOff, 160 + yOff);
g.setColor(Tile.Type.PIT.c);
g.fillRect(20, 180, 10, 10);
g.setColor(Color.WHITE);
g.drawString(" ...pits! Kobolds move much faster through pits and get less hungry resting in them.", 20 + xOff, 180 + yOff);
g.drawString(" Kobold claws are so sharp that they tear up the ground beneath them, causing the pit to widen with time.", 20 + xOff, 200 + yOff);
g.setColor(Color.YELLOW);
g.drawString("h", 20 + xOff, 220 + yOff);
g.setColor(Color.WHITE);
g.drawString(" A hungry kobold.", 20 + xOff, 220 + yOff);
g.drawString("H", 20 + xOff, 240 + yOff);
g.setColor(Color.WHITE);
g.drawString(" A very hungry kobold.", 20 + xOff, 240 + yOff);
g.setColor(new Color(255, 80, 180));
g.drawString("P", 20 + xOff, 260 + yOff);
g.setColor(Color.WHITE);
g.drawString(" A pregnant kobold. They only get pregnant in the presence of skulls. Don't ask.", 20 + xOff, 260 + yOff);
g.setColor(new Color(0, 71, 171));
g.drawString("K", 20 + xOff, 280 + yOff);
g.setColor(Color.WHITE);
g.drawString(" A kobold champion. It has earned the right to eat other kobolds!", 20 + xOff, 280 + yOff);
g.setColor(new Color(10, 100, 10));
g.drawString("t", 20 + xOff, 300 + yOff);
g.setColor(Color.WHITE);
g.drawString(" A tree. It's mostly in the way. But it will fall into your pit eventually.", 20 + xOff, 300 + yOff);
g.setColor(Color.WHITE);
g.drawString("Instructions: Use your mouse to direct the kobolds to victory!", 20 + xOff, 340 + yOff);
g.setColor(new Color(30, 101, 201));
g.drawString("k", 20 + xOff, 360 + yOff);
g.setColor(Color.WHITE);
g.drawString(" This kobold is following your cursor. Kobolds close to the cursor tend to follow it.", 20 + xOff, 360 + yOff);
g.setColor(Color.WHITE);
g.drawString("That's all! Click to start the game. Contact david.stark@zarkonnen.com if you have questions.", 20 + xOff, 400 + yOff);
return;
}
g.setColor(Color.BLACK);
g.fillRect(0, 0, width, height);
int skulls = 0;
for (int y = 0; y < w.map.length; y++) {
for (int x = 0; x < w.map[y].length; x++) {
g.setColor(w.map[y][x].type.c);
/*if (x == w.cursorX && y == w.cursorY) {
g.setColor(Color.YELLOW);
}*/
g.fillRect(x * 10, y * 10, 10, 10);
if (w.map[y][x].erosion > 0 && w.map[y][x].type != Tile.Type.PIT) {
g.setColor(new Color(130, 125, 90));
g.drawString("#", x * 10 + xOff, y * 10 + yOff);
}
if (w.map[y][x].blood > 0) {
g.setColor(Color.RED);
g.drawString("*", x * 10 + xOff, y * 10 + yOff);
}
if (w.map[y][x].skulls > 0) {
g.setColor(new Color(245, 245, 215));
g.drawString("ø", x * 10 + xOff, y * 10 + yOff);
skulls += w.map[y][x].skulls;
}
}
}
for (Item item : w.items) {
if (item instanceof Animal) {
Animal a = (Animal) item;
if (a.hunger > a.deathHunger * 3 / 4 && (w.tick / 4) % 12 < 3) {
g.setColor(Color.YELLOW);
g.drawString(a.hunger > a.deathHunger * 6 / 7 ? "H" : "h", item.x * 10 + xOff, item.y * 10 + yOff);
} else {
if (a instanceof Kobold && ((Kobold) a).pregnant > 0 && (w.tick / 4) % 12 < 6) {
g.setColor(new Color(255, 80, 180));
g.drawString("P", item.x * 10 + xOff, item.y * 10 + yOff);
} else {
if (a instanceof Kobold && ((Kobold) a).skulls > 0 && (w.tick / 4) % 12 < 6) {
g.setColor(new Color(245, 245, 215));
g.drawString("ø", item.x * 10 + xOff, item.y * 10 + yOff);
} else {
g.setColor(item.c);
if (a instanceof Kobold && ((Kobold) a).following) {
g.setColor(new Color(30, 101, 201));
}
g.drawString(item.l, item.x * 10 + xOff, item.y * 10 + yOff);
}
}
}
} else {
g.setColor(item.c);
g.drawString(item.l, item.x * 10 + xOff, item.y * 10 + yOff);
}
}
int nks = 0;
for (Item i : w.items) {
if (i instanceof Kobold) { nks++; }
}
if (skulls > prevMilestone * 2) {
w.info("Your skull pile has grown to more than " + (prevMilestone * 2) + " skulls.", new Color(70, 0, 0));
prevMilestone *= 2;
}
g.setColor(Color.WHITE);
g.drawString(nks + " kobolds, " + skulls + " skulls in pile", 20 + xOff, 560 + yOff);
if (w.infoT != null) {
g.setColor(w.infoC);
g.drawString(w.infoT, 20 + xOff, 540 + yOff);
}
}
}
| 37.27673 | 151 | 0.595242 |
29772271adfa52b7a672445d2848dff6a0693fdd | 622 | /*
* blackduck-common-api
*
* Copyright (c) 2022 Synopsys, Inc.
*
* Use subject to the terms and conditions of the Synopsys End User Software License and Maintenance Agreement. All rights reserved worldwide.
*/
package com.synopsys.integration.blackduck.api.manual.view;
import com.synopsys.integration.blackduck.api.core.BlackDuckView;
public class ProjectMappingView extends BlackDuckView {
private String applicationId;
public String getApplicationId() {
return applicationId;
}
public void setApplicationId(String applicationId) {
this.applicationId = applicationId;
}
}
| 25.916667 | 142 | 0.747588 |
29dc81341d10d684fb9e9a348110d9e6ccfb3581 | 1,465 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.vmwarecloudsimple.models;
import com.azure.core.util.ExpandableStringEnum;
import com.fasterxml.jackson.annotation.JsonCreator;
import java.util.Collection;
/** Defines values for GuestOsnicCustomizationAllocation. */
public final class GuestOsnicCustomizationAllocation extends ExpandableStringEnum<GuestOsnicCustomizationAllocation> {
/** Static value static for GuestOsnicCustomizationAllocation. */
public static final GuestOsnicCustomizationAllocation STATIC = fromString("static");
/** Static value dynamic for GuestOsnicCustomizationAllocation. */
public static final GuestOsnicCustomizationAllocation DYNAMIC = fromString("dynamic");
/**
* Creates or finds a GuestOsnicCustomizationAllocation from its string representation.
*
* @param name a name to look for.
* @return the corresponding GuestOsnicCustomizationAllocation.
*/
@JsonCreator
public static GuestOsnicCustomizationAllocation fromString(String name) {
return fromString(name, GuestOsnicCustomizationAllocation.class);
}
/** @return known GuestOsnicCustomizationAllocation values. */
public static Collection<GuestOsnicCustomizationAllocation> values() {
return values(GuestOsnicCustomizationAllocation.class);
}
}
| 41.857143 | 118 | 0.780205 |
0d2e15be138ebf5420436c3c21a612b3ca740ec9 | 2,195 |
//----------------------------------------------------
// The following code was generated by CUP v0.11b 20160615 (GIT 4ac7450)
//----------------------------------------------------
package MonaParser;
/** CUP generated class containing symbol constants. */
public class sym {
/* terminals */
public static final int EQUALS = 21;
public static final int LPAREN = 14;
public static final int GREATER = 23;
public static final int WS1S = 6;
public static final int LESS = 24;
public static final int RPAREN = 15;
public static final int IMPLICATION = 19;
public static final int SEMICOLON = 10;
public static final int AND = 18;
public static final int IN = 28;
public static final int OR = 17;
public static final int COMMA = 36;
public static final int M2LSTR = 8;
public static final int PLUS = 35;
public static final int LESSEQ = 25;
public static final int ID = 4;
public static final int VAR2 = 13;
public static final int EOF = 0;
public static final int VAR1 = 12;
public static final int VAR0 = 11;
public static final int EQUIVALENCE = 20;
public static final int TRUE = 2;
public static final int error = 1;
public static final int NEGATION = 16;
public static final int ALL2 = 33;
public static final int ALL1 = 32;
public static final int INTLITERAL = 5;
public static final int COLON = 34;
public static final int NOTIN = 29;
public static final int NOTEQUALS = 22;
public static final int EX2 = 31;
public static final int EX1 = 30;
public static final int GREATEREQ = 26;
public static final int FALSE = 3;
public static final int WS2S = 7;
public static final int M2LTREE = 9;
public static final int SUB = 27;
public static final String[] terminalNames = new String[] {
"EOF",
"error",
"TRUE",
"FALSE",
"ID",
"INTLITERAL",
"WS1S",
"WS2S",
"M2LSTR",
"M2LTREE",
"SEMICOLON",
"VAR0",
"VAR1",
"VAR2",
"LPAREN",
"RPAREN",
"NEGATION",
"OR",
"AND",
"IMPLICATION",
"EQUIVALENCE",
"EQUALS",
"NOTEQUALS",
"GREATER",
"LESS",
"LESSEQ",
"GREATEREQ",
"SUB",
"IN",
"NOTIN",
"EX1",
"EX2",
"ALL1",
"ALL2",
"COLON",
"PLUS",
"COMMA"
};
}
| 24.662921 | 72 | 0.629157 |
f3c5440322499ce43c35d5ad0ce5790aee80f08e | 5,987 | /*
* Copyright (c) 2010-2015 Pivotal Software, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You
* may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License. See accompanying
* LICENSE file.
*/
package com.gemstone.gemfire.internal.cache;
import java.io.File;
import java.util.Properties;
import junit.framework.TestCase;
import com.gemstone.gemfire.cache.*;
import com.gemstone.gemfire.distributed.*;
/**
* This test tests Illegal arguements being passed to create disk regions. The
* creation of the DWA object should throw a relevant exception if the
* arguements specified are incorrect.
*
* @author mbid
*
*/
public class DiskRegionIllegalArguementsJUnitTest extends TestCase
{
protected static Cache cache = null;
protected static DistributedSystem ds = null;
protected static Properties props = new Properties();
static {
props.setProperty("mcast-port", "0");
props.setProperty("locators", "");
props.setProperty("log-level", "config"); // to keep diskPerf logs smaller
props.setProperty("statistic-sampling-enabled", "true");
props.setProperty("enable-time-statistics", "true");
props.setProperty("statistic-archive-file", "stats.gfs");
}
protected void setUp() throws Exception {
super.setUp();
cache = new CacheFactory(props).create();
ds = cache.getDistributedSystem();
}
protected void tearDown() throws Exception {
cache.close();
super.tearDown();
}
public DiskRegionIllegalArguementsJUnitTest(String name) {
super(name);
}
/**
* test Illegal max oplog size
*/
public void testMaxOplogSize()
{
DiskStoreFactory dsf = cache.createDiskStoreFactory();
try {
dsf.setMaxOplogSize(-1);
fail("expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
}
dsf.setMaxOplogSize(1);
assertEquals(1, dsf.create("test").getMaxOplogSize());
}
public void testCompactionThreshold() {
DiskStoreFactory dsf = cache.createDiskStoreFactory();
try {
dsf.setCompactionThreshold(-1);
fail("expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
}
try {
dsf.setCompactionThreshold(101);
fail("expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
}
dsf.setCompactionThreshold(0);
dsf.setCompactionThreshold(100);
assertEquals(100, dsf.create("test").getCompactionThreshold());
}
public void testAutoCompact()
{
DiskStoreFactory dsf = cache.createDiskStoreFactory();
dsf.setAutoCompact(true);
assertEquals(true, dsf.create("test").getAutoCompact());
dsf.setAutoCompact(false);
assertEquals(false, dsf.create("test2").getAutoCompact());
}
public void testAllowForceCompaction()
{
DiskStoreFactory dsf = cache.createDiskStoreFactory();
dsf.setAllowForceCompaction(true);
assertEquals(true, dsf.create("test").getAllowForceCompaction());
dsf.setAllowForceCompaction(false);
assertEquals(false, dsf.create("test2").getAllowForceCompaction());
}
public void testDiskDirSize()
{
File file1 = new File("file1");
File file2 = new File("file2");
File file3 = new File("file3");
File file4 = new File("file4");
file1.mkdir();
file2.mkdir();
file3.mkdir();
file4.mkdir();
file1.deleteOnExit();
file2.deleteOnExit();
file3.deleteOnExit();
file4.deleteOnExit();
File[] dirs = { file1, file2, file3, file4 };
int[] ints = { 1, 2, 3, -4 };
DiskStoreFactory dsf = cache.createDiskStoreFactory();
try {
dsf.setDiskDirsAndSizes(dirs, ints);
fail("expected IllegalArgumentException");
}
catch (IllegalArgumentException ok) {
}
int[] ints1 = { 1, 2, 3 };
try {
dsf.setDiskDirsAndSizes(dirs, ints1);
fail("expected IllegalArgumentException");
}
catch (IllegalArgumentException ok) {
}
ints[3] = 4;
dsf.setDiskDirsAndSizes(dirs, ints);
}
public void testDiskDirs()
{
File file1 = new File("file6");
File file2 = new File("file7");
File file3 = new File("file8");
File file4 = new File("file9");
File[] dirs = { file1, file2, file3, file4 };
int[] ints = { 1, 2, 3, 4 };
DiskStoreFactory dsf = cache.createDiskStoreFactory();
try {
dsf.setDiskDirsAndSizes(dirs, ints);
fail("expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
}
int[] ints1 = { 1, 2, 3 };
file1.mkdir();
file2.mkdir();
file3.mkdir();
file4.mkdir();
file1.deleteOnExit();
file2.deleteOnExit();
file3.deleteOnExit();
file4.deleteOnExit();
try {
dsf.setDiskDirsAndSizes(dirs, ints1);
fail("expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
}
dsf.setDiskDirsAndSizes(dirs, ints);
}
public void testQueueSize()
{
DiskStoreFactory dsf = cache.createDiskStoreFactory();
try {
dsf.setQueueSize(-1);
fail("expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
}
dsf.setQueueSize(1);
assertEquals(1, dsf.create("test").getQueueSize(), 1);
}
public void testTimeInterval()
{
DiskStoreFactory dsf = cache.createDiskStoreFactory();
try {
dsf.setTimeInterval(-1);
fail("expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
}
dsf.setTimeInterval(1);
assertEquals(dsf.create("test").getTimeInterval(), 1);
}
}
| 26.258772 | 78 | 0.675129 |
de2fd096c3d9c9c4a69eff847f82c088e06141e5 | 1,168 | package net.thucydides.core.util;
import java.util.List;
import java.util.Properties;
/**
* Return system environment variable values.
*/
public interface EnvironmentVariables {
String getValue(final String name);
String getValue(final Enum<?> property);
String getValue(final String name, final String defaultValue);
String getValue(Enum<?> property, String defaultValue);
Integer getPropertyAsInteger(final String name, final Integer defaultValue);
Integer getPropertyAsInteger(final Enum<?> property, final Integer defaultValue);
Boolean getPropertyAsBoolean(final String name, boolean defaultValue);
Boolean getPropertyAsBoolean(final Enum<?> property, boolean defaultValue);
String getProperty(final String name);
String getProperty(final Enum<?> property);
String getProperty(final String name, final String defaultValue);
String getProperty(final Enum<?> property, final String defaultValue);
void setProperty(final String name, final String value);
void clearProperty(final String name);
EnvironmentVariables copy();
List<String> getKeys();
Properties getProperties();
}
| 25.955556 | 85 | 0.75 |
b336e999d553abbb0cfab9d28a9cd6e6ce9e4884 | 3,773 | /*
* Copyright 2021 Stefan9110
*
* 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.github.stefan9110.dcm.command;
import com.github.stefan9110.dcm.manager.executor.Executor;
import org.jetbrains.annotations.NotNull;
import java.util.List;
/**
* Later in this block we will refer to the instances of the interface as `command registered through the interface`
* representing any descendant class / variable instance that uses the class to store data.
*/
public interface Command {
/**
* Method used to obtain the name of the command registered through the interface.
* Commands shall have a String unique identifier, stored lowercase and not null.
*
* @return The name of the command registered through the interface
*/
@NotNull
String getName();
/**
* Method used to obtain the aliases of a command registered through the interface.
* Aliases should respect the same rules Command#getName() String presents.
* Aliases shall be stored in lowercase form and be unique to the given Command as well as other commands.
* In case there are no aliases this method shall return an empty List.
*
* @return List of Strings representing the aliases the command registered through the interface presents.
*/
List<String> getAliases();
/**
* Method used to obtain the description of the command registered through the interface.
* The description String has no restrictions in formation, but shall respect the SlashCommand description registration rules.
*
* @return The description of the command registered through the interface.
*/
String getDescription();
/**
* Method used to obtain the usage of the command registered through the interface.
* No limitations sets to the formation / length of the String.
* To be noted: the String may be used in embed forms so proper indentation for embeds is required.
* Example of command usage: "at!test [requiredArgument] <optionalArgument>.
*
* @return Useful information about the usage of the command registered through the interface.
*/
String getUsage();
/**
* The Executor interface is the key feature of the command registered through the interface.
* The interface value returned by the method contains the executor command which is used to execute the command when called.
* See Executor documentation for further information.
*
* @return Executor interface, including methods used for the proper execution of the command registered through the interface when called.
*/
@NotNull
Executor getExecutor();
/**
* The method is used to obtain the arguments of the command registered through the interface.
* The value returned is used in the ShlashCommand registration of the command.
* The values stored in the List shall respect the JDA implementations of the CommandArgument class.
* In the case of a command not containing any predefined arguments the method shall return an empty List.
*
* @return List of CommandArgument used for the SlashCommand identification of the command registered through the interface.
*/
List<CommandArgument> getArguments();
}
| 42.875 | 143 | 0.730188 |
c2f09c735e15d3aaf554c74ba097dfef403f7e74 | 128 | package com.baeldung.components;
import org.springframework.stereotype.Component;
@Component
public class AccountService {
}
| 14.222222 | 48 | 0.820313 |
6ba35d038cec781a3ab064bc4ec0bc7f6ff6b163 | 1,848 | package havis.util.core.common.rmi;
import havis.util.core.rmi.LogRemote;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
/**
* Server for logging remotely
*/
public class LogRemoteServer implements LogRemote {
public final static String NAME = "LogServer";
private Registry registry;
/**
* Creates a new log remote server
*
* @param registry
* the registry to bind to
* @throws RemoteException
* if binding fails
*/
public LogRemoteServer(Registry registry) throws RemoteException {
super();
if (registry == null) {
throw new NullPointerException("registry must not be null");
}
this.registry = registry;
this.registry.rebind(NAME, UnicastRemoteObject.exportObject(this, 0));
}
@Override
public void log(LogRecord record) throws RemoteException {
Logger.getLogger(record.getLoggerName() != null ? record.getLoggerName() : "").log(record);
}
@Override
public Map<String, Level> getLevels() throws RemoteException {
Map<String, Level> levels = new LinkedHashMap<>();
LogManager logManager = LogManager.getLogManager();
Enumeration<String> names = logManager.getLoggerNames();
while (names.hasMoreElements()) {
Logger logger = logManager.getLogger(names.nextElement());
if (logger != null && logger.getLevel() != null) {
levels.put(logger.getName(), logger.getLevel());
}
}
return levels;
}
public void dispose() {
try {
this.registry.unbind(NAME);
} catch (RemoteException | NotBoundException e) {
// ignore
}
}
}
| 26.4 | 93 | 0.722403 |
f5ee5e6735f5eaeb8e2cbe451436018badea1d45 | 6,499 | /**
* Copyright (C) 2002-2014 Fabrizio Giustina, the Displaytag team
*
* 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 org.displaytag.properties;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.lang3.builder.HashCodeBuilder;
/**
* Enumeration for media types.
* @author Fabrizio Giustina
* @version $Revision$ ($Author$)
*/
public final class MediaTypeEnum
{
/**
* Array containing all the export types.
*/
private static final List<MediaTypeEnum> ALL = new ArrayList<MediaTypeEnum>();
/**
* media type HTML = 0.
*/
public static final MediaTypeEnum HTML = new MediaTypeEnum(0, "html"); //$NON-NLS-1$
/**
* Media type CSV = 1.
*/
public static final MediaTypeEnum CSV = new MediaTypeEnum(1, "csv"); //$NON-NLS-1$
/**
* media type EXCEL = 2.
*/
public static final MediaTypeEnum EXCEL = new MediaTypeEnum(2, "excel"); //$NON-NLS-1$
/**
* media type XML = 3.
*/
public static final MediaTypeEnum XML = new MediaTypeEnum(3, "xml"); //$NON-NLS-1$
/**
* media type XML = 3.
*/
public static final MediaTypeEnum PDF = new MediaTypeEnum(4, "pdf"); //$NON-NLS-1$
/**
* Code; this is the primary key for these objects.
*/
private final int enumCode;
/**
* description.
*/
private final String enumName;
/**
* private constructor. Use only constants.
* @param code int code
* @param name description of media type
*/
private MediaTypeEnum(int code, String name)
{
this.enumCode = code;
this.enumName = name;
ALL.add(this);
}
/**
* returns the int code.
* @return int code
*/
public int getCode()
{
return this.enumCode;
}
/**
* returns the description.
* @return String description of the media type ("excel", "xml", "csv", "html", "pdf")
*/
public String getName()
{
return this.enumName;
}
/**
* lookup a media type by key.
* @param key int code
* @return MediaTypeEnum or null if no mediaType is found with the given key
*/
public static MediaTypeEnum fromCode(int key)
{
// @todo optimization needed
for (int i = 0; i < ALL.size(); i++)
{
if (key == ALL.get(i).getCode())
{
return ALL.get(i);
}
}
// lookup failed
return null;
}
/**
* lookup a media type by an Integer key.
* @param key Integer code - null safe: a null key returns a null Enum
* @return MediaTypeEnum or null if no mediaType is found with the given key
*/
public static MediaTypeEnum fromCode(Integer key)
{
if (key == null)
{
return null;
}
return fromCode(key.intValue());
}
/**
* lookup a media type by an Integer key.
* @param key Integer code - null safe: a null key returns a null Enum
* @return MediaTypeEnum or null if no mediaType is found with the given key
* @deprecated use fromCode(Integer)
*/
@Deprecated
public static MediaTypeEnum fromIntegerCode(Integer key)
{
return fromCode(key);
}
/**
* Lookup a media type by a String key.
* @param code String code - null safe: a null key returns a null Enum
* @return MediaTypeEnum or null if no mediaType is found with the given key
*/
public static MediaTypeEnum fromName(String code)
{
// @todo optimization needed
for (int i = 0; i < ALL.size(); i++)
{
if (ALL.get(i).getName().equals(code))
{
return ALL.get(i);
}
}
// lookup failed
return null;
}
/**
* returns an iterator on all the media type.
* @return iterator
*/
public static Iterator<MediaTypeEnum> iterator()
{
return ALL.iterator();
}
/**
* Register a new MediaType. If <code>name</code> is already assigned the existing instance is returned, otherwise
* a new instance is created.
* @param name media name
* @return assigned MediaTypeEnum instance
*/
public static synchronized MediaTypeEnum registerMediaType(String name)
{
MediaTypeEnum existing = fromName(name);
if (existing == null)
{
existing = new MediaTypeEnum(ALL.size() + 1, name);
}
return existing;
}
/**
* Returns the number of media type currently loaded.
* @return number of media types loaded
*/
public static int getSize()
{
return ALL.size();
}
/**
* returns the media type description.
* @see java.lang.Object#toString()
*/
@Override
public String toString()
{
return getName();
}
/**
* Only a single instance of a specific MediaTypeEnum can be created, so we can check using ==.
* @param o the object to compare to
* @return hashCode
*/
@Override
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
return false;
}
/**
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode()
{
return new HashCodeBuilder(1188997057, -1289297553).append(this.enumCode).toHashCode();
}
} | 26.744856 | 118 | 0.60517 |
522843b35d99aecbf1251426b1b77bb2fcb07447 | 1,425 | /*
* Copyright (C) 2020 Alibaba Group Holding Limited
*/
package com.alibaba.sdk.android.vod.upload.exception;
/**
* CVS定义的错误代码。
*/
public class VODErrorCode {
/**
* 参数格式错误。
*/
public static final String INVALID_ARGUMENT = "InvalidArgument";
/**
* 缺少必须参数。
*/
public static final String MISSING_ARGUMENT = "MissingArgument";
/**
* 文件已经存在。
*/
public static final String FILE_ALREADY_EXIST = "FileAlreadyExist";
/**
* 文件不存在。
*/
public static final String FILE_NOT_EXIST = "FileNotExist";
/**
* 文件已经取消。
*/
public static final String FILE_ALREADY_CANCEL = "FileAlreadyCancel";
/**
* 上传没有过期。
*/
public static final String UPLOAD_NOT_EXPIRE = "UploadNotExpire";
/**
* 上传还未开始。
*/
public static final String UPLOAD_NOT_START = "UploadNotStart";
/**
* 上传步骤错误
*/
public static final String UPLOAD_STEP_NOT_IDLE = "Step Not Idle";
/**
* 上传状态错误
*/
public static final String UPLOAD_STATUS_RRROR = "Upload Status Error";
/**
* 上传Token过期
*/
public static final String UPLOAD_EXPIRED = "UploadTokenExpired";
/**
* SecurityTokenExpired
*/
public static final String SECURITY_TOKEN_EXPIRED = "SecurityTokenExpired";
/**
* Permission Denied
*/
public static final String PERMISSION_DENIED = "PermissionDenied";
}
| 20.955882 | 79 | 0.621754 |
ad1beae528b72dc338c39ad365a6180458e06a9e | 325 | package com.kucoin.sdk.websocket.event;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.math.BigDecimal;
@EqualsAndHashCode(callSuper = true)
@Data
public class StopOrderEvent extends AdvancedOrderEvent {
private String stop;
private BigDecimal stopPrice;
private Boolean triggerSuccess;
}
| 18.055556 | 56 | 0.790769 |
f1463c28cbcd8148f61519665e24b74024a8a0b8 | 506 | package com.ws.ogre.v2.utils;
import com.beust.jcommander.IParameterValidator;
import com.beust.jcommander.ParameterException;
public class FromToValidator implements IParameterValidator {
public void validate(String theName, String theValue) throws ParameterException {
if (!theValue.matches("[0-9]{4}-[0-1][0-9]-[0-3][0-9]:[0-2][0-9]")) {
throw new ParameterException("Parameter " + theName + " should be on format 'yyyy-MM-dd:HH'. (found " + theValue + ")");
}
}
} | 38.923077 | 132 | 0.681818 |
dcaea612824ee599f4459bac9d2109a9238abbc8 | 3,748 |
package com.esri.soap;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for TableEditResult complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* &lt;complexType name="TableEditResult"&gt;
* &lt;complexContent&gt;
* &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt;
* &lt;sequence&gt;
* &lt;element name="AddResults" type="{http://www.esri.com/schemas/ArcGIS/10.7}ArrayOfEditResult"/&gt;
* &lt;element name="DeleteResults" type="{http://www.esri.com/schemas/ArcGIS/10.7}ArrayOfEditResult"/&gt;
* &lt;element name="LayerOrTableID" type="{http://www.w3.org/2001/XMLSchema}int"/&gt;
* &lt;element name="UpdateResults" type="{http://www.esri.com/schemas/ArcGIS/10.7}ArrayOfEditResult"/&gt;
* &lt;/sequence&gt;
* &lt;/restriction&gt;
* &lt;/complexContent&gt;
* &lt;/complexType&gt;
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "TableEditResult", propOrder = {
"addResults",
"deleteResults",
"layerOrTableID",
"updateResults"
})
public class TableEditResult {
@XmlElement(name = "AddResults", required = true)
protected ArrayOfEditResult addResults;
@XmlElement(name = "DeleteResults", required = true)
protected ArrayOfEditResult deleteResults;
@XmlElement(name = "LayerOrTableID")
protected int layerOrTableID;
@XmlElement(name = "UpdateResults", required = true)
protected ArrayOfEditResult updateResults;
/**
* Gets the value of the addResults property.
*
* @return
* possible object is
* {@link ArrayOfEditResult }
*
*/
public ArrayOfEditResult getAddResults() {
return addResults;
}
/**
* Sets the value of the addResults property.
*
* @param value
* allowed object is
* {@link ArrayOfEditResult }
*
*/
public void setAddResults(ArrayOfEditResult value) {
this.addResults = value;
}
/**
* Gets the value of the deleteResults property.
*
* @return
* possible object is
* {@link ArrayOfEditResult }
*
*/
public ArrayOfEditResult getDeleteResults() {
return deleteResults;
}
/**
* Sets the value of the deleteResults property.
*
* @param value
* allowed object is
* {@link ArrayOfEditResult }
*
*/
public void setDeleteResults(ArrayOfEditResult value) {
this.deleteResults = value;
}
/**
* Gets the value of the layerOrTableID property.
*
*/
public int getLayerOrTableID() {
return layerOrTableID;
}
/**
* Sets the value of the layerOrTableID property.
*
*/
public void setLayerOrTableID(int value) {
this.layerOrTableID = value;
}
/**
* Gets the value of the updateResults property.
*
* @return
* possible object is
* {@link ArrayOfEditResult }
*
*/
public ArrayOfEditResult getUpdateResults() {
return updateResults;
}
/**
* Sets the value of the updateResults property.
*
* @param value
* allowed object is
* {@link ArrayOfEditResult }
*
*/
public void setUpdateResults(ArrayOfEditResult value) {
this.updateResults = value;
}
}
| 26.964029 | 122 | 0.620331 |
a596616e611caa6d07bce81d1f578efc5fb0ec40 | 3,652 | /*
* Copyright © 2013-2020, The SeedStack authors <http://seedstack.org>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package org.seedstack.seed.core.internal.command;
import static org.seedstack.shed.reflect.ReflectUtils.makeAccessible;
import io.nuun.kernel.api.plugin.InitState;
import io.nuun.kernel.api.plugin.context.InitContext;
import io.nuun.kernel.api.plugin.request.ClasspathScanRequest;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.seedstack.seed.command.Argument;
import org.seedstack.seed.command.Command;
import org.seedstack.seed.command.Option;
import org.seedstack.seed.core.internal.AbstractSeedPlugin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Nuun plugin in charge of collecting all commands definitions.
*/
public class CommandPlugin extends AbstractSeedPlugin {
private static final Logger LOGGER = LoggerFactory.getLogger(CommandPlugin.class);
private final Map<String, CommandDefinition> commandDefinitions = new HashMap<>();
@Override
public String name() {
return "command";
}
@Override
public InitState initialize(InitContext initContext) {
Map<Class<? extends Annotation>, Collection<Class<?>>> scannedClassesByAnnotationClass = initContext
.scannedClassesByAnnotationClass();
Collection<Class<?>> commandAnnotatedClasses = scannedClassesByAnnotationClass.get(
org.seedstack.seed.command.CommandDefinition.class);
for (Class<?> candidate : commandAnnotatedClasses) {
if (Command.class.isAssignableFrom(candidate)) {
org.seedstack.seed.command.CommandDefinition commandDefinitionAnnotation = candidate.getAnnotation(
org.seedstack.seed.command.CommandDefinition.class);
if (commandDefinitionAnnotation != null) {
CommandDefinition commandDefinition = new CommandDefinition(commandDefinitionAnnotation,
candidate.asSubclass(Command.class));
for (Field field : candidate.getDeclaredFields()) {
Argument argumentAnnotation = field.getAnnotation(Argument.class);
Option optionAnnotation = field.getAnnotation(Option.class);
makeAccessible(field);
if (argumentAnnotation != null) {
commandDefinition.addArgumentField(argumentAnnotation, field);
} else if (optionAnnotation != null) {
commandDefinition.addOptionField(optionAnnotation, field);
}
}
commandDefinitions.put(commandDefinition.getQualifiedName(), commandDefinition);
LOGGER.debug("Command {} detected, implemented in {}", commandDefinition.getQualifiedName(),
commandDefinition.getCommandActionClass().getCanonicalName());
}
}
}
return InitState.INITIALIZED;
}
@Override
public Collection<ClasspathScanRequest> classpathScanRequests() {
return classpathScanRequestBuilder().annotationType(org.seedstack.seed.command.CommandDefinition.class).build();
}
@Override
public Object nativeUnitModule() {
return new CommandModule(commandDefinitions);
}
}
| 41.5 | 120 | 0.675246 |
e96a8f04655ac1fab8cf79eb5065c167f997f0fb | 1,017 | package com.fr.swift.cube.nio.write;
import com.fr.swift.cube.nio.NIOConstant;
import java.io.File;
import java.nio.LongBuffer;
public class LongNIOWriter extends AbstractNIOWriter<Long> {
private LongBuffer longBuffer;
public LongNIOWriter(File cacheFile) {
super(cacheFile);
}
public LongNIOWriter(String path) {
super(new File(path));
}
@Override
public long getPageStep() {
return NIOConstant.LONG.PAGE_STEP;
}
@Override
protected void initChild() {
longBuffer = buffer.asLongBuffer();
}
@Override
protected void releaseChild() {
if (longBuffer != null) {
longBuffer.clear();
longBuffer = null;
}
}
@Override
protected void addValue(int row, Long value) {
longBuffer.put(row, value == null ? NIOConstant.LONG.NULL_VALUE : value);
}
@Override
protected long getPageModeValue() {
return NIOConstant.LONG.PAGE_MODE_TO_AND_WRITE_VALUE;
}
} | 22.108696 | 81 | 0.641101 |
23b07044357f18aa4a3f9f32231c0b24656d335c | 10,109 | /**
* <ul>
* Android Tutorial, An <strong>Android2EE</strong>'s project.</br>
* Produced by <strong>Dr. Mathias SEGUY</strong> with the smart contribution of <strong>Julien PAPUT</strong>.</br>
* Delivered by <strong>http://android2ee.com/</strong></br>
* Belongs to <strong>Mathias Seguy</strong></br>
* ****************************************************************************************************************</br>
* This code is free for any usage but can't be distribute.</br>
* The distribution is reserved to the site <strong>http://android2ee.com</strong>.</br>
* The intelectual property belongs to <strong>Mathias Seguy</strong>.</br>
* <em>http://mathias-seguy.developpez.com/</em></br>
* </br>
* For any information (Advice, Expertise, J2EE or Android Training, Rates, Business):</br>
* <em>mathias.seguy.it@gmail.com</em></br>
* *****************************************************************************************************************</br>
* Ce code est libre de toute utilisation mais n'est pas distribuable.</br>
* Sa distribution est reservée au site <strong>http://android2ee.com</strong>.</br>
* Sa propriété intellectuelle appartient à <strong>Mathias Séguy</strong>.</br>
* <em>http://mathias-seguy.developpez.com/</em></br>
* </br>
* Pour tous renseignements (Conseil, Expertise, Formations J2EE ou Android, Prestations, Forfaits):</br>
* <em>mathias.seguy.it@gmail.com</em></br>
* *****************************************************************************************************************</br>
* Merci à vous d'avoir confiance en Android2EE les Ebooks de programmation Android.
* N'hésitez pas à nous suivre sur twitter: http://fr.twitter.com/#!/android2ee
* N'hésitez pas à suivre le blog Android2ee sur Developpez.com : http://blog.developpez.com/android2ee-mathias-seguy/
* *****************************************************************************************************************</br>
* com.android2ee.android.tuto</br>
* 25 mars 2011</br>
*/
package com.android2ee.android.tuto.chronometre;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Chronometer;
/**
* @author (Julien PAPUT sous la direction du Dr. Mathias Séguy)
* @goals This class aims to:
* <ul>
* <li>This class use a chronometer</li>
* </ul>
*/
public class ChronoTuto extends Activity {
/**
* The DeltaStopped String, witch permit to store the delta time
*/
private static final String DELTA_STOPPED = "deltaStopped";
/**
* The IsRunning String, witch permit to store the IsRunning Boolean
*/
private static final String IS_RUNNING = "isRunning";
/**
* The IsRunning String, witch permit to store the IsRunning Boolean
*/
private static final String IS_BACK_TO_DEATH = "isActivityDestroyed";
/**
* The baseTime witch permit to store the basetime of the chronometer
*/
private static final String BASE_TIME = "baseTime";
/**
* tag for the log
*/
private static final String tag = "ChronoTuto";
/******************************************************************************************/
/** Attributes **************************************************************************/
/******************************************************************************************/
/** The Chronometer Widget */
Chronometer chronometer;
/** This attribute store the */
long baseTime = 0;
/**
* set the pausing boolean to "false"
**/
boolean pausing = false;
/**
* Init the deltapaused to 0
*/
long deltaPaused = 0;
/**
* THe IsRunning Boolean
*/
boolean isRunning = false;
/**
* To know if the activity is recreated
*/
boolean activityRecreation = false;
/******************************************************************************************/
/** Define the Handler ********************************************************************/
/******************************************************************************************/
/**
* Define the Handler
*/
Handler handler = null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
Log.v(tag, "onCreate called");
super.onCreate(savedInstanceState);
if (null != savedInstanceState) {
activityRecreation = true;
}
setContentView(R.layout.main);
// initiate the chronometer
chronometer = (Chronometer) findViewById(R.id.chronometer);
chronometer.stop();
baseTime = SystemClock.elapsedRealtime();
chronometer.setText(makeDisplayableTime(baseTime));
/*
*
*
*
* /****************************************************************************************
*/
/** Adding listeners *********************************************************************/
/*****************************************************************************************/
// listener on the start button
Button btnStart = (Button) findViewById(R.id.btnStart);
btnStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startChrono();
}
});
// listener on the stop button
Button btnStop = (Button) findViewById(R.id.btnPause);
btnStop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
pauseChrono();
}
});
// listener on the reset button
Button btnReset = (Button) findViewById(R.id.btnReset);
btnReset.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
resetChrono();
}
});
// tickchronometerListener
chronometer.setOnChronometerTickListener(new Chronometer.OnChronometerTickListener() {
/**
* onChronometerTick() //On each chronometer tick
*/
@Override
public void onChronometerTick(Chronometer chronometer) {
// display the time into the chronometer
chronometer.setText(makeDisplayableTime(SystemClock.elapsedRealtime()));
}
});
}
/******************************************************************************************/
/** Managing Chrono Actions (stop, pause, resume) **************************************************************************/
/******************************************************************************************/
/**
* startChrono() //start chronometer
*/
public void startChrono() {
// set running ti true
isRunning = true;
// if pausing is false, set the chronometer basetime to the elapsed real time
if (!pausing) {
baseTime = SystemClock.elapsedRealtime();
} else {
// else set the chronometer basetime to the moment where you push the pause button
deltaPaused = SystemClock.elapsedRealtime() - deltaPaused;
baseTime = baseTime + deltaPaused;
}
// set pausing to false
pausing = false;
// start the chronometer
chronometer.start();
}
/**
* stopChrono() //stop chronometer
*/
public void pauseChrono() {
// stop the chronometer
chronometer.stop();
// if isRunning boolean is true
if (isRunning) {
// save the elapsedtime
deltaPaused = SystemClock.elapsedRealtime();
}
// set pausing to true, and running to false
pausing = true;
isRunning = false;
}
/**
* resetChrono() //reset chronometer
*/
public void resetChrono() {
// if pausing is fasle, set the chronometer's basetime to the elapsed real time
if (!pausing) {
baseTime = SystemClock.elapsedRealtime();
} else {
pausing = false;
}
// display time
chronometer.setText(makeDisplayableTime(baseTime));
}
/**
* MakeDisplayableTime
*
* @return The String time
*/
public String makeDisplayableTime(long SystemClockElapsedRealtime) {
long minutes = ((SystemClockElapsedRealtime - baseTime) / 1000) / 60;
long seconds = ((SystemClockElapsedRealtime - baseTime) / 1000) % 60;
StringBuilder currentTimeStrB = new StringBuilder(minutes < 10 ? "0" + minutes : String.valueOf(minutes));
currentTimeStrB.append(":");
currentTimeStrB.append(seconds < 10 ? "0" + seconds : String.valueOf(seconds));
return currentTimeStrB.toString();
}
/******************************************************************************************/
/** Managing LifeCycle **************************************************************************/
/******************************************************************************************/
/*
* (non-Javadoc)
*
* @see android.app.Activity#onResume()
*/
@Override
protected void onResume() {
Log.v(tag, "onResume called, isRunning " + isRunning + " pausing " + pausing + " activityBackToPause "
+ activityRecreation);
// here is the method where you need to intialize your variable again
super.onResume();
if (isRunning) {
if (activityRecreation) {
// if isRunning is true and the activity is recreate, start the chronometer
startChrono();
}
} else {
// init the chronometers value
baseTime = SystemClock.elapsedRealtime();
chronometer.setText(makeDisplayableTime(baseTime));
}
// Set the recreation mode to false (the activity is running now)
activityRecreation = false;
}
@Override
protected void onPause() {
super.onPause();
chronometer.stop();
isRunning=false;
}
@Override
protected void onSaveInstanceState(Bundle outState) {
Log.v(tag, "onSaveInstanceState called");
// Save instance some state
outState.putLong(BASE_TIME, baseTime);
outState.putBoolean(IS_RUNNING, isRunning);
deltaPaused = SystemClock.elapsedRealtime();
outState.putLong(DELTA_STOPPED, deltaPaused);
super.onSaveInstanceState(outState);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
Log.v(tag, "onRestoreInstanceState called");
// restore instance some state
super.onRestoreInstanceState(savedInstanceState);
pausing = true;
baseTime = savedInstanceState.getLong(BASE_TIME);
deltaPaused = savedInstanceState.getLong(DELTA_STOPPED);
isRunning = savedInstanceState.getBoolean(IS_RUNNING);
}
} | 34.619863 | 126 | 0.579879 |
ccd97f82e9b4b9cd875b6cbc226fd56ca2081680 | 3,308 | /*
* Copyright (c) 2021, 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.
*
* 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.
*/
/* @test
* @bug 8265079
* @run testng/othervm -Xverify:all TestVHInvokerCaching
*/
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import static java.lang.invoke.MethodHandles.lookup;
import static org.testng.Assert.assertSame;
public class TestVHInvokerCaching {
@Test(dataProvider = "testHandles")
public static void testVHIInvokerCaching(VarHandle testHandle) throws Throwable {
for (VarHandle.AccessMode mode : VarHandle.AccessMode.values()) {
MethodHandle handle1 = MethodHandles.varHandleInvoker(mode, testHandle.accessModeType(mode));
MethodHandle handle2 = MethodHandles.varHandleInvoker(mode, testHandle.accessModeType(mode));
assertSame(handle1, handle2);
}
for (VarHandle.AccessMode mode : VarHandle.AccessMode.values()) {
MethodHandle handle1 = MethodHandles.varHandleExactInvoker(mode, testHandle.accessModeType(mode));
MethodHandle handle2 = MethodHandles.varHandleExactInvoker(mode, testHandle.accessModeType(mode));
assertSame(handle1, handle2);
}
}
@DataProvider
public static Object[][] testHandles() throws NoSuchFieldException, IllegalAccessException {
List<VarHandle> testHandles = new ArrayList<>();
class Holder {
byte f_byte;
short f_short;
char f_char;
int f_int;
long f_long;
float f_float;
double f_double;
Object f_Object;
String f_String;
}
MethodHandles.Lookup lookup = lookup();
for (Field field : Holder.class.getFields()) {
String fieldName = field.getName();
Class<?> fieldType = field.getType();
testHandles.add(MethodHandles.arrayElementVarHandle(fieldType.arrayType()));
testHandles.add(lookup.findVarHandle(Holder.class, fieldName, fieldType));
}
return testHandles.stream().map(vh -> new Object[]{ vh }).toArray(Object[][]::new);
}
}
| 37.168539 | 110 | 0.6974 |
baf0065dc48e65344fd48bd390559c492c3e2031 | 3,314 | package fr.philippedeoliveira.dao.impl;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Repository;
import fr.philippedeoliveira.beans.Bet;
import fr.philippedeoliveira.beans.NbBettersByGame;
import fr.philippedeoliveira.beans.NbExactScoreByGame;
import fr.philippedeoliveira.beans.NbGoodResultByGame;
import fr.philippedeoliveira.beans.NumberOfPeople;
import fr.philippedeoliveira.beans.PointLogin;
import fr.philippedeoliveira.dao.IBetDAO;
/**
* DAO for Bet bean using Hibernate
*
* @author waddle
*
*/
@Repository
public class HibernateBetDAO extends GenericHibernateDAO<Bet, Integer> implements IBetDAO {
public HibernateBetDAO() {
super(Bet.class);
}
@Override
public List<Bet> getBetsByPlayer(String login) {
return getCurrentSession().getNamedQuery("bet.getBetsByPlayer").setParameter("login", login).list();
}
@Override
public List<PointLogin> getExactScoreBets() {
return getCurrentSession().getNamedQuery("bet.getExactScoreBets").list();
}
@Override
public List<PointLogin> getWinningBets() {
return getCurrentSession().getNamedQuery("bet.getWinningBets").list();
}
@Override
public Integer getNumberOfBetsByPlayerOnPlayedGames(String login) {
return ((Long) getCurrentSession().getNamedQuery("bet.getNumberOfBetsByPlayerOnPlayedGames")
.setParameter("login", login).uniqueResult()).intValue();
}
@Override
public List<Integer> getBonifiedGames() {
List<Integer> bonifiedGamesId = new ArrayList<>();
List<NbBettersByGame> nbBettersByGame = getNbBettersByGame();
List<NbExactScoreByGame> nbExactScoreByGame = getNbExactScoreByGame();
for (NbBettersByGame nbBetter : nbBettersByGame) {
for (NbExactScoreByGame nbExactScore : nbExactScoreByGame) {
if (nbBetter.getGameId().equals(nbExactScore.getGameId())) {
if (nbExactScore.getNbExactScore() != 0
&& nbExactScore.getNbExactScore().floatValue() / nbBetter.getNbBetters().floatValue() < 0.1f) {
bonifiedGamesId.add(nbBetter.getGameId());
}
}
}
}
return bonifiedGamesId;
}
@Override
public List<NumberOfPeople> getNumberOfPeopleThatBetSameResult(String userLogin) {
return getCurrentSession().getNamedQuery("bet.getNumberOfPeopleThatBetSameResult")
.setParameter("login", userLogin).list();
}
@Override
public List<NumberOfPeople> getNumberOfPeopleThatBetSameScore(String userLogin) {
return getCurrentSession().getNamedQuery("bet.getNumberOfPeopleThatBetSameScore")
.setParameter("login", userLogin).list();
}
@Override
public List<NbBettersByGame> getNbBettersByGame() {
return getCurrentSession().getNamedQuery("bet.getNbBettersByGame").list();
}
@Override
public List<NbExactScoreByGame> getNbExactScoreByGame() {
return getCurrentSession().getNamedQuery("bet.nbExactScoreByGame").list();
}
@Override
public List<NbGoodResultByGame> getNbGoodResultByGame() {
return getCurrentSession().getNamedQuery("bet.nbGoodResultByGame").list();
}
}
| 34.520833 | 123 | 0.694327 |
8ec19d94866da08127a187c85a799596577cd1d8 | 2,285 | /*
SPDX-FileCopyrightText: (C)2021 SAP SE or an affiliate company and aas-transformation-library contributors. All rights reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.sap.dsc.aas.lib.mapping.model;
import io.adminshell.aas.v3.model.KeyElements;
import io.adminshell.aas.v3.model.KeyType;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.sap.dsc.aas.lib.config.pojo.ConfigIdGeneration;
import com.sap.dsc.aas.lib.config.pojo.ConfigReference;
/**
* Includes the legacy config attributes that may be replaced by a new template DSL in the future.
*/
public interface LegacyTemplate extends Template {
String getXPath();
@JsonProperty("from_xpath")
void setXPath(String xPath);
@JsonProperty("from_attributeName")
void setAttributeName(String attributeName);
@JsonProperty("semanticId_str")
void setSemanticIdFromString(String id);
String getIdShortXPath();
@JsonProperty("idShort_xpath")
void setIdShortXPath(String idShortXPath);
String getLangXPath();
@JsonProperty("langXPath")
void setLangXPath(String langXPath);
String getValueXPath();
@JsonProperty("valueXPath")
void setValueXPath(String valueXPath);
String getMinValueXPath();
void setMinValueXPath(String minValueXPath);
String getMaxValueXPath();
void setMaxValueXPath(String maxValueXPath);
String getMimeTypeXPath();
void setMimeTypeXPath(String mimeTypeXPath);
ConfigIdGeneration getIdGeneration();
void setIdGeneration(ConfigIdGeneration idGeneration);
KeyType getKeyType();
void setKeyType(KeyType keyType);
KeyElements getKeyElement();
void setKeyElement(KeyElements keyElement);
String getKindTypeXPath();
@JsonProperty("kindType_xpath")
void setKindTypeXPath(String kindTypeXPath);
ConfigReference getGlobalAssetIdReference();
@JsonProperty("globalAssetIdReference")
void setGlobalAssetIdReference(ConfigReference globalAssetIdReference);
void setValueId(String valueId);
/**
* Returns an (optional) Id that can be used to refer to an element of the config
*
* @return The config element's Id
*/
String getConfigElementId();
void setConfigElementId(String configElementId);
}
| 25.10989 | 130 | 0.745295 |
845e463a84f4d7d4affb59e65a0f36029cdc7e32 | 3,033 | package com.trickl.flux.publishers;
import java.time.Duration;
import java.time.Instant;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.function.Supplier;
import lombok.Builder;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Scheduler;
public class RenewableResource<T> {
private final ExpirableResource<T> expiryableResource;
/**
* Create a time limited cachable resource.
*
* @param resourceGenerator The supplier of resources.
* @param resourceRenewer Take a resource and make it usable again.
* @param expiryAccessor Determine the expiration from the resource.
* @param timeout How long to wait for a response.
* @param scheduler The flux scheduler.
* @param resourceRenewPeriodBeforeExpiry When should we renew?
*/
@Builder
public RenewableResource(
Supplier<Mono<T>> resourceGenerator,
Function<T, Mono<T>> resourceRenewer,
Function<T, Instant> expiryAccessor,
Duration timeout,
Scheduler scheduler,
Duration resourceRenewPeriodBeforeExpiry) {
expiryableResource = ExpirableResource.<T>builder()
.resourceGenerator(
resource -> generate(
resource,
resourceGenerator,
resourceRenewer,
expiryAccessor,
scheduler))
.expiryAccessor(
resource -> getRenewTime(
resource, expiryAccessor, resourceRenewPeriodBeforeExpiry))
.scheduler(scheduler)
.timeout(timeout)
.build();
}
protected Mono<T> generate(
T lastResource,
Supplier<Mono<T>> resourceGenerator,
Function<T, Mono<T>> resourceRenewer,
Function<T, Instant> expiryAccessor,
Scheduler scheduler) {
Instant now = Instant.ofEpochMilli(scheduler.now(TimeUnit.MILLISECONDS));
Instant expiry = Optional.ofNullable(lastResource)
.map(expiryAccessor)
.orElse(Instant.ofEpochMilli(0));
if (lastResource == null || now.isAfter(expiry)) {
return resourceGenerator.get();
}
return resourceRenewer.apply(lastResource);
}
protected Instant getRenewTime(
T resource,
Function<T, Instant> expiryAccessor,
Duration resourceRenewPeriodBeforeExpiry) {
return Optional.ofNullable(resource)
.map(expiryAccessor)
.map(expiry -> expiry.minus(resourceRenewPeriodBeforeExpiry))
.orElse(Instant.ofEpochMilli(0));
}
/**
* Force a new resource on the next request.
*/
public void supplyOnNextRequest() {
expiryableResource.supplyOnNextRequest();
}
/**
* Get a new resource directly from the supplier.
*
* @return A new Resource
*/
public Mono<T> getResourceWithoutCache() {
return expiryableResource.getResourceWithoutCache();
}
/**
* Get a resource, making use of a cached value if one exists.
*
* @return A session Resource
*/
public Mono<T> getResource() {
return expiryableResource.getResource();
}
}
| 29.446602 | 77 | 0.688757 |
2f675528033a159736789955765f8febc721181d | 396 | package us.chotchki.kanbanr;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.RestController;
@RestController
@EnableAutoConfiguration
public class Main {
public static void main(String[] args) throws Exception {
SpringApplication.run(Main.class, args);
}
} | 28.285714 | 70 | 0.80303 |
67ae43589ae8ced791a8f6620f71e1148a33e40f | 613 | package zh.maven.SQuartz.task;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;
import zh.maven.SQuartz.service.FirstService;
@DisallowConcurrentExecution
public class FirstTask extends QuartzJobBean {
private FirstService firstService;
@Override
protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
firstService.service();
}
public void setFirstService(FirstService firstService) {
this.firstService = firstService;
}
}
| 25.541667 | 91 | 0.835237 |
a521f3ed3e5aad05a2c01999bcf9956f18dd5638 | 13,786 | package com.Ultra_Nerd.CodeLyokoLegacy;
import com.Ultra_Nerd.CodeLyokoLegacy.Entity.MegaTankEntity;
import com.Ultra_Nerd.CodeLyokoLegacy.Util.CardinalData;
import com.Ultra_Nerd.CodeLyokoLegacy.Util.ConstantUtil;
import com.Ultra_Nerd.CodeLyokoLegacy.Util.MethodUtil;
import com.Ultra_Nerd.CodeLyokoLegacy.Util.handlers.XanaHandler;
import com.Ultra_Nerd.CodeLyokoLegacy.init.*;
import com.Ultra_Nerd.CodeLyokoLegacy.mixin.StructyreFeatureAccessor;
import com.Ultra_Nerd.CodeLyokoLegacy.world.WorldGen.Carthage.CarthageBiomeProvider;
import com.Ultra_Nerd.CodeLyokoLegacy.world.WorldGen.Carthage.CarthageGenerator;
import io.github.ladysnake.locki.DefaultInventoryNodes;
import io.github.ladysnake.locki.InventoryLock;
import io.github.ladysnake.locki.Locki;
import io.netty.buffer.Unpooled;
import net.fabricmc.api.ModInitializer;
import net.fabricmc.fabric.api.biome.v1.BiomeModifications;
import net.fabricmc.fabric.api.biome.v1.BiomeSelectors;
import net.fabricmc.fabric.api.client.itemgroup.FabricItemGroupBuilder;
import net.fabricmc.fabric.api.client.rendering.v1.ColorProviderRegistry;
import net.fabricmc.fabric.api.entity.event.v1.ServerEntityWorldChangeEvents;
import net.fabricmc.fabric.api.entity.event.v1.ServerPlayerEvents;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerEntityEvents;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerTickEvents;
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerWorldEvents;
import net.fabricmc.fabric.api.event.player.AttackBlockCallback;
import net.fabricmc.fabric.api.item.v1.FabricItemSettings;
import net.fabricmc.fabric.api.networking.v1.ServerPlayConnectionEvents;
import net.fabricmc.fabric.api.networking.v1.ServerPlayNetworking;
import net.fabricmc.fabric.api.object.builder.v1.entity.FabricDefaultAttributeRegistry;
import net.fabricmc.fabric.api.screenhandler.v1.ScreenHandlerRegistry;
import net.minecraft.client.gui.screen.ingame.HandledScreens;
import net.minecraft.entity.ItemEntity;
import net.minecraft.entity.data.DataTracker;
import net.minecraft.entity.data.TrackedData;
import net.minecraft.entity.data.TrackedDataHandlerRegistry;
import net.minecraft.item.BlockItem;
import net.minecraft.item.ItemGroup;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NbtCompound;
import net.minecraft.network.PacketByteBuf;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.stat.Stats;
import net.minecraft.text.Text;
import net.minecraft.text.TranslatableTextContent;
import net.minecraft.util.ActionResult;
import net.minecraft.util.Formatting;
import net.minecraft.util.Identifier;
import net.minecraft.util.math.ColorHelper;
import net.minecraft.util.registry.BuiltinRegistries;
import net.minecraft.util.registry.Registry;
import net.minecraft.util.registry.RegistryKey;
import net.minecraft.world.gen.GenerationStep;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.bernie.geckolib3.GeckoLib;
import team.reborn.energy.api.EnergyStorage;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
public record CodeLyokoMain() implements ModInitializer {
public static final InventoryLock LYOKO_LOCK = Locki.registerLock(CodeLyokoPrefix("lyoko_lock"));
public static final String MOD_ID = "cm";
public static final Logger LOG = LoggerFactory.getLogger(MOD_ID);
public static final ItemGroup LYOKO_ITEM = FabricItemGroupBuilder.build(new Identifier(MOD_ID,"lyoko_items"),() -> new ItemStack(ModItems.BIT));
public static final ItemGroup LYOKO_BLOCKS = FabricItemGroupBuilder.build(new Identifier(MOD_ID,"lyoko_blocks"), () -> new ItemStack(ModBlocks.TOWER_INTERFACE));
public static final ItemGroup LYOKO_ARMOR = FabricItemGroupBuilder.build(CodeLyokoPrefix("lyoko_armor"), ()->new ItemStack(ModItems.WILLIAM_CHESTPLATE));
public static final ItemGroup LYOKO_WEAPONS = FabricItemGroupBuilder.build(CodeLyokoPrefix("lyoko_weapons"),() -> new ItemStack(ModItems.LASER_ARROWSHOOTER));
public static final Identifier COMPUTER_PANEL_TAG = CodeLyokoPrefix("control_panel_tag");
@Contract("_ -> new")
public static @NotNull Identifier CodeLyokoPrefix(String name)
{
return new Identifier(MOD_ID,name);
}
public static final Identifier ChannelID = CodeLyokoMain.CodeLyokoPrefix("lyokopacket");
private static void registerEnergyStorageBE()
{EnergyStorage.SIDED.registerForBlockEntity((blockEntity, direction) -> blockEntity.simpleEnergyStorage, ModTileEntities.UNIVERSAL_ENERGY_STORAGE);
}
@Override
public void onInitialize() {
GeckoLib.initialize();
generalRegistration();
SetupFunctions();
registerDefaultAttributes();
registerEnergyStorageBE();
}
private static void generalRegistration()
{
ModBlocks.BLOCK_MAP.forEach((s, block) -> {
Registry.register(Registry.BLOCK,new Identifier(MOD_ID,s),block);
//LOG.info(String.valueOf(blocks));
if(block != ModBlocks.LYOKO_CORE && block != ModBlocks.DIGITAL_OCEAN_BLOCK && block != ModBlocks.DIGITAL_LAVA_BLOCK) {
Registry.register(Registry.ITEM, new Identifier(MOD_ID, s), new BlockItem(block, new FabricItemSettings().group(LYOKO_BLOCKS)));
}
});
ModItems.ITEM_MAP.forEach((s, item) -> Registry.register(Registry.ITEM,new Identifier(MOD_ID,s),item));
ModTileEntities.BLOCKENTITY_MAP.forEach((s, blockEntityType) -> Registry.register(Registry.BLOCK_ENTITY_TYPE,CodeLyokoPrefix(s),blockEntityType));
//ModSounds.SOUNDS.forEach(soundEvent -> Registry.register(Registry.SOUND_EVENT,soundEvent.getId(),soundEvent));
final int size = ModSounds.SOUNDS.length;
for(int i =0; i < size; i++)
{
Registry.register(Registry.SOUND_EVENT, ModSounds.SOUNDS[i].getId(),ModSounds.SOUNDS[i]);
}
ModBiome.BIOME_MAP.forEach((s, biome) -> Registry.register(BuiltinRegistries.BIOME,CodeLyokoPrefix(s),biome));
ModEntities.ENTITY_TYPE_HASH_MAP.forEach((s, entityType) -> Registry.register(Registry.ENTITY_TYPE,CodeLyokoPrefix(s),entityType));
ModFluids.FLUID_IMMUTABLE_MAP.forEach((s, fluid) ->
Registry.register(Registry.FLUID,CodeLyokoPrefix(s),fluid));
ModParticles.PARTICLE_TYPE_IMMUTABLE_MAP.forEach((s, defaultParticleType) -> Registry.register(Registry.PARTICLE_TYPE,CodeLyokoPrefix(s),defaultParticleType));
Registry.register(Registry.CHUNK_GENERATOR,CodeLyokoPrefix("carthage_chunkgen"), CarthageGenerator.CARTHAGE_GENERATOR_CODEC);
Registry.register(Registry.BIOME_SOURCE,CodeLyokoPrefix("carthage_biome"), CarthageBiomeProvider.CARTHAGE_BIOME_PROVIDER_CODEC);
ModScreenHandlers.screenHandlerMap.forEach((s, screenHandlerType) -> Registry.register(Registry.SCREEN_HANDLER,CodeLyokoPrefix(s),screenHandlerType));
ModStructures.structmap.forEach((s, structureFeature) -> StructyreFeatureAccessor.callRegister(MOD_ID + ":"+s,structureFeature, GenerationStep.Feature.SURFACE_STRUCTURES));
ModFeature.CONFIGURED_TREE_IMMUTABLE_MAP.forEach((s,feature) -> {
Registry.register(BuiltinRegistries.CONFIGURED_FEATURE,CodeLyokoPrefix(s),feature.getLeft());
Registry.register(BuiltinRegistries.PLACED_FEATURE,CodeLyokoPrefix(s),feature.getRight());
});
ModStats.RegisterStats();
BiomeFeatureInject();
ColorProviderRegistry.ITEM.register((stack, tintIndex) ->
{
return switch (stack.getTranslationKey()) {
case "item.cm.story_book" -> 0x00008B;
case "item.cm.story_book2" -> ColorHelper.Argb.getArgb(255,255,0,0);
default -> 1;
};
//return 0x00008B;
}
,ModItems.STORY_BOOK,ModItems.STORY_BOOK2);
}
private static void BiomeFeatureInject()
{
BiomeModifications.addFeature(BiomeSelectors.foundInOverworld(), GenerationStep.Feature.UNDERGROUND_ORES,RegistryKey.of(Registry.PLACED_FEATURE_KEY,CodeLyokoPrefix("coffinite_ore_overworld")));
}
private static void registerDefaultAttributes()
{
//FabricDefaultAttributeRegistry.register(ModEntities.BLOK, EntityBlok.createMonsterAttributes());
FabricDefaultAttributeRegistry.register(ModEntities.MEGATANK, MegaTankEntity.registerAttributes());
}
private static final TrackedData<NbtCompound> peristent = DataTracker.registerData(ServerPlayerEntity.class,TrackedDataHandlerRegistry.NBT_COMPOUND);
private static void SetupFunctions(){
//sets the properties for the xana handler to calcualate on
ServerWorldEvents.LOAD.register((server, world) -> XanaHandler.setProperties(world.getLevelProperties()));
//saves and loats the inventoryfor both respawn and joining
ServerPlayerEvents.AFTER_RESPAWN.register((oldPlayer, newPlayer, alive) -> {
if(MethodUtil.DimensionCheck.playerInVanilla(newPlayer)) {
CardinalData.LyokoInventorySave.loadPlayerInventory(newPlayer.server.getSaveProperties().getMainWorldProperties(),newPlayer);
}
});
ServerEntityWorldChangeEvents.AFTER_PLAYER_CHANGE_WORLD.register((player, origin, destination) -> {
if(player != null) {
if (MethodUtil.DimensionCheck.worldIsNotVanilla(destination)) {
CardinalData.LyokoInventorySave.savePlayerInventory(player.server.getSaveProperties().getMainWorldProperties(), player);
} else if (MethodUtil.DimensionCheck.worldIsNotVanilla(origin)) {
CardinalData.LyokoInventorySave.loadPlayerInventory(player.server.getSaveProperties().getMainWorldProperties(), player);
}
}
});
XanaHandler.setTicksToNextCalculation(1);
AttackBlockCallback.EVENT.register((player, world, hand, pos, direction) -> {
if(MethodUtil.DimensionCheck.playerNotInVanillaWorld(player) && !player.isCreative())
{
return ActionResult.FAIL;
}
return ActionResult.PASS;
});
//gives the player the first entry into the story
final String nbtdat = "first_join";
final AtomicReference<NbtCompound> t = new AtomicReference<>(new NbtCompound());
ServerPlayConnectionEvents.JOIN.register((handler, sender, server) -> {
handler.player.getDataTracker().startTracking(peristent,t.getAcquire());
if(!handler.player.getDataTracker().get(peristent).contains(nbtdat))
{
handler.player.getDataTracker().get(peristent).putBoolean(nbtdat,true);
handler.player.getInventory().setStack(handler.player.getInventory().getEmptySlot(),new ItemStack(ModItems.STORY_BOOK));
}
else
{
t.set(handler.player.getDataTracker().get(peristent));
}
});
final AtomicInteger tick = new AtomicInteger();
ServerTickEvents.START_WORLD_TICK.register(world -> world.getPlayers().forEach(serverPlayerEntity -> {
//tick the xana attack handler
tick.getAndIncrement();
if((tick.get() >> 3) % 5 == 0) {
if(serverPlayerEntity.getStatHandler().getStat(Stats.CUSTOM,ModStats.ENTERED_LYOKO_IDENTIFIER) > 0) {
if (XanaHandler.calculateAttackProbability()) {
final int notifyPlayerRandom = new Random().nextInt(world.getPlayers().size());
world.getPlayers().get(notifyPlayerRandom).sendMessage(Text.translatable("xana.attack.start").fillStyle(ConstantUtil.Styles.GUNSHIP.getThisStyle().withColor(Formatting.RED)), true);
}
}
}
//carry out continuous operations dependant on the dimension
if(MethodUtil.DimensionCheck.playerNotInVanillaWorld(serverPlayerEntity))
{
serverPlayerEntity.getHungerManager().setExhaustion(0);
serverPlayerEntity.getHungerManager().setSaturationLevel(5);
CodeLyokoMain.LYOKO_LOCK.lock(serverPlayerEntity, DefaultInventoryNodes.CRAFTING);
serverPlayerEntity.getAbilities().allowModifyWorld = serverPlayerEntity.isCreative();
//CodeLyokoMain.LYOKO_LOCK.lock(serverPlayerEntity, DefaultInventoryNodes.MAIN_INVENTORY);
} else if (CodeLyokoMain.LYOKO_LOCK.isLocking(serverPlayerEntity,DefaultInventoryNodes.CRAFTING) /*&& CodeLyokoMain.LYOKO_LOCK.isLocking(serverPlayerEntity,DefaultInventoryNodes.MAIN_INVENTORY)*/) {
CodeLyokoMain.LYOKO_LOCK.unlock(serverPlayerEntity,DefaultInventoryNodes.CRAFTING);
serverPlayerEntity.getAbilities().allowModifyWorld = true;
//CodeLyokoMain.LYOKO_LOCK.unlock(serverPlayerEntity,DefaultInventoryNodes.MAIN_INVENTORY);
}
}));
//stop items from being able to drop in lyoko
ServerEntityEvents.ENTITY_LOAD.register((entity, world) -> {
if(entity instanceof final ItemEntity itemEntity)
{
if(MethodUtil.DimensionCheck.worldIsNotVanilla(world))
{
itemEntity.kill();
}
}
});
//prevents the player from losing EXP
ServerPlayerEvents.COPY_FROM.register( (oldPlayer, newPlayer, alive) -> {
if(MethodUtil.DimensionCheck.playerNotInVanillaWorld(oldPlayer))
{
newPlayer.experienceLevel = oldPlayer.experienceLevel;
}
});
}
}
| 46.891156 | 210 | 0.72755 |
1ab61ad8d9a587234eb1fafe2c090583114e7767 | 1,571 | package org.iartisan.admin.template.controller.support.rest;
import org.iartisan.admin.template.service.entity.LogEntity;
import org.iartisan.admin.template.service.query.LogQueryService;
import org.iartisan.runtime.bean.PageWrapper;
import org.iartisan.runtime.bean.Pagination;
import org.iartisan.runtime.web.WebR;
import org.iartisan.runtime.web.contants.ReqContants;
import org.iartisan.runtime.web.controller.BaseController;
import org.iartisan.runtime.web.controller.ISupportRestController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* <p>
*
* @author King
* @since 2018/4/17
*/
@RestController
@RequestMapping("log")
public class LogRestController extends BaseController implements ISupportRestController<LogEntity> {
@Autowired
private LogQueryService logQueryService;
@Override
public WebR deleteData(String keyId) {
return null;
}
@Override
public WebR modifyData(LogEntity logEntity) {
return null;
}
@Override
public WebR addData(LogEntity logEntity) {
return null;
}
@PostMapping(ReqContants.REQ_QUERY_PAGE_DATA)
public WebR queryPageData(Pagination page) {
PageWrapper<LogEntity> pageData = logQueryService.getAllPageData(page);
WebR webR = new WebR(pageData.getPage());
webR.setData(pageData.getRows());
return webR;
}
}
| 29.641509 | 100 | 0.760662 |
ef1f7837a09368b8fbac55dca9bb108c69d6cb5e | 20,289 | package com.vmware.avi.vro.model;
import java.util.*;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.vmware.o11n.plugin.sdk.annotation.VsoFinder;
import com.vmware.o11n.plugin.sdk.annotation.VsoMethod;
import com.vmware.o11n.plugin.sdk.annotation.VsoObject;
import com.vmware.avi.vro.Constants;
import org.springframework.stereotype.Service;
/**
* The AuditComplianceEventInfo is a POJO class extends AviRestResource that used for creating
* AuditComplianceEventInfo.
*
* @version 1.0
* @since
*
*/
@VsoObject(create = false, name = "AuditComplianceEventInfo")
@VsoFinder(name = Constants.FINDER_VRO_AUDITCOMPLIANCEEVENTINFO)
@JsonIgnoreProperties(ignoreUnknown = true)
@Service
public class AuditComplianceEventInfo extends AviRestResource {
@JsonProperty("cluster_uuid")
@JsonInclude(Include.NON_NULL)
private String clusterUuid = null;
@JsonProperty("core_archive")
@JsonInclude(Include.NON_NULL)
private String coreArchive = null;
@JsonProperty("detailed_reason")
@JsonInclude(Include.NON_NULL)
private String detailedReason = null;
@JsonProperty("event_generated_by_se")
@JsonInclude(Include.NON_NULL)
private Boolean eventGeneratedBySe = null;
@JsonProperty("fingerprint")
@JsonInclude(Include.NON_NULL)
private String fingerprint = null;
@JsonProperty("location")
@JsonInclude(Include.NON_NULL)
private String location = null;
@JsonProperty("node")
@JsonInclude(Include.NON_NULL)
private String node = null;
@JsonProperty("patch_version")
@JsonInclude(Include.NON_NULL)
private String patchVersion = null;
@JsonProperty("process_name")
@JsonInclude(Include.NON_NULL)
private String processName = null;
@JsonProperty("protocol")
@JsonInclude(Include.NON_NULL)
private String protocol = null;
@JsonProperty("result")
@JsonInclude(Include.NON_NULL)
private String result = null;
@JsonProperty("se_uuid")
@JsonInclude(Include.NON_NULL)
private String seUuid = null;
@JsonProperty("subjects")
@JsonInclude(Include.NON_NULL)
private List<ACSubjectInfo> subjects = null;
@JsonProperty("type")
@JsonInclude(Include.NON_NULL)
private String type = null;
@JsonProperty("user_identities")
@JsonInclude(Include.NON_NULL)
private List<ACUserIdentity> userIdentities = null;
@JsonProperty("version")
@JsonInclude(Include.NON_NULL)
private String version = null;
/**
* This is the getter method this will return the attribute value.
* Cluster uuid used for controller event.
* Field introduced in 20.1.6.
* Default value when not specified in API or module is interpreted by Avi Controller as null.
* @return clusterUuid
*/
@VsoMethod
public String getClusterUuid() {
return clusterUuid;
}
/**
* This is the setter method to the attribute.
* Cluster uuid used for controller event.
* Field introduced in 20.1.6.
* Default value when not specified in API or module is interpreted by Avi Controller as null.
* @param clusterUuid set the clusterUuid.
*/
@VsoMethod
public void setClusterUuid(String clusterUuid) {
this.clusterUuid = clusterUuid;
}
/**
* This is the getter method this will return the attribute value.
* Name of core archive.
* Field introduced in 20.1.6.
* Default value when not specified in API or module is interpreted by Avi Controller as null.
* @return coreArchive
*/
@VsoMethod
public String getCoreArchive() {
return coreArchive;
}
/**
* This is the setter method to the attribute.
* Name of core archive.
* Field introduced in 20.1.6.
* Default value when not specified in API or module is interpreted by Avi Controller as null.
* @param coreArchive set the coreArchive.
*/
@VsoMethod
public void setCoreArchive(String coreArchive) {
this.coreArchive = coreArchive;
}
/**
* This is the getter method this will return the attribute value.
* Detailed report of the audit event.
* Field introduced in 20.1.3.
* Default value when not specified in API or module is interpreted by Avi Controller as null.
* @return detailedReason
*/
@VsoMethod
public String getDetailedReason() {
return detailedReason;
}
/**
* This is the setter method to the attribute.
* Detailed report of the audit event.
* Field introduced in 20.1.3.
* Default value when not specified in API or module is interpreted by Avi Controller as null.
* @param detailedReason set the detailedReason.
*/
@VsoMethod
public void setDetailedReason(String detailedReason) {
this.detailedReason = detailedReason;
}
/**
* This is the getter method this will return the attribute value.
* Set the flag if event is generated by se.
* Field introduced in 20.1.6.
* Default value when not specified in API or module is interpreted by Avi Controller as null.
* @return eventGeneratedBySe
*/
@VsoMethod
public Boolean getEventGeneratedBySe() {
return eventGeneratedBySe;
}
/**
* This is the setter method to the attribute.
* Set the flag if event is generated by se.
* Field introduced in 20.1.6.
* Default value when not specified in API or module is interpreted by Avi Controller as null.
* @param eventGeneratedBySe set the eventGeneratedBySe.
*/
@VsoMethod
public void setEventGeneratedBySe(Boolean eventGeneratedBySe) {
this.eventGeneratedBySe = eventGeneratedBySe;
}
/**
* This is the getter method this will return the attribute value.
* Fingerprint extracted from the stacktrace.
* Field introduced in 20.1.6.
* Default value when not specified in API or module is interpreted by Avi Controller as null.
* @return fingerprint
*/
@VsoMethod
public String getFingerprint() {
return fingerprint;
}
/**
* This is the setter method to the attribute.
* Fingerprint extracted from the stacktrace.
* Field introduced in 20.1.6.
* Default value when not specified in API or module is interpreted by Avi Controller as null.
* @param fingerprint set the fingerprint.
*/
@VsoMethod
public void setFingerprint(String fingerprint) {
this.fingerprint = fingerprint;
}
/**
* This is the getter method this will return the attribute value.
* Information identifying physical location for audit event (e.g.
* Santa clara (usa), bengaluru (india)).
* Field introduced in 20.1.3.
* Default value when not specified in API or module is interpreted by Avi Controller as null.
* @return location
*/
@VsoMethod
public String getLocation() {
return location;
}
/**
* This is the setter method to the attribute.
* Information identifying physical location for audit event (e.g.
* Santa clara (usa), bengaluru (india)).
* Field introduced in 20.1.3.
* Default value when not specified in API or module is interpreted by Avi Controller as null.
* @param location set the location.
*/
@VsoMethod
public void setLocation(String location) {
this.location = location;
}
/**
* This is the getter method this will return the attribute value.
* Node on which crash is generated.
* Field introduced in 20.1.4.
* Default value when not specified in API or module is interpreted by Avi Controller as null.
* @return node
*/
@VsoMethod
public String getNode() {
return node;
}
/**
* This is the setter method to the attribute.
* Node on which crash is generated.
* Field introduced in 20.1.4.
* Default value when not specified in API or module is interpreted by Avi Controller as null.
* @param node set the node.
*/
@VsoMethod
public void setNode(String node) {
this.node = node;
}
/**
* This is the getter method this will return the attribute value.
* Patch version of node.
* Field introduced in 20.1.6.
* Default value when not specified in API or module is interpreted by Avi Controller as null.
* @return patchVersion
*/
@VsoMethod
public String getPatchVersion() {
return patchVersion;
}
/**
* This is the setter method to the attribute.
* Patch version of node.
* Field introduced in 20.1.6.
* Default value when not specified in API or module is interpreted by Avi Controller as null.
* @param patchVersion set the patchVersion.
*/
@VsoMethod
public void setPatchVersion(String patchVersion) {
this.patchVersion = patchVersion;
}
/**
* This is the getter method this will return the attribute value.
* Crashed core process name.
* Field introduced in 20.1.4.
* Default value when not specified in API or module is interpreted by Avi Controller as null.
* @return processName
*/
@VsoMethod
public String getProcessName() {
return processName;
}
/**
* This is the setter method to the attribute.
* Crashed core process name.
* Field introduced in 20.1.4.
* Default value when not specified in API or module is interpreted by Avi Controller as null.
* @param processName set the processName.
*/
@VsoMethod
public void setProcessName(String processName) {
this.processName = processName;
}
/**
* This is the getter method this will return the attribute value.
* Protocol used for communication to the external entity.
* Enum options - SSH1_0, TLS1_2, HTTPS1_0, HTTP_PLAIN_TEXT, HTTPS_INSECURE, SSH2_0.
* Field introduced in 20.1.3.
* Default value when not specified in API or module is interpreted by Avi Controller as null.
* @return protocol
*/
@VsoMethod
public String getProtocol() {
return protocol;
}
/**
* This is the setter method to the attribute.
* Protocol used for communication to the external entity.
* Enum options - SSH1_0, TLS1_2, HTTPS1_0, HTTP_PLAIN_TEXT, HTTPS_INSECURE, SSH2_0.
* Field introduced in 20.1.3.
* Default value when not specified in API or module is interpreted by Avi Controller as null.
* @param protocol set the protocol.
*/
@VsoMethod
public void setProtocol(String protocol) {
this.protocol = protocol;
}
/**
* This is the getter method this will return the attribute value.
* Summarized failure of the transaction (e.g.
* Invalid request, expired certificate).
* Field introduced in 20.1.3.
* Default value when not specified in API or module is interpreted by Avi Controller as null.
* @return result
*/
@VsoMethod
public String getResult() {
return result;
}
/**
* This is the setter method to the attribute.
* Summarized failure of the transaction (e.g.
* Invalid request, expired certificate).
* Field introduced in 20.1.3.
* Default value when not specified in API or module is interpreted by Avi Controller as null.
* @param result set the result.
*/
@VsoMethod
public void setResult(String result) {
this.result = result;
}
/**
* This is the getter method this will return the attribute value.
* Service engine uuid used for service engine event.
* Field introduced in 20.1.6.
* Default value when not specified in API or module is interpreted by Avi Controller as null.
* @return seUuid
*/
@VsoMethod
public String getSeUuid() {
return seUuid;
}
/**
* This is the setter method to the attribute.
* Service engine uuid used for service engine event.
* Field introduced in 20.1.6.
* Default value when not specified in API or module is interpreted by Avi Controller as null.
* @param seUuid set the seUuid.
*/
@VsoMethod
public void setSeUuid(String seUuid) {
this.seUuid = seUuid;
}
/**
* This is the getter method this will return the attribute value.
* Subjects of audit event.
* Field introduced in 20.1.3.
* Minimum of 1 items required.
* Default value when not specified in API or module is interpreted by Avi Controller as null.
* @return subjects
*/
@VsoMethod
public List<ACSubjectInfo> getSubjects() {
return subjects;
}
/**
* This is the setter method. this will set the subjects
* Subjects of audit event.
* Field introduced in 20.1.3.
* Minimum of 1 items required.
* Default value when not specified in API or module is interpreted by Avi Controller as null.
* @return subjects
*/
@VsoMethod
public void setSubjects(List<ACSubjectInfo> subjects) {
this.subjects = subjects;
}
/**
* This is the setter method this will set the subjects
* Subjects of audit event.
* Field introduced in 20.1.3.
* Minimum of 1 items required.
* Default value when not specified in API or module is interpreted by Avi Controller as null.
* @return subjects
*/
@VsoMethod
public AuditComplianceEventInfo addSubjectsItem(ACSubjectInfo subjectsItem) {
if (this.subjects == null) {
this.subjects = new ArrayList<ACSubjectInfo>();
}
this.subjects.add(subjectsItem);
return this;
}
/**
* This is the getter method this will return the attribute value.
* Type of audit event.
* Enum options - AUDIT_INVALID_CREDENTIALS, AUDIT_NAME_RESOLUTION_ERROR, AUDIT_DIAL_X509_ERROR, AUDIT_CORE_GENERATED,
* AUDIT_SECURE_KEY_EXCHANGE_BAD_REQUEST_FORMAT, AUDIT_SECURE_KEY_EXCHANGE_BAD_CLIENT_TYPE, AUDIT_SECURE_KEY_EXCHANGE_FIELD_NOT_FOUND,
* AUDIT_SECURE_KEY_EXCHANGE_BAD_FIELD_VALUE, AUDIT_SECURE_KEY_EXCHANGE_INVALID_AUTHORIZATION, AUDIT_SECURE_KEY_EXCHANGE_INTERNAL_ERROR,
* AUDIT_SECURE_KEY_EXCHANGE_CERTIFICATE_VERIFY_ERROR, AUDIT_SECURE_KEY_EXCHANGE_RESPONSE_ERROR.
* Field introduced in 20.1.3.
* Default value when not specified in API or module is interpreted by Avi Controller as null.
* @return type
*/
@VsoMethod
public String getType() {
return type;
}
/**
* This is the setter method to the attribute.
* Type of audit event.
* Enum options - AUDIT_INVALID_CREDENTIALS, AUDIT_NAME_RESOLUTION_ERROR, AUDIT_DIAL_X509_ERROR, AUDIT_CORE_GENERATED,
* AUDIT_SECURE_KEY_EXCHANGE_BAD_REQUEST_FORMAT, AUDIT_SECURE_KEY_EXCHANGE_BAD_CLIENT_TYPE, AUDIT_SECURE_KEY_EXCHANGE_FIELD_NOT_FOUND,
* AUDIT_SECURE_KEY_EXCHANGE_BAD_FIELD_VALUE, AUDIT_SECURE_KEY_EXCHANGE_INVALID_AUTHORIZATION, AUDIT_SECURE_KEY_EXCHANGE_INTERNAL_ERROR,
* AUDIT_SECURE_KEY_EXCHANGE_CERTIFICATE_VERIFY_ERROR, AUDIT_SECURE_KEY_EXCHANGE_RESPONSE_ERROR.
* Field introduced in 20.1.3.
* Default value when not specified in API or module is interpreted by Avi Controller as null.
* @param type set the type.
*/
@VsoMethod
public void setType(String type) {
this.type = type;
}
/**
* This is the getter method this will return the attribute value.
* List of users (username etc) related to the audit event.
* Field introduced in 20.1.3.
* Minimum of 1 items required.
* Default value when not specified in API or module is interpreted by Avi Controller as null.
* @return userIdentities
*/
@VsoMethod
public List<ACUserIdentity> getUserIdentities() {
return userIdentities;
}
/**
* This is the setter method. this will set the userIdentities
* List of users (username etc) related to the audit event.
* Field introduced in 20.1.3.
* Minimum of 1 items required.
* Default value when not specified in API or module is interpreted by Avi Controller as null.
* @return userIdentities
*/
@VsoMethod
public void setUserIdentities(List<ACUserIdentity> userIdentities) {
this.userIdentities = userIdentities;
}
/**
* This is the setter method this will set the userIdentities
* List of users (username etc) related to the audit event.
* Field introduced in 20.1.3.
* Minimum of 1 items required.
* Default value when not specified in API or module is interpreted by Avi Controller as null.
* @return userIdentities
*/
@VsoMethod
public AuditComplianceEventInfo addUserIdentitiesItem(ACUserIdentity userIdentitiesItem) {
if (this.userIdentities == null) {
this.userIdentities = new ArrayList<ACUserIdentity>();
}
this.userIdentities.add(userIdentitiesItem);
return this;
}
/**
* This is the getter method this will return the attribute value.
* Version tag of node.
* Field introduced in 20.1.6.
* Default value when not specified in API or module is interpreted by Avi Controller as null.
* @return version
*/
@VsoMethod
public String getVersion() {
return version;
}
/**
* This is the setter method to the attribute.
* Version tag of node.
* Field introduced in 20.1.6.
* Default value when not specified in API or module is interpreted by Avi Controller as null.
* @param version set the version.
*/
@VsoMethod
public void setVersion(String version) {
this.version = version;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
AuditComplianceEventInfo objAuditComplianceEventInfo = (AuditComplianceEventInfo) o;
return Objects.equals(this.type, objAuditComplianceEventInfo.type)&&
Objects.equals(this.location, objAuditComplianceEventInfo.location)&&
Objects.equals(this.result, objAuditComplianceEventInfo.result)&&
Objects.equals(this.userIdentities, objAuditComplianceEventInfo.userIdentities)&&
Objects.equals(this.protocol, objAuditComplianceEventInfo.protocol)&&
Objects.equals(this.subjects, objAuditComplianceEventInfo.subjects)&&
Objects.equals(this.detailedReason, objAuditComplianceEventInfo.detailedReason)&&
Objects.equals(this.processName, objAuditComplianceEventInfo.processName)&&
Objects.equals(this.node, objAuditComplianceEventInfo.node)&&
Objects.equals(this.clusterUuid, objAuditComplianceEventInfo.clusterUuid)&&
Objects.equals(this.seUuid, objAuditComplianceEventInfo.seUuid)&&
Objects.equals(this.version, objAuditComplianceEventInfo.version)&&
Objects.equals(this.patchVersion, objAuditComplianceEventInfo.patchVersion)&&
Objects.equals(this.eventGeneratedBySe, objAuditComplianceEventInfo.eventGeneratedBySe)&&
Objects.equals(this.fingerprint, objAuditComplianceEventInfo.fingerprint)&&
Objects.equals(this.coreArchive, objAuditComplianceEventInfo.coreArchive);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class AuditComplianceEventInfo {\n");
sb.append(" clusterUuid: ").append(toIndentedString(clusterUuid)).append("\n");
sb.append(" coreArchive: ").append(toIndentedString(coreArchive)).append("\n");
sb.append(" detailedReason: ").append(toIndentedString(detailedReason)).append("\n");
sb.append(" eventGeneratedBySe: ").append(toIndentedString(eventGeneratedBySe)).append("\n");
sb.append(" fingerprint: ").append(toIndentedString(fingerprint)).append("\n");
sb.append(" location: ").append(toIndentedString(location)).append("\n");
sb.append(" node: ").append(toIndentedString(node)).append("\n");
sb.append(" patchVersion: ").append(toIndentedString(patchVersion)).append("\n");
sb.append(" processName: ").append(toIndentedString(processName)).append("\n");
sb.append(" protocol: ").append(toIndentedString(protocol)).append("\n");
sb.append(" result: ").append(toIndentedString(result)).append("\n");
sb.append(" seUuid: ").append(toIndentedString(seUuid)).append("\n");
sb.append(" subjects: ").append(toIndentedString(subjects)).append("\n");
sb.append(" type: ").append(toIndentedString(type)).append("\n");
sb.append(" userIdentities: ").append(toIndentedString(userIdentities)).append("\n");
sb.append(" version: ").append(toIndentedString(version)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
| 34.041946 | 138 | 0.716102 |
9d0a7c74eae1d2771da4a8b425ad782ca3f74953 | 3,360 | package ar.edu.itba.paw.persistence.relation;
import java.time.LocalDate;
import java.util.List;
import java.util.Optional;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Repository;
import ar.edu.itba.paw.interfaces.persistence.relation.RejectDAO;
import ar.edu.itba.paw.model.profile.User;
import ar.edu.itba.paw.model.pub.Pub;
import ar.edu.itba.paw.model.relation.Reject;
@Repository
public class RejectJPA implements RejectDAO {
@PersistenceContext
private EntityManager manager;
@Override
public Reject create(final Long senderId, final Long receiverId, final Long pubId, final LocalDate date) {
final Reject reject = new Reject.Builder()
.sender(manager.find(User.class, senderId))
.receiver(manager.find(User.class, receiverId))
.pub(manager.find(Pub.class, pubId))
.date(date)
.build();
manager.persist(reject);
manager.flush();
return reject;
}
@Override
public Optional<Reject> findById(final Long id) {
return Optional.ofNullable(manager.find(Reject.class, id));
}
public Optional<Reject> findBySenderAndReceiverAndPubAndDate(final Long senderId, final Long receiverId,
final Long pubId, final LocalDate date) {
try {
return Optional.of(manager.createQuery(
"FROM Reject AS reject " +
"WHERE reject.sender.id = :senderId " +
"AND reject.receiver.id = :receiverId " +
"AND reject.pub.id = :pubId " +
"AND reject.date = :date",
Reject.class)
.setParameter("senderId", senderId)
.setParameter("receiverId", receiverId)
.setParameter("pubId", pubId)
.setParameter("date", date)
.getSingleResult());
} catch (NoResultException exception) {
return Optional.empty();
}
}
@Override
public List<Reject> listBySenderAndPubAndDate(final Long senderId, final Long pubId, final LocalDate date) {
return manager.createQuery(
"FROM Reject AS reject " +
"WHERE reject.sender.id = :senderId " +
"AND reject.pub.id = :pubId " +
"AND date = :date",
Reject.class)
.setParameter("senderId", senderId)
.setParameter("pubId", pubId)
.setParameter("date", date)
.getResultList();
}
@Override
public List<Reject> listByReceiverAndPubAndDate(final Long receiverId, final Long pubId, final LocalDate date) {
return manager.createQuery(
"FROM Reject AS reject " +
"WHERE reject.receiver.id = :receiverId " +
"AND reject.pub.id = :pubId " +
"AND date = :date",
Reject.class)
.setParameter("receiverId", receiverId)
.setParameter("pubId", pubId)
.setParameter("date", date)
.getResultList();
}
@Override
public List<Reject> listBySender(final Long id) {
return manager.createQuery(
"FROM Reject AS reject " +
"WHERE reject.sender.id = :id",
Reject.class)
.setParameter("id", id)
.getResultList();
}
@Override
public List<Reject> listByReceiver(final Long id) {
return manager.createQuery(
"FROM Reject AS reject " +
"WHERE reject.receiver.id = :id",
Reject.class)
.setParameter("id", id)
.getResultList();
}
@Override
public void delete(Long id) {
findById(id).ifPresent(reject -> {
manager.remove(reject);
manager.flush();
});
}
}
| 28.235294 | 113 | 0.690476 |
d2624b2573f3b51b8ed613d74810900d5eee6205 | 14,394 | package de.spricom.dessert.classfile;
/*-
* #%L
* Dessert Dependency Assertion Library for Java
* %%
* Copyright (C) 2017 - 2022 Hans Jörg Heßmann
* %%
* 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 de.spricom.dessert.classfile.attribute.*;
import de.spricom.dessert.classfile.attribute.AttributeInfo.AttributeContext;
import de.spricom.dessert.classfile.constpool.ConstantPool;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
/**
* Wraps the information contained in a .class file according
* to the <a href="https://docs.oracle.com/javase/specs/jvms/se18/html/jvms-4.html" target="_blank">
* Java Virtual Machine Specification</a>.
*/
public class ClassFile {
public static final int MAGIC = 0xCAFEBABE;
public static final int ACC_PUBLIC = 0x0001; // Declared public; may be accessed from outside its package.
public static final int ACC_FINAL = 0x0010; // Declared final; no subclasses allowed.
public static final int ACC_SUPER = 0x0020; // Treat superclass methods specially when invoked by the invoke-special instruction.
public static final int ACC_INTERFACE = 0x0200; // Is an interface, not a class.
public static final int ACC_ABSTRACT = 0x0400; // Declared abstract; must not be instantiated.
public static final int ACC_SYNTHETIC = 0x1000; // Declared synthetic; not present in the source code.
public static final int ACC_ANNOTATION = 0x2000; // Declared as an annotation type.
public static final int ACC_ENUM = 0x4000; // Declared as an enum type.
public static final int ACC_MODULE = 0x8000; // Is a module, not a class or interface.
private final int minorVersion;
private final int majorVersion;
private final ConstantPool constantPool;
private final int accessFlags;
private final String thisClass;
private final String superClass;
private String[] interfaces;
private FieldInfo[] fields;
private MethodInfo[] methods;
private final AttributeInfo[] attributes;
public ClassFile(Class<?> clazz) throws IOException {
this(open(clazz));
}
private static InputStream open(Class<?> clazz) {
InputStream is = clazz.getResourceAsStream("/" + clazz.getName().replace('.', '/') + ".class");
assert is != null : "No file found for " + clazz;
return is;
}
public ClassFile(InputStream in) throws IOException {
BufferedInputStream bi = new BufferedInputStream(in);
try {
DataInputStream is = new DataInputStream(bi);
if (ClassFile.MAGIC != is.readInt()) {
throw new IOException("Not a class file.");
}
minorVersion = is.readUnsignedShort();
majorVersion = is.readUnsignedShort();
constantPool = new ConstantPool(is);
accessFlags = is.readUnsignedShort();
thisClass = constantPool.getConstantClassName(is.readUnsignedShort());
superClass = constantPool.getConstantClassName(is.readUnsignedShort());
readInterfaces(is);
readFields(is);
readMethods(is);
attributes = AttributeInfo.readAttributes(is, constantPool, AttributeContext.CLASS);
if (is.read() != -1) {
throw new IOException("EOF not reached!");
}
} finally {
bi.close();
}
}
private void readInterfaces(DataInputStream is) throws IOException {
int interfacesCount = is.readUnsignedShort();
interfaces = new String[interfacesCount];
for (int i = 0; i < interfacesCount; i++) {
interfaces[i] = constantPool.getConstantClassName(is.readUnsignedShort());
}
}
private void readFields(DataInputStream is) throws IOException {
int fieldCount = is.readUnsignedShort();
fields = new FieldInfo[fieldCount];
for (int i = 0; i < fieldCount; i++) {
fields[i] = new FieldInfo();
readMember(fields[i], is, AttributeContext.FIELD);
}
}
private void readMethods(DataInputStream is) throws IOException {
int methodCount = is.readUnsignedShort();
methods = new MethodInfo[methodCount];
for (int i = 0; i < methodCount; i++) {
methods[i] = new MethodInfo();
readMember(methods[i], is, AttributeContext.METHOD);
}
}
private void readMember(MemberInfo member, DataInputStream is, AttributeContext context) throws IOException {
member.setAccessFlags(is.readUnsignedShort());
member.setName(readString(is));
member.setDescriptor(readString(is));
member.setAttributes(AttributeInfo.readAttributes(is, constantPool, context));
}
private String readString(DataInputStream is) throws IOException {
return constantPool.getUtf8String(is.readUnsignedShort());
}
public Set<String> getDependentClasses() {
Set<String> classNames = new TreeSet<String>();
for (FieldInfo fieldInfo : fields) {
fieldInfo.addDependentClassNames(classNames);
}
for (MethodInfo methodInfo : methods) {
methodInfo.addDependentClassNames(classNames);
}
for (AttributeInfo attribute : attributes) {
attribute.addDependentClassNames(classNames);
}
constantPool.addDependentClassNames(classNames);
classNames.remove(thisClass);
return classNames;
}
public String dumpConstantPool() {
return constantPool.dumpConstantPool();
}
/**
* Produces a dump similar to <i>javap -verbose</i>.
*
* @return the dump
*/
public String dump() {
StringBuilder sb = new StringBuilder();
sb.append(constantPool.dumpConstantPool());
String indent = "\t";
sb.append("Interfaces:\n");
for (String ifc : getInterfaces()) {
sb.append(indent).append(ifc).append("\n");
}
sb.append("Fields:\n");
for (FieldInfo field : getFields()) {
sb.append(indent).append(field).append("\n");
dump(field.getAttributes(), sb, indent + indent);
}
sb.append("Methods:\n");
for (MethodInfo method : getMethods()) {
sb.append(indent).append(method).append("\n");
dump(method.getAttributes(), sb, indent + indent);
}
sb.append("Class attributes:\n");
dump(getAttributes(), sb, indent);
sb.append("Dependent classes:\n");
for (String dependentClass : getDependentClasses()) {
sb.append(" ").append(dependentClass).append("\n");
}
return sb.toString();
}
private void dump(AttributeInfo[] attributes, StringBuilder sb, String indent) {
for (AttributeInfo attribute : attributes) {
sb.append(indent).append("attribute: ").append(attribute).append("\n");
}
}
public int getMinorVersion() {
return minorVersion;
}
public int getMajorVersion() {
return majorVersion;
}
public int getAccessFlags() {
return accessFlags;
}
public String getThisClass() {
return thisClass;
}
public String getSuperClass() {
return superClass;
}
public String[] getInterfaces() {
return interfaces;
}
public FieldInfo[] getFields() {
return fields;
}
public MethodInfo[] getMethods() {
return methods;
}
public AttributeInfo[] getAttributes() {
return attributes;
}
public boolean isPublic() {
return (accessFlags & ACC_PUBLIC) != 0;
}
public boolean isFinal() {
return (accessFlags & ACC_FINAL) != 0;
}
public boolean isSuper() {
return (accessFlags & ACC_SUPER) != 0;
}
public boolean isInterface() {
return (accessFlags & ACC_INTERFACE) != 0;
}
public boolean isAbstract() {
return (accessFlags & ACC_ABSTRACT) != 0;
}
public boolean isSynthetic() {
return (accessFlags & ACC_SYNTHETIC) != 0;
}
public boolean isAnnotation() {
return (accessFlags & ACC_ANNOTATION) != 0;
}
public boolean isEnum() {
return (accessFlags & ACC_ENUM) != 0;
}
public boolean isModule() {
return (accessFlags & ACC_MODULE) != 0;
}
public String getSimpleName() {
List<InnerClassesAttribute> innerClassesAttributes = Attributes.filter(attributes, InnerClassesAttribute.class);
if (!innerClassesAttributes.isEmpty()) {
for (InnerClass innerClass : innerClassesAttributes.get(0).getInnerClasses()) {
if (thisClass.equals(innerClass.getInnerClassName())) {
String simpleName = innerClass.getSimpleName();
return simpleName == null ? "" : simpleName;
}
}
}
return thisClass.substring(thisClass.lastIndexOf('.') + 1);
}
public boolean isInnerClass() {
if (thisClass.indexOf('$') == -1) {
return false;
}
if (majorVersion >= 55) {
return !Attributes.filter(attributes, NestHostAttribute.class).isEmpty();
}
if (!Attributes.filter(attributes, EnclosingMethodAttribute.class).isEmpty()) {
return true;
}
List<InnerClassesAttribute> innerClassesAttributes =
Attributes.filter(attributes, InnerClassesAttribute.class);
if (innerClassesAttributes.isEmpty()) {
return false;
}
for (InnerClass innerClass : innerClassesAttributes.get(0).getInnerClasses()) {
if (thisClass.equals(innerClass.getInnerClassName())) {
return true;
}
}
return false;
}
public boolean isNestHost() {
if (majorVersion >= 55) {
List<NestMembersAttribute> nestMembersAttributes =
Attributes.filter(attributes, NestMembersAttribute.class);
return !nestMembersAttributes.isEmpty();
}
List<InnerClassesAttribute> innerClassesAttributes =
Attributes.filter(attributes, InnerClassesAttribute.class);
if (innerClassesAttributes.isEmpty()) {
return false;
}
int dollarIndex = thisClass.indexOf('$');
boolean hasInnerClass = false;
for (InnerClass innerClass : innerClassesAttributes.get(0).getInnerClasses()) {
if (this.thisClass.equals(innerClass.getInnerClassName())) {
return false;
}
if (innerClass.getInnerClassName().startsWith(thisClass)) {
if (dollarIndex == -1) {
return true;
}
hasInnerClass = true;
}
}
return hasInnerClass;
}
public String getNestHost() {
if (majorVersion >= 55) {
List<NestHostAttribute> nestHostAttributes = Attributes.filter(attributes, NestHostAttribute.class);
return nestHostAttributes.isEmpty() ? null : nestHostAttributes.get(0).getHostClassName();
}
List<InnerClassesAttribute> innerClassesAttributes =
Attributes.filter(attributes, InnerClassesAttribute.class);
if (innerClassesAttributes.isEmpty()) {
return null;
}
List<EnclosingMethodAttribute> enclosingMethodAttributes =
Attributes.filter(attributes, EnclosingMethodAttribute.class);
String outerName = enclosingMethodAttributes.isEmpty()
? thisClass
: enclosingMethodAttributes.get(0).getEnclosingClassname();
InnerClass[] innerClasses = innerClassesAttributes.get(0).getInnerClasses();
boolean outerMost = false;
while (!outerMost) {
outerMost = true;
for (InnerClass innerClass : innerClasses) {
if (outerName.equals(innerClass.getInnerClassName())
&& innerClass.getOuterClassName() != null) {
outerName = innerClass.getOuterClassName();
outerMost = false;
}
}
}
if (thisClass.equals(outerName)) {
for (InnerClass innerClass : innerClasses) {
if (thisClass.equals(innerClass.getOuterClassName())
|| innerClass.getInnerClassName().startsWith(thisClass)) {
return thisClass;
}
}
return null;
}
return outerName;
}
public List<String> getNestMembers() {
if (majorVersion >= 55) {
List<NestMembersAttribute> nestMembersAttributes =
Attributes.filter(attributes, NestMembersAttribute.class);
if (nestMembersAttributes.isEmpty()) {
return Collections.emptyList();
}
return Arrays.asList(nestMembersAttributes.get(0).getMembers());
}
List<InnerClassesAttribute> innerClassesAttributes =
Attributes.filter(attributes, InnerClassesAttribute.class);
if (innerClassesAttributes.isEmpty()) {
return Collections.emptyList();
}
InnerClass[] innerClasses = innerClassesAttributes.get(0).getInnerClasses();
List<String> nestMembers = new ArrayList<String>(innerClasses.length);
for (InnerClass innerClass : innerClasses) {
if (innerClass.getInnerClassName().startsWith(thisClass)) {
nestMembers.add(innerClass.getInnerClassName());
}
}
return nestMembers;
}
public boolean isDeprecated() {
return !Attributes.filter(attributes, DeprecatedAttribute.class).isEmpty();
}
}
| 36.256927 | 133 | 0.621787 |
6a8a8083bcbfd2e5c98a3bce41bd78b89a4e03d7 | 2,354 | package com.mobiussoftware.iotbroker.mqtt.net;
import java.net.InetSocketAddress;
import java.net.URI;
import com.mobius.software.mqtt.parser.header.api.MQMessage;
import com.mobiussoftware.iotbroker.network.ConnectionListener;
import com.mobiussoftware.iotbroker.network.ExceptionHandler;
import com.mobiussoftware.iotbroker.network.TLSHelper;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshakerFactory;
import io.netty.handler.codec.http.websocketx.WebSocketVersion;
import io.netty.handler.ssl.SslHandler;
public class WSSClient extends WSClient
{
private String certPath;
private String certPwd;
public WSSClient(InetSocketAddress address, int workerThreads, String certPath, String certPwd)
{
super(address, workerThreads);
this.certPath = certPath;
this.certPwd = certPwd;
}
@Override
protected ChannelInitializer<SocketChannel> getChannelInitializer(final ConnectionListener<MQMessage> listener)
{
WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(this.getUri(), WebSocketVersion.V13, null, false, EmptyHttpHeaders.INSTANCE, 1280000);
final WebSocketClientHandler handler = new WebSocketClientHandler(this, handshaker, listener);
return new ChannelInitializer<SocketChannel>()
{
@Override
public void initChannel(SocketChannel ch) throws Exception
{
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("ssl", new SslHandler(TLSHelper.getClientEngine(certPath, certPwd)));
pipeline.addLast("http-codec", new HttpClientCodec());
pipeline.addLast("aggregator", new HttpObjectAggregator(65536));
pipeline.addLast("ws-handler", handler);
pipeline.addLast(new ExceptionHandler());
}
};
}
@Override
protected URI getUri()
{
String type = "wss";
String prefix = "ws";
String url = type + "://" + this.address.getHostName() + ":" + String.valueOf(this.address.getPort()) + "/" + prefix;
URI uri;
try
{
uri = new URI(url);
}
catch (Exception e)
{
return null;
}
return uri;
}
} | 33.15493 | 174 | 0.776126 |
eeedd485406f0691da67d6a3d1926bcde905c664 | 3,019 | package edu.upf.model.config;
import java.util.Properties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import edu.upf.model.properties.HibernateProperties;
import lombok.extern.slf4j.Slf4j;
/**
* Classe de configuració de l'aplicació.
* <p>
* Aquesta classe configura el TransactionManager, l'Hibernate, a on es troben les classes Repository...
* <p>
* Abans això ho configuravem a l'applicationContext-dataSource.xml, veure exemple a GAP
*/
@Configuration
@EnableJpaRepositories(basePackages = "edu.upf.model.repository")
@EnableTransactionManagement
@Slf4j
public class OracleSQLConfiguration {
@Autowired
private HibernateProperties hibernateProperties;
@Autowired
private DataConfig dataConfig;
@Bean
public JpaTransactionManager transactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager;
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
vendorAdapter.setGenerateDdl(false);
entityManagerFactoryBean.setPackagesToScan("edu.upf.model.model");
log.debug("entityManagerFactory() dataConfig.dataSource()? = " + dataConfig.dataSource());
entityManagerFactoryBean.setDataSource(dataConfig.dataSource());
entityManagerFactoryBean.setJpaVendorAdapter(vendorAdapter);
entityManagerFactoryBean.setJpaProperties(jpaProperties());
return entityManagerFactoryBean;
}
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
private Properties jpaProperties() {
Properties jpaProperties = new Properties();
jpaProperties.setProperty("hibernate.hbm2ddl.auto", "none");
jpaProperties.setProperty("hibernate.dialect", hibernateProperties.getDialect());
jpaProperties.setProperty("hibernate.connection.charSet", "UTF-8");
jpaProperties.put("hibernate.show_sql", hibernateProperties.getShowSql());
return jpaProperties;
}
} | 39.723684 | 119 | 0.771447 |
4c4310ac0af26856b787958aefc7186fb3e12f75 | 1,769 | package com.rent.management.app.Model.Role;
import com.rent.management.app.Model.Property.*;
import com.rent.management.app.Model.Util.Name;
public class Landlord implements Person{
private Name name; //landlord name from Person
private String email; //email from Person
/**
* default constructor
*/
public Landlord(){}
/**
* constructor for Landlord
* @param name Name object to be stored
* @param email String for email to be stored
*/
public Landlord(Name name, String email){
setName(name);
setEmail(email);
}
/**
* changes the property status
* @param p Property object argument to be changed
* @param ps PropertyStatus object to be changed to
*/
public void changePropertyStatus(Property p, PropertyStatus ps){
p.setPropertyStatus(ps);
}
/**
* getter for person
* @return returns a Person object
*/
public Person getPerson(){
return this;
}
/**
* getter for landlord name
* @return returns Name object
*/
@Override
public Name getName(){
return this.name;
}
/**
* getter for landlord email
* @return returns String for email
*/
public String getEmail(){
return this.email;
}
/**
* setter for landlord name
* @param name Name object to be stored
*/
@Override
public void setName(Name name){
this.name = name;
}
/**
* setter for email
* @param email String argument to be stored
*/
public void setEmail(String email){
this.email = email;
}
/**
* instantiates name
*/
@Override
public Name name() {
return null;
}
}
| 21.059524 | 68 | 0.590164 |
100775c5fdb2f99a8978f184e299060ec070e41f | 20,716 | package com.krishagni.catissueplus.core.common.service.impl;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Header;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.FileSystemResource;
import org.springframework.integration.mail.ImapMailReceiver;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import com.krishagni.catissueplus.core.biospecimen.repository.DaoFactory;
import com.krishagni.catissueplus.core.common.OpenSpecimenAppCtxProvider;
import com.krishagni.catissueplus.core.common.PlusTransactional;
import com.krishagni.catissueplus.core.common.domain.Email;
import com.krishagni.catissueplus.core.common.domain.factory.EmailErrorCode;
import com.krishagni.catissueplus.core.common.errors.OpenSpecimenException;
import com.krishagni.catissueplus.core.common.service.ConfigChangeListener;
import com.krishagni.catissueplus.core.common.service.ConfigurationService;
import com.krishagni.catissueplus.core.common.service.EmailProcessor;
import com.krishagni.catissueplus.core.common.service.EmailService;
import com.krishagni.catissueplus.core.common.service.TemplateService;
import com.krishagni.catissueplus.core.common.util.AuthUtil;
import com.krishagni.catissueplus.core.common.util.ConfigUtil;
import com.krishagni.catissueplus.core.common.util.MessageUtil;
import com.krishagni.catissueplus.core.common.util.Utility;
import com.krishagni.rbac.common.errors.RbacErrorCode;
public class EmailServiceImpl implements EmailService, ConfigChangeListener, InitializingBean {
private static final Log logger = LogFactory.getLog(EmailServiceImpl.class);
private static final String MODULE = "email";
private static final String TEMPLATE_SOURCE = "email-templates/";
private static final String BASE_TMPL = "baseTemplate";
private static final String FOOTER_TMPL = "footer";
private JavaMailSender mailSender;
private TemplateService templateService;
private ThreadPoolTaskExecutor taskExecutor;
private ConfigurationService cfgSvc;
private DaoFactory daoFactory;
private ImapMailReceiver mailReceiver;
private ScheduledFuture<?> receiverFuture;
private List<EmailProcessor> processors = new ArrayList<>();
public void setTemplateService(TemplateService templateService) {
this.templateService = templateService;
}
public void setTaskExecutor(ThreadPoolTaskExecutor taskExecutor) {
this.taskExecutor = taskExecutor;
}
public void setCfgSvc(ConfigurationService cfgSvc) {
this.cfgSvc = cfgSvc;
}
public DaoFactory getDaoFactory() {
return daoFactory;
}
public void setDaoFactory(DaoFactory daoFactory) {
this.daoFactory = daoFactory;
}
@Override
public void onConfigChange(String name, String value) {
initializeMailSender();
if (StringUtils.isBlank(name) ||
name.equals("imap_server_host") ||
name.equals("imap_server_port") ||
name.equals("imap_poll_interval")) {
initializeMailReceiver();
}
}
@Override
public void afterPropertiesSet() throws Exception {
initializeMailSender();
initializeMailReceiver();
cfgSvc.registerChangeListener(MODULE, this);
}
private void initializeMailSender() {
try {
JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
mailSender.setUsername(getAccountId());
mailSender.setPassword(getAccountPassword());
mailSender.setHost(getSmtpHost());
mailSender.setPort(getSmtpPort());
Properties props = new Properties();
props.put("mail.smtp.timeout", 10000);
props.put("mail.smtp.connectiontimeout", 10000);
String startTlsEnabled = getStartTlsEnabled();
String authEnabled = getSmtpAuthEnabled();
if (StringUtils.isNotBlank(startTlsEnabled) && StringUtils.isNotBlank(authEnabled)) {
props.put("mail.smtp.starttls.enable", startTlsEnabled);
props.put("mail.smtp.auth", authEnabled);
}
mailSender.setJavaMailProperties(props);
this.mailSender = mailSender;
} catch (Exception e) {
logger.error("Error initialising e-mail sender", e);
}
}
@Override
public boolean sendEmail(String emailTmplKey, String[] to, Map<String, Object> props) {
return sendEmail(emailTmplKey, to, null, props);
}
@Override
public boolean sendEmail(String emailTmplKey, String[] to, File[] attachments, Map<String, Object> props) {
return sendEmail(emailTmplKey, to, null, attachments, props);
}
@Override
public boolean sendEmail(String emailTmplKey, String[] to, String[] bcc, File[] attachments, Map<String, Object> props) {
return sendEmail(emailTmplKey, null, null, to, bcc, attachments, props);
}
@Override
public boolean sendEmail(String emailTmplKey, String emailTmpl, String[] to, Map<String, Object> props) {
return sendEmail(emailTmplKey, null, emailTmpl, to, null, null, props);
}
@Override
public boolean sendEmail(String emailTmplKey, String tmplSubj, String tmplContent, String[] to, Map<String, Object> props) {
return sendEmail(emailTmplKey, tmplSubj, tmplContent, to, null , null, props);
}
@Override
public boolean sendEmail(Email mail) {
return sendEmail(mail, null);
}
public boolean sendEmail(Email mail, Map<String, Object> props) {
try {
if (!isEmailNotifEnabled()) {
logger.debug("Email notification is disabled. Not sending email: " + mail.getSubject());
return false;
}
boolean ignoreDnd = (Boolean) props.getOrDefault("ignoreDnd", false);
String[] toRcpts = filterEmailIds("To", mail.getToAddress(), ignoreDnd);
if (toRcpts.length == 0) {
return false;
}
mail.setToAddress(toRcpts);
mail.setBccAddress(filterEmailIds("Bcc", mail.getBccAddress(), ignoreDnd));
mail.setCcAddress(filterEmailIds("Cc", mail.getCcAddress(), ignoreDnd));
MimeMessage mimeMessage = createMessage(mail, props);
SendMailTask sendTask = new SendMailTask(mimeMessage);
boolean result = true;
if (!(Boolean) props.getOrDefault("$synchronous", false)) {
logger.info("Invoking task executor to send the e-mail asynchronously: " + mimeMessage.getSubject());
taskExecutor.submit(sendTask);
result = true;
} else {
logger.warn("Sending e-mail synchronously: " + mimeMessage.getSubject());
sendTask.run();
if (StringUtils.isNotBlank(sendTask.getError())) {
props.put("$error", sendTask.getError());
result = false;
}
}
return result;
} catch (Exception e) {
logger.error("Error sending e-mail", e);
props.put("$error", e.getMessage());
return false;
}
}
@Override
public void registerProcessor(EmailProcessor processor) {
if (processors.contains(processor)) {
return;
}
processors.add(processor);
if (processors.size() == 1) {
initializeMailReceiver();
}
}
@Override
public void sendTestEmail() {
if (!AuthUtil.isAdmin()) {
throw OpenSpecimenException.userError(RbacErrorCode.ADMIN_RIGHTS_REQUIRED);
}
if (!isEmailNotifEnabled()) {
throw OpenSpecimenException.userError(EmailErrorCode.NOTIFS_ARE_DISABLED);
}
if (StringUtils.isEmpty(getAdminEmailId())) {
throw OpenSpecimenException.userError(EmailErrorCode.ADMIN_EMAIL_REQ);
}
String[] adminEmailId = new String[] {getAdminEmailId()};
Map<String, Object> props = new HashMap<>();
props.put("$synchronous", true);
boolean status = sendEmail("test_email", null, null, adminEmailId, null, null, props);
if (!status) {
throw OpenSpecimenException.userError(EmailErrorCode.UNABLE_TO_SEND, props.get("$error"));
}
}
private boolean sendEmail(String tmplKey, String tmplSubj, String tmplContent, String[] to, String[] bcc, File[] attachments, Map<String, Object> props) {
if (!isEmailNotifEnabled()) {
return false;
}
boolean emailEnabled = cfgSvc.getBoolSetting("notifications", "email_" + tmplKey, true);
if (!emailEnabled) {
return false;
}
if (props == null) {
props = new HashMap<>();
}
String adminEmailId = getAdminEmailId();
if (StringUtils.isNotBlank(tmplContent)) {
props.put("templateContent", tmplContent);
} else {
props.put("template", getTemplate(tmplKey));
}
props.put("footer", getFooterTmpl());
props.put("appUrl", getAppUrl());
props.put("adminEmailAddress", adminEmailId);
props.put("adminPhone", cfgSvc.getStrSetting("email", "admin_phone_no", "Not Specified"));
props.put("dateFmt", new SimpleDateFormat(ConfigUtil.getInstance().getDateTimeFmt()));
props.put("urlEncoder", URLEncoder.class);
String subject = StringUtils.isNotBlank(tmplSubj) ? tmplSubj : getSubject(tmplKey, (Object[]) props.get("$subject"));
String content = templateService.render(getBaseTmpl(), props);
Email email = new Email();
email.setSubject(subject);
email.setBody(content);
email.setToAddress(to);
email.setBccAddress(bcc);
email.setAttachments(attachments);
boolean ccAdmin = BooleanUtils.toBooleanDefaultIfNull((Boolean) props.get("ccAdmin"), true);
if (ccAdmin) {
email.setCcAddress(new String[] { adminEmailId });
}
return sendEmail(email, props);
}
private String getTemplate(String tmplKey) {
String localeTmpl = TEMPLATE_SOURCE + Locale.getDefault().toString() + "/" + tmplKey + ".vm";
URL url = this.getClass().getClassLoader().getResource(localeTmpl);
if (url == null) {
localeTmpl = TEMPLATE_SOURCE + "default/" + tmplKey + ".vm";
}
return localeTmpl;
}
private String getSubject(String subject, Object[] params) {
String key = subject.toLowerCase() + "_subj";
String message = MessageUtil.getInstance().getMessage(key, "not_found_subj", params);
if (!message.equals("not_found_subj")) {
subject = message;
}
return getSubjectPrefix() + subject;
}
private String getSubjectPrefix() {
String subjectPrefix = MessageUtil.getInstance().getMessage("email_subject_prefix");
String deployEnv = ConfigUtil.getInstance().getStrSetting("common", "deploy_env", "");
subjectPrefix += " " + StringUtils.substring(deployEnv, 0, 10);
return "[" + subjectPrefix.trim() + "]: ";
}
private MimeMessage createMessage(Email mail, Map<String, Object> props)
throws MessagingException, UnsupportedEncodingException {
if (props == null) {
props = Collections.emptyMap();
}
MimeMessage mimeMessage;
Map<String, String> replyToHeaders = (Map<String, String>) props.get("$replyToHeaders");
if (replyToHeaders != null && !replyToHeaders.isEmpty()) {
MimeMessage parent = mailSender.createMimeMessage();
for (Map.Entry<String, String> header : replyToHeaders.entrySet()) {
parent.setHeader(header.getKey(), header.getValue());
}
mimeMessage = (MimeMessage) parent.reply(false, true);
} else {
mimeMessage = mailSender.createMimeMessage();
}
MimeMessageHelper message = new MimeMessageHelper(mimeMessage, true, "UTF-8"); // true = multipart
message.setSubject(mail.getSubject());
message.setTo(mail.getToAddress());
if (mail.getBccAddress() != null) {
message.setBcc(mail.getBccAddress());
}
if (mail.getCcAddress() != null) {
message.setCc(mail.getCcAddress());
}
message.setText(mail.getBody(), true); // true = isHtml
message.setFrom(getAccountId());
String fromDisplayName = (String) props.getOrDefault("$fromDisplayName", null);
String fromId = (String) props.getOrDefault("$fromEmailId", null);
if (StringUtils.isBlank(fromDisplayName)) {
fromDisplayName = fromId;
}
if (StringUtils.isNotBlank(fromId)) {
message.setFrom(new InternetAddress(fromId, fromDisplayName));
message.setReplyTo(new InternetAddress(fromId, fromDisplayName));
} else if (StringUtils.isNotBlank(fromDisplayName)) {
message.setFrom(new InternetAddress(getAccountId(), fromDisplayName));
message.setReplyTo(new InternetAddress(getAccountId(), fromDisplayName));
}
if (mail.getAttachments() != null) {
for (File attachment: mail.getAttachments()) {
FileSystemResource file = new FileSystemResource(attachment);
message.addAttachment(file.getFilename(), file);
}
}
return mimeMessage;
}
private class SendMailTask implements Runnable {
private MimeMessage mimeMessage;
private String error;
public SendMailTask(MimeMessage mimeMessage) {
this.mimeMessage = mimeMessage;
}
public void run() {
try {
String rcpts = toString(mimeMessage.getAllRecipients());
logger.info("Sending email '" + mimeMessage.getSubject() + "' to " + rcpts);
mailSender.send(mimeMessage);
logger.info("Email '" + mimeMessage.getSubject() + "' sent to " + rcpts);
} catch (Exception e) {
logger.error("Error sending e-mail ", e);
this.error = e.getMessage();
}
}
public String getError() {
return this.error;
}
private String toString(Address[] addresses) {
return Stream.of(addresses).map(addr -> ((InternetAddress) addr).getAddress()).collect(Collectors.joining(", "));
}
}
private String getBaseTmpl() {
return getTemplate(BASE_TMPL);
}
private String getFooterTmpl() {
return getTemplate(FOOTER_TMPL);
}
private String[] filterEmailIds(String field, String[] emailIds, boolean ignoreDnd) {
String[] validEmailIds = filterInvalidEmails(emailIds);
if (validEmailIds.length == 0) {
logger.error("Invalid email IDs in " + field + " : " + toString(emailIds));
return validEmailIds;
}
String[] filteredEmailIds = ignoreDnd ? validEmailIds : filterEmailIds(validEmailIds);
if (logger.isDebugEnabled()) {
String ignoredEmailIds = Stream.of(validEmailIds)
.filter(emailId -> Stream.of(filteredEmailIds).noneMatch(emailId::equals))
.collect(Collectors.joining(", "));
logger.debug("Not sending email to contacts and users having DND enabled: " + ignoredEmailIds);
}
return filteredEmailIds;
}
private String[] filterEmailIds(String[] emailIds) {
Map<String, Boolean> settings = getEmailIdDnds(emailIds);
return Arrays.stream(emailIds)
.filter(emailId -> !settings.getOrDefault(emailId, false))
.toArray(String[]::new);
}
private String[] filterInvalidEmails(String[] emailIds) {
if (emailIds == null) {
return new String[0];
}
return Arrays.stream(emailIds).filter(Utility::isValidEmail).toArray(String[]::new);
}
@PlusTransactional
private Map<String, Boolean> getEmailIdDnds(String[] validEmailIds) {
return daoFactory.getUserDao().getEmailIdDnds(Arrays.asList(validEmailIds));
}
private String toString(String[] arr) {
if (arr == null) {
return StringUtils.EMPTY;
}
return StringUtils.join(arr, ",");
}
private void initializeMailReceiver() {
if (mailReceiver != null) {
mailReceiver = null;
}
if (receiverFuture != null) {
receiverFuture.cancel(false);
receiverFuture = null;
}
if (processors.isEmpty() || StringUtils.isBlank(getImapHost())) {
logger.info("IMAP service is not configured. Will not poll for inbound emails.");
return;
}
try {
String url = isSecuredImap() ? "imaps://" : "imap://";
url += URLEncoder.encode(getAccountId(), "UTF-8") + ":";
url += URLEncoder.encode(getAccountPassword(), "UTF-8") + "@";
url += getImapHost() + ":" + getImapPort() + "/" + getFolder().toUpperCase();
Properties mailProperties = new Properties();
mailProperties.setProperty("mail.store.protocol", isSecuredImap() ? "imaps" : "imap");
ImapMailReceiver receiver = new ImapMailReceiver(url);
receiver.setShouldMarkMessagesAsRead(true);
receiver.setShouldDeleteMessages(false);
receiver.setJavaMailProperties(mailProperties);
receiver.setBeanFactory(OpenSpecimenAppCtxProvider.getAppCtx());
receiver.afterPropertiesSet();
mailReceiver = receiver;
receiverFuture = Executors.newSingleThreadScheduledExecutor().scheduleWithFixedDelay(
new ReceiveEmailTask(), getPollInterval(), getPollInterval(), TimeUnit.MINUTES);
} catch (Exception e) {
logger.error("Error initialising IMAP receiver", e);
}
}
private class ReceiveEmailTask implements Runnable {
@Override
public void run() {
try {
if (mailReceiver == null) {
return;
}
Object[] messages = mailReceiver.receive();
for (Object message : messages) {
handleMessage((MimeMessage) message);
}
} catch (Throwable t) {
logger.error("Error receiving e-mail messages", t);
}
}
}
private void handleMessage(MimeMessage message) {
try {
Email email = toEmail(message);
for (EmailProcessor processor : processors) {
try {
processor.process(email);
} catch (Throwable t) {
logger.error("Error processing the email by: " + processor.getName(), t);
}
}
} catch (Throwable t) {
logger.error("Error handling the email message", t);
}
}
private Email toEmail(MimeMessage message)
throws Exception {
Map<String, String> headers = new HashMap<>();
Enumeration<Header> headersIter = message.getAllHeaders();
while (headersIter.hasMoreElements()) {
Header header = headersIter.nextElement();
headers.put(header.getName(), header.getValue());
}
Email email = new Email();
email.setHeaders(headers);
email.setSubject(message.getSubject());
for (Address from : message.getFrom()) {
if (from instanceof InternetAddress) {
email.setFromAddress(((InternetAddress) from).getAddress());
}
}
String text = getText(message);
text = text.replaceAll("\r\n", "\n")
.replaceAll(STRIP_EMAIL_REPLY_PATTERN, "")
.trim();
email.setBody(text);
return email;
}
private String getText(Message message)
throws Exception {
if (message.isMimeType("text/plain")) {
return message.getContent().toString();
} else if (message.isMimeType("multipart/*")) {
return getText((MimeMultipart) message.getContent());
}
return "";
}
private String getText(MimeMultipart mimeMultipart)
throws Exception {
int parts = mimeMultipart.getCount();
String result = "";
for (int i = 0; i < parts; ++i) {
BodyPart part = mimeMultipart.getBodyPart(i);
if (part.isMimeType("text/plain")) {
result += "\n" + part.getContent().toString();
} else if (part.getContent() instanceof MimeMultipart) {
result += "\n" + getText((MimeMultipart) part.getContent());
}
}
return result;
}
/**
* Config helper methods
*/
private String getAccountId() {
return cfgSvc.getStrSetting(MODULE, "account_id");
}
private String getAccountPassword() {
return cfgSvc.getStrSetting(MODULE, "account_password");
}
private String getSmtpHost() {
return cfgSvc.getStrSetting(MODULE, "smtp_server_host");
}
private Integer getSmtpPort() {
return cfgSvc.getIntSetting(MODULE, "smtp_server_port", 25);
}
private String getStartTlsEnabled() {
return cfgSvc.getStrSetting(MODULE, "starttls_enabled");
}
private String getSmtpAuthEnabled() {
return cfgSvc.getStrSetting(MODULE, "smtp_auth_enabled");
}
private String getAdminEmailId() {
return cfgSvc.getStrSetting(MODULE, "admin_email_id");
}
private String getAppUrl() {
return cfgSvc.getStrSetting("common", "app_url");
}
private boolean isEmailNotifEnabled() {
return cfgSvc.getBoolSetting("notifications", "all", true);
}
private boolean isSecuredImap() {
return true;
}
private String getImapHost() {
return cfgSvc.getStrSetting(MODULE, "imap_server_host");
}
private Integer getImapPort() {
return cfgSvc.getIntSetting(MODULE, "imap_server_port", 993);
}
private String getFolder() {
return "INBOX";
}
private Integer getPollInterval() {
return cfgSvc.getIntSetting(MODULE, "imap_poll_interval", 5);
}
private final static String STRIP_EMAIL_REPLY_PATTERN =
"(?m)" + // turn on multi-line regex matching
"^>.*$|" + // any line starting with > is ignored
"^On\\s+.*\\s+wrote:"; // strip On Wed, Mar 6, 2019 at 11:25 AM XYZ wrote:
}
| 31.105105 | 155 | 0.728471 |
4f73931e8aac8f19c084f279f531ce6299a596e1 | 139 | package com.lvonce.hera;
public class Test implements IFoo {
public String hello(String name) {
return "Test implement " + name;
}
}
| 17.375 | 35 | 0.71223 |
59caa3dbda3c08ce92fb5412a8a0724796b55f7b | 2,350 | package com.promyze.themis.jenkins.action;
import com.promyze.themis.jenkins.ThemisGlobalConfiguration;
import com.promyze.themis.jenkins.ThemisGlobalConfiguration.ThemisInstance;
import hudson.FilePath;
import hudson.model.Run;
import hudson.model.TaskListener;
import jenkins.model.GlobalConfiguration;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.only;
import static org.mockito.Mockito.verify;
public class ThemisActionTest extends BaseThemisActionTest<ThemisAction> {
@Before
public void setupAction() {
action = Mockito.spy(new ThemisActionImpl(INSTANCE_NAME));
}
@Test
public void testGetInstanceName() {
assertThat(action.getInstanceName()).isEqualTo(INSTANCE_NAME);
}
@Test
public void testIsFailBuildDefault() {
assertThat(action.isFailBuild()).isFalse();
}
@Test
public void testIsFailBuildChanged() {
action.setFailBuild(true);
assertThat(action.isFailBuild()).isTrue();
}
@Test
public void testPerformNominal() {
action.perform(run, workspace, listener);
verify(action).doPerform(themisInstance, run, workspace, listener);
}
@Test
public void testPerformUnknownInstance() {
GlobalConfiguration.all().get(ThemisGlobalConfiguration.class).getInstances().clear();
action.perform(run, workspace, listener);
verify(logger, never()).println(anyString());
verify(listener, only()).error("Unknown Themis instance: " + INSTANCE_NAME);
}
@Test(expected = RuntimeException.class)
public void testPerformUnknownInstanceFailBuild() {
GlobalConfiguration.all().get(ThemisGlobalConfiguration.class).getInstances().clear();
action.setFailBuild(true);
action.perform(run, workspace, listener);
}
private static class ThemisActionImpl extends ThemisAction {
ThemisActionImpl(String instanceName) {
super(instanceName);
}
@Override
void doPerform(ThemisInstance instance, Run<?, ?> run, FilePath workspace,
TaskListener listener) {
}
}
}
| 28.313253 | 94 | 0.706809 |
5833fdf5f17a02f2ec882872505ce0968126042a | 1,821 | /*
* The JASDB software and code is Copyright protected 2012 and owned by Renze de Vries
*
* All the code and design principals in the codebase are also Copyright 2012
* protected and owned Renze de Vries. Any unauthorized usage of the code or the
* design and principals as in this code is prohibited.
*/
package com.oberasoftware.jasdb.integration.rest;
import com.oberasoftware.jasdb.api.exceptions.JasDBStorageException;
import com.oberasoftware.jasdb.api.security.Credentials;
import com.oberasoftware.jasdb.api.session.DBSession;
import com.oberasoftware.jasdb.rest.client.RestDBSessionFactory;
/**
* User: renarj
* Date: 4/28/12
* Time: 6:34 PM
*/
public class TestRestDBSessionFactory extends RestDBSessionFactory {
private Credentials credentials;
public static String INSTANCE_ID = "default";
public static String BAG_NAME = "bag0";
public static int DEFAULT_PORT = 7050;
public TestRestDBSessionFactory() {
setHostname("localhost");
setPort(DEFAULT_PORT);
setInstanceId(INSTANCE_ID);
}
public TestRestDBSessionFactory(Credentials credentials) {
super(false);
this.credentials = credentials;
setHostname("localhost");
setPort(DEFAULT_PORT);
setInstanceId(INSTANCE_ID);
}
@Override
public DBSession createSession() throws JasDBStorageException {
if(credentials != null) {
return super.createSession(credentials);
} else {
return super.createSession();
}
}
@Override
public DBSession createSession(String instance) throws JasDBStorageException {
if(credentials != null) {
return super.createSession(instance, credentials);
} else {
return super.createSession(instance);
}
}
}
| 30.35 | 86 | 0.69687 |
e5d2db8e6a6951f0f78d860bb154e7282f28cbf6 | 11,452 | package org.openstreetmap.atlas.utilities.identifiers;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.openstreetmap.atlas.exception.CoreException;
import org.openstreetmap.atlas.geography.Location;
import org.openstreetmap.atlas.geography.PolyLine;
import org.openstreetmap.atlas.geography.Rectangle;
import org.openstreetmap.atlas.geography.atlas.builder.RelationBean;
import org.openstreetmap.atlas.geography.atlas.complete.CompleteEdge;
import org.openstreetmap.atlas.geography.atlas.complete.CompletePoint;
import org.openstreetmap.atlas.geography.atlas.complete.CompleteRelation;
import org.openstreetmap.atlas.geography.atlas.items.ItemType;
import org.openstreetmap.atlas.utilities.collections.Maps;
import org.openstreetmap.atlas.utilities.collections.Sets;
/**
* @author lcram
*/
public class EntityIdentifierGeneratorTest
{
@Rule
public final ExpectedException expectedException = ExpectedException.none();
@Test
public void testEmptyConfigException()
{
final CompletePoint point = new CompletePoint(1L, Location.CENTER,
Maps.hashMap("a", "b", "c", "d"), Sets.hashSet());
Assert.assertTrue((new EntityIdentifierGenerator.Configuration().getGenerator()
.getBasicPropertyString(point)
+ new EntityIdentifierGenerator.Configuration().getGenerator()
.getTypeSpecificPropertyString(point)).isEmpty());
this.expectedException.expect(CoreException.class);
this.expectedException.expectMessage(
"EntityIdentifierGenerator.Configuration was empty! Please set at least one of geometry, tags, or relation members.");
new EntityIdentifierGenerator.Configuration().getGenerator().generateIdentifier(point);
}
@Test
public void testForcePositiveIDForEdge()
{
final CompleteEdge edge = new CompleteEdge(1L, PolyLine.SIMPLE_POLYLINE,
Maps.hashMap("a", "b", "c", "d"), 2L, 3L, Sets.hashSet());
this.expectedException.expect(IllegalArgumentException.class);
this.expectedException
.expectMessage("For type EDGE, please use generatePositiveIdentifierForEdge");
new EntityIdentifierGenerator.Configuration().useDefaults().getGenerator()
.generateIdentifier(edge);
}
@Test
public void testGetFullPropertyString()
{
final CompleteEdge edge = new CompleteEdge(1L, PolyLine.SIMPLE_POLYLINE,
Maps.hashMap("a", "b", "c", "d"), 2L, 3L, Sets.hashSet());
final String goldenPropertyStringAll = "LINESTRING (1 1, 2 2);a=b,c=d";
Assert.assertEquals(goldenPropertyStringAll,
new EntityIdentifierGenerator.Configuration().useDefaults().getGenerator()
.getBasicPropertyString(edge)
+ new EntityIdentifierGenerator().getTypeSpecificPropertyString(edge));
final String goldenPropertyStringGeometryOnly = "LINESTRING (1 1, 2 2)";
Assert.assertEquals(goldenPropertyStringGeometryOnly,
new EntityIdentifierGenerator.Configuration().useGeometry().getGenerator()
.getBasicPropertyString(edge)
+ new EntityIdentifierGenerator().getTypeSpecificPropertyString(edge));
final String goldenPropertyStringTagsOnly = ";a=b,c=d";
Assert.assertEquals(goldenPropertyStringTagsOnly,
new EntityIdentifierGenerator.Configuration().useTags().getGenerator()
.getBasicPropertyString(edge)
+ new EntityIdentifierGenerator().getTypeSpecificPropertyString(edge));
}
@Test
public void testGetPropertyString()
{
final CompletePoint point = new CompletePoint(1L, Location.CENTER,
Maps.hashMap("a", "b", "c", "d"), Sets.hashSet());
final String goldenPropertyString = "POINT (0 0);a=b,c=d";
Assert.assertEquals(goldenPropertyString,
new EntityIdentifierGenerator().getBasicPropertyString(point));
}
@Test
public void testGetTypeSpecificPropertyStringForRelation()
{
final RelationBean bean1 = new RelationBean();
bean1.addItem(1L, "role", ItemType.POINT);
bean1.addItem(10L, "role", ItemType.AREA);
final RelationBean bean2 = new RelationBean();
bean2.addItem(10L, "role", ItemType.AREA);
bean2.addItem(1L, "role", ItemType.POINT);
final CompleteRelation relation1 = new CompleteRelation(1L,
Maps.hashMap("a", "b", "c", "d"), Rectangle.MINIMUM, bean1, null, null, null,
Sets.hashSet());
final CompleteRelation relation2 = new CompleteRelation(1L,
Maps.hashMap("a", "b", "c", "d"), Rectangle.MINIMUM, bean2, null, null, null,
Sets.hashSet());
final String goldenPropertyString = ";RelationBean[(AREA,10,role)(POINT,1,role)]";
Assert.assertEquals(goldenPropertyString,
new EntityIdentifierGenerator().getTypeSpecificPropertyString(relation1));
Assert.assertEquals(goldenPropertyString,
new EntityIdentifierGenerator().getTypeSpecificPropertyString(relation2));
Assert.assertTrue(
new EntityIdentifierGenerator.Configuration().useDefaults().excludeRelationMembers()
.getGenerator().getTypeSpecificPropertyString(relation1).isEmpty());
Assert.assertEquals(goldenPropertyString, new EntityIdentifierGenerator.Configuration()
.useRelationMembers().getGenerator().getTypeSpecificPropertyString(relation2));
}
@Test
public void testHashes()
{
final CompleteEdge edge = new CompleteEdge(1L, PolyLine.SIMPLE_POLYLINE,
Maps.hashMap("a", "b", "c", "d"), 2L, 3L, Sets.hashSet());
final long goldenHash1 = 6463671242943641314L;
Assert.assertEquals(goldenHash1,
new EntityIdentifierGenerator().generatePositiveIdentifierForEdge(edge));
final CompletePoint point = new CompletePoint(1L, Location.CENTER,
Maps.hashMap("a", "b", "c", "d"), Sets.hashSet());
final long goldenHash2 = 4334702026426103264L;
Assert.assertEquals(goldenHash2, new EntityIdentifierGenerator().generateIdentifier(point));
Assert.assertEquals(goldenHash2, new EntityIdentifierGenerator.Configuration().useDefaults()
.getGenerator().generateIdentifier(point));
final long goldenHash3 = -2934213421148195810L;
Assert.assertEquals(goldenHash3, new EntityIdentifierGenerator.Configuration().useGeometry()
.getGenerator().generateIdentifier(point));
Assert.assertEquals(goldenHash3, new EntityIdentifierGenerator.Configuration().useDefaults()
.excludeTags().excludeRelationMembers().getGenerator().generateIdentifier(point));
final long goldenHash4 = 3739460904040018219L;
Assert.assertEquals(goldenHash4, new EntityIdentifierGenerator.Configuration().useTags()
.getGenerator().generateIdentifier(point));
Assert.assertEquals(goldenHash4,
new EntityIdentifierGenerator.Configuration().useDefaults().excludeGeometry()
.excludeRelationMembers().getGenerator().generateIdentifier(point));
}
@Test
public void testNonRelationInvariantConfigException()
{
final EntityIdentifierGenerator nonRelationInvariantGenerator = new EntityIdentifierGenerator.Configuration()
.useRelationMembers().getGenerator();
final RelationBean bean1 = new RelationBean();
bean1.addItem(1L, "role", ItemType.POINT);
bean1.addItem(10L, "role", ItemType.AREA);
final CompleteRelation relation1 = new CompleteRelation(1L,
Maps.hashMap("a", "b", "c", "d"), Rectangle.MINIMUM, bean1, null, null, null,
Sets.hashSet());
Assert.assertEquals(6707509058043000459L,
nonRelationInvariantGenerator.generateIdentifier(relation1));
final CompletePoint point = new CompletePoint(1L, Location.CENTER,
Maps.hashMap("a", "b", "c", "d"), Sets.hashSet());
this.expectedException.expect(CoreException.class);
this.expectedException.expectMessage(
"EntityIdentifierGenerator.Configuration was non-relation invariant! Please set at least one of geometry or tags to generate IDs for non-relation type entities.");
nonRelationInvariantGenerator.generateIdentifier(point);
}
@Test
public void testUnsetGeometryException()
{
final CompletePoint pointNoGeometry = new CompletePoint(1L, null,
Maps.hashMap("a", "b", "c", "d"), Sets.hashSet());
final CompletePoint pointNoTags = new CompletePoint(1L, Location.CENTER, null,
Sets.hashSet());
new EntityIdentifierGenerator.Configuration().useTags().getGenerator()
.generateIdentifier(pointNoGeometry);
new EntityIdentifierGenerator.Configuration().useGeometry().getGenerator()
.generateIdentifier(pointNoTags);
this.expectedException.expect(CoreException.class);
this.expectedException.expectMessage("Geometry must be set for entity");
new EntityIdentifierGenerator().generateIdentifier(pointNoGeometry);
}
@Test
public void testUnsetRelationMembersException()
{
final RelationBean bean1 = new RelationBean();
bean1.addItem(1L, "role", ItemType.POINT);
bean1.addItem(10L, "role", ItemType.AREA);
final CompleteRelation relationWithMembers = new CompleteRelation(1L,
Maps.hashMap("a", "b", "c", "d"), Rectangle.MINIMUM, bean1, null, null, null,
Sets.hashSet());
final CompleteRelation relationNoMembers = new CompleteRelation(1L,
Maps.hashMap("a", "b", "c", "d"), Rectangle.MINIMUM, null, null, null, null,
Sets.hashSet());
new EntityIdentifierGenerator.Configuration().useDefaults().getGenerator()
.generateIdentifier(relationWithMembers);
new EntityIdentifierGenerator.Configuration().useDefaults().excludeRelationMembers()
.getGenerator().generateIdentifier(relationNoMembers);
this.expectedException.expect(CoreException.class);
this.expectedException.expectMessage("Relation members must be set for entity");
new EntityIdentifierGenerator().generateIdentifier(relationNoMembers);
}
@Test
public void testUnsetTagsException()
{
final CompletePoint pointNoGeometry = new CompletePoint(1L, null,
Maps.hashMap("a", "b", "c", "d"), Sets.hashSet());
final CompletePoint pointNoTags = new CompletePoint(1L, Location.CENTER, null,
Sets.hashSet());
new EntityIdentifierGenerator.Configuration().useTags().getGenerator()
.generateIdentifier(pointNoGeometry);
new EntityIdentifierGenerator.Configuration().useGeometry().getGenerator()
.generateIdentifier(pointNoTags);
this.expectedException.expect(CoreException.class);
this.expectedException.expectMessage("Tags must be set for entity");
new EntityIdentifierGenerator().generateIdentifier(pointNoTags);
}
}
| 48.320675 | 179 | 0.681278 |
b1a1928a2f1fbcecf368d97dfddc7517225b26a2 | 161 | package floobits.common.protocol;
import java.io.Serializable;
public interface Base extends Serializable {
String name = null;
Integer req_id = 0;
}
| 16.1 | 44 | 0.73913 |
6a38fc19b44cea3d03ba9e3f44382b3849e8cfb2 | 2,843 | package eu.bcvsolutions.idm.core.bulk.action.impl.notification;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Description;
import org.springframework.stereotype.Component;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import eu.bcvsolutions.idm.core.api.bulk.action.AbstractRemoveBulkAction;
import eu.bcvsolutions.idm.core.api.bulk.action.dto.IdmBulkActionDto;
import eu.bcvsolutions.idm.core.api.domain.CoreResultCode;
import eu.bcvsolutions.idm.core.api.dto.DefaultResultModel;
import eu.bcvsolutions.idm.core.api.dto.ResultModels;
import eu.bcvsolutions.idm.core.api.service.ReadWriteDtoService;
import eu.bcvsolutions.idm.core.notification.api.dto.IdmNotificationTemplateDto;
import eu.bcvsolutions.idm.core.notification.api.dto.filter.IdmNotificationTemplateFilter;
import eu.bcvsolutions.idm.core.notification.api.service.IdmNotificationTemplateService;
import eu.bcvsolutions.idm.core.notification.domain.NotificationGroupPermission;
/**
* Delete given notification template
*
* @author Ondrej Husnik
* @since 10.6.0
*/
@Component(NotificationTemplateDeleteBulkAction.NAME)
@Description("Delete given notification template.")
public class NotificationTemplateDeleteBulkAction extends AbstractRemoveBulkAction<IdmNotificationTemplateDto, IdmNotificationTemplateFilter> {
public static final String NAME = "notification-template-delete-bulk-action";
@Autowired
private IdmNotificationTemplateService notificationService;
@Override
public String getName() {
return NAME;
}
@Override
protected List<String> getAuthoritiesForEntity() {
return Lists.newArrayList(NotificationGroupPermission.NOTIFICATIONTEMPLATE_DELETE);
}
@Override
public ReadWriteDtoService<IdmNotificationTemplateDto, IdmNotificationTemplateFilter> getService() {
return notificationService;
}
@Override
public ResultModels prevalidate() {
IdmBulkActionDto action = getAction();
List<UUID> entities = getEntities(action, new StringBuilder());
ResultModels results = new ResultModels();
IdmNotificationTemplateFilter templateFilter = new IdmNotificationTemplateFilter();
templateFilter.setUnmodifiable(Boolean.TRUE);
List<IdmNotificationTemplateDto> unmodifiable = notificationService.find(templateFilter, null).getContent();
List<IdmNotificationTemplateDto> templatesToWarn = unmodifiable.stream().filter(dto -> {
return entities.contains(dto.getId());
}).collect(Collectors.toList());
for (IdmNotificationTemplateDto item : templatesToWarn) {
results.addInfo(new DefaultResultModel(CoreResultCode.NOTIFICATION_SYSTEM_TEMPLATE_DELETE_FAILED,
ImmutableMap.of("template", item.getCode())));
}
return results;
}
}
| 37.906667 | 143 | 0.821667 |
f6a9a77f51e414a093fe9f03e5c7d3778f4479cf | 395 | package com.example.harrymuzart.myapplication14oct2017;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity1a7b extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity1a7b);
}
}
| 23.235294 | 61 | 0.746835 |
b385e98d8f459e1488b2641ec6bc35eee1e13600 | 3,466 | package de.tub.dima.babelfish.benchmark.string.queries;
import de.tub.dima.babelfish.conf.RuntimeConfiguration;
import de.tub.dima.babelfish.ir.lqp.LogicalOperator;
import de.tub.dima.babelfish.ir.lqp.Scan;
import de.tub.dima.babelfish.ir.lqp.Sink;
import de.tub.dima.babelfish.ir.lqp.relational.Projection;
import de.tub.dima.babelfish.ir.lqp.schema.FieldReference;
import de.tub.dima.babelfish.ir.lqp.udf.UDFOperator;
import de.tub.dima.babelfish.ir.lqp.udf.java.JavaDynamicUDFOperator;
import de.tub.dima.babelfish.ir.lqp.udf.java.dynamic.DynamicFilterFunction;
import de.tub.dima.babelfish.ir.lqp.udf.js.JavaScriptOperator;
import de.tub.dima.babelfish.ir.lqp.udf.js.JavaScriptUDF;
import de.tub.dima.babelfish.ir.lqp.udf.python.PythonOperator;
import de.tub.dima.babelfish.ir.lqp.udf.python.PythonUDF;
import de.tub.dima.babelfish.typesytem.record.DynamicRecord;
import de.tub.dima.babelfish.typesytem.variableLengthType.Text;
public class StringEqualsNative {
static DynamicFilterFunction stringEqualsUDF = new DynamicFilterFunction() {
@Override
public boolean filter(DynamicRecord record) {
String text = record.getString("o_orderpriority");
return text.equals("5-LOW");
}
};
public static LogicalOperator stringEqualsJava() {
Scan scan = new Scan("table.orders");
Projection projection = new Projection(new FieldReference("o_orderpriority", Text.class, 25));
scan.addChild(projection);
UDFOperator selection = new JavaDynamicUDFOperator(stringEqualsUDF);
projection.addChild(selection);
Sink sink = new Sink.MemorySink();
selection.addChild(sink);
return sink;
}
;
public static LogicalOperator stringEqualsPython() {
Scan scan = new Scan("table.orders");
Projection projection = new Projection(new FieldReference("o_orderpriority", Text.class, 25));
scan.addChild(projection);
PythonOperator selection = new PythonOperator(new PythonUDF("def udf(rec,ctx):\n" +
"\tif rec.o_orderpriority == \"5-LOW\":\n" +
"\t\tctx(rec)\n" +
"lambda rec,ctx: rec.o_orderpriority == \"5-LOW\""));
projection.addChild(selection);
Sink sink = new Sink.MemorySink();
selection.addChild(sink);
return sink;
}
;
public static LogicalOperator stringEqualsJavaScript() {
Scan scan = new Scan("table.orders");
Projection projection = new Projection(new FieldReference("o_orderpriority", Text.class, 25));
scan.addChild(projection);
JavaScriptOperator selection = new JavaScriptOperator(new JavaScriptUDF("(record,ctx)=>{" +
"return record.o_orderpriority == \"5-LOW\";\n" +
"}"));
projection.addChild(selection);
Sink sink = new Sink.MemorySink();
selection.addChild(sink);
return sink;
}
;
public static LogicalOperator getExecution(String language) {
RuntimeConfiguration.NAIVE_STRING_HANDLING = true;
switch (language) {
case "python":
return stringEqualsPython();
case "java":
return stringEqualsJava();
case "js":
return stringEqualsJavaScript();
}
throw new RuntimeException("Language: " + language + " not suported in " + StringEqualsNative.class.getClass().getName());
}
}
| 38.94382 | 130 | 0.672822 |
b927a0c6777205467d4a752fbb7b7763439a37f1 | 351 | package top.naccl.constant;
/**
* 上传文件相关常量
*
* @author: Naccl
* @date: 2022-01-23
*/
public class UploadConstants {
/**
* 评论中QQ头像存储方式-本地
*/
public static final String LOCAL = "local";
/**
* 评论中QQ头像存储方式-GitHub
*/
public static final String GITHUB = "github";
/**
* 图片ContentType
*/
public static final String IMAGE = "image";
}
| 15.26087 | 46 | 0.638177 |
2f0f5fbae2e48591c1a8d0d230f86af79a84c8a2 | 488 | package com.fangsf.easyjoke.hookactivity;
import android.content.Context;
/**
* Created by fangsf on 2018/8/15.
* Useful:
*/
public class PluginManager {
public static void install(Context context, String apkPath) {
// 把apk中的class 加载到 applicationClassLoader中
FixBugManager fixBugManager = new FixBugManager(context);
try {
fixBugManager.fixBug(apkPath);
} catch (Exception e) {
e.printStackTrace();
}
}
}
| 20.333333 | 66 | 0.641393 |
f722a5964a4506233bd8de832b4775276d709cec | 695 | package me.etki.grac.infrastructure;
import me.etki.grac.transport.Transport;
import me.etki.grac.transport.TransportRegistry;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* @author Etki {@literal <etki@etki.name>}
* @version %I%, %G%
* @since 0.1.0
*/
public class TransportRegistries {
public static TransportRegistry empty() {
return new TransportRegistry(Collections.emptyList());
}
public static TransportRegistry of(List<Transport> transports) {
return new TransportRegistry(transports);
}
public static TransportRegistry of(Transport... transports) {
return of(Arrays.asList(transports));
}
}
| 23.965517 | 68 | 0.713669 |
80ca7f4c1d88095f50a729338c41ce0ebdc4c55a | 3,238 | /**
* Copyright 2018 The Feign 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 reactivefeign;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import reactivefeign.testcase.IcecreamServiceApi;
import reactivefeign.testcase.domain.OrderGenerator;
import reactor.core.publisher.Mono;
import reactor.netty.DisposableServer;
import reactor.netty.http.server.HttpServer;
import java.time.Duration;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import static org.awaitility.Awaitility.waitAtMost;
import static org.hamcrest.CoreMatchers.is;
import static reactor.netty.http.HttpProtocol.H2C;
import static reactor.netty.http.HttpProtocol.HTTP11;
/**
* @author Sergii Karpenko
*/
abstract public class ReactivityTest extends BaseReactorTest {
public static final int DELAY_IN_MILLIS = 500;
public static final int CALLS_NUMBER = 500;
public static final int REACTIVE_GAIN_RATIO = 40;
abstract protected ReactiveFeignBuilder<IcecreamServiceApi> builder();
private static DisposableServer server;
@BeforeClass
public static void startServer() throws JsonProcessingException {
byte[] data = TestUtils.MAPPER.writeValueAsString(new OrderGenerator().generate(1)).getBytes();
server = HttpServer.create()
.protocol(HTTP11, H2C)
.route(r -> r.get("/icecream/orders/1",
(req, res) -> {
res.header("Content-Type", "application/json");
return Mono.delay(Duration.ofMillis(DELAY_IN_MILLIS))
.thenEmpty(res.sendByteArray(Mono.just(data)));
}))
.bindNow();
}
@AfterClass
public static void stopServer(){
server.disposeNow();
}
@Test
public void shouldRunReactively() throws JsonProcessingException {
IcecreamServiceApi client = builder()
.target(IcecreamServiceApi.class,
"http://localhost:" + server.port());
AtomicInteger counter = new AtomicInteger();
new Thread(() -> {
for (int i = 0; i < CALLS_NUMBER; i++) {
client.findFirstOrder().subscribeOn(testScheduler())
.doOnNext(order -> counter.incrementAndGet())
.subscribe();
}
}).start();
waitAtMost(timeToCompleteReactively(), TimeUnit.MILLISECONDS)
.untilAtomic(counter, is(CALLS_NUMBER));
}
public static int timeToCompleteReactively(){
return CALLS_NUMBER * DELAY_IN_MILLIS
/ (INSTALL_BLOCKHOUND
? (int)(REACTIVE_GAIN_RATIO / BLOCKHOUND_DEGRADATION)
: REACTIVE_GAIN_RATIO);
}
}
| 33.729167 | 100 | 0.699197 |
e2d77173455dded18d4e387882f6d49f08918e76 | 180 | package com.yoti.api.client.aml;
public interface AmlProfile {
String getGivenNames();
String getFamilyName();
String getSsn();
AmlAddress getAmlAddress();
}
| 12.857143 | 32 | 0.688889 |
73fe714d7c83ef24fbb451f746205523dc231438 | 3,545 | /**
* Copyright (C) 2017-2018 Credifix
*/
package com.byoskill.datafaker;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import com.byoskill.datafaker.annotations.Faker;
import com.byoskill.datafaker.configuration.FakerConfiguration;
import com.byoskill.datafaker.randomizers.Randomizer;
/**
* The Class FakerAnnotationProcessor is scanning the bean properties to guess
* how to randomize its data.
*/
public class FakerAnnotationProcessor {
private final Map<BeanPropertyKey, Randomizer> cachedRand = new HashMap<>();
private final RandomizerRegistry randomizerRegistry;
/**
* Instantiates a new faker annotation processor.
*
* @param configuration the configuration
*/
public FakerAnnotationProcessor(final FakerConfiguration configuration) {
super();
randomizerRegistry = new RandomizerRegistry(configuration);
}
/**
* Gets the randomizer for the given bean property.
*
* @param bean
* the bean
* @param propertyName
* the property name
* @return the randomizer
*/
public Optional<Randomizer> getRandomizer(final Object bean, final String propertyName) {
Validate.notNull(bean);
Validate.notEmpty(propertyName);
final BeanPropertyKey beanPropertyKey = BeanPropertyKey.of(bean, propertyName);
if (cachedRand.containsKey(beanPropertyKey)) {
return Optional.ofNullable(cachedRand.get(beanPropertyKey));
}
final Optional<Randomizer> randomizer = readRandomizerProperty(bean, propertyName, beanPropertyKey);
cachedRand.put(beanPropertyKey, randomizer.isPresent() ? randomizer.get() : null);
return randomizer;
}
/**
* Read randomizer property without access to the cache.
*
* @param bean
* the bean
* @param propertyName
* the property name
* @param beanPropertyKey
* the bean property key
* @return the optional
*/
public Optional<Randomizer> readRandomizerProperty(final Object bean, final String propertyName,
final BeanPropertyKey beanPropertyKey) {
if (randomizerRegistry.hasDedicatedRandomizerForThisType(bean.getClass())) {
return randomizerRegistry.findTypeRandomizer(bean.getClass());
}
if (randomizerRegistry.isTypeAnnotated(bean.getClass())) {
return randomizerRegistry.findAnnotationTypeRandomizer(bean.getClass());
}
if (FakerBeanUtils.isPropertyAnnotatedWithFaker(beanPropertyKey)) {
final Optional<Faker> annotation = FakerBeanUtils.findAnnotation(BeanPropertyKey.of(bean, propertyName),
Faker.class);
final String pickedRandomizer = annotation.get().value();
if (StringUtils.isNotBlank(pickedRandomizer)) {
final Optional<Randomizer> randomizerWithName = randomizerRegistry.getRandomizerWithName(pickedRandomizer);
if (randomizerWithName.isPresent()) {
return Optional.of(new FieldPropertyOverridenRandomizer(propertyName, pickedRandomizer, randomizerWithName.get()));
} else {
return Optional.empty();
}
} else {
return randomizerRegistry.guessRandomizerWithPropertyName(beanPropertyKey);
}
} else if (randomizerRegistry.isFieldAnnotated(beanPropertyKey)) {
return randomizerRegistry.getFieldAnnotation(beanPropertyKey);
} else if (FakerBeanUtils.isPojoAnnotatedWithFaker(bean)) {
return randomizerRegistry.guessRandomizerWithPropertyName(beanPropertyKey);
}
return Optional.empty();
}
}
| 35.09901 | 121 | 0.739633 |
94be6c1eaa31b7766982f554e5024993e2dbe394 | 1,677 | /*
* ScoringSchemeService.java
*
* Created on 07 July 2007, 00:20
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package org.pimslims.business.crystallization.service;
import java.util.Collection;
import org.pimslims.business.BaseService;
import org.pimslims.business.criteria.BusinessCriteria;
import org.pimslims.business.crystallization.model.ScoringScheme;
import org.pimslims.business.exception.BusinessException;
/**
*
* @author IMB
*/
public interface ScoringSchemeService extends BaseService {
/**
*
* @param id
* @return
* @throws org.pimslims.business.exception.BusinessException
*/
public ScoringScheme find(long id) throws BusinessException;
/**
*
* @param name
* @return
* @throws org.pimslims.business.exception.BusinessException
*/
public ScoringScheme findByName (String name) throws BusinessException;
/**
* Gets all the available scoring schemes
* @param paging
* @return
* @throws org.pimslims.business.exception.BusinessException
*/
public Collection<ScoringScheme> findAll(BusinessCriteria criteria) throws BusinessException;
/**
*
* @param scoringScheme
* @throws org.pimslims.business.exception.BusinessException
*/
public void create(ScoringScheme scoringScheme) throws BusinessException;
/**
*
* @param scoringScheme
* @throws org.pimslims.business.exception.BusinessException
*/
public void update(ScoringScheme scoringScheme) throws BusinessException;
}
| 27.95 | 98 | 0.683363 |
dc765ee29048e5445ce0f010db07cb2f35859d6f | 1,531 | /*
* Copyright (c) 2018 OCLC, Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the MIT/X11 license. The text of the license can be
* found at http://www.opensource.org/licenses/mit-license.php.
*/
package org.oclc.circill.toolkit.service.iso18626;
import org.oclc.circill.toolkit.service.base.ConfigurationException;
import org.oclc.circill.toolkit.service.base.SchemeValuePair;
import org.oclc.circill.toolkit.service.base.ToolkitInternalException;
/**
* The reason why the request cannot be filled unless it is modified or repeated at a future date.
*/
public class ReasonRetryType extends SchemeValuePair {
/**
* Construct a {@link ReasonRetryType}.
* @param scheme the Scheme URI
* @param value the value
*/
public ReasonRetryType(final String scheme, final String value) {
super(scheme, value);
}
/**
* Find the ReasonRetryType that matches the scheme & value strings supplied.
*
* @param scheme a String representing the Scheme URI.
* @param value a String representing the Value in the Scheme.
* @return a ReasonRetryType that matches, or null if none is found to match.
* @throws ConfigurationException -
* @throws ToolkitInternalException -
*/
public static ReasonRetryType find(final String scheme, final String value) throws ConfigurationException, ToolkitInternalException {
return (ReasonRetryType) find(scheme, value, ReasonRetryType.class);
}
}
| 36.452381 | 137 | 0.724363 |
7047e7882e69032f087b11900e8a0c9ce6ebb447 | 941 | /*
* alert-common
*
* Copyright (c) 2022 Synopsys, Inc.
*
* Use subject to the terms and conditions of the Synopsys End User Software License and Maintenance Agreement. All rights reserved worldwide.
*/
package com.synopsys.integration.alert.common.rest.api;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.synopsys.integration.alert.common.rest.model.AlertPagedModel;
public interface ReadPageController<P extends AlertPagedModel<?>> {
@GetMapping
P getPage(
@RequestParam(defaultValue = AlertPagedModel.DEFAULT_PAGE_NUMBER_STRING) Integer pageNumber,
@RequestParam(defaultValue = AlertPagedModel.DEFAULT_PAGE_SIZE_STRING) Integer pageSize,
@RequestParam(required = false) String searchTerm,
@RequestParam(required = false) String sortName,
@RequestParam(required = false) String sortOrder
);
}
| 36.192308 | 142 | 0.766206 |
6e24726fe2af7aaaff12363e185e2080483462a1 | 563 | private static String getScore(String str, int k) {
StringBuilder s = new StringBuilder();
int val = str.length() - k;
if (val % 2 == 1) {
for (int i = k; i < str.length(); i++) {
s.append(str.charAt(i));
}
for (int i = k - 1; i >= 0; i--) {
s.append(str.charAt(i));
}
} else {
for (int i = k; i < str.length(); i++) {
s.append(str.charAt(i));
}
for (int i = 0; i < k; i++) {
s.append(str.charAt(i));
}
}
return s.toString();
} | 28.15 | 51 | 0.428064 |
1569c0762dd2ceac4e53dae422e53c4569a89c58 | 3,544 | /*
* Copyright (C) 2013 The Minium 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 com.vilt.minium.impl;
import static java.lang.String.format;
import javax.annotation.Nullable;
import org.openqa.selenium.WebElement;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
import com.vilt.minium.WaitWebElements;
import com.vilt.minium.WebElementsDriver;
import com.vilt.minium.WebElementsDriverProvider;
public class WaitPredicates {
/**
* Predicate to use with {@link WaitWebElements#wait(Predicate)} methods which ensures that
* evaluation will only be successful when this instance is empty (that is, evaluates
* to zero {@link WebElement} instances).
*
* @param <T> the generic type
* @return predicate that returns true if it is empty
*/
public static <T extends WaitWebElements<?>> Predicate<T> whileNotEmpty() {
return new Predicate<T>() {
public boolean apply(T input) {
return Iterables.isEmpty(input);
}
@Override
public String toString() {
return "whileNotEmpty()";
}
};
}
/**
* Predicate to use with {@link WaitWebElements#wait(Predicate)} methods which ensures that
* evaluation will only be successful when this instance is not empty (that is, evaluates
* to one or more {@link WebElement} instances.
*
* @param <T> the generic type
* @return predicate that returns true if it is empty
*/
public static <T extends WaitWebElements<?>> Predicate<T> whileEmpty() {
return new Predicate<T>() {
public boolean apply(T input) {
return !Iterables.isEmpty(input);
}
@Override
public String toString() {
return "whileEmpty()";
}
};
}
/**
* Predicate to use with {@link WaitWebElements#wait(Predicate)} methods which ensures that
* evaluation will only be successful when this instance has a specific size.
*
* @param <T> the generic type
* @param size number of matched {@link WebElement} instances
* @return predicate that returns true if it has the exact size
*/
public static <T extends WaitWebElements<?>> Predicate<T> untilSize(final int size) {
return new Predicate<T>() {
public boolean apply(T input) {
return Iterables.size(input) == size;
}
@Override
public String toString() {
return format("untilSize(%d)", size);
}
};
}
/**
* Until window closed.
*
* @param <T> the generic type
* @return the predicate
*/
public static <T extends WaitWebElements<?>> Predicate<T> untilWindowClosed() {
return new Predicate<T>() {
private WebElementsDriver<?> webDriver;
@Override
public boolean apply(@Nullable T elems) {
WebElementsDriver<?> webDriver = getWebDriver(elems);
return webDriver.isClosed();
}
protected WebElementsDriver<?> getWebDriver(T elems) {
if (webDriver == null) {
webDriver = ((WebElementsDriverProvider<?>) elems).webDriver();
}
return webDriver;
}
@Override
public String toString() {
return "untilWindowClosed()";
}
};
}
}
| 28.352 | 92 | 0.69921 |
e9ce72e27db5260ca47e1b34fe95d5e1db46f102 | 1,366 | package com.sequenceiq.cloudbreak.converter;
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Component;
import com.sequenceiq.cloudbreak.controller.json.CredentialResponse;
import com.sequenceiq.cloudbreak.controller.validation.AWSCredentialParam;
import com.sequenceiq.cloudbreak.domain.AwsCredential;
import com.sequenceiq.cloudbreak.common.type.CloudPlatform;
@Component
public class AwsCredentialToJsonConverter extends AbstractConversionServiceAwareConverter<AwsCredential, CredentialResponse> {
@Override
public CredentialResponse convert(AwsCredential source) {
CredentialResponse credentialJson = new CredentialResponse();
credentialJson.setId(source.getId());
credentialJson.setCloudPlatform(CloudPlatform.AWS);
credentialJson.setName(source.getName());
credentialJson.setPublicInAccount(source.isPublicInAccount());
Map<String, Object> params = new HashMap<>();
params.put(AWSCredentialParam.ROLE_ARN.getName(), source.getRoleArn());
credentialJson.setParameters(params);
credentialJson.setDescription(source.getDescription() == null ? "" : source.getDescription());
credentialJson.setPublicKey(source.getPublicKey());
credentialJson.setLoginUserName(source.getLoginUserName());
return credentialJson;
}
}
| 44.064516 | 126 | 0.775256 |
fa5782d502b09c280938ac2770ff93d30f840f91 | 1,954 | package deepDriver.dl.aml.cnn;
import deepDriver.dl.aml.ann.IActivationFunction;
public class CNNBP4MaxPooling extends CNNBP {
public CNNBP4MaxPooling(CNNConfigurator cfg) {
super(cfg);
this.fv = new CNNFV4MaxPooling();
fv.bp = this;
}
public void bpSampling(SubSamplingKernal ck, IFeatureMap ffm, IFeatureMap t2fm, IActivationFunction acf,
boolean begin) {
SamplingFeatureMap sfm = (SamplingFeatureMap) t2fm;
FeatureMapTag [][] fmts = sfm.getFmts();
for (int i = 0; i < t2fm.getDeltaZzs().length; i++) {
for (int j = 0; j < t2fm.getDeltaZzs()[i].length; j++) {
if (begin) {
t2fm.getDeltaZzs()[i][j] = t2fm.getDeltaZzs()[i][j]
* acf.deActivate(t2fm.getzZs()[i][j]);
}
if (!ck.initB) {
ck.initB = true;
ck.deltab = cfg.getM() * ck.deltab - cfg.getL() * t2fm.getDeltaZzs()[i][j];
} else {
ck.deltab = ck.deltab - cfg.getL() * t2fm.getDeltaZzs()[i][j];
}
FeatureMapTag fmt = fmts[i][j];
int fr = i * ck.ckRows + fmt.getR();
int fc = j * ck.ckColumns + fmt.getC();
/*auto padding
* **/
if (fr >= ffm.getFeatures().length || fc >= ffm.getFeatures()[0].length) {
continue;
}/*auto padding
* **/
if (!ffm.getInitDeltaZzs()[fr][fc]) {
ffm.getInitDeltaZzs()[fr][fc] = true;
ffm.getDeltaZzs()[fr][fc] = t2fm.getDeltaZzs()[i][j] * ck.wW;
} else {
ffm.getDeltaZzs()[fr][fc] = ffm.getDeltaZzs()[fr][fc] +
t2fm.getDeltaZzs()[i][j] * ck.wW;
}
if (!ck.initwW) {
ck.initwW = true;
ck.deltawW = cfg.getM() * ck.deltawW
- cfg.getL() * t2fm.getDeltaZzs()[i][j] * ffm.getFeatures()[fr][fc];
} else {
ck.deltawW = ck.deltawW
- cfg.getL() * t2fm.getDeltaZzs()[i][j] * ffm.getFeatures()[fr][fc];
}
// double cs = 0;
// for (int j2 = 0; j2 < ck.ckRows; j2++) {
// for (int k = 0; k < ck.ckColumns; k++) {
//
// }
// }
}
}
}
}
| 28.735294 | 106 | 0.561924 |
d3bace2d92fa36fe4e189178789b25908b79c55e | 865 | import java.util.Scanner;
public class task1 {
public static void main (String[] args) {
System.out.println("Welcome to my first lab task in Java!");
System.out.println("--------------------------------------");
System.out.println("To find the distance I will need you to enter two points :)");
Scanner input = new Scanner(System.in);
System.out.println("Enter x1 and y1");
double x1 = input.nextDouble();
double y1 = input.nextDouble();
System.out.println("Enter x2 and y2");
double x2 = input.nextDouble();
double y2 = input.nextDouble();
double totalDistance = Math.pow((Math.pow((x2 - x1), 2) + Math.pow((y2 - y1), 2)), 0.5);
System.out.println("Distance within the point are:"+totalDistance);
}
} | 50.882353 | 100 | 0.546821 |
bbd0af44bac3faac70787f43c54947966d14c8ef | 5,353 | package br.com.tiagohs.popmovies.dragger.modules;
import br.com.tiagohs.popmovies.ui.contracts.GenresContract;
import br.com.tiagohs.popmovies.ui.contracts.ListMoviesDefaultContract;
import br.com.tiagohs.popmovies.ui.contracts.ListPersonsDefaultContract;
import br.com.tiagohs.popmovies.ui.contracts.LoginContract;
import br.com.tiagohs.popmovies.ui.contracts.MovieDetailsContract;
import br.com.tiagohs.popmovies.ui.contracts.MovieDetailsMidiaContract;
import br.com.tiagohs.popmovies.ui.contracts.MovieDetailsOverviewContract;
import br.com.tiagohs.popmovies.ui.contracts.PerfilContract;
import br.com.tiagohs.popmovies.ui.contracts.PerfilEstatisticasContract;
import br.com.tiagohs.popmovies.ui.contracts.PerfilFilmesContract;
import br.com.tiagohs.popmovies.ui.contracts.PersonDetailContract;
import br.com.tiagohs.popmovies.ui.contracts.SearchContract;
import br.com.tiagohs.popmovies.ui.contracts.VideosContract;
import br.com.tiagohs.popmovies.database.repository.MovieRepository;
import br.com.tiagohs.popmovies.database.repository.ProfileRepository;
import br.com.tiagohs.popmovies.ui.interceptor.GenresInterceptor;
import br.com.tiagohs.popmovies.ui.interceptor.ListMoviesDefaultInterceptor;
import br.com.tiagohs.popmovies.ui.interceptor.ListPersonsDefaultInterceptor;
import br.com.tiagohs.popmovies.ui.interceptor.LoginInterceptor;
import br.com.tiagohs.popmovies.ui.interceptor.MovieDetailsInterceptor;
import br.com.tiagohs.popmovies.ui.interceptor.MovieDetailsMidiaInterceptor;
import br.com.tiagohs.popmovies.ui.interceptor.MovieDetailsOverviewInterceptor;
import br.com.tiagohs.popmovies.ui.interceptor.PerfilEstatisticasInterceptor;
import br.com.tiagohs.popmovies.ui.interceptor.PerfilFilmesInterceptor;
import br.com.tiagohs.popmovies.ui.interceptor.PerfilInterceptor;
import br.com.tiagohs.popmovies.ui.interceptor.PersonDetailInterceptor;
import br.com.tiagohs.popmovies.ui.interceptor.SearchInterceptor;
import br.com.tiagohs.popmovies.ui.interceptor.VideoInterceptor;
import br.com.tiagohs.popmovies.server.methods.MoviesMethod;
import br.com.tiagohs.popmovies.server.methods.PersonsMethod;
import dagger.Module;
import dagger.Provides;
@Module
public class InterceptorModule {
@Provides
public ListMoviesDefaultContract.ListMoviesDefaultInterceptor providesListMoviesDefaultInterceptor(MoviesMethod moviesMethod, PersonsMethod personsMethod,
MovieRepository movieRepository, ProfileRepository profileRepository) {
return new ListMoviesDefaultInterceptor(moviesMethod, personsMethod, movieRepository, profileRepository);
}
@Provides
public GenresContract.GenresInterceptor providesGenresInterceptor(MoviesMethod moviesMethod) {
return new GenresInterceptor(moviesMethod);
}
@Provides
public ListPersonsDefaultContract.ListPersonsDefaultInterceptor providesListPersonsDefaultInterceptor(PersonsMethod personsMethod) {
return new ListPersonsDefaultInterceptor(personsMethod);
}
@Provides
public MovieDetailsMidiaContract.MovieDetailsMidiaInterceptor providesMovieDetailsMidiaInterceptor(MoviesMethod moviesMethod) {
return new MovieDetailsMidiaInterceptor(moviesMethod);
}
@Provides
public MovieDetailsOverviewContract.MovieDetailsOverviewInterceptor providesMovieDetailsOverviewInterceptor(MoviesMethod moviesMethod, MovieRepository movieRepository) {
return new MovieDetailsOverviewInterceptor(moviesMethod, movieRepository);
}
@Provides
public MovieDetailsContract.MovieDetailsInterceptor providesMovieDetailsInterceptor(MoviesMethod moviesMethod, MovieRepository movieRepository) {
return new MovieDetailsInterceptor(moviesMethod, movieRepository);
}
@Provides
public VideosContract.VideoInterceptor providesVideoInterceptor(MoviesMethod moviesMethod) {
return new VideoInterceptor(moviesMethod);
}
@Provides
public PerfilContract.PerfilInterceptor providesPerfilInterceptor(MoviesMethod moviesMethod, ProfileRepository profileRepository, MovieRepository movieRepository) {
return new PerfilInterceptor(moviesMethod, profileRepository, movieRepository);
}
@Provides
public PerfilEstatisticasContract.PerfilEstatisticasInterceptor providesPerfilEstatisticasInterceptor(ProfileRepository profileRepository) {
return new PerfilEstatisticasInterceptor(profileRepository);
}
@Provides
public PersonDetailContract.PersonDetailInterceptor providesPersonDetailInterceptor(PersonsMethod personsMethod) {
return new PersonDetailInterceptor(personsMethod);
}
@Provides
public SearchContract.SearchInterceptor providesSearchInterceptor(MoviesMethod moviesMethod, PersonsMethod personsMethod, MovieRepository movieRepository) {
return new SearchInterceptor(moviesMethod, personsMethod, movieRepository);
}
@Provides
public LoginContract.LoginInterceptor providesLoginInterceptor(ProfileRepository profileRepository) {
return new LoginInterceptor(profileRepository);
}
@Provides
public PerfilFilmesContract.PerfilFilmesInterceptor providesPerfilFilmesInterceptor(ProfileRepository profileRepository) {
return new PerfilFilmesInterceptor(profileRepository);
}
}
| 50.980952 | 174 | 0.819727 |
7a49f5b1206991b57cbc4826e00e4dcb6b917378 | 5,676 | package at.vintagestory.modelcreator.gui;
import javax.swing.Icon;
import javax.swing.ImageIcon;
public class Icons
{
public static Icon add;
public static Icon add_rollover;
public static Icon bin;
public static Icon bin_open;
public static Icon remove_rollover;
public static Icon new_;
public static Icon import_;
public static Icon export;
public static Icon texture;
public static Icon clear;
public static Icon copy;
public static Icon clipboard;
public static Icon transparent;
public static Icon coin;
public static Icon load;
public static Icon disk;
public static Icon disk_multiple;
public static Icon exit;
public static Icon cube;
public static Icon inout;
public static Icon rainbow;
public static Icon smallcube;
public static Icon smallcubegray;
public static Icon point;
public static Icon light_on;
public static Icon light_off;
public static Icon arrow_up;
public static Icon arrow_down;
public static Icon arrow_join;
public static Icon reload;
public static Icon keyboard;
public static Icon drink;
public static Icon arrow_up_x;
public static Icon arrow_down_x;
public static Icon arrow_up_y;
public static Icon arrow_down_y;
public static Icon arrow_up_z;
public static Icon arrow_down_z;
public static Icon facebook;
public static Icon twitter;
public static Icon reddit;
public static Icon imgur;
public static Icon planet_minecraft;
public static Icon minecraft_forum;
public static Icon github;
public static Icon model_cauldron;
public static Icon model_chair;
public static Icon play;
public static Icon pause;
public static Icon previous;
public static Icon next;
public static Icon addremove;
public static Icon left;
public static Icon right;
public static Icon weather_snow;
public static void init(Class<?> clazz)
{
ClassLoader loader = clazz.getClassLoader();
cube = new ImageIcon(loader.getResource("icons/cube.png"));
inout = new ImageIcon(loader.getResource("icons/arrow_inout.png"));
rainbow = new ImageIcon(loader.getResource("icons/rainbow.png"));
smallcube = new ImageIcon(loader.getResource("icons/smallcube.png"));
smallcubegray = new ImageIcon(loader.getResource("icons/smallcube-gray.png"));
point = new ImageIcon(loader.getResource("icons/point.png"));
bin = new ImageIcon(loader.getResource("icons/bin.png"));
bin_open = new ImageIcon(loader.getResource("icons/bin_open.png"));
add = new ImageIcon(loader.getResource("icons/add.png"));
add_rollover = new ImageIcon(loader.getResource("icons/add_rollover.png"));
new_ = new ImageIcon(loader.getResource("icons/new.png"));
import_ = new ImageIcon(loader.getResource("icons/import.png"));
export = new ImageIcon(loader.getResource("icons/export.png"));
texture = new ImageIcon(loader.getResource("icons/texture.png"));
clear = new ImageIcon(loader.getResource("icons/clear.png"));
copy = new ImageIcon(loader.getResource("icons/copy.png"));
clipboard = new ImageIcon(loader.getResource("icons/clipboard.png"));
transparent = new ImageIcon(loader.getResource("icons/transparent.png"));
coin = new ImageIcon(loader.getResource("icons/coin.png"));
load = new ImageIcon(loader.getResource("icons/load.png"));
disk = new ImageIcon(loader.getResource("icons/disk.png"));
disk_multiple = new ImageIcon(loader.getResource("icons/disk_multiple.png"));
exit = new ImageIcon(loader.getResource("icons/exit.png"));
reload = new ImageIcon(loader.getResource("icons/reload.png"));
keyboard = new ImageIcon(loader.getResource("icons/keyboard.png"));
drink = new ImageIcon(loader.getResource("icons/drink.png"));
light_on = new ImageIcon(loader.getResource("icons/box_off.png"));
light_off = new ImageIcon(loader.getResource("icons/box_on.png"));
arrow_up = new ImageIcon(loader.getResource("icons/arrow_up.png"));
arrow_down = new ImageIcon(loader.getResource("icons/arrow_down.png"));
arrow_join = new ImageIcon(loader.getResource("icons/arrow_join.png"));
arrow_up_x = new ImageIcon(loader.getResource("icons/arrow_up_x.png"));
arrow_down_x = new ImageIcon(loader.getResource("icons/arrow_down_x.png"));
arrow_up_y = new ImageIcon(loader.getResource("icons/arrow_up_y.png"));
arrow_down_y = new ImageIcon(loader.getResource("icons/arrow_down_y.png"));
arrow_up_z = new ImageIcon(loader.getResource("icons/arrow_up_z.png"));
arrow_down_z = new ImageIcon(loader.getResource("icons/arrow_down_z.png"));
play = new ImageIcon(loader.getResource("icons/play.png"));
pause = new ImageIcon(loader.getResource("icons/pause.png"));
previous = new ImageIcon(loader.getResource("icons/prev.png"));
next = new ImageIcon(loader.getResource("icons/next.png"));
left = new ImageIcon(loader.getResource("icons/move_left.png"));
right = new ImageIcon(loader.getResource("icons/move_right.png"));
addremove = new ImageIcon(loader.getResource("icons/addremove.png"));
facebook = new ImageIcon(loader.getResource("icons/facebook.png"));
twitter = new ImageIcon(loader.getResource("icons/twitter.png"));
reddit = new ImageIcon(loader.getResource("icons/reddit.png"));
imgur = new ImageIcon(loader.getResource("icons/imgur.png"));
planet_minecraft = new ImageIcon(loader.getResource("icons/planet_minecraft.png"));
minecraft_forum = new ImageIcon(loader.getResource("icons/minecraft_forum.png"));
github = new ImageIcon(loader.getResource("icons/github.png"));
model_cauldron = new ImageIcon(loader.getResource("icons/model_cauldron.png"));
model_chair = new ImageIcon(loader.getResource("icons/model_chair.png"));
weather_snow = new ImageIcon(loader.getResource("icons/weather_snow.png"));
}
}
| 39.971831 | 85 | 0.761452 |
32dcd8b4e50923fc94e255e329262178239245aa | 399 | package L19StringAndText;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Ex01ReverseString {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println(new StringBuilder(reader.readLine()).reverse().toString());
}
}
| 30.692308 | 86 | 0.756892 |
5775c03387c7bb22448b6a4bb6c37023cb3fbc79 | 4,025 | package com.congitive.test;
/*******************************************************************************
* Copyright (c) 2018 seanmuir.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* seanmuir - initial API and implementation
*
*******************************************************************************/
import static org.junit.Assert.assertTrue;
import org.hl7.fhir.r4.model.Observation;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import com.cognitive.nih.niddk.mccapi.MccApiApplication;
import com.cognitive.nih.niddk.mccapi.data.Acceptance;
import com.cognitive.nih.niddk.mccapi.data.GoalTarget;
import com.cognitive.nih.niddk.mccapi.data.MccGoal;
import com.cognitive.nih.niddk.mccapi.data.MccObservation;
import com.cognitive.nih.niddk.mccapi.data.primative.MccCodeableConcept;
import com.cognitive.nih.niddk.mccapi.data.primative.MccCoding;
import com.cognitive.nih.niddk.mccapi.data.primative.MccReference;
import com.cognitive.nih.niddk.mccapi.mappers.ObservationMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = MccApiApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT)
@TestPropertySource(properties = { "FHIR_SERVER=https://gw.interop.community/CarePlanningQA/open" })
public class TestCreateObervation {
@Autowired
private TestRestTemplate template;
@Test
public void testTransform() {
ObservationMapper om = new ObservationMapper();
MccObservation mccObservation = new MccObservation();
mccObservation.setCode(createMccCodeableConcept("obervation code"));
MccReference[] yy = new MccReference[1];
yy[0] = new MccReference();
yy[0].setDisplay("addressses");
mccObservation.setBasedOn(yy);
mccObservation.setStatus("final");
Observation observation = ObservationMapper.local2fhir("patientid",mccObservation );
}
private static MccCodeableConcept createMccCodeableConcept(String text) {
MccCodeableConcept description = new MccCodeableConcept();
description.setText(text);
MccCoding[] coding = new MccCoding[1];
coding[0] = new MccCoding();
coding[0].setDisplay(text);
description.setCoding(coding);
return description;
}
@Test
public void testCreateObservation() throws JsonProcessingException {
MccObservation mccObservation = new MccObservation();
// MccCodeableConcept code;
mccObservation.setCode(createMccCodeableConcept("obervation code"));
MccReference[] yy = new MccReference[1];
yy[0] = new MccReference();
yy[0].setDisplay("addressses");
mccObservation.setBasedOn(yy);
mccObservation.setStatus("final");
ResponseEntity<String> response = template.postForEntity("/createPROM?patientId=smart-1557780", mccObservation,
String.class);
assertTrue(response.getStatusCode().equals(HttpStatus.OK));
System.out.println(response.getBody());
}
@Test
public void testCreateGoalNulls() throws JsonProcessingException {
MccGoal mccGoal = new MccGoal();
mccGoal.setDescription(createMccCodeableConcept("description"));
mccGoal.setLifecycleStatus("proposed");
ResponseEntity<String> response = template.postForEntity("/creategoal?patientId=smart-1557780", mccGoal,
String.class);
assertTrue(response.getStatusCode().equals(HttpStatus.OK));
System.out.println(response.getBody());
}
} | 36.590909 | 113 | 0.759752 |
978de568b655bb31d447b6476f51a3c2785faeee | 8,086 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.digitaltwins.core;
import com.azure.core.credential.TokenCredential;
import com.azure.core.http.policy.HttpLogDetailLevel;
import com.azure.core.http.policy.HttpLogOptions;
import com.azure.core.http.rest.PagedFlux;
import com.azure.identity.ClientSecretCredentialBuilder;
import reactor.core.publisher.Mono;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
public class AsyncSample
{
public static void main(String[] args) throws InterruptedException
{
String tenantId = System.getenv("TENANT_ID");
String clientId = System.getenv("CLIENT_ID");
String clientSecret = System.getenv("CLIENT_SECRET");
String endpoint = System.getenv("DIGITAL_TWINS_ENDPOINT");
String sourceDigitalTwinId = System.getenv("SOURCE_DIGITAL_TWIN_ID");
String sourceDigitalTwin = System.getenv("SOURCE_DIGITAL_TWIN");
String targetDigitalTwinId = System.getenv("TARGET_DIGITAL_TWIN_ID");
String targetDigitalTwin = System.getenv("TARGET_DIGITAL_TWIN");
String relationshipId = System.getenv("RELATIONSHIP_ID");
String relationship = System.getenv("RELATIONSHIP");
TokenCredential tokenCredential = new ClientSecretCredentialBuilder()
.tenantId(tenantId)
.clientId(clientId)
.clientSecret(clientSecret)
.build();
DigitalTwinsAsyncClient client = new DigitalTwinsClientBuilder()
.tokenCredential(tokenCredential)
.endpoint(endpoint)
.httpLogOptions(
new HttpLogOptions()
.setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS))
.buildAsyncClient();
// Create the source and target twins
final Semaphore createTwinsSemaphore = new Semaphore(0);
// Create source digital twin
Mono<String> sourceTwin = client.createDigitalTwin(sourceDigitalTwinId, sourceDigitalTwin);
sourceTwin.subscribe(
result -> System.out.println("Created source twin: " + result),
throwable -> System.err.println("Failed to create source twin on digital twin with Id " + sourceDigitalTwinId + " due to error message " + throwable.getMessage()),
// Once the createRelationship operation has completed asynchronously, release the corresponding semaphore so that
// the thread that is subscribed to this method call can complete successfully.
createTwinsSemaphore::release); // This is an method reference call, which is the same as the following lambda expression: () -> createSemaphore.release()
// Create target digital twin
Mono<String> targetTwin = client.createDigitalTwin(targetDigitalTwinId, targetDigitalTwin);
targetTwin.subscribe(
result -> System.out.println("Created target twin: " + result),
throwable -> System.err.println("Failed to create target twin on digital twin with Id " + targetDigitalTwinId + " due to error message " + throwable.getMessage()),
// Once the createRelationship operation has completed asynchronously, release the corresponding semaphore so that
// the thread that is subscribed to this method call can complete successfully.
createTwinsSemaphore::release); // This is an method reference call, which is the same as the following lambda expression: () -> createSemaphore.release()
boolean created = createTwinsSemaphore.tryAcquire(2, 5, TimeUnit.SECONDS);
System.out.println("Source and target twins created: " + created);
// Create relationship on a digital twin
// Initialize a semaphore with no permits available. A permit must be released before this semaphore can be grabbed by a thread.
final Semaphore createSemaphore = new Semaphore(0);
Mono<String> createdRelationship = client.createRelationship(sourceDigitalTwinId, relationshipId, relationship);
// Once the async thread completes, the relationship created on the digital twin will be printed, or an error will be printed.
createdRelationship.subscribe(
result -> System.out.println("Created relationship: " + result),
throwable -> System.err.println("Failed to create relationship " + relationshipId + "on digital twin with Id " + sourceDigitalTwin + " due to error message " + throwable.getMessage()),
// Once the createRelationship operation has completed asynchronously, release the corresponding semaphore so that
// the thread that is subscribed to this method call can complete successfully.
createSemaphore::release); // This is an method reference call, which is the same as the following lambda expression: () -> createSemaphore.release()
// Wait for a maximum of 5secs to acquire the semaphore.
boolean createSuccessful = createSemaphore.tryAcquire(5, TimeUnit.SECONDS);
if (createSuccessful) {
System.out.println("Create operations completed successfully.");
} else {
System.out.println("Could not finish the create operations within the specified time.");
}
if (createSuccessful) {
// List all relationships on a digital twin
// Initialize a semaphore with no permits available. A permit must be released before this semaphore can be grabbed by a thread.
final Semaphore listSemaphore = new Semaphore(0);
PagedFlux<Object> relationships = client.listRelationships(sourceDigitalTwinId, relationshipId);
// Subscribe to process one relationship at a time
relationships
.subscribe(
item -> System.out.println("Relationship retrieved: " + item),
throwable -> System.err.println("Error occurred while retrieving relationship: " + throwable),
() -> {
System.out.println("Completed processing, all relationships have been retrieved.");
// Once the createRelationship operation has completed asynchronously, release the corresponding semaphore so that
// the thread that is subscribed to this API call can complete successfully.
listSemaphore.release();
});
// Subscribe to process one page at a time from the beginning
relationships
// You can also subscribe to pages by specifying the preferred page size or the associated continuation token to start the processing from.
.byPage()
.subscribe(
page -> {
System.out.println("Response headers status code is " + page.getStatusCode());
page.getValue().forEach(item -> System.out.println("Relationship retrieved: " + item));
},
throwable -> System.err.println("Error occurred while retrieving relationship: " + throwable),
() -> {
System.out.println("Completed processing, all relationships have been retrieved.");
// Once the createRelationship operation has completed asynchronously, release the corresponding semaphore so that
// the thread that is subscribed to this API call can complete successfully.
listSemaphore.release();
}
);
// Wait for a maximum of 5secs to acquire both the semaphores.
boolean listSuccessful = listSemaphore.tryAcquire(2, 5, TimeUnit.SECONDS);
if (listSuccessful) {
System.out.println("List operations completed successfully.");
} else {
System.out.println("Could not finish the list operations within the specified time.");
}
System.out.println("Done, exiting.");
}
}
}
| 56.152778 | 196 | 0.662379 |
62e082f67ac638621d60a985b6d3ce662a45c047 | 587 | package com.marklogic.appdeployer.cli;
import com.marklogic.appdeployer.command.Command;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class DeployCommand implements CommandArray {
private Map<String, List<Command>> commandMap;
public DeployCommand(Map<String, List<Command>> commandMap) {
this.commandMap = commandMap;
}
@Override
public Command[] getCommands() {
List<Command> list = new ArrayList<>();
for (String group : commandMap.keySet()) {
list.addAll(commandMap.get(group));
}
return list.toArray(new Command[]{});
}
}
| 22.576923 | 62 | 0.739353 |
1c060b8f2d20f457007428789da7a2293e486c0f | 3,773 | /*
* Testerra
*
* (C) 2020, Peter Lehmann, T-Systems Multimedia Solutions GmbH, Deutsche Telekom AG
*
* Deutsche Telekom AG and all other contributors /
* copyright owners license 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 eu.tsystems.mms.tic.testframework.utils;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Stream;
public final class ObjectUtils {
public static boolean isNull(Object... objects) {
for (Object object : objects) {
if (object == null) {
return true;
}
}
return false;
}
public static boolean oneOfTypes(Object value, Class... classes) {
Class<?> valueClass = value.getClass();
for (Class aClass : classes) {
if (aClass.isAssignableFrom(valueClass)) {
return true;
}
}
return false;
}
public static <T> T simpleProxy(Class<? extends T> iface, InvocationHandler handler, Class<?>...otherIfaces) {
Class<?>[] allInterfaces = Stream.concat(
Stream.of(iface),
Stream.of(otherIfaces))
.distinct()
.toArray(Class<?>[]::new);
return (T) Proxy.newProxyInstance(
iface.getClassLoader(),
allInterfaces,
handler);
}
public static <T> T simpleProxy(Class<? extends T> iface, T target, Class<? extends PassThroughProxy> handler, Class<?>...otherIfaces) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
InvocationHandler handlerInstance = handler.getConstructor(iface).newInstance(target);
return simpleProxy(iface, handlerInstance, otherIfaces);
}
public static abstract class PassThroughProxy<T> implements InvocationHandler {
protected final T target;
public PassThroughProxy(T target) {
this.target = target;
}
public Object invoke(Method method, Object[] args) throws Throwable {
try {
return method.invoke(target, args);
} catch (IllegalAccessException | IllegalArgumentException e) {
throw e;
} catch (InvocationTargetException e) {
throw e.getTargetException();
}
}
}
public static Class[] getAllInterfacesOf(Object o) {
List<Class> interfaces = new ArrayList<>();
interfaces.addAll(Arrays.asList(o.getClass().getInterfaces()));
Class<?> superclass = o.getClass().getSuperclass();
while (superclass != null) {
interfaces.addAll(Arrays.asList(superclass.getInterfaces()));
superclass = superclass.getSuperclass();
}
// remove duplicates
interfaces = new ArrayList<>(new HashSet<>(interfaces));
return interfaces.toArray(new Class[0]);
}
}
| 35.261682 | 245 | 0.625497 |
769093d1775954c87d82ab2a0f4d03ffe97217a6 | 1,089 | package it.polito.dp2.WF.sol1;
import it.polito.dp2.WF.ActionReader;
import it.polito.dp2.WF.ProcessReader;
import it.polito.dp2.WF.WorkflowReader;
import java.util.LinkedHashSet;
import java.util.Set;
public class WorkflowReaderImpl implements WorkflowReader {
private String name;
private Set<ActionReader> actionReaders;
private Set<ProcessReader> processReaders;
public WorkflowReaderImpl(String name) {
this.name = name;
this.actionReaders = new LinkedHashSet<>();
this.processReaders = new LinkedHashSet<>();
}
@Override
public String getName() {
return this.name;
}
@Override
public Set<ActionReader> getActions() {
return this.actionReaders;
}
@Override
public Set<ProcessReader> getProcesses() {
return this.processReaders;
}
@Override
public ActionReader getAction(String s) {
for (ActionReader reader : actionReaders) {
if (reader.getName().equals(s)) {
return reader;
}
}
return null;
}
}
| 23.673913 | 59 | 0.650138 |
51af4c8205ced8c4e80b9d0feedb6e528c767db3 | 10,446 | /*
* This file is part of dConomy.
*
* Copyright © 2011-2015 Visual Illusions Entertainment
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse
* or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package net.visualillusionsent.dconomy.data.wallet;
import net.visualillusionsent.dconomy.accounting.AccountingException;
import net.visualillusionsent.dconomy.accounting.wallet.UserWallet;
import net.visualillusionsent.dconomy.accounting.wallet.Wallet;
import net.visualillusionsent.dconomy.accounting.wallet.WalletHandler;
import net.visualillusionsent.dconomy.dCoBase;
import net.visualillusionsent.dconomy.data.DataLock;
import net.visualillusionsent.minecraft.plugin.util.Tools;
import net.visualillusionsent.utils.SystemUtils;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.List;
import java.util.UUID;
public final class WalletXMLSource extends WalletDataSource {
private final DataLock lock = new DataLock();
private final Format xmlform = Format.getPrettyFormat().setExpandEmptyElements(false).setOmitDeclaration(true).setOmitEncoding(true).setLineSeparator(SystemUtils.LINE_SEP);
private final XMLOutputter outputter = new XMLOutputter(xmlform);
private final SAXBuilder builder = new SAXBuilder();
private final String wallet_Path = dCoBase.getProperties().getConfigurationDirectory().concat("wallets.xml");
private FileWriter writer;
private Document doc;
public WalletXMLSource(WalletHandler wallet_handler) {
super(wallet_handler);
}
@Override
public final boolean load() {
dCoBase.info("Loading Wallets...");
synchronized (lock) {
File walletFile = new File(wallet_Path);
Exception ex = null;
int load = 0;
if (!walletFile.exists()) {
dCoBase.info("Wallets file not found. Creating...");
Element wallets = new Element("wallets");
doc = new Document(wallets);
try {
writer = new FileWriter(wallet_Path);
outputter.output(doc, writer);
}
catch (IOException e) {
ex = e;
}
finally {
try {
if (writer != null) {
writer.close();
}
}
catch (IOException e) {
dCoBase.warning("Failure closing Wallets writer...");
}
if (ex != null) {
dCoBase.severe("Failed to create new Wallets file...");
dCoBase.stacktrace(ex);
}
}
if (ex != null) {
return false;
}
}
else {
try {
if (doc == null) {
doc = builder.build(walletFile);
}
Element root = doc.getRootElement();
List<Element> wallets = root.getChildren();
for (Element wallet : wallets) {
String owner = wallet.getAttributeValue("owner");
UUID ownerUUID;
if (Tools.isUserName(owner)) {
ownerUUID = dCoBase.getServer().getUUIDFromName(owner);
wallet.detach(); // Remove the old account
}
else {
ownerUUID = UUID.fromString(owner);
}
wallet_handler.addWallet(new UserWallet(ownerUUID, wallet.getAttribute("balance").getDoubleValue(), wallet.getAttribute("lockedOut").getBooleanValue(), this));
load++;
}
}
catch (JDOMException jdomex) {
dCoBase.severe("JDOM Exception while parsing Wallets file...");
dCoBase.stacktrace(jdomex);
return false;
}
catch (IOException ioex) {
dCoBase.severe("Input/Output Exception while parsing Wallets file...");
dCoBase.stacktrace(ioex);
return false;
}
}
dCoBase.info(String.format("Loaded %d Wallets...", load));
}
return true;
}
@Override
public final boolean saveAccount(Wallet account) {
boolean success = true;
synchronized (lock) {
File walletFile = new File(wallet_Path);
try {
if (doc == null) {
doc = builder.build(walletFile);
}
Element root = doc.getRootElement();
List<Element> wallets = root.getChildren();
boolean found = false;
for (Element wallet : wallets) {
String name = wallet.getAttributeValue("owner");
if (name.equals(account.getOwner().toString())) {
wallet.getAttribute("balance").setValue(MessageFormat.format("{0,number,#.00}", account.getBalance()));
wallet.getAttribute("lockedOut").setValue(String.valueOf(account.isLocked()));
found = true;
break;
}
}
if (!found) {
Element newWallet = new Element("wallet");
newWallet.setAttribute("owner", account.getOwner().toString());
newWallet.setAttribute("balance", MessageFormat.format("{0,number,#.00}", account.getBalance()));
newWallet.setAttribute("lockedOut", String.valueOf(account.isLocked()));
root.addContent(newWallet);
}
try {
writer = new FileWriter(walletFile);
outputter.output(root, writer);
}
catch (IOException ex) {
dCoBase.severe("Failed to write to Wallets file...");
dCoBase.stacktrace(ex);
success = false;
}
finally {
try {
if (writer != null) {
writer.close();
}
}
catch (IOException e) {
//
}
}
}
catch (JDOMException jdomex) {
dCoBase.severe("JDOM Exception while trying to save wallet for User:" + account.getOwner());
dCoBase.stacktrace(jdomex);
success = false;
}
catch (IOException ioex) {
dCoBase.severe("Input/Output Exception while trying to save wallet for User:" + account.getOwner());
dCoBase.stacktrace(ioex);
success = false;
}
}
return success;
}
@Override
public final boolean reloadAccount(Wallet account) {
boolean success = true;
synchronized (lock) {
File walletFile = new File(wallet_Path);
try {
doc = builder.build(walletFile);
Element root = doc.getRootElement();
List<Element> wallets = root.getChildren();
for (Element wallet : wallets) {
String name = wallet.getAttributeValue("owner");
if (name.equals(account.getOwner().toString())) {
account.setBalance(wallet.getAttribute("balance").getDoubleValue());
account.setLockOut(wallet.getAttribute("lockedOut").getBooleanValue());
break;
}
}
}
catch (JDOMException jdomex) {
dCoBase.severe("JDOM Exception while trying to reload wallet for User:" + account.getOwner());
dCoBase.stacktrace(jdomex);
success = false;
}
catch (IOException ioex) {
dCoBase.severe("Input/Output Exception while trying to reload wallet for User:" + account.getOwner());
dCoBase.stacktrace(ioex);
success = false;
}
catch (AccountingException aex) {
dCoBase.severe("Accounting Exception while trying to reload wallet for User:" + account.getOwner());
dCoBase.stacktrace(aex);
success = false;
}
}
return success;
}
}
| 43.890756 | 183 | 0.551886 |
3173685250011f2f573b9a984d83f9074826782a | 32,774 | package at.fhtw.mcs.controller;
import static at.fhtw.mcs.util.NullSafety.emptyListIfNull;
import static java.util.Comparator.comparing;
import java.awt.Desktop;
import java.awt.Desktop.Action;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.ResourceBundle;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.Line;
import javax.sound.sampled.Mixer;
import javax.xml.bind.JAXBException;
import org.controlsfx.control.RangeSlider;
import at.fhtw.mcs.model.Format;
import at.fhtw.mcs.model.Project;
import at.fhtw.mcs.model.Track;
import at.fhtw.mcs.ui.LocalizedAlertBuilder;
import at.fhtw.mcs.ui.ProgressOverlay;
import at.fhtw.mcs.util.AudioOuput;
import at.fhtw.mcs.util.TrackFactory;
import at.fhtw.mcs.util.TrackFactory.UnsupportedFormatException;
import at.fhtw.mcs.util.VersionCompare;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.chart.LineChart;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonBar;
import javafx.scene.control.ButtonBar.ButtonData;
import javafx.scene.control.ButtonType;
import javafx.scene.control.CheckMenuItem;
import javafx.scene.control.Menu;
import javafx.scene.control.MenuItem;
import javafx.scene.control.ProgressBar;
import javafx.scene.control.RadioButton;
import javafx.scene.control.RadioMenuItem;
import javafx.scene.control.ScrollPane;
import javafx.scene.control.Slider;
import javafx.scene.control.Toggle;
import javafx.scene.control.ToggleGroup;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.input.KeyCombination;
import javafx.scene.layout.Region;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.shape.Rectangle;
import javafx.scene.text.Text;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
/**
* Controller class for Root.fxml
*/
public class RootController implements Initializable {
/*
* Where to move those? ResourceBundles?
*/
private static final String ICON_PAUSE = "||";
private static final String ICON_PLAY = "\u25B6";
private static final String URL_MANUAL = "https://github.com/flpa/mcs/wiki";
@FXML
private StackPane stackPaneRoot;
@FXML
private VBox vboxTracks;
@FXML
private CheckMenuItem checkMenuItemSyncronizeStartPoints;
@FXML
private CheckMenuItem checkMenuItemLoopPlayback;
@FXML
private Menu menuOutputDevices;
@FXML
private MenuItem menuItemQuit;
@FXML
private MenuItem menuItemNewProject;
@FXML
private MenuItem menuItemOpenProject;
@FXML
private MenuItem menuItemSaveProject;
@FXML
private MenuItem menuItemSaveProjectAs;
@FXML
private MenuItem menuItemCloseProject;
@FXML
private MenuItem menuItemAddTracks;
@FXML
private MenuItem menuItemManual;
@FXML
private MenuItem menuItemAbout;
@FXML
private Button buttonPlayPause;
@FXML
private Button buttonStop;
@FXML
private Button buttonAddTracks;
@FXML
private Text textCurrentTime;
@FXML
private Text textTotalTime;
@FXML
private ProgressBar progressBarTime;
@FXML
private Slider sliderProgressBarTime;
@FXML
private ScrollPane scrollPaneTracks;
@FXML
private Rectangle rectangleSpacer;
@FXML
private Slider sliderMasterVolume;
@FXML
private RangeSlider rangesliderLoop;
private ToggleGroup toggleGroupActiveTrack = new ToggleGroup();
private ResourceBundle bundle;
private Stage stage;
private FileChooser fileChooser = new FileChooser();
private ProgressOverlay progressOverlay;
private List<TrackController> trackControllers = new ArrayList<>();
private List<List<Button>> moveButtonList = new ArrayList<>();
private List<Button> deleteButtonList = new ArrayList<>();
private List<LineChart<Number, Number>> lineChartList = new ArrayList<>();
// TODO: could be a configuration parameter?
private long updateFrequencyMs = 100;
private int longestTrackFrameLength;
private long longestTrackMicrosecondsLength;
private Project project;
private Boolean startOfProject = true;
private Boolean loopActive = false;
Boolean trackChanged = false;
int trackChangedChecker = 0;
public RootController(Stage stage) {
this.stage = stage;
stage.setOnCloseRequest(event -> {
if (handleUnsavedChanges() == false) {
event.consume();
}
});
}
@Override
public void initialize(URL viewSource, ResourceBundle translations) {
this.bundle = translations;
FileChooser.ExtensionFilter filter = new FileChooser.ExtensionFilter(
bundle.getString("fileChooser.addTrack.filterText"), "*.mp3", "*.wav", "*.wave", "*.aif", "*.aiff");
fileChooser.getExtensionFilters().add(filter);
VersionCompare versionCompare = new VersionCompare(bundle);
(new Thread(versionCompare)).start();
startUpDialog();
startOfProject = false;
menuItemQuit.setOnAction(e -> afterUnsavedChangesAreHandledDo(Platform::exit));
menuItemNewProject.setOnAction(e -> afterUnsavedChangesAreHandledDo(this::newProject));
menuItemOpenProject.setOnAction(e -> afterUnsavedChangesAreHandledDo(this::openProject));
menuItemSaveProject.setOnAction(e -> this.save());
menuItemSaveProject.setAccelerator(new KeyCodeCombination(KeyCode.S, KeyCombination.SHORTCUT_DOWN));
menuItemSaveProjectAs.setOnAction(e -> this.saveAs());
menuItemCloseProject.setOnAction(e -> afterUnsavedChangesAreHandledDo(this::closeProject));
menuItemAddTracks.setOnAction(this::handleAddTracks);
menuItemAbout.setOnAction(this::handleAbout);
menuItemManual.setOnAction(this::handleManual);
// TODO: inline lambdas vs methods?
buttonPlayPause.setOnAction(e -> {
getSelectedTrack().ifPresent(Track::togglePlayPause);
buttonPlayPause.setText(ICON_PLAY.equals(buttonPlayPause.getText()) ? ICON_PAUSE : ICON_PLAY);
});
buttonStop.setOnAction(this::handleStop);
buttonAddTracks.setOnAction(this::handleAddTracks);
sliderMasterVolume.setMax(1);
sliderMasterVolume.setMin(0);
// TODO: check if Volume changes if you alter the value with clicking
// instead of dragging
sliderMasterVolume.valueProperty()
.addListener((observable, oldValue, newValue) -> project.setMasterLevel((double) newValue));
checkMenuItemSyncronizeStartPoints.selectedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
project.setSynchronizeStartPoints(newValue);
for (TrackController trackController : trackControllers) {
trackController.drawTrack();
}
}
});
checkMenuItemLoopPlayback.selectedProperty().addListener(new ChangeListener<Boolean>() {
@Override
public void changed(ObservableValue<? extends Boolean> observable, Boolean oldValue, Boolean newValue) {
toggleLoopActive();
project.setLoopActivated(newValue);
}
});
ToggleGroup toggleGroupOutputDevice = new ToggleGroup();
// @formatter:off
Arrays.stream(AudioSystem.getMixerInfo()).filter(RootController::isOutputMixerInfo).forEach(info -> {
RadioMenuItem radio = new RadioMenuItem();
radio.setText(String.format("%s (%s)", info.getName(), info.getDescription()));
radio.setUserData(info);
radio.setToggleGroup(toggleGroupOutputDevice);
radio.setSelected(info.equals(AudioOuput.getSelectedMixerInfo()));
menuOutputDevices.getItems().add(radio);
});
// @formatter:on
toggleGroupOutputDevice.selectedToggleProperty().addListener(new ChangeListener<Toggle>() {
public void changed(ObservableValue<? extends Toggle> value, Toggle previousSelection,
Toggle newSelection) {
/*
* When modifying grouped RadioMenuItems, this is invoked twice:
* 1) oldValue and null 2) null and newValue
*/
if (newSelection != null) {
AudioOuput.setSelectedMixerInfo((Mixer.Info) newSelection.getUserData());
project.getTracks().forEach(Track::reload);
}
}
});
toggleGroupActiveTrack.selectedToggleProperty().addListener(new ChangeListener<Toggle>() {
public void changed(ObservableValue<? extends Toggle> value, Toggle previousSelection,
Toggle newSelection) {
long currentMs = 0;
boolean wasPlaying = false;
trackChanged = true;
if (previousSelection != null) {
Track prevTrack = getToggleTrack(previousSelection);
wasPlaying = prevTrack.isPlaying();
prevTrack.pause();
currentMs = prevTrack.getCurrentMicroseconds();
}
if (newSelection != null) {
Track newTrack = getToggleTrack(newSelection);
newTrack.setCurrentMicroseconds(currentMs);
if (wasPlaying) {
newTrack.play();
}
}
setStylesheetsForTracks();
}
});
/*
* Start the update thread here to prevent multiple threads when adding
* a track, deleting it, adding a track [...]
*/
startTimeUpdateThread();
// Eventlistener to change the Playbackpoint
// TODO fix bug, where timeline is set back when switching between
// tracks
sliderProgressBarTime.valueProperty().addListener(new ChangeListener<Number>() {
@Override
public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
if ((double) newValue - (double) oldValue > 2_500_000 || (double) newValue - (double) oldValue < 0) {
if (!trackChanged) {
for (Track track : project.getTracks()) {
long temp = Math.round((double) newValue);
track.setCurrentMicroseconds(temp + 250000);
// System.out.println("valuechange: " + newValue +
// ":" + oldValue);
}
}
}
}
});
progressOverlay = new ProgressOverlay(this.stackPaneRoot, bundle.getString("label.addTracks.progress"));
/*
* Loopslider and Line initialisation
*/
rangesliderLoop.setLowValue(rangesliderLoop.getMin());
rangesliderLoop.setHighValue(rangesliderLoop.getMax());
toggleLoopActive();
rangesliderLoop.lowValueProperty()
.addListener((observable, oldValue, newValue) -> project.setLoopLowValue((double) newValue));
rangesliderLoop.highValueProperty()
.addListener((observable, oldValue, newValue) -> project.setLoopHighValue((double) newValue));
}
private void startUpDialog() {
LocalizedAlertBuilder builder = new LocalizedAlertBuilder(bundle, "alert.OpenOrNew.", AlertType.CONFIRMATION);
ButtonType newProject = new ButtonType(bundle.getString("alert.OpenOrNew.button.new"), ButtonData.YES);
ButtonType openProject = new ButtonType(bundle.getString("alert.OpenOrNew.button.open"), ButtonData.OTHER);
ButtonType closeProject = new ButtonType(bundle.getString("alert.OpenOrNew.button.cancel"), ButtonData.NO);
builder.setButtons(closeProject, openProject, newProject);
Alert alertOpenOrNew = builder.build();
for (Node node : alertOpenOrNew.getDialogPane().getChildren()) {
if (node instanceof ButtonBar) {
((ButtonBar) node).setButtonOrder("NYU");
}
}
Optional<ButtonType> result = alertOpenOrNew.showAndWait();
if (!result.isPresent()) {
Platform.exit();
} else {
if (result.get().equals(newProject)) {
newProject();
} else if (result.get().equals(openProject)) {
openProject();
} else {
Platform.exit();
}
}
}
private void afterUnsavedChangesAreHandledDo(Runnable callback) {
if (handleUnsavedChanges()) {
callback.run();
}
}
private boolean handleUnsavedChanges() {
return project.hasUnsavedChanges() == false || letUserHandleUnsavedChanges();
}
private boolean letUserHandleUnsavedChanges() {
// ButtonData.YES means this is our default button
ButtonType save = new ButtonType(bundle.getString("alert.unsavedChanges.button.save"), ButtonData.YES);
ButtonType proceedWithoutSaving = new ButtonType(
bundle.getString("alert.unsavedChanges.button.proceedWithoutSaving"));
LocalizedAlertBuilder builder = new LocalizedAlertBuilder(bundle, "alert.unsavedChanges.",
AlertType.CONFIRMATION);
builder.setButtons(proceedWithoutSaving, ButtonType.CANCEL, save);
builder.setHeaderFormatParameters(getProjectName());
Optional<ButtonType> result = builder.build().showAndWait();
return result.isPresent() && (result.get() == proceedWithoutSaving || (result.get() == save && save()));
}
private String getProjectName() {
String name = project.getName();
return name == null ? bundle.getString("project.unnamed") : name;
}
private boolean save() {
if (project.getDirectory() == null) {
return saveAs();
}
return saveAndCatchErrors();
}
private boolean saveAs() {
Optional<File> directory = letUserChooseProjectDirectory();
if (directory.isPresent()) {
project.setDirectory(directory.get());
return saveAndCatchErrors();
}
return false;
}
private Optional<File> letUserChooseProjectDirectory() {
DirectoryChooser directoryChooser = new DirectoryChooser();
return Optional.ofNullable(directoryChooser.showDialog(stage));
}
private boolean saveAndCatchErrors() {
boolean success = false;
try {
project.save();
updateApplicationTitle();
success = true;
} catch (IOException e) {
handleSaveError(e);
}
return success;
}
private void handleSaveError(IOException e) {
e.printStackTrace();
new LocalizedAlertBuilder(bundle, "alert.saveFailed.", AlertType.ERROR).build().showAndWait();
}
private void newProject() {
setProject(new Project());
FileChooser fileChooser = new FileChooser();
File f = fileChooser.showSaveDialog(stage);
if (f != null) {
project.setDirectory(f);
save();
} else if (startOfProject) {
startUpDialog();
}
}
private void setProject(Project project) {
removeAllTracks();
this.project = project;
updateApplicationTitle();
loadTrackUis(project.getTracks());
sliderMasterVolume.setValue(project.getMasterLevel());
checkMenuItemSyncronizeStartPoints.setSelected(project.isSynchronizeStartPoints());
rangesliderLoop.setLowValue(project.getLoopLowValue());
rangesliderLoop.setHighValue(project.getLoopHighValue());
rangesliderLoop.setMax(project.getLoopMaxValue());
rangesliderLoop.setMin(project.getLoopMinValue());
checkMenuItemLoopPlayback.setSelected(project.isLoopActivated());
project.unsavedChangesProperty().addListener((observable, oldValue, newValue) -> this.updateApplicationTitle());
}
private void removeAllTracks() {
if (this.project != null) {
int trackCount = this.project.getTracks().size();
for (int i = 0; i < trackCount; i++) {
// removing first track until all have been removed
removeTrack(0);
}
}
}
private void openProject() {
Optional<File> chosenDirectory = letUserChooseProjectDirectory();
if (chosenDirectory.isPresent()) {
try {
setProject(Project.load(chosenDirectory.get()));
} catch (FileNotFoundException | JAXBException e) {
handleOpenError(e);
openProject();
}
} else if (startOfProject) {
startUpDialog();
}
}
private void handleOpenError(Exception e) {
e.printStackTrace();
LocalizedAlertBuilder builder = new LocalizedAlertBuilder(bundle, "alert.loadFailed.", AlertType.ERROR);
builder.setContentKey(e instanceof FileNotFoundException ? "content.loadError" : "content.parseError");
builder.build().showAndWait();
}
private void closeProject() {
startOfProject = true;
startUpDialog();
}
private void updateApplicationTitle() {
String format = MessageFormat.format(bundle.getString("app.title") + "{1}", getProjectName(),
project.hasUnsavedChanges() ? "*" : "");
Platform.runLater(() -> stage.setTitle(format));
}
private static boolean isOutputMixerInfo(Mixer.Info info) {
return AudioSystem.getMixer(info).isLineSupported(new Line.Info(Clip.class));
}
private Optional<Track> getSelectedTrack() {
Toggle selectedToggle = toggleGroupActiveTrack.getSelectedToggle();
if (selectedToggle == null) {
return Optional.empty();
}
return Optional.of(getToggleTrack(selectedToggle));
}
private void updateTime() {
Optional<Track> selectedTrack = getSelectedTrack();
if (selectedTrack.isPresent() == false) {
return;
}
if (trackChanged && trackChangedChecker > 10) {
trackChanged = false;
trackChangedChecker = 0;
} else if (trackChanged) {
trackChangedChecker++;
}
Track currentTrack = selectedTrack.get();
long currentMicroseconds = currentTrack.getCurrentMicroseconds();
double progress = (double) currentMicroseconds / longestTrackMicrosecondsLength;
boolean currentTrackHasEnded = currentTrack.getTotalMicroseconds() == currentMicroseconds;
/*
* Disable tracks with a length shorter than the current position. Also
* enables them again after resetting via stop.
*/
for (Toggle toggle : toggleGroupActiveTrack.getToggles()) {
RadioButton radio = (RadioButton) toggle;
Track track = getToggleTrack(toggle);
radio.setDisable(track != currentTrack && currentMicroseconds > track.getTotalMicroseconds());
}
/*
* This seems to ensure that the actual update is done on the Java FX
* thread. Trying to update GUI components from another thrßead can lead
* to IllegalStateExceptions.
*/
Platform.runLater(() -> {
progressBarTime.setProgress(progress);
sliderProgressBarTime.setValue(currentMicroseconds - 250000);
textCurrentTime.setText(formatTimeString(currentMicroseconds));
if (loopActive) {
if (sliderProgressBarTime.getValue() > rangesliderLoop.getHighValue()) {
sliderProgressBarTime.setValue(rangesliderLoop.getLowValue());
}
if (sliderProgressBarTime.getValue() < rangesliderLoop.getLowValue()) {
sliderProgressBarTime.setValue(rangesliderLoop.getLowValue());
}
}
if (currentTrackHasEnded) {
buttonPlayPause.setText(ICON_PLAY);
}
});
}
private void handleAddTracks(ActionEvent event) {
List<File> files = emptyListIfNull(fileChooser.showOpenMultipleDialog(stage));
addFiles(files);
if (files.isEmpty() == false) {
fileChooser.setInitialDirectory(files.get(files.size() - 1).getParentFile());
}
}
public void addFiles(File... files) {
addFiles(Arrays.asList(files));
}
public void addFiles(List<File> files) {
if (files.isEmpty()) {
return;
}
progressOverlay.show();
new Thread(() -> {
try {
files.forEach(this::addFile);
} finally {
Platform.runLater(progressOverlay::hide);
}
}).start();
}
private void addFile(File file) {
Track track;
try {
track = TrackFactory.loadTrack(file.getAbsolutePath(), project.getDirectory().toString());
} catch (UnsupportedFormatException e) {
Platform.runLater(() -> {
this.showErrorUnsupportedFormat(e.getFormat(), e.getAudioFormat());
});
return;
} catch (OutOfMemoryError e) {
Platform.runLater(this::showErrorOutOfMemory);
return;
}
if (checkMenuItemSyncronizeStartPoints.isSelected()) {
track.applyStartPointOffset();
}
/*
* Needs to be added before drawing so that the longest track can be
* determined.
*/
project.addTrack(track);
loadTrackUis(Arrays.asList(track));
}
private void loadTrackUis(List<Track> tracks) {
Platform.runLater(() -> {
determineLongestTrackLengths();
for (Track track : tracks) {
loadTrackUi(track);
}
setPlaybackControlsDisable(tracks.isEmpty());
addButtonsAndChart();
project.setLoudnessLevel();
// setMoveButtons();
setButtonsEventHandler();
setLineChartEventHandler();
setStylesheetsForTracks();
});
}
public void setPlaybackControlsDisable(boolean disable) {
buttonPlayPause.setDisable(disable);
buttonStop.setDisable(disable);
}
public void determineLongestTrackLengths() {
if (project.getTracks().isEmpty()) {
return;
}
Track longestTrack = project.getTracks().stream().max(comparing(Track::getTotalMicroseconds)).get();
longestTrackFrameLength = longestTrack.getLengthWeighted();
longestTrackMicrosecondsLength = longestTrack.getTotalMicroseconds();
trackControllers.forEach(controller -> controller.setLongestTrackFrameLength(longestTrackFrameLength));
String timeString = formatTimeString(longestTrackMicrosecondsLength);
textTotalTime.setText(timeString);
// Set the Slider to the same length as the Progressbar
sliderProgressBarTime.setMin(0);
sliderProgressBarTime.setMax(longestTrackMicrosecondsLength - 250000);
rangesliderLoop.setMin(0);
rangesliderLoop.setMax(longestTrackMicrosecondsLength - 250000);
project.setLoopMinValue(0);
project.setLoopMaxValue(longestTrackMicrosecondsLength - 250000);
rangesliderLoop.setLowValue(project.getLoopLowValue());
if (project.getLoopHighValue() == 0) {
rangesliderLoop.setHighValue(longestTrackMicrosecondsLength - 250000);
} else {
rangesliderLoop.setHighValue(project.getLoopHighValue());
}
}
private void loadTrackUi(Track track) {
FXMLLoader loader = new FXMLLoader();
loader.setController(new TrackController(track, toggleGroupActiveTrack, longestTrackFrameLength));
loader.setLocation(getClass().getClassLoader().getResource("views/Track.fxml"));
loader.setResources(bundle);
trackControllers.add(loader.getController());
try {
vboxTracks.getChildren().add(loader.load());
} catch (IOException e) {
throw new RuntimeException("Error while loading track UI.", e);
}
}
private void startTimeUpdateThread() {
Timer timer = new Timer(true);
/*
* Reading the documentation of timer.schedule(...), it seems like
* there's no danger of timer-execution-congestion when a time
* invocation blocks: "[...]each execution is scheduled relative to the
* actual execution time of the previous execution."
*/
timer.schedule(new TimerTask() {
@Override
public void run() {
long prevMillis = System.currentTimeMillis();
updateTime();
long elapsedMs = System.currentTimeMillis() - prevMillis;
if (elapsedMs >= updateFrequencyMs) {
System.err.println(
String.format("Warning: Time update (%dms) took longer than the update frequency (%dms).",
elapsedMs, updateFrequencyMs));
}
}
}, 0, updateFrequencyMs);
}
private String formatTimeString(long totalMicroseconds) {
long minutes = TimeUnit.MICROSECONDS.toMinutes(totalMicroseconds);
long seconds = TimeUnit.MICROSECONDS.toSeconds(totalMicroseconds) % 60;
return String.format("%d:%02d", minutes, seconds);
}
private void handleStop(ActionEvent event) {
getSelectedTrack().ifPresent(Track::stop);
buttonPlayPause.setText(ICON_PLAY);
}
private void handleAbout(ActionEvent event) {
LocalizedAlertBuilder builder = new LocalizedAlertBuilder(bundle, "about.", AlertType.INFORMATION);
Alert alertAbout = builder.build();
alertAbout.getDialogPane().setPrefHeight(Region.USE_COMPUTED_SIZE);
// TODO: auto-resize to content
alertAbout.getDialogPane().setPrefWidth(700);
alertAbout.showAndWait();
}
private void handleManual(ActionEvent event) {
if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Action.BROWSE)) {
new Thread(() -> {
try {
Desktop.getDesktop().browse(new URI(URL_MANUAL));
} catch (IOException | URISyntaxException e) {
System.err.println("Error while opening manual webpage.");
e.printStackTrace();
}
}).start();
} else {
LocalizedAlertBuilder builder = new LocalizedAlertBuilder(bundle, "manual.", AlertType.INFORMATION);
String contentText = bundle.getString("manual.content");
contentText += URL_MANUAL;
builder.setContentText(contentText);
Alert alertManual = builder.build();
alertManual.getDialogPane().setPrefHeight(Region.USE_COMPUTED_SIZE);
alertManual.getDialogPane().setPrefWidth(700);
alertManual.showAndWait();
}
}
private void showErrorUnsupportedFormat(Format format, AudioFormat audioFormat) {
LocalizedAlertBuilder builder = new LocalizedAlertBuilder(bundle, "errorUnsupportedFormat.", AlertType.ERROR);
builder.setHeaderText(null);
String errorText = bundle.getString(determineErrorDescriptionForFormat(format, audioFormat));
errorText += bundle.getString("errorUnsupportedFormat.supportedFormats");
builder.setContentText(errorText);
Alert alertError = builder.build();
alertError.getDialogPane().setPrefHeight(Region.USE_COMPUTED_SIZE);
alertError.getDialogPane().setPrefWidth(700);
alertError.showAndWait();
}
private String determineErrorDescriptionForFormat(Format format, AudioFormat audioFormat) {
if (audioFormat == null) {
return "errorUnsupportedFormat.contentDefault";
}
switch (format) {
case AIFF:
case WAV:
if (audioFormat.getSampleSizeInBits() == 24) {
return "errorUnsupportedFormat.content24bit";
} else {
return "errorUnsupportedFormat.contentDefault";
}
case MP3:
return "errorUnsupportedFormat.contentMp3";
default:
return "errorUnsupportedFormat.contentDefault";
}
}
private void showErrorOutOfMemory() {
LocalizedAlertBuilder builder = new LocalizedAlertBuilder(bundle, "errorOutOfMemory.", AlertType.ERROR);
builder.setHeaderText(null);
Alert alertError = builder.build();
alertError.getDialogPane().setPrefHeight(Region.USE_COMPUTED_SIZE);
alertError.getDialogPane().setPrefWidth(700);
alertError.showAndWait();
}
private void addButtonsAndChart() {
moveButtonList.clear();
deleteButtonList.clear();
lineChartList.clear();
for (int i = 0; i < trackControllers.size(); i++) {
// deleteButton
deleteButtonList.add(trackControllers.get(i).getButtonDelete());
// moveButtons
List<Button> tempList = new ArrayList<>();
tempList.add(trackControllers.get(i).getButtonMoveUp());
tempList.add(trackControllers.get(i).getButtonMoveDown());
moveButtonList.add(tempList);
// Linechart Waveform
lineChartList.add(trackControllers.get(i).getChart());
}
}
private void setMoveButtons() {
List<Track> tracks = project.getTracks();
for (int i = 0; i < tracks.size(); i++) {
if (i == 0) {
moveButtonList.get(i).get(0).setDisable(true);
moveButtonList.get(i).get(1).setDisable(false);
} else if (i < tracks.size() - 1) {
moveButtonList.get(i).get(0).setDisable(false);
moveButtonList.get(i).get(1).setDisable(false);
}
if (i == tracks.size() - 1) {
moveButtonList.get(i).get(1).setDisable(true);
}
}
}
private void setButtonsEventHandler() {
for (int i = 0; i < moveButtonList.size(); i++) {
final int trackNumber = i;
deleteButtonList.get(i).setOnAction(e -> {
deleteTrack(trackNumber);
});
for (int j = 0; j < moveButtonList.get(i).size(); j++) {
final int buttonNumber = j;
moveButtonList.get(i).get(j).setOnAction(e -> {
if (buttonNumber != 1) {
moveUp(trackNumber);
} else {
moveDown(trackNumber);
}
});
}
}
}
private void setLineChartEventHandler() {
for (int i = 0; i < lineChartList.size(); i++) {
final int trackNumber = i;
lineChartList.get(i).setOnMouseClicked(e -> {
trackControllers.get(trackNumber).setRadioButtonActive();
if (trackControllers.get(trackNumber).getRadioButtonActiveTrack().isSelected()) {
trackControllers.get(trackNumber).getChart().getStylesheets()
.add(getClass().getClassLoader().getResource("css/ActiveTrack.css").toExternalForm());
}
});
}
}
private void deleteTrack(int number) {
List<Track> tracks = project.getTracks();
String trackName = tracks.get(number).getName();
LocalizedAlertBuilder builder = new LocalizedAlertBuilder(bundle, "alert.deleteTrack.", AlertType.CONFIRMATION);
builder.setHeaderFormatParameters(trackName);
Optional<ButtonType> result = builder.build().showAndWait();
if (result.get() == ButtonType.OK) {
removeTrack(number);
determineLongestTrackLengths();
}
}
private void removeTrack(int number) {
List<Track> tracks = project.getTracks();
handleStop(null);
vboxTracks.getChildren().remove(number);
Track removed = tracks.remove(number);
toggleGroupActiveTrack.getToggles().removeIf(toggle -> removed.equals(getToggleTrack(toggle)));
trackControllers.remove(number);
moveButtonList.remove(number);
deleteButtonList.remove(number);
addButtonsAndChart();
// setMoveButtons();
setButtonsEventHandler();
setLineChartEventHandler();
setStylesheetsForTracks();
project.setLoudnessLevel();
if (tracks.size() > 0) {
trackControllers.get(0).getRadioButtonActiveTrack().fire();
} else {
setPlaybackControlsDisable(true);
}
}
@SuppressWarnings("unchecked")
private Track getToggleTrack(Toggle toggle) {
return ((WeakReference<Track>) toggle.getUserData()).get();
}
private void moveUp(int number) {
if (number != 0) {
List<Node> tempVboxTracks = new ArrayList<>();
List<TrackController> tempTrackController = new ArrayList<>();
List<Track> tempTracks = new ArrayList<>();
List<Track> tracks = project.getTracks();
for (int i = 0; i < vboxTracks.getChildren().size(); i++) {
if (i == number - 1) {
tempVboxTracks.add(vboxTracks.getChildren().get(i + 1));
tempTrackController.add(trackControllers.get(i + 1));
tempTracks.add(tracks.get(i + 1));
} else if (i == number) {
tempVboxTracks.add(vboxTracks.getChildren().get(i - 1));
tempTrackController.add(trackControllers.get(i - 1));
tempTracks.add(tracks.get(i - 1));
} else {
tempVboxTracks.add(vboxTracks.getChildren().get(i));
tempTrackController.add(trackControllers.get(i));
tempTracks.add(tracks.get(i));
}
}
vboxTracks.getChildren().clear();
trackControllers.clear();
tracks.clear();
for (int i = 0; i < tempVboxTracks.size(); i++) {
vboxTracks.getChildren().add(tempVboxTracks.get(i));
trackControllers.add(tempTrackController.get(i));
tracks.add(tempTracks.get(i));
}
addButtonsAndChart();
// setMoveButtons();
setButtonsEventHandler();
setLineChartEventHandler();
setStylesheetsForTracks();
}
}
private void moveDown(int number) {
List<Track> tracks = project.getTracks();
if (number != tracks.size() - 1) {
List<Node> tempVboxTracks = new ArrayList<>();
List<TrackController> tempTrackController = new ArrayList<>();
List<Track> tempTracks = new ArrayList<>();
for (int i = 0; i < vboxTracks.getChildren().size(); i++) {
if (i == number + 1) {
tempVboxTracks.add(vboxTracks.getChildren().get(i - 1));
tempTrackController.add(trackControllers.get(i - 1));
tempTracks.add(tracks.get(i - 1));
} else if (i == number) {
tempVboxTracks.add(vboxTracks.getChildren().get(i + 1));
tempTrackController.add(trackControllers.get(i + 1));
tempTracks.add(tracks.get(i + 1));
} else {
tempVboxTracks.add(vboxTracks.getChildren().get(i));
tempTrackController.add(trackControllers.get(i));
tempTracks.add(tracks.get(i));
}
}
vboxTracks.getChildren().clear();
trackControllers.clear();
tracks.clear();
for (int i = 0; i < tempVboxTracks.size(); i++) {
vboxTracks.getChildren().add(tempVboxTracks.get(i));
trackControllers.add(tempTrackController.get(i));
tracks.add(tempTracks.get(i));
}
addButtonsAndChart();
// setMoveButtons();
setButtonsEventHandler();
setLineChartEventHandler();
setStylesheetsForTracks();
}
}
private void setStylesheetsForTracks() {
for (TrackController trackController : trackControllers) {
trackController.getChart().getStylesheets().clear();
if (trackController.getRadioButtonActiveTrack().isSelected()) {
trackController.getChart().getStylesheets()
.add(getClass().getClassLoader().getResource("css/ActiveTrack.css").toExternalForm());
} else {
trackController.getChart().getStylesheets()
.add(getClass().getClassLoader().getResource("css/NotActiveTrack.css").toExternalForm());
}
}
}
public void sceneInitialization(Scene scene) {
scene.getAccelerators().put(new KeyCodeCombination(KeyCode.SPACE), buttonPlayPause::fire);
// To unfocus the comment text field
scene.setOnMouseClicked(event -> scene.getRoot().requestFocus());
}
private void toggleLoopActive() {
loopActive = checkMenuItemLoopPlayback.isSelected();
if (loopActive) {
rangesliderLoop.setDisable(false);
} else {
rangesliderLoop.setDisable(true);
}
}
}
| 32.005859 | 114 | 0.734546 |
43124eb6c320dbc04cf34c7ee105d6f8883083a1 | 3,110 | package com.vk.api.sdk.queries.notes;
import com.vk.api.sdk.client.AbstractQueryBuilder;
import com.vk.api.sdk.client.VkApiClient;
import com.vk.api.sdk.client.actors.UserActor;
import java.util.Arrays;
import java.util.List;
/**
* Query for Notes.add method
*/
public class NotesAddQuery extends AbstractQueryBuilder<NotesAddQuery, Integer> {
/**
* Creates a AbstractQueryBuilder instance that can be used to build api request with various parameters
*
* @param client VK API client
* @param actor actor with access token
* @param title value of "title" parameter.
* @param text value of "text" parameter.
*/
public NotesAddQuery(VkApiClient client, UserActor actor, String title, String text) {
super(client, "notes.add", Integer.class);
accessToken(actor.getAccessToken());
title(title);
text(text);
}
/**
* Note title.
*
* @param value value of "title" parameter.
* @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern.
*/
protected NotesAddQuery title(String value) {
return unsafeParam("title", value);
}
/**
* Note text.
*
* @param value value of "text" parameter.
* @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern.
*/
protected NotesAddQuery text(String value) {
return unsafeParam("text", value);
}
/**
* privacy_view
* Set privacy view
*
* @param value value of "privacy view" parameter. By default all.
* @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern.
*/
public NotesAddQuery privacyView(String... value) {
return unsafeParam("privacy_view", value);
}
/**
* Set privacy view
*
* @param value value of "privacy view" parameter. By default all.
* @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern.
*/
public NotesAddQuery privacyView(List<String> value) {
return unsafeParam("privacy_view", value);
}
/**
* privacy_comment
* Set privacy comment
*
* @param value value of "privacy comment" parameter. By default all.
* @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern.
*/
public NotesAddQuery privacyComment(String... value) {
return unsafeParam("privacy_comment", value);
}
/**
* Set privacy comment
*
* @param value value of "privacy comment" parameter. By default all.
* @return a reference to this {@code AbstractQueryBuilder} object to fulfill the "Builder" pattern.
*/
public NotesAddQuery privacyComment(List<String> value) {
return unsafeParam("privacy_comment", value);
}
@Override
protected NotesAddQuery getThis() {
return this;
}
@Override
protected List<String> essentialKeys() {
return Arrays.asList("text", "title", "access_token");
}
}
| 31.1 | 108 | 0.654662 |
e60a8d906e222234a853d301ed470604fb5417c7 | 1,421 | package org.oobench.io;
import org.oobench.common.*;
public abstract class IOBenchmark extends AbstractBenchmark {
public int getMajorNumber() {
return 4;
}
public abstract void write(int count);
public abstract void read(int count);
public abstract void writeAndRead(int count);
public void test(int count, String typeOfIO) {
count = getCountWithDefault(count);
System.out.println("*** Testing IO (" + typeOfIO + ")");
for (int c = 0; c < 10; c++) {
if (c == 9) {
beginAction(1, "write", count, typeOfIO);
}
write(count);
if (c == 9) {
endAction();
beginAction(2, "read", count, typeOfIO);
}
read(count);
if (c == 9) {
endAction();
beginAction(3, "writeAndRead", count, typeOfIO);
}
writeAndRead(count);
if (c == 9) {
endAction();
}
}
}
public static void testIO(Class theClass, int count,
String typeOfMessage, String[] args) {
try {
IOBenchmark bench = (IOBenchmark)theClass.newInstance();
bench.setArguments(args);
bench.test(count, typeOfMessage);
} catch (Exception e) {
e.printStackTrace();
return;
}
}
}
| 26.811321 | 68 | 0.503167 |
cecd09925c18ec8d65b3c575d7b57ad0eacf222c | 1,078 | package org.billing.accountingpoints.service.implementation;
import java.time.Instant;
import java.util.Collections;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.billing.accountingpoints.dto.AccountingPointMeterStateDto;
import org.billing.accountingpoints.repository.AccountingPointMeterStateRepository;
import org.billing.accountingpoints.service.MeterStateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Slf4j
public class MeterStateServiceImpl implements MeterStateService {
private final AccountingPointMeterStateRepository meterStateDao;
@Override
public CompletableFuture<Set<AccountingPointMeterStateDto>> currentStateByEntityServiceIdAsync(
Set<UUID> accountingPointKeyRoomServiceEntities, Instant period) {
return CompletableFuture.completedFuture(Collections.emptySet());
}
}
| 38.5 | 97 | 0.852505 |
f79b326e0ca792a451e729588a23e30e1ea9ab8f | 1,818 | package com.blamejared.crafttweaker.api.mods;
import com.blamejared.crafttweaker.api.annotations.ZenRegister;
import com.blamejared.crafttweaker_annotations.annotations.Document;
import net.minecraftforge.fml.ModList;
import org.openzen.zencode.java.*;
import java.util.List;
import java.util.stream.Collectors;
/**
* Holds information on all the mods that are registered.
* Can be accessed using the `loadedMods` global keyword
*
* @docParam this loadedMods
*/
@ZenRegister
@ZenCodeType.Name("crafttweaker.api.mods.Mods")
@Document("vanilla/api/mods/Mods")
public class MCMods {
/**
* Gets a list of all mods in the game
*
* @return list of MCModInfo
*/
@ZenCodeType.Getter("mods")
public List<MCModInfo> getMods() {
return ModList.get().getMods().stream().map(MCModInfo::new).collect(Collectors.toList());
}
/**
* Gets a specific mod
*
* @return a specific MCModInfo
* @docParam modid "minecraft"
*/
@ZenCodeType.Method
public MCModInfo getMod(String modid) {
return ModList.get().getMods().stream().filter(modInfo -> modInfo.getModId().equals(modid)).map(MCModInfo::new).findFirst().orElseThrow(() -> new IllegalArgumentException("No modid with name: \"" + modid + "\"!"));
}
/**
* Checks if a mod is laoded
*
* @param modid modid to check
*
* @return true if the mod is loaded
* @docParam modid "minecraft"
*/
@ZenCodeType.Method
public boolean isModLoaded(String modid) {
return ModList.get().isLoaded(modid);
}
/**
* Gets the amount of mods loaded
*
* @return The amount of mods that are loaded
*/
@ZenCodeType.Getter("size")
public int getSize() {
return ModList.get().size();
}
}
| 27.134328 | 222 | 0.647965 |
3f2cda5a004205ab5353689280af943042a4feb9 | 2,027 | package de.metas.requisition.callout;
import org.adempiere.ad.callout.annotations.Callout;
import org.adempiere.ad.callout.annotations.CalloutMethod;
import org.compiere.model.I_C_DocType;
import org.compiere.model.I_M_Requisition;
import de.metas.document.DocTypeId;
import de.metas.document.IDocTypeDAO;
import de.metas.document.sequence.IDocumentNoBuilderFactory;
import de.metas.document.sequence.impl.IDocumentNoInfo;
import de.metas.util.Services;
/*
* #%L
* de.metas.business
* %%
* Copyright (C) 2019 metas GmbH
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 2 of the
* License, or (at your option) any later version.
*
* This program 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 for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
@Callout(I_M_Requisition.class)
public class M_Requisition
{
@CalloutMethod(columnNames = I_M_Requisition.COLUMNNAME_C_DocType_ID)
public void onDocTypeChanged(final I_M_Requisition requisition)
{
final DocTypeId docTypeId = DocTypeId.ofRepoIdOrNull(requisition.getC_DocType_ID());
if (docTypeId == null)
{
return;
}
final I_C_DocType docType = Services.get(IDocTypeDAO.class).getById(docTypeId);
final IDocumentNoInfo documentNoInfo = Services.get(IDocumentNoBuilderFactory.class)
.createPreliminaryDocumentNoBuilder()
.setNewDocType(docType)
.setOldDocumentNo(requisition.getDocumentNo())
.setDocumentModel(requisition)
.buildOrNull();
if (documentNoInfo != null && documentNoInfo.isDocNoControlled())
{
requisition.setDocumentNo(documentNoInfo.getDocumentNo());
}
}
}
| 32.693548 | 86 | 0.76961 |
39df82f5875e945e216585e9b7741577d35b2d70 | 2,268 | package com.gigamole.sample.adapters;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.gigamole.sample.R;
import com.gigamole.sample.utils.Utils;
import static com.gigamole.sample.utils.Utils.setupItem;
/**
* Created by GIGAMOLE on 7/27/16.
*/
public class VerticalPagerAdapter extends PagerAdapter {
private final Utils.LibraryObject[] TWO_WAY_LIBRARIES = new Utils.LibraryObject[]{
new Utils.LibraryObject(
R.drawable.ic_fintech,
"Fintech"
),
new Utils.LibraryObject(
R.drawable.ic_delivery,
"Delivery"
),
new Utils.LibraryObject(
R.drawable.ic_social,
"Social network"
),
new Utils.LibraryObject(
R.drawable.ic_ecommerce,
"E-commerce"
),
new Utils.LibraryObject(
R.drawable.ic_wearable,
"Wearable"
),
new Utils.LibraryObject(
R.drawable.ic_internet,
"Internet of things"
)
};
private LayoutInflater mLayoutInflater;
public VerticalPagerAdapter(final Context context) {
mLayoutInflater = LayoutInflater.from(context);
}
@Override
public int getCount() {
return TWO_WAY_LIBRARIES.length;
}
@Override
public int getItemPosition(final Object object) {
return POSITION_NONE;
}
@Override
public Object instantiateItem(final ViewGroup container, final int position) {
final View view = mLayoutInflater.inflate(R.layout.item, container, false);
setupItem(view, TWO_WAY_LIBRARIES[position]);
container.addView(view);
return view;
}
@Override
public boolean isViewFromObject(final View view, final Object object) {
return view.equals(object);
}
@Override
public void destroyItem(final ViewGroup container, final int position, final Object object) {
container.removeView((View) object);
}
}
| 27.325301 | 97 | 0.606261 |
f8a58d538a68db1f210ebee9440d2798086307a3 | 1,174 | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
package com.microsoft.gctoolkit.io;
import java.nio.file.Path;
/**
* A DataSource rooted in a file system.
* @param <T> The type of data returned from the DataSource
*/
public abstract class FileDataSource<T> implements DataSource<T> {
protected final Path path;
protected final FileDataSourceMetaData metaData;
/**
* Subclass only.
* @param path The path to the file in the file system.
*/
protected FileDataSource(Path path) {
this.path = path;
this.metaData = new FileDataSourceMetaData(path);
}
/**
* Return the path to the file in the file system.
* @return The path to the file in the file system.
*/
public Path getPath() {
return path;
}
/**
* Return meta data about the file.
* @return Meta data about the file.
*/
public FileDataSourceMetaData getMetaData() {
return metaData;
}
/**
* {@inheritDoc}
* @return Returns {@code this.getPath().toString();}
*/
@Override
public String toString() {
return path.toString();
}
} | 23.959184 | 66 | 0.626917 |
ddb1c9bba3efb8622a43343714cb00d20f66645c | 1,854 | /*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tv.common.support.tis;
import android.media.tv.TvInputService.Session;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.util.ArraySet;
import androidx.annotation.VisibleForTesting;
import com.google.common.collect.ImmutableSet;
import java.util.HashSet;
import java.util.Set;
/** A simple session manager that allows a maximum number of concurrent session. */
public final class SimpleSessionManager implements SessionManager {
private final Set<Session> sessions;
private final int max;
public SimpleSessionManager(int max) {
this.max = max;
sessions = VERSION.SDK_INT >= VERSION_CODES.M ? new ArraySet<>() : new HashSet<>();
}
@Override
public void removeSession(Session session) {
sessions.remove(session);
}
@Override
public void addSession(Session session) {
sessions.add(session);
}
@Override
public boolean canCreateNewSession() {
return sessions.size() < max;
}
@Override
public ImmutableSet<Session> getSessions() {
return ImmutableSet.copyOf(sessions);
}
@VisibleForTesting
int getSessionCount() {
return sessions.size();
}
}
| 28.090909 | 91 | 0.713592 |
4c85c7a0713a672f0175e1652cf2045c4428c72e | 10,362 | /*
* Copyright 2011 Goldman Sachs.
*
* 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.webguys.ponzu.impl.set.sorted.mutable;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.SortedSet;
import java.util.TreeSet;
import com.webguys.ponzu.api.block.procedure.ObjectIntProcedure;
import com.webguys.ponzu.api.collection.MutableCollection;
import com.webguys.ponzu.api.list.MutableList;
import com.webguys.ponzu.api.set.sorted.MutableSortedSet;
import com.webguys.ponzu.impl.block.factory.Comparators;
import com.webguys.ponzu.impl.block.factory.Functions;
import com.webguys.ponzu.impl.block.factory.Predicates;
import com.webguys.ponzu.impl.block.procedure.CollectionAddProcedure;
import com.webguys.ponzu.impl.factory.Lists;
import com.webguys.ponzu.impl.list.mutable.FastList;
import com.webguys.ponzu.impl.set.mutable.UnifiedSet;
import com.webguys.ponzu.impl.test.SerializeTestHelper;
import com.webguys.ponzu.impl.test.Verify;
import com.webguys.ponzu.impl.utility.ArrayIterate;
import org.junit.Assert;
import org.junit.Test;
/**
* JUnit test for {@link SortedSetAdapter}.
*/
public class SortedSetAdapterTest extends AbstractSortedSetTestCase
{
@Override
protected <T> SortedSetAdapter<T> classUnderTest()
{
return new SortedSetAdapter<T>(new TreeSet<T>());
}
@Override
protected <T> SortedSetAdapter<T> classUnderTest(T... elements)
{
TreeSet<T> set = new TreeSet<T>();
ArrayIterate.forEach(elements, CollectionAddProcedure.on(set));
return new SortedSetAdapter<T>(set);
}
@Override
protected <T> SortedSetAdapter<T> classUnderTest(Comparator<? super T> comparator, T... elements)
{
TreeSet<T> set = new TreeSet<T>(comparator);
ArrayIterate.forEach(elements, CollectionAddProcedure.on(set));
return new SortedSetAdapter<T>(set);
}
@Override
@Test
public void asSynchronized()
{
Verify.assertInstanceOf(SynchronizedSortedSet.class, SortedSetAdapter.adapt(new TreeSet<Integer>()).asSynchronized());
}
@Override
@Test
public void asUnmodifiable()
{
Verify.assertInstanceOf(UnmodifiableSortedSet.class, this.classUnderTest().asUnmodifiable());
}
@Override
@Test
public void testClone()
{
super.testClone();
MutableSortedSet<Integer> set = this.<Integer>classUnderTest(Collections.<Integer>reverseOrder()).with(1, 2, 3);
MutableSortedSet<Integer> list2 = set.clone();
Verify.assertSortedSetsEqual(set, list2);
}
@Test
public void adapt()
{
TreeSet<Integer> integers = new TreeSet<Integer>(FastList.newListWith(1, 2, 3, 4));
MutableSortedSet<Integer> adapter1 = SortedSetAdapter.adapt(integers);
MutableSortedSet<Integer> adapter2 = new SortedSetAdapter<Integer>(new TreeSet<Integer>()).with(1, 2, 3, 4);
Verify.assertEqualsAndHashCode(adapter1, adapter2);
Verify.assertSortedSetsEqual(adapter1, adapter2);
}
@Override
@Test
public void select()
{
super.select();
SortedSetAdapter<Integer> integers = this.<Integer>classUnderTest(1, 2, 3, 4, 5);
Verify.assertSortedSetsEqual(TreeSortedSet.<Integer>newSetWith(1, 2), integers.filter(Predicates.lessThan(3)));
Verify.assertInstanceOf(MutableSortedSet.class, this.<Integer>classUnderTest().filter(Predicates.alwaysTrue()));
Verify.assertSortedSetsEqual(TreeSortedSet.newSet(), this.<Object>classUnderTest().filter(Predicates.alwaysTrue()));
}
@Override
@Test
public void reject()
{
super.reject();
SortedSetAdapter<Integer> integers = this.classUnderTest(Comparators.<Integer>reverseNaturalOrder(), 1, 2, 3, 4);
Verify.assertSortedSetsEqual(TreeSortedSet.newSetWith(Comparators.<Object>reverseNaturalOrder(), 1, 2), integers.filterNot(Predicates.greaterThan(2)));
Verify.assertInstanceOf(MutableSortedSet.class, this.<Integer>classUnderTest().filter(Predicates.alwaysTrue()));
Verify.assertSortedSetsEqual(TreeSortedSet.newSet(), this.<Object>classUnderTest().filterNot(Predicates.alwaysTrue()));
}
@Override
@Test
public void collect()
{
super.collect();
Verify.assertListsEqual(FastList.newListWith("1", "2", "3", "4"),
this.<Integer>classUnderTest(1, 2, 3, 4).transform(Functions.getToString()));
Verify.assertListsEqual(FastList.newListWith("1", "2", "3", "4"), this.<Integer>classUnderTest(1, 2, 3, 4).transform(Functions.getToString(),
FastList.<String>newList()));
Verify.assertInstanceOf(FastList.class, this.<Object>classUnderTest().transform(Functions.getToString()));
}
@Override
@Test
public void equalsAndHashCode()
{
super.equalsAndHashCode();
MutableCollection<Integer> set1 = this.<Integer>classUnderTest(1, 2, 3);
SortedSetAdapter<Integer> set2 = this.<Integer>classUnderTest(Collections.<Integer>reverseOrder(), 1, 2, 3);
MutableCollection<Integer> set3 = this.<Integer>classUnderTest(2, 3, 4);
MutableSortedSet<Integer> set4 = TreeSortedSet.newSetWith(2, 3, 4);
Verify.assertEqualsAndHashCode(set1, set1);
Assert.assertEquals(UnifiedSet.newSetWith(1, 2, 3), set1);
Assert.assertEquals(UnifiedSet.newSetWith(1, 2, 3), set2);
Assert.assertEquals(set1, set2);
Verify.assertNotEquals(set2, set3);
Verify.assertEqualsAndHashCode(set3, set4);
Verify.assertSortedSetsEqual(TreeSortedSet.newSetWith(Collections.<Integer>reverseOrder(), 1, 2, 3), set2);
}
@Test
public void serialization()
{
MutableSortedSet<Integer> collection = this.classUnderTest(Comparators.<Integer>reverseNaturalOrder(), 1, 2, 3);
MutableSortedSet<Integer> deserialized = SerializeTestHelper.serializeDeserialize(collection);
Verify.assertPostSerializedEqualsAndHashCode(collection);
deserialized.add(4);
Verify.assertSortedSetsEqual(TreeSortedSet.newSetWith(Comparators.<Object>reverseNaturalOrder(), 1, 2, 3, 4), deserialized);
}
@Override
@Test
public void forEachWithIndex()
{
super.forEachWithIndex();
final MutableList<Integer> result = Lists.mutable.of();
MutableCollection<Integer> collection = this.classUnderTest(Comparators.<Integer>reverseNaturalOrder(), 1, 2, 3, 4);
collection.forEachWithIndex(new ObjectIntProcedure<Integer>()
{
public void value(Integer object, int index)
{
result.add(object);
}
});
Verify.assertListsEqual(FastList.newListWith(4, 3, 2, 1), result);
}
@Override
@Test
public void getFirst()
{
super.getFirst();
Assert.assertEquals(Integer.valueOf(1), this.<Integer>classUnderTest(1, 2, 3).getFirst());
Assert.assertEquals(Integer.valueOf(3), this.<Integer>classUnderTest(Collections.<Integer>reverseOrder(), 1, 2, 3).getFirst());
Verify.assertThrows(NoSuchElementException.class, new Runnable()
{
public void run()
{
new SortedSetAdapter(new TreeSet<Object>()).getFirst();
}
});
}
@Override
@Test
public void getLast()
{
super.getLast();
Assert.assertNotNull(this.<Object>classUnderTest(1, 2, 3).getLast());
Assert.assertEquals(Integer.valueOf(3), this.<Integer>classUnderTest(1, 2, 3).getLast());
Assert.assertEquals(Integer.valueOf(1), this.<Integer>classUnderTest(Collections.<Integer>reverseOrder(), 1, 2, 3).getLast());
Verify.assertThrows(NoSuchElementException.class, new Runnable()
{
public void run()
{
new SortedSetAdapter(new TreeSet<Object>()).getFirst();
}
});
}
@Override
@Test
public void iterator()
{
super.iterator();
MutableCollection<Integer> objects = this.classUnderTest(2, 3, 1, 4, 5);
MutableList<Integer> result = Lists.mutable.of();
Iterator<Integer> iterator = objects.iterator();
for (int i = objects.size(); i > 0; i--)
{
Integer integer = iterator.next();
result.add(integer);
}
Verify.assertListsEqual(FastList.newListWith(1, 2, 3, 4, 5), result);
}
@Test
public void withMethods()
{
Verify.assertContainsAll(this.classUnderTest().with(1), 1);
Verify.assertContainsAll(this.classUnderTest().with(1, 2), 1, 2);
Verify.assertContainsAll(this.classUnderTest().with(1, 2, 3), 1, 2, 3);
Verify.assertContainsAll(this.classUnderTest().with(1, 2, 3, 4), 1, 2, 3, 4);
}
@Test
public void returnType()
{
//Type TreeSet is important here because it's not a MutableSet
SortedSet<Integer> set = new TreeSet<Integer>();
MutableSortedSet<Integer> integerSetAdapter = SortedSetAdapter.adapt(set);
Verify.assertInstanceOf(MutableSortedSet.class, integerSetAdapter.filter(Predicates.alwaysTrue()));
}
@Test
public void adaptNull()
{
Verify.assertThrows(
NullPointerException.class,
new Runnable()
{
public void run()
{
new SortedSetAdapter<Object>(null);
}
});
Verify.assertThrows(
NullPointerException.class,
new Runnable()
{
public void run()
{
SortedSetAdapter.adapt(null);
}
});
}
}
| 37.543478 | 159 | 0.660008 |
be971f85eb086b47712c2c513542ab5966aaa49c | 509 | package org.gourd.hu.notice.sms.listener;
import com.alibaba.alicloud.sms.SmsReportMessageListener;
import com.aliyun.mns.model.Message;
/**
* 如果需要监听短信是否被对方成功接收,只需实现这个接口并初始化一个 Spring Bean 即可。
* @author gourd.hu
*/
//@Component
public class GourdSmsReportMessageListener implements SmsReportMessageListener {
@Override
public boolean dealMessage(Message message) {
// 在这里添加你的处理逻辑
//do something
System.err.println(this.getClass().getName() + "; " + message.toString());
return true;
}
} | 24.238095 | 80 | 0.750491 |
c885564d273199b1162c2b3913f3f964e929e528 | 380 | package com.clstephenson.homeinfo.api.service;
import com.clstephenson.homeinfo.model.User;
import java.util.List;
import java.util.Optional;
public interface UserService {
List<User> getAll();
Optional<User> findById(long id);
Optional<User> findByEmail(String email);
User save(User user);
void deleteById(long id);
boolean existsById(long id);
} | 19 | 46 | 0.728947 |
34ad46b9f2e8af6ee205433f734c8a653f3b1172 | 6,412 |
package com.netsuite.webservices.lists.employees;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.datatype.XMLGregorianCalendar;
import com.netsuite.webservices.platform.core.RecordRef;
/**
* <p>Java class for EmployeeEarning complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="EmployeeEarning">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="payrollItem" type="{urn:core_2014_2.platform.webservices.netsuite.com}RecordRef" minOccurs="0"/>
* <element name="payRate" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="primaryEarning" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
* <element name="defaultHours" type="{http://www.w3.org/2001/XMLSchema}double" minOccurs="0"/>
* <element name="inactive" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
* <element name="defaultEarning" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/>
* <element name="effectiveDate" type="{http://www.w3.org/2001/XMLSchema}dateTime" minOccurs="0"/>
* <element name="expirationDate" type="{http://www.w3.org/2001/XMLSchema}dateTime" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "EmployeeEarning", propOrder = {
"payrollItem",
"payRate",
"primaryEarning",
"defaultHours",
"inactive",
"defaultEarning",
"effectiveDate",
"expirationDate"
})
public class EmployeeEarning {
protected RecordRef payrollItem;
protected String payRate;
protected Boolean primaryEarning;
protected Double defaultHours;
protected Boolean inactive;
protected Boolean defaultEarning;
@XmlSchemaType(name = "dateTime")
protected XMLGregorianCalendar effectiveDate;
@XmlSchemaType(name = "dateTime")
protected XMLGregorianCalendar expirationDate;
/**
* Gets the value of the payrollItem property.
*
* @return
* possible object is
* {@link RecordRef }
*
*/
public RecordRef getPayrollItem() {
return payrollItem;
}
/**
* Sets the value of the payrollItem property.
*
* @param value
* allowed object is
* {@link RecordRef }
*
*/
public void setPayrollItem(RecordRef value) {
this.payrollItem = value;
}
/**
* Gets the value of the payRate property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPayRate() {
return payRate;
}
/**
* Sets the value of the payRate property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPayRate(String value) {
this.payRate = value;
}
/**
* Gets the value of the primaryEarning property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isPrimaryEarning() {
return primaryEarning;
}
/**
* Sets the value of the primaryEarning property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setPrimaryEarning(Boolean value) {
this.primaryEarning = value;
}
/**
* Gets the value of the defaultHours property.
*
* @return
* possible object is
* {@link Double }
*
*/
public Double getDefaultHours() {
return defaultHours;
}
/**
* Sets the value of the defaultHours property.
*
* @param value
* allowed object is
* {@link Double }
*
*/
public void setDefaultHours(Double value) {
this.defaultHours = value;
}
/**
* Gets the value of the inactive property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isInactive() {
return inactive;
}
/**
* Sets the value of the inactive property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setInactive(Boolean value) {
this.inactive = value;
}
/**
* Gets the value of the defaultEarning property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isDefaultEarning() {
return defaultEarning;
}
/**
* Sets the value of the defaultEarning property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setDefaultEarning(Boolean value) {
this.defaultEarning = value;
}
/**
* Gets the value of the effectiveDate property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getEffectiveDate() {
return effectiveDate;
}
/**
* Sets the value of the effectiveDate property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setEffectiveDate(XMLGregorianCalendar value) {
this.effectiveDate = value;
}
/**
* Gets the value of the expirationDate property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getExpirationDate() {
return expirationDate;
}
/**
* Sets the value of the expirationDate property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setExpirationDate(XMLGregorianCalendar value) {
this.expirationDate = value;
}
}
| 25.145098 | 128 | 0.582813 |
a63c533ae242c424151f93f7fc76f9903e19e957 | 8,107 | /*
* Copyright 2012 Aleksejs Okolovskis <oko@aloko.de>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package architecturesimulator;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.geom.Point2D;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
/**
*
* @author Aleksejs Okolovskis (oko@aloko.de)
*/
public class Register implements ArchitectureObjectWithBusConnection {
Bus Input = null;
Bus Output = null;
private int bitLength = 0;
private String name = "";
private Long Value = 0L;
private Dimension lastDimension = new Dimension(0, 0);
private Orientation orientation = Orientation.north;
private boolean ChipSelected = false;
private boolean OutputEnabled = false;
public void resetState() {
ChipSelected = false;
OutputEnabled = false;
}
public Register() {
}
public Dimension getDimension(FontMetrics metrics) {
String description = getName() + ": ";
String string1 = "1";
String string0 = "0";
int bitwidth = (metrics.stringWidth(string0) > metrics.stringWidth(string1)) ? metrics.stringWidth(string0) : metrics.stringWidth(string1);
bitwidth = bitwidth
* bitLength;
int hgt = metrics.getHeight();
int adv = metrics.stringWidth(description);
adv = adv + bitwidth;
Dimension sizeofbox = new Dimension(adv + 2 + 1, hgt + 4 + 1);
lastDimension = sizeofbox;
return sizeofbox;
}
public Register(int bitLength) {
this.bitLength = bitLength;
}
public Register(int bitLength, String name) {
this.bitLength = bitLength;
this.name = name;
}
public Register(int bitLength, String name, Bus Input, Bus Output) {
this.bitLength = bitLength;
this.name = name;
this.Input = Input;
this.Output = Output;
}
/**
* @return the bitLength
*/
public int getBitLength() {
return bitLength;
}
/**
* @param bitLength the bitLength to set
*/
public void setBitLength(int bitLength) {
this.bitLength = bitLength;
}
/**
* @return the name
*/
public String getName() {
return name;
}
/**
* @param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the Value
*/
public String getValue() {
String result = BinaryFunctions.normalizeStringlengt(Long.toBinaryString(Value), bitLength);
return result;
/*
int length = Long.toBinaryString(Value).length();
if (length > bitLength) {
int from = length - bitLength;
return Long.toBinaryString(Value).substring(from+outputhighestbitmask, length);
} else {
return Long.toBinaryString(Value).substring(outputhighestbitmask, length);
}*/
}
/**
* @param Value the Value to set
*/
private void setValue(String BinaryValue) {
this.Value = Long.parseLong(BinaryValue, 2);
}
public void paint(Graphics g) {
Rectangle virtualBounds = new Rectangle();
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] gs =
ge.getScreenDevices();
for (int j = 0; j < gs.length; j++) {
GraphicsDevice gd = gs[j];
GraphicsConfiguration[] gc =
gd.getConfigurations();
for (int i = 0; i < gc.length; i++) {
virtualBounds =
virtualBounds.union(gc[i].getBounds());
}
}
Graphics2D g2d = (Graphics2D) g;
Font f = g2d.getFont();
String description = getName() + ": ";
FontMetrics metrics = g2d.getFontMetrics(f);
String string1 = "1";
String string0 = "0";
int bitwidth = (metrics.stringWidth(string0) > metrics.stringWidth(string1)) ? metrics.stringWidth(string0) : metrics.stringWidth(string1);
bitwidth = bitwidth
* bitLength;
int hgt = metrics.getHeight();
int adv = metrics.stringWidth(description);
adv = adv + bitwidth;
Dimension sizeofbox = new Dimension(adv + 2, hgt + 4);
Color old = g2d.getColor();
if (ChipSelected & OutputEnabled) {
g2d.setColor(Color.YELLOW);
} else if (ChipSelected) {
g2d.setColor(Color.RED);
} else if (OutputEnabled) {
g2d.setColor(Color.GREEN);
} else {
g2d.setColor(defaultBackgroundColor);
}
g2d.fillRect(0, 0, sizeofbox.width, sizeofbox.height);
g2d.setColor(old);
g2d.drawRect(0, 0, sizeofbox.width, sizeofbox.height);
g2d.drawString(description + getValue(), 1, hgt);
}
public Bus getInput() {
return Input;
}
public Bus getOutput() {
return Output;
}
public void setInput(Bus Input) {
this.Input = Input;
}
public void setOutput(Bus Output) {
this.Output = Output;
}
public void chipEnable() {
this.setValue(Input.getValue());
ChipSelected = true;
}
public void outputEnable() {
Output.setValue(getValue());
OutputEnabled = true;
}
public Dimension getDimension() {
return new Dimension();
}
public State getState() {
return (OutputEnabled | ChipSelected) ? State.Active : State.Inactive;
}
public Collection<Bus> getInvoldedBuses() {
ArrayList<Bus> t = new ArrayList<Bus>();
if (Input != null) {
t.add(Input);
}
if (Output != null) {
t.add(Output);
}
return t;
}
public Point2D getConnectionPoint(Bus b) throws IOException {
if (b == Input) {
switch (orientation) {
case north:
return new Point2D.Double(lastDimension.width / 2, lastDimension.height);
case east:
return new Point2D.Double(0, lastDimension.height / 2);
case south:
return new Point2D.Double(lastDimension.width / 2, 0);
case west:
return new Point2D.Double(lastDimension.width, lastDimension.height / 2);
default:
throw new AssertionError();
}
} else if (b == Output) {
switch (orientation) {
case north:
return new Point2D.Double(lastDimension.width / 2, 0);
case east:
return new Point2D.Double(lastDimension.width, lastDimension.height / 2);
case south:
return new Point2D.Double(lastDimension.width / 2, lastDimension.height);
case west:
return new Point2D.Double(0, lastDimension.height / 2);
default:
throw new AssertionError();
}
}
throw new IOException("Bus not Connected to Register");
}
public Orientation getOrientation() {
return orientation;
}
public void setOrientation(Orientation orientation) {
this.orientation = orientation;
}
}
| 26.151613 | 147 | 0.591588 |
d4c855afa9bd274420c3841281784a6aee811256 | 711 | package com.wxdlong.jersey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;
@Provider
public class HelpMeException implements ExceptionMapper<Exception> {
private final static Logger LOGGER = LoggerFactory.getLogger(HelpMeException.class);
@Override
public Response toResponse(Exception exception) {
LOGGER.error("HelpMe", exception);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.type(MediaType.APPLICATION_JSON)
.entity(exception.getCause())
.build();
}
}
| 28.44 | 88 | 0.720113 |
2cb87398308d7121da8fbabed613575a0ce125f2 | 1,122 | package com.dsi.parallax.optimization.stochastic.anneal;
import com.dsi.parallax.ml.util.MLUtils;
import com.dsi.parallax.optimization.Gradient;
/**
* see Adaptive Subgradient Methods for Online Learning and Stochastic
* Optimization, Duchi et al.
*
* @author jattenberg
*
*/
public class AdaGradAnnealingSchedule extends AnnealingSchedule implements
GradientUpdateable {
/** The grad storage. */
private transient double[] gradStorage;
public AdaGradAnnealingSchedule(double initialRate) {
super(initialRate);
}
/**
* Component wise eta.
*
* @param dim
* the dim
* @param grads
* the grads
* @return the double
*/
@Override
public double learningRate(int epoch, int dimension) {
if (gradStorage == null) {
return initialLearningRate;
} else {
return MLUtils.inverseSquareRoot(new Double(gradStorage[dimension])
.floatValue());
}
}
@Override
public void update(Gradient grad) {
if (gradStorage == null)
gradStorage = new double[grad.size()];
for (int x_i : grad) {
gradStorage[x_i] += Math.pow(grad.getValue(x_i), 2d);
}
}
}
| 22 | 74 | 0.692513 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.