repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
bing-ads-sdk/BingAds-Java-SDK
proxies/com/microsoft/bingads/v12/adinsight/KeywordCategory.java
2193
package com.microsoft.bingads.v12.adinsight; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for KeywordCategory complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="KeywordCategory"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="Category" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="ConfidenceScore" type="{http://www.w3.org/2001/XMLSchema}double" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "KeywordCategory", propOrder = { "category", "confidenceScore" }) public class KeywordCategory { @XmlElement(name = "Category", nillable = true) protected String category; @XmlElement(name = "ConfidenceScore") protected Double confidenceScore; /** * Gets the value of the category property. * * @return * possible object is * {@link String } * */ public String getCategory() { return category; } /** * Sets the value of the category property. * * @param value * allowed object is * {@link String } * */ public void setCategory(String value) { this.category = value; } /** * Gets the value of the confidenceScore property. * * @return * possible object is * {@link Double } * */ public Double getConfidenceScore() { return confidenceScore; } /** * Sets the value of the confidenceScore property. * * @param value * allowed object is * {@link Double } * */ public void setConfidenceScore(Double value) { this.confidenceScore = value; } }
mit
Ben880/GNGH-2
src/gui/main/TabHolder.java
842
package gui.main; /* // Author: Benjamin Wilcox // Project GNGH */ import java.awt.Dimension; import javax.swing.JTabbedPane; public class TabHolder extends JTabbedPane { private WorldTab world = new WorldTab(); private JobTab jobs = new JobTab(); private ResourcesTab resources = new ResourcesTab(); private ResearchTab research = new ResearchTab(); private DebugTab debug = new DebugTab(); //holds all the tabs public TabHolder() { new UpdateGUI().passTabHolder(this); setPreferredSize(new Dimension(390, 540)); addTab("World", world); addTab("Jobs", jobs); addTab("Resources", resources); addTab("Research", research); addTab("Debug", debug); } public void setSelected(int i) { setSelectedIndex(i); } }
mit
sebastianlaag/caketastic
business/src/main/java/de/laag/service/LoginService.java
798
package de.laag.service; import org.mindrot.jbcrypt.BCrypt; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import de.laag.entities.User; import de.laag.repositories.UserRepository; @Service public class LoginService { private UserRepository userRepository; @Autowired public LoginService(UserRepository userRepository) { this.userRepository = userRepository; } public User login(String login, String passwordPlain) { final User user = userRepository.findByLogin(login); final boolean pwMatches = BCrypt.checkpw(passwordPlain, user.getPasswordHash()); if (!pwMatches) { throw new IllegalStateException("Incorrect password."); } return user; } }
mit
tomcz/spring-conversations
src/main/java/example/spring/oktabs/restful/RestfulFormController.java
3744
package example.spring.oktabs.restful; import example.Conversation; import example.ConversationRepository; import example.DomainObject; import example.DomainObjectRepository; import example.spring.PathBuilder; import example.spring.success.SuccessController; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.propertyeditors.StringTrimmerEditor; import org.springframework.stereotype.Controller; import org.springframework.validation.DataBinder; import org.springframework.web.bind.ServletRequestDataBinder; import org.springframework.web.bind.ServletRequestParameterPropertyValues; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.context.request.WebRequest; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.View; import org.springframework.web.servlet.view.RedirectView; import javax.servlet.ServletRequest; import static example.spring.PathBuilder.pathTo; @Controller @RequestMapping("/form/{id}") public class RestfulFormController { private final Logger log = LoggerFactory.getLogger(getClass()); private final ConversationRepository conversationRepository; private final DomainObjectRepository domainRepository; @Autowired public RestfulFormController(ConversationRepository conversationRepository, DomainObjectRepository domainRepository) { this.conversationRepository = conversationRepository; this.domainRepository = domainRepository; } @RequestMapping(method = RequestMethod.GET) public ModelAndView display(@PathVariable String id) { Conversation conversation = conversationRepository.getOrCreate(id); log.info("Displaying " + conversation); ModelAndView mv = new ModelAndView("form"); mv.addObject("title", "OK TABS (restful)"); mv.addObject("formAction", pathToSelf(conversation).POST().build()); mv.addAllObjects(conversation.createModel("conversation")); return mv; } @RequestMapping(method = RequestMethod.POST) public View process(@PathVariable String id, WebRequest request) { Conversation conversation = conversationRepository.getOrCreate(id); update(conversation, request); if (conversation.isCancelled()) { log.info("Cancelled " + conversation); conversationRepository.remove(conversation); return new RedirectView("/", true); } log.info("Processing " + conversation); if (conversation.validate()) { DomainObject object = conversation.createDomainObject(); domainRepository.set(object); conversationRepository.remove(conversation); return pathTo(SuccessController.class).withVar("id", object.getId()).redirect(); } conversationRepository.set(conversation); return pathToSelf(conversation).redirect(); } private PathBuilder pathToSelf(Conversation conversation) { return pathTo(getClass()).withVar("id", conversation.getId()); } private void update(Conversation conversation, WebRequest request) { DataBinder binder = new ServletRequestDataBinder(conversation); binder.registerCustomEditor(String.class, new StringTrimmerEditor(true)); ServletRequest servletRequest = (ServletRequest) request.resolveReference(WebRequest.REFERENCE_REQUEST); binder.bind(new ServletRequestParameterPropertyValues(servletRequest)); } }
mit
okapies/rx-process
src/main/java/com/github/okapies/rx/process/ReactiveCommand.java
3480
package com.github.okapies.rx.process; import java.net.URI; import java.nio.ByteBuffer; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.TreeMap; import com.zaxxer.nuprocess.NuProcess; import com.zaxxer.nuprocess.NuProcessBuilder; import rx.Observer; public class ReactiveCommand<T> extends AbstractReactiveProcessBuilder<T> { private final List<String> command; private final Map<String, String> environment; private final Path directory; private final ReactiveDecoder<T> decoder; private ReactiveCommand( List<String> command, Map<String, String> environment, Path directory, ReactiveDecoder<T> decoder) { this.command = command; this.environment = environment; this.directory = directory; this.decoder = decoder; } public static ReactiveCommand<ByteBuffer> build(String... command) { return build(Arrays.asList(command)); } public static ReactiveCommand<ByteBuffer> build(List<String> command) { return new ReactiveCommand<>( command, new TreeMap<>(System.getenv()), null, RawDecoder.instance()); } public List<String> command() { return this.command; } public ReactiveCommand<T> command(List<String> command) { return new ReactiveCommand<>( command, this.environment, this.directory, this.decoder); } public ReactiveCommand<T> command(String... command) { return new ReactiveCommand<>( Arrays.asList(command), this.environment, this.directory, this.decoder); } public Map<String, String> environment() { return this.environment; } public ReactiveCommand environment(Map<String, String> environment) { return new ReactiveCommand<>( this.command, environment, this.directory, this.decoder); } public Path directory() { return this.directory; } public ReactiveCommand<T> directory(String first, String... more) { Path path = Paths.get(first, more); return directory(path); } public ReactiveCommand<T> directory(URI uri) { Path path = Paths.get(uri); return directory(path); } public ReactiveCommand<T> directory(Path directory) { return new ReactiveCommand<>(this.command, this.environment, directory, this.decoder); } public ReactiveDecoder decoder() { return this.decoder; } public <R> ReactiveCommand<R> decoder(ReactiveDecoder<R> decoder) { return new ReactiveCommand<>(this.command, this.environment, this.directory, decoder); } @Override public ReactiveProcess run() { return run(null); } @Override public ReactiveProcess run(ProcessObserver<T> observer) { ReactiveProcessHandler<T> handler; if (observer != null) { handler = new ReactiveProcessHandler<>(decoder, observer.stdout(), observer.stderr()); } else { handler = new ReactiveProcessHandler<>(decoder, null, null); } // run an observed process NuProcessBuilder builder = new NuProcessBuilder(handler, command); builder.environment().clear(); builder.environment().putAll(environment); builder.setCwd(directory); builder.start(); return handler.process(); } }
mit
Azure/azure-sdk-for-java
sdk/metricsadvisor/azure-ai-metricsadvisor/src/main/java/com/azure/ai/metricsadvisor/implementation/models/DataLakeGen2SharedKeyParam.java
1173
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.ai.metricsadvisor.implementation.models; import com.azure.core.annotation.Fluent; import com.fasterxml.jackson.annotation.JsonProperty; /** The DataLakeGen2SharedKeyParam model. */ @Fluent public final class DataLakeGen2SharedKeyParam { /* * The account key to access the Azure Data Lake Storage Gen2. */ @JsonProperty(value = "accountKey") private String accountKey; /** * Get the accountKey property: The account key to access the Azure Data Lake Storage Gen2. * * @return the accountKey value. */ public String getAccountKey() { return this.accountKey; } /** * Set the accountKey property: The account key to access the Azure Data Lake Storage Gen2. * * @param accountKey the accountKey value to set. * @return the DataLakeGen2SharedKeyParam object itself. */ public DataLakeGen2SharedKeyParam setAccountKey(String accountKey) { this.accountKey = accountKey; return this; } }
mit
sblectric/AdvancedAddons
src/main/java/com/advancedaddons/events/CustomShieldHandler.java
2763
package com.advancedaddons.events; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.SoundEvents; import net.minecraft.inventory.EntityEquipmentSlot; import net.minecraft.item.ItemStack; import net.minecraft.util.DamageSource; import net.minecraft.util.EnumHand; import net.minecraft.util.math.MathHelper; import net.minecraft.util.math.Vec3d; import net.minecraftforge.event.ForgeEventFactory; import net.minecraftforge.event.entity.living.LivingAttackEvent; import net.minecraftforge.fml.common.eventhandler.SubscribeEvent; import com.advancedaddons.items.ItemShieldAdvanced; /** Handles the custom shield's functionality */ public class CustomShieldHandler { /** Damage the advanced shield correctly, as vanilla code only works for the vanilla shield */ @SubscribeEvent public void onShieldedAttack(LivingAttackEvent e) { EntityLivingBase guy = e.getEntityLiving(); if(!guy.worldObj.isRemote && guy instanceof EntityPlayer) { if(e.getAmount() > 0.0F && guy.getActiveItemStack() != null && guy.getActiveItemStack().getItem() instanceof ItemShieldAdvanced) { if(this.canBlockDamageSource((EntityPlayer)guy, e.getSource())) { this.damageShield((EntityPlayer)guy, e.getAmount()); } } } } /** Better to copy over than to use reflection to the private method */ private boolean canBlockDamageSource(EntityPlayer owner, DamageSource damageSourceIn) { if (!damageSourceIn.isUnblockable() && owner.isActiveItemStackBlocking()) { Vec3d vec3d = damageSourceIn.getDamageLocation(); if (vec3d != null) { Vec3d vec3d1 = owner.getLook(1.0F); Vec3d vec3d2 = vec3d.subtractReverse(new Vec3d(owner.posX, owner.posY, owner.posZ)).normalize(); vec3d2 = new Vec3d(vec3d2.xCoord, 0.0D, vec3d2.zCoord); if (vec3d2.dotProduct(vec3d1) < 0.0D) { return true; } } } return false; } /** Fixed vanilla code */ private void damageShield(EntityPlayer owner, float damage) { int i = 1 + MathHelper.floor_float(damage); owner.getActiveItemStack().damageItem(i, owner); if (owner.getActiveItemStack().stackSize <= 0) { EnumHand enumhand = owner.getActiveHand(); ForgeEventFactory.onPlayerDestroyItem(owner, owner.getActiveItemStack(), enumhand); if(enumhand == EnumHand.MAIN_HAND) { owner.setItemStackToSlot(EntityEquipmentSlot.MAINHAND, (ItemStack)null); } else { owner.setItemStackToSlot(EntityEquipmentSlot.OFFHAND, (ItemStack)null); } owner.resetActiveHand(); owner.playSound(SoundEvents.ITEM_SHIELD_BREAK, 0.8F, 0.8F + owner.worldObj.rand.nextFloat() * 0.4F); } } }
mit
TPeterW/Java-Library
security/signature/ecdsa/ECReader.java
1100
package com.tpwang.security.signature.ecdsa; import java.security.KeyFactory; import java.security.PublicKey; import java.security.Signature; import java.security.spec.X509EncodedKeySpec; import org.apache.commons.codec.binary.Base64; public class ECReader { private byte[] publicKeyEncoded; /*** * Constructor * @param publicKeyEncoded */ public ECReader(byte[] publicKeyEncoded) { this.publicKeyEncoded = publicKeyEncoded; } public boolean verify(String origMsg, String signedMsg) { boolean verified = false; try { // generate public key X509EncodedKeySpec spec = new X509EncodedKeySpec(publicKeyEncoded); KeyFactory factory = KeyFactory.getInstance("EC"); PublicKey publicKey = factory.generatePublic(spec); // prepare signature Signature signature = Signature.getInstance("SHA1withECDSA"); signature.initVerify(publicKey); // verify signature signature.update(origMsg.getBytes()); verified = signature.verify(Base64.decodeBase64(signedMsg)); } catch (Exception e) { e.printStackTrace(); } return verified; } }
mit
bzak/simple-network-simulator
src/pl/lome/socialsym/CalculateFOAF3Correlation.java
5657
package pl.lome.socialsym; import java.util.ArrayList; import java.util.HashMap; import com.tinkerpop.blueprints.pgm.Edge; import com.tinkerpop.blueprints.pgm.Graph; import com.tinkerpop.blueprints.pgm.Vertex; import com.tinkerpop.gremlin.GremlinScriptEngine; public class CalculateFOAF3Correlation extends CalculateFOAF2Correlation { @Override public void execute(GremlinScriptEngine engine, Graph graph) throws Exception { for (Vertex v : graph.getVertices()) { calculateNeighbourAvg(v); } ArrayList<Double> inScores = new ArrayList<Double>(); ArrayList<Double> inValues = new ArrayList<Double>(); ArrayList<Double> outScores = new ArrayList<Double>(); ArrayList<Double> outValues = new ArrayList<Double>(); ArrayList<Double> allScores = new ArrayList<Double>(); ArrayList<Double> allValues = new ArrayList<Double>(); ArrayList<Double> mutualScores = new ArrayList<Double>(); ArrayList<Double> mutualValues = new ArrayList<Double>(); for (Vertex v : graph.getVertices()) { double attitude = new Attitude(v).getValue(); if (v.getProperty("in_foaf3_avg") != null) { AddScore(inScores, v.getProperty("in_foaf3_avg")); AddScore(inValues, attitude); } if (v.getProperty("out_foaf3_avg") != null) { AddScore(outScores, v.getProperty("out_foaf3_avg")); AddScore(outValues, attitude); } if (v.getProperty("all_foaf3_avg") != null) { AddScore(allScores, v.getProperty("all_foaf3_avg")); AddScore(allValues, attitude); } if (v.getProperty("mutual_foaf3_avg") != null) { AddScore(mutualScores, v.getProperty("mutual_foaf3_avg")); AddScore(mutualValues, attitude); } } // System.out.println(); System.out.println("mutual foaf3 corelation = "+getPearsonCorrelation(mutualValues, mutualScores) + " ["+mutualValues.size()+"]"); System.out.println("out foaf3 corelation = "+getPearsonCorrelation(outValues, outScores) + " ["+outValues.size()+"]"); System.out.println("in foaf3 corelation = "+getPearsonCorrelation(inValues, inScores) + " ["+inValues.size()+"]"); System.out.println(); } protected void calculateNeighbourAvg(Vertex v) { // find "in" vertices (remove duplicate relations with hashmap) HashMap<String, Vertex> inV = new HashMap<String, Vertex>(); for (Edge firstEdge : v.getInEdges()) { if (firstEdge.getLabel().equalsIgnoreCase("close") && !isMutual(firstEdge)) { for (Edge secondEdge : firstEdge.getOutVertex().getInEdges()) { if (secondEdge.getLabel().equalsIgnoreCase("close") && !isMutual(firstEdge)) { for (Edge thirdEdge : secondEdge.getOutVertex().getInEdges()) { if (thirdEdge.getLabel().equalsIgnoreCase("close") && !isMutual(firstEdge)) { for (Edge edge : thirdEdge.getOutVertex().getInEdges()) { if (edge.getLabel().equalsIgnoreCase("close") && !isMutual(firstEdge)) { Vertex vertex = edge.getOutVertex(); inV.put(vertex.getId().toString(), vertex); } } } } } } } } // find "out" vertices (remove duplicate relations with hashmap) HashMap<String, Vertex> outV = new HashMap<String, Vertex>(); for (Edge firstEdge : v.getOutEdges()) { if (firstEdge.getLabel().equalsIgnoreCase("close") && !isMutual(firstEdge)) { for (Edge secondEdge : firstEdge.getInVertex().getOutEdges()) { if (secondEdge.getLabel().equalsIgnoreCase("close") && !isMutual(firstEdge)) { for (Edge thirdEdge : secondEdge.getInVertex().getOutEdges()) { if (thirdEdge.getLabel().equalsIgnoreCase("close") && !isMutual(firstEdge)) { for (Edge edge : thirdEdge.getInVertex().getOutEdges()) { if (edge.getLabel().equalsIgnoreCase("close") && !isMutual(firstEdge)) { Vertex vertex = edge.getInVertex(); outV.put(vertex.getId().toString(), vertex); } } } } } } } } HashMap<String, Vertex> mutualV = new HashMap<String, Vertex>(); for (Edge firstEdge : v.getOutEdges()) { if (firstEdge.getLabel().equalsIgnoreCase("close") && isMutual(firstEdge)) { for (Edge secondEdge : firstEdge.getInVertex().getOutEdges()) { if (secondEdge.getLabel().equalsIgnoreCase("close") && isMutual(firstEdge)) { for (Edge thirdEdge : secondEdge.getInVertex().getOutEdges()) { if (thirdEdge.getLabel().equalsIgnoreCase("close") && isMutual(firstEdge)) { for (Edge edge : thirdEdge.getInVertex().getOutEdges()) { if (edge.getLabel().equalsIgnoreCase("close") && isMutual(firstEdge)) { Vertex vertex = edge.getInVertex(); mutualV.put(vertex.getId().toString(), vertex); } } } } } } } } // fill all connected verticies HashMap<String, Vertex> allV = new HashMap<String, Vertex>(); for (Edge firstEdge : union( v.getOutEdges(), v.getInEdges())) { if (firstEdge.getLabel().equalsIgnoreCase("close")) { for (Edge edge : union4( firstEdge.getInVertex().getOutEdges() , firstEdge.getInVertex().getInEdges(), firstEdge.getOutVertex().getOutEdges(), firstEdge.getOutVertex().getInEdges()) ) { if (edge.getLabel().equalsIgnoreCase("close")) { Vertex vertex = edge.getInVertex(); allV.put(vertex.getId().toString(), vertex); } } } } neighbourSetAverage(v, new ArrayList<Vertex>( inV.values() ), "in_foaf3_avg"); neighbourSetAverage(v, new ArrayList<Vertex>( outV.values() ), "out_foaf3_avg"); neighbourSetAverage(v, new ArrayList<Vertex>( allV.values() ), "all_foaf3_avg"); neighbourSetAverage(v, new ArrayList<Vertex>( mutualV.values()), "mutual_foaf3_avg"); } }
mit
zijan/hprose-java
src/main/java/hprose/io/unserialize/TreeMapUnserializer.java
1814
/**********************************************************\ | | | hprose | | | | Official WebSite: http://www.hprose.com/ | | http://www.hprose.org/ | | | \**********************************************************/ /**********************************************************\ * * * TreeMapUnserializer.java * * * * TreeMap unserializer class for Java. * * * * LastModified: Jun 24, 2015 * * Author: Ma Bingyao <andot@hprose.com> * * * \**********************************************************/ package hprose.io.unserialize; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Type; import java.nio.ByteBuffer; import java.util.TreeMap; final class TreeMapUnserializer implements HproseUnserializer { public final static TreeMapUnserializer instance = new TreeMapUnserializer(); public final Object read(HproseReader reader, ByteBuffer buffer, Class<?> cls, Type type) throws IOException { return MapUnserializer.readMap(reader, buffer, TreeMap.class, type); } public final Object read(HproseReader reader, InputStream stream, Class<?> cls, Type type) throws IOException { return MapUnserializer.readMap(reader, stream, TreeMap.class, type); } }
mit
camsys/onebusaway-siri-api-v20
src/main/java/uk/org/siri/siri_2/DeliveryMethodEnumeration.java
1575
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2014.11.22 at 01:45:09 PM EST // package uk.org.siri.siri_2; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for DeliveryMethodEnumeration. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="DeliveryMethodEnumeration"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}NMTOKEN"> * &lt;enumeration value="direct"/> * &lt;enumeration value="fetched"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "DeliveryMethodEnumeration") @XmlEnum public enum DeliveryMethodEnumeration { @XmlEnumValue("direct") DIRECT("direct"), @XmlEnumValue("fetched") FETCHED("fetched"); private final String value; DeliveryMethodEnumeration(String v) { value = v; } public String value() { return value; } public static DeliveryMethodEnumeration fromValue(String v) { for (DeliveryMethodEnumeration c: DeliveryMethodEnumeration.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); } }
mit
3pillarlabs/spring-integration-aws
spring-integration-aws/src/main/java/org/springframework/integration/aws/sns/channel/PublishSubscribeSnsChannel.java
3176
package org.springframework.integration.aws.sns.channel; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.DisposableBean; import org.springframework.context.SmartLifecycle; import org.springframework.integration.Message; import org.springframework.integration.aws.sns.core.NotificationHandler; import org.springframework.integration.aws.sns.core.SnsExecutor; import org.springframework.integration.channel.AbstractMessageChannel; import org.springframework.integration.core.MessageHandler; import org.springframework.integration.core.SubscribableChannel; import org.springframework.integration.dispatcher.BroadcastingDispatcher; import org.springframework.integration.dispatcher.MessageDispatcher; import org.springframework.util.Assert; public class PublishSubscribeSnsChannel extends AbstractMessageChannel implements SubscribableChannel, SmartLifecycle, DisposableBean { private final Log log = LogFactory.getLog(PublishSubscribeSnsChannel.class); private int phase = 0; private boolean autoStartup = true; private boolean running = false; private NotificationHandler notificationHandler; private volatile SnsExecutor snsExecutor; private volatile MessageDispatcher dispatcher; public PublishSubscribeSnsChannel() { super(); this.dispatcher = new BroadcastingDispatcher(); } public void setSnsExecutor(SnsExecutor snsExecutor) { this.snsExecutor = snsExecutor; } @Override protected boolean doSend(Message<?> message, long timeout) { snsExecutor.executeOutboundOperation(message); return true; } @Override public void start() { snsExecutor.registerHandler(notificationHandler); running = true; log.info(getComponentName() + "[" + this.getClass().getName() + "] started listening for messages..."); } @Override public void stop() { if (running) { running = false; log.info(getComponentName() + "[" + this.getClass().getName() + "] listener stopped"); } } @Override public boolean isRunning() { return running; } @Override public int getPhase() { return phase; } public void setPhase(int phase) { this.phase = phase; } @Override public void destroy() throws Exception { stop(); } @Override public boolean isAutoStartup() { return autoStartup; } public void setAutoStartup(boolean autoStartup) { this.autoStartup = autoStartup; } @Override public void stop(Runnable callback) { stop(); callback.run(); } @Override public boolean subscribe(MessageHandler handler) { return dispatcher.addHandler(handler); } @Override public boolean unsubscribe(MessageHandler handler) { return dispatcher.removeHandler(handler); } @Override protected void onInit() throws Exception { super.onInit(); Assert.notNull(snsExecutor, "'snsExecutor' must not be null"); notificationHandler = new NotificationHandler() { @Override protected void dispatch(Message<?> message) { dispatcher.dispatch(message); } }; log.info("Initialized SNS Channel: [" + getComponentName() + "]"); } @Override public String getComponentType() { return "publish-subscribe-channel"; } }
mit
schmirob000/2016-Stronghold
src/org/usfirst/frc/team4915/stronghold/Robot.java
7923
package org.usfirst.frc.team4915.stronghold; import org.usfirst.frc.team4915.stronghold.commands.AutoCommand1; import org.usfirst.frc.team4915.stronghold.commands.PortcullisMoveUp; import org.usfirst.frc.team4915.stronghold.subsystems.Autonomous; import org.usfirst.frc.team4915.stronghold.subsystems.DriveTrain; import org.usfirst.frc.team4915.stronghold.subsystems.GearShift; import org.usfirst.frc.team4915.stronghold.subsystems.IntakeLauncher; import org.usfirst.frc.team4915.stronghold.subsystems.Scaler; import org.usfirst.frc.team4915.stronghold.utils.BNO055; import edu.wpi.first.wpilibj.IterativeRobot; import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.command.Command; import edu.wpi.first.wpilibj.command.Scheduler; import edu.wpi.first.wpilibj.livewindow.LiveWindow; import edu.wpi.first.wpilibj.smartdashboard.SendableChooser; import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard; /** * The VM is configured to automatically run this class, and to call the * functions corresponding to each mode, as described in the IterativeRobot * documentation. If you change the name of this class or the package after * creating this project, you must also update the manifest file in the resource * directory. */ public class Robot extends IterativeRobot { public static DriveTrain driveTrain; public static IntakeLauncher intakeLauncher; public static OI oi; public static GearShift gearShift; public static Scaler scaler; Command autonomousCommand; SendableChooser autonomousProgramChooser; private volatile double lastTime; /** * This function is run when the robot is first started up and should be * used for any initialization code. */ @Override public void robotInit() { RobotMap.init(); // 1. Initialize RobotMap prior to initializing modules // 2. conditionally create the modules if (ModuleManager.PORTCULLIS_MODULE_ON){ new PortcullisMoveUp().start(); } if (ModuleManager.DRIVE_MODULE_ON) { driveTrain = new DriveTrain(); SmartDashboard.putString("Drivetrain Module", "initialized"); } else SmartDashboard.putString("Drivetrain Module", "disabled"); if (ModuleManager.GEARSHIFT_MODULE_ON) { gearShift = new GearShift(); SmartDashboard.putString("Shift Module", "initialized"); } else SmartDashboard.putString("Shift Module", "disabled"); if (ModuleManager.INTAKELAUNCHER_MODULE_ON) { /* to prevent module-manager-madness (M-cubed), we * place try/catch block for exceptions thrown on account of * missing hardware. */ try { intakeLauncher = new IntakeLauncher(); SmartDashboard.putString("IntakeLauncher Module", "initialized"); } catch (Throwable e) { System.out.println("Disabling IntakeLauncher at runtime"); SmartDashboard.putString("IntakeLauncher Module", "ERROR"); ModuleManager.INTAKELAUNCHER_MODULE_ON = false; } } else SmartDashboard.putString("IntakeLauncher Module", "disabled"); if (ModuleManager.SCALING_MODULE_ON) { scaler = new Scaler(); SmartDashboard.putString("Scaling Module", "initialized"); } else SmartDashboard.putString("Scaling Module", "disabled"); if (ModuleManager.IMU_MODULE_ON) { // imu is initialized in RobotMap.init() SmartDashboard.putString("IMU Module", "initialized"); SmartDashboard.putBoolean("IMU present", RobotMap.imu.isSensorPresent()); updateIMUStatus(); } else SmartDashboard.putString("IMU Module", "disabled"); oi = new OI(); // 3. Construct OI after subsystems created } @Override public void disabledPeriodic() { Scheduler.getInstance().run(); } @Override public void autonomousInit() { // schedule the autonomous command autonomousCommand = new AutoCommand1((Autonomous.Type) oi.barrierType.getSelected(), (Autonomous.Strat) oi.strategy.getSelected(), (Autonomous.Position) oi.startingFieldPosition.getSelected()); System.out.println("Autonomous selection Angle: " + oi.startingFieldPosition.getSelected() + "Field Position " + oi.startingFieldPosition.getSelected() + "strategy " + oi.strategy.getSelected() + "Obstacle " + oi.barrierType.getSelected()); if (this.autonomousCommand != null) { this.autonomousCommand.start(); } } /** * This function is called periodically during autonomous */ @Override public void autonomousPeriodic() { Scheduler.getInstance().run(); periodicStatusUpdate(); } @Override public void teleopInit() { // This makes sure that the autonomous stops running when // teleop starts running. If you want the autonomous to // continue until interrupted by another command, remove // this line or comment it out. //set speed // RobotMap.rightBackMotor.changeControlMode(CANTalon.TalonControlMode.Speed); // RobotMap.leftBackMotor.changeControlMode(CANTalon.TalonControlMode.Speed); System.out.println("entering teleop"); Robot.intakeLauncher.aimMotor.enableControl(); if (this.autonomousCommand != null) { this.autonomousCommand.cancel(); } } /** * This function is called when the disabled button is hit. You can use it * to reset subsystems before shutting down. */ @Override public void disabledInit() { } /** * This function is called periodically during operator control */ @Override public void teleopPeriodic() { Scheduler.getInstance().run(); periodicStatusUpdate(); } /** * This function is called periodically during test mode */ @Override public void testPeriodic() { LiveWindow.run(); periodicStatusUpdate(); } public void periodicStatusUpdate() { double currentTime = Timer.getFPGATimestamp(); // seconds // only update the smart dashboard twice per second to prevent // network congestion. if(currentTime - this.lastTime > .5) { updateIMUStatus(); updateLauncherStatus(); updateDrivetrainStatus(); this.lastTime = currentTime; } } public void updateIMUStatus() { if (ModuleManager.IMU_MODULE_ON) { BNO055.CalData calData = RobotMap.imu.getCalibration(); SmartDashboard.putNumber("IMU heading", RobotMap.imu.getNormalizedHeading()); // SmartDashboard.putNumber("IMU dist to origin", RobotMap.imu.getDistFromOrigin()); SmartDashboard.putNumber("IMU calibration", (1000 + (calData.accel * 100) + calData.gyro *10 + calData.mag)); //Calibration values range from 0-3, Right to left: mag, gyro, accel } } public void updateLauncherStatus() { if (ModuleManager.INTAKELAUNCHER_MODULE_ON) { SmartDashboard.putNumber("aimMotor Potentiometer: ", intakeLauncher.getPosition()); SmartDashboard.putBoolean("Top Limit Switch: ", intakeLauncher.isLauncherAtTop()); SmartDashboard.putBoolean("Bottom Limit Switch: ", intakeLauncher.isLauncherAtBottom()); SmartDashboard.putBoolean("Boulder Limit Switch: ", intakeLauncher.boulderSwitch.get()); SmartDashboard.putBoolean("Potentiometer might be broken", intakeLauncher.getIsPotentiometerScrewed()); } } public void toggleSpeed() { } public void updateDrivetrainStatus() { if (ModuleManager.DRIVE_MODULE_ON) { } } }
mit
beeant0512/spring
spring-sitemesh-dojo-bootstrap/src/main/java/com/beeant/service/IUserService.java
156
package com.beeant.service; import com.beeant.common.IBaseService; import com.beeant.po.User; public interface IUserService extends IBaseService<User> { }
mit
nithinvnath/PAVProject
com.ibm.wala.core/src/com/ibm/wala/demandpa/alg/IntraProcFilter.java
3985
/******************************************************************************* * This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html. * * This file is a derivative of code released by the University of * California under the terms listed below. * * Refinement Analysis Tools is Copyright (c) 2007 The Regents of the * University of California (Regents). Provided that this notice and * the following two paragraphs are included in any distribution of * Refinement Analysis Tools or its derivative work, Regents agrees * not to assert any of Regents' copyright rights in Refinement * Analysis Tools against recipient for recipient's reproduction, * preparation of derivative works, public display, public * performance, distribution or sublicensing of Refinement Analysis * Tools and derivative works, in source code and object code form. * This agreement not to assert does not confer, by implication, * estoppel, or otherwise any license or rights in any intellectual * property of Regents, including, but not limited to, any patents * of Regents or Regents' employees. * * IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, * INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, * INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE * AND ITS DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE AND FURTHER DISCLAIMS ANY STATUTORY * WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE AND ACCOMPANYING * DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS * IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, * UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ package com.ibm.wala.demandpa.alg; import com.ibm.wala.demandpa.alg.statemachine.StateMachine; import com.ibm.wala.demandpa.alg.statemachine.StateMachineFactory; import com.ibm.wala.demandpa.flowgraph.AbstractFlowLabelVisitor; import com.ibm.wala.demandpa.flowgraph.IFlowLabel; import com.ibm.wala.demandpa.flowgraph.ParamBarLabel; import com.ibm.wala.demandpa.flowgraph.ParamLabel; import com.ibm.wala.demandpa.flowgraph.ReturnBarLabel; import com.ibm.wala.demandpa.flowgraph.ReturnLabel; /** * State machine that only allows intraprocedural paths. Mainly for testing * purposes. * * @author Manu Sridharan * */ public class IntraProcFilter implements StateMachine<IFlowLabel> { private static final State DUMMY = new State() { }; @Override public State getStartState() { return DUMMY; } private static class InterprocFilterVisitor extends AbstractFlowLabelVisitor { @Override public void visitParamBar(ParamBarLabel label, Object dst) { interprocEdge = true; } @Override public void visitParam(ParamLabel label, Object dst) { interprocEdge = true; } @Override public void visitReturn(ReturnLabel label, Object dst) { interprocEdge = true; } @Override public void visitReturnBar(ReturnBarLabel label, Object dst) { interprocEdge = true; } boolean interprocEdge = false; } @Override public State transition(State prevState, IFlowLabel label) throws IllegalArgumentException { if (label == null) { throw new IllegalArgumentException("label == null"); } // filter out all interprocedural edges InterprocFilterVisitor v = new InterprocFilterVisitor(); label.visit(v, null); return v.interprocEdge ? ERROR : DUMMY; } private IntraProcFilter() { } public static class Factory implements StateMachineFactory<IFlowLabel> { @Override public StateMachine<IFlowLabel> make() { return new IntraProcFilter(); } } }
mit
seregamorph/revolut
sinap-payment/src/main/java/com/revolut/sinap/payment/Payment.java
2839
package com.revolut.sinap.payment; import java.util.Objects; import java.util.UUID; public class Payment implements PaymentServiceOperation { private final UUID transactionId; private long sourceAccountId; private Currency sourceCurrency; /** * minor units */ private long sourceAmount; private long targetAccountId; private Currency targetCurrency; /** * minor units */ private long targetAmount; private String comment; public Payment(UUID transactionId) { this.transactionId = Objects.requireNonNull(transactionId, "transactionId"); } public Payment setSourceAccountId(long sourceAccountId) { this.sourceAccountId = sourceAccountId; return this; } public Payment setSourceCurrency(Currency sourceCurrency) { this.sourceCurrency = sourceCurrency; return this; } public Payment setSourceAmount(long sourceAmount) { this.sourceAmount = sourceAmount; return this; } public Payment setTargetAccountId(long targetAccountid) { this.targetAccountId = targetAccountid; return this; } public Payment setTargetCurrency(Currency targetCurrency) { this.targetCurrency = targetCurrency; return this; } public Payment setTargetAmount(long targetAmount) { this.targetAmount = targetAmount; return this; } public Payment setComment(String comment) { this.comment = comment; return this; } @Override public UUID transactionId() { return transactionId; } @Override public long getSourceAccountId() { return sourceAccountId; } @Override public Currency getSourceCurrency() { return sourceCurrency; } @Override public long getSourceAmount() { return sourceAmount; } @Override public long getTargetAccountId() { return targetAccountId; } @Override public Currency getTargetCurrency() { return targetCurrency; } @Override public long getTargetAmount() { return targetAmount; } @Override public String getComment() { return comment; } @Override public String toString() { // todo mask account ids if it is card numbers return "Payment{" + "transactionId=" + transactionId + ", sourceAccountId=" + sourceAccountId + ", sourceCurrency='" + sourceCurrency + '\'' + ", sourceAmount=" + sourceAmount + ", targetAccountId=" + targetAccountId + ", targetCurrency='" + targetCurrency + '\'' + ", targetAmount=" + targetAmount + ", comment='" + comment + '\'' + '}'; } }
mit
Karlis/CommitAnalysis
_EclipsePluginsPPA/MyHeadlessPlugin/src/myheadlessplugin/Perspective.java
225
package myheadlessplugin; import org.eclipse.ui.IPageLayout; import org.eclipse.ui.IPerspectiveFactory; public class Perspective implements IPerspectiveFactory { public void createInitialLayout(IPageLayout layout) { } }
mit
memo33/NAMControllerCompiler
src/controller/tasks/CollectRULsTask.java
3307
package controller.tasks; import static controller.NAMControllerCompilerMain.LOGGER; import java.io.File; import java.io.FileFilter; import java.util.Arrays; import java.util.LinkedList; import java.util.Queue; import java.util.concurrent.ExecutionException; import javax.swing.SwingWorker; import controller.CompileMode; public abstract class CollectRULsTask implements ExecutableTask { private static FileFilter fileFilter = new FileFilter() { @Override public boolean accept(File pathname) { return pathname.isDirectory() || pathname.getName().endsWith(".txt") || pathname.getName().endsWith(".rul"); } }; private final File[] rulDirs; public static CollectRULsTask getInstance(CompileMode mode, File[] rulDirs) { return mode.isInteractive() ? new GUITask(rulDirs) : new CommandLineTask(rulDirs); } private CollectRULsTask(File[] rulDirs) { this.rulDirs = rulDirs; } public abstract Queue<File>[] get() throws InterruptedException, ExecutionException; private Queue<File>[] mainProcess() { LOGGER.info("Collecting input data."); @SuppressWarnings("unchecked") Queue<File>[] rulInputFiles = new Queue[3]; for (int i = 0; i < rulInputFiles.length; i++) rulInputFiles[i] = collectRecursively(CollectRULsTask.this.rulDirs[i]); return rulInputFiles; } /** * Recursive collecting. * @param parent parent file of the directory. * @return Queue of subfiles. */ private Queue<File> collectRecursively(File parent) { Queue<File> result = new LinkedList<File>(); File[] subFiles = parent.listFiles(fileFilter); Arrays.sort(subFiles); // sort files alphabetically for (int i = 0; i < subFiles.length; i++) { if (subFiles[i].isDirectory()) result.addAll(collectRecursively(subFiles[i])); else result.add(subFiles[i]); } return result; } private static class GUITask extends CollectRULsTask { private final SwingWorker<Queue<File>[], Void> worker; private GUITask(File[] rulDirs) { super(rulDirs); this.worker = new SwingWorker<Queue<File>[], Void>() { @Override protected Queue<File>[] doInBackground() { return GUITask.super.mainProcess(); } }; } @Override public void execute() { this.worker.execute(); } @Override public Queue<File>[] get() throws InterruptedException, ExecutionException { return worker.get(); } } private static class CommandLineTask extends CollectRULsTask { private Queue<File>[] result; private CommandLineTask(File[] rulDirs) { super(rulDirs); } @Override public void execute() { result = CommandLineTask.super.mainProcess(); } @Override public Queue<File>[] get() { return result; } } }
mit
CS2103JAN2017-F11-B3/main
src/main/java/seedu/task/commons/util/FileUtil.java
4193
package seedu.task.commons.util; import java.io.File; import java.io.IOException; import java.nio.file.Files; import javafx.stage.FileChooser; import javafx.stage.FileChooser.ExtensionFilter; import javafx.stage.Stage; /** * Writes and reads files */ public class FileUtil { private static final String CHARSET = "UTF-8"; public static boolean isFileExists(File file) { return file.exists() && file.isFile(); } public static void createIfMissing(File file) throws IOException { if (!isFileExists(file)) { createFile(file); } } /** * Creates a file if it does not exist along with its missing parent directories * * @return true if file is created, false if file already exists */ public static boolean createFile(File file) throws IOException { if (file.exists()) { return false; } createParentDirsOfFile(file); return file.createNewFile(); } /** * Creates the given directory along with its parent directories * * @param dir the directory to be created; assumed not null * @throws IOException if the directory or a parent directory cannot be created */ public static void createDirs(File dir) throws IOException { if (!dir.exists() && !dir.mkdirs()) { throw new IOException("Failed to make directories of " + dir.getName()); } } /** * Creates parent directories of file if it has a parent directory */ public static void createParentDirsOfFile(File file) throws IOException { File parentDir = file.getParentFile(); if (parentDir != null) { createDirs(parentDir); } } /** * Assumes file exists */ public static String readFromFile(File file) throws IOException { return new String(Files.readAllBytes(file.toPath()), CHARSET); } /** * Writes given string to a file. * Will create the file if it does not exist yet. */ public static void writeToFile(File file, String content) throws IOException { Files.write(file.toPath(), content.getBytes(CHARSET)); } /** * Converts a string to a platform-specific file path * @param pathWithForwardSlash A String representing a file path but using '/' as the separator * @return {@code pathWithForwardSlash} but '/' replaced with {@code File.separator} */ public static String getPath(String pathWithForwardSlash) { assert pathWithForwardSlash != null; assert pathWithForwardSlash.contains("/"); return pathWithForwardSlash.replace("/", File.separator); } //@@author A0163848R /** * Creates a localized window to create a file for saving. * @param Window title * @param File extension filters * @return Chosen file */ public static File promptSaveFileDialog(String title, Stage stage, ExtensionFilter ...extensionFilters) { FileChooser prompt = getFileChooser(title, extensionFilters); File saved = prompt.showSaveDialog(stage); if (!saved.getName().contains(".")) { saved = new File(saved.getAbsolutePath() + prompt.getSelectedExtensionFilter().getExtensions().get(0).substring(1)); } return saved; } /** * Creates a localized window to select a file for loading. * @param Window title * @param File extension filters * @return Chosen file */ public static File promptOpenFileDialog(String title, Stage stage, ExtensionFilter ...extensionFilters) { return getFileChooser(title, extensionFilters).showOpenDialog(stage); } /** * Returns a new file chooser prompt * @param Title of prompt * @param Extension filters to allow for writing/reading * @return New file chooser prompt */ private static FileChooser getFileChooser(String title, ExtensionFilter ...extensionFilters) { FileChooser fileChooser = new FileChooser(); fileChooser.setTitle(title); fileChooser.getExtensionFilters().addAll(extensionFilters); return fileChooser; } }
mit
RafidSaad/CI_And_Refactoring
src/pieces/Bishop.java
2069
package pieces; import java.util.ArrayList; import chess.ChessboardCell; /** * This is the Bishop Class. * The Move Function defines the basic rules for movement of Bishop on a chess board * * */ public class Bishop extends Piece{ //Constructor public Bishop(String i,String p,int c) { setId(i); setPath(p); setColor(c); } //move function defined. It returns a list of all the possible destinations of a Bishop //The basic principle of Bishop Movement on chess board has been implemented public ArrayList<ChessboardCell> move(ChessboardCell state[][],int x,int y) { //Bishop can Move diagonally in all 4 direction (NW,NE,SW,SE) //This function defines that logic possiblemoves.clear(); int tempx=x+1; int tempy=y-1; while(tempx<8&&tempy>=0) { if(state[tempx][tempy].getpiece()==null) { possiblemoves.add(state[tempx][tempy]); } else if(state[tempx][tempy].getpiece().getcolor()==this.getcolor()) break; else { possiblemoves.add(state[tempx][tempy]); break; } tempx++; tempy--; } tempx=x-1;tempy=y+1; while(tempx>=0&&tempy<8) { if(state[tempx][tempy].getpiece()==null) possiblemoves.add(state[tempx][tempy]); else if(state[tempx][tempy].getpiece().getcolor()==this.getcolor()) break; else { possiblemoves.add(state[tempx][tempy]); break; } tempx--; tempy++; } tempx=x-1;tempy=y-1; while(tempx>=0&&tempy>=0) { if(state[tempx][tempy].getpiece()==null) possiblemoves.add(state[tempx][tempy]); else if(state[tempx][tempy].getpiece().getcolor()==this.getcolor()) break; else { possiblemoves.add(state[tempx][tempy]); break; } tempx--; tempy--; } tempx=x+1;tempy=y+1; while(tempx<8&&tempy<8) { if(state[tempx][tempy].getpiece()==null) possiblemoves.add(state[tempx][tempy]); else if(state[tempx][tempy].getpiece().getcolor()==this.getcolor()) break; else { possiblemoves.add(state[tempx][tempy]); break; } tempx++; tempy++; } return possiblemoves; } }
mit
Uristqwerty/CraftGuide
src/main/java/uristqwerty/CraftGuide/api/ItemSlot.java
4518
package uristqwerty.CraftGuide.api; import java.util.List; /** * When a recipe is rendered, the ItemSlots provided to the template are * used to determine the layout of the recipe's items. * * @deprecated API re-organization. Use the copy in uristqwerty.craftguide.api.slotTypes * instead, if possible. This copy will remain until at least Minecraft 1.14, probably longer. */ @SuppressWarnings("deprecation") @Deprecated public class ItemSlot implements Slot { /** * This slot's size and location relative to the containing * recipe's top left corner */ public int x, y, width, height; /** * Used by {@link ItemSlotImplementation#draw} to decide * whether to draw a background before drawing the actual * slot contents. */ public boolean drawBackground; /** * A sneaky field that is read by the default recipe implementation * when an instance is created. If an ItemStack with a quantity * greater than one would match up to an ItemSlot where * drawQuantity equals false, it replaces the stack with one * with a size of 1. This is only provided for convenience, it * is entirely possibly to implement the same logic if it * is needed but unavailable, such as with a custom recipe, * or an implementation of Slot that is not an ItemSlot. * <br><br> * The actual effect of this field may change in the future * (for example, copying only part of the method that Minecraft * uses to draw the item overlay, making the part that draws the * stack size conditional), but for the moment, I'm assuming that * doing it this way will be more compatible if Minecraft changes * its implementation in the future, or if another mod edits * {@link net.minecraft.src.RenderItem#renderItemOverlayIntoGUI}. */ public boolean drawQuantity; /** * Used by {@link ItemSlotImplementation#matches} to * restrict what sort of searches can match this slot */ public SlotType slotType = SlotType.INPUT_SLOT; /** * Implementation of ItemSlot functionality, allowing it * to change if needed, without altering the API. This * field is set during CraftGuide's {@literal @PreInit}. */ public static ItemSlotImplementation implementation; /** * Creates a new ItemSlot. Same as * {@link #ItemSlot(int, int, int, int, boolean)}, with * false as the last parameter. * @param x * @param y * @param width * @param height */ public ItemSlot(int x, int y, int width, int height) { this(x, y, width, height, false); } /** * Creates a new ItemSlot * @param x * @param y * @param width * @param height * @param drawQuantity */ public ItemSlot(int x, int y, int width, int height, boolean drawQuantity) { this.x = x; this.y = y; this.width = width; this.height = height; this.drawQuantity = drawQuantity; } @Override public void draw(Renderer renderer, int x, int y, Object[] data, int dataIndex, boolean isMouseOver) { implementation.draw(this, renderer, x, y, data[dataIndex], isMouseOver); } @Override public List<String> getTooltip(int x, int y, Object[] data, int dataIndex) { return implementation.getTooltip(this, data[dataIndex]); } @Override public boolean matches(ItemFilter search, Object[] data, int dataIndex, SlotType type) { return implementation.matches(this, search, data[dataIndex], type); } @Override public boolean isPointInBounds(int x, int y, Object[] data, int dataIndex) { return implementation.isPointInBounds(this, x, y); } @Override public ItemFilter getClickedFilter(int x, int y, Object[] data, int dataIndex) { return implementation.getClickedFilter(x, y, data[dataIndex]); } /** * Sets whether or not this ItemSlot draws a background square * during its draw method. * @param draw * @return this, to permit method chaining */ public ItemSlot drawOwnBackground(boolean draw) { drawBackground = draw; return this; } /** * Sets whether or not this ItemSlot draws a background square * during its draw method. Same as {@link #drawOwnBackground()}, * but uses the default value of true. * @return this, to permit method chaining */ public ItemSlot drawOwnBackground() { return drawOwnBackground(true); } /** * Sets the {@link SlotType} associated with this ItemSlot. * The SlotType is used for searches, both from in-game, and * from the use of the API * @param type * @return this ItemSlot, to permit method chaining */ public ItemSlot setSlotType(SlotType type) { slotType = type; return this; } }
mit
ch-x01/fuzzy
src/main/java/ch/x01/fuzzy/core/LinguisticVariable.java
5647
package ch.x01.fuzzy.core; import ch.x01.fuzzy.parser.SymbolTable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Objects; /** * This class implements the concept of a linguistic variable. Linguistic variables take on values * defined in its term set - its set of linguistic terms. Linguistic terms are subjective categories * for the linguistic variable. For example, for linguistic variable 'age', the term set T(age) may * be defined as follows: * <p> * T(age)={"young", "middle aged", "old"} * </p> * Each linguistic term is associated with a reference fuzzy set, each of which has a defined * membership function (MF). */ public class LinguisticVariable { private static final Logger logger = LoggerFactory.getLogger(LinguisticVariable.class); private final String name; private final Map<String, MembershipFunction> termSet = new HashMap<>(); private double value; /** * Constructs a linguistic variable. The constructed variable needs to be registered with the symbol table. * * @param name the name of this linguistic variable */ public LinguisticVariable(String name) { this.name = name.toLowerCase(); } /** * Constructs a linguistic variable and registers it with the symbol table. * * @param name the name of this linguistic variable * @param symbolTable the table where linguistic variables and its terms are registered */ public LinguisticVariable(String name, SymbolTable symbolTable) { this.name = name.toLowerCase(); symbolTable.registerLV(this); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; LinguisticVariable that = (LinguisticVariable) o; return Objects.equals(name, that.name); } @Override public int hashCode() { return Objects.hash(name); } /** * Returns the name of this linguistic variable. * * @return name */ public String getName() { return this.name; } /** * Returns the current crisp value for this linguistic variable. * * @return current value */ public double getValue() { return this.value; } /** * Sets a crisp value for this linguistic variable. * * @param value the value */ public void setValue(double value) { this.value = value; if (logger.isDebugEnabled()) { logger.debug(String.format("Set crisp value = %.4f for linguistic variable \"%s\".", this.value, this.name)); } } /** * Adds a linguistic term with its associated membership function to the variable's term set. * * @param name the name of linguistic term * @param mf the associated membership function */ public void addTerm(String name, MembershipFunction mf) { String term = name.toLowerCase(); if (!this.termSet.containsKey(term)) { this.termSet.put(term, mf); } else { throw new RuntimeException(String.format( "Cannot add linguistic term \"%s\" because it is already a member of the term set of linguistic variable \"%s\".", term, this.name)); } } /** * Computes the degree of membership for a crisp input value for a given linguistic term. * * @param name the name of linguistic term * @return degree of membership for the given linguistic term as a result of fuzzification or -1 * if fuzzification is not possible. */ public double is(String name) { double result; String term = name.toLowerCase(); if (this.termSet.containsKey(term)) { MembershipFunction mf = this.termSet.get(term); result = mf.fuzzify(this.value); } else { throw new RuntimeException(String.format( "Cannot compute fuzzification for linguistic term \"%s\" because it is not a member of the term set of linguistic variable \"%s\".", term, this.name)); } return result; } /** * Returns the membership function associated to the specified linguistic term. * * @param name the name of linguistic term * @return the associated membership function */ public MembershipFunction getMembershipFunction(String name) { MembershipFunction mf; String term = name.toLowerCase(); if (this.termSet.containsKey(term)) { mf = this.termSet.get(term); } else { throw new RuntimeException( String.format( "Cannot retrieve membership function because linguistic term \"%s\" is not a member of the term set of linguistic variable \"%s\".", term, this.name)); } return mf; } public boolean containsTerm(String name) { return this.termSet.containsKey(name.toLowerCase()); } @Override public String toString() { StringBuilder builder = new StringBuilder(); for (Iterator<String> it = this.termSet.keySet() .iterator(); it.hasNext(); ) { builder.append(it.next()); if (it.hasNext()) { builder.append(", "); } } return "T(" + this.name + ") = {" + builder.toString() + "}"; } }
mit
Azure/azure-sdk-for-java
sdk/customerinsights/azure-resourcemanager-customerinsights/src/main/java/com/azure/resourcemanager/customerinsights/models/RoleListResult.java
2249
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.customerinsights.models; import com.azure.core.annotation.Fluent; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.customerinsights.fluent.models.RoleResourceFormatInner; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; /** The response of list role assignment operation. */ @Fluent public final class RoleListResult { @JsonIgnore private final ClientLogger logger = new ClientLogger(RoleListResult.class); /* * Results of the list operation. */ @JsonProperty(value = "value") private List<RoleResourceFormatInner> value; /* * Link to the next set of results. */ @JsonProperty(value = "nextLink") private String nextLink; /** * Get the value property: Results of the list operation. * * @return the value value. */ public List<RoleResourceFormatInner> value() { return this.value; } /** * Set the value property: Results of the list operation. * * @param value the value value to set. * @return the RoleListResult object itself. */ public RoleListResult withValue(List<RoleResourceFormatInner> value) { this.value = value; return this; } /** * Get the nextLink property: Link to the next set of results. * * @return the nextLink value. */ public String nextLink() { return this.nextLink; } /** * Set the nextLink property: Link to the next set of results. * * @param nextLink the nextLink value to set. * @return the RoleListResult object itself. */ public RoleListResult withNextLink(String nextLink) { this.nextLink = nextLink; return this; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { if (value() != null) { value().forEach(e -> e.validate()); } } }
mit
funIntentions/chitchat
src/com/lamepancake/chitchat/packet/MessagePacket.java
3310
package com.lamepancake.chitchat.packet; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.util.Objects; /** * Contains a message to be sent to other users in the chat. * * Specifies the chat to which the message is to be sent and the user sending * the message. * * @author shane */ public class MessagePacket extends Packet { private final String message; private int userID; private final int chatID; /** * Constructs a MessagePacket with the given message and userID. * * @param message The message to send. * @param userID The ID of the user sending the message. */ public MessagePacket(String message, int userID, int chatID) { super(Packet.MESSAGE, 8 + message.length() * 2); this.message = message; this.userID = userID; this.chatID = chatID; } /** * Construct a MessagePacket from a serialised one. * * @param header The serialised header. * @param data A ByteBuffer containing the serialised packet. */ public MessagePacket(ByteBuffer header, ByteBuffer data) { super(header); byte[] rawMessage = new byte[data.capacity() - 8]; this.userID = data.getInt(); this.chatID = data.getInt(); data.get(rawMessage); this.message = new String(rawMessage, StandardCharsets.UTF_16LE); } @Override public ByteBuffer serialise() { ByteBuffer buf = super.serialise(); buf.putInt(this.userID); buf.putInt(this.chatID); buf.put(this.message.getBytes(StandardCharsets.UTF_16LE)); buf.rewind(); return buf; } /** * Get the message contained in this packet. * @return The message contained in this packet. */ public String getMessage() { return message; } /** * Returns the ID of the user sending the message. * * @return The ID of the user sending the message. */ public int getUserID() { return this.userID; } /** * Set the user ID in case it's not set. * * The user ID must be >= 0. The method will throw an IllegalArgumentException * if this rule is not followed. * * @param newID The new user ID to assign to this message. */ public void setUserID(int newID) { if(newID < 0) throw new IllegalArgumentException("MessagePacket.setUserID: newID must be >= 0, was " + newID); this.userID = newID; } public int getChatID() { return this.chatID; } @Override public boolean equals(Object o) { if(!super.equals(o)) return false; if(o instanceof MessagePacket) { MessagePacket p = (MessagePacket)o; if(!message.equals(p.getMessage())) return false; if(chatID != p.getChatID()) return false; return userID == p.getUserID(); } return false; } @Override public int hashCode() { int hash = 7; hash = 73 * hash + Objects.hashCode(this.message); hash = 73 * hash + this.userID; hash = 73 * hash + this.chatID; return hash; } }
mit
CellarHQ/cellarhq.com
model/src/main/generated/com/cellarhq/generated/tables/daos/CategoryDao.java
7484
/* * This file is generated by jOOQ. */ package com.cellarhq.generated.tables.daos; import com.cellarhq.generated.tables.Category; import com.cellarhq.generated.tables.records.CategoryRecord; import java.time.LocalDateTime; import java.util.List; import javax.annotation.processing.Generated; import org.jooq.Configuration; import org.jooq.JSON; import org.jooq.impl.DAOImpl; /** * This class is generated by jOOQ. */ @Generated( value = { "http://www.jooq.org", "jOOQ version:3.12.3" }, comments = "This class is generated by jOOQ" ) @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class CategoryDao extends DAOImpl<CategoryRecord, com.cellarhq.generated.tables.pojos.Category, Long> { /** * Create a new CategoryDao without any configuration */ public CategoryDao() { super(Category.CATEGORY, com.cellarhq.generated.tables.pojos.Category.class); } /** * Create a new CategoryDao with an attached configuration */ public CategoryDao(Configuration configuration) { super(Category.CATEGORY, com.cellarhq.generated.tables.pojos.Category.class, configuration); } @Override public Long getId(com.cellarhq.generated.tables.pojos.Category object) { return object.getId(); } /** * Fetch records that have <code>id BETWEEN lowerInclusive AND upperInclusive</code> */ public List<com.cellarhq.generated.tables.pojos.Category> fetchRangeOfId(Long lowerInclusive, Long upperInclusive) { return fetchRange(Category.CATEGORY.ID, lowerInclusive, upperInclusive); } /** * Fetch records that have <code>id IN (values)</code> */ public List<com.cellarhq.generated.tables.pojos.Category> fetchById(Long... values) { return fetch(Category.CATEGORY.ID, values); } /** * Fetch a unique record that has <code>id = value</code> */ public com.cellarhq.generated.tables.pojos.Category fetchOneById(Long value) { return fetchOne(Category.CATEGORY.ID, value); } /** * Fetch records that have <code>version BETWEEN lowerInclusive AND upperInclusive</code> */ public List<com.cellarhq.generated.tables.pojos.Category> fetchRangeOfVersion(Integer lowerInclusive, Integer upperInclusive) { return fetchRange(Category.CATEGORY.VERSION, lowerInclusive, upperInclusive); } /** * Fetch records that have <code>version IN (values)</code> */ public List<com.cellarhq.generated.tables.pojos.Category> fetchByVersion(Integer... values) { return fetch(Category.CATEGORY.VERSION, values); } /** * Fetch records that have <code>name BETWEEN lowerInclusive AND upperInclusive</code> */ public List<com.cellarhq.generated.tables.pojos.Category> fetchRangeOfName(String lowerInclusive, String upperInclusive) { return fetchRange(Category.CATEGORY.NAME, lowerInclusive, upperInclusive); } /** * Fetch records that have <code>name IN (values)</code> */ public List<com.cellarhq.generated.tables.pojos.Category> fetchByName(String... values) { return fetch(Category.CATEGORY.NAME, values); } /** * Fetch records that have <code>description BETWEEN lowerInclusive AND upperInclusive</code> */ public List<com.cellarhq.generated.tables.pojos.Category> fetchRangeOfDescription(String lowerInclusive, String upperInclusive) { return fetchRange(Category.CATEGORY.DESCRIPTION, lowerInclusive, upperInclusive); } /** * Fetch records that have <code>description IN (values)</code> */ public List<com.cellarhq.generated.tables.pojos.Category> fetchByDescription(String... values) { return fetch(Category.CATEGORY.DESCRIPTION, values); } /** * Fetch records that have <code>searchable BETWEEN lowerInclusive AND upperInclusive</code> */ public List<com.cellarhq.generated.tables.pojos.Category> fetchRangeOfSearchable(Boolean lowerInclusive, Boolean upperInclusive) { return fetchRange(Category.CATEGORY.SEARCHABLE, lowerInclusive, upperInclusive); } /** * Fetch records that have <code>searchable IN (values)</code> */ public List<com.cellarhq.generated.tables.pojos.Category> fetchBySearchable(Boolean... values) { return fetch(Category.CATEGORY.SEARCHABLE, values); } /** * Fetch records that have <code>brewery_db_id BETWEEN lowerInclusive AND upperInclusive</code> */ public List<com.cellarhq.generated.tables.pojos.Category> fetchRangeOfBreweryDbId(String lowerInclusive, String upperInclusive) { return fetchRange(Category.CATEGORY.BREWERY_DB_ID, lowerInclusive, upperInclusive); } /** * Fetch records that have <code>brewery_db_id IN (values)</code> */ public List<com.cellarhq.generated.tables.pojos.Category> fetchByBreweryDbId(String... values) { return fetch(Category.CATEGORY.BREWERY_DB_ID, values); } /** * Fetch records that have <code>brewery_db_last_updated BETWEEN lowerInclusive AND upperInclusive</code> */ public List<com.cellarhq.generated.tables.pojos.Category> fetchRangeOfBreweryDbLastUpdated(LocalDateTime lowerInclusive, LocalDateTime upperInclusive) { return fetchRange(Category.CATEGORY.BREWERY_DB_LAST_UPDATED, lowerInclusive, upperInclusive); } /** * Fetch records that have <code>brewery_db_last_updated IN (values)</code> */ public List<com.cellarhq.generated.tables.pojos.Category> fetchByBreweryDbLastUpdated(LocalDateTime... values) { return fetch(Category.CATEGORY.BREWERY_DB_LAST_UPDATED, values); } /** * Fetch records that have <code>created_date BETWEEN lowerInclusive AND upperInclusive</code> */ public List<com.cellarhq.generated.tables.pojos.Category> fetchRangeOfCreatedDate(LocalDateTime lowerInclusive, LocalDateTime upperInclusive) { return fetchRange(Category.CATEGORY.CREATED_DATE, lowerInclusive, upperInclusive); } /** * Fetch records that have <code>created_date IN (values)</code> */ public List<com.cellarhq.generated.tables.pojos.Category> fetchByCreatedDate(LocalDateTime... values) { return fetch(Category.CATEGORY.CREATED_DATE, values); } /** * Fetch records that have <code>modified_date BETWEEN lowerInclusive AND upperInclusive</code> */ public List<com.cellarhq.generated.tables.pojos.Category> fetchRangeOfModifiedDate(LocalDateTime lowerInclusive, LocalDateTime upperInclusive) { return fetchRange(Category.CATEGORY.MODIFIED_DATE, lowerInclusive, upperInclusive); } /** * Fetch records that have <code>modified_date IN (values)</code> */ public List<com.cellarhq.generated.tables.pojos.Category> fetchByModifiedDate(LocalDateTime... values) { return fetch(Category.CATEGORY.MODIFIED_DATE, values); } /** * Fetch records that have <code>data BETWEEN lowerInclusive AND upperInclusive</code> */ public List<com.cellarhq.generated.tables.pojos.Category> fetchRangeOfData(JSON lowerInclusive, JSON upperInclusive) { return fetchRange(Category.CATEGORY.DATA, lowerInclusive, upperInclusive); } /** * Fetch records that have <code>data IN (values)</code> */ public List<com.cellarhq.generated.tables.pojos.Category> fetchByData(JSON... values) { return fetch(Category.CATEGORY.DATA, values); } }
mit
zhoujiagen/giant-data-analysis
data-models/datamodel-logic/src/main/java/com/spike/giantdataanalysis/model/logic/relational/interpreter/core/RelationalInterpreterEnum.java
249
package com.spike.giantdataanalysis.model.logic.relational.interpreter.core; import com.spike.giantdataanalysis.model.logic.relational.core.Literal; /** 解释器枚举标记接口. */ public interface RelationalInterpreterEnum extends Literal { }
mit
zgqq/mah
mah-plugin/src/main/java/mah/plugin/support/orgnote/source/Sort.java
1382
/** * MIT License * * Copyright (c) 2017 zgqq * * 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 mah.plugin.support.orgnote.source; import mah.plugin.support.orgnote.entity.NodeEntity; import java.util.List; /** * Created by zgq on 10/1/16. */ public interface Sort { NodeEntity getNextReviewNote(List<NodeEntity> nodeEntityList); }
mit
dumrelu/QuizMaster
src/com/quizmaster/components/Question.java
4386
package com.quizmaster.components; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; public class Question extends Component<Answer> { private static final long serialVersionUID = 1L; //The answers that are going to be displayed private List<Answer> displayedAnswers; //The chosen answers private Set<Answer> pickedAnswers; //Number of questions to be displayed private int answers; //Number of correct answers in the displayed answers private int correctAnswers; /*------------------------------------------------*/ /** * Constructs a question object with the given parameters * @param question The text to be displayed * @param answers Number of questions to be displayed * @param correctAnswers Number of correct answers in the displayed answers */ protected Question(String question, int answers, int correctAnswers) { super(question); this.answers = answers; this.correctAnswers = correctAnswers; this.displayedAnswers = new ArrayList<Answer>(); this.pickedAnswers = new HashSet<Answer>(); } /** * Constructs a question object with the given parameters * @param question The text to be displayed * @param nAnswers Number of questions to be displayed * @param correctAnswers Number of correct answers in the displayed answers * @param answers Initial answer pool */ public Question(String question, List<Answer> answers, int nAnswers, int correctAnswers) { this(question, nAnswers, correctAnswers); this.add(answers); shuffle(); } /** * Resets the pickedAnswers and displayedAnswers. Reconstructs the displayedAnswers by picking random correct * answers from the answers pool and completing it with wrong ones. */ public void shuffle() { //Clear previous data pickedAnswers.clear(); displayedAnswers.clear(); List<Answer> correct = new ArrayList<Answer>(), wrong = new ArrayList<Answer>(); List<Answer> answers = this.getComponents(); for(Answer answer : answers) if(answer.isCorrect()) correct.add(answer); else wrong.add(answer); //Shuffle lists Collections.shuffle(correct); Collections.shuffle(wrong); //Add the corresponding number of correct answer to the displayed questions int i; for(i = 0; i < correctAnswers && correct.size() != 0; i++, correct.remove(0)) displayedAnswers.add(correct.get(0)); //Complete the rest with wrong answers for(;i < this.answers && wrong.size() != 0; i++, wrong.remove(0)) displayedAnswers.add(wrong.get(0)); //Shuffle again Collections.shuffle(displayedAnswers); } /** * Adds the answer in the pickedAnswers unique sets if the answer is contained in the displayAnswers list * and the maximum number of answers was not exceeded * @param answer The chosen answer * @return True if added to pickedAnswers set, false otherwise */ public boolean answer(Answer answer) { if(!displayedAnswers.contains(answer) || pickedAnswers.size() >= answers) return false; return pickedAnswers.add(answer); } /** * Removes an answer from the pickedAnswers set * @param answer The chosen answer * @return True if the answer was removed from the pickedAnswers set, false otherwise */ public boolean unanswer(Answer answer) { return pickedAnswers.remove(answer); } /** * @return The answers that are going to be displayed */ public List<Answer> getDisplayedAnswers() { return displayedAnswers; } /** * @return The chosen answers */ public Set<Answer> getPickedAnswers() { return pickedAnswers; } /** * Indicates if the correct number of questions has been chosen * @return True if enough chosen, false otherwise */ public boolean isAnswered() { return (pickedAnswers.size() == correctAnswers); } /** * Indicates if the chosen answers are the correct ones or not * @return True if the question was answered correctly, false otherwise */ public boolean isCorrect() { if(!isAnswered()) return false; for(Answer answer : pickedAnswers) if(!answer.isCorrect()) return false; return true; } public String toString() { String result = getText() + "(" + correctAnswers + " answers)" + "\n"; char index = 'a'; for(Answer answer : displayedAnswers) result += "\t" + index++ + ") " + answer + "\n"; return result; } }
mit
GLAProject/Auction
DeliveryClient/src/main/java/com/ul/deliveryclient/Main.java
5219
package com.ul.deliveryclient; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.Destination; import javax.jms.MessageConsumer; import javax.jms.MessageProducer; import javax.jms.ObjectMessage; import javax.jms.Session; import javax.naming.Context; import javax.naming.InitialContext; /** * Enterprise Application Client main class. * */ public class Main { private static List<Long> unprocessedRequests = new ArrayList<>(); public static void main( String[] args ) { // // check that four numbers are given as parameter // if(args.length<4) { // System.out.println("Usage : "+args[0]+" reportId, weight, height, width"); // System.exit(1); // } // // long[] values=new long[4]; // // for(int i=1;i<args.length;i++) // values[i-1]=Long.parseLong(args[i]); Scanner scanner = new Scanner(System.in); try { // get the required information from the context Context context=new InitialContext(); ConnectionFactory connectionFactory=(ConnectionFactory) context.lookup("jms/QueueConnectionFactory"); Destination replyQueue = (Destination)context.lookup("DeliveryReplyQueue"); Destination requestQueue = (Destination)context.lookup("DeliveryRequestQueue"); // create the connection Connection connection = connectionFactory.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer messageProducer = session.createProducer(replyQueue); MessageConsumer messageConsumer = session.createConsumer(requestQueue); messageConsumer.setMessageListener(new DeliveryRequestMessageListener()); connection.start(); System.out.println(""); System.out.println(""); System.out.println("==============================================================================="); System.out.println(" INSTRUCTIONS:"); System.out.println(" The client will now start listening for delivery requests"); System.out.println(" At any time, enter -1 for a list of unprocessed requests"); System.out.println(" enter 0 to exit"); System.out.println(" enter the order id to confirm the delivery"); System.out.println("==============================================================================="); System.out.println(""); System.out.println(""); while(true){ System.out.print("Enter command: "); long input = scanner.nextLong(); if(input < 0) { printUnprocessedRequests(); System.out.println("==============================================================================="); } else if (input == 0) { break; } else { if(!hasRequest(input)) { System.out.println(""); System.out.println("The ID does not seem to correspond to an active request. Enter -1 to get list of requests."); System.out.println("==============================================================================="); } else { // create and send the message ObjectMessage message = session.createObjectMessage(); message.setObject(input); messageProducer.send(message); removeRequest(input); System.out.println(""); System.out.println("Confirmation message sent for the bill of order with id: " + input); printUnprocessedRequests(); System.out.println("==============================================================================="); } } } session.close(); connection.close(); connection = null; } catch (Exception e) { e.printStackTrace(); } } public static void printUnprocessedRequests() { if (unprocessedRequests.isEmpty()) { System.out.println(""); System.out.println("No unprocessed requests"); } else { System.out.println(""); System.out.println("Unprocessed request IDs: "); for(Long element : unprocessedRequests) { System.out.println(element.toString()); } } } public static void addRequest(Long id) { unprocessedRequests.add(id); } public static void removeRequest(Long id) { unprocessedRequests.remove(id); } public static boolean hasRequest(Long id) { return unprocessedRequests.contains(id); } }
mit
lotaris/rox-commons-maven-plugin
src/main/java/org/twdata/maven/mojoexecutor/MojoExecutor.java
9298
/* * Copyright 2008-2011 Don Brown * * 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.twdata.maven.mojoexecutor; import org.apache.maven.execution.MavenSession; import org.apache.maven.model.Plugin; import org.apache.maven.plugin.BuildPluginManager; import org.apache.maven.plugin.InvalidPluginDescriptorException; import org.apache.maven.plugin.MojoExecution; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugin.PluginConfigurationException; import org.apache.maven.plugin.PluginDescriptorParsingException; import org.apache.maven.plugin.PluginManagerException; import org.apache.maven.plugin.PluginNotFoundException; import org.apache.maven.plugin.PluginResolutionException; import org.apache.maven.plugin.descriptor.MojoDescriptor; import org.apache.maven.plugin.descriptor.PluginDescriptor; import org.apache.maven.project.MavenProject; import org.codehaus.plexus.util.xml.Xpp3Dom; import org.codehaus.plexus.util.xml.Xpp3DomUtils; import static org.twdata.maven.mojoexecutor.PlexusConfigurationUtils.toXpp3Dom; /** * Executes an arbitrary mojo using a fluent interface. This is meant to be executed within the * context of a Maven 2 mojo. * <p/> * Here is an execution that invokes the dependency plugin: * <pre> * executeMojo( * plugin( * groupId("org.apache.maven.plugins"), * artifactId("maven-dependency-plugin"), * version("2.0") * ), * goal("copy-dependencies"), * configuration( * element( * name("outputDirectory"), "${project.build.directory}/foo") * ), * executionEnvironment( * project, * session, * pluginManager * ) * ); * </pre> */ public class MojoExecutor { /** * Entry point for executing a mojo * * @param plugin The plugin to execute * @param goal The goal to execute * @param configuration The execution configuration * @param env The execution environment * @throws MojoExecutionException If there are any exceptions locating or executing the mojo */ public static void executeMojo(Plugin plugin, String goal, Xpp3Dom configuration, ExecutionEnvironment env) throws MojoExecutionException { if (configuration == null) { throw new NullPointerException("configuration may not be null"); } try { String executionId = null; if (goal != null && goal.length() > 0 && goal.indexOf('#') > -1) { int pos = goal.indexOf('#'); executionId = goal.substring(pos + 1); goal = goal.substring(0, pos); } MavenSession session = env.getMavenSession(); PluginDescriptor pluginDescriptor = env.getPluginManager().loadPlugin( plugin, env.getMavenProject().getRemotePluginRepositories(), session.getRepositorySession()); MojoDescriptor mojoDescriptor = pluginDescriptor.getMojo(goal); if (mojoDescriptor == null) { throw new MojoExecutionException("Could not find goal '" + goal + "' in plugin " + plugin.getGroupId() + ":" + plugin.getArtifactId() + ":" + plugin.getVersion()); } MojoExecution exec = mojoExecution(mojoDescriptor, executionId, configuration); env.getPluginManager().executeMojo(session, exec); } catch (PluginNotFoundException | PluginResolutionException | PluginDescriptorParsingException | InvalidPluginDescriptorException | MojoExecutionException | MojoFailureException | PluginConfigurationException | PluginManagerException e) { throw new MojoExecutionException("Unable to execute mojo", e); } } private static MojoExecution mojoExecution(MojoDescriptor mojoDescriptor, String executionId, Xpp3Dom configuration) { if (executionId != null) { return new MojoExecution(mojoDescriptor, executionId); } else { configuration = Xpp3DomUtils.mergeXpp3Dom(configuration, toXpp3Dom(mojoDescriptor.getMojoConfiguration())); return new MojoExecution(mojoDescriptor, configuration); } } /** * Constructs the {@link ExecutionEnvironment} instance fluently * * @param mavenProject The current Maven project * @param mavenSession The current Maven session * @param pluginManager The Build plugin manager * @return The execution environment * @throws NullPointerException if mavenProject, mavenSession or pluginManager are null */ public static ExecutionEnvironment executionEnvironment(MavenProject mavenProject, MavenSession mavenSession, BuildPluginManager pluginManager) { return new ExecutionEnvironment(mavenProject, mavenSession, pluginManager); } /** * Builds the configuration for the goal using Elements * * @param elements A list of elements for the configuration section * @return The elements transformed into the Maven-native XML format */ public static Xpp3Dom configuration(Element... elements) { Xpp3Dom dom = new Xpp3Dom("configuration"); for (Element e : elements) { dom.addChild(e.toDom()); } return dom; } /** * Defines the plugin without its version * * @param groupId The group id * @param artifactId The artifact id * @return The plugin instance */ public static Plugin plugin(String groupId, String artifactId) { return plugin(groupId, artifactId, null); } /** * Defines a plugin * * @param groupId The group id * @param artifactId The artifact id * @param version The plugin version * @return The plugin instance */ public static Plugin plugin(String groupId, String artifactId, String version) { Plugin plugin = new Plugin(); plugin.setArtifactId(artifactId); plugin.setGroupId(groupId); plugin.setVersion(version); return plugin; } /** * Wraps the group id string in a more readable format * * @param groupId The value * @return The value */ public static String groupId(String groupId) { return groupId; } /** * Wraps the artifact id string in a more readable format * * @param artifactId The value * @return The value */ public static String artifactId(String artifactId) { return artifactId; } /** * Wraps the version string in a more readable format * * @param version The value * @return The value */ public static String version(String version) { return version; } /** * Wraps the goal string in a more readable format * * @param goal The value * @return The value */ public static String goal(String goal) { return goal; } /** * Wraps the element name string in a more readable format * * @param name The value * @return The value */ public static String name(String name) { return name; } /** * Constructs the element with a textual body * * @param name The element name * @param value The element text value * @return The element object */ public static Element element(String name, String value) { return new Element(name, value); } /** * Constructs the element containing child elements * * @param name The element name * @param elements The child elements * @return The Element object */ public static Element element(String name, Element... elements) { return new Element(name, elements); } /** * Element wrapper class for configuration elements */ public static class Element { private final Element[] children; private final String name; private final String text; public Element(String name, Element... children) { this(name, null, children); } public Element(String name, String text, Element... children) { this.name = name; this.text = text; this.children = children; } public Xpp3Dom toDom() { Xpp3Dom dom = new Xpp3Dom(name); if (text != null) { dom.setValue(text); } for (Element e : children) { dom.addChild(e.toDom()); } return dom; } } /** * Collects Maven execution information */ public static class ExecutionEnvironment { private final MavenProject mavenProject; private final MavenSession mavenSession; private final BuildPluginManager pluginManager; public ExecutionEnvironment(MavenProject mavenProject, MavenSession mavenSession, BuildPluginManager pluginManager) { if (mavenProject == null) { throw new NullPointerException("mavenProject may not be null"); } if (mavenSession == null) { throw new NullPointerException("mavenSession may not be null"); } if (pluginManager == null) { throw new NullPointerException("pluginManager may not be null"); } this.mavenProject = mavenProject; this.mavenSession = mavenSession; this.pluginManager = pluginManager; } public MavenProject getMavenProject() { return mavenProject; } public MavenSession getMavenSession() { return mavenSession; } public BuildPluginManager getPluginManager() { return pluginManager; } } }
mit
achacha/SomeWebCardGame
src/main/java/org/achacha/webcardgame/game/logic/EventType.java
297
package org.achacha.webcardgame.game.logic; public enum EventType { Start, CardStart, CardHealth, CardAttack, CardAttackCrit, CardAttackAbsorb, CardAttackCritAbsorb, CardDeath, PlayerWin, PlayerDraw, PlayerLose, StickerHeal, StickerDamage }
mit
bhgomes/jaql
src/main/java/bhgomes/jaql/logging/STDOUT.java
608
package bhgomes.jaql.logging; import java.util.logging.StreamHandler; /** * Singleton object for System.out as a StreamHandler * * @author Brandon Gomes (bhgomes) */ public final class STDOUT extends StreamHandler { /** * Singleton instance */ private static final STDOUT instance = new STDOUT(); /** * Default constructor of the singleton instance */ private STDOUT() { this.setOutputStream(System.out); } /** * @return instance of the singleton */ public static final STDOUT getInstance() { return STDOUT.instance; } }
mit
venkatramanm/common
src/main/java/com/venky/core/security/SignatureComputer.java
2127
package com.venky.core.security; import com.venky.core.util.ObjectUtil; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import java.util.Base64; public class SignatureComputer { public static void main(String[] args) throws Exception{ Options options = new Options(); Option help = new Option("h","help",false, "print this message"); Option url = new Option("u","url", true,"Url called"); url.setRequired(true); Option privateKey = new Option("b64pvk","base64privatekey", true,"Private Key to Sign with"); privateKey.setRequired(true); Option data = new Option("d","data", true,"Data posted to the url"); options.addOption(help); options.addOption(url); options.addOption(privateKey); options.addOption(data); CommandLineParser parser = new DefaultParser(); HelpFormatter formatter = new HelpFormatter(); CommandLine cmd = null; try { cmd = parser.parse(options,args); }catch (Exception ex){ formatter.printHelp(SignatureComputer.class.getName(),options); System.exit(1); } StringBuilder payload = new StringBuilder(); String sUrl = cmd.getOptionValue("url"); if (sUrl.startsWith("http://")){ sUrl = sUrl.substring("http://".length()); sUrl = sUrl.substring(sUrl.indexOf("/")); } payload.append(sUrl); String sData = cmd.getOptionValue("data"); if (!ObjectUtil.isVoid(sData)){ payload.append("|"); payload.append(sData); } String sign = Crypt.getInstance().generateSignature(Base64.getEncoder().encodeToString(payload.toString().getBytes()),Crypt.SIGNATURE_ALGO, Crypt.getInstance().getPrivateKey(Crypt.KEY_ALGO,cmd.getOptionValue("base64privatekey"))); System.out.println(sign); } }
mit
bagage/bootstraped-multi-test-results-report
bootstraped-multi-test-results-report/src/main/java/com/github/bogdanlivadariu/jenkins/reporting/testng/TestNGTestReportBaseAction.java
1161
package com.github.bogdanlivadariu.jenkins.reporting.testng; import hudson.FilePath; import hudson.model.Action; import hudson.model.DirectoryBrowserSupport; import java.io.File; import java.io.IOException; import javax.servlet.ServletException; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; public abstract class TestNGTestReportBaseAction implements Action { public String getUrlName() { return "testng-reports-with-handlebars"; } public String getDisplayName() { return "View TestNG Reports"; } public String getIconFileName() { return "/plugin/bootstraped-multi-test-results-report/testng.png"; } public void doDynamic(StaplerRequest req, StaplerResponse rsp) throws IOException, ServletException { DirectoryBrowserSupport dbs = new DirectoryBrowserSupport(this, new FilePath(this.dir()), this.getTitle(), "graph.gif", false); dbs.setIndexFileName("testsByClassOverview.html"); dbs.generateResponse(req, rsp, this); } protected abstract String getTitle(); protected abstract File dir(); }
mit
bitDecayGames/LudumDare38
src/main/java/com/bitdecay/game/ui/Tray.java
2669
package com.bitdecay.game.ui; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.scenes.scene2d.Group; import com.badlogic.gdx.scenes.scene2d.actions.Actions; import com.badlogic.gdx.scenes.scene2d.actions.MoveToAction; import com.bitdecay.game.util.Quest; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; import java.util.Optional; import static com.badlogic.gdx.scenes.scene2d.actions.Actions.moveTo; public class Tray extends Group { protected Logger log = LogManager.getLogger(this.getClass()); public TrayCard taskCard; public ConversationDialog dialog; private TaskList taskList; private boolean isHidden = false; public Tray(TaskList taskList) { super(); this.taskList = taskList; Vector2 screenSize = new Vector2(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); Group taskCardGroup = new Group(); taskCard = new TrayCard(); taskCard.setPosition(0, 0); taskCardGroup.addActor(taskCard); taskCardGroup.setScale(0.7f); addActor(taskCardGroup); dialog = new ConversationDialog(); dialog.setPosition(screenSize.x * 0.2125f, 0); addActor(dialog); } @Override public void act(float delta) { super.act(delta); Optional<Quest> curQuest = taskList.currentQuest(); if (curQuest.isPresent()){ Quest q = curQuest.get(); if (q != taskCard.quest) { taskCard.quest = q; showTray(); } } else if (!isHidden) hideTray(); } public void showTray(){ log.info("Show tray"); MoveToAction move = moveTo(getX(), Gdx.graphics.getHeight() * 1.01f); move.setDuration(0.25f); addAction(Actions.sequence(Actions.run(()-> { if(taskCard.quest != null && taskCard.quest.currentZone().isPresent()) { taskCard.quest.currentZone().ifPresent(zone -> { dialog.setPersonName(taskCard.quest.personName); dialog.setText(zone.flavorText); }); } else { dialog.setPersonName(null); dialog.setText(""); } }), move)); isHidden = false; } public void hideTray(){ log.info("Hide tray"); MoveToAction move = moveTo(getX(), 0); move.setDuration(0.25f); addAction(Actions.sequence(move, Actions.run(()-> taskCard.quest = null))); isHidden = true; } public void toggle(){ if (isHidden) showTray(); else hideTray(); } }
mit
lcmatrix/logoquiz
src/main/java/app/LogoquizMainApp.java
1350
package app; import java.util.ResourceBundle; import control.MainController; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.layout.VBox; import javafx.stage.Stage; /** * Main class for Logoquiz app. */ public class LogoquizMainApp extends Application { /** * Root layout of the application. */ private VBox rootLayout; /** * Primary Stage. */ private Stage primaryStage; /** * main() method. * @param args arguments */ public static final void main(String[] args) { launch(args); } @Override public void start(Stage stage) throws Exception { primaryStage = stage; FXMLLoader loader = new FXMLLoader(); loader.setLocation(getClass().getResource("/fxml/rootLayout.fxml")); loader.setResources(ResourceBundle.getBundle("i18n/message")); rootLayout = loader.load(); MainController controller = loader.getController(); controller.setMainApp(this); primaryStage.setTitle("Logoquiz"); primaryStage.setScene(new Scene(rootLayout)); primaryStage.show(); } /** * Getter for primaryStage. * * @return primaryStage */ public Stage getPrimaryStage() { return primaryStage; } }
mit
Azure/azure-sdk-for-java
sdk/security/azure-resourcemanager-security/src/main/java/com/azure/resourcemanager/security/fluent/models/IoTSecuritySolutionModelInner.java
12547
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.security.fluent.models; import com.azure.core.annotation.Fluent; import com.azure.core.annotation.JsonFlatten; import com.azure.core.management.ProxyResource; import com.azure.core.management.SystemData; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.security.models.AdditionalWorkspacesProperties; import com.azure.resourcemanager.security.models.DataSource; import com.azure.resourcemanager.security.models.ExportData; import com.azure.resourcemanager.security.models.RecommendationConfigurationProperties; import com.azure.resourcemanager.security.models.SecuritySolutionStatus; import com.azure.resourcemanager.security.models.UnmaskedIpLoggingStatus; import com.azure.resourcemanager.security.models.UserDefinedResourcesProperties; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; import java.util.Map; /** IoT Security solution configuration and resource information. */ @JsonFlatten @Fluent public class IoTSecuritySolutionModelInner extends ProxyResource { @JsonIgnore private final ClientLogger logger = new ClientLogger(IoTSecuritySolutionModelInner.class); /* * The resource location. */ @JsonProperty(value = "location") private String location; /* * Azure Resource Manager metadata containing createdBy and modifiedBy * information. */ @JsonProperty(value = "systemData", access = JsonProperty.Access.WRITE_ONLY) private SystemData systemData; /* * Workspace resource ID */ @JsonProperty(value = "properties.workspace") private String workspace; /* * Resource display name. */ @JsonProperty(value = "properties.displayName") private String displayName; /* * Status of the IoT Security solution. */ @JsonProperty(value = "properties.status") private SecuritySolutionStatus status; /* * List of additional options for exporting to workspace data. */ @JsonProperty(value = "properties.export") private List<ExportData> export; /* * Disabled data sources. Disabling these data sources compromises the * system. */ @JsonProperty(value = "properties.disabledDataSources") private List<DataSource> disabledDataSources; /* * IoT Hub resource IDs */ @JsonProperty(value = "properties.iotHubs") private List<String> iotHubs; /* * Properties of the IoT Security solution's user defined resources. */ @JsonProperty(value = "properties.userDefinedResources") private UserDefinedResourcesProperties userDefinedResources; /* * List of resources that were automatically discovered as relevant to the * security solution. */ @JsonProperty(value = "properties.autoDiscoveredResources", access = JsonProperty.Access.WRITE_ONLY) private List<String> autoDiscoveredResources; /* * List of the configuration status for each recommendation type. */ @JsonProperty(value = "properties.recommendationsConfiguration") private List<RecommendationConfigurationProperties> recommendationsConfiguration; /* * Unmasked IP address logging status */ @JsonProperty(value = "properties.unmaskedIpLoggingStatus") private UnmaskedIpLoggingStatus unmaskedIpLoggingStatus; /* * List of additional workspaces */ @JsonProperty(value = "properties.additionalWorkspaces") private List<AdditionalWorkspacesProperties> additionalWorkspaces; /* * Resource tags */ @JsonProperty(value = "tags") private Map<String, String> tags; /** * Get the location property: The resource location. * * @return the location value. */ public String location() { return this.location; } /** * Set the location property: The resource location. * * @param location the location value to set. * @return the IoTSecuritySolutionModelInner object itself. */ public IoTSecuritySolutionModelInner withLocation(String location) { this.location = location; return this; } /** * Get the systemData property: Azure Resource Manager metadata containing createdBy and modifiedBy information. * * @return the systemData value. */ public SystemData systemData() { return this.systemData; } /** * Get the workspace property: Workspace resource ID. * * @return the workspace value. */ public String workspace() { return this.workspace; } /** * Set the workspace property: Workspace resource ID. * * @param workspace the workspace value to set. * @return the IoTSecuritySolutionModelInner object itself. */ public IoTSecuritySolutionModelInner withWorkspace(String workspace) { this.workspace = workspace; return this; } /** * Get the displayName property: Resource display name. * * @return the displayName value. */ public String displayName() { return this.displayName; } /** * Set the displayName property: Resource display name. * * @param displayName the displayName value to set. * @return the IoTSecuritySolutionModelInner object itself. */ public IoTSecuritySolutionModelInner withDisplayName(String displayName) { this.displayName = displayName; return this; } /** * Get the status property: Status of the IoT Security solution. * * @return the status value. */ public SecuritySolutionStatus status() { return this.status; } /** * Set the status property: Status of the IoT Security solution. * * @param status the status value to set. * @return the IoTSecuritySolutionModelInner object itself. */ public IoTSecuritySolutionModelInner withStatus(SecuritySolutionStatus status) { this.status = status; return this; } /** * Get the export property: List of additional options for exporting to workspace data. * * @return the export value. */ public List<ExportData> export() { return this.export; } /** * Set the export property: List of additional options for exporting to workspace data. * * @param export the export value to set. * @return the IoTSecuritySolutionModelInner object itself. */ public IoTSecuritySolutionModelInner withExport(List<ExportData> export) { this.export = export; return this; } /** * Get the disabledDataSources property: Disabled data sources. Disabling these data sources compromises the system. * * @return the disabledDataSources value. */ public List<DataSource> disabledDataSources() { return this.disabledDataSources; } /** * Set the disabledDataSources property: Disabled data sources. Disabling these data sources compromises the system. * * @param disabledDataSources the disabledDataSources value to set. * @return the IoTSecuritySolutionModelInner object itself. */ public IoTSecuritySolutionModelInner withDisabledDataSources(List<DataSource> disabledDataSources) { this.disabledDataSources = disabledDataSources; return this; } /** * Get the iotHubs property: IoT Hub resource IDs. * * @return the iotHubs value. */ public List<String> iotHubs() { return this.iotHubs; } /** * Set the iotHubs property: IoT Hub resource IDs. * * @param iotHubs the iotHubs value to set. * @return the IoTSecuritySolutionModelInner object itself. */ public IoTSecuritySolutionModelInner withIotHubs(List<String> iotHubs) { this.iotHubs = iotHubs; return this; } /** * Get the userDefinedResources property: Properties of the IoT Security solution's user defined resources. * * @return the userDefinedResources value. */ public UserDefinedResourcesProperties userDefinedResources() { return this.userDefinedResources; } /** * Set the userDefinedResources property: Properties of the IoT Security solution's user defined resources. * * @param userDefinedResources the userDefinedResources value to set. * @return the IoTSecuritySolutionModelInner object itself. */ public IoTSecuritySolutionModelInner withUserDefinedResources(UserDefinedResourcesProperties userDefinedResources) { this.userDefinedResources = userDefinedResources; return this; } /** * Get the autoDiscoveredResources property: List of resources that were automatically discovered as relevant to the * security solution. * * @return the autoDiscoveredResources value. */ public List<String> autoDiscoveredResources() { return this.autoDiscoveredResources; } /** * Get the recommendationsConfiguration property: List of the configuration status for each recommendation type. * * @return the recommendationsConfiguration value. */ public List<RecommendationConfigurationProperties> recommendationsConfiguration() { return this.recommendationsConfiguration; } /** * Set the recommendationsConfiguration property: List of the configuration status for each recommendation type. * * @param recommendationsConfiguration the recommendationsConfiguration value to set. * @return the IoTSecuritySolutionModelInner object itself. */ public IoTSecuritySolutionModelInner withRecommendationsConfiguration( List<RecommendationConfigurationProperties> recommendationsConfiguration) { this.recommendationsConfiguration = recommendationsConfiguration; return this; } /** * Get the unmaskedIpLoggingStatus property: Unmasked IP address logging status. * * @return the unmaskedIpLoggingStatus value. */ public UnmaskedIpLoggingStatus unmaskedIpLoggingStatus() { return this.unmaskedIpLoggingStatus; } /** * Set the unmaskedIpLoggingStatus property: Unmasked IP address logging status. * * @param unmaskedIpLoggingStatus the unmaskedIpLoggingStatus value to set. * @return the IoTSecuritySolutionModelInner object itself. */ public IoTSecuritySolutionModelInner withUnmaskedIpLoggingStatus(UnmaskedIpLoggingStatus unmaskedIpLoggingStatus) { this.unmaskedIpLoggingStatus = unmaskedIpLoggingStatus; return this; } /** * Get the additionalWorkspaces property: List of additional workspaces. * * @return the additionalWorkspaces value. */ public List<AdditionalWorkspacesProperties> additionalWorkspaces() { return this.additionalWorkspaces; } /** * Set the additionalWorkspaces property: List of additional workspaces. * * @param additionalWorkspaces the additionalWorkspaces value to set. * @return the IoTSecuritySolutionModelInner object itself. */ public IoTSecuritySolutionModelInner withAdditionalWorkspaces( List<AdditionalWorkspacesProperties> additionalWorkspaces) { this.additionalWorkspaces = additionalWorkspaces; return this; } /** * Get the tags property: Resource tags. * * @return the tags value. */ public Map<String, String> tags() { return this.tags; } /** * Set the tags property: Resource tags. * * @param tags the tags value to set. * @return the IoTSecuritySolutionModelInner object itself. */ public IoTSecuritySolutionModelInner withTags(Map<String, String> tags) { this.tags = tags; return this; } /** * Validates the instance. * * @throws IllegalArgumentException thrown if the instance is not valid. */ public void validate() { if (userDefinedResources() != null) { userDefinedResources().validate(); } if (recommendationsConfiguration() != null) { recommendationsConfiguration().forEach(e -> e.validate()); } if (additionalWorkspaces() != null) { additionalWorkspaces().forEach(e -> e.validate()); } } }
mit
purityooo/unwatermark
src/main/java/ooo/purity/unwatermark/gui/ViewFrame.java
7117
package ooo.purity.unwatermark.gui; import ooo.purity.unwatermark.Mode; import ooo.purity.unwatermark.ModeFactory; import ooo.purity.unwatermark.mode.MFSA; import javax.swing.*; import java.awt.*; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.awt.image.BufferedImage; import java.awt.print.PrinterException; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; class ViewFrame extends JFrame { private static final long serialVersionUID = -908237280313491890L; private final JFileChooser openChooser = new JFileChooser(); private final JFileChooser saveChooser = new JFileChooser(); private final ImagePanel imagePanel = new ImagePanel(); private final JScrollPane scrollPane = new JScrollPane(imagePanel, ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); private final DefaultListModel<Document> listModel = new DefaultListModel<>(); final JList<Document> list = new JList<>(listModel); private class Document { private final File file; private BufferedImage image; private Mode mode = ModeFactory.create(MFSA.NAME); private Document(final File file) throws IOException { this.file = file; image = mode.apply(file); } private void show() { imagePanel.setName(file.getName()); imagePanel.setImage(image); imagePanel.setBounds(0, 0, scrollPane.getWidth() - scrollPane.getVerticalScrollBar().getWidth(), scrollPane.getHeight() - scrollPane.getHorizontalScrollBar().getHeight()); imagePanel.setVisible(true); imagePanel.repaint(); } @Override public String toString() { return file.getName(); } } private class ViewTransferHandler extends TransferHandler { private static final long serialVersionUID = 2695692501459052660L; @Override public boolean canImport(final TransferSupport support) { if (!support.isDataFlavorSupported(DataFlavor.javaFileListFlavor)) { return false; } final boolean copySupported = (COPY & support.getSourceDropActions()) == COPY; if (!copySupported) { return false; } support.setDropAction(COPY); return true; } @Override @SuppressWarnings({"unchecked", "serial"}) public boolean importData(final TransferSupport support) { if (!canImport(support)) { return false; } final Transferable transferable = support.getTransferable(); try { final java.util.List<File> fileList = (java.util.List<File>) transferable.getTransferData(DataFlavor.javaFileListFlavor); return unwatermark(fileList.toArray(new File[fileList.size()])); } catch (final UnsupportedFlavorException | IOException e) { return false; } } } ViewFrame() { super("Unwatermark"); final JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, list, scrollPane); splitPane.setDividerLocation(120); getContentPane().add(splitPane); list.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION); list.addListSelectionListener(e -> { if (e.getValueIsAdjusting()) { return; } final Document document = list.getSelectedValue(); if (document != null) { document.show(); } }); final TransferHandler transferHandler = new ViewTransferHandler(); setTransferHandler(transferHandler); setBackground(Color.LIGHT_GRAY); imagePanel.setTransferHandler(transferHandler); imagePanel.setLayout(new BorderLayout()); imagePanel.setBackground(Color.LIGHT_GRAY); scrollPane.setBackground(Color.LIGHT_GRAY); scrollPane.addComponentListener(new ComponentListener() { @Override public void componentResized(ComponentEvent e) { imagePanel.setBounds(0, 0, scrollPane.getWidth() - scrollPane.getVerticalScrollBar().getWidth(), scrollPane.getHeight() - scrollPane.getHorizontalScrollBar().getHeight()); } @Override public void componentMoved(ComponentEvent e) { } @Override public void componentShown(ComponentEvent e) { } @Override public void componentHidden(ComponentEvent e) { } }); pack(); initialiseMenuBar(); openChooser.setMultiSelectionEnabled(true); openChooser.setFileSelectionMode(JFileChooser.FILES_ONLY); saveChooser.setMultiSelectionEnabled(false); } private void initialiseMenuBar() { final JMenuBar menuBar = new JMenuBar(); JMenu menu; menu = new JMenu("File"); menu.add(new JMenuItem("Open...")).addActionListener(e -> { if (openChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { unwatermark(openChooser.getSelectedFiles()); } }); menu.add(new JMenuItem("Save...")).addActionListener(e -> { Document document = list.getSelectedValue(); if (null == document && listModel.size() > 0) { document = listModel.getElementAt(0); } if (null == document) { return; } saveChooser.setSelectedFile(document.file); if (saveChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION) { unwatermark(document, saveChooser.getSelectedFile()); } }); menu.add(new JMenuItem("Print")).addActionListener(e -> { Document document = list.getSelectedValue(); if (null == document && listModel.size() > 0) { document = listModel.getElementAt(0); } if (null == document) { return; } try { document.mode.print(document.file); } catch (final IOException | PrinterException exc) { displayException(exc); } }); menuBar.add(menu); menu = new JMenu("Help"); menu.add(new JMenuItem("About")).addActionListener(e -> { JOptionPane.showMessageDialog(imagePanel, "Unwatermark\nmattcg@gmail.com"); }); menuBar.add(menu); setJMenuBar(menuBar); } private boolean unwatermark(final File... files) { try { Document document = null; for (File file : files) { document = new Document(file); listModel.add(listModel.size(), document); } if (null != document) { document.show(); } } catch (final IOException e) { displayException(e); return false; } return true; } private void unwatermark(final Document input, final File output) { try { input.mode.apply(input.file, output); } catch (final IOException e) { displayException(e); } } @SuppressWarnings("serial") private void displayException(final Exception e) { final JPanel panel = new JPanel(); final JPanel labelPanel = new JPanel(new BorderLayout()); final StringWriter writer = new StringWriter(); labelPanel.add(new JLabel("Unable to unwatermark.")); panel.add(labelPanel); panel.add(Box.createVerticalStrut(10)); e.printStackTrace(new PrintWriter(writer)); panel.add(new JScrollPane(new JTextArea(writer.toString())){ @Override public Dimension getPreferredSize() { return new Dimension(480, 320); } }); panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS)); JOptionPane.showMessageDialog(imagePanel, panel, "Error", JOptionPane.ERROR_MESSAGE); } }
mit
r24mille/IesoPublicReportBindings
src/main/java/ca/ieso/reports/schema/daareareserveconst/DocHeader.java
4315
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.6 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2013.12.21 at 09:18:55 AM CST // package ca.ieso.reports.schema.daareareserveconst; import java.math.BigInteger; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.datatype.XMLGregorianCalendar; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element ref="{http://www.ieso.ca/schema}DocTitle"/> * &lt;element ref="{http://www.ieso.ca/schema}DocRevision"/> * &lt;element ref="{http://www.ieso.ca/schema}DocConfidentiality"/> * &lt;element ref="{http://www.ieso.ca/schema}CreatedAt"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "docTitle", "docRevision", "docConfidentiality", "createdAt" }) @XmlRootElement(name = "DocHeader") public class DocHeader { @XmlElement(name = "DocTitle", required = true) protected String docTitle; @XmlElement(name = "DocRevision", required = true) protected BigInteger docRevision; @XmlElement(name = "DocConfidentiality", required = true) protected DocConfidentiality docConfidentiality; @XmlElement(name = "CreatedAt", required = true) @XmlSchemaType(name = "dateTime") protected XMLGregorianCalendar createdAt; /** * Gets the value of the docTitle property. * * @return * possible object is * {@link String } * */ public String getDocTitle() { return docTitle; } /** * Sets the value of the docTitle property. * * @param value * allowed object is * {@link String } * */ public void setDocTitle(String value) { this.docTitle = value; } /** * Gets the value of the docRevision property. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getDocRevision() { return docRevision; } /** * Sets the value of the docRevision property. * * @param value * allowed object is * {@link BigInteger } * */ public void setDocRevision(BigInteger value) { this.docRevision = value; } /** * Gets the value of the docConfidentiality property. * * @return * possible object is * {@link DocConfidentiality } * */ public DocConfidentiality getDocConfidentiality() { return docConfidentiality; } /** * Sets the value of the docConfidentiality property. * * @param value * allowed object is * {@link DocConfidentiality } * */ public void setDocConfidentiality(DocConfidentiality value) { this.docConfidentiality = value; } /** * Gets the value of the createdAt property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getCreatedAt() { return createdAt; } /** * Sets the value of the createdAt property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setCreatedAt(XMLGregorianCalendar value) { this.createdAt = value; } }
mit
rwaldron/es6draft
src/main/java/com/github/anba/es6draft/ast/ComprehensionFor.java
1224
/** * Copyright (c) 2012-2014 André Bargull * Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms. * * <https://github.com/anba/es6draft> */ package com.github.anba.es6draft.ast; /** * <h1>12 ECMAScript Language: Expressions</h1><br> * <h2>12.1 Primary Expressions</h2><br> * <h3>12.1.4 Array Initialiser</h3> * <ul> * <li>12.1.4.2 Array Comprehension * </ul> */ public final class ComprehensionFor extends ComprehensionQualifier implements ScopedNode { private BlockScope scope; private Binding binding; private Expression expression; public ComprehensionFor(long beginPosition, long endPosition, BlockScope scope, Binding binding, Expression expression) { super(beginPosition, endPosition); this.scope = scope; this.binding = binding; this.expression = expression; } @Override public BlockScope getScope() { return scope; } public Binding getBinding() { return binding; } public Expression getExpression() { return expression; } @Override public <R, V> R accept(NodeVisitor<R, V> visitor, V value) { return visitor.visit(this, value); } }
mit
revati1701/topcoder
src/main/java/srm149/MessageMess.java
1972
package main.java.srm149; import java.util.HashSet; import java.util.Set; /* * SRM 149 DIV I Level 2 * http://community.topcoder.com/stat?c=problem_statement&pm=1331 */ public class MessageMess { private Set<String> _dictionarySet = new HashSet<String>(); public String restore(String[] dictionary, String message) { populateDictionarySet(dictionary); int numAnswers = 0; StringBuilder answer = findPossibleAnswer(0, message, ""); int ansLength = answer.length(); //Find answer if (ansLength > 0 && ansLength < message.length()) { answer = answer.deleteCharAt(ansLength - 1); ansLength = answer.length(); answer = findPossibleAnswer(ansLength, message, answer.toString()); } else if ( ansLength > 0) { //Find multiple answers numAnswers++; StringBuilder alternative = new StringBuilder(answer.substring(0, answer.indexOf(" "))); ansLength = alternative.length(); alternative = findPossibleAnswer(ansLength, message, alternative.toString()); if (alternative.length() >= message.length()) { numAnswers++; } } if(numAnswers > 1) { answer = new StringBuilder("AMBIGUOUS!"); } else if(answer.length() == 0 || answer.length() < message.length()) { answer = new StringBuilder("IMPOSSIBLE!"); } else { answer.deleteCharAt(answer.length() - 1); } return answer.toString(); } private StringBuilder findPossibleAnswer(int startIndex, String message, String prefix) { StringBuilder possibleWord = new StringBuilder(prefix); StringBuilder answer = new StringBuilder(); for(int i = startIndex; i < message.length(); i++) { possibleWord.append(message.charAt(i)); if(_dictionarySet.contains(possibleWord.toString())) { answer.append(possibleWord).append(" "); possibleWord.delete(0, possibleWord.length()); } } return answer; } private void populateDictionarySet(String[] array) { for(int i = 0; i < array.length; i++) { _dictionarySet.add(array[i]); } } }
mit
CS2103JAN2017-W14-B2/main
src/main/java/seedu/taskboss/logic/commands/FindCommand.java
2391
package seedu.taskboss.logic.commands; import java.util.Arrays; import java.util.HashSet; import java.util.Set; /** * Finds and lists all tasks in TaskBoss whose name contains any of the argument keywords. * Keyword matching is case sensitive. */ public class FindCommand extends Command { private static final String ALL_WHITESPACE = "\\s+"; public static final String COMMAND_WORD = "find"; public static final String COMMAND_WORD_SHORT = "f"; public static final String MESSAGE_USAGE = COMMAND_WORD + "/" + COMMAND_WORD_SHORT + ": Finds all tasks with names or information containing any of " + "the specified keywords (case-sensitive),\n" + " or with dates specified in any of following formats" + " e.g 28 / Feb / Feb 28 / Feb 28, 2017,\n" + " and displays them in a list.\n" + "Parameters: NAME AND INFORMATION KEYWORDS or sd/START_DATE or ed/END_DATE \n" + "Example: " + COMMAND_WORD + " meeting" + " || " + COMMAND_WORD_SHORT + " sd/march 19"; private static final String TYPE_KEYWORDS = "keywords"; private static final String TYPE_START_DATE = "startDate"; private static final String TYPE_END_DATE = "endDate"; private final String keywords; private final String type; //@@author A0147990R public FindCommand(String type, String keywords) { this.type = type; this.keywords = keywords; } @Override public CommandResult execute() { switch(type) { case TYPE_KEYWORDS: String[] keywordsList = keywords.split(ALL_WHITESPACE); final Set<String> keywordSet = new HashSet<String>(Arrays.asList(keywordsList)); model.updateFilteredTaskListByKeywords(keywordSet); return new CommandResult(getMessageForTaskListShownSummary(model.getFilteredTaskList().size())); case TYPE_START_DATE: model.updateFilteredTaskListByStartDateTime(keywords); return new CommandResult(getMessageForTaskListShownSummary(model.getFilteredTaskList().size())); case TYPE_END_DATE: model.updateFilteredTaskListByEndDateTime(keywords); return new CommandResult(getMessageForTaskListShownSummary(model.getFilteredTaskList().size())); default: return null; //will never reach here } } }
mit
felipefsn-07/EasyDrive
autoEscola/src/autoescola/view/TelaCadastroVeiculo.java
15576
/* * 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 autoescola.view; import autoescola.controleDao.ControleLogin; import autoescola.controleDao.ControleVeiculo; import autoescola.modelo.bean.Veiculo; /** * * @author felipe */ public class TelaCadastroVeiculo extends javax.swing.JDialog { /** * Creates new form TelaCadastroVeiculo */ private final ControleLogin controleLogin = new ControleLogin(); private final ControleVeiculo controleVeiculo = new ControleVeiculo(); public TelaCadastroVeiculo(java.awt.Frame parent, boolean modal, int id) { super(parent, modal); initComponents(); editar(id); } /** * 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() { jPanel1 = new javax.swing.JPanel(); jLabel7 = new javax.swing.JLabel(); jtUsario = new javax.swing.JTabbedPane(); jPanel10 = new javax.swing.JPanel(); jLabel11 = new javax.swing.JLabel(); jLabel16 = new javax.swing.JLabel(); jLabel17 = new javax.swing.JLabel(); jLabel18 = new javax.swing.JLabel(); txtPlaca = new javax.swing.JFormattedTextField(); txtAno = new javax.swing.JFormattedTextField(); bntCadastrarVeiculo = new javax.swing.JPanel(); lblCadastrarEditar = new javax.swing.JLabel(); jSCapacidade = new javax.swing.JSpinner(); txtModelo = new javax.swing.JTextField(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); jPanel1.setBackground(new java.awt.Color(144, 180, 242)); jLabel7.setFont(new java.awt.Font("Ubuntu", 1, 24)); // NOI18N jLabel7.setForeground(new java.awt.Color(254, 254, 254)); jLabel7.setText("Veículo"); jtUsario.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jtUsarioMouseClicked(evt); } }); jPanel10.setBackground(new java.awt.Color(254, 254, 254)); jLabel11.setText("Placa"); jLabel16.setText("Modelo"); jLabel17.setText("Capacidade"); jLabel18.setText("Ano"); try { txtPlaca.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("AAA-####"))); } catch (java.text.ParseException ex) { ex.printStackTrace(); } try { txtAno.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("####"))); } catch (java.text.ParseException ex) { ex.printStackTrace(); } bntCadastrarVeiculo.setBackground(new java.awt.Color(28, 181, 165)); bntCadastrarVeiculo.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); bntCadastrarVeiculo.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { bntCadastrarVeiculoMouseClicked(evt); } }); lblCadastrarEditar.setBackground(new java.awt.Color(254, 254, 254)); lblCadastrarEditar.setFont(new java.awt.Font("Ubuntu", 1, 18)); // NOI18N lblCadastrarEditar.setForeground(new java.awt.Color(254, 254, 254)); lblCadastrarEditar.setText("Cadastrar veiculo"); javax.swing.GroupLayout bntCadastrarVeiculoLayout = new javax.swing.GroupLayout(bntCadastrarVeiculo); bntCadastrarVeiculo.setLayout(bntCadastrarVeiculoLayout); bntCadastrarVeiculoLayout.setHorizontalGroup( bntCadastrarVeiculoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(bntCadastrarVeiculoLayout.createSequentialGroup() .addGap(13, 13, 13) .addComponent(lblCadastrarEditar) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); bntCadastrarVeiculoLayout.setVerticalGroup( bntCadastrarVeiculoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(bntCadastrarVeiculoLayout.createSequentialGroup() .addContainerGap() .addComponent(lblCadastrarEditar) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jSCapacidade.setModel(new javax.swing.SpinnerNumberModel(1, 1, null, 1)); javax.swing.GroupLayout jPanel10Layout = new javax.swing.GroupLayout(jPanel10); jPanel10.setLayout(jPanel10Layout); jPanel10Layout.setHorizontalGroup( jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel10Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jPanel10Layout.createSequentialGroup() .addComponent(jLabel18, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGap(244, 244, 244)) .addComponent(txtPlaca) .addComponent(jLabel11) .addGroup(jPanel10Layout.createSequentialGroup() .addGroup(jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(txtAno, javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel10Layout.createSequentialGroup() .addComponent(jLabel16) .addGap(168, 168, 168)) .addComponent(txtModelo, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 225, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel17) .addComponent(jSCapacidade, javax.swing.GroupLayout.PREFERRED_SIZE, 232, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel10Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(bntCadastrarVeiculo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); jPanel10Layout.setVerticalGroup( jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel10Layout.createSequentialGroup() .addGap(17, 17, 17) .addComponent(jLabel11) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(txtPlaca, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel16) .addComponent(jLabel17)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel10Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txtModelo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jSCapacidade, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(25, 25, 25) .addComponent(jLabel18) .addGap(18, 18, 18) .addComponent(txtAno, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 69, Short.MAX_VALUE) .addComponent(bntCadastrarVeiculo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); jtUsario.addTab("Dados do veiculo", jPanel10); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel7) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(jtUsario)) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel7) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jtUsario, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE) .addContainerGap()) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); setBounds(0, 0, 713, 480); }// </editor-fold>//GEN-END:initComponents private void editar(int id) { if (id != 0) { Veiculo veiculo = controleVeiculo.getVeiculo(id); txtPlaca.setText(veiculo.getPlaca()); jSCapacidade.setValue(veiculo.getCapacidade()); txtModelo.setText(veiculo.getModelo()); txtAno.setText(veiculo.getAno()); lblCadastrarEditar.setText("Editar veículo"); } } private void bntCadastrarVeiculoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bntCadastrarVeiculoMouseClicked Veiculo veiculo = new Veiculo(); veiculo.setPlaca(txtPlaca.getText()); float capacidade = Float.parseFloat(jSCapacidade.getValue().toString()); veiculo.setCapacidade(capacidade); veiculo.setModelo(txtModelo.getText()); veiculo.setAno(txtAno.getText()); if (controleVeiculo.isEditar()) { boolean res = controleVeiculo.editarVeiculo(veiculo); if (res) { lblCadastrarEditar.setText("Editar Veiculo"); //verificarTela(); } } else { veiculo.setStatus(true); boolean res = controleVeiculo.cadastrarVeiculo(veiculo); if (res) { lblCadastrarEditar.setText("Editar Veiculo"); //verificarTela(); } } }//GEN-LAST:event_bntCadastrarVeiculoMouseClicked private void jtUsarioMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jtUsarioMouseClicked }//GEN-LAST:event_jtUsarioMouseClicked /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(TelaCadastroVeiculo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(TelaCadastroVeiculo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(TelaCadastroVeiculo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(TelaCadastroVeiculo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> /* Create and display the dialog */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { TelaCadastroVeiculo dialog = new TelaCadastroVeiculo(new javax.swing.JFrame(), true, 0); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel bntCadastrarVeiculo; private javax.swing.JLabel jLabel11; private javax.swing.JLabel jLabel16; private javax.swing.JLabel jLabel17; private javax.swing.JLabel jLabel18; private javax.swing.JLabel jLabel7; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel10; private javax.swing.JSpinner jSCapacidade; private javax.swing.JTabbedPane jtUsario; private javax.swing.JLabel lblCadastrarEditar; private javax.swing.JFormattedTextField txtAno; private javax.swing.JTextField txtModelo; private javax.swing.JFormattedTextField txtPlaca; // End of variables declaration//GEN-END:variables }
mit
nico01f/z-pec
ZimbraSelenium/src/java/com/zimbra/qa/selenium/framework/util/ZimbraExternalAccount.java
4848
/** * */ package com.zimbra.qa.selenium.framework.util; import java.net.*; import java.util.regex.*; import org.apache.log4j.*; import com.zimbra.common.soap.Element; /** * Represents an 'external' account * * @author Matt Rhoades * */ public class ZimbraExternalAccount extends ZimbraAccount { private static Logger logger = LogManager.getLogger(ZimbraExternalAccount.class); protected URI UrlRegistration = null; protected URI UrlLogin = null; public ZimbraExternalAccount() { logger.info("new "+ ZimbraExternalAccount.class.getCanonicalName()); } public void setEmailAddress(String address) { this.EmailAddress = address; } public void setPassword(String password) { this.Password = password; } /** * Based on the external invitation message, * set both the login and registration URLs for this account * @param GetMsgResponse * @throws HarnessException */ public void setURL(Element GetMsgResponse) throws HarnessException { this.setRegistrationURL(GetMsgResponse); this.setLoginURL(GetMsgResponse); } /** * Based on the external invitation message, extract the login URL * example, https://zqa-062.eng.vmware.com/service/extuserprov/?p=0_46059ce585e90f5d2d5...12e636f6d3b * @param GetMsgResponse */ public void setRegistrationURL(Element GetMsgResponse) throws HarnessException { String content = this.soapClient.selectValue(GetMsgResponse, "//mail:mp[@ct='text/html']//mail:content", null, 1); try { setRegistrationURL(determineRegistrationURL(content)); } catch (URISyntaxException e) { throw new HarnessException("Unable to parse registration URL from ["+ content +"]", e); } } /** * Set the external user's registration URL to the specified URL * @param url */ public void setRegistrationURL(URI url) { this.UrlRegistration = url; } public URI getRegistrationURL() { return (this.UrlRegistration); } /** * Based on the external invitation message, extract the login URL * example, https://zqa-062.eng.vmware.com/?virtualacctdomain=zqa-062.eng.vmware.com * @param GetMsgResponse * @throws HarnessException */ public void setLoginURL(Element GetMsgResponse) throws HarnessException { String content = this.soapClient.selectValue(GetMsgResponse, "//mail:mp[@ct='text/html']//mail:content", null, 1); try { setLoginURL(determineLoginURL(content)); } catch (URISyntaxException e) { throw new HarnessException("Unable to parse registration URL from ["+ content +"]", e); } } /** * Set the external user's login URL to the specified URL * @param url */ public void setLoginURL(URI url) { this.UrlLogin = url; } public URI getLoginURL() { return (this.UrlLogin); } public static final Pattern patternTag = Pattern.compile("(?i)<a([^>]+)>(.+?)</a>"); public static final Pattern patternLink = Pattern.compile("\\s*(?i)href\\s*=\\s*(\"([^\"]*\")|'[^']*'|([^'\">\\s]+))"); /** * Parse the invitation message to grab the registration URL * for the external user * @param content * @return * @throws HarnessException * @throws MalformedURLException * @throws URISyntaxException */ protected URI determineRegistrationURL(String content) throws HarnessException, URISyntaxException { String registrationURL = null; Matcher matcherTag = patternTag.matcher(content); while (matcherTag.find()) { String href = matcherTag.group(1); String text = matcherTag.group(2); logger.info("href: "+ href); logger.info("text: "+ text); Matcher matcherLink = patternLink.matcher(href); while(matcherLink.find()){ registrationURL = matcherLink.group(1); //link if ( registrationURL.startsWith("\"") ) { registrationURL = registrationURL.substring(1); // Strip the beginning " } if ( registrationURL.endsWith("\"") ) { registrationURL = registrationURL.substring(0, registrationURL.length()-1); // Strip the ending " } logger.info("link: "+ registrationURL); return (new URI(registrationURL)); } } throw new HarnessException("Unable to determine the regisration URL from "+ content); } /** * Parse the invitation message to grab the login URL * for the external user * @param content * @return * @throws HarnessException * @throws URISyntaxException */ protected URI determineLoginURL(String content) throws HarnessException, URISyntaxException { // TODO: implement me! return (determineRegistrationURL(content)); } /** * Get the external account for config.properties -> external.yahoo.account * @return the ZimbraExternalAccount */ public static synchronized ZimbraExternalAccount ExternalA() { if ( _ExternalA == null ) { _ExternalA = new ZimbraExternalAccount(); } return (_ExternalA); } private static ZimbraExternalAccount _ExternalA = null; }
mit
ysl3000/Quantum-Connectors
QuantumPlugin/src/main/java/com/github/ysl3000/quantum/impl/ConfigConverter.java
3964
package com.github.ysl3000.quantum.impl; import com.github.ysl3000.quantum.QuantumConnectors; import com.github.ysl3000.quantum.impl.circuits.CircuitManager; import com.github.ysl3000.quantum.impl.utils.MessageLogger; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.configuration.file.YamlConfiguration; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; public class ConfigConverter { private QuantumConnectors plugin; private MessageLogger messageLogger; public ConfigConverter(QuantumConnectors plugin, MessageLogger messageLogger) { this.plugin = plugin; this.messageLogger = messageLogger; } //1.2.3 circuits.yml Converter public void convertOldCircuitsYml() { File oldYmlFile = new File(plugin.getDataFolder(), "circuits.yml"); if (oldYmlFile.exists()) { messageLogger.log(messageLogger.getMessage("found_old_file").replace("%file%", oldYmlFile.getName())); FileConfiguration oldYml = YamlConfiguration.loadConfiguration(oldYmlFile); for (String worldName : oldYml.getValues(false).keySet()) { ArrayList<Map<String, Object>> tempCircuitObjs = new ArrayList<>(); for (int x = 0; ; x++) { String path = worldName + ".circuit_" + x; if (oldYml.get(path) == null) { break; } Map<String, Object> tempCircuitObj = new HashMap<String, Object>(); String[] senderXYZ = oldYml.get(path + ".sender").toString().split(","); tempCircuitObj.put("x", Integer.parseInt(senderXYZ[0])); tempCircuitObj.put("y", Integer.parseInt(senderXYZ[1])); tempCircuitObj.put("z", Integer.parseInt(senderXYZ[2])); //they'll all be the same, should only ever be one anyway String receiversType = oldYml.get(path + ".type").toString(); ArrayList<Map<String, Object>> tempReceiverObjs = new ArrayList<Map<String, Object>>(); for (Object receiver : oldYml.getList(path + ".receivers")) { Map<String, Object> tempReceiverObj = new HashMap<String, Object>(); String[] sReceiverLoc = receiver.toString().split(","); tempReceiverObj.put("x", Integer.parseInt(sReceiverLoc[0])); tempReceiverObj.put("y", Integer.parseInt(sReceiverLoc[1])); tempReceiverObj.put("z", Integer.parseInt(sReceiverLoc[2])); tempReceiverObj.put("d", 0); tempReceiverObj.put("t", Integer.parseInt(receiversType)); tempReceiverObjs.add(tempReceiverObj); } tempCircuitObj.put("r", tempReceiverObjs); tempCircuitObjs.add(tempCircuitObj); } File newYmlFile = new File(plugin.getDataFolder(), worldName + ".circuits.yml"); FileConfiguration newYml = YamlConfiguration.loadConfiguration(newYmlFile); newYml.set("fileVersion", 2); newYml.set("circuits", tempCircuitObjs); try { newYml.save(newYmlFile); } catch (IOException ex) { messageLogger.error(messageLogger.getMessage("unable_to_save").replace("%file%", newYmlFile.getName())); Logger.getLogger(CircuitManager.class.getName()).log(Level.SEVERE, null, ex); } } File testFile = new File(plugin.getDataFolder(), "circuits.yml.bak"); new File(plugin.getDataFolder(), "circuits.yml").renameTo(testFile); } } }
mit
bpervan/wavelet-rrr
Java1/src/hr/fer/bio/project/booleanarray/BooleanArray.java
4405
package hr.fer.bio.project.booleanarray; import hr.fer.bio.project.rankable.Rankable; import hr.fer.bio.project.wavelet.TreeNode; import java.util.Arrays; /** * Simple class for boolean[] encapsulation * * @author bpervan * @since 1.0 */ public class BooleanArray implements Rankable { public boolean[] data; public BooleanArray(int size){ data = new boolean[size]; } public BooleanArray(boolean[] data){ this.data = Arrays.copyOf(data, data.length); } @Override public int rank(char c, int endPos, TreeNode rootNode){ TreeNode<BooleanArray> workingNode = rootNode; if(workingNode.data.data.length <= endPos){ throw new IllegalArgumentException("End position larger than input data"); } int counter = 0; int rightBound = endPos; while(workingNode != null){ if(workingNode.charMap.get(c) == true){ //char c is encoded as 1, count 1es, proceed to right child for(int i = 0; i < rightBound; ++i){ if(workingNode.data.data[i]){ counter++; } } workingNode = workingNode.rightChild; } else { //char c is encoded as 0, count 0es, proceed to left child for(int i = 0; i < rightBound; ++i){ if(!workingNode.data.data[i]){ counter++; } } workingNode = workingNode.leftChild; } rightBound = counter; counter = 0; } return rightBound; } @Override public int select(char c, int boundary, TreeNode rootNode) { TreeNode<BooleanArray> workingNode = rootNode; while(true){ if(!workingNode.charMap.get(c)){ //left if(workingNode.leftChild != null){ workingNode = workingNode.leftChild; } else { break; } } else { //right if(workingNode.rightChild != null){ workingNode = workingNode.rightChild; } else { break; } } } //workingNode now contains leaf with char c //count 0/1 //parent with same operation count -> previously calculated boundary int counter = 0; int newBound = boundary; int Select = 0; while(workingNode != null){ if(workingNode.charMap.get(c)){ for(int i = 0; i < workingNode.data.data.length; ++i){ Select++; if(workingNode.data.data[i]){ counter++; if(counter == newBound){ break; } } } } else { for(int i = 0; i < workingNode.data.data.length; ++i){ Select++; if(!workingNode.data.data[i]){ counter++; if(counter == newBound){ break; } } } } workingNode = workingNode.parent; newBound = Select; counter = 0; Select = 0; } return newBound; } @Override public String toString(){ StringBuilder stringBuilder = new StringBuilder(); for(int i = 0; i < data.length; ++i){ if(data[i]){ stringBuilder.append(1); } else { stringBuilder.append(0); } } return stringBuilder.toString(); } @Override public boolean equals(Object that){ if(that == null){ return false; } if(!(that instanceof BooleanArray)){ return false; } BooleanArray thatBooleanArray = (BooleanArray) that; if(data.length != thatBooleanArray.data.length){ return false; } for(int i = 0; i < data.length; ++i){ if(data[i] != thatBooleanArray.data[i]){ return false; } } return true; } }
mit
dxiao/PPBunnies
slick/trunk/Slick/src/org/newdawn/slick/util/pathfinding/navmesh/NavMesh.java
4275
package org.newdawn.slick.util.pathfinding.navmesh; import java.util.ArrayList; /** * A nav-mesh is a set of shapes that describe the navigation of a map. These * shapes are linked together allow path finding but without the high * resolution that tile maps require. This leads to fast path finding and * potentially much more accurate map definition. * * @author kevin * */ public class NavMesh { /** The list of spaces that build up this navigation mesh */ private ArrayList spaces = new ArrayList(); /** * Create a new empty mesh */ public NavMesh() { } /** * Create a new mesh with a set of spaces * * @param spaces The spaces included in the mesh */ public NavMesh(ArrayList spaces) { this.spaces.addAll(spaces); } /** * Get the number of spaces that are in the mesh * * @return The spaces in the mesh */ public int getSpaceCount() { return spaces.size(); } /** * Get the space at a given index * * @param index The index of the space to retrieve * @return The space at the given index */ public Space getSpace(int index) { return (Space) spaces.get(index); } /** * Add a single space to the mesh * * @param space The space to be added */ public void addSpace(Space space) { spaces.add(space); } /** * Find the space at a given location * * @param x The x coordinate at which to find the space * @param y The y coordinate at which to find the space * @return The space at the given location */ public Space findSpace(float x, float y) { for (int i=0;i<spaces.size();i++) { Space space = getSpace(i); if (space.contains(x,y)) { return space; } } return null; } /** * Find a path from the source to the target coordinates * * @param sx The x coordinate of the source location * @param sy The y coordinate of the source location * @param tx The x coordinate of the target location * @param ty The y coordinate of the target location * @param optimize True if paths should be optimized * @return The path between the two spaces */ public NavPath findPath(float sx, float sy, float tx, float ty, boolean optimize) { Space source = findSpace(sx,sy); Space target = findSpace(tx,ty); if ((source == null) || (target == null)) { return null; } for (int i=0;i<spaces.size();i++) { ((Space) spaces.get(i)).clearCost(); } target.fill(source,tx, ty, 0); if (target.getCost() == Float.MAX_VALUE) { return null; } if (source.getCost() == Float.MAX_VALUE) { return null; } NavPath path = new NavPath(); path.push(new Link(sx, sy, null)); if (source.pickLowestCost(target, path)) { path.push(new Link(tx, ty, null)); if (optimize) { optimize(path); } return path; } return null; } /** * Check if a particular path is clear * * @param x1 The x coordinate of the starting point * @param y1 The y coordinate of the starting point * @param x2 The x coordinate of the ending point * @param y2 The y coordinate of the ending point * @param step The size of the step between points * @return True if there are no blockages along the path */ private boolean isClear(float x1, float y1, float x2, float y2, float step) { float dx = (x2 - x1); float dy = (y2 - y1); float len = (float) Math.sqrt((dx*dx)+(dy*dy)); dx *= step; dx /= len; dy *= step; dy /= len; int steps = (int) (len / step); for (int i=0;i<steps;i++) { float x = x1 + (dx*i); float y = y1 + (dy*i); if (findSpace(x,y) == null) { return false; } } return true; } /** * Optimize a path by removing segments that arn't required * to reach the end point * * @param path The path to optimize. Redundant segments will be removed */ private void optimize(NavPath path) { int pt = 0; while (pt < path.length()-2) { float sx = path.getX(pt); float sy = path.getY(pt); float nx = path.getX(pt+2); float ny = path.getY(pt+2); if (isClear(sx,sy,nx,ny,0.1f)) { path.remove(pt+1); } else { pt++; } } } }
mit
mstane/algorithms-in-java
src/main/java/org/sm/jdsa/graph/algorithm/coloring/ColoringAdjacentListStrategyImpl.java
2912
package org.sm.jdsa.graph.algorithm.coloring; import java.util.stream.IntStream; import org.sm.jdsa.graph.GraphAdjacencyListImpl; import org.sm.jdsa.list.LinkedList; import org.sm.jdsa.list.Iterator; /** * * Counts number of colors upper bound for graph (vertex) * coloring problem using greedy algorithm. * * @author Stanislav Markov * */ public class ColoringAdjacentListStrategyImpl implements ColoringStrategy { private final GraphAdjacencyListImpl graph; private final int graphSize; private int colorsUsed; private final int[] vertexColors; private final boolean[] adjecentsColors; int numberOfColors = -1; public ColoringAdjacentListStrategyImpl(GraphAdjacencyListImpl graph) { this.graph = graph; this.graphSize = graph.getGraphSize(); this.colorsUsed = 0; this.vertexColors = new int[graphSize]; this.adjecentsColors = new boolean[graphSize]; initVertexColors(); } /** * Main Method, in charge of counting number of different colors. * In case it is already calculated it just passes the value * * @return */ @Override public int getNumberOfColors() { if (numberOfColors < 0 && graphSize > 0) { vertexColors[0] = colorsUsed; IntStream.range(0, graphSize).forEach(vertex -> { int leastAvailableColor = getLeastAvailableColor(vertex); vertexColors[vertex] = leastAvailableColor; colorsUsed = Math.max(colorsUsed, leastAvailableColor); }); numberOfColors = colorsUsed + 1; } return numberOfColors; } /** * Finds the least available color from vertex's adjacents * * @param vertex * @return */ private int getLeastAvailableColor(int vertex) { loadAdjecentsColors(vertex); int leastAvailableColor = -1; int i = 0; while (leastAvailableColor < 0 && i < adjecentsColors.length) { if (!adjecentsColors[i]) leastAvailableColor = i; i++; } return leastAvailableColor; } /** * Loads helper array with already taken color by vertex's adjacents * * @param vertex */ private void loadAdjecentsColors(int vertex) { resetAdjecentsColors(); LinkedList<Integer> vertexAdjecents = graph.getDataStructure()[vertex]; for (int i = 0; i < adjecentsColors.length; i++) { } for(Iterator<Integer> iterator = vertexAdjecents.iterator(); iterator.hasNext();) { int adjacent = iterator.next(); if (adjacent > -1) { adjecentsColors[vertexColors[adjacent]] = true; } } } /* * Resets helper array used for recording colors * assigned to the vertex's adjecents for next vertex */ private void resetAdjecentsColors() { IntStream.range(0, graphSize).forEach(color -> adjecentsColors[color] = false); } /* * Initialization of the array which holds colors assigned to verticies */ private void initVertexColors() { IntStream.range(0, graphSize).forEach(vertex -> vertexColors[vertex] = -1); } }
mit
VoxelGamesLib/VoxelGamesLibv2
VoxelGamesLib/src/main/java/com/voxelgameslib/voxelgameslib/api/feature/features/NoBlockBreakFeature.java
2127
package com.voxelgameslib.voxelgameslib.api.feature.features; import com.google.gson.annotations.Expose; import java.util.Arrays; import javax.annotation.Nonnull; import com.voxelgameslib.voxelgameslib.api.event.GameEvent; import com.voxelgameslib.voxelgameslib.api.feature.AbstractFeature; import com.voxelgameslib.voxelgameslib.api.feature.FeatureInfo; import org.bukkit.Material; import org.bukkit.event.block.BlockBreakEvent; @FeatureInfo(name = "NoBlockBreakFeature", author = "MiniDigger", version = "1.0", description = "Small feature that blocks block breaking if active") public class NoBlockBreakFeature extends AbstractFeature { @Expose private Material[] whitelist = new Material[0]; @Expose private Material[] blacklist = new Material[0]; /** * Sets the list with whitelisted materials. Enabling the whitelist means that ppl are allowed to break only * materials which are on the whitelist. to disabled the whitelist, pass an empty array. * * @param whitelist the new whitelist */ public void setWhitelist(@Nonnull Material[] whitelist) { this.whitelist = whitelist; } /** * Sets the list with blacklisted materials. Enabling the blacklist means that ppl are allowed to break every * material other than those on the blacklist. to disabled the blacklist, pass an empty array * * @param blacklist the new blacklist */ public void setBlacklist(@Nonnull Material[] blacklist) { this.blacklist = blacklist; } @SuppressWarnings({"JavaDoc", "Duplicates"}) @GameEvent public void onBlockBreak(@Nonnull BlockBreakEvent event) { if (blacklist.length != 0) { if (Arrays.stream(blacklist).anyMatch(m -> m.equals(event.getBlock().getType()))) { event.setCancelled(true); } } else if (whitelist.length != 0) { if (Arrays.stream(whitelist).noneMatch(m -> m.equals(event.getBlock().getType()))) { event.setCancelled(true); } } else { event.setCancelled(true); } } }
mit
ordinary-developer/book_pragmatic_unit_testing_in_java_8_with_junit_j_langr
my_code/chapter_1_BUILDING_YOUR_FIRST_JUNIT_TEST/ScoreCollectionTest.java
488
import static org.junit.Assert.*; import static org.hamcrest.CoreMatchers.*; import org.junit.*; public class ScoreCollectionTest { @Test public void answersArithmeticMeanOfTwoNumbers() { // arrange ScoreCollection collection = new ScoreCollection(); collection.add(() -> 5); collection.add(() -> 7); // act int actualResult = collection.arithmeticMean(); // assert assertThat(actualResult, equalTo(6)); } }
mit
rpayonline/rpayonline-lite-java
src/test/java/jp/co/rakuten/checkout/lite/model/EventTest.java
3237
package jp.co.rakuten.checkout.lite.model; import static org.junit.Assert.assertEquals; import org.junit.Before; import org.junit.Test; import jp.co.rakuten.checkout.lite.RpayLite; import jp.co.rakuten.checkout.lite.RpayLiteTest; import jp.co.rakuten.checkout.lite.exception.UnexpectedValueException; import jp.co.rakuten.checkout.lite.net.Webhook; import jp.co.rakuten.checkout.lite.net.Webhook.SignatureVerificationException; public class EventTest extends RpayLiteTest { String payload = ""; @Before public void setUpAll() { payload += "{\"object\": \"event\",\"id\": \"evt_ace3a9e65ad548a8b5c8de7965efa160\",\"livemode\": false,\"type\": \"charge.check\",\"synchronous\": true,\"data\": {\"object\": {\"object\": \"charge\","; payload += "\"open_id\": \"https://myid.rakuten.co.jp/openid/user/h65MxxxxxxxQxn0wJENoHHsalseDD==\", \"id\": null,\"cipher\": null,\"livemode\": false,\"currency\": \"jpy\",\"amount\": 5000,\"point\": 1000,"; payload += "\"cart_id\": \"cart_id1\",\"paid\": false,\"captured\": false,\"status\": null,\"refunded\": false,"; payload += "\"items\": [{\"id\": \"item_id1\",\"name\": \"item1\",\"quantity\": 10,\"unit_price\": 1000},{\"id\": \"item_id2\",\"name\": \"item2\",\"quantity\": 20,\"unit_price\": 2000}],"; payload += "\"address\": null,\"created\": null,\"updated\": null}},\"pending_webhooks\":0,\"created\":1433862000}"; } @Test public void testConstruct() throws UnexpectedValueException, SignatureVerificationException { RpayLite.setWebhookSignature("123"); Event ev = Webhook.constructEvent(payload, "123", "123"); assertEquals(ev.getId(), "evt_ace3a9e65ad548a8b5c8de7965efa160"); assertEquals(ev.getData().getObject().getPoint(), 1000); } @Test(expected = SignatureVerificationException.class) public void testNullSigHeader() throws SignatureVerificationException, UnexpectedValueException { Webhook.constructEvent(payload, null, "123"); } @Test(expected = SignatureVerificationException.class) public void testSignatureNotEqual() throws SignatureVerificationException, UnexpectedValueException { RpayLite.setWebhookSignature("123"); Webhook.constructEvent(payload, "188", "123"); } @Test(expected = UnexpectedValueException.class) public void testInvalidJson() throws SignatureVerificationException, UnexpectedValueException { String payloadError = "{\"object\" \"event\",\"id\": \"evt_0a28558a912043d7bb82ba0702afda7f\",\"livemode\": false,\"type\": \"ping\",\"synchronous\": true,\"data\": null,\"pending_webhooks\": 0,\"created\": 1499068723}"; Webhook.constructEvent(payloadError, "188", "123"); } @Test(expected = SignatureVerificationException.class) public void testNullSignature() throws SignatureVerificationException, UnexpectedValueException { Webhook.constructEvent(payload, "188", null); } @Test public void testExceptionSigHeader() throws UnexpectedValueException { try { Webhook.constructEvent(payload, "188", "123"); } catch (SignatureVerificationException e) { assertEquals("188", e.getSigHeader()); } } }
mit
amilcar-andrade/explore
app/src/main/java/a2ndrade/explore/data/model/Repo.java
1618
package a2ndrade.explore.data.model; import android.graphics.Color; import android.os.Parcel; import android.os.Parcelable; public class Repo implements Parcelable { public static final int DEFAULT_COLOR = Color.DKGRAY; public final String name; public final String description; private boolean isStarred; // Avatar color private int color = DEFAULT_COLOR; public Repo(String name, String description, boolean isStarred) { this.name = name; this.description = description; this.isStarred = isStarred; } public boolean isStarred() { return isStarred; } public void setStarred(boolean isStarred) { this.isStarred = isStarred; } public void setColor(int color) { this.color = color; } public int getColor() { return color; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(this.name); dest.writeString(this.description); dest.writeByte(this.isStarred ? (byte) 1 : (byte) 0); } protected Repo(Parcel in) { this.name = in.readString(); this.description = in.readString(); this.isStarred = in.readByte() != 0; } public static final Creator<Repo> CREATOR = new Creator<Repo>() { @Override public Repo createFromParcel(Parcel source) { return new Repo(source); } @Override public Repo[] newArray(int size) { return new Repo[size]; } }; }
mit
shootboss/goja
goja-core/src/main/java/goja/lang/util/Context.java
1292
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright (c) 2013-2014 sagyf Yang. The Four Group. */ package goja.lang.util; import java.util.List; import java.util.Map; import java.util.Set; public interface Context extends Cloneable { Context set(String name, Object value); Set<String> keys(); Map<String, Object> getInnerMap(); Context putAll(Object obj); Context putAll(String prefix, Object obj); boolean has(String key); Context clear(); int size(); boolean isEmpty(); Object get(String name); Object get(String name, Object dft); <T> T getAs(Class<T> type, String name); <T> T getAs(Class<T> type, String name, T dft); int getInt(String name); int getInt(String name, int dft); String getString(String name); String getString(String name, String dft); boolean getBoolean(String name); boolean getBoolean(String name, boolean dft); float getFloat(String name); float getFloat(String name, float dft); double getDouble(String name); double getDouble(String name, double dft); Map<String, Object> getMap(String name); List<Object> getList(String name); <T> List<T> getList(Class<T> classOfT, String name); Context clone(); }
mit
mpecero/jaxrs-jwt-example
src/main/java/es/infointernet/bean/User.java
538
package es.infointernet.bean; import java.security.Principal; import java.util.List; public class User implements Principal { private String username; private List<String> roles; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } @Override public String getName() { return username; } public List<String> getRoles() { return roles; } public void setRoles(List<String> roles) { this.roles = roles; } }
mit
yu-kopylov/shared-mq
src/main/java/org/sharedmq/primitives/MappedByteArrayStorageKeyStorageAdapter.java
1277
package org.sharedmq.primitives; import java.nio.ByteBuffer; /** * An adapter for the {@link MappedByteArrayStorageKey}. */ public class MappedByteArrayStorageKeyStorageAdapter implements StorageAdapter<MappedByteArrayStorageKey> { private static final MappedByteArrayStorageKeyStorageAdapter instance = new MappedByteArrayStorageKeyStorageAdapter(); public static MappedByteArrayStorageKeyStorageAdapter getInstance() { return instance; } @Override public int getRecordSize() { return 4 * 2 + 8; } @Override public void store(ByteBuffer buffer, MappedByteArrayStorageKey key) { if (key == null) { throw new IllegalArgumentException( "The MappedByteArrayStorageKeyStorageAdapter does not support null records."); } buffer.putInt(key.getSegmentNumber()); buffer.putInt(key.getRecordNumber()); buffer.putLong(key.getRecordId()); } @Override public MappedByteArrayStorageKey load(ByteBuffer buffer) { int segmentNumber = buffer.getInt(); int recordNumber = buffer.getInt(); long recordId = buffer.getLong(); return new MappedByteArrayStorageKey(segmentNumber, recordNumber, recordId); } }
mit
nking/curvature-scale-space-corners-and-transformations
src/algorithms/imageProcessing/features/PatchUtil.java
12845
package algorithms.imageProcessing.features; import algorithms.util.PairInt; import algorithms.util.PixelHelper; import gnu.trove.iterator.TIntIterator; import gnu.trove.set.TIntSet; import gnu.trove.set.hash.TIntHashSet; import java.util.HashSet; import java.util.Set; import algorithms.packing.Intersection2DPacking; /** * carries the current integrated histogram from a region of * HOGS, HCPT, or HGS data. * Note that orientation is not used. * Note that the user must restrict the arguments to * being the same origin data. * * @author nichole */ public class PatchUtil { private static float eps = 0.000001f; private final long[] h; private final TIntSet pixIdxs; private final int imgW; private final int imgH; private double err = 0; private double blockTotals = 0; public PatchUtil(int imageWidth, int imageHeight, int nBins) { this.h = new long[nBins]; this.imgW = imageWidth; this.imgH = imageHeight; this.pixIdxs = new TIntHashSet(); } public void add(TIntSet addPixelIndexes, HOGs hogs) { if (hogs.getNumberOfBins() != h.length) { throw new IllegalArgumentException( "hog number of bins differs the expected"); } if (hogs.getImageWidth() != imgW) { throw new IllegalArgumentException( "hog image width differs the expected"); } if (hogs.getImageHeight() != imgH) { throw new IllegalArgumentException( "hog image height differs the expected"); } if (addPixelIndexes.isEmpty()) { return; } int c0 = pixIdxs.size(); // to keep adding to block totals, square and factor by count again double tmpBlockTotals = blockTotals; if (blockTotals > 0) { double norm = 255.f/(blockTotals + eps); div(h, norm); } long tmpSum = 0; long tmpSumErrSq = 0; double maxValue; long[] tmp = new long[h.length]; int[] xy = new int[2]; PixelHelper ph = new PixelHelper(); //TODO: correct to use a scan by cell size pattern TIntIterator iter = addPixelIndexes.iterator(); while (iter.hasNext()) { int pixIdx = iter.next(); if (pixIdxs.contains(pixIdx)) { continue; } pixIdxs.add(pixIdx); ph.toPixelCoords(pixIdx, imgW, xy); hogs.extractBlock(xy[0], xy[1], tmp); HOGs.add(h, tmp); tmpSum = 0; maxValue = Double.NEGATIVE_INFINITY; for (int j = 0; j < tmp.length; ++j) { tmpSum += tmp[j]; if (tmp[j] > maxValue) { maxValue = tmp[j]; } } maxValue += eps; tmpBlockTotals += tmpSum; tmpSum /= tmp.length; tmpSumErrSq += ((tmpSum/maxValue)*(tmpSum/maxValue)); } int nAdded = pixIdxs.size() - c0; int c1 = pixIdxs.size(); if (c1 > 0) { this.blockTotals = tmpBlockTotals; } double norm = 1./(blockTotals + eps); float maxBlock = 255.f; norm *= maxBlock; mult(h, norm); //TODO: examine the order of divide by count and sqrt this.err *= this.err; this.err *= c0; this.err += tmpSumErrSq; this.err /= (double)c1; this.err = Math.sqrt(err); } public void add(TIntSet addPixelIndexes, HCPT hcpt) { if (hcpt.getNumberOfBins() != h.length) { throw new IllegalArgumentException( "hog number of bins differs the expected"); } if (hcpt.getImageWidth() != imgW) { throw new IllegalArgumentException( "hog image width differs the expected"); } if (hcpt.getImageHeight() != imgH) { throw new IllegalArgumentException( "hog image height differs the expected"); } if (addPixelIndexes.isEmpty()) { return; } int c0 = pixIdxs.size(); // to keep adding to block totals, square and factor by count again double tmpBlockTotals = blockTotals; if (blockTotals > 0) { double norm = 255.f/(blockTotals + eps); div(h, norm); } long tmpSum = 0; long tmpSumErrSq = 0; double maxValue; long[] tmp = new long[h.length]; int[] xy = new int[2]; PixelHelper ph = new PixelHelper(); //TODO: correct to use a scan by cell size pattern TIntIterator iter = addPixelIndexes.iterator(); while (iter.hasNext()) { int pixIdx = iter.next(); if (pixIdxs.contains(pixIdx)) { continue; } pixIdxs.add(pixIdx); ph.toPixelCoords(pixIdx, imgW, xy); hcpt.extractBlock(xy[0], xy[1], tmp); HOGs.add(h, tmp); tmpSum = 0; maxValue = Double.NEGATIVE_INFINITY; for (int j = 0; j < tmp.length; ++j) { tmpSum += tmp[j]; if (tmp[j] > maxValue) { maxValue = tmp[j]; } } maxValue += eps; tmpBlockTotals += tmpSum; tmpSum /= tmp.length; tmpSumErrSq += ((tmpSum/maxValue)*(tmpSum/maxValue)); } int nAdded = pixIdxs.size() - c0; int c1 = pixIdxs.size(); if (c1 > 0) { this.blockTotals = tmpBlockTotals; } double norm = 1./(blockTotals + eps); float maxBlock = 255.f; norm *= maxBlock; mult(h, norm); //TODO: examine the order of divide by count and sqrt this.err *= this.err; this.err *= c0; this.err += tmpSumErrSq; this.err /= (double)c1; this.err = Math.sqrt(err); } public void add(TIntSet addPixelIndexes, HGS hgs) { if (hgs.getNumberOfBins() != h.length) { throw new IllegalArgumentException( "hog number of bins differs the expected"); } if (hgs.getImageWidth() != imgW) { throw new IllegalArgumentException( "hog image width differs the expected"); } if (hgs.getImageHeight() != imgH) { throw new IllegalArgumentException( "hog image height differs the expected"); } if (addPixelIndexes.isEmpty()) { return; } int c0 = pixIdxs.size(); // to keep adding to block totals, square and factor by count again double tmpBlockTotals = blockTotals; if (blockTotals > 0) { double norm = 255.f/(blockTotals + eps); div(h, norm); } long tmpSum = 0; long tmpSumErrSq = 0; double maxValue; long[] tmp = new long[h.length]; int[] xy = new int[2]; PixelHelper ph = new PixelHelper(); //TODO: correct to use a scan by cell size pattern TIntIterator iter = addPixelIndexes.iterator(); while (iter.hasNext()) { int pixIdx = iter.next(); if (pixIdxs.contains(pixIdx)) { continue; } pixIdxs.add(pixIdx); ph.toPixelCoords(pixIdx, imgW, xy); hgs.extractBlock(xy[0], xy[1], tmp); HOGs.add(h, tmp); tmpSum = 0; maxValue = Double.NEGATIVE_INFINITY; for (int j = 0; j < tmp.length; ++j) { tmpSum += tmp[j]; if (tmp[j] > maxValue) { maxValue = tmp[j]; } } maxValue += eps; tmpBlockTotals += tmpSum; tmpSum /= tmp.length; tmpSumErrSq += ((tmpSum/maxValue)*(tmpSum/maxValue)); } int nAdded = pixIdxs.size() - c0; int c1 = pixIdxs.size(); if (c1 > 0) { this.blockTotals = tmpBlockTotals; } double norm = 1./(blockTotals + eps); float maxBlock = 255.f; norm *= maxBlock; mult(h, norm); //TODO: examine the order of divide by count and sqrt this.err *= this.err; this.err *= c0; this.err += tmpSumErrSq; this.err /= (double)c1; this.err = Math.sqrt(err); } /** * returns the set of points that is a subset of the intersection, scanned * from center to perimeter by interval of size hog cell. * @param other * @param nCellSize * @return */ public TIntSet calculateDetectorWindow(PatchUtil other, int nCellSize) { Intersection2DPacking ip = new Intersection2DPacking(); TIntSet seeds = ip.naiveStripPacking(pixIdxs, other.pixIdxs, imgW, nCellSize); return seeds; } /** * calculate the intersection of the histograms. histograms that are * identical have a result of 1.0 and histograms that are completely * different have a result of 0. * * @param other * @return */ public double intersection(PatchUtil other) { if ((h.length != other.h.length)) { throw new IllegalArgumentException( "h and other.h must be same dimensions"); } int nBins = h.length; double sum = 0; double sumA = 0; double sumB = 0; for (int j = 0; j < nBins; ++j) { long yA = h[j]; long yB = other.h[j]; sum += Math.min(yA, yB); sumA += yA; sumB += yB; //System.out.println(" " + yA + " -- " + yB + " sum="+sum + ", " + sumA + "," + sumB); } double d = eps + Math.min(sumA, sumB); double sim = sum/d; return sim; } /** * calculate the difference of the histograms. histograms that are * identical have a result of 0.0 and histograms that are completely * different have a result of 1. * * @param other * @return */ public double[] diff(PatchUtil other) { if ((h.length != other.h.length)) { throw new IllegalArgumentException( "h and other.h must be same dimensions"); } int nBins = h.length; double tmpSumDiff = 0; double tmpErr = 0; for (int j = 0; j < nBins; ++j) { long yA = h[j]; long yB = other.h[j]; float maxValue = Math.max(yA, yB) + eps; float diff = Math.abs((yA - yB)/maxValue); tmpSumDiff += diff; // already squared tmpErr += (diff/maxValue); } tmpSumDiff /= (double)nBins; tmpErr /= (double)nBins; tmpErr = Math.sqrt(tmpErr); return new double[]{tmpSumDiff, tmpErr}; } private void mult(long[] a, double factor) { double t; for (int j = 0; j < a.length; ++j) { t = factor * a[j]; a[j] = (long)t; } } private void div(long[] a, double factor) { if (factor == 0) { throw new IllegalArgumentException("factor cannot be 0"); } double t; for (int j = 0; j < a.length; ++j) { t = a[j] / factor; a[j] = (long)t; } } public double getAvgErr() { return Math.sqrt(err); } public long[] getHistogram() { return h; } public TIntSet getPixelIndexes() { return pixIdxs; } public Set<PairInt> getPixelSet() { PixelHelper ph = new PixelHelper(); int[] xy = new int[2]; Set<PairInt> set = new HashSet<PairInt>(); TIntIterator iter = pixIdxs.iterator(); while (iter.hasNext()) { int pixIdx = iter.next(); ph.toPixelCoords(pixIdx, imgW, xy); set.add(new PairInt(xy[0], xy[1])); } return set; } }
mit
jandk/editor
src/main/java/be/tjoener/editor/model/Movable.java
124
package be.tjoener.editor.model; public interface Movable { Point getPosition(); void moveTo(Point position); }
mit
cstudioteam/csFrame
handywedge-master/handywedge-core/src/main/java/com/handywedge/context/FWRequestContextImpl.java
616
/* * Copyright (c) 2019 Handywedge Co.,Ltd. * * This software is released under the MIT License. * * http://opensource.org/licenses/mit-license.php */ package com.handywedge.context; import java.util.Date; import javax.enterprise.context.RequestScoped; import com.handywedge.context.FWRequestContext; import lombok.Data; @Data @RequestScoped public class FWRequestContextImpl implements FWRequestContext { private String requestId; private String contextPath; private Date requestStartTime; private boolean rest; private String token; private String requestUrl; private String preToken; }
mit
Nikolay-Kha/TabletClock
app/src/main/java/lcf/clock/prefs/CityDialog.java
4834
package lcf.clock.prefs; import java.util.List; import lcf.clock.R; import lcf.weather.CitiesCallback; import lcf.weather.City; import lcf.weather.WeatherMain; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.inputmethod.EditorInfo; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import android.widget.TextView.OnEditorActionListener; public class CityDialog extends PrefsDialog implements OnEditorActionListener, OnClickListener, OnItemClickListener { private TextView mSearchStatus; private ListView mCitiesList; private EditText mSearchLine; private Button mSearchButton; private CityListAdapter mCitiesListAdapter; private SharedPreferences mSharedPreferences; private static final String CITY_NOT_SET = " "; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.city_dialog); setTitle(R.string.cat1_city); applySize(R.id.dcityroot); mSearchStatus = (TextView) findViewById(R.id.searchStatus); mCitiesList = (ListView) findViewById(R.id.citieslist); mSearchLine = (EditText) findViewById(R.id.citysearch); mSearchLine.setOnEditorActionListener(this); mSearchButton = ((Button) findViewById(R.id.buttonSearch)); mSearchButton.setOnClickListener(this); ((Button) findViewById(R.id.button3)) .setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { finish(); } }); mCitiesListAdapter = new CityListAdapter(this); mCitiesList.setAdapter(mCitiesListAdapter); mCitiesList.setOnItemClickListener(this); mSharedPreferences = PreferenceManager .getDefaultSharedPreferences(this); } @Override public void onClick(View v) { search(false); } @Override public boolean onEditorAction(TextView view, int actionId, KeyEvent event) { if (actionId == EditorInfo.IME_ACTION_DONE) { if (event != null && event.isShiftPressed()) { return false; } search(false); return true; } return false; } @Override protected void onResume() { super.onResume(); String c = getCityName(mSharedPreferences, this); if (c.length() != 0 && !c.equals(CITY_NOT_SET)) { int p = c.lastIndexOf(","); if (p > 0) { mSearchLine.setText(c.substring(0, p)); } } else { search(true); } } private void search(boolean byIp) { mCitiesListAdapter.clear(); mCitiesList.setVisibility(View.GONE); mSearchStatus.setVisibility(View.VISIBLE); mSearchLine.setEnabled(false); mSearchButton.setEnabled(false); mSearchStatus.setText(R.string.search_process); CitiesCallback cc = new CitiesCallback() { @Override public void ready(List<City> result) { if (result == null || result.size() == 0) { if (getPattern() != null) { mSearchStatus.setText(R.string.notfound); } else { mSearchStatus.setText(""); } } else { mSearchStatus.setText(""); mSearchStatus.setVisibility(View.GONE); mCitiesList.setVisibility(View.VISIBLE); for (int i = 0; i < result.size(); i++) { mCitiesListAdapter.add(result.get(i)); } } mSearchLine.setEnabled(true); mSearchButton.setEnabled(true); } }; if (byIp) { WeatherMain.findNearestCitiesByCurrentIP(cc); } else { String s = mSearchLine.getText().toString(); if (s.length() == 0) { WeatherMain.findNearestCitiesByCurrentIP(cc); } else { WeatherMain.findCities(s, cc); } } } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { City c = mCitiesListAdapter.getItem(position); mSharedPreferences .edit() .putString(getString(R.string.key_city), CityListAdapter.getCityReadable(c, this)) .putInt(getString(R.string.key_city_id), c.getId()).commit(); finish(); } public static boolean checkFirstTime(SharedPreferences sharedPreferences, Context context) { if (getCityName(sharedPreferences, context).length() == 0) { sharedPreferences .edit() .putString(context.getString(R.string.key_city), CITY_NOT_SET).commit(); return true; } return false; } public static String getCityName(SharedPreferences sharedPreferences, Context context) { return sharedPreferences.getString( context.getString(R.string.key_city), ""); } public static int getCityId(SharedPreferences sharedPreferences, Context context) { return sharedPreferences.getInt( context.getString(R.string.key_city_id), 0); } }
mit
iogav/Partner-Center-Java-SDK
PartnerSdk/src/main/java/com/microsoft/store/partnercenter/usage/SubscriptionDailyUsageRecordCollectionOperations.java
3167
// ----------------------------------------------------------------------- // <copyright file="SubscriptionDailyUsageRecordCollectionOperations.java" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // ----------------------------------------------------------------------- package com.microsoft.store.partnercenter.usage; import java.text.MessageFormat; import java.util.Locale; import com.fasterxml.jackson.core.type.TypeReference; import com.microsoft.store.partnercenter.BasePartnerComponent; import com.microsoft.store.partnercenter.IPartner; import com.microsoft.store.partnercenter.PartnerService; import com.microsoft.store.partnercenter.models.ResourceCollection; import com.microsoft.store.partnercenter.models.usage.SubscriptionDailyUsageRecord; import com.microsoft.store.partnercenter.models.utils.Tuple; import com.microsoft.store.partnercenter.network.PartnerServiceProxy; import com.microsoft.store.partnercenter.utils.StringHelper; /** * Implements operations related to a single subscription daily usage records. */ public class SubscriptionDailyUsageRecordCollectionOperations extends BasePartnerComponent<Tuple<String, String>> implements ISubscriptionDailyUsageRecordCollection { /** * Initializes a new instance of the {@link #SubscriptionDailyUsageRecordCollectionOperations} class. * * @param rootPartnerOperations The root partner operations instance. * @param customerId The customer Id. * @param subscriptionId The subscription id. */ public SubscriptionDailyUsageRecordCollectionOperations( IPartner rootPartnerOperations, String customerId, String subscriptionId ) { super( rootPartnerOperations, new Tuple<String, String>( customerId, subscriptionId ) ); if ( StringHelper.isNullOrWhiteSpace( customerId ) ) { throw new IllegalArgumentException( "customerId should be set." ); } if ( StringHelper.isNullOrWhiteSpace( subscriptionId ) ) { throw new IllegalArgumentException( "subscriptionId should be set." ); } } /** * Retrieves the subscription daily usage records. * * @return Collection of subscription daily usage records. */ @Override public ResourceCollection<SubscriptionDailyUsageRecord> get() { PartnerServiceProxy<SubscriptionDailyUsageRecord, ResourceCollection<SubscriptionDailyUsageRecord>> partnerServiceProxy = new PartnerServiceProxy<SubscriptionDailyUsageRecord, ResourceCollection<SubscriptionDailyUsageRecord>>( new TypeReference<ResourceCollection<SubscriptionDailyUsageRecord>>() { }, this.getPartner(), MessageFormat.format( PartnerService.getInstance().getConfiguration().getApis().get( "GetSubscriptionDailyUsageRecords" ).getPath(), this.getContext().getItem1(), this.getContext().getItem2(), Locale.US ) ); return partnerServiceProxy.get(); } }
mit
spearsandshields/RecJ
HelloWorld/HelloWorld.java
110
public class HelloWorld{ public static void main(String[] args) { System.out.println("Hello, World"); } }
mit
el-groucho/jsRules
src/main/java/org/grouchotools/jsrules/config/Config.java
1230
/* * The MIT License * * Copyright 2015 Paul. * * 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.grouchotools.jsrules.config; /** * * @author Paul */ public interface Config { }
mit
arhughes/droidchatty
src/cc/hughes/droidchatty/SearchResult.java
661
package cc.hughes.droidchatty; public class SearchResult { private int _postId; private String _author; private String _content; private String _posted; public SearchResult(int postId, String author, String content, String posted) { _postId = postId; _author = author; _content = content; _posted = posted; } public int getPostId() { return _postId; } public String getAuthor() { return _author; } public String getContent() { return _content; } public String getPosted() { return _posted; } }
mit
lauw/mustached-octo-happiness
app/src/main/java/com/muller/wikimagesearch/volley/GsonRequest.java
1897
package com.muller.wikimagesearch.volley; import com.android.volley.AuthFailureError; import com.android.volley.NetworkResponse; import com.android.volley.ParseError; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.toolbox.HttpHeaderParser; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonSyntaxException; import com.muller.wikimagesearch.model.Query; import java.io.UnsupportedEncodingException; import java.util.Map; public class GsonRequest<T> extends Request<T> { private final Gson gson; private final Class<T> clazz; private final Response.Listener<T> listener; /** * Make a GET request and return a parsed object from JSON. * * @param url URL of the request to make * @param clazz Relevant class object, for Gson's reflection */ public GsonRequest(String url, Class<T> clazz, Response.Listener<T> listener, Response.ErrorListener errorListener) { super(Method.GET, url, errorListener); this.gson = new GsonBuilder().registerTypeAdapter(Query.class, new Query.GsonDeserializer()).create(); this.clazz = clazz; this.listener = listener; } @Override public Map<String, String> getHeaders() throws AuthFailureError { return super.getHeaders(); } @Override protected void deliverResponse(T response) { listener.onResponse(response); } @Override protected Response<T> parseNetworkResponse(NetworkResponse response) { try { String json = new String(response.data, HttpHeaderParser.parseCharset(response.headers)); return Response.success(gson.fromJson(json, clazz), HttpHeaderParser.parseCacheHeaders(response)); } catch (UnsupportedEncodingException e) { return Response.error(new ParseError(e)); } catch (JsonSyntaxException e) { return Response.error(new ParseError(e)); } } }
mit
eileenzhuang1/mozu-java
mozu-java-core/src/main/java/com/mozu/api/clients/commerce/orders/FulfillmentActionClient.java
3797
/** * This code was auto-generated by a Codezu. * * Changes to this file may cause incorrect behavior and will be lost if * the code is regenerated. */ package com.mozu.api.clients.commerce.orders; import java.util.List; import java.util.ArrayList; import com.mozu.api.MozuClient; import com.mozu.api.MozuUrl; import com.mozu.api.Headers; import com.mozu.api.security.AuthTicket; import org.apache.commons.lang3.StringUtils; /** <summary> * Use the Fulfillment resource to manage shipments or pickups of collections of packages for an order. * </summary> */ public class FulfillmentActionClient { /** * Sets the fulfillment action to "Ship" or "PickUp". To ship an order or prepare it for in-store pickup, the order must have a customer name, the "Open" or "OpenAndProcessing" status. To ship the order, it must also have the full shipping address and shipping method. Shipping all packages or picking up all pickups for an order will complete a paid order. * <p><pre><code> * MozuClient<com.mozu.api.contracts.commerceruntime.orders.Order> mozuClient=PerformFulfillmentActionClient( action, orderId); * client.setBaseAddress(url); * client.executeRequest(); * Order order = client.Result(); * </code></pre></p> * @param orderId Unique identifier of the order for which to perform the fulfillment action. * @param action The action to perform for the order fulfillment. * @return Mozu.Api.MozuClient <com.mozu.api.contracts.commerceruntime.orders.Order> * @see com.mozu.api.contracts.commerceruntime.orders.Order * @see com.mozu.api.contracts.commerceruntime.fulfillment.FulfillmentAction */ public static MozuClient<com.mozu.api.contracts.commerceruntime.orders.Order> performFulfillmentActionClient(com.mozu.api.contracts.commerceruntime.fulfillment.FulfillmentAction action, String orderId) throws Exception { return performFulfillmentActionClient( action, orderId, null); } /** * Sets the fulfillment action to "Ship" or "PickUp". To ship an order or prepare it for in-store pickup, the order must have a customer name, the "Open" or "OpenAndProcessing" status. To ship the order, it must also have the full shipping address and shipping method. Shipping all packages or picking up all pickups for an order will complete a paid order. * <p><pre><code> * MozuClient<com.mozu.api.contracts.commerceruntime.orders.Order> mozuClient=PerformFulfillmentActionClient( action, orderId, responseFields); * client.setBaseAddress(url); * client.executeRequest(); * Order order = client.Result(); * </code></pre></p> * @param orderId Unique identifier of the order for which to perform the fulfillment action. * @param responseFields Updated order with a new fulfillment status resulting from the action supplied in the request. * @param action The action to perform for the order fulfillment. * @return Mozu.Api.MozuClient <com.mozu.api.contracts.commerceruntime.orders.Order> * @see com.mozu.api.contracts.commerceruntime.orders.Order * @see com.mozu.api.contracts.commerceruntime.fulfillment.FulfillmentAction */ public static MozuClient<com.mozu.api.contracts.commerceruntime.orders.Order> performFulfillmentActionClient(com.mozu.api.contracts.commerceruntime.fulfillment.FulfillmentAction action, String orderId, String responseFields) throws Exception { MozuUrl url = com.mozu.api.urls.commerce.orders.FulfillmentActionUrl.performFulfillmentActionUrl(orderId, responseFields); String verb = "POST"; Class<?> clz = com.mozu.api.contracts.commerceruntime.orders.Order.class; MozuClient<com.mozu.api.contracts.commerceruntime.orders.Order> mozuClient = new MozuClient(clz); mozuClient.setVerb(verb); mozuClient.setResourceUrl(url); mozuClient.setBody(action); return mozuClient; } }
mit
taomanwai/a5steak
glocation/src/test/java/com/tommytao/a5steak/glocation/ExampleUnitTest.java
323
package com.tommytao.a5steak.glocation; 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
openforis/collect
collect-server/src/main/java/org/openforis/collect/web/manager/SessionRecordProvider.java
1273
package org.openforis.collect.web.manager; import java.util.HashMap; import java.util.Map; import org.openforis.collect.manager.CachedRecordProvider; import org.openforis.collect.model.CollectRecord; import org.openforis.collect.model.CollectRecord.Step; import org.openforis.collect.model.CollectSurvey; public class SessionRecordProvider extends CachedRecordProvider { private CachedRecordProvider delegate; private Map<Integer, CollectRecord> recordsPreviewBySurvey = new HashMap<Integer, CollectRecord>(); public SessionRecordProvider(CachedRecordProvider cachedRecordProvider) { super(null); this.delegate = cachedRecordProvider; } @Override public CollectRecord provide(CollectSurvey survey, Integer recordId, Step recordStep) { if (recordId == null) { // Preview record return this.recordsPreviewBySurvey.get(survey.getId()); } else { return delegate.provide(survey, recordId, recordStep); } } public void putRecord(CollectRecord record) { if (record.isPreview()) { this.recordsPreviewBySurvey.put(record.getSurvey().getId(), record); } else { delegate.putRecord(record); } } @Override public void clearRecords(int surveyId) { delegate.clearRecords(surveyId); this.recordsPreviewBySurvey.remove(surveyId); } }
mit
yangra/SoftUni
JavaFundamentals/JavaOOPBasic/03.InheritanceExercise/src/_04MordorsCrueltyPlan/Wizard.java
1184
package _04MordorsCrueltyPlan; import java.util.HashMap; import java.util.List; import java.util.Map; public class Wizard { private static final Map<String, Integer> FOODS = new HashMap<String, Integer>() {{ put("cram", 2); put("lembas", 3); put("apple", 1); put("melon", 1); put("honeycake", 5); put("mushrooms", -10); }}; public int getHappinessIndex() { return this.happinessIndex; } private int happinessIndex; public void setHappinessIndex(List<String> foods) { foods.forEach(this::eatFood); } public String getMood() { if (this.happinessIndex < -5) { return "Angry"; } else if (this.happinessIndex <= 0) { return "Sad"; } else if (this.happinessIndex <= 15) { return "Happy"; } else { return "JavaScript"; } } private void eatFood(String food) { String foodLowerName = food.toLowerCase(); if (FOODS.containsKey(foodLowerName)) { this.happinessIndex += FOODS.get(foodLowerName); } else { this.happinessIndex -= 1; } } }
mit
gsoertsz/dojo-services
src/main/java/org/distributedproficiency/dojo/dto/KataSaveRequest.java
503
package org.distributedproficiency.dojo.dto; import org.distributedproficiency.dojo.domain.KataContent; public class KataSaveRequest { private KataContent newContent; public KataSaveRequest() { super(); } public KataSaveRequest(KataContent c) { super(); this.newContent = c; } public KataContent getNewContent() { return newContent; } public void setNewContent(KataContent newContent) { this.newContent = newContent; } }
mit
arjunvnair/ParfA
src/ASTStringLiteral.java
289
public class ASTStringLiteral extends SimpleNode { String val; public ASTStringLiteral(int id) { super(id); } public ASTStringLiteral(ParfA p, int id) { super(p, id); } public void interpret() { ParfANode.stack[++ParfANode.p] = new String(val); } }
mit
akyker20/Slogo_IDE
src/commandParsing/drawableObectGenerationInterfaces/ShapePaletteUpdateGenerator.java
1028
package commandParsing.drawableObectGenerationInterfaces; import gui.factories.ShapePaletteEntryFactory; import java.util.HashMap; import java.util.Map; import workspaceState.Shape; import drawableobject.DrawableObject; /** * This class generates the actual ShapePaletteUpdate drawableObjects to give to the GUI. * * @author Stanley Yuan, Steve Kuznetsov * */ public interface ShapePaletteUpdateGenerator { default public DrawableObject generateDrawableObjectRepresentingShapePaletteUpdate (int index, Shape shape) { String parent = ShapePaletteEntryFactory.PARENT; String type = ShapePaletteEntryFactory.TYPE; Map<String, String> parameters = new HashMap<String, String>(); parameters.put(ShapePaletteEntryFactory.INDEX, Integer.toString(index)); parameters.put(ShapePaletteEntryFactory.IMAGE_PATH, shape.getPath()); return new DrawableObject(parent, type, parameters); } }
mit
ZherebtsovAlexandr/Object-oriented-robot
sample/ObjectOrientedRobot/Data/src/com/mansonheart/data/Repository.java
238
package com.mansonheart.data; import java.util.Objects; /** * Created by alexandr on 18.09.16. */ public class Repository { public Object get() { return new Object(); } public void add(Object object) { } }
mit
sci10n/Quake2D
core/src/se/sciion/quake2d/level/Statistics.java
4664
package se.sciion.quake2d.level; import java.io.File; import com.badlogic.gdx.files.FileHandle; import com.badlogic.gdx.utils.ObjectMap; import se.sciion.quake2d.ai.behaviour.BehaviourTree; import se.sciion.quake2d.level.items.Weapon; public class Statistics { private ObjectMap<BehaviourTree,Float> totalDamageGiven; private ObjectMap<BehaviourTree,Float> totalDamageTaken; private ObjectMap<BehaviourTree,Float> armorAtEnd; private ObjectMap<BehaviourTree,Float> healthAtEnd; private ObjectMap<BehaviourTree,Boolean> survived; private ObjectMap<BehaviourTree,Integer> killcount; private ObjectMap<BehaviourTree,Integer> roundsPlayed; private ObjectMap<BehaviourTree,Integer> pickedWeapon; public Statistics() { totalDamageGiven = new ObjectMap<BehaviourTree,Float>(); totalDamageTaken = new ObjectMap<BehaviourTree,Float>(); armorAtEnd = new ObjectMap<BehaviourTree,Float>(); healthAtEnd = new ObjectMap<BehaviourTree,Float>(); survived = new ObjectMap<BehaviourTree,Boolean>(); killcount = new ObjectMap<BehaviourTree,Integer>(); roundsPlayed = new ObjectMap<BehaviourTree, Integer>(); pickedWeapon = new ObjectMap<BehaviourTree, Integer>(); } public void recordDamageTaken(BehaviourTree giver, BehaviourTree reciever, float amount) { if(giver != null) { if(!totalDamageGiven.containsKey(giver)) { totalDamageGiven.put(giver, 0.0f); } totalDamageGiven.put(giver, totalDamageGiven.get(giver) + amount); } if(reciever != null) { if(!totalDamageTaken.containsKey(reciever)) { totalDamageTaken.put(reciever, 0.0f); } totalDamageTaken.put(reciever, totalDamageTaken.get(reciever) + amount); } } public void recordHealth(float health, float armor, BehaviourTree entity) { if(entity == null) { return; } armorAtEnd.put(entity, armor); healthAtEnd.put(entity, health); } public void recordWeaponPickup(BehaviourTree tree){ if(!pickedWeapon.containsKey(tree)){ pickedWeapon.put(tree, 0); } pickedWeapon.put(tree, pickedWeapon.get(tree) + 1); } public void recordParticipant(BehaviourTree tree){ if(!roundsPlayed.containsKey(tree)){ roundsPlayed.put(tree, 0); } roundsPlayed.put(tree, roundsPlayed.get(tree) + 1); } public void recordSurvivior(BehaviourTree entity) { if(entity == null) { return; } survived.put(entity, true); } public void recordKill(BehaviourTree giver) { if(giver == null) { return; } if(!killcount.containsKey(giver)) { killcount.put(giver, 0); } killcount.put(giver, killcount.get(giver) + 1); } public float getFitness(BehaviourTree tree) { float damageGiven = totalDamageGiven.get(tree, 0.0f); float damageTaken = totalDamageTaken.get(tree, 0.0f); float armor = armorAtEnd.get(tree, 0.0f); //float health = healthAtEnd.get(tree,0.0f); int killcount = this.killcount.get(tree, 0); boolean survived = this.survived.get(tree, false); int rounds = roundsPlayed.get(tree,1); int weapon = pickedWeapon.get(tree, 0); return (5.0f * damageGiven + 2.0f * armor + (survived ? 500.0f : 0.0f) + 50.0f * weapon + 1000.0f * killcount) / (float)(rounds); } public boolean hasSurvived(BehaviourTree tree) { return survived.get(tree, false); } public int getTotalKillcount() { int total = 0; for(Integer i: killcount.values()) { total += i; } return total; } @Override public String toString() { String output = "Match statistics:\n"; for(BehaviourTree tree: totalDamageGiven.keys()) { output += "Tree: " + tree.toString() + " damage given: " + totalDamageGiven.get(tree) + "\n"; } for(BehaviourTree tree: totalDamageTaken.keys()) { output += "Tree: " + tree.toString() + " damage taken: " + totalDamageGiven.get(tree) + "\n"; } for(BehaviourTree tree: healthAtEnd.keys()) { output += "Tree: " + tree.toString() + " " + healthAtEnd.get(tree,0.0f) + " health at end\n"; } for(BehaviourTree tree: armorAtEnd.keys()) { output += "Tree: " + tree.toString() + " " + armorAtEnd.get(tree,0.0f) + " armor at end\n"; } for(BehaviourTree tree: survived.keys()) { output += "Tree: " + tree.toString() + " survived\n"; } for(BehaviourTree tree: roundsPlayed.keys()) { output += "Tree: " + tree.toString() + " played " + roundsPlayed.get(tree) + " rounds\n"; } for(BehaviourTree tree: pickedWeapon.keys()) { output += "Tree: " + tree.toString() + " picked weapon\n"; } return output; } public void clear() { armorAtEnd.clear(); healthAtEnd.clear(); killcount.clear(); survived.clear(); totalDamageGiven.clear(); totalDamageTaken.clear(); pickedWeapon.clear(); roundsPlayed.clear(); } }
mit
cezarykluczynski/stapi
etl/src/main/java/com/cezarykluczynski/stapi/etl/template/starship_class/dto/StarshipClassTemplateParameter.java
546
package com.cezarykluczynski.stapi.etl.template.starship_class.dto; public class StarshipClassTemplateParameter { public static final String NAME = "name"; public static final String OWNER = "owner"; public static final String OPERATOR = "operator"; public static final String AFFILIATION = "affiliation"; public static final String DECKS = "decks"; public static final String SPEED = "speed"; public static final String TYPE = "type"; public static final String ACTIVE = "active"; public static final String ARMAMENT = "armament"; }
mit
EvilMcJerkface/jessy
src/fr/inria/jessy/transaction/termination/vote/VotePiggyback.java
817
package fr.inria.jessy.transaction.termination.vote; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import fr.inria.jessy.ConstantPool; /** * * @author Masoud Saeida Ardekani * */ public class VotePiggyback implements Externalizable { private static final long serialVersionUID = -ConstantPool.JESSY_MID; Object piggyback; public VotePiggyback() { } public VotePiggyback(Object piggyback) { this.piggyback = piggyback; } public Object getPiggyback() { return piggyback; } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { piggyback = in.readObject(); } @Override public void writeExternal(ObjectOutput out) throws IOException { out.writeObject(piggyback); } }
mit
GiovanniSM20/Java
src/ExFixacao_02/src/controller/Ex_5.java
330
package controller; import java.text.DecimalFormat; import util.Teclado; public class Ex_5 { public static void main(String[] args){ double salario; salario = Teclado.lerDouble("Digite o salário desejado: "); DecimalFormat df = new DecimalFormat("R$ ###, ###, ###.00"); System.out.println(df.format(salario)); } }
mit
devsunny/mt-rpc-server
src/main/java/com/asksunny/rpc/admin/AdminRPCRuntime.java
1997
package com.asksunny.rpc.admin; import java.util.concurrent.ExecutorService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.asksunny.protocol.rpc.RPCAdminCommand; import com.asksunny.protocol.rpc.RPCAdminEnvelope; import com.asksunny.protocol.rpc.RPCEnvelope; import com.asksunny.rpc.mtserver.RPCRuntime; public class AdminRPCRuntime implements RPCRuntime{ ExecutorService executorService; final static Logger log = LoggerFactory.getLogger(AdminRPCRuntime.class); public ExecutorService getExecutorService() { return executorService; } public void setExecutorService(ExecutorService executorService) { this.executorService = executorService; } public RPCEnvelope invoke(RPCEnvelope request) throws Exception { RPCAdminEnvelope adminRequest = (RPCAdminEnvelope)request; RPCAdminEnvelope response = new RPCAdminEnvelope(); response.setRpcType(RPCEnvelope.RPC_TYPE_RESPONSE); RPCAdminCommand cmd = RPCAdminCommand.valueOf(adminRequest.getAdminCommand()); if(cmd == RPCAdminCommand.PING ){ response.setAdminCommand(RPCAdminCommand.PING); response.addRpcObjects(System.currentTimeMillis()); }else if(cmd == RPCAdminCommand.ECHO ){ response.setAdminCommand(RPCAdminCommand.ECHO); response.setRpcObjects(request.getRpcObjects()); }else if(cmd == RPCAdminCommand.UPTIME ){ response.setAdminCommand(RPCAdminCommand.UPTIME); response.addRpcObjects(System.currentTimeMillis()); }else if(cmd == RPCAdminCommand.STATUS ){ response.setAdminCommand(RPCAdminCommand.STATUS); response.addRpcObjects(System.currentTimeMillis()); }else if(cmd == RPCAdminCommand.HEARTBEAT ){ response.setAdminCommand(RPCAdminCommand.HEARTBEAT); response.addRpcObjects(System.currentTimeMillis()); }else if(cmd == RPCAdminCommand.SHUTDOWN ){ System.exit(0); } return response; } public boolean accept(RPCEnvelope envelope) throws Exception { return envelope.getRpcType()==RPCEnvelope.RPC_ENVELOPE_TYPE_ADMIN; } }
mit
SpongePowered/SpongeCommon
src/main/java/org/spongepowered/common/registry/type/world/gen/BiomeTreeTypeRegistryModule.java
5058
/* * 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.registry.type.world.gen; import net.minecraft.block.BlockLeaves; import net.minecraft.block.BlockOldLeaf; import net.minecraft.block.BlockOldLog; import net.minecraft.block.BlockPlanks; import net.minecraft.block.state.IBlockState; import net.minecraft.init.Blocks; import net.minecraft.world.gen.feature.WorldGenBigTree; import net.minecraft.world.gen.feature.WorldGenBirchTree; import net.minecraft.world.gen.feature.WorldGenCanopyTree; import net.minecraft.world.gen.feature.WorldGenMegaJungle; import net.minecraft.world.gen.feature.WorldGenMegaPineTree; import net.minecraft.world.gen.feature.WorldGenSavannaTree; import net.minecraft.world.gen.feature.WorldGenShrub; import net.minecraft.world.gen.feature.WorldGenSwamp; import net.minecraft.world.gen.feature.WorldGenTaiga1; import net.minecraft.world.gen.feature.WorldGenTaiga2; import net.minecraft.world.gen.feature.WorldGenTrees; import net.minecraft.world.gen.feature.WorldGenerator; import org.spongepowered.api.registry.util.RegisterCatalog; import org.spongepowered.api.util.weighted.VariableAmount; import org.spongepowered.api.world.gen.PopulatorObject; import org.spongepowered.api.world.gen.type.BiomeTreeType; import org.spongepowered.api.world.gen.type.BiomeTreeTypes; import org.spongepowered.common.bridge.world.gen.WorldGenTreesBridge; import org.spongepowered.common.registry.type.AbstractPrefixAlternateCatalogTypeRegistryModule; import org.spongepowered.common.world.gen.type.SpongeBiomeTreeType; import javax.annotation.Nullable; @RegisterCatalog(BiomeTreeTypes.class) public class BiomeTreeTypeRegistryModule extends AbstractPrefixAlternateCatalogTypeRegistryModule<BiomeTreeType> { public BiomeTreeTypeRegistryModule() { super("minecraft"); } @Override public void registerDefaults() { register(create("oak", new WorldGenTrees(false), new WorldGenBigTree(false))); register(create("birch", new WorldGenBirchTree(false, false), new WorldGenBirchTree(false, true))); WorldGenMegaPineTree tall_megapine = new WorldGenMegaPineTree(false, true); WorldGenMegaPineTree megapine = new WorldGenMegaPineTree(false, false); register(create("tall_taiga", new WorldGenTaiga2(false), tall_megapine)); register(create("pointy_taiga", new WorldGenTaiga1(), megapine)); IBlockState jlog = Blocks.LOG.getDefaultState() .withProperty(BlockOldLog.VARIANT, BlockPlanks.EnumType.JUNGLE); IBlockState jleaf = Blocks.LEAVES.getDefaultState() .withProperty(BlockOldLeaf.VARIANT, BlockPlanks.EnumType.JUNGLE) .withProperty(BlockLeaves.CHECK_DECAY, Boolean.valueOf(false)); IBlockState leaf = Blocks.LEAVES.getDefaultState() .withProperty(BlockOldLeaf.VARIANT, BlockPlanks.EnumType.JUNGLE) .withProperty(BlockLeaves.CHECK_DECAY, Boolean.valueOf(false)); WorldGenTreesBridge trees = (WorldGenTreesBridge) new WorldGenTrees(false, 4, jlog, jleaf, true); trees.bridge$setMinHeight(VariableAmount.baseWithRandomAddition(4, 7)); WorldGenMegaJungle mega = new WorldGenMegaJungle(false, 10, 20, jlog, jleaf); register(create("jungle", (WorldGenTrees) trees, mega)); WorldGenShrub bush = new WorldGenShrub(jlog, leaf); register(create("jungle_bush", bush, null)); register(create("savanna", new WorldGenSavannaTree(false), null)); register(create("canopy", new WorldGenCanopyTree(false), null)); register(create("swamp", new WorldGenSwamp(), null)); } private SpongeBiomeTreeType create(String name, WorldGenerator small, @Nullable WorldGenerator large) { return new SpongeBiomeTreeType("minecraft:" + name, name, (PopulatorObject) small, (PopulatorObject) large); } }
mit
Avocarrot/android-adapters
avocarrot-app-sample/src/main/java/com/avocarrot/adapters/sample/admob/AdmobNativeActivity.java
8086
package com.avocarrot.adapters.sample.admob; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.view.View; import android.widget.Button; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.RatingBar; import android.widget.TextView; import android.widget.Toast; import com.avocarrot.adapters.sample.R; import com.google.android.gms.ads.AdListener; import com.google.android.gms.ads.AdLoader; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.formats.NativeAd; import com.google.android.gms.ads.formats.NativeAppInstallAd; import com.google.android.gms.ads.formats.NativeAppInstallAdView; import com.google.android.gms.ads.formats.NativeContentAd; import com.google.android.gms.ads.formats.NativeContentAdView; import java.util.List; public class AdmobNativeActivity extends AppCompatActivity { @NonNull private static final String EXTRA_AD_UNIT_ID = "ad_unit_id"; @NonNull public static Intent buildIntent(@NonNull final Context context, @NonNull final String adUnitId) { return new Intent(context, AdmobNativeActivity.class).putExtra(EXTRA_AD_UNIT_ID, adUnitId); } @Override protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_admob_native); final Intent intent = getIntent(); final String adUnitId = intent.getStringExtra(EXTRA_AD_UNIT_ID); if (TextUtils.isEmpty(adUnitId)) { finish(); return; } final AdLoader adLoader = new AdLoader.Builder(this, adUnitId) .forAppInstallAd(new NativeAppInstallAd.OnAppInstallAdLoadedListener() { @Override public void onAppInstallAdLoaded(final NativeAppInstallAd ad) { final FrameLayout frameLayout = (FrameLayout) findViewById(R.id.admob_ad_view); final NativeAppInstallAdView adView = (NativeAppInstallAdView) getLayoutInflater().inflate(R.layout.admob_ad_app_install, null); populate(ad, adView); frameLayout.removeAllViews(); frameLayout.addView(adView); } }) .forContentAd(new NativeContentAd.OnContentAdLoadedListener() { @Override public void onContentAdLoaded(final NativeContentAd ad) { final FrameLayout frameLayout = (FrameLayout) findViewById(R.id.admob_ad_view); final NativeContentAdView adView = (NativeContentAdView) getLayoutInflater().inflate(R.layout.admob_ad_content, null); populate(ad, adView); frameLayout.removeAllViews(); frameLayout.addView(adView); } }) .withAdListener(new AdListener() { @Override public void onAdFailedToLoad(final int errorCode) { Toast.makeText(getApplicationContext(), "Custom event native ad failed with code: " + errorCode, Toast.LENGTH_LONG).show(); } }) .build(); adLoader.loadAd(new AdRequest.Builder().build()); final ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); } } /** * Populates a {@link NativeAppInstallAdView} object with data from a given {@link NativeAppInstallAd}. */ private void populate(@NonNull final NativeAppInstallAd nativeAppInstallAd, @NonNull final NativeAppInstallAdView adView) { adView.setNativeAd(nativeAppInstallAd); adView.setHeadlineView(adView.findViewById(R.id.appinstall_headline)); adView.setImageView(adView.findViewById(R.id.appinstall_image)); adView.setBodyView(adView.findViewById(R.id.appinstall_body)); adView.setCallToActionView(adView.findViewById(R.id.appinstall_call_to_action)); adView.setIconView(adView.findViewById(R.id.appinstall_app_icon)); adView.setPriceView(adView.findViewById(R.id.appinstall_price)); adView.setStarRatingView(adView.findViewById(R.id.appinstall_stars)); adView.setStoreView(adView.findViewById(R.id.appinstall_store)); // Some assets are guaranteed to be in every NativeAppInstallAd. ((TextView) adView.getHeadlineView()).setText(nativeAppInstallAd.getHeadline()); ((TextView) adView.getBodyView()).setText(nativeAppInstallAd.getBody()); ((Button) adView.getCallToActionView()).setText(nativeAppInstallAd.getCallToAction()); ((ImageView) adView.getIconView()).setImageDrawable(nativeAppInstallAd.getIcon().getDrawable()); final List<NativeAd.Image> images = nativeAppInstallAd.getImages(); if (images.size() > 0) { ((ImageView) adView.getImageView()).setImageDrawable(images.get(0).getDrawable()); } // Some aren't guaranteed, however, and should be checked. if (nativeAppInstallAd.getPrice() == null) { adView.getPriceView().setVisibility(View.INVISIBLE); } else { adView.getPriceView().setVisibility(View.VISIBLE); ((TextView) adView.getPriceView()).setText(nativeAppInstallAd.getPrice()); } if (nativeAppInstallAd.getStore() == null) { adView.getStoreView().setVisibility(View.INVISIBLE); } else { adView.getStoreView().setVisibility(View.VISIBLE); ((TextView) adView.getStoreView()).setText(nativeAppInstallAd.getStore()); } if (nativeAppInstallAd.getStarRating() == null) { adView.getStarRatingView().setVisibility(View.INVISIBLE); } else { ((RatingBar) adView.getStarRatingView()).setRating(nativeAppInstallAd.getStarRating().floatValue()); adView.getStarRatingView().setVisibility(View.VISIBLE); } } /** * Populates a {@link NativeContentAdView} object with data from a given {@link NativeContentAd}. */ private void populate(@NonNull final NativeContentAd nativeContentAd, @NonNull final NativeContentAdView adView) { adView.setNativeAd(nativeContentAd); adView.setHeadlineView(adView.findViewById(R.id.contentad_headline)); adView.setImageView(adView.findViewById(R.id.contentad_image)); adView.setBodyView(adView.findViewById(R.id.contentad_body)); adView.setCallToActionView(adView.findViewById(R.id.contentad_call_to_action)); adView.setLogoView(adView.findViewById(R.id.contentad_logo)); adView.setAdvertiserView(adView.findViewById(R.id.contentad_advertiser)); // Some assets are guaranteed to be in every NativeContentAd. ((TextView) adView.getHeadlineView()).setText(nativeContentAd.getHeadline()); ((TextView) adView.getBodyView()).setText(nativeContentAd.getBody()); ((TextView) adView.getCallToActionView()).setText(nativeContentAd.getCallToAction()); ((TextView) adView.getAdvertiserView()).setText(nativeContentAd.getAdvertiser()); final List<NativeAd.Image> images = nativeContentAd.getImages(); if (images.size() > 0) { ((ImageView) adView.getImageView()).setImageDrawable(images.get(0).getDrawable()); } // Some aren't guaranteed, however, and should be checked. final NativeAd.Image logoImage = nativeContentAd.getLogo(); if (logoImage == null) { adView.getLogoView().setVisibility(View.INVISIBLE); } else { ((ImageView) adView.getLogoView()).setImageDrawable(logoImage.getDrawable()); adView.getLogoView().setVisibility(View.VISIBLE); } } }
mit
yiping999/springcloud-pig
user-service/src/main/java/com/piggymetrics/user/domain/User.java
1115
package com.piggymetrics.user.domain; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.NamedQuery; @Entity @NamedQuery(name = "User.findByName", query = "select name,address from User u where u.name=?1") public class User implements Serializable { private static final long serialVersionUID = 1L; @Id long id; @Column(name = "name") String name; @Column(name = "address") String address; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return this.id + "," + this.name + "," + this.address; } }
mit
HKMOpen/UrbanDicSDK
urbanSDK/urbansdk/src/main/java/com/hkm/urbansdk/gson/NullStringToEmptyAdapterFactory.java
1266
package com.hkm.urbansdk.gson; import com.google.gson.Gson; import com.google.gson.TypeAdapter; import com.google.gson.TypeAdapterFactory; import com.google.gson.reflect.TypeToken; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; import com.google.gson.stream.JsonWriter; import java.io.IOException; /** * Created by hesk on 2/17/15. */ public class NullStringToEmptyAdapterFactory<T> implements TypeAdapterFactory { public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) { Class<T> rawType = (Class<T>) type.getRawType(); if (!rawType.equals(String.class)) { return null; } return (TypeAdapter<T>) new StringAdapter(); } public class StringAdapter extends TypeAdapter<String> { public String read(JsonReader reader) throws IOException { if (reader.peek() == JsonToken.NULL) { reader.nextNull(); return ""; } return reader.nextString(); } public void write(JsonWriter writer, String value) throws IOException { if (value == null) { writer.nullValue(); return; } writer.value(value); } } }
mit
gravitylow/TravelPad
src/main/java/net/h31ix/travelpad/api/UnnamedPad.java
884
package net.h31ix.travelpad.api; import net.h31ix.travelpad.LangManager; import org.bukkit.Location; import org.bukkit.entity.Player; /** * <p> * Defines a new Unnamed TravelPad on the map, this is only used before a pad is named by the player. */ public class UnnamedPad { private Location location = null; private Player owner = null; public UnnamedPad(Location location, Player owner) { this.location = location; this.owner = owner; } /** * Get the location of the pad * * @return location Location of the obsidian center of the pad */ public Location getLocation() { return location; } /** * Get the owner of the pad * * @return owner Player who owns the pad's name */ public Player getOwner() { return owner; } }
mit
kicholen/jelly-gp-server
src/main/java/jelly/exception/level/LevelNotFound.java
85
package jelly.exception.level; public class LevelNotFound extends Exception { }
mit
sadikovi/algorithms
src/Prime.java
1245
public class Prime { private Prime() { } public static void printPrimes(int max) { boolean[] flags = sieveOfEratosthenes(max); System.out.println("== Primes up to " + max + " =="); for (int i = 0; i < flags.length; i++) { if (flags[i]) { System.out.println("* " + i); } } } public static boolean[] sieveOfEratosthenes(int max) { boolean[] flags = new boolean[max + 1]; // initialize flags except 0 and 1 for (int i = 2; i < flags.length; i++) { flags[i] = true; } int prime = 2; while (prime * prime <= max) { crossOff(flags, prime); prime = getNextPrime(flags, prime); } return flags; } private static void crossOff(boolean[] flags, int prime) { for (int i = prime * prime; i < flags.length; i += prime) { flags[i] = false; } } private static int getNextPrime(boolean[] flags, int prime) { int next = prime + 1; while (next < flags.length && !flags[next]) { next++; } return next; } public static boolean isPrime(int num) { if (num < 2) return false; int prime = 2; while (prime * prime <= num) { if (num % prime == 0) return false; ++prime; } return true; } }
mit
PantryPrep/PantryPrep
app/src/main/java/com/sonnytron/sortatech/pantryprep/Fragments/IngredientFilters/ProteinFragment.java
872
package com.sonnytron.sortatech.pantryprep.Fragments.IngredientFilters; import android.os.Bundle; import com.sonnytron.sortatech.pantryprep.Fragments.IngredientsListFragment; import com.sonnytron.sortatech.pantryprep.Models.Ingredient; import com.sonnytron.sortatech.pantryprep.Service.IngredientManager; import java.util.List; public class ProteinFragment extends IngredientsListFragment { public ProteinFragment() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public void updateUI() { IngredientManager ingredientManager = IngredientManager.get(getActivity()); List<Ingredient> ingredients = ingredientManager.getIngredientsProtein(); addAll(ingredients); setSpinner(1); } }
mit
joltix/Cinnamon
com/cinnamon/object/BodyFactory.java
2496
package com.cinnamon.object; import com.cinnamon.system.ComponentFactory; import com.cinnamon.system.Config; import com.cinnamon.utils.Shape; /** * <p> * Provides {@link BodyComponent} lookup when computing physics updates. * </p> */ public abstract class BodyFactory extends ComponentFactory<BodyComponent, Object> { // Width to use when body's instantiated private static final float DEFAULT_WIDTH = 1f; // Height to use when body's instantiated private static final float DEFAULT_HEIGHT = 1f; /** * <p>Constructs a BodyFactory.</p> * * @param object resource for constructing {@link BodyComponent}s. * @param load initial BodyComponent capacity. * @param growth normalized capacity expansion. */ protected BodyFactory(Object object, int load, float growth) { super(object, load, growth); } /** * <p>Gets a {@link BodyComponent} of a specific mass.</p> * * @param mass in kilograms. * @return body. */ public final BodyComponent get(float mass) { final BodyComponent body = super.get(); // Set mass before being used body.setMass(mass); return body; } @Override public final BodyComponent get() { return super.get(); } @Override public final BodyComponent get(String configName) { return super.get(configName); } @Override public final BodyComponent get(int id, int version) { return super.get(id, version); } @Override public final BodyComponent get(int id) { return super.get(id); } @Override protected final BodyComponent createIdentifiable() { return new BodyComponent(new Shape(DEFAULT_WIDTH, DEFAULT_HEIGHT)); } @Override public final BodyComponent remove(int id, int version) { return super.remove(id, version); } @Override public final BodyComponent remove(int id) { return super.remove(id); } @Override public final Config<BodyComponent, Object> getConfig(String name) { return super.getConfig(name); } @Override public final Config<BodyComponent, Object> addConfig(String name, Config<BodyComponent, Object> config) { return super.addConfig(name, config); } @Override public final Config<BodyComponent, Object> removeConfig(String name) { return super.removeConfig(name); } }
mit
javicacheiro/hadoop-on-demand-rest-jhipster
src/main/java/es/cesga/hadoop/service/package-info.java
65
/** * Service layer beans. */ package es.cesga.hadoop.service;
mit
vpmalley/tpblogr
app/src/main/java/blogr/vpm/fr/blogr/activity/PostContentEditionActions.java
2107
package blogr.vpm.fr.blogr.activity; import android.view.ActionMode; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.EditText; import blogr.vpm.fr.blogr.R; import blogr.vpm.fr.blogr.format.AlignCenterTagsProvider; import blogr.vpm.fr.blogr.format.AlignLeftTagsProvider; import blogr.vpm.fr.blogr.format.AlignRightTagsProvider; import blogr.vpm.fr.blogr.insertion.Inserter; import blogr.vpm.fr.blogr.insertion.WikipediaLinkTagsProvider; /** * Created by vince on 11/05/15. */ public class PostContentEditionActions implements ActionMode.Callback { private final Inserter inserter; private final EditText editText; public PostContentEditionActions(Inserter inserter, EditText editText) { this.inserter = inserter; this.editText = editText; } @Override public boolean onCreateActionMode(ActionMode actionMode, Menu menu) { MenuInflater inflater = actionMode.getMenuInflater(); inflater.inflate(R.menu.postcontentedition, menu); return true; } @Override public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) { return false; } @Override public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) { switch (menuItem.getItemId()) { case R.id.action_wiki_link: if (editText.getSelectionStart() < editText.getSelectionEnd()) { String articleName = editText.getText().toString().substring(editText.getSelectionStart(), editText.getSelectionEnd()); inserter.insert(editText, new WikipediaLinkTagsProvider(articleName)); } return true; case R.id.action_align_left: inserter.insert(editText, new AlignLeftTagsProvider()); return true; case R.id.action_align_center: inserter.insert(editText, new AlignCenterTagsProvider()); return true; case R.id.action_align_right: inserter.insert(editText, new AlignRightTagsProvider()); return true; } return false; } @Override public void onDestroyActionMode(ActionMode actionMode) { } }
mit
awylie/carcassonne
src/main/java/net/andrewwylie/carcassonne/net/server/SocketServerProtocol.java
1236
package net.server; import java.net.Socket; import net.client.SocketClientProtocol; public abstract class SocketServerProtocol extends SocketClientProtocol { /** * Allow a sender to be added to the socket protocol's list of senders. * * This can be useful to send messages to clients which are not the current * senders, though which are affected by the actions of the current sender. * * @param sender * A Socket object which is tied to the sender object. */ public abstract void addSender(Socket sender); /** * Allow a sender to be removed from the socket protocol's list of senders. * * @param sender * A Socket object which is tied to the sender object. */ public abstract void removeSender(Socket sender); /** * Get the maximum number of allowed client connections to this protocol. * * @return an integer representing the maximum number of allowed * connections. */ public abstract int getMaxConnections(); /** * Get the current number of clients connected to this protocol. * * @return an integer representing the current number of connections. */ public abstract int getNumConnections(); }
mit
lqd-io/android-examples
personalization/src/main/java/com/onliquid/personalization/MainActivity.java
1370
package com.onliquid.personalization; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import io.lqd.sdk.Liquid; import java.util.HashMap; public class MainActivity extends Activity { private Liquid lqd; protected void onCreate(Bundle bundle) { super.onCreate(bundle); setContentView(R.layout.activity_main); lqd = Liquid.getInstance(); } public void enterSecondActivity(String username) { Intent intent = new Intent(this, SecondActivity.class); intent.putExtra("user", username); startActivity(intent); } public void login(View view) { String username = ""; HashMap attrs = new HashMap(); switch (view.getId()) { case R.id.jack: attrs.put("age", 23); attrs.put("gender", "male"); username = "Jack"; break; case R.id.jill: attrs.put("age", 32); attrs.put("gender", "female"); username = "Jill"; break; case R.id.jonas: attrs.put("age", 35); attrs.put("gender", "male"); username = "Jonas"; } lqd.identifyUser(username, attrs); enterSecondActivity(username); } }
mit
rayjun/awesome-algorithm
leetcode/hashtable/LeetCode171.java
817
import java.util.HashMap; import java.util.Map; public class LeetCode171 { public int titleToNumber(String s) { char[] chars = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'}; Map<Character, Integer> map = new HashMap<Character, Integer>(); for (int i = 1; i <= chars.length; i++) { map.put(chars[i-1], i); } int result = 0; for (int i = s.length() -1; i >= 0; i--) { int num1 = map.get(s.charAt(i)); int pow = (int) Math.pow(26, s.length() -1 -i); result += num1 * pow; } return result; } public static void main(String[] args) { LeetCode171 leetCode171 = new LeetCode171(); System.out.println(leetCode171.titleToNumber("ZY")); } }
mit
baluubas/XBMC-Widget
XBMCWidget/src/com/anderspersson/xbmcwidget/remote/RemoteWidget.java
2278
package com.anderspersson.xbmcwidget.remote; import com.anderspersson.xbmcwidget.R; import com.anderspersson.xbmcwidget.xbmc.XbmcService; import android.app.PendingIntent; import android.appwidget.AppWidgetProvider; import android.appwidget.AppWidgetManager; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.widget.RemoteViews; public class RemoteWidget extends AppWidgetProvider { @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { RemoteViews remoteViews; ComponentName remoteWidget; remoteViews = new RemoteViews( context.getPackageName(), R.layout.remote_widget ); remoteWidget = new ComponentName( context, RemoteWidget.class ); Intent intent = new Intent(context, XbmcService.class); context.startService(intent); setupButton(context, remoteViews, XbmcService.PLAYPAUSE_ACTION, R.id.playpause); setupButton(context, remoteViews, XbmcService.UP_ACTION, R.id.up); setupButton(context, remoteViews, XbmcService.DOWN_ACTION, R.id.down); setupButton(context, remoteViews, XbmcService.LEFT_ACTION, R.id.left); setupButton(context, remoteViews, XbmcService.RIGHT_ACTION, R.id.right); setupButton(context, remoteViews, XbmcService.SELECT_ACTION, R.id.select); setupButton(context, remoteViews, XbmcService.BACK_ACTION, R.id.back); setupButton(context, remoteViews, XbmcService.TOGGLE_FULLSCREEN_ACTION, R.id.togglefullscreen); setupButton(context, remoteViews, XbmcService.TOGGLE_OSD_ACTION, R.id.toggleosd); setupButton(context, remoteViews, XbmcService.HOME_ACTION, R.id.home); setupButton(context, remoteViews, XbmcService.CONTEXT_ACTION, R.id.context); appWidgetManager.updateAppWidget( remoteWidget, remoteViews ); } private void setupButton(Context context, RemoteViews remoteViews, String action, int id) { Intent playIntent = new Intent(context, XbmcService.class); playIntent.setAction(action); PendingIntent pendingIntent = PendingIntent.getService(context, 0, playIntent, 0); remoteViews.setOnClickPendingIntent(id, pendingIntent); } }
mit
000ubird/JikkenII
src/com/jikken2/ConnectDB_PP.java
2503
package com.jikken2; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import android.annotation.SuppressLint; import android.app.Activity; import android.app.ProgressDialog; import android.os.AsyncTask; @SuppressLint("NewApi") public class ConnectDB_PP extends AsyncTask<Void, Void, String> { private static String URL = "172.29.139.104/db_group_a"; private static String USER = "group_a"; private static String PASS = "m4we6baq"; private static int TIMEOUT = 5; private Activity act = null; private String sql = ""; private ProgressDialog dialog; private ResultSet rs = null; private String sta = ""; private double longi; private double lati; private AsyncTaskCallback callback = null;; public interface AsyncTaskCallback { void preExecute(); void postExecute(String result); void progressUpdate(int progress); void cancel(); } public ConnectDB_PP(Activity act) { this.act = act; } public ConnectDB_PP(Activity act, String sql) { this.act = act; this.sql = sql; } public ConnectDB_PP(Activity act, String sql, AsyncTaskCallback _callback) { this.act = act; this.sql = sql; this.callback = _callback; } public String getSta() { return sta; } public double getLati() { return lati; } public double getLongi() { return longi; } @Override protected void onPreExecute() { super.onPreExecute(); callback.preExecute(); this.dialog = new ProgressDialog(this.act); this.dialog.setMessage("Connecting..."); this.dialog.show(); } @Override protected String doInBackground(Void... arg0) { String text = ""; try { // JDBC load Class.forName("com.mysql.jdbc.Driver"); // time out DriverManager.setLoginTimeout(TIMEOUT); // connect to DB Connection con = DriverManager.getConnection("jdbc:mysql://" + URL, USER, PASS); Statement stmt = con.createStatement(); // execute query rs = stmt.executeQuery(sql); while (rs.next()) { sta += rs.getString("station"); lati += rs.getDouble("latitude"); longi += rs.getDouble("longitude"); } rs.close(); stmt.close(); con.close(); } catch (Exception e) { // text = e.getMessage(); text = "螟ア謨�"; sta = "螟ア謨�"; } return text; } protected void onPostExecute(String result) { super.onPostExecute(result); callback.postExecute(result); if (this.dialog != null && this.dialog.isShowing()) { this.dialog.dismiss(); } } }
mit
daveayan/rjson
src/main/java/com/daveayan/rjson/utils/RjsonUtil.java
4825
/* * Copyright (c) 2011 Ayan Dave http://daveayan.com * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and * associated documentation files (the "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the * following conditions: * * 1) The above copyright notice and this permission notice shall be included without any changes or alterations * in all copies or substantial portions of the Software. * 2) The copyright notice part of the org.json package and its classes shall be honored. * 3) This software shall be used for Good, not Evil. * portions of the Software. * * The copyright notice part of the org.json package and its classes shall be honored. * This software shall be used for Good, not Evil. * * 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.daveayan.rjson.utils; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import com.daveayan.json.JSONArray; import com.daveayan.json.JSONException; import com.daveayan.json.JSONObject; import com.daveayan.json.JSONTokener; import com.daveayan.rjson.Rjson; import com.daveayan.rjson.transformer.BaseTransformer; public class RjsonUtil { private static Log log = LogFactory.getLog(BaseTransformer.class); public static Object getJsonObject(String json) throws JSONException { log.debug("getJsonObject for " + json); if(StringUtils.isEmpty(json)) { return ""; } JSONTokener tokener = new JSONTokener(json); char firstChar = tokener.nextClean(); if (firstChar == '\"') { return tokener.nextString('\"'); } if (firstChar == '{') { tokener.back(); return new JSONObject(tokener); } if (firstChar == '[') { tokener.back(); return new JSONArray(tokener); } if (Character.isDigit(firstChar)) { tokener.back(); return tokener.nextValue(); } tokener.back(); return tokener.nextValue(); } public static String reformat(String inputJson) { String outputJson = new String(inputJson); try { JSONObject jo = new JSONObject(inputJson.toString()); outputJson = jo.toString(2); } catch (JSONException e) { } return outputJson; } public static Object fileAsObject(String filename) throws IOException { return Rjson.newInstance().toObject(fileAsString(filename)); } public static String fileAsString(String file) throws IOException { return FileUtils.readFileToString(new File(file)).replaceAll("\\r\\n", "\n"); } public static Rjson completeSerializer() { return Rjson.newInstance().with(new NullifyDateTransformer()).andRecordAllModifiers(); } public static Rjson pointInTimeSerializer() { return Rjson.newInstance().andRecordAllModifiers().andRecordFinal().andDoNotFormatJson(); } public static void recordJsonToFile(Object object, String absolutePath) { recordJsonToFile(object, absolutePath, RjsonUtil.completeSerializer()); } public static void recordJsonToFile(Object object, String absolutePath, Rjson rjson) { try { FileUtils.writeStringToFile(new File(absolutePath), rjson.toJson(object)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static String escapeJsonCharactersIn(String string) { String newString = StringUtils.replace(string, "\"", ""); newString = StringUtils.replace(newString, "[", "\\["); newString = StringUtils.replace(newString, "]", "\\]"); newString = StringUtils.replace(newString, "{", "\\{"); newString = StringUtils.replace(newString, "}", "\\}"); return newString; } public static String unEscapeJsonCharactersIn(String string) { String newString = StringUtils.replace(string, "\"", ""); newString = StringUtils.replace(newString, "\\[", "["); newString = StringUtils.replace(newString, "\\]", "]"); newString = StringUtils.replace(newString, "\\{", "{"); newString = StringUtils.replace(newString, "\\}", "}"); return newString; } }
mit
ls1intum/ArTEMiS
src/main/java/de/tum/in/www1/artemis/repository/ModelingSubmissionRepository.java
3605
package de.tum.in.www1.artemis.repository; import java.util.List; import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import de.tum.in.www1.artemis.domain.modeling.ModelingSubmission; /** * Spring Data JPA repository for the ModelingSubmission entity. */ @SuppressWarnings("unused") @Repository public interface ModelingSubmissionRepository extends JpaRepository<ModelingSubmission, Long> { @Query("select distinct submission from ModelingSubmission submission left join fetch submission.result r left join fetch r.assessor where submission.id = :#{#submissionId}") Optional<ModelingSubmission> findByIdWithEagerResult(@Param("submissionId") Long submissionId); @Query("select distinct submission from ModelingSubmission submission left join fetch submission.result r left join fetch r.feedbacks left join fetch r.assessor where submission.id = :#{#submissionId}") Optional<ModelingSubmission> findByIdWithEagerResultAndFeedback(@Param("submissionId") Long submissionId); @Query("select distinct submission from ModelingSubmission submission left join fetch submission.participation p left join fetch submission.result r left join fetch r.feedbacks where p.exercise.id = :#{#exerciseId} and r.assessmentType = 'MANUAL'") List<ModelingSubmission> findByExerciseIdWithEagerResultsWithManualAssessment(@Param("exerciseId") Long exerciseId); @Query("select distinct submission from ModelingSubmission submission left join fetch submission.result r left join fetch r.feedbacks where submission.exampleSubmission = true and submission.id = :#{#submissionId}") Optional<ModelingSubmission> findExampleSubmissionByIdWithEagerResult(@Param("submissionId") Long submissionId); /** * @param courseId the course we are interested in * @param submitted boolean to check if an exercise has been submitted or not * @return number of submissions belonging to courseId with submitted status */ long countByParticipation_Exercise_Course_IdAndSubmitted(Long courseId, boolean submitted); /** * @param courseId the course id we are interested in * @return the number of submissions belonging to the course id, which have the submitted flag set to true and the submission date before the exercise due date, or no exercise * due date at all */ @Query("SELECT COUNT (DISTINCT submission) FROM ModelingSubmission submission WHERE submission.participation.exercise.course.id = :#{#courseId} AND submission.submitted = TRUE AND (submission.submissionDate < submission.participation.exercise.dueDate OR submission.participation.exercise.dueDate IS NULL)") long countByCourseIdSubmittedBeforeDueDate(@Param("courseId") Long courseId); /** * @param exerciseId the exercise id we are interested in * @return the number of submissions belonging to the exercise id, which have the submitted flag set to true and the submission date before the exercise due date, or no * exercise due date at all */ @Query("SELECT COUNT (DISTINCT submission) FROM ModelingSubmission submission WHERE submission.participation.exercise.id = :#{#exerciseId} AND submission.submitted = TRUE AND (submission.submissionDate < submission.participation.exercise.dueDate OR submission.participation.exercise.dueDate IS NULL)") long countByExerciseIdSubmittedBeforeDueDate(@Param("exerciseId") Long exerciseId); }
mit
shaunmahony/seqcode
src/edu/psu/compbio/seqcode/gse/ewok/nouns/GeneDomainTimeSeries.java
897
package edu.psu.compbio.seqcode.gse.ewok.nouns; import java.util.Vector; import edu.psu.compbio.seqcode.gse.datasets.species.Gene; public class GeneDomainTimeSeries { public static final int window = 30000; private Gene gene; private Vector<GeneDomainData> data; public GeneDomainTimeSeries(Gene g, int tps) { gene = g; data = new Vector<GeneDomainData>(); for(int i = 0; i < tps; i++) { data.add(new GeneDomainData(gene, window)); } } public void addDomain(SimpleDomain sd, int tp) { data.get(tp).addDomain(sd); } public boolean isCovered(int tp) { return data.get(tp).isTSSCovered(); } public String getBitString() { String str = ""; for(int i = 0; i < data.size(); i++) { str += isCovered(i) ? "1" : "0"; } return str; } public String toString() { return gene.getID() + " " + getBitString(); } }
mit
digammas/damas
solutions.digamma.damas.api/src/main/java/solutions/digamma/damas/common/CompatibilityException.java
651
package solutions.digamma.damas.common; /** * Exception occurs in case of incompatibility between DMS items. For example * this exception should be thrown when an identifier of existing but * incompatible item is passed to a method. * * @author Ahmad Shahwan */ public class CompatibilityException extends MisuseException { public CompatibilityException() { super(); } public CompatibilityException(String message) { super(message); } public CompatibilityException(Exception e) { super(e); } public CompatibilityException(String message, Exception e) { super(message, e); } }
mit
Azure/azure-sdk-for-java
sdk/resourcemanager/azure-resourcemanager/src/samples/java/com/azure/resourcemanager/storage/generated/TableCreateSamples.java
925
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.storage.generated; import com.azure.core.util.Context; /** Samples for Table Create. */ public final class TableCreateSamples { /* * x-ms-original-file: specification/storage/resource-manager/Microsoft.Storage/stable/2021-08-01/examples/TableOperationPut.json */ /** * Sample code: TableOperationPut. * * @param azure The entry point for accessing resource management APIs in Azure. */ public static void tableOperationPut(com.azure.resourcemanager.AzureResourceManager azure) { azure .storageAccounts() .manager() .serviceClient() .getTables() .createWithResponse("res3376", "sto328", "table6185", Context.NONE); } }
mit
SpongeHistory/Sponge-History
src/main/java/org/spongepowered/mod/mixin/api/text/title/MixinTitle.java
3524
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered.org <http://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.mod.mixin.api.text.title; import com.google.common.base.Optional; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.network.play.server.S45PacketTitle; import org.spongepowered.api.text.Text; import org.spongepowered.api.text.title.Title; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; import org.spongepowered.mod.text.SpongeText; import org.spongepowered.mod.text.title.SpongeTitle; import java.util.Arrays; @Mixin(value = Title.class, remap = false) public abstract class MixinTitle implements SpongeTitle { @Shadow protected Optional<Text> title; @Shadow protected Optional<Text> subtitle; @Shadow protected Optional<Integer> fadeIn; @Shadow protected Optional<Integer> stay; @Shadow protected Optional<Integer> fadeOut; @Shadow protected boolean clear; @Shadow protected boolean reset; private S45PacketTitle[] packets; public boolean isFlowerPot() { return false; } @Override public void send(EntityPlayerMP player) { if (this.packets == null) { S45PacketTitle[] packets = new S45PacketTitle[5]; int i = 0; if (this.clear) { packets[i++] = new S45PacketTitle(S45PacketTitle.Type.CLEAR, null); } if (this.reset) { packets[i++] = new S45PacketTitle(S45PacketTitle.Type.RESET, null); } if (this.fadeIn.isPresent() || this.stay.isPresent() || this.fadeOut.isPresent()) { packets[i++] = new S45PacketTitle(this.fadeIn.or(20), this.stay.or(60), this.fadeOut.or(20)); } if (this.subtitle.isPresent()) { packets[i++] = new S45PacketTitle(S45PacketTitle.Type.SUBTITLE, ((SpongeText) this.subtitle.get()).toComponent()); } if (this.title.isPresent()) { packets[i++] = new S45PacketTitle(S45PacketTitle.Type.TITLE, ((SpongeText) this.title.get()).toComponent()); } this.packets = i == packets.length ? packets : Arrays.copyOf(packets, i); } for (S45PacketTitle packet : this.packets) { player.playerNetServerHandler.sendPacket(packet); } } }
mit
tom5454/ARKCraft
src/main/java/com/uberverse/arkcraft/common/item/ranged/ItemSlingshot.java
84
package com.uberverse.arkcraft.common.item.ranged; public class ItemSlingshot { }
mit