repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
FunnyMan3595/mcp_deobfuscate
src/main/java/org/ldg/mcpd/NonloadingClassWriter.java
459
package org.ldg.mcpd; import org.objectweb.asm.*; import java.util.*; public class NonloadingClassWriter extends ClassWriter { InheritanceGraph inheritance; public NonloadingClassWriter(InheritanceGraph inheritance) { super(0); this.inheritance = inheritance; } @Override protected String getCommonSuperClass(final String type1, final String type2) { return inheritance.getCommonAncestor(type1, type2); } }
mit
jblindsay/jblindsay.github.io
ghrg/Whitebox/WhiteboxGAT-linux/resources/plugins/source_files/ShapeComplexityIndex.java
21623
/* * Copyright (C) 2011-2012 Dr. John Lindsay <jlindsay@uoguelph.ca> * * 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 3 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/>. */ package plugins; import com.vividsolutions.jts.algorithm.ConvexHull; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.GeometryFactory; import com.vividsolutions.jts.geom.impl.CoordinateArraySequence; import java.text.DecimalFormat; import java.util.Date; import whitebox.geospatialfiles.ShapeFile; import whitebox.geospatialfiles.WhiteboxRaster; import whitebox.geospatialfiles.shapefile.PolygonM; import whitebox.geospatialfiles.shapefile.PolygonZ; import whitebox.geospatialfiles.shapefile.ShapeFileRecord; import whitebox.geospatialfiles.shapefile.ShapeType; import whitebox.geospatialfiles.shapefile.attributes.DBFField; import whitebox.interfaces.WhiteboxPlugin; import whitebox.interfaces.WhiteboxPluginHost; /** * This tool provides a measure of overall polygon shape complexity, or irregularity, for both raster and vector features. * @author Dr. John Lindsay email: jlindsay@uoguelph.ca */ public class ShapeComplexityIndex implements WhiteboxPlugin { private WhiteboxPluginHost myHost; private String[] args; /** * Used to retrieve the plugin tool's name. This is a short, unique name * containing no spaces. * * @return String containing plugin name. */ @Override public String getName() { return "ShapeComplexityIndex"; } /** * Used to retrieve the plugin tool's descriptive name. This can be a longer name (containing spaces) and is used in the interface to list the tool. * @return String containing the plugin descriptive name. */ @Override public String getDescriptiveName() { return "Shape Complexity Index"; } /** * Used to retrieve a short description of what the plugin tool does. * @return String containing the plugin's description. */ @Override public String getToolDescription() { return "Assigns each patch a simple index value based " + "on the patch's shape complexity."; } /** * Used to identify which toolboxes this plugin tool should be listed in. * @return Array of Strings. */ @Override public String[] getToolbox() { String[] ret = { "PatchShapeTools" }; return ret; } /** * Sets the WhiteboxPluginHost to which the plugin tool is tied. This is the class * that the plugin will send all feedback messages, progress updates, and return objects. * @param host The WhiteboxPluginHost that called the plugin tool. */ @Override public void setPluginHost(WhiteboxPluginHost host) { myHost = host; } /** * Used to communicate feedback pop-up messages between a plugin tool and the main Whitebox user-interface. * @param feedback String containing the text to display. */ private void showFeedback(String feedback) { if (myHost != null) { myHost.showFeedback(feedback); } else { System.out.println(feedback); } } /** * Used to communicate a return object from a plugin tool to the main Whitebox user-interface. * @return Object, such as an output WhiteboxRaster. */ private void returnData(Object ret) { if (myHost != null) { myHost.returnData(ret); } } /** * Used to communicate a progress update between a plugin tool and the main Whitebox user interface. * @param progressLabel A String to use for the progress label. * @param progress Float containing the progress value (between 0 and 100). */ private void updateProgress(String progressLabel, int progress) { if (myHost != null) { myHost.updateProgress(progressLabel, progress); } else { System.out.println(progressLabel + " " + progress + "%"); } } /** * Used to communicate a progress update between a plugin tool and the main Whitebox user interface. * @param progress Float containing the progress value (between 0 and 100). */ private void updateProgress(int progress) { if (myHost != null) { myHost.updateProgress(progress); } else { System.out.println("Progress: " + progress + "%"); } } /** * Sets the arguments (parameters) used by the plugin. * @param args An array of string arguments. */ @Override public void setArgs(String[] args) { this.args = args.clone(); } private boolean cancelOp = false; /** * Used to communicate a cancel operation from the Whitebox GUI. * @param cancel Set to true if the plugin should be canceled. */ @Override public void setCancelOp(boolean cancel) { cancelOp = cancel; } private void cancelOperation() { showFeedback("Operation cancelled."); updateProgress("Progress: ", 0); } private boolean amIActive = false; /** * Used by the Whitebox GUI to tell if this plugin is still running. * @return a boolean describing whether or not the plugin is actively being used. */ @Override public boolean isActive() { return amIActive; } private void calculateRaster() { amIActive = true; String inputHeader = null; String outputHeader = null; int col; int row; int numCols; int numRows; int a, i; float progress; int minValue, maxValue, range; boolean blnTextOutput = false; int z; int previousZ; if (args.length <= 0) { showFeedback("Plugin parameters have not been set."); return; } inputHeader = args[0]; outputHeader = args[1]; blnTextOutput = Boolean.parseBoolean(args[2]); // check to see that the inputHeader and outputHeader are not null. if ((inputHeader == null) || (outputHeader == null)) { showFeedback("One or more of the input parameters have not been set properly."); return; } try { WhiteboxRaster image = new WhiteboxRaster(inputHeader, "r"); numRows = image.getNumberRows(); numCols = image.getNumberColumns(); double noData = image.getNoDataValue(); WhiteboxRaster output = new WhiteboxRaster(outputHeader, "rw", inputHeader, WhiteboxRaster.DataType.FLOAT, noData); output.setPreferredPalette("spectrum.pal"); output.setDataScale(WhiteboxRaster.DataScale.CONTINUOUS); //minValue = (int)(image.getMinimumValue()); maxValue = (int)(image.getMaximumValue()); range = maxValue; // - minValue; double[] data; double[] totalColumns = new double[range + 1]; double[] totalRows = new double[range + 1]; double[] totalSW_NE = new double[range + 1]; double[] totalSE_NW = new double[range + 1]; double[] spanColumns = new double[range + 1]; double[] spanRows = new double[range + 1]; double[] spanSW_NE = new double[range + 1]; double[] spanSE_NW = new double[range + 1]; boolean[] counter; double[] shapeComplexity = new double[range + 1]; updateProgress("Loop 1 of 5:", 0); for (row = 0; row < numRows; row++) { previousZ = (int) noData; counter = new boolean[range + 1]; data = image.getRowValues(row); for (col = 0; col < numCols; col++) { if (data[col] > 0 && data[col] != previousZ) { totalRows[(int) data[col]]++; if (counter[(int) data[col]] == false) { spanRows[(int) data[col]]++; counter[(int) data[col]] = true; } } previousZ = (int) data[col]; } if (cancelOp) { cancelOperation(); return; } progress = (float) (100f * row / (numRows - 1)); updateProgress("Loop 1 of 5:", (int) progress); } updateProgress("Loop 2 of 5:", 0); for (col = 0; col < numCols; col++) { previousZ = (int) noData; counter = new boolean[range + 1]; data = image.getRowValues(row); for (row = 0; row < numRows; row++) { z = (int)image.getValue(row, col); if (z > 0 && data[col] != previousZ) { totalColumns[z]++; if (counter[z] == false) { spanColumns[z]++; counter[z] = true; } } previousZ = z; } if (cancelOp) { cancelOperation(); return; } progress = (float) (100f * row / (numRows - 1)); updateProgress("Loop 2 of 5:", (int) progress); } int j, k; int numCells = numCols * numRows; updateProgress("Loop 3 of 5:", 0); row = 0; col = 0; k = 0; do { i = col; j = row; previousZ = (int) noData; counter = new boolean[range + 1]; do { k++; z = (int) (image.getValue(j, i)); if (z > 0 && z != previousZ) { totalSW_NE[z]++; if (counter[z] == false) { spanSW_NE[z]++; counter[z] = true; } } previousZ = z; i++; j--; } while (i < numCols && j >= 0); if (row == (numRows - 1)) { col++; } else { row++; } if (cancelOp) { cancelOperation(); return; } progress = (float) (k * 100f / numCells); updateProgress("Loop 3 of 5:", (int) progress); } while (col < numCols); updateProgress("Loop 4 of 5:", 0); row = 0; col = numCols - 1; k = 0; do { i = col; j = row; previousZ = (int) noData; counter = new boolean[range + 1]; do { k++; z = (int) (image.getValue(j, i)); if (z > 0 && z != previousZ) { totalSE_NW[z]++; if (counter[z] == false) { spanSE_NW[z]++; counter[z] = true; } } previousZ = z; i--; j--; } while (i >= 0 && j >= 0); if (row == (numRows - 1)) { col--; } else { row++; } if (cancelOp) { cancelOperation(); return; } progress = (float) (k * 100f / numCells); updateProgress("Loop 4 of 5:", (int) progress); } while (col >= 0); for (a = 0; a <= range; a++) { if (totalColumns[a] > 0) { shapeComplexity[a] = (totalColumns[a] / spanColumns[a] + totalRows[a] / spanRows[a] + totalSW_NE[a] / spanSW_NE[a] + totalSE_NW[a] / spanSE_NW[a]) / 4; } } updateProgress("Loop 5 of 5:", 0); for (row = 0; row < numRows; row++) { data = image.getRowValues(row); for (col = 0; col < numCols; col++) { if (data[col] > 0) { output.setValue(row, col, shapeComplexity[(int) data[col]]); } } if (cancelOp) { cancelOperation(); return; } progress = (float) (100f * row / (numRows - 1)); updateProgress("Loop 5 of 5:", (int) progress); } output.addMetadataEntry("Created by the " + getDescriptiveName() + " tool."); output.addMetadataEntry("Created on " + new Date()); image.close(); output.close(); if (blnTextOutput) { DecimalFormat df; df = new DecimalFormat("0.0000"); String retstr = "Shape Complexity Index\nPatch ID\tComplexity"; for (a = 0; a <= range; a++) { if (shapeComplexity[a] > 0) { retstr = retstr + "\n" + a + "\t" + df.format(shapeComplexity[a]); } } returnData(retstr); } // returning a header file string displays the image. returnData(outputHeader); } catch (OutOfMemoryError oe) { myHost.showFeedback("An out-of-memory error has occurred during operation."); } catch (Exception e) { myHost.showFeedback("An error has occurred during operation. See log file for details."); myHost.logException("Error in " + getDescriptiveName(), e); } finally { updateProgress("Progress: ", 0); // tells the main application that this process is completed. amIActive = false; myHost.pluginComplete(); } } private void calculateVector() { /* * Notice that this tool assumes that each record in the shapefile is an * individual polygon. The feature can contain multiple parts only if it * has holes, i.e. islands. A multipart record cannot contain multiple * and seperate features. This is because it complicates the calculation * of feature area and perimeter. */ amIActive = true; // Declare the variable. String inputFile = null; int progress; double featureArea = 0; double hullArea = 0; int recNum; int j, i; double[][] vertices = null; CoordinateArraySequence coordArray; ConvexHull ch; GeometryFactory factory = new GeometryFactory(); Geometry geom; if (args.length <= 0) { showFeedback("Plugin parameters have not been set."); return; } inputFile = args[0]; /* * args[1], args[2], and args[3] are ignored by the vector tool */ // check to see that the inputHeader and outputHeader are not null. if (inputFile == null) { showFeedback("One or more of the input parameters have not been set properly."); return; } try { ShapeFile input = new ShapeFile(inputFile); double numberOfRecords = input.getNumberOfRecords(); if (input.getShapeType().getBaseType() != ShapeType.POLYGON) { showFeedback("This function can only be applied to polygon type shapefiles."); return; } /* create a new field in the input file's database to hold the fractal dimension. Put it at the end of the database. */ DBFField field = new DBFField(); field = new DBFField(); field.setName("COMPLEXITY"); field.setDataType(DBFField.DBFDataType.NUMERIC); field.setFieldLength(10); field.setDecimalCount(4); input.getAttributeTable().addField(field); // initialize the shapefile. ShapeType inputType = input.getShapeType(); for (ShapeFileRecord record : input.records) { switch (inputType) { case POLYGON: whitebox.geospatialfiles.shapefile.Polygon recPolygon = (whitebox.geospatialfiles.shapefile.Polygon) (record.getGeometry()); vertices = recPolygon.getPoints(); coordArray = new CoordinateArraySequence(vertices.length); j = 0; for (i = 0; i < vertices.length; i++) { coordArray.setOrdinate(j, 0, vertices[i][0]); coordArray.setOrdinate(j, 1, vertices[i][1]); j++; } geom = factory.createMultiPoint(coordArray); ch = new ConvexHull(geom); hullArea = ch.getConvexHull().getArea(); featureArea = recPolygon.getArea(); break; case POLYGONZ: PolygonZ recPolygonZ = (PolygonZ) (record.getGeometry()); vertices = recPolygonZ.getPoints(); coordArray = new CoordinateArraySequence(vertices.length); j = 0; for (i = 0; i < vertices.length; i++) { coordArray.setOrdinate(j, 0, vertices[i][0]); coordArray.setOrdinate(j, 1, vertices[i][1]); j++; } geom = factory.createMultiPoint(coordArray); ch = new ConvexHull(geom); hullArea = ch.getConvexHull().getArea(); featureArea = recPolygonZ.getArea(); break; case POLYGONM: PolygonM recPolygonM = (PolygonM) (record.getGeometry()); vertices = recPolygonM.getPoints(); coordArray = new CoordinateArraySequence(vertices.length); j = 0; for (i = 0; i < vertices.length; i++) { coordArray.setOrdinate(j, 0, vertices[i][0]); coordArray.setOrdinate(j, 1, vertices[i][1]); j++; } geom = factory.createMultiPoint(coordArray); ch = new ConvexHull(geom); hullArea = ch.getConvexHull().getArea(); featureArea = recPolygonM.getArea(); break; } recNum = record.getRecordNumber() - 1; Object[] recData = input.getAttributeTable().getRecord(recNum); if (hullArea > 0) { recData[recData.length - 1] = Math.abs(1 - featureArea / hullArea); } else { recData[recData.length - 1] = 0d; } input.getAttributeTable().updateRecord(recNum, recData); if (cancelOp) { cancelOperation(); return; } progress = (int) (record.getRecordNumber() / numberOfRecords * 100); updateProgress(progress); } // returning the database file will result in it being opened in the Whitebox GUI. returnData(input.getDatabaseFile()); } catch (OutOfMemoryError oe) { myHost.showFeedback("An out-of-memory error has occurred during operation."); } catch (Exception e) { myHost.showFeedback("An error has occurred during operation. See log file for details."); myHost.logException("Error in " + getDescriptiveName(), e); } finally { updateProgress("Progress: ", 0); // tells the main application that this process is completed. amIActive = false; myHost.pluginComplete(); } } /** * Used to execute this plugin tool. */ @Override public void run() { String inputFile = args[0]; if (inputFile.toLowerCase().contains(".dep")) { calculateRaster(); } else if (inputFile.toLowerCase().contains(".shp")) { calculateVector(); } else { showFeedback("There was a problem reading the input file."); } } }
mit
Adyen/adyen-java-api-library
src/main/java/com/adyen/model/marketpay/AccountStateLimit.java
2874
/* * ###### * ###### * ############ ####( ###### #####. ###### ############ ############ * ############# #####( ###### #####. ###### ############# ############# * ###### #####( ###### #####. ###### ##### ###### ##### ###### * ###### ###### #####( ###### #####. ###### ##### ##### ##### ###### * ###### ###### #####( ###### #####. ###### ##### ##### ###### * ############# ############# ############# ############# ##### ###### * ############ ############ ############# ############ ##### ###### * ###### * ############# * ############ * * Adyen Java API Library * * Copyright (c) 2017 Adyen B.V. * This file is open source and available under the MIT license. * See the LICENSE file for more info. */ package com.adyen.model.marketpay; import com.google.gson.annotations.SerializedName; import java.util.Objects; import static com.adyen.util.Util.toIndentedString; /** * AccountStateLimit */ public class AccountStateLimit { @SerializedName("amount") private Long amount = null; @SerializedName("currency") private String currency = null; public AccountStateLimit amount(Long amount) { this.amount = amount; return this; } /** * the amount value in minor units * * @return amount **/ public Long getAmount() { return amount; } public void setAmount(Long amount) { this.amount = amount; } public AccountStateLimit currency(String currency) { this.currency = currency; return this; } /** * the amount three letter currency code (ISO 4217) * * @return currency **/ public String getCurrency() { return currency; } public void setCurrency(String currency) { this.currency = currency; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } AccountStateLimit accountStateLimit = (AccountStateLimit) o; return Objects.equals(this.amount, accountStateLimit.amount) && Objects.equals(this.currency, accountStateLimit.currency); } @Override public int hashCode() { return Objects.hash(amount, currency); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class AccountStateLimit {\n"); sb.append(" amount: ").append(toIndentedString(amount)).append("\n"); sb.append(" currency: ").append(toIndentedString(currency)).append("\n"); sb.append("}"); return sb.toString(); } }
mit
aserg-ufmg/RefDiff
refdiff-core/src/test/java/refdiff/test/util/CstDiffMatchers.java
5269
package refdiff.test.util; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Set; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeDiagnosingMatcher; import refdiff.core.diff.CstDiff; import refdiff.core.diff.CstRootHelper; import refdiff.core.diff.Relationship; import refdiff.core.diff.RelationshipType; import refdiff.core.cst.CstNode; import refdiff.core.cst.CstRoot; public class CstDiffMatchers { public static RelationshipQuery relationship(RelationshipType type, NodeQuery nodeBefore, NodeQuery nodeAfter) { return new RelationshipQuery(type, nodeBefore, nodeAfter); } public static NodeQuery node(String... path) { return new NodeQuery(path); } public static CstDiffMatcher contains(RelationshipQuery... queries) { return new CstDiffMatcher(false, queries); } public static CstDiffMatcher containsOnly(RelationshipQuery... queries) { return new CstDiffMatcher(true, queries); } public static Matcher<CstDiff> doesntContain(RelationshipQuery... queries) { return new CstDiffMatcherDoesntContain(queries); } public static class NodeQuery { final String[] namePath; public NodeQuery(String... namePath) { this.namePath = namePath; } @Override public String toString() { return Arrays.toString(namePath); } } public static class RelationshipQuery { final RelationshipType type; final NodeQuery nodeQBefore; final NodeQuery nodeQAfter; public RelationshipQuery(RelationshipType type, NodeQuery nodeQBefore, NodeQuery nodeQAfter) { this.type = type; this.nodeQBefore = nodeQBefore; this.nodeQAfter = nodeQAfter; } @Override public String toString() { return String.format("%s(%s, %s)", type, nodeQBefore, nodeQAfter); } public Optional<Relationship> find(CstDiff diff) { CstRoot before = diff.getBefore(); CstRoot after = diff.getAfter(); Optional<CstNode> oNodeBefore = CstRootHelper.findByNamePath(before, nodeQBefore.namePath); Optional<CstNode> oNodeAfter = CstRootHelper.findByNamePath(after, nodeQAfter.namePath); return oNodeBefore.flatMap(nodeBefore -> oNodeAfter.flatMap(nodeAfter -> { Relationship r = new Relationship(type, nodeBefore, nodeAfter); if (diff.getRelationships().contains(r)) { return Optional.of(r); } return Optional.empty(); })); } } private static class CstDiffMatcher extends TypeSafeDiagnosingMatcher<CstDiff> { RelationshipQuery[] queries; boolean computeFp; public CstDiffMatcher(boolean computeFp, RelationshipQuery... queries) { this.computeFp = computeFp; this.queries = queries; } @Override public void describeTo(Description description) { description.appendText(queries.length + " true positives"); } @Override protected boolean matchesSafely(CstDiff diff, Description mismatchDescription) { List<RelationshipQuery> falseNegatives = new ArrayList<>(); Set<Relationship> truePositives = new HashSet<>(); Set<Relationship> falsePositives = new HashSet<>(diff.getRelationships()); for (RelationshipQuery query : queries) { Optional<Relationship> optional = query.find(diff); if (optional.isPresent()) { truePositives.add(optional.get()); falsePositives.remove(optional.get()); } else { falseNegatives.add(query); } } int tp = truePositives.size(); int fp = computeFp ? falsePositives.size() : 0; int fn = falseNegatives.size(); if (fn != 0 || fp != 0) { if (computeFp) { mismatchDescription.appendText(String.format("%d true positives, %d false positives, %d false negatives", tp, fp, fn)); } else { mismatchDescription.appendText(String.format("%d true positives, %d false negatives", tp, fn)); } if (!falseNegatives.isEmpty()) { mismatchDescription.appendValueList("\nFalse negatives:\n", "\n", "", falseNegatives); } if (!falsePositives.isEmpty()) { mismatchDescription.appendValueList("\nFalse positives:\n", "\n", "", falsePositives); } return false; } return true; } } private static class CstDiffMatcherDoesntContain extends TypeSafeDiagnosingMatcher<CstDiff> { RelationshipQuery[] queries; public CstDiffMatcherDoesntContain(RelationshipQuery... queries) { this.queries = queries; } @Override public void describeTo(Description description) { description.appendText(queries.length + " true positives"); } @Override protected boolean matchesSafely(CstDiff diff, Description mismatchDescription) { int truePositives = 0; int falsePositives = 0; for (RelationshipQuery query : queries) { Optional<Relationship> optional = query.find(diff); if (optional.isPresent()) { falsePositives++; } else { truePositives++; } } if (falsePositives != 0) { mismatchDescription.appendText(String.format( "%d true positives, %d false positives", truePositives, falsePositives)); return false; } return true; } } }
mit
ragnor/simple-spring-memcached
integration-test/src/main/java/com/google/code/ssm/test/dao/MultiCacheDAO.java
1548
package com.google.code.ssm.test.dao; /* * Copyright (c) 2012-2019 Jakub Białek * * 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. */ /** * * @author Jakub Białek * */ public interface MultiCacheDAO { void storeToDefault(final String key, final String value); String getFromDefault(final String key); void removeFromDefault(final String key); void storeToDedicated(final String key, final String value); String getFromDedicated(final String key); void removeFromDedicated(final String key); }
mit
selvasingh/azure-sdk-for-java
sdk/search/azure-search-documents/src/main/java/com/azure/search/documents/indexes/models/BM25SimilarityAlgorithm.java
3476
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.search.documents.indexes.models; import com.azure.core.annotation.Fluent; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; /** * Ranking function based on the Okapi BM25 similarity algorithm. BM25 is a * TF-IDF-like algorithm that includes length normalization (controlled by the * 'b' parameter) as well as term frequency saturation (controlled by the 'k1' * parameter). */ @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "@odata.type") @JsonTypeName("#Microsoft.Azure.Search.BM25Similarity") @Fluent public final class BM25SimilarityAlgorithm extends SimilarityAlgorithm { /* * This property controls the scaling function between the term frequency * of each matching terms and the final relevance score of a document-query * pair. By default, a value of 1.2 is used. A value of 0.0 means the score * does not scale with an increase in term frequency. */ @JsonProperty(value = "k1") private Double k1; /* * This property controls how the length of a document affects the * relevance score. By default, a value of 0.75 is used. A value of 0.0 * means no length normalization is applied, while a value of 1.0 means the * score is fully normalized by the length of the document. */ @JsonProperty(value = "b") private Double b; /** * Get the k1 property: This property controls the scaling function between * the term frequency of each matching terms and the final relevance score * of a document-query pair. By default, a value of 1.2 is used. A value of * 0.0 means the score does not scale with an increase in term frequency. * * @return the k1 value. */ public Double getK1() { return this.k1; } /** * Set the k1 property: This property controls the scaling function between * the term frequency of each matching terms and the final relevance score * of a document-query pair. By default, a value of 1.2 is used. A value of * 0.0 means the score does not scale with an increase in term frequency. * * @param k1 the k1 value to set. * @return the BM25Similarity object itself. */ public BM25SimilarityAlgorithm setK1(Double k1) { this.k1 = k1; return this; } /** * Get the b property: This property controls how the length of a document * affects the relevance score. By default, a value of 0.75 is used. A * value of 0.0 means no length normalization is applied, while a value of * 1.0 means the score is fully normalized by the length of the document. * * @return the b value. */ public Double getB() { return this.b; } /** * Set the b property: This property controls how the length of a document * affects the relevance score. By default, a value of 0.75 is used. A * value of 0.0 means no length normalization is applied, while a value of * 1.0 means the score is fully normalized by the length of the document. * * @param b the b value to set. * @return the BM25Similarity object itself. */ public BM25SimilarityAlgorithm setB(Double b) { this.b = b; return this; } }
mit
selvasingh/azure-sdk-for-java
sdk/spring/azure-spring-boot/src/main/java/com/microsoft/azure/spring/autoconfigure/aad/AzureADGraphClient.java
10706
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.microsoft.azure.spring.autoconfigure.aad; import com.fasterxml.jackson.databind.ObjectMapper; import com.microsoft.aad.msal4j.ClientCredentialFactory; import com.microsoft.aad.msal4j.ConfidentialClientApplication; import com.microsoft.aad.msal4j.IAuthenticationResult; import com.microsoft.aad.msal4j.IClientCredential; import com.microsoft.aad.msal4j.MsalServiceException; import com.microsoft.aad.msal4j.OnBehalfOfParameters; import com.microsoft.aad.msal4j.UserAssertion; import com.nimbusds.oauth2.sdk.http.HTTPResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.authority.SimpleGrantedAuthority; import javax.naming.ServiceUnavailableException; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.UUID; import java.util.concurrent.ExecutionException; import java.util.stream.Collectors; /** * Microsoft Graph client encapsulation. */ public class AzureADGraphClient { private static final Logger LOGGER = LoggerFactory.getLogger(AzureADGraphClient.class); private static final SimpleGrantedAuthority DEFAULT_AUTHORITY = new SimpleGrantedAuthority("ROLE_USER"); private static final String DEFAULT_ROLE_PREFIX = "ROLE_"; private static final String MICROSOFT_GRAPH_SCOPE = "https://graph.microsoft.com/user.read"; private static final String AAD_GRAPH_API_SCOPE = "https://graph.windows.net/user.read"; // We use "aadfeed5" as suffix when client library is ADAL, upgrade to "aadfeed6" for MSAL private static final String REQUEST_ID_SUFFIX = "aadfeed6"; private static final String V2_VERSION_ENV_FLAG = "v2-graph"; private final String clientId; private final String clientSecret; private final ServiceEndpoints serviceEndpoints; private final AADAuthenticationProperties aadAuthenticationProperties; private final boolean graphApiVersionIsV2; public AzureADGraphClient(String clientId, String clientSecret, AADAuthenticationProperties aadAuthProps, ServiceEndpointsProperties serviceEndpointsProps) { this.clientId = clientId; this.clientSecret = clientSecret; this.aadAuthenticationProperties = aadAuthProps; this.serviceEndpoints = serviceEndpointsProps.getServiceEndpoints(aadAuthProps.getEnvironment()); this.graphApiVersionIsV2 = aadAuthProps.getEnvironment().contains(V2_VERSION_ENV_FLAG); } private String getUserMemberships(String accessToken, String urlString) throws IOException { URL url = new URL(urlString); final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // Set the appropriate header fields in the request header. if (this.graphApiVersionIsV2) { connection.setRequestMethod(HttpMethod.GET.toString()); connection.setRequestProperty(HttpHeaders.AUTHORIZATION, String.format("Bearer %s", accessToken)); connection.setRequestProperty(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE); connection.setRequestProperty(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE); } else { connection.setRequestMethod(HttpMethod.GET.toString()); connection.setRequestProperty("api-version", "1.6"); connection.setRequestProperty(HttpHeaders.AUTHORIZATION, String.format("Bearer %s", accessToken)); connection.setRequestProperty(HttpHeaders.ACCEPT, "application/json;odata=minimalmetadata"); } final String responseInJson = getResponseString(connection); final int responseCode = connection.getResponseCode(); if (responseCode == HTTPResponse.SC_OK) { return responseInJson; } else { throw new IllegalStateException( "Response is not " + HTTPResponse.SC_OK + ", response json: " + responseInJson); } } private String getUrlStringFromODataNextLink(String odataNextLink) { if (this.graphApiVersionIsV2) { return odataNextLink; } else { String skipToken = odataNextLink.split("/memberOf\\?")[1]; return serviceEndpoints.getAadMembershipRestUri() + "&" + skipToken; } } private static String getResponseString(HttpURLConnection connection) throws IOException { try (BufferedReader reader = new BufferedReader( new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) { final StringBuilder stringBuffer = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { stringBuffer.append(line); } return stringBuffer.toString(); } } public List<UserGroup> getGroups(String graphApiToken) throws IOException { final List<UserGroup> userGroupList = new ArrayList<>(); final ObjectMapper objectMapper = JacksonObjectMapperFactory.getInstance(); String urlString = serviceEndpoints.getAadMembershipRestUri(); while (urlString != null) { String responseInJson = getUserMemberships(graphApiToken, urlString); UserGroups userGroups = objectMapper.readValue(responseInJson, UserGroups.class); userGroups.getValue() .stream() .filter(this::isMatchingUserGroupKey) .forEach(userGroupList::add); urlString = Optional.of(userGroups) .map(UserGroups::getOdataNextLink) .map(this::getUrlStringFromODataNextLink) .orElse(null); } return userGroupList; } /** * Checks that the UserGroup has a Group object type. * * @param userGroup - userGroup * @return true if the json node contains the correct key, and expected value to identify a user group. */ private boolean isMatchingUserGroupKey(final UserGroup userGroup) { return userGroup.getObjectType().equals(aadAuthenticationProperties.getUserGroup().getValue()); } public Set<GrantedAuthority> getGrantedAuthorities(String graphApiToken) throws IOException { // Fetch the authority information from the protected resource using accessToken final List<UserGroup> groups = getGroups(graphApiToken); // Map the authority information to one or more GrantedAuthority's and add it to mappedAuthorities return convertGroupsToGrantedAuthorities(groups); } /** * Converts UserGroup list to Set of GrantedAuthorities * * @param groups user groups * @return granted authorities */ public Set<GrantedAuthority> convertGroupsToGrantedAuthorities(final List<UserGroup> groups) { // Map the authority information to one or more GrantedAuthority's and add it to mappedAuthorities final Set<GrantedAuthority> mappedAuthorities = groups.stream() .filter(this::isValidUserGroupToGrantAuthority) .map(userGroup -> new SimpleGrantedAuthority(DEFAULT_ROLE_PREFIX + userGroup.getDisplayName())) .collect(Collectors.toCollection(LinkedHashSet::new)); if (mappedAuthorities.isEmpty()) { mappedAuthorities.add(DEFAULT_AUTHORITY); } return mappedAuthorities; } /** * Determines if this is a valid {@link UserGroup} to build to a GrantedAuthority. * <p> * If the {@link AADAuthenticationProperties.UserGroupProperties#getAllowedGroups()} * contains the {@link UserGroup#getDisplayName()} return * true. * * @param group - User Group to check if valid to grant an authority to. * @return true if allowed-groups contains the UserGroup display name */ private boolean isValidUserGroupToGrantAuthority(final UserGroup group) { return aadAuthenticationProperties.getUserGroup().getAllowedGroups().contains(group.getDisplayName()); } public IAuthenticationResult acquireTokenForGraphApi(String idToken, String tenantId) throws ServiceUnavailableException { final IClientCredential clientCredential = ClientCredentialFactory.createFromSecret(clientSecret); final UserAssertion assertion = new UserAssertion(idToken); IAuthenticationResult result = null; try { final ConfidentialClientApplication application = ConfidentialClientApplication .builder(clientId, clientCredential) .authority(serviceEndpoints.getAadSigninUri() + tenantId + "/") .correlationId(getCorrelationId()) .build(); final Set<String> scopes = new HashSet<>(); scopes.add(graphApiVersionIsV2 ? MICROSOFT_GRAPH_SCOPE : AAD_GRAPH_API_SCOPE); final OnBehalfOfParameters onBehalfOfParameters = OnBehalfOfParameters.builder(scopes, assertion).build(); result = application.acquireToken(onBehalfOfParameters).get(); } catch (ExecutionException | InterruptedException | MalformedURLException e) { // Handle conditional access policy final Throwable cause = e.getCause(); if (cause instanceof MsalServiceException) { final MsalServiceException exception = (MsalServiceException) cause; if (exception.claims() != null && !exception.claims().isEmpty()) { throw exception; } } LOGGER.error("acquire on behalf of token for graph api error", e); } if (result == null) { throw new ServiceUnavailableException("unable to acquire on-behalf-of token for client " + clientId); } return result; } private static String getCorrelationId() { final String uuid = UUID.randomUUID().toString(); return uuid.substring(0, uuid.length() - REQUEST_ID_SUFFIX.length()) + REQUEST_ID_SUFFIX; } }
mit
wombling/mobilequiz
mobilequiz/src/main/java/com/wombling/mobilequiz/persistance/StoredQuestionDAO.java
405
package com.wombling.mobilequiz.persistance; import java.util.List; public interface StoredQuestionDAO { public StoredQuestion save(StoredQuestion entity); public StoredQuestion findById(String id); public void delete(String id); public void delete(StoredQuestion entity); public void deleteAll(); public List<StoredQuestion> findAll(); public List<StoredQuestion> findByCurrentTrue(); }
mit
devinsba/dropwizard-spring-template
src/main/java/com/briandevins/healthcheck/TestHealthcheck.java
667
package com.briandevins.healthcheck; import com.briandevins.config.DropwizardConfig; import com.codahale.metrics.health.HealthCheck; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; /** * Created by devinsba on 8/1/14. */ @Controller public class TestHealthcheck extends HealthCheck { @Autowired private DropwizardConfig config; @Override protected Result check() throws Exception { if (config.getValue().equalsIgnoreCase("test")) { return Result.healthy(); } else { return Result.unhealthy("Config: [value] is not test"); } } }
mit
Da-Technomancer/Crossroads
src/main/java/com/Da_Technomancer/crossroads/tileentities/technomancy/CosAxisTileEntity.java
1216
package com.Da_Technomancer.crossroads.tileentities.technomancy; import com.Da_Technomancer.crossroads.API.Properties; import com.Da_Technomancer.crossroads.blocks.ModBlocks; import net.minecraft.util.EnumFacing; import javax.annotation.Nullable; public class CosAxisTileEntity extends AbstractMathAxisTE{ private EnumFacing facing; @Override protected double getOutSpeed(double speed1, double speed2){ return Math.cos(speed1); } @Override protected EnumFacing getInOne(){ if(facing == null){ if(!world.getBlockState(pos).getProperties().containsKey(Properties.FACING)){ return EnumFacing.DOWN; } facing = world.getBlockState(pos).getValue(Properties.FACING); } return facing.getOpposite(); } @Nullable @Override protected EnumFacing getInTwo(){ return null; } @Override protected EnumFacing getOut(){ if(facing == null){ if(!world.getBlockState(pos).getProperties().containsKey(Properties.FACING)){ return EnumFacing.DOWN; } facing = world.getBlockState(pos).getValue(Properties.FACING); } return facing; } @Override protected EnumFacing getBattery(){ return EnumFacing.DOWN; } @Override protected void cleanDirCache(){ facing = null; } }
mit
sorlok/ornagai-mobile
src/ornagai/mobile/gui/FormController.java
577
/* * This code is licensed under the terms of the MIT License. * Please see the file LICENSE.TXT for the full license text. */ package ornagai.mobile.gui; /** * General hook to the main MIDlet. Centralizes control. * * @author Seth N. Hetu */ public interface FormController { public abstract void switchToSplashForm(); public abstract void switchToOptionsForm(); public abstract void switchToDictionaryForm(); public abstract boolean reloadDictionary(); public abstract void waitForDictionaryToLoad(); public abstract void closeProgram(); }
mit
dineshp2/Popular-Movies-Stage-2
app/src/main/java/app/com/example/android/popularmoviesstage1/model/TrailerResult.java
1399
package app.com.example.android.popularmoviesstage1.model; import android.os.Parcel; import android.os.Parcelable; import java.util.ArrayList; /** * Created by dinesh on 20/4/16. */ public class TrailerResult implements Parcelable { private int id; private ArrayList<Trailer> results; public TrailerResult(int id,ArrayList<Trailer> results) { this.id = id; this.results = results; } public int getId() { return id; } public void setId(int id) { this.id = id; } public ArrayList<Trailer> getResults() { return results; } public void setResults(ArrayList<Trailer> results) { this.results = results; } public int describeContents() { return 0; } public void writeToParcel(Parcel out,int flags) { out.writeInt(id); out.writeList(results); } public static final Parcelable.Creator<TrailerResult> CREATOR = new Parcelable.Creator<TrailerResult>(){ public TrailerResult createFromParcel(Parcel in) { return new TrailerResult(in); } public TrailerResult[] newArray(int size) { return new TrailerResult[size]; } }; private TrailerResult(Parcel in) { id = in.readInt(); results = in.readArrayList(null); } }
mit
wizzardo/http-servlet-api
src/main/java/com/wizzardo/servlet/streams/ServletEpollInputStream.java
2975
package com.wizzardo.servlet.streams; import com.wizzardo.http.EpollInputStream; import com.wizzardo.servlet.HttpRequest; import com.wizzardo.servlet.ServletHttpConnection; import javax.servlet.ReadListener; import javax.servlet.ServletInputStream; import java.io.IOException; /** * @author: wizzardo * Date: 05.11.14 */ public class ServletEpollInputStream extends EpollInputStream { protected AsyncServletInputStream asyncServletInputStream; public ServletEpollInputStream(ServletHttpConnection connection, byte[] buffer, int currentOffset, int currentLimit, long contentLength) { super(connection, buffer, currentOffset, currentLimit, contentLength); asyncServletInputStream = new AsyncServletInputStream(connection.getRequest()); } @Override protected void fillBuffer() throws IOException { super.fillBuffer(); } @Override protected void waitForData() throws IOException { if (!asyncServletInputStream.request.isAsyncStarted()) super.waitForData(); } @Override protected void wakeUp() { if (!asyncServletInputStream.request.isAsyncStarted()) super.wakeUp(); else if (asyncServletInputStream.listener != null) asyncServletInputStream.listener.onDataAvailable(); } public ServletInputStream getServletInputStream() { return asyncServletInputStream; } class AsyncServletInputStream extends ServletInputStream { protected HttpRequest request; protected volatile ReadListenerWrapper listener; public AsyncServletInputStream(HttpRequest request) { this.request = request; } @Override public boolean isFinished() { return ServletEpollInputStream.this.isFinished(); } @Override public boolean isReady() { int available = ServletEpollInputStream.this.available(); if (available == 0) { try { ServletEpollInputStream.this.fillBuffer(); } catch (Exception e) { if (listener != null) listener.onError(e); else e.printStackTrace(); } available = ServletEpollInputStream.this.available(); } return available != 0; } @Override public void setReadListener(ReadListener readListener) { if (listener != null) throw new IllegalStateException("Listener was already set"); listener = new ReadListenerWrapper(readListener); } @Override public int read() throws IOException { return ServletEpollInputStream.this.read(); } @Override public int read(byte[] b, int off, int len) throws IOException { return ServletEpollInputStream.this.read(b, off, len); } } }
mit
Cynthia0217/KinectPV2
Build_libs/KinectPV2_Eclipse/src/KinectPV2/Device.java
21107
package KinectPV2; /* Copyright (C) 2014 Thomas Sanchez Lengeling. KinectPV2, Kinect for Windows v2 library for processing 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. */ import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.util.ArrayList; import com.jogamp.common.nio.Buffers; import processing.core.PApplet; import processing.core.PImage; import processing.core.PVector; /** * Initilice Device * * @author Thomas Sanchez Lengeling * */ public class Device implements Constants, FaceProperties, SkeletonProperties, Runnable { static { int arch = Integer.parseInt(System.getProperty("sun.arch.data.model")); String platformName = System.getProperty("os.name"); platformName = platformName.toLowerCase(); System.out.println(arch + " " + platformName); if (arch == 64) { System.loadLibrary("Kinect20.Face"); System.loadLibrary("KinectPV2"); System.out.println("Loading KinectV2"); } else { System.out.println("not compatible with 32bits"); } } // IMAGES private Image colorImg; private Image depthImg; private Image depth256Img; private Image infraredImg; private Image infraredLongExposureImg; private Image bodyTrackImg; private Image [] bodyTrackUsersImg; private Image depthMaskImg; private Image pointCloudDepthImg; // SKELETON private KSkeleton[] skeletonDepth; private KSkeleton[] skeleton3d; private KSkeleton[] skeletonColor; private HDFaceData[] HDFace; private FaceData[] faceData; protected boolean runningKinect; protected boolean stopDevice; FloatBuffer pointCloudDepthPos; FloatBuffer pointCloudColorPos; FloatBuffer colorChannelBuffer; //color buffers IntBuffer depthColorBuffer; IntBuffer irColorBuffer; IntBuffer registeredColorBuffer; private PApplet parent; private long ptr; private boolean startSensor; private String Version = "0.7.6"; /** * Start device * * @param _p * PApplet */ public Device(PApplet _p) { parent = _p; // SETUP IMAGES colorImg = new Image(parent, WIDTHColor, HEIGHTColor, PImage.ARGB); depthImg = new Image(parent, WIDTHDepth, HEIGHTDepth, PImage.ALPHA); depth256Img = new Image(parent, WIDTHDepth, HEIGHTDepth, PImage.ALPHA); infraredImg = new Image(parent, WIDTHDepth, HEIGHTDepth, PImage.ALPHA); bodyTrackImg = new Image(parent, WIDTHDepth, HEIGHTDepth, PImage.RGB); depthMaskImg = new Image(parent, WIDTHDepth, HEIGHTDepth, PImage.RGB); bodyTrackUsersImg = new Image[BODY_COUNT]; for (int i = 0; i < BODY_COUNT; i++) { bodyTrackUsersImg[i] = new Image(parent, WIDTHDepth, HEIGHTDepth, PImage.RGB); } infraredLongExposureImg = new Image(parent, WIDTHDepth, HEIGHTDepth, PImage.ALPHA); pointCloudDepthImg = new Image(parent, WIDTHDepth, HEIGHTDepth, PImage.ALPHA); pointCloudDepthPos = Buffers.newDirectFloatBuffer(WIDTHDepth * HEIGHTDepth * 3); pointCloudColorPos = Buffers.newDirectFloatBuffer(WIDTHColor * HEIGHTColor * 3); colorChannelBuffer = Buffers.newDirectFloatBuffer(WIDTHColor * HEIGHTColor * 3); // SETUP SKELETON skeletonDepth = new KSkeleton[BODY_COUNT]; for (int i = 0; i < BODY_COUNT; i++) { skeletonDepth[i] = new KSkeleton(); } skeleton3d = new KSkeleton[BODY_COUNT]; for (int i = 0; i < BODY_COUNT; i++) { skeleton3d[i] = new KSkeleton(); } skeletonColor = new KSkeleton[BODY_COUNT]; for (int i = 0; i < BODY_COUNT; i++) { skeletonColor[i] = new KSkeleton(); } // SETUP FACEDATA faceData = new FaceData[BODY_COUNT]; for (int i = 0; i < BODY_COUNT; i++) { faceData[i] = new FaceData(); } HDFace = new HDFaceData[BODY_COUNT]; for (int i = 0; i < BODY_COUNT; i++) { HDFace[i] = new HDFaceData(); } //colors depthColorBuffer = Buffers.newDirectIntBuffer(WIDTHDepth * HEIGHTDepth); irColorBuffer = Buffers.newDirectIntBuffer(WIDTHDepth * HEIGHTDepth); registeredColorBuffer = Buffers.newDirectIntBuffer(WIDTHDepth * HEIGHTDepth); startSensor = false; jniDevice(); } protected void initDevice() { startSensor = jniInit(); //String load = jniVersion(); //System.out.println("Version: " + load); System.out.println("Version: " + Version); if (startSensor == false) { System.out.println("ERROR STARTING KINECT V2"); parent.exit(); } if (startSensor) { runningKinect = true; (new Thread(this)).start(); } } public void closeDevice(){ runningKinect = false; stopDevice(); cleanDevice(); } // IMAGES /** * Get Color Image as PImage 1920 x 1080 * * @return PImage */ public PImage getColorImage() { int[] colorData = jniGetColorData(); PApplet.arrayCopy(colorData, 0, colorImg.pixels(), 0, colorImg.getImgSize()); colorImg.updatePixels(); PApplet.arrayCopy(colorData, 0, colorImg.rawIntData, 0, colorImg.getImgSize()); return colorImg.img; } public int [] getRawColor(){ return colorImg.rawIntData; } /** * Get Depth Image as PImage 512 x 424 * * @return PImage */ public PImage getDepthImage() { int [] depthData = jniGetDepth16Data(); PApplet.arrayCopy(depthData, 0, depthImg.pixels(), 0, depthImg.getImgSize()); depthImg.updatePixels(); return depthImg.img; } /** * Get Depth 256 strip data 512 x 424 * @return PImage */ public PImage getDepth256Image() { int[] depth256Data = jniGetDepth256Data(); PApplet.arrayCopy(depth256Data, 0, depth256Img.pixels(), 0, depth256Img.getImgSize()); depth256Img.updatePixels(); // jniDepthReadyCopy(true); return depth256Img.img; } /** * Obtain the raw depth data values in mm from 0 to 4500 * @return array of int */ public int [] getRawDepthData(){ return jniGetRawDepth16Data(); } /** * Obtain the raw depth data values in mm from 0 to 256 * Data based on the getDepth256Image * @return array of int */ public int [] getRawDepth256Data(){ return jniGetRawDepth256Data(); } /** * Get Depth Mask Image, outline color of the users. * * @return PImage */ public PImage getDepthMaskImage() { int[] depthMaskData = jniGetDepthMask(); PApplet.arrayCopy(depthMaskData, 0, depthMaskImg.pixels(), 0, depthMaskImg.getImgSize()); depthMaskImg.updatePixels(); // jniDepthReadyCopy(true); return depthMaskImg.img; } /** * Get InfraredImage as PImage 512 x 424 * * @return PImage */ public PImage getInfraredImage() { int[] infraredData = jniGetInfraredData(); PApplet.arrayCopy(infraredData, 0, infraredImg.pixels(), 0, infraredImg.getImgSize()); infraredImg.updatePixels(); return infraredImg.img; } /** * Get BodyTracking as PImage 512 x 424 * * @return PImage */ public PImage getBodyTrackImage() { int[] bodyTrackData = jniGetBodyTrack(); PApplet.arrayCopy(bodyTrackData, 0, bodyTrackImg.pixels(), 0, bodyTrackImg.getImgSize()); bodyTrackImg.updatePixels(); return bodyTrackImg.img; } /** * Get Independent Body Index Track * * @param index * @return */ public ArrayList getBodyTrackUser() { ArrayList<PImage> listBodyTack = new ArrayList<PImage>(0); int [] usersIds = jniGetBodyTrackIds(); for(int i = 0; i < usersIds.length; i++){ if( usersIds[i] == 1){ int[] rawData = jniGetBodyIndexUser(i); PApplet.arrayCopy(rawData, 0, bodyTrackUsersImg[i].pixels(), 0, bodyTrackUsersImg[i].getImgSize()); bodyTrackUsersImg[i].updatePixels(); listBodyTack.add(bodyTrackUsersImg[i].img); } } return listBodyTack; } /** * Get the Number of currently track users based on the Body Track frame * @return Number of Users */ public int getNumOfUsers(){ return jniGetNumberOfUsers(); } /** * Get Long Exposure Infrared Image as PImage 512 x 424 * * @return PImage */ public PImage getInfraredLongExposureImage() { int[] longExposureData = jniGetInfraredLongExposure(); PApplet.arrayCopy(longExposureData, 0, infraredLongExposureImg.pixels(), 0, infraredLongExposureImg.getImgSize()); infraredLongExposureImg.updatePixels(); return infraredLongExposureImg.img; } /** * Get Skeleton as Joints with Positions and Tracking states in 3D, (x,y,z) * joint and orientation, Skeleton up to 6 users * * @return Skeleton [] */ public ArrayList<KSkeleton> getSkeleton3d() { ArrayList<KSkeleton> arraySkeleton = new ArrayList<KSkeleton>(); float[] rawData = jniGetSkeleton3D(); for (int i = 0; i < BODY_COUNT; i++) { int indexJoint = i * (JointType_Count+1) * 9 + (JointType_Count+1) * 9 - 1; if(rawData[indexJoint] == 1.0){ skeleton3d[i].createSkeletonData(rawData, i); arraySkeleton.add(skeleton3d[i]); } } return arraySkeleton; } /** * Get Skeleton as Joints with Positions and Tracking states base on Depth * Image, Skeleton with only (x, y) skeleton position mapped to the depth * Image, get z value from the Depth Image. * * @return Skeleton [] */ public ArrayList<KSkeleton> getSkeletonDepthMap() { ArrayList<KSkeleton> arraySkeleton = new ArrayList<KSkeleton>(); float[] rawData = jniGetSkeletonDepth(); for (int i = 0; i < BODY_COUNT; i++) { int indexJoint = i * (JointType_Count+1) * 9 + (JointType_Count+1) * 9 - 1; if(rawData[indexJoint] == 1.0){ skeletonDepth[i].createSkeletonData(rawData, i); arraySkeleton.add(skeletonDepth[i]); } } return arraySkeleton; } /** * Get Skeleton as Joints with Positions and Tracking states base on color * Image, * * @return Skeleton [] */ public ArrayList<KSkeleton> getSkeletonColorMap() { ArrayList<KSkeleton> arraySkeleton = new ArrayList<KSkeleton>(); float[] rawData = jniGetSkeletonColor(); for (int i = 0; i < BODY_COUNT; i++) { int indexJoint = i * (JointType_Count+1) * 9 + (JointType_Count+1) * 9 - 1; if(rawData[indexJoint] == 1.0){ skeletonColor[i].createSkeletonData(rawData, i); arraySkeleton.add(skeletonColor[i]); } } return arraySkeleton; } // FACE DATA /** * Generate Face Data for color map and infrared map */ public void generateFaceData() { float[] rawFaceColorData = jniGetFaceColorData(); float[] rawFaceInfraredData = jniGetFaceInfraredData(); for (int i = 0; i < BODY_COUNT; i++) faceData[i].createFaceData(rawFaceColorData, rawFaceInfraredData, i); } /** * Obtain Vertex positions corresponding the HD Color frame * @return */ public ArrayList<HDFaceData> getHDFaceVertex() { ArrayList<HDFaceData> HDFArray = new ArrayList<HDFaceData>(); float[] rawData = jniGetHDFaceDetection(); for (int i = 0; i < BODY_COUNT; i++){ HDFace[i].createHDFaceVertexData(rawData, i); if(HDFace[i].isTracked()){ HDFArray.add(HDFace[i]); } } return HDFArray; } /** * Obtain the face data, 5 face points and mode detection from each user * @return ArrayList of FaceData */ public ArrayList<FaceData> getFaceData() { ArrayList<FaceData> faceArray = new ArrayList<FaceData>(); for (int i = 0; i < BODY_COUNT; i++){ if(faceData[i].isFaceTracked()){ faceArray.add(faceData[i]); } } return faceArray; } // POINT CLOUDS /** * Get Point Cloud Depth Map as FloatBuffer, transform to a float array with .array(), or get values with get(index) * * @return FloatBuffer */ public FloatBuffer getPointCloudDepthPos() { float[] pcRawData = jniGetPointCloudDeptMap(); pointCloudDepthPos.put(pcRawData, 0, WIDTHDepth * HEIGHTDepth * 3); pointCloudDepthPos.rewind(); return pointCloudDepthPos; } /** * Get Point Cloud Color Positions as a FloatBuffer, transform to a float array with .array(), or get values with get(index) * @return FloatBuffer */ public FloatBuffer getPointCloudColorPos() { float[] pcRawData = jniGetPointCloudColorMap(); pointCloudColorPos.put(pcRawData, 0, WIDTHColor * HEIGHTColor * 3); pointCloudColorPos.rewind(); return pointCloudColorPos; } /** * Get the color channel buffer, 3 channels, 1920 x 1080 x 3 from [0-1] * transform to a float array with .array(), or get values with get(index) * Ideal method for load level openGL calls * @return FloatBuffer */ public FloatBuffer getColorChannelBuffer() { float[] pcRawData = jniGetColorChannel(); colorChannelBuffer.put(pcRawData, 0, WIDTHColor * HEIGHTColor * 3); colorChannelBuffer.rewind(); return colorChannelBuffer; } /** * Enable point cloud capture * @param toggle */ public void enablePointCloud(boolean toggle) { jniEnablePointCloud(toggle); } /** * Get Point cloud Depth Image * @return PImage */ public PImage getPointCloudDepthImage() { int[] rawData = jniGetPointCloudDepthImage(); PApplet.arrayCopy(rawData, 0, pointCloudDepthImg.pixels(), 0, pointCloudDepthImg.getImgSize()); pointCloudDepthImg.updatePixels(); return pointCloudDepthImg.img; } /** * Set Threshold Depth Value Z for Point Cloud * * @param float val */ public void setLowThresholdPC(int val) { jniSetLowThresholdDepthPC(val); } /** * Get Threshold Depth Value Z from Point Cloud Default 1.9 * * @return default Threshold */ public int getLowThresholdDepthPC() { return jniGetLowThresholdDepthPC(); } /** * Set Threshold Depth Value Z for Point Cloud * * @param float val */ public void setHighThresholdPC(int val) { jniSetHighThresholdDepthPC(val); } /** * Get Threshold Depth Value Z from Point Cloud Default 1.9 * * @return default Threshold */ public int getHighThresholdDepthPC() { return jniGetHighThresholdDepthPC(); } /** * Get Raw BodyTracking Data 512 x 424 * * @return int [] */ public int[] getRawBodyTrack() { return jniGetRawBodyTrack(); } /** * Enable or Disable Color Image Capture * * @param boolean toggle */ public void enableColorImg(boolean toggle) { jniEnableColorFrame(toggle); } /** * Enable or disable color Point cloud. * Which is used to obtain getPointCloudColorPos() and getColorChannelBuffer(); * The FloatBuffer getColorChannelBuffer is a 3 independent color channels of 1920 x 1080 x 3, * Values form between 0 and 1, ideally for openGL calls * * @param toggle */ public void enableColorPointCloud(boolean toggle) { jniEnableColorChannel(toggle); } /** * Enable or Disable Depth Image Capture * * @param boolean toggle */ public void enableDepthImg(boolean toggle) { jniEnableDepthFrame(toggle); } /** * Enable or Disable DepthMask Image Capture * * @param boolean toggle */ public void enableDepthMaskImg(boolean toggle) { jniEnableDepthMaskFrame(toggle); } /** * Enable or Disable Infrared Image Capture * * @param boolean toggle */ public void enableInfraredImg(boolean toggle) { jniEnableInfraredFrame(toggle); } /** * Enable or Disable BodyTrack Image Capture * * @param boolean toggle */ public void enableBodyTrackImg(boolean toggle) { jniEnableBodyTrackFrame(toggle); } /** * Enable or Disable LongExposure Infrared Image Capture * * @param boolean toggle */ public void enableInfraredLongExposureImg(boolean toggle) { jniEnableInfraredLongExposure(toggle); } /** * Enable or Disable Skeleton Depth Map Capture * * @param boolean toggle */ public void enableSkeletonDepthMap(boolean toggle) { jniEnableSkeletonDepth(toggle); } /** * Enable or Disable Skeleton Color Map Capture * * @param boolean toggle */ public void enableSkeletonColorMap(boolean toggle) { jniEnableSkeletonColor(toggle); } /** * Enable or Disable Skeleton 3D Map Capture * * @param boolean toggle */ public void enableSkeleton3DMap(boolean toggle) { jniEnableSkeleton3D(toggle); } /** * Enable or Disable Face Tracking * * @param boolean toggle */ public void enableFaceDetection(boolean toggle) { jniEnableFaceDetection(toggle); } /** * Enable HDFace detection * * @param toggle */ public void enableHDFaceDetection(boolean toggle) { jniEnableHDFaceDetection(toggle); } public void enableCoordinateMapperRGBDepth(boolean toggle){ jniEnableCoordinateMapperRGBDepth(); } /* * public void enableMirror(boolean toggle){ jniSetMirror(toggle); } */ //MAPPERS public PVector MapCameraPointToDepthSpace(PVector pos){ float [] rawData = jniMapCameraPointToDepthSpace(pos.x, pos.y, pos.z); return new PVector(rawData[0], rawData[1]); } public PVector MapCameraPointToColorSpace(PVector pos){ float [] rawData = jniMapCameraPointToColorSpace(pos.x, pos.y, pos.z); return new PVector(rawData[0], rawData[1]); } public float [] getMapDepthToColor(){ return jniGetMapDethToColorSpace(); } protected boolean updateDevice() { boolean result = jniUpdate(); return result; } protected void stopDevice() { jniStopDevice(); } protected void cleanDevice() { jniStopSignal(); } // ------JNI FUNCTIONS private native void jniDevice(); private native boolean jniInit(); private native String jniVersion(); private native boolean jniUpdate(); // STOP private native void jniStopDevice(); private native boolean jniStopSignal(); // ENABLE FRAMES private native void jniEnableColorFrame(boolean toggle); private native void jniEnableDepthFrame(boolean toggle); private native void jniEnableDepthMaskFrame(boolean toggle); private native void jniEnableInfraredFrame(boolean toggle); private native void jniEnableBodyTrackFrame(boolean toggle); private native void jniEnableInfraredLongExposure(boolean toggle); private native void jniEnableSkeletonDepth(boolean toggle); private native void jniEnableSkeletonColor(boolean toggle); private native void jniEnableSkeleton3D(boolean toggle); private native void jniEnableFaceDetection(boolean toggle); private native void jniEnableHDFaceDetection(boolean toggle); private native void jniEnablePointCloud(boolean toggle); // COLOR CHANNEL private native void jniEnableColorChannel(boolean toggle); private native float[] jniGetColorChannel(); private native int[] jniGetColorData(); // DEPTH private native int[] jniGetDepth16Data(); private native int[] jniGetDepth256Data(); //DEPTH RAW private native int[] jniGetRawDepth16Data(); private native int[] jniGetRawDepth256Data(); private native int[] jniGetInfraredData(); private native int[] jniGetInfraredLongExposure(); private native int[] jniGetBodyTrack(); private native int[] jniGetDepthMask(); private native float[] jniGetSkeleton3D(); private native float[] jniGetSkeletonDepth(); private native float[] jniGetSkeletonColor(); private native float[] jniGetFaceColorData(); private native float[] jniGetFaceInfraredData(); private native float[] jniGetHDFaceDetection(); // POINT CLOUD private native float[] jniGetPointCloudDeptMap(); private native float[] jniGetPointCloudColorMap(); private native int[] jniGetPointCloudDepthImage(); // PC THRESHOLDS private native void jniSetLowThresholdDepthPC(int val); private native int jniGetLowThresholdDepthPC(); private native void jniSetHighThresholdDepthPC(int val); private native int jniGetHighThresholdDepthPC(); // BODY INDEX private native void jniSetNumberOfUsers(int index); private native int[] jniGetBodyIndexUser(int index); private native int[] jniGetBodyTrackIds(); private native int[] jniGetRawBodyTrack(); private native int jniGetNumberOfUsers(); //crists //MAPERS private native float[] jniMapCameraPointToDepthSpace(float camaraSpacePointX, float cameraSpacePointY, float cameraSpacePointZ); private native float[] jniMapCameraPointToColorSpace(float camaraSpacePointX, float cameraSpacePointY, float cameraSpacePointZ); private native float[] jniGetMapDethToColorSpace(); private native void jniEnableCoordinateMapperRGBDepth(); public void run() { int fr = PApplet.round(1000.0f / parent.frameRate); while (runningKinect) { // boolean result = updateDevice(); // if(!result){ // System.out.println("Error updating Kinect EXIT"); // } try { Thread.sleep(fr); // 2 } catch (InterruptedException e) { e.printStackTrace(); return; } } } }
mit
FanHuaRan/interview.algorithm
offerjava/剑指offer/平衡二叉树/Solution.java
1643
public class Solution { /*public class TreeNode{ public TreeNode left; public TreeNode right; }*/ public boolean IsBalanced_Solution(TreeNode root) { int[] deep=new int[1]; return isBanlanced(root,deep); } //类似于后序遍历 可以减少时间复杂度 private boolean isBanlanced(TreeNode tree,int []deep){ if(tree==null){ deep[0]=0; return true; } int[] leftDeep=new int[1]; int[] rightDeep=new int[1]; if(isBanlanced(tree.left,leftDeep)){ if(isBanlanced(tree.right,rightDeep)){ if(Math.abs(leftDeep[0]-rightDeep[0])<=1){ deep[0]=leftDeep[0]>rightDeep[0]?leftDeep[0]+1:rightDeep[0]+1; return true; } } } return false; } public class Solution { /*public class TreeNode{ public TreeNode left; public TreeNode right; }*/ public boolean IsBalanced_Solution(TreeNode root) { int[] deep=new int[1]; return isBanlanced(root,deep); } //类似于后序遍历 可以减少时间复杂度 private boolean isBanlanced(TreeNode tree,int []deep){ if(tree==null){ deep[0]=0; return true; } int[] leftDeep=new int[1]; int[] rightDeep=new int[1]; if(isBanlanced(tree.left,leftDeep)){ if(isBanlanced(tree.right,rightDeep)){ if(Math.abs(leftDeep[0]-rightDeep[0])<=1){ deep[0]=leftDeep[0]>rightDeep[0]?leftDeep[0]+1:rightDeep[0]+1; return true; } } } return false; } }
mit
games647/FastLogin
bungee/src/main/java/com/github/games647/fastlogin/bungee/task/ForceLoginTask.java
4817
/* * SPDX-License-Identifier: MIT * * The MIT License (MIT) * * Copyright (c) 2015-2021 <Your name and contributors> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.github.games647.fastlogin.bungee.task; import com.github.games647.fastlogin.bungee.BungeeLoginSession; import com.github.games647.fastlogin.bungee.FastLoginBungee; import com.github.games647.fastlogin.bungee.event.BungeeFastLoginAutoLoginEvent; import com.github.games647.fastlogin.core.StoredProfile; import com.github.games647.fastlogin.core.message.ChannelMessage; import com.github.games647.fastlogin.core.message.LoginActionMessage; import com.github.games647.fastlogin.core.message.LoginActionMessage.Type; import com.github.games647.fastlogin.core.shared.FastLoginCore; import com.github.games647.fastlogin.core.shared.ForceLoginManagement; import com.github.games647.fastlogin.core.shared.LoginSession; import com.github.games647.fastlogin.core.shared.event.FastLoginAutoLoginEvent; import java.util.UUID; import net.md_5.bungee.api.CommandSender; import net.md_5.bungee.api.ProxyServer; import net.md_5.bungee.api.connection.ProxiedPlayer; import net.md_5.bungee.api.connection.Server; public class ForceLoginTask extends ForceLoginManagement<ProxiedPlayer, CommandSender, BungeeLoginSession, FastLoginBungee> { private final Server server; //treat player as if they had a premium account, even when they don't //use for Floodgate auto login/register private final boolean forcedOnlineMode; public ForceLoginTask(FastLoginCore<ProxiedPlayer, CommandSender, FastLoginBungee> core, ProxiedPlayer player, Server server, BungeeLoginSession session, boolean forcedOnlineMode) { super(core, player, session); this.server = server; this.forcedOnlineMode = forcedOnlineMode; } public ForceLoginTask(FastLoginCore<ProxiedPlayer, CommandSender, FastLoginBungee> core, ProxiedPlayer player, Server server, BungeeLoginSession session) { this(core, player, server, session, false); } @Override public void run() { if (session == null) { return; } super.run(); if (!isOnlineMode()) { session.setAlreadySaved(true); } } @Override public boolean forceLogin(ProxiedPlayer player) { if (session.isAlreadyLogged()) { return true; } session.setAlreadyLogged(true); return super.forceLogin(player); } @Override public FastLoginAutoLoginEvent callFastLoginAutoLoginEvent(LoginSession session, StoredProfile profile) { return core.getPlugin().getProxy().getPluginManager() .callEvent(new BungeeFastLoginAutoLoginEvent(session, profile)); } @Override public boolean forceRegister(ProxiedPlayer player) { return session.isAlreadyLogged() || super.forceRegister(player); } @Override public void onForceActionSuccess(LoginSession session) { //sub channel name Type type = Type.LOGIN; if (session.needsRegistration()) { type = Type.REGISTER; } UUID proxyId = UUID.fromString(ProxyServer.getInstance().getConfig().getUuid()); ChannelMessage loginMessage = new LoginActionMessage(type, player.getName(), proxyId); core.getPlugin().sendPluginMessage(server, loginMessage); } @Override public String getName(ProxiedPlayer player) { return player.getName(); } @Override public boolean isOnline(ProxiedPlayer player) { return player.isConnected(); } @Override public boolean isOnlineMode() { return forcedOnlineMode || player.getPendingConnection().isOnlineMode(); } }
mit
kluetkemeyer/TTCore
src/de/brainiiiii/tt/core/IIsOpponent.java
1526
/* * The MIT License * * Copyright 2014 Kilian Lütkemeyer <kilian@luetkemeyer.com>. * * 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 de.brainiiiii.tt.core; /** * An interface for an opponent providing object. * * @param <O> The type of the opponent. * @author Kilian Lütkemeyer <kilian@luetkemeyer.com> */ public interface IIsOpponent<O extends IOpponent> { /** * Returns the opponent. * * @return The opponent. */ public O getOpponent(); }
mit
ot4i/perf-harness
MQJavaPerfHarness/src/com/ibm/uk/hursley/perfharness/mqjava/MQJavaWorkerThread.java
6912
/********************************************************* {COPYRIGHT-TOP} *** * Copyright 2016 IBM Corporation * * All rights reserved. This program and the accompanying materials * are made available under the terms of the MIT License * which accompanies this distribution, and is available at * http://opensource.org/licenses/MIT ********************************************************** {COPYRIGHT-END} **/ package com.ibm.uk.hursley.perfharness.mqjava; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.logging.Level; import com.ibm.mq.*; import com.ibm.uk.hursley.perfharness.*; public class MQJavaWorkerThread extends WorkerThread { @SuppressWarnings("unused") private static final String c = com.ibm.uk.hursley.perfharness.Copyright.COPYRIGHT; protected static DestinationFactory destFactory; protected static MQProvider mqprovider; protected boolean done = false; protected boolean ignoreExceptions = false; protected MQQueueManager qm = null; protected MQQueue queue; protected MQQueue inqueue; protected MQQueue outqueue; private final int writeLastMsgOnShutdown = Config.parms.getInt("ws"); private final int writeMessageInterval = Config.parms.getInt("wo"); protected MQMessage inMessage; protected MQMessage outMessage; protected MQGetMessageOptions gmo; protected MQPutMessageOptions pmo; protected int savedGmoWaitInterval = 0; // Save timeout value protected int savedGmoMatchOptions = 0; // Save match options protected int savedGmoOptions = 0; // Save options protected int savedPmoOptions = 0; // Save save options protected MQJavaWorkerThread(String name) { super(name); mqprovider = MQProvider.getInstance(); try { /* * TODO: Java 8 support target type inference, so when moving to Java 8 can * replace the following line with: * destFactory = Config.parms.<DestinationFactory>getClazz("df").newInstance(); */ destFactory = (DestinationFactory)Config.parms.getClazz("df").newInstance(); } catch (Exception e) { Log.logger.log(Level.SEVERE, "Problem getting DestinationFactory class", e); } } public static void registerConfig() { Config.registerSelf(MQProvider.class); if (!Config.isInvalid()) Config.registerAnother(Config.parms.getClazz("df")); } public void writeMessageToFileIfRequested() { //if we are writing some of the response msgs to a file and we have have sent numMsgs msgs then append msg to a file if (writeMessageInterval <= 0 || ((getIterations() % writeMessageInterval) != 0)) return; try { final FileOutputStream out = new FileOutputStream(new File(this.getName() + ".responsemsg"), true); try { final byte[] buf = new byte[inMessage.getMessageLength()]; inMessage.readFully(buf); out.write(buf); } finally { out.close(); } } catch (IOException e) { } } /** * General implementation of the main body of a simple JMS primitive. * * @param paceable * A paceable instance of WorkerThread. * @param listener * If not null, this overrides the above method and the given * object as an asynchronous listener. */ protected void run(WorkerThread.Paceable paceable) { Log.logger.log(Level.INFO, "START"); try { status = sCONNECTING; buildMQJavaResources(); status = sRUNNING; Log.logger.log(Level.FINE, "Entering client loop"); if (startTime == 0) startTime = System.currentTimeMillis(); pace(paceable); done = true; } catch (Throwable e) { handleException(e); } finally { if (done) { status = (status & sERROR) | sENDING; if (endTime == 0) endTime = System.currentTimeMillis(); // On shutdown, write the first 100 bytes off the received message to the screen if (writeLastMsgOnShutdown > 0) { try { if (inMessage != null) { if (inMessage.getMessageLength() > 0) { if (inMessage.getMessageLength() > 200) { String line = inMessage.readLine(); if (line.length() > 200) System.out.println("\nResponse msg (Thread " + this.getThreadNum() + ", MsgLength " + inMessage.getTotalMessageLength() + ") : " + line.substring(0, 199) + "..."); else System.out.println("\nResponse msg (Thread " + this.getThreadNum() + ", MsgLength " + inMessage.getTotalMessageLength() + ") : " + line + "..."); } else System.out.println("\nResponse msg (Thread " + this.getThreadNum() + ", MsgLength " + inMessage.getTotalMessageLength() + ") : " + inMessage.readLine()); } else System.out.println("\nResponse msg (" + this.getThreadNum() + ") : ERROR zero length message"); } else System.out.println("\nResponse msg (" + this.getThreadNum() + ") : No MQ message"); } catch (IOException e) { if (e.getMessage().contains("MQJE088")) { System.out.println("Failed to decode response message"); } else { e.printStackTrace(); } } } destroyMQJavaResources(false); Log.logger.info("STOP"); status = (status & sERROR) | sENDED; try { int wait = Config.parms.getInt("ss"); if (wait < 0) wait = 1; Thread.sleep(1000 * wait); } catch (InterruptedException e) { } ControlThread.signalShutdown(); } } } // End public void run() protected void buildMQJavaResources() throws Exception { Log.logger.log(Level.FINE, "Connecting to queue manager"); qm = mqprovider.getQueueManager(); gmo = mqprovider.getGMO(); savedGmoWaitInterval = gmo.waitInterval; savedGmoMatchOptions = gmo.matchOptions; savedGmoOptions = gmo.options; pmo = mqprovider.getPMO(); savedPmoOptions = pmo.options; } private void destroyMQJavaResources(boolean b) { if (queue != null) { try { Log.logger.log(Level.FINE, "Closing queue " + queue.getName()); queue.close(); } catch (MQException e) { } finally { queue = null; } } if (inqueue != null) { try { Log.logger.log(Level.FINE, "Closing queue " + inqueue.getName()); inqueue.close(); } catch (MQException e) { } finally { inqueue = null; } } if (outqueue != null) { try { Log.logger.log(Level.FINE, "Closing queue " + outqueue.getName()); outqueue.close(); } catch (MQException e) { } finally { outqueue = null; } } if (qm != null) { try { Log.logger.log(Level.FINE, "Closing queue manager " + qm.getName()); qm.disconnect(); } catch (MQException e) { } finally { qm = null; } } } /** * Log an exception. * * @param e */ protected void handleException(Throwable e) { if (endTime == 0) endTime = System.currentTimeMillis(); Log.logger.log(Level.SEVERE, "Uncaught exception.", e); status |= sERROR; ControlThread.signalShutdown(); done = true; } }
mit
nubbel/swift-tensorflow
JavaGenerated/org/tensorflow/framework/DataType.java
12235
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: tensorflow/core/framework/types.proto package org.tensorflow.framework; /** * <pre> * LINT.IfChange * </pre> * * Protobuf enum {@code tensorflow.DataType} */ public enum DataType implements com.google.protobuf.ProtocolMessageEnum { /** * <pre> * Not a legal value for DataType. Used to indicate a DataType field * has not been set. * </pre> * * <code>DT_INVALID = 0;</code> */ DT_INVALID(0), /** * <pre> * Data types that all computation devices are expected to be * capable to support. * </pre> * * <code>DT_FLOAT = 1;</code> */ DT_FLOAT(1), /** * <code>DT_DOUBLE = 2;</code> */ DT_DOUBLE(2), /** * <code>DT_INT32 = 3;</code> */ DT_INT32(3), /** * <code>DT_UINT8 = 4;</code> */ DT_UINT8(4), /** * <code>DT_INT16 = 5;</code> */ DT_INT16(5), /** * <code>DT_INT8 = 6;</code> */ DT_INT8(6), /** * <code>DT_STRING = 7;</code> */ DT_STRING(7), /** * <pre> * Single-precision complex * </pre> * * <code>DT_COMPLEX64 = 8;</code> */ DT_COMPLEX64(8), /** * <code>DT_INT64 = 9;</code> */ DT_INT64(9), /** * <code>DT_BOOL = 10;</code> */ DT_BOOL(10), /** * <pre> * Quantized int8 * </pre> * * <code>DT_QINT8 = 11;</code> */ DT_QINT8(11), /** * <pre> * Quantized uint8 * </pre> * * <code>DT_QUINT8 = 12;</code> */ DT_QUINT8(12), /** * <pre> * Quantized int32 * </pre> * * <code>DT_QINT32 = 13;</code> */ DT_QINT32(13), /** * <pre> * Float32 truncated to 16 bits. Only for cast ops. * </pre> * * <code>DT_BFLOAT16 = 14;</code> */ DT_BFLOAT16(14), /** * <pre> * Quantized int16 * </pre> * * <code>DT_QINT16 = 15;</code> */ DT_QINT16(15), /** * <pre> * Quantized uint16 * </pre> * * <code>DT_QUINT16 = 16;</code> */ DT_QUINT16(16), /** * <code>DT_UINT16 = 17;</code> */ DT_UINT16(17), /** * <pre> * Double-precision complex * </pre> * * <code>DT_COMPLEX128 = 18;</code> */ DT_COMPLEX128(18), /** * <code>DT_HALF = 19;</code> */ DT_HALF(19), /** * <code>DT_RESOURCE = 20;</code> */ DT_RESOURCE(20), /** * <pre> * Do not use! These are only for parameters. Every enum above * should have a corresponding value below (verified by types_test). * </pre> * * <code>DT_FLOAT_REF = 101;</code> */ DT_FLOAT_REF(101), /** * <code>DT_DOUBLE_REF = 102;</code> */ DT_DOUBLE_REF(102), /** * <code>DT_INT32_REF = 103;</code> */ DT_INT32_REF(103), /** * <code>DT_UINT8_REF = 104;</code> */ DT_UINT8_REF(104), /** * <code>DT_INT16_REF = 105;</code> */ DT_INT16_REF(105), /** * <code>DT_INT8_REF = 106;</code> */ DT_INT8_REF(106), /** * <code>DT_STRING_REF = 107;</code> */ DT_STRING_REF(107), /** * <code>DT_COMPLEX64_REF = 108;</code> */ DT_COMPLEX64_REF(108), /** * <code>DT_INT64_REF = 109;</code> */ DT_INT64_REF(109), /** * <code>DT_BOOL_REF = 110;</code> */ DT_BOOL_REF(110), /** * <code>DT_QINT8_REF = 111;</code> */ DT_QINT8_REF(111), /** * <code>DT_QUINT8_REF = 112;</code> */ DT_QUINT8_REF(112), /** * <code>DT_QINT32_REF = 113;</code> */ DT_QINT32_REF(113), /** * <code>DT_BFLOAT16_REF = 114;</code> */ DT_BFLOAT16_REF(114), /** * <code>DT_QINT16_REF = 115;</code> */ DT_QINT16_REF(115), /** * <code>DT_QUINT16_REF = 116;</code> */ DT_QUINT16_REF(116), /** * <code>DT_UINT16_REF = 117;</code> */ DT_UINT16_REF(117), /** * <code>DT_COMPLEX128_REF = 118;</code> */ DT_COMPLEX128_REF(118), /** * <code>DT_HALF_REF = 119;</code> */ DT_HALF_REF(119), /** * <code>DT_RESOURCE_REF = 120;</code> */ DT_RESOURCE_REF(120), UNRECOGNIZED(-1), ; /** * <pre> * Not a legal value for DataType. Used to indicate a DataType field * has not been set. * </pre> * * <code>DT_INVALID = 0;</code> */ public static final int DT_INVALID_VALUE = 0; /** * <pre> * Data types that all computation devices are expected to be * capable to support. * </pre> * * <code>DT_FLOAT = 1;</code> */ public static final int DT_FLOAT_VALUE = 1; /** * <code>DT_DOUBLE = 2;</code> */ public static final int DT_DOUBLE_VALUE = 2; /** * <code>DT_INT32 = 3;</code> */ public static final int DT_INT32_VALUE = 3; /** * <code>DT_UINT8 = 4;</code> */ public static final int DT_UINT8_VALUE = 4; /** * <code>DT_INT16 = 5;</code> */ public static final int DT_INT16_VALUE = 5; /** * <code>DT_INT8 = 6;</code> */ public static final int DT_INT8_VALUE = 6; /** * <code>DT_STRING = 7;</code> */ public static final int DT_STRING_VALUE = 7; /** * <pre> * Single-precision complex * </pre> * * <code>DT_COMPLEX64 = 8;</code> */ public static final int DT_COMPLEX64_VALUE = 8; /** * <code>DT_INT64 = 9;</code> */ public static final int DT_INT64_VALUE = 9; /** * <code>DT_BOOL = 10;</code> */ public static final int DT_BOOL_VALUE = 10; /** * <pre> * Quantized int8 * </pre> * * <code>DT_QINT8 = 11;</code> */ public static final int DT_QINT8_VALUE = 11; /** * <pre> * Quantized uint8 * </pre> * * <code>DT_QUINT8 = 12;</code> */ public static final int DT_QUINT8_VALUE = 12; /** * <pre> * Quantized int32 * </pre> * * <code>DT_QINT32 = 13;</code> */ public static final int DT_QINT32_VALUE = 13; /** * <pre> * Float32 truncated to 16 bits. Only for cast ops. * </pre> * * <code>DT_BFLOAT16 = 14;</code> */ public static final int DT_BFLOAT16_VALUE = 14; /** * <pre> * Quantized int16 * </pre> * * <code>DT_QINT16 = 15;</code> */ public static final int DT_QINT16_VALUE = 15; /** * <pre> * Quantized uint16 * </pre> * * <code>DT_QUINT16 = 16;</code> */ public static final int DT_QUINT16_VALUE = 16; /** * <code>DT_UINT16 = 17;</code> */ public static final int DT_UINT16_VALUE = 17; /** * <pre> * Double-precision complex * </pre> * * <code>DT_COMPLEX128 = 18;</code> */ public static final int DT_COMPLEX128_VALUE = 18; /** * <code>DT_HALF = 19;</code> */ public static final int DT_HALF_VALUE = 19; /** * <code>DT_RESOURCE = 20;</code> */ public static final int DT_RESOURCE_VALUE = 20; /** * <pre> * Do not use! These are only for parameters. Every enum above * should have a corresponding value below (verified by types_test). * </pre> * * <code>DT_FLOAT_REF = 101;</code> */ public static final int DT_FLOAT_REF_VALUE = 101; /** * <code>DT_DOUBLE_REF = 102;</code> */ public static final int DT_DOUBLE_REF_VALUE = 102; /** * <code>DT_INT32_REF = 103;</code> */ public static final int DT_INT32_REF_VALUE = 103; /** * <code>DT_UINT8_REF = 104;</code> */ public static final int DT_UINT8_REF_VALUE = 104; /** * <code>DT_INT16_REF = 105;</code> */ public static final int DT_INT16_REF_VALUE = 105; /** * <code>DT_INT8_REF = 106;</code> */ public static final int DT_INT8_REF_VALUE = 106; /** * <code>DT_STRING_REF = 107;</code> */ public static final int DT_STRING_REF_VALUE = 107; /** * <code>DT_COMPLEX64_REF = 108;</code> */ public static final int DT_COMPLEX64_REF_VALUE = 108; /** * <code>DT_INT64_REF = 109;</code> */ public static final int DT_INT64_REF_VALUE = 109; /** * <code>DT_BOOL_REF = 110;</code> */ public static final int DT_BOOL_REF_VALUE = 110; /** * <code>DT_QINT8_REF = 111;</code> */ public static final int DT_QINT8_REF_VALUE = 111; /** * <code>DT_QUINT8_REF = 112;</code> */ public static final int DT_QUINT8_REF_VALUE = 112; /** * <code>DT_QINT32_REF = 113;</code> */ public static final int DT_QINT32_REF_VALUE = 113; /** * <code>DT_BFLOAT16_REF = 114;</code> */ public static final int DT_BFLOAT16_REF_VALUE = 114; /** * <code>DT_QINT16_REF = 115;</code> */ public static final int DT_QINT16_REF_VALUE = 115; /** * <code>DT_QUINT16_REF = 116;</code> */ public static final int DT_QUINT16_REF_VALUE = 116; /** * <code>DT_UINT16_REF = 117;</code> */ public static final int DT_UINT16_REF_VALUE = 117; /** * <code>DT_COMPLEX128_REF = 118;</code> */ public static final int DT_COMPLEX128_REF_VALUE = 118; /** * <code>DT_HALF_REF = 119;</code> */ public static final int DT_HALF_REF_VALUE = 119; /** * <code>DT_RESOURCE_REF = 120;</code> */ public static final int DT_RESOURCE_REF_VALUE = 120; public final int getNumber() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalArgumentException( "Can't get the number of an unknown enum value."); } return value; } /** * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static DataType valueOf(int value) { return forNumber(value); } public static DataType forNumber(int value) { switch (value) { case 0: return DT_INVALID; case 1: return DT_FLOAT; case 2: return DT_DOUBLE; case 3: return DT_INT32; case 4: return DT_UINT8; case 5: return DT_INT16; case 6: return DT_INT8; case 7: return DT_STRING; case 8: return DT_COMPLEX64; case 9: return DT_INT64; case 10: return DT_BOOL; case 11: return DT_QINT8; case 12: return DT_QUINT8; case 13: return DT_QINT32; case 14: return DT_BFLOAT16; case 15: return DT_QINT16; case 16: return DT_QUINT16; case 17: return DT_UINT16; case 18: return DT_COMPLEX128; case 19: return DT_HALF; case 20: return DT_RESOURCE; case 101: return DT_FLOAT_REF; case 102: return DT_DOUBLE_REF; case 103: return DT_INT32_REF; case 104: return DT_UINT8_REF; case 105: return DT_INT16_REF; case 106: return DT_INT8_REF; case 107: return DT_STRING_REF; case 108: return DT_COMPLEX64_REF; case 109: return DT_INT64_REF; case 110: return DT_BOOL_REF; case 111: return DT_QINT8_REF; case 112: return DT_QUINT8_REF; case 113: return DT_QINT32_REF; case 114: return DT_BFLOAT16_REF; case 115: return DT_QINT16_REF; case 116: return DT_QUINT16_REF; case 117: return DT_UINT16_REF; case 118: return DT_COMPLEX128_REF; case 119: return DT_HALF_REF; case 120: return DT_RESOURCE_REF; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<DataType> internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap< DataType> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<DataType>() { public DataType findValueByNumber(int number) { return DataType.forNumber(number); } }; public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { return getDescriptor().getValues().get(ordinal()); } public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { return getDescriptor(); } public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { return org.tensorflow.framework.TypesProtos.getDescriptor().getEnumTypes().get(0); } private static final DataType[] VALUES = values(); public static DataType valueOf( com.google.protobuf.Descriptors.EnumValueDescriptor desc) { if (desc.getType() != getDescriptor()) { throw new java.lang.IllegalArgumentException( "EnumValueDescriptor is not for this type."); } if (desc.getIndex() == -1) { return UNRECOGNIZED; } return VALUES[desc.getIndex()]; } private final int value; private DataType(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:tensorflow.DataType) }
mit
GeoSmartCity-CIP/gsc-datacatalogue
server/src/main/java/it/sinergis/datacatalogue/mock/Gsc007DatasetEntityMock.java
1327
/* * Created on 18 dic 2015 ( Time 16:29:07 ) * Generated by Telosys Tools Generator ( version 2.1.1 ) */ package it.sinergis.datacatalogue.mock; import java.util.LinkedList; import java.util.List; import it.sinergis.datacatalogue.bean.jpa.Gsc007DatasetEntity; import it.sinergis.datacatalogue.mock.tool.MockValues; public class Gsc007DatasetEntityMock { private MockValues mockValues = new MockValues(); /** * Creates an instance with random Primary Key * @return */ public Gsc007DatasetEntity createInstance() { // Primary Key values return createInstance( mockValues.nextLong() ); } /** * Creates an instance with a specific Primary Key * @param id1 * @return */ public Gsc007DatasetEntity createInstance( Long id ) { Gsc007DatasetEntity entity = new Gsc007DatasetEntity(); // Init Primary Key fields entity.setId( id) ; // Init Data fields entity.setJson("{}" ) ; // java.lang.String // Init Link fields (if any) return entity ; } /** * Creates a list of instances * @param count number of instances to be created * @return */ public List<Gsc007DatasetEntity> createList(int count) { List<Gsc007DatasetEntity> list = new LinkedList<Gsc007DatasetEntity>(); for ( int i = 1 ; i <= count ; i++ ) { list.add( createInstance() ); } return list; } }
mit
mwcaisse/CarTracker
CarTracker.Android/src/main/java/com/ricex/cartracker/android/service/OBDCommandJob.java
803
package com.ricex.cartracker.android.service; import com.github.pires.obd.commands.ObdCommand; /** * Created by Mitchell on 2/12/2016. */ public class OBDCommandJob { private ObdCommand command; private OBDCommandStatus status; public OBDCommandJob(ObdCommand command) { if (null == command) { throw new IllegalArgumentException("Command cannot be null!"); } this.command = command; status = OBDCommandStatus.NEW; } public OBDCommandStatus getStatus() { return status; } public void setStatus(OBDCommandStatus status) { this.status = status; } public ObdCommand getCommand() { return command; } public void setCommand(ObdCommand command) { this.command = command; } }
mit
bergeoisie/jtextiles
src/test/java/edu/umd/math/TestProductTextile.java
811
package edu.umd.math; import org.jgrapht.graph.DirectedPseudograph; import org.junit.Test; public class TestProductTextile { @Test public void testCreateDual() { Textile t = TestTextileUtils.generateNasu(); Textile s = TestTextileUtils.generateNasu(); try { Textile prod = TextileBuilder.createProductTextile(t, s); GGraph prodG = prod.getGGraph(); GammaGraph prodGamma = prod.getGammaGraph(); OutputHelper.printTextile(prod); org.junit.Assert.assertEquals("failure - g vertexset sizes not equal", 2, prodG.vertexSet().size()); org.junit.Assert.assertEquals("failure - gamma vertexset sizes not equal", 3, prodGamma.vertexSet().size()); } catch(Exception e) { System.out.println("Caught " + e.getMessage()); } } }
mit
Ernestyj/JStudy
src/main/java/eugene/reflect/App.java
202
package eugene.reflect; /** * Created by Jian on 2015/7/28. */ public class App { public static void main(String[] args){ System.out.println("args: " + args[0] + ", " + args[1]); } }
mit
bgithub1/span-java
src/main/java/com/billybyte/spanjava/generated/Tick.java
2927
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2012.05.24 at 08:06:09 AM EDT // package com.billybyte.spanjava.generated; import java.math.BigDecimal; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element ref="{}val"/> * &lt;element ref="{}loVal"/> * &lt;element ref="{}hiVal"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "val", "loVal", "hiVal" }) @XmlRootElement(name = "tick") public class Tick { @XmlElement(required = true) protected BigDecimal val; @XmlElement(required = true) protected BigDecimal loVal; @XmlElement(required = true) protected BigDecimal hiVal; /** * Gets the value of the val property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getVal() { return val; } /** * Sets the value of the val property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setVal(BigDecimal value) { this.val = value; } /** * Gets the value of the loVal property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getLoVal() { return loVal; } /** * Sets the value of the loVal property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setLoVal(BigDecimal value) { this.loVal = value; } /** * Gets the value of the hiVal property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getHiVal() { return hiVal; } /** * Sets the value of the hiVal property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setHiVal(BigDecimal value) { this.hiVal = value; } }
mit
bitDecayGames/GlobalGameJam2017
src/main/java/com/bitdecay/game/system/CameraPredictiveSystem.java
1174
package com.bitdecay.game.system; import com.badlogic.gdx.math.Vector2; import com.bitdecay.game.component.PositionComponent; import com.bitdecay.game.component.PredictiveCameraFollowComponent; import com.bitdecay.game.gameobject.MyGameObject; import com.bitdecay.game.room.AbstractRoom; import com.bitdecay.game.system.abstracted.AbstractForEachUpdatableSystem; /** * This system is in charge of updating the camera with the list of points to follow each step. */ public class CameraPredictiveSystem extends AbstractForEachUpdatableSystem { private float leadDistance = 0; private Vector2 right = new Vector2(1, 0); public CameraPredictiveSystem(AbstractRoom room, float leadDistance) { super(room); this.leadDistance = leadDistance; } @Override protected boolean validateGob(MyGameObject gob) { return gob.hasComponents(PredictiveCameraFollowComponent.class, PositionComponent.class); } @Override protected void forEach(float delta, MyGameObject gob) { gob.forEachComponentDo(PositionComponent.class, pos -> room.camera.addFollowPoint(right.cpy().scl(leadDistance).add(pos.toVector2()))); } }
mit
accelazh/Dimension2GTA2
Dimension2GTA/animatedGUI/AConstants.java
512
package animatedGUI; public interface AConstants { public static final int TIMER_INTERVAL=10; public static final int UP=1; public static final int DOWN=-1; public static final int LEFT=2; public static final int RIGHT=-2; //mode public static final int SHOW=0; public static final int POP_AND_SHOW=1; public static final int POP_AND_LOOP=2; //for MouseEvent public static final int BUTTON1=0; public static final int BUTTON2=1; public static final int BUTTON3=2; }
mit
ztory/sleek
sleek_module/src/main/java/com/ztory/lib/sleek/touch/ISleekTouchRun.java
475
package com.ztory.lib.sleek.touch; import android.view.MotionEvent; import com.ztory.lib.sleek.SleekCanvasInfo; import com.ztory.lib.sleek.Sleek; /** * Interface that represents an onTouch action, passing in all the relevant parameters. * Created by jonruna on 09/10/14. */ public interface ISleekTouchRun { int RETURN_TRUE = 0, RETURN_FALSE = 1, DONT_RETURN = 2; int onTouch(Sleek view, SleekTouchHandler handler, MotionEvent event, SleekCanvasInfo info); }
mit
albericocolaco/ponto-inteligente-api
src/main/java/com/example/pontointeligente/api/PontoInteligenteApplication.java
344
package com.example.pontointeligente.api; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class PontoInteligenteApplication { public static void main(String[] args) { SpringApplication.run(PontoInteligenteApplication.class, args); } }
mit
Azure/azure-sdk-for-java
sdk/datafactory/azure-resourcemanager-datafactory/src/main/java/com/azure/resourcemanager/datafactory/models/IntegrationRuntimeStatus.java
3367
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.datafactory.models; import com.azure.core.annotation.Fluent; import com.azure.core.util.logging.ClientLogger; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; import java.util.HashMap; import java.util.Map; /** Integration runtime status. */ @JsonTypeInfo( use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type", defaultImpl = IntegrationRuntimeStatus.class) @JsonTypeName("IntegrationRuntimeStatus") @JsonSubTypes({ @JsonSubTypes.Type(name = "Managed", value = ManagedIntegrationRuntimeStatus.class), @JsonSubTypes.Type(name = "SelfHosted", value = SelfHostedIntegrationRuntimeStatus.class) }) @Fluent public class IntegrationRuntimeStatus { @JsonIgnore private final ClientLogger logger = new ClientLogger(IntegrationRuntimeStatus.class); /* * The data factory name which the integration runtime belong to. */ @JsonProperty(value = "dataFactoryName", access = JsonProperty.Access.WRITE_ONLY) private String dataFactoryName; /* * The state of integration runtime. */ @JsonProperty(value = "state", access = JsonProperty.Access.WRITE_ONLY) private IntegrationRuntimeState state; /* * Integration runtime status. */ @JsonIgnore private Map<String, Object> additionalProperties; /** * Get the dataFactoryName property: The data factory name which the integration runtime belong to. * * @return the dataFactoryName value. */ public String dataFactoryName() { return this.dataFactoryName; } /** * Get the state property: The state of integration runtime. * * @return the state value. */ public IntegrationRuntimeState state() { return this.state; } /** * Get the additionalProperties property: Integration runtime status. * * @return the additionalProperties value. */ @JsonAnyGetter public Map<String, Object> additionalProperties() { return this.additionalProperties; } /** * Set the additionalProperties property: Integration runtime status. * * @param additionalProperties the additionalProperties value to set. * @return the IntegrationRuntimeStatus object itself. */ public IntegrationRuntimeStatus withAdditionalProperties(Map<String, Object> additionalProperties) { this.additionalProperties = additionalProperties; return this; } @JsonAnySetter void withAdditionalProperties(String key, Object value) { if (additionalProperties == null) { additionalProperties = new HashMap<>(); } additionalProperties.put(key, value); } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { } }
mit
normanmaurer/hector
core/src/test/java/me/prettyprint/cassandra/model/MutatorTest.java
9343
package me.prettyprint.cassandra.model; import static me.prettyprint.hector.api.factory.HFactory.createColumn; import static me.prettyprint.hector.api.factory.HFactory.createCounterColumn; import static me.prettyprint.hector.api.factory.HFactory.createColumnQuery; import static me.prettyprint.hector.api.factory.HFactory.createKeyspace; import static me.prettyprint.hector.api.factory.HFactory.createMutator; import static me.prettyprint.hector.api.factory.HFactory.createSuperColumn; import static me.prettyprint.hector.api.factory.HFactory.getOrCreateCluster; import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List; import me.prettyprint.cassandra.BaseEmbededServerSetupTest; import me.prettyprint.cassandra.model.thrift.ThriftCounterColumnQuery; import me.prettyprint.cassandra.serializers.StringSerializer; import me.prettyprint.cassandra.utils.StringUtils; import me.prettyprint.hector.api.Cluster; import me.prettyprint.hector.api.Keyspace; import me.prettyprint.hector.api.beans.HColumn; import me.prettyprint.hector.api.beans.HSuperColumn; import me.prettyprint.hector.api.factory.HFactory; import me.prettyprint.hector.api.mutation.MutationResult; import me.prettyprint.hector.api.mutation.Mutator; import me.prettyprint.hector.api.query.ColumnQuery; import me.prettyprint.hector.api.query.CounterQuery; import me.prettyprint.hector.api.query.QueryResult; import me.prettyprint.hector.api.query.SuperColumnQuery; import org.apache.cassandra.thrift.ColumnPath; import org.junit.After; import org.junit.Before; import org.junit.Test; public class MutatorTest extends BaseEmbededServerSetupTest { private static final StringSerializer se = new StringSerializer(); private Cluster cluster; private Keyspace keyspace; @Before public void setupCase() { cluster = getOrCreateCluster("Test Cluster", "127.0.0.1:9170"); keyspace = createKeyspace("Keyspace1", cluster); } @After public void teardownCase() { keyspace = null; cluster = null; } @Test public void testInsert() { Mutator<String> m = createMutator(keyspace, se); MutationResult mr = m.insert("k", "Standard1", createColumn("name", "value", se, se)); assertTrue("Execution time on single insert should be > 0",mr.getExecutionTimeMicro() > 0); assertTrue("Should have operated on a host", mr.getHostUsed() != null); assertColumnExists("Keyspace1", "Standard1", "k", "name"); } @Test public void testInsertAndDeleteSuper() { Mutator<String> m = createMutator(keyspace, se); List<HColumn<String, String>> columnList = new ArrayList<HColumn<String,String>>(); columnList.add(createColumn("name","value",se,se)); HSuperColumn<String, String, String> superColumn = createSuperColumn("super_name", columnList, se, se, se); // Insert Super Column MutationResult r = m.insert("sk", "Super1", superColumn); assertTrue("Execute time should be > 0", r.getExecutionTimeMicro() > 0); assertTrue("Should have operated on a host", r.getHostUsed() != null); // Fetch and verify it exists. SuperColumnQuery<String, String, String, String> scq = HFactory.createSuperColumnQuery(keyspace, se, se, se, se); scq.setColumnFamily("Super1"); scq.setKey("sk"); scq.setSuperName("super_name"); assertEquals("super_name", scq.execute().get().getName()); // Remove the Super Column m.superDelete("sk", "Super1", "super_name", se); // Fetch and verify it exists. scq = HFactory.createSuperColumnQuery(keyspace, se, se, se, se); scq.setColumnFamily("Super1"); scq.setKey("sk"); scq.setSuperName("super_name"); assertNull("super_name", scq.execute().get()); } @Test public void testSubDelete() { Mutator<String> m = createMutator(keyspace, se); List<HColumn<String, String>> columnList = new ArrayList<HColumn<String,String>>(); columnList.add(createColumn("col_1","val_1",se,se)); columnList.add(createColumn("col_2","val_2",se,se)); columnList.add(createColumn("col_3","val_3",se,se)); HSuperColumn<String, String, String> superColumn = createSuperColumn("super_name", columnList, se, se, se); m.insert("sk1", "Super1", superColumn); SuperColumnQuery<String, String, String, String> scq = HFactory.createSuperColumnQuery(keyspace, se, se, se, se); scq.setColumnFamily("Super1"); scq.setKey("sk1"); scq.setSuperName("super_name"); assertEquals(3,scq.execute().get().getColumns().size()); m.discardPendingMutations(); m.addSubDelete("sk1", "Super1", "super_name", "col_1", se, se); m.execute(); assertEquals(2,scq.execute().get().getColumns().size()); } @Test public void testSubDeleteHSuperColumn() { Mutator<String> m = createMutator(keyspace, se); List<HColumn<String, String>> columnList = new ArrayList<HColumn<String,String>>(); columnList.add(createColumn("col_1","val_1",se,se)); columnList.add(createColumn("col_2","val_2",se,se)); columnList.add(createColumn("col_3","val_3",se,se)); HSuperColumn<String, String, String> superColumn = createSuperColumn("super_name", columnList, se, se, se); m.insert("sk1", "Super1", superColumn); SuperColumnQuery<String, String, String, String> scq = HFactory.createSuperColumnQuery(keyspace, se, se, se, se); scq.setColumnFamily("Super1"); scq.setKey("sk1"); scq.setSuperName("super_name"); assertEquals(3,scq.execute().get().getColumns().size()); m.discardPendingMutations(); columnList.remove(1); columnList.remove(0); superColumn.setSubcolumns(columnList); m.addSubDelete("sk1", "Super1", superColumn); m.execute(); assertEquals(2,scq.execute().get().getColumns().size()); } @Test public void testBatchMutationManagement() { String cf = "Standard1"; Mutator<String> m = createMutator(keyspace, se); for (int i = 0; i < 5; i++) { m.addInsertion("k" + i, cf, createColumn("name", "value" + i, se, se)); } MutationResult r = m.execute(); assertTrue("Execute time should be > 0", r.getExecutionTimeMicro() > 0); assertTrue("Should have operated on a host", r.getHostUsed() != null); for (int i = 0; i < 5; i++) { assertColumnExists("Keyspace1", "Standard1", "k"+i, "name"); } // Execute an empty mutation r = m.execute(); assertEquals("Execute time should be 0", 0, r.getExecutionTimeMicro()); // Test discard and then exec an empty mutation for (int i = 0; i < 5; i++) { m.addInsertion("k" + i, cf, createColumn("name", "value" + i, se, se)); } m.discardPendingMutations(); r = m.execute(); assertEquals("Execute time should be 0", 0, r.getExecutionTimeMicro()); assertTrue("Should have operated with a null host", r.getHostUsed() == null); // cleanup for (int i = 0; i < 5; i++) { m.addDeletion("k" + i, cf, "name", se); } m.execute(); } @Test public void testRowDeletion() { String cf = "Standard1"; long initialTime = keyspace.createClock(); Mutator<String> m = createMutator(keyspace, se); for (int i = 0; i < 5; i++) { m.addInsertion("key" + i, cf, createColumn("name", "value" + i, se, se)); } m.execute(); // Try to delete the row with key "k0" with a clock previous to the insertion. // Cassandra will discard this operation. m.addDeletion("key0", cf, null, se, (initialTime - 100)); m.execute(); // Check that the delete was harmless QueryResult<HColumn<String, String>> columnResult = createColumnQuery(keyspace, se, se, se).setColumnFamily(cf).setKey("key0"). setName("name").execute(); assertEquals("value0", columnResult.get().getValue()); for (int i = 0; i < 5; i++) { m.addDeletion("key" + i, cf, null, se); } m.execute(); // Check that the delete took place now columnResult = createColumnQuery(keyspace, se, se, se). setColumnFamily(cf).setKey("key0").setName("name").execute(); assertNull(columnResult.get()); } @Test public void testInsertCounter() { Mutator<String> m = createMutator(keyspace, se); MutationResult mr = m.insertCounter("k", "Counter1", createCounterColumn("name", 5)); assertTrue("Execution time on single counter insert should be > 0", mr.getExecutionTimeMicro() > 0); assertTrue("Should have operated on a host", mr.getHostUsed() != null); CounterQuery<String, String> counter = new ThriftCounterColumnQuery<String,String>(keyspace, se, se); counter.setColumnFamily("Counter1").setKey("k").setName("name"); assertEquals(new Long(5), counter.execute().get().getValue()); } private void assertColumnExists(String keyspace, String cf, String key, String column) { ColumnPath cp = new ColumnPath(cf); cp.setColumn(StringUtils.bytes(column)); Keyspace ks = HFactory.createKeyspace(keyspace, cluster); ColumnQuery<String, String, String> columnQuery = HFactory.createStringColumnQuery(ks); assertNotNull(String.format("Should have value for %s.%s[%s][%s]", keyspace, cf, key, column), columnQuery.setColumnFamily(cf).setKey(key).setName(column).execute().get().getValue()); //client.getKeyspace(keyspace).getColumn(key, cp)); //cluster.releaseClient(client); } }
mit
DataAgg/DAFramework
commons/src/main/java/com/dataagg/util/lang/TextUtils.java
11055
package com.dataagg.util.lang; import jodd.util.StringUtil; import java.math.BigDecimal; import java.net.URLEncoder; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; public class TextUtils { public final static String Encoding = "utf-8"; public final static String NULL = "__null__"; public final static String EMPTY = "____"; public final static String DateFormat = "yyyyMMdd"; public final static String TimeFormat = "yyyyMMddHHmmss"; public final static String DisplayDateFormat = "yyyy-MM-dd"; public final static String DisplayTimeFormat = "yyyy-MM-dd HH:mm:ss"; public static String repeat(String tpl, List<String> items, String rmEndStr) { StringBuffer sb = new StringBuffer(); for (String item : items) { sb.append(StringUtil.replace(tpl, "${0}", item)); } String code = sb.toString().trim(); if (rmEndStr != null && code.endsWith(rmEndStr)) { code = code.substring(0, code.length() - rmEndStr.length()); } return code; } public static String toUrlParam(Object value) { if (value == null) { return NULL; } if (value instanceof Number) { return value.toString(); } if (value instanceof String && ((String) value).length() <= 0) { return EMPTY; } try { return URLEncoder.encode(value.toString(), Encoding); } catch (Exception e) { return value.toString(); } } public static String findGroup1(String text, String regx) { Matcher matcher = Pattern.compile(regx).matcher(text); if (matcher.find()) { return matcher.group(1); } return null; } public static double round_half_up(double a, int newScale) { return new BigDecimal(Double.toString(a)).setScale(newScale, BigDecimal.ROUND_HALF_UP).doubleValue(); } public static String formatDate(Date date, String format) { if (date == null) { return ""; } SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format, Locale.CHINA); return simpleDateFormat.format(date); } public static Date parseDate(Long date, String format) { if (date == null) { return null; } SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format, Locale.CHINA); try { return simpleDateFormat.parse(date + ""); } catch (ParseException e) { return null; } } public static Date parseDate(String date, String format) { if (date == null) { return null; } SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format, Locale.CHINA); try { return simpleDateFormat.parse(date + ""); } catch (ParseException e) { return null; } } public static String formatDate(Date date) { return formatDate(date, DisplayDateFormat); } public static String formatTime(Date date) { return formatDate(date, DisplayTimeFormat); } public static Long simpleDate(Date date) { if (date == null) { date = new Date(); } return Long.parseLong(formatDate(date, DateFormat)); } public static Long simpleTime(Date date) { if (date == null) { date = new Date(); } return Long.parseLong(formatDate(date, TimeFormat)); } public static String getAgo(Long oldTime) { Date old = parseDate(oldTime, TimeFormat); Date now = new Date(); long time = (now.getTime() - old.getTime()) / 1000; long hour = time / 3600; long minute = time % 3600 / 60; String text = ""; if (hour <= 24) { if (hour > 0) { text = hour + "小时"; } if (minute > 0) { text += minute + "分钟"; } } else { long day = hour / 24; text += day + "天"; } if (text.length() <= 0) { text = "刚才"; } else { text += "前"; } return text; } public static String getTimeText(Long oldTime) { Date old = parseDate(oldTime, TimeFormat); return formatTime(old); } @SuppressWarnings("deprecation") public static String getShortTimeText(Long oldTime) { Date time = parseDate(oldTime, TimeFormat); Date now = new Date(); String format = "yyyy-MM-dd HH:mm"; if (time.getYear() == now.getYear()) { format = format.substring("yyyy-".length()); if (time.getMonth() == now.getMonth() && time.getDay() == now.getDay()) { format = format.substring("MM-dd ".length()); } } return formatDate(time, format); } public static long cutLong(long time, int scale) { return (time - time % scale) / scale; } /** * 得到N天后的日期,如果days为负数,前得到N天前的日期 * * @param format * @param days * @return */ public static String getAfterByNDay(String format, int days) { Calendar c = Calendar.getInstance(); c.setTime(new Date()); c.add(Calendar.DAY_OF_MONTH, days); Date newDate = c.getTime(); return formatDate(newDate, format); } /** * 得到N月后的日期,如果months为负数,前得到N月前的日期 * * @param format * @param months * @return */ public static String getAfterByNMonth(String format, int months) { Calendar c = Calendar.getInstance(); c.setTime(new Date()); c.add(Calendar.MONTH, months); Date newDate = c.getTime(); return formatDate(newDate, format); } public static String toString(String[] ss) { StringBuffer buf = new StringBuffer(); if (ss != null) { for (String s : ss) { buf.append(s).append(' '); } } return buf.toString().trim(); } public static String strLen(int num, int len) { return strLen(String.valueOf(num), len); } public static String strLen(long num, int len) { return strLen(String.valueOf(num), len); } public static String strLen(String s, int len) { if (s == null) { s = ""; } int length = s.length(); for (int i = 0; i < len - length; i++) { s = "0" + s; } return s; } public static String[] split(String str, String separator) { return split(str, separator, true); } /** * Splits a string at the specified character. */ public static String[] split(String s, char c) { int i, b, e; int cnt; String res[]; int ln = s.length(); i = 0; cnt = 1; while ((i = s.indexOf(c, i)) != -1) { cnt++; i++; } res = new String[cnt]; i = 0; b = 0; while (b <= ln) { e = s.indexOf(c, b); if (e == -1) { e = ln; } res[i++] = s.substring(b, e); b = e + 1; } return res; } /** * Splits a string at the specified string. */ public static String[] split(String s, String sep, boolean caseInsensitive) { String splitString = caseInsensitive ? sep.toLowerCase() : sep; String input = caseInsensitive ? s.toLowerCase() : s; int i, b, e; int cnt; String res[]; int ln = s.length(); int sln = sep.length(); if (sln == 0) { throw new IllegalArgumentException("The separator string has 0 length"); } i = 0; cnt = 1; while ((i = input.indexOf(splitString, i)) != -1) { cnt++; i += sln; } res = new String[cnt]; i = 0; b = 0; while (b <= ln) { e = input.indexOf(splitString, b); if (e == -1) { e = ln; } res[i++] = s.substring(b, e); b = e + sln; } return res; } public static String repeat(String s, int count) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < count; i++) { sb.append(s); } return sb.toString(); } public static String repeatIds(Long[] ids, String s) { StringBuffer sb = new StringBuffer(); for (Long id : ids) { sb.append(id + s); } if (sb.length() > 1) { return sb.substring(0, sb.length() - 1); } else { return ""; } } public static boolean contains(Collection<String> mainCollection, String str) { String[] mainArr = new String[mainCollection.size()]; return contains(mainCollection.toArray(mainArr), str); } public static boolean contains(Collection<String> mainCollection, Collection<String> subCollection) { String[] mainArr = new String[mainCollection.size()]; String[] subArr = new String[subCollection.size()]; return contains(mainCollection.toArray(mainArr), subCollection.toArray(subArr)); } public static boolean contains(String[] mainArr, String[] subArr) { for (String s : subArr) { if (!contains(mainArr, s)) { return false; } } return true; } public static boolean contains(String[] strArr, String str) { for (String s : strArr) { if (s.equals(str)) { return true; } } return false; } public static String[] rebuildArray(String[] arr) { if (arr != null) { List<String> list = new ArrayList<String>(Arrays.asList(arr)); for (Iterator<String> iter = list.iterator(); iter.hasNext(); ) { String s = iter.next(); if (StringUtil.isEmpty(s)) { iter.remove(); } } String[] newArr = new String[list.size()]; return list.toArray(newArr); } return new String[0]; } public static Long[] parseLongs(String text) { List<Long> randIds = new ArrayList<Long>(); if (text != null) { for (String strBID : StringUtil.split(text, "|")) { if (strBID != null && !strBID.trim().equals("")) { randIds.add(Long.parseLong(strBID)); } } } return randIds.toArray(new Long[]{}); } public static String getIdsString(List<Long> ids) { if (ids != null && ids.size() > 0) { return ""; } else { return getIdsString(new Long[]{}); } } public static String getIdsString(Long[] ids) { String text = ""; for (Long id : ids) { text += "|" + id.longValue() + "|"; } return text; } public static String toText(Object[] objs, String ch) { StringBuffer text = new StringBuffer(); for (Object o : objs) { text.append(o.toString()); text.append(ch); } String t = text.toString().trim(); if (t.endsWith(ch)) { t = t.substring(0, t.length() - 1); } return t; } public static Long parseId(Object id) { if (id == null) { return null; } if (id instanceof String && !StringUtil.isBlank((String) id)) { return Long.parseLong((String) id); } else if (id instanceof Number) { return ((Number) id).longValue(); } return -1l; } public static boolean match(String text, String regex) { regex = StringUtil.replace(regex, "\\", "\\\\"); regex = StringUtil.replace(regex, ".", "\\."); regex = StringUtil.replace(regex, "[", "\\["); regex = StringUtil.replace(regex, "]", "\\]"); regex = StringUtil.replace(regex, "(", "\\("); regex = StringUtil.replace(regex, ")", "\\)"); regex = StringUtil.replace(regex, "?", ".+"); regex = StringUtil.replace(regex, "*", ".*"); return text.matches(regex); } public static String getAbbreviation(String text) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < text.length(); i++) { char ch = text.charAt(i); if (ch >= 'A' && ch <= 'Z') { sb.append(ch); } } if (sb.length() > 0) { return sb.toString(); } return text; } public static String prefix(String key) { return StringUtil.isBlank(key) ? "" : (key + "."); } public static String postfix(String key) { return StringUtil.isBlank(key) ? "" : ("." + key); } }
mit
backpaper0/sealion
src/main/java/sealion/service/CommentService.java
835
package sealion.service; import java.time.Clock; import java.time.LocalDateTime; import javax.inject.Inject; import sealion.dao.CommentDao; import sealion.domain.Key; import sealion.domain.MarkedText; import sealion.domain.PostedDate; import sealion.entity.Comment; import sealion.entity.Task; import sealion.session.User; @Service public class CommentService { @Inject private CommentDao commentDao; @Inject private User user; @Inject private Clock clock; public Comment create(Key<Task> task, MarkedText content) { Comment entity = new Comment(); entity.task = task; entity.content = content; entity.postedBy = user.getAccount().id; entity.postedAt = new PostedDate(LocalDateTime.now(clock)); commentDao.insert(entity); return entity; } }
mit
AdmirilRed/RedLibrary
RedLibrarian/src/redlibrarian/utility/BugReport.java
1849
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package redlibrarian.utility; import java.io.Serializable; import java.util.logging.Level; import java.util.logging.Logger; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import redlibrarian.GUI.UserInterface; import redlibrarian.login.ContactDetails; /** * * @author admir */ @Entity public class BugReport implements Serializable { @GeneratedValue(strategy=GenerationType.AUTO) @Id private long id; private String summary; private String description; @ManyToOne private ContactDetails contact; public BugReport() { } public BugReport(ContactDetails contact, String summary, String description) { this.summary = summary; this.description = description; this.contact = contact; } public boolean save(SessionFactory sessionFactory) { try { Session session = sessionFactory.getCurrentSession(); session.beginTransaction(); session.saveOrUpdate(this); session.getTransaction().commit(); return true; } catch(HibernateException hibernateException) { Logger.getLogger(UserInterface.class.getName()).log(Level.SEVERE, null, hibernateException); return false; } } public Long getId() { return id; } public void setId(Long id) { this.id = id; } }
mit
jonathanlermitage/manon
src/main/java/manon/repository/user/FriendshipRepository.java
1808
package manon.repository.user; import manon.document.user.FriendshipEntity; import manon.util.ExistForTesting; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import java.util.List; import java.util.stream.Stream; @Repository public interface FriendshipRepository extends JpaRepository<FriendshipEntity, Long> { /** Find a friendship between two users. */ @Query("select count(f) from Friendship f " + "where (f.requestFrom.id = :userId1 and f.requestTo.id = :userId2) or (f.requestFrom.id = :userId2 and f.requestTo.id = :userId1)") long countCouple(@Param("userId1") long userId1, @Param("userId2") long userId2); /** Delete a friendship between two users. */ @Modifying @Query("delete from Friendship f " + "where (f.requestFrom.id = :userId1 and f.requestTo.id = :userId2) or (f.requestFrom.id = :userId2 and f.requestTo.id = :userId1)") void deleteCouple(@Param("userId1") long userId1, @Param("userId2") long userId2); /** Find all friends for given user. */ @Query("select f from Friendship f " + "where f.requestFrom.id = :userId or f.requestTo.id = :userId order by f.creationDate desc, f.id desc") Stream<FriendshipEntity> streamAllFor(@Param("userId") long userId); /** Find all friends for given user. */ @ExistForTesting(why = "FriendshipWSIntegrationTest") @Query("select f from Friendship f " + "where f.requestFrom.id = :userId or f.requestTo.id = :userId order by f.creationDate desc, f.id desc") List<FriendshipEntity> findAllFor(@Param("userId") long userId); }
mit
manishkarney/H2OBot
H2OBot/src/edu/scu/cs/robotics/communication/JoysticksInput.java
3108
package edu.scu.cs.robotics.communication; /** * Singleton that maintains joystick inputs. This is used to obtain string representation of current Joystick inputs. * Created by manishkarney on 4/20/14. */ public class JoysticksInput { private static JoysticksInput instance=null; private JoystickReading leftJoystickReadings=null; private JoystickReading rightJoystickReadings=null; private StringBuilder mStringBuilder=null; //Constants private static final char[] messageHead = {'{','[','l','#'}; private static final char[] messageMid = {']','%','[','r','#'}; private static final char[] messageEnd = {']','}'}; private static final char comma = ','; private static final char[] directionId = {'d',':'}; private static final char[] angleId = {'a',':'}; private static final char[] powerId = {'p',':'}; private JoysticksInput(){ leftJoystickReadings = new JoystickReading(0,0,0); rightJoystickReadings = new JoystickReading(0,0,0); } public static synchronized JoysticksInput getInstance(){ if(instance==null){ instance = new JoysticksInput(); } return instance; } //TODO Possibly make this a JSON string. public synchronized String getReadingsData(){ if(mStringBuilder==null) { mStringBuilder = new StringBuilder(); } //forming the string char[] directionValue; char[] angleValue; char[] powerValue; //Left Joystick directionValue = (""+leftJoystickReadings.getDirection()).toCharArray(); angleValue = (""+leftJoystickReadings.getAngle()).toCharArray(); powerValue = (""+leftJoystickReadings.getPower()).toCharArray(); mStringBuilder.append(messageHead); mStringBuilder.append(directionId); mStringBuilder.append(directionValue); mStringBuilder.append(comma); mStringBuilder.append(angleId); mStringBuilder.append(angleValue); mStringBuilder.append(comma); mStringBuilder.append(powerId); mStringBuilder.append(powerValue); mStringBuilder.append(messageMid); directionValue = (""+rightJoystickReadings.getDirection()).toCharArray(); angleValue = (""+rightJoystickReadings.getAngle()).toCharArray(); powerValue = (""+rightJoystickReadings.getPower()).toCharArray(); mStringBuilder.append(directionId); mStringBuilder.append(directionValue); mStringBuilder.append(comma); mStringBuilder.append(angleId); mStringBuilder.append(angleValue); mStringBuilder.append(comma); mStringBuilder.append(powerId); mStringBuilder.append(powerValue); mStringBuilder.append(messageEnd); String data = mStringBuilder.toString(); mStringBuilder.setLength(0); return data; } public synchronized JoystickReading getRightJoystick() { return rightJoystickReadings; } public synchronized JoystickReading getLeftJoystick() { return leftJoystickReadings; } }
mit
bragex/the-vigilantes
Is-202/Sprint_1/StudentProsjektV2/src/java/Servlet/Add.java
3631
package Servlet; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import Java.Tools; import javax.servlet.RequestDispatcher; /** * * @author by-cr */ @WebServlet(urlPatterns = {"/Add"}) public class Add extends HttpServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet ModulLagrer</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Servlet ModulLagrer at " + request.getContextPath() + "</h1>"); String first; String last; String email; String status; first = request.getParameter("first"); last = request.getParameter("last"); email = request.getParameter("email"); status = request.getParameter("status"); Tools dbTools = new Tools(); dbTools.connect(); dbTools.newUser(first, last, email, status); out.println("</body>"); out.println("</html>"); RequestDispatcher rd = request.getRequestDispatcher("AddUser"); rd.forward(request, response); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
mit
deepsleep/json-validations
src/main/java/com/jfcheng/json/annotation/MethodValidation.java
399
package com.jfcheng.json.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Created by jfcheng on 2/27/16. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface MethodValidation { boolean isRequest(); boolean isResponse(); }
mit
stackprobe/Java
charlotte/saber/htt/HttSaberLily.java
91
package charlotte.saber.htt; public interface HttSaberLily extends HttSaber { // empty }
mit
digitalheir/java-legislation-gov-uk-library
src/main/java/uk/gov/legislation/namespaces/metadata/ScheduleParagraphs.java
1638
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2015.08.07 at 06:17:52 PM CEST // package uk.gov.legislation.namespaces.metadata; import javax.xml.bind.annotation.*; import java.math.BigInteger; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;attribute name="Value" use="required" type="{http://www.w3.org/2001/XMLSchema}integer" /&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") @XmlRootElement(name = "ScheduleParagraphs") public class ScheduleParagraphs { @XmlAttribute(name = "Value", required = true) protected BigInteger value; /** * Gets the value of the value property. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getValue() { return value; } /** * Sets the value of the value property. * * @param value * allowed object is * {@link BigInteger } * */ public void setValue(BigInteger value) { this.value = value; } }
mit
ngageoint/disconnected-content-explorer-android
app/src/main/java/mil/nga/dice/report/WebViewJavascriptBridgeClient.java
1553
package mil.nga.dice.report; import android.content.Context; import android.os.Build; import android.util.Log; import android.webkit.WebView; import android.webkit.WebViewClient; import java.io.IOException; import java.io.InputStream; import java.util.Scanner; import mil.nga.dice.R; /** * WebView Javascript Bridge Client */ public class WebViewJavascriptBridgeClient extends WebViewClient { /** * Application context */ protected final Context context; public WebViewJavascriptBridgeClient(Context context) { this.context = context; } @Override public void onPageFinished(WebView webView, String url) { Log.d("JSBridge", "onPageFinished"); loadWebViewJavascriptBridgeJs(webView); } private void loadWebViewJavascriptBridgeJs(WebView webView) { InputStream is = context.getResources().openRawResource(R.raw.webviewjavascriptbridge); String script = convertStreamToString(is); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { webView.evaluateJavascript(script, null); } else { webView.loadUrl("javascript:" + script); } } public static String convertStreamToString(java.io.InputStream is) { String s = ""; try { Scanner scanner = new Scanner(is, "UTF-8").useDelimiter("\\A"); if (scanner.hasNext()) s = scanner.next(); is.close(); } catch (IOException e) { e.printStackTrace(); } return s; } }
mit
Azure/azure-sdk-for-java
sdk/databox/azure-resourcemanager-databox/src/main/java/com/azure/resourcemanager/databox/models/RegionConfigurationResponse.java
1150
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.databox.models; import com.azure.resourcemanager.databox.fluent.models.RegionConfigurationResponseInner; /** An immutable client-side representation of RegionConfigurationResponse. */ public interface RegionConfigurationResponse { /** * Gets the scheduleAvailabilityResponse property: Schedule availability for given sku in a region. * * @return the scheduleAvailabilityResponse value. */ ScheduleAvailabilityResponse scheduleAvailabilityResponse(); /** * Gets the transportAvailabilityResponse property: Transport options available for given sku in a region. * * @return the transportAvailabilityResponse value. */ TransportAvailabilityResponse transportAvailabilityResponse(); /** * Gets the inner com.azure.resourcemanager.databox.fluent.models.RegionConfigurationResponseInner object. * * @return the inner object. */ RegionConfigurationResponseInner innerModel(); }
mit
Mozu/mozu-java
mozu-javaasync-core/src/main/java/com/mozu/api/resources/commerce/orders/OrderAttributeResource.java
9726
/** * This code was auto-generated by a Codezu. * * Changes to this file may cause incorrect behavior and will be lost if * the code is regenerated. */ package com.mozu.api.resources.commerce.orders; import com.mozu.api.ApiContext; import java.util.List; import java.util.ArrayList; import com.mozu.api.MozuClient; import com.mozu.api.MozuClientFactory; import com.mozu.api.MozuUrl; import com.mozu.api.Headers; import org.joda.time.DateTime; import com.mozu.api.AsyncCallback; import java.util.concurrent.CountDownLatch; import com.mozu.api.security.AuthTicket; import org.apache.commons.lang.StringUtils; /** <summary> * Use the Order Attributes resource to define how an order attribute definition applies to a specific order. * </summary> */ public class OrderAttributeResource { /// /// <see cref="Mozu.Api.ApiContext"/> /// private ApiContext _apiContext; public OrderAttributeResource(ApiContext apiContext) { _apiContext = apiContext; } /** * * <p><pre><code> * OrderAttribute orderattribute = new OrderAttribute(); * OrderAttribute orderAttribute = orderattribute.getOrderAttributes( orderId); * </code></pre></p> * @param orderId Unique identifier of the order. * @return List<com.mozu.api.contracts.commerceruntime.orders.OrderAttribute> * @see com.mozu.api.contracts.commerceruntime.orders.OrderAttribute */ public List<com.mozu.api.contracts.commerceruntime.orders.OrderAttribute> getOrderAttributes(String orderId) throws Exception { MozuClient<List<com.mozu.api.contracts.commerceruntime.orders.OrderAttribute>> client = com.mozu.api.clients.commerce.orders.OrderAttributeClient.getOrderAttributesClient( orderId); client.setContext(_apiContext); client.executeRequest(); return client.getResult(); } /** * * <p><pre><code> * OrderAttribute orderattribute = new OrderAttribute(); * CountDownLatch latch = orderattribute.getOrderAttributes( orderId, callback ); * latch.await() * </code></pre></p> * @param orderId Unique identifier of the order. * @param callback callback handler for asynchronous operations * @return List<com.mozu.api.contracts.commerceruntime.orders.OrderAttribute> * @see com.mozu.api.contracts.commerceruntime.orders.OrderAttribute */ public CountDownLatch getOrderAttributesAsync(String orderId, AsyncCallback<List<com.mozu.api.contracts.commerceruntime.orders.OrderAttribute>> callback) throws Exception { MozuClient<List<com.mozu.api.contracts.commerceruntime.orders.OrderAttribute>> client = com.mozu.api.clients.commerce.orders.OrderAttributeClient.getOrderAttributesClient( orderId); client.setContext(_apiContext); return client.executeRequest(callback); } /** * * <p><pre><code> * OrderAttribute orderattribute = new OrderAttribute(); * OrderAttribute orderAttribute = orderattribute.createOrderAttributes( orderAttributes, orderId); * </code></pre></p> * @param orderId Unique identifier of the order. * @param orderAttributes Properties of an attribute applied to an order. * @return List<com.mozu.api.contracts.commerceruntime.orders.OrderAttribute> * @see com.mozu.api.contracts.commerceruntime.orders.OrderAttribute * @see com.mozu.api.contracts.commerceruntime.orders.OrderAttribute */ public List<com.mozu.api.contracts.commerceruntime.orders.OrderAttribute> createOrderAttributes(List<com.mozu.api.contracts.commerceruntime.orders.OrderAttribute> orderAttributes, String orderId) throws Exception { MozuClient<List<com.mozu.api.contracts.commerceruntime.orders.OrderAttribute>> client = com.mozu.api.clients.commerce.orders.OrderAttributeClient.createOrderAttributesClient( orderAttributes, orderId); client.setContext(_apiContext); client.executeRequest(); return client.getResult(); } /** * * <p><pre><code> * OrderAttribute orderattribute = new OrderAttribute(); * CountDownLatch latch = orderattribute.createOrderAttributes( orderAttributes, orderId, callback ); * latch.await() * </code></pre></p> * @param orderId Unique identifier of the order. * @param callback callback handler for asynchronous operations * @param orderAttributes Properties of an attribute applied to an order. * @return List<com.mozu.api.contracts.commerceruntime.orders.OrderAttribute> * @see com.mozu.api.contracts.commerceruntime.orders.OrderAttribute * @see com.mozu.api.contracts.commerceruntime.orders.OrderAttribute */ public CountDownLatch createOrderAttributesAsync(List<com.mozu.api.contracts.commerceruntime.orders.OrderAttribute> orderAttributes, String orderId, AsyncCallback<List<com.mozu.api.contracts.commerceruntime.orders.OrderAttribute>> callback) throws Exception { MozuClient<List<com.mozu.api.contracts.commerceruntime.orders.OrderAttribute>> client = com.mozu.api.clients.commerce.orders.OrderAttributeClient.createOrderAttributesClient( orderAttributes, orderId); client.setContext(_apiContext); return client.executeRequest(callback); } /** * * <p><pre><code> * OrderAttribute orderattribute = new OrderAttribute(); * OrderAttribute orderAttribute = orderattribute.updateOrderAttributes( orderAttributes, orderId); * </code></pre></p> * @param orderId Unique identifier of the order. * @param orderAttributes Properties of an attribute applied to an order. * @return List<com.mozu.api.contracts.commerceruntime.orders.OrderAttribute> * @see com.mozu.api.contracts.commerceruntime.orders.OrderAttribute * @see com.mozu.api.contracts.commerceruntime.orders.OrderAttribute */ public List<com.mozu.api.contracts.commerceruntime.orders.OrderAttribute> updateOrderAttributes(List<com.mozu.api.contracts.commerceruntime.orders.OrderAttribute> orderAttributes, String orderId) throws Exception { return updateOrderAttributes( orderAttributes, orderId, null); } /** * * <p><pre><code> * OrderAttribute orderattribute = new OrderAttribute(); * CountDownLatch latch = orderattribute.updateOrderAttributes( orderAttributes, orderId, callback ); * latch.await() * </code></pre></p> * @param orderId Unique identifier of the order. * @param callback callback handler for asynchronous operations * @param orderAttributes Properties of an attribute applied to an order. * @return List<com.mozu.api.contracts.commerceruntime.orders.OrderAttribute> * @see com.mozu.api.contracts.commerceruntime.orders.OrderAttribute * @see com.mozu.api.contracts.commerceruntime.orders.OrderAttribute */ public CountDownLatch updateOrderAttributesAsync(List<com.mozu.api.contracts.commerceruntime.orders.OrderAttribute> orderAttributes, String orderId, AsyncCallback<List<com.mozu.api.contracts.commerceruntime.orders.OrderAttribute>> callback) throws Exception { return updateOrderAttributesAsync( orderAttributes, orderId, null, callback); } /** * * <p><pre><code> * OrderAttribute orderattribute = new OrderAttribute(); * OrderAttribute orderAttribute = orderattribute.updateOrderAttributes( orderAttributes, orderId, removeMissing); * </code></pre></p> * @param orderId Unique identifier of the order. * @param removeMissing If true, the operation removes missing properties so that the updated order attributes will not show properties with a null value. * @param orderAttributes Properties of an attribute applied to an order. * @return List<com.mozu.api.contracts.commerceruntime.orders.OrderAttribute> * @see com.mozu.api.contracts.commerceruntime.orders.OrderAttribute * @see com.mozu.api.contracts.commerceruntime.orders.OrderAttribute */ public List<com.mozu.api.contracts.commerceruntime.orders.OrderAttribute> updateOrderAttributes(List<com.mozu.api.contracts.commerceruntime.orders.OrderAttribute> orderAttributes, String orderId, Boolean removeMissing) throws Exception { MozuClient<List<com.mozu.api.contracts.commerceruntime.orders.OrderAttribute>> client = com.mozu.api.clients.commerce.orders.OrderAttributeClient.updateOrderAttributesClient( orderAttributes, orderId, removeMissing); client.setContext(_apiContext); client.executeRequest(); return client.getResult(); } /** * * <p><pre><code> * OrderAttribute orderattribute = new OrderAttribute(); * CountDownLatch latch = orderattribute.updateOrderAttributes( orderAttributes, orderId, removeMissing, callback ); * latch.await() * </code></pre></p> * @param orderId Unique identifier of the order. * @param removeMissing If true, the operation removes missing properties so that the updated order attributes will not show properties with a null value. * @param callback callback handler for asynchronous operations * @param orderAttributes Properties of an attribute applied to an order. * @return List<com.mozu.api.contracts.commerceruntime.orders.OrderAttribute> * @see com.mozu.api.contracts.commerceruntime.orders.OrderAttribute * @see com.mozu.api.contracts.commerceruntime.orders.OrderAttribute */ public CountDownLatch updateOrderAttributesAsync(List<com.mozu.api.contracts.commerceruntime.orders.OrderAttribute> orderAttributes, String orderId, Boolean removeMissing, AsyncCallback<List<com.mozu.api.contracts.commerceruntime.orders.OrderAttribute>> callback) throws Exception { MozuClient<List<com.mozu.api.contracts.commerceruntime.orders.OrderAttribute>> client = com.mozu.api.clients.commerce.orders.OrderAttributeClient.updateOrderAttributesClient( orderAttributes, orderId, removeMissing); client.setContext(_apiContext); return client.executeRequest(callback); } }
mit
madumlao/oxAuth
Client/src/test/java/org/xdi/oxauth/ws/rs/PkceHttpTest.java
9792
/* * oxAuth is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text. * * Copyright (c) 2014, Gluu */ package org.xdi.oxauth.ws.rs; import org.testng.annotations.Parameters; import org.testng.annotations.Test; import org.xdi.oxauth.BaseTest; import org.xdi.oxauth.client.*; import org.xdi.oxauth.model.authorize.CodeVerifier; import org.xdi.oxauth.model.common.AuthenticationMethod; import org.xdi.oxauth.model.common.GrantType; import org.xdi.oxauth.model.common.ResponseType; import org.xdi.oxauth.model.crypto.signature.RSAPublicKey; import org.xdi.oxauth.model.crypto.signature.SignatureAlgorithm; import org.xdi.oxauth.model.jws.RSASigner; import org.xdi.oxauth.model.jwt.Jwt; import org.xdi.oxauth.model.jwt.JwtClaimName; import org.xdi.oxauth.model.jwt.JwtHeaderName; import org.xdi.oxauth.model.register.ApplicationType; import org.xdi.oxauth.model.util.StringUtils; import java.util.Arrays; import java.util.List; import java.util.UUID; import static org.testng.Assert.*; import static org.xdi.oxauth.client.Asserter.assertOk; /** * @author Yuriy Zabrovarnyy * @author Javier Rojas Blum * @version March 3, 2017 */ public class PkceHttpTest extends BaseTest { @Parameters({"redirectUris", "userId", "userSecret", "redirectUri", "sectorIdentifierUri"}) @Test public void tokenWithPkceCheck( final String redirectUris, final String userId, final String userSecret, final String redirectUri, final String sectorIdentifierUri) throws Exception { showTitle("tokenWithPkceCheck"); // 1. Register client List<ResponseType> responseTypes = Arrays.asList(ResponseType.CODE, ResponseType.ID_TOKEN); RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app", StringUtils.spaceSeparatedToList(redirectUris)); registerRequest.setTokenEndpointAuthMethod(AuthenticationMethod.CLIENT_SECRET_POST); registerRequest.setSectorIdentifierUri(sectorIdentifierUri); registerRequest.setResponseTypes(responseTypes); RegisterClient registerClient = new RegisterClient(registrationEndpoint); registerClient.setRequest(registerRequest); RegisterResponse registerResponse = registerClient.exec(); showClient(registerClient); assertOk(registerResponse); assertNotNull(registerResponse.getRegistrationAccessToken()); // 3. Request authorization List<String> scopes = Arrays.asList( "openid", "profile", "address", "email"); String state = UUID.randomUUID().toString(); String nonce = UUID.randomUUID().toString(); AuthorizationRequest authorizationRequest = new AuthorizationRequest(responseTypes, registerResponse.getClientId(), scopes, redirectUri, nonce); authorizationRequest.setState(state); CodeVerifier verifier = authorizationRequest.generateAndSetCodeChallengeWithMethod(); AuthorizationResponse authorizationResponse = authenticateResourceOwnerAndGrantAccess( authorizationEndpoint, authorizationRequest, userId, userSecret); assertNotNull(authorizationResponse.getLocation(), "The location is null"); assertNotNull(authorizationResponse.getCode(), "The authorization code is null"); assertNotNull(authorizationResponse.getIdToken(), "The ID Token is null"); assertNotNull(authorizationResponse.getState(), "The state is null"); assertNotNull(authorizationResponse.getScope(), "The scope is null"); String authorizationCode = authorizationResponse.getCode(); String idToken = authorizationResponse.getIdToken(); // 4. Validate id_token Jwt jwt = Jwt.parse(idToken); assertNotNull(jwt.getHeader().getClaimAsString(JwtHeaderName.TYPE)); assertNotNull(jwt.getHeader().getClaimAsString(JwtHeaderName.ALGORITHM)); assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.ISSUER)); assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.AUDIENCE)); assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.EXPIRATION_TIME)); assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.ISSUED_AT)); assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.SUBJECT_IDENTIFIER)); assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.CODE_HASH)); assertNotNull(jwt.getClaims().getClaimAsString(JwtClaimName.AUTHENTICATION_TIME)); RSAPublicKey publicKey = JwkClient.getRSAPublicKey( jwksUri, jwt.getHeader().getClaimAsString(JwtHeaderName.KEY_ID)); RSASigner rsaSigner = new RSASigner(SignatureAlgorithm.RS256, publicKey); assertTrue(rsaSigner.validate(jwt)); // 5. Get Access Token TokenRequest tokenRequest = new TokenRequest(GrantType.AUTHORIZATION_CODE); tokenRequest.setCode(authorizationCode); tokenRequest.setRedirectUri(redirectUri); tokenRequest.setAuthUsername(registerResponse.getClientId()); tokenRequest.setAuthPassword(registerResponse.getClientSecret()); tokenRequest.setAuthenticationMethod(AuthenticationMethod.CLIENT_SECRET_POST); tokenRequest.setCodeVerifier(verifier.getCodeVerifier()); TokenClient tokenClient = new TokenClient(tokenEndpoint); tokenClient.setRequest(tokenRequest); TokenResponse tokenResponse = tokenClient.exec(); showClient(tokenClient); assertEquals(tokenResponse.getStatus(), 200, "Unexpected response code: " + tokenResponse.getStatus()); assertNotNull(tokenResponse.getEntity(), "The entity is null"); assertNotNull(tokenResponse.getAccessToken(), "The access token is null"); assertNotNull(tokenResponse.getExpiresIn(), "The expires in value is null"); assertNotNull(tokenResponse.getTokenType(), "The token type is null"); assertNotNull(tokenResponse.getRefreshToken(), "The refresh token is null"); } @Parameters({"redirectUris", "userId", "userSecret", "redirectUri", "sectorIdentifierUri"}) @Test public void invalidCodeVerifier( final String redirectUris, final String userId, final String userSecret, final String redirectUri, final String sectorIdentifierUri) throws Exception { showTitle("invalidCodeVerifier"); // 1. Register client RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth test app", StringUtils.spaceSeparatedToList(redirectUris)); registerRequest.setTokenEndpointAuthMethod(AuthenticationMethod.CLIENT_SECRET_POST); registerRequest.setSectorIdentifierUri(sectorIdentifierUri); RegisterClient registerClient = new RegisterClient(registrationEndpoint); registerClient.setRequest(registerRequest); RegisterResponse registerResponse = registerClient.exec(); showClient(registerClient); assertOk(registerResponse); assertNotNull(registerResponse.getRegistrationAccessToken()); // 3. Request authorization List<ResponseType> responseTypes = Arrays.asList(ResponseType.CODE); List<String> scopes = Arrays.asList( "openid", "profile", "address", "email"); String state = UUID.randomUUID().toString(); AuthorizationRequest authorizationRequest = new AuthorizationRequest(responseTypes, registerResponse.getClientId(), scopes, redirectUri, null); authorizationRequest.setState(state); authorizationRequest.generateAndSetCodeChallengeWithMethod(); // PKCE is set !!! AuthorizationResponse authorizationResponse = authenticateResourceOwnerAndGrantAccess( authorizationEndpoint, authorizationRequest, userId, userSecret); assertNotNull(authorizationResponse.getLocation(), "The location is null"); assertNotNull(authorizationResponse.getCode(), "The authorization code is null"); assertNotNull(authorizationResponse.getState(), "The state is null"); assertNotNull(authorizationResponse.getScope(), "The scope is null"); assertNull(authorizationResponse.getIdToken(), "The id token is not null"); String authorizationCode = authorizationResponse.getCode(); // 4. Get Access Token with invalid code verifier TokenRequest tokenRequest = new TokenRequest(GrantType.AUTHORIZATION_CODE); tokenRequest.setCode(authorizationCode); tokenRequest.setRedirectUri(redirectUri); tokenRequest.setAuthUsername(registerResponse.getClientId()); tokenRequest.setAuthPassword(registerResponse.getClientSecret()); tokenRequest.setAuthenticationMethod(AuthenticationMethod.CLIENT_SECRET_POST); tokenRequest.setCodeVerifier("invalid_code_verifier"); TokenClient tokenClient = new TokenClient(tokenEndpoint); tokenClient.setRequest(tokenRequest); TokenResponse tokenResponse = tokenClient.exec(); showClient(tokenClient); assertEquals(tokenResponse.getStatus(), 401, "Unexpected response code: " + tokenResponse.getStatus()); assertNull(tokenResponse.getAccessToken(), "The access token is null"); // 5. Get Access Token without code verifier tokenRequest.setCodeVerifier(null); tokenClient.setRequest(tokenRequest); tokenResponse = tokenClient.exec(); showClient(tokenClient); assertEquals(tokenResponse.getStatus(), 401, "Unexpected response code: " + tokenResponse.getStatus()); assertNull(tokenResponse.getAccessToken(), "The access token is null"); } }
mit
ntemplon/ygo-combo-calculator
src/com/croffgrin/ygocalc/ui/DeckViewer.java
2096
package com.croffgrin.ygocalc.ui; import com.croffgrin.ygocalc.card.Card; import com.croffgrin.ygocalc.card.Deck; import javax.swing.*; import java.awt.*; /** * Copyright (c) 2016 Nathan S. Templon * <p> * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, * and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * <p> * The above copyright notice and this permission notice shall be included in all copies or substantial portions * of the Software. * <p> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ public class DeckViewer extends JFrame { private final Deck deck; private JList<Card> mainList; private JList<Card> extraList; private JList<Card> sideList; private JButton closeButton; private JPanel mainPanel; public DeckViewer(Deck deck) { super(deck.getName()); this.deck = deck; this.mainList.setListData(deck.getMain().cardArray()); this.extraList.setListData(deck.getExtra().cardArray()); this.sideList.setListData(deck.getSide().cardArray()); this.closeButton.addActionListener(e -> this.dispose()); this.setContentPane(this.mainPanel); this.setSize(new Dimension(1200, 700)); this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); } public Deck getDeck() { return this.deck; } }
mit
selvasingh/azure-sdk-for-java
sdk/network/mgmt-v2020_06_01/src/main/java/com/microsoft/azure/management/network/v2020_06_01/GatewayRoute.java
2696
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.network.v2020_06_01; import com.fasterxml.jackson.annotation.JsonProperty; /** * Gateway routing details. */ public class GatewayRoute { /** * The gateway's local address. */ @JsonProperty(value = "localAddress", access = JsonProperty.Access.WRITE_ONLY) private String localAddress; /** * The route's network prefix. */ @JsonProperty(value = "network", access = JsonProperty.Access.WRITE_ONLY) private String network; /** * The route's next hop. */ @JsonProperty(value = "nextHop", access = JsonProperty.Access.WRITE_ONLY) private String nextHop; /** * The peer this route was learned from. */ @JsonProperty(value = "sourcePeer", access = JsonProperty.Access.WRITE_ONLY) private String sourcePeer; /** * The source this route was learned from. */ @JsonProperty(value = "origin", access = JsonProperty.Access.WRITE_ONLY) private String origin; /** * The route's AS path sequence. */ @JsonProperty(value = "asPath", access = JsonProperty.Access.WRITE_ONLY) private String asPath; /** * The route's weight. */ @JsonProperty(value = "weight", access = JsonProperty.Access.WRITE_ONLY) private Integer weight; /** * Get the gateway's local address. * * @return the localAddress value */ public String localAddress() { return this.localAddress; } /** * Get the route's network prefix. * * @return the network value */ public String network() { return this.network; } /** * Get the route's next hop. * * @return the nextHop value */ public String nextHop() { return this.nextHop; } /** * Get the peer this route was learned from. * * @return the sourcePeer value */ public String sourcePeer() { return this.sourcePeer; } /** * Get the source this route was learned from. * * @return the origin value */ public String origin() { return this.origin; } /** * Get the route's AS path sequence. * * @return the asPath value */ public String asPath() { return this.asPath; } /** * Get the route's weight. * * @return the weight value */ public Integer weight() { return this.weight; } }
mit
ikhaliq15/JHearthstone
src/net/theinterweb/Server/JSonReader.java
23589
package net.theinterweb.Server; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; public class JSonReader { private static ArrayList<String> collections = new ArrayList<String>(); private static ArrayList<String> legendaries = new ArrayList<String>(); private static ArrayList<String> epics = new ArrayList<String>(); private static ArrayList<String> rares = new ArrayList<String>(); private static ArrayList<String> commons = new ArrayList<String>(); private static String file; public JSonReader(String inputStream){ file = inputStream; } public ArrayList<String> getAttributes (String n) throws org.json.simple.parser.ParseException { ArrayList<String> attr = new ArrayList<>(); JSONParser parser = new JSONParser(); try { Object obj = parser.parse(new FileReader(file)); JSONObject jsonObject = (JSONObject) obj; JSONArray cards = (JSONArray) jsonObject.get("cards"); for (int i = 0; i < cards.size(); i++){ JSONObject card = (JSONObject) cards.get(i); if(card.get("name").equals(n)){ if (card.containsKey("attributes")) { JSONObject attributes = (JSONObject) card.get("attributes"); for (int j = 0; j < attributes.keySet().size(); j++) { attr.add((String) (attributes.keySet().toArray()[j])); } } } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return attr; } public boolean hasAura (String n) throws org.json.simple.parser.ParseException { JSONParser parser = new JSONParser(); try { Object obj = parser.parse(new FileReader(file)); JSONObject jsonObject = (JSONObject) obj; JSONArray cards = (JSONArray) jsonObject.get("cards"); for (int i = 0; i < cards.size(); i++){ JSONObject card = (JSONObject) cards.get(i); if(card.get("name").equals(n)){ return card.containsKey("aura"); } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return false; } public boolean hasAura (String n, String t) throws org.json.simple.parser.ParseException{ JSONParser parser = new JSONParser(); try { Object obj = parser.parse(new FileReader(file)); JSONObject jsonObject = (JSONObject) obj; JSONArray cards = (JSONArray) jsonObject.get("cards"); for (int i = 0; i < cards.size(); i++){ JSONObject card = (JSONObject) cards.get(i); if(card.get("name").equals(n) && card.get("type").equals(t)){ return card.containsKey("aura"); } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return false; } public JSONObject getAura(String n) throws org.json.simple.parser.ParseException{ JSONObject temp = new JSONObject(); JSONParser parser = new JSONParser(); try { Object obj = parser.parse(new FileReader(file)); JSONObject jsonObject = (JSONObject) obj; JSONArray cards = (JSONArray) jsonObject.get("cards"); for (int i = 0; i < cards.size(); i++){ JSONObject card = (JSONObject) cards.get(i); if(card.get("name").equals(n)){ if (card.containsKey("aura")) { return (JSONObject)(card.get("aura")); } } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return temp; } public ArrayList<String> getAttributes (String n, String t) throws org.json.simple.parser.ParseException{ ArrayList<String> attr = new ArrayList<>(); JSONParser parser = new JSONParser(); try { Object obj = parser.parse(new FileReader(file)); JSONObject jsonObject = (JSONObject) obj; JSONArray cards = (JSONArray) jsonObject.get("cards"); for (int i = 0; i < cards.size(); i++){ JSONObject card = (JSONObject) cards.get(i); if(card.get("name").equals(n) && card.get("type").equals(t)){ if (card.containsKey("attributes")) { JSONObject attributes = (JSONObject) card.get("attributes"); for (int j = 0; j < attributes.keySet().size(); j++) { attr.add((String) (attributes.keySet().toArray()[j])); } } } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return attr; } public ArrayList<Object> getAttributeValues (String n, String t) throws org.json.simple.parser.ParseException{ t = t.toUpperCase(); ArrayList<Object> attr = new ArrayList<>(); JSONParser parser = new JSONParser(); try { Object obj = parser.parse(new FileReader(file)); JSONObject jsonObject = (JSONObject) obj; JSONArray cards = (JSONArray) jsonObject.get("cards"); for (int i = 0; i < cards.size(); i++){ JSONObject card = (JSONObject) cards.get(i); if(card.get("name").equals(n) && card.get("type").equals(t)){ if (card.containsKey("attributes")) { JSONObject attributes = (JSONObject) card.get("attributes"); for (int j = 0; j < attributes.keySet().size(); j++) { attr.add(attributes.get(attributes.keySet().toArray()[j])); } } } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } //System.out.println("ATTRIBUTE VALUES OF " + n.toUpperCase() + ": " + attr); return attr; } public ArrayList<String> getTriggers (String n, String t) throws org.json.simple.parser.ParseException{ t = t.toUpperCase(); ArrayList<String> triggers = new ArrayList<>(); JSONParser parser = new JSONParser(); try { Object obj = parser.parse(new FileReader(file)); JSONObject jsonObject = (JSONObject) obj; JSONArray cards = (JSONArray) jsonObject.get("cards"); for (int i = 0; i < cards.size(); i++){ JSONObject card = (JSONObject) cards.get(i); if(card.get("name").equals(n) && card.get("type").equals(t)){ if (card.containsKey("trigger")) { JSONObject trigger = (JSONObject) card.get("trigger"); if (trigger.containsKey("eventTrigger")) { JSONObject eventTrigger = (JSONObject) trigger.get("eventTrigger"); if (eventTrigger.containsKey("class")) { triggers.add((String)eventTrigger.get("class")); } } } } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return triggers; } public String getRace (String n, String t) throws org.json.simple.parser.ParseException{ t = t.toUpperCase(); JSONParser parser = new JSONParser(); try { Object obj = parser.parse(new FileReader(file)); JSONObject jsonObject = (JSONObject) obj; JSONArray cards = (JSONArray) jsonObject.get("cards"); for (int i = 0; i < cards.size(); i++){ JSONObject card = (JSONObject) cards.get(i); if(card.get("name").equals(n) && card.get("type").equals(t)){ if (card.containsKey("race")) { return (String) card.get("race"); } } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return ""; } public JSONObject getTriggerObject (String n, String t) throws org.json.simple.parser.ParseException{ t = t.toUpperCase(); JSONParser parser = new JSONParser(); try { Object obj = parser.parse(new FileReader(file)); JSONObject jsonObject = (JSONObject) obj; JSONArray cards = (JSONArray) jsonObject.get("cards"); for (int i = 0; i < cards.size(); i++){ JSONObject card = (JSONObject) cards.get(i); if(card.get("name").equals(n) && card.get("type").equals(t)){ if (card.containsKey("trigger")) { JSONObject trigger = (JSONObject) card.get("trigger"); return trigger; } } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } public JSONObject getBattlecry(String n) throws org.json.simple.parser.ParseException{ JSONObject temp = new JSONObject(); JSONParser parser = new JSONParser(); try { Object obj = parser.parse(new FileReader(file)); JSONObject jsonObject = (JSONObject) obj; JSONArray cards = (JSONArray) jsonObject.get("cards"); for (int i = 0; i < cards.size(); i++){ JSONObject card = (JSONObject) cards.get(i); if(card.get("name").equals(n)){ if (card.containsKey("battlecry")) { return (JSONObject)(card.get("battlecry")); } } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return temp; } public JSONObject getEffect(String n) throws org.json.simple.parser.ParseException{ JSONObject temp = new JSONObject(); JSONParser parser = new JSONParser(); try { Object obj = parser.parse(new FileReader(file)); JSONObject jsonObject = (JSONObject) obj; JSONArray cards = (JSONArray) jsonObject.get("cards"); for (int i = 0; i < cards.size(); i++){ JSONObject card = (JSONObject) cards.get(i); if(card.get("name").equals(n)){ return card; } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return temp; } public ArrayList<ArrayList<String>> getEffects(String n) throws org.json.simple.parser.ParseException{ ArrayList<ArrayList<String>> effects = new ArrayList<ArrayList<String>>(); JSONParser parser = new JSONParser(); try { Object obj = parser.parse(new FileReader(file)); JSONObject jsonObject = (JSONObject) obj; JSONArray cards = (JSONArray) jsonObject.get("cards"); for (int i = 0; i < cards.size(); i++){ JSONObject card = (JSONObject) cards.get(i); if(card.get("name").equals(n)){ JSONArray effect = (JSONArray) card.get("effect_list"); for(int j = 0; j < effect.size(); j++){ effects.add(new ArrayList<String>()); JSONObject e = (JSONObject) effect.get(j); effects.get(effects.size()-1).add(e.get("effect").toString()); effects.get(effects.size()-1).add(e.get("extra").toString()); } } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return effects; } private long [] findCard(String n) throws org.json.simple.parser.ParseException{ JSONParser parser = new JSONParser(); try { Object obj = parser.parse(new FileReader(file)); JSONObject jsonObject = (JSONObject) obj; JSONArray cards = (JSONArray) jsonObject.get("cards"); for (int i = 0; i < cards.size(); i++){ JSONObject card = (JSONObject) cards.get(i); if(card.get("name").equals(n)){ long t = -1; if(card.get("type") != null && card.get("type").equals("MINION")){ t = 1; }else if(card.get("type") != null && card.get("type").equals("SPELL")){ t = 2; }else if(card.get("type") != null && card.get("type").equals("WEAPON")){ t = 3; } if(t == 1){ long attack = 0; if (card.get("baseAttack") == null){ attack = 0; //System.out.println("CARD IS ZERO ATTACK!"); }else{ attack = (long) card.get("baseAttack"); } long [] info = { t, (long) card.get("baseManaCost"), attack, (long) card.get("baseHp")}; return info; }else if(t == 2){ long[] info = { t, (long) card.get("baseManaCost")}; return info; }else if (t == 3) { long [] info = { t, (long) card.get("baseManaCost"), (long) card.get("damage"), (long) card.get("durability")}; return info; } } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.out.println("Card not found: " + n); return new long[0]; } private long [] findCard(String n, String ty) throws org.json.simple.parser.ParseException{ JSONParser parser = new JSONParser(); try { Object obj = parser.parse(new FileReader(file)); JSONObject jsonObject = (JSONObject) obj; JSONArray cards = (JSONArray) jsonObject.get("cards"); for (int i = 0; i < cards.size(); i++){ JSONObject card = (JSONObject) cards.get(i); if(card.get("name").equals(n) && card.get("type").equals(ty)){ long t = -1; if(card.get("type") != null && card.get("type").equals("MINION")){ t = 1; }else if(card.get("type") != null && card.get("type").equals("SPELL")){ t = 2; }else if(card.get("type") != null && card.get("type").equals("WEAPON")){ t = 3; } if(t == 1){ long attack = 0; if (card.get("baseAttack") == null){ attack = 0; //System.out.println("CARD IS ZERO ATTACK!"); }else{ attack = (long) card.get("baseAttack"); } long [] info = { t, (long) card.get("baseManaCost"), attack, (long) card.get("baseHp")}; return info; }else if(t == 2){ long[] info = { t, (long) card.get("baseManaCost")}; return info; }else if (t == 3) { long [] info = { t, (long) card.get("baseManaCost"), (long) card.get("damage"), (long) card.get("durability")}; return info; } } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.out.println("Card not found: " + n); return new long[0]; } public long getAttack(String n) throws org.json.simple.parser.ParseException{ long[] info = findCard(n); if(info[0] != 2){ return info[2]; } return -1; } public long getHealth(String n) throws org.json.simple.parser.ParseException{ long[] info = findCard(n); if(info[0] != 2){ return info[3]; } return -1; } public long getAttack(String n, String t) throws org.json.simple.parser.ParseException{ long[] info = findCard(n, t); if(info[0] != 2){ return info[2]; } return -1; } public long getHealth(String n, String t) throws org.json.simple.parser.ParseException{ long[] info = findCard(n, t); if(info[0] != 2){ return info[3]; } return -1; } public long getCost(String n) throws org.json.simple.parser.ParseException{ //return findCard(n)[1]; file = "all-cards.json"; JSONParser parser = new JSONParser(); try { Object obj = parser.parse(new FileReader(file)); JSONObject jsonObject = (JSONObject) obj; JSONArray cards = (JSONArray) jsonObject.get("cards"); for (int i = 0; i < cards.size(); i++){ JSONObject card = (JSONObject) cards.get(i); if (card.get("name").equals(n)) { return (long) card.get("baseManaCost"); } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } System.out.println("COULD NOT FIND CARD: " + n); return -1; } public long getCost(String n, String t) throws org.json.simple.parser.ParseException{ //return findCard(n)[1]; file = "all-cards.json"; JSONParser parser = new JSONParser(); try { Object obj = parser.parse(new FileReader(file)); JSONObject jsonObject = (JSONObject) obj; JSONArray cards = (JSONArray) jsonObject.get("cards"); for (int i = 0; i < cards.size(); i++){ JSONObject card = (JSONObject) cards.get(i); if (card.get("name").equals(n) && card.get("type").equals(t)) { return (long) card.get("baseManaCost"); } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } System.out.println("COULD NOT FIND CARD: " + n); return -1; } public String getType(String n) throws org.json.simple.parser.ParseException{ long type = findCard(n)[0]; if (type == 1){ return "minion"; }else if(type == 2){ return "spell"; }else if(type == 3){ return "weapon"; } return "null"; } public static ArrayList<String> getCollection() { if (collections.size() > 0){ return collections; } file = "all-cards.json"; ArrayList<String> c = new ArrayList<String>(); JSONParser parser = new JSONParser(); try { Object obj = parser.parse(new FileReader(file)); JSONObject jsonObject = (JSONObject) obj; JSONArray cards = (JSONArray) jsonObject.get("cards"); for (int i = 0; i < cards.size(); i++){ JSONObject card = (JSONObject) cards.get(i); System.out.println(card.get("name")); if ((boolean)(card.get("collectible"))) { c.add((String) card.get("name")); } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } collections = c; return c; } public static String getRarity(String card_name) { file = "all-cards.json"; JSONParser parser = new JSONParser(); try { Object obj = parser.parse(new FileReader(file)); JSONObject jsonObject = (JSONObject) obj; JSONArray cards = (JSONArray) jsonObject.get("cards"); for (int i = 0; i < cards.size(); i++){ JSONObject card = (JSONObject) cards.get(i); if (card.get("name").equals(card_name)) { return (String) card.get("rarity"); } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } return ""; } public static String getRarity(String card_name, String type) { file = "all-cards.json"; JSONParser parser = new JSONParser(); try { Object obj = parser.parse(new FileReader(file)); JSONObject jsonObject = (JSONObject) obj; JSONArray cards = (JSONArray) jsonObject.get("cards"); for (int i = 0; i < cards.size(); i++){ JSONObject card = (JSONObject) cards.get(i); if (card.get("name").equals(card_name) && card.get("type").equals(type)) { return (String) card.get("rarity"); } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } return ""; } public static ArrayList<String> getARandomPack() { boolean gotBetterThanCommon = false; ArrayList<String> p = new ArrayList<String>(); for (int i = 0; i < 5; i++) { double f = Math.random(); if (f >= .9890) { p.add(getRandomLegendary()); gotBetterThanCommon = true; } else if (f >= .9558) { gotBetterThanCommon = true; p.add(getRandomEpic()); } else if (f >= .7716){ gotBetterThanCommon = true; p.add(getRandomRare()); } else { p.add(getRandomCommon()); } if (i == 4 && !gotBetterThanCommon) { p.remove(0); p.add(getRandomRare()); } } return p; } private static String getRandomLegendary() { if (legendaries.size() > 0) { return legendaries.get((int) (Math.random() * legendaries.size())); } file = "all-cards.json"; JSONParser parser = new JSONParser(); try { Object obj = parser.parse(new FileReader(file)); JSONObject jsonObject = (JSONObject) obj; JSONArray cards = (JSONArray) jsonObject.get("cards"); for (int i = 0; i < cards.size(); i++){ JSONObject card = (JSONObject) cards.get(i); if (card.get("rarity").equals("LEGENDARY") && (boolean)(card.get("collectible"))) { legendaries.add((String) card.get("name")); } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } return legendaries.get((int) (Math.random() * legendaries.size())); } private static String getRandomEpic() { if (epics.size() > 0) { return epics.get((int) (Math.random() * epics.size())); } file = "all-cards.json"; JSONParser parser = new JSONParser(); try { Object obj = parser.parse(new FileReader(file)); JSONObject jsonObject = (JSONObject) obj; JSONArray cards = (JSONArray) jsonObject.get("cards"); for (int i = 0; i < cards.size(); i++){ JSONObject card = (JSONObject) cards.get(i); if (card.get("rarity").equals("EPIC") && (boolean)(card.get("collectible"))) { epics.add((String) card.get("name")); } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } return epics.get((int) (Math.random() * epics.size())); } private static String getRandomRare() { if (rares.size() > 0) { return rares.get((int) (Math.random() * rares.size())); } file = "all-cards.json"; JSONParser parser = new JSONParser(); try { Object obj = parser.parse(new FileReader(file)); JSONObject jsonObject = (JSONObject) obj; JSONArray cards = (JSONArray) jsonObject.get("cards"); for (int i = 0; i < cards.size(); i++){ JSONObject card = (JSONObject) cards.get(i); if (card.get("rarity").equals("RARE") && (boolean)(card.get("collectible"))) { rares.add((String) card.get("name")); } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } return rares.get((int) (Math.random() * rares.size())); } private static String getRandomCommon() { if (commons.size() > 0) { return commons.get((int) (Math.random() * commons.size())); } file = "all-cards.json"; JSONParser parser = new JSONParser(); try { Object obj = parser.parse(new FileReader(file)); JSONObject jsonObject = (JSONObject) obj; JSONArray cards = (JSONArray) jsonObject.get("cards"); for (int i = 0; i < cards.size(); i++){ JSONObject card = (JSONObject) cards.get(i); if (card.get("rarity").equals("COMMON") && (boolean)(card.get("collectible"))) { commons.add((String) card.get("name")); } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } return commons.get((int) (Math.random() * commons.size())); } public static String getSet(String n) { file = "all-cards.json"; JSONParser parser = new JSONParser(); try { Object obj = parser.parse(new FileReader(file)); JSONObject jsonObject = (JSONObject) obj; JSONArray cards = (JSONArray) jsonObject.get("cards"); for (int i = 0; i < cards.size(); i++){ JSONObject card = (JSONObject) cards.get(i); if (card.get("name").equals(n)) { return (String) card.get("set"); } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } return ""; } public static String getSet(String n, String t) { file = "all-cards.json"; JSONParser parser = new JSONParser(); try { Object obj = parser.parse(new FileReader(file)); JSONObject jsonObject = (JSONObject) obj; JSONArray cards = (JSONArray) jsonObject.get("cards"); for (int i = 0; i < cards.size(); i++){ JSONObject card = (JSONObject) cards.get(i); if (card.get("name").equals(n) && card.get("type").equals(t)) { return (String) card.get("set"); } } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParseException e) { e.printStackTrace(); } return ""; } }
mit
kaeluka/spencer-all
spencer/src/main/java/com/github/kaeluka/spencer/Main.java
8559
package com.github.kaeluka.spencer; import com.github.kaeluka.spencer.server.TransformerServer; import org.apache.commons.cli.*; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.util.*; import java.net.URLClassLoader; import java.util.stream.Collectors; public class Main { private static final Options spencerOptions = initSpencerOptions(); private static Options initSpencerOptions() { final Options options = new Options(); final OptionGroup ioOptions = new OptionGroup(); ioOptions.addOption(Option .builder("tracedir") .hasArg() .argName("path/to/dir") .optionalArg(false) .desc("The directory to write to (default: /tmp).") .build()); ioOptions.addOption(Option .builder("notrace") .desc("For debugging, disable tracing to disk.") .build()); options.addOptionGroup(ioOptions); options.addOption(Option .builder("verbose") .desc("Show diagnostic output.") .build()); options.addOption(Option .builder("help") .desc("Display this help.") .build()); return options; } public static void main(String[] _args) throws IOException, InterruptedException { final ArrayList<String> args = tokenizeArgs(_args); final CommandLine spencerArgs = parseSpencerArgs(popSpencerArgs(args)); assert spencerArgs != null; logIfVerbose("spencerArgs: ", spencerArgs); final Iterator<Option> argIter = spencerArgs.iterator(); while (argIter.hasNext()) { logIfVerbose(argIter.next().toString(), spencerArgs); } logIfVerbose("tracedir:"+spencerArgs.getOptionValue("tracedir"), spencerArgs); new Thread(() -> { try { TransformerServer.main(new String[0]); } catch (ClassNotFoundException e) { e.printStackTrace(); } }).start(); //waiting for server to start TransformerServer.awaitRunning(); final Process process = getProcess(args, spencerArgs); final int exitStatus = process.waitFor(); TransformerServer.tearDown(); System.exit(exitStatus); } private static List<String> popSpencerArgs(List<String> args) { if (args.contains("--")) { final ArrayList<String> ret = new ArrayList<>(); int i = 0; for (String arg : args) { i++; if (arg.equals("--")) { break; } else { ret.add(arg); } } for ( ; i>0; --i) { args.remove(0); } return ret; } else { final ArrayList<String> ret = new ArrayList<>(args); args.clear(); return ret; } } private static CommandLine parseSpencerArgs(List<String> spencerArgs) { // System.out.println("spencer args are: "+spencerArgs); final DefaultParser defaultParser = new DefaultParser(); final CommandLine parsed; try { String[] args = Arrays.copyOf(spencerArgs.toArray(), spencerArgs.size(), String[].class); parsed = defaultParser.parse(Main.spencerOptions, args); if (parsed.hasOption("help")) { printHelp(); System.exit(0); } final String tracedir = parsed.getOptionValue("tracedir"); if (tracedir != null) { final File dir = new File(tracedir); if ((! dir.exists()) || (! dir.isDirectory())) { System.err.println( "ERROR: trace directory " +tracedir +" does not exist or is no directory"); System.exit(1); } } return parsed; } catch (ParseException e) { System.err.println("ERROR: "+e.getMessage()); printHelp(); System.err.println("quitting"); System.exit(1); return null; } } private static void printHelp() { final HelpFormatter helpFormatter = new HelpFormatter(); helpFormatter.printHelp( "spencer", "A JVM with memory instrumentation.", spencerOptions, "stephan.brandauer@it.uu.se", true); } private static void logIfVerbose(String txt, CommandLine spencerArgs) { if (spencerArgs.hasOption("verbose")) { System.out.println(txt); } } private static Process getProcess(final ArrayList<String> jvmArgs, CommandLine spencerArgs) throws IOException { final String sep = System.getProperty("file.separator"); final ArrayList<String> argStrings = new ArrayList<>(); //executable: argStrings.add(System.getProperty("java.home") + sep + "bin" + sep + "java"); logIfVerbose("cp is: "+System.getProperty("java.class.path"), spencerArgs); final URL resource = getAgentLib(); assert resource != null; final File tempAgentFile = Files.createTempFile("spencer-tracing-agent", ".jnilib").toFile(); assert tempAgentFile.createNewFile(); //tempAgentFile.deleteOnExit(); FileUtils.copyURLToFile(resource, tempAgentFile); logIfVerbose("agent binary: "+tempAgentFile, spencerArgs); if (!tempAgentFile.exists()) { throw new IllegalStateException("could not find agent binary: "+tempAgentFile); } final String tracedirOpt = spencerArgs.getOptionValue("tracedir"); if (spencerArgs.hasOption("notrace")) { argStrings.add("-agentpath:" + tempAgentFile.getAbsolutePath() + "=tracefile=none"); } else { final String tracedir = (tracedirOpt == null) ? "/tmp" : tracedirOpt; argStrings.add("-agentpath:" + tempAgentFile.getAbsolutePath() + "=tracefile="+tracedir+"/tracefile"); } argStrings.add("-Xverify:none"); for (String arg : jvmArgs) { argStrings.addAll(Arrays.asList(arg.split(" "))); } //argStrings.addAll(Arrays.asList(args)); ProcessBuilder processBuilder = new ProcessBuilder( argStrings); logIfVerbose("running command: "+processBuilder.command(), spencerArgs); processBuilder.redirectOutput(ProcessBuilder.Redirect.INHERIT); processBuilder.redirectError(ProcessBuilder.Redirect.INHERIT); processBuilder.redirectInput(ProcessBuilder.Redirect.INHERIT); return processBuilder.start(); } private static URL getAgentLib() throws IOException { java.io.InputStream is = Main.class.getResourceAsStream("/dependencies.properties"); java.util.Properties p = new Properties(); p.load(is); String aol = p.getProperty("nar.aol"); assert aol != null; aol = aol.replace(".", "-"); final String version="0.1.3-SNAPSHOT"; final String lib = "/nar/spencer-tracing-" + version + "-" + aol + "-jni" + "/lib/" + aol + "/jni/libspencer-tracing-" + version + ".jnilib"; URL resource = Main.class.getResource(lib); if (resource == null) { resource = Main.class.getResource(lib.replace(".jnilib", ".so")); } if (resource == null) { throw new AssertionError("could not find agent lib: "+lib); } return resource; } private static ArrayList<String> tokenizeArgs(final String[] args) { ArrayList<String> ret = new ArrayList<>(); for (String arg : args) { final String[] split = arg.split(" "); ret.addAll(Arrays.asList(split)); } return ret; } // private static void printClassPath(CommandLine spencerArgs) { // final List<URL> urLs = Arrays.asList(((URLClassLoader) Main.class.getClassLoader()).getURLs()); // logIfVerbose("class path: "+ urLs, spencerArgs); // } }
mit
DIKU-Steiner/ProGAL
src/ProGAL/proteins/beltaStructure/bnb/lowerBounds/CN_ClashLowerBound.java
575
package ProGAL.proteins.beltaStructure.bnb.lowerBounds; import ProGAL.proteins.beltaStructure.bnb.BnBNode; import ProGAL.proteins.beltaStructure.bnb.BnBSolver; import ProGAL.proteins.structure.AminoAcidChain; public class CN_ClashLowerBound implements LowerBound { private double[] contactNumbers; public CN_ClashLowerBound(double[] contactNumbers){ this.contactNumbers = contactNumbers; } @Override public double lowerBound(BnBNode n, BnBSolver solver) { AminoAcidChain chain = solver.getChain(); // TODO Auto-generated method stub return 0; } }
mit
clxy/BigFileUploadJava
src/main/java/cn/clxy/upload/ApacheHCUploader.java
3608
/** * Copyright (C) 2013 CLXY Studio. * This content is released under the (Link Goes Here) MIT License. * http://en.wikipedia.org/wiki/MIT_License */ package cn.clxy.upload; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.ByteArrayBody; import org.apache.http.entity.mime.content.ContentBody; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.PoolingClientConnectionManager; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; /** * Use http client to upload. * @author clxy */ public class ApacheHCUploader implements Uploader { private static HttpClient client = createClient(); private static final Log log = LogFactory.getLog(ApacheHCUploader.class); @Override public void upload(Part part) { String partName = part.getName(); Map<String, ContentBody> params = new HashMap<String, ContentBody>(); params.put(Config.keyFile, new ByteArrayBody(part.getContent(), partName)); post(params); log.debug(partName + " uploaded."); } @Override public void done(String fileName, long partCount) { Map<String, ContentBody> params = new HashMap<String, ContentBody>(); try { params.put(Config.keyFileName, new StringBody(fileName)); params.put(Config.keyPartCount, new StringBody(String.valueOf(partCount))); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } post(params); log.debug(fileName + " notification is done."); } private void post(Map<String, ContentBody> params) { HttpPost post = new HttpPost(Config.url); MultipartEntity entity = new MultipartEntity(); for (Entry<String, ContentBody> e : params.entrySet()) { entity.addPart(e.getKey(), e.getValue()); } post.setEntity(entity); try { HttpResponse response = client.execute(post); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { throw new RuntimeException("Upload failed."); } } catch (Exception e) { post.abort(); throw new RuntimeException(e); } finally { post.releaseConnection(); } } /** * The timeout should be adjusted by network condition. * @return */ private static HttpClient createClient() { SchemeRegistry schReg = new SchemeRegistry(); schReg.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); schReg.register(new Scheme("https", 443, SSLSocketFactory.getSocketFactory())); PoolingClientConnectionManager ccm = new PoolingClientConnectionManager(schReg); ccm.setMaxTotal(Config.maxUpload); HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, 10 * 1000); HttpConnectionParams.setSoTimeout(params, Config.timeOut); return new DefaultHttpClient(ccm, params); } }
mit
grzechu92/frogment
app/src/androidTest/java/ch/grze/frogmentexample/FragmentStateTest.java
5259
package ch.grze.frogmentexample; import android.support.test.espresso.ViewInteraction; import android.support.test.rule.ActivityTestRule; import android.support.test.runner.AndroidJUnit4; import android.test.suitebuilder.annotation.LargeTest; import android.view.View; import android.view.ViewGroup; import android.view.ViewParent; import org.hamcrest.Description; import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.action.ViewActions.click; import static android.support.test.espresso.assertion.ViewAssertions.matches; import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed; import static android.support.test.espresso.matcher.ViewMatchers.withClassName; import static android.support.test.espresso.matcher.ViewMatchers.withId; import static android.support.test.espresso.matcher.ViewMatchers.withText; import static org.hamcrest.Matchers.allOf; import static org.hamcrest.Matchers.is; @LargeTest @RunWith(AndroidJUnit4.class) public class FragmentStateTest { @Rule public ActivityTestRule<DemoActivity> mActivityTestRule = new ActivityTestRule<>(DemoActivity.class); @Test public void fragmentStateTest() { ViewInteraction appCompatButton = onView( allOf(withId(R.id.activity_state), withText("Activity state"), childAtPosition( childAtPosition( withId(android.R.id.content), 0), 6), isDisplayed())); appCompatButton.perform(click()); ViewInteraction textView = onView( allOf(withId(R.id.state), withText("State not changed"), childAtPosition( childAtPosition( withId(android.R.id.content), 0), 0), isDisplayed())); textView.check(matches(withText("State not changed"))); ViewInteraction textView2 = onView( allOf(withId(R.id.value), withText("0"), childAtPosition( childAtPosition( withId(R.id.fragment_container), 0), 0), isDisplayed())); textView2.check(matches(withText("0"))); ViewInteraction appCompatButton2 = onView( allOf(withId(R.id.increment), withText("+"), childAtPosition( childAtPosition( withClassName(is("android.widget.LinearLayout")), 1), 0), isDisplayed())); appCompatButton2.perform(click()); ViewInteraction appCompatButton3 = onView( allOf(withId(R.id.increment), withText("+"), childAtPosition( childAtPosition( withClassName(is("android.widget.LinearLayout")), 1), 0), isDisplayed())); appCompatButton3.perform(click()); ViewInteraction textView3 = onView( allOf(withId(R.id.state), withText("Counter value: 2"), childAtPosition( childAtPosition( withId(android.R.id.content), 0), 0), isDisplayed())); textView3.check(matches(withText("Counter value: 2"))); ViewInteraction textView4 = onView( allOf(withId(R.id.value), withText("2"), childAtPosition( childAtPosition( withId(R.id.fragment_container), 0), 0), isDisplayed())); textView4.check(matches(withText("2"))); } private static Matcher<View> childAtPosition( final Matcher<View> parentMatcher, final int position) { return new TypeSafeMatcher<View>() { @Override public void describeTo(Description description) { description.appendText("Child at position " + position + " in parent "); parentMatcher.describeTo(description); } @Override public boolean matchesSafely(View view) { ViewParent parent = view.getParent(); return parent instanceof ViewGroup && parentMatcher.matches(parent) && view.equals(((ViewGroup) parent).getChildAt(position)); } }; } }
mit
bing-ads-sdk/BingAds-Java-SDK
proxies/com/microsoft/bingads/v12/campaignmanagement/EditorialErrorCollection.java
4426
package com.microsoft.bingads.v12.campaignmanagement; 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 EditorialErrorCollection complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="EditorialErrorCollection"> * &lt;complexContent> * &lt;extension base="{https://bingads.microsoft.com/CampaignManagement/v12}BatchErrorCollection"> * &lt;sequence> * &lt;element name="Appealable" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/> * &lt;element name="DisapprovedText" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="Location" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="PublisherCountry" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="ReasonCode" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "EditorialErrorCollection", propOrder = { "appealable", "disapprovedText", "location", "publisherCountry", "reasonCode" }) public class EditorialErrorCollection extends BatchErrorCollection { @XmlElement(name = "Appealable", nillable = true) protected Boolean appealable; @XmlElement(name = "DisapprovedText", nillable = true) protected String disapprovedText; @XmlElement(name = "Location", nillable = true) protected String location; @XmlElement(name = "PublisherCountry", nillable = true) protected String publisherCountry; @XmlElement(name = "ReasonCode") protected Integer reasonCode; /** * Gets the value of the appealable property. * * @return * possible object is * {@link Boolean } * */ public Boolean getAppealable() { return appealable; } /** * Sets the value of the appealable property. * * @param value * allowed object is * {@link Boolean } * */ public void setAppealable(Boolean value) { this.appealable = value; } /** * Gets the value of the disapprovedText property. * * @return * possible object is * {@link String } * */ public String getDisapprovedText() { return disapprovedText; } /** * Sets the value of the disapprovedText property. * * @param value * allowed object is * {@link String } * */ public void setDisapprovedText(String value) { this.disapprovedText = value; } /** * Gets the value of the location property. * * @return * possible object is * {@link String } * */ public String getLocation() { return location; } /** * Sets the value of the location property. * * @param value * allowed object is * {@link String } * */ public void setLocation(String value) { this.location = value; } /** * Gets the value of the publisherCountry property. * * @return * possible object is * {@link String } * */ public String getPublisherCountry() { return publisherCountry; } /** * Sets the value of the publisherCountry property. * * @param value * allowed object is * {@link String } * */ public void setPublisherCountry(String value) { this.publisherCountry = value; } /** * Gets the value of the reasonCode property. * * @return * possible object is * {@link Integer } * */ public Integer getReasonCode() { return reasonCode; } /** * Sets the value of the reasonCode property. * * @param value * allowed object is * {@link Integer } * */ public void setReasonCode(Integer value) { this.reasonCode = value; } }
mit
RodrigoQuesadaDev/XGen4J
xgen4j/src/test-gen/java/com/rodrigodev/xgen4j/test/integration/bedroom/bed/bugs_infestation/BugsInfestationException.java
1200
package com.rodrigodev.xgen4j.test.integration.bedroom.bed.bugs_infestation; import com.rodrigodev.xgen4j.test.integration.bedroom.bed.BedException; import com.rodrigodev.xgen4j.test.integration.HouseException; import com.rodrigodev.xgen4j.test.integration.ErrorCode; /** * Autogenerated by XGen4J on January 1, 0001. */ public class BugsInfestationException extends BedException { public static final ExceptionType TYPE = new ExceptionType(); protected BugsInfestationException(ErrorCode errorCode, String message) { super(errorCode, message); } protected BugsInfestationException(ErrorCode errorCode, String message, Throwable cause) { super(errorCode, message, cause); } private static class ExceptionType extends HouseException.ExceptionType { @Override protected HouseException createException(ErrorCode errorCode, String message) { return new BugsInfestationException(errorCode, message); } @Override protected HouseException createException(ErrorCode errorCode, String message, Throwable cause) { return new BugsInfestationException(errorCode, message, cause); } } }
mit
P0ke55/specbot
src/main/java/net/hypixel/api/reply/KeyReply.java
1323
package net.hypixel.api.reply; import net.hypixel.api.request.RequestType; import java.util.UUID; @SuppressWarnings("unused") public class KeyReply extends AbstractReply { private Key record; public Key getRecord() { return record; } @Override public RequestType getRequestType() { return RequestType.KEY; } @Override public String toString() { return "KeyReply{" + "record=" + record + ", super=" + super.toString() + "}"; } public class Key { private UUID key; private UUID ownerUuid; private int totalQueries; private int queriesInPastMin; public UUID getKey() { return key; } public UUID getOwnerUuid() { return ownerUuid; } public int getTotalQueries() { return totalQueries; } public int getQueriesInPastMin() { return queriesInPastMin; } @Override public String toString() { return "Key{" + "key=" + key + ", ownerUuid=" + ownerUuid + ", totalQueries=" + totalQueries + ", queriesInPastMin=" + queriesInPastMin + '}'; } } }
mit
LousyLynx/Infinity-Storage
src/main/java/infinitystorage/apiimpl/solderer/SoldererRegistry.java
1599
package infinitystorage.apiimpl.solderer; import net.minecraft.item.ItemStack; import net.minecraftforge.items.IItemHandler; import infinitystorage.api.solderer.ISoldererRecipe; import infinitystorage.api.solderer.ISoldererRegistry; import infinitystorage.api.storage.CompareUtils; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.List; public class SoldererRegistry implements ISoldererRegistry { private List<ISoldererRecipe> recipes = new ArrayList<ISoldererRecipe>(); @Override public void addRecipe(@Nonnull ISoldererRecipe recipe) { recipes.add(recipe); } @Override public List<ISoldererRecipe> getRecipes() { return recipes; } @Override @Nullable public ISoldererRecipe getRecipe(@Nonnull IItemHandler rows) { for (ISoldererRecipe recipe : recipes) { boolean found = true; for (int i = 0; i < 3; ++i) { if (!CompareUtils.compareStackNoQuantity(recipe.getRow(i), rows.getStackInSlot(i)) && !CompareUtils.compareStackOreDict(recipe.getRow(i), rows.getStackInSlot(i))) { found = false; } ItemStack row = recipe.getRow(i); if(rows.getStackInSlot(i) != null && row != null){ if(rows.getStackInSlot(i).stackSize < row.stackSize){ found = false; } } } if (found) { return recipe; } } return null; } }
mit
patrickneubauer/XMLIntellEdit
xmlintelledit/intelledit/src/main/java/at/ac/tuwien/big/xmlintelledit/intelledit/oclvisit/fixinggenerators/FakeIdentityExpressions.java
1227
package at.ac.tuwien.big.xmlintelledit.intelledit.oclvisit.fixinggenerators; import java.util.Collection; import org.eclipse.ocl.expressions.OperationCallExp; import at.ac.tuwien.big.xmlintelledit.intelledit.fixer.FixAttempt; import at.ac.tuwien.big.xmlintelledit.intelledit.oclvisit.AbstractSelectiveEvaluator; import at.ac.tuwien.big.xmlintelledit.intelledit.oclvisit.ExpressionResult; import at.ac.tuwien.big.xmlintelledit.intelledit.oclvisit.FixingGenerator; public class FakeIdentityExpressions extends AbstractSelectiveEvaluator<OperationCallExp, Object> implements FixingGenerator<OperationCallExp, Object> { public FakeIdentityExpressions(String requiredName) { super(OperationCallExp.class, Object.class, true, requiredName); } public static final FakeIdentityExpressions OCLASTYPE = new FakeIdentityExpressions("oclAsType"); public static final FakeIdentityExpressions[] INSTANCES = new FakeIdentityExpressions[]{ OCLASTYPE }; @Override public boolean addFixingPossibilitiesLocal(FixAttempt singleAttemptForThis, ExpressionResult res, OperationCallExp expr, Object result, Collection<FixAttempt>[] fixAttemptsPerSub) { fixAttemptsPerSub[0].add(singleAttemptForThis); return true; } }
mit
InkApplications/android-monolog
src/main/java/monolog/handler/HandlerResult.java
626
/* * Copyright (c) 2015 Ink Applications, LLC. * Distributed under the MIT License (http://opensource.org/licenses/MIT) */ package monolog.handler; /** * Describes how a handler dealt with a record, and whether or not it was * handled, and whether the logger should continue. * * @author Maxwell Vandervelde (Max@MaxVandervelde.com) */ public enum HandlerResult { /** Handler did NOT deal with the record. */ PASSED, /** Handler sent the record into its logs and the logger should continue. */ HANDLED, /** Handler sent the record to its logs and the logger should NOT continue. */ FINISHED }
mit
universal-automata/liblevenshtein-java
src/test/java/com/github/liblevenshtein/assertion/StateAssertions.java
3217
package com.github.liblevenshtein.assertion; import org.assertj.core.api.AbstractAssert; import com.github.liblevenshtein.transducer.Position; import com.github.liblevenshtein.transducer.State; /** * AssertJ-style assertions for {@link State}. */ public class StateAssertions extends AbstractAssert<StateAssertions, State> { /** * Constructs a new {@link StateAssertions} to assert-against. * @param actual {@link State} to assert-against. */ public StateAssertions(final State actual) { super(actual, StateAssertions.class); } /** * Constructs a new {@link StateAssertions} to assert-against. * @param actual {@link State} to assert-against. * @return A new {@link StateAssertions} to assert-against. */ public static StateAssertions assertThat(final State actual) { return new StateAssertions(actual); } /** * Returns a new {@link StateIteratorAssertions} to assert against the * {@link #actual} iterator. * @return New {@link StateIteratorAssertions} to assert-against the iterator * of the {@link #actual} {@link State}. */ public StateIteratorAssertions iterator() { isNotNull(); return new StateIteratorAssertions(actual.iterator()); } /** * Adds a number of positions to the state. * @param positions {@link Position}s to add to the {@link #actual} state. * @return This {@link StateAssertions} for fluency. */ public StateAssertions add(final Position... positions) { isNotNull(); for (int i = 0; i < positions.length; i += 1) { final Position position = positions[i]; if (null == position) { failWithMessage("Position at index [%d] is null", i); } actual.add(position); } return this; } /** * Asserts that {@link #actual} has the expected head element. * @param expectedHead {@link Position} expected to be the head element. * @return This {@link StateAssertions} for fluency. * @throws AssertionError When the head element is unexpected. */ public StateAssertions hasHead(final Position expectedHead) { isNotNull(); final Position actualHead = actual.head(); if (null == expectedHead) { if (null != actualHead) { failWithMessage("Expected actual.head() to be [null], but was [%s]", actualHead); } } else if (!expectedHead.equals(actualHead)) { failWithMessage("Expected actual.head() to be [%s], but was [%s]", expectedHead, actualHead); } return this; } /** * Inserts the element into the head of the {@link #actual} state. * @param head Head element for the state. * @return This {@link StateAssertions} for fluency. */ public StateAssertions head(final Position head) { isNotNull(); actual.head(head); return this; } /** * Inserts an element after another in the state. * @param curr {@link Position} after which to insert {@link next}.. * @param next {@link Position} to insert after {@link curr}. * @return This {@link StateAssertions} for fluency. */ public StateAssertions insertAfter(final Position curr, final Position next) { isNotNull(); actual.insertAfter(curr, next); return this; } }
mit
idanarye/nisui
h2_store/src/main/java/nisui/h2_store/H2Operations.java
10081
package nisui.h2_store; import java.sql.Array; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import nisui.core.*; import nisui.core.util.IterWithSeparator; import nisui.core.util.QueryChunk; import nisui.core.util.ResultSetIterator; public abstract class H2Operations<D, R> implements AutoCloseable { private static Logger logger = LoggerFactory.getLogger(H2Operations.class); protected H2ResultsStorage<D, R>.Connection con; protected PreparedStatement stmt; public H2Operations(H2ResultsStorage<D, R>.Connection con) { this.con = con; } @Override public void close() throws SQLException { if (stmt != null) { stmt.close(); } } private static <V> Object toDbRep(ExperimentValuesHandler<V>.Field field, V experimentValue) { Object value = field.get(experimentValue); if (value != null && field.getType().isEnum()) { value = value.toString(); } return value; } private static <V> Object fromDbRep(ExperimentValuesHandler<V>.Field field, Object dbRep) { if (dbRep instanceof String) { return field.parseString((String)dbRep); } else { return dbRep; } } private static void applyQueryChunk(QueryChunk chunk, StringBuilder sql, List<Object> parameters) { chunk.scan(sql::append, (param) -> { sql.append(" ? "); parameters.add(param); }); } public static class InsertDataPoint<D, R> extends H2Operations<D, R> implements DataPointInserter<D> { InsertDataPoint(H2ResultsStorage<D, R>.Connection con) { super(con); StringBuilder sql = new StringBuilder(); sql.append("INSERT INTO ").append(con.DATA_POINTS_TABLE_NAME).append("("); sql.append("num_planned").append(", ").append("num_performed"); for (ExperimentValuesHandler<D>.Field field : con.parent().dataPointHandler.fields()) { sql.append(", ").append(field.getName()); } sql.append(") VALUES("); int numberOfFields = con.parent().dataPointHandler.fields().size(); for (int i = 0; i < 2 + numberOfFields; ++i) { if (0 < i) { sql.append(", "); } sql.append("?"); } sql.append(");"); stmt = con.createPreparedStatement(sql.toString()); } @Override public void insert(long numPlanned, long numPerformed, D dataPoint) throws SQLException { stmt.clearParameters(); stmt.setLong(1, numPlanned); stmt.setLong(2, numPerformed); int paramIndex = 3; for (ExperimentValuesHandler<D>.Field field : con.parent().dataPointHandler.fields()) { stmt.setObject(paramIndex, toDbRep(field, dataPoint)); ++paramIndex; } stmt.executeUpdate(); } } public static class ReadDataPoints<D, R> extends H2Operations<D, R> implements DataPointsReader<D> { String[] filters; ReadDataPoints(H2ResultsStorage<D, R>.Connection con, String... filters) { super(con); this.filters = filters; } @Override public Iterator<DataPoint<D>> iterator() { LinkedList<Object> parameters = new LinkedList<>(); if (stmt == null) { StringBuilder sql = new StringBuilder(); sql.append("SELECT id, num_planned, num_performed"); for (ExperimentValuesHandler<D>.Field field : con.parent().dataPointHandler.fields()) { sql.append(", ").append(field.getName()); } sql.append(" FROM ").append(con.DATA_POINTS_TABLE_NAME); if (0 < filters.length) { H2QueryParser queryParser = new H2QueryParser(); for (int i = 0; i < filters.length; ++i) { if (0 == i) { sql.append(" WHERE "); } else { sql.append(" AND "); } sql.append("("); applyQueryChunk(queryParser.parseBoolean(filters[i]), sql, parameters); sql.append(")"); } } sql.append(';'); stmt = con.createPreparedStatement(sql.toString()); } try { { int i = 1; for (Object parameter : parameters) { stmt.setObject(i, parameter); i += 1; } } return new ResultSetIterator<>(stmt.executeQuery(), rs -> { D value = con.parent().dataPointHandler.createValue(); int i = 4; for (ExperimentValuesHandler<D>.Field field : con.parent().dataPointHandler.fields()) { field.set(value, fromDbRep(field, rs.getObject(i))); ++i; } return new H2DataPoint<>(rs.getLong(1), rs.getLong(2), rs.getLong(3), value); }); } catch (SQLException e) { throw new RuntimeException(e); } } } public static class InsertExperimentResult<D, R> extends H2Operations<D, R> implements ExperimentResultInserter<R> { private PreparedStatement updateDpStatement; @Override public void close() throws SQLException { try { if (updateDpStatement != null) { updateDpStatement.close(); } } finally { super.close(); } } InsertExperimentResult(H2ResultsStorage<D, R>.Connection con) { super(con); StringBuilder sql = new StringBuilder(); sql.append("INSERT INTO ").append(con.EXPERIMENT_RESULTS_TABLE_NAME).append("("); sql.append("data_point_id").append(", ").append("seed"); for (ExperimentValuesHandler<R>.Field field : con.parent().experimentResultHandler.fields()) { sql.append(", ").append(field.getName()); } sql.append(") VALUES("); int numberOfFields = con.parent().experimentResultHandler.fields().size(); for (int i = 0; i < 2 + numberOfFields; ++i) { if (0 < i) { sql.append(", "); } sql.append("?"); } sql.append(");"); stmt = con.createPreparedStatement(sql.toString()); updateDpStatement = con.createPreparedStatement(String.format("UPDATE %s SET num_performed = num_performed + 1 WHERE id = ?;", con.DATA_POINTS_TABLE_NAME)); } @Override public void insert(DataPoint<?> dataPoint, long seed, R experimentResult) throws SQLException { stmt.clearParameters(); stmt.setLong(1, ((H2DataPoint<?>)dataPoint).getId()); stmt.setLong(2, seed); int paramIndex = 3; for (ExperimentValuesHandler<R>.Field field : con.parent().experimentResultHandler.fields()) { stmt.setObject(paramIndex, toDbRep(field, experimentResult)); ++paramIndex; } updateDpStatement.setLong(1, ((H2DataPoint<?>)dataPoint).getId()); stmt.executeUpdate(); updateDpStatement.executeUpdate(); } } public static class ReadExperimentResults<D, R> extends H2Operations<D, R> implements ExperimentResultsReader<D, R> { private HashMap<Long, H2DataPoint<D>> dataPoints; ReadExperimentResults(H2ResultsStorage<D, R>.Connection con, Iterable<DataPoint<D>> dataPoints) { super(con); this.dataPoints = new HashMap<>(); for (DataPoint<D> dp : dataPoints) { H2DataPoint<D> h2dp = (H2DataPoint<D>)dp; this.dataPoints.put(h2dp.getId(), h2dp); } } @Override public Iterator<ExperimentResult<D, R>> iterator() { if (stmt == null) { StringBuilder sql = new StringBuilder(); sql.append("SELECT id"); sql.append(", ").append("data_point_id"); sql.append(", ").append("seed"); for (ExperimentValuesHandler<R>.Field field : con.parent().experimentResultHandler.fields()) { sql.append(", ").append(field.getName()); } sql.append(" FROM ").append(con.EXPERIMENT_RESULTS_TABLE_NAME); sql.append(" WHERE data_point_id IN (SELECT * FROM TABLE(id BIGINT = ?))"); sql.append(';'); stmt = con.createPreparedStatement(sql.toString()); } try { Array array = stmt.getConnection().createArrayOf("BIGINT", dataPoints.keySet().toArray()); stmt.setArray(1, array); return new ResultSetIterator<>(stmt.executeQuery(), rs -> { R value = con.parent().experimentResultHandler.createValue(); int i = 4; for (ExperimentValuesHandler<R>.Field field : con.parent().experimentResultHandler.fields()) { field.set(value, fromDbRep(field, rs.getObject(i))); ++i; } return new H2ExperimentResult<>(rs.getLong(1), dataPoints.get(rs.getLong(2)), rs.getLong(3), value); }); } catch (SQLException e) { throw new RuntimeException(e); } } } }
mit
juliocnsouzadev/ocpjp
src/oldcodes/collections/ListIteratorTest.java
2030
package oldcodes.collections; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; /** * ListIteratorTest.java -> Testes com ListIterator: * <p> * @since 14/04/2014 * @version 1.0 * @author Julio Cesar Nunes de Souza (julio.souza@mobilitasistemas.com.br) */ public class ListIteratorTest { public static void simpleTest() { List<String> lista = new LinkedList<>( Arrays.asList( "PARA FRENTE" , "PARA TRÁS" ) ); //iterface List prove metodo listIterator ListIterator<String> listIterator = lista.listIterator(); // ListIterator extends Iterator int counter = 0; while ( listIterator.hasNext() ) { boolean temAnterior = listIterator.hasPrevious(); String next = null; String anterior = null; if ( counter > 15 ) { System.out.println( "\nCansei..." ); break; } System.out.println( "\n1 para frente" ); for ( int i = 0 ; i < 1 ; i++ ) { if ( listIterator.hasNext() ) {//verifica se tem um proximo next = listIterator.next();//chama proximo item System.out.println( next ); listIterator.set( "to the front (" + counter + ")" );//troca o valor do chamado no caso next } } System.out.println( "\n1 para trás" ); for ( int i = 0 ; i < 1 ; i++ ) { if ( listIterator.hasPrevious() ) {//verifica se tem um anterior anterior = listIterator.previous();// chama item anterios System.out.println( anterior ); listIterator.set( "from behind (" + counter + ")" ); //troca valor do chamado no caso previous } } counter++; } } public static void main( String[] args ) { simpleTest(); } }
mit
nzufelt/java_sample
project_euler_problems/OneTwentySix.java
5243
import java.lang.ArrayIndexOutOfBoundsException; import java.lang.NumberFormatException; /** Prompt: The minimum number of cubes to cover every visible face on a cuboid measuring 3 x 2 x 1 is twenty-two. If we then add a second layer to this solid it would require forty-six cubes to cover every visible face, the third layer would require seventy-eight cubes, and the fourth layer would require one-hundred and eighteen cubes to cover every visible face. However, the first layer on a cuboid measuring 5 x 1 x 1 also requires twenty-two cubes; similarly the first layer on cuboids measuring 5 x 3 x 1, 7 x 2 x 1, and 11 x 1 x 1 all contain forty-six cubes. We shall define C(n) to represent the number of cuboids that contain n cubes in one of its layers. So C(22) = 2, C(46) = 4, C(78) = 5, and C(118) = 8. It turns out that 154 is the least value of n for which C(n) = 10. Find the least value of n for which C(n) = 1000. */ public class OneTwentySix { private static int[] cubeCount; private static int limit; private static final int TARGET = 1000; /** This class implements Nicholas Zufelt's solution to Project Euler problem 126. It takes one command-line argument, namely the limit to attempt to find the solution. If the input is too low, it will give an error. Otherwise, it prints the solution to standard out. */ public static void main(String[] args) { try { limit = Integer.parseInt(args[0]); } catch (NumberFormatException exception) { System.err.println("Argument" + args[0] + " must be an integer."); System.exit(1); } long timeStart = System.currentTimeMillis(); cubeCount = new int[limit + 1]; /* Each outer loop is terminated by one way a cuboid could be too big in its first layer. They are arranged to avoid overcounting. */ for (int len = 1; countLayer(len, len, len, 1) <= limit; len++) { // Cuboid is a cube (length == width == height) for (int wid = len; countLayer(len, wid, len, 1) <= limit; wid++) { // Cuboid is a square rectangular prism (length == height) for (int hei = wid; countLayer(len, wid, hei, 1) <= limit; hei++) { // Cuboid is a generic rectangular prism for (int layer = 1; countLayer(len, wid, hei, layer) <= limit; layer++) { try { cubeCount[countLayer(len, wid, hei, layer)]++; } catch (ArrayIndexOutOfBoundsException exception) { System.out.println("An error occured, probably the" + " limit was too large."); System.out.println(exception); System.exit(1); } } } } } long time = System.currentTimeMillis() - timeStart; int smallestInd = smallest(); if (smallestInd == -1) { System.out.println("The limit was set too low. Try again with" + " a larger limit."); } else { System.out.println( String.format("The smallest n with C(n) = %d is %d. ", TARGET,smallestInd)); System.out.println("Solution took " + time + " milliseconds"); } } private static int smallest() { for (int i = 0; i < limit; i++) { if (cubeCount[i] == TARGET) { return i; } } return -1; } /* Like most project euler problems, there is a significantly faster way to compute the number of of cubes in layer `n` of a cuboid with dimensions `l x w x h`. In fact, it is not even recurrent (i.e. it doesn't require storage of previous layer size/information). See implementation for more explanation. */ private static int countLayer(int length, int width, int height, int layerInd) { /* This counts the cubes that eminate straight out from a cuboid's face. We call these "face cubes" below */ int layer = 2 * (length * width + width * height + length * height ); /* This counts the cubes that border a face cube. We call these "border cubes" below */ layer += 4 * (layerInd - 1) * (length + width + height); /* This counts the cubes that border a previous layer's border cubes, but are not themselves face or border cubes. One could call them "corner cubes", as they fill in the corners of each layer. A careful picture demonstrates that there are 8 sets of corner cubes, and each set is the (n-2)^nd triangle number. */ if (layerInd > 2) { layer += 4 * (layerInd - 1) * (layerInd - 2); } return layer; } }
mit
Azure/azure-sdk-for-java
sdk/batch/azure-resourcemanager-batch/src/samples/java/com/azure/resourcemanager/batch/LocationGetQuotasSamples.java
632
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.batch; import com.azure.core.util.Context; /** Samples for Location GetQuotas. */ public final class LocationGetQuotasSamples { /** * Sample code: LocationGetQuotas. * * @param batchManager Entry point to BatchManager. */ public static void locationGetQuotas(com.azure.resourcemanager.batch.BatchManager batchManager) { batchManager.locations().getQuotasWithResponse("japaneast", Context.NONE); } }
mit
backpaper0/sandbox
karate-demo/src/main/java/com/example/karatedemo/Color.java
567
package com.example.karatedemo; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class Color implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String name; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
mit
facebook/fresco
imagepipeline/src/main/java/com/facebook/imagepipeline/listener/RequestLoggingListener.java
7252
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.imagepipeline.listener; import android.os.SystemClock; import android.util.Pair; import com.facebook.common.logging.FLog; import com.facebook.imagepipeline.request.ImageRequest; import com.facebook.infer.annotation.Nullsafe; import java.util.HashMap; import java.util.Map; import javax.annotation.Nullable; import javax.annotation.concurrent.GuardedBy; /** Logging for {@link ImageRequest}s. */ @Nullsafe(Nullsafe.Mode.STRICT) public class RequestLoggingListener implements RequestListener { private static final String TAG = "RequestLoggingListener"; @GuardedBy("this") private final Map<Pair<String, String>, Long> mProducerStartTimeMap; @GuardedBy("this") private final Map<String, Long> mRequestStartTimeMap; public RequestLoggingListener() { mProducerStartTimeMap = new HashMap<>(); mRequestStartTimeMap = new HashMap<>(); } @Override public synchronized void onRequestStart( ImageRequest request, Object callerContextObject, String requestId, boolean isPrefetch) { if (FLog.isLoggable(FLog.VERBOSE)) { FLog.v( TAG, "time %d: onRequestSubmit: {requestId: %s, callerContext: %s, isPrefetch: %b}", getTime(), requestId, callerContextObject, isPrefetch); mRequestStartTimeMap.put(requestId, getTime()); } } @Override public synchronized void onProducerStart(String requestId, String producerName) { if (FLog.isLoggable(FLog.VERBOSE)) { Pair<String, String> mapKey = Pair.create(requestId, producerName); long startTime = getTime(); mProducerStartTimeMap.put(mapKey, startTime); FLog.v( TAG, "time %d: onProducerStart: {requestId: %s, producer: %s}", startTime, requestId, producerName); } } @Override public synchronized void onProducerFinishWithSuccess( String requestId, String producerName, @Nullable Map<String, String> extraMap) { if (FLog.isLoggable(FLog.VERBOSE)) { Pair<String, String> mapKey = Pair.create(requestId, producerName); Long startTime = mProducerStartTimeMap.remove(mapKey); long currentTime = getTime(); FLog.v( TAG, "time %d: onProducerFinishWithSuccess: " + "{requestId: %s, producer: %s, elapsedTime: %d ms, extraMap: %s}", currentTime, requestId, producerName, getElapsedTime(startTime, currentTime), extraMap); } } @Override public synchronized void onProducerFinishWithFailure( String requestId, String producerName, Throwable throwable, @Nullable Map<String, String> extraMap) { if (FLog.isLoggable(FLog.WARN)) { Pair<String, String> mapKey = Pair.create(requestId, producerName); Long startTime = mProducerStartTimeMap.remove(mapKey); long currentTime = getTime(); FLog.w( TAG, throwable, "time %d: onProducerFinishWithFailure: " + "{requestId: %s, stage: %s, elapsedTime: %d ms, extraMap: %s, throwable: %s}", currentTime, requestId, producerName, getElapsedTime(startTime, currentTime), extraMap, throwable.toString()); } } @Override public synchronized void onProducerFinishWithCancellation( String requestId, String producerName, @Nullable Map<String, String> extraMap) { if (FLog.isLoggable(FLog.VERBOSE)) { Pair<String, String> mapKey = Pair.create(requestId, producerName); Long startTime = mProducerStartTimeMap.remove(mapKey); long currentTime = getTime(); FLog.v( TAG, "time %d: onProducerFinishWithCancellation: " + "{requestId: %s, stage: %s, elapsedTime: %d ms, extraMap: %s}", currentTime, requestId, producerName, getElapsedTime(startTime, currentTime), extraMap); } } @Override public synchronized void onProducerEvent( String requestId, String producerName, String producerEventName) { if (FLog.isLoggable(FLog.VERBOSE)) { Pair<String, String> mapKey = Pair.create(requestId, producerName); Long startTime = mProducerStartTimeMap.get(mapKey); long currentTime = getTime(); FLog.v( TAG, "time %d: onProducerEvent: {requestId: %s, stage: %s, eventName: %s; elapsedTime: %d ms}", getTime(), requestId, producerName, producerEventName, getElapsedTime(startTime, currentTime)); } } @Override public synchronized void onUltimateProducerReached( String requestId, String producerName, boolean successful) { if (FLog.isLoggable(FLog.VERBOSE)) { Pair<String, String> mapKey = Pair.create(requestId, producerName); Long startTime = mProducerStartTimeMap.remove(mapKey); long currentTime = getTime(); FLog.v( TAG, "time %d: onUltimateProducerReached: " + "{requestId: %s, producer: %s, elapsedTime: %d ms, success: %b}", currentTime, requestId, producerName, getElapsedTime(startTime, currentTime), successful); } } @Override public synchronized void onRequestSuccess( ImageRequest request, String requestId, boolean isPrefetch) { if (FLog.isLoggable(FLog.VERBOSE)) { Long startTime = mRequestStartTimeMap.remove(requestId); long currentTime = getTime(); FLog.v( TAG, "time %d: onRequestSuccess: {requestId: %s, elapsedTime: %d ms}", currentTime, requestId, getElapsedTime(startTime, currentTime)); } } @Override public synchronized void onRequestFailure( ImageRequest request, String requestId, Throwable throwable, boolean isPrefetch) { if (FLog.isLoggable(FLog.WARN)) { Long startTime = mRequestStartTimeMap.remove(requestId); long currentTime = getTime(); FLog.w( TAG, "time %d: onRequestFailure: {requestId: %s, elapsedTime: %d ms, throwable: %s}", currentTime, requestId, getElapsedTime(startTime, currentTime), throwable.toString()); } } @Override public synchronized void onRequestCancellation(String requestId) { if (FLog.isLoggable(FLog.VERBOSE)) { Long startTime = mRequestStartTimeMap.remove(requestId); long currentTime = getTime(); FLog.v( TAG, "time %d: onRequestCancellation: {requestId: %s, elapsedTime: %d ms}", currentTime, requestId, getElapsedTime(startTime, currentTime)); } } @Override public boolean requiresExtraMap(String id) { return FLog.isLoggable(FLog.VERBOSE); } private static long getElapsedTime(@Nullable Long startTime, long endTime) { if (startTime != null) { return endTime - startTime; } return -1; } private static long getTime() { return SystemClock.uptimeMillis(); } }
mit
AceCode123/ArenaPvP
CompleteArenaPvP/src/me/Anthony/ArenaManager.java
16666
package me.Anthony; import me.Anthony.me.Anthony.SubCommands.BuildUHC; import org.bukkit.*; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.bukkit.scoreboard.*; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; /** * Created by thresher1436 on 1/24/2016. */ public class ArenaManager { public static ArenaManager am; private Map<UUID, ItemStack[]> contents = new HashMap<UUID, ItemStack[]>(); private Map<UUID, ItemStack[]> armorContents = new HashMap<UUID, ItemStack[]>(); private Map<UUID, Location> location = new HashMap<UUID, Location>(); public static List<UUID> waiting = new ArrayList<UUID>(); private ArrayList<Arena> arenas = new ArrayList<Arena>(); private int arenaIds = 0; public static ArenaManager getManager() { if(am == null) am = new ArenaManager(); return am; } public Arena getArena(int id) { for(Arena a : arenas) { if(a.getId() == id) { return a; } } return null; } public boolean isArena(int id) { for(Arena a : arenas) { if(a.getId() == id) { return true; } } return false; } public Arena getArenaPlayer(Player p) { for(Arena a : arenas) { if(a.getPlayers().contains(p)) { return a; } } return null; } public void createArena(Location l, Location l2, String type) { arenaIds++; Arena a = new Arena(arenaIds, l, l2, type, true); arenas.add(a); System.out.println(ChatColor.RED + "[" + ChatColor.BLUE + "M" + ChatColor.RED + "L" + ChatColor.BLUE + "M" + ChatColor.RED + "]" + "Successfully created Arena with Id: " + arenaIds + "."); } public void deleteArena(int id) { for(Arena a : arenas) { if(a.getId() == id) { if(a.isStarted() == false) { arenas.remove(a); } else { return; } } } } public boolean isInGame(Player p) { for(Arena a : arenas) { if(a.getPlayers().contains(p)) return true; } return false; } public boolean isSpectating(Player p) { for(Arena a : arenas) { if(a.getSpectaters().contains(p)) return true; } return false; } public void addPlayer(int id, Player p) { for(Arena a : arenas) { if(a.getId() == id) { if(a.isStarted()) { p.sendMessage(ChatColor.RED + "[" + ChatColor.BLUE + "M" + ChatColor.RED + "L" + ChatColor.BLUE + "M" + ChatColor.RED + "]" + ChatColor.YELLOW + "Sorry this Arena is already in progress!"); return; } if(isInGame(p)) { p.sendMessage(ChatColor.RED + "[" + ChatColor.BLUE + "M" + ChatColor.RED + "L" + ChatColor.BLUE + "M" + ChatColor.RED + "]" + ChatColor.RED + "You are already in a game!"); return; } if(isSpectating(p)) { p.sendMessage(ChatColor.RED + "[" + ChatColor.BLUE + "M" + ChatColor.RED + "L" + ChatColor.BLUE + "M" + ChatColor.RED + "]" + ChatColor.RED + "Please leave Spectater mode to join!"); return; } contents.put(p.getUniqueId(), p.getInventory().getContents()); armorContents.put(p.getUniqueId(),p.getInventory().getArmorContents()); location.put(p.getUniqueId(),p.getLocation()); p.getInventory().clear(); p.getInventory().setArmorContents(null); p.setHealth(20); waiting.add(p.getUniqueId()); a.getPlayers().add(p); startJoin(a.getId()); if(a.getPlayers().size() == 1) { p.teleport(a.getFighter1()); } else { p.teleport(a.getFighter2()); } if(a.getType().equalsIgnoreCase("SG")) { Kits.giveSG(p); } if(a.getType().equalsIgnoreCase("Iron")) { Kits.giveIron(p); } if(a.getType().equalsIgnoreCase("Gold")) { Kits.giveGold(p); } if(a.getType().equalsIgnoreCase("Diamond")) { Kits.giveDiamond(p); } if(a.getType().equalsIgnoreCase("Archer")) { Kits.giveArcher(p); } if(a.getType().equalsIgnoreCase("Combo")) { Kits.giveCombo(p); } if(a.getType().equalsIgnoreCase("NoDebuff")) { Kits.giveNoDebuff(p); } if(a.getType().equalsIgnoreCase("OG")) { Kits.giveOG(p); } if(a.getType().equalsIgnoreCase("Fisticuffs")) { Kits.giveFisticuffs(p); } if(a.getType().equalsIgnoreCase("Viking")) { Kits.giveViking(p); } if(a.getType().equalsIgnoreCase("UHC")) { Kits.giveUHC(p); } if(a.getType().equalsIgnoreCase("AdvancedUHC")) { Kits.giveAdvancedUHC(p); } if(a.getType().equalsIgnoreCase("Tank")) { Kits.giveTank(p); } if(a.getType().equalsIgnoreCase("Gapple")) { Kits.giveGapple(p); } if(a.getType().equalsIgnoreCase("AbilityPvP")) { Kits.giveAbility(p); } if(a.getType().equalsIgnoreCase("Strafe")) { Kits.giveStrafe(p); } if(a.getType().equalsIgnoreCase("Soup")) { Kits.giveSoup(p); } if(a.getType().equalsIgnoreCase("BuildUHC")) { BuildUHC.giveBuildUHC(p); p.setGameMode(GameMode.SURVIVAL); } } } } public void addSpectator(Player p, Player toSpectate) { if(isInGame(p) == false) { for (Arena a : arenas) { if (a.getPlayers().contains(toSpectate)) { if (a.isStarted()) { contents.put(p.getUniqueId(), p.getInventory().getContents()); armorContents.put(p.getUniqueId(), p.getInventory().getArmorContents()); location.put(p.getUniqueId(), p.getLocation()); p.getInventory().clear(); p.getInventory().setArmorContents(null); p.teleport(a.getFighter1()); p.setGameMode(GameMode.CREATIVE); p.addPotionEffect(new PotionEffect(PotionEffectType.INVISIBILITY, 1800000, 2)); p.setCanPickupItems(false); a.getSpectaters().add(p); } } } } } public void leaveSpectator(Player p) { for(Arena a : arenas) { if(a.getSpectaters().contains(p)) { a.getSpectaters().remove(p); p.setGameMode(GameMode.ADVENTURE); p.setCanPickupItems(true); p.removePotionEffect(PotionEffectType.INVISIBILITY); p.getInventory().setContents(contents.get(p.getUniqueId())); p.getInventory().setArmorContents(armorContents.get(p.getUniqueId())); p.teleport(location.get(p.getUniqueId())); p.getInventory().clear(); ItemStack vs = new ItemStack(Material.NAME_TAG); ItemMeta vsmeta = vs.getItemMeta(); vsmeta.setDisplayName(ChatColor.BLUE + "1v1 Queue " + ChatColor.GRAY + "(Right Click)"); vs.setItemMeta(vsmeta); ItemStack shop = new ItemStack(Material.ENDER_CHEST); ItemMeta smeta = shop.getItemMeta(); smeta.setDisplayName(ChatColor.YELLOW + "Store " + ChatColor.GRAY + "(Right Click)"); shop.setItemMeta(smeta); ItemStack matchesLeft = new ItemStack(Material.GOLD_INGOT); ItemMeta matchesLeftMeta = matchesLeft.getItemMeta(); matchesLeftMeta.setDisplayName(ChatColor.YELLOW + "Matches Left" + ChatColor.GRAY + " (Right Click)"); p.getInventory().setItem(3, vs); p.getInventory().setItem(4, shop); p.getInventory().setItem(8, matchesLeft); p.setGameMode(GameMode.ADVENTURE); } else { p.sendMessage(ChatColor.RED + "[" + ChatColor.BLUE + "M" + ChatColor.RED + "L" + ChatColor.BLUE + "M" + ChatColor.RED + "]" + "You are not spectating an Arena!"); } } } public void removePlayer(Player p) { p.getInventory().clear(); p.getInventory().setArmorContents(null); p.setFireTicks(0); p.setMaxHealth(20); p.setHealth(20); p.getInventory().setContents(contents.get(p.getUniqueId())); p.getInventory().setArmorContents(armorContents.get(p.getUniqueId())); p.teleport(location.get(p.getUniqueId())); p.getInventory().clear(); ItemStack vs = new ItemStack(Material.NAME_TAG); ItemMeta vsmeta = vs.getItemMeta(); vsmeta.setDisplayName(ChatColor.BLUE + "1v1 Queue " + ChatColor.GRAY + "(Right Click)"); vs.setItemMeta(vsmeta); ItemStack shop = new ItemStack(Material.ENDER_CHEST); ItemMeta smeta = shop.getItemMeta(); smeta.setDisplayName(ChatColor.YELLOW + "Shop " + ChatColor.GRAY + "(Right Click)"); shop.setItemMeta(smeta); ItemStack matchesLeft = new ItemStack(Material.GOLD_INGOT); ItemMeta matchesLeftMeta = matchesLeft.getItemMeta(); matchesLeftMeta.setDisplayName(ChatColor.YELLOW + "Matches Left" + ChatColor.GRAY + " (Right Click)"); p.getInventory().setItem(3, vs); p.getInventory().setItem(4, shop); p.getInventory().setItem(8, matchesLeft); p.setGameMode(GameMode.ADVENTURE); for(Arena a : arenas) { a.getPlayers().remove(p); } if (waiting.contains(p.getUniqueId())) { waiting.remove(p.getUniqueId()); } if(Kits.uhc.contains(p.getUniqueId())) { Kits.uhc.remove(p.getUniqueId()); } } public void stop(Player p) { for(Arena a : arenas) { if(a.getPlayers().contains(p)) { if(a.isStarted()) { a.stop(); removePlayer(p); for(Player specs : a.getSpectaters()) { leaveSpectator(specs); } } } } } public void joinQueue(Player p, String type) { for(Arena a : arenas) { if(a.getType().equalsIgnoreCase(type)) { if (a.isStarted() == false) { addPlayer(a.getId(), p); p.sendMessage(ChatColor.RED + "[" + ChatColor.BLUE + "M" + ChatColor.RED + "L" + ChatColor.BLUE + "M" + ChatColor.RED + "]" + ChatColor.YELLOW + "Sending you to Arena " + a.getId() + " in type " + a.getType() + "."); } else { p.sendMessage(ChatColor.RED + "[" + ChatColor.BLUE + "M" + ChatColor.RED + "L" + ChatColor.BLUE + "M" + ChatColor.RED + "]" + ChatColor.YELLOW + "No Arenas for this type are available at this time! Please try another type or again in a few minutes."); } } } } public void setScoreboard(Player p) { ScoreboardManager manager = Bukkit.getScoreboardManager(); Scoreboard board = manager.getNewScoreboard(); Objective obj = board.registerNewObjective("test", "dummy"); obj.setDisplaySlot(DisplaySlot.SIDEBAR); obj.setDisplayName(ChatColor.BOLD + "" + ChatColor.RED + "[" + ChatColor.BOLD + "" + ChatColor.BLUE + "M" + ChatColor.BOLD + "" + ChatColor.RED + "L" + ChatColor.BOLD + "" + ChatColor.BLUE + "M" + ChatColor.BOLD + "" + ChatColor.RED + "]"); Date date = new Date(); DateFormat format = new SimpleDateFormat("dd,mm,yy"); format.format(date); Score score = obj.getScore(ChatColor.YELLOW + date.toString()); score.setScore(9); if(p.hasPermission("Arena.Major")) { Score score2 = obj.getScore(ChatColor.BOLD + "" + ChatColor.BLUE + "RANK: " + ChatColor.GREEN + "Famous"); score2.setScore(8); } else { Score score2 = obj.getScore(ChatColor.BOLD + "" + ChatColor.BLUE + "RANK: " + ChatColor.GRAY + "Default"); score2.setScore(8); } Score score3 = obj.getScore(ChatColor.BOLD + "" + ChatColor.GREEN + "ELO: " + Main.config.getInt(p.getUniqueId() + ".elo")); score3.setScore(7); Score score4 = obj.getScore(ChatColor.BOLD + "" + ChatColor.GREEN + "KILLS: " + Main.config.getInt(p.getUniqueId() + ".kills")); score4.setScore(6); Score score5 = obj.getScore(ChatColor.BOLD + "" + ChatColor.GREEN + "DEATHS: " + Main.config.getInt(p.getUniqueId() + ".deaths")); score5.setScore(5); Score score6 = obj.getScore(ChatColor.BOLD + "" + ChatColor.GREEN + "WINS: " + Main.config.getInt(p.getUniqueId() + ".wins")); score6.setScore(4); Score score7 = obj.getScore(ChatColor.BOLD + "" + ChatColor.GREEN + "LOSSES: " + Main.config.getInt(p.getUniqueId() + ".losses")); score7.setScore(3); Score score8 = obj.getScore(ChatColor.BOLD + "" + ChatColor.YELLOW + ""); score8.setScore(2); Score score9 = obj.getScore(ChatColor.BOLD + "" + ChatColor.YELLOW + "MLMShop.buycraft.net"); score9.setScore(1); p.setScoreboard(board); } public void removeScoreboard(Player p) { p.setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard()); } public void startJoin(int id) { for(Arena a : arenas) { if(a.getId() == id) { if(a.getPlayers().size() == 2) { for(Player p : a.getPlayers()) { waiting.remove(p.getUniqueId()); p.sendMessage(ChatColor.RED + "[" + ChatColor.BLUE + "M" + ChatColor.RED + "L" + ChatColor.BLUE + "M" + ChatColor.RED + "]" + ChatColor.YELLOW + "Your Game Has Started! FIGHT!"); a.start(); } } else { if(a.getPlayers().size() == 1) { for(Player p : a.getPlayers()) { p.sendMessage(ChatColor.RED + "[" + ChatColor.BLUE + "M" + ChatColor.RED + "L" + ChatColor.BLUE + "M" + ChatColor.RED + "]" + ChatColor.YELLOW + "One more player needs to join for your game to start!"); } } } } } } public void Duel(Player p, Player p2, String type) { for(Arena a : arenas) { if(a.getType() == type) { if(a.isStarted() == false) { if (a.getPlayers().size() == 0) { addPlayer(a.getId(), p); addPlayer(a.getId(), p2); } else { p.sendMessage(ChatColor.RED + "[" + ChatColor.BLUE + "M" + ChatColor.RED + "L" + ChatColor.BLUE + "M" + ChatColor.RED + "]" + ChatColor.RED + "No arenas are currently open! Please try again in a few minutes!"); } } } } } }
mit
CS2103JAN2017-W09-B3/main
src/main/java/seedu/task/logic/parser/ParserUtil.java
6958
package seedu.task.logic.parser; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import seedu.task.commons.exceptions.IllegalValueException; import seedu.task.commons.util.NattyDateUtil; import seedu.task.commons.util.StringUtil; import seedu.task.model.tag.Tag; import seedu.task.model.tag.UniqueTagList; import seedu.task.model.task.CompletionStatus; import seedu.task.model.task.EndTime; import seedu.task.model.task.Name; import seedu.task.model.task.StartTime; //@@author A0146789H /** * Contains utility methods used for parsing strings in the various *Parser classes */ public class ParserUtil { private static final Pattern INDEX_ARGS_FORMAT = Pattern.compile("(?<targetIndex>.+)"); /** * Returns the specified index in the {@code command} if it is a positive unsigned integer * Returns an {@code Optional.empty()} otherwise. */ public static Optional<Integer> parseIndex(String command) { final Matcher matcher = INDEX_ARGS_FORMAT.matcher(command.trim()); if (!matcher.matches()) { return Optional.empty(); } String index = matcher.group("targetIndex"); if (!StringUtil.isUnsignedInteger(index)) { return Optional.empty(); } return Optional.of(Integer.parseInt(index)); } /** * Returns a new Set populated by all elements in the given list of strings * Returns an empty set if the given {@code Optional} is empty, * or if the list contained in the {@code Optional} is empty */ public static Set<String> toSet(Optional<List<String>> list) { List<String> elements = list.orElse(Collections.emptyList()); return new HashSet<>(elements); } /** * Splits a preamble string into ordered fields. * @return A list of size {@code numFields} where the ith element is the ith field value if specified in * the input, {@code Optional.empty()} otherwise. */ public static List<Optional<String>> splitPreamble(String preamble, int numFields) { return Arrays.stream(Arrays.copyOf(preamble.split("\\s+", numFields), numFields)) .map(Optional::ofNullable) .collect(Collectors.toList()); } /** * Parses a {@code Optional<String> name} into an {@code Optional<Name>} if {@code name} is present. */ public static Optional<Name> parseName(Optional<String> name) throws IllegalValueException { assert name != null; return name.isPresent() ? Optional.of(new Name(name.get())) : Optional.empty(); } /** * Parses a {@code String name} into a {@code Optional<Name>} if {@code name} is present. * * @param name * @return * @throws IllegalValueException */ public static Optional<Name> parseName(String name) throws IllegalValueException { assert name != null; String tempName = name.equals("") ? null : name; return parseName(Optional.ofNullable(tempName)); } /** * Parses a {@code Optional<String> completionStatus} into an * {@code Optional<CompletionStatus>} if {@code completionStatus} is present. */ public static Optional<CompletionStatus> parseCompletionStatus(Optional<String> completionStatus) throws IllegalValueException { assert completionStatus != null; return completionStatus.isPresent() ? Optional.of(new CompletionStatus(Boolean.valueOf(completionStatus.get()))) : Optional.empty(); } /** * Parses a {@code Optional<String> startDate} into an {@code Optional<StartTime>} if {@code startDate} is present. */ public static Optional<StartTime> parseStartTime(Optional<Date> startDate) throws IllegalValueException { assert startDate != null; return startDate.isPresent() ? Optional.of(new StartTime(startDate.get())) : Optional.empty(); } /** * Parses a {@code String startDate} into an {@code Optional<StartTime>} if {@code startDate} is present. */ public static Optional<StartTime> parseStartTime(String startDate) throws IllegalValueException { String processedDate = Optional.ofNullable(startDate).orElse(""); Date parsedDate = NattyDateUtil.parseSingleDate(processedDate); return parseStartTime(Optional.ofNullable(parsedDate)); } /** * Parses a {@code Optional<String> endDate} into an {@code Optional<EndTime>} if {@code endDate} is present. */ public static Optional<EndTime> parseEndTime(Optional<Date> endDate) throws IllegalValueException { assert endDate != null; return endDate.isPresent() ? Optional.of(new EndTime(endDate.get())) : Optional.empty(); } /** * Parses a {@code String endDate} into an {@code Optional<EndTime>} if {@code endDate} is present. */ public static Optional<EndTime> parseEndTime(String endDate) throws IllegalValueException { String processedDate = Optional.ofNullable(endDate).orElse(""); Date parsedDate = NattyDateUtil.parseSingleDate(processedDate); return parseEndTime(Optional.ofNullable(parsedDate)); } /** * Parses {@code Collection<String> tags} into an {@code UniqueTagList}. */ public static UniqueTagList parseTags(Collection<String> tags) throws IllegalValueException { assert tags != null; final Set<Tag> tagSet = new HashSet<>(); for (String tagName : tags) { tagSet.add(new Tag(tagName)); } return new UniqueTagList(tagSet); } /** * Parses {@code Collection<String> tags} into an {@code Optional<UniqueTagList>} if {@code tags} is non-empty. * If {@code tags} contain only one element which is an empty string, it will be parsed into a * {@code Optional<UniqueTagList>} containing zero tags. */ public static Optional<UniqueTagList> parseTagsForEdit(Collection<String> tags) throws IllegalValueException { assert tags != null; if (tags.isEmpty()) { return Optional.empty(); } Collection<String> tagSet = tags.size() == 1 && tags.contains("") ? Collections.emptySet() : tags; return Optional.of(ParserUtil.parseTags(tagSet)); } /** * Split the tags string into a set. * Example: "#one #two" into ["one", "two"] * * @param tagsString * @return */ public static Set<String> parseTagStringToSet(String tagsString) { Set<String> tagSet = new HashSet<String>(); for (String i : tagsString.split("\\s+")) { if (i.length() > 1) { tagSet.add(i.substring(1)); } } return tagSet; } }
mit
kcsl/immutability-benchmark
benchmark-applications/reiminfer-oopsla-2012/source/JdbF/src/org/jdbf/engine/mapping/DatabaseMap.java
4704
/* * 18/04/2002 - 21:06:27 * * $RCSfile: DatabaseMap.java,v $ - JdbF Object Relational mapping system * Copyright (C) 2002 JDBF Development Team * * http://jdbf.sourceforge.net * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2 * 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* * $Id: DatabaseMap.java,v 1.3 2004/05/20 22:40:24 gmartone Exp $ */ package org.jdbf.engine.mapping; /** * <code>DatabaseMap </code> represents a mapping of database * * @author Giovanni Martone * @version $Revision * last changed by $Author: gmartone $ * */ public class DatabaseMap{ /** name of class */ private static final String CLASS_NAME = "org.jdbf.engine.mapping.DatabaseMap"; /** name of database */ private String name; /** vendor of database */ private String vendor; /** JDBC driver */ private String dbDriver; /** Server of database */ private String dbServer; /** Login of database */ private String dbLogin; /** Password of database*/ private String dbPassword; /** * Creates the DatabaseMap object. */ public DatabaseMap(){} /** * Return vendor of database * @return String vendor of database */ public String getVendor(){ return vendor; } /** * Return name of database * @return String name of database */ public String getName(){ return name; } /** * Return JDBC driver * @return String name of JDBC driver */ public String getDbDriver(){ return dbDriver; } /** * Return name of server * @return String name of server */ public String getDbServer(){ return dbServer; } /** * Return login of database * @return String login of database */ public String getDbLogin(){ return dbLogin; } /** * Return password of database * @return String password of database */ public String getDbPassword(){ return dbPassword; } /** * Set vendor name of database * @param vendor name of database */ public void setVendor(String vendor){ this.vendor = vendor; } /** * Set name of database * @param name of database */ public void setName(String name){ this.name = name; } /** * Set JDBC driver * @param dbDriver */ public void setDbDriver(String dbDriver){ this.dbDriver = dbDriver; } /** * Set server * @param dbServer server */ public void setDbServer(String dbServer){ this.dbServer = dbServer; } /** * Set login of database * @param dbLogin login of database */ public void setDbLogin(String dbLogin){ this.dbLogin = dbLogin; } /** * Set password of database * @param dbPassword password of database */ public void setDbPassword(String dbPassword){ this.dbPassword = dbPassword; } /** * Return the object as String * @return String */ public String toString(){ StringBuffer buff = new StringBuffer(); buff.append(CLASS_NAME).append("[").append("\n") .append("name ").append(name).append("\n") .append("vendor ").append(vendor).append("\n") .append("dbDriver ").append(dbDriver).append("\n") .append("dbServer ").append(dbServer).append("\n") .append("dbLogin ").append(dbLogin).append("\n") .append("]").append("\n"); return buff.toString(); } } /* * * $Log: DatabaseMap.java,v $ * Revision 1.3 2004/05/20 22:40:24 gmartone * Changed for task 99073 (Coverage Javadocs) * * */
mit
kimxogus/react-native-version-check
packages/react-native-version-check/android/src/main/java/io/xogus/reactnative/versioncheck/RNVersionCheckPackage.java
891
package io.xogus.reactnative.versioncheck; import java.util.Arrays; import java.util.Collections; import java.util.List; import com.facebook.react.ReactPackage; import com.facebook.react.bridge.NativeModule; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.uimanager.ViewManager; import com.facebook.react.bridge.JavaScriptModule; public class RNVersionCheckPackage implements ReactPackage { @Override public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) { return Arrays.<NativeModule>asList(new RNVersionCheckModule(reactContext)); } public List<Class<? extends JavaScriptModule>> createJSModules() { return Collections.emptyList(); } @Override public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) { return Collections.emptyList(); } }
mit
atealxt/work-workspaces
HttpForwardDemo/src_restlet/com/noelios/restlet/util/FormReader.java
12367
/** * Copyright 2005-2008 Noelios Technologies. * * The contents of this file are subject to the terms of the following open * source licenses: LGPL 3.0 or LGPL 2.1 or CDDL 1.0 (the "Licenses"). You can * select the license that you prefer but you may not use this file except in * compliance with one of these Licenses. * * You can obtain a copy of the LGPL 3.0 license at * http://www.gnu.org/licenses/lgpl-3.0.html * * You can obtain a copy of the LGPL 2.1 license at * http://www.gnu.org/licenses/lgpl-2.1.html * * You can obtain a copy of the CDDL 1.0 license at * http://www.sun.com/cddl/cddl.html * * See the Licenses for the specific language governing permissions and * limitations under the Licenses. * * Alternatively, you can obtain a royaltee free commercial license with less * limitations, transferable or non-transferable, directly at * http://www.noelios.com/products/restlet-engine * * Restlet is a registered trademark of Noelios Technologies. */ package com.noelios.restlet.util; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.logging.Level; import org.restlet.Context; import org.restlet.data.CharacterSet; import org.restlet.data.Form; import org.restlet.data.Parameter; import org.restlet.resource.Representation; import org.restlet.util.Series; /** * Form reader. * * @author Jerome Louvel */ public class FormReader { /** The encoding to use, decoding is enabled, see {@link #decode}. */ private volatile CharacterSet characterSet; /** Indicates if the parameters should be decoded. */ private volatile boolean decode; /** The form stream. */ private volatile InputStream stream; /** The separator character used between parameters. */ private volatile char separator; /** * Constructor.<br> * In case the representation does not define a character set, the UTF-8 * character set is used. * * @param representation * The web form content. * @throws IOException * if the stream of the representation could not be opened. */ public FormReader(Representation representation) throws IOException { this.decode = true; this.stream = representation.getStream(); this.separator = '&'; if (representation.getCharacterSet() != null) { this.characterSet = representation.getCharacterSet(); } else { this.characterSet = CharacterSet.UTF_8; } } /** * Constructor. Will leave the parsed data encoded. * * @param parametersString * The parameters string. */ public FormReader(String parametersString, char separator) { this.decode = false; this.stream = new ByteArrayInputStream(parametersString.getBytes()); this.characterSet = null; this.separator = separator; } /** * Constructor. * * @param parametersString * The parameters string. * @param characterSet * The supported character encoding. Set to null to leave the * data encoded. */ public FormReader(String parametersString, CharacterSet characterSet, char separator) { this.decode = true; this.stream = new ByteArrayInputStream(parametersString.getBytes()); this.characterSet = characterSet; this.separator = separator; } /** * Adds the parameters into a given form. * * @param form * The target form. */ public void addParameters(Form form) { boolean readNext = true; Parameter param = null; // Let's read all form parameters try { while (readNext) { param = readNextParameter(); if (param != null) { // Add parsed parameter to the form form.add(param); } else { // Last parameter parsed readNext = false; } } } catch (IOException ioe) { Context .getCurrentLogger() .log( Level.WARNING, "Unable to parse a form parameter. Skipping the remaining parameters.", ioe); } try { this.stream.close(); } catch (IOException ioe) { Context.getCurrentLogger().log(Level.WARNING, "Unable to close the form input stream", ioe); } } /** * Reads all the parameters. * * @return The form read. * @throws IOException * If the parameters could not be read. */ public Form read() throws IOException { final Form result = new Form(); Parameter param = readNextParameter(); while (param != null) { result.add(param); param = readNextParameter(); } this.stream.close(); return result; } /** * Reads the first parameter with the given name. * * @param name * The parameter name to match. * @return The parameter value. * @throws IOException */ public Parameter readFirstParameter(String name) throws IOException { Parameter param = readNextParameter(); Parameter result = null; while ((param != null) && (result == null)) { if (param.getName().equals(name)) { result = param; } param = readNextParameter(); } this.stream.close(); return result; } /** * Reads the next parameter available or null. * * @return The next parameter available or null. * @throws IOException * If the next parameter could not be read. */ public Parameter readNextParameter() throws IOException { Parameter result = null; try { boolean readingName = true; boolean readingValue = false; final StringBuilder nameBuffer = new StringBuilder(); final StringBuilder valueBuffer = new StringBuilder(); int nextChar = 0; while ((result == null) && (nextChar != -1)) { nextChar = this.stream.read(); if (readingName) { if (nextChar == '=') { if (nameBuffer.length() > 0) { readingName = false; readingValue = true; } else { throw new IOException( "Empty parameter name detected. Please check your form data"); } } else if ((nextChar == this.separator) || (nextChar == -1)) { if (nameBuffer.length() > 0) { result = FormUtils.create(nameBuffer, null, this.decode, this.characterSet); } else if (nextChar == -1) { // Do nothing return null preference } else { throw new IOException( "Empty parameter name detected. Please check your form data"); } } else { nameBuffer.append((char) nextChar); } } else if (readingValue) { if ((nextChar == this.separator) || (nextChar == -1)) { if (valueBuffer.length() > 0) { result = FormUtils.create(nameBuffer, valueBuffer, this.decode, this.characterSet); } else { result = FormUtils.create(nameBuffer, null, this.decode, this.characterSet); } } else { valueBuffer.append((char) nextChar); } } } } catch (UnsupportedEncodingException uee) { throw new IOException( "Unsupported encoding. Please contact the administrator"); } return result; } /** * Reads the parameters with the given name. If multiple values are found, a * list is returned created. * * @param name * The parameter name to match. * @return The parameter value or list of values. * @throws IOException * If the parameters could not be read. */ @SuppressWarnings("unchecked") public Object readParameter(String name) throws IOException { Parameter param = readNextParameter(); Object result = null; while (param != null) { if (param.getName().equals(name)) { if (result != null) { List<Object> values = null; if (result instanceof List) { // Multiple values already found for this parameter values = (List) result; } else { // Second value found for this parameter // Create a list of values values = new ArrayList<Object>(); values.add(result); result = values; } if (param.getValue() == null) { values.add(Series.EMPTY_VALUE); } else { values.add(param.getValue()); } } else { if (param.getValue() == null) { result = Series.EMPTY_VALUE; } else { result = param.getValue(); } } } param = readNextParameter(); } this.stream.close(); return result; } /** * Reads the parameters whose name is a key in the given map. If a matching * parameter is found, its value is put in the map. If multiple values are * found, a list is created and set in the map. * * @param parameters * The parameters map controlling the reading. * @throws IOException * If the parameters could not be read. */ @SuppressWarnings("unchecked") public void readParameters(Map<String, Object> parameters) throws IOException { Parameter param = readNextParameter(); Object currentValue = null; while (param != null) { if (parameters.containsKey(param.getName())) { currentValue = parameters.get(param.getName()); if (currentValue != null) { List<Object> values = null; if (currentValue instanceof List) { // Multiple values already found for this parameter values = (List) currentValue; } else { // Second value found for this parameter // Create a list of values values = new ArrayList<Object>(); values.add(currentValue); parameters.put(param.getName(), values); } if (param.getValue() == null) { values.add(Series.EMPTY_VALUE); } else { values.add(param.getValue()); } } else { if (param.getValue() == null) { parameters.put(param.getName(), Series.EMPTY_VALUE); } else { parameters.put(param.getName(), param.getValue()); } } } param = readNextParameter(); } this.stream.close(); } }
mit
ray6080/JavaPractice
src/main/java/cn/edu/ruc/dbiir/algorithms/LRUCache.java
1976
package cn.edu.ruc.dbiir.algorithms; import java.util.HashMap; /** * Created by jelly on 1/24/16. * LeetCode LRUCache */ public class LRUCache { class CacheNode { int value; int key; CacheNode prev; CacheNode next; } HashMap<Integer, CacheNode> cacheMap = new HashMap<Integer, CacheNode>(); int capacity; int numNodes; CacheNode head = new CacheNode(); CacheNode tail = new CacheNode(); public LRUCache(int capacity) { this.capacity = capacity; this.numNodes = 0; head.next = tail; tail.prev = head; } public void moveToTail(CacheNode node) { if (numNodes <= 1 || node.next==tail) { return; } node.prev.next = node.next; node.next.prev = node.prev; tail.prev.next = node; node.prev = tail.prev; node.next = tail; tail.prev = node; } public int get(int key) { if (!cacheMap.containsKey(key)) return -1; CacheNode tmpNode = cacheMap.get(key); moveToTail(tmpNode); return tmpNode.value; } public void set(int key, int value) { CacheNode tmpNode; if (cacheMap.containsKey(key)) { tmpNode = cacheMap.get(key); tmpNode.value = value; moveToTail(tmpNode); } else { tmpNode = new CacheNode(); if (numNodes >= capacity) { CacheNode removeNode = head.next; head.next = removeNode.next; removeNode.next.prev = head; cacheMap.remove(removeNode.key); numNodes--; } tmpNode.value = value; tmpNode.key = key; cacheMap.put(key, tmpNode); tmpNode.next = tail; tmpNode.prev = tail.prev; tmpNode.prev.next = tmpNode; tail.prev = tmpNode; numNodes++; } } }
mit
Adar/dacato
src/main/java/co/ecso/dacato/database/cache/CachedEntityRemover.java
747
package co.ecso.dacato.database.cache; import co.ecso.dacato.database.query.EntityRemover; import co.ecso.dacato.database.querywrapper.RemoveQuery; import java.util.concurrent.CompletableFuture; /** * CachedEntityRemover. * * @author Christian Scharmach (cs@e-cs.co) * @version $Id:$ * @since 04.10.16 */ public interface CachedEntityRemover extends EntityRemover, CacheGetter { @Override default <S> CompletableFuture<Integer> removeOne(final RemoveQuery<S> query) { final CompletableFuture<Integer> rVal = EntityRemover.super.removeOne(query); cache().keySet().stream() .filter(k -> k.hasKey(query.tableName())) .forEach(k -> cache().invalidate(k)); return rVal; } }
mit
selvasingh/azure-sdk-for-java
sdk/network/mgmt-v2020_05_01/src/main/java/com/microsoft/azure/management/network/v2020_05_01/ExpressRouteCircuitPeeringId.java
1019
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.network.v2020_05_01; import com.fasterxml.jackson.annotation.JsonProperty; /** * ExpressRoute circuit peering identifier. */ public class ExpressRouteCircuitPeeringId { /** * The ID of the ExpressRoute circuit peering. */ @JsonProperty(value = "id") private String id; /** * Get the ID of the ExpressRoute circuit peering. * * @return the id value */ public String id() { return this.id; } /** * Set the ID of the ExpressRoute circuit peering. * * @param id the id value to set * @return the ExpressRouteCircuitPeeringId object itself. */ public ExpressRouteCircuitPeeringId withId(String id) { this.id = id; return this; } }
mit
jchaganti/gharonda
server/src/main/java/org/jchlabs/gharonda/domain/pom/dao/NeightbourhoodDAO.java
400
package org.jchlabs.gharonda.domain.pom.dao; import org.hibernate.Session; import org.jchlabs.gharonda.domain.pom.base.BaseNeightbourhoodDAO; public class NeightbourhoodDAO extends BaseNeightbourhoodDAO implements org.jchlabs.gharonda.domain.pom.dao.iface.NeightbourhoodDAO { public NeightbourhoodDAO() { } public NeightbourhoodDAO(Session session) { super(session); } }
mit
nacx/sjmvc
src/main/java/org/sjmvc/web/dispatch/path/PathBasedRequestDispatcher.java
6466
/** * Copyright (c) 2010 Ignasi Barrera * * 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.sjmvc.web.dispatch.path; import java.util.HashMap; import java.util.Map; import java.util.Properties; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.sjmvc.config.Configuration; import org.sjmvc.config.ConfigurationException; import org.sjmvc.controller.Controller; import org.sjmvc.web.ResourceMapping; import org.sjmvc.web.dispatch.RequestDispatcher; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Base class for the {@link RequestDispatcher} implementations. * * @author Ignasi Barrera * * @see PathMatcher */ public class PathBasedRequestDispatcher implements RequestDispatcher { /** The logger. */ private static final Logger LOGGER = LoggerFactory .getLogger(PathBasedRequestDispatcher.class); /** Mappings from request path to {@link ResourceMapping} objects. */ protected Map<String, ResourceMapping> mappings; /** The path matcher used to check controller mappings. */ protected PathMatcher pathMatcher; /** * Creates the request dispatcher. * * @throws ConfigurationException If controller mapping configuration cannot * be read. */ public PathBasedRequestDispatcher() throws ConfigurationException { super(); loadPathMatcher(); loadControllerMappings(); } @Override public void dispatch(final HttpServletRequest req, final HttpServletResponse resp) throws Exception { LOGGER.debug("Looking for a controller to handle request to: {}", req.getRequestURI()); ResourceMapping mapping = null; String requestedPath = getRequestedPath(req); for (String path : mappings.keySet()) { if (pathMatcher.matches(path, requestedPath)) { mapping = mappings.get(path); LOGGER.debug("Using {} controller to handle request to: {}", mapping.getClass().getName(), req.getRequestURI()); // Use first match to handle the request break; } } if (mapping != null) { // Instantiate the controller on each request to make it thread-safe Controller controller = mapping.getControllerClass().newInstance(); // Execute controller logic and get the view to render String viewName = controller.execute(req, resp); if (viewName != null) { // Publish the view and layout attributes to render the view if (mapping.getLayout() != null) { String layoutPath = Configuration.LAYOUT_PATH + "/" + mapping.getLayout(); req.setAttribute(Configuration.CURRENT_LAYOUT_ATTRIBUTE, layoutPath); } String viewPath = Configuration.VIEW_PATH + mapping.getPath() + "/" + viewName + Configuration.VIEW_SUFFIX; req.setAttribute(Configuration.CURRENT_VIEW_ATTRIBUTE, viewPath); } } else { LOGGER.error("No controller was found to handle request to: {}", req.getRequestURI()); resp.sendError( HttpServletResponse.SC_NOT_FOUND, "No controller was found to handle request to: " + req.getRequestURI()); } } /** * Load the {@link PathMatcher} to use to process request URIs. */ protected void loadPathMatcher() throws ConfigurationException { Class<? extends PathMatcher> pathMatcherClass = Configuration .getPathMatcherClass(); try { pathMatcher = pathMatcherClass.newInstance(); } catch (Exception ex) { throw new ConfigurationException( "Could not instantiate the path matcher class: " + ex.getMessage()); } } /** * Load configured controller mappings. * * @throws Exception If mappings cannot be loaded. */ protected void loadControllerMappings() throws ConfigurationException { mappings = new HashMap<String, ResourceMapping>(); Properties config = Configuration.getConfiguration(); LOGGER.info("Loading controller mappings..."); for (Object mappingKey : config.keySet()) { String key = (String) mappingKey; if (Configuration.isControllerPathProperty(key)) { String path = config.getProperty(key); String clazz = config.getProperty(key.replace( Configuration.CONTROLLER_PATH_SUFFIX, Configuration.CONTROLLER_CLASS_SUFFIX)); String layout = config.getProperty(key.replace( Configuration.CONTROLLER_PATH_SUFFIX, Configuration.CONTROLLER_LAYOUT_SUFFIX)); if (clazz == null) { throw new ConfigurationException( "Missing controller class for path: " + path); } try { ClassLoader cl = Thread.currentThread() .getContextClassLoader(); @SuppressWarnings("unchecked") Class<Controller> controllerClass = (Class<Controller>) Class .forName(clazz, true, cl); ResourceMapping mapping = new ResourceMapping(); mapping.setPath(path); mapping.setLayout(layout); mapping.setControllerClass(controllerClass); mappings.put(path, mapping); LOGGER.info("Mapping {} to {}", path, controllerClass.getName()); } catch (Exception ex) { throw new ConfigurationException( "Could not get controller class: " + clazz); } } } } /** * Get the requested path relative to the servlet path. * * @param req The request. * @return The requested path. */ private String getRequestedPath(final HttpServletRequest req) { return req.getRequestURI().replaceFirst(req.getContextPath(), "") .replaceFirst(req.getServletPath(), ""); } }
mit
selvasingh/azure-sdk-for-java
sdk/network/mgmt-v2020_06_01/src/main/java/com/microsoft/azure/management/network/v2020_06_01/implementation/VirtualHubRouteTableV2sImpl.java
3311
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. * */ package com.microsoft.azure.management.network.v2020_06_01.implementation; import com.microsoft.azure.arm.model.implementation.WrapperImpl; import com.microsoft.azure.management.network.v2020_06_01.VirtualHubRouteTableV2s; import rx.Completable; import rx.Observable; import rx.functions.Func1; import com.microsoft.azure.Page; import com.microsoft.azure.management.network.v2020_06_01.VirtualHubRouteTableV2; class VirtualHubRouteTableV2sImpl extends WrapperImpl<VirtualHubRouteTableV2sInner> implements VirtualHubRouteTableV2s { private final NetworkManager manager; VirtualHubRouteTableV2sImpl(NetworkManager manager) { super(manager.inner().virtualHubRouteTableV2s()); this.manager = manager; } public NetworkManager manager() { return this.manager; } @Override public VirtualHubRouteTableV2Impl define(String name) { return wrapModel(name); } private VirtualHubRouteTableV2Impl wrapModel(VirtualHubRouteTableV2Inner inner) { return new VirtualHubRouteTableV2Impl(inner, manager()); } private VirtualHubRouteTableV2Impl wrapModel(String name) { return new VirtualHubRouteTableV2Impl(name, this.manager()); } @Override public Observable<VirtualHubRouteTableV2> listAsync(final String resourceGroupName, final String virtualHubName) { VirtualHubRouteTableV2sInner client = this.inner(); return client.listAsync(resourceGroupName, virtualHubName) .flatMapIterable(new Func1<Page<VirtualHubRouteTableV2Inner>, Iterable<VirtualHubRouteTableV2Inner>>() { @Override public Iterable<VirtualHubRouteTableV2Inner> call(Page<VirtualHubRouteTableV2Inner> page) { return page.items(); } }) .map(new Func1<VirtualHubRouteTableV2Inner, VirtualHubRouteTableV2>() { @Override public VirtualHubRouteTableV2 call(VirtualHubRouteTableV2Inner inner) { return wrapModel(inner); } }); } @Override public Observable<VirtualHubRouteTableV2> getAsync(String resourceGroupName, String virtualHubName, String routeTableName) { VirtualHubRouteTableV2sInner client = this.inner(); return client.getAsync(resourceGroupName, virtualHubName, routeTableName) .flatMap(new Func1<VirtualHubRouteTableV2Inner, Observable<VirtualHubRouteTableV2>>() { @Override public Observable<VirtualHubRouteTableV2> call(VirtualHubRouteTableV2Inner inner) { if (inner == null) { return Observable.empty(); } else { return Observable.just((VirtualHubRouteTableV2)wrapModel(inner)); } } }); } @Override public Completable deleteAsync(String resourceGroupName, String virtualHubName, String routeTableName) { VirtualHubRouteTableV2sInner client = this.inner(); return client.deleteAsync(resourceGroupName, virtualHubName, routeTableName).toCompletable(); } }
mit
georghinkel/ttc2017smartGrids
solutions/ModelJoin/src/main/java/COSEM/InterfaceClasses/impl/M_Bus_diagnosticImpl.java
765
/** */ package COSEM.InterfaceClasses.impl; import COSEM.InterfaceClasses.InterfaceClassesPackage; import COSEM.InterfaceClasses.M_Bus_diagnostic; import org.eclipse.emf.ecore.EClass; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>MBus diagnostic</b></em>'. * <!-- end-user-doc --> * * @generated */ public class M_Bus_diagnosticImpl extends BaseImpl implements M_Bus_diagnostic { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected M_Bus_diagnosticImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return InterfaceClassesPackage.Literals.MBUS_DIAGNOSTIC; } } //M_Bus_diagnosticImpl
mit
Fundynamic/dune2themaker4j
src/main/java/com/fundynamic/d2tm/game/rendering/gui/sidebar/MiniMap.java
7022
package com.fundynamic.d2tm.game.rendering.gui.sidebar; import com.fundynamic.d2tm.game.entities.Entity; import com.fundynamic.d2tm.game.entities.EntityRepository; import com.fundynamic.d2tm.game.entities.EntityType; import com.fundynamic.d2tm.game.entities.Player; import com.fundynamic.d2tm.game.map.Cell; import com.fundynamic.d2tm.game.map.Map; import com.fundynamic.d2tm.game.rendering.gui.GuiElement; import com.fundynamic.d2tm.game.rendering.gui.battlefield.BattleField; import com.fundynamic.d2tm.math.MapCoordinate; import com.fundynamic.d2tm.math.Rectangle; import com.fundynamic.d2tm.math.Vector2D; import org.newdawn.slick.*; import static com.fundynamic.d2tm.game.map.Cell.TILE_SIZE; public class MiniMap extends GuiElement { private final BattleField battleField; private final EntityRepository entityRepository; private final Map map; private final Player player; private final Rectangle renderPosition; private final float renderScale; private float elapsedTime = 0f; private boolean redrawMiniMap; private Image unscaledMiniMapImage; private Vector2D mouseCoordinates; public MiniMap(int x, int y, int width, int height, BattleField battleField, EntityRepository entityRepository, Map map, Player player) { super(x, y, width, height); this.battleField = battleField; this.entityRepository = entityRepository; this.map = map; this.player = player; this.redrawMiniMap = true; this.renderPosition = getRenderPosition(); this.renderScale = getRenderScale(Vector2D.create(map.getWidth(), map.getHeight())); if (player.hasFocusMapCoordinate()) { centerViewportOn(player.getFocusMapCoordinate()); } } private Rectangle getRenderPosition() { Vector2D mapDimensions = new Vector2D(map.getWidth() * TILE_SIZE, map.getHeight() * TILE_SIZE); return this.scaleContainCenter(mapDimensions); } private float getRenderScale(Vector2D mapDimensions) { if (mapDimensions.getX() > mapDimensions.getY()) { return getWidth() / mapDimensions.getX(); } else { return getHeight() / mapDimensions.getY(); } } @Override public void update(float deltaInSeconds) { elapsedTime += deltaInSeconds; if (elapsedTime >= 0.5f) { redrawMiniMap = true; elapsedTime = 0; } } @Override public void render(Graphics graphics) { // clear background graphics.setColor(Color.black); graphics.fillRect(getTopLeftX(), getTopLeftY(), getWidth(), getHeight()); if (player.isHasRadar()) { if (!player.isLowPower()) { // render minimap Image unscaledMiniMapImage = getMaybeRedrawnOrStaleMiniMapImage(); unscaledMiniMapImage.draw( renderPosition.getTopLeftX(), renderPosition.getTopLeftY(), renderPosition.getWidth(), renderPosition.getHeight()); } } // render viewport outline drawViewportOutline(graphics); } private Image getMaybeRedrawnOrStaleMiniMapImage() { if (redrawMiniMap) { // free memory of previously generated mini-map image if (unscaledMiniMapImage != null) { try { unscaledMiniMapImage.destroy(); } catch (SlickException e) { throw new RuntimeException(e); } } // regenerate the minimap unscaledMiniMapImage = createMiniMapImage(); redrawMiniMap = false; } return unscaledMiniMapImage; } private Image createMiniMapImage() { final int width = map.getWidth(); final int height = map.getHeight(); ImageBuffer buffer = new ImageBuffer(width, height); // render terrain for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { // skip shrouded terrain Cell cell = map.getCell(x + 1, y + 1); if (player.isShrouded(cell.getMapCoordinate())) { continue; } final Color terrainColor = cell.getTerrainColor(); buffer.setRGBA(x, y, terrainColor.getRed(), terrainColor.getGreen(), terrainColor.getBlue(), 255); } } // render entities for(Entity entity : entityRepository.findAliveEntitiesWithinPlayableMapBoundariesOfType(EntityType.STRUCTURE, EntityType.UNIT)) { for(MapCoordinate mapCoordinate : entity.getAllCellsAsMapCoordinates()) { // skip shrouded entities if (player.isShrouded(mapCoordinate)) { continue; } // use one pixel offset, because map coordinates are one-based int x = mapCoordinate.getXAsInt() - 1; int y = mapCoordinate.getYAsInt() - 1; Color factionColor = entity.getPlayer().getFactionColor(); buffer.setRGBA(x, y, factionColor.getRed(), factionColor.getGreen(), factionColor.getBlue(), 255); } } return buffer.getImage(Image.FILTER_NEAREST); } private void drawViewportOutline(Graphics graphics) { graphics.setColor(Color.white); graphics.setLineWidth(1f); Rectangle boundaries = battleField.getViewportCellBoundaries(); // x and y are offset by 1 because the boundaries are 1-based float x = renderPosition.getTopLeftX() + (boundaries.getTopLeftX() - 1) * renderScale; float y = renderPosition.getTopLeftY() + (boundaries.getTopLeftY() - 1) * renderScale; graphics.drawRect(x, y, (boundaries.getWidth() * renderScale) -1f, (boundaries.getHeight() * renderScale) -1f); } @Override public void leftClicked() { MapCoordinate clickedCoordinate = mouseCoordinates .min(renderPosition.getTopLeft()) // convert to relative coordinates .scale(1f / renderScale) // convert to map coordinates .add(new Vector2D(1, 1)) // and offset by one, because of the invisible border .asMapCoordinate(); centerViewportOn(clickedCoordinate); } public void centerViewportOn(MapCoordinate clickedCoordinate) { battleField.centerViewportOn(clickedCoordinate); } @Override public void rightClicked() { // No action on right-click } @Override public void leftButtonReleased() { // No action when left-click is released } @Override public void draggedToCoordinates(Vector2D coordinates) { mouseCoordinates = coordinates; leftClicked(); } @Override public void movedTo(Vector2D coordinates) { mouseCoordinates = coordinates; } @Override public String toString() { return "Minimap"; } }
mit
canselcik/subsequence
app/internal/Database/TransactionDB.java
5967
package internal.database; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import internal.Global; import internal.rpc.pojo.RawTransaction; import play.db.DB; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.List; public class TransactionDB { public enum TxDatabasePresence { ERROR(-1), NOT_PRESENT(0), UNCONFIRMED(1), CONFIRMED(2); private final int id; TxDatabasePresence(int id) { this.id = id; } public int getValue() { return id; } }; public static TxDatabasePresence txPresentInDB(String txHash){ Connection c = DB.getConnection(); try { PreparedStatement ps = c.prepareStatement("SELECT internal_txid, matched_user_id, inbound, tx_hash, confirmed FROM transactions WHERE tx_hash = ?"); ps.setString(1, txHash); ResultSet rs = ps.executeQuery(); c.close(); if(rs == null) return TxDatabasePresence.ERROR; if(!rs.next()) return TxDatabasePresence.NOT_PRESENT; if(!rs.getString("tx_hash").equals(txHash)) return TxDatabasePresence.NOT_PRESENT; if(rs.getBoolean("confirmed")) return TxDatabasePresence.CONFIRMED; else return TxDatabasePresence.UNCONFIRMED; } catch(Exception e){ e.printStackTrace(); return TxDatabasePresence.ERROR; } } public static boolean insertTxIntoDB(String txHash, long userId, boolean inbound, boolean confirmed, long amountSatoshis){ Connection c = DB.getConnection(); try { PreparedStatement ps = c.prepareStatement("INSERT INTO transactions(matched_user_id, inbound, tx_hash, confirmed, amount_satoshi) VALUES(?, ?, ?, ?, ?)"); ps.setLong(1, userId); ps.setBoolean(2, inbound); ps.setString(3, txHash); ps.setBoolean(4, confirmed); ps.setLong(5, amountSatoshis); int result = ps.executeUpdate(); c.close(); boolean ret = (result == 1); return ret; } catch(Exception e){ e.printStackTrace(); return false; } } public static boolean updateTxStatus(String txHash, boolean confirmed){ Connection c = DB.getConnection(); try { PreparedStatement ps = c.prepareStatement("UPDATE transactions SET confirmed = ? WHERE tx_hash = ?"); ps.setBoolean(1, confirmed); ps.setString(2, txHash); int result = ps.executeUpdate(); c.close(); boolean ret = (result == 1); return ret; } catch(Exception e){ e.printStackTrace(); return false; } } public static boolean txInputsUsedInDB(RawTransaction tx){ if(tx == null) return true; List<String> inputTxIds = tx.extractInputTxIds(); if(inputTxIds.size() == 0) return true; Connection conn = DB.getConnection(); try { for(String txid : inputTxIds) { PreparedStatement ps = conn.prepareStatement("SELECT count(*) FROM used_txos WHERE txo = ?"); ps.setString(1, txid); ResultSet rs = ps.executeQuery(); if (rs == null || !rs.next()) { conn.close(); return true; } Integer count = rs.getInt(1); if (count == null || count > 0) return true; } conn.close(); return false; } catch (Exception e) { e.printStackTrace(); return true; } } public static boolean addTxInputsToDB(List<String> inputTxIds, String parentTx) { if(inputTxIds == null) return false; if(inputTxIds.size() == 0) return false; Connection conn = DB.getConnection(); try { for(String txid : inputTxIds){ PreparedStatement ps = conn.prepareStatement("INSERT INTO used_txos (txo, new_txid) VALUES (?, ?)"); ps.setString(1, txid); ps.setString(2, parentTx); int res = ps.executeUpdate(); if(res == 0) return false; } conn.close(); return true; } catch (Exception e) { e.printStackTrace(); return false; } } public static ArrayNode getTransactions(Long accountId){ Connection c = DB.getConnection(); try { PreparedStatement ps = c.prepareStatement("SELECT * FROM transactions WHERE matched_user_id = ?"); ps.setLong(1, accountId); ResultSet rs = ps.executeQuery(); if(rs == null) return null; ArrayNode nodes = Global.mapper.createArrayNode(); while(rs.next()){ ObjectNode root = Global.mapper.createObjectNode(); root.put("internal_txid", rs.getLong("internal_txid")); root.put("matched_user_id", rs.getLong("matched_user_id")); root.put("inbound", rs.getBoolean("inbound")); root.put("txhash", rs.getString("tx_hash")); if(rs.getBoolean("inbound")) root.put("confirmed", rs.getBoolean("confirmed")); root.put("satoshi_amount", rs.getLong("amount_satoshi")); nodes.add(root); } c.close(); return nodes; } catch(Exception e){ e.printStackTrace(); return null; } } }
mit
munificent/magpie
src/com/stuffwithstuff/magpie/intrinsic/ProcessMethods.java
1610
package com.stuffwithstuff.magpie.intrinsic; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.stuffwithstuff.magpie.Def; import com.stuffwithstuff.magpie.Doc; import com.stuffwithstuff.magpie.interpreter.Context; import com.stuffwithstuff.magpie.interpreter.Obj; import com.stuffwithstuff.magpie.util.IO; public class ProcessMethods { @Def("execute(command is String)") @Doc("Spawns a new process, executes the given command in it, and waits " + "it to end. Returns the process's output and exit code.") public static class Execute implements Intrinsic { public Obj invoke(Context context, Obj left, Obj right) { String command = right.asString(); Runtime runtime = Runtime.getRuntime(); try { Process process = runtime.exec(command); int exit = process.waitFor(); String output = IO.readAll(new BufferedReader( new InputStreamReader(process.getInputStream()))); List<String> keys = new ArrayList<String>(); keys.add("out"); keys.add("exit"); Map<String, Obj> record = new HashMap<String, Obj>(); record.put("out", context.toObj(output)); record.put("exit", context.toObj(exit)); return context.toObj(keys, record); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } return context.nothing(); } } }
mit
fccn/PTCRISync
src/main/java/pt/ptcris/utils/ORCIDWorkHelper.java
13661
/* * Copyright (c) 2016, 2017 PTCRIS - FCT|FCCN and others. * Licensed under MIT License * http://ptcris.pt * * This copyright and license information (including a link to the full license) * shall be included in its entirety in all copies or substantial portion of * the software. */ package pt.ptcris.utils; import java.math.BigInteger; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import org.um.dsi.gavea.orcid.client.exception.OrcidClientException; import org.um.dsi.gavea.orcid.model.activities.WorkGroup; import org.um.dsi.gavea.orcid.model.common.ExternalId; import org.um.dsi.gavea.orcid.model.common.ExternalIds; import org.um.dsi.gavea.orcid.model.common.WorkType; import org.um.dsi.gavea.orcid.model.work.Work; import org.um.dsi.gavea.orcid.model.work.WorkSummary; import pt.ptcris.ORCIDClient; import pt.ptcris.PTCRISyncResult; import pt.ptcris.handlers.ProgressHandler; /** * An helper to simplify the use of the low-level ORCID * {@link pt.ptcris.ORCIDClient client}. * * Provides support for asynchronous communication with ORCID although it is * only active for GET requests due to resource limitations. */ public final class ORCIDWorkHelper extends ORCIDHelper<Work, WorkSummary, WorkGroup, WorkType> { public enum EIdType { OTHER_ID("other-id"), AGR("agr"), ARXIV("arxiv"), ARK("ark"), ASIN("asin"), BIBCODE("bibcode"), CBA("cba"), CIT("cit"), CTX("ctx"), DNB("dnb"), DOI("doi"), EID("eid"), ETHOS("ethos"), HANDLE("handle"), HIR("hir"), ISBN("isbn"), ISSN("issn"), JFM("jfm"), JSTOR("jstor"), LCCN("lccn"), MR("mr"), OCLC("oclc"), OL("ol"), OSTI("osti"), PAT("pat"), PMC("pmc"), PMID("pmid"), RFC("rfc"), SOURCE_WORK_ID("source-work-id"), SSRN("ssrn"), URI("uri"), URN("urn"), WOSUID("wosuid"), ZBL("zbl"), CIENCIAIUL("cienciaiul"), LENSID("lensid"), PDB("pdb"), KUID("kuid"), ASIN_TLD("asin-tld"), AUTHENTICUSID("authenticusid"), RRID("rrid"), HAL("hal"), ISMN("ismn"), EMDB("emdb"), PPR("ppr"); public final String value; private EIdType(String value) { this.value = value; } } /** * Initializes the helper with a given ORCID client. * * @param orcidClient * the ORCID client */ public ORCIDWorkHelper(ORCIDClient orcidClient) { super(orcidClient, 100, 50); } /* * Client methods instantiated for ORCID work activities. */ /** {@inheritDoc} */ @Override protected List<WorkGroup> getSummariesClient() throws OrcidClientException { assert client != null; _log.debug("[getWorkSummaries] "+client.getUserId()); return client.getWorksSummary().getGroup(); } /** {@inheritDoc} */ @Override protected PTCRISyncResult<Work> readClient(WorkSummary work) { assert client != null; assert work != null; assert work.getPutCode() != null; _log.debug("[getFullWork] "+work.getPutCode()); return client.getWork(work); } /** {@inheritDoc} */ @Override protected Map<BigInteger, PTCRISyncResult<Work>> readClient(List<WorkSummary> summaries) { assert client != null; if (summaries == null || summaries.isEmpty()) return new HashMap<BigInteger, PTCRISyncResult<Work>>(); _log.debug("[getFullBulkWork] "+summaries.size()); return client.getWorks(summaries); } /** {@inheritDoc} */ @Override protected ORCIDWorker<Work> readWorker(WorkSummary summary, Map<BigInteger, PTCRISyncResult<Work>> cb, ProgressHandler handler) { assert client != null; assert cb != null; assert summary != null; return new ORCIDGetWorkWorker(summary, client, cb, _log, handler); } /** {@inheritDoc} */ @Override protected ORCIDWorker<Work> readWorker(List<WorkSummary> summaries, Map<BigInteger, PTCRISyncResult<Work>> cb, ProgressHandler handler) { assert client != null; assert cb != null; if (summaries == null) summaries = new ArrayList<WorkSummary>(); return new ORCIDGetBulkWorkWorker(summaries, client, cb, _log, handler); } /** {@inheritDoc} */ @Override protected PTCRISyncResult<Work> addClient(Work work) { assert client != null; _log.debug("[addWork] "+work.getTitle()); return client.addWork(work); } /** {@inheritDoc} */ @Override protected List<PTCRISyncResult<Work>> addClient(List<Work> works) { assert client != null; _log.debug("[addBulkWork] "+works.size()); if (works == null || works.isEmpty()) return new ArrayList<PTCRISyncResult<Work>>(); return client.addWorks(works); } /** {@inheritDoc} */ @Override protected PTCRISyncResult<Work> updateClient(BigInteger remotePutcode, Work work) { assert client != null; assert remotePutcode != null; assert work != null; _log.debug("[updateWork] "+remotePutcode); return client.updateWork(remotePutcode, work); } /** {@inheritDoc} */ @Override protected PTCRISyncResult<Work> deleteClient(BigInteger remotePutcode) { assert client != null; assert remotePutcode != null; _log.debug("[deleteWork] "+remotePutcode); return client.deleteWork(remotePutcode); } /* * Static methods instantiated for ORCID work activities. */ /** {@inheritDoc} */ @Override public ExternalIds getNonNullExternalIdsE(Work work) { if (work.getExternalIds() == null || work.getExternalIds().getExternalId() == null) { return new ExternalIds(new ArrayList<ExternalId>()); } else { return work.getExternalIds(); } } /** {@inheritDoc} */ @Override public ExternalIds getNonNullExternalIdsS(WorkSummary summary) { if (summary.getExternalIds() == null || summary.getExternalIds().getExternalId() == null) { return new ExternalIds(new ArrayList<ExternalId>()); } else { return summary.getExternalIds(); } } /** {@inheritDoc} */ @Override public void setExternalIdsE(Work work, ExternalIds eids) { assert work != null; if (eids == null) eids = new ExternalIds(new ArrayList<ExternalId>()); work.setExternalIds(eids); } /** {@inheritDoc} */ @Override public void setExternalIdsS(WorkSummary summary, ExternalIds eids) { assert summary != null; if (eids == null) eids = new ExternalIds(new ArrayList<ExternalId>()); summary.setExternalIds(eids); } /** {@inheritDoc} */ @Override protected WorkType getTypeS(WorkSummary summary) { assert summary != null; return summary.getType(); } /** * {@inheritDoc} * * Elements of the enum {@link EIdType} take the shape of upper-case valid * EId types, with slashes replaced by underscores. */ @Override protected boolean validExternalIdType(String eid) { try { EIdType.valueOf(eid.replace('-', '_').toUpperCase()); return true; } catch (Exception e) { return false; } } /** {@inheritDoc} */ @Override protected String getTitleS(WorkSummary summary) { assert summary != null; if (summary.getTitle() == null) return ""; return summary.getTitle().getTitle(); } /** {@inheritDoc} */ @Override protected String getYearS(WorkSummary summary) { assert summary != null; if (summary.getPublicationDate() == null || summary.getPublicationDate().getYear() == null) return null; return String.valueOf(summary.getPublicationDate().getYear().getValue()); } /** {@inheritDoc} */ @Override protected List<WorkSummary> getGroupSummaries(WorkGroup group) { assert group != null; return group.getWorkSummary(); } /** {@inheritDoc} */ @Override protected WorkSummary group(WorkGroup group) throws IllegalArgumentException { assert group != null; if (group.getWorkSummary() == null || group.getWorkSummary().isEmpty()) throw new IllegalArgumentException("Can't merge empty group."); final WorkSummary preferred = group.getWorkSummary().get(0); final WorkSummary dummy = cloneS(preferred); final List<ExternalId> eids = getPartOfExternalIdsS(dummy) .getExternalId(); addFundedByEidsFromAllWorkSummaries(group, eids); for (ExternalId id : group.getExternalIds().getExternalId()) eids.add(clone(id)); dummy.setExternalIds(new ExternalIds(eids)); return dummy; } private void addFundedByEidsFromAllWorkSummaries(WorkGroup group, final List<ExternalId> eids) { Set<String> set = new HashSet<>(eids.size()); for (int i = 0 ; i < group.getWorkSummary().size(); i++){ WorkSummary cloned = cloneS(group.getWorkSummary().get(i)); List<ExternalId> fundedByEids = getFundedByExternalIdsS(cloned).getExternalId(); List<ExternalId> fundedByEidsWithoutDuplicates = fundedByEids.stream() .filter(eid -> set.add(eid.getExternalIdValue())) .collect(Collectors.toList()); eids.addAll(fundedByEidsWithoutDuplicates); } } /** * {@inheritDoc} * * The considered fields are: title, publication date (year), work type and * part-of external identifiers (excluding URLs). All this meta-data is * available in work summaries. * * TODO: contributors are not being considered as they are not contained in * the summaries. */ @Override protected boolean isMetaUpToDate(Work preWork, WorkSummary posWork) { assert preWork != null; assert posWork != null; boolean res = true; res &= identicalExternalIDs(getPartOfExternalIdsE(preWork), getPartOfExternalIdsS(posWork)); res &= getTitleE(preWork).equals(getTitleS(posWork)); res &= (getPubYearE(preWork) == null && getYearS(posWork) == null) || (getPubYearE(preWork) != null && getYearS(posWork) != null && getPubYearE(preWork) .equals(getYearS(posWork))); res &= (preWork.getType() == null && posWork.getType() == null) || (preWork.getType() != null && posWork.getType() != null && preWork .getType().equals(posWork.getType())); return res; } /** * {@inheritDoc} * * The considered fields are: self external identifiers, title, publication * date (year) and work type. The test also checks whether the external * identifiers overlap with those of the coexisting works. All this * meta-data is available in work summaries. The publication date is not * necessary for data sets and research techniques. * * TODO: contributors are not being considered as they are not contained in * the summaries. */ @Override public Set<String> testMinimalQuality(WorkSummary work, Collection<Work> others) { assert work != null; if (others == null) others = new ArrayList<Work>(); final Set<String> res = new HashSet<String>(); if (getSelfExternalIdsS(work).getExternalId().isEmpty()) res.add(INVALID_EXTERNALIDENTIFIERS); else for (ExternalId eid : getSelfExternalIdsS(work).getExternalId()) if (!validExternalIdType(eid.getExternalIdType())) res.add(INVALID_EXTERNALIDENTIFIERS); if (work.getTitle() == null) res.add(INVALID_TITLE); else if (work.getTitle().getTitle() == null) res.add(INVALID_TITLE); if (work.getType() == null) res.add(INVALID_TYPE); if (work.getType() == null || (work.getType() != WorkType.DATA_SET && work.getType() != WorkType.RESEARCH_TECHNIQUE)) { if (work.getPublicationDate() == null) res.add(INVALID_PUBLICATIONDATE); else { if (!testQualityFuzzyDate(work.getPublicationDate())) res.add(INVALID_PUBLICATIONDATE); if (work.getPublicationDate().getYear() == null) res.add(INVALID_YEAR); } // TODO: months and days must have two characters; but these are optional; should it be tested here? } Map<Work, ExternalIdsDiff> worksDiffs = getSelfExternalIdsDiffS(work, others); for (Work match : worksDiffs.keySet()) if (match.getPutCode() != work.getPutCode() && !worksDiffs.get(match).same.isEmpty()) res.add(OVERLAPPING_EIDs); return res; } /** {@inheritDoc} */ @Override public Work createUpdate(Work original, ExternalIdsDiff diff) { assert original != null; assert diff != null; Work workUpdate = cloneE(original); ExternalIds weids = new ExternalIds(); List<ExternalId> neids = new ArrayList<ExternalId>(diff.more); weids.setExternalId(neids); ORCIDHelper.setWorkLocalKey(workUpdate, ORCIDHelper.getActivityLocalKey(original)); workUpdate.setExternalIds(weids); workUpdate.setTitle(null); workUpdate.setType(null); workUpdate.setPublicationDate(null); return workUpdate; } /** {@inheritDoc} */ @Override public WorkSummary cloneS(WorkSummary summary) { assert summary != null; final WorkSummary dummy = new WorkSummary(); copy(summary, dummy); dummy.setPublicationDate(summary.getPublicationDate()); dummy.setTitle(summary.getTitle()); dummy.setType(summary.getType()); dummy.setExternalIds(getNonNullExternalIdsS(summary)); return dummy; } /** {@inheritDoc} */ @Override public Work cloneE(Work work) { assert work != null; final Work dummy = new Work(); copy(work, dummy); dummy.setPublicationDate(work.getPublicationDate()); dummy.setTitle(work.getTitle()); dummy.setType(work.getType()); dummy.setExternalIds(getNonNullExternalIdsE(work)); dummy.setContributors(work.getContributors()); dummy.setCitation(work.getCitation()); dummy.setContributors(work.getContributors()); dummy.setCountry(work.getCountry()); dummy.setJournalTitle(work.getJournalTitle()); dummy.setLanguageCode(work.getLanguageCode()); dummy.setShortDescription(work.getShortDescription()); dummy.setUrl(work.getUrl()); return dummy; } /** {@inheritDoc} */ @Override public WorkSummary summarize(Work work) { assert work != null; final WorkSummary dummy = new WorkSummary(); copy(work, dummy); dummy.setPublicationDate(work.getPublicationDate()); dummy.setTitle(work.getTitle()); dummy.setType(work.getType()); dummy.setExternalIds(getNonNullExternalIdsE(work)); return dummy; } }
mit
DanielLuis/springboot-angularjs
src/main/java/br/com/springboot/app/support/ErrorJson.java
588
package br.com.springboot.app.support; import java.util.Map; public class ErrorJson { public Integer status; public String error; public String message; public String timeStamp; public String trace; public ErrorJson(int status, Map<String, Object> errorAttributes) { this.status = status; this.error = (String) errorAttributes.get("error"); this.message = (String) errorAttributes.get("message"); this.timeStamp = errorAttributes.get("timestamp").toString(); this.trace = (String) errorAttributes.get("trace"); } }
mit
iontorrent/Torrent-Variant-Caller-stable
public/java/src/org/broadinstitute/sting/gatk/walkers/annotator/NBaseCount.java
2547
package org.broadinstitute.sting.gatk.walkers.annotator; import org.broadinstitute.sting.gatk.contexts.AlignmentContext; import org.broadinstitute.sting.gatk.contexts.ReferenceContext; import org.broadinstitute.sting.gatk.refdata.RefMetaDataTracker; import org.broadinstitute.sting.gatk.walkers.annotator.interfaces.AnnotatorCompatibleWalker; import org.broadinstitute.sting.gatk.walkers.annotator.interfaces.InfoFieldAnnotation; import org.broadinstitute.sting.utils.BaseUtils; import org.broadinstitute.sting.utils.codecs.vcf.VCFHeaderLineType; import org.broadinstitute.sting.utils.codecs.vcf.VCFInfoHeaderLine; import org.broadinstitute.sting.utils.pileup.PileupElement; import org.broadinstitute.sting.utils.variantcontext.VariantContext; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; /** * The number of N bases, counting only SOLiD data */ public class NBaseCount extends InfoFieldAnnotation { public Map<String, Object> annotate(RefMetaDataTracker tracker, AnnotatorCompatibleWalker walker, ReferenceContext ref, Map<String, AlignmentContext> stratifiedContexts, VariantContext vc) { if( stratifiedContexts.size() == 0 ) return null; int countNBaseSolid = 0; int countRegularBaseSolid = 0; for( final AlignmentContext context : stratifiedContexts.values() ) { if ( context.hasBasePileup() ) { // must be called as getBasePileup may throw error when pileup has no bases for( final PileupElement p : context.getBasePileup()) { if( p.getRead().getReadGroup().getPlatform().toUpperCase().contains("SOLID") ) { if( BaseUtils.isNBase( p.getBase() ) ) { countNBaseSolid++; } else if( BaseUtils.isRegularBase( p.getBase() ) ) { countRegularBaseSolid++; } } } } } final Map<String, Object> map = new HashMap<String, Object>(); map.put(getKeyNames().get(0), String.format("%.4f", (double)countNBaseSolid / (double)(countNBaseSolid + countRegularBaseSolid + 1))); return map; } public List<String> getKeyNames() { return Arrays.asList("PercentNBaseSolid"); } public List<VCFInfoHeaderLine> getDescriptions() { return Arrays.asList(new VCFInfoHeaderLine("PercentNBaseSolid", 1, VCFHeaderLineType.Float, "Percentage of N bases in the pileup (counting only SOLiD reads)")); } }
mit
mamorum/poml
src/test/java/poml/convert/BasicTest.java
3813
package poml.convert; import org.junit.Test; import poml.UtCase; public class BasicTest extends UtCase { //-> pkg @Test public void pkg_id2pac() { poml( "pkg=com.example:demo:0.0.1:jar" ); Basic.pkg(poml, xml); xml( " <groupId>com.example</groupId>" + nl + " <artifactId>demo</artifactId>" + nl + " <version>0.0.1</version>" + nl + " <packaging>jar</packaging>" + nl ); } @Test public void pkg_id2ver() { poml( "pkg=com.example:demo:0.0.1" ); Basic.pkg(poml, xml); xml( " <groupId>com.example</groupId>" + nl + " <artifactId>demo</artifactId>" + nl + " <version>0.0.1</version>" + nl ); } //-> parent @Test public void parent_id2ver() { poml( "parent=com.example:demo-parent:0.0.1" ); Basic.parent(poml, xml); xml( " <parent>" + nl + " <groupId>com.example</groupId>" + nl + " <artifactId>demo-parent</artifactId>" + nl + " <version>0.0.1</version>" + nl + " </parent>" + nl ); } @Test public void parent_id2rel() { poml( "parent=com.example:demo-parent:0.0.1:../pom.xml" ); Basic.parent(poml, xml); xml( " <parent>" + nl + " <groupId>com.example</groupId>" + nl + " <artifactId>demo-parent</artifactId>" + nl + " <version>0.0.1</version>" + nl + " <relativePath>../pom.xml</relativePath>" + nl + " </parent>" + nl ); } //-> depend @Test public void depend_multi() { poml( "depend=" + nl + " com.example:artifact1:0.0.1:test:true:jar," + nl + " com.example:artifact2::::jar," + nl + " com.example:artifact3" ); Basic.depend(poml, xml); xml( " <dependency>" + nl + " <groupId>com.example</groupId>" + nl + " <artifactId>artifact1</artifactId>" + nl + " <version>0.0.1</version>" + nl + " <scope>test</scope>" + nl + " <optional>true</optional>" + nl + " <type>jar</type>" + nl + " </dependency>" + nl + " <dependency>" + nl + " <groupId>com.example</groupId>" + nl + " <artifactId>artifact2</artifactId>" + nl + " <type>jar</type>" + nl + " </dependency>" + nl + " <dependency>" + nl + " <groupId>com.example</groupId>" + nl + " <artifactId>artifact3</artifactId>" + nl + " </dependency>" + nl ); } @Test public void depend_single() { poml( "depend=junit:junit:[4.12\\,):test" ); Basic.depend(poml, xml); xml( " <dependency>" + nl + " <groupId>junit</groupId>" + nl + " <artifactId>junit</artifactId>" + nl + " <version>[4.12,)</version>" + nl + " <scope>test</scope>" + nl + " </dependency>" + nl ); } //-> properties @Test public void properties_multi() { poml( "properties=" + nl + " gpg.skip>true," + nl + " &encoding>UTF-8, &compiler>1.8" ); Basic.properties(poml, xml); xml( " <properties>" + nl + " <gpg.skip>true</gpg.skip>" + nl + " <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>" + nl + " <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>" + nl + " <maven.compiler.source>1.8</maven.compiler.source>" + nl + " <maven.compiler.target>1.8</maven.compiler.target>" + nl + " </properties>" + nl ); } @Test public void properties_single() { poml( "properties=gpg.skip>true" ); Basic.properties(poml, xml); xml( " <properties>" + nl + " <gpg.skip>true</gpg.skip>" + nl + " </properties>" + nl ); } }
mit
TPL-Group/TPL-Compiler
src/parser/nodes/NonEmptyFormalsNode.java
567
package src.parser.nodes; import src.parser.*; public class NonEmptyFormalsNode extends SemanticNode{ @Override public void setChildren(){ if(TableDrivenParser.semanticStack.peek() instanceof NonEmptyFormalsPrimeNode){ this.takeChildren((NonEmptyFormalsPrimeNode)TableDrivenParser.semanticStack.pop(), this); } if(TableDrivenParser.semanticStack.peek() instanceof FormalNode){ this.addChild((FormalNode)TableDrivenParser.semanticStack.pop(), this); } } @Override public String toString(){ return "NonEmptyFormalsNode"; } }
mit
a64adam/ulti
src/main/java/dto/currentgame/CurrentGameInfo.java
3222
/* * The MIT License (MIT) * * Copyright (c) 2014 Adam Alyyan * * 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 dto.currentgame; import java.util.List; public class CurrentGameInfo { private List<BannedChampion> bannedChampions; private long gameId; private long gameLength; private String gameMode; private long gameQueueConfigId; private long gameStartTime; private String gameType; private long mapId; private Observer observers; private List<Participant> participants; private String platformId; /** * @return A list of the banned champions */ public List<BannedChampion> getBannedChampions() { return bannedChampions; } /** * @return The ID of the game */ public long getGameId() { return gameId; } /** * @return The amount of time in seconds that has passed since the game started */ public long getGameLength() { return gameLength; } /** * @return The game mode: {Legal values: CLASSIC, ODIN, ARAM, TUTORIAL, ONEFORALL, ASCENSION, FIRSTBLOOD, KINGPORO} */ public String getGameMode() { return gameMode; } /** * @return The queue type of the game */ public long getGameQueueConfigId() { return gameQueueConfigId; } /** * @return The game start time represented in epoch time */ public long getGameStartTime() { return gameStartTime; } /** * @return The game type: {Legal values: CUSTOM_GAME, MATCHED_GAME, TUTORIAL_GAME} */ public String getGameType() { return gameType; } /** * @return The ID of the map */ public long getMapId() { return mapId; } /** * @return The participant information */ public List<Participant> getParticipants() { return participants; } /** * @return The observer information */ public Observer getObservers() { return observers; } /** * @return The ID of the platform that the game is being played on */ public String getPlatformId() { return platformId; } }
mit
linkedpipes/uv2etl
src/main/java/com/linkedpipes/etl/convert/uv/configuration/SparqlConstructConfig_V1.java
2426
package com.linkedpipes.etl.convert.uv.configuration; import com.linkedpipes.etl.convert.uv.pipeline.LpPipeline; import com.thoughtworks.xstream.annotations.XStreamAlias; import java.util.ArrayList; import java.util.List; import org.openrdf.model.IRI; import org.openrdf.model.Statement; import org.openrdf.model.ValueFactory; import org.openrdf.model.impl.SimpleValueFactory; import org.openrdf.model.vocabulary.RDF; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @XStreamAlias("cz.cuni.mff.xrg.uv.transformer.sparql.construct.SparqlConstructConfig_V1") class SparqlConstructConfig_V1 implements Configuration { private static final Logger LOG = LoggerFactory.getLogger(SparqlConstructConfig_V1.class); String query = "CONSTRUCT {?s ?p ?o} WHERE {?s ?p ?o}"; boolean perGraph = true; @Override public void update(LpPipeline pipeline, LpPipeline.Component component, boolean asTemplate) { pipeline.renameInPort(component, "input", "InputRdf"); pipeline.renameOutPort(component, "output", "OutputRdf"); component.setTemplate("http://etl.linkedpipes.com/resources/components/t-sparqlConstruct/0.0.0"); final ValueFactory vf = SimpleValueFactory.getInstance(); final List<Statement> st = new ArrayList<>(); st.add(vf.createStatement( vf.createIRI("http://localhost/resources/configuration/t-sparqlConstruct"), RDF.TYPE, vf.createIRI("http://plugins.linkedpipes.com/ontology/t-sparqlConstruct#Configuration"))); st.add(vf.createStatement( vf.createIRI("http://localhost/resources/configuration/t-sparqlConstruct"), vf.createIRI("http://plugins.linkedpipes.com/ontology/t-sparqlConstruct#query"), vf.createLiteral(query))); if (perGraph) { LOG.warn("{} : Per graph mode ignored.", component); } if (asTemplate) { final IRI force = vf.createIRI( "http://plugins.linkedpipes.com/resource/configuration/Force"); st.add(vf.createStatement( vf.createIRI("http://localhost/resources/configuration/t-sparqlConstruct"), vf.createIRI("http://plugins.linkedpipes.com/ontology/t-sparqlConstruct#queryControl"), force)); } component.setLpConfiguration(st); } }
mit
branscha/lib-jsontools
src/test/java/com/sdicons/json/mapper/helper/impl/CharacterMapperTest.java
2335
/******************************************************************************* * Copyright (c) 2006-2013 Bruno Ranschaert * Released under the MIT License: http://opensource.org/licenses/MIT * Library "jsontools" ******************************************************************************/ package com.sdicons.json.mapper.helper.impl; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import com.sdicons.json.mapper.JSONMapper; import com.sdicons.json.mapper.MapperException; import com.sdicons.json.mapper.helper.CharacterMapper; import com.sdicons.json.mapper.helper.ClassMapper; import com.sdicons.json.model.JSONArray; import com.sdicons.json.model.JSONString; import com.sdicons.json.model.JSONValue; public class CharacterMapperTest { private CharacterMapper helper; private JSONMapper mapper; @Before public void init() { helper = new CharacterMapper(); mapper = new JSONMapper(new ClassMapper[]{}); } @Test public void charTest() throws MapperException { Character ch = new Character('A'); JSONValue json = helper.toJSON(mapper, ch); Assert.assertNotNull(json); Assert.assertTrue(json.isString()); // Character back = (Character) helper.toJava(mapper, json, Character.class); Assert.assertNotNull(back); Assert.assertThat(back, is(instanceOf(Character.class))); Assert.assertEquals(ch, back); } @Test(expected=MapperException.class) public void badInput2() throws MapperException { // Source JSON type cannot be converted. JSONValue json = new JSONArray(); helper.toJava(mapper, json, Character.class); } @Test(expected=MapperException.class) public void badInput3() throws MapperException { // Target class is not supported by this mapper. JSONValue json = new JSONString("B"); helper.toJava(mapper, json, Boolean.class); } @Test(expected=MapperException.class) public void badInput4() throws MapperException { // Source value cannot be converted. JSONValue json = new JSONString("aiai"); helper.toJava(mapper, json, Character.class); } }
mit
jjhesk/parallaxmotion
jmotion/jparallex/src/main/java/com/jparallex/motion/SensorInterpreter.java
3677
package com.jparallex.motion; import android.content.Context; import android.hardware.SensorEvent; import android.view.Surface; import android.view.WindowManager; public class SensorInterpreter { private static final String TAG = SensorInterpreter.class.getName(); /** * The standardized vectors corresponding to yaw, pitch, and roll. */ private float[] mVectors; /** * The sensitivity the parallax effect has towards tilting. */ private float mTiltSensitivity = 2.0f; /** * The forward tilt offset adjustment to counteract a natural forward phone tilt. */ private float mForwardTiltOffset = 0.3f; public SensorInterpreter() { mVectors = new float[3]; } /** * Converts sensor data to yaw, pitch, and roll * * @param context the context of the * @param event the event to interpret * @return and interpreted array of yaw, pitch, and roll vectors */ public final float[] interpretSensorEvent(Context context, SensorEvent event) { if (event == null || event.values.length < 3 || event.values[0] == 0 || event.values[1] == 0 || event.values[2] == 0) return null; // Acquire rotation of screen final int rotation = ((WindowManager) context .getSystemService(Context.WINDOW_SERVICE)) .getDefaultDisplay() .getRotation(); // Adjust for forward tilt based on screen orientation switch (rotation) { case Surface.ROTATION_90: mVectors[0] = event.values[0]; mVectors[1] = event.values[2]; mVectors[2] = -event.values[1]; break; case Surface.ROTATION_180: mVectors[0] = event.values[0]; mVectors[1] = event.values[1]; mVectors[2] = event.values[2]; break; case Surface.ROTATION_270: mVectors[0] = event.values[0]; mVectors[1] = -event.values[2]; mVectors[2] = event.values[1]; break; default: mVectors[0] = event.values[0]; mVectors[1] = -event.values[1]; mVectors[2] = -event.values[2]; break; } // Adjust roll for sensitivity differences based on pitch // double tiltScale = 1/Math.cos(mVectors[1] * Math.PI/180); // if (tiltScale > 12) tiltScale = 12; // if (tiltScale < -12) tiltScale = -12; // mVectors[2] *= tiltScale; // Make roll and pitch percentages out of 1 mVectors[1] /= 90; mVectors[2] /= 90; // Add in forward tilt offset mVectors[1] -= mForwardTiltOffset; if (mVectors[1] < -1) mVectors[1] += 2; // Adjust for tilt sensitivity mVectors[1] *= mTiltSensitivity; mVectors[2] *= mTiltSensitivity; // Clamp values to image bounds if (mVectors[1] > 1) mVectors[1] = 1f; if (mVectors[1] < -1) mVectors[1] = -1f; if (mVectors[2] > 1) mVectors[2] = 1f; if (mVectors[2] < -1) mVectors[2] = -1f; return mVectors; } public float getForwardTiltOffset() { return mForwardTiltOffset; } public void setForwardTiltOffset(float forwardTiltOffset) { mForwardTiltOffset = forwardTiltOffset; } public float getTiltSensitivity() { return mTiltSensitivity; } public void setTiltSensitivity(float tiltSensitivity) { mTiltSensitivity = tiltSensitivity; } }
mit
s-aska/Justaway-for-Android-Original
Justaway/src/main/java/info/justaway/widget/ScaleImageView.java
9368
package info.justaway.widget; import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Matrix; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.widget.ImageView; public class ScaleImageView extends ImageView implements OnTouchListener { static boolean sBounds = false; private Activity mActivity; private Context mContext; private static final float MAX_SCALE = 10f; private Matrix mMatrix; private final float[] mMatrixValues = new float[9]; // display width height. private int mWidth; private int mHeight; private int mIntrinsicWidth; private int mIntrinsicHeight; private float mMinScale; private float mPrevDistance; private boolean mIsScaling; private boolean mIsInitializedScaling; private int mPrevMoveX; private int mPrevMoveY; private GestureDetector mDetector; @SuppressWarnings("unused") public ScaleImageView(Context context, AttributeSet attr) { super(context, attr); mContext = context; initialize(); } public void setActivity(Activity activity) { mActivity = activity; } public ScaleImageView(Context context) { super(context); mContext = context; initialize(); } @Override public void setImageBitmap(Bitmap bm) { super.setImageBitmap(bm); initialize(); } @Override public void setImageDrawable(Drawable drawable) { super.setImageDrawable(drawable); initialize(); } @Override public void setImageResource(int resId) { super.setImageResource(resId); initialize(); } private void initialize() { setScaleType(ScaleType.MATRIX); mMatrix = new Matrix(); Drawable d = getDrawable(); if (d != null) { mIntrinsicWidth = d.getIntrinsicWidth(); mIntrinsicHeight = d.getIntrinsicHeight(); setOnTouchListener(this); } mDetector = new GestureDetector(mContext, new GestureDetector.SimpleOnGestureListener() { @Override public boolean onDoubleTap(MotionEvent e) { maxZoomTo((int) e.getX(), (int) e.getY()); cutting(); return super.onDoubleTap(e); } @Override public boolean onSingleTapUp(MotionEvent e) { if (mActivity != null) { mActivity.finish(); } return super.onSingleTapUp(e); } @Override public void onLongPress(MotionEvent e) { if (mActivity != null) { mActivity.openOptionsMenu(); } super.onLongPress(e); } }); } @Override protected boolean setFrame(int l, int t, int r, int b) { mWidth = r - l; mHeight = b - t; mMatrix.reset(); int r_norm = r - l; float scale = (float) r_norm / (float) mIntrinsicWidth; // Log.d("justaway", "[setFrame] l:" + l + " t:" + t + " r:" + r + " b:" + b + " width:" + mWidth + " height:" + mHeight + " intrinsicWidth:" + mIntrinsicWidth + " scale:" + scale); int paddingHeight; int paddingWidth; // scaling vertical if (scale * mIntrinsicHeight > mHeight) { scale = (float) mHeight / (float) mIntrinsicHeight; mMatrix.postScale(scale, scale); paddingWidth = (r - mWidth) / 2; paddingHeight = 0; // scaling horizontal } else { mMatrix.postScale(scale, scale); paddingHeight = (b - mHeight) / 2; paddingWidth = 0; } mMatrix.postTranslate(paddingWidth, paddingHeight); setImageMatrix(mMatrix); if (!mIsInitializedScaling) { mIsInitializedScaling = true; // zoomTo(scale, mWidth / 2, mHeight / 2); // Log.d("justaway", "[setFrame] mIsInitializedScaling scale:" + scale); } cutting(); boolean isChanges = super.setFrame(l, t, r, b); if (mMinScale != scale) { mMinScale = scale; isChanges = true; } return isChanges; } protected float getValue(Matrix matrix, int whichValue) { matrix.getValues(mMatrixValues); return mMatrixValues[whichValue]; } protected float getScale() { return getValue(mMatrix, Matrix.MSCALE_X); } public float getTranslateX() { return getValue(mMatrix, Matrix.MTRANS_X); } protected float getTranslateY() { return getValue(mMatrix, Matrix.MTRANS_Y); } protected void maxZoomTo(int x, int y) { if (mMinScale != getScale() && (getScale() - mMinScale) > 0.1f) { // threshold 0.1f float scale = mMinScale / getScale(); zoomTo(scale, x, y); } else { float scale = 2f / getScale(); zoomTo(scale, x, y); } } public void zoomTo(float scale, int x, int y) { if (getScale() * scale < mMinScale) { return; } if (scale >= 1 && getScale() * scale > MAX_SCALE) { return; } mMatrix.postScale(scale, scale); // move to center mMatrix.postTranslate(-(mWidth * scale - mWidth) / 2, -(mHeight * scale - mHeight) / 2); // move x and y distance mMatrix.postTranslate(-(x - (mWidth / 2)) * scale, 0); mMatrix.postTranslate(0, -(y - (mHeight / 2)) * scale); setImageMatrix(mMatrix); } public void cutting() { int width = (int) (mIntrinsicWidth * getScale()); int height = (int) (mIntrinsicHeight * getScale()); boolean bounds = false; if (getTranslateX() < -(width - mWidth)) { mMatrix.postTranslate(-(getTranslateX() + width - mWidth), 0); bounds = true; } else if (getTranslateX() == -(width - mWidth)) { bounds = true; } if (getTranslateX() > 0) { mMatrix.postTranslate(-getTranslateX(), 0); bounds = true; } else if (getTranslateX() == 0) { bounds = true; } if (getTranslateY() < -(height - mHeight)) { mMatrix.postTranslate(0, -(getTranslateY() + height - mHeight)); } if (getTranslateY() > 0) { mMatrix.postTranslate(0, -getTranslateY()); } if (width < mWidth) { mMatrix.postTranslate((mWidth - width) / 2, 0); } if (height < mHeight) { mMatrix.postTranslate(0, (mHeight - height) / 2); } sBounds = bounds; setImageMatrix(mMatrix); } private float distance(float x0, float x1, float y0, float y1) { float x = x0 - x1; float y = y0 - y1; return (float) Math.sqrt(x * x + y * y); } private float displayDistance() { return (float) Math.sqrt(mWidth * mWidth + mHeight * mHeight); } @SuppressWarnings("NullableProblems") @Override public boolean onTouchEvent(MotionEvent event) { if (event == null) { return true; } if (mDetector.onTouchEvent(event)) { return true; } int touchCount = event.getPointerCount(); int action = event.getAction() & MotionEvent.ACTION_MASK; switch (action) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_POINTER_DOWN: if (touchCount >= 2) { mPrevDistance = distance(event.getX(0), event.getX(1), event.getY(0), event.getY(1)); mIsScaling = true; } else { mPrevMoveX = (int) event.getX(); mPrevMoveY = (int) event.getY(); } case MotionEvent.ACTION_MOVE: if (touchCount >= 2 && mIsScaling) { float dist = distance(event.getX(0), event.getX(1), event.getY(0), event.getY(1)); float scale = (dist - mPrevDistance) / displayDistance(); mPrevDistance = dist; scale += 1; scale = scale * scale; zoomTo(scale, mWidth / 2, mHeight / 2); cutting(); } else { int distanceX = mPrevMoveX - (int) event.getX(); int distanceY = mPrevMoveY - (int) event.getY(); mPrevMoveX = (int) event.getX(); mPrevMoveY = (int) event.getY(); mMatrix.postTranslate(-distanceX, -distanceY); cutting(); } break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_POINTER_UP: if (event.getPointerCount() <= 1) { mIsScaling = false; } break; } return true; } @Override public boolean onTouch(View v, MotionEvent event) { return super.onTouchEvent(event); } }
mit
Jelmerro/UniCam
src/main/java/com/github/jelmerro/unicam/LoadingDialog.java
5586
package com.github.jelmerro.unicam; import com.github.sarxos.webcam.Webcam; import java.awt.Dimension; import java.awt.Toolkit; import javax.swing.JDialog; import javax.swing.JOptionPane; import javax.swing.JTextArea; /** * Dialog displayed when switching panels/settings * * @author Jelmerro */ public class LoadingDialog extends JDialog { private JTextArea log; /** * Constructor of the dialog */ public LoadingDialog() { //Call super method super(Frame.getInstance(), "Loading", ModalityType.APPLICATION_MODAL); //Set properties setResizable(false); setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE); Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); setLocation(screen.width / 2 - 125, screen.height / 2 - 100); setSize(250, 200); //Add the log log = new JTextArea(); log.setEditable(false); add(log); } /** * Shows the dialog and starts the process of switching panels/settings using the Task class * * @param webcam Object * @param res Dimension */ public void load(Object webcam, Dimension res) { Task task = new Task(webcam, res); task.start(); setVisible(true); } /** * Adds the specified string to the displayed log * * @param line String */ private void addToLog(String line) { //Adds it to the textarea and prints it in the console log.setText(log.getText() + "\n" + line); System.out.println(line); } /** * Inner class Task, responsible for the steps needed to change panels/settings */ private class Task extends Thread { Object webcam; Dimension res; /** * Constructor of a Task * * @param webcam Object * @param res Dimension */ public Task(Object webcam, Dimension res) { this.webcam = webcam; this.res = res; } /** * Thread applying the new panels/settings */ @Override public void run() { boolean error = false; //Stop the existing panel if needed if (Frame.getInstance().getPanel() != null) { addToLog("Stopping current panel"); Frame.getInstance().getPanel().stop(); } //Cast the provided object to a webcam //If it's null or not a webcam, this step will fail addToLog("Setting webcam"); Webcam selectedWebcam = null; try { selectedWebcam = (Webcam) webcam; } catch (Exception ex) { addToLog(ex.toString()); error = true; } //Continue only if the webcam is set if (selectedWebcam != null) { //Try to set the requested resolution //This step shouldn't fail under regular circumstances addToLog("Setting resolution"); try { Dimension[] array = {res}; selectedWebcam.setCustomViewSizes(array); selectedWebcam.setViewSize(res); } catch (Exception ex) { addToLog(ex.toString()); error = true; } //Try to create the new panel //If another panel is using the webcam and is frozen, this step will fail addToLog("Creating webcam panel"); try { ViewPanel panel = new ViewPanel(selectedWebcam); addToLog("Building panel"); panel.setFPSDisplayed(true); Frame.getInstance().setPanel(panel); panel.updateUI(); } catch (Exception ex) { addToLog(ex.toString()); error = true; } //If all went well, dispose the LoadingDialog and show a message if the resolution had to be changed //Else make the LoadingDialog wider, show the exception and allow closing of the dialog if (!error) { dispose(); addToLog("Done"); if (!res.equals(Frame.getInstance().getPanel().getPreferredSize()) && !(res.getHeight() == 10000 && res.getWidth() == 10000)) { Dimension panelSize = Frame.getInstance().getPanel().getPreferredSize(); Frame.getInstance().getPanel().drawMessage("Different resolution: " + (int) panelSize.getWidth() + "x" + (int) panelSize.getHeight() + " instead of " + (int) res.getWidth() + "x" + (int) res.getHeight()); } } else { setResizable(true); Dimension screen = Toolkit.getDefaultToolkit().getScreenSize(); setLocation(screen.width / 2 - 250, screen.height / 2 - 100); setSize(500, 200); addToLog("You can close this window once you're done here"); setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); } } else { //Close the LoadingDialog if no webcam was found/selected dispose(); addToLog("No webcam available"); JOptionPane.showMessageDialog(null, "No usable webcam could be found", "Webcam warning", JOptionPane.WARNING_MESSAGE); } } } }
mit
Vovas11/courses
src/main/java/com/devproserv/courses/jooq/tables/Courses.java
4839
/* * This file is generated by jOOQ. */ package com.devproserv.courses.jooq.tables; import com.devproserv.courses.jooq.Coursedb; import com.devproserv.courses.jooq.Indexes; import com.devproserv.courses.jooq.Keys; import com.devproserv.courses.jooq.tables.records.CoursesRecord; import java.util.Arrays; import java.util.List; import javax.annotation.Generated; import org.jooq.Field; import org.jooq.ForeignKey; import org.jooq.Identity; import org.jooq.Index; import org.jooq.Name; import org.jooq.Record; import org.jooq.Schema; import org.jooq.Table; import org.jooq.TableField; import org.jooq.UniqueKey; import org.jooq.impl.DSL; import org.jooq.impl.TableImpl; /** * This class is generated by jOOQ. */ @Generated( value = { "http://www.jooq.org", "jOOQ version:3.11.7" }, comments = "This class is generated by jOOQ" ) @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class Courses extends TableImpl<CoursesRecord> { private static final long serialVersionUID = 564979766; /** * The reference instance of <code>coursedb.courses</code> */ public static final Courses COURSES = new Courses(); /** * The class holding records for this type */ @Override public Class<CoursesRecord> getRecordType() { return CoursesRecord.class; } /** * The column <code>coursedb.courses.course_id</code>. */ public final TableField<CoursesRecord, Integer> COURSE_ID = createField("course_id", org.jooq.impl.SQLDataType.INTEGER.nullable(false).identity(true), this, ""); /** * The column <code>coursedb.courses.name</code>. */ public final TableField<CoursesRecord, String> NAME = createField("name", org.jooq.impl.SQLDataType.VARCHAR(20).nullable(false), this, ""); /** * The column <code>coursedb.courses.description</code>. */ public final TableField<CoursesRecord, String> DESCRIPTION = createField("description", org.jooq.impl.SQLDataType.VARCHAR(40), this, ""); /** * The column <code>coursedb.courses.lect_id</code>. */ public final TableField<CoursesRecord, Integer> LECT_ID = createField("lect_id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, ""); /** * Create a <code>coursedb.courses</code> table reference */ public Courses() { this(DSL.name("courses"), null); } /** * Create an aliased <code>coursedb.courses</code> table reference */ public Courses(String alias) { this(DSL.name(alias), COURSES); } /** * Create an aliased <code>coursedb.courses</code> table reference */ public Courses(Name alias) { this(alias, COURSES); } private Courses(Name alias, Table<CoursesRecord> aliased) { this(alias, aliased, null); } private Courses(Name alias, Table<CoursesRecord> aliased, Field<?>[] parameters) { super(alias, null, aliased, parameters, DSL.comment("")); } public <O extends Record> Courses(Table<O> child, ForeignKey<O, CoursesRecord> key) { super(child, key, COURSES); } /** * {@inheritDoc} */ @Override public Schema getSchema() { return Coursedb.COURSEDB; } /** * {@inheritDoc} */ @Override public List<Index> getIndexes() { return Arrays.<Index>asList(Indexes.COURSES_FK_COURSES_LECTURERS1_IDX, Indexes.COURSES_PRIMARY); } /** * {@inheritDoc} */ @Override public Identity<CoursesRecord, Integer> getIdentity() { return Keys.IDENTITY_COURSES; } /** * {@inheritDoc} */ @Override public UniqueKey<CoursesRecord> getPrimaryKey() { return Keys.KEY_COURSES_PRIMARY; } /** * {@inheritDoc} */ @Override public List<UniqueKey<CoursesRecord>> getKeys() { return Arrays.<UniqueKey<CoursesRecord>>asList(Keys.KEY_COURSES_PRIMARY); } /** * {@inheritDoc} */ @Override public List<ForeignKey<CoursesRecord, ?>> getReferences() { return Arrays.<ForeignKey<CoursesRecord, ?>>asList(Keys.FK_COURSES_LECTURERS1); } public Lecturers lecturers() { return new Lecturers(this, Keys.FK_COURSES_LECTURERS1); } /** * {@inheritDoc} */ @Override public Courses as(String alias) { return new Courses(DSL.name(alias), this); } /** * {@inheritDoc} */ @Override public Courses as(Name alias) { return new Courses(alias, this); } /** * Rename this table */ @Override public Courses rename(String name) { return new Courses(DSL.name(name), null); } /** * Rename this table */ @Override public Courses rename(Name name) { return new Courses(name, null); } }
mit
Codealike/Codealike-Android
app/src/main/java/com/codealike/android/activities/util/SystemUiHiderHoneycomb.java
4996
package com.codealike.android.activities.util; import android.annotation.TargetApi; import android.app.Activity; import android.os.Build; import android.view.View; import android.view.WindowManager; /** * An API 11+ implementation of {@link SystemUiHider}. Uses APIs available in * Honeycomb and later (specifically {@link View#setSystemUiVisibility(int)}) to * show and hide the system UI. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public class SystemUiHiderHoneycomb extends SystemUiHiderBase { /** * Flags for {@link View#setSystemUiVisibility(int)} to use when showing the * system UI. */ private int mShowFlags; /** * Flags for {@link View#setSystemUiVisibility(int)} to use when hiding the * system UI. */ private int mHideFlags; /** * Flags to test against the first parameter in * {@link android.view.View.OnSystemUiVisibilityChangeListener#onSystemUiVisibilityChange(int)} * to determine the system UI visibility state. */ private int mTestFlags; /** * Whether or not the system UI is currently visible. This is cached from * {@link android.view.View.OnSystemUiVisibilityChangeListener}. */ private boolean mVisible = true; /** * Constructor not intended to be called by clients. Use * {@link SystemUiHider#getInstance} to obtain an instance. */ protected SystemUiHiderHoneycomb(Activity activity, View anchorView, int flags) { super(activity, anchorView, flags); mShowFlags = View.SYSTEM_UI_FLAG_VISIBLE; mHideFlags = View.SYSTEM_UI_FLAG_LOW_PROFILE; mTestFlags = View.SYSTEM_UI_FLAG_LOW_PROFILE; if ((mFlags & FLAG_FULLSCREEN) != 0) { // If the client requested fullscreen, add flags relevant to hiding // the status bar. Note that some of these constants are new as of // API 16 (Jelly Bean). It is safe to use them, as they are inlined // at compile-time and do nothing on pre-Jelly Bean devices. mShowFlags |= View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; mHideFlags |= View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_FULLSCREEN; } if ((mFlags & FLAG_HIDE_NAVIGATION) != 0) { // If the client requested hiding navigation, add relevant flags. mShowFlags |= View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION; mHideFlags |= View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION; mTestFlags |= View.SYSTEM_UI_FLAG_HIDE_NAVIGATION; } } /** * {@inheritDoc} */ @Override public void setup() { mAnchorView.setOnSystemUiVisibilityChangeListener(mSystemUiVisibilityChangeListener); } /** * {@inheritDoc} */ @Override public void hide() { mAnchorView.setSystemUiVisibility(mHideFlags); } /** * {@inheritDoc} */ @Override public void show() { mAnchorView.setSystemUiVisibility(mShowFlags); } /** * {@inheritDoc} */ @Override public boolean isVisible() { return mVisible; } private View.OnSystemUiVisibilityChangeListener mSystemUiVisibilityChangeListener = new View.OnSystemUiVisibilityChangeListener() { @Override public void onSystemUiVisibilityChange(int vis) { // Test against mTestFlags to see if the system UI is visible. if ((vis & mTestFlags) != 0) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { // Pre-Jelly Bean, we must manually hide the action bar // and use the old window flags API. mActivity.getActionBar().hide(); mActivity.getWindow().setFlags( WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); } // Trigger the registered listener and cache the visibility // state. mOnVisibilityChangeListener.onVisibilityChange(false); mVisible = false; } else { mAnchorView.setSystemUiVisibility(mShowFlags); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { // Pre-Jelly Bean, we must manually show the action bar // and use the old window flags API. mActivity.getActionBar().show(); mActivity.getWindow().setFlags( 0, WindowManager.LayoutParams.FLAG_FULLSCREEN); } // Trigger the registered listener and cache the visibility // state. mOnVisibilityChangeListener.onVisibilityChange(true); mVisible = true; } } }; }
mit
ai-ku/langvis
src/edu/cmu/cs/stage3/alice/core/visualization/ListOfModelsVisualization.java
140
package edu.cmu.cs.stage3.alice.core.visualization; public class ListOfModelsVisualization extends CollectionOfModelsVisualization { }
mit
guillaume-gouchon/dungeonhero
android/app/src/main/java/com/glevel/dungeonhero/models/dungeons/decorations/Stairs.java
1260
package com.glevel.dungeonhero.models.dungeons.decorations; import com.glevel.dungeonhero.game.graphics.StairsSprite; import com.glevel.dungeonhero.models.dungeons.Tile; import org.andengine.opengl.vbo.VertexBufferObjectManager; /** * Created by guillaume on 10/16/14. */ public class Stairs extends Decoration { private static final long serialVersionUID = 7188693630132735199L; private final boolean isDownStairs; public Stairs(boolean isDownStairs) { super(isDownStairs ? "exit_stairs" : "entrance_stairs", 32, 20, 2, 1); this.isDownStairs = isDownStairs; } @Override public String getSpriteName() { return "stairs.png"; } @Override public void setTilePosition(Tile tilePosition) { if (this.tilePosition != null) { this.tilePosition.getSubContent().remove(this); } this.tilePosition = tilePosition; if (tilePosition != null) { tilePosition.getSubContent().add(this); } } @Override public void createSprite(VertexBufferObjectManager vertexBufferObjectManager) { sprite = new StairsSprite(this, vertexBufferObjectManager); } public boolean isDownStairs() { return isDownStairs; } }
mit
tilastokeskus/Matertis
Matertis/src/main/java/com/github/tilastokeskus/matertis/core/Game.java
6720
package com.github.tilastokeskus.matertis.core; import com.github.tilastokeskus.matertis.audio.AudioManager; import com.github.tilastokeskus.matertis.util.TetrominoFactory; /** * Provides the necessary logic to play the game. * <p> * This class holds information of the game's state and provides basic * functionality to retrieve that information, and to play a round of the game. * <p> * In this case a "round" is a collection of events which includes moving the * falling tetromino down by one row, and, in the case that the tetromino has * hit the ground, spawning a new falling tetromino. The falling tetromino may * be moved left, right or down, or dropped, without disturbing the flow of the * game, though such actions must be done externally: this class provides no * functionality to capture user commands. * <p> * The game area consists of two sections: the game area and the spawn area. The * game area is where tetrominoes will be stacked. The spawn area is an area on * top of the game area, where new tetrominoes spawn and start falling. If * tetrominoes are stacked so high on the game area that a piece of some * tetromino is partially in the spawn area, the game is considered over. * <p> * Sound effects are invoked by this class. * * @author tilastokeskus */ public class Game { protected final GameGrid grid; protected Tetromino fallingTetromino; protected Tetromino nextTetromino; protected boolean isGameOver; /** * Constructs a game with the given width and height of the game area. * Additionally, a spawn area of a fixed size will be added on top of the * game area. The final width and height will be defined by the * {@link GameGrid} class. * * @param width the width of the game area. * @param height the height of the game area. */ public Game(int width, int height) { this.grid = new GameGrid(width, height); this.isGameOver = false; this.spawnFirstTetromino(); } private void spawnFirstTetromino() { this.nextTetromino = TetrominoFactory.getRandomTetromino(); int midX = getWidth() / 2 - nextTetromino.getSize() / 2; nextTetromino.setX(midX); this.spawnNewTetromino(); } /** * Moves the falling tetromino down by one row, and, if it then collides * with the ground, spawns a new tetromino that starts falling. This method * also checks if the fallen tetromino is overflowing from the top of the * game area, in which case the game is considered over. * * @return amount of rows cleared during this round. */ public int playRound() { int clearedRows = 0; boolean canMoveDown = this.moveFallingTetromino(Direction.DOWN); if (!canMoveDown) { this.handleFallenTetromino(); clearedRows = grid.handleFilledRows(); if (clearedRows > 0) { AudioManager.playSound(AudioManager.SOUND_CLEAR_ROW); } else { AudioManager.playSound(AudioManager.SOUND_DROP_PIECE); } } return clearedRows; } /** * Tells whether or not the game is over. * * @return true if the game is over, otherwise false. */ public boolean isGameOver() { return this.isGameOver; } /** * Returns the tetromino that is currently falling. * * @return the currently falling tetromino. */ public Tetromino getFallingTetromino() { return this.fallingTetromino; } /** * Returns the tetromino that will start falling after the current one. * * @return the next tetromino to start falling. */ public Tetromino getNextTetromino() { return this.nextTetromino; } /** * The grid object holding information of the current situation of the game. * * @return a grid. */ public GameGrid getGrid() { return this.grid; } public int getWidth() { return this.grid.getWidth(); } public int getHeight() { return this.grid.getHeight(); } /** * Tries to move the currently falling tetromino to the specified direction. * If the tetromino would collide with something on the board, or if it * would go out of bounds, the tetromino won't be moved. * * @param direction the direction in which the tetromino should be moved. * @return true if the tetromino was moved, otherwise false. */ public boolean moveFallingTetromino(Direction direction) { boolean tetrominoWasMoved = true; fallingTetromino.move(direction); if (grid.tetrominoCollides(fallingTetromino)) { fallingTetromino.move(direction.getOpposite()); tetrominoWasMoved = false; } return tetrominoWasMoved; } /** * Moves the currently falling tetromino down until it hits the ground. * * @return amount of rows cleared as the result of this call. */ public int dropFallingTetromino() { boolean hasNotHitGround; do { hasNotHitGround = this.moveFallingTetromino(Direction.DOWN); } while (hasNotHitGround); return this.playRound(); } /** * Tries to rotate the currently falling tetromino clockwise. If the * tetromino would collide with something on the game area, or if it would * go out of bounds, it won't be rotated. * * @return true if the tetromino was rotated, otherwise false. */ public boolean rotateFallingTetromino() { boolean tetrominoWasRotated = true; fallingTetromino.rotateCW(); /* if the tetromino is rotated into a bad position, rotate it back */ if (grid.tetrominoCollides(fallingTetromino)) { fallingTetromino.rotateCCW(); tetrominoWasRotated = false; } return tetrominoWasRotated; } private void handleFallenTetromino() { grid.setTetromino(fallingTetromino); if (fallingTetromino.getY() < 4) { this.isGameOver = true; AudioManager.playSound(AudioManager.SOUND_GAME_OVER); } else { this.spawnNewTetromino(); } } private void spawnNewTetromino() { fallingTetromino = nextTetromino; nextTetromino = TetrominoFactory.getRandomTetromino(); int midX = getWidth() / 2 - nextTetromino.getSize() / 2; nextTetromino.setX(midX); } }
mit
Harha/LD32
src/to/us/harha/ld32/core/util/ResourceUtils.java
2331
package to.us.harha.ld32.core.util; import to.us.harha.ld32.gfx.Font; import to.us.harha.ld32.gfx.Sprite; import to.us.harha.ld32.gfx.SpriteSheet; public class ResourceUtils { public static final LogUtils g_logger = new LogUtils(ResourceUtils.class.getName()); // Spritesheets public static SpriteSheet g_sh_menu; public static SpriteSheet g_sh_font_main_320x54; public static SpriteSheet g_sh_font_main_320x48; public static SpriteSheet g_sh_font_main_320x500; public static SpriteSheet g_sh_level; // Sprites public static Sprite g_sp_menu_button_0_off; public static Sprite g_sp_menu_button_0_on; public static Sprite g_sp_menu_field_0_off; public static Sprite g_sp_menu_field_0_on; // Sprite arrays public static Sprite[] g_fc_font_main_320x54; public static Sprite[] g_fc_font_main_320x48; public static Sprite[] g_fc_font_main_320x500; public static Sprite[] g_sa_level; // Fonts public static Font g_font_main_320x54; public static Font g_font_main_320x48; public static Font g_font_main_320x500; public static void load() { g_logger.printMsg("Loading resources..."); // Spritesheets g_sh_menu = new SpriteSheet("spritesheets/sh_menu.png"); g_sh_font_main_320x54 = new SpriteSheet("fonts/font_main_320x54.png"); g_sh_font_main_320x48 = new SpriteSheet("fonts/font_main_320x48.png"); g_sh_font_main_320x500 = new SpriteSheet("fonts/font_main_320x500.png"); g_sh_level = new SpriteSheet("spritesheets/sh_level.png"); // Sprites g_sp_menu_button_0_off = new Sprite(32, 32, 0, 0, 16, 16, g_sh_menu); g_sp_menu_button_0_on = new Sprite(32, 32, 2, 0, 16, 16, g_sh_menu); g_sp_menu_field_0_off = new Sprite(32, 32, 0, 3, 16, 16, g_sh_menu); g_sp_menu_field_0_on = new Sprite(32, 32, 2, 3, 16, 16, g_sh_menu); // Sprite Arrays g_fc_font_main_320x54 = g_sh_font_main_320x54.extractToSpriteArray(16, 18); g_fc_font_main_320x48 = g_sh_font_main_320x48.extractToSpriteArray(16, 16); g_fc_font_main_320x500 = g_sh_font_main_320x500.extractToSpriteArray(64, 50); g_sa_level = g_sh_level.extractToSpriteArray(16, 16); // Fonts g_font_main_320x54 = new Font(0, 16, 18); g_font_main_320x48 = new Font(1, 16, 16); g_font_main_320x500 = new Font(2, 64, 50); } }
mit
pphdsny/ArithmeticTest
src/pp/arithmetic/leetcode/_39_combinationSum.java
3236
package pp.arithmetic.leetcode; import pp.arithmetic.Util; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; /** * Created by wangpeng on 2019-05-20. * 39. 组合总和 * <p> * 给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。 * <p> * candidates 中的数字可以无限制重复被选取。 * <p> * 说明: * <p> * 所有数字(包括 target)都是正整数。 * 解集不能包含重复的组合。 * 示例 1: * <p> * 输入: candidates = [2,3,6,7], target = 7, * 所求解集为: * [ * [7], * [2,2,3] * ] * 示例 2: * <p> * 输入: candidates = [2,3,5], target = 8, * 所求解集为: * [ * [2,2,2,2], * [2,3,3], * [3,5] * ] * * @see <a href="https://leetcode-cn.com/problems/combination-sum/">combination-sum</a> */ public class _39_combinationSum { public static void main(String[] args) { _39_combinationSum combinationSum = new _39_combinationSum(); // List<List<Integer>> lists = combinationSum.combinationSum(new int[]{1,2}, 2); List<List<Integer>> lists = combinationSum.combinationSum(new int[]{2, 3, 5}, 8); for (int i = 0; i < lists.size(); i++) { Util.printList(lists.get(i)); } } /** * 解题思路: * 1.先对数组进行排序 * 2.循环数组,从第0位开始取数,不断叠加直到(c[i]/target的除数) * 3.如 == target,则保存下来 * 4.如 > target,则--当前数的个数,循环步骤2 * 5.如 < target,则取下一位 * * @param candidates * @param target * @return */ public List<List<Integer>> combinationSum(int[] candidates, int target) { List<List<Integer>> retList = new ArrayList<>(); //排序 Arrays.sort(candidates); //递归循环 combinationSum(candidates, target, 0, retList, new ArrayList<>(), 0); return retList; } private void combinationSum(int[] candidates, int target, int index, List<List<Integer>> retList, List<Integer> addList, int addSum) { if (index >= candidates.length) return; int n = (target - addSum) / candidates[index]; if (n == 0) return; //全部添加到队列中 for (int i = 0; i <= n; i++) { addList.add(candidates[index]); } int nSum = (n+1) * candidates[index]; for (int i = n; i >= 0; i--) { //每次减-后,更新sum和list nSum -= candidates[index]; addList.remove(addList.size() - 1); if (nSum + addSum == target) { //等于,添加到队列中 retList.add(new ArrayList<>(addList)); } else if (nSum + addSum > target) { //大于,--i } else { //小于,向后取数 combinationSum(candidates, target, index + 1, retList, addList, addSum + nSum); } } } }
mit
jaamal/overclocking
sources/Trees/src/cartesianTree/heapKeyResolvers/RandomHeapKeyResolverFactory.java
479
package cartesianTree.heapKeyResolvers; public class RandomHeapKeyResolverFactory implements IHeapKeyResolverFactory { private IRandomGeneratorFactory randomGeneratorFactory; public RandomHeapKeyResolverFactory(IRandomGeneratorFactory randomGeneratorFactory) { this.randomGeneratorFactory = randomGeneratorFactory; } @Override public IHeapKeyResolver create() { return new RandomHeapKeyResolver(randomGeneratorFactory); } }
mit
flyzsd/java-code-snippets
ibm.jdk8/src/java/awt/print/PageFormat.java
10396
/*=========================================================================== * Licensed Materials - Property of IBM * "Restricted Materials of IBM" * * IBM SDK, Java(tm) Technology Edition, v8 * (C) Copyright IBM Corp. 1997, 2013. All Rights Reserved * * US Government Users Restricted Rights - Use, duplication or disclosure * restricted by GSA ADP Schedule Contract with IBM Corp. *=========================================================================== */ /* * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package java.awt.print; import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.lang.annotation.Native; /** * The <code>PageFormat</code> class describes the size and * orientation of a page to be printed. */ public class PageFormat implements Cloneable { /* Class Constants */ /** * The origin is at the bottom left of the paper with * x running bottom to top and y running left to right. * Note that this is not the Macintosh landscape but * is the Window's and PostScript landscape. */ @Native public static final int LANDSCAPE = 0; /** * The origin is at the top left of the paper with * x running to the right and y running down the * paper. */ @Native public static final int PORTRAIT = 1; /** * The origin is at the top right of the paper with x * running top to bottom and y running right to left. * Note that this is the Macintosh landscape. */ @Native public static final int REVERSE_LANDSCAPE = 2; /* Instance Variables */ /** * A description of the physical piece of paper. */ private Paper mPaper; /** * The orientation of the current page. This will be * one of the constants: PORTRIAT, LANDSCAPE, or * REVERSE_LANDSCAPE, */ private int mOrientation = PORTRAIT; /* Constructors */ /** * Creates a default, portrait-oriented * <code>PageFormat</code>. */ public PageFormat() { mPaper = new Paper(); } /* Instance Methods */ /** * Makes a copy of this <code>PageFormat</code> with the same * contents as this <code>PageFormat</code>. * @return a copy of this <code>PageFormat</code>. */ public Object clone() { PageFormat newPage; try { newPage = (PageFormat) super.clone(); newPage.mPaper = (Paper)mPaper.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); newPage = null; // should never happen. } return newPage; } /** * Returns the width, in 1/72nds of an inch, of the page. * This method takes into account the orientation of the * page when determining the width. * @return the width of the page. */ public double getWidth() { double width; int orientation = getOrientation(); if (orientation == PORTRAIT) { width = mPaper.getWidth(); } else { width = mPaper.getHeight(); } return width; } /** * Returns the height, in 1/72nds of an inch, of the page. * This method takes into account the orientation of the * page when determining the height. * @return the height of the page. */ public double getHeight() { double height; int orientation = getOrientation(); if (orientation == PORTRAIT) { height = mPaper.getHeight(); } else { height = mPaper.getWidth(); } return height; } /** * Returns the x coordinate of the upper left point of the * imageable area of the <code>Paper</code> object * associated with this <code>PageFormat</code>. * This method takes into account the * orientation of the page. * @return the x coordinate of the upper left point of the * imageable area of the <code>Paper</code> object * associated with this <code>PageFormat</code>. */ public double getImageableX() { double x; switch (getOrientation()) { case LANDSCAPE: x = mPaper.getHeight() - (mPaper.getImageableY() + mPaper.getImageableHeight()); break; case PORTRAIT: x = mPaper.getImageableX(); break; case REVERSE_LANDSCAPE: x = mPaper.getImageableY(); break; default: /* This should never happen since it signifies that the * PageFormat is in an invalid orientation. */ throw new InternalError("unrecognized orientation"); } return x; } /** * Returns the y coordinate of the upper left point of the * imageable area of the <code>Paper</code> object * associated with this <code>PageFormat</code>. * This method takes into account the * orientation of the page. * @return the y coordinate of the upper left point of the * imageable area of the <code>Paper</code> object * associated with this <code>PageFormat</code>. */ public double getImageableY() { double y; switch (getOrientation()) { case LANDSCAPE: y = mPaper.getImageableX(); break; case PORTRAIT: y = mPaper.getImageableY(); break; case REVERSE_LANDSCAPE: y = mPaper.getWidth() - (mPaper.getImageableX() + mPaper.getImageableWidth()); break; default: /* This should never happen since it signifies that the * PageFormat is in an invalid orientation. */ throw new InternalError("unrecognized orientation"); } return y; } /** * Returns the width, in 1/72nds of an inch, of the imageable * area of the page. This method takes into account the orientation * of the page. * @return the width of the page. */ public double getImageableWidth() { double width; if (getOrientation() == PORTRAIT) { width = mPaper.getImageableWidth(); } else { width = mPaper.getImageableHeight(); } return width; } /** * Return the height, in 1/72nds of an inch, of the imageable * area of the page. This method takes into account the orientation * of the page. * @return the height of the page. */ public double getImageableHeight() { double height; if (getOrientation() == PORTRAIT) { height = mPaper.getImageableHeight(); } else { height = mPaper.getImageableWidth(); } return height; } /** * Returns a copy of the {@link Paper} object associated * with this <code>PageFormat</code>. Changes made to the * <code>Paper</code> object returned from this method do not * affect the <code>Paper</code> object of this * <code>PageFormat</code>. To update the <code>Paper</code> * object of this <code>PageFormat</code>, create a new * <code>Paper</code> object and set it into this * <code>PageFormat</code> by using the {@link #setPaper(Paper)} * method. * @return a copy of the <code>Paper</code> object associated * with this <code>PageFormat</code>. * @see #setPaper */ public Paper getPaper() { return (Paper)mPaper.clone(); } /** * Sets the <code>Paper</code> object for this * <code>PageFormat</code>. * @param paper the <code>Paper</code> object to which to set * the <code>Paper</code> object for this <code>PageFormat</code>. * @exception NullPointerException * a null paper instance was passed as a parameter. * @see #getPaper */ public void setPaper(Paper paper) { mPaper = (Paper)paper.clone(); } /** * Sets the page orientation. <code>orientation</code> must be * one of the constants: PORTRAIT, LANDSCAPE, * or REVERSE_LANDSCAPE. * @param orientation the new orientation for the page * @throws IllegalArgumentException if * an unknown orientation was requested * @see #getOrientation */ public void setOrientation(int orientation) throws IllegalArgumentException { if (0 <= orientation && orientation <= REVERSE_LANDSCAPE) { mOrientation = orientation; } else { throw new IllegalArgumentException(); } } /** * Returns the orientation of this <code>PageFormat</code>. * @return this <code>PageFormat</code> object's orientation. * @see #setOrientation */ public int getOrientation() { return mOrientation; } /** * Returns a transformation matrix that translates user * space rendering to the requested orientation * of the page. The values are placed into the * array as * {&nbsp;m00,&nbsp;m10,&nbsp;m01,&nbsp;m11,&nbsp;m02,&nbsp;m12} in * the form required by the {@link AffineTransform} * constructor. * @return the matrix used to translate user space rendering * to the orientation of the page. * @see java.awt.geom.AffineTransform */ public double[] getMatrix() { double[] matrix = new double[6]; switch (mOrientation) { case LANDSCAPE: matrix[0] = 0; matrix[1] = -1; matrix[2] = 1; matrix[3] = 0; matrix[4] = 0; matrix[5] = mPaper.getHeight(); break; case PORTRAIT: matrix[0] = 1; matrix[1] = 0; matrix[2] = 0; matrix[3] = 1; matrix[4] = 0; matrix[5] = 0; break; case REVERSE_LANDSCAPE: matrix[0] = 0; matrix[1] = 1; matrix[2] = -1; matrix[3] = 0; matrix[4] = mPaper.getWidth(); matrix[5] = 0; break; default: throw new IllegalArgumentException(); } return matrix; } }
mit
schophil/census
server/src/main/java/lb/census/record/metrics/SourceIpCollector.java
400
package lb.census.record.metrics; import lb.census.record.log.LogRecord; import java.util.HashSet; /** * */ public class SourceIpCollector implements MetricsCollector { private HashSet<String> ips = new HashSet<>(); @Override public void add(LogRecord logRecord) { ips.add(logRecord.getSourceIp()); } public HashSet<String> getIps() { return ips; } }
mit
yuweijun/learning-programming
quartz/src/main/java/com/example/quartz/example7/DumbInterruptableJob.java
3495
/* * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * */ package com.example.quartz.example7; import org.quartz.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Date; /** * <p> * A dumb implementation of an InterruptableJob, for unit testing purposes. * </p> * * @author <a href="mailto:bonhamcm@thirdeyeconsulting.com">Chris Bonham</a> * @author Bill Kratzer */ public class DumbInterruptableJob implements InterruptableJob { // logging services private static Logger _log = LoggerFactory.getLogger(DumbInterruptableJob.class); // has the job been interrupted? private boolean _interrupted = false; // job name private JobKey _jobKey = null; /** * <p> * Empty constructor for job initialization * </p> */ public DumbInterruptableJob() { } /** * <p> * Called by the <code>{@link org.quartz.Scheduler}</code> when a <code>{@link org.quartz.Trigger}</code> * fires that is associated with the <code>Job</code>. * </p> * * @throws JobExecutionException * if there is an exception while executing the job. */ public void execute(JobExecutionContext context) throws JobExecutionException { _jobKey = context.getJobDetail().getKey(); _log.info("---- " + _jobKey + " executing at " + new Date()); try { // main job loop... see the JavaDOC for InterruptableJob for discussion... // do some work... in this example we are 'simulating' work by sleeping... :) for (int i = 0; i < 4; i++) { try { Thread.sleep(1000L); } catch (Exception ignore) { ignore.printStackTrace(); } // periodically check if we've been interrupted... if(_interrupted) { _log.info("--- " + _jobKey + " -- Interrupted... bailing out!"); return; // could also choose to throw a JobExecutionException // if that made for sense based on the particular // job's responsibilities/behaviors } } } finally { _log.info("---- " + _jobKey + " completed at " + new Date()); } } /** * <p> * Called by the <code>{@link Scheduler}</code> when a user * interrupts the <code>Job</code>. * </p> * * @return void (nothing) if job interrupt is successful. * @throws JobExecutionException * if there is an exception while interrupting the job. */ public void interrupt() throws UnableToInterruptJobException { _log.info("---" + _jobKey + " -- INTERRUPTING --"); _interrupted = true; } }
mit