repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
moiseslorap/RIT
Computer Science 2/Lab3/src/PriorityQueue.java
585
/** * Name: Moisés Lora Pérez * Email: mal3941@rit.edu * Class: CSCI-142 Professor Strout * Language: Java 8 */ public interface PriorityQueue<T extends Prioritizable> { /** * Is there anything in the queue * * @return queue is empty. */ boolean isEmpty(); /** * Add an item to the queue (at the appropriate location) * * @param toInsert Item to be added */ void insert(T toInsert); /** * Removes and returns the item at the front of the queue. * * @return Removed element */ T dequeue(); }
mit
treytomes/dwarf-craft
src/main/java/org/treytomes/dwarfCraft/block/BlockRegistry.java
4570
package org.treytomes.dwarfCraft.block; import org.treytomes.dwarfCraft.block.deployer.DeployerBehaviorRegistry; import org.treytomes.dwarfCraft.lib.EnumSide; import org.treytomes.dwarfCraft.lib.LogHelper; import scala.collection.Seq; import codechicken.microblock.BlockMicroMaterial; import codechicken.microblock.MicroMaterialRegistry; import cpw.mods.fml.common.registry.GameData; import cpw.mods.fml.common.registry.GameRegistry; import cpw.mods.fml.common.registry.LanguageRegistry; import net.minecraft.block.Block; import net.minecraft.block.BlockPistonBase; import net.minecraft.block.BlockSlab; import net.minecraft.dispenser.IBlockSource; import net.minecraft.dispenser.IPosition; import net.minecraft.dispenser.PositionImpl; import net.minecraft.entity.EntityLivingBase; import net.minecraft.init.Blocks; import net.minecraft.item.Item; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemSlab; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumFacing; import net.minecraft.util.MathHelper; import net.minecraft.world.World; public class BlockRegistry { public static Block packedEarth; public static Block tomatoCrops; public static Block ironFurnace; public static Block ironFurnaceLit; public static Block workbench; public static Block deployer; public static void register() { LogHelper.info("Begin registering blocks."); packedEarth = new BlockPackedEarth(); tomatoCrops = new BlockTomatoCrops(); ironFurnace = new BlockIronFurnace(false); ironFurnaceLit = new BlockIronFurnace(true); workbench = new BlockWorkbench(); deployer = new BlockDeployer(); register(packedEarth); register(tomatoCrops); register(ironFurnace); register(ironFurnaceLit); register(workbench); register(deployer); registerMultipart(packedEarth, 0); DeployerBehaviorRegistry.register(); LogHelper.info("Block registration complete."); } private static void registerMultipartMetadataLine(Block block, int maxMeta) { for (int i = 0; i < maxMeta; i++) { registerMultipart(block, i); } } private static void registerMultipart(Block block, int meta) { MicroMaterialRegistry.registerMaterial(new BlockMicroMaterial(block, meta), block.getUnlocalizedName() + (meta == 0 ? "" : "_" + meta)); } private static Block find(String blockName) { return GameData.getBlockRegistry().getObject(blockName); } private static Block register(Block block) { return register(block, block.getUnlocalizedName()); } private static Block register(Block block, String key) { LogHelper.info("Registering ''{0}''.", block.getLocalizedName()); return GameRegistry.registerBlock(block, key); } private static Block register(Block block, Class<? extends ItemBlock> itemBlockClass, String key) { LogHelper.info("Registering ''{0}''.", block.getLocalizedName()); return GameRegistry.registerBlock(block, itemBlockClass, key); } public static int determineOrientation(World world, int x, int y, int z, EntityLivingBase target, boolean allowVerticalOrientation) { if (allowVerticalOrientation) { return BlockPistonBase.determineOrientation(world, x, y, z, target); } int rotationQuadrant = MathHelper.floor_double((double)(target.rotationYaw * 4.0f / 360.0f) + 0.5d) & 3; switch (rotationQuadrant) { case 0: return EnumSide.NORTH.value; case 1: return EnumSide.WEST.value; case 2: return EnumSide.SOUTH.value; case 3: return EnumSide.EAST.value; default: return EnumSide.SOUTH.value; } } public static EnumFacing getFacing(int metadata) { // Do the lowest 3 bits of metadata always give the block facing? return EnumFacing.getFront(metadata & 7); } public static boolean isPowered(World world, int x, int y, int z) { return (world.getBlockMetadata(x, y, z) & 8) != 0; } /** * Get the position that this block is pointing towards. * * @param block The block being queried. * @return The position that this block is pointing towards. */ public static IPosition getPositionFromBlock(IBlockSource block) { EnumFacing facing = getFacing(block.getBlockMetadata()); double facingX = block.getX() + 0.7d * (double)facing.getFrontOffsetX(); double facingY = block.getY() + 0.7d * (double)facing.getFrontOffsetY(); double facingZ = block.getZ() + 0.7d * (double)facing.getFrontOffsetZ(); return new PositionImpl(facingX, facingY, facingZ); } }
mit
GeBeater/dozer-jdk8-support
src/test/java/io/craftsman/creator/PeriodCreatorTest.java
525
package io.craftsman.creator; import org.junit.Before; import org.junit.Test; import java.time.Period; import static org.junit.Assert.assertEquals; public class PeriodCreatorTest { private PeriodCreator objectUnderTest; @Before public void setUp() { objectUnderTest = new PeriodCreator(); } @Test public void testCreate() { Period period = Period.of(2015, 11, 8); Period actualPeriod = objectUnderTest.create(period); assertEquals(period, actualPeriod); } }
mit
jwlin/web-apollo-dbdump
src/org/bbop/apollo/web/datastore/DataStoreChangeEvent.java
1096
package org.bbop.apollo.web.datastore; import java.util.EventObject; import org.json.JSONObject; public class DataStoreChangeEvent extends EventObject { private static final long serialVersionUID = 1L; private JSONObject features; private String track; private Operation operation; private boolean sequenceAlterationEvent; public DataStoreChangeEvent(Object source, JSONObject features, String track, Operation operation) { this(source, features, track, operation, false); } public DataStoreChangeEvent(Object source, JSONObject features, String track, Operation operation, boolean sequenceAlterationEvent) { super(source); this.features = features; this.track = track; this.operation = operation; this.sequenceAlterationEvent = sequenceAlterationEvent; } public enum Operation { ADD, DELETE, UPDATE } public JSONObject getFeatures() { return features; } public String getTrack() { return track; } public Operation getOperation() { return operation; } public boolean isSequenceAlterationEvent() { return sequenceAlterationEvent; } }
mit
austriapro/ebinterface-web
ebinterface-web/src/main/java/at/ebinterface/validation/web/pages/resultpages/ResultPanel.java
7093
package at.ebinterface.validation.web.pages.resultpages; import java.io.IOException; import java.io.OutputStream; import javax.annotation.Nullable; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.WebPage; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.link.Link; import org.apache.wicket.markup.html.panel.EmptyPanel; import org.apache.wicket.markup.html.panel.Panel; import org.apache.wicket.model.Model; import org.apache.wicket.request.handler.resource.ResourceStreamRequestHandler; import org.apache.wicket.util.resource.AbstractResourceStreamWriter; import com.helger.commons.string.StringHelper; import at.ebinterface.validation.dto.SignatureValidationResult; import at.ebinterface.validation.validator.ValidationResult; import at.ebinterface.validation.web.panels.SignatureDetailsPanel; public final class ResultPanel extends Panel { public ResultPanel(final String id, final ValidationResult validationResult, final byte[] pdf, final byte[] xml, final String log, @Nullable final Class<? extends WebPage> returnPage) { super(id); final StringBuilder schemaVersion = new StringBuilder(); Label schemaVersionLabel; Label schemaVersionLabelNoOk; if (validationResult.getDeterminedEbInterfaceVersion() != null) { schemaVersion.append(validationResult.getDeterminedEbInterfaceVersion().getCaption()); if (validationResult.getDeterminedEbInterfaceVersion().supportsSigning()) { if (validationResult.getDeterminedEbInterfaceVersion().isSigned()) { schemaVersion.append(" (signiert)"); } else { schemaVersion.append(" (unsigniert)"); } } } if (schemaVersion.length() > 0) { //Add a label with the schema version schemaVersionLabel = new Label("schemaVersion", Model.of(schemaVersion.toString())); schemaVersionLabelNoOk = new Label("schemaVersion", Model.of(schemaVersion.toString())); } else { schemaVersionLabel = new Label("schemaVersion", Model.of("Es wurde keine gültige Version erkannt.")); schemaVersionLabelNoOk = new Label("schemaVersion", Model.of("Es wurde keine gültige Version erkannt.")); } //Schema OK Container final WebMarkupContainer schemaOkContainer = new WebMarkupContainer("schemvalidationOK"); schemaOkContainer.add(schemaVersionLabel); add(schemaOkContainer); //Schema NOK Container final WebMarkupContainer schemaNOkContainer = new WebMarkupContainer("schemvalidationNOK"); schemaNOkContainer.add(schemaVersionLabelNoOk); schemaNOkContainer.add(new Label("schemaValidationError", Model.of(validationResult.getSchemaValidationErrorMessage()))); add(schemaNOkContainer); //Schema is OK if (StringHelper.hasNoText(validationResult.getSchemaValidationErrorMessage())) { schemaOkContainer.setVisible(true); schemaNOkContainer.setVisible(false); } //Schema NOK else { schemaOkContainer.setVisible(false); schemaNOkContainer.setVisible(true); } //Signature result container final WebMarkupContainer signatureResultContainer = new WebMarkupContainer("signatureResultContainer"); //If no signature is applied we do not show the containers if (validationResult.getDeterminedEbInterfaceVersion() == null || !validationResult .getDeterminedEbInterfaceVersion().isSigned()) { signatureResultContainer.setVisibilityAllowed(false); } //Get the result details for the signature final SignatureValidationResult signatureValidationResult = new SignatureValidationResult(validationResult.getVerifyDocumentResponse()); //Signature signatureResultContainer.add(new SignatureDetailsPanel("signatureDetails", Model .of(signatureValidationResult.getSignatureText()), Model.of(Boolean.valueOf(signatureValidationResult .isSignatureValid())))); //Certificate signatureResultContainer.add(new SignatureDetailsPanel("certificateDetails", Model .of(signatureValidationResult.getCertificateText()), Model.of(Boolean.valueOf(signatureValidationResult .isCertificateValid())))); //Manifest signatureResultContainer.add(new SignatureDetailsPanel("manifestDetails", Model .of(signatureValidationResult.getManifestText()), Model.of(Boolean.valueOf(signatureValidationResult .isManifestValid())))); add(signatureResultContainer); //Log Container final WebMarkupContainer mappingContainer = new WebMarkupContainer("mappingLog"); add(mappingContainer); final WebMarkupContainer errorContainer = new WebMarkupContainer("mappingLogError"); mappingContainer.add(errorContainer); errorContainer.setVisible(true); if (log != null) { mappingContainer.setVisible(true); final Label slog = new Label("logErrorPanel", Model.of(new String(log).trim())); errorContainer.add(slog.setEscapeModelStrings(false)); } else { mappingContainer.setVisible(false); final EmptyPanel slog = new EmptyPanel("logErrorPanel"); errorContainer.add(slog); } add(new Link<Object>("returnLink") { @Override public void onClick() { setResponsePage(returnPage); } }.setVisibilityAllowed(returnPage != null)); final Link<Void> pdflink = new Link<Void>("linkPDFDownload") { @Override public void onClick() { final AbstractResourceStreamWriter rstream = new AbstractResourceStreamWriter() { @Override public void write(final OutputStream output) throws IOException { output.write(pdf); } }; final ResourceStreamRequestHandler handler = new ResourceStreamRequestHandler(rstream, "ebInterface-Invoice.pdf"); getRequestCycle().scheduleRequestHandlerAfterCurrent(handler); } }; pdflink.setVisible(pdf != null); //Add a PDF-download button add(pdflink); final Link<Void> xmllink = new Link<Void>("linkXMLDownload") { @Override public void onClick() { final AbstractResourceStreamWriter rstream = new AbstractResourceStreamWriter() { @Override public void write(final OutputStream output) throws IOException { output.write(xml); } }; final ResourceStreamRequestHandler handler = new ResourceStreamRequestHandler(rstream, "ebInterface-Invoice.xml"); getRequestCycle().scheduleRequestHandlerAfterCurrent(handler); } }; xmllink.setVisible(xml != null); //Add a PDF-download button add(xmllink); } }
mit
nico01f/z-pec
ZimbraSoap/src/wsdl-test/generated/zcsclient/mail/testMailYabDataSource.java
764
package generated.zcsclient.mail; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for mailYabDataSource complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="mailYabDataSource"> * &lt;complexContent> * &lt;extension base="{urn:zimbraMail}mailDataSource"> * &lt;sequence> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "mailYabDataSource") public class testMailYabDataSource extends testMailDataSource { }
mit
david850067064/visualflexunit
dev/arc-flexunit2/src/java/com/allurent/flexunit2/framework/UnitTestReportServer.java
5083
/* * Copyright (c) 2007 Allurent, Inc. * http://code.google.com/p/antennae/ * * 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.allurent.flexunit2.framework; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; /** * A lightweight Java server that listens for input from a client program. This server is designed * to work exclusively with the ActionScript client test program, and is therefore very lax about * protocol and error issues. When the ActionScript tests have completed, the server dumps the * output of the tests to standard out. The server listens on port 50031 by default. In order to * change the port number, pass the port number as the first argument to the program. If the server * notes that all tests passed it exits with code 0. Exit code -1 means that there was an unhandled * exception and exit code 1 means that the tests failed. */ public class UnitTestReportServer { /** * Status string to indicate that all tests passed. */ public static final String PASS = "PASS"; /** * Status string to indicate that the tests failed. */ public static final String FAIL = "FAIL"; /** * Status string to indicate that Flex requested a policy file. */ public static final String POLICY = "POLICY"; /** * Default port the server listens on. */ private static int DEFAULT_PORT = 50031; /** * Port the server is listening on. */ private int port; /** * Create a new Unit Test Report Server which listens on the given port. * * @param port * Port */ public UnitTestReportServer(int port) { this.port = port; } /** * Handle a single report. The report server can also handle a policy file request if needed. * * @param serverSocket * Server socket to read report from * @return Status code of report server; PASS, POLICY, FAIL, or null (same as FAIL) * @throws IOException * @throws InterruptedException */ private String handleReport(ServerSocket serverSocket) throws IOException, InterruptedException { Socket socket = serverSocket.accept(); UnitTestReportHandler handler = new UnitTestReportHandler(socket.getInputStream(), socket .getOutputStream()); handler.start(); handler.join(); return handler.getStatus(); } /** * Record all of the information supplied to us from the Flex testing service. * * @return Exit code; 0 for PASS; anything else for FAIL * @throws IOException * @throws InterruptedException */ public int recordTests() throws IOException, InterruptedException { ServerSocket serverSocket = new ServerSocket(port); String status = handleReport(serverSocket); // If a policy file was requested, need to accept another // connection to actually read the test report if (POLICY.equals(status)) { status = handleReport(serverSocket); } serverSocket.close(); if (PASS.equals(status)) { return 0; } return 1; } /** * This server is executed from the command line, or by Ant. * * @param args * [port] */ public static void main(String args[]) { int port = DEFAULT_PORT; if (args.length > 1) { port = Integer.parseInt(args[0], 10); } UnitTestReportServer unitTestReportServer = new UnitTestReportServer(port); int exitCode = 0; try { exitCode = unitTestReportServer.recordTests(); } catch (Exception error) { error.printStackTrace(); exitCode = -1; } System.exit(exitCode); } }
mit
selvasingh/azure-sdk-for-java
sdk/netapp/mgmt-v2020_02_01/src/main/java/com/microsoft/azure/management/netapp/v2020_02_01/VolumePropertiesExportPolicy.java
1081
/** * 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.netapp.v2020_02_01; import java.util.List; import com.fasterxml.jackson.annotation.JsonProperty; /** * exportPolicy. * Set of export policy rules. */ public class VolumePropertiesExportPolicy { /** * Export policy rule. * Export policy rule. */ @JsonProperty(value = "rules") private List<ExportPolicyRule> rules; /** * Get export policy rule. * * @return the rules value */ public List<ExportPolicyRule> rules() { return this.rules; } /** * Set export policy rule. * * @param rules the rules value to set * @return the VolumePropertiesExportPolicy object itself. */ public VolumePropertiesExportPolicy withRules(List<ExportPolicyRule> rules) { this.rules = rules; return this; } }
mit
yogoloth/jmxtrans
jmxtrans-examples/src/main/java/com/googlecode/jmxtrans/example/ActiveMQ2.java
4220
/** * The MIT License * Copyright (c) 2010 JmxTrans team * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.googlecode.jmxtrans.example; import com.google.inject.Injector; import com.googlecode.jmxtrans.JmxTransformer; import com.googlecode.jmxtrans.cli.JmxTransConfiguration; import com.googlecode.jmxtrans.guice.JmxTransModule; import com.googlecode.jmxtrans.model.JmxProcess; import com.googlecode.jmxtrans.model.Query; import com.googlecode.jmxtrans.model.Server; import com.googlecode.jmxtrans.model.output.RRDToolWriter; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import java.io.File; import java.io.IOException; /** * This example shows how to query an ActiveMQ server for some information. * * The point of this example is to show that * works as part of the objectName. * It also shows that you don't have to set an attribute to get for a query. * jmxtrans will get all attributes on an object if you don't specify any. * * @author jon */ @SuppressWarnings({"squid:S106", "squid:S1118"}) // using StdOut if fine in an example public class ActiveMQ2 { private static final JsonPrinter jsonPrinter = new JsonPrinter(System.out); @SuppressFBWarnings( value = "DMI_HARDCODED_ABSOLUTE_FILENAME", justification = "Path to RRD binary is hardcoded as this is example code") public static void main(String[] args) throws Exception { File outputFile = new File("target/w2-TEST.rrd"); if (!outputFile.exists() && !outputFile.createNewFile()) { throw new IOException("Could not create output file"); } RRDToolWriter gw = RRDToolWriter.builder() .setTemplateFile(new File("memorypool-rrd-template.xml")) .setOutputFile(outputFile) .setBinaryPath(new File("/opt/local/bin")) .setDebugEnabled(true) .setGenerate(true) .addTypeName("Destination") .build(); JmxProcess process = new JmxProcess(Server.builder() .setHost("w2") .setPort("1105") .setAlias("w2_activemq_1105") .addQuery(Query.builder() .setObj("org.apache.activemq:BrokerName=localhost,Type=Queue,Destination=*") .addAttr("QueueSize") .addAttr("MaxEnqueueTime") .addAttr("MinEnqueueTime") .addAttr("AverageEnqueueTime") .addAttr("InFlightCount") .addAttr("ConsumerCount") .addAttr("ProducerCount") .addAttr("DispatchCount") .addAttr("DequeueCount") .addAttr("EnqueueCount") .addOutputWriterFactory(gw) .build()) .addQuery(Query.builder() .setObj("org.apache.activemq:BrokerName=localhost,Type=Topic,Destination=*") .addAttr("QueueSize") .addAttr("MaxEnqueueTime") .addAttr("MinEnqueueTime") .addAttr("AverageEnqueueTime") .addAttr("InFlightCount") .addAttr("ConsumerCount") .addAttr("ProducerCount") .addAttr("DispatchCount") .addAttr("DequeueCount") .addAttr("EnqueueCount") .addOutputWriterFactory(gw) .build()).build()); jsonPrinter.prettyPrint(process); Injector injector = JmxTransModule.createInjector(new JmxTransConfiguration()); JmxTransformer transformer = injector.getInstance(JmxTransformer.class); transformer.executeStandalone(process); } }
mit
kohsuke/rngom
src/org/kohsuke/rngom/binary/EmptyPattern.java
1999
/* * Copyright (C) 2004-2011 * * 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.kohsuke.rngom.binary; import org.kohsuke.rngom.binary.visitor.PatternFunction; import org.kohsuke.rngom.binary.visitor.PatternVisitor; public class EmptyPattern extends Pattern { EmptyPattern() { super(true, EMPTY_CONTENT_TYPE, EMPTY_HASH_CODE); } boolean samePattern(Pattern other) { return other instanceof EmptyPattern; } public void accept(PatternVisitor visitor) { visitor.visitEmpty(); } public Object apply(PatternFunction f) { return f.caseEmpty(this); } @Override void checkRestrictions(int context, DuplicateAttributeDetector dad, Alphabet alpha) throws RestrictionViolationException { switch (context) { case DATA_EXCEPT_CONTEXT: throw new RestrictionViolationException("data_except_contains_empty"); case START_CONTEXT: throw new RestrictionViolationException("start_contains_empty"); } } }
mit
Mehdi-H/LDMH---Gestion-de-projet-logiciel-Java-J2EE---ESIEE-Paris-Atos
MultimediaWorld/src/servlets/MajCatalogue.java
4224
package servlets; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; 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 javax.servlet.http.Part; import beans.Etat; import beans.Produit; import beans.Role; import beans.User; import daos.CommandeDao; import daos.DaoFactory; import daos.ProduitDao; import daos.RubriqueDao; import daos.UserDao; import helpers.DataHelpers; import helpers.RequestHelpers; /** * Servlet implementation class MajCatalogue */ @WebServlet("/MajCatalogue") public class MajCatalogue extends HttpServlet { // ======================================================================== // == ATTRIBUTS // ======================================================================== private static final long serialVersionUID = 1L; // === DAOs === private UserDao userDao; private RubriqueDao rubriqueDao; private ProduitDao produitDao; private CommandeDao commandeDao; // ======================================================================== // == CONSTRUCTEUR // ======================================================================== public MajCatalogue() { super(); } // ======================================================================== // == INIT // ======================================================================== public void init() throws ServletException { this.userDao = DaoFactory.getUserDao(); this.rubriqueDao = DaoFactory.getRubriqueDao(); this.produitDao = DaoFactory.getProduitDao(); this.commandeDao = DaoFactory.getCommandeDao(); } // ======================================================================== // == HTTP // ======================================================================== protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // === User === User user = RequestHelpers.getCurrentUser(request); if (user == null) { // Redirection vers la page d'accueil : request.setAttribute("flash_error", "Connectez-vous avant d'administrer ;-)"); RequestHelpers.homePageDoGet(request, response, this); return; } if (! user.getRole().equals(Role.Label.ADMIN.toString())) { // Redirection vers la page d'accueil : request.setAttribute("flash_error", "Vous devez être administrateur pour administrer ;-)"); RequestHelpers.homePageDoGet(request, response, this); return; } // === GENERATION DE LA JSP === RequestHelpers.setUsualAttributes(request, "Mise à jour du catalogue"); this.getServletContext().getRequestDispatcher("/WEB-INF/catalogue.jsp").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // === User === User user = RequestHelpers.getCurrentUser(request); if (user == null) { // Redirection vers la page d'accueil : request.setAttribute("flash_error", "Connectez-vous avant d'administrer ;-)"); RequestHelpers.homePageDoGet(request, response, this); return; } if (! user.getRole().equals(Role.Label.ADMIN.toString())) { // Redirection vers la page d'accueil : request.setAttribute("flash_error", "Vous devez être administrateur pour administrer ;-)"); RequestHelpers.homePageDoGet(request, response, this); return; } // === Récupérer le fichier CSV === /*Part part = request.getPart("csv"); String nomFichier = RequestHelpers.getNomFichier(part); if (nomFichier == null || nomFichier.isEmpty()) { request.setAttribute("flash_error", "Erreur lors de l'upload du fichier :S"); this.doGet(request, response); return; }*/ // === Recharger la vue === // request.setAttribute("flash_success", "Le fichier "+ nomFichier +" a bien été importé :)"); request.setAttribute("flash_error", "Cette fonction n'est pas encore implémentée :("); this.doGet(request, response); } }
mit
eZubia/video-club
src/main/java/mx/uach/videoclub/modelos/Actor.java
2977
package mx.uach.videoclub.modelos; import javax.persistence.Entity; import mx.uach.videoclub.modelos.genericos.Model; /** * Modelo para mappear los actores de las películas del video club. * * @author Erik David Zubia Hernández * @version 1.0 */ @Entity public class Actor extends Model{ public static final String TABLA = "actores"; public static final String TABLA_HIBERNATE = "Actor"; public static final String[] FIELDS = {"id", "nombre", "apellido"}; public static final String Q = String.format("SELECT %s FROM %s", fieldsToQuery(FIELDS, Boolean.FALSE), TABLA); public static final String Q_HIBERNATE = String.format("SELECT a FROM %s", TABLA_HIBERNATE); public static final String INSERT_ACTOR = String.format("%s %s (%s) VALUES (%s)", Model.INSERT, TABLA, fieldsToQuery(FIELDS, Boolean.TRUE), paramsToStatement(FIELDS, Boolean.TRUE) ); public static final String UPDATE_ACTOR = String.format("%s %s SET %s WHERE %s = ?", Model.UPDATE, TABLA, paramsToStatementToCreate(FIELDS, Boolean.TRUE), ID); public static final String DELETE_ACTOR = String.format("%s %s %s ?", Model.DELETE, TABLA, Model.Q_WHERE_ID); private String nombre; private String apellido; /** * Constructor vacío. */ public Actor() { } /** * Constructor con los parámetros necesarios para crear describir a un * {@code Actor}. * * @param nombre {@code String} nombre del actor * @param apellido {@code String} apellido del actor */ public Actor(String nombre, String apellido) { this.nombre = nombre; this.apellido = apellido; } /** * Constructor con los parámetros necesarios para crear describir a un * {@code Actor}, adicionado de su identificador único dentro de la * base de datos. * * @param nombre {@code String} nombre del actor * @param apellido {@code String} apellido del actor * @param id {@code Integer} identificador único */ public Actor(String nombre, String apellido, Long id) { super(id); this.nombre = nombre; this.apellido = apellido; } /** * Consigue el nombre del {@code Actor}. * * @return {@code String} nombre del actor */ public String getNombre() { return nombre; } /** * Asigna un nombre al {@code Actor}. * * @param nombre {@code String} nombre a asignar */ public void setNombre(String nombre) { this.nombre = nombre; } /** * Consigue el apellido del {@code Actor}. * * @return {@code String} apellido del actor */ public String getApellido() { return apellido; } /** * Asigna un apellido al {@code Actor}. * * @param apellido {@code String} apellido a asignar */ public void setApellido(String apellido) { this.apellido = apellido; } }
mit
hamdouni/iut
src/coo/ctrl/exo2/Test.java
655
package coo.ctrl.exo2; public class Test { public static void AfficherActeur(Acteur a) { System.out.println(a + "et gagne " + a.salaire() + " €" ); } public static void main(String[] args) { ActeurTheatre JacquesWeber = new ActeurTheatre("Jacques Weber"); AfficherActeur(JacquesWeber); ActeurDeguise jwp = new Perruque(JacquesWeber); AfficherActeur(jwp); ActeurDeguise jwpm = new Moustache(jwp); AfficherActeur(jwpm); Acteur TomCruise = new ActeurCinema("Tom Cruise"); AfficherActeur(TomCruise); Acteur tcp = new Perruque(TomCruise); AfficherActeur(tcp); Acteur tcpp = new Perruque(tcp); AfficherActeur(tcpp); } }
mit
ruscoe/Space-Trivia
src/org/ruscoe/spacetrivia/dao/QuestionData.java
2818
package org.ruscoe.spacetrivia.dao; import java.util.HashMap; import org.ruscoe.spacetrivia.models.Question; import static android.provider.BaseColumns._ID; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; /** * Extends TriviaDAO, providing methods to access data specific to * trivia questions in the application. * * @author Dan Ruscoe */ public class QuestionData extends TriviaDAO { public static final String TABLE_NAME = "questions"; public static final String CATEGORY_ID = "categoryId"; public static final String DIFFICULTY = "difficulty"; public static final String TEXT = "text"; public static final String DESCRIPTION = "description"; public static final int FIELD_ID_ID = 0; public static final int FIELD_ID_CATEGORY_ID = 1; public static final int FIELD_ID_DIFFICULTY = 2; public static final int FIELD_ID_TEXT = 3; public static final int FIELD_ID_DESCRIPTION = 4; private String[] selectFields = { _ID, CATEGORY_ID, DIFFICULTY, TEXT, DESCRIPTION }; /** * Constructor for QuestionData. * * @param Context context - The current application context. */ public QuestionData(Context context) { super(context); } /** * Returns a Map of Question instances for all questions relating * to a given category ID. * * @param int categoryId - The ID of the category to get questions for. * @return HashMap<Integer, Question> - A map of Question instances, * indexed by question ID. */ public HashMap<Integer, Question> getQuestionsByCategoryId(long categoryId) { SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.query(TABLE_NAME, selectFields, CATEGORY_ID + "=" + categoryId, null, null, null, null); HashMap<Integer, Question> questions = new HashMap<Integer, Question>(); if (cursor != null) { while (cursor.moveToNext()) { Question question = getQuestionFromCursor(cursor); questions.put(question.getQuestionId(), question); } cursor.close(); } db.close(); return questions; } /** * Returns a populated Question instance using data from a Cursor instance. * * @param Cursor cursor - A Cursor instance resulting from a query * on the questions database table. * @return Question - A populated Question instance. */ private Question getQuestionFromCursor(Cursor cursor) { Question question = new Question(); question.setQuestionId(cursor.getInt(FIELD_ID_ID)); question.setCategoryId(cursor.getInt(FIELD_ID_CATEGORY_ID)); question.setDifficulty(cursor.getInt(FIELD_ID_DIFFICULTY)); question.setText(cursor.getString(FIELD_ID_TEXT)); question.setDescription(cursor.getString(FIELD_ID_DESCRIPTION)); return question; } }
mit
mccallister/RoboticsHours
RoboticsHours/src/roboticshours/CalendarRenderer.java
529
package roboticshours; import java.util.Calendar; import javax.swing.table.DefaultTableCellRenderer; class CalendarRenderer extends DefaultTableCellRenderer { public CalendarRenderer() { super(); this.setHorizontalAlignment(CENTER); } @Override public void setValue(Object value) { Calendar date = (Calendar)value; setText(date.get(Calendar.MONTH) + 1 + "/" + date.get(Calendar.DAY_OF_MONTH) + "/" + (date.get(Calendar.YEAR))); } }
mit
Rexee/MistaReader
src/com/mistareader/TextProcessors/S.java
477
package com.mistareader.TextProcessors; import android.util.Log; public class S { public static class ResultContainer { public boolean result; public String resultStr; public String userID; public String resultSessionID; public String cookie; } public static void L(Object object) { Log.d("mylog", "" + object); } public static void L(String string, Exception e) { Log.d("mylog", "" + string + " " + Log.getStackTraceString(e)); } }
mit
MjAbuz/influent
influent-selenium-test/src/main/java/influent/selenium/tests/ColdStartTransactionsByIdTest.java
2181
/* * Copyright (C) 2013-2015 Uncharted Software Inc. * * Property of Uncharted(TM), formerly Oculus Info Inc. * http://uncharted.software/ * * Released under the MIT License. * * 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 influent.selenium.tests; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import influent.selenium.util.SeleniumUtils; public class ColdStartTransactionsByIdTest extends ColdStartTestBase{ public ColdStartTransactionsByIdTest(BROWSER browser) { super(browser, SeleniumUtils.ACCOUNTS_NAME.toLowerCase(), "id%3Aa.null.b146773", "accountsSearchResult"); } @Test public void coldStartTestBasicTerm() { WebElement element = (new WebDriverWait(driver, 120)).until(ExpectedConditions.presenceOfElementLocated(By.className(this.classToFind))); if (element == null) { throw new AssertionError("Could not find any " + this.classToFind + " elements. The server either did not return any search results for the url or the search failed."); } } }
mit
iitc/access
src/main/java/com/iancaffey/access/google/GoogleWorkContext.java
777
package com.iancaffey.access.google; import com.iancaffey.access.Context; import com.iancaffey.access.Host; /** * GoogleContext * * @author Ian Caffey * @since 1.0 */ public class GoogleWorkContext extends Context { private final String client; private final String signature; public GoogleWorkContext(String client, String signature) { super(new Host(new GoogleWorkRouter(signature), new GoogleQueryTypeAdapter(), new GoogleAdapterRegistry())); if (client == null || signature == null) throw new IllegalArgumentException(); this.client = client; this.signature = signature; } public String getClient() { return client; } public String getSignature() { return signature; } }
mit
UCSB-CS56-W15/W15-lab04
src/edu/ucsb/cs56/w15/drawings/yamen/SimpleGui1.java
981
package edu.ucsb.cs56.w15.drawings.yamen; import javax.swing.*; /** SimpleGui1 comes from Head First Java 2nd Edition p. 355. It illustrates a simple GUI with a Button that doesn't do anything yet. @author Head First Java, 2nd Edition p. 355 @author P. Conrad (who only typed it in and added the Javadoc comments) @author Yamen Alghrer @version CS56, Winter 2015, UCSB */ public class SimpleGui1 { /** main method to fire up a JFrame on the screen @param args not used */ public static void main (String[] args) { JFrame frame = new JFrame() ; JButton button = new JButton("click me you beautiful boy"); java.awt.Color myColor = new java.awt.Color(111,255,153); // R, G, B values. button.setBackground(myColor); button.setOpaque(true); frame. setDefaultCloseOperation(JFrame. EXIT_ON_CLOSE) ; frame. getContentPane() . add(button) ; frame. setSize(300,300) ; frame. setVisible(true) ; } }
mit
java-goodies/ews-java-api
src/main/java/microsoft/exchange/webservices/data/WebClientUrlCollection.java
2596
/************************************************************************** Exchange Web Services Java API Copyright (c) Microsoft Corporation All rights reserved. MIT License 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 microsoft.exchange.webservices.data; import java.util.ArrayList; /** * Represents a user setting that is a collection of Exchange web client URLs. */ public final class WebClientUrlCollection { /** The urls. */ private ArrayList<WebClientUrl> urls; /** * Initializes a new instance of the <see cref="WebClientUrlCollection"/> * class. */ protected WebClientUrlCollection() { this.urls = new ArrayList<WebClientUrl>(); } /** * Loads instance of WebClientUrlCollection from XML. * * @param reader * The reader. * @return the web client url collection * @throws Exception * the exception */ protected static WebClientUrlCollection loadFromXml(EwsXmlReader reader) throws Exception { WebClientUrlCollection instance = new WebClientUrlCollection(); do { reader.read(); if ((reader.getNodeType().getNodeType() == XmlNodeType.START_ELEMENT) && (reader.getLocalName() .equals(XmlElementNames.WebClientUrl))) { instance.getUrls().add(WebClientUrl.loadFromXml(reader)); } } while (!reader.isEndElement(XmlNamespace.Autodiscover, XmlElementNames.WebClientUrls)); return instance; } /** * Gets the URLs. * * @return the urls */ public ArrayList<WebClientUrl> getUrls() { return this.urls; } }
mit
selvasingh/azure-sdk-for-java
sdk/spring/azure-spring-cloud-messaging/src/main/java/com/microsoft/azure/spring/messaging/container/AbstractAzureListenerContainerFactory.java
1718
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.microsoft.azure.spring.messaging.container; import com.microsoft.azure.spring.integration.core.api.SubscribeByGroupOperation; import com.microsoft.azure.spring.messaging.endpoint.AbstractAzureListenerEndpoint; import com.microsoft.azure.spring.messaging.endpoint.AzureListenerEndpoint; /** * Base {@link ListenerContainerFactory} for Spring's base container implementation. * * @param <C> the container type * @author Warren Zhu * @see AbstractAzureListenerEndpoint */ abstract class AbstractAzureListenerContainerFactory<C extends AbstractListenerContainer> implements ListenerContainerFactory<C> { private final SubscribeByGroupOperation subscribeOperation; protected AbstractAzureListenerContainerFactory(SubscribeByGroupOperation subscribeOperation) { this.subscribeOperation = subscribeOperation; } @Override public C createListenerContainer(AzureListenerEndpoint endpoint) { C instance = createContainerInstance(); initializeContainer(instance); endpoint.setupListenerContainer(instance); return instance; } /** * Create an empty container instance. * * @return C instance */ protected abstract C createContainerInstance(); /** * Further initialize the specified container. * <p>Subclasses can inherit from this method to apply extra * configuration if necessary. * @param instance instance */ protected void initializeContainer(C instance) { } public SubscribeByGroupOperation getSubscribeOperation() { return subscribeOperation; } }
mit
foxaice/SmartLight
app/src/main/java/me/foxaice/smartlight/fragments/controllers_screen/controller_management/view/ViewHandler.java
5602
package me.foxaice.smartlight.fragments.controllers_screen.controller_management.view; import android.os.Handler; import android.os.Message; import android.widget.Toast; import java.lang.ref.WeakReference; import me.foxaice.smartlight.fragments.controllers_screen.controller_management.view.dialogs.execution_task.ExecutionTaskDialog; class ViewHandler extends Handler { private static final int START_CONNECTION = 0x0001; private static final int IS_CONNECTED = 0x0002; private static final int FAILED_CONNECTION = 0x0004; private static final int SUB_TASK_COMPLETED = 0x0005; private static final int EXECUTION_TASK_COMPLETED = 0x0006; private static final int DELAY = 150; private static final int MAX_SEARCHING_SECONDS = 10000; private static final int IS_CONNECTING = 0x0003; private final WeakReference<ControllerManagementFragment> wrFragment; private ControllerManagementFragment mFragment; ViewHandler(ControllerManagementFragment fragment) { wrFragment = new WeakReference<>(fragment); } @Override public void handleMessage(Message msg) { mFragment = wrFragment.get(); if (mFragment != null) { switch (msg.what) { case START_CONNECTION: onReceivedMessageStartConnection(); break; case IS_CONNECTING: onReceivedMessageIsConnecting(msg); break; case IS_CONNECTED: onReceivedMessageIsConnected(); break; case FAILED_CONNECTION: onReceivedMessageFailedConnection(); break; case SUB_TASK_COMPLETED: onReceivedMessageSubTaskComplete(msg); break; case EXECUTION_TASK_COMPLETED: onReceivedMessageExecutionTaskCompleted(msg); } } } void removeAllCallbacksAndMessages() { removeCallbacksAndMessages(null); } void sendStartConnectionMessage() { sendEmptyMessage(START_CONNECTION); } void sendIsConnectingMessage() { sendEmptyMessage(IS_CONNECTED); } void sendSubTaskCompletedMessage(int taskPosition) { sendMessage(obtainMessage(SUB_TASK_COMPLETED, taskPosition, taskPosition)); } void sendExecutionTaskCompletedMessage(boolean successful) { int successId = successful ? 1 : 0; sendMessage(obtainMessage(EXECUTION_TASK_COMPLETED, successId, successId)); } void sendFailedConnectionMessage() { sendEmptyMessage(FAILED_CONNECTION); } private void onReceivedMessageExecutionTaskCompleted(Message msg) { ExecutionTaskDialog dialog = mFragment.getTaskDialog(); if (dialog != null) { if (msg.arg1 == 1) { dialog.removeCallbacksAndMessages(); Toast.makeText(dialog.getContext(), "SUCCESS", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(dialog.getContext(), "FAILED", Toast.LENGTH_SHORT).show(); } this.postDelayed(new Runnable() { @Override public void run() { if (mFragment.getActivity() != null) { mFragment.getActivity().finish(); } } }, 1500); } } private void onReceivedMessageSubTaskComplete(Message msg) { if (mFragment.getTaskDialog() != null) { mFragment.getTaskDialog().setSubTaskComplete(msg.arg1); } } private void onReceivedMessageStartConnection() { this.sendMessageDelayed(this.obtainMessage(IS_CONNECTING, 0, 0, new StringBuilder()), DELAY); mFragment.getPresenter().startSearchDeviceTask(); } private void onReceivedMessageIsConnecting(Message msg) { int milliseconds = msg.arg1; int dotsCounter = msg.arg2; StringBuilder sb = (StringBuilder) msg.obj; sb = getStringBuilderWithDots(sb, dotsCounter++, true); if (dotsCounter == 12) dotsCounter = 0; milliseconds += DELAY; mFragment.showIsSearchingContent(sb); if (milliseconds >= MAX_SEARCHING_SECONDS) { this.sendEmptyMessage(FAILED_CONNECTION); } else { this.sendMessageDelayed(this.obtainMessage(IS_CONNECTING, milliseconds, dotsCounter, sb), DELAY); } } private void onReceivedMessageIsConnected() { this.removeMessages(IS_CONNECTING); mFragment.showSuccessfulConnectionContent(); } private void onReceivedMessageFailedConnection() { this.removeMessages(IS_CONNECTING); mFragment.showFailedConnectionContent(); } private StringBuilder getStringBuilderWithDots(StringBuilder sb, int i, boolean firstEnterRecursive) { if (sb == null) return null; boolean reverse = false; if (firstEnterRecursive) sb.delete(0, sb.length()); if (i == 0) { sb.append(' ').append('.'); } else if (i >= 1 && i <= 3) { getStringBuilderWithDots(sb, --i, false).append(' ').append('.'); } else if (i >= 4 && i <= 9) { getStringBuilderWithDots(sb, (6 - i) > 0 ? 6 - i : i - 6, false); reverse = true; } else if (i >= 10 && i <= 12) { getStringBuilderWithDots(sb, 12 - i, false); } if (firstEnterRecursive) while (sb.length() < 9) sb.append(' '); return reverse ? sb.reverse() : sb; } }
mit
krukru/CodeFight
src/kru/codefight/fighter/attacks/Jab.java
475
package kru.codefight.fighter.attacks; public class Jab extends AbstractAttack { @Override public int getFullDamage() { return 5; } @Override public int getBlockedDamage() { return 0; } @Override public int getStaminaCost() { return 15; } @Override public int getCastTimeInMs() { return 600; } @Override public int getStunDurationInMs() { return 0; } @Override public boolean isDodgeable() { return true; } }
mit
joansmith/XChange
xchange-independentreserve/src/main/java/com/xeiam/xchange/independentreserve/service/polling/IndependentReserveTradeService.java
3273
package com.xeiam.xchange.independentreserve.service.polling; import java.io.IOException; import java.util.Collection; import com.xeiam.xchange.Exchange; import com.xeiam.xchange.currency.CurrencyPair; import com.xeiam.xchange.dto.Order; import com.xeiam.xchange.dto.trade.LimitOrder; import com.xeiam.xchange.dto.trade.MarketOrder; import com.xeiam.xchange.dto.trade.OpenOrders; import com.xeiam.xchange.dto.trade.UserTrades; import com.xeiam.xchange.exceptions.ExchangeException; import com.xeiam.xchange.exceptions.NotAvailableFromExchangeException; import com.xeiam.xchange.exceptions.NotYetImplementedForExchangeException; import com.xeiam.xchange.independentreserve.IndependentReserveAdapters; import com.xeiam.xchange.service.polling.trade.PollingTradeService; import com.xeiam.xchange.service.polling.trade.params.DefaultTradeHistoryParamPaging; import com.xeiam.xchange.service.polling.trade.params.TradeHistoryParamPaging; import com.xeiam.xchange.service.polling.trade.params.TradeHistoryParams; public class IndependentReserveTradeService extends IndependentReserveTradeServiceRaw implements PollingTradeService { public IndependentReserveTradeService(Exchange exchange) { super(exchange); } /** * Assumes asking for the first 50 orders with the currency pair BTCUSD */ @Override public OpenOrders getOpenOrders() throws ExchangeException, NotAvailableFromExchangeException, NotYetImplementedForExchangeException, IOException { return IndependentReserveAdapters.adaptOpenOrders(getIndependentReserveOpenOrders(CurrencyPair.BTC_USD, 1)); } @Override public String placeMarketOrder(MarketOrder marketOrder) throws ExchangeException, NotAvailableFromExchangeException, NotYetImplementedForExchangeException, IOException { throw new UnsupportedOperationException(); } @Override public String placeLimitOrder(LimitOrder limitOrder) throws ExchangeException, NotAvailableFromExchangeException, NotYetImplementedForExchangeException, IOException { return independentReservePlaceLimitOrder(CurrencyPair.BTC_USD, limitOrder.getType(), limitOrder.getLimitPrice(), limitOrder.getTradableAmount()); } @Override public Collection<Order> getOrder(String... orderIds) throws ExchangeException, NotAvailableFromExchangeException, NotYetImplementedForExchangeException, IOException { throw new NotYetImplementedForExchangeException(); } @Override public boolean cancelOrder(String orderId) throws ExchangeException, NotAvailableFromExchangeException, NotYetImplementedForExchangeException, IOException { return independentReserveCancelOrder(orderId); } /** * Optional parameters: {@link TradeHistoryParamPaging#getPageNumber()} indexed from 0 */ @Override public UserTrades getTradeHistory(TradeHistoryParams params) throws IOException { int pageNumber = ((TradeHistoryParamPaging) params).getPageNumber() + 1; return IndependentReserveAdapters.adaptTradeHistory(getIndependentReserveTradeHistory(pageNumber)); } @Override public TradeHistoryParamPaging createTradeHistoryParams() { return new DefaultTradeHistoryParamPaging(null, 0); } }
mit
karim/adila
database/src/main/java/adila/db/diablo5flte_alcatel20one20touch206034m.java
257
// This file is automatically generated. package adila.db; /* * Alcatel Idol S * * DEVICE: Diablo_LTE * MODEL: ALCATEL ONE TOUCH 6034M */ final class diablo5flte_alcatel20one20touch206034m { public static final String DATA = "Alcatel|Idol S|"; }
mit
Moudoux/OTIRC
IRCServer/src/com/opentexon/Server/Server/Filter.java
2707
/** * This software is licensed under the MIT license. * If you wish to modify this software please give credit and link to the git: https://github.com/Moudoux/OTIRC. */ package com.opentexon.Server.Server; import java.util.ArrayList; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * * @author Alexander * */ public class Filter { private boolean hideLinks = true; private boolean hideIpAddresses = true; public String getHiddenIP(String ip) { String result = ""; for (String s : ip.split("")) { if (!s.equals(".")) { result = result + "*"; } else { result = result + s; } } return result; } public String proccessIPAddresses(String line) { String result = ""; Pattern p = Pattern.compile( "^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"); for (String s : line.split(" ")) { Matcher m = p.matcher(s); if (m.find()) { if (hideIpAddresses) { s = getHiddenIP(s); } result = result.equals("") ? s : result + " " + s; } else { result = result.equals("") ? s : result + " " + s; } } return result; } public String proccessLinks(String line) { String result = ""; String URL_REGEX = "^((https?|ftp)://|(www|ftp)\\.)?[a-z0-9-]+(\\.[a-z0-9-]+)+([/?].*)?$"; Pattern p = Pattern.compile(URL_REGEX); for (String s : line.split(" ")) { Matcher m = p.matcher(s.toLowerCase()); if (m.find()) { if (hideLinks && !s.contains("dl.opentexon.com")) { s = getHiddenIP(s); } result = result.equals("") ? s : result + " " + s; } else { result = result.equals("") ? s : result + " " + s; } } return result; } public boolean containsIP(String line) { Pattern p = Pattern.compile( "^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$"); for (String s : line.split(" ")) { Matcher m = p.matcher(s); if (m.find()) { return true; } } return false; } public boolean containsLink(String line) { String URL_REGEX = "^((https?|ftp)://|(www|ftp)\\.)?[a-z0-9-]+(\\.[a-z0-9-]+)+([/?].*)?$"; Pattern p = Pattern.compile(URL_REGEX); for (String s : line.split(" ")) { Matcher m = p.matcher(s); if (m.find()) { return true; } } return false; } public boolean isSwearWord(String line) { boolean result = false; line = line.toLowerCase(); ArrayList<String> badWords = Badwords.getBadWords(); for (String s : line.split(" ")) { if (badWords.contains(s)) { result = true; break; } } return result; } }
mit
uppsala-university/ati-ladok3-rest-client
src/main/java/se/sunet/ati/ladok/rest/services/Studentinformation.java
687
package se.sunet.ati.ladok.rest.services; import se.ladok.schemas.dap.ServiceIndex; import se.ladok.schemas.studentinformation.AvskiljandebeslutLista; import se.ladok.schemas.studentinformation.Avstangningar; import se.ladok.schemas.studentinformation.Kontaktuppgifter; import se.ladok.schemas.studentinformation.Student; public interface Studentinformation extends LadokServiceProperties { AvskiljandebeslutLista hamtaAvskiljandebeslutGivetStudent(String studentUID); Avstangningar hamtaAvstangningarGivetStudent(String studentUID); Student hamtaStudent(String studentUID); Kontaktuppgifter hamtaKontaktuppgifterGivetStudent(String studentUID); ServiceIndex hamtaIndex(); }
mit
jkschoen/jenkins-gitlab-merge-request-sonar-plugin
src/main/java/jenkins/plugins/sonarparser/models/SonarRule.java
3444
/* * Copyright (c) 2014 Jacob Schoen * * 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 jenkins.plugins.sonarparser.models; /** * * @author jacob.schoen@ge.com */ public class SonarRule { private String key; private String rule; private String repository; private String name; public SonarRule() { } public SonarRule(String key, String rule, String repository, String name) { this.key = key; this.rule = rule; this.repository = repository; this.name = name; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getRule() { return rule; } public void setRule(String rule) { this.rule = rule; } public String getRepository() { return repository; } public void setRepository(String repository) { this.repository = repository; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public int hashCode() { int hash = 7; hash = 59 * hash + (this.key != null ? this.key.hashCode() : 0); hash = 59 * hash + (this.rule != null ? this.rule.hashCode() : 0); hash = 59 * hash + (this.repository != null ? this.repository.hashCode() : 0); hash = 59 * hash + (this.name != null ? this.name.hashCode() : 0); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final SonarRule other = (SonarRule) obj; if ((this.key == null) ? (other.key != null) : !this.key.equals(other.key)) { return false; } if ((this.rule == null) ? (other.rule != null) : !this.rule.equals(other.rule)) { return false; } if ((this.repository == null) ? (other.repository != null) : !this.repository.equals(other.repository)) { return false; } return !((this.name == null) ? (other.name != null) : !this.name.equals(other.name)); } @Override public String toString() { return "SonarRule{" + "key=" + key + ", rule=" + rule + ", repository=" + repository + ", name=" + name + '}'; } }
mit
achtern/AchternEngine
src/main/java/org/achtern/AchternEngine/core/resource/ResourceLoaderProvider.java
4254
/* * The MIT License (MIT) * * Copyright (c) 2014 Christian Gärtner * * 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.achtern.AchternEngine.core.resource; import org.achtern.AchternEngine.core.audio.openal.AudioSource; import org.achtern.AchternEngine.core.rendering.Dimension; import org.achtern.AchternEngine.core.rendering.mesh.Mesh; import org.achtern.AchternEngine.core.rendering.texture.Texture; import org.achtern.AchternEngine.core.resource.fileparser.GLSLProgram; import org.achtern.AchternEngine.core.resource.fileparser.LineBasedParser; import org.achtern.AchternEngine.core.resource.loader.AsciiFileLoader; import org.achtern.AchternEngine.core.resource.loader.BinaryLoader; import org.achtern.AchternEngine.core.scenegraph.entity.Figure; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.List; /** * For javadoc see {@link org.achtern.AchternEngine.core.resource.ResourceLoader} * * This is just the interface to proxy, all methods should behave like described, * in the JavaDoc of the proxy. * * @see org.achtern.AchternEngine.core.resource.ResourceLoader */ public interface ResourceLoaderProvider { void addResourceLocation(ResourceLocation location); void pushResourceLocation(ResourceLocation location); void removeResourceLocation(ResourceLocation location); void clearResourceLocations(); List<ResourceLocation> getResourceLocations(); void preLoadMesh(String name) throws Exception; void preLoadTexture(String name) throws Exception; void preLoadShader(String name) throws Exception; Figure getFigure(String name) throws Exception; Figure getFigure(String name, boolean forceLoading) throws Exception; Mesh getMesh(String name) throws Exception; Mesh getMesh(String name, boolean forceLoading) throws Exception; Texture getTexture(String name) throws Exception; Texture getTexture(String name, Dimension dimension) throws Exception; Texture getTexture(String name, Dimension dimension, boolean forceLoading) throws Exception; String getShader(String name) throws Exception; String getShader(String name, boolean forceLoading) throws Exception; String getShader(String name, boolean forceLoading, LineBasedParser parser) throws Exception; GLSLProgram getShaderProgram(String name) throws Exception; GLSLProgram getShaderProgram(String name, boolean forceLoading) throws Exception; AudioSource getAudioSource(String name) throws Exception; AudioSource getAudioSource(String name, boolean forceLoading) throws Exception; <T> T load(String name, AsciiFileLoader<T> loader, boolean forceLoading) throws Exception; @SuppressWarnings("unchecked") <T, C> T load(String name, BinaryLoader<T, C> loader, boolean forceLoading) throws Exception; String readFile(String name) throws IOException; String readFile(String name, boolean forceLoading) throws IOException; String readFile(String name, boolean forceLoading, LineBasedParser parser) throws IOException; boolean exists(String name); InputStream getStream(String name) throws IOException; URL getURL(String name) throws IOException; }
mit
LauncherGroup/GotLunchToday
app/src/main/java/de/schkola/kitchenscanner/fragment/StatsListFragment.java
2866
package de.schkola.kitchenscanner.fragment; import android.app.ProgressDialog; import android.os.Bundle; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ExpandableListView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import de.schkola.kitchenscanner.R; import de.schkola.kitchenscanner.database.DatabaseAccess; import de.schkola.kitchenscanner.task.ProgressAsyncTask; import de.schkola.kitchenscanner.task.StatTask; import de.schkola.kitchenscanner.util.LunchListAdapter; public class StatsListFragment extends Fragment { @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.content_stats_list, container, false); } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); ProgressDialog dialog = new ProgressDialog(getContext()); dialog.setCancelable(false); dialog.setTitle(getString(R.string.collecting_data)); dialog.setMessage(getString(R.string.collecting_data_lunch)); StatTask statTask = new StatTask((new DatabaseAccess(getContext())).getDatabase(), result -> { ExpandableListView listView = view.findViewById(R.id.listview); listView.setAdapter(new LunchListAdapter(getContext(), result.getToDispenseA(), result.getToDispenseB(), result.getToDispenseS())); }); statTask.setProgressListener(new ProgressAsyncTask.ProgressListener() { @Override public void onStart() { dialog.show(); } @Override public void onFinished() { dialog.dismiss(); dialog.cancel(); } }); statTask.execute(); } @Override public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) { inflater.inflate(R.menu.menu_stats_list, menu); super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { if (item.getItemId() == R.id.action_chart) { getParentFragmentManager().beginTransaction() .replace(R.id.container, new StatsChartFragment()) .commit(); return true; } return super.onOptionsItemSelected(item); } }
mit
thorinii/summis-client
src/main/java/me/lachlanap/summis/ui/ActionPanel.java
5808
/* * The MIT License * * Copyright 2014 Lachlan Phillips. * * 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 me.lachlanap.summis.ui; import javax.swing.JPanel; import me.lachlanap.summis.MemoryUnit; import me.lachlanap.summis.StatusListener; import me.lachlanap.summis.Version; import me.lachlanap.summis.downloader.DownloadListener; /** * * @author Lachlan Phillips */ public class ActionPanel extends JPanel implements StatusListener, DownloadListener { private int totalFiles; private MemoryUnit totalSize; private int currentCompleteFiles; private MemoryUnit runningTotal; /** * Creates new form ActionPanel */ public ActionPanel() { initComponents(); } /** * This method is called from within the constructor to initialize the form. WARNING: Do NOT modify this code. The * content of this method is always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { progressBar = new javax.swing.JProgressBar(); progressBar.setMaximum(1000); progressBar.setString("-- not set up --"); progressBar.setStringPainted(true); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(progressBar, javax.swing.GroupLayout.DEFAULT_SIZE, 267, Short.MAX_VALUE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); }// </editor-fold>//GEN-END:initComponents @Override public void checking() { progressBar.setIndeterminate(true); progressBar.setString("Checking for Updates..."); } @Override public void foundLatest(Version latest) { progressBar.setIndeterminate(false); progressBar.setString("Latest: " + latest); } @Override public void errorChecking(Exception e) { } @Override public DownloadListener downloading() { progressBar.setIndeterminate(true); progressBar.setString("Downloading..."); return null; } @Override public void launching() { progressBar.setString("Launching..."); } @Override public void finished() { progressBar.setString("Done"); } @Override public void startingDownload(int numberOfFiles, MemoryUnit totalSize) { this.totalFiles = numberOfFiles; this.totalSize = totalSize; currentCompleteFiles = 0; runningTotal = MemoryUnit.ZERO; progressBar.setIndeterminate(false); refreshDownloadStatus(); } @Override public void downloadedSome(MemoryUnit amount) { runningTotal = runningTotal.plus(amount); refreshDownloadStatus(); } @Override public void completedADownload() { currentCompleteFiles++; refreshDownloadStatus(); } @Override public void startingVerify(int numberOfFiles) { this.totalFiles = numberOfFiles; currentCompleteFiles = 0; refreshVerifyStatus(); } @Override public void completedAVerify() { currentCompleteFiles++; refreshVerifyStatus(); } private void refreshDownloadStatus() { progressBar.setString( String.format("Downloaded %d of %d files, %s of %s...", currentCompleteFiles, totalFiles, runningTotal.toString(), totalSize.toString())); progressBar.setValue((int) ((float) runningTotal.inBytes() * 1000 / totalSize.inBytes())); } private void refreshVerifyStatus() { progressBar.setString( String.format("Verified %d of %d files...", currentCompleteFiles, totalFiles)); progressBar.setValue((int) ((float) currentCompleteFiles * 1000 / totalFiles)); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JProgressBar progressBar; // End of variables declaration//GEN-END:variables }
mit
shankey/Finance
src/main/java/tr/com/lucidcode/controller/HomeController.java
10410
package tr.com.lucidcode.controller; import java.io.File; import java.util.*; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import org.apache.log4j.Logger; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import tr.com.lucidcode.model.MoneyControlScrips; import tr.com.lucidcode.model.StockSymbols; import tr.com.lucidcode.pojo.*; import tr.com.lucidcode.scripts.MoneyControlDataIngest; import tr.com.lucidcode.scripts.MoneyControlScrapper; import tr.com.lucidcode.scripts.XMLParse; import tr.com.lucidcode.service.AccountService; import tr.com.lucidcode.util.ServiceDispatcher; import tr.com.lucidcode.util.Strings; import tr.com.lucidcode.util.Utils; @Controller public class HomeController { protected static Logger logger = Logger.getLogger("sessionListener"); @Resource(name = "accountService") private AccountService accountService; @RequestMapping(value = "/home") public ModelAndView listAll() { logger.debug("Homepage requested"); System.out.println("Catalina Base "+System.getProperty("catalina.base") + "/MoneyControl/"); System.out.println("Current path " + new File(".").getAbsolutePath()); ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("home"); List<String> industries = ServiceDispatcher.getMoneyControlScripService().getAllIndustries(); modelAndView.addObject("industries", industries); return modelAndView; } @RequestMapping(value = "/profits", produces = "application/json") @ResponseBody public String getProfits(HttpServletResponse response) { addCORS(response); List<ReportVariableOutput> list = ServiceDispatcher.getRatioCalculatorService().getProfitDetails(); Gson gson = new GsonBuilder() .setDateFormat("dd-MM-yyyy").create(); String jsonProfitOutput = gson.toJson(list); return jsonProfitOutput; } @RequestMapping(value = "/profitWDC") public ModelAndView getWDC(HttpServletResponse response) { addCORS(response); ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("profitWDC"); return modelAndView; } @RequestMapping(value = "/prices", produces = "application/json") @ResponseBody public String getPrices(HttpServletResponse response) { addCORS(response); logger.debug("Profits requested"); List<PricesOutput> list = ServiceDispatcher.getStockPriceService().getStockPrices(500387); Gson gson = new GsonBuilder() .setDateFormat("dd-MM-yyyy").create(); String jsonProfitOutput = gson.toJson(list); return jsonProfitOutput; } @RequestMapping(value = "/pricesWDC") public ModelAndView getPricesWDC(HttpServletResponse response) { addCORS(response); ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("pricesWDC"); // intercept OPTIONS method return modelAndView; } @RequestMapping(value = "/eps", produces = "application/json") @ResponseBody public String getEps(HttpServletResponse response) { addCORS(response); logger.debug("EPS requested"); List<ReportVariableOutput> list = ServiceDispatcher.getRatioCalculatorService().getEPS(); Gson gson = new GsonBuilder() .setDateFormat("dd-MM-yyyy").create(); String jsonProfitOutput = gson.toJson(list); return jsonProfitOutput; } @RequestMapping(value = "/EPSWDC") public ModelAndView getEPSWDC(HttpServletResponse response) { addCORS(response); ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("EPSWDC"); // intercept OPTIONS method return modelAndView; } public void addCORS(HttpServletResponse response){ response.setHeader( "Pragma", "no-cache" ); response.setHeader( "Cache-Control", "no-cache" ); response.setDateHeader( "Expires", 0 ); response.addHeader("Access-Control-Allow-Origin", "*"); response.addHeader("Access-Control-Allow-Methods", "PUT, GET, POST, DELETE, OPTIONS"); response.addHeader("Access-Control-Allow-Headers", "accept, content-type, x-parse-application-id, x-parse-rest-api-key, x-parse-session-token"); } @RequestMapping(value = "/mcdata", produces = "application/json", method = RequestMethod.GET) @ResponseBody public String MCData(HttpServletResponse response, HttpServletRequest request) { logger.debug("MC Data requested"); List<String> list = new ArrayList<String>(); list.add("ROCE"); list.add("DILUTED EPS"); Map<String, String[]> map = request.getParameterMap(); String industry = map.get(Strings.INDUSTRY)[0]; if(industry==null || industry.equals("")){ return null; } List<List> ratioScripDataMap = ServiceDispatcher.getScripsDataService().getDataForSector(industry, list); List<ScripRatioData> scripRatioDataList = new ArrayList<ScripRatioData>(); for(List li: ratioScripDataMap) { ScripRatioData scripRatioData = new ScripRatioData(); scripRatioData.setRatio((String) li.get(0)); scripRatioData.setReportType((String) li.get(1)); scripRatioData.setName((String) li.get(2)); scripRatioData.setYear_2011((Float)li.get(3)); scripRatioData.setYear_2012((Float)li.get(4)); scripRatioData.setYear_2013((Float)li.get(5)); scripRatioData.setYear_2014((Float)li.get(6)); scripRatioData.setYear_2015((Float)li.get(7)); scripRatioData.setYear_2016((Float)li.get(8)); scripRatioData.setYear_2017((Float)li.get(9)); scripRatioDataList.add(scripRatioData); } addCORS(response); Gson gson = new GsonBuilder().setPrettyPrinting() .setDateFormat("dd-MM-yyyy").create(); String jsonProfitOutput = gson.toJson(scripRatioDataList); return jsonProfitOutput; } @RequestMapping(value = "/mcscrape", produces = "application/json", method = RequestMethod.GET) @ResponseBody public String MCScrape(HttpServletResponse response, HttpServletRequest request){ Map<String, String[]> map = request.getParameterMap(); for(String key: map.keySet()){ logger.info("Parms = " + key); for(String value: map.get(key)){ logger.info("Parm Value = "+ value); } } for(String value: map.get(Strings.INDUSTRY)){ //new MoneyControlScrapper().scrapeForIndustry(value); //new MoneyControlDataIngest().getAllFolders(value); } Gson gson = new GsonBuilder().setPrettyPrinting() .setDateFormat("dd-MM-yyyy").create(); String jsonProfitOutput = gson.toJson(map.get(Strings.INDUSTRY)); return jsonProfitOutput; } @RequestMapping(value = "/portfoliovalue", produces = "application/json", method = RequestMethod.GET) @ResponseBody public String portfolioValue(HttpServletResponse response, HttpServletRequest request){ Map<String, String[]> map = request.getParameterMap(); Integer noOfStocks = map.get(Strings.NAME).length; Float perStockAllocation = 10000.0f/noOfStocks; List<MoneyControlScrips> mcsList = ServiceDispatcher.getMoneyControlScripService().getByNames(Arrays.asList(map.get(Strings.NAME))); Map<Integer, String> bseIdNameMap = new HashMap<Integer, String>(); for(MoneyControlScrips mcs: mcsList){ bseIdNameMap.put(mcs.getBseId(), mcs.getName()); } List<Integer> bseIds = new ArrayList<Integer>(); bseIds.addAll(bseIdNameMap.keySet()); Map<Integer, Map<Date, PricesOutput>> bsePriceMap = ServiceDispatcher.getStockPriceService().getAllStockPrices(bseIds); List<ScripRatioData> scripRatioDataList = new ArrayList<ScripRatioData>(); for(Integer bseId: bsePriceMap.keySet()){ Map<Date, PricesOutput> datePriceMap = bsePriceMap.get(bseId); System.out.println("datePriceMap = " + datePriceMap); ScripRatioData scd = new ScripRatioData(); scd.setName(bseIdNameMap.get(bseId)); scd.setRatio("PRICE"); //2011 Date d2011 = Utils.getDate(2011, 7, 1, Collections.min(datePriceMap.keySet())); System.out.println(d2011); Date p2011 = Utils.nextForward(d2011, datePriceMap.keySet()); System.out.println("found date = " +p2011); if(p2011!=null){ PricesOutput po2011 = datePriceMap.get(p2011); scd.setYear_2011(po2011.getClose()); } //2012 Date d2012 = Utils.getDate(2012, 7, 1, Collections.min(datePriceMap.keySet())); Date p2012 = Utils.nextForward(d2012, datePriceMap.keySet()); if(p2012!=null) { PricesOutput po2012 = datePriceMap.get(p2012); scd.setYear_2012(po2012.getClose()); } //2011 Date d2013 = Utils.getDate(2013, 7, 1, Collections.min(datePriceMap.keySet())); Date p2013 = Utils.nextForward(d2013, datePriceMap.keySet()); if(p2013!=null) { PricesOutput po2013 = datePriceMap.get(p2013); scd.setYear_2013(po2013.getClose()); } //2011 Date d2014 = Utils.getDate(2014, 7, 1, Collections.min(datePriceMap.keySet())); Date p2014 = Utils.nextForward(d2014, datePriceMap.keySet()); if(p2014!=null) { PricesOutput po2014 = datePriceMap.get(p2014); scd.setYear_2014(po2014.getClose()); } //2011 Date d2015 = Utils.getDate(2015, 7, 1, Collections.min(datePriceMap.keySet())); Date p2015 = Utils.nextForward(d2015, datePriceMap.keySet()); if(p2015!=null) { PricesOutput po2015 = datePriceMap.get(p2015); scd.setYear_2015(po2015.getClose()); } //2011 Date d2016 = Utils.getDate(2016, 7, 1, Collections.min(datePriceMap.keySet())); Date p2016 = Utils.nextForward(d2016, datePriceMap.keySet()); if(p2016!=null) { PricesOutput po2016 = datePriceMap.get(p2016); scd.setYear_2016(po2016.getClose()); } //2011 Date d2017 = Utils.getDate(2017, 7, 1, Collections.min(datePriceMap.keySet())); Date p2017 = Utils.nextForward(d2017, datePriceMap.keySet()); if(p2017!=null) { PricesOutput po2017 = datePriceMap.get(p2017); scd.setYear_2017(po2017.getClose()); } scripRatioDataList.add(scd); } Gson gson = new GsonBuilder().setPrettyPrinting() .setDateFormat("dd-MM-yyyy").create(); String jsonScripRatioDataList = gson.toJson(scripRatioDataList); return jsonScripRatioDataList; } }
mit
Belgabor/DrawersBits
src/main/java/mods/belgabor/bitdrawers/storage/BitDrawerData.java
5004
package mods.belgabor.bitdrawers.storage; import com.jaquadro.minecraft.storagedrawers.api.storage.IDrawer; import com.jaquadro.minecraft.storagedrawers.api.storage.IFractionalDrawer; import com.jaquadro.minecraft.storagedrawers.api.storage.attribute.*; import com.jaquadro.minecraft.storagedrawers.storage.BaseDrawerData; import com.jaquadro.minecraft.storagedrawers.storage.ICentralInventory; import mods.belgabor.bitdrawers.BitDrawers; import mods.belgabor.bitdrawers.core.BDLogger; import mods.belgabor.bitdrawers.core.BitHelper; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; /** * Created by Belgabor on 02.06.2016. * Based on CompDrawerData by jaquadro */ public class BitDrawerData extends BaseDrawerData implements IFractionalDrawer, IVoidable, IShroudable, IItemLockable, IQuantifiable { private static final ItemStack nullStack = new ItemStack((Item)null); private ICentralInventory central; private int slot; public BitDrawerData (ICentralInventory centralInventory, int slot) { this.slot = slot; this.central = centralInventory; } @Override public ItemStack getStoredItemPrototype () { return central.getStoredItemPrototype(slot); } @Override public void setStoredItem (ItemStack itemPrototype, int amount) { if (BitDrawers.config.debugTrace) BDLogger.info("setStoredItem %d %s %d", slot, itemPrototype==null?"null":itemPrototype.getDisplayName(), amount); central.setStoredItem(slot, itemPrototype, amount); refresh(); // markDirty } @Override public IDrawer setStoredItemRedir (ItemStack itemPrototype, int amount) { IDrawer target = central.setStoredItem(slot, itemPrototype, amount); refresh(); return target; } @Override public boolean areItemsEqual(ItemStack item) { ItemStack protoStack = this.getStoredItemPrototype(); return BitHelper.areItemsEqual(item, protoStack); } @Override public int getStoredItemCount () { return central.getStoredItemCount(slot); } @Override public void setStoredItemCount (int amount) { central.setStoredItemCount(slot, amount); } @Override public int getMaxCapacity () { return central.getMaxCapacity(slot); } @Override public int getMaxCapacity (ItemStack itemPrototype) { return central.getMaxCapacity(slot, itemPrototype); } @Override public int getRemainingCapacity () { return central.getRemainingCapacity(slot); } @Override public int getStoredItemStackSize () { return central.getStoredItemStackSize(slot); } @Override protected int getItemCapacityForInventoryStack () { return central.getItemCapacityForInventoryStack(slot); } @Override public boolean canItemBeStored (ItemStack itemPrototype) { if (getStoredItemPrototype() == null && !isItemLocked(LockAttribute.LOCK_EMPTY)) { return BitHelper.getBit(itemPrototype) != null || BitHelper.getBlock(itemPrototype) != null; } return areItemsEqual(itemPrototype); } @Override public boolean canItemBeExtracted (ItemStack itemPrototype) { return areItemsEqual(itemPrototype); } @Override public boolean isEmpty () { return getStoredItemPrototype() == null; } @Override public void writeToNBT (NBTTagCompound tag) { central.writeToNBT(slot, tag); } @Override public void readFromNBT (NBTTagCompound tag) { central.readFromNBT(slot, tag); refresh(); } @Override public int getConversionRate () { return central.getConversionRate(slot); } @Override public int getStoredItemRemainder () { return central.getStoredItemRemainder(slot); } @Override public boolean isSmallestUnit () { return central.isSmallestUnit(slot); } public void refresh () { reset(); refreshOreDictMatches(); } @Override public boolean isVoid () { return central.isVoidSlot(slot); } @Override public boolean isShrouded () { return central.isShroudedSlot(slot); } @Override public boolean setIsShrouded (boolean state) { return central.setIsSlotShrouded(slot, state); } @Override public boolean isShowingQuantity () { return central.isSlotShowingQuantity(slot); } @Override public boolean setIsShowingQuantity (boolean state) { return central.setIsSlotShowingQuantity(slot, state); } @Override public boolean isItemLocked (LockAttribute attr) { return central.isLocked(slot, attr); } @Override public boolean canItemLock (LockAttribute attr) { return false; } @Override public void setItemLocked (LockAttribute attr, boolean isLocked) { } }
mit
clarks3/ConnectFour-Lookuptree
src/updatedfiles/src/Experience.java
1845
public class Experience { final int WIN = 2; final int LOSS = 1; final int UNKNOWN = 0; final int DRAW = 3; final int ILLEGAL = 4; final int PLAYER_1 = 1; final int PLAYER_2 = 2; final int EMPTY = 0; public void writeFile(String name, String contents) { } public String readFile(String name) { return name; } public String generateOldBoardState(String state, int moves ) { return state; } /* * Takes a given string and modifies a specified character of that string * to a specified value. * * @param which the character of the string to modify; Zero based indexing. * @param result the character that replaces character at the specified index. * @param outcomes the original outcomes before modification. * @return the modified string. */ public static String editOutcomes(int which, int result, String outcomes) { String modifiedOutcomes=""; // Bounds Checking if(which >= outcomes.length() || which < 0) { modifiedOutcomes = "The specifed character is outside of the string."; } else { modifiedOutcomes += outcomes.substring(0,which); modifiedOutcomes += String.valueOf(result); modifiedOutcomes += outcomes.substring(which+1); } return modifiedOutcomes; } public static void main(String[] args) { String Test = "10010001001001"; System.out.println(Test); System.out.println(editOutcomes(1,9,Test).equals("19010001001001")); System.out.println(editOutcomes(99,0,Test).equals("The specifed character is outside of the string.")); System.out.println(editOutcomes(0,9,Test).equals("90010001001001")); System.out.println(editOutcomes(13,9,Test).equals("10010001001009")); } }
mit
KoljaTM/HoebApp
app/src/main/java/de/vanmar/android/hoebapp/db/MediaContentProvider.java
7530
package de.vanmar.android.hoebapp.db; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import android.content.ContentProvider; import android.content.ContentProviderOperation; import android.content.ContentProviderResult; import android.content.ContentResolver; import android.content.ContentValues; import android.content.OperationApplicationException; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; import android.text.TextUtils; public class MediaContentProvider extends ContentProvider { // database private HoebAppDbHelper database; // Used for the UriMacher private static final int MEDIA = 10; private static final int MEDIA_ID = 20; private static final int AGGREGATE = 30; private static final int REFRESH = 40; public static final String AUTHORITY = "de.vanmar.android.hoebapp.contentprovider.media"; private static final String BASE_PATH = "media"; public static final String MEDIA_AGGREGATE = "/media_aggregate"; public static final String MEDIA_REFRESH = "/refresh"; private static final String AGGREGATE_PATH = BASE_PATH + MEDIA_AGGREGATE; private static final String REFRESH_PATH = BASE_PATH + MEDIA_REFRESH; public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + BASE_PATH); public static final String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + "/media"; public static final String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/media_item"; public static final String CONTENT_AGGREGATE_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE + MEDIA_AGGREGATE; public static final int COLUMN_INDEX_AGGREGATE_COUNT = 0; public static final int COLUMN_INDEX_AGGREGATE_MIN_DUEDATE = 1; private static final String AGGREGATE_QUERY = String.format( "Select count(*), min(%s) from %s", MediaDbHelper.COLUMN_DUEDATE, MediaDbHelper.MEDIA_TABLE_NAME); private static final UriMatcher sURIMatcher = new UriMatcher( UriMatcher.NO_MATCH); static { sURIMatcher.addURI(AUTHORITY, BASE_PATH, MEDIA); sURIMatcher.addURI(AUTHORITY, BASE_PATH + "/#", MEDIA_ID); sURIMatcher.addURI(AUTHORITY, AGGREGATE_PATH, AGGREGATE); sURIMatcher.addURI(AUTHORITY, REFRESH_PATH, REFRESH); } @Override public boolean onCreate() { database = new HoebAppDbHelper(getContext()); return false; } @Override public ContentProviderResult[] applyBatch( final ArrayList<ContentProviderOperation> operations) throws OperationApplicationException { try { database.getWritableDatabase().beginTransaction(); final ContentProviderResult[] result = super.applyBatch(operations); database.getWritableDatabase().setTransactionSuccessful(); return result; } finally { database.getWritableDatabase().endTransaction(); } } @Override public int delete(final Uri uri, final String selection, final String[] selectionArgs) { final int uriType = sURIMatcher.match(uri); final SQLiteDatabase sqlDB = database.getWritableDatabase(); int rowsDeleted = 0; switch (uriType) { case MEDIA: rowsDeleted = sqlDB.delete(MediaDbHelper.MEDIA_TABLE_NAME, selection, selectionArgs); break; case MEDIA_ID: final String id = uri.getLastPathSegment(); if (TextUtils.isEmpty(selection)) { rowsDeleted = sqlDB.delete(MediaDbHelper.MEDIA_TABLE_NAME, MediaDbHelper.COLUMN_ID + "=" + id, null); } else { rowsDeleted = sqlDB.delete(MediaDbHelper.MEDIA_TABLE_NAME, MediaDbHelper.COLUMN_ID + "=" + id + " and " + selection, selectionArgs); } break; default: throw new IllegalArgumentException("Unknown URI: " + uri); } getContext().getContentResolver().notifyChange(uri, null); return rowsDeleted; } @Override public String getType(final Uri arg0) { // TODO Auto-generated method stub return null; } @Override public Uri insert(final Uri uri, final ContentValues values) { final int uriType = sURIMatcher.match(uri); final SQLiteDatabase sqlDB = database.getWritableDatabase(); long id = 0; switch (uriType) { case MEDIA: id = sqlDB.insert(MediaDbHelper.MEDIA_TABLE_NAME, null, values); break; default: throw new IllegalArgumentException("Unknown URI: " + uri); } getContext().getContentResolver().notifyChange(uri, null); return Uri.parse(BASE_PATH + "/" + id); } @Override public Cursor query(final Uri uri, final String[] projection, final String selection, final String[] selectionArgs, final String sortOrder) { // Using SQLiteQueryBuilder instead of query() method final SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder(); // Check if the caller has requested a column which does not exists checkColumns(projection); // Set the table queryBuilder.setTables(MediaDbHelper.MEDIA_TABLE_NAME); final int uriType = sURIMatcher.match(uri); switch (uriType) { case MEDIA: break; case MEDIA_ID: // Adding the ID to the original query queryBuilder.appendWhere(MediaDbHelper.COLUMN_ID + "=" + uri.getLastPathSegment()); break; case AGGREGATE: final Cursor cursor = getCursorForAggregateQuery(); // Make sure that potential listeners are getting notified cursor.setNotificationUri(getContext().getContentResolver(), uri); return cursor; case REFRESH: database.getWritableDatabase().close(); break; default: throw new IllegalArgumentException("Unknown URI: " + uri); } final SQLiteDatabase db = database.getReadableDatabase(); final Cursor cursor = queryBuilder.query(db, projection, selection, selectionArgs, null, null, sortOrder); // Make sure that potential listeners are getting notified cursor.setNotificationUri(getContext().getContentResolver(), uri); return cursor; } private Cursor getCursorForAggregateQuery() { final SQLiteDatabase db = database.getWritableDatabase(); final Cursor cursor = db.rawQuery(AGGREGATE_QUERY, null); return cursor; } @Override public int update(final Uri uri, final ContentValues values, final String selection, final String[] selectionArgs) { final int uriType = sURIMatcher.match(uri); final SQLiteDatabase sqlDB = database.getWritableDatabase(); int rowsUpdated = 0; switch (uriType) { case MEDIA: rowsUpdated = sqlDB.update(MediaDbHelper.MEDIA_TABLE_NAME, values, selection, selectionArgs); break; case MEDIA_ID: final String id = uri.getLastPathSegment(); if (TextUtils.isEmpty(selection)) { rowsUpdated = sqlDB.update(MediaDbHelper.MEDIA_TABLE_NAME, values, MediaDbHelper.COLUMN_ID + "=" + id, null); } else { rowsUpdated = sqlDB.update(MediaDbHelper.MEDIA_TABLE_NAME, values, MediaDbHelper.COLUMN_ID + "=" + id + " and " + selection, selectionArgs); } break; default: throw new IllegalArgumentException("Unknown URI: " + uri); } getContext().getContentResolver().notifyChange(uri, null); return rowsUpdated; } private void checkColumns(final String[] projection) { if (projection != null) { final HashSet<String> requestedColumns = new HashSet<String>( Arrays.asList(projection)); final HashSet<String> availableColumns = new HashSet<String>( Arrays.asList(MediaDbHelper.ALL_COLUMNS)); // Check if all columns which are requested are available if (!availableColumns.containsAll(requestedColumns)) { throw new IllegalArgumentException( "Unknown columns in projection"); } } } }
mit
mpgarate/Production-Quality-Software
PS1_fa14/src/test/edu/nyu/mpgarate/pqs1/AddressBookSerializationTest.java
1846
package edu.nyu.mpgarate.pqs1; import static org.junit.Assert.assertEquals; import java.io.File; import java.io.IOException; import org.junit.Test; import edu.nyu.mpgarate.pqs1.AddressBook; import edu.nyu.mpgarate.pqs1.Contact; import edu.nyu.mpgarate.pqs1.ContactBuilder; public class AddressBookSerializationTest { @Test public void writeAndReadAddressBookViaJson() throws IOException { AddressBook originalAddressBook = new AddressBook(); Contact contact1 = new ContactBuilder().withName("John Doe") .withPostalAddress("310 3rd Avenue NY, NY") .withEmailAddress("johndoe@example.com") .withNote("lorem ipsum dolor sit amet") .withPhoneNumber("2405555123").build(); Contact contact2 = new ContactBuilder().withName("Andrew Smith").build(); Contact contact3 = new ContactBuilder().withName("Beth Smith") .withPostalAddress("190 Mercer St").build(); originalAddressBook.add(contact1); originalAddressBook.add(contact2); originalAddressBook.add(contact3); String targetFilePath = new File("src/test/resources/addressbook.json").getAbsolutePath(); File targetFile = new File(targetFilePath); originalAddressBook.writeTo(targetFile); AddressBook newAddressBook = new AddressBook(); newAddressBook.readFrom(targetFile); Contact newContact1 = newAddressBook.search("John Doe").get(0); Contact newContact2 = newAddressBook.search("Andrew Smith").get(0); Contact newContact3 = newAddressBook.search("Beth Smith").get(0); assertEquals(contact1.getUniqueId(), newContact1.getUniqueId()); assertEquals(contact2.getName(), newContact2.getName()); assertEquals(contact3.getPostalAddress(), newContact3.getPostalAddress()); } }
mit
razakal/Qora
Qora/src/gui/transaction/RegisterNameDetailsFrame.java
5167
package gui.transaction; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Image; import java.awt.Insets; import java.awt.Toolkit; import java.text.DateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.swing.*; import javax.swing.border.EmptyBorder; import qora.crypto.Base58; import qora.transaction.RegisterNameTransaction; @SuppressWarnings("serial") public class RegisterNameDetailsFrame extends JFrame { public RegisterNameDetailsFrame(RegisterNameTransaction nameRegistration) { super("Qora - Transaction Details"); //ICON List<Image> icons = new ArrayList<Image>(); icons.add(Toolkit.getDefaultToolkit().getImage("images/icons/icon16.png")); icons.add(Toolkit.getDefaultToolkit().getImage("images/icons/icon32.png")); icons.add(Toolkit.getDefaultToolkit().getImage("images/icons/icon64.png")); icons.add(Toolkit.getDefaultToolkit().getImage("images/icons/icon128.png")); this.setIconImages(icons); //CLOSE setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); //LAYOUT this.setLayout(new GridBagLayout()); //PADDING ((JComponent) this.getContentPane()).setBorder(new EmptyBorder(5, 5, 5, 5)); //LABEL GBC GridBagConstraints labelGBC = new GridBagConstraints(); labelGBC.insets = new Insets(0, 5, 5, 0); labelGBC.fill = GridBagConstraints.HORIZONTAL; labelGBC.anchor = GridBagConstraints.NORTHWEST; labelGBC.weightx = 0; labelGBC.gridx = 0; //DETAIL GBC GridBagConstraints detailGBC = new GridBagConstraints(); detailGBC.insets = new Insets(0, 5, 5, 0); detailGBC.fill = GridBagConstraints.HORIZONTAL; detailGBC.anchor = GridBagConstraints.NORTHWEST; detailGBC.weightx = 1; detailGBC.gridwidth = 2; detailGBC.gridx = 1; //LABEL TYPE labelGBC.gridy = 0; JLabel typeLabel = new JLabel("Type:"); this.add(typeLabel, labelGBC); //TYPE detailGBC.gridy = 0; JLabel type = new JLabel("Register Name Transaction"); this.add(type, detailGBC); //LABEL SIGNATURE labelGBC.gridy = 1; JLabel signatureLabel = new JLabel("Signature:"); this.add(signatureLabel, labelGBC); //SIGNATURE detailGBC.gridy = 1; JTextField signature = new JTextField(Base58.encode(nameRegistration.getSignature())); signature.setEditable(false); this.add(signature, detailGBC); //LABEL REFERENCE labelGBC.gridy = 2; JLabel referenceLabel = new JLabel("Reference:"); this.add(referenceLabel, labelGBC); //REFERENCE detailGBC.gridy = 2; JTextField reference = new JTextField(Base58.encode(nameRegistration.getReference())); reference.setEditable(false); this.add(reference, detailGBC); //LABEL TIMESTAMP labelGBC.gridy = 3; JLabel timestampLabel = new JLabel("Timestamp:"); this.add(timestampLabel, labelGBC); //TIMESTAMP detailGBC.gridy = 3; Date date = new Date(nameRegistration.getTimestamp()); DateFormat format = DateFormat.getDateTimeInstance(); JLabel timestamp = new JLabel(format.format(date)); this.add(timestamp, detailGBC); //LABEL REGISTRANT labelGBC.gridy = 4; JLabel registrantLabel = new JLabel("Registrant:"); this.add(registrantLabel, labelGBC); //REGISTRANT detailGBC.gridy = 4; JTextField registrant = new JTextField(nameRegistration.getRegistrant().getAddress()); registrant.setEditable(false); this.add(registrant, detailGBC); //LABEL OWNER labelGBC.gridy = 5; JLabel ownerLabel = new JLabel("Owner:"); this.add(ownerLabel, labelGBC); //OWNER detailGBC.gridy = 5; JTextField owner = new JTextField(nameRegistration.getName().getOwner().getAddress()); owner.setEditable(false); this.add(owner, detailGBC); //LABEL NAME labelGBC.gridy = 6; JLabel nameLabel = new JLabel("Name:"); this.add(nameLabel, labelGBC); //NAME detailGBC.gridy = 6; JTextField name = new JTextField(nameRegistration.getName().getName()); name.setEditable(false); this.add(name, detailGBC); //LABEL VALUE labelGBC.gridy = 7; JLabel valueLabel = new JLabel("Value:"); this.add(valueLabel, labelGBC); //VALUE detailGBC.gridy = 7; JTextArea txtAreaValue = new JTextArea(nameRegistration.getName().getValue()); txtAreaValue.setRows(4); txtAreaValue.setBorder(name.getBorder()); txtAreaValue.setEditable(false); this.add(txtAreaValue, detailGBC); //LABEL FEE labelGBC.gridy = 8; JLabel feeLabel = new JLabel("Fee:"); this.add(feeLabel, labelGBC); //FEE detailGBC.gridy = 8; JTextField fee = new JTextField(nameRegistration.getFee().toPlainString()); fee.setEditable(false); this.add(fee, detailGBC); //LABEL CONFIRMATIONS labelGBC.gridy = 9; JLabel confirmationsLabel = new JLabel("Confirmations:"); this.add(confirmationsLabel, labelGBC); //CONFIRMATIONS detailGBC.gridy = 9; JLabel confirmations = new JLabel(String.valueOf(nameRegistration.getConfirmations())); this.add(confirmations, detailGBC); //PACK this.pack(); this.setResizable(false); this.setLocationRelativeTo(null); this.setVisible(true); } }
mit
AmethystAir/ExtraCells2
src/main/scala/extracells/block/BlockCertusTank.java
6897
package extracells.block; import appeng.api.implementations.items.IAEWrench; import buildcraft.api.tools.IToolWrench; import extracells.Extracells; import extracells.network.ChannelHandler; import extracells.registries.BlockEnum; import extracells.render.RenderHandler; import extracells.tileentity.TileEntityCertusTank; import net.minecraft.block.Block; import net.minecraft.block.ITileEntityProvider; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.tileentity.TileEntity; import net.minecraft.util.IIcon; import net.minecraft.util.MovingObjectPosition; import net.minecraft.util.StatCollector; import net.minecraft.world.World; import net.minecraftforge.common.util.ForgeDirection; import net.minecraftforge.fluids.FluidContainerRegistry; import net.minecraftforge.fluids.FluidStack; public class BlockCertusTank extends Block implements ITileEntityProvider { IIcon breakIcon; IIcon topIcon; IIcon bottomIcon; IIcon sideIcon; IIcon sideMiddleIcon; IIcon sideTopIcon; IIcon sideBottomIcon; public BlockCertusTank() { super(Material.glass); setCreativeTab(Extracells.ModTab()); setHardness(2.0F); setResistance(10.0F); setBlockBounds(0.0625F, 0.0F, 0.0625F, 0.9375F, 1.0F, 0.9375F); } @Override public boolean canRenderInPass(int pass) { RenderHandler.renderPass = pass; return true; } @Override public TileEntity createNewTileEntity(World var1, int var2) { return new TileEntityCertusTank(); } public ItemStack getDropWithNBT(World world, int x, int y, int z) { NBTTagCompound tileEntity = new NBTTagCompound(); TileEntity worldTE = world.getTileEntity(x, y, z); if (worldTE != null && worldTE instanceof TileEntityCertusTank) { ItemStack dropStack = new ItemStack( BlockEnum.CERTUSTANK.getBlock(), 1); ((TileEntityCertusTank) worldTE) .writeToNBTWithoutCoords(tileEntity); if (!tileEntity.hasKey("Empty")) { dropStack.setTagCompound(new NBTTagCompound()); dropStack.stackTagCompound.setTag("tileEntity", tileEntity); } return dropStack; } return null; } @Override public IIcon getIcon(int side, int b) { switch (b) { case 1: return this.sideTopIcon; case 2: return this.sideBottomIcon; case 3: return this.sideMiddleIcon; default: return side == 0 ? this.bottomIcon : side == 1 ? this.topIcon : this.sideIcon; } } @Override public String getLocalizedName() { return StatCollector.translateToLocal(getUnlocalizedName() + ".name"); } @Override public ItemStack getPickBlock(MovingObjectPosition target, World world, int x, int y, int z) { return getDropWithNBT(world, x, y, z); } @Override public int getRenderBlockPass() { return 1; } @Override public int getRenderType() { return RenderHandler.getId(); } @Override public String getUnlocalizedName() { return super.getUnlocalizedName().replace("tile.", ""); } @Override public boolean isOpaqueCube() { return false; } @Override public boolean onBlockActivated(World worldObj, int x, int y, int z, EntityPlayer entityplayer, int blockID, float offsetX, float offsetY, float offsetZ) { ItemStack current = entityplayer.inventory.getCurrentItem(); if (entityplayer.isSneaking() && current != null) { try { if (current.getItem() instanceof IToolWrench && ((IToolWrench) current.getItem()).canWrench( entityplayer, x, y, z)) { dropBlockAsItem(worldObj, x, y, z, getDropWithNBT(worldObj, x, y, z)); worldObj.setBlockToAir(x, y, z); ((IToolWrench) current.getItem()).wrenchUsed(entityplayer, x, y, z); return true; } } catch (Throwable e) { // No IToolWrench } if (current.getItem() instanceof IAEWrench && ((IAEWrench) current.getItem()).canWrench(current, entityplayer, x, y, z)) { dropBlockAsItem(worldObj, x, y, z, getDropWithNBT(worldObj, x, y, z)); worldObj.setBlockToAir(x, y, z); return true; } } if (current != null) { FluidStack liquid = FluidContainerRegistry .getFluidForFilledItem(current); TileEntityCertusTank tank = (TileEntityCertusTank) worldObj .getTileEntity(x, y, z); if (liquid != null) { int amountFilled = tank.fill(ForgeDirection.UNKNOWN, liquid, true); if (amountFilled != 0 && !entityplayer.capabilities.isCreativeMode) { if (current.stackSize > 1) { entityplayer.inventory.mainInventory[entityplayer.inventory.currentItem].stackSize -= 1; entityplayer.inventory.addItemStackToInventory(current .getItem().getContainerItem(current)); } else { entityplayer.inventory.mainInventory[entityplayer.inventory.currentItem] = current .getItem().getContainerItem(current); } } return true; // Handle empty containers } else { FluidStack available = tank.getTankInfo(ForgeDirection.UNKNOWN)[0].fluid; if (available != null) { ItemStack filled = FluidContainerRegistry .fillFluidContainer(available, current); liquid = FluidContainerRegistry .getFluidForFilledItem(filled); if (liquid != null) { if (!entityplayer.capabilities.isCreativeMode) { if (current.stackSize > 1) { if (!entityplayer.inventory .addItemStackToInventory(filled)) { tank.fill(ForgeDirection.UNKNOWN, new FluidStack(liquid, liquid.amount), true); return false; } else { entityplayer.inventory.mainInventory[entityplayer.inventory.currentItem].stackSize -= 1; } } else { entityplayer.inventory.mainInventory[entityplayer.inventory.currentItem] = filled; } } tank.drain(ForgeDirection.UNKNOWN, liquid.amount, true); return true; } } } } return false; } @Override public void onNeighborBlockChange(World world, int x, int y, int z, Block neighborBlock) { if (!world.isRemote) { ChannelHandler.sendPacketToAllPlayers(world.getTileEntity(x, y, z) .getDescriptionPacket(), world); } } @Override public void registerBlockIcons(IIconRegister iconregister) { this.breakIcon = iconregister.registerIcon("extracells:certustank"); this.topIcon = iconregister.registerIcon("extracells:CTankTop"); this.bottomIcon = iconregister.registerIcon("extracells:CTankBottom"); this.sideIcon = iconregister.registerIcon("extracells:CTankSide"); this.sideMiddleIcon = iconregister .registerIcon("extracells:CTankSideMiddle"); this.sideTopIcon = iconregister.registerIcon("extracells:CTankSideTop"); this.sideBottomIcon = iconregister .registerIcon("extracells:CTankSideBottom"); } @Override public boolean renderAsNormalBlock() { return false; } }
mit
fredyw/leetcode
src/main/java/leetcode/Problem2011.java
472
package leetcode; /** * https://leetcode.com/problems/final-value-of-variable-after-performing-operations/ */ public class Problem2011 { public int finalValueAfterOperations(String[] operations) { int answer = 0; for (String operation : operations) { if (operation.equals("--X") || operation.equals("X--")) { answer--; } else { answer++; } } return answer; } }
mit
everKalle/ExperienceSamplingApplication
ExperienceSamplingApp/app/src/main/java/com/example/madiskar/experiencesamplingapp/activities/LoginActivity.java
11798
package com.example.madiskar.experiencesamplingapp.activities; import android.app.ProgressDialog; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.view.WindowManager; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.example.madiskar.experiencesamplingapp.background_tasks.ExecutorSupplier; import com.example.madiskar.experiencesamplingapp.R; import com.example.madiskar.experiencesamplingapp.receivers.ResponseReceiver; import com.example.madiskar.experiencesamplingapp.background_tasks.GetParticipantStudiesTask; import com.example.madiskar.experiencesamplingapp.data_types.Study; import com.example.madiskar.experiencesamplingapp.interfaces.RunnableResponse; import com.example.madiskar.experiencesamplingapp.local_database.DBHandler; import org.json.JSONArray; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; public class LoginActivity extends AppCompatActivity { private EditText emailField; private EditText pwdField; private Button loginbtn; private Button signupbtn; private SharedPreferences sharedPref; private HttpsURLConnection connection; private OutputStreamWriter wr; private BufferedReader reader; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN); sharedPref = getApplicationContext().getSharedPreferences("com.example.madiskar.ExperienceSampler", Context.MODE_PRIVATE); int loggedIn = sharedPref.getInt("LoggedIn", 0); if(loggedIn == 1) { Intent intent = new Intent(LoginActivity.this, MainActivity.class); startActivity(intent); } else { setContentView(R.layout.activity_login); emailField = (EditText) findViewById(R.id.email_input); pwdField = (EditText) findViewById(R.id.password_input); loginbtn = (Button) findViewById(R.id.button_login); signupbtn = (Button) findViewById(R.id.button_signup); loginbtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { login(); } }); signupbtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(LoginActivity.this, RegisterActivity.class); startActivity(intent); } }); } } @Override public void onBackPressed() { moveTaskToBack(true); } private boolean login() { if (!validateInput()) { Toast.makeText(getBaseContext(), getString(R.string.wrong_format), Toast.LENGTH_LONG).show(); loginbtn.setEnabled(true); return false; } if(!isNetworkAvailable()) { Toast.makeText(getBaseContext(), getString(R.string.no_internet) , Toast.LENGTH_LONG).show(); loginbtn.setEnabled(true); return false; } loginbtn.setEnabled(false); final ProgressDialog progressDialog = new ProgressDialog(LoginActivity.this, R.style.AppTheme_Dark_Dialog); progressDialog.setIndeterminate(true); progressDialog.setMessage(getString(R.string.wait)); progressDialog.setCanceledOnTouchOutside(false); progressDialog.show(); new AsyncTask<String, Void, String>() { @Override protected String doInBackground(String... params) { try { String link = "https://experiencesampling.herokuapp.com/index.php/participant/login"; String data = URLEncoder.encode("email", "UTF-8") + "=" + URLEncoder.encode(params[0], "UTF-8"); data += "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(params[1], "UTF-8"); connection = (HttpsURLConnection) new URL(link).openConnection(); SSLContext sc; sc = SSLContext.getInstance("TLS"); sc.init(null, null, new java.security.SecureRandom()); connection.setSSLSocketFactory(sc.getSocketFactory()); //send data connection.setRequestMethod("POST"); connection.setReadTimeout(15000); connection.setConnectTimeout(20000); connection.setDoOutput(true); wr = new OutputStreamWriter(connection.getOutputStream()); wr.write(data); wr.flush(); //read response reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line); } return sb.toString(); } catch (Exception e) { return "Exception: " + e.getMessage(); } finally { if(wr != null) { try { wr.close(); } catch (IOException e) { e.printStackTrace(); } } if(reader != null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } if(connection != null) { connection.disconnect(); } } } @Override protected void onPostExecute(final String result) { if(result.equals("nothing")) { loginbtn.setEnabled(true); progressDialog.dismiss(); Toast.makeText(getApplicationContext(), getString(R.string.log_fail), Toast.LENGTH_LONG).show(); } else if(result.equals("invalid")) { loginbtn.setEnabled(true); progressDialog.dismiss(); Toast.makeText(getApplicationContext(), getString(R.string.wrong), Toast.LENGTH_LONG).show(); } else if(!result.equals(getString(R.string.not_established))) { final Intent intent = new Intent(LoginActivity.this, MainActivity.class); progressDialog.dismiss(); final ProgressDialog fetchDataDialog = new ProgressDialog(LoginActivity.this, R.style.AppTheme_Dark_Dialog); fetchDataDialog.setIndeterminate(true); fetchDataDialog.setMessage(getString(R.string.fetching)); fetchDataDialog.setCanceledOnTouchOutside(false); fetchDataDialog.show(); GetParticipantStudiesTask task1 = new GetParticipantStudiesTask(result, new RunnableResponse() { @Override public void processFinish(String output) { if(output.equals("invalid_token")) { loginbtn.setEnabled(true); fetchDataDialog.dismiss(); Toast.makeText(LoginActivity.this, getString(R.string.auth_fail), Toast.LENGTH_LONG).show(); } else if(output.equals("nothing")) { loginbtn.setEnabled(true); fetchDataDialog.dismiss(); Toast.makeText(LoginActivity.this, getString(R.string.fetch_fail), Toast.LENGTH_LONG).show(); } else { DBHandler mydb = DBHandler.getInstance(getApplicationContext()); mydb.clearTables(); try { JSONArray jsonArray = DBHandler.parseJsonString(output); ArrayList<Study> studies = DBHandler.jsonArrayToStudyArray(jsonArray, true); for (Study s : studies) { // add studies to local db and also set up alarms mydb.insertStudy(s); } for (Study s : studies) { ResponseReceiver rR = new ResponseReceiver(s); rR.setupAlarm(getApplicationContext(), true); } SharedPreferences.Editor editor = sharedPref.edit(); editor.putString("token", result); editor.putInt("LoggedIn", 1); editor.putString("username", emailField.getText().toString()); editor.apply(); fetchDataDialog.dismiss(); startActivity(intent); finish(); } catch (Exception e) { loginbtn.setEnabled(true); fetchDataDialog.dismiss(); Toast.makeText(getApplicationContext(), getString(R.string.log_fail), Toast.LENGTH_LONG).show(); } } } }); ExecutorSupplier.getInstance().forBackgroundTasks().execute(task1); } else { loginbtn.setEnabled(true); progressDialog.dismiss(); Toast.makeText(getApplicationContext(), getString(R.string.log_fail), Toast.LENGTH_SHORT).show(); } } }.execute(emailField.getText().toString(), DBHandler.hashSha256(pwdField.getText().toString())); return true; } private boolean validateInput() { boolean isValid = true; String email = emailField.getText().toString(); String pwd = pwdField.getText().toString(); if(email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) { emailField.setError(getString(R.string.enter_valid)); isValid = false; } if(pwd.isEmpty() || pwd.length() > 16 || pwd.length() < 6) { pwdField.setError(getString(R.string.enter_pass)); isValid = false; } return isValid; } private boolean isNetworkAvailable() { ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo(); return activeNetworkInfo != null && activeNetworkInfo.isConnected(); } }
mit
RMuskovets/JLibs
JLibs/src/com/roman/util/RandomList.java
1397
package com.roman.util; import java.util.*; /** * Created by LINKOR on 11.11.2016 in 15:50. * Date: 2016.11.11 */ public class RandomList<E> { private ArrayList<E> storage; private Random r = new Random(); public RandomList() { super(); } public int size() { return storage.size(); } public boolean empty() { return storage.isEmpty(); } public E get(int index) { return storage.get(index); } public E set(int index, E element) { return storage.set(index, element); } public void add(E e) { storage.add(e); } public void add(int index, E element) { storage.add(index, element); } public E remove(int index) { return storage.remove(index); } public ListIterator<E> listIterator(int index) { return storage.listIterator(index); } public ListIterator<E> listIterator() { return storage.listIterator(); } public Spliterator<E> spliterator() { return storage.spliterator(); } public boolean containsAll(Collection<?> c) { return storage.containsAll(c); } @SafeVarargs public RandomList(E... elems) { storage = new ArrayList<E>(Arrays.asList(elems)); } public E select() { return get(r.nextInt(size())); } }
mit
DIKU-Steiner/ProGAL
src/ProGAL/dataStructures/rangeSearching/rangeTree2/NaivRangeArray.java
1575
package ProGAL.dataStructures.rangeSearching.rangeTree2; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import ProGAL.geomNd.Point; /** * This class models a simple list which implements the Query-method in O(n) time. * @author Søren Lynnerup 11.01.2012 */ public class NaivRangeArray { private List<Point> points; private int dimensions; /** * Initialize the NaivRangeArray. */ public NaivRangeArray(List<Point> points) { this.dimensions = points.get(0).getDimensions(); this.points = points; } /** * Return the points inside the given range. */ public List<Point> query(double[] low, double[] high) { // Make sure low <= high for every dimension. for(int dimension = 0; dimension < this.dimensions; dimension++) { if(low[dimension] > high[dimension]) { double temp = low[dimension]; low[dimension] = high[dimension]; high[dimension] = temp; } } // Initialize variables. Iterator<Point> iter = this.points.iterator(); List<Point> reported = new ArrayList<Point>(); // Run through every point and check if it is inside the interval. while(iter.hasNext()) { Point p = iter.next(); boolean report = true; // Check that each dimension is inside the interval. for(int d = 0; d < this.dimensions; d++) { report = report && (p.get(d) >= low[d] && p.get(d) <= high[d]); } // Check if the point should be reported. if(report) { reported.add(p); } } return reported; } }
mit
payjp/payjp-java
src/main/java/jp/pay/model/Subscription.java
9380
/* * Copyright (c) 2010-2011 Stripe (http://stripe.com) * Copyright (c) 2015 Base, Inc. (http://binc.jp/) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ package jp.pay.model; import java.util.Map; import java.util.HashMap; import jp.pay.exception.APIConnectionException; import jp.pay.exception.APIException; import jp.pay.exception.AuthenticationException; import jp.pay.exception.CardException; import jp.pay.exception.InvalidRequestException; import jp.pay.net.APIResource; import jp.pay.net.RequestOptions; public class Subscription extends APIResource implements MetadataStore<Subscription> { Long canceledAt; Long created; Long currentPeriodEnd; Long currentPeriodStart; String customer; String id; Boolean livemode; Long pausedAt; Plan plan; Plan nextCyclePlan; Long resumedAt; Long start; String status; Long trialEnd; Long trialStart; Map<String, String> metadata = new HashMap<String, String>(); public static Subscription create(Map<String, Object> params) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return create(params, (RequestOptions) null); } public static Subscription create(Map<String, Object> params, RequestOptions options) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return request(RequestMethod.POST, classURL(Subscription.class), params, Subscription.class, options); } public static Subscription retrieve(String id) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return retrieve(id, (RequestOptions) null); } public static Subscription retrieve(String id, RequestOptions options) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return request(RequestMethod.GET, instanceURL(Subscription.class, id), null, Subscription.class, options); } public Subscription update(Map<String, Object> params) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return update(params, (RequestOptions) null); } public Subscription update(Map<String, Object> params, RequestOptions options) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return request(RequestMethod.POST, instanceURL(Subscription.class, id), params, Subscription.class, options); } public static SubscriptionCollection all(Map<String, Object> params) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return all(params, (RequestOptions) null); } public static SubscriptionCollection all(Map<String, Object> params, RequestOptions options) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return request(RequestMethod.GET, classURL(Subscription.class), params, SubscriptionCollection.class, options); } public Subscription pause() throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return this.pause(null, (RequestOptions) null); } public Subscription pause(RequestOptions options) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return this.pause(null, options); } public Subscription pause(Map<String, Object> params, RequestOptions options) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return request(RequestMethod.POST, String.format("%s/pause", instanceURL(Subscription.class, this.getId())), params, Subscription.class, options); } public Subscription resume() throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return this.resume(null, (RequestOptions) null); } public Subscription resume(RequestOptions options) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return this.resume(null, options); } public Subscription resume(Map<String, Object> params, RequestOptions options) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return request(RequestMethod.POST, String.format("%s/resume", instanceURL(Subscription.class, this.getId())), params, Subscription.class, options); } public Subscription cancel() throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return this.cancel(null, (RequestOptions) null); } public Subscription cancel(RequestOptions options) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return this.cancel(null, options); } public Subscription cancel(Map<String, Object> params, RequestOptions options) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return request(RequestMethod.POST, String.format("%s/cancel", instanceURL(Subscription.class, this.getId())), params, Subscription.class, options); } public DeletedSubscription delete() throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return this.delete(null, (RequestOptions) null); } public DeletedSubscription delete(Map<String, Object> params) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return delete(params, (RequestOptions) null); } public DeletedSubscription delete(Map<String, Object> params, RequestOptions options) throws AuthenticationException, InvalidRequestException, APIConnectionException, CardException, APIException { return request(RequestMethod.DELETE, instanceURL(Subscription.class, id), params, DeletedSubscription.class, options); } public String getId() { return id; } public void setId(String id) { this.id = id; } public Long getCurrentPeriodEnd() { return currentPeriodEnd; } public void setCurrentPeriodEnd(Long currentPeriodEnd) { this.currentPeriodEnd = currentPeriodEnd; } public Long getCurrentPeriodStart() { return currentPeriodStart; } public void setCurrentPeriodStart(Long currentPeriodStart) { this.currentPeriodStart = currentPeriodStart; } public String getCustomer() { return customer; } public void setCustomer(String customer) { this.customer = customer; } public Long getStart() { return start; } public void setStart(Long start) { this.start = start; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Long getTrialStart() { return trialStart; } public void setTrialStart(Long trialStart) { this.trialStart = trialStart; } public Long getTrialEnd() { return trialEnd; } public void setTrialEnd(Long trialEnd) { this.trialEnd = trialEnd; } public Plan getPlan() { return plan; } public Plan getNextCyclePlan() { return this.nextCyclePlan; } public void setPlan(Plan plan) { this.plan = plan; } public void setNextCyclePlan(Plan plan) { this.nextCyclePlan = plan; } public Long getCanceledAt() { return canceledAt; } public void setCanceledAt(Long canceledAt) { this.canceledAt = canceledAt; } public Long getCreated() { return created; } public Boolean getLivemode() { return livemode; } public Long getPausedAt() { return pausedAt; } public Long getResumedAt() { return resumedAt; } public void setLivemode(Boolean livemode) { this.livemode = livemode; } public void setPausedAt(Long pausedAt) { this.pausedAt = pausedAt; } public void setResumedAt(Long resumedAt) { this.resumedAt = resumedAt; } public Map<String, String> getMetadata() { return metadata; } /** * Assigning a whole collection from outside the object is not quite a right thing to do. * Be stick to use getMetadata(). */ @Deprecated public void setMetadata(Map<String, String> metadata) { this.metadata = metadata; } }
mit
MauricePeek513/MySneakerProject
app/src/main/java/com/adafruit/bluefruit/le/connect/app/neopixel/NeopixelColorPickerActivity.java
2899
package com.adafruit.bluefruit.le.connect.app.neopixel; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.adafruit.bluefruit.le.connect.R; import com.larswerkman.holocolorpicker.ColorPicker; import com.larswerkman.holocolorpicker.SaturationBar; import com.larswerkman.holocolorpicker.ValueBar; public class NeopixelColorPickerActivity extends AppCompatActivity implements ColorPicker.OnColorChangedListener { // Result return public static final String kActivityParameter_SelectedColorKey = "kActivityParameter_SelectedColorKey"; public static final String kActivityResult_SelectedColorResultKey = "kActivityResult_SelectedColorResultKey"; // UI private ColorPicker mColorPicker; private View mRgbColorView; private TextView mRgbTextView; private int mSelectedColor; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // setContentView(R.layout.activity_neopixel_colorpicker); setContentView(R.layout.activity_color_picker); Intent intent = getIntent(); mSelectedColor = intent.getIntExtra(kActivityParameter_SelectedColorKey, Color.WHITE); // UI mRgbColorView = findViewById(R.id.rgbColorView); mRgbTextView = (TextView) findViewById(R.id.rgbTextView); SaturationBar mSaturationBar = (SaturationBar) findViewById(R.id.saturationbar); ValueBar mValueBar = (ValueBar) findViewById(R.id.valuebar); mColorPicker = (ColorPicker) findViewById(R.id.colorPicker); if (mColorPicker != null) { mColorPicker.addSaturationBar(mSaturationBar); mColorPicker.addValueBar(mValueBar); mColorPicker.setOnColorChangedListener(this); mColorPicker.setOldCenterColor(mSelectedColor); mColorPicker.setColor(mSelectedColor); } onColorChanged(mSelectedColor); Button sendButton = (Button) findViewById(R.id.sendButton); sendButton.setText(R.string.neopixel_colorpicker_setcolor); } @Override public void onColorChanged(int color) { // Save selected color mSelectedColor = color; // Update UI mRgbColorView.setBackgroundColor(color); int r = (color >> 16) & 0xFF; int g = (color >> 8) & 0xFF; int b = (color >> 0) & 0xFF; String text = String.format(getString(R.string.colorpicker_rgbformat), r, g, b); mRgbTextView.setText(text); } public void onClickSend(View view) { Intent output = new Intent(); output.putExtra(kActivityResult_SelectedColorResultKey, mSelectedColor); setResult(RESULT_OK, output); finish(); } }
mit
AlmasB/CodeSamplesJava
src/com/almasb/spring/rest/Greeting.java
344
package com.almasb.spring.rest; public class Greeting { private final long id; private final String content; public Greeting(long id, String content) { this.id = id; this.content = content; } public long getId() { return id; } public String getContent() { return content; } }
mit
asposewords/Aspose_Words_Java
Examples/src/main/java/com/aspose/words/examples/programming_documents/document/DocumentBuilderInsertBreak.java
945
package com.aspose.words.examples.programming_documents.document; import com.aspose.words.BreakType; import com.aspose.words.Document; import com.aspose.words.DocumentBuilder; import com.aspose.words.examples.Utils; public class DocumentBuilderInsertBreak { public static void main(String[] args) throws Exception { //ExStart:DocumentBuilderInsertBreak // The path to the documents directory. String dataDir = Utils.getDataDir(DocumentBuilderInsertBreak.class); // Open the document. Document doc = new Document(); DocumentBuilder builder = new DocumentBuilder(doc); builder.write("This is Page 1"); builder.insertBreak(BreakType.PAGE_BREAK); builder.write("This is Page 2"); builder.insertBreak(BreakType.PAGE_BREAK); builder.write("This is Page 3"); doc.save(dataDir + "output.doc"); //ExEnd:DocumentBuilderInsertBreak } }
mit
NavjotPanesar/IRCu
app/src/main/java/ircu/navjotpanesar/com/ircu/database/ChannelsTable.java
1301
package ircu.navjotpanesar.com.ircu.database; import android.database.sqlite.SQLiteDatabase; import android.util.Log; /** * Created by Navjot on 1/2/2015. */ public class ChannelsTable { public static final String TABLE_CHANNELS = "channels"; //TODO: make table unique by channel public class COLUMNS{ public static final String ID = "_id"; public static final String CHANNEL = "channel"; public static final String SERVER = "server"; } // Database creation sql statement private static final String DATABASE_CREATE = "create table " + TABLE_CHANNELS + "(" + COLUMNS.ID + " integer primary key autoincrement, " + COLUMNS.CHANNEL + " text not null, " + COLUMNS.SERVER + " text not null);"; public static void onCreate(SQLiteDatabase database) { database.execSQL(DATABASE_CREATE); } public static void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(ChannelsTable.class.getName(), "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL("DROP TABLE IF EXISTS " + TABLE_CHANNELS); onCreate(db); } }
mit
Sowapps/android-mvc
demo/src/test/java/com/sowapps/mvc/ExampleUnitTest.java
298
package com.sowapps.mvc.demo; import org.junit.Test; import static org.junit.Assert.*; /** * To work on unit tests, switch the Test Artifact in the Build Variants view. */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
mit
platan/idea-gradle-dependencies-formatter
src/main/java/com/github/platan/idea/dependencies/intentions/MapNotationToStringNotationIntention.java
3699
package com.github.platan.idea.dependencies.intentions; import com.github.platan.idea.dependencies.gradle.Coordinate; import com.github.platan.idea.dependencies.gradle.PsiElementCoordinate; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiElement; import org.jetbrains.annotations.NotNull; import org.jetbrains.plugins.groovy.intentions.base.PsiElementPredicate; import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory; import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList; import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrNamedArgument; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression; import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall; import java.util.Map; import static com.github.platan.idea.dependencies.sort.DependencyUtil.toMapWithPsiElementValues; public class MapNotationToStringNotationIntention extends SelectionIntention<GrMethodCall> { @Override protected void processIntention(@NotNull PsiElement element, @NotNull Project project, Editor editor) { GrArgumentList argumentList = getGrArgumentList(element); if (argumentList == null) { return; } toStringNotation(project, argumentList); } private void toStringNotation(@NotNull Project project, GrArgumentList argumentList) { GrNamedArgument[] namedArguments = argumentList.getNamedArguments(); Map<String, PsiElement> map = toMapWithPsiElementValues(namedArguments); PsiElementCoordinate coordinate = PsiElementCoordinate.fromMap(map); String stringNotation = coordinate.toGrStringNotation(); for (GrNamedArgument namedArgument : namedArguments) { namedArgument.delete(); } GrExpression expressionFromText = GroovyPsiElementFactory.getInstance(project).createExpressionFromText(stringNotation); argumentList.add(expressionFromText); } @Override protected Class<GrMethodCall> elementTypeToFindInSelection() { return GrMethodCall.class; } @NotNull @Override protected PsiElementPredicate getElementPredicate() { return element -> { GrArgumentList argumentList = getGrArgumentList(element); if (argumentList == null) { return false; } GrNamedArgument[] namedArguments = argumentList.getNamedArguments(); if (namedArguments.length == 0) { return false; } Map<String, PsiElement> map = toMapWithPsiElementValues(namedArguments); return Coordinate.isValidMap(map); }; } private GrArgumentList getGrArgumentList(@NotNull PsiElement element) { if (element.getParent() == null || element.getParent().getParent() == null) { return null; } else if (element instanceof GrMethodCall) { return ((GrMethodCall) element).getArgumentList(); } else if (element.getParent().getParent() instanceof GrMethodCall) { return ((GrMethodCall) element.getParent().getParent()).getArgumentList(); } else if (element.getParent().getParent().getParent() instanceof GrMethodCall) { return ((GrMethodCall) element.getParent().getParent().getParent()).getArgumentList(); } return null; } @NotNull @Override public String getText() { return "Convert to string notation"; } @NotNull @Override public String getFamilyName() { return "Convert map notation to string notation"; } }
mit
0ED/Toy
RashHour/Constants.java
451
public class Constants { public static int WIN_WIDTH = 700, WIN_HEIGHT = 700; public static int WIN_CENTER_WIDTH = WIN_WIDTH/2, WIN_CENTER_HEIGHT = WIN_HEIGHT/2, MAP_SIZE = 6; public static String mapFileName = "text/map_", menuFileName="img/RashMenu.png", boardFileName="img/RashBoard.png", startButtonRed = "img/startButtonRed.png", startButtonBlue = "img/startButtonBlue.png", menuMusic="audio/Recognizer.wav", gameMusic="audio/Derezzed.wav"; }
mit
bitkylin/ClusterDeviceControlPlatform
Project-v1-Obsolete/clustermanage-server/src/main/java/cc/bitky/clustermanage/db/bean/routineinfo/LampStatusHistory.java
782
package cc.bitky.clustermanage.db.bean.routineinfo; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.Field; import java.util.ArrayList; import java.util.List; @Document(collection = "LampStatusHistory") public class LampStatusHistory { @Id private String id; @Field("StatusList") private List<HistoryInfo> statusList = new ArrayList<>(); public String getId() { return id; } public void setId(String id) { this.id = id; } public List<HistoryInfo> getStatusList() { return statusList; } public void setStatusList(List<HistoryInfo> statusList) { this.statusList = statusList; } }
mit
kennetham/LTA-Traffic-Demo
LTATraffic/src/java/cispackage/JURONGCHANGI6.java
3790
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package cispackage; import dataservice.CISDataServiceQuery; import properties.CISTraffic; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import common.constants; /** * * @author ケネス */ public class JURONGCHANGI6 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"); // Set standard HTTP/1.1 no-cache headers. response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); // Set IE extended HTTP/1.1 no-cache headers (use addHeader). response.addHeader("Cache-Control", "post-check=0, pre-check=0"); // Set standard HTTP/1.0 no-cache header. response.setHeader("Pragma", "no-cache"); // Set to expire far in the past. Prevents caching at the proxy server response.setHeader("Expires", "Fri, 1 Jan 2010 00:00:00 GMT"); // Set Date Header to expire response.setDateHeader("Expires", 0); PrintWriter out = response.getWriter(); try { CISDataServiceQuery _cisDataServiceQuery = new CISDataServiceQuery(); ArrayList<CISTraffic> list = _cisDataServiceQuery.getCameras(); CISTraffic _cisTraffic; _cisTraffic = (CISTraffic) list.get(constants.CAMERA_JURONGCHANGI6); request.setAttribute("title", "Jurong - Changi 06"); request.setAttribute("clat", _cisTraffic.getCLatitude()); request.setAttribute("clon", _cisTraffic.getCLongitude()); request.setAttribute("imgLink", _cisTraffic.getCImageURL()); request.getRequestDispatcher("googlemap.jsp").forward(request, response); return; } finally { out.checkError(); out.flush(); out.close(); } } // <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
razorpay/razorpay-java
src/main/java/com/razorpay/Customer.java
164
package com.razorpay; import org.json.JSONObject; public class Customer extends Entity { public Customer(JSONObject jsonObject) { super(jsonObject); } }
mit
SpongePowered/Sponge
src/mixins/java/org/spongepowered/common/mixin/core/world/entity/projectile/LargeFireballMixin.java
5570
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) 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 org.spongepowered.common.mixin.core.world.entity.projectile; import org.spongepowered.api.data.Keys; import org.spongepowered.api.entity.projectile.Projectile; import org.spongepowered.api.entity.projectile.explosive.fireball.ExplosiveFireball; import org.spongepowered.api.event.CauseStackManager; import org.spongepowered.api.event.EventContextKeys; import org.spongepowered.api.world.explosion.Explosion; import org.spongepowered.api.world.server.ServerLocation; import org.spongepowered.api.world.server.ServerWorld; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.common.bridge.world.entity.GrieferBridge; import org.spongepowered.common.bridge.world.entity.projectile.LargeFireballBridge; import org.spongepowered.common.bridge.explosives.ExplosiveBridge; import org.spongepowered.common.event.SpongeCommonEventFactory; import org.spongepowered.common.event.tracking.PhaseTracker; import org.spongepowered.common.util.Constants; import java.util.Optional; import javax.annotation.Nullable; import net.minecraft.world.entity.Entity; import net.minecraft.world.entity.projectile.LargeFireball; import net.minecraft.world.level.Explosion.BlockInteraction; @Mixin(LargeFireball.class) public abstract class LargeFireballMixin extends AbstractHurtingProjectileMixin implements LargeFireballBridge, ExplosiveBridge { // @formatter:off @Shadow public int explosionPower; // @formatter:on /** * @author gabizou April 13th, 2018 * @reason Due to changes from Forge, we have to redirect osr modify the gamerule check, * but since forge doesn't allow us to continue to check the gamerule method call here, * we have to modify the arguments passed in (the two booleans). There may be a better way, * which may include redirecting the world.newExplosion method call instead of modifyargs, * but, it is what it is. */ @Redirect(method = "onHit", at = @At(value = "INVOKE", target = "Lnet/minecraft/world/level/Level;explode(Lnet/minecraft/world/entity/Entity;DDDFZLnet/minecraft/world/level/Explosion$BlockInteraction;)Lnet/minecraft/world/level/Explosion;" ) ) @Nullable public net.minecraft.world.level.Explosion impl$throwExplosionEventAndExplode(final net.minecraft.world.level.Level worldObj, @Nullable final Entity nil, final double x, final double y, final double z, final float strength, final boolean flaming, final BlockInteraction mode) { return this.bridge$throwExplosionEventAndExplode(worldObj, nil, x, y, z, strength, flaming, mode); } @Override public net.minecraft.world.level.Explosion bridge$throwExplosionEventAndExplode(net.minecraft.world.level.Level worldObj, @Nullable Entity nil, double x, double y, double z, float strength, boolean flaming, net.minecraft.world.level.Explosion.BlockInteraction mode) { final boolean griefer = ((GrieferBridge) this).bridge$canGrief(); try (final CauseStackManager.StackFrame frame = PhaseTracker.getCauseStackManager().pushCauseFrame()) { frame.pushCause(this); ((Projectile) this).get(Keys.SHOOTER).ifPresent(shooter -> frame.addContext(EventContextKeys.PROJECTILE_SOURCE, shooter)); final Optional<net.minecraft.world.level.Explosion> ex = SpongeCommonEventFactory.detonateExplosive(this, Explosion.builder() .location(ServerLocation.of((ServerWorld) worldObj, x, y, z)) .sourceExplosive(((ExplosiveFireball) this)) .radius(strength) .canCauseFire(flaming && griefer) .shouldPlaySmoke(mode != BlockInteraction.NONE && griefer) .shouldBreakBlocks(mode != BlockInteraction.NONE && griefer)); return ex.orElse(null); } } @Override public Optional<Integer> bridge$getExplosionRadius() { return Optional.of(this.explosionPower); } @Override public void bridge$setExplosionRadius(@Nullable final Integer radius) { this.explosionPower = radius == null ? Constants.Entity.Fireball.DEFAULT_EXPLOSION_RADIUS : radius; } }
mit
bbonnin/mongo2els
src/main/java/io/millesabords/mongo2els/OplogTailer.java
1704
package io.millesabords.mongo2els; import com.mongodb.CursorType; import com.mongodb.MongoClient; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCursor; import org.bson.Document; import org.bson.types.BSONTimestamp; import java.util.Date; import java.util.LinkedList; import java.util.List; import java.util.concurrent.Callable; /** * MongoDB oplog tailer. * * @author Bruno Bonnin */ public class OplogTailer implements Callable<Void> { private final MongoClient client; private final MongoCollection<Document> oplog; private final String ns; private final List<OplogListener> listeners = new LinkedList<>(); private final Config cfg = Config.get(); public OplogTailer(final MongoClient client) { this.client = client; this.ns = cfg.get(Config.MONGO_DB) + "." + cfg.get(Config.MONGO_COLLECTION); this.oplog = this.client.getDatabase("local").getCollection("oplog.rs"); } @Override public Void call() throws Exception { final Date now = new Date(); final Document query = new Document("ns", ns) .append("ts", new Document("$gt", new BSONTimestamp((int) (now.getTime() / 1000), 0))); final MongoCursor<Document> cursor = oplog.find(query) .cursorType(CursorType.TailableAwait).iterator(); while (cursor.hasNext()) { final Document doc = cursor.next(); for (final OplogListener listener : listeners) { listener.onOplog(doc); } } return null; } public void addListener(OplogListener listener) { listeners.add(listener); } }
mit
ldipotetjob/onlinetor
src/org/itadaki/bobbin/torrentdb/MutableFileset.java
4288
package org.itadaki.bobbin.torrentdb; import java.util.ArrayList; import java.util.List; /** * A mutable fileset used to represent the current (rather than initial) fileset of a torrent. A * MutableFileset is created either with an initial single or multi-file fileset as specified in an * Info, or as an empty fileset that can be differentiated into a single or multi-file fileset at a * later point */ public class MutableFileset { /** * If {@code false}, the fileset has not yet been differentiated into a single or multi-file * fileset, and cannot be extended even if unsealed. If {@code true}, the fileset has been * differentiated, and can be extended if unsealed. */ private boolean initialised = false; /** * If {@code false}, files can be added to the fileset if it has been initialised. If * {@code true}, the fileset cannot be extended. */ private boolean filesSealed = false; /** * If {@code false}, the last file can be extended if the fileset has been initialised. If * {@code true}, the last file cannot be extended. */ private boolean dataSealed = false; /** * The base directory name of the fileset. This may be set once during initialisation if the * fileset is to be a multi-file fileset, or remain null for a single-file fileset */ private String baseDirectoryName = null; /** * The files currently contained within the fileset */ private List<Filespec> files = new ArrayList<Filespec>(); /** * @return The base directory name of the fileset. May be {code null} before the fileset is * differentiated, or in the case of a single-file fileset after differentiation */ public String getBaseDirectoryName() { return this.baseDirectoryName; } /** * @return The current files of the fileset */ public List<Filespec> getFiles() { return new ArrayList<Filespec> (this.files); } /** * Applies a fileset delta to the fileset * * @param delta The delta to apply */ public void applyDelta (FilesetDelta delta) { if (!this.initialised) { throw new IllegalStateException(); } if (!canExtendData()) { throw new IllegalArgumentException ("Cannot extend fileset data"); } if (!canExtendFiles() && (delta.getAdditionalFiles().size() > 0)) { throw new IllegalArgumentException ("Cannot add files to fileset"); } if ((this.files.size() == 0) && (delta.getLastFileLength() != 0)) { throw new IllegalArgumentException ("Cannot extend nonexistent file"); } if (this.files.size() > 0) { Filespec currentFile = this.files.get (this.files.size() - 1); if (delta.getLastFileLength() < currentFile.getLength()) { throw new IllegalArgumentException ("Cannot shrink existing file"); } Filespec updatedFile = new Filespec (currentFile.getName(), delta.getLastFileLength()); this.files.set (this.files.size() - 1, updatedFile); } this.filesSealed = (delta.isDataSealed() | delta.isFilesSealed()); this.dataSealed = delta.isDataSealed(); this.files.addAll (delta.getAdditionalFiles()); } /** * @return {@code true} if the data of the final file in the fileset can currently be extended, * otherwise {@code false} */ public boolean canExtendData() { return this.initialised && !this.dataSealed; } /** * @return {@code true} if new files can currently be added to the fileset, otherwise * {@code false} */ public boolean canExtendFiles() { return this.initialised && !this.filesSealed && (this.baseDirectoryName != null); } /** * @param infoFileset * @throws IllegalStateException If the MutableFileset is already initialised */ public void setInfoFileset (InfoFileset infoFileset) { if (this.initialised) { throw new IllegalStateException(); } this.baseDirectoryName = infoFileset.getBaseDirectoryName(); this.files.addAll (infoFileset.getFiles()); this.initialised = true; } /** * Creates an undifferentiated MutableFileset */ public MutableFileset() { } /** * Creates a MutableFileset with an initial InfoFileset * * @param infoFileset The initial InfoFileset */ public MutableFileset (InfoFileset infoFileset) { this.initialised = true; this.baseDirectoryName = infoFileset.getBaseDirectoryName(); this.files.addAll (infoFileset.getFiles()); } }
mit
FundRequest/platform
core/src/main/java/io/fundrequest/core/request/fund/FundServiceImpl.java
18756
package io.fundrequest.core.request.fund; import io.fundrequest.common.infrastructure.exception.ResourceNotFoundException; import io.fundrequest.common.infrastructure.mapping.Mappers; import io.fundrequest.core.contract.service.FundRequestContractsService; import io.fundrequest.core.request.domain.IssueInformation; import io.fundrequest.core.request.domain.Request; import io.fundrequest.core.request.domain.RequestStatus; import io.fundrequest.core.request.fiat.FiatService; import io.fundrequest.core.request.fund.command.FundsAddedCommand; import io.fundrequest.core.request.fund.domain.Fund; import io.fundrequest.core.request.fund.domain.PendingFund; import io.fundrequest.core.request.fund.domain.Refund; import io.fundrequest.core.request.fund.dto.FundDto; import io.fundrequest.core.request.fund.dto.FundFundsByFunderAggregator; import io.fundrequest.core.request.fund.dto.FundsAndRefundsAggregator; import io.fundrequest.core.request.fund.dto.FundsForRequestDto; import io.fundrequest.core.request.fund.dto.RefundFundsByFunderAggregator; import io.fundrequest.core.request.fund.event.RequestFundedEvent; import io.fundrequest.core.request.fund.infrastructure.FundRepository; import io.fundrequest.core.request.fund.infrastructure.PendingFundRepository; import io.fundrequest.core.request.fund.infrastructure.RefundRepository; import io.fundrequest.core.request.infrastructure.RequestRepository; import io.fundrequest.core.token.dto.TokenValueDto; import io.fundrequest.core.token.mapper.TokenValueMapper; import io.fundrequest.core.token.model.TokenValue; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.CacheManager; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import org.springframework.context.ApplicationEventPublisher; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.LongStream; import java.util.stream.Stream; import static java.math.BigDecimal.ZERO; @Service class FundServiceImpl implements FundService { private final FundRepository fundRepository; private final RefundRepository refundRepository; private final PendingFundRepository pendingFundRepository; private final RequestRepository requestRepository; private final Mappers mappers; private final ApplicationEventPublisher eventPublisher; private final CacheManager cacheManager; private final FundRequestContractsService fundRequestContractsService; private final FiatService fiatService; private final TokenValueMapper tokenValueMapper; private final FundFundsByFunderAggregator fundFundsByFunderAggregator; private final RefundFundsByFunderAggregator refundFundsByFunderAggregator; private final FundsAndRefundsAggregator fundsAndRefundsAggregator; @Autowired public FundServiceImpl(final FundRepository fundRepository, final RefundRepository refundRepository, final PendingFundRepository pendingFundRepository, final RequestRepository requestRepository, final Mappers mappers, final ApplicationEventPublisher eventPublisher, final CacheManager cacheManager, final FundRequestContractsService fundRequestContractsService, final FiatService fiatService, final TokenValueMapper tokenValueMapper, final FundFundsByFunderAggregator fundFundsByFunderAggregator, final RefundFundsByFunderAggregator refundFundsByFunderAggregator, final FundsAndRefundsAggregator fundsAndRefundsAggregator) { this.fundRepository = fundRepository; this.refundRepository = refundRepository; this.pendingFundRepository = pendingFundRepository; this.requestRepository = requestRepository; this.mappers = mappers; this.eventPublisher = eventPublisher; this.cacheManager = cacheManager; this.fundRequestContractsService = fundRequestContractsService; this.fiatService = fiatService; this.tokenValueMapper = tokenValueMapper; this.fundFundsByFunderAggregator = fundFundsByFunderAggregator; this.refundFundsByFunderAggregator = refundFundsByFunderAggregator; this.fundsAndRefundsAggregator = fundsAndRefundsAggregator; } @Transactional(readOnly = true) @Override public List<FundDto> findAll() { return mappers.mapList(Fund.class, FundDto.class, fundRepository.findAll()); } @Transactional(readOnly = true) @Override public List<FundDto> findAll(Iterable<Long> ids) { return mappers.mapList(Fund.class, FundDto.class, fundRepository.findAll(ids)); } @Override @Transactional(readOnly = true) public FundDto findOne(Long id) { return mappers.map(Fund.class, FundDto.class, fundRepository.findOne(id).orElseThrow(ResourceNotFoundException::new)); } @Override @Transactional(readOnly = true) @Cacheable(value = "funds", key = "#requestId", unless = "#result.isEmpty()") public List<TokenValueDto> getTotalFundsForRequest(Long requestId) { final Optional<Request> one = requestRepository.findOne(requestId); if (one.isPresent()) { try { if (one.get().getStatus() == RequestStatus.CLAIMED) { return getFromClaimRepository(one.get()); } else { return getFromFundRepository(one.get()); } } catch (final Exception ex) { return Collections.emptyList(); } } else { return Collections.emptyList(); } } private List<TokenValueDto> getFromClaimRepository(final Request request) { final Long tokenCount = fundRequestContractsService.claimRepository() .getTokenCount(request.getIssueInformation().getPlatform().name(), request.getIssueInformation().getPlatformId()); return LongStream.range(0, tokenCount) .mapToObj(x -> fundRequestContractsService.claimRepository() .getTokenByIndex(request.getIssueInformation().getPlatform().name(), request.getIssueInformation().getPlatformId(), x)) .filter(Optional::isPresent) .map(Optional::get) .map(getTotalClaimFundDto(request)).collect(Collectors.toList()); } private List<TokenValueDto> getFromFundRepository(final Request request) { final Long fundedTokenCount = fundRequestContractsService.fundRepository() .getFundedTokenCount(request.getIssueInformation().getPlatform().name(), request.getIssueInformation().getPlatformId()); return LongStream.range(0, fundedTokenCount) .mapToObj(x -> fundRequestContractsService.fundRepository() .getFundedToken(request.getIssueInformation().getPlatform().name(), request.getIssueInformation().getPlatformId(), x)).filter(Optional::isPresent) .map(Optional::get) .map(getTotalFundDto(request)).collect(Collectors.toList()); } @Override @Transactional(readOnly = true) public FundsForRequestDto getFundsForRequestGroupedByFunder(final Long requestId) { final List<UserFundsDto> userFunds = getFundsAndRefundsFor(requestId); enrichFundsWithZeroValues(userFunds); final TokenValueDto fndFunds = totalFunds(userFunds, UserFundsDto::getFndFunds, UserFundsDto::getFndRefunds); final TokenValueDto otherFunds = totalFunds(userFunds, UserFundsDto::getOtherFunds, UserFundsDto::getOtherRefunds); return FundsForRequestDto.builder() .userFunds(userFunds) .fndFunds(fndFunds) .otherFunds(otherFunds) .usdFunds(fiatService.getUsdPrice(fndFunds, otherFunds)) .build(); } private List<UserFundsDto> getFundsAndRefundsFor(final Long requestId) { final List<Fund> fundsForRequest = fundRepository.findAllByRequestId(requestId); final List<Refund> refundsForRequest = refundRepository.findAllByRequestId(requestId); return fundsAndRefundsAggregator.aggregate(Stream.concat(fundFundsByFunderAggregator.aggregate(fundsForRequest).stream(), refundFundsByFunderAggregator.aggregate(refundsForRequest).stream()) .collect(Collectors.toList())); } private void enrichFundsWithZeroValues(final List<UserFundsDto> userFunds) { TokenValueDto fndFundTemplate = null; TokenValueDto otherFundTemplate = null; TokenValueDto fndRefundTemplate = null; TokenValueDto otherRefundTemplate = null; for (final UserFundsDto userFund : userFunds) { fndFundTemplate = Optional.ofNullable(userFund.getFndFunds()).orElse(fndFundTemplate); otherFundTemplate = Optional.ofNullable(userFund.getOtherFunds()).orElse(otherFundTemplate); fndRefundTemplate = Optional.ofNullable(userFund.getFndRefunds()).orElse(fndRefundTemplate); otherRefundTemplate = Optional.ofNullable(userFund.getOtherRefunds()).orElse(otherRefundTemplate); } final TokenValueDto zeroFndFundTokenValue = buildZeroTokenValueDto(fndFundTemplate); final TokenValueDto zeroOtherFundTokenValue = buildZeroTokenValueDto(otherFundTemplate); final TokenValueDto zeroFndRefundTokenValue = buildZeroTokenValueDto(fndRefundTemplate); final TokenValueDto zeroOtherRefundTokenValue = buildZeroTokenValueDto(otherRefundTemplate); for (final UserFundsDto userFund : userFunds) { if (noFundsAndTemplateNotNull(userFund.getFndFunds(), fndFundTemplate)) { userFund.setFndFunds(zeroFndFundTokenValue); } if (noFundsAndTemplateNotNull(userFund.getOtherFunds(), otherFundTemplate)) { userFund.setOtherFunds(zeroOtherFundTokenValue); } if (userFund.hasRefunds()) { if (noFundsAndTemplateNotNull(userFund.getFndRefunds(), fndRefundTemplate)) { userFund.setFndRefunds(zeroFndRefundTokenValue); } if (noFundsAndTemplateNotNull(userFund.getOtherRefunds(), otherRefundTemplate)) { userFund.setOtherRefunds(zeroOtherRefundTokenValue); } } } } private boolean noFundsAndTemplateNotNull(final TokenValueDto funds, final TokenValueDto template) { return funds == null && template != null; } private TokenValueDto buildZeroTokenValueDto(final TokenValueDto tokenValueTemplate) { return Optional.ofNullable(tokenValueTemplate) .map(template -> TokenValueDto.builder() .tokenSymbol(template.getTokenSymbol()) .tokenAddress(template.getTokenAddress()) .totalAmount(ZERO) .build()) .orElse(null); } private TokenValueDto totalFunds(final List<UserFundsDto> funds, final Function<UserFundsDto, TokenValueDto> getFundsFunction, final Function<UserFundsDto, TokenValueDto> getRefundsFunction) { if (funds.isEmpty()) { return null; } final BigDecimal totalFundsValue = sumTokenValue(funds, getFundsFunction); final BigDecimal totalRefundsValue = sumTokenValue(funds, getRefundsFunction); return funds.stream() .map(getFundsFunction) .filter(Objects::nonNull) .findFirst() .map(fund -> TokenValueDto.builder() .tokenSymbol(fund.getTokenSymbol()) .tokenAddress(fund.getTokenAddress()) .totalAmount(totalFundsValue.add(totalRefundsValue)) .build()) .orElse(null); } private BigDecimal sumTokenValue(final List<UserFundsDto> funds, final Function<UserFundsDto, TokenValueDto> getFundsFunction) { return funds.stream() .map(getFundsFunction) .filter(Objects::nonNull) .map(TokenValueDto::getTotalAmount) .reduce(ZERO, BigDecimal::add); } @Override @CacheEvict(value = "funds", key = "#requestId") public void clearTotalFundsCache(Long requestId) { // Intentionally blank } private Function<String, TokenValueDto> getTotalClaimFundDto(final Request request) { return tokenAddress -> { final BigDecimal rawBalance = new BigDecimal(fundRequestContractsService.claimRepository() .getAmountByToken(request.getIssueInformation().getPlatform().name(), request.getIssueInformation().getPlatformId(), tokenAddress)); return tokenValueMapper.map(tokenAddress, rawBalance); }; } private Function<String, TokenValueDto> getTotalFundDto(final Request request) { return tokenAddress -> { final BigDecimal rawBalance = new BigDecimal(fundRequestContractsService.fundRepository() .balance(request.getIssueInformation().getPlatform().name(), request.getIssueInformation().getPlatformId(), tokenAddress)); return tokenValueMapper.map(tokenAddress, rawBalance); }; } @Override @Transactional public void addFunds(final FundsAddedCommand command) { final Fund.FundBuilder fundBuilder = Fund.builder() .tokenValue(TokenValue.builder() .amountInWei(command.getAmountInWei()) .tokenAddress(command.getToken()) .build()) .requestId(command.getRequestId()) .timestamp(command.getTimestamp()) .funderAddress(command.getFunderAddress()) .blockchainEventId(command.getBlockchainEventId()); final Optional<PendingFund> pendingFund = pendingFundRepository.findByTransactionHash(command.getTransactionHash()); if (pendingFund.isPresent()) { fundBuilder.funderUserId(pendingFund.get().getUserId()); } final Fund fund = fundRepository.saveAndFlush(fundBuilder.build()); cacheManager.getCache("funds").evict(fund.getRequestId()); eventPublisher.publishEvent(RequestFundedEvent.builder() .fundDto(mappers.map(Fund.class, FundDto.class, fund)) .requestId(command.getRequestId()) .timestamp(command.getTimestamp()) .build()); } @Override public Optional<TokenValueDto> getFundsFor(final Long requestId, final String funderAddress, final String tokenAddress) { return requestRepository.findOne(requestId) .map(request -> { try { final IssueInformation issueInformation = request.getIssueInformation(); final BigInteger amountFunded = fundRequestContractsService.fundRepository() .amountFunded(issueInformation.getPlatform().name(), issueInformation.getPlatformId(), funderAddress, tokenAddress) .send(); return tokenValueMapper.map(tokenAddress, new BigDecimal(amountFunded)); } catch (Exception e) { return null; } }); } }
mit
javahuang/rp
rp-web/src/test/java/com/google/guava/test/MapSorter.java
2963
/** * Copyright (c) 2005-2012 https://github.com/javahuang * * Licensed under the Apache License, Version 2.0 (the "License"); */ package com.google.guava.test; /** * 可重复键的map排序 * <p/> * <p>User: Huang rp * <p>Date: 2015年5月19日 下午9:24:57 * <p>Version: 1.0 */ import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import com.google.guava.test.KeyValueComparator.Order; import com.google.guava.test.KeyValueComparator.Type; public class MapSorter { public static void main(String[] args) { IdentityHashMap<Double, String> map = new IdentityHashMap<Double, String>(); map.put(10.1, "aaaa"); map.put(10.1, "bbbb"); map.put(10.1, "cccc"); map.put(10.08, "dddd"); map.put(10.02, "eeee"); map.put(10.08, "aaaa"); System.out.println("----------[ [ [ 排序前 ] ] ]----------\n"); for (Entry<Double, String> entry : map.entrySet()) { System.out.println("\t" + entry.getKey() + "\t\t" + entry.getValue()); } System.out.println("\n----------[ [ [ 按键降序 ] ] ]----------\n"); List<Map.Entry<Double, String>> list1 = new ArrayList<Map.Entry<Double, String>>(map.entrySet()); Collections.sort(list1, new KeyValueComparator(Type.KEY, Order.DESC)); for (Entry<Double, String> entry : list1) { System.out.println("\t" + entry.getKey() + "\t\t" + entry.getValue()); } System.out.println("\n----------[ [ [ 按值升序 ] ] ]----------\n"); List<Map.Entry<Double, String>> list2 = new ArrayList<Map.Entry<Double, String>>(map.entrySet()); Collections.sort(list2, new KeyValueComparator(Type.VALUE, Order.ASC)); for (Entry<Double, String> entry : list2) { System.out.println("\t" + entry.getKey() + "\t\t" + entry.getValue()); } System.out.println("\n----------[ [ [ 结束啦 ] ] ]----------\n"); } } class KeyValueComparator implements Comparator<Map.Entry<Double, String>> { enum Type { KEY, VALUE; } enum Order { ASC, DESC } private Type type; private Order order; public KeyValueComparator(Type type, Order order) { this.type = type; this.order = order; } @Override public int compare(Entry<Double, String> o1, Entry<Double, String> o2) { switch (type) { case KEY: switch (order) { case ASC: return o1.getKey().compareTo(o2.getKey()); case DESC: return o2.getKey().compareTo(o1.getKey()); default: throw new RuntimeException("顺序参数错误"); } case VALUE: switch (order) { case ASC: return o1.getValue().compareTo(o2.getValue()); case DESC: return o2.getValue().compareTo(o1.getValue()); default: throw new RuntimeException("顺序参数错误"); } default: throw new RuntimeException("类型参数错误"); } } }
mit
mallikaviswas/mytweeter
app/build/generated/source/buildConfig/androidTest/debug/com/codepath/apps/mytweeter/test/BuildConfig.java
469
/** * Automatically generated file. DO NOT MODIFY */ package com.codepath.apps.mytweeter.test; public final class BuildConfig { public static final boolean DEBUG = Boolean.parseBoolean("true"); public static final String APPLICATION_ID = "com.codepath.apps.mytweeter.test"; public static final String BUILD_TYPE = "debug"; public static final String FLAVOR = ""; public static final int VERSION_CODE = -1; public static final String VERSION_NAME = ""; }
mit
sgurusharan/Automatium
src/main/java/com/automatium/annotation/TestProperties.java
432
package com.automatium.annotation; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Created by Gurusharan on 20-11-2016. */ @Retention(RetentionPolicy.RUNTIME) public @interface TestProperties { String product(); String module(); String name(); String id(); String description(); String urlFormat(); String url(); String priority(); String group(); }
mit
T5750/book-repositories
SpringBootInAction/UnsecuredReadingList/src/test/java/readinglist/ServerWebTests.java
1967
package readinglist; import static org.junit.Assert.assertEquals; import java.util.concurrent.TimeUnit; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.boot.test.WebIntegrationTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = ReadingListApplication.class) @WebIntegrationTest(randomPort = true) public class ServerWebTests { private static FirefoxDriver browser; @Value("${local.server.port}") private int port; @BeforeClass public static void openBrowser() { browser = new FirefoxDriver(); browser.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); } @Test public void addBookToEmptyList() { String baseUrl = "http://localhost:" + port; browser.get(baseUrl); String currentUrl = browser.getCurrentUrl(); assertEquals(baseUrl + "/readingList", currentUrl); assertEquals("You have no books in your book list", browser.findElementByTagName("div").getText()); browser.findElementByName("title").sendKeys("BOOK TITLE"); browser.findElementByName("author").sendKeys("BOOK AUTHOR"); browser.findElementByName("isbn").sendKeys("1234567890"); browser.findElementByName("description").sendKeys("DESCRIPTION"); browser.findElementByTagName("form").submit(); WebElement dl = browser.findElementByCssSelector("dt.bookHeadline"); assertEquals("BOOK TITLE by BOOK AUTHOR (ISBN: 1234567890)", dl.getText()); WebElement dt = browser.findElementByCssSelector("dd.bookDescription"); assertEquals("DESCRIPTION", dt.getText()); } @AfterClass public static void closeBrowser() { browser.quit(); } }
mit
JerryXia/BizHttpRequestTest
source/devhelper/src/test/java/com/github/jerryxia/devhelper/util/MapTest.java
1968
/** * */ package com.github.jerryxia.devhelper.util; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import org.junit.Assert; import org.junit.Test; /** * @author Administrator * */ public class MapTest { @Test public void testCloneIsOk() { String k1 = "k1"; String[] v1 = { "1", "2", "3" }; String k2 = new String("k2"); String[] v2 = { "3", "4", "5" }; Map<String, String[]> originMap = new LinkedHashMap<String, String[]>(); originMap.put(k1, v1); originMap.put(k2, Arrays.copyOf(v2, v2.length)); k2 = null; System.gc(); try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(originMap); System.out.println(originMap.keySet()); Iterator<String> iterator = originMap.keySet().iterator(); String lastKey = null; while (iterator.hasNext()) { lastKey = iterator.next(); } Assert.assertTrue("k2" != lastKey); Assert.assertTrue("k2" == lastKey.intern()); v2[0] = "123"; System.out.println(originMap.get(lastKey)[0]); } @Test public void testPutAllIsOk() { HashMap<String, Object> origin = new HashMap<String, Object>(); String a0 = new String("a0"); String a1 = new String("a1"); String a2 = new String("a2"); origin.put("a0", a0); origin.put("a1", a1); origin.put("a2", a2); HashMap<String, Object> target = new HashMap<String, Object>(); target.put("a1", a1); target.put("a2", "asdfdas"); target.putAll(origin); Assert.assertTrue(target.get("a1") == a1); Assert.assertTrue(target.get("a2") == a2); } }
mit
rnaufal/junit-parameters
src/main/java/br/com/rnaufal/junit/parameters/statement/MethodParameterStatement.java
1159
package br.com.rnaufal.junit.parameters.statement; import org.junit.runners.model.FrameworkMethod; import org.junit.runners.model.Statement; import br.com.rnaufal.junit.parameters.generator.ParameterGenerator; /** * @author rnaufal */ public class MethodParameterStatement extends Statement { private final Object test; private final FrameworkMethod method; private final ParameterGenerator generator; public MethodParameterStatement(final Object test, final FrameworkMethod method, final ParameterGenerator generator) { this.test = test; this.method = method; this.generator = generator; } @Override public void evaluate() { convertParameters().forEach(params -> { try { method.invokeExplosively(test, params); } catch (Throwable e) { throw new RuntimeException(e); } }); } private Iterable<Object[]> convertParameters() { return new ParameterTypeConverterFactory(method).convertParameters(generator.parameters()); } }
mit
dachengxi/spring1.1.1_source
mock/org/springframework/mock/web/DelegatingServletInputStream.java
1605
/* * Copyright 2002-2004 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.mock.web; import java.io.IOException; import java.io.InputStream; import javax.servlet.ServletInputStream; /** * Delegating implementation of ServletInputStream. * * <p>Used by MockHttpServletRequest; typically not * necessary for testing application controllers. * * @author Juergen Hoeller * @since 27.04.2004 * @see org.springframework.mock.web.MockHttpServletRequest */ public class DelegatingServletInputStream extends ServletInputStream { private final InputStream sourceStream; /** * Create a new DelegatingServletInputStream. * @param sourceStream the sourceStream InputStream */ public DelegatingServletInputStream(InputStream sourceStream) { this.sourceStream = sourceStream; } public InputStream getSourceStream() { return sourceStream; } public int read() throws IOException { return this.sourceStream.read(); } public void close() throws IOException { super.close(); this.sourceStream.close(); } }
mit
maugithuber/grupo09sa
src/correos/tiendaonline/software/Negocio/EncargadoNegocio.java
2394
/* * 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 correos.tiendaonline.software.Negocio; import correos.tiendaonline.software.Datos.Encargado; import correos.tiendaonline.software.Datos.Persona; import correos.tiendaonline.software.Datos.User; import javax.swing.table.DefaultTableModel; /** * * @author Mauricio */ public class EncargadoNegocio { private Encargado m_Encargado; private User m_user; private Persona m_persona; public EncargadoNegocio() { this.m_Encargado = new Encargado(); this.m_persona = new Persona(); this.m_user = new User(); } public DefaultTableModel obtenerEncargado(int id) { return this.m_Encargado.getEncargado(id); } public DefaultTableModel obtenerEncargados() { return this.m_Encargado.getEncargados(); } public int registrarEncargado(String nombre, String apellido, int id_user, String email, String pass, int tipo,int id_persona) { this.m_persona.setPersona(id_persona, nombre, apellido); this.m_Encargado.setEncargado(id_persona,id_persona); this.m_user.setUser(id_persona,tipo, id_persona, email, pass); this.m_persona.registrarPersona(); this.m_user.registrarUser(); return this.m_Encargado.registrarEncargado(); } public void eliminarEncargado(int id) { DefaultTableModel t= this.m_Encargado.getEncargado(id); this.m_Encargado.setEncargado(id,(int)t.getValueAt(0, 1)); this.m_Encargado.eliminarEncargado(); } public int registrarEncargado2(String nombre, String apellido, String email, String pass) { // No olvidar primero settear los datos int id_persona = (int) this.m_persona.getultimapersona().getValueAt(0, 0); id_persona++; System.out.println(id_persona); this.m_persona.setPersona(id_persona, nombre, apellido); this.m_Encargado.setEncargado(id_persona,id_persona); this.m_user.setUser(id_persona,2, id_persona, email, pass); this.m_persona.registrarPersona(); this.m_user.registrarUser(); return this.m_Encargado.registrarEncargado(); } }
mit
demo-cards-trading-game/game
src/demo/Card.java
2050
package demo; public class Card{ private String SetNumber; private int Cost; private String Name; private String Class; private int Limit; private String Source; private String Description; private int Hp; private int Mp; private int Sup; private String Type; private int CardNumber; public Card(){ this.SetNumber=""; this.Limit=0; this.Cost=0; } public String getType(){ return(this.Type); } public String getId(){ return(this.SetNumber); } public int getCost(){ return(this.Cost); } public String getDescription(){ return(this.Description); } public String getName(){ return(this.Name); } public String getSource(){ return (this.Source); } public int getHp(){ return(this.Hp); } public int getMp(){ return(this.Mp); } public int getSup(){ return(this.Sup); } public int getCardNumber(){ return(this.CardNumber); } public int getLimit(){ return(Limit); } public void setCardNumber(int New){ this.CardNumber=New; } public void setHp(int New){ this.Hp=New; } public void setMp(int New){ this.Mp=New; } public void setSup(int New){ this.Sup=New; } public void setType(String New){ this.Type=New; } public void setDescription(String New){ this.Description=New; } public void setId(String New){ this.SetNumber=New; } public void setCost(int New){ this.Cost=New; } public void setName(String New){ this.Name=New; } public void setSource(String New){ this.Source=New; } public void setClass(String New){ this.Class=New; } public void setLimit(int New){ this.Limit=New; } public void asignar( Card b){ this.SetNumber=b.SetNumber; this.Cost=b.Cost; this.Name=b.Name; this.Class=b.Class; this.Limit=b.Limit; this.Source=b.Source; this.Description=b.Description; this.Hp=b.Hp; this.Mp=b.Mp; this.Sup=b.Sup; this.Type=b.Type; this.CardNumber=b.CardNumber; } }
mit
magx2/jSupla
protocol-java/src/test/java/pl/grzeslowski/jsupla/protocoljava/common/VersionErrorRandomizer.java
813
package pl.grzeslowski.jsupla.protocoljava.common; import io.github.benas.randombeans.api.EnhancedRandom; import io.github.benas.randombeans.api.Randomizer; import pl.grzeslowski.jsupla.protocoljava.api.entities.sdc.VersionError; import static pl.grzeslowski.jsupla.protocol.api.consts.JavaConsts.UNSIGNED_BYTE_MAX; public class VersionErrorRandomizer implements Randomizer<VersionError> { private final EnhancedRandom random; public VersionErrorRandomizer(final EnhancedRandom random) { this.random = random; } @Override public VersionError getRandomValue() { final int serverVersion = random.nextInt(UNSIGNED_BYTE_MAX - 2) + 1; final int serverVersionMin = random.nextInt(serverVersion); return new VersionError(serverVersionMin, serverVersion); } }
mit
MagnetonBora/KeyValueStorage
src/kvs/kv.core.java
1667
package kvs; import java.util.*; import sun.reflect.generics.reflectiveObjects.NotImplementedException; class Item { private Map<String, Object> item = null; public Item() { super(); item = new HashMap<String, Object>(); }; public Item(String key, Object value) { item = new HashMap<String, Object>(); item.put(key, value); }; @Override public String toString() { return item.toString(); }; } class Record { private int id; private String name; public Record() { super(); }; public Record(int id, String name) { this.id = id; this.name = name; }; public int getId() { return id; }; public String getName() { return name; }; @Override public String toString() { return "item (id, name) => " + "(" + id + ", " + name + ")"; } }; class CRUD { private List<Record> storage = null; public CRUD() { super(); storage = new ArrayList<Record>(); }; public CRUD add(Record record) { storage.add(record); return this; }; public void get() throws NotImplementedException { throw new NotImplementedException(); }; public void update() throws NotImplementedException { throw new NotImplementedException(); }; public void delete() throws NotImplementedException { throw new NotImplementedException(); }; @Override public String toString() { String buf = ""; for(Record record : storage) { buf += record + "\n"; } return buf; }; };
mit
coderkd10/TeamRegistrationApp
app/src/main/java/com/ashish/cop290assign0/utils/LdapFetcher.java
5890
package com.ashish.cop290assign0.utils; import android.util.Log; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.ashish.cop290assign0.config.Config; import org.json.JSONException; import org.json.JSONObject; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Networking Utility to fetch data for auto-form completion/ data verification, uses Volley. * @author Abhishek Kedia on 15/01/16 */ public class LdapFetcher { private static final String TAG = LdapFetcher.class.getSimpleName(); public interface StudentJsonDataHandler { void handle(JSONObject studentDataJson); } private RequestQueue ldapRequestQueue; public LdapFetcher(RequestQueue requestQueue){ ldapRequestQueue = requestQueue; } private Response.Listener<String> ldapResponseHandler(final StudentJsonDataHandler resultHandler) { return new Response.Listener<String>() { @Override public void onResponse(String response) { try{ JSONObject parsedLdapData = parseLdapUsingRegex(response); if(parsedLdapData != null) resultHandler.handle(parsedLdapData); } catch (Exception e){ e.printStackTrace(); } } }; } //fetching student details from LDAP using entered entry number public void getAndHandleStudentDetails(final String inputEntryNumber, final StudentJsonDataHandler resultHandler, final Response.ErrorListener errorHandler){ String studentUserId; try{ studentUserId = entryNumberToUserId(inputEntryNumber); } catch (IllegalArgumentException exception) { exception.printStackTrace(); return; } String requestUrl = Config.LDAP_BASE_URL+"?uid="+studentUserId; StringRequest strReq = new StringRequest(Request.Method.GET, requestUrl, ldapResponseHandler(resultHandler), errorHandler); Log.d(TAG,String.format("Sending request for entryNumber:%s",inputEntryNumber)); ldapRequestQueue.add(strReq); } //fetching student details from LDAP using entered entry number public void getAndHandleStudentDetails(final String inputEntryNumber, final StudentJsonDataHandler resultHandler){ getAndHandleStudentDetails(inputEntryNumber, resultHandler, new Response.ErrorListener(){ @Override public void onErrorResponse(VolleyError error) { Log.i(TAG,"Cannot connect to LDAP. error:"+error); } }); } //converts entry number to userId for fetching details from LDAP private String entryNumberToUserId(String entryNumber) throws IllegalArgumentException{ Pattern entryNumberDataExtractPattern = Pattern.compile(Config.REGEX_ENTRY_NUMBER); Matcher entryNumDataMatcher = entryNumberDataExtractPattern.matcher(entryNumber); if(!entryNumDataMatcher.find() || entryNumDataMatcher.groupCount() < 3) throw new IllegalArgumentException("Input entry number structure invalid"); else { String userId = entryNumDataMatcher.group(2) + entryNumDataMatcher.group(1) + entryNumDataMatcher.group(3); Log.v(TAG,String.format("uid(%s)=%s",entryNumber,userId)); return userId; } } //gets entry number from the html using regex pattern matching private Map<String,String> getEntryNumberAndNameFromLdapH1Text(String h1Text) { Pattern h1TextFormatRegEx = Pattern.compile("^(.+?) \\((20\\d{2}[a-zA-z]{2}[a-zA-z\\d]\\d{4})\\)$"); Matcher h1TextFormatMatcher = h1TextFormatRegEx.matcher(h1Text); if(!h1TextFormatMatcher.find() || h1TextFormatMatcher.groupCount() < 2) return null; Map<String,String> entryNumberAndName = new HashMap<>(); entryNumberAndName.put("name",h1TextFormatMatcher.group(1)); entryNumberAndName.put("entryNumber",h1TextFormatMatcher.group(2)); return entryNumberAndName; }; //gets base64 image from the html using regex pattern matching private String getImageSrcInBase64(String htmlSrc) { Pattern imgBase64SrcRegex = Pattern.compile("<img.*src='data:image/gif;base64,(.*?)' />"); Matcher imgBas64Matcher = imgBase64SrcRegex.matcher(htmlSrc); if(!imgBas64Matcher.find() || imgBas64Matcher.groupCount() < 1) return null; return imgBas64Matcher.group(1); } /** * Parses the html returned by Ldap and retrieves the data contained. * @throws JSONException * @return */ private JSONObject parseLdapUsingRegex(String response) throws JSONException{ JSONObject dataAsJson = new JSONObject(); Pattern h1HeaderRegex = Pattern.compile("<H1>(.*?)</H1>"); Matcher h1HeaderMatcher = h1HeaderRegex.matcher(response); if(!h1HeaderMatcher.find()) return null; String h1HeaderText = h1HeaderMatcher.group(1); if(h1HeaderText.equals(" ()")) { dataAsJson.put("isValid", false); return dataAsJson; } Map<String,String> entryNumberAndName = getEntryNumberAndNameFromLdapH1Text(h1HeaderText); if(entryNumberAndName == null) return null; dataAsJson.put("isValid", true); dataAsJson.put("entryNumber", entryNumberAndName.get("entryNumber")); dataAsJson.put("name", entryNumberAndName.get("name")); String imgSrcInBase64 = getImageSrcInBase64(response); if(imgSrcInBase64 != null) { dataAsJson.put("img", imgSrcInBase64); } return dataAsJson; } }
mit
java-scott/java-project
实战突击:JavaWeb项目整合开发/12/WebRoot/src/com/action/Borrow.java
9085
package com.action; import org.apache.struts.action.*; import javax.servlet.http.*; import com.dao.*; import com.actionForm.*; public class Borrow extends Action { /******************ÔÚ¹¹Ôì·½·¨ÖÐʵÀý»¯BorrowÀàÖÐÓ¦Óõij־òãÀàµÄ¶ÔÏó**************************/ private BorrowDAO borrowDAO = null; private ReaderDAO readerDAO=null; private BookDAO bookDAO=null; private ReaderForm readerForm=new ReaderForm(); public Borrow() { this.borrowDAO = new BorrowDAO(); this.readerDAO=new ReaderDAO(); this.bookDAO=new BookDAO(); } /******************************************************************************************/ public void execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { BorrowForm borrowForm = (BorrowForm) form; String action =request.getParameter("action"); if(action==null||"".equals(action)){ request.setAttribute("error","ÄúµÄ²Ù×÷ÓÐÎó£¡"); request.getRequestDispatcher("error.jsp").forward(request, response); }else if("bookBorrowSort".equals(action)){ return bookBorrowSort(request,response); }else if("bookborrow".equals(action)){ return bookborrow(request,response); //ͼÊé½èÔÄ }else if("bookrenew".equals(action)){ return bookrenew(request,response); //ͼÊéÐø½è }else if("bookback".equals(action)){ return bookback(request,response); //ͼÊé¹é»¹ }else if("Bremind".equals(action)){ return bremind(request,response); //½èÔĵ½ÆÚÌáÐÑ }else if("borrowQuery".equals(action)){ return borrowQuery(request,response); //½èÔÄÐÅÏ¢²éѯ } request.setAttribute("error","²Ù×÷ʧ°Ü£¡"); request.getRequestDispatcher("error.jsp").forward(request, response); } /*********************ͼÊé½èÔÄÅÅÐÐ***********************/ private void bookBorrowSort(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response){ request.setAttribute("bookBorrowSort",borrowDAO.bookBorrowSort()); return mapping.findForward("bookBorrowSort"); } /*********************ͼÊé½èÔIJéѯ***********************/ private void borrowQuery(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response){ String str=null; String flag[]=request.getParameterValues("flag"); if (flag!=null){ String aa = flag[0]; if ("a".equals(aa)) { if (request.getParameter("f") != null) { str = request.getParameter("f") + " like '%" + request.getParameter("key") + "%'"; } } if ("b".equals(aa)) { String sdate = request.getParameter("sdate"); String edate = request.getParameter("edate"); if (sdate != null && edate != null) { str = "borrowTime between '" + sdate + "' and '" + edate + "'"; } System.out.println("ÈÕÆÚ" + str); } //ͬʱѡÔñÈÕÆÚºÍÌõ¼þ½øÐвéѯ if (flag.length == 2) { if (request.getParameter("f") != null) { str = request.getParameter("f") + " like '%" + request.getParameter("key") + "%'"; } System.out.println("ÈÕÆÚºÍÌõ¼þ"); String sdate = request.getParameter("sdate"); String edate = request.getParameter("edate"); String str1 = null; if (sdate != null && edate != null) { str1 = "borrowTime between '" + sdate + "' and '" + edate + "'"; } str = str + " and borr." + str1; System.out.println("Ìõ¼þºÍÈÕÆÚ£º" + str); } } request.setAttribute("borrowQuery",borrowDAO.borrowQuery(str)); System.out.print("Ìõ¼þ²éѯͼÊé½èÔÄÐÅϢʱµÄstr:"+str); return mapping.findForward("borrowQuery"); } /*********************µ½ÆÚÌáÐÑ***********************/ private void bremind(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response){ request.setAttribute("Bremind",borrowDAO.bremind()); return mapping.findForward("Bremind"); } /*********************ͼÊé½èÔÄ***********************/ private void bookborrow(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response){ //²éѯ¶ÁÕßÐÅÏ¢ //ReaderForm readerForm=(ReaderForm)form; //´Ë´¦Ò»¶¨²»ÄÜʹÓøÃÓï¾ä½øÐÐת»» readerForm.setBarcode(request.getParameter("barcode")); ReaderForm reader = (ReaderForm) readerDAO.queryM(readerForm); request.setAttribute("readerinfo", reader); //²éѯ¶ÁÕߵĽèÔÄÐÅÏ¢ request.setAttribute("borrowinfo",borrowDAO.borrowinfo(request.getParameter("barcode"))); //Íê³É½èÔÄ String f = request.getParameter("f"); String key = request.getParameter("inputkey"); if (key != null && !key.equals("")) { String operator = request.getParameter("operator"); BookForm bookForm=bookDAO.queryB(f, key); if (bookForm!=null){ int ret = borrowDAO.insertBorrow(reader, bookDAO.queryB(f, key), operator); if (ret == 1) { request.setAttribute("bar", request.getParameter("barcode")); return mapping.findForward("bookborrowok"); } else { request.setAttribute("error", "Ìí¼Ó½èÔÄÐÅϢʧ°Ü!"); request.getRequestDispatcher("error.jsp").forward(request, response); } }else{ request.setAttribute("error", "ûÓиÃͼÊé!"); request.getRequestDispatcher("error.jsp").forward(request, response); } } return mapping.findForward("bookborrow"); } /*********************ͼÊé¼Ì½è***********************/ private void bookrenew(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response){ //²éѯ¶ÁÕßÐÅÏ¢ readerForm.setBarcode(request.getParameter("barcode")); ReaderForm reader = (ReaderForm) readerDAO.queryM(readerForm); request.setAttribute("readerinfo", reader); //²éѯ¶ÁÕߵĽèÔÄÐÅÏ¢ request.setAttribute("borrowinfo",borrowDAO.borrowinfo(request.getParameter("barcode"))); if(request.getParameter("id")!=null){ int id = Integer.parseInt(request.getParameter("id")); if (id > 0) { //Ö´Ðм̽è²Ù×÷ int ret = borrowDAO.renew(id); if (ret == 0) { request.setAttribute("error", "ͼÊé¼Ì½èʧ°Ü!"); request.getRequestDispatcher("error.jsp").forward(request, response); } else { request.setAttribute("bar", request.getParameter("barcode")); return mapping.findForward("bookrenewok"); } } } return mapping.findForward("bookrenew"); } /*********************ͼÊé¹é»¹***********************/ private void bookback(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response){ //²éѯ¶ÁÕßÐÅÏ¢ readerForm.setBarcode(request.getParameter("barcode")); ReaderForm reader = (ReaderForm) readerDAO.queryM(readerForm); request.setAttribute("readerinfo", reader); //²éѯ¶ÁÕߵĽèÔÄÐÅÏ¢ request.setAttribute("borrowinfo",borrowDAO.borrowinfo(request.getParameter("barcode"))); if(request.getParameter("id")!=null){ int id = Integer.parseInt(request.getParameter("id")); String operator=request.getParameter("operator"); if (id > 0) { //Ö´Ðй黹²Ù×÷ int ret = borrowDAO.back(id,operator); if (ret == 0) { request.setAttribute("error", "ͼÊé¹é»¹Ê§°Ü!"); request.getRequestDispatcher("error.jsp").forward(request, response); } else { request.setAttribute("bar", request.getParameter("barcode")); return mapping.findForward("bookbackok"); } } } return mapping.findForward("bookback"); } }
mit
stanciua/exercism
java/triangle/src/test/java/TriangleTest.java
3931
import org.junit.Test; import org.junit.Ignore; import org.junit.Rule; import org.junit.rules.ExpectedException; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertFalse; public class TriangleTest { @Rule public ExpectedException expectedException = ExpectedException.none(); @Test public void equilateralTrianglesHaveEqualSides() throws TriangleException { Triangle triangle = new Triangle(2, 2, 2); assertTrue(triangle.isEquilateral()); } @Test public void trianglesWithOneUnequalSideAreNotEquilateral() throws TriangleException { Triangle triangle = new Triangle(2, 3, 2); assertFalse(triangle.isEquilateral()); } @Test public void trianglesWithNoEqualSidesAreNotEquilateral() throws TriangleException { Triangle triangle = new Triangle(5, 4, 6); assertFalse(triangle.isEquilateral()); } @Test public void trianglesWithNoSizeAreIllegal() throws TriangleException { expectedException.expect(TriangleException.class); new Triangle(0, 0, 0); } @Test public void verySmallTrianglesCanBeEquilateral() throws TriangleException { Triangle triangle = new Triangle(0.5, 0.5, 0.5); assertTrue(triangle.isEquilateral()); } @Test public void isoscelesTrianglesHaveLastTwoSidesEqual() throws TriangleException { Triangle triangle = new Triangle(3, 4, 4); assertTrue(triangle.isIsosceles()); } @Test public void isoscelesTrianglesHaveTwoFirstSidesEqual() throws TriangleException { Triangle triangle = new Triangle(4, 4, 3); assertTrue(triangle.isIsosceles()); } @Test public void isoscelesTrianglesHaveFirstAndLastSidesEqual() throws TriangleException { Triangle triangle = new Triangle(4, 3, 4); assertTrue(triangle.isIsosceles()); } @Test public void isoscelesTrianglesCanHaveAllSidesEqual() throws TriangleException { Triangle triangle = new Triangle(4, 4, 4); assertTrue(triangle.isIsosceles()); } @Test public void isoscelesTrianglesMustHaveAtLeastTwoEqualSides() throws TriangleException { Triangle triangle = new Triangle(2, 3, 4); assertFalse(triangle.isIsosceles()); } @Test public void testSidesThatViolateTriangleInequalityAreNotIsoscelesEvenIfTwoAreEqual() throws TriangleException { expectedException.expect(TriangleException.class); new Triangle(1, 1, 3); } @Test public void verySmallTrianglesCanBeIsosceles() throws TriangleException { Triangle triangle = new Triangle(0.5, 0.4, 0.5); assertTrue(triangle.isIsosceles()); } @Test public void scaleneTrianglesHaveNoEqualSides() throws TriangleException { Triangle triangle = new Triangle(5, 4, 6); assertTrue(triangle.isScalene()); } @Test public void trianglesWithAllSidesEqualAreNotScalene() throws TriangleException { Triangle triangle = new Triangle(4, 4, 4); assertFalse(triangle.isScalene()); } @Test public void trianglesWithOneUnequalSideAreNotScalene() throws TriangleException { Triangle triangle = new Triangle(4, 4, 3); assertFalse(triangle.isScalene()); } @Test public void testSidesThatViolateTriangleInequalityAreNotScaleneEvenIfTheyAreAllDifferent() throws TriangleException { expectedException.expect(TriangleException.class); new Triangle(7, 3, 2); } @Test public void verySmallTrianglesCanBeScalene() throws TriangleException { Triangle triangle = new Triangle(0.5, 0.4, 0.6); assertTrue(triangle.isScalene()); } @Test public void degenerateTriangle() throws TriangleException { Triangle triangle = new Triangle(0.5, 0.5, 1.0); assertTrue(triangle.isDegenerate()); } }
mit
firstziiz/Classroom
src/classroom/modal/Work.java
3227
/* * 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 classroom.modal; import classroom.database.ConnectionDB; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; /** * * @author KS */ public class Work { private int id; private String name; private String desc; private int status; private int score; private int std; private int tch; private String answer; private String path; public Work(int id) throws SQLException{ Connection conn = ConnectionDB.getConnection(); PreparedStatement ps = conn.prepareStatement("select * from Work where id=?"); ps.setInt(1, id); ResultSet rs = ps.executeQuery(); if (rs.next()) { this.id = rs.getInt("id"); this.name = rs.getString("name"); this.desc = rs.getString("description"); this.status = rs.getInt("status"); this.score = rs.getInt("score"); this.tch = rs.getInt("tch"); this.std = rs.getInt("std"); this.answer = rs.getString("answer"); this.path = rs.getString("path"); } conn.close(); } // [STATIC] Get All Student on Arraylist public static ArrayList<Work> getAllStudent() throws SQLException { Connection conn = ConnectionDB.getConnection(); ArrayList<Work> listWrk = new ArrayList<Work>(); PreparedStatement ck = conn.prepareStatement("select * from Work"); ResultSet result = ck.executeQuery(); while (result.next()) { listWrk.add(new Work(result.getInt("id"))); } conn.close(); return listWrk; } public int getId() { return id; } public String getName() { return name; } public String getDesc() { return desc; } public int getStatus() { return status; } public int getScore() { return score; } public int getStd() { return std; } public int getTch() { return tch; } public String getAnswer() { return answer; } public String getPath() { return path; } @Override public String toString() { // return "Work{" + "id=" + id + ", name=" + name + ", desc=" + desc + ", status=" + status + ", score=" + score + ", std=" + std + ", tch=" + tch + ", answer=" + answer + '}'; if (status==0){ return " "+name+" | "+"Description : "+desc+" | "+"Teacher : "+tch+" | "+"Student : "+std+" | "+"Status : Unsent" ; }else if(status==1){ return " "+name+" | "+"Description : "+desc+" | "+"Teacher : "+tch+" | "+"Student : "+std+" | "+"Status : Sent .. wait for approve"+" | "+"Answer : "+answer ; }else{ return " "+name+" | "+"Description : "+desc+" | "+"Teacher : "+tch+" | "+"Student : "+std+" | "+"Status : "+status+" | "+"Answer : "+answer+" | score : "+score; } } }
mit
Noukkis/NoukkisBot
src/main/java/noukkisBot/sockets/Configurator.java
1257
/* * The MIT License * * Copyright 2018 Noukkis. * * 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 noukkisBot.sockets; /** * * @author Noukkis */ public class Configurator { }
mit
PFGimenez/The-Kraken-Pathfinding
core/src/main/java/pfg/kraken/astar/tentacles/Tentacle.java
3389
/* * Copyright (C) 2013-2019 Pierre-François Gimenez * Distributed under the MIT License. */ package pfg.kraken.astar.tentacles; import java.awt.Graphics; import java.util.Iterator; import pfg.kraken.display.Display; import pfg.kraken.display.Printable; import pfg.kraken.display.PrintablePoint; import pfg.kraken.obstacles.RectangularObstacle; import pfg.kraken.struct.EmbodiedKinematic; /** * Un arc de trajectoire courbe. Juste une succession de points. * * @author pf * */ public abstract class Tentacle implements Printable, Iterable<RectangularObstacle>, Iterator<RectangularObstacle> { public static final double PRECISION_TRACE = 0.02; // précision du tracé, en // m (distance entre // deux points // consécutifs). Plus le // tracé est précis, // plus on couvre de // point une même // distance public static final double PRECISION_TRACE_MM = PRECISION_TRACE * 1000; // précision // du // tracé, // en // mm public static final int NB_POINTS = 5; // nombre de points dans un arc public static final double DISTANCE_ARC_COURBE = PRECISION_TRACE_MM * NB_POINTS; // en // mm public static final double DISTANCE_ARC_COURBE_M = PRECISION_TRACE * NB_POINTS; // en // m private static final long serialVersionUID = 1268198325807123306L; public TentacleType vitesse; // utilisé pour le debug private int indexIter; private int remainingNb; public abstract int getNbPoints(); public abstract EmbodiedKinematic getPoint(int indice); public abstract EmbodiedKinematic getLast(); public final double getDuree(Tentacle tentacleParent, double translationalSpeed, int tempsArret, double curvaturePenalty) { boolean firstMove = tentacleParent == null; // le premier mouvement est particulier : on est déjà arrêté ! int nb = getNbPoints(); double out = 0; // l'arc courant est construit classiquement (ce cas est géré à la reconstruction de la trajectoire) for(int i = 0; i < nb; i++) { EmbodiedKinematic ek = getPoint(i); ek.maxSpeed = Math.min(ek.maxSpeed, translationalSpeed); out += PRECISION_TRACE_MM / ek.maxSpeed; out += Math.abs(ek.cinem.courbureReelle) * curvaturePenalty; } assert vitesse.getNbArrets(firstMove) >= 0; return out + vitesse.getNbArrets(firstMove) * tempsArret; } @Override public String toString() { String out = getClass().getSimpleName() + " (" + vitesse + ") with " + getNbPoints() + " points:\n"; for(int i = 0; i < getNbPoints() - 1; i++) out += getPoint(i) + "\n"; out += getLast(); return out; } @Override public void print(Graphics g, Display f) { for(int i = 0; i < getNbPoints(); i++) new PrintablePoint(getPoint(i).cinem.getX(), getPoint(i).cinem.getY()).print(g, f); } @Override public Iterator<RectangularObstacle> iterator() { indexIter = 0; remainingNb = 0; for(int i = 0; i < getNbPoints(); i++) if(!getPoint(i).ignoreCollision) remainingNb++; return this; } @Override public boolean hasNext() { return remainingNb > 0; } @Override public RectangularObstacle next() { while(getPoint(indexIter).ignoreCollision) indexIter++; remainingNb--; return getPoint(indexIter++).obstacle; } }
mit
yamashiro0110/JavaEE
Payara/src/main/java/sample/payara/model/SampleModel.java
1072
package sample.payara.model; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import com.fasterxml.jackson.annotation.JsonFormat; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.AllArgsConstructor; import lombok.NoArgsConstructor; @Entity @Table(name = "sample_model") @NoArgsConstructor @AllArgsConstructor public class SampleModel { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @JsonProperty private Long id = null; @Column(name = "name") @JsonProperty private String name = ""; @Column(name = "created") @JsonFormat(pattern = "yyyy-MM-dd HH:mm") private Date created = new Date(); @Column(name = "updated") @JsonFormat(pattern = "yyyy-MM-dd HH:mm") private Date updated = null; public SampleModel(final long id, final String name) { this.id = id; this.name = name; } }
mit
asciiCerebrum/neocortexEngine
src/test/java/org/asciicerebrum/neocortexengine/domain/core/particles/CriticalFactorTest.java
1078
package org.asciicerebrum.neocortexengine.domain.core.particles; import org.junit.After; import org.junit.AfterClass; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; /** * * @author species8472 */ public class CriticalFactorTest { private CriticalFactor factor; public CriticalFactorTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { this.factor = new CriticalFactor(42L); } @After public void tearDown() { } @Test public void equalsSameClassTrueTest() { assertTrue(this.factor.equals(new CriticalFactor(42L))); } @Test public void equalsSameClassFalseTest() { assertFalse(this.factor.equals(new CriticalFactor(43L))); } @Test public void equalsDifferentClassTest() { assertFalse(this.factor.equals(new AbilityScore(42L))); } }
mit
javawolfpack/CSCI567---Workspace
SimpleDBExample/src/csci567/simpledbexample/DBHelper.java
2012
package csci567.simpledbexample; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; public class DBHelper extends SQLiteOpenHelper{ final static String DB_NAME = "example.db"; final static int DB_VERSION = 1; private final String EXAMPLE_TABLE = "configTable"; Context context; public DBHelper(Context context){ super(context, DB_NAME, null, DB_VERSION); this.context=context; } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE IF NOT EXISTS " + EXAMPLE_TABLE + " (text VARCHAR);"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub } public boolean insertText(String text){ try{ //DBHelper appDB = new DBHelper(context); SQLiteDatabase qdb = this.getWritableDatabase(); Log.d("DB Insert: ", "INSERT OR REPLACE INTO " + EXAMPLE_TABLE + " (text) Values ("+ text + ");"); qdb.execSQL("INSERT OR REPLACE INTO " + EXAMPLE_TABLE + " (text) Values (\""+ text + "\");"); qdb.close(); } catch(SQLiteException se){ Log.d("DB Insert Error: ",se.toString()); return false; } return true; } public String getText(){ String toReturn = ""; try{ //DBHelper appDB = new DBHelper(context); SQLiteDatabase qdb = this.getReadableDatabase(); qdb.execSQL("CREATE TABLE IF NOT EXISTS " + EXAMPLE_TABLE + " (text VARCHAR);"); Cursor c = qdb.rawQuery("SELECT * FROM " + EXAMPLE_TABLE, null); if (c != null ) { if (c.moveToFirst()) { do { String text = c.getString(c.getColumnIndex("text")); toReturn += text + "\n"; } while (c.moveToNext()); } } qdb.close(); } catch(SQLiteException se){ Log.d("DB Select Error: ",se.toString()); return ""; } return toReturn; } }
mit
raeffu/prog1
src/_excercises/ch03/House.java
1447
package _excercises.ch03; import java.awt.Graphics2D; import java.awt.Rectangle; import java.awt.geom.Line2D; import java.awt.geom.Point2D; /** A house that can be positioned anywhere on the screen. */ public class House { private int xPos; private int yPos; public House(int x, int y) { xPos = x; yPos = y; } public void draw(Graphics2D g2) { Rectangle front = new Rectangle(xPos, yPos, 100, 100); Rectangle door = new Rectangle(xPos+10, yPos+60, 20, 40); Rectangle window = new Rectangle(xPos+60, yPos+30, 20, 20); Point2D.Double roofLeftPoint = new Point2D.Double(xPos, yPos); Point2D.Double roofRightPoint = new Point2D.Double(xPos+100, yPos); Point2D.Double roofTopPoint = new Point2D.Double(xPos+50, yPos-50); Line2D.Double roofLeftLine = new Line2D.Double(roofLeftPoint, roofTopPoint); Line2D.Double roofRightLine = new Line2D.Double(roofRightPoint, roofTopPoint); g2.draw(front); g2.draw(door); g2.draw(window); g2.draw(roofLeftLine); g2.draw(roofRightLine); } public int[] setPos(int x, int y) { xPos = x; yPos = y; return new int[]{xPos, yPos}; } public int[] getPos() { return new int[]{xPos, yPos}; } public int getxPos() { return xPos; } public int getyPos() { return yPos; } }
mit
daviscook477/DotPaths
src/expands/GifSequenceWriter.java
6283
package expands; // // GifSequenceWriter.java // // Created by Elliot Kroo on 2009-04-25. // // This work is licensed under the Creative Commons Attribution 3.0 Unported // License. To view a copy of this license, visit // http://creativecommons.org/licenses/by/3.0/ or send a letter to Creative // Commons, 171 Second Street, Suite 300, San Francisco, California, 94105, USA. import javax.imageio.*; import javax.imageio.metadata.*; import javax.imageio.stream.*; import java.awt.image.*; import java.io.*; import java.util.Iterator; public class GifSequenceWriter { protected ImageWriter gifWriter; protected ImageWriteParam imageWriteParam; protected IIOMetadata imageMetaData; /** * Creates a new GifSequenceWriter * * @param outputStream the ImageOutputStream to be written to * @param imageType one of the imageTypes specified in BufferedImage * @param timeBetweenFramesMS the time between frames in miliseconds * @param loopContinuously wether the gif should loop repeatedly * @throws IIOException if no gif ImageWriters are found * * @author Elliot Kroo (elliot[at]kroo[dot]net) */ public GifSequenceWriter( ImageOutputStream outputStream, int imageType, int timeBetweenFramesMS, boolean loopContinuously) throws IIOException, IOException { // my method to create a writer gifWriter = getWriter(); imageWriteParam = gifWriter.getDefaultWriteParam(); ImageTypeSpecifier imageTypeSpecifier = ImageTypeSpecifier.createFromBufferedImageType(imageType); imageMetaData = gifWriter.getDefaultImageMetadata(imageTypeSpecifier, imageWriteParam); String metaFormatName = imageMetaData.getNativeMetadataFormatName(); IIOMetadataNode root = (IIOMetadataNode) imageMetaData.getAsTree(metaFormatName); IIOMetadataNode graphicsControlExtensionNode = getNode( root, "GraphicControlExtension"); graphicsControlExtensionNode.setAttribute("disposalMethod", "none"); graphicsControlExtensionNode.setAttribute("userInputFlag", "FALSE"); graphicsControlExtensionNode.setAttribute( "transparentColorFlag", "FALSE"); graphicsControlExtensionNode.setAttribute( "delayTime", Integer.toString(timeBetweenFramesMS / 10)); graphicsControlExtensionNode.setAttribute( "transparentColorIndex", "0"); IIOMetadataNode commentsNode = getNode(root, "CommentExtensions"); commentsNode.setAttribute("CommentExtension", "Created by MAH"); IIOMetadataNode appEntensionsNode = getNode( root, "ApplicationExtensions"); IIOMetadataNode child = new IIOMetadataNode("ApplicationExtension"); child.setAttribute("applicationID", "NETSCAPE"); child.setAttribute("authenticationCode", "2.0"); int loop = loopContinuously ? 0 : 1; child.setUserObject(new byte[]{ 0x1, (byte) (loop & 0xFF), (byte) ((loop >> 8) & 0xFF)}); appEntensionsNode.appendChild(child); imageMetaData.setFromTree(metaFormatName, root); gifWriter.setOutput(outputStream); gifWriter.prepareWriteSequence(null); } public void writeToSequence(RenderedImage img) throws IOException { gifWriter.writeToSequence( new IIOImage( img, null, imageMetaData), imageWriteParam); } /** * Close this GifSequenceWriter object. This does not close the underlying * stream, just finishes off the GIF. */ public void close() throws IOException { gifWriter.endWriteSequence(); } /** * Returns the first available GIF ImageWriter using * ImageIO.getImageWritersBySuffix("gif"). * * @return a GIF ImageWriter object * @throws IIOException if no GIF image writers are returned */ private static ImageWriter getWriter() throws IIOException { Iterator<ImageWriter> iter = ImageIO.getImageWritersBySuffix("gif"); if(!iter.hasNext()) { throw new IIOException("No GIF Image Writers Exist"); } else { return iter.next(); } } /** * Returns an existing child node, or creates and returns a new child node (if * the requested node does not exist). * * @param rootNode the <tt>IIOMetadataNode</tt> to search for the child node. * @param nodeName the name of the child node. * * @return the child node, if found or a new node created with the given name. */ private static IIOMetadataNode getNode( IIOMetadataNode rootNode, String nodeName) { int nNodes = rootNode.getLength(); for (int i = 0; i < nNodes; i++) { if (rootNode.item(i).getNodeName().compareToIgnoreCase(nodeName) == 0) { return((IIOMetadataNode) rootNode.item(i)); } } IIOMetadataNode node = new IIOMetadataNode(nodeName); rootNode.appendChild(node); return(node); } /** public GifSequenceWriter( BufferedOutputStream outputStream, int imageType, int timeBetweenFramesMS, boolean loopContinuously) { */ public static void main(String[] args) throws Exception { if (args.length > 1) { // grab the output image type from the first image in the sequence BufferedImage firstImage = ImageIO.read(new File(args[0])); // create a new BufferedOutputStream with the last argument ImageOutputStream output = new FileImageOutputStream(new File(args[args.length - 1])); // create a gif sequence with the type of the first image, 1 second // between frames, which loops continuously GifSequenceWriter writer = new GifSequenceWriter(output, firstImage.getType(), 1, false); // write out the first image to our sequence... writer.writeToSequence(firstImage); for(int i=1; i<args.length-1; i++) { BufferedImage nextImage = ImageIO.read(new File(args[i])); writer.writeToSequence(nextImage); } writer.close(); output.close(); } else { System.out.println( "Usage: java GifSequenceWriter [list of gif files] [output file]"); } } }
mit
HenryHarper/Acquire-Reboot
gradle/src/platform-jvm/org/gradle/jvm/tasks/api/internal/SortingAnnotationVisitor.java
3093
/* * Copyright 2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.jvm.tasks.api.internal; import com.google.common.collect.Lists; import org.objectweb.asm.AnnotationVisitor; import java.util.List; import static org.objectweb.asm.Opcodes.ASM5; public class SortingAnnotationVisitor extends AnnotationVisitor { private final List<AnnotationValue<?>> annotationValues = Lists.newLinkedList(); private final AnnotationMember annotation; private SortingAnnotationVisitor parentVisitor; private String annotationValueName; private String arrayValueName; public SortingAnnotationVisitor(AnnotationMember parentAnnotation, AnnotationVisitor av) { super(ASM5, av); this.annotation = parentAnnotation; } @Override public AnnotationVisitor visitAnnotation(String name, String desc) { AnnotationMember annotation = new AnnotationMember(desc, true); SortingAnnotationVisitor visitor = new SortingAnnotationVisitor(annotation, super.visitAnnotation(name, desc)); visitor.parentVisitor = this; visitor.annotationValueName = (name == null) ? "value" : name; return visitor; } @Override public void visit(String name, Object value) { annotationValues.add(new SimpleAnnotationValue(name, value)); super.visit(name, value); } @Override public AnnotationVisitor visitArray(String name) { SortingAnnotationVisitor visitor = new SortingAnnotationVisitor(annotation, super.visitArray(name)); visitor.arrayValueName = name; return visitor; } @Override public void visitEnum(String name, String desc, String value) { annotationValues.add(new EnumAnnotationValue(name == null ? "value" : name, value, desc)); super.visitEnum(name, desc, value); } @Override public void visitEnd() { if (annotationValueName != null) { AnnotationAnnotationValue value = new AnnotationAnnotationValue(annotationValueName, annotation); parentVisitor.annotationValues.add(value); annotationValueName = null; } else if (arrayValueName != null) { ArrayAnnotationValue value = new ArrayAnnotationValue( arrayValueName, annotationValues.toArray(new AnnotationValue<?>[0])); annotation.addValue(value); arrayValueName = null; } annotation.addValues(annotationValues); annotationValues.clear(); super.visitEnd(); } }
mit
MrCelticFox/RoM_TPRP
Main.java
6088
import java.awt.EventQueue; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextArea; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; public class Main { private static ArrayList<Transporter> transporters; /** * Creates the UI, all components are defined in the natural reading order * (left to right, top to bottom) unless otherwise specified. */ private static void create() { // list of locations to choose from is generated based on the ArrayList String locations[] = new String[transporters.size()]; for (int i=0; i<transporters.size(); i++) locations[i] = transporters.get(i).toStringShort(); JFrame frame; frame = new JFrame(); frame.setBounds(100, 100, 500, 300); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); GridBagLayout gridBagLayout = new GridBagLayout(); gridBagLayout.columnWidths = new int[]{0, 0, 0}; gridBagLayout.rowHeights = new int[]{0, 0, 0, 0, 0}; gridBagLayout.columnWeights = new double[]{0.0, 0.0, 0.0}; gridBagLayout.rowWeights = new double[]{0.0, 0.0, 0.0, 0.0, 1.0}; frame.getContentPane().setLayout(gridBagLayout); JLabel title = new JLabel("Transport Portal Route Planner"); GridBagConstraints gbc_title = new GridBagConstraints(); gbc_title.insets = new Insets(5, 5, 30, 5); gbc_title.gridwidth = 3; gbc_title.gridx = 0; gbc_title.gridy = 0; frame.getContentPane().add(title, gbc_title); JLabel opt1_lbl = new JLabel("Start Point:"); GridBagConstraints gbc_opt1_lbl = new GridBagConstraints(); gbc_opt1_lbl.insets = new Insets(10, 10, 10, 10); gbc_opt1_lbl.gridx = 0; gbc_opt1_lbl.gridy = 1; frame.getContentPane().add(opt1_lbl, gbc_opt1_lbl); JLabel opt2_lbl = new JLabel("Destination:"); GridBagConstraints gbc_opt2_lbl = new GridBagConstraints(); gbc_opt2_lbl.insets = new Insets(10, 10, 10, 10); gbc_opt2_lbl.gridx = 2; gbc_opt2_lbl.gridy = 1; frame.getContentPane().add(opt2_lbl, gbc_opt2_lbl); final JComboBox<String> start = new JComboBox<String>(locations); GridBagConstraints gbc_start = new GridBagConstraints(); gbc_start.insets = new Insets(10, 10, 10, 10); gbc_start.fill = GridBagConstraints.HORIZONTAL; gbc_start.gridx = 0; gbc_start.gridy = 2; frame.getContentPane().add(start, gbc_start); JLabel lbl = new JLabel("to"); GridBagConstraints gbc_lbl = new GridBagConstraints(); gbc_lbl.insets = new Insets(10, 10, 10, 10); gbc_lbl.gridx = 1; gbc_lbl.gridy = 2; frame.getContentPane().add(lbl, gbc_lbl); final JComboBox<String> destination = new JComboBox<String>(locations); GridBagConstraints gbc_destination = new GridBagConstraints(); gbc_destination.insets = new Insets(10, 10, 10, 10); gbc_destination.fill = GridBagConstraints.HORIZONTAL; gbc_destination.gridx = 2; gbc_destination.gridy = 2; frame.getContentPane().add(destination, gbc_destination); JLabel type_lbl = new JLabel("Route Type:"); GridBagConstraints gbc_type_lbl = new GridBagConstraints(); gbc_type_lbl.insets = new Insets(10, 10, 10, 10); gbc_type_lbl.gridx = 0; gbc_type_lbl.gridy = 3; frame.getContentPane().add(type_lbl, gbc_type_lbl); String options[] = {"cheapest", "quickest"}; JComboBox<String> type = new JComboBox<String>(options); GridBagConstraints gbc_type = new GridBagConstraints(); gbc_type.insets = new Insets(10, 10, 10, 10); gbc_type.fill = GridBagConstraints.HORIZONTAL; gbc_type.gridx = 1; gbc_type.gridy = 3; frame.getContentPane().add(type, gbc_type); // textarea for the results, text will be set when the user presses the submit button final JTextArea results = new JTextArea(); results.setEditable(false); results.setAlignmentX(JComponent.CENTER_ALIGNMENT); /*output = new JTextPane(); //Code for aligning if needed (untested) SimpleAttributeSet attribs = new SimpleAttributeSet(); StyleConstants.setAlignment(attribs , StyleConstants.ALIGN_RIGHT); output.setParagraphAttributes(attribs,true);*/ GridBagConstraints gbc_results = new GridBagConstraints(); gbc_results.insets = new Insets(10, 10, 10, 10); gbc_results.fill = GridBagConstraints.BOTH; gbc_results.gridwidth = 3; gbc_results.gridx = 0; gbc_results.gridy = 4; frame.getContentPane().add(results, gbc_results); // needs to come after all the parts is uses are declared JButton submit = new JButton("GO"); submit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String path = ""; int a = start.getSelectedIndex(); int b = destination.getSelectedIndex(); path += transporters.get(a).goesTo().get(1).get(Transporter.TAG_PLACE) + "\n"; path += transporters.get(b).goesTo().get(0).get(Transporter.TAG_PLACE) + "\n"; results.setText(path); // TODO: replace contents with pathGenerator method } }); GridBagConstraints gbc_submit = new GridBagConstraints(); gbc_submit.insets = new Insets(10, 10, 10, 10); gbc_submit.gridx = 2; gbc_submit.gridy = 3; frame.getContentPane().add(submit, gbc_submit); // show the whole thing frame.setVisible(true); } /** * Starts the program. The list of transporters is loaded and then the Main * thread passes control immediately to the Swing event thread. * * @param args not used */ public static void main(String[] args) { TransporterUtils t = new TransporterUtils(); transporters = t.parseFromFile("src/transporters.json"); transporters = t.sortTransporters(transporters); // look and feel closer to what users are used to try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (IllegalAccessException | InstantiationException | ClassNotFoundException | UnsupportedLookAndFeelException e) { } EventQueue.invokeLater(new Runnable() { public void run() { create(); } }); } }
mit
kodejava/webapp-example
springbean-servlet-example/src/main/java/org/kodejava/example/servlet/dao/impl/UserDaoImpl.java
366
package org.kodejava.example.servlet.dao.impl; import org.kodejava.example.servlet.dao.UserDao; import org.kodejava.example.servlet.model.User; public class UserDaoImpl implements UserDao { public User getUser(Long userId) { if (userId == 1L) { return new User(1L, "wsaryada", "Wayan Saryada"); } return new User(); } }
mit
arvjus/fintrack-java
fintrack-model/src/test/java/org/zv/fintrack/support/LoadDataTestCaseSupport.java
1791
package org.zv.fintrack.support; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import junit.framework.TestCase; import org.dbunit.dataset.IDataSet; import org.dbunit.dataset.xml.XmlDataSet; import org.dbunit.IDatabaseTester; import org.dbunit.JndiDatabaseTester; /** * Base class for test cases, where data is loaded manually. * * @author arju */ public abstract class LoadDataTestCaseSupport extends TestCase { /** * Target database. */ private static final String JNDI_DATASET = "java:openejb/Resource/fintrackDB"; /** * Used to cleanup database etc. */ private IDatabaseTester databaseTester; /** * Call this first whenever need to access JNDI or logging. * * @return initial context. * @throws NamingException */ protected Context getContext() throws NamingException { return new InitialContext(); } /** * Call this 1st to enable JNDI and logging */ @Override protected void setUp() throws Exception { super.setUp(); getContext(); } /** * Loads data set from xml file. Performs CLEAR_INSERT operation on database. * * @param filename * @throws Exception */ protected void loadData(String filename) throws Exception { IDataSet dataSet = new XmlDataSet(ClassLoader.getSystemClassLoader().getResourceAsStream(filename)); databaseTester = new JndiDatabaseTester(JNDI_DATASET); databaseTester.setDataSet(dataSet); databaseTester.onSetup(); } /** * Unload data. Performs CLEAR operation on loaded database. * * @throws Exception */ protected void unloadData() throws Exception { if (databaseTester != null) { databaseTester.onTearDown(); } databaseTester = null; } }
mit
mcaliman/dochi
src/org/docbook/ns/docbook/Refclass.java
19736
// // Questo file è stato generato dall'architettura JavaTM per XML Binding (JAXB) Reference Implementation, v2.2.8-b130911.1802 // Vedere <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Qualsiasi modifica a questo file andrà persa durante la ricompilazione dello schema di origine. // Generato il: 2016.09.12 alle 10:18:45 PM CEST // package org.docbook.ns.docbook; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElementRef; import javax.xml.bind.annotation.XmlID; import javax.xml.bind.annotation.XmlIDREF; import javax.xml.bind.annotation.XmlMixed; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; /** * <p>Classe Java per anonymous complex type. * * <p>Il seguente frammento di schema specifica il contenuto previsto contenuto in questa classe. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element ref="{http://docbook.org/ns/docbook}application" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;attGroup ref="{http://docbook.org/ns/docbook}db.common.attributes"/> * &lt;attGroup ref="{http://docbook.org/ns/docbook}db.common.linking.attributes"/> * &lt;attribute name="role" type="{http://www.w3.org/2001/XMLSchema}anySimpleType" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "content" }) @XmlRootElement(name = "refclass") public class Refclass { @XmlElementRef(name = "application", namespace = "http://docbook.org/ns/docbook", type = Application.class, required = false) @XmlMixed protected List<Object> content; @XmlAttribute(name = "role") @XmlSchemaType(name = "anySimpleType") protected String role; @XmlAttribute(name = "id", namespace = "http://www.w3.org/XML/1998/namespace") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID @XmlSchemaType(name = "ID") protected String id; @XmlAttribute(name = "version") @XmlSchemaType(name = "anySimpleType") protected String commonVersion; @XmlAttribute(name = "lang", namespace = "http://www.w3.org/XML/1998/namespace") @XmlSchemaType(name = "anySimpleType") protected String xmlLang; @XmlAttribute(name = "base", namespace = "http://www.w3.org/XML/1998/namespace") @XmlSchemaType(name = "anySimpleType") protected String base; @XmlAttribute(name = "remap") @XmlSchemaType(name = "anySimpleType") protected String remap; @XmlAttribute(name = "xreflabel") @XmlSchemaType(name = "anySimpleType") protected String xreflabel; @XmlAttribute(name = "revisionflag") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) protected String revisionflag; @XmlAttribute(name = "dir") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) protected String dir; @XmlAttribute(name = "arch") @XmlSchemaType(name = "anySimpleType") protected String arch; @XmlAttribute(name = "audience") @XmlSchemaType(name = "anySimpleType") protected String audience; @XmlAttribute(name = "condition") @XmlSchemaType(name = "anySimpleType") protected String condition; @XmlAttribute(name = "conformance") @XmlSchemaType(name = "anySimpleType") protected String conformance; @XmlAttribute(name = "os") @XmlSchemaType(name = "anySimpleType") protected String os; @XmlAttribute(name = "revision") @XmlSchemaType(name = "anySimpleType") protected String commonRevision; @XmlAttribute(name = "security") @XmlSchemaType(name = "anySimpleType") protected String security; @XmlAttribute(name = "userlevel") @XmlSchemaType(name = "anySimpleType") protected String userlevel; @XmlAttribute(name = "vendor") @XmlSchemaType(name = "anySimpleType") protected String vendor; @XmlAttribute(name = "wordsize") @XmlSchemaType(name = "anySimpleType") protected String wordsize; @XmlAttribute(name = "annotations") @XmlSchemaType(name = "anySimpleType") protected String annotations; @XmlAttribute(name = "linkend") @XmlIDREF @XmlSchemaType(name = "IDREF") protected Object linkend; @XmlAttribute(name = "href", namespace = "http://www.w3.org/1999/xlink") @XmlSchemaType(name = "anySimpleType") protected String href; @XmlAttribute(name = "type", namespace = "http://www.w3.org/1999/xlink") @XmlSchemaType(name = "anySimpleType") protected String xlinkType; @XmlAttribute(name = "role", namespace = "http://www.w3.org/1999/xlink") @XmlSchemaType(name = "anySimpleType") protected String xlinkRole; @XmlAttribute(name = "arcrole", namespace = "http://www.w3.org/1999/xlink") @XmlSchemaType(name = "anySimpleType") protected String arcrole; @XmlAttribute(name = "title", namespace = "http://www.w3.org/1999/xlink") @XmlSchemaType(name = "anySimpleType") protected String xlinkTitle; @XmlAttribute(name = "show", namespace = "http://www.w3.org/1999/xlink") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) protected String show; @XmlAttribute(name = "actuate", namespace = "http://www.w3.org/1999/xlink") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) protected String actuate; /** * Gets the value of the content property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the content property. * * <p> * For example, to add a new item, do as follows: * <pre> * getContent().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Application } * {@link String } * * */ public List<Object> getContent() { if (content == null) { content = new ArrayList<Object>(); } return this.content; } /** * Recupera il valore della proprietà role. * * @return * possible object is * {@link String } * */ public String getRole() { return role; } /** * Imposta il valore della proprietà role. * * @param value * allowed object is * {@link String } * */ public void setRole(String value) { this.role = value; } /** * Recupera il valore della proprietà id. * * @return * possible object is * {@link String } * */ public String getId() { return id; } /** * Imposta il valore della proprietà id. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Recupera il valore della proprietà commonVersion. * * @return * possible object is * {@link String } * */ public String getCommonVersion() { return commonVersion; } /** * Imposta il valore della proprietà commonVersion. * * @param value * allowed object is * {@link String } * */ public void setCommonVersion(String value) { this.commonVersion = value; } /** * Recupera il valore della proprietà xmlLang. * * @return * possible object is * {@link String } * */ public String getXmlLang() { return xmlLang; } /** * Imposta il valore della proprietà xmlLang. * * @param value * allowed object is * {@link String } * */ public void setXmlLang(String value) { this.xmlLang = value; } /** * Recupera il valore della proprietà base. * * @return * possible object is * {@link String } * */ public String getBase() { return base; } /** * Imposta il valore della proprietà base. * * @param value * allowed object is * {@link String } * */ public void setBase(String value) { this.base = value; } /** * Recupera il valore della proprietà remap. * * @return * possible object is * {@link String } * */ public String getRemap() { return remap; } /** * Imposta il valore della proprietà remap. * * @param value * allowed object is * {@link String } * */ public void setRemap(String value) { this.remap = value; } /** * Recupera il valore della proprietà xreflabel. * * @return * possible object is * {@link String } * */ public String getXreflabel() { return xreflabel; } /** * Imposta il valore della proprietà xreflabel. * * @param value * allowed object is * {@link String } * */ public void setXreflabel(String value) { this.xreflabel = value; } /** * Recupera il valore della proprietà revisionflag. * * @return * possible object is * {@link String } * */ public String getRevisionflag() { return revisionflag; } /** * Imposta il valore della proprietà revisionflag. * * @param value * allowed object is * {@link String } * */ public void setRevisionflag(String value) { this.revisionflag = value; } /** * Recupera il valore della proprietà dir. * * @return * possible object is * {@link String } * */ public String getDir() { return dir; } /** * Imposta il valore della proprietà dir. * * @param value * allowed object is * {@link String } * */ public void setDir(String value) { this.dir = value; } /** * Recupera il valore della proprietà arch. * * @return * possible object is * {@link String } * */ public String getArch() { return arch; } /** * Imposta il valore della proprietà arch. * * @param value * allowed object is * {@link String } * */ public void setArch(String value) { this.arch = value; } /** * Recupera il valore della proprietà audience. * * @return * possible object is * {@link String } * */ public String getAudience() { return audience; } /** * Imposta il valore della proprietà audience. * * @param value * allowed object is * {@link String } * */ public void setAudience(String value) { this.audience = value; } /** * Recupera il valore della proprietà condition. * * @return * possible object is * {@link String } * */ public String getCondition() { return condition; } /** * Imposta il valore della proprietà condition. * * @param value * allowed object is * {@link String } * */ public void setCondition(String value) { this.condition = value; } /** * Recupera il valore della proprietà conformance. * * @return * possible object is * {@link String } * */ public String getConformance() { return conformance; } /** * Imposta il valore della proprietà conformance. * * @param value * allowed object is * {@link String } * */ public void setConformance(String value) { this.conformance = value; } /** * Recupera il valore della proprietà os. * * @return * possible object is * {@link String } * */ public String getOs() { return os; } /** * Imposta il valore della proprietà os. * * @param value * allowed object is * {@link String } * */ public void setOs(String value) { this.os = value; } /** * Recupera il valore della proprietà commonRevision. * * @return * possible object is * {@link String } * */ public String getCommonRevision() { return commonRevision; } /** * Imposta il valore della proprietà commonRevision. * * @param value * allowed object is * {@link String } * */ public void setCommonRevision(String value) { this.commonRevision = value; } /** * Recupera il valore della proprietà security. * * @return * possible object is * {@link String } * */ public String getSecurity() { return security; } /** * Imposta il valore della proprietà security. * * @param value * allowed object is * {@link String } * */ public void setSecurity(String value) { this.security = value; } /** * Recupera il valore della proprietà userlevel. * * @return * possible object is * {@link String } * */ public String getUserlevel() { return userlevel; } /** * Imposta il valore della proprietà userlevel. * * @param value * allowed object is * {@link String } * */ public void setUserlevel(String value) { this.userlevel = value; } /** * Recupera il valore della proprietà vendor. * * @return * possible object is * {@link String } * */ public String getVendor() { return vendor; } /** * Imposta il valore della proprietà vendor. * * @param value * allowed object is * {@link String } * */ public void setVendor(String value) { this.vendor = value; } /** * Recupera il valore della proprietà wordsize. * * @return * possible object is * {@link String } * */ public String getWordsize() { return wordsize; } /** * Imposta il valore della proprietà wordsize. * * @param value * allowed object is * {@link String } * */ public void setWordsize(String value) { this.wordsize = value; } /** * Recupera il valore della proprietà annotations. * * @return * possible object is * {@link String } * */ public String getAnnotations() { return annotations; } /** * Imposta il valore della proprietà annotations. * * @param value * allowed object is * {@link String } * */ public void setAnnotations(String value) { this.annotations = value; } /** * Recupera il valore della proprietà linkend. * * @return * possible object is * {@link Object } * */ public Object getLinkend() { return linkend; } /** * Imposta il valore della proprietà linkend. * * @param value * allowed object is * {@link Object } * */ public void setLinkend(Object value) { this.linkend = value; } /** * Recupera il valore della proprietà href. * * @return * possible object is * {@link String } * */ public String getHref() { return href; } /** * Imposta il valore della proprietà href. * * @param value * allowed object is * {@link String } * */ public void setHref(String value) { this.href = value; } /** * Recupera il valore della proprietà xlinkType. * * @return * possible object is * {@link String } * */ public String getXlinkType() { return xlinkType; } /** * Imposta il valore della proprietà xlinkType. * * @param value * allowed object is * {@link String } * */ public void setXlinkType(String value) { this.xlinkType = value; } /** * Recupera il valore della proprietà xlinkRole. * * @return * possible object is * {@link String } * */ public String getXlinkRole() { return xlinkRole; } /** * Imposta il valore della proprietà xlinkRole. * * @param value * allowed object is * {@link String } * */ public void setXlinkRole(String value) { this.xlinkRole = value; } /** * Recupera il valore della proprietà arcrole. * * @return * possible object is * {@link String } * */ public String getArcrole() { return arcrole; } /** * Imposta il valore della proprietà arcrole. * * @param value * allowed object is * {@link String } * */ public void setArcrole(String value) { this.arcrole = value; } /** * Recupera il valore della proprietà xlinkTitle. * * @return * possible object is * {@link String } * */ public String getXlinkTitle() { return xlinkTitle; } /** * Imposta il valore della proprietà xlinkTitle. * * @param value * allowed object is * {@link String } * */ public void setXlinkTitle(String value) { this.xlinkTitle = value; } /** * Recupera il valore della proprietà show. * * @return * possible object is * {@link String } * */ public String getShow() { return show; } /** * Imposta il valore della proprietà show. * * @param value * allowed object is * {@link String } * */ public void setShow(String value) { this.show = value; } /** * Recupera il valore della proprietà actuate. * * @return * possible object is * {@link String } * */ public String getActuate() { return actuate; } /** * Imposta il valore della proprietà actuate. * * @param value * allowed object is * {@link String } * */ public void setActuate(String value) { this.actuate = value; } }
mit
hanson-andrew/GruesomeSerpent
forge/mcp/src/minecraft/net/gruesomeserpent/RenderMagicMissileBolt.java
3094
package net.gruesomeserpent; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.Tessellator; import net.minecraft.client.renderer.entity.Render; import net.minecraft.entity.Entity; import net.minecraft.util.MathHelper; import net.minecraft.util.ResourceLocation; public class RenderMagicMissileBolt extends Render { private static final ResourceLocation magicMissileTextures = new ResourceLocation("gruesomeserpent:textures/items/MagicMissileScroll.png"); @Override public void doRender(Entity entity, double par2, double par4, double par6, float par8, float par9) { this.bindEntityTexture(entity); GL11.glPushMatrix(); GL11.glTranslatef((float)par2, (float)par4, (float)par6); GL11.glRotatef(entity.prevRotationYaw + (entity.rotationYaw - entity.prevRotationYaw) * par9 - 90.0F, 0.0F, 1.0F, 0.0F); GL11.glRotatef(entity.prevRotationPitch + (entity.rotationPitch - entity.prevRotationPitch) * par9, 0.0F, 0.0F, 1.0F); Tessellator tessellator = Tessellator.instance; byte b0 = 0; float f2 = 0.0F; float f3 = 0.5F; float f4 = (float)(0 + b0 * 10) / 32.0F; float f5 = (float)(5 + b0 * 10) / 32.0F; float f6 = 0.0F; float f7 = 0.15625F; float f8 = (float)(5 + b0 * 10) / 32.0F; float f9 = (float)(10 + b0 * 10) / 32.0F; float f10 = 0.05625F; GL11.glEnable(GL12.GL_RESCALE_NORMAL); GL11.glRotatef(45.0F, 1.0F, 0.0F, 0.0F); GL11.glScalef(f10, f10, f10); GL11.glTranslatef(-4.0F, 0.0F, 0.0F); GL11.glNormal3f(f10, 0.0F, 0.0F); tessellator.startDrawingQuads(); tessellator.addVertexWithUV(-7.0D, -2.0D, -2.0D, (double)f6, (double)f8); tessellator.addVertexWithUV(-7.0D, -2.0D, 2.0D, (double)f7, (double)f8); tessellator.addVertexWithUV(-7.0D, 2.0D, 2.0D, (double)f7, (double)f9); tessellator.addVertexWithUV(-7.0D, 2.0D, -2.0D, (double)f6, (double)f9); tessellator.draw(); GL11.glNormal3f(-f10, 0.0F, 0.0F); tessellator.startDrawingQuads(); tessellator.addVertexWithUV(-7.0D, 2.0D, -2.0D, (double)f6, (double)f8); tessellator.addVertexWithUV(-7.0D, 2.0D, 2.0D, (double)f7, (double)f8); tessellator.addVertexWithUV(-7.0D, -2.0D, 2.0D, (double)f7, (double)f9); tessellator.addVertexWithUV(-7.0D, -2.0D, -2.0D, (double)f6, (double)f9); tessellator.draw(); for (int i = 0; i < 4; ++i) { GL11.glRotatef(90.0F, 1.0F, 0.0F, 0.0F); GL11.glNormal3f(0.0F, 0.0F, f10); tessellator.startDrawingQuads(); tessellator.addVertexWithUV(-8.0D, -2.0D, 0.0D, (double)f2, (double)f4); tessellator.addVertexWithUV(8.0D, -2.0D, 0.0D, (double)f3, (double)f4); tessellator.addVertexWithUV(8.0D, 2.0D, 0.0D, (double)f3, (double)f5); tessellator.addVertexWithUV(-8.0D, 2.0D, 0.0D, (double)f2, (double)f5); tessellator.draw(); } GL11.glDisable(GL12.GL_RESCALE_NORMAL); GL11.glPopMatrix(); } @Override protected ResourceLocation getEntityTexture(Entity entity) { return magicMissileTextures; } }
mit
aawuley/evolutionary-computation
ec/island/connect/Client.java
6746
/******************************************************************************* * Copyright (c) 2014, 2015 * Anthony Awuley - Brock University Computer Science Department * All rights reserved. This program and the accompanying materials * are made available under the Academic Free License version 3.0 * which accompanies this distribution, and is available at * https://aawuley@bitbucket.org/aawuley/evolvex.git * * Contributors: * ECJ MersenneTwister & MersenneTwisterFast (https://cs.gmu.edu/~eclab/projects/ecj) * voidException Tabu Search (http://voidException.weebly.com) * Lucia Blondel Simulated Anealing * * * *******************************************************************************/ package ec.island.connect; //File Name GreetingClient.java import ec.island.Packet; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.InetAddress; import java.net.Socket; import java.util.ArrayList; public class Client { private static Socket socket; private String host; private int port; private int mailBoxCapacity; private int numberOfMigrants; private int numberOfConnections; private int updateFrequecy; private int startGeneration; private ArrayList<Integer> connectingDemmes; private String clientName; private Packet txPacket; private Packet rxPacket; private Client connectedClient; public int priorityKey = 0; //tx or recieve public Client(String h, int p) { this.host = h; this.port = p; } public void startClient() { try { InetAddress address = InetAddress.getByName(this.host); socket = new Socket(address, this.port); System.out.println("Client Started and listening on "+this.getClientName() + ":"+ this.port ); switch(priorityKey) { case 1: //client-server communication /** * SENDing population to another client to SERVER */ System.out.println("Client sending packet population of "+this.getTxPacket().getPopulation().size() + " to "+ this.getTxPacket().getDestinationPort()); ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream()); /** Get population to be dispatched */ oos.writeObject(this.getTxPacket()); break; case 2: //client-server-client communication /** * RECEIVing population from another client via SERVER */ ObjectInputStream ois = new ObjectInputStream(socket.getInputStream()); Packet rxPop = (Packet) ois.readObject(); this.setRxPacket(rxPop); //set new population /** dispatcher pop to mailbox */ System.out.println("Packet received from " + this.getRxPacket().getOrginationPort()); break; default: System.out.println("Client operation not set..."); break; } //socket.close(); } catch (Exception exception) { exception.printStackTrace(); } finally { //Closing the socket try { //socket.close(); } catch(Exception e) { e.printStackTrace(); } } } /** * @return the host */ public String getHost() { return host; } /** * @param host the host to set */ public void setHost(String host) { this.host = host; } /** * @return the port */ public int getPort() { return port; } /** * @param port the port to set */ public void setPort(int port) { this.port = port; } /** * @return the clientName */ public String getClientName() { return clientName; } /** * @param clientName the clientName to set */ public void setClientName(String clientName) { this.clientName = clientName; } /** * @return the txPacket */ public Packet getTxPacket() { return txPacket; } /** * @param txPacket the txPacket to set */ public void setTxPacket(Packet txPacket) { this.txPacket = txPacket; } /** * @return the rxPacket */ public Packet getRxPacket() { return rxPacket; } /** * @param rxPacket the rxPacket to set */ public void setRxPacket(Packet rxPacket) { this.rxPacket = rxPacket; } /** * @return the mailBoxCapacity */ public int getMailBoxCapacity() { return mailBoxCapacity; } /** * @param mailBoxCapacity the mailBoxCapacity to set */ public void setMailBoxCapacity(int mailBoxCapacity) { this.mailBoxCapacity = mailBoxCapacity; } /** * @return the numberOfMigrants */ public int getNumberOfMigrants() { return numberOfMigrants; } /** * @param numberOfMigrants the numberOfMigrants to set */ public void setNumberOfMigrants(int numberOfMigrants) { this.numberOfMigrants = numberOfMigrants; } /** * @return the numberOfConnections */ public int getNumberOfConnections() { return numberOfConnections; } /** * @param numberOfConnections the numberOfConnections to set */ public void setNumberOfConnections(int numberOfConnections) { this.numberOfConnections = numberOfConnections; } /** * @return the updateFrequecy */ public int getUpdateFrequecy() { return updateFrequecy; } /** * @param updateFrequecy the updateFrequecy to set */ public void setUpdateFrequecy(int updateFrequecy) { this.updateFrequecy = updateFrequecy; } /** * @return the startGeneration */ public int getStartGeneration() { return startGeneration; } /** * @param startGeneration the startGeneration to set */ public void setStartGeneration(int startGeneration) { this.startGeneration = startGeneration; } /** * @return the connectingDemmes */ public ArrayList<Integer> getConnectingDemmes() { return connectingDemmes; } /** * @param connectingDemmes the connectingDemmes to set */ public void setConnectingDemmes(ArrayList<Integer> connectingDemmes) { this.connectingDemmes = connectingDemmes; } /** * @return the connectedClient */ public Client getConnectedClient() { return connectedClient; } /** * @param connectedClient the connectedClient to set */ public void setConnectedClient(Client connectedClient) { this.connectedClient = connectedClient; } }
mit
nico01f/z-pec
ZimbraSoap/src/wsdl-test/generated/zcsclient/mail/testGetWatchersResponse.java
1810
package generated.zcsclient.mail; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for getWatchersResponse complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="getWatchersResponse"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="watcher" type="{urn:zimbraMail}watcherInfo" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "getWatchersResponse", propOrder = { "watcher" }) public class testGetWatchersResponse { protected List<testWatcherInfo> watcher; /** * Gets the value of the watcher property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the watcher property. * * <p> * For example, to add a new item, do as follows: * <pre> * getWatcher().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link testWatcherInfo } * * */ public List<testWatcherInfo> getWatcher() { if (watcher == null) { watcher = new ArrayList<testWatcherInfo>(); } return this.watcher; } }
mit
chuwuwang/ReadingNotes
Android/android-exercise/MainExercise/src/main/java/paint/ShadowLayerView.java
1421
package paint; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.View; /** * 在之后的绘制内容下面加一层阴影。 */ public class ShadowLayerView extends View { private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); public ShadowLayerView(Context context) { super(context); } public ShadowLayerView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); } public ShadowLayerView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } { // 使用 Paint.setShadowLayer() 设置阴影 paint.setShadowLayer(10, 0, 0, Color.RED); // 方法的参数里, radius 是阴影的模糊范围; dx dy 是阴影的偏移量; shadowColor 是阴影的颜色。 // 如果要清除阴影层,使用 clearShadowLayer() 。 // 在硬件加速开启的情况下, setShadowLayer() 只支持文字的绘制,文字之外的绘制必须关闭硬件加速才能正常绘制阴影。 } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); paint.setTextSize(120); canvas.drawText("Hello HenCoder", 50, 200, paint); } }
mit
Andrew0000/DependencyProvider
Sample/src/androidTest/java/crocodile8008/dependencyprovider/ApplicationTest.java
363
package crocodile8008.dependencyprovider; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
mit
dharmik/AndroidNative---ListView
listFromCustom/src/com/mobmaxime/listfromcustom/MainActivity.java
2571
package com.mobmaxime.listfromcustom; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import com.mobmaxime.listfromcustom.R.id; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.util.Log; import android.widget.Button; import android.widget.ListView; public class MainActivity extends Activity { protected static final int BUTTON_POSITIVE = 0; Button singleBtn, doubleBtn, multipleBtn; Context appContext; private ListView listView; final Context context = this; List<createRow> rowItems; LazyAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listView = (ListView) findViewById(R.id.list_item); rowItems = new ArrayList<createRow>(); try { BufferedReader bReader = new BufferedReader(new InputStreamReader( getAssets().open("NewData.json"))); String line = bReader.readLine(); Log.e("line---->", line.toString()); try { JSONObject listLength = new JSONObject(line); JSONArray data = listLength.getJSONArray("List"); Log.d("Hi---->", data.length() + ""); for (int i = 0; i < data.length(); i++) { String Name = null, screenname = null, ProfileBanner = null, description = null; JSONObject content = data.getJSONObject(i); JSONArray subdata = content.getJSONArray("recent"); Log.d("subdata---->", subdata.length() + ""); Name = content.getString("Name"); screenname = content.getString("screenname"); ProfileBanner = content.getString("ProfileBanner"); description = content.getString("description"); Log.d("name", Name); Log.d("screenname", screenname); Log.d("profileBanner", ProfileBanner); Log.d("description", description); rowItems.add(new createRow(Name, screenname, ProfileBanner, description)); } adapter = new LazyAdapter(getApplicationContext(), rowItems); listView.setAdapter(adapter); //adapter.notifyDataSetChanged(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } catch (IOException e) { // TODO Auto-generated catch block Log.e("Error", e.getMessage()); e.printStackTrace(); } } private ListView findViewById(Class<id> class1) { // TODO Auto-generated method stub return null; } }
mit
anba/es6draft
src/main/java/com/github/anba/es6draft/interpreter/InterpretedScriptBody.java
6610
/** * Copyright (c) André Bargull * Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms. * * <https://github.com/anba/es6draft> */ package com.github.anba.es6draft.interpreter; import static com.github.anba.es6draft.interpreter.DeclarationBindingInstantiation.EvalDeclarationInstantiation; import static com.github.anba.es6draft.interpreter.DeclarationBindingInstantiation.GlobalDeclarationInstantiation; import static com.github.anba.es6draft.runtime.ExecutionContext.newEvalExecutionContext; import static com.github.anba.es6draft.runtime.ExecutionContext.newScriptExecutionContext; import static com.github.anba.es6draft.runtime.LexicalEnvironment.newDeclarativeEnvironment; import com.github.anba.es6draft.Script; import com.github.anba.es6draft.runtime.DeclarativeEnvironmentRecord; import com.github.anba.es6draft.runtime.ExecutionContext; import com.github.anba.es6draft.runtime.GlobalEnvironmentRecord; import com.github.anba.es6draft.runtime.LexicalEnvironment; import com.github.anba.es6draft.runtime.Realm; import com.github.anba.es6draft.runtime.internal.DebugInfo; import com.github.anba.es6draft.runtime.internal.RuntimeInfo; import com.github.anba.es6draft.runtime.internal.ScriptException; /** * */ final class InterpretedScriptBody implements RuntimeInfo.ScriptBody { private static final String INTERPRETER_SCRIPTBODY = InterpretedScriptBody.class.getName(); private final com.github.anba.es6draft.ast.Script parsedScript; InterpretedScriptBody(com.github.anba.es6draft.ast.Script parsedScript) { this.parsedScript = parsedScript; } @Override public Object evaluate(ExecutionContext cx, Script script) { assert script.getScriptBody() == this; Interpreter interpreter = new Interpreter(parsedScript); try { if (parsedScript.isScripting()) { return scriptingEvaluation(cx, interpreter); } if (parsedScript.isEvalScript()) { return evalScriptEvaluation(cx, script, interpreter); } return scriptEvaluation(cx, script, interpreter); } catch (ScriptException e) { throw interpreterException(interpreter, e); } } private ScriptException interpreterException(Interpreter interpreter, ScriptException e) { StackTraceElement[] elements = e.getStackTrace(); int entry = -1; for (int i = 0; i < elements.length; ++i) { StackTraceElement element = elements[i]; if (INTERPRETER_SCRIPTBODY.equals(element.getClassName()) && "evaluate".equals(element.getMethodName())) { entry = i; break; } } // Replace entry frame with script file information. if (entry != -1) { StackTraceElement[] newElements = elements.clone(); newElements[entry] = new StackTraceElement("#Interpreter", "~interpreter", parsedScript.getSource().getName(), interpreter.getCurrentLine()); e.setStackTrace(newElements); } return e; } /** * 15.1.7 Runtime Semantics: ScriptEvaluation * * @param cx * the execution context * @param script * the script object * @param interpreter * the interpreter * @return the script evaluation result */ private Object scriptEvaluation(ExecutionContext cx, Script script, Interpreter interpreter) { Realm realm = cx.getRealm(); /* step 1 (not applicable) */ /* step 2 */ LexicalEnvironment<GlobalEnvironmentRecord> globalEnv = realm.getGlobalEnv(); /* steps 3-7 */ ExecutionContext scriptCxt = newScriptExecutionContext(realm, script); /* steps 8-9 */ ExecutionContext oldScriptContext = realm.getWorld().getScriptContext(); try { realm.getWorld().setScriptContext(scriptCxt); /* step 10 */ GlobalDeclarationInstantiation(scriptCxt, parsedScript, globalEnv); /* steps 11-12 */ Object result = parsedScript.accept(interpreter, scriptCxt); /* step 16 */ return result; } finally { /* steps 13-15 */ realm.getWorld().setScriptContext(oldScriptContext); } } /** * 18.2.1.1 Runtime Semantics: PerformEval( x, evalRealm, strictCaller, direct) * * @param cx * the execution context * @param script * the script object * @param interpreter * the interpreter * @return the script evaluation result */ private Object evalScriptEvaluation(ExecutionContext cx, Script script, Interpreter interpreter) { // TODO: Skip allocating lex-env if not needed /* steps 1-5 (not applicable) */ /* steps 6-7 */ boolean strictEval = parsedScript.isStrict(); /* step 8 (omitted) */ /* steps 9-10 */ LexicalEnvironment<DeclarativeEnvironmentRecord> lexEnv; LexicalEnvironment<?> varEnv; if (parsedScript.isDirectEval()) { /* step 9 */ lexEnv = newDeclarativeEnvironment(cx.getLexicalEnvironment()); varEnv = cx.getVariableEnvironment(); } else { Realm evalRealm = cx.getRealm(); /* step 10 */ lexEnv = newDeclarativeEnvironment(evalRealm.getGlobalEnv()); varEnv = evalRealm.getGlobalEnv(); } /* step 11 */ if (strictEval) { varEnv = lexEnv; } /* steps 12-19 */ ExecutionContext evalCxt = newEvalExecutionContext(cx, script, varEnv, lexEnv); /* step 20 */ EvalDeclarationInstantiation(evalCxt, parsedScript, varEnv, lexEnv); /* steps 21-25 */ return parsedScript.accept(interpreter, evalCxt); } private Object scriptingEvaluation(ExecutionContext cx, Interpreter interpreter) { // NB: Don't need to create a new execution context here, cf. ScriptEngineImpl. // TODO: Skip allocating lex-env if not needed LexicalEnvironment<?> varEnv = cx.getVariableEnvironment(); LexicalEnvironment<DeclarativeEnvironmentRecord> lexEnv = newDeclarativeEnvironment(cx.getLexicalEnvironment()); cx.setLexicalEnvironment(lexEnv); EvalDeclarationInstantiation(cx, parsedScript, varEnv, lexEnv); return parsedScript.accept(interpreter, cx); } @Override public DebugInfo debugInfo() { return null; } }
mit
polytomous/TerrariaClone
src/main/java/TerrariaClone/StartingSkycolorProvider.java
104
package TerrariaClone; public interface StartingSkycolorProvider { int[] getStartingSkycolors(); }
mit
LiangMaYong/android-base
base/src/main/java/com/liangmayong/base/support/utils/ClipboardUtils.java
3923
package com.liangmayong.base.support.utils; import android.content.ClipData; import android.content.ClipboardManager; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Build; /** * Created by LiangMaYong on 2016/11/9. */ public final class ClipboardUtils { private ClipboardUtils() { throw new UnsupportedOperationException("u can't instantiate me..."); } /** * copyText * * @param context context * @param text text */ public static void copyText(Context context, CharSequence text) { if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) { ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); clipboard.setPrimaryClip(ClipData.newPlainText("text", text)); } else { android.text.ClipboardManager c = (android.text.ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); c.setText(text); } } /** * getText * * @param context context * @return chars */ public static CharSequence getText(Context context) { if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) { ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); ClipData clip = null; clip = clipboard.getPrimaryClip(); if (clip != null && clip.getItemCount() > 0) { return clip.getItemAt(0).coerceToText(context); } } else { android.text.ClipboardManager c = (android.text.ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); return c.getText(); } return null; } /** * copyUri * * @param context context * @param uri uri */ public static void copyUri(Context context, Uri uri) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); clipboard.setPrimaryClip(ClipData.newUri(context.getContentResolver(), "uri", uri)); } } /** * getUri * * @param context context * @return uri */ public static Uri getUri(Context context) { ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); ClipData clip = null; if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) { clip = clipboard.getPrimaryClip(); if (clip != null && clip.getItemCount() > 0) { return clip.getItemAt(0).getUri(); } } return null; } /** * copyIntent * * @param context context * @param intent intent */ public static void copyIntent(Context context, Intent intent) { ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { clipboard.setPrimaryClip(ClipData.newIntent("intent", intent)); } } /** * getIntent * * @param context context * @return intent */ public static Intent getIntent(Context context) { if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) { ClipboardManager clipboard = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE); ClipData clip = null; clip = clipboard.getPrimaryClip(); if (clip != null && clip.getItemCount() > 0) { return clip.getItemAt(0).getIntent(); } } return null; } }
mit
applecool/Revision-Java
src/org/shellzero/exp/Demo.java
1892
package org.shellzero.exp; import java.util.ArrayList; public class Demo { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Player player1 = new Player("Gyu", 01); System.out.println(player1.getHandleName()); System.out.println(player1.getWeapon().getName()); System.out.println(player1.getWeapon().getHitPoints()); Weapon Axe = new Weapon("Greyskull Axe", 100, 120); player1.setWeapon(Axe); System.out.println(player1.getWeapon().getName()); InventoryItem potion = new InventoryItem(ItemType.POTION, "Healing Potion"); player1.addInventoryItem(potion); player1.addInventoryItem(new InventoryItem(ItemType.ARMOUR, "Bullet Proof Armor")); player1.addInventoryItem(new InventoryItem(ItemType.RING, "Fire ring")); player1.addInventoryItem(new InventoryItem(ItemType.RING, "Water ring")); player1.addInventoryItem(new InventoryItem(ItemType.RING, "Magic ring")); player1.addInventoryItem(new InventoryItem(ItemType.POTION, "Rage Potion")); boolean wasDeleted = player1.dropInventoryItem(potion); System.out.println(wasDeleted); ArrayList<InventoryItem> allItems = player1.getInventoryitems(); int count = 0; for(InventoryItem item: allItems){ System.out.println(item.getName()); count++; } System.out.println("No of items in the inventory are : "+count); Enemy enemy = new Enemy(10, 5); System.out.println("Hitpoints: " +enemy.getHitPonts() + " Lives: " +enemy.getLives()); enemy.takeDamage(4); Soldier soldier = new Soldier(30, 3); System.out.println("Hitpoints: " +soldier.getHitPonts() + " Lives: " +soldier.getLives()); soldier.takeDamage(12); SuperSoldier supersoldier = new SuperSoldier(100, 10); System.out.println("Hitpoints: " +supersoldier.getHitPonts() + " Lives: " +supersoldier.getLives()); supersoldier.takeDamage(8); } }
mit
TheChaiClub/algorithms
Strings/StringBuffer.java
741
import java.util.Arrays; public class StringBuffer { private char [] bufferArray; private int size = 0; public StringBuffer(int paramInt){ bufferArray = new char[paramInt]; } public void append(String s){ ensureCapacity(size+s.length()); System.arraycopy(s, 0, bufferArray, size, s.length()); size += s.length(); } private void ensureCapacity(int paramInt) { if(paramInt <= bufferArray.length) return; grow(paramInt); } private void grow(int paramInt) { int newSize = paramInt << 1; bufferArray = Arrays.copyOf(bufferArray, newSize); } public String toString(){ return String.valueOf(bufferArray); } public void append(char char1) { ensureCapacity(size+1); bufferArray[size++] = char1; } }
mit
config4star/config4j
demos/extended-schema-validator/SchemaTypeHex.java
4583
//----------------------------------------------------------------------- // Copyright 2011 Ciaran McHale. // // 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 org.config4j.Configuration; import org.config4j.ConfigurationException; import org.config4j.SchemaType; import org.config4j.SchemaValidator; public class SchemaTypeHex extends SchemaType { public SchemaTypeHex() { super("hex", Configuration.CFG_STRING); } public void checkRule( SchemaValidator sv, Configuration cfg, String typeName, String[] typeArgs, String rule) throws ConfigurationException { int len; int maxDigits; len = typeArgs.length; if (len == 0) { return; } else if (len > 1) { throw new ConfigurationException("schema error: the '" + typeName + "' type should take either no arguments or 1 " + "argument (denoting max-digits) " + "in rule '" + rule + "'"); } try { maxDigits = cfg.stringToInt("", "", typeArgs[0]); } catch(ConfigurationException ex) { throw new ConfigurationException("schema error: non-integer value " + "for the 'max-digits' argument in rule '" + rule + "'"); } if (maxDigits < 1) { throw new ConfigurationException("schema error: the max-digits " + "argument must be 1 or greater in rule '" + rule + "'"); } } public boolean isA( SchemaValidator sv, Configuration cfg, String value, String typeName, String[] typeArgs, int indentLevel, StringBuffer errSuffix) throws ConfigurationException { int maxDigits; if (!isHex(value)) { errSuffix.append("the value is not a hexadecimal number"); return false; } if (typeArgs.length == 1) { //-------- // Check if there are too many hex digits in the value //-------- maxDigits = cfg.stringToInt("", "", typeArgs[0]); if (value.length() > maxDigits) { errSuffix.append("the value must not contain more than " + maxDigits + " digits"); return false; } } return true; } public static int lookupHex( Configuration cfg, String scope, String localName) throws ConfigurationException { String str; str = cfg.lookupString(scope, localName); return stringToHex(cfg, scope, localName, str); } public static int lookupHex( Configuration cfg, String scope, String localName, int defaultVal) throws ConfigurationException { String str; if (cfg.type(scope, localName) == Configuration.CFG_NO_VALUE) { return defaultVal; } str = cfg.lookupString(scope, localName); return stringToHex(cfg, scope, localName, str); } public static int stringToHex( Configuration cfg, String scope, String localName, String str) throws ConfigurationException { return stringToHex(cfg, scope, localName, str, "hex"); } public static int stringToHex( Configuration cfg, String scope, String localName, String str, String typeName) throws ConfigurationException { String fullyScopedName; try { return (int)Long.parseLong(str, 16); } catch(NumberFormatException ex) { fullyScopedName = cfg.mergeNames(scope, localName); throw new ConfigurationException(cfg.fileName() + ": bad " + typeName + " value ('" + str + "') specified for '" + fullyScopedName); } } public static boolean isHex(String str) { try { Long.parseLong(str, 16); return true; } catch(NumberFormatException ex) { return false; } } }
mit
prototypev/android-side-projects
PermissiveFov/src/prototypev/PermissiveFov/LevelGeneration/Generators/RoomGenerator.java
13072
package prototypev.PermissiveFov.LevelGeneration.Generators; import prototypev.PermissiveFov.LevelGeneration.DirectionType; import prototypev.PermissiveFov.LevelGeneration.Entities.Cell; import prototypev.PermissiveFov.LevelGeneration.Entities.Room; import prototypev.PermissiveFov.LevelGeneration.SideType; import prototypev.PermissiveFov.Randomizer; import java.util.List; public class RoomGenerator { private final int maxHeight; private final int maxWidth; private final int minHeight; private final int minWidth; /** * Creates a new RoomGenerator with the specified constraints. * * @param minWidth The minimum width of each room to create. * @param maxWidth The maximum width of each room to create. * @param minHeight The minimum height of each room to create. * @param maxHeight The maximum height of each room to create. */ public RoomGenerator(int minWidth, int maxWidth, int minHeight, int maxHeight) { this.minWidth = minWidth; this.maxWidth = maxWidth; this.minHeight = minHeight; this.maxHeight = maxHeight; } /** * @param container The containing room. * @param room The room to attempt to be placed in the containing room. * @param x The horizontal component of the location to place the room. * @param y The vertical component of the location to place the room. * @return The placement score. The score is inversely proportional to the chance to place the room. */ public static int getRoomPlacementScore(Room container, Room room, int x, int y) { // Check if the room at the given point will fit inside the bounds of the container if (container.getLeft() > x || container.getTop() > y || container.getLeft() + container.width < x + room.width || container.getTop() + container.height < y + room.height) { // Room does not fit inside container return Integer.MAX_VALUE; } int roomPlacementScore = 0; for (int j = 0; j < room.height; j++) { for (int i = 0; i < room.width; i++) { Cell cell = room.getCellAt(room.getLeft() + i, room.getTop() + j); // Translate the room's cell's location to its location in the container int translatedX = cell.getX() - room.getLeft() + x; int translatedY = cell.getY() - room.getTop() + y; // Add 1 point for each adjacent corridor to the cell for (DirectionType direction : DirectionType.values()) { if (container.isAdjacentCellCorridor(translatedX, translatedY, direction)) { roomPlacementScore++; } } // Add 3 points if the cell overlaps an existing corridor if (container.getCellAt(translatedX, translatedY).isCorridor()) { roomPlacementScore += 3; } // Add 100 points if the cell overlaps any existing room cells List<Room> existingRooms = container.getRooms(); for (Room existingRoom : existingRooms) { if (!existingRoom.isOutOfBounds(translatedX, translatedY)) { roomPlacementScore += 100; } } } } return roomPlacementScore; } /** * Creates rooms of random dimensions bounded by the input parameters in the specified containing room. * * @param container The containing room. * @param numRooms The number of rooms to create. */ public void createRooms(Room container, int numRooms) { for (int roomCounter = 0; roomCounter < numRooms; roomCounter++) { int width = Randomizer.getInstance().nextInt(minWidth, maxWidth); int height = Randomizer.getInstance().nextInt(minHeight, maxHeight); Room room = Room.createWalledInRoom(0, 0, width, height); int bestScore = Integer.MAX_VALUE; int bestX = -1; int bestY = -1; // Ensure that rooms are always created adjacent to a corridor List<Cell> corridorCells = container.getCorridorCells(); if (corridorCells.isEmpty()) { throw new IllegalStateException("Cannot place rooms if map has no corridors!"); } for (Cell cell : corridorCells) { int currentRoomPlacementScore = getRoomPlacementScore(container, room, cell.getX(), cell.getY()); if (currentRoomPlacementScore < bestScore) { bestScore = currentRoomPlacementScore; bestX = cell.getX(); bestY = cell.getY(); } } if (bestX < 0 || bestY < 0) { throw new IllegalStateException("Room placement point should have been initialized!"); } // Create room at best room placement cell container.addRoom(room, bestX, bestY); } } /** * Creates doors in the specified room. * * @param room The room. */ static void createDoors(Room room) { List<Room> rooms = room.getRooms(); for (Room innerRoom : rooms) { int left = innerRoom.getLeft(); int top = innerRoom.getTop(); Iterable<Cell> cells = innerRoom.getCells(); for (Cell cell : cells) { int x = cell.getX(); int y = cell.getY(); // Check if we are on the boundaries of our room and if there is a corridor in that direction if (y == top && room.isAdjacentCellCorridor(cell, DirectionType.NORTH)) { room.setCellSide(cell, DirectionType.NORTH, SideType.DOOR); } if (x == left && room.isAdjacentCellCorridor(cell, DirectionType.WEST)) { room.setCellSide(cell, DirectionType.WEST, SideType.DOOR); } if (y == top + innerRoom.height - 1 && room.isAdjacentCellCorridor(cell, DirectionType.SOUTH)) { room.setCellSide(cell, DirectionType.SOUTH, SideType.DOOR); } if (x == left + innerRoom.width - 1 && room.isAdjacentCellCorridor(cell, DirectionType.EAST)) { room.setCellSide(cell, DirectionType.EAST, SideType.DOOR); } // Discard any redundant doors that surround this cell's location removeRedundantDoors(room, cell); } } } /** * Removes redundant doors around the specified cell. * * @param room The room containing the cell. * @param cell The cell. */ private static void removeRedundantDoors(Room room, Cell cell) { Cell cellNorth = room.getAdjacentCell(cell, DirectionType.NORTH); Cell cellWest = room.getAdjacentCell(cell, DirectionType.WEST); Cell cellSouth = room.getAdjacentCell(cell, DirectionType.SOUTH); Cell cellEast = room.getAdjacentCell(cell, DirectionType.EAST); // Remove redundant north side doors if (cell.getSide(DirectionType.NORTH) == SideType.DOOR) { if (cellNorth == null) { throw new IllegalStateException("The cell to the north cannot possibly be null if the north side of the current cell is a door!"); } // If there is a cell to the west of the reference cell, // check if that cell has a door to the north if (cellWest != null && cellWest.getSide(DirectionType.NORTH) == SideType.DOOR) { // Check if cell to the north of the current cell is a corridor to the west if (room.isAdjacentCellCorridor(cellNorth, DirectionType.WEST)) { // Remove redundant door in west cell room.setCellSide(cellWest, DirectionType.NORTH, SideType.WALL); } } // If there is a cell to the east of the reference cell, // check if that cell has a door to the north if (cellEast != null && cellEast.getSide(DirectionType.NORTH) == SideType.DOOR) { // Check if cell to the north of the current cell is a corridor to the east if (room.isAdjacentCellCorridor(cellNorth, DirectionType.EAST)) { // Remove redundant door in east cell room.setCellSide(cellEast, DirectionType.NORTH, SideType.WALL); } } } // Remove redundant south side doors if (cell.getSide(DirectionType.SOUTH) == SideType.DOOR) { if (cellSouth == null) { throw new IllegalStateException("The cell to the south cannot possibly be null if the south side of the current cell is a door!"); } // If there is a cell to the west of the reference cell, // check if that cell has a door to the south if (cellWest != null && cellWest.getSide(DirectionType.SOUTH) == SideType.DOOR) { // Check if cell to the south of the current cell is a corridor to the west if (room.isAdjacentCellCorridor(cellSouth, DirectionType.WEST)) { // Remove redundant door in west cell room.setCellSide(cellWest, DirectionType.SOUTH, SideType.WALL); } } // If there is a cell to the east of the reference cell, check if that // cell has a door to the south if (cellEast != null && cellEast.getSide(DirectionType.SOUTH) == SideType.DOOR) { // Check if cell to the south of the current cell is a corridor to the east if (room.isAdjacentCellCorridor(cellSouth, DirectionType.EAST)) { // Remove redundant door in east cell room.setCellSide(cellEast, DirectionType.SOUTH, SideType.WALL); } } } // Remove redundant west side doors if (cell.getSide(DirectionType.WEST) == SideType.DOOR) { if (cellWest == null) { throw new IllegalStateException("The cell to the west cannot possibly be null if the west side of the current cell is a door!"); } // If there is a cell to the north of the reference cell, // check if that cell has a door to the west if (cellNorth != null && cellNorth.getSide(DirectionType.WEST) == SideType.DOOR) { // Check if cell to the west of the current cell is a corridor to the north if (room.isAdjacentCellCorridor(cellWest, DirectionType.NORTH)) { // Remove redundant door in north cell room.setCellSide(cellNorth, DirectionType.WEST, SideType.WALL); } } // If there is a cell to the south of the reference cell, // check if that cell has a door to the west if (cellSouth != null && cellSouth.getSide(DirectionType.WEST) == SideType.DOOR) { // Check if cell to the west of the current cell is a corridor to the south if (room.isAdjacentCellCorridor(cellWest, DirectionType.SOUTH)) { // Remove redundant door in south cell room.setCellSide(cellSouth, DirectionType.WEST, SideType.WALL); } } } // Remove redundant east side doors if (cell.getSide(DirectionType.EAST) == SideType.DOOR) { if (cellEast == null) { throw new IllegalStateException("The cell to the east cannot possibly be null if the east side of the current cell is a door!"); } // If there is a cell to the north of the reference cell, // check if that cell has a door to the east if (cellNorth != null && cellNorth.getSide(DirectionType.EAST) == SideType.DOOR) { // Check if cell to the east of the current cell is a corridor to the north if (room.isAdjacentCellCorridor(cellEast, DirectionType.NORTH)) { // Remove redundant door in north cell room.setCellSide(cellNorth, DirectionType.EAST, SideType.WALL); } } // If there is a cell to the south of the reference cell, check if that // cell has a door to the east if (cellSouth != null && cellSouth.getSide(DirectionType.EAST) == SideType.DOOR) { // Check if cell to the east of the current cell is a corridor to the south if (room.isAdjacentCellCorridor(cellEast, DirectionType.SOUTH)) { // Remove redundant door in south cell room.setCellSide(cellSouth, DirectionType.EAST, SideType.WALL); } } } } }
mit
themaddoctor1/BattlefieldCommanderGame
src/engine/physics/Coordinate.java
1005
/* * Stores a coordinate/ */ package engine.physics; /** * * @author Christopher Hittner */ public class Coordinate { private double x, y, z; /** * * @param X The x-coord * @param Y The y-coord * @param Z The z-coord */ public Coordinate(double X, double Y, double Z){ x = X; y = Y; z = Z; } /** * Increments the coordinate by the value of the vector. * @param v */ public void addVector(Vector v){ x += v.getMagnitudeX(); y += v.getMagnitudeY(); z += v.getMagnitudeZ(); } public double X(){ return x; } public double Y(){ return y; } public double Z(){ return z; } public String toString(){ return "(" + x + "," + y + "," + z + ")"; } public static double relativeDistance(Coordinate a, Coordinate b){ return Math.sqrt(Math.pow(a.X() - b.X(), 2) + Math.pow(a.Y() - b.Y(), 2) + Math.pow(a.Z() - b.Z(), 2)); } }
mit
IPPETAD/adventure.datetime
adventure.testtime/src/ca/cmput301f13t03/adventure_datetime/model/StoryDBTest.java
5318
package ca.cmput301f13t03.adventure_datetime.model;/* * Copyright (c) 2013 Andrew Fontaine, James Finlay, Jesse Tucker, Jacob Viau, and * Evan DeGraff * * 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 android.graphics.BitmapFactory; import android.test.AndroidTestCase; import android.test.RenamingDelegatingContext; import ca.cmput301f13t03.adventure_datetime.R; import ca.cmput301f13t03.adventure_datetime.model.Interfaces.ILocalStorage; import junit.framework.Assert; import java.util.UUID; /** * @author Andrew Fontaine * @version 1.0 * @since 31/10/13 */ public class StoryDBTest extends AndroidTestCase { private ILocalStorage database; @Override public void setUp() throws Exception { super.setUp(); //TODO Implement RenamingDelegatingContext context = new RenamingDelegatingContext(getContext(), "test_"); database = new StoryDB(context); } public void testSetStoryFragment() throws Exception { UUID uuid = UUID.randomUUID(); Choice choice = new Choice("test", uuid); StoryFragment frag = new StoryFragment(uuid, "testing", choice); UUID fragUuid = frag.getFragmentID(); Assert.assertTrue("Error inserting fragment", database.setStoryFragment(frag)); StoryFragment frag2 = database.getStoryFragment(frag.getFragmentID()); Assert.assertEquals("Not equivalent fragment ids", frag.getFragmentID(), frag2.getFragmentID()); Assert.assertEquals("Not equivalent story ids", frag.getStoryID(), frag2.getStoryID()); Assert.assertEquals("Not equivalent UUIDs", fragUuid, frag.getFragmentID()); database.deleteStoryFragment(fragUuid); frag2 = database.getStoryFragment(fragUuid); Assert.assertNull("Frgament not null", frag2); } public void testSetStory() throws Exception { Story story = new Story("TestAuthor", "TestTitle", "TestSynop"); UUID uuid = story.getId(); story.setHeadFragmentId(UUID.randomUUID()); story.setThumbnail(BitmapFactory.decodeResource(getContext().getResources(), R.drawable.grumpy_cat)); Assert.assertTrue("Error inserting story", database.setStory(story)); Story story2 = database.getStory(story.getId()); Assert.assertEquals("Not equivalent story ids", story.getId(), story2.getId()); Assert.assertEquals("Not equivalent uuids", uuid, story.getId()); database.deleteStory(story.getId()); story2 = database.getStory(story.getId()); Assert.assertNull("Story not null", story2); } public void testSetStory_Thumbnail() throws Exception { Story story = new Story("TestAuthor", "TestTitle", "TestSynop"); UUID uuid = story.getId(); story.setHeadFragmentId(UUID.randomUUID()); story.setThumbnail(BitmapFactory.decodeResource(getContext().getResources(), R.drawable.grumpy_cat)); Assert.assertTrue("Error inserting story", database.setStory(story)); Story story2 = database.getStory(story.getId()); assertEquals(story.getThumbnail().getEncodedBitmap(), story2.getThumbnail().getEncodedBitmap()); Assert.assertEquals("Not equivalent story ids", story.getId(), story2.getId()); Assert.assertEquals("Not equivalent uuids", uuid, story.getId()); database.deleteStory(story.getId()); story2 = database.getStory(story.getId()); Assert.assertNull("Story not null", story2); } public void testSetBookmark() throws Exception { UUID sUuid, sFUuid; sUuid = UUID.randomUUID(); sFUuid = UUID.randomUUID(); Bookmark bookmark = new Bookmark(sUuid, sFUuid); Assert.assertTrue("Error inserting bookmark", database.setBookmark(bookmark)); Bookmark bookmark2 = database.getBookmark(sUuid); Assert.assertEquals("Not equivalent story ids", bookmark.getStoryID(), bookmark2.getStoryID()); Assert.assertEquals("Not equivalent uuids", sUuid, bookmark.getStoryID()); database.deleteBookmarkByStory(sUuid); bookmark2 = database.getBookmark(sUuid); Assert.assertNull("Bookmark not null", bookmark2); Assert.assertTrue("Error inserting bookmark", database.setBookmark(bookmark)); database.deleteStoryFragment(sFUuid); bookmark2 = database.getBookmark(sUuid); Assert.assertNull("Bookmark not null", bookmark2); } @Override public void tearDown() throws Exception { super.tearDown(); //TODO Implement } }
mit
jamf/HealthCheckUtility
src/main/java/com/jamfsoftware/jss/healthcheck/JSSSummaryPasteHandler.java
1673
package com.jamfsoftware.jss.healthcheck; /*- * #%L * HealthCheckUtility * %% * Copyright (C) 2015 - 2016 JAMF Software, LLC * %% * 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. * #L% */ import javax.swing.*; public class JSSSummaryPasteHandler extends JFrame{ public JSSSummaryPasteHandler(){ JOptionPane.showMessageDialog(null, "Unable to get the JSS Summary with the supplied account. \nYou have encountered a JSS oddity that causes some accounts to not be able to access the summary.\nPlease create a new account with at least read privileges, and try again.", "JSS Summary Error", JOptionPane.ERROR_MESSAGE); } }
mit