repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
ganguo/yingping_rn
Yingping/android/OfficialOpenSDK/src/main/java/com/share/api/interfaces/alipay/AlipayShareType.java
240
package com.share.api.interfaces.alipay; /** * Created by aaron on 6/23/16. * 支付宝分享类型 * 1.文本 * 2.图片 * 3.网页 */ public interface AlipayShareType<T> { T isText(); T isImage(); T isWebpage(); }
mit
Azure/azure-sdk-for-java
sdk/resourcemanager/azure-resourcemanager-cdn/src/main/java/com/azure/resourcemanager/cdn/implementation/ValidatesClientImpl.java
9487
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.cdn.implementation; import com.azure.core.annotation.BodyParam; import com.azure.core.annotation.ExpectedResponses; import com.azure.core.annotation.HeaderParam; import com.azure.core.annotation.Headers; import com.azure.core.annotation.Host; import com.azure.core.annotation.HostParam; import com.azure.core.annotation.PathParam; import com.azure.core.annotation.Post; import com.azure.core.annotation.QueryParam; import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceInterface; import com.azure.core.annotation.ServiceMethod; import com.azure.core.annotation.UnexpectedResponseExceptionType; import com.azure.core.http.rest.Response; import com.azure.core.http.rest.RestProxy; import com.azure.core.management.exception.ManagementException; import com.azure.core.util.Context; import com.azure.core.util.FluxUtil; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.cdn.fluent.ValidatesClient; import com.azure.resourcemanager.cdn.fluent.models.ValidateSecretOutputInner; import com.azure.resourcemanager.cdn.models.ValidateSecretInput; import reactor.core.publisher.Mono; /** An instance of this class provides access to all the operations defined in ValidatesClient. */ public final class ValidatesClientImpl implements ValidatesClient { private final ClientLogger logger = new ClientLogger(ValidatesClientImpl.class); /** The proxy service used to perform REST calls. */ private final ValidatesService service; /** The service client containing this operation class. */ private final CdnManagementClientImpl client; /** * Initializes an instance of ValidatesClientImpl. * * @param client the instance of the service client containing this operation class. */ ValidatesClientImpl(CdnManagementClientImpl client) { this.service = RestProxy.create(ValidatesService.class, client.getHttpPipeline(), client.getSerializerAdapter()); this.client = client; } /** * The interface defining all the services for CdnManagementClientValidates to be used by the proxy service to * perform REST calls. */ @Host("{$host}") @ServiceInterface(name = "CdnManagementClientV") private interface ValidatesService { @Headers({"Content-Type: application/json"}) @Post("/subscriptions/{subscriptionId}/providers/Microsoft.Cdn/validateSecret") @ExpectedResponses({200}) @UnexpectedResponseExceptionType(ManagementException.class) Mono<Response<ValidateSecretOutputInner>> secret( @HostParam("$host") String endpoint, @PathParam("subscriptionId") String subscriptionId, @QueryParam("api-version") String apiVersion, @BodyParam("application/json") ValidateSecretInput validateSecretInput, @HeaderParam("Accept") String accept, Context context); } /** * Validate a Secret in the profile. * * @param validateSecretInput The Secret source. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return output of the validated secret along with {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<Response<ValidateSecretOutputInner>> secretWithResponseAsync(ValidateSecretInput validateSecretInput) { if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } if (this.client.getSubscriptionId() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getSubscriptionId() is required and cannot be null.")); } if (validateSecretInput == null) { return Mono .error(new IllegalArgumentException("Parameter validateSecretInput is required and cannot be null.")); } else { validateSecretInput.validate(); } final String accept = "application/json"; return FluxUtil .withContext( context -> service .secret( this.client.getEndpoint(), this.client.getSubscriptionId(), this.client.getApiVersion(), validateSecretInput, accept, context)) .contextWrite(context -> context.putAll(FluxUtil.toReactorContext(this.client.getContext()).readOnly())); } /** * Validate a Secret in the profile. * * @param validateSecretInput The Secret source. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return output of the validated secret along with {@link Response} on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) private Mono<Response<ValidateSecretOutputInner>> secretWithResponseAsync( ValidateSecretInput validateSecretInput, Context context) { if (this.client.getEndpoint() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getEndpoint() is required and cannot be null.")); } if (this.client.getSubscriptionId() == null) { return Mono .error( new IllegalArgumentException( "Parameter this.client.getSubscriptionId() is required and cannot be null.")); } if (validateSecretInput == null) { return Mono .error(new IllegalArgumentException("Parameter validateSecretInput is required and cannot be null.")); } else { validateSecretInput.validate(); } final String accept = "application/json"; context = this.client.mergeContext(context); return service .secret( this.client.getEndpoint(), this.client.getSubscriptionId(), this.client.getApiVersion(), validateSecretInput, accept, context); } /** * Validate a Secret in the profile. * * @param validateSecretInput The Secret source. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return output of the validated secret on successful completion of {@link Mono}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono<ValidateSecretOutputInner> secretAsync(ValidateSecretInput validateSecretInput) { return secretWithResponseAsync(validateSecretInput) .flatMap( (Response<ValidateSecretOutputInner> res) -> { if (res.getValue() != null) { return Mono.just(res.getValue()); } else { return Mono.empty(); } }); } /** * Validate a Secret in the profile. * * @param validateSecretInput The Secret source. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return output of the validated secret. */ @ServiceMethod(returns = ReturnType.SINGLE) public ValidateSecretOutputInner secret(ValidateSecretInput validateSecretInput) { return secretAsync(validateSecretInput).block(); } /** * Validate a Secret in the profile. * * @param validateSecretInput The Secret source. * @param context The context to associate with this operation. * @throws IllegalArgumentException thrown if parameters fail the validation. * @throws ManagementException thrown if the request is rejected by server. * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent. * @return output of the validated secret along with {@link Response}. */ @ServiceMethod(returns = ReturnType.SINGLE) public Response<ValidateSecretOutputInner> secretWithResponse( ValidateSecretInput validateSecretInput, Context context) { return secretWithResponseAsync(validateSecretInput, context).block(); } }
mit
hanjos/genericcons
src/test/java/org/sbrubbles/genericcons/fixtures/ClassWithMultipleInterfaces.java
203
package org.sbrubbles.genericcons.fixtures; import java.util.List; public class ClassWithMultipleInterfaces implements IOneParameter<String>, ITwoParameters<Integer, List<Double>> { // empty block }
mit
nullbox/Data-and-Information-Visualization-Project
src/big/marketing/data/Node.java
3257
package big.marketing.data; import com.mongodb.BasicDBObject; import com.mongodb.DBObject; /** * @author jaakkju * * #Column 1: IP #Column 2: Host Name. Hosts with a "WSS" prefix are * user workstations. "Administrator" is the administrator workstation. * Others are servers. #Column 3 (Optional): Comments */ public class Node implements DBWritable, Comparable<Node> { public static final int TYPE_WORKSTATION = 0; public static final int TYPE_ADMINISTRATOR = 1; public static final int TYPE_SERVER = 2; private static final String administrator = "Administrator"; private static final String workstation = "WSS"; private final String address; private final String hostName; private final int type; private String comment = null; /** * Constructor takes the one line as a string array from the BigMktNetwork.txt * @param args String array ["IP address, hostname, comment(optional)"] */ public Node(String[] args) { this.address = args[0].trim(); this.hostName = args[1].trim(); if (args.length == 3) { this.comment = args[2].trim(); } if (this.hostName.startsWith(Node.administrator)) { this.type = Node.TYPE_ADMINISTRATOR; } else if (this.hostName.startsWith(Node.workstation)) { this.type = Node.TYPE_WORKSTATION; } else { this.type = Node.TYPE_SERVER; } } public boolean isServer() { return this.type == Node.TYPE_SERVER; } public boolean isWorkstation() { return this.type == Node.TYPE_WORKSTATION; } public boolean isAdministator() { return this.type == Node.TYPE_ADMINISTRATOR; } public String getAddress() { return address; } public String getHostName() { return hostName; } public String getComment() { return comment; } public int getType() { return type; } @Override public String toString() { return this.comment != null ? this.address + " " + this.hostName + " " + this.comment : this.address + " " + this.hostName; } @Override public DBObject asDBObject() { BasicDBObject dbObject = new BasicDBObject(); dbObject.append("address", address); dbObject.append("hostName", hostName); dbObject.append("type", type); dbObject.append("comment", comment); return dbObject; } public Node(DBObject dbo) { this.address = (String) dbo.get("address"); this.hostName = (String) dbo.get("hostName"); this.type = (Integer) dbo.get("type"); this.comment = (String) dbo.get("comment"); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((address == null) ? 0 : address.hashCode()); result = prime * result + ((comment == null) ? 0 : comment.hashCode()); result = prime * result + ((hostName == null) ? 0 : hostName.hashCode()); result = prime * result + type; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof Node)) return false; Node other = (Node) obj; if (hostName == null) { if (other.hostName != null) return false; } else if (!hostName.equals(other.hostName)) return false; return true; } @Override public int compareTo(Node node) { return this.getHostName().compareTo(node.getHostName()); } }
mit
Gruci/g_frog
g_frog/src/main/java/net/frog/services/diners/DinersServiceImpl.java
869
package net.frog.services.diners; import javax.annotation.Resource; import org.springframework.stereotype.Service; import net.frog.dao.diners.DinersDAO; import net.frog.vo.DinersVO; import net.frog.vo.diners.photo.DinersPhotopathVO; @Service("dinersService") public class DinersServiceImpl implements DinersService{ @Resource(name="dinersDAO") private DinersDAO dinersDAO; //private ContentDAO contentDAO; @Override public int count() throws Exception { // return contentDAO.insert(contentVO); return dinersDAO.count(); } @Override public DinersVO dinersDetail(int no) throws Exception{ return dinersDAO.dinersSelect_diners(no); } @Override public String[] dinersPhtopathDetail(int no)throws Exception { // TODO Auto-generated method stub return dinersDAO.dinersSelect_photopath(no); } }
mit
Dacaspex/Fractal
org/jcodec/movtool/streaming/VirtualWebmMovie.java
2337
package org.jcodec.movtool.streaming; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.jcodec.containers.mkv.MKVStreamingMuxer; /** * This class is part of JCodec ( www.jcodec.org ) This software is distributed under FreeBSD License * * WebM specific muxing * * @author The JCodec project * */ public class VirtualWebmMovie extends VirtualMovie { private MKVStreamingMuxer muxer = null; public VirtualWebmMovie(VirtualTrack... arguments) throws IOException { super(arguments); muxer = new MKVStreamingMuxer(); muxTracks(); } @Override protected void muxTracks() throws IOException { List<MovieSegment> chch = new ArrayList<MovieSegment>(); VirtualPacket[] heads = new VirtualPacket[tracks.length], tails = new VirtualPacket[tracks.length]; long currentlyAddedContentSize = 0; for (int curChunk = 1;; curChunk++) { int min = -1; for (int i = 0; i < heads.length; i++) { if (heads[i] == null) { heads[i] = tracks[i].nextPacket(); if (heads[i] == null) continue; } min = min == -1 || heads[i].getPts() < heads[min].getPts() ? i : min; } if (min == -1) break; MovieSegment packetChunk = packetChunk(tracks[min], heads[min], curChunk, min, currentlyAddedContentSize); chch.add(packetChunk); currentlyAddedContentSize += packetChunk.getDataLen(); tails[min] = heads[min]; heads[min] = tracks[min].nextPacket(); } _headerChunk = headerChunk(chch, tracks, _size); _size += _headerChunk.getDataLen()+currentlyAddedContentSize; chunks = chch.toArray(new MovieSegment[0]); } @Override protected MovieSegment packetChunk(VirtualTrack track, VirtualPacket pkt, int chunkNo, int trackNo, long previousClustersSize) { return muxer.preparePacket(track, pkt, chunkNo, trackNo, previousClustersSize); } @Override protected MovieSegment headerChunk(List<MovieSegment> chunks, VirtualTrack[] tracks, long dataSize) throws IOException { return muxer.prepareHeader(chunks, tracks); } }
mit
FLamparski/islondonbridgefucked.com
src-generated/com/thalesgroup/pushport/TSLocation.java
9745
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2015.12.12 at 08:50:47 PM GMT // package com.thalesgroup.pushport; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; /** * Forecast data for an individual location in the service's schedule * * <p>Java class for TSLocation complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="TSLocation"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="arr" type="{http://www.thalesgroup.com/rtti/PushPort/Forecasts/v2}TSTimeData" minOccurs="0"/> * &lt;element name="dep" type="{http://www.thalesgroup.com/rtti/PushPort/Forecasts/v2}TSTimeData" minOccurs="0"/> * &lt;element name="pass" type="{http://www.thalesgroup.com/rtti/PushPort/Forecasts/v2}TSTimeData" minOccurs="0"/> * &lt;element name="plat" type="{http://www.thalesgroup.com/rtti/PushPort/Forecasts/v2}PlatformData" minOccurs="0"/> * &lt;element name="suppr" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/> * &lt;element name="length" type="{http://www.thalesgroup.com/rtti/PushPort/CommonTypes/v1}TrainLengthType" minOccurs="0"/> * &lt;element name="detachFront" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/> * &lt;/sequence> * &lt;attGroup ref="{http://www.thalesgroup.com/rtti/PushPort/CommonTypes/v1}CircularTimes"/> * &lt;attribute name="tpl" use="required" type="{http://www.thalesgroup.com/rtti/PushPort/CommonTypes/v1}TiplocType" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "TSLocation", namespace = "http://www.thalesgroup.com/rtti/PushPort/Forecasts/v2", propOrder = { "arr", "dep", "pass", "plat", "suppr", "length", "detachFront" }) public class TSLocation { protected TSTimeData arr; protected TSTimeData dep; protected TSTimeData pass; protected PlatformData plat; @XmlElement(defaultValue = "false") protected Boolean suppr; @XmlElement(defaultValue = "0") @XmlSchemaType(name = "unsignedShort") protected Integer length; @XmlElement(defaultValue = "false") protected Boolean detachFront; @XmlAttribute(name = "tpl", required = true) protected String tpl; @XmlAttribute(name = "wta") protected String wta; @XmlAttribute(name = "wtd") protected String wtd; @XmlAttribute(name = "wtp") protected String wtp; @XmlAttribute(name = "pta") protected String pta; @XmlAttribute(name = "ptd") protected String ptd; /** * Get the arrival time * * @return * possible object is * {@link TSTimeData } * */ public TSTimeData getArr() { return arr; } /** * Sets the value of the arr property. * * @param value * allowed object is * {@link TSTimeData } * */ public void setArr(TSTimeData value) { this.arr = value; } /** * Get the departure time * * @return * possible object is * {@link TSTimeData } * */ public TSTimeData getDep() { return dep; } /** * Sets the value of the dep property. * * @param value * allowed object is * {@link TSTimeData } * */ public void setDep(TSTimeData value) { this.dep = value; } /** * Get the time at which this train is supposed * to pass the location * * @return * possible object is * {@link TSTimeData } * */ public TSTimeData getPass() { return pass; } /** * Sets the value of the pass property. * * @param value * allowed object is * {@link TSTimeData } * */ public void setPass(TSTimeData value) { this.pass = value; } /** * Get the platform information for this train * * @return * possible object is * {@link PlatformData } * */ public PlatformData getPlat() { return plat; } /** * Sets the value of the plat property. * * @param value * allowed object is * {@link PlatformData } * */ public void setPlat(PlatformData value) { this.plat = value; } /** * True if the train should not be shown to users * (for islondonbridgefucked it still may be worth * to use it for calculations) * * @return * possible object is * {@link Boolean } * */ public Boolean isSuppr() { return suppr; } /** * Sets the value of the suppr property. * * @param value * allowed object is * {@link Boolean } * */ public void setSuppr(Boolean value) { this.suppr = value; } /** * Get train length (in number of cars?) * * @return * possible object is * {@link Integer } * */ public Integer getLength() { return length; } /** * Sets the value of the length property. * * @param value * allowed object is * {@link Integer } * */ public void setLength(Integer value) { this.length = value; } /** * Does the front of the train detach? * * @return * possible object is * {@link Boolean } * */ public Boolean isDetachFront() { return detachFront; } /** * Sets the value of the detachFront property. * * @param value * allowed object is * {@link Boolean } * */ public void setDetachFront(Boolean value) { this.detachFront = value; } /** * The TIPLOC of this Location. Cross-reference * with the official data files and <a href="http://www.railwaycodes.org.uk/CRS/CRS0.shtm">this site</a>. * * @return * possible object is * {@link String } * */ public String getTpl() { return tpl; } /** * Sets the value of the tpl property. * * @param value * allowed object is * {@link String } * */ public void setTpl(String value) { this.tpl = value; } /** * Gets the Working Timetable Arrival time for this train. * Working scheduled time as HH:MM[:SS] * * Working Timetable is not intended for public use, but could * be useful for islondonbridgefucked to determine true delays. * * @return * possible object is * {@link String } * */ public String getWta() { return wta; } /** * Sets the value of the wta property. * * @param value * allowed object is * {@link String } * */ public void setWta(String value) { this.wta = value; } /** * Gets the Working Timetable Departure for this train. * Working scheduled time as HH:MM[:SS] * * @return * possible object is * {@link String } * */ public String getWtd() { return wtd; } /** * Sets the value of the wtd property. * * @param value * allowed object is * {@link String } * */ public void setWtd(String value) { this.wtd = value; } /** * Gets the Working Timetable Pass (ie. when in the * working timetable this train is supposed to pass * this location). * Working scheduled time as HH:MM[:SS] * * @return * possible object is * {@link String } * */ public String getWtp() { return wtp; } /** * Sets the value of the wtp property. * * @param value * allowed object is * {@link String } * */ public void setWtp(String value) { this.wtp = value; } /** * Gets the Public Timetable Arrival. * Time as HH:MM * * @return * possible object is * {@link String } * */ public String getPta() { return pta; } /** * Sets the value of the pta property. * * @param value * allowed object is * {@link String } * */ public void setPta(String value) { this.pta = value; } /** * Gets the Public Timetable Departure. * Time as HH:MM * * @return * possible object is * {@link String } * */ public String getPtd() { return ptd; } /** * Sets the value of the ptd property. * * @param value * allowed object is * {@link String } * */ public void setPtd(String value) { this.ptd = value; } }
mit
smarr/SOMns-vscode
server/org.eclipse.lsp4j-gen/org/eclipse/lsp4j/DidCloseTextDocumentParams.java
2560
/** * Copyright (c) 2016-2018 TypeFox and others. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0, * or the Eclipse Distribution License v. 1.0 which is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause */ package org.eclipse.lsp4j; import org.eclipse.lsp4j.TextDocumentIdentifier; import org.eclipse.lsp4j.jsonrpc.validation.NonNull; import org.eclipse.lsp4j.util.Preconditions; import org.eclipse.xtext.xbase.lib.Pure; import org.eclipse.xtext.xbase.lib.util.ToStringBuilder; /** * The document close notification is sent from the client to the server when the document got closed in the client. * The document's truth now exists where the document's uri points to (e.g. if the document's uri is a file uri the * truth now exists on disk). */ @SuppressWarnings("all") public class DidCloseTextDocumentParams { /** * The document that was closed. */ @NonNull private TextDocumentIdentifier textDocument; public DidCloseTextDocumentParams() { } public DidCloseTextDocumentParams(@NonNull final TextDocumentIdentifier textDocument) { this.textDocument = Preconditions.<TextDocumentIdentifier>checkNotNull(textDocument, "textDocument"); } /** * The document that was closed. */ @Pure @NonNull public TextDocumentIdentifier getTextDocument() { return this.textDocument; } /** * The document that was closed. */ public void setTextDocument(@NonNull final TextDocumentIdentifier textDocument) { this.textDocument = Preconditions.checkNotNull(textDocument, "textDocument"); } @Override @Pure public String toString() { ToStringBuilder b = new ToStringBuilder(this); b.add("textDocument", this.textDocument); return b.toString(); } @Override @Pure public boolean equals(final Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; DidCloseTextDocumentParams other = (DidCloseTextDocumentParams) obj; if (this.textDocument == null) { if (other.textDocument != null) return false; } else if (!this.textDocument.equals(other.textDocument)) return false; return true; } @Override @Pure public int hashCode() { return 31 * 1 + ((this.textDocument== null) ? 0 : this.textDocument.hashCode()); } }
mit
bcvsolutions/CzechIdMng
Realization/backend/core/core-impl/src/test/java/eu/bcvsolutions/idm/core/bulk/action/impl/configuration/ConfigurationSwitchInstanceBulkActionIntegrationTest.java
10424
package eu.bcvsolutions.idm.core.bulk.action.impl.configuration; import java.util.HashMap; import java.util.Map; import java.util.UUID; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import eu.bcvsolutions.idm.core.api.bulk.action.dto.IdmBulkActionDto; import eu.bcvsolutions.idm.core.api.config.domain.EventConfiguration; import eu.bcvsolutions.idm.core.api.domain.OperationState; import eu.bcvsolutions.idm.core.api.domain.PriorityType; import eu.bcvsolutions.idm.core.api.dto.IdmConfigurationDto; import eu.bcvsolutions.idm.core.api.dto.IdmEntityEventDto; import eu.bcvsolutions.idm.core.api.dto.OperationResultDto; import eu.bcvsolutions.idm.core.api.dto.ResultModels; import eu.bcvsolutions.idm.core.api.entity.OperationResult; import eu.bcvsolutions.idm.core.api.service.EntityEventManager; import eu.bcvsolutions.idm.core.api.service.IdmConfigurationService; import eu.bcvsolutions.idm.core.api.service.IdmEntityEventService; import eu.bcvsolutions.idm.core.model.domain.CoreGroupPermission; import eu.bcvsolutions.idm.core.model.entity.IdmConfiguration; import eu.bcvsolutions.idm.core.scheduler.api.dto.IdmLongRunningTaskDto; import eu.bcvsolutions.idm.core.scheduler.api.dto.Task; import eu.bcvsolutions.idm.core.scheduler.api.service.IdmLongRunningTaskService; import eu.bcvsolutions.idm.core.scheduler.api.service.LongRunningTaskManager; import eu.bcvsolutions.idm.core.scheduler.api.service.SchedulerManager; import eu.bcvsolutions.idm.core.scheduler.service.impl.TestSchedulableTask; import eu.bcvsolutions.idm.core.security.api.domain.IdmGroupPermission; import eu.bcvsolutions.idm.test.api.AbstractBulkActionTest; import eu.bcvsolutions.idm.test.api.TestHelper; /** * Switch asynchronous instance test. * * @author Radek Tomiška * */ public class ConfigurationSwitchInstanceBulkActionIntegrationTest extends AbstractBulkActionTest { @Autowired private IdmEntityEventService entityEventService; @Autowired private SchedulerManager schedulerManager; @Autowired private IdmLongRunningTaskService longRunningTaskService; @Autowired private IdmConfigurationService configurationService; @Autowired private EntityEventManager eventManager; @Autowired private LongRunningTaskManager taskManager; @Before public void login() { loginAsAdmin(); } @After public void logout() { super.logout(); } @Test public void testSwitchSuccess() { // prepare all data String previousInstanceIdOne = getHelper().createName(); String previousInstanceIdTwo = getHelper().createName(); String newInstanceId = getHelper().createName(); // // create events IdmEntityEventDto eventOne = createEvent(previousInstanceIdOne); IdmEntityEventDto eventTwo = createEvent(previousInstanceIdTwo); // // create LRT IdmLongRunningTaskDto taskOne = createTask(previousInstanceIdOne); IdmLongRunningTaskDto taskTwo = createTask(previousInstanceIdTwo); // // create scheduledTasks Task scheduledTaskOne = createScheduledTask(previousInstanceIdOne); Task scheduledTaskTwo = createScheduledTask(previousInstanceIdTwo); // IdmBulkActionDto bulkAction = this.findBulkAction(IdmConfiguration.class, ConfigurationSwitchInstanceBulkAction.NAME); Map<String, Object> properties = new HashMap<>(); properties.put(ConfigurationSwitchInstanceBulkAction.PROPERTY_PREVIOUS_INSTANCE_ID, previousInstanceIdOne); properties.put(ConfigurationSwitchInstanceBulkAction.PROPERTY_NEW_INSTANCE_ID, newInstanceId); bulkAction.setProperties(properties); // prevalidate ResultModels models = bulkActionManager.prevalidate(bulkAction); Assert.assertFalse(models.getInfos().isEmpty()); // change IdmBulkActionDto processAction = bulkActionManager.processAction(bulkAction); checkResultLrt(processAction, 1l, null, null); // Assert.assertEquals(newInstanceId, entityEventService.get(eventOne).getInstanceId()); Assert.assertEquals(previousInstanceIdTwo, entityEventService.get(eventTwo).getInstanceId()); // Assert.assertEquals(newInstanceId, schedulerManager.getTask(scheduledTaskOne.getId()).getInstanceId()); Assert.assertEquals(previousInstanceIdTwo, schedulerManager.getTask(scheduledTaskTwo.getId()).getInstanceId()); // Assert.assertEquals(newInstanceId, longRunningTaskService.get(taskOne.getId()).getInstanceId()); Assert.assertEquals(previousInstanceIdTwo, longRunningTaskService.get(taskTwo.getId()).getInstanceId()); // // clean up created, just for sure entityEventService.delete(eventOne); entityEventService.delete(eventTwo); schedulerManager.deleteTask(scheduledTaskOne.getId()); schedulerManager.deleteTask(scheduledTaskTwo.getId()); longRunningTaskService.delete(taskOne); longRunningTaskService.delete(taskTwo); } @Test public void testNotChangeSameInstances() { String newInstanceId = getHelper().createName(); // IdmBulkActionDto bulkAction = this.findBulkAction(IdmConfiguration.class, ConfigurationSwitchInstanceBulkAction.NAME); Map<String, Object> properties = new HashMap<>(); properties.put(ConfigurationSwitchInstanceBulkAction.PROPERTY_PREVIOUS_INSTANCE_ID, newInstanceId); properties.put(ConfigurationSwitchInstanceBulkAction.PROPERTY_NEW_INSTANCE_ID, newInstanceId); bulkAction.setProperties(properties); // prevalidate bulkActionManager.prevalidate(bulkAction); // change IdmBulkActionDto processAction = bulkActionManager.processAction(bulkAction); checkResultLrt(processAction, null, null, 1l); } @Test public void testProcessWithoutAuthority() { logout(); loginWithout(TestHelper.ADMIN_USERNAME, IdmGroupPermission.APP_ADMIN, CoreGroupPermission.SCHEDULER_ADMIN, CoreGroupPermission.SCHEDULER_UPDATE); // IdmBulkActionDto bulkAction = this.findBulkAction(IdmConfiguration.class, ConfigurationSwitchInstanceBulkAction.NAME); Map<String, Object> properties = new HashMap<>(); properties.put(ConfigurationSwitchInstanceBulkAction.PROPERTY_PREVIOUS_INSTANCE_ID, getHelper().createName()); properties.put(ConfigurationSwitchInstanceBulkAction.PROPERTY_NEW_INSTANCE_ID, getHelper().createName()); bulkAction.setProperties(properties); // prevalidate bulkActionManager.prevalidate(bulkAction); // change IdmBulkActionDto processAction = bulkActionManager.processAction(bulkAction); checkResultLrt(processAction, null, null, 1l); } @Test public void testReuseAsynchronousEventInstanceId() { String eventInstanceId = getHelper().createName(); IdmConfigurationDto instanceId = configurationService.getByCode(EventConfiguration.PROPERTY_EVENT_ASYNCHRONOUS_INSTANCE_ID); if (instanceId == null) { configurationService.setValue(EventConfiguration.PROPERTY_EVENT_ASYNCHRONOUS_INSTANCE_ID, eventInstanceId); instanceId = configurationService.getByCode(EventConfiguration.PROPERTY_EVENT_ASYNCHRONOUS_INSTANCE_ID); } else { eventInstanceId = instanceId.getValue(); } // String newInstanceId = getHelper().createName(); IdmBulkActionDto bulkAction = this.findBulkAction(IdmConfiguration.class, ConfigurationSwitchInstanceBulkAction.NAME); Map<String, Object> properties = new HashMap<>(); properties.put(ConfigurationSwitchInstanceBulkAction.PROPERTY_PREVIOUS_INSTANCE_ID, newInstanceId); properties.put(ConfigurationSwitchInstanceBulkAction.PROPERTY_NEW_INSTANCE_ID, newInstanceId); bulkAction.setProperties(properties); // prevalidate bulkActionManager.prevalidate(bulkAction); // change IdmBulkActionDto processAction = bulkActionManager.processAction(bulkAction); checkResultLrt(processAction, null, null, 1l); // IdmConfigurationDto afterActionInstanceId = configurationService.getByCode(EventConfiguration.PROPERTY_EVENT_ASYNCHRONOUS_INSTANCE_ID); Assert.assertNotNull(afterActionInstanceId); Assert.assertEquals(instanceId.getId(), afterActionInstanceId.getId()); Assert.assertEquals(eventInstanceId, afterActionInstanceId.getValue()); } @Test public void testNotReuseAsynchronousEventInstanceId() { IdmConfigurationDto instanceId = configurationService.getByCode(EventConfiguration.PROPERTY_EVENT_ASYNCHRONOUS_INSTANCE_ID); if (instanceId != null) { configurationService.delete(instanceId); } // String newInstanceId = getHelper().createName(); IdmBulkActionDto bulkAction = this.findBulkAction(IdmConfiguration.class, ConfigurationSwitchInstanceBulkAction.NAME); Map<String, Object> properties = new HashMap<>(); properties.put(ConfigurationSwitchInstanceBulkAction.PROPERTY_PREVIOUS_INSTANCE_ID, newInstanceId); properties.put(ConfigurationSwitchInstanceBulkAction.PROPERTY_NEW_INSTANCE_ID, newInstanceId); bulkAction.setProperties(properties); // prevalidate bulkActionManager.prevalidate(bulkAction); // change IdmBulkActionDto processAction = bulkActionManager.processAction(bulkAction); checkResultLrt(processAction, null, null, 1l); // Assert.assertNull(configurationService.getByCode(EventConfiguration.PROPERTY_EVENT_ASYNCHRONOUS_INSTANCE_ID)); } @Test public void testDefaultInstanceId() { String previousInstanceId = configurationService.getInstanceId(); configurationService.setValue(EventConfiguration.PROPERTY_EVENT_ASYNCHRONOUS_INSTANCE_ID, previousInstanceId); // Assert.assertEquals(0, schedulerManager.switchInstanceId(previousInstanceId, null)); Assert.assertEquals(0, taskManager.switchInstanceId(previousInstanceId, null)); Assert.assertEquals(0, eventManager.switchInstanceId(previousInstanceId, null)); } private IdmEntityEventDto createEvent(String instanceId) { IdmEntityEventDto dto = new IdmEntityEventDto(); dto.setOwnerId(UUID.randomUUID()); dto.setOwnerType("mock"); dto.setInstanceId(instanceId); dto.setPriority(PriorityType.NORMAL); dto.setResult(new OperationResultDto(OperationState.CREATED)); // return entityEventService.save(dto); } private Task createScheduledTask(String instanceId) { Task task = new Task(); task.setInstanceId(instanceId); task.setTaskType(TestSchedulableTask.class); task.setDescription("test"); // return schedulerManager.createTask(task); } private IdmLongRunningTaskDto createTask(String instanceId) { IdmLongRunningTaskDto dto = new IdmLongRunningTaskDto(); dto.setTaskType("mock"); dto.setInstanceId(instanceId); dto.setResult(new OperationResult(OperationState.CREATED)); // return longRunningTaskService.save(dto); } }
mit
chrrasmussen/NTNU-Master-Project
no.ntnu.assignmentsystem.model/src/no/ntnu/assignmentsystem/services/ModelServices.java
1773
package no.ntnu.assignmentsystem.services; import java.util.List; import java.util.Optional; import no.ntnu.assignmentsystem.model.Assignment; import no.ntnu.assignmentsystem.model.Course; import no.ntnu.assignmentsystem.model.ModelLoader; import no.ntnu.assignmentsystem.model.Participant; import no.ntnu.assignmentsystem.model.Problem; import no.ntnu.assignmentsystem.model.SourceCodeFile; import no.ntnu.assignmentsystem.model.User; import org.eclipse.emf.ecore.EObject; public class ModelServices { private final ModelLoader modelLoader; public ModelServices(ModelLoader modelLoader) { this.modelLoader = modelLoader; } public Optional<? extends SourceCodeFile> getSourceCodeFile(String fileId) { return Optional.ofNullable((SourceCodeFile)findObject(fileId)); } public Optional<? extends Problem> getProblem(String problemId) { return Optional.ofNullable((Problem)findObject(problemId)); } public Optional<Assignment> getAssignment(String assignmentId) { return Optional.ofNullable((Assignment)findObject(assignmentId)); } public Optional<Course> getCourse(String courseId) { return Optional.ofNullable((Course)findObject(courseId)); } public Optional<? extends Participant> getParticipant(String courseId, String userId) { return getCourse(courseId).flatMap( course -> course.getParticipants().stream().filter( participant -> getUser(userId).equals(Optional.ofNullable(participant.getUser())) ).findAny() ); } public Optional<User> getUser(String userId) { return Optional.ofNullable((User)findObject(userId)); } public List<User> getUsers() { return modelLoader.getUoD().getUsers(); } // --- Private methods --- private EObject findObject(String id) { return modelLoader.findObject(id); } }
mit
vinayakapte/azure_event_hub_sample
azure-eventhubs/src/main/java/com/microsoft/azure/servicebus/ITimeoutErrorHandler.java
625
/* * Copyright (c) Microsoft. All rights reserved. * Licensed under the MIT license. See LICENSE file in the project root for full license information. */ package com.microsoft.azure.servicebus; // multiple issues were identified in the proton-j layer which could lead to a stuck state in Transport // https://issues.apache.org/jira/browse/PROTON-1185 // https://issues.apache.org/jira/browse/PROTON-1171 // This handler is built to - recover client from the underlying TransportStack-Stuck situation public interface ITimeoutErrorHandler { public void reportTimeoutError(); public void resetTimeoutErrorTracking(); }
mit
kleber-maia/iobjects
src/java/iobjects/util/mail/URLDataSourceEx.java
4974
/* The MIT License (MIT) Copyright (c) 2008 Kleber Maia de Andrade 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 iobjects.util.mail; import java.io.*; import java.net.*; import javax.activation.*; /** * Implementa a interface DataSource para obter conteúdo a partir de uma URL * com a possibilidade de uso de uma sessão de usuário existente no web server. * @since 2006 */ public class URLDataSourceEx implements DataSource { private URL url = null; private String sessionID = ""; /** * Construtor padrão. * @param url URL contendo o caminho de origem para ser acessado. */ public URLDataSourceEx(URL url) { // guarda a URL e a sessão this.url = url; } /** * Construtor estendido. * @param url URL contendo o caminho de origem para ser acessado. * @param sessionID String Identifação da sessão do usuário no servidor web. * Permite obter conteúdo associado exclusivamente ao usuário * que mantém a sessão informada. */ public URLDataSourceEx(URL url, String sessionID) { // guarda a URL e a sessão this.url = url; this.sessionID = sessionID; } /** * Retorna o tipo do conteúdo de origem no formato 'type/subtype'. * @return String Retorna o tipo do conteúdo de origem no formato 'type/subtype'. */ public String getContentType() { // conexão que será utilizada URLConnection urlConnection = null; try { // tenta abrir uma conexão urlConnection = openConnection(); } catch (IOException e) { } // try-catch // retorno padrão String result = "application/octet-stream"; // se conseguimos uma conexão...obtém o tipo do dado de origem if (urlConnection != null) result = urlConnection.getContentType(); // retorna return result; } /** * Retorna o InputStream para leitura do dado de origem. * @return InputStream Retorna o InputStream para leitura do dado de origem. * @throws IOException Em caso de exceção na tentavida de se conectar com o * servidor. */ public InputStream getInputStream() throws IOException { // tenta abrir uma conexão URLConnection urlConnection = openConnection(); // retorna return urlConnection.getInputStream(); } /** * Retorna o nome do conteúdo de origem. * @return String Retorna o nome do conteúdo de origem. */ public String getName() { // retorna return url.getFile(); } /** * Retorna o OutputStream para escrita na requisição do dado de origem. * @return OutputStream Retorna o OutputStream para escrita na requisição do * dado de origem. * @throws IOException Em caso de exceção na tentavida de se conectar com o * servidor. */ public OutputStream getOutputStream() throws IOException { // tenta abrir uma conexão URLConnection urlConnection = openConnection(); // deixa escrever urlConnection.setDoOutput(true); // retorna return urlConnection.getOutputStream(); } /** * Retorna uma URLConnection para acesso ao conteúdo de origem apontado * pela URL passada no construtor. * @return URLConnection Retorna uma URLConnection para acesso ao conteúdo de * origem apontado pela URL passada no construtor. * @throws IOException Em caso de exceção na tentavida de se conectar com o * servidor. */ private URLConnection openConnection() throws IOException { // abre a conexão URLConnection result = url.openConnection(); // adiciona a informação da sessão if ((sessionID != null) && (!sessionID.equals(""))) result.addRequestProperty("Cookie", "JSESSIONID=" + sessionID + ";"); // retorna return result; } }
mit
PrinceOfAmber/CyclicMagic
src/main/java/com/lothrazar/cyclic/block/crusher/ScreenCrusher.java
2237
package com.lothrazar.cyclic.block.crusher; import com.lothrazar.cyclic.gui.ButtonMachineField; import com.lothrazar.cyclic.gui.EnergyBar; import com.lothrazar.cyclic.gui.ScreenBase; import com.lothrazar.cyclic.gui.TexturedProgress; import com.lothrazar.cyclic.registry.TextureRegistry; import com.mojang.blaze3d.vertex.PoseStack; import net.minecraft.network.chat.Component; import net.minecraft.world.entity.player.Inventory; public class ScreenCrusher extends ScreenBase<ContainerCrusher> { private ButtonMachineField btnRedstone; private EnergyBar energy; private TexturedProgress progress; public ScreenCrusher(ContainerCrusher screenContainer, Inventory inv, Component titleIn) { super(screenContainer, inv, titleIn); this.energy = new EnergyBar(this, TileCrusher.MAX); this.progress = new TexturedProgress(this, 78, 40, TextureRegistry.SAW); } @Override public void init() { super.init(); progress.guiLeft = energy.guiLeft = leftPos; progress.guiTop = energy.guiTop = topPos; int x, y; x = leftPos + 6; y = topPos + 6; btnRedstone = addRenderableWidget(new ButtonMachineField(x, y, TileCrusher.Fields.REDSTONE.ordinal(), menu.tile.getBlockPos())); } @Override public void render(PoseStack ms, int mouseX, int mouseY, float partialTicks) { this.renderBackground(ms); super.render(ms, mouseX, mouseY, partialTicks); this.renderTooltip(ms, mouseX, mouseY); energy.renderHoveredToolTip(ms, mouseX, mouseY, menu.tile.getEnergy()); btnRedstone.onValueUpdate(menu.tile); } @Override protected void renderLabels(PoseStack ms, int mouseX, int mouseY) { this.drawButtonTooltips(ms, mouseX, mouseY); this.drawName(ms, this.title.getString()); } @Override protected void renderBg(PoseStack ms, float partialTicks, int mouseX, int mouseY) { this.drawBackground(ms, TextureRegistry.INVENTORY); this.drawSlot(ms, 52, 34); this.drawSlotLarge(ms, 104, 20); this.drawSlot(ms, 108, 54); energy.draw(ms, menu.tile.getEnergy()); final int max = menu.tile.getField(TileCrusher.Fields.TIMERMAX.ordinal()); progress.max = max; progress.draw(ms, max - menu.tile.getField(TileCrusher.Fields.TIMER.ordinal())); } }
mit
Aquerr/EagleFactions
src/main/java/io/github/aquerr/eaglefactions/storage/sql/sqlite/SqliteFactionStorage.java
386
package io.github.aquerr.eaglefactions.storage.sql.sqlite; import io.github.aquerr.eaglefactions.api.EagleFactions; import io.github.aquerr.eaglefactions.storage.sql.AbstractFactionStorage; public class SqliteFactionStorage extends AbstractFactionStorage { public SqliteFactionStorage(EagleFactions plugin) { super(plugin, SqliteProvider.getInstance(plugin)); } }
mit
KitchenStudio/shcx
shcx/src/main/java/org/kitchenstudio/service/SiteService.java
293
package org.kitchenstudio.service; import java.util.List; import org.kitchenstudio.entity.Company; import org.kitchenstudio.entity.Site; public interface SiteService { List<Site> findAll(); void add(Site site); void delete(Site site); List<Site> findByCompany(Company company); }
mit
berry-cs/big-data-cse
big-data-java/src/easy/data/xml/XMLDataSourceIterator.java
2587
package easy.data.xml; import java.util.HashMap; import easy.data.*; import easy.data.field.*; import easy.data.sig.*; import easy.data.util.*; public class XMLDataSourceIterator implements DataSourceIterator { XMLDataSource xds; IDataField df; XML[] nodes; int curIndex; public XMLDataSourceIterator(XMLDataSource xds, final IDataField df, final XML xml) { this.xds = xds; this.curIndex = 0; df.apply(new IDFVisitor<Void>() { public Void defaultVisit(IDataField df) { XMLDataSourceIterator.this.df = df; XMLDataSourceIterator.this.nodes = new XML[] { xml }; return null; } public Void visitListField(ListField f, String b, String d, String ep, IDataField ef) { XMLDataSourceIterator.this.df = ef; XMLDataSourceIterator.this.nodes = xml.getChildren(ep); return null; } public Void visitPrimField(PrimField f, String b, String d) { return defaultVisit(f); } public Void visitCompField(CompField f, String b, String d, HashMap<String, IDataField> fm) { return defaultVisit(f); } }); } public boolean hasData() { return curIndex < nodes.length; } public DataSourceIterator loadNext() { if (hasData()) curIndex++; //if (!hasData()) throw new DataSourceException("Attempted to move past end of iterator"); //curIndex++; return this; } @SuppressWarnings("unchecked") public <T> T fetch(String clsName, String... keys) { return (T) fetch(SigBuilder.classFor(clsName), keys); } public <T> T fetch(Class<T> cls, String... keys) { //if (curIndex < 0) throw new DataSourceException("Must call loadNext() before attempting to fetch from iterator"); if (!hasData()) throw new DataSourceException("No more data available through iterator: " + xds.getName()); ISig sig = SigBuilder.buildCompSig(cls, keys); return df.apply(new XMLInstantiator<T>(nodes[curIndex], sig)); } public boolean fetchBoolean(String key) { return fetch(Boolean.class, key); } public byte fetchByte(String key) { return fetch(Byte.class, key); } public char fetchChar(String key) { return fetch(Character.class, key); } public double fetchDouble(String key) { return fetch(Double.class, key); } public float fetchFloat(String key) { return fetch(Float.class, key); } public int fetchInt(String key) { return fetch(Integer.class, key); } public String fetchString(String key) { return fetch(String.class, key); } public String usageString() { String s = "\nThe following data is available through iterator for: " + xds.getName() + "\n"; s += df.apply(new FieldStringPrettyPrint(3, true, true)) + "\n"; return s; } }
mit
hprose/hprose-java
src/main/java/hprose/io/unserialize/CharArrayUnserializer.java
2104
/**********************************************************\ | | | hprose | | | | Official WebSite: http://www.hprose.com/ | | http://www.hprose.org/ | | | \**********************************************************/ /**********************************************************\ * * * CharArrayUnserializer.java * * * * char array unserializer class for Java. * * * * LastModified: Aug 3, 2016 * * Author: Ma Bingyao <andot@hprose.com> * * * \**********************************************************/ package hprose.io.unserialize; import static hprose.io.HproseTags.TagEmpty; import static hprose.io.HproseTags.TagList; import static hprose.io.HproseTags.TagString; import static hprose.io.HproseTags.TagUTF8Char; import java.io.IOException; import java.lang.reflect.Type; public final class CharArrayUnserializer extends BaseUnserializer<char[]> { public final static CharArrayUnserializer instance = new CharArrayUnserializer(); @Override public char[] unserialize(Reader reader, int tag, Type type) throws IOException { switch (tag) { case TagEmpty: return new char[0]; case TagUTF8Char: return new char[] { ValueReader.readChar(reader) }; case TagList: return ReferenceReader.readCharArray(reader); case TagString: return ReferenceReader.readChars(reader); } return super.unserialize(reader, tag, type); } public char[] read(Reader reader) throws IOException { return read(reader, char[].class); } }
mit
TGX-ZQ/Z-Queen
src/main/java/com/tgx/zq/z/queen/cluster/replication/bean/raft/NodeEntity.java
3111
/* * MIT License * * Copyright (c) 2016~2017 Z-Chess * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package com.tgx.zq.z.queen.cluster.replication.bean.raft; import com.tgx.zq.z.queen.cluster.election.raft.RaftStage; /** * @author William.d.zk */ public class NodeEntity { private final long _Identify; private RaftStage mStage; private int mSessionCount; private long mTermId; private long mLastCommittedSlotIndex; private long mLastAppendedSlotIndex; private long mBallotId; public NodeEntity(long identify) { _Identify = identify; mStage = RaftStage.DISCOVER; mBallotId = identify; mSessionCount = 1; } public void leader() { mStage = RaftStage.LEADER; mBallotId = _Identify; } public void follower() { mStage = RaftStage.FOLLOWER; } public void candidate() { mStage = RaftStage.CANDIDATE; mBallotId = _Identify; } public RaftStage getStage() { return mStage; } public long getIdentify() { return _Identify; } public void sessionIncrement() { mSessionCount++; } public boolean sessionDecrement() { mSessionCount--; return mSessionCount == 0; } public long getAppendSlotIndex() { return mLastAppendedSlotIndex; } public void setAppendSlotIndex(long slotIndex) { mLastAppendedSlotIndex = Math.max(slotIndex, mLastAppendedSlotIndex); } public long getCommittedSlotIndex() { return mLastCommittedSlotIndex; } public void setCommittedSlotIndex(long committedSlotIndex) { mLastCommittedSlotIndex = Math.max(committedSlotIndex, mLastCommittedSlotIndex); } public boolean updateBallot(long termId, long ballotId) { if (termId > mTermId) { mTermId = termId; mBallotId = ballotId; return true; } return false; } public long getBallot() { return mBallotId; } }
mit
ngageoint/geopackage-mapcache-android
mapcache/src/main/java/mil/nga/mapcache/MainActivity.java
7404
package mil.nga.mapcache; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Bundle; import android.provider.Settings; import android.view.MenuItem; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentTransaction; import com.ipaulpro.afilechooser.utils.FileUtils; import org.piwik.sdk.Piwik; import org.piwik.sdk.Tracker; import org.piwik.sdk.TrackerConfig; import org.piwik.sdk.extra.TrackHelper; import mil.nga.mapcache.io.MapCacheFileUtils; //import org.matomo.sdk.Matomo; //import org.matomo.sdk.TrackMe; //import org.matomo.sdk.Tracker; //import org.matomo.sdk.TrackerBuilder; //import org.matomo.sdk.extra.MatomoApplication; //import org.matomo.sdk.extra.TrackHelper; /** * Main Activity * * @author osbornb */ public class MainActivity extends AppCompatActivity { /** * Map permissions request code for accessing fine locations */ public static final int MAP_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 100; /** * Manager permissions request code for importing a GeoPackage as an external link */ public static final int MANAGER_PERMISSIONS_REQUEST_ACCESS_IMPORT_EXTERNAL = 200; /** * Manager permissions request code for reading / writing to GeoPackages already externally linked */ public static final int MANAGER_PERMISSIONS_REQUEST_ACCESS_EXISTING_EXTERNAL = 201; /** * Manager permissions request code for exporting a GeoPackage to external storage */ public static final int MANAGER_PERMISSIONS_REQUEST_ACCESS_EXPORT_DATABASE = 202; /** * Used to store the last screen title. For use in * {@link #hideActionBar()}. */ private CharSequence title; /** * Map fragment */ private GeoPackageMapFragment mapFragment; /** * Manager fragment */ // private GeoPackageManagerFragment managerFragment; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Set the content view setContentView(R.layout.activity_main); // Retrieve the fragments // managerFragment = (GeoPackageManagerFragment) getSupportFragmentManager() // .findFragmentById(R.id.fragment_manager); mapFragment = (GeoPackageMapFragment) getSupportFragmentManager() .findFragmentById(R.id.fragment_map); // Set up the map fragment createMainFragment(); hideActionBar(); // Handle opening and importing GeoPackages if(getIntent() != null) { Intent intent = getIntent(); Uri uri = intent.getData(); if (uri == null) { Bundle bundle = intent.getExtras(); if (bundle != null) { Object objectUri = bundle.get(Intent.EXTRA_STREAM); if (objectUri != null) { uri = (Uri) objectUri; } } } if (uri != null) { handleIntentUri(uri, intent); } } /** * Use Matomo to track when users open the app */ String siteUrl = getString(R.string.matomo_url); int siteId = getResources().getInteger(R.integer.matomo_site_id); Tracker piwik = Piwik.getInstance(getApplicationContext()).newTracker(new TrackerConfig(siteUrl, siteId, "MapCacheTracker")); String androidId = Settings.Secure.getString(getBaseContext().getContentResolver(), Settings.Secure.ANDROID_ID); TrackHelper.track().screen("/Main Activity").title("App Opened").with(piwik); piwik.dispatch(); } /** * Set up the map fragment */ private void createMainFragment(){ FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction transaction = fragmentManager.beginTransaction(); transaction.show(mapFragment); title = getString(R.string.title_map); transaction.commit(); } /** * Handle the URI from an intent for opening or importing a GeoPackage * * @param uri intent uri */ private void handleIntentUri(final Uri uri, Intent intent) { String path = FileUtils.getPath(this, uri); String name = MapCacheFileUtils.getDisplayName(this, uri, path); try { if (path != null) { // managerFragment.importGeoPackageExternalLinkWithPermissions(name, uri, path); mapFragment.startImportTaskWithPermissions(name, uri, path, intent); } else { // managerFragment.importGeoPackage(name, uri, path); mapFragment.startImportTask(name, uri, path, intent); } } catch (final Exception e) { try { runOnUiThread( new Runnable() { @Override public void run() { GeoPackageUtils.showMessage(MainActivity.this, "Open GeoPackage", "Could not open file as a GeoPackage" + "\n\n" + e.getMessage()); } }); } catch (Exception e2) { // eat } } } /** * {@inheritDoc} */ @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); } /** * Hide the action bar */ public void hideActionBar() { ActionBar actionBar = getSupportActionBar(); // actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); // actionBar.setDisplayShowTitleEnabled(true); // actionBar.setTitle(title); actionBar.hide(); } /** * {@inheritDoc} */ @Override public boolean onOptionsItemSelected(MenuItem item) { if (mapFragment.handleMenuClick(item)) { return true; } // if (managerFragment.handleMenuClick(item)) { // return true; // } return super.onOptionsItemSelected(item); } /** * {@inheritDoc} */ @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { // Check if permission was granted boolean granted = grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED; switch(requestCode) { case MAP_PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: mapFragment.setMyLocationEnabled(); break; case MANAGER_PERMISSIONS_REQUEST_ACCESS_IMPORT_EXTERNAL: mapFragment.importGeopackageFromFile(); break; case MANAGER_PERMISSIONS_REQUEST_ACCESS_EXPORT_DATABASE: mapFragment.exportGeoPackageToExternal(); break; case MANAGER_PERMISSIONS_REQUEST_ACCESS_EXISTING_EXTERNAL: // managerFragment.update(granted); break; } } }
mit
mmailhot/skip-android
SKIPProject/SKIP/src/main/java/ca/mlht/android/skip/MainActivity.java
3790
package ca.mlht.android.skip; import android.content.Context; import android.os.Bundle; import android.app.Activity; import android.provider.Settings; import android.view.Menu; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import android.app.ProgressDialog; import java.util.HashMap; public class MainActivity extends Activity { private SkipApiHandler apiHandler; private String api_key; @Override protected void onCreate(Bundle savedInstanceState) { apiHandler = new SkipApiHandler(this.getApplicationContext()); apiHandler.checkIfDeviceRegistered(new AsyncReturn() { @Override public void callback(HashMap<String, String> results) { if(results.get("exists")=="true"){ TextView api_view = (TextView)findViewById(R.id.api_key_view); api_key = results.get("api_key"); api_view.setText(results.get("api_key")); Button unregister = (Button)findViewById(R.id.unregister_button); unregister.setEnabled(true); }else{ Button register = (Button)findViewById(R.id.register_button); register.setEnabled(true); } } }); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void onRegisterDeviceClicked (View v){ final Button register = (Button)findViewById(R.id.register_button); final Button unregister = (Button)findViewById(R.id.unregister_button); final ProgressDialog dialog = new ProgressDialog(this); final TextView api_view = (TextView)findViewById(R.id.api_key_view); dialog.setCancelable(false); dialog.show(); register.setEnabled(false); apiHandler.registerDevice(new AsyncReturn() { @Override public void callback(HashMap<String, String> results) { dialog.cancel(); if(results.get("success")!="true"){ Toast.makeText(getApplicationContext(),"Failed to Register",Toast.LENGTH_LONG).show(); register.setEnabled(true); }else{ api_key = results.get("api_key"); api_view.setText(results.get("api_key")); unregister.setEnabled(true); } } }); } public void onUnregisterDeviceClicked (View v){ final Button register = (Button)findViewById(R.id.register_button); final Button unregister = (Button)findViewById(R.id.unregister_button); final ProgressDialog dialog = new ProgressDialog(this); final TextView api_view = (TextView)findViewById(R.id.api_key_view); dialog.setCancelable(false); dialog.show(); unregister.setEnabled(false); apiHandler.unregisterDevice(api_key,new AsyncReturn() { @Override public void callback(HashMap<String, String> results) { dialog.cancel(); if(results.get("success")!="true"){ Toast.makeText(getApplicationContext(),"Failed to Unregister",Toast.LENGTH_LONG).show(); unregister.setEnabled(true); return; } api_view.setText(""); api_key = ""; register.setEnabled(true); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
mit
bladestery/Sapphire
example_apps/AndroidStudioMinnie/sapphire/src/main/java/boofcv/BorderIndex1D_Reflect_Stub.java
1551
/* * Stub for class boofcv.core.image.border.BorderIndex1D_Reflect * Generated by Sapphire Compiler (sc). */ package boofcv.core.image.border.stubs; public final class BorderIndex1D_Reflect_Stub extends boofcv.core.image.border.BorderIndex1D_Reflect implements sapphire.common.AppObjectStub { sapphire.policy.SapphirePolicy.SapphireClientPolicy $__client = null; boolean $__directInvocation = false; public BorderIndex1D_Reflect_Stub () { super(); } public void $__initialize(sapphire.policy.SapphirePolicy.SapphireClientPolicy client) { $__client = client; } public void $__initialize(boolean directInvocation) { $__directInvocation = directInvocation; } public Object $__clone() throws CloneNotSupportedException { return super.clone(); } // Implementation of getIndex(int) public int getIndex(int $param_int_1) { java.lang.Object $__result = null; try { if ($__directInvocation) $__result = super.getIndex( $param_int_1); else { java.util.ArrayList<Object> $__params = new java.util.ArrayList<Object>(); String $__method = "public int boofcv.core.image.border.BorderIndex1D_Reflect.getIndex(int)"; $__params.add($param_int_1); $__result = $__client.onRPC($__method, $__params); } } catch (Exception e) { e.printStackTrace(); } return ((java.lang.Integer) $__result).intValue(); } }
mit
tbian7/pst
training/src/leetcode/Solution321.java
929
package leetcode; public class Solution321 { public int maxNumber(int[] nums1, int[] nums2, int k) { int m = nums1.length, n = nums2.length; int[][][] F = new int[m + 1][n + 1][k + 1]; for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { for (int c = 1; c <= Math.min(i + j, k); c++) { int maxValue = 0; if (i > 0) { maxValue = Math.max(F[i - 1][j][c - 1] * 10 + nums1[i - 1], maxValue); // pick nums1 maxValue = Math.max(F[i - 1][j][c], maxValue); // don't pick nums1 } if (j > 0) { maxValue = Math.max(F[i][j - 1][c - 1] * 10 + nums2[j - 1], maxValue); // pick nums2 maxValue = Math.max(F[i][j - 1][c], maxValue); // don't pick nums2 } F[i][j][c] = maxValue; } } } return F[m][n][k]; } }
mit
isigoing/analysis-model
src/main/java/edu/hm/hafner/analysis/parser/InvalidsParser.java
1678
package edu.hm.hafner.analysis.parser; import java.util.regex.Matcher; import org.apache.commons.lang3.StringUtils; import edu.hm.hafner.analysis.Issue; import edu.hm.hafner.analysis.Priority; import edu.hm.hafner.analysis.RegexpLineParser; /** * A parser for Oracle Invalids. * * @author Ullrich Hafner */ public class InvalidsParser extends RegexpLineParser { private static final long serialVersionUID = 440910718005095427L; static final String WARNING_PREFIX = "Oracle "; private static final String INVALIDS_PATTERN = "^\\s*(\\w+),([a-zA-Z#_0-9/]*),([A-Z_ ]*),(.*),(\\d+),\\d+,([^:]*)" + ":\\s*(.*)$"; /** * Creates a new instance of {@link InvalidsParser}. */ public InvalidsParser() { super("oracle-invalids", INVALIDS_PATTERN); } @Override protected Issue createWarning(final Matcher matcher) { String type = WARNING_PREFIX + StringUtils.capitalize(StringUtils.lowerCase(matcher.group(4))); String category = matcher.group(6); Priority priority; if (StringUtils.contains(category, "PLW-07")) { priority = Priority.LOW; } else if (StringUtils.contains(category, "ORA")) { priority = Priority.HIGH; } else { priority = Priority.NORMAL; } return issueBuilder().setFileName(matcher.group(2) + "." + matcher.group(3)) .setLineStart(parseInt(matcher.group(5))).setType(type).setCategory(category) .setPackageName(matcher.group(1)).setMessage(matcher.group(7)).setPriority(priority) .build(); } }
mit
team1389/Simulation-Ohm
Simulation-Ohm/src/simulation/drive_sim/Resources.java
610
package simulation.drive_sim; public class Resources { public static String resources = "res"; public static String robotImage = resources + "/octi.png"; public static String blueAllianceRobotImage = resources + "/octi-blue bumpers.png"; public static String redAllianceRobotImage = resources + "/octi-red bumpers.png"; public static String gearImage = resources + "/Gear.png"; public static String ds1vis = resources + "/DS1VisibilityBlock.png"; public static String ds2vis = resources + "/DS2VisibilityBlock.png"; public static String ds3vis = resources + "/DS3VisibilityBlock.png"; }
mit
kingdaa/Leetcode_Java
src/PopulatingNextRightPointersInEachNodeII.java
2037
/* Follow up for problem "Populating Next Right Pointers in Each Node". What if the given tree could be any binary tree? Would your previous solution still work? Note: You may only use constant extra space. For example, Given the following binary tree, 1 / \ 2 3 / \ \ 4 5 7 After calling your function, the tree should look like: 1 -> NULL / \ 2 -> 3 -> NULL / \ \ 4-> 5 -> 7 -> NULL - Reference - http://codeganker.blogspot.com/2014/04/populating-next-right-pointers-in-each.html - Keep track of current Head, last level head and current level rightmost node in processing - For processing one level 1. Start from head of last level (leftmost node of last level) 2. Keep track of head (leftmost node) of current level (first met node in processing current level) 3. Using one pointer to store current rightmost node, and keep it linked to next right node found, update the pointer 4. Once current head is null (no node in current level), return - O(N) time, O(1) Space */ public class PopulatingNextRightPointersInEachNodeII { static class TreeLinkNode { int val; TreeLinkNode left, right, next; TreeLinkNode(int x) { val = x; } } public void connect(TreeLinkNode root) { if (root == null) return; TreeLinkNode lastHead = root; TreeLinkNode curHead = null; TreeLinkNode prev = null; while (lastHead != null) { TreeLinkNode lastLevelCur = lastHead; while (lastLevelCur != null) { if (lastLevelCur.left != null) { if (curHead == null) { curHead = lastLevelCur.left; prev = curHead; } else { prev.next = lastLevelCur.left; prev = prev.next; } } if (lastLevelCur.right != null) { if (curHead == null) { curHead = lastLevelCur.right; prev = curHead; } else { prev.next = lastLevelCur.right; prev = prev.next; } } lastLevelCur = lastLevelCur.next; } lastHead = curHead; curHead = null; } } }
mit
kazaky/Breakout-Android-Game
app/src/main/java/com/kazaky/breakout/MenuActivity.java
1284
package com.kazaky.breakout; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MenuActivity extends Activity implements View.OnClickListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.menu_layout); Button start = (Button) findViewById(R.id.start); Button about = (Button) findViewById(R.id.about); Button exit = (Button) findViewById(R.id.exit); start.setOnClickListener(this); about.setOnClickListener(this); exit.setOnClickListener(this); } //implement the onClick method here public void onClick(View v) { Intent intent; // Perform action on click switch (v.getId()) { case R.id.start: intent = new Intent(this, GameActivity.class); startActivity(intent); break; case R.id.about: intent = new Intent(this, AboutActivity.class); startActivity(intent); break; case R.id.exit: finish(); break; } } }
mit
intuit/karate
karate-robot/src/main/java/com/intuit/karate/robot/mac/MacRobot.java
3998
/* * The MIT License * * Copyright 2020 Intuit Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.intuit.karate.robot.mac; import com.intuit.karate.StringUtils; import com.intuit.karate.robot.Element; import com.intuit.karate.robot.ImageElement; import com.intuit.karate.robot.RobotBase; import com.intuit.karate.robot.Window; import com.intuit.karate.core.ScenarioEngine; import com.intuit.karate.core.ScenarioRuntime; import com.intuit.karate.shell.Command; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.function.Predicate; /** * * @author pthomas3 */ public class MacRobot extends RobotBase { public MacRobot(ScenarioRuntime runtime, Map<String, Object> options) { super(runtime, options); } @Override public Map<String, Object> afterScenario() { return Collections.EMPTY_MAP; } private static final String MAC_GET_PROCS = " tell application \"System Events\"" + "\n set procs to (processes whose background only is false)" + "\n set results to {}" + "\n repeat with n from 1 to the length of procs" + "\n set p to item n of procs" + "\n set entry to { name of p as text,\"|\"}" + "\n set end of results to entry" + "\n end repeat" + "\n end tell" + "\n results"; public static List<String> getAppsMacOs() { String res = Command.exec(true, null, "osascript", "-e", MAC_GET_PROCS); res = res + ", "; res = res.replace(", |, ", "\n"); return StringUtils.split(res, '\n', false); } @Override public Element windowInternal(String title) { Command.exec(true, null, "osascript", "-e", "tell app \"" + title + "\" to activate"); return new ImageElement(screen); // TODO } @Override public Element windowInternal(Predicate<String> condition) { List<String> list = getAppsMacOs(); for (String s : list) { if (condition.test(s)) { Command.exec(true, null, "osascript", "-e", "tell app \"" + s + "\" to activate"); return new ImageElement(screen); // TODO } } return null; } @Override public List<Element> locateAllInternal(Element searchRoot, String locator) { throw new UnsupportedOperationException("not supported yet."); } @Override public Element locateInternal(Element root, String locator) { throw new UnsupportedOperationException("not supported yet."); } @Override public Element getRoot() { return new ImageElement(screen); } @Override public Element getFocused() { return new ImageElement(screen); } @Override public List<Window> getAllWindows() { throw new UnsupportedOperationException("not supported yet."); } }
mit
Valandur/Web-API
webapi-sponge/src/main/java/valandur/webapi/config/CacheConfig.java
1407
package valandur.webapi.config; import com.google.common.collect.Lists; import ninja.leaping.configurate.objectmapping.Setting; import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; import java.util.HashMap; import java.util.List; import java.util.Map; @ConfigSerializable public class CacheConfig extends BaseConfig { @Setting(comment = "The number of entries that are saved. This defines how \"far back\" the history goes.") public int chat_amount = 100; @Setting(comment = "The number of entries that are saved. This defines how \"far back\" the history goes.") public int cmd_amount = 100; @Setting(comment = "The number of seconds that the different types of data is cached for") public Map<String, Long> duration = new HashMap<>(); @Setting(comment = "The folders in which Web-API looks for other plugins.") public List<String> pluginFolders = Lists.newArrayList("./mods", "./plugins"); @Setting(comment = "These are commands that should not show up in the command log.\n" + "For example if you have a second auth plugin, or something where\n" + "players enter private data, put the command here, so that it's\n" + "filtered from the logs, and also won't show up in the admin panel.") public List<String> censoredCommands = Lists.newArrayList("register", "reg", "login", "password", "pass"); }
mit
InnovateUKGitHub/innovation-funding-service
ifs-data-layer/ifs-data-service/src/main/java/org/innovateuk/ifs/application/domain/ApplicationProcess.java
3335
package org.innovateuk.ifs.application.domain; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.innovateuk.ifs.application.repository.ApplicationStateConverter; import org.innovateuk.ifs.application.resource.ApplicationState; import org.innovateuk.ifs.user.domain.ProcessRole; import org.innovateuk.ifs.workflow.domain.Process; import javax.persistence.*; import java.util.ArrayList; import java.util.List; /** * The current state of an {@link Application}. */ @Entity public class ApplicationProcess extends Process<ProcessRole, Application, ApplicationState> { @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "participant_id", referencedColumnName = "id") private ProcessRole participant; @ManyToOne(fetch = FetchType.LAZY, optional = false ) @JoinColumn(name = "target_id", referencedColumnName = "id") private Application target; @OneToMany(orphanRemoval = true, cascade = CascadeType.ALL) @JoinColumn(name="process_id") @OrderBy("id ASC") private List<IneligibleOutcome> ineligibleOutcomes = new ArrayList<>(); @Convert(converter = ApplicationStateConverter.class) @Column(name="activity_state_id") private ApplicationState activityState; ApplicationProcess() { } public ApplicationProcess(Application target, ProcessRole participant, ApplicationState initialState) { this.target = target; this.participant = participant; this.setProcessState(initialState); } @Override public ProcessRole getParticipant() { return participant; } @Override public void setParticipant(ProcessRole participant) { this.participant = participant; } @Override public Application getTarget() { return target; } @Override public void setTarget(Application target) { this.target = target; } @Override public ApplicationState getProcessState() { return activityState; } @Override public void setProcessState(ApplicationState status) { this.activityState = status; } public List<IneligibleOutcome> getIneligibleOutcomes() { return ineligibleOutcomes; } public void setIneligibleOutcomes(List<IneligibleOutcome> ineligibleOutcomes) { this.ineligibleOutcomes = ineligibleOutcomes; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ApplicationProcess that = (ApplicationProcess) o; return new EqualsBuilder() .appendSuper(super.equals(o)) .append(participant, that.participant) .append(target, that.target) .append(ineligibleOutcomes, that.ineligibleOutcomes) .append(activityState, that.activityState) .isEquals(); } @Override public int hashCode() { return new HashCodeBuilder(17, 37) .appendSuper(super.hashCode()) .append(participant) .append(target) .append(ineligibleOutcomes) .append(activityState) .toHashCode(); } }
mit
tectronics/two-point-correlation
src/test/java/algorithms/compGeometry/clustering/twopointcorrelation/SubsetSamplingVoidFinderTest.java
2810
package algorithms.compGeometry.clustering.twopointcorrelation; import java.util.logging.Logger; /** * * @author nichole */ public class SubsetSamplingVoidFinderTest extends BaseTwoPointTest { boolean debug = true; protected Logger log = Logger.getLogger(this.getClass().getSimpleName()); public void testFindVoids_0() throws Exception { log.info("testFindVoids_0()"); float xmin = 0; float xmax = 3; float ymin = 0; float ymax = 3; int numberOfBackgroundPoints = 9; float[] xb = new float[numberOfBackgroundPoints]; float[] yb = new float[numberOfBackgroundPoints]; // make a uniform grid of background points: int nDiv = (int) Math.ceil(Math.sqrt(numberOfBackgroundPoints)); double divXSz = (xmax - xmin)/nDiv; double divYSz = (ymax - ymin)/nDiv; int c = 0; for (int j = 0; j < nDiv; j++) { float yStart = (float) (ymin + j*divYSz); if (yStart > ymax) { yStart = ymax; } for (int jj = 0; jj < nDiv; jj++) { float xStart = (float)(xmin + jj*divXSz); if (xStart > xmax) { xStart = xmax; } if (c > (numberOfBackgroundPoints - 1)) { break; } xb[c] = xStart; yb[c] = yStart; c++; } } float[] xbe = new float[numberOfBackgroundPoints]; float[] ybe = new float[numberOfBackgroundPoints]; for (int i = 0; i < numberOfBackgroundPoints; i++) { // simulate x error as a percent error of 0.03 for each bin xbe[i] = xb[i] * 0.03f; ybe[i] = (float) (Math.sqrt(yb[i])); } AxisIndexer indexer = new AxisIndexer(); indexer.sortAndIndexX(xb, yb, xbe, ybe, xb.length); IVoidFinder voidFinder = new SubsetSamplingVoidFinder(); voidFinder.findVoids(indexer); float[] linearDensities = voidFinder.getTwoPointDensities(); assertNotNull(linearDensities); log.info("n densities=" + linearDensities.length); assertTrue(linearDensities.length == 20); // count values of 2 and 1.6817929 int count0 = 0; int count1 = 0; for (int i = 0; i < linearDensities.length; i++) { float d = linearDensities[i]; if (d == 2.) { count0++; } else if (Math.abs(d - 1.6817929) < 0.0001) { count1++; } } assertTrue(count0 == 12); assertTrue(count1 == 8); } }
mit
catzhangy1/cellSociety
src/visualUnits/SquareUnit.java
482
package visualUnits; import javafx.scene.paint.Color; import javafx.scene.shape.Rectangle; public class SquareUnit extends Units{ public SquareUnit (int r, int c, boolean outline, double width, double height, Color col) { super (r ,c, outline); create(width, height); set(col, unit); } public void create(double width, double height){ unit = new Rectangle((double) (width * x), (double) (height * y), width , height ); } }
mit
lucasperin/Beluga
AL/src/langB.java
7909
/* Generated By:JavaCC: Do not edit this line. langB.java */ package parser; import java.io.*; public class langB implements langBConstants { final static String Version = "Compilador Beluga - 2013/1"; boolean Menosshort = false; // sa�da resumida = falso // Define o m�todo "main" da classe langB. public static void main(String args[]) throws ParseException { String filename = ""; // nome do arquivo a ser analisado langB parser; // analisador l�xico/sint�tico int i; boolean ms = false; System.out.println(Version); // l� os par�metros passados para o compilador // verificar a necessidade deste for. for (i = 0; i < args.length - 1; i++) { if ( args[i].toLowerCase().equals("-short") ) ms = true; else { System.out.println("Uso correto deve ser: java langB [-short] arquivo_de_entrada"); System.exit(0); } } if (args[i].equals("-")) { // l� da entrada padr�o System.out.println("Lendo da entrada padrao . . ."); parser = new langB(System.in); } else { // l� do arquivo filename = args[args.length-1]; System.out.println("Lendo do arquivo " + filename + " . . ."); try { parser = new langB(new java.io.FileInputStream(filename)); } catch (java.io.FileNotFoundException e) { System.out.println("Arquivo " + filename + " nao ."); return; } } parser.Menosshort = ms; parser.program(); // chama o m�todo que faz a an�lise if ( parser.token_source.foundLexError() != 0 ) // verifica se houve erro l�xico System.out.println(parser.token_source.foundLexError() + " Erros lexicos encontrados"); else System.out.println("Programa analisado corretamente."); } // main static public String im(int x) { int k; String s; s = tokenImage[x]; k = s.lastIndexOf("\u005c""); try {s = s.substring(1,k);} catch (StringIndexOutOfBoundsException e) {} return s; } void program() throws ParseException { Token t; do { t = getNextToken(); Token st = t; while ( st.specialToken != null) st = st.specialToken; do { if ( Menosshort ) System.out.println(st.image + " " + im(st.kind) + " " + st.kind); else System.out.println("Linha: " + st.beginLine + " Coluna: " + st.beginColumn + " " + st.image + " " + im(st.kind) + " "+t.kind); st = st.next; } while (st != t.next); } while (t.kind != langBConstants.EOF); } /** Generated Token Manager. */ public langBTokenManager token_source; SimpleCharStream jj_input_stream; /** Current token. */ public Token token; /** Next token. */ public Token jj_nt; private int jj_ntk; private int jj_gen; final private int[] jj_la1 = new int[0]; static private int[] jj_la1_0; static private int[] jj_la1_1; static private int[] jj_la1_2; static { jj_la1_init_0(); jj_la1_init_1(); jj_la1_init_2(); } private static void jj_la1_init_0() { jj_la1_0 = new int[] {}; } private static void jj_la1_init_1() { jj_la1_1 = new int[] {}; } private static void jj_la1_init_2() { jj_la1_2 = new int[] {}; } /** Constructor with InputStream. */ public langB(java.io.InputStream stream) { this(stream, null); } /** Constructor with InputStream and supplied encoding */ public langB(java.io.InputStream stream, String encoding) { try { jj_input_stream = new SimpleCharStream(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); } token_source = new langBTokenManager(jj_input_stream); token = new Token(); jj_ntk = -1; jj_gen = 0; for (int i = 0; i < 0; i++) jj_la1[i] = -1; } /** Reinitialise. */ public void ReInit(java.io.InputStream stream) { ReInit(stream, null); } /** Reinitialise. */ public void ReInit(java.io.InputStream stream, String encoding) { try { jj_input_stream.ReInit(stream, encoding, 1, 1); } catch(java.io.UnsupportedEncodingException e) { throw new RuntimeException(e); } token_source.ReInit(jj_input_stream); token = new Token(); jj_ntk = -1; jj_gen = 0; for (int i = 0; i < 0; i++) jj_la1[i] = -1; } /** Constructor. */ public langB(java.io.Reader stream) { jj_input_stream = new SimpleCharStream(stream, 1, 1); token_source = new langBTokenManager(jj_input_stream); token = new Token(); jj_ntk = -1; jj_gen = 0; for (int i = 0; i < 0; i++) jj_la1[i] = -1; } /** Reinitialise. */ public void ReInit(java.io.Reader stream) { jj_input_stream.ReInit(stream, 1, 1); token_source.ReInit(jj_input_stream); token = new Token(); jj_ntk = -1; jj_gen = 0; for (int i = 0; i < 0; i++) jj_la1[i] = -1; } /** Constructor with generated Token Manager. */ public langB(langBTokenManager tm) { token_source = tm; token = new Token(); jj_ntk = -1; jj_gen = 0; for (int i = 0; i < 0; i++) jj_la1[i] = -1; } /** Reinitialise. */ public void ReInit(langBTokenManager tm) { token_source = tm; token = new Token(); jj_ntk = -1; jj_gen = 0; for (int i = 0; i < 0; i++) jj_la1[i] = -1; } private Token jj_consume_token(int kind) throws ParseException { Token oldToken; if ((oldToken = token).next != null) token = token.next; else token = token.next = token_source.getNextToken(); jj_ntk = -1; if (token.kind == kind) { jj_gen++; return token; } token = oldToken; jj_kind = kind; throw generateParseException(); } /** Get the next Token. */ final public Token getNextToken() { if (token.next != null) token = token.next; else token = token.next = token_source.getNextToken(); jj_ntk = -1; jj_gen++; return token; } /** Get the specific Token. */ final public Token getToken(int index) { Token t = token; for (int i = 0; i < index; i++) { if (t.next != null) t = t.next; else t = t.next = token_source.getNextToken(); } return t; } private int jj_ntk() { if ((jj_nt=token.next) == null) return (jj_ntk = (token.next=token_source.getNextToken()).kind); else return (jj_ntk = jj_nt.kind); } private java.util.List<int[]> jj_expentries = new java.util.ArrayList<int[]>(); private int[] jj_expentry; private int jj_kind = -1; /** Generate ParseException. */ public ParseException generateParseException() { jj_expentries.clear(); boolean[] la1tokens = new boolean[67]; if (jj_kind >= 0) { la1tokens[jj_kind] = true; jj_kind = -1; } for (int i = 0; i < 0; i++) { if (jj_la1[i] == jj_gen) { for (int j = 0; j < 32; j++) { if ((jj_la1_0[i] & (1<<j)) != 0) { la1tokens[j] = true; } if ((jj_la1_1[i] & (1<<j)) != 0) { la1tokens[32+j] = true; } if ((jj_la1_2[i] & (1<<j)) != 0) { la1tokens[64+j] = true; } } } } for (int i = 0; i < 67; i++) { if (la1tokens[i]) { jj_expentry = new int[1]; jj_expentry[0] = i; jj_expentries.add(jj_expentry); } } int[][] exptokseq = new int[jj_expentries.size()][]; for (int i = 0; i < jj_expentries.size(); i++) { exptokseq[i] = jj_expentries.get(i); } return new ParseException(token, exptokseq, tokenImage); } /** Enable tracing. */ final public void enable_tracing() { } /** Disable tracing. */ final public void disable_tracing() { } }
mit
Tmtravlr/PotionCore
src/main/java/com/tmtravlr/potioncore/potion/EntityPotionCorePotion.java
5504
package com.tmtravlr.potioncore.potion; import io.netty.buffer.Unpooled; import java.util.List; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.projectile.EntityPotion; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.PacketBuffer; import net.minecraft.potion.Potion; import net.minecraft.potion.PotionEffect; import net.minecraft.util.AxisAlignedBB; import net.minecraft.util.BlockPos; import net.minecraft.util.MovingObjectPosition; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import com.tmtravlr.potioncore.PotionCore; import com.tmtravlr.potioncore.network.PacketHandlerClient; import com.tmtravlr.potioncore.network.SToCMessage; public class EntityPotionCorePotion extends EntityPotion { public boolean smashed = false; public ItemStack potion; public EntityPotionCorePotion(World worldIn) { super(worldIn); } public EntityPotionCorePotion(World worldIn, EntityLivingBase throwerIn, int meta) { this(worldIn, throwerIn, new ItemStack(Items.potionitem, 1, meta)); } public EntityPotionCorePotion(World worldIn, EntityLivingBase throwerIn, ItemStack potionIn) { super(worldIn, throwerIn, potionIn); potion = potionIn; } public void sendPotionToClient() { PacketBuffer out = new PacketBuffer(Unpooled.buffer()); out.writeInt(PacketHandlerClient.POTION_ENTITY); out.writeInt(this.getEntityId()); out.writeItemStackToBuffer(potion); SToCMessage packet = new SToCMessage(out); PotionCore.networkWrapper.sendToDimension(packet, this.worldObj.provider.getDimensionId()); } public void doSmashEffects() { PotionCore.proxy.doPotionSmashEffects(new BlockPos(this), potion); } /** * Called when this EntityThrowable hits a block or entity. */ protected void onImpact(MovingObjectPosition position) { if (!this.worldObj.isRemote) { List<PotionEffect> list = ItemPotionCorePotion.instance.getEffects(potion); if (list != null && !list.isEmpty()) { AxisAlignedBB axisalignedbb = this.getEntityBoundingBox().expand(4.0D, 2.0D, 4.0D); List<EntityLivingBase> list1 = this.worldObj.<EntityLivingBase>getEntitiesWithinAABB(EntityLivingBase.class, axisalignedbb); if (!list1.isEmpty()) { for (EntityLivingBase entitylivingbase : list1) { double d0 = this.getDistanceSqToEntity(entitylivingbase); if (d0 < 16.0D) { double d1 = 1.0D - Math.sqrt(d0) / 4.0D; if (entitylivingbase == position.entityHit) { d1 = 1.0D; } for (PotionEffect potioneffect : list) { int i = potioneffect.getPotionID(); if (Potion.potionTypes[i].isInstant()) { Potion.potionTypes[i].affectEntity(this, this.getThrower(), entitylivingbase, potioneffect.getAmplifier(), d1); } else { int j = (int)(d1 * (double)potioneffect.getDuration() + 0.5D); if (j > 20) { entitylivingbase.addPotionEffect(new PotionEffect(i, j, potioneffect.getAmplifier())); } } } } } } } this.worldObj.playSoundAtEntity(this, "game.potion.smash", 1.0F, this.worldObj.rand.nextFloat() * 0.1F + 0.9F); this.setDead(); } else { if(!smashed) { doSmashEffects(); smashed = true; } } } /** * Called to update the entity's position/logic. */ public void onUpdate() { super.onUpdate(); if(!this.worldObj.isRemote && this.ticksExisted < 5) { this.sendPotionToClient(); } } /** * (abstract) Protected helper method to read subclass entity data from NBT. */ public void readEntityFromNBT(NBTTagCompound tagCompund) { super.readEntityFromNBT(tagCompund); if (tagCompund.hasKey("Potion", 10)) { this.potion = ItemStack.loadItemStackFromNBT(tagCompund.getCompoundTag("Potion")); } else { this.setPotionDamage(tagCompund.getInteger("potionValue")); } if (this.potion == null) { this.setDead(); } } /** * (abstract) Protected helper method to write subclass entity data to NBT. */ public void writeEntityToNBT(NBTTagCompound tagCompound) { super.writeEntityToNBT(tagCompound); if (this.potion != null) { tagCompound.setTag("Potion", this.potion.writeToNBT(new NBTTagCompound())); } } }
mit
fjlopez/iw7i
servlets/src/main/java/iw7i/servlets/HelloWorld.java
1683
package iw7i.servlets; import java.io.IOException; import java.io.PrintWriter; import java.util.concurrent.atomic.AtomicInteger; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @SuppressWarnings("serial") @WebServlet(urlPatterns = { "/hello" }) public class HelloWorld extends HttpServlet implements Runnable { private AtomicInteger ticks; private int tocks; private boolean exit; @Override public void init() throws ServletException { ticks = new AtomicInteger(); tocks = 0; exit = false; Thread t = new Thread(this); t.setPriority(1); t.start(); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); out.println("<html><body><h2>Hello (dynamic) World!</h2>"); String value = req.getParameter("name"); if (value != null && value.trim().length() > 0) { out.println("Hello " + value.trim() + "!!"); } out.println("You requested with "+req.getMethod()+" to know my tick " + ticks.incrementAndGet() + " and my tock " + tocks); out.println("</body></html>"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } @Override public void destroy() { ticks = null; exit = true; } @Override public void run() { while(!exit) { tocks++; try { Thread.sleep(100); } catch (InterruptedException e) { } } } }
mit
InnovateUKGitHub/innovation-funding-service
ifs-data-layer/ifs-data-service/src/test/java/org/innovateuk/ifs/competition/transactional/CompetitionSearchServiceImplTest.java
26735
package org.innovateuk.ifs.competition.transactional; import com.google.common.collect.Lists; import org.innovateuk.ifs.BaseServiceUnitTest; import org.innovateuk.ifs.application.repository.ApplicationRepository; import org.innovateuk.ifs.competition.domain.Competition; import org.innovateuk.ifs.competition.domain.Milestone; import org.innovateuk.ifs.competition.mapper.CompetitionMapper; import org.innovateuk.ifs.competition.repository.CompetitionRepository; import org.innovateuk.ifs.competition.repository.GrantTermsAndConditionsRepository; import org.innovateuk.ifs.competition.repository.InnovationLeadRepository; import org.innovateuk.ifs.competition.resource.CompetitionCountResource; import org.innovateuk.ifs.competition.resource.CompetitionStatus; import org.innovateuk.ifs.competition.resource.MilestoneResource; import org.innovateuk.ifs.competition.resource.MilestoneType; import org.innovateuk.ifs.competition.resource.search.CompetitionSearchResult; import org.innovateuk.ifs.competition.resource.search.CompetitionSearchResultItem; import org.innovateuk.ifs.competition.resource.search.PreviousCompetitionSearchResultItem; import org.innovateuk.ifs.competition.resource.search.UpcomingCompetitionSearchResultItem; import org.innovateuk.ifs.organisation.mapper.OrganisationTypeMapper; import org.innovateuk.ifs.project.core.repository.ProjectRepository; import org.innovateuk.ifs.project.resource.ProjectState; import org.innovateuk.ifs.publiccontent.repository.PublicContentRepository; import org.innovateuk.ifs.user.domain.User; import org.innovateuk.ifs.user.mapper.UserMapper; import org.innovateuk.ifs.user.repository.UserRepository; import org.innovateuk.ifs.user.resource.Role; import org.innovateuk.ifs.user.resource.UserResource; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.PageRequest; import org.springframework.test.util.ReflectionTestUtils; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.List; import java.util.Optional; import static java.util.Arrays.asList; import static java.util.Collections.*; import static org.innovateuk.ifs.application.builder.ApplicationBuilder.newApplication; import static org.innovateuk.ifs.commons.service.ServiceResult.serviceSuccess; import static org.innovateuk.ifs.competition.builder.CompetitionBuilder.newCompetition; import static org.innovateuk.ifs.competition.builder.CompetitionTypeBuilder.newCompetitionType; import static org.innovateuk.ifs.competition.builder.MilestoneBuilder.newMilestone; import static org.innovateuk.ifs.competition.builder.MilestoneResourceBuilder.newMilestoneResource; import static org.innovateuk.ifs.publiccontent.builder.PublicContentBuilder.newPublicContent; import static org.innovateuk.ifs.user.builder.UserBuilder.newUser; import static org.innovateuk.ifs.user.builder.UserResourceBuilder.newUserResource; import static org.innovateuk.ifs.user.resource.Role.*; import static org.innovateuk.ifs.util.CollectionFunctions.forEachWithIndex; import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.*; public class CompetitionSearchServiceImplTest extends BaseServiceUnitTest<CompetitionSearchServiceImpl> { @Override protected CompetitionSearchServiceImpl supplyServiceUnderTest() { return new CompetitionSearchServiceImpl(); } @Mock private PublicContentRepository publicContentRepository; @Mock private MilestoneService milestoneService; @Mock private UserRepository userRepositoryMock; @Mock private CompetitionRepository competitionRepositoryMock; @Mock private ApplicationRepository applicationRepository; @Mock private CompetitionMapper competitionMapperMock; @Mock private CompetitionKeyApplicationStatisticsService competitionKeyApplicationStatisticsServiceMock; @Mock private UserMapper userMapperMock; @Mock private OrganisationTypeMapper organisationTypeMapperMock; @Mock private InnovationLeadRepository innovationLeadRepositoryMock; @Mock private GrantTermsAndConditionsRepository grantTermsAndConditionsRepositoryMock; @Mock private ApplicationRepository applicationRepositoryMock; @Mock private ProjectRepository projectRepositoryMock; private Long competitionId = 1L; @Before public void setUp() { UserResource userResource = newUserResource().withRoleGlobal(Role.COMP_ADMIN).build(); User user = newUser().withId(userResource.getId()).withRoles(singleton(Role.COMP_ADMIN)).build(); setLoggedInUser(userResource); when(userRepositoryMock.findById(user.getId())).thenReturn(Optional.of(user)); MilestoneResource milestone = newMilestoneResource().withType(MilestoneType.OPEN_DATE).withDate(ZonedDateTime.now()).build(); when(milestoneService.getMilestoneByTypeAndCompetitionId(eq(MilestoneType.OPEN_DATE), anyLong())).thenReturn(serviceSuccess(milestone)); } @Test public void findLiveCompetitions() { List<Competition> competitions = Lists.newArrayList(newCompetition().withId(competitionId).build()); when(competitionRepositoryMock.findLive()).thenReturn(competitions); List<CompetitionSearchResultItem> response = service.findLiveCompetitions().getSuccess(); assertCompetitionSearchResultsEqualToCompetitions(competitions, response); } @Test public void findProjectSetupCompetitions() { int page = 0; int size = 20; List<Competition> expectedCompetitions = newCompetition().build(2); when(competitionRepositoryMock.findProjectSetup(any())).thenReturn(new PageImpl<>(expectedCompetitions, PageRequest.of(page, size), 1L)); when(applicationRepository.findTopByCompetitionIdOrderByManageFundingEmailDateDesc(expectedCompetitions.get(0).getId())).thenReturn(Optional.of(newApplication().withManageFundingEmailDate(ZonedDateTime.now().minusDays(1)).build())); when(applicationRepository.findTopByCompetitionIdOrderByManageFundingEmailDateDesc(expectedCompetitions.get(1).getId())).thenReturn(Optional.of(newApplication().withManageFundingEmailDate(ZonedDateTime.now()).build())); CompetitionSearchResult response = service.findProjectSetupCompetitions(page, size).getSuccess(); assertCompetitionSearchResultsEqualToCompetitions(expectedCompetitions, response.getContent()); } @Test public void findProjectSetupCompetitions_NoApplications() { int page = 0; int size = 20; List<Competition> expectedCompetitions = newCompetition().build(1); when(competitionRepositoryMock.findProjectSetup(any())).thenReturn(new PageImpl<>(expectedCompetitions, PageRequest.of(page, size), 1L)); when(applicationRepository.findTopByCompetitionIdOrderByManageFundingEmailDateDesc(expectedCompetitions.get(0).getId())).thenReturn(Optional.empty()); CompetitionSearchResult response = service.findProjectSetupCompetitions(page, size).getSuccess(); assertCompetitionSearchResultsEqualToCompetitions(expectedCompetitions, response.getContent()); } @Test public void findProjectSetupCompetitionsWhenLoggedInAsStakeholder() { int page = 0; int size = 20; UserResource stakeholderUser = newUserResource().withId(1L).withRoleGlobal(STAKEHOLDER).build(); User user = newUser().withId(stakeholderUser.getId()).withRoles(singleton(STAKEHOLDER)).build(); setLoggedInUser(stakeholderUser); when(userRepositoryMock.findById(user.getId())).thenReturn(Optional.of(user)); List<Competition> expectedCompetitions = newCompetition().build(2); when(competitionRepositoryMock.findProjectSetupForInnovationLeadOrStakeholderOrCompetitionFinance(eq(stakeholderUser.getId()), any())).thenReturn(new PageImpl<>(expectedCompetitions, PageRequest.of(page, size), 1L)); when(applicationRepository.findTopByCompetitionIdOrderByManageFundingEmailDateDesc(expectedCompetitions.get(0).getId())).thenReturn(Optional.of(newApplication().withManageFundingEmailDate(ZonedDateTime.now().minusDays(1)).build())); when(applicationRepository.findTopByCompetitionIdOrderByManageFundingEmailDateDesc(expectedCompetitions.get(1).getId())).thenReturn(Optional.of(newApplication().withManageFundingEmailDate(ZonedDateTime.now()).build())); CompetitionSearchResult response = service.findProjectSetupCompetitions(page, size).getSuccess(); assertCompetitionSearchResultsEqualToCompetitions(expectedCompetitions, response.getContent()); verify(competitionRepositoryMock).findProjectSetupForInnovationLeadOrStakeholderOrCompetitionFinance(eq(stakeholderUser.getId()), any()); verify(competitionRepositoryMock, never()).findProjectSetup(any()); } @Test public void findProjectSetupCompetitionsWhenLoggedInAsCompetitionFinance() { int page = 0; int size = 20; UserResource competitionFinanceUser = newUserResource().withId(1L).withRoleGlobal(EXTERNAL_FINANCE).build(); User user = newUser().withId(competitionFinanceUser.getId()).withRoles(singleton(EXTERNAL_FINANCE)).build(); setLoggedInUser(competitionFinanceUser); when(userRepositoryMock.findById(user.getId())).thenReturn(Optional.of(user)); List<Competition> expectedCompetitions = newCompetition().build(2); when(competitionRepositoryMock.findProjectSetupForInnovationLeadOrStakeholderOrCompetitionFinance(eq(competitionFinanceUser.getId()), any())).thenReturn(new PageImpl<>(expectedCompetitions, PageRequest.of(page, size), 1L)); when(applicationRepository.findTopByCompetitionIdOrderByManageFundingEmailDateDesc(expectedCompetitions.get(0).getId())).thenReturn(Optional.of(newApplication().withManageFundingEmailDate(ZonedDateTime.now().minusDays(1)).build())); when(applicationRepository.findTopByCompetitionIdOrderByManageFundingEmailDateDesc(expectedCompetitions.get(1).getId())).thenReturn(Optional.of(newApplication().withManageFundingEmailDate(ZonedDateTime.now()).build())); CompetitionSearchResult response = service.findProjectSetupCompetitions(page, size).getSuccess(); assertCompetitionSearchResultsEqualToCompetitions(expectedCompetitions, response.getContent()); verify(competitionRepositoryMock).findProjectSetupForInnovationLeadOrStakeholderOrCompetitionFinance(eq(competitionFinanceUser.getId()), any()); verify(competitionRepositoryMock, never()).findProjectSetup(any()); } @Test public void findUpcomingCompetitions() { List<Competition> competitions = Lists.newArrayList(newCompetition().withId(competitionId).build()); when(competitionRepositoryMock.findUpcoming()).thenReturn(competitions); List<CompetitionSearchResultItem> response = service.findUpcomingCompetitions().getSuccess(); assertCompetitionSearchResultsEqualToCompetitions(competitions, response); } @Test public void findNonIfsCompetitions() { int page = 0; int size = 20; List<Competition> competitions = Lists.newArrayList(newCompetition().withId(competitionId).build()); when(publicContentRepository.findByCompetitionId(competitionId)).thenReturn(newPublicContent().build()); when(competitionRepositoryMock.findNonIfs(any())).thenReturn(new PageImpl<>(competitions, PageRequest.of(page, size), 1L)); CompetitionSearchResult response = service.findNonIfsCompetitions(page, size).getSuccess(); assertCompetitionSearchResultsEqualToCompetitions(competitions, response.getContent()); } @Test public void findPreviousCompetitions() { int page = 0; int size = 20; List<Competition> competitions = Lists.newArrayList(newCompetition().withId(competitionId).build(1)); when(competitionRepositoryMock.findPrevious(any())).thenReturn(new PageImpl<>(competitions, PageRequest.of(page, size), 30)); when(applicationRepository.countPrevious(competitionId)).thenReturn(1); when(projectRepositoryMock.countByApplicationCompetitionId(competitionId)).thenReturn(2); when(projectRepositoryMock.countByApplicationCompetitionIdAndProjectProcessActivityStateIn(competitionId, ProjectState.COMPLETED_STATES)).thenReturn(3); CompetitionSearchResult response = service.findPreviousCompetitions(page, size).getSuccess(); assertEquals((long) competitionId, response.getContent().get(0).getId()); assertEquals(1, ((PreviousCompetitionSearchResultItem) response.getContent().get(0)).getApplications()); assertEquals(2, ((PreviousCompetitionSearchResultItem) response.getContent().get(0)).getProjects()); assertEquals(3, ((PreviousCompetitionSearchResultItem) response.getContent().get(0)).getCompleteProjects()); } @Test public void findPreviousCompetitionsWhenLoggedInAsCompetitionFinanceUser() { int page = 0; int size = 20; UserResource competitionFinanceUser = newUserResource().withId(1L).withRoleGlobal(EXTERNAL_FINANCE).build(); User user = newUser().withId(competitionFinanceUser.getId()).withRoles(singleton(EXTERNAL_FINANCE)).build(); setLoggedInUser(competitionFinanceUser); when(userRepositoryMock.findById(user.getId())).thenReturn(Optional.of(user)); List<Competition> competitions = Lists.newArrayList(newCompetition().withId(competitionId).build(1)); when(competitionRepositoryMock.findPreviousForInnovationLeadOrStakeholderOrCompetitionFinance(user.getId(), PageRequest.of(page, size))).thenReturn(new PageImpl<>(competitions, PageRequest.of(page, size), 30)); when(applicationRepository.countPrevious(competitionId)).thenReturn(1); when(projectRepositoryMock.countByApplicationCompetitionId(competitionId)).thenReturn(2); when(projectRepositoryMock.countByApplicationCompetitionIdAndProjectProcessActivityStateIn(competitionId, ProjectState.COMPLETED_STATES)).thenReturn(3); CompetitionSearchResult response = service.findPreviousCompetitions(page, size).getSuccess(); assertEquals((long) competitionId, response.getContent().get(0).getId()); assertEquals(1, ((PreviousCompetitionSearchResultItem) response.getContent().get(0)).getApplications()); assertEquals(2, ((PreviousCompetitionSearchResultItem) response.getContent().get(0)).getProjects()); assertEquals(3, ((PreviousCompetitionSearchResultItem) response.getContent().get(0)).getCompleteProjects()); } @Test public void countCompetitions() { Long countLive = 1L; Long countProjectSetup = 2L; Long countUpcoming = 3L; Long countFeedbackReleased = 4L; when(competitionRepositoryMock.countLive()).thenReturn(countLive); when(competitionRepositoryMock.countProjectSetup()).thenReturn(countProjectSetup); when(competitionRepositoryMock.countUpcoming()).thenReturn(countUpcoming); when(competitionRepositoryMock.countPrevious()).thenReturn(countFeedbackReleased); CompetitionCountResource response = service.countCompetitions().getSuccess(); assertEquals(countLive, response.getLiveCount()); assertEquals(countProjectSetup, response.getProjectSetupCount()); assertEquals(countUpcoming, response.getUpcomingCount()); assertEquals(countFeedbackReleased, response.getFeedbackReleasedCount()); // Test for innovation lead user where only competitions they are assigned to should be counted // actual query tested in repository integration test, this is only testing correct repository method is called. UserResource innovationLeadUser = newUserResource().withRoleGlobal(INNOVATION_LEAD).build(); setLoggedInUser(innovationLeadUser); when(competitionRepositoryMock.countLiveForInnovationLeadOrStakeholder(innovationLeadUser.getId())).thenReturn(countLive); when(competitionRepositoryMock.countProjectSetupForInnovationLeadOrStakeholder(innovationLeadUser.getId())).thenReturn(countProjectSetup); when(competitionRepositoryMock.countPreviousForInnovationLeadOrStakeholder(innovationLeadUser.getId())).thenReturn(countFeedbackReleased); when(userRepositoryMock.findById(innovationLeadUser.getId())).thenReturn(Optional.of(newUser().withId(innovationLeadUser.getId()).withRoles(singleton(Role.INNOVATION_LEAD)).build())); response = service.countCompetitions().getSuccess(); assertEquals(countLive, response.getLiveCount()); assertEquals(countProjectSetup, response.getProjectSetupCount()); assertEquals(countUpcoming, response.getUpcomingCount()); assertEquals(countFeedbackReleased, response.getFeedbackReleasedCount()); // Test for Stakeholder user UserResource stakeholderUser = newUserResource().withRoleGlobal(Role.STAKEHOLDER).build(); setLoggedInUser(stakeholderUser); when(competitionRepositoryMock.countLiveForInnovationLeadOrStakeholder(stakeholderUser.getId())).thenReturn(countLive); when(competitionRepositoryMock.countProjectSetupForInnovationLeadOrStakeholder(stakeholderUser.getId())).thenReturn(countProjectSetup); when(competitionRepositoryMock.countPreviousForInnovationLeadOrStakeholder(stakeholderUser.getId())).thenReturn(countFeedbackReleased); when(userRepositoryMock.findById(stakeholderUser.getId())).thenReturn(Optional.of(newUser().withId(stakeholderUser.getId()).withRoles(singleton(Role.STAKEHOLDER)).build())); response = service.countCompetitions().getSuccess(); assertEquals(countLive, response.getLiveCount()); assertEquals(countProjectSetup, response.getProjectSetupCount()); assertEquals(countUpcoming, response.getUpcomingCount()); assertEquals(countFeedbackReleased, response.getFeedbackReleasedCount()); } @Test public void searchCompetitions() { String searchQuery = "SearchQuery"; String searchLike = "%" + searchQuery + "%"; String competitionType = "Comp type"; int page = 1; int size = 20; PageRequest pageRequest = PageRequest.of(page, size); Page<Competition> queryResponse = mock(Page.class); long totalElements = 2L; int totalPages = 1; ZonedDateTime openDate = ZonedDateTime.now(); Milestone openDateMilestone = newMilestone().withType(MilestoneType.OPEN_DATE).withDate(openDate).build(); Competition competition = newCompetition().withId(competitionId).withCompetitionType(newCompetitionType().withName(competitionType).build()).withMilestones(asList(openDateMilestone)).build(); when(queryResponse.getTotalElements()).thenReturn(totalElements); when(queryResponse.getTotalPages()).thenReturn(totalPages); when(queryResponse.getNumber()).thenReturn(page); when(queryResponse.getNumberOfElements()).thenReturn(size); when(queryResponse.getContent()).thenReturn(singletonList(competition)); when(queryResponse.getPageable()).thenReturn(pageRequest); when(competitionRepositoryMock.search(searchLike, pageRequest)).thenReturn(queryResponse); CompetitionSearchResult response = service.searchCompetitions(searchQuery, page, size).getSuccess(); assertEquals(totalElements, response.getTotalElements()); assertEquals(totalPages, response.getTotalPages()); assertEquals(page, response.getNumber()); assertEquals(size, response.getSize()); CompetitionSearchResultItem expectedSearchResult = new UpcomingCompetitionSearchResultItem(competition.getId(), competition.getName(), CompetitionStatus.COMPETITION_SETUP, competitionType, EMPTY_SET, openDate.format(DateTimeFormatter.ofPattern("dd/MM/YYYY"))); assertEquals(expectedSearchResult.getId(), (long) competition.getId()); } @Test public void searchCompetitionsAsLeadTechnologist() { long totalElements = 2L; int totalPages = 1; int page = 1; int size = 20; String searchQuery = "SearchQuery"; String competitionType = "Comp type"; Competition competition = newCompetition().withId(competitionId).withCompetitionType(newCompetitionType().withName(competitionType).build()).build(); UserResource userResource = newUserResource().withRoleGlobal(Role.INNOVATION_LEAD).build(); User user = newUser().withId(userResource.getId()).withRoles(singleton(Role.INNOVATION_LEAD)).build(); searchCompetitionsMocking(totalElements, totalPages, page, size, searchQuery, competition, userResource, user); CompetitionSearchResult response = service.searchCompetitions(searchQuery, page, size).getSuccess(); searchCompetitionsAssertions(totalElements, totalPages, page, size, competitionType, competition, response); verify(competitionRepositoryMock).searchForInnovationLeadOrStakeholder(any(), anyLong(), any()); verify(competitionRepositoryMock, never()).searchForSupportUser(any(), any()); verify(competitionRepositoryMock, never()).search(any(), any()); } private void searchCompetitionsMocking(long totalElements, int totalPages, int page, int size, String searchQuery, Competition competition, UserResource userResource, User user) { String searchLike = "%" + searchQuery + "%"; PageRequest pageRequest = PageRequest.of(page, size); Page<Competition> queryResponse = mock(Page.class); setLoggedInUser(userResource); when(userRepositoryMock.findById(user.getId())).thenReturn(Optional.of(user)); when(queryResponse.getTotalElements()).thenReturn(totalElements); when(queryResponse.getTotalPages()).thenReturn(totalPages); when(queryResponse.getNumber()).thenReturn(page); when(queryResponse.getNumberOfElements()).thenReturn(size); when(queryResponse.getContent()).thenReturn(singletonList(competition)); when(queryResponse.getPageable()).thenReturn(pageRequest); if (user.hasRole(INNOVATION_LEAD) || user.hasRole(STAKEHOLDER)) { when(competitionRepositoryMock.searchForInnovationLeadOrStakeholder(searchLike, user.getId(), pageRequest)).thenReturn(queryResponse); } else if (user.hasRole(SUPPORT)) { when(competitionRepositoryMock.searchForSupportUser(searchLike, pageRequest)).thenReturn(queryResponse); } } private void searchCompetitionsAssertions(long totalElements, int totalPages, int page, int size, String competitionType, Competition competition, CompetitionSearchResult response) { assertEquals(totalElements, response.getTotalElements()); assertEquals(totalPages, response.getTotalPages()); assertEquals(page, response.getNumber()); assertEquals(size, response.getSize()); CompetitionSearchResultItem expectedSearchResult = new UpcomingCompetitionSearchResultItem(competition.getId(), competition.getName(), CompetitionStatus.COMPETITION_SETUP, competitionType, EMPTY_SET, ZonedDateTime.now().format(DateTimeFormatter.ofPattern("dd/MM/YYYY"))); assertEquals(expectedSearchResult.getId(), (long) competition.getId()); } @Test public void searchCompetitionsAsStakeholder() { long totalElements = 2L; int totalPages = 1; int page = 1; int size = 20; String searchQuery = "SearchQuery"; String competitionType = "Comp type"; Competition competition = newCompetition().withId(competitionId).withCompetitionType(newCompetitionType().withName(competitionType).build()).build(); UserResource userResource = newUserResource().withRoleGlobal(Role.STAKEHOLDER).build(); User user = newUser().withId(userResource.getId()).withRoles(singleton(Role.STAKEHOLDER)).build(); searchCompetitionsMocking(totalElements, totalPages, page, size, searchQuery, competition, userResource, user); CompetitionSearchResult response = service.searchCompetitions(searchQuery, page, size).getSuccess(); searchCompetitionsAssertions(totalElements, totalPages, page, size, competitionType, competition, response); verify(competitionRepositoryMock).searchForInnovationLeadOrStakeholder(any(), anyLong(), any()); verify(competitionRepositoryMock, never()).searchForSupportUser(any(), any()); verify(competitionRepositoryMock, never()).search(any(), any()); } @Test public void searchCompetitionsAsSupportUser() { long totalElements = 2L; int totalPages = 1; int page = 1; int size = 20; String searchQuery = "SearchQuery"; String competitionType = "Comp type"; Competition competition = newCompetition().withId(competitionId).withCompetitionType(newCompetitionType().withName(competitionType).build()).build(); UserResource userResource = newUserResource().withRoleGlobal(Role.SUPPORT).build(); User user = newUser().withId(userResource.getId()).withRoles(singleton(Role.SUPPORT)).build(); searchCompetitionsMocking(totalElements, totalPages, page, size, searchQuery, competition, userResource, user); CompetitionSearchResult response = service.searchCompetitions(searchQuery, page, size).getSuccess(); searchCompetitionsAssertions(totalElements, totalPages, page, size, competitionType, competition, response); verify(competitionRepositoryMock, never()).searchForInnovationLeadOrStakeholder(any(), anyLong(), any()); verify(competitionRepositoryMock).searchForSupportUser(any(), any()); verify(competitionRepositoryMock, never()).search(any(), any()); } private void assertCompetitionSearchResultsEqualToCompetitions(List<Competition> competitions, List<CompetitionSearchResultItem> searchResults) { assertEquals(competitions.size(), searchResults.size()); forEachWithIndex(searchResults, (i, searchResult) -> { Competition originalCompetition = competitions.get(i); assertEquals((long) originalCompetition.getId(), searchResult.getId()); assertEquals(originalCompetition.getName(), ReflectionTestUtils.getField(searchResult, "name")); }); } }
mit
cecylopez/inventario
src/org/inventario/data/SolicitudesRepository.java
2031
package org.inventario.data; import java.util.ArrayList; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.TypedQuery; import org.inventario.data.entities.SolicitudAsignacion; public class SolicitudesRepository extends BaseRepository<SolicitudAsignacion> { public SolicitudesRepository() { super(SolicitudAsignacion.class); } public List<SolicitudAsignacion> get(long departamentoId, String nombreItem, int startIndex, int pageSize) { List<SolicitudAsignacion> solicitudes = new ArrayList(0); TypedQuery<SolicitudAsignacion> qry = null; if ((nombreItem != null) && (nombreItem.trim().length() > 0)) { qry = this.eMgr.createQuery("SELECT s FROM SolicitudAsignacion s INNER JOIN AsignacionItem a ON s.asignacionItem.id=a.id INNER JOIN Item i ON a.item.id=i.id WHERE a.departamento.id= :departamento AND i.nombre LIKE :nombre ", SolicitudAsignacion.class); qry.setParameter("nombre", "%" + nombreItem + "%"); } else { qry = this.eMgr.createQuery("SELECT s FROM SolicitudAsignacion s INNER JOIN AsignacionItem a ON s.asignacionItem.id=a.id INNER JOIN Item i ON a.item.id=i.id WHERE a.departamento.id= :departamento ", SolicitudAsignacion.class); } qry.setParameter("departamento", Long.valueOf(departamentoId)); qry.setFirstResult(startIndex); qry.setMaxResults(pageSize); solicitudes = qry.getResultList(); return solicitudes; } public SolicitudAsignacion getSolicitudPendiente(long departamentoId, long itemId){ SolicitudAsignacion solicitud= new SolicitudAsignacion(); TypedQuery<SolicitudAsignacion> qry=this.eMgr.createQuery("SELECT s FROM SolicitudAsignacion s INNER JOIN AsignacionItem a ON s.asignacionItem.id=a.id WHERE a.departamento.id= :departamentoId AND a.item.id= :itemId AND s.estado='P'", SolicitudAsignacion.class); qry.setParameter("departamentoId", departamentoId); qry.setParameter("itemId", itemId); solicitud=qry.getSingleResult(); return solicitud; } }
mit
vangav/vos_instagram
app/com/vangav/vos_instagram/cassandra_keyspaces/ig_app_data/CountTotal.java
13943
/** * "First, solve the problem. Then, write the code. -John Johnson" * "Or use Vangav M" * www.vangav.com * */ /** * MIT License * * Copyright (c) 2016 Vangav * * 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. * */ /** * Community * Facebook Group: Vangav Open Source - Backend * fb.com/groups/575834775932682/ * Facebook Page: Vangav * fb.com/vangav.f * * Third party communities for Vangav Backend * - play framework * - cassandra * - datastax * * Tag your question online (e.g.: stack overflow, etc ...) with * #vangav_backend * to easier find questions/answers online * */ package com.vangav.vos_instagram.cassandra_keyspaces.ig_app_data; import com.datastax.driver.core.BoundStatement; import com.datastax.driver.core.ResultSet; import com.datastax.driver.core.ResultSetFuture; import com.vangav.backend.cassandra.keyspaces.Query; import com.vangav.backend.cassandra.keyspaces.Table; import com.vangav.backend.cassandra.keyspaces.dispatch_message.QueryDispatchable; /** * GENERATED using JavaClientGeneratorMain.java */ /** * CountTotal represents * Table [count_total] * in Keyspace [ig_app_data] * * Name: count_total * Description: * stores user-related counts (e.g.: total likes/comments received, ...) * -- used for ranking/scoring * * Columns: * user_id : uuid * likes_received_count : counter * comments_received_count : counter * Partition Keys: user_id * Secondary Keys: * Caching: ALL * Order By: * Queries: * - Name: increment_likes_received_count * Description: * increments received likes count * Prepared Statement: * UPDATE ig_app_data.count_total SET likes_received_count = * likes_received_count + 1 WHERE user_id = :user_id; * - Name: increment_comments_received_count * Description: * increments received comments count * Prepared Statement: * UPDATE ig_app_data.count_total SET comments_received_count = * comments_received_count + 1 WHERE user_id = :user_id; * - Name: select * Description: * selects all counters * Prepared Statement: * SELECT likes_received_count, comments_received_count FROM * ig_app_data.count_total WHERE user_id = :user_id; * */ public class CountTotal extends Table { private static final String kKeySpaceName = "ig_app_data"; private static final String kTableName = "count_total"; public static final String kUserIdColumnName = "user_id"; public static final String kLikesReceivedCountColumnName = "likes_received_count"; public static final String kCommentsReceivedCountColumnName = "comments_received_count"; /** * Query: * Name: increment_likes_received_count * Description: * increments received likes count * Prepared Statement: * UPDATE ig_app_data.count_total SET likes_received_count = * likes_received_count + 1 WHERE user_id = :user_id; */ private static final String kIncrementLikesReceivedCountName = "increment_likes_received_count"; private static final String kIncrementLikesReceivedCountDescription = "increments received likes count "; private static final String kIncrementLikesReceivedCountPreparedStatement = "UPDATE ig_app_data.count_total SET likes_received_count = " + "likes_received_count + 1 WHERE user_id = :user_id; "; /** * Query: * Name: increment_comments_received_count * Description: * increments received comments count * Prepared Statement: * UPDATE ig_app_data.count_total SET comments_received_count = * comments_received_count + 1 WHERE user_id = :user_id; */ private static final String kIncrementCommentsReceivedCountName = "increment_comments_received_count"; private static final String kIncrementCommentsReceivedCountDescription = "increments received comments count "; private static final String kIncrementCommentsReceivedCountPreparedStatement = "UPDATE ig_app_data.count_total SET comments_received_count = " + "comments_received_count + 1 WHERE user_id = :user_id; "; /** * Query: * Name: select * Description: * selects all counters * Prepared Statement: * SELECT likes_received_count, comments_received_count FROM * ig_app_data.count_total WHERE user_id = :user_id; */ private static final String kSelectName = "select"; private static final String kSelectDescription = "selects all counters "; private static final String kSelectPreparedStatement = "SELECT likes_received_count, comments_received_count FROM " + "ig_app_data.count_total WHERE user_id = :user_id; "; /** * Constructor CountTotal * @return new CountTotal Object * @throws Exception */ private CountTotal () throws Exception { super ( kKeySpaceName, kTableName, new Query ( kIncrementLikesReceivedCountDescription, kIncrementLikesReceivedCountName, kIncrementLikesReceivedCountPreparedStatement), new Query ( kIncrementCommentsReceivedCountDescription, kIncrementCommentsReceivedCountName, kIncrementCommentsReceivedCountPreparedStatement), new Query ( kSelectDescription, kSelectName, kSelectPreparedStatement)); } private static CountTotal instance = null; /** * loadTable * OPTIONAL method * instance is created either upon calling this method or upon the first call * to singleton instance method i * this method is useful for loading upon program start instead of loading * it upon the first use since there's a small time overhead for loading * since all queries are prepared synchronously in a blocking network * operation with Cassandra's server * @throws Exception */ public static void loadTable () throws Exception { if (instance == null) { instance = new CountTotal(); } } /** * i * @return singleton static instance of CountTotal * @throws Exception */ public static CountTotal i () throws Exception { if (instance == null) { instance = new CountTotal(); } return instance; } // Query: IncrementLikesReceivedCount // Description: // increments received likes count // Parepared Statement: // UPDATE ig_app_data.count_total SET likes_received_count = // likes_received_count + 1 WHERE user_id = :user_id; /** * getQueryIncrementLikesReceivedCount * @return IncrementLikesReceivedCount Query in the form of * a Query Object * @throws Exception */ public Query getQueryIncrementLikesReceivedCount ( ) throws Exception { return this.getQuery(kIncrementLikesReceivedCountName); } /** * getQueryDispatchableIncrementLikesReceivedCount * @param userid * @return IncrementLikesReceivedCount Query in the form of * a QueryDisbatchable Object * (e.g.: to be passed on to a worker instance) * @throws Exception */ public QueryDispatchable getQueryDispatchableIncrementLikesReceivedCount ( Object userid) throws Exception { return this.getQueryDispatchable( kIncrementLikesReceivedCountName, userid); } /** * getBoundStatementIncrementLikesReceivedCount * @param userid * @return IncrementLikesReceivedCount Query in the form of * a BoundStatement ready for execution or to be added to * a BatchStatement * @throws Exception */ public BoundStatement getBoundStatementIncrementLikesReceivedCount ( Object userid) throws Exception { return this.getQuery(kIncrementLikesReceivedCountName).getBoundStatement( userid); } /** * executeAsyncIncrementLikesReceivedCount * executes IncrementLikesReceivedCount Query asynchronously * @param userid * @return ResultSetFuture * @throws Exception */ public ResultSetFuture executeAsyncIncrementLikesReceivedCount ( Object userid) throws Exception { return this.getQuery(kIncrementLikesReceivedCountName).executeAsync( userid); } /** * executeSyncIncrementLikesReceivedCount * BLOCKING-METHOD: blocks till the ResultSet is ready * executes IncrementLikesReceivedCount Query synchronously * @param userid * @return ResultSet * @throws Exception */ public ResultSet executeSyncIncrementLikesReceivedCount ( Object userid) throws Exception { return this.getQuery(kIncrementLikesReceivedCountName).executeSync( userid); } // Query: IncrementCommentsReceivedCount // Description: // increments received comments count // Parepared Statement: // UPDATE ig_app_data.count_total SET comments_received_count = // comments_received_count + 1 WHERE user_id = :user_id; /** * getQueryIncrementCommentsReceivedCount * @return IncrementCommentsReceivedCount Query in the form of * a Query Object * @throws Exception */ public Query getQueryIncrementCommentsReceivedCount ( ) throws Exception { return this.getQuery(kIncrementCommentsReceivedCountName); } /** * getQueryDispatchableIncrementCommentsReceivedCount * @param userid * @return IncrementCommentsReceivedCount Query in the form of * a QueryDisbatchable Object * (e.g.: to be passed on to a worker instance) * @throws Exception */ public QueryDispatchable getQueryDispatchableIncrementCommentsReceivedCount ( Object userid) throws Exception { return this.getQueryDispatchable( kIncrementCommentsReceivedCountName, userid); } /** * getBoundStatementIncrementCommentsReceivedCount * @param userid * @return IncrementCommentsReceivedCount Query in the form of * a BoundStatement ready for execution or to be added to * a BatchStatement * @throws Exception */ public BoundStatement getBoundStatementIncrementCommentsReceivedCount ( Object userid) throws Exception { return this.getQuery(kIncrementCommentsReceivedCountName).getBoundStatement( userid); } /** * executeAsyncIncrementCommentsReceivedCount * executes IncrementCommentsReceivedCount Query asynchronously * @param userid * @return ResultSetFuture * @throws Exception */ public ResultSetFuture executeAsyncIncrementCommentsReceivedCount ( Object userid) throws Exception { return this.getQuery(kIncrementCommentsReceivedCountName).executeAsync( userid); } /** * executeSyncIncrementCommentsReceivedCount * BLOCKING-METHOD: blocks till the ResultSet is ready * executes IncrementCommentsReceivedCount Query synchronously * @param userid * @return ResultSet * @throws Exception */ public ResultSet executeSyncIncrementCommentsReceivedCount ( Object userid) throws Exception { return this.getQuery(kIncrementCommentsReceivedCountName).executeSync( userid); } // Query: Select // Description: // selects all counters // Parepared Statement: // SELECT likes_received_count, comments_received_count FROM // ig_app_data.count_total WHERE user_id = :user_id; /** * getQuerySelect * @return Select Query in the form of * a Query Object * @throws Exception */ public Query getQuerySelect ( ) throws Exception { return this.getQuery(kSelectName); } /** * getQueryDispatchableSelect * @param userid * @return Select Query in the form of * a QueryDisbatchable Object * (e.g.: to be passed on to a worker instance) * @throws Exception */ public QueryDispatchable getQueryDispatchableSelect ( Object userid) throws Exception { return this.getQueryDispatchable( kSelectName, userid); } /** * getBoundStatementSelect * @param userid * @return Select Query in the form of * a BoundStatement ready for execution or to be added to * a BatchStatement * @throws Exception */ public BoundStatement getBoundStatementSelect ( Object userid) throws Exception { return this.getQuery(kSelectName).getBoundStatement( userid); } /** * executeAsyncSelect * executes Select Query asynchronously * @param userid * @return ResultSetFuture * @throws Exception */ public ResultSetFuture executeAsyncSelect ( Object userid) throws Exception { return this.getQuery(kSelectName).executeAsync( userid); } /** * executeSyncSelect * BLOCKING-METHOD: blocks till the ResultSet is ready * executes Select Query synchronously * @param userid * @return ResultSet * @throws Exception */ public ResultSet executeSyncSelect ( Object userid) throws Exception { return this.getQuery(kSelectName).executeSync( userid); } }
mit
PaulNoth/hackerrank
practice/algorithms/implementation/sherlock_and_the_beast/SherlockBeast.java
1122
import java.util.Arrays; import java.util.Scanner; public class SherlockBeast { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int tests = stdin.nextInt(); for(int i = 0; i < tests; i++) { int num = stdin.nextInt(); int fives = fiveCount(num); System.out.println(createOutput(num, fives)); } stdin.close(); } private static int fiveCount(int num) { int fives = num; while (fives >= 0 && (num - fives) <= num) { if(fives % 3 == 0 && (num - fives) % 5 == 0) { return fives; } fives -= 5; } return -1; } private static String createOutput(int num, int fives) { if(fives == -1) { return "-1"; } else { char[] fivess = new char[fives]; char[] threes = new char[num - fives]; Arrays.fill(fivess, '5'); Arrays.fill(threes, '3'); return new StringBuilder().append(fivess).append(threes).toString(); } } }
mit
meiyl/GeekBBS
src/com/geekbbs/service/CommentServiceImpl.java
759
package com.geekbbs.service; import java.util.List; import com.geekbbs.dao.CommentDAO; import com.geekbbs.model.Comment; public class CommentServiceImpl implements CommentService { private CommentDAO commentDAO; @Override public void addComment(String author, int articleId, String comment) { // TODO Auto-generated method stub commentDAO.createComment(comment, author, articleId); } @Override public List<Comment> getCommentsByArticleId(String articleId) { // TODO Auto-generated method stub List<Comment> comments = commentDAO.getCommentsByArticleId(articleId); return comments; } public CommentDAO getCommentDAO() { return commentDAO; } public void setCommentDAO(CommentDAO commentDAO) { this.commentDAO = commentDAO; } }
mit
highcharts4gwt/highcharts4gwt
src/main/java/com/github/highcharts4gwt/generator/object/field/FieldArrayObjectWriter.java
3300
package com.github.highcharts4gwt.generator.object.field; import javax.annotation.CheckForNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.highcharts4gwt.generator.common.ClassRegistry; import com.github.highcharts4gwt.generator.common.OutputType; import com.github.highcharts4gwt.generator.common.OutputTypeVisitor; import com.github.highcharts4gwt.generator.object.Object; import com.github.highcharts4gwt.generator.option.field.AbstractFieldWriter; import com.github.highcharts4gwt.generator.option.field.InterfaceFieldHelper; import com.github.highcharts4gwt.generator.option.field.JsoFieldHelper; import com.github.highcharts4gwt.generator.option.field.MockFieldHelper; import com.github.highcharts4gwt.model.array.api.Array; import com.sun.codemodel.JClass; import com.sun.codemodel.JCodeModel; import com.sun.codemodel.JDefinedClass; public class FieldArrayObjectWriter extends AbstractFieldWriter implements OutputTypeVisitor<Void, Void> { private static final Logger logger = LoggerFactory.getLogger(FieldArrayObjectWriter.class); private final Object object; public FieldArrayObjectWriter(JDefinedClass jClass, boolean pipe, String fieldName, Object object) { super(jClass, pipe, fieldName, object.getDescription()); this.object = object; } @Override @CheckForNull public Void visitInterface(Void in) { JClass fieldClazz = getNarrowedArrayClass(); if (fieldClazz == null) return null; InterfaceFieldHelper.addGetterDeclaration(getNames(), fieldClazz, getJclass()); return null; } @Override @CheckForNull public Void visitJso(Void in) { JClass fieldClazz = getNarrowedArrayClass(); if (fieldClazz == null) return null; JsoFieldHelper.writeGetterNativeCodeArrayObject(getNames(), fieldClazz, getJclass(), null); return null; } @Override @CheckForNull public Void visitMock(Void in) { JClass fieldClazz = getNarrowedArrayClass(); if (fieldClazz == null) return null; MockFieldHelper.addGetterDeclaration(getNames(), fieldClazz, getJclass()); return null; } private JClass getNarrowedArrayClass() { // extract String narrowedClass = null; if (!hasPipe()) { narrowedClass = object.getReturnType().substring(6, object.getReturnType().length() - 1); } else { logger.error("Array with pipe not supported for object;" + object.getFullname()); return null; } ClassRegistry.RegistryKey key = new ClassRegistry.RegistryKey(new Object(narrowedClass, narrowedClass, narrowedClass), OutputType.Interface); JClass jClass = ClassRegistry.INSTANCE.getRegistry().get(key); if (jClass == null) { logger.error("Could not create field Array<>;" + object.getFullname()); return null; } JClass genericArray = new JCodeModel().ref(Array.class); JClass arrayOfSpecializedType = genericArray.narrow(jClass); return arrayOfSpecializedType; } @Override protected String getNameExtension() { return "AsArrayObject"; } }
mit
SWEZenith/Living-History-API
src/main/java/com/zenith/livinghistory/api/zenithlivinghistoryapi/controller/UserController.java
2392
package com.zenith.livinghistory.api.zenithlivinghistoryapi.controller; import com.zenith.livinghistory.api.zenithlivinghistoryapi.data.repository.AnnotationRepository; import com.zenith.livinghistory.api.zenithlivinghistoryapi.data.repository.ContentRepository; import com.zenith.livinghistory.api.zenithlivinghistoryapi.data.repository.UserRepository; import com.zenith.livinghistory.api.zenithlivinghistoryapi.dto.Annotation; import com.zenith.livinghistory.api.zenithlivinghistoryapi.dto.Content; import com.zenith.livinghistory.api.zenithlivinghistoryapi.dto.User; import com.zenith.livinghistory.api.zenithlivinghistoryapi.dto.request.ContentsByCreator; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("api/v1/users") public class UserController { private ContentRepository contentRepository; private UserRepository userRepository; private AnnotationRepository annotationRepository; public UserController(ContentRepository contentRepository, UserRepository userRepository, AnnotationRepository annotationRepository) { this.contentRepository = contentRepository; this.userRepository = userRepository; this.annotationRepository = annotationRepository; } @RequestMapping(method = RequestMethod.GET, value = "/{username}") public User get(@PathVariable String username) { return userRepository.findFirstByUsername(username); } @RequestMapping(method = RequestMethod.GET, value = "/{username}/contents") public List<Content> getContents(@PathVariable String username) { return contentRepository.findContentsByUsername(username); } @RequestMapping(method = RequestMethod.POST, value = "/contents") public List<Content> getContents(@RequestBody ContentsByCreator request) { return contentRepository.findContentsByCreator(request.getCreator()); } @RequestMapping(method = RequestMethod.GET, value = "/{username}/annotations") public List<Annotation> getAnnotations(@PathVariable String username) { return annotationRepository.findAnnotationsByUsername(username); } @RequestMapping(method = RequestMethod.POST, value = "/annotations") public List<Annotation> getAnnotations(@RequestBody ContentsByCreator request) { return annotationRepository.findByCreator(request.getCreator()); } }
mit
xxbeanxx/spring-cxf
src/main/generated/cxf/net/webservicex/GetWeatherResponse.java
1661
package net.webservicex; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="GetWeatherResult" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "getWeatherResult" }) @XmlRootElement(name = "GetWeatherResponse") public class GetWeatherResponse { @XmlElement(name = "GetWeatherResult") protected String getWeatherResult; /** * Gets the value of the getWeatherResult property. * * @return * possible object is * {@link String } * */ public String getGetWeatherResult() { return getWeatherResult; } /** * Sets the value of the getWeatherResult property. * * @param value * allowed object is * {@link String } * */ public void setGetWeatherResult(String value) { this.getWeatherResult = value; } }
mit
openforis/calc
calc-core/src/generated/java/org/openforis/calc/persistence/jooq/tables/daos/ProcessingChainDao.java
3080
/** * This class is generated by jOOQ */ package org.openforis.calc.persistence.jooq.tables.daos; import java.util.List; import javax.annotation.Generated; import org.jooq.Configuration; import org.jooq.impl.DAOImpl; import org.openforis.calc.engine.ParameterMap; import org.openforis.calc.engine.Worker.Status; import org.openforis.calc.persistence.jooq.tables.ProcessingChainTable; import org.openforis.calc.persistence.jooq.tables.records.ProcessingChainRecord; import org.openforis.calc.chain.ProcessingChain; /** * This class is generated by jOOQ. */ @Generated( value = { "http://www.jooq.org", "jOOQ version:3.6.2" }, comments = "This class is generated by jOOQ" ) @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class ProcessingChainDao extends DAOImpl<ProcessingChainRecord, ProcessingChain, Integer> { /** * Create a new ProcessingChainDao without any configuration */ public ProcessingChainDao() { super(ProcessingChainTable.PROCESSING_CHAIN, ProcessingChain.class); } /** * Create a new ProcessingChainDao with an attached configuration */ public ProcessingChainDao(Configuration configuration) { super(ProcessingChainTable.PROCESSING_CHAIN, ProcessingChain.class, configuration); } /** * {@inheritDoc} */ @Override protected Integer getId(ProcessingChain object) { return object.getId(); } /** * Fetch records that have <code>id IN (values)</code> */ public List<ProcessingChain> fetchById(Integer... values) { return fetch(ProcessingChainTable.PROCESSING_CHAIN.ID, values); } /** * Fetch a unique record that has <code>id = value</code> */ public ProcessingChain fetchOneById(Integer value) { return fetchOne(ProcessingChainTable.PROCESSING_CHAIN.ID, value); } /** * Fetch records that have <code>workspace_id IN (values)</code> */ public List<ProcessingChain> fetchByWorkspaceId(Integer... values) { return fetch(ProcessingChainTable.PROCESSING_CHAIN.WORKSPACE_ID, values); } /** * Fetch records that have <code>parameters IN (values)</code> */ public List<ProcessingChain> fetchByParameters(ParameterMap... values) { return fetch(ProcessingChainTable.PROCESSING_CHAIN.PARAMETERS, values); } /** * Fetch records that have <code>caption IN (values)</code> */ public List<ProcessingChain> fetchByCaption(String... values) { return fetch(ProcessingChainTable.PROCESSING_CHAIN.CAPTION, values); } /** * Fetch records that have <code>description IN (values)</code> */ public List<ProcessingChain> fetchByDescription(String... values) { return fetch(ProcessingChainTable.PROCESSING_CHAIN.DESCRIPTION, values); } /** * Fetch records that have <code>status IN (values)</code> */ public List<ProcessingChain> fetchByStatus(Status... values) { return fetch(ProcessingChainTable.PROCESSING_CHAIN.STATUS, values); } /** * Fetch records that have <code>common_script IN (values)</code> */ public List<ProcessingChain> fetchByCommonScript(String... values) { return fetch(ProcessingChainTable.PROCESSING_CHAIN.COMMON_SCRIPT, values); } }
mit
WorriedMan/Crimes-base
client/src/ConnectionWorker.java
16014
import javax.crypto.Cipher; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.nio.ByteBuffer; import java.security.PublicKey; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Objects; public class ConnectionWorker implements Runnable { private final String ANSI_RED_BACKGROUND = "\u001B[41m"; private DataInputStream mInputStream; private DataOutputStream mOutputStream; private boolean mAnswerWaiting; private final byte MODE_DEFAULT = 0; private final byte MODE_EDIT_CRIME = 1; private byte mMode = 0; private ArrayList<Crime> mCrimes; private Crime editingCrime; private ClientKeysUtils mClientKeys; ConnectionWorker(DataInputStream inStream, DataOutputStream outStream) { mInputStream = inStream; mOutputStream = outStream; mClientKeys = new ClientKeysUtils(); } @Override public void run() { sendCommand("HELLO"); while (true) { try { Thread.sleep(500); } catch (InterruptedException ignored) { } try { if (mInputStream.available() > 0) { proceedMessage(); } } catch (IOException e) { e.printStackTrace(); } } } private void proceedMessage() throws IOException { byte[] commandByte = new byte[6]; mInputStream.read(commandByte); commandByte = CriminalUtils.trimBytes(commandByte); String command = new String(commandByte, "UTF-8"); if (!Objects.equals(command, "PING")) { // System.out.println("Command REC: " + command); } try { proceedServerCommand(command); } catch (ClassNotFoundException e) { e.printStackTrace(); } } private void proceedServerCommand(String command) throws IOException, ClassNotFoundException { switch (command) { case "HELLOK": proceedKeysExchange(); break; case "HELLO": System.out.println("Server said that encryption is disabled"); readyToEnterCommand(); break; case "KTEST": checkTestKeys(); break; case "CRIMEN": getCrimesFromServer(false); break; case "CRIMES": getCrimesFromServer(true); break; case "CRIME": printCrime(); break; case "CSEND": mAnswerWaiting = false; break; case "SEND": mAnswerWaiting = false; break; case "PING": sendCommand("PONG"); break; } } private void checkTestKeys() throws IOException, ClassNotFoundException { byte[] lengthHeader = new byte[4]; mInputStream.read(lengthHeader); int dataSize = ByteBuffer.wrap(lengthHeader).getInt(); byte[] body = new byte[dataSize]; mInputStream.read(body); body = mClientKeys.decrypt(body); String message = (String) CriminalUtils.deserialize(body); if (message != null && Objects.equals(message, "SUCCESS")) { System.out.println("Keys test success. Encryption enabled!"); mClientKeys.setEnabled(true); } else { mClientKeys.setEnabled(false); System.out.println("Keys test failed. Encryption disabled."); sendCommand("ENCDIS"); } readyToEnterCommand(); } private void proceedKeysExchange() throws IOException, ClassNotFoundException { byte[] lengthHeader = new byte[4]; mInputStream.read(lengthHeader); int dataSize = ByteBuffer.wrap(lengthHeader).getInt(); byte[] body = new byte[dataSize]; mInputStream.read(body); PublicKey serverPublicKey = (PublicKey) CriminalUtils.deserialize(body); mClientKeys.setServerPublicKey(serverPublicKey); try { Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, mClientKeys.getServerPublicKey()); byte[] cipherData = cipher.doFinal(mClientKeys.getKey().getEncoded()); sendBytes("PKEY", cipherData); } catch (Exception e) { e.printStackTrace(); } } private void getCrimesFromServer(boolean show) throws IOException { mCrimes = new ArrayList<>(); byte[] commandByte = new byte[6]; mInputStream.read(commandByte); commandByte = CriminalUtils.trimBytes(commandByte); String message = new String(commandByte, "UTF-8"); while (!Objects.equals(message, "CSEND")) { printCrime(); commandByte = new byte[6]; mInputStream.read(commandByte); commandByte = CriminalUtils.trimBytes(commandByte); message = new String(commandByte, "UTF-8"); } if (mMode != MODE_EDIT_CRIME && show) { printAllCrimes(); readyToEnterCommand(); } mAnswerWaiting = false; } private void printCrime() throws IOException { Crime crime = CriminalUtils.readCrime(mInputStream, mClientKeys); if (crime != null) { mCrimes.add(crime); } } private void printAllCrimes() { System.out.println("~~~~~~~~~~~~~~CRIMES LIST~~~~~~~~~~~~~~"); System.out.println("#_|_______________________Id_______________________|_________Title________|____Date of crime_____"); mCrimes.forEach((crime) -> { String dateString = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(crime.getDate()); StringBuilder crimeString = new StringBuilder(); if (crime.needPolice()) { crimeString.append(ANSI_RED_BACKGROUND); } crimeString.append(mCrimes.indexOf(crime)).append(" | "); crimeString.append("CRIME ID: ").append(crime.getId().toString()).append(" | TITLE: ").append(crime.getTitle()).append(" | ").append(dateString); System.out.println(crimeString); }); System.out.println("~~~~~~~~~~~~~~END OF LIST~~~~~~~~~~~~~~"); } void proceedConsoleCommand(String command, String arguments) { if (mAnswerWaiting) { return; } if (mMode == MODE_EDIT_CRIME) { switch (command) { case "title": editTitle(arguments); break; case "time": editTime(arguments); break; case "solved": editSolved(arguments); break; case "police": editPolice(arguments); break; case "save": saveEditedCrime(); break; case "close": closeEditMode(); break; case "help": System.out.println("Editing crime commands:"); System.out.println("title [new title] - shows title or changes title to new"); System.out.println("time [timestamp] - shows time or sets time to timestamp"); System.out.println("solved [0-1] - shows solved state or sets it"); System.out.println("police [0-1] - shows police needing or sets it"); System.out.println("save - updates crime on server and closes editing mode"); System.out.println("close - discard changes and closes editing mode"); default: readyToEnterCommand(); } } else { switch (command) { case "shutdown": case "bye": sendCommand("BYE"); System.exit(0); break; case "create": createCrime(arguments); break; case "edit": startEditMode(arguments); break; case "delete": deleteCrime(arguments); break; case "crimes": System.out.println("Loading crimes..."); sendCommand("CRIMES"); mAnswerWaiting = true; break; case "help": System.out.println("Criminal client commands:"); System.out.println("crimes - get all crimes from server"); System.out.println("create [crime title] - creates new crime"); System.out.println("edit [crime #] - stars edit crime mode"); System.out.println("delete [crime #] - deletes crime"); System.out.println("bye - shutdown"); default: readyToEnterCommand(); } } } private void readyToEnterCommand() { if (mMode == MODE_DEFAULT) { System.out.print("Command: "); } else { System.out.print("> "); } } private void createCrime(String arguments) { if (Objects.equals(arguments, "")) { System.out.println("Please specify crime title"); readyToEnterCommand(); return; } Crime crime = new Crime(); crime.setTitle(arguments); sendCommand("ADD", crime); mAnswerWaiting = true; } private void deleteCrime(String arguments) { try { Integer crimeIndex = Integer.parseInt(arguments); Crime crime = mCrimes.get(crimeIndex); if (crime != null) { sendCommand("DELETE", crime); mAnswerWaiting = true; } } catch (NumberFormatException e) { System.out.println("Please specify crime id"); readyToEnterCommand(); } catch (IndexOutOfBoundsException e) { System.out.println("Crime not found, did you asked crimes from server?"); readyToEnterCommand(); } } // Edit mode private void startEditMode(String arguments) { try { Integer crimeIndex = Integer.parseInt(arguments); Crime crime = mCrimes.get(crimeIndex); if (crime != null) { mMode = MODE_EDIT_CRIME; System.out.println("Editing crime \"" + crime.getTitle() + "\"(#" + crimeIndex + ")"); System.out.println("Type \"help\" to get help"); editingCrime = new Crime(crime); readyToEnterCommand(); } } catch (NumberFormatException e) { System.out.println("Please specify crime id"); readyToEnterCommand(); } catch (IndexOutOfBoundsException e) { System.out.println("Crime not found, did you asked crimes from server?"); readyToEnterCommand(); } } private void saveEditedCrime() { sendCommand("UPDATE", editingCrime); System.out.println("Crime saved"); closeEditMode(); } private void closeEditMode() { mMode = MODE_DEFAULT; editingCrime = null; System.out.println("Editing crime mode closed"); readyToEnterCommand(); } private void editTitle(String arguments) { if (Objects.equals(arguments, "")) { System.out.println("Title: " + editingCrime.getTitle()); readyToEnterCommand(); } else { editingCrime.setTitle(arguments); System.out.println("Title set"); readyToEnterCommand(); } } private void editTime(String arguments) { if (Objects.equals(arguments, "")) { String dateString = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(editingCrime.getDate()); System.out.println("Date and time: " + dateString); readyToEnterCommand(); } else { try { Long crimeTimestamp = Long.parseLong(arguments); editingCrime.setDate(crimeTimestamp * 1000); System.out.println("Timestamp set"); readyToEnterCommand(); } catch (NumberFormatException e) { System.out.println("Wrong timestamp"); readyToEnterCommand(); } } } private void editSolved(String arguments) { if (Objects.equals(arguments, "")) { System.out.println("Solved: " + (editingCrime.isSolved() ? "true" : "false")); readyToEnterCommand(); } else { try { Byte solvedByte = Byte.parseByte(arguments); if (solvedByte != 0 && solvedByte != 1) { throw new NumberFormatException(); } editingCrime.setSolved(solvedByte == 1); System.out.println("Solved state set"); readyToEnterCommand(); } catch (NumberFormatException e) { System.out.println("Wrong solved state (must be either 0 or 1)"); readyToEnterCommand(); } } } private void editPolice(String arguments) { if (Objects.equals(arguments, "")) { System.out.println("Police needed: " + (editingCrime.needPolice() ? "true" : "false")); readyToEnterCommand(); } else { try { Byte policeByte = Byte.parseByte(arguments); if (policeByte != 0 && policeByte != 1) { throw new NumberFormatException(); } editingCrime.setPolice(policeByte == 1); System.out.println("Police needing state set"); readyToEnterCommand(); } catch (NumberFormatException e) { System.out.println("Wrong police needing state (must be either 0 or 1)"); readyToEnterCommand(); } } } // Send command private void sendCommand(String command) { final byte[] bodyBytes; try { bodyBytes = command.getBytes("UTF-8"); ByteBuffer headerBuffer = ByteBuffer.allocate(6).put(bodyBytes); byte[] message = headerBuffer.array(); mOutputStream.write(message); mOutputStream.flush(); } catch (Exception e) { e.printStackTrace(); } } private void sendCommand(String command, Crime crime) { sendCommand(command, (Object) crime); } private void sendCommand(String command, Object object) { try { byte[] crimeBytes = CriminalUtils.serialize(object); if (mClientKeys.isEnabled()) { sendBytes(command, mClientKeys.encrypt(crimeBytes)); } else { sendBytes(command, crimeBytes); } } catch (Exception e) { e.printStackTrace(); } } private void sendBytes(String command, byte[] bytes) { try { final byte[] bodyBytes = command.getBytes("UTF-8"); ByteBuffer headerBuffer = ByteBuffer.allocate(6).put(bodyBytes); headerBuffer.position(0); ByteBuffer lengthBuffer = ByteBuffer.allocate(4).putInt(bytes.length); lengthBuffer.position(0); byte[] header = headerBuffer.array(); byte[] message = ByteBuffer.allocate(10 + bytes.length).put(header).put(lengthBuffer.array()).put(bytes).array(); mOutputStream.write(message); mOutputStream.flush(); } catch (IOException e) { e.printStackTrace(); } } }
mit
AceSevenFive/projectm
src/main/java/com/siderislabs/projectmendeleev/objects/Element.java
3169
package com.siderislabs.projectmendeleev.objects; import com.siderislabs.projectmendeleev.functions.ElementFunctions; import com.siderislabs.projectmendeleev.items.ItemVial; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; public class Element { public String name; public Integer atomicNumber; public long atomicWeight; public String state; public long meltingPoint; public long boilingPoint; public long density; private int isUnsafe; public Element(String[] data) { if(data.length == 6) { this.name = data[0]; this.atomicNumber = Integer.valueOf(data[1]); this.atomicWeight = Long.valueOf(data[2]); this.state = data[3]; this.meltingPoint = Long.valueOf(data[4]); this.density = Long.valueOf(data[5]); } else { System.err.println("Error: A new element does not have the required parameters. Calls to this var are unsafe."); isUnsafe = 1; } } public String getName() { if (this.name != null) { return this.name; } else { System.err.println("Error: A getName() call was made to an unsafe element."); return "Void in a Vial"; } } public Integer getAtomicNumber() { if (this.atomicNumber > 0) { return this.atomicNumber; } else { System.err.println("Error: a getAtomicNumber() call was made to an unsafe element."); return 0; } } public Long getAtomicWeight() { if(this.atomicWeight >= 0) { return this.atomicWeight; } else { System.err.println("Error: a getAtomicWeight() call was made to an unsafe element."); return Long.valueOf(0); } } public String getState() { if(this.state != null) { return this.state; } else { System.err.println("Error: a getState() call was made to an unsafe element."); return "Unknown"; } } public Long getMeltingPoint() { if(this.meltingPoint >= 0) { return this.meltingPoint; } else { System.err.println("Error: a getMeltingPoint() call was made to an unsafe element."); return Long.valueOf(0); } } public Long getDensity() { if(this.density >= 0) { return this.density; } else { System.err.println("Error: a getDensity() call was made to an unsafe element."); return Long.valueOf(0); } } public ItemStack getElementInstance(Integer quantity) { Item Vial = new ItemVial(); NBTTagCompound tagCompound = new NBTTagCompound(); if(isUnsafe != 1) { tagCompound.setString("Element", this.name); tagCompound.setInteger("Atomic Number", this.atomicNumber); tagCompound.setLong("Atomic Weight", this.atomicWeight); tagCompound.setString("State", this.state); tagCompound.setLong("Melting Point", this.meltingPoint); tagCompound.setLong("Boiling Point", this.boilingPoint); tagCompound.setLong("Density", this.density); ItemStack result = new ItemStack(Vial, quantity); result.setTagCompound(tagCompound); return result; } else { System.err.println("Error: An attempt was made to generate an item using an invalid element."); return null; } } }
mit
iMartinezMateu/gamecraft
gamecraft-twitter-notification-manager/src/main/java/com/gamecraft/config/ApplicationProperties.java
442
package com.gamecraft.config; import org.springframework.boot.context.properties.ConfigurationProperties; /** * Properties specific to Gamecrafttwitternotificationmanager. * <p> * Properties are configured in the application.yml file. * See {@link io.github.jhipster.config.JHipsterProperties} for a good example. */ @ConfigurationProperties(prefix = "application", ignoreUnknownFields = false) public class ApplicationProperties { }
mit
MarsCapone/game-data-structures
Jenga/JengaTest.java
3274
/* * The MIT License (MIT) * * Copyright (c) 2015 Samson Danziger * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ import junit.framework.TestCase; import org.junit.Test; public class JengaTest extends TestCase { protected Jenga<Integer> jenga; protected boolean ex; @Override protected void setUp() { jenga = new Jenga<Integer>(); ex = false; } @Test public void testAddFirst() throws NonExistentBlockException { boolean oneAdd = jenga.add(1, 0); assertTrue("Adding the first element should succeed.", oneAdd); boolean secondAdd = jenga.add(2); assertTrue("Next element should be added in next available space.", secondAdd); } @Test public void testMultipleAdd() throws NonExistentBlockException { int blocksToAdd = 3 * Constants.LAYER_BLOCKS; for (int i = 0; i < blocksToAdd; i++) { jenga.add(i); } assertTrue(String.format("Adding %d blocks should create 3 layers, each with %d blocks.", blocksToAdd, Constants.LAYER_BLOCKS), jenga.height == 3); } @Test public void testNonExistentBlockException() { try { jenga.add(1, 4); } catch (NonExistentBlockException e) { ex = true; } assertTrue("Exception should be thrown when adding an element to the 5th space out of 3.", ex); } @Test public void testHandOfGodError() { boolean ex = false; try { jenga.destroy(); } catch (HandOfGodError e) { ex = true; } assertTrue("Error should be thrown when deliberately knocking down the tower.", ex); } @Test public void testLayoutCheck() throws NonExistentBlockException { for (int i = 0; i < 13; i++) { jenga.add(i); } int remainingBlocks = 13 % Constants.LAYER_BLOCKS; String[] layerLayouts = jenga.toString().split("\n"); StringBuilder sb = new StringBuilder(); for (int i = 0; i < remainingBlocks; i++) { sb.append('#'); } boolean check = layerLayouts[layerLayouts.length-1].substring(0, remainingBlocks).equals(sb.toString()); assertTrue(check); } }
mit
nullpointerexceptionapps/TeamCityDownloader
java/com/raidzero/teamcitydownloader/global/ThemeUtility.java
3257
package com.raidzero.teamcitydownloader.global; import android.app.AlertDialog; import android.content.Context; import android.content.SharedPreferences; import android.content.res.TypedArray; import android.graphics.drawable.Drawable; import android.preference.PreferenceManager; import android.util.TypedValue; import com.raidzero.teamcitydownloader.R; /** * Created by posborn on 6/27/14. */ public class ThemeUtility { private static final String tag = "ThemeUtility"; public static void setAppTheme(Context context) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); String themeName = prefs.getString("theme", ""); // if it doesnt exist in prefs, create it, as dark if (prefs.getString("theme", "").isEmpty()) { SharedPreferences.Editor editor = prefs.edit(); editor.putString("theme", "dark"); editor.apply(); themeName = "dark"; } if (themeName.equalsIgnoreCase("light")) { context.setTheme(R.style.Light); } else { context.setTheme(R.style.Dark); } } public static int getDialogActivityTheme(Context context) { SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); String themeName = prefs.getString("theme", ""); // if it doesnt exist in prefs, create it, as dark if (prefs.getString("theme", "").isEmpty()) { SharedPreferences.Editor editor = prefs.edit(); editor.putString("theme", "dark"); editor.apply(); themeName = "dark"; } if (themeName.equalsIgnoreCase("light")) { return R.style.LightDialogActivity; } else { return R.style.DarkDialogActivity; } } public static int getThemeId(Context context) { TypedValue outValue = new TypedValue(); context.getTheme().resolveAttribute(R.attr.themeName, outValue, true); if ("Dark".equals(outValue.string)) { return R.style.Dark; } else { return R.style.Light; } } public static int getHoloDialogTheme(Context context) { if (getThemeId(context) == R.style.Dark) { Debug.Log(tag, "returning dark theme"); return AlertDialog.THEME_HOLO_DARK; } else { Debug.Log(tag, "returning light theme"); return AlertDialog.THEME_HOLO_LIGHT; } } public static Drawable getThemedDrawable(Context context, int resId) { TypedArray a = context.getTheme().obtainStyledAttributes(getThemeId(context), new int[]{resId}); if (a != null) { int attributeResourceId = a.getResourceId(0, 0); return context.getResources().getDrawable(attributeResourceId); } return null; } public static int getThemedColor(Context context, int resId) { TypedArray a = context.getTheme().obtainStyledAttributes(getThemeId(context), new int[]{resId}); if (a != null) { int attributeResourceId = a.getResourceId(0, 0); return context.getResources().getColor(attributeResourceId); } return -1; } }
mit
afonsofernandes11/projeto-integrado-web-usjt
api/model/Fly.java
3085
package model; import java.util.Date; import java.util.ResourceBundle; public class Fly { private int code; private String source; private String destiny; private double value; private int qtdeScales; private String date; private Aircrafit aircrafit; private String situation; public Fly() { setCode( -1 ); setSource( "" ); setDestiny ( "" ); setQtdeScales( -1 ); setAircrafit( null ); setSituation( "" ); setValue( 0.00 ); } public void setValue( double value ) { this.value = value; } public void setCode( int code ) { this.code = code; } public void setSource( String source ) { this.source = source; } public double getValue () { return value; } public void setDestiny( String destiny ) { this.destiny = destiny; } public void setDateTime( String date ) { this.date = date; } public void setQtdeScales( int qtde ) { this.qtdeScales = qtde; } public void setAircrafit( Aircrafit aircrafit ) { this.aircrafit = aircrafit; } public void setSituation( String situation ) { this.situation = situation; } public int getCode() { return code; } public String getSource() { return source; } public String getDestiny() { return destiny; } public String getDateTime() { return date; } public String getFormatDate() { String oldDate = getDateTime(); String day = oldDate.substring(0,2); String months = oldDate.substring(3,5); String year = oldDate.substring(6, 10); String hour = oldDate.substring( 10, 16 ); return year + "/" + months + "/" + day + hour; } public void setFormatDate(String oldDate) { if( oldDate != null && oldDate.length() >= 15 ) { String year = oldDate.substring(0,4); String months = oldDate.substring(5,7); String day = oldDate.substring(8,10); String hour = oldDate.substring( 10, 16 ); setDateTime( day + "/" + months + "/" + year + hour); } } public int getQtdeScales() { return qtdeScales; } public Aircrafit getAircrafit() { return aircrafit; } public String getDescSituation( ResourceBundle lang ) { String Return; switch( getSituation() ) { default: return lang.getString("status.espera"); case "2" : return lang.getString( "status.cancelado"); case "3": return lang.getString( "status.atrasado" ); case "4": return lang.getString( "status.embarque" ); case "5": return lang.getString( "status.finalizado" ); case "1" : return lang.getString( "status.confirmado" ); } } public String getSituation() { return situation; } }
mit
KarboniteKream/scc
src/scc/imcode/ImcStmt.java
261
package scc.imcode; /** * Stavki vmesne kode. * * @author sliva */ public abstract class ImcStmt extends ImcCode { /** * Vrne linearizirano vmesno kodo stavka. * * @return linearizirana vmesna koda stavka. */ public abstract ImcSEQ linear(); }
mit
6ag/BaoKanAndroid
app/src/main/java/tv/baokan/baokanandroid/cache/NewsContentCache.java
742
package tv.baokan.baokanandroid.cache; import org.litepal.crud.DataSupport; /** * 新闻正文数据缓存 */ public class NewsContentCache extends DataSupport { // 文章id private String articleid; // 分类id private String classid; // json数据 private String news; public String getArticleid() { return articleid; } public void setArticleid(String articleid) { this.articleid = articleid; } public String getClassid() { return classid; } public void setClassid(String classid) { this.classid = classid; } public String getNews() { return news; } public void setNews(String news) { this.news = news; } }
mit
xgouchet/Editors
axel/src/main/java/fr/xgouchet/xmleditor/core/actions/ActionQueueExecutor.java
4710
package fr.xgouchet.xmleditor.core.actions; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; /** * The ActionQueueExecutor keeps a queue of actions and performs them one by one on a background thread. * Once the action is performed, it notifies the listener * * @author Xavier Gouchet */ public class ActionQueueExecutor { private static final int WHAT_ACTION_PERFORMED = 0xACED; private static final String TAG = ActionQueueExecutor.class.getSimpleName(); private final Executor mExecutor = Executors.newSingleThreadExecutor(new ThreadFactory() { @Override public Thread newThread(final @NonNull Runnable runnable) { return new Thread(runnable, "ActionQueueWorker"); } }); private final Handler mHandler; /** * Creates an instance, with all listener callback performed on the main thread */ public ActionQueueExecutor() { this(Looper.getMainLooper()); } /** * Creates an instance, with all listener callback performed on the given looper */ public ActionQueueExecutor(final @NonNull Looper looper) { mHandler = new AsyncActionHandler(looper); } /** * Adds an action to the queue to be performed in the background * * @param action the action to perform */ public <I, O> void queueAction(final @NonNull AsyncAction<I, O> action, final @Nullable I input, final @NonNull AsyncActionListener<O> listener) { Log.d(TAG, "Queue action " + action); mExecutor.execute(new AsyncActionRunnable<>(action, input, listener, mHandler)); } /** * A Runnable which performs the Action. * * @param <I> the input type * @param <O> the output type */ private static final class AsyncActionRunnable<I, O> implements Runnable { private final AsyncAction<I, O> mAction; private final Handler mHandler; private final I mInput; private final AsyncActionListener<O> mListener; private O mOutput; private Exception mException; private AsyncActionRunnable(final @NonNull AsyncAction<I, O> action, final @NonNull I input, final @NonNull AsyncActionListener<O> listener, final @NonNull Handler handler) { mAction = action; mInput = input; mListener = listener; mHandler = handler; } @Override public void run() { Log.d(TAG, "Perform action " + mAction); try { mOutput = mAction.performAction(mInput); Log.d(TAG, "Action successfull : " + mInput + " -> " + mOutput); } catch (Exception e) { mException = e; Log.w(TAG, "Action failed : " + mInput + " -> " + mException); } // notify target Log.d(TAG, "Notify handler"); Message msg = mHandler.obtainMessage(WHAT_ACTION_PERFORMED); msg.obj = this; msg.sendToTarget(); } /** * Notifies the listener of the success or failure of the operation */ void notifyListener() { Log.d(TAG, "notifyListener()"); if (mException == null) { mListener.onActionPerformed(mOutput); } else { mListener.onActionFailed(mException); } } } /** * The handler class to notify the listeners for each AsyncAction we treated */ private static class AsyncActionHandler extends Handler { /** * Creates an Handler living in the given Looper * * @param looper the looper to use (NonNull) */ public AsyncActionHandler(final @NonNull Looper looper) { super(looper); } @Override public void handleMessage(final @NonNull Message msg) { Log.d(TAG, "handleMessage(" + msg.what + ")"); switch (msg.what) { case WHAT_ACTION_PERFORMED: AsyncActionRunnable action = (AsyncActionRunnable) msg.obj; Log.d(TAG, "Notify listener for action " + action); action.notifyListener(); break; } } } }
mit
Peiffap/Project-Euler-solutions
src/p024.java
423
/** * https://projecteuler.net/problem=24 * * Validated. */ class p024 { public static void main(String[] args) { long s = System.nanoTime(); int[] nums = {0,1,2,3,4,5,6,7,8,9}; for (int i = 1; i < 1000000; i++) { Library.nextPermutation(nums); } Library.showVect(nums); long e = System.nanoTime(); System.out.println((e-s)/1000000000.0); } }
mit
martin-lizner/trezor-ssh-agent
src/main/java/com/trezoragent/utils/LocalizedLogger.java
1565
package com.trezoragent.utils; import java.io.IOException; import java.net.URISyntaxException; import java.util.Locale; import java.util.ResourceBundle; import java.util.logging.LogManager; /** * * @author martin.lizner */ public class LocalizedLogger { private static ResourceBundle messages; public static void setUpDefault() throws URISyntaxException, IOException { setupLoggerConfig(); setLoggerLanguage(AgentConstants.DEFAULT_LOGGER_LANGUAGE, AgentConstants.DEFAULT_LOGGER_COUNTRY); } private static void setupLoggerConfig() throws URISyntaxException, IOException { LogManager.getLogManager().readConfiguration(LocalizedLogger.class.getResourceAsStream("/" + AgentConstants.CONFIG_FILE_NAME)); } public static void setLoggerLanguage(String language, String country) { Locale currentLocale = new Locale(language, country); messages = ResourceBundle.getBundle(AgentConstants.LOCALE_BUNDLES_PATH, currentLocale); } public static String getLocalizedMessage(String key) { if (messages == null) { setLoggerLanguage(AgentConstants.DEFAULT_LOGGER_LANGUAGE, AgentConstants.DEFAULT_LOGGER_COUNTRY); } return messages.getString(key); } public static String getLocalizedMessage(String messageKey, Object... args) { if (messages == null) { setLoggerLanguage(AgentConstants.DEFAULT_LOGGER_LANGUAGE, AgentConstants.DEFAULT_LOGGER_COUNTRY); } return String.format(messages.getString(messageKey), args); } }
mit
vitrivr/cineast
cineast-core/src/main/java/org/vitrivr/cineast/core/util/LogHelper.java
535
package org.vitrivr.cineast.core.util; import java.io.PrintWriter; import java.io.StringWriter; import org.apache.logging.log4j.Marker; import org.apache.logging.log4j.MarkerManager; public class LogHelper { private LogHelper() { } public static final Marker SQL_MARKER = MarkerManager.getMarker("SQL"); public static String getStackTrace(Throwable e) { StringWriter sWriter = new StringWriter(); PrintWriter pWriter = new PrintWriter(sWriter); e.printStackTrace(pWriter); return sWriter.toString(); } }
mit
Codeforces/inmemo
src/test/java/com/codeforces/inmemo/model/Wrapper.java
178
package com.codeforces.inmemo.model; /** * @author MikeMirzayanov (mirzayanovmr@gmail.com) */ public class Wrapper { public static class a extends User { } }
mit
psjava/psjava
src/main/java/org/psjava/ds/AddToMapWithSameValue.java
253
package org.psjava.ds; import org.psjava.ds.map.MutableMap; public class AddToMapWithSameValue { public static <K, V> void add(MutableMap<K, V> map, Iterable<K> keys, V value) { for (K key : keys) map.add(key, value); } }
mit
doe300/jactiverecord
src/de/doe300/activerecord/dsl/functions/LowerCase.java
2316
/* * The MIC License (MIT) * * Copyright (c) 2015 doe300 * * 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 BUC NOC LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENC SHALL THE * AUTHORS OR COPYRIGHC HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACC, TORC OR OTHERWISE, ARISING FROM, * OUC OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package de.doe300.activerecord.dsl.functions; import de.doe300.activerecord.dsl.SQLFunction; import de.doe300.activerecord.dsl.ScalarFunction; import de.doe300.activerecord.jdbc.driver.JDBCDriver; import de.doe300.activerecord.record.ActiveRecord; import java.util.function.Function; import javax.annotation.Nonnull; /** * Returns the string in lower case * * @author daniel * * @param <T> the record-type * @since 0.6 * @see String#toLowerCase() */ public class LowerCase<T extends ActiveRecord> extends ScalarFunction<T, String, String> { /** * @param columnName the name of the string-type column * @param columnFunc the function to map the record to a string */ public LowerCase(@Nonnull final String columnName, @Nonnull final Function<T, String> columnFunc) { super(JDBCDriver.SCALAR_LOWER, columnName, columnFunc); } /** * @param sqlFunction the nested SQL-function */ public LowerCase(@Nonnull final SQLFunction<T, String> sqlFunction) { super(JDBCDriver.SCALAR_LOWER, sqlFunction); } @Override protected String applySQLFunction(final String columnValue) { return columnValue == null ? null : columnValue.toLowerCase(); } }
mit
SquidDev-CC/CCTweaks-Lua
src/main/java/org/squiddev/cctweaks/lua/lib/socket/ISocketListener.java
306
package org.squiddev.cctweaks.lua.lib.socket; public interface ISocketListener { /** * Fired when the socket is closed */ void onClosed(); /** * Fired when there is more data to read */ void onMessage(); /** * Fired when the connection is finished/ready */ void onConnectFinished(); }
mit
vitrivr/cineast
cineast-api/src/main/java/org/vitrivr/cineast/api/messages/result/DistinctElementsResult.java
1400
package org.vitrivr.cineast.api.messages.result; import com.fasterxml.jackson.annotation.JsonCreator; import java.util.List; import org.apache.commons.lang3.builder.ReflectionToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import org.vitrivr.cineast.api.rest.handlers.actions.bool.FindDistinctElementsByColumnPostHandler; /** * A {@link DistinctElementsResult} contains the response to a {@link FindDistinctElementsByColumnPostHandler} request. It contains a list of elements which can be considered as a set. */ public class DistinctElementsResult { /** * The query ID to which this distinct elements result belongs. */ public final String queryId; /** * List of distinct elements to be retrieved by a find distinct column request. */ public final List<String> distinctElements; /** * Constructor for the FeaturesTextCategoryQueryResult object. * * @param queryId String representing the ID of the query to which this part of the result message. * @param distinctElements List of Strings containing distinct elements. */ @JsonCreator public DistinctElementsResult(String queryId, List<String> distinctElements) { this.queryId = queryId; this.distinctElements = distinctElements; } @Override public String toString() { return ReflectionToStringBuilder.toString(this, ToStringStyle.JSON_STYLE); } }
mit
SpongePowered/repoindexer
src/main/java/org/spongepowered/repoindexer/Cmd.java
3943
/* * 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.repoindexer; import com.beust.jcommander.Parameter; /** * Created by progwml6 on 4/7/15. */ public class Cmd { private static Cmd instance; public static Cmd getInstance() { return instance; } static { instance = new Cmd(); } @Parameter(names = {"--user", "-u"}, description = "username") public String user = null; @Parameter(names = {"--pass", "-p"}, description = "pass") public String pass = null; @Parameter(names = {"--ftpurl", "-l"}, description = "ftpurl") public String url = null; @Parameter(names = {"--key", "-k"}, description = "s3 key") public String key = null; @Parameter(names = {"--secure-key", "-s"}, description = "s3 secure key") public String securekey = null; @Parameter(names = {"--bucket", "-t"}, description = "s3 bucket") public String bucket = null; @Parameter(names = {"--region", "-r"}, description = "s3 region") public String region = null; @Parameter(names = {"--localLocation","-o"}, description = "local location to copy index file to") public String localLoc = null; @Parameter(names = {"--ftpmode", "-f"}, description = "true = FTP false=sftp", arity = 1) public boolean ftpmode = true; @Parameter(names = {"--base", "-b"}, description = "base location to deploy in ftp/sftp repo") public String base = ""; @Parameter(names = {"--index", "-i"}, description = "location of index.mustache file") public String loc = "index.mustache"; @Parameter(names = {"--mavenrepo", "-m"}, description = "maven repo url") public String mavenrepo = "http://repo.spongepowered.org/maven/"; @Parameter(names = {"--additionalRepos"}, description = "additional maven repos to use for dependency resolution use ^ to seperate") public String additionalRepos = null; @Parameter(names = {"--excludes", "-x"}, description = "allows specifying certain artifacts that should be excluded from transitive resolution in the tool group:artifact seperated by ^") public String exclude = null; @Parameter(names = {"--coord", "-c"}, description = "maven coordinate in gradle format NO VERSION, classifier, or extension") public String mavencoord = "org.spongepowered:sponge"; @Parameter(names = {"--extra", "-e"}, description = " classifier^extension*after seperated by % use the text 'null' for null data, can add *VERSION to specify that something only exists after that version") public String extra = "sources^jar%javadoc^jar"; @Parameter(names = {"--deployFile", "-d"}, description = "change the filename to deploy to") public String deployFile = "index.html"; }
mit
rudky4/Expense-Manager
src/main/java/project/AccountManager.java
1164
package project; import java.util.List; /* * 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. */ /** * * @author marek */ public interface AccountManager { /** * function checks all parameters and create account * @param account */ public void createAccount(Account account); /** * function checks all parameter and updates account * @param account */ public void updateAccount(Account account); /** * function deletes account * @param id */ public void deleteAccount(Long id); /** * function finds accout by id * @param id * @return account */ public Account getAccountById(Long id); /** * function finds accout by name * @param name * @return account */ public Account getAccountByName(String name); /** * function finds all accounts * @return List of account */ public List<Account> findAllAccounts(); }
mit
dariver/jenkins
test/src/test/java/lib/form/PasswordTest.java
10809
/* * The MIT License * * Copyright (c) 2004-2010, InfraDNA, Inc. * * 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 lib.form; import com.gargoylesoftware.htmlunit.Page; import com.gargoylesoftware.htmlunit.html.HtmlInput; import com.gargoylesoftware.htmlunit.html.HtmlPage; import com.gargoylesoftware.htmlunit.html.HtmlPasswordInput; import hudson.cli.CopyJobCommand; import hudson.cli.GetJobCommand; import hudson.model.*; import hudson.util.FormValidation; import hudson.util.Secret; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.Arrays; import java.util.Collections; import java.util.Locale; import java.util.regex.Pattern; import jenkins.model.Jenkins; import org.acegisecurity.Authentication; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.not; import static org.hamcrest.core.Is.is; import static org.junit.Assert.*; import org.junit.Rule; import org.junit.Test; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.JenkinsRule; import org.jvnet.hudson.test.MockAuthorizationStrategy; import org.jvnet.hudson.test.TestExtension; import org.kohsuke.stapler.DataBoundConstructor; import org.kohsuke.stapler.QueryParameter; import org.kohsuke.stapler.Stapler; import org.kohsuke.stapler.StaplerRequest; public class PasswordTest { @Rule public JenkinsRule j = new JenkinsRule(); @Test public void secretNotPlainText() throws Exception { SecretNotPlainText.secret = Secret.fromString("secret"); HtmlPage p = j.createWebClient().goTo("secretNotPlainText"); String value = ((HtmlInput)p.getElementById("password")).getValueAttribute(); assertFalse("password shouldn't be plain text",value.equals("secret")); assertEquals("secret",Secret.fromString(value).getPlainText()); } @TestExtension("secretNotPlainText") public static class SecretNotPlainText implements RootAction { public static Secret secret; @Override public String getIconFileName() { return null; } @Override public String getDisplayName() { return null; } @Override public String getUrlName() { return "secretNotPlainText"; } } @Issue({"SECURITY-266", "SECURITY-304"}) @Test public void testExposedCiphertext() throws Exception { boolean saveEnabled = Item.EXTENDED_READ.getEnabled(); Item.EXTENDED_READ.setEnabled(true); try { //final String plain_regex_match = ".*\\{[A-Za-z0-9+/]+={0,2}}.*"; final String xml_regex_match = "\\{[A-Za-z0-9+/]+={0,2}}"; final Pattern xml_regex_pattern = Pattern.compile(xml_regex_match); final String staticTest = "\n\nvalue=\"{AQAAABAAAAAgXhXgopokysZkduhl+v1gm0UhUBBbjKDVpKz7bGk3mIO53cNTRdlu7LC4jZYEc+vF}\"\n"; //Just a quick verification on what could be on the page and that the regexp is correctly set up assertThat(xml_regex_pattern.matcher(staticTest).find(), is(true)); j.jenkins.setSecurityRealm(new JenkinsRule().createDummySecurityRealm()); j.jenkins.setAuthorizationStrategy(new MockAuthorizationStrategy(). grant(Jenkins.ADMINISTER).everywhere().to("admin"). grant(Jenkins.READ, Item.READ, Item.EXTENDED_READ, Item.CREATE // so we can show CopyJobCommand would barf; more realistic would be to grant it only in a subfolder ).everywhere().to("dev")); Secret s = Secret.fromString("s3cr3t"); //String sEnc = s.getEncryptedValue(); FreeStyleProject p = j.createFreeStyleProject("p"); p.setDisplayName("Unicode here ←"); p.setDescription("This+looks+like+Base64+but+is+not+a+secret"); p.addProperty(new VulnerableProperty(s)); User admin = User.getById("admin", true); User dev = User.getById("dev", true); JenkinsRule.WebClient wc = j.createWebClient(); // Control case: an administrator can read and write configuration freely. wc.withBasicApiToken(admin); HtmlPage configure = wc.getPage(p, "configure"); assertThat(xml_regex_pattern.matcher(configure.getWebResponse().getContentAsString()).find(), is(true)); j.submit(configure.getFormByName("config")); VulnerableProperty vp = p.getProperty(VulnerableProperty.class); assertNotNull(vp); assertEquals(s, vp.secret); Page configXml = wc.goTo(p.getUrl() + "config.xml", "application/xml"); String xmlAdmin = configXml.getWebResponse().getContentAsString(); assertThat(Pattern.compile("<secret>" + xml_regex_match + "</secret>").matcher(xmlAdmin).find(), is(true)); assertThat(xmlAdmin, containsString("<displayName>" + p.getDisplayName() + "</displayName>")); assertThat(xmlAdmin, containsString("<description>" + p.getDescription() + "</description>")); // CLICommandInvoker does not work here, as it sets up its own SecurityRealm + AuthorizationStrategy. GetJobCommand getJobCommand = new GetJobCommand(); Authentication adminAuth = User.get("admin").impersonate(); getJobCommand.setTransportAuth(adminAuth); ByteArrayOutputStream baos = new ByteArrayOutputStream(); String pName = p.getFullName(); getJobCommand.main(Collections.singletonList(pName), Locale.ENGLISH, System.in, new PrintStream(baos), System.err); assertEquals(xmlAdmin, baos.toString(configXml.getWebResponse().getContentCharset())); CopyJobCommand copyJobCommand = new CopyJobCommand(); copyJobCommand.setTransportAuth(adminAuth); String pAdminName = pName + "-admin"; assertEquals(0, copyJobCommand.main(Arrays.asList(pName, pAdminName), Locale.ENGLISH, System.in, System.out, System.err)); FreeStyleProject pAdmin = j.jenkins.getItemByFullName(pAdminName, FreeStyleProject.class); assertNotNull(pAdmin); pAdmin.setDisplayName(p.getDisplayName()); // counteract DisplayNameListener assertEquals(p.getConfigFile().asString(), pAdmin.getConfigFile().asString()); // Test case: another user with EXTENDED_READ but not CONFIGURE should not get access even to encrypted secrets. wc.withBasicApiToken(dev); configure = wc.getPage(p, "configure"); assertThat(xml_regex_pattern.matcher(configure.getWebResponse().getContentAsString()).find(), is(false)); configXml = wc.goTo(p.getUrl() + "config.xml", "application/xml"); String xmlDev = configXml.getWebResponse().getContentAsString(); assertThat(xml_regex_pattern.matcher(xmlDev).find(), is(false)); assertEquals(xmlAdmin.replaceAll(xml_regex_match, "********"), xmlDev); getJobCommand = new GetJobCommand(); Authentication devAuth = User.get("dev").impersonate(); getJobCommand.setTransportAuth(devAuth); baos = new ByteArrayOutputStream(); getJobCommand.main(Collections.singletonList(pName), Locale.ENGLISH, System.in, new PrintStream(baos), System.err); assertEquals(xmlDev, baos.toString(configXml.getWebResponse().getContentCharset())); copyJobCommand = new CopyJobCommand(); copyJobCommand.setTransportAuth(devAuth); String pDevName = pName + "-dev"; assertThat(copyJobCommand.main(Arrays.asList(pName, pDevName), Locale.ENGLISH, System.in, System.out, System.err), not(0)); assertNull(j.jenkins.getItemByFullName(pDevName, FreeStyleProject.class)); } finally { Item.EXTENDED_READ.setEnabled(saveEnabled); } } @Test @Issue("SECURITY-616") public void testCheckMethod() throws Exception { FreeStyleProject p = j.createFreeStyleProject("p"); p.addProperty(new VulnerableProperty(Secret.fromString(""))); HtmlPasswordInput field = j.createWebClient().getPage(p, "configure").getFormByName("config").getInputByName("_.secret"); while (VulnerableProperty.DescriptorImpl.incomingURL == null) { // waitForBackgroundJavaScript does not work well Thread.sleep(100); // form validation of saved value } VulnerableProperty.DescriptorImpl.incomingURL = null; String secret = "s3cr3t"; field.setText(secret); while (VulnerableProperty.DescriptorImpl.incomingURL == null) { Thread.sleep(100); // form validation of edited value } assertThat(VulnerableProperty.DescriptorImpl.incomingURL, not(containsString(secret))); assertEquals(secret, VulnerableProperty.DescriptorImpl.checkedSecret); } public static class VulnerableProperty extends JobProperty<FreeStyleProject> { public final Secret secret; @DataBoundConstructor public VulnerableProperty(Secret secret) { this.secret = secret; } @TestExtension public static class DescriptorImpl extends JobPropertyDescriptor { static String incomingURL; static String checkedSecret; public FormValidation doCheckSecret(@QueryParameter String value) { StaplerRequest req = Stapler.getCurrentRequest(); incomingURL = req.getRequestURIWithQueryString(); System.err.println("processing " + incomingURL + " via " + req.getMethod() + ": " + value); checkedSecret = value; return FormValidation.ok(); } } } }
mit
ComputerArchitectureGroupPWr/JGenerilo
src/main/java/edu/byu/ece/rapidSmith/util/DesignDiff.java
6421
/* * Copyright (c) 2010 Brigham Young University * * This file is part of the BYU RapidSmith Tools. * * BYU RapidSmith Tools is free software: you may redistribute it * and/or modify it under the terms of the GNU General Public License * as published by the Free Software Foundation, either version 2 of * the License, or (at your option) any later version. * * BYU RapidSmith Tools is distributed in the hope that it will be * useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * A copy of the GNU General Public License is included with the BYU * RapidSmith Tools. It can be found at doc/gpl2.txt. You may also * get a copy of the license at <http://www.gnu.org/licenses/>. * */ package edu.byu.ece.rapidSmith.util; import edu.byu.ece.rapidSmith.design.Attribute; import edu.byu.ece.rapidSmith.design.Design; import java.util.ArrayList; import java.util.Arrays; public class DesignDiff { private boolean identical = true; public void printDifference(String name, String design1, String design2) { System.out.println(name + " = "); System.out.println(" Design 1: <" + design1 + ">"); System.out.println(" Design 2: <" + design2 + ">"); identical = false; } public boolean compareAttributes(ArrayList<Attribute> a1, ArrayList<Attribute> a2, String verbose) { if (a1 == null && a2 == null) { return true; } else if (a1 == null) { if (verbose != null) { printDifference("Attributes in " + verbose + " don't match", "null", "non-null"); } return false; } else if (a2 == null) { if (verbose != null) { printDifference("Attributes in " + verbose + " don't match", "non-null", "null"); } } else if (a1.size() == 0 && a2.size() == 0) { return true; } else if (a1.size() != a2.size()) { if (verbose != null) printDifference("Number of Attributes in " + verbose + "differ", Integer.toString(a1.size()), Integer.toString(a2.size())); return false; } String[] a1Strings = new String[a1.size()]; String[] a2Strings = new String[a2.size()]; for (int i = 0; i < a1Strings.length; i++) { a1Strings[i] = a1.get(i).toString(); a2Strings[i] = a2.get(i).toString(); } Arrays.sort(a1Strings); Arrays.sort(a2Strings); for (int i = 0; i < a1Strings.length; i++) { if (!a1Strings[i].equals(a2Strings[i])) { if (verbose != null) printDifference("Attributes in " + verbose + " differ", a1Strings[i], a2Strings[i]); return false; } } return true; } /** * This method will compare two designs and optionally print the differences found. Unless * the parameter verbose is specified, the method will return at the first sign of a difference. * * @param design1 First design to compare. * @param design2 Second design to compare. * @param verbose A flag which indicates to print all differences found between the two designs * @return True if the designs are identical, false otherwise. */ public boolean compareDesigns(Design design1, Design design2, boolean verbose) { // Compare Design elements if (!design1.getName().equals(design2.getName())) { if (verbose) printDifference("Design Name", design1.getName(), design2.getName()); else return false; } if (!design1.getPartName().equals(design2.getPartName())) { if (verbose) printDifference("Part Name", design1.getPartName(), design2.getPartName()); else return false; } if (!design1.getNCDVersion().equals(design2.getNCDVersion())) { if (verbose) printDifference("NCD Version", design1.getNCDVersion(), design2.getNCDVersion()); else return false; } if (design1.isHardMacro() != design2.isHardMacro()) { if (verbose) printDifference("Is Hard Macro?", Boolean.toString(design1.isHardMacro()), Boolean.toString(design2.isHardMacro())); else return false; } // Compare Counts of Design Objects if (design1.getInstances().size() != design2.getInstances().size()) { if (verbose) printDifference("Design Instance Count", Integer.toString(design1.getInstances().size()), Integer.toString(design2.getInstances().size())); else return false; } if (design1.getNets().size() != design2.getNets().size()) { if (verbose) printDifference("Design Net Count", Integer.toString(design1.getNets().size()), Integer.toString(design2.getNets().size())); else return false; } if (design1.getModules().size() != design2.getModules().size()) { if (verbose) printDifference("Design Module Count", Integer.toString(design1.getModules().size()), Integer.toString(design2.getModules().size())); else return false; } if (design1.getModuleInstances().size() != design2.getModuleInstances().size()) { if (verbose) printDifference("Design ModuleInstance Count", Integer.toString(design1.getModuleInstances().size()), Integer.toString(design2.getModuleInstances().size())); else return false; } // Compare Individual Elements in Design // Attributes if (!compareAttributes(design1.getAttributes(), design2.getAttributes(), "Design Attributes")) { identical = false; } // TODO - Finish this later return identical; } public static void main(String[] args) { if (args.length != 2) { MessageGenerator.briefMessageAndExit("USAGE: <design1.xdl> <design2.xdl>"); } Design design1 = new Design(); Design design2 = new Design(); design1.loadXDLFile(args[0]); design2.loadXDLFile(args[1]); DesignDiff dd = new DesignDiff(); dd.compareDesigns(design1, design2, true); } }
mit
sebastienhouzet/nabaztag-source-code
server/OS/net/violet/platform/api/exceptions/InvalidNotificationException.java
235
package net.violet.platform.api.exceptions; public class InvalidNotificationException extends APIException { public InvalidNotificationException() { super(ErrorCode.InvalidNotification, APIErrorMessage.INVALID_NOTIFICATION); } }
mit
lakb248/LeetCodeByJava
src/StringToInteger.java
942
package solution; public class StringToInteger { public static void main(String[] args){ StringToInteger switcher = new StringToInteger() ; System.out.println(switcher.atoi(" 2147483648qwqqw")); } public int atoi(String str) { int length = str.length() ; if(length == 0) return 0 ; int base = 0 , sign = 1; int i = 0 ; while(str.charAt(i) == ' ') i ++ ; if(str.charAt(i) == '-'){ sign = -1 ; i ++ ; }else if(str.charAt(i) == '+'){ sign = 1 ; i ++ ; } while(i < length && str.charAt(i) <= '9' && str.charAt(i) >= '0'){ if(base > Integer.MAX_VALUE/10 || ((base == Integer.MAX_VALUE/10) && str.charAt(i) > '7')){ if(sign == 1) return Integer.MAX_VALUE ; else return Integer.MIN_VALUE ; } base = 10*base + (str.charAt(i++) - '0') ; } return base*sign ; } }
mit
heivsene/pessoal
HackerRank/src/easy/ModifiedKaprekarNumbers.java
1426
package easy; import java.util.Scanner; /** * https://www.hackerrank.com/challenges/kaprekar-numbers * @author G0012477 * Problem: Modified Kaprekar Numbers * cd C:\workspace\HackerRank\bin\ * java easy.ModifiedKaprekarNumbers < ../resource/ModifiedKaprekarNumbers.in * */ public class ModifiedKaprekarNumbers { public static void main(String[] args) { Scanner in = new Scanner(System.in); int p = in.nextInt(); int q = in.nextInt(); int sumSqrt; long sqrt = 0; StringBuilder sb = new StringBuilder(); String number; // if ( p == 1) { // sb.append("1 "); // p = 2; // } for ( int i = p ; i <= q ; i++ ){ sqrt = (long)i*(long)i; number = Long.toString(sqrt); sumSqrt = findSumHalf(number); if ( i == sumSqrt ){ sb.append(i+" "); } } if ( sb.length() > 0 ){ System.out.println(sb.toString().trim()); } else { System.out.println("INVALID RANGE"); } in.close(); } private static int findSumHalf(String number) { System.out.println(number); int tamanho = number.length(); if ( tamanho%2 != 0 ){ tamanho++; number = "0"+number; } int l_half = (tamanho>>1); int r_half = (tamanho-l_half); r_half = Integer.parseInt(number.substring(r_half)); l_half = Integer.parseInt(number.substring(0, l_half)); return r_half+l_half; } }
mit
TitaniumSapphire/JNetwork
src/example/JLSTNetworkFactory.java
1045
package example; import java.io.IOException; import java.net.UnknownHostException; import org.jnetwork.ClientConnectionCallback; import org.jnetwork.Connection; import org.jnetwork.CryptographyException; import org.jnetwork.NetworkFactory; import org.jnetwork.Server; import org.jnetwork.ServerException; import org.jnetwork.TCPConnectionCallback; /** * A factory for creating JLST sockets. * * @author Lucas Baizer */ public class JLSTNetworkFactory extends NetworkFactory { JLSTNetworkFactory() { } @Override public Connection createConnection(String host, int port) throws UnknownHostException, IOException { try { return new JLSTConnection(host, port); } catch (CryptographyException e) { throw new IOException(e); } } @Override public Server createServer(int port, ClientConnectionCallback l) throws ServerException { try { return new JLSTServer(port, (TCPConnectionCallback) l, null); } catch (CryptographyException e) { throw new ServerException(e); } } }
mit
jamesET/does-world-tour-server
src/main/java/com/justjames/beertour/ISpecification.java
112
package com.justjames.beertour; public interface ISpecification<M> { boolean IsSatisfiedBy(M candidate); }
mit
cleviojr/Akane
src/main/java/akane/command/commands/music/LCommand.java
1608
package akane.command.commands.music; import java.util.concurrent.TimeUnit; import akane.command.core.CommandInterface; import net.dv8tion.jda.core.entities.ChannelType; import net.dv8tion.jda.core.entities.MessageChannel; import net.dv8tion.jda.core.events.message.MessageReceivedEvent; public class LCommand implements CommandInterface { private String channelName; @Override public boolean isSafe(String[] args, MessageReceivedEvent event) { if (!event.isFromType(ChannelType.TEXT)) { notifyServerCommand(event.getChannel()); return false; } if (!event.getGuild().getAudioManager().isConnected()) { event.getTextChannel().sendMessage(":no_entry: O bot não está em um canal de voz.").queue(); return false; } return true; } @Override public void main(String[] args, MessageReceivedEvent event) { event.getTextChannel().sendMessage("Procurando o canal que estou...").queue((message) -> { channelName = message.getMember().getVoiceState().getChannel().getName(); message.delete().queueAfter(500, TimeUnit.MILLISECONDS); }); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } event.getGuild().getAudioManager().closeAudioConnection(); event.getTextChannel().sendMessage(":notes: Saí do canal de voz: #" + channelName + ".").queue(); try { event.getMessage().delete().queueAfter(5, TimeUnit.SECONDS); } catch (Exception ignored) { } } private void notifyServerCommand(MessageChannel channel) { channel.sendMessage(":no_entry: Só uso esse comando em servidores e não no privado.").queue(); } }
mit
openengsb-attic/forks-org.odlabs.wiquery
src/main/java/org/odlabs/wiquery/ui/themes/UiIcon.java
7305
package org.odlabs.wiquery.ui.themes; /** * Enumeration of all possible icons from the jQuery UI theme * * All possible icons are displayed here : http://jqueryui.com/themeroller/#themeGallery * * @author Julien roche * @author Ernesto Reinaldo * */ public enum UiIcon { CARAT_1_NORTH ("carat-1-n"), CARAT_1_NORTH_EAST ("carat-1-ne"), CARAT_1_EAST ("carat-1-e"), CARAT_1_SOUTH_EAST ("carat-1-se"), CARAT_1_SOUTH ("carat-1-s"), CARAT_1_SOUTH_WEST ("carat-1-sw"), CARAT_1_WEST ("carat-1-w"), CARAT_1_NORTH_WEST ("carat-1-nw"), CARAT_2_NORTH_SOUTH ("carat-2-n-s"), CARAT_2_EAST_WEST ("carat-2-e-w"), TRIANGLE_1_NORTH ("carat-1-n"), TRIANGLE_1_NORTH_EAST ("triangle-1-ne"), TRIANGLE_1_EAST ("triangle-1-e"), TRIANGLE_1_SOUTH_EAST ("triangle-1-se"), TRIANGLE_1_SOUTH ("triangle-1-s"), TRIANGLE_1_SOUTH_WEST ("triangle-1-sw"), TRIANGLE_1_WEST ("triangle-1-w"), TRIANGLE_1_NORTH_WEST ("triangle-1-nw"), TRIANGLE_2_NORTH_SOUTH ("triangle-2-n-s"), TRIANGLE_2_EAST_WEST ("triangle-2-e-w"), ARROW_1_NORTH ("arrow-1-n"), ARROW_1_NORTH_EAST ("arrow-1-ne"), ARROW_1_EAST ("arrow-1-e"), ARROW_1_SOUTH_EAST ("arrow-1-se"), ARROW_1_SOUTH ("arrow-1-s"), ARROW_1_SOUTH_WEST ("arrow-1-sw"), ARROW_1_WEST ("arrow-1-w"), ARROW_1_NORTH_WEST ("arrow-1-nw"), ARROW_2_NORTH_SOUTH ("arrow-2-n-s"), ARROW_2_NORTH_EAST_SOUTH_WEST ("arrow-2-ne-sw"), ARROW_2_EAST_WEST ("arrow-2-e-w"), ARROW_2_SOUTH_EAST_NORTH_WEST ("arrow-2-se-nw"), ARROWSTOP_1_NORTH ("arrowstop-1-n"), ARROWSTOP_1_EAST ("arrowstop-1-e"), ARROWSTOP_1_SOUTH ("arrowstop-1-s"), ARROWSTOP_1_WEST ("arrowstop-1-w"), ARROWTHICK_1_NORTH ("arrowthick-1-n"), ARROWTHICK_1_NORTH_EAST ("arrowthick-1-ne"), ARROWTHICK_1_EAST ("arrowthick-1-e"), ARROWTHICK_1_SOUTH_EAST ("arrowthick-1-se"), ARROWTHICK_1_SOUTH ("arrowthick-1-s"), ARROWTHICK_1_SOUTH_WEST ("arrowthick-1-sw"), ARROWTHICK_1_WEST ("arrowthick-1-w"), ARROWTHICK_1_NORTH_WEST ("arrowthick-1-nw"), ARROWTHICK_2_NORTH_SOUTH ("arrowthick-2-n-s"), ARROWTHICK_2_NORTH_EAST_SOUTH_WEST ("arrowthick-2-ne-sw"), ARROWTHICK_2_EAST_WEST ("arrowthick-2-e-w"), ARROWTHICK_2_SOUTH_EAST_NORTH_WEST ("arrowthick-2-se-nw"), ARROWTHICKSTOP_1_NORTH ("arrowthickstop-1-n"), ARROWTHICKSTOP_1_EAST ("arrowthickstop-1-e"), ARROWTHICKSTOP_1_SOUTH ("arrowthickstop-1-s"), ARROWTHICKSTOP_1_WEST ("arrowthickstop-1-w"), ARROWRETURNTHICK_1_NORTH ("arrowreturnthick-1-n"), ARROWRETURNTHICK_1_EAST ("arrowreturnthick-1-e"), ARROWRETURNTHICK_1_SOUTH ("arrowreturnthick-1-s"), ARROWRETURNTHICK_1_WEST ("arrowreturnthick-1-w"), ARROWRETURN_1_NORTH ("arrowreturn-1-n"), ARROWRETURN_1_EAST ("arrowreturn-1-e"), ARROWRETURN_1_SOUTH ("arrowreturn-1-s"), ARROWRETURN_1_WEST ("arrowreturn-1-w"), ARROWREFRESH_1_NORTH ("arrowrefresh-1-n"), ARROWREFRESH_1_EAST ("arrowrefresh-1-e"), ARROWREFRESH_1_SOUTH ("arrowrefresh-1-s"), ARROWREFRESH_1_WEST ("arrowrefresh-1-w"), ARROW_4 ("arrow-4"), ARROW_4_DIAG ("arrow-4-diag"), EXTLINK ("extlink"), NEWWIN ("newwin"), REFRESH ("refresh"), SHUFFLE ("shuffle"), TRANSFER_E_W ("transfer-e-w"), TRANSFERTHICK_E_W ("transferthick-e-w"), FOLDER_COLLAPSED ("folder-collapsed"), FOLDER_OPEN ("folder-open"), DOCUMENT ("document"), DOCUMENT_B ("document-b"), NOTE ("note"), MAIL_CLOSED ("mail-closed"), MAIL_OPEN ("mail-open"), SUITCASE ("suitcase"), COMMENT ("comment"), PERSON ("person"), PRINT ("print"), TRASH ("trash"), LOCKED ("locked"), UNLOCKED ("unlocked"), BOOKMARK ("bookmark"), TAG ("tag"), HOME ("home"), FLAG ("flag"), CALENDAR ("calendar"), CART ("cart"), PENCIL ("pencil"), CLOCK ("clock"), DISK ("disk"), CALCULATOR ("calculator"), ZOOMIN ("zoomin"), ZOOMOUT ("zoomout"), SEARCH ("search"), WRENCH ("wrench"), GEAR ("gear"), HEART ("heart"), STAR ("star"), LINK ("link"), CANCEL ("cancel"), PLUS ("plus"), PLUSTHICK ("plusthick"), MINUS ("minus"), MINUSTHICK ("minusthick"), CLOSE ("close"), CLOSETHICK ("closethick"), KEY ("key"), LIGHTBULB ("lightbulb"), SCISSORS ("scissors"), CLIPBOARD ("clipboard"), COPY ("copy"), CONTACT ("contact"), IMAGE ("image"), VIDEO ("video"), SCRIPT ("script"), ALERT ("alert"), NOTICE ("notice"), HELP ("help"), CHECK ("check"), BULLET ("bullet"), RADIO_OFF ("radio-off"), RADIO_ON ("radio-on"), PIN_WEST ("pin-w"), PIN_SOUTH ("pin-s"), PLAY ("play"), PAUSE ("pause"), SEEK_NEXT ("seek-next"), SEEK_PREV ("seek-prev"), SEEK_END ("seek-end"), SEEK_FIRST ("seek-first"), STOP ("stop"), EJECT ("eject"), VOLUME_OFF ("volume-off"), VOLUME_ON ("volume-on"), POWER ("power"), SIGNAL_DIAG ("signal-diag"), SIGNAL ("signal"), BATTERY_0 ("battery-0"), BATTERY_1 ("battery-1"), BATTERY_2 ("battery-2"), BATTERY_3 ("battery-3"), CIRCLE_PLUS ("circle-plus"), CIRCLE_MINUS ("circle-minus"), CIRCLE_CLOSE ("circle-close"), CIRCLE_ZOOMIN ("circle-zoomin"), CIRCLE_ZOOMOUT ("circle-zoomout"), CIRCLE_CHECK ("circle-check"), CIRCLE_TRIANGLE_NORTH ("circle-triangle-n"), CIRCLE_TRIANGLE_EAST ("circle-triangle-e"), CIRCLE_TRIANGLE_SOUTH ("circle-triangle-s"), CIRCLE_TRIANGLE_WEST ("circle-triangle-w"), CIRCLE_ARROW_NORTH ("circle-arrow-n"), CIRCLE_ARROW_EAST ("circle-arrow-e"), CIRCLE_ARROW_SOUTH ("circle-arrow-s"), CIRCLE_ARROW_WEST ("circle-arrow-w"), CIRCLESMALL_PLUS ("circlesmall-plus"), CIRCLESMALL_MINUS ("circlesmall-minus"), CIRCLESMALL_CLOSE ("circlesmall-close"), SQUARESMALL_PLUS ("squaresmall-plus"), SQUARESMALL_MINUS ("squaresmall-minus"), SQUARESMALL_CLOSE ("squaresmall-close"), GRIP_DOTTED_VERTICAL ("grip-dotted-vertical"), GRIP_DOTTED_HORIZONTAL ("grip-dotted-horizontal"), GRIP_SOLID_VERTICAL ("grip-solid-vertical"), GRIP_SOLID_HORIZONTAL ("grip-solid-horizontal"), GRIPSMALL_DIAGONAL_SE ("gripsmall-diagonal-se"), GRIP_DIAGONAL_SE ("grip-diagonal-se"), INFO ("info"); //-------- // Properties private String cssClass; /** * Constructor * @param cssClass Associated CSS class */ UiIcon(String cssClass){ this.cssClass = cssClass; } /** * @return the associated CSS class */ public String getCssClass() { return "ui-icon-" + cssClass; } }
mit
ammaraskar/KittehIRCClientLib
src/main/java/org/kitteh/irc/client/library/CTCPUtil.java
6933
/* * * Copyright (C) 2013-2015 Matt Baxter http://kitteh.org * * 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.kitteh.irc.client.library; import javax.annotation.Nonnull; import java.util.regex.Matcher; import java.util.regex.Pattern; /* * A note on CTCP handling: * According to the original 'documentation' on the matter, * there can be multiple CTCP messages as well as normal messages * spread throughout. However, from what I can tell, most folks * don't bother with that in their implementations. So, we're * going to stick with having a single CTCP message at the start * of a message. * * CTCP is magic! * * Messages are defined as being between two \u0001 characters. * * The following characters are escaped by the MQUOTE character: \u0016 * \n -> MQUOTE n * \r -> MQUOTE r * \u0000 -> MQUOTE 0 * MQUOTE -> MQUOTE MQUOTE * When converting, anything else escaped with the MQUOTE should just strip the MQUOTE * * The following characters are escaped by a backslash * \u0001 -> \a * \ -> \\ * When converting, anything else escaped with a backslash should just strip the backslash */ /** * A utility class for CTCP handling. * <p> * Stored in this package so it can be package private to avoid confusion. * This stuff is all handled internally by the client; no client user needs * to know how to do this. */ final class CTCPUtil { private static final char CTCP_DELIMITER = '\u0001'; private static final char CTCP_MQUOTE = '\u0016'; private static final Pattern CTCP_ESCAPABLE_CHAR = Pattern.compile("[\n\r\u0000" + CTCP_DELIMITER + CTCP_MQUOTE + "\\\\]"); private static final Pattern CTCP_ESCAPED_CHAR = Pattern.compile("([" + CTCP_MQUOTE + "\\\\])(.)"); private static final Pattern CTCP_MESSAGE = Pattern.compile(CTCP_DELIMITER + "([^" + CTCP_DELIMITER + "]*)" + CTCP_DELIMITER + "[^" + CTCP_DELIMITER + "]*"); private CTCPUtil() { } /** * Converts a given message from CTCP escaping. * * @param message message to convert * @return converted message */ @Nonnull static String fromCTCP(@Nonnull String message) { message = message.substring(1); // Strip the starting delimiter message = message.substring(0, message.indexOf(CTCP_DELIMITER)); // Strip the second delimiter StringBuilder builder = new StringBuilder(message.length()); int currentIndex = 0; Matcher matcher = CTCP_ESCAPED_CHAR.matcher(message); while (matcher.find()) { if (matcher.start() > currentIndex) { builder.append(message.substring(currentIndex, matcher.start())); } switch (matcher.group(1)) { case CTCP_MQUOTE + "": switch (matcher.group(2)) { case "n": builder.append('\n'); break; case "r": builder.append('\r'); break; case "0": builder.append('\u0000'); break; default: builder.append(matcher.group(2)); // If not one of the above, disregard the MQUOTE. If MQUOTE, it's covered here anyway. } break; case "\\": switch (matcher.group(2)) { case "a": builder.append(CTCP_DELIMITER); break; default: builder.append(matcher.group(2)); // If not one of the above, disregard the \. If \, it's covered here anyway. } } currentIndex = matcher.end(); } if (currentIndex < message.length()) { builder.append(message.substring(currentIndex)); } return builder.toString(); } /** * Gets if a given message is a CTCP message. * * @param message message to test * @return true if the message is a CTCP message */ static boolean isCTCP(@Nonnull String message) { return CTCP_MESSAGE.matcher(message).matches(); } /** * Converts a given message to CTCP formatting. * * @param message message to convert * @return converted message */ @Nonnull static String toCTCP(@Nonnull String message) { StringBuilder builder = new StringBuilder(message.length()); builder.append(CTCP_DELIMITER); int currentIndex = 0; Matcher matcher = CTCP_ESCAPABLE_CHAR.matcher(message); while (matcher.find()) { if (matcher.start() > currentIndex) { builder.append(message.substring(currentIndex, matcher.start())); } switch (matcher.group()) { case "\n": builder.append(CTCP_MQUOTE).append('n'); break; case "\r": builder.append(CTCP_MQUOTE).append('r'); break; case "\u0000": builder.append(CTCP_MQUOTE).append('0'); break; case CTCP_MQUOTE + "": builder.append(CTCP_MQUOTE).append(CTCP_MQUOTE); break; case CTCP_DELIMITER + "": builder.append("\\a"); break; case "\\": builder.append("\\\\"); break; } currentIndex = matcher.end(); } if (currentIndex < message.length()) { builder.append(message.substring(currentIndex)); } builder.append(CTCP_DELIMITER); return builder.toString(); } }
mit
yugandar/javatask
30jun/block3.java
131
class block3{ static{ main(null); } public static void main(String []args){ System.out.println("main method"); } }
mit
cohadar/gcj-practice
2015/DCJ/sandwich/Input4.java
241
// Sample input 4, in Java. | 2499999 public class sandwich { public sandwich() { } public static long GetN() { return (long)5e6; } public static long GetTaste(long index) { return (index % 2 == 0) ? index : -index; } }
mit
yejingfu/im
im_server/java/src/main/java/com/mogujie/ares/manager/CacheManager.java
3805
package com.mogujie.ares.manager; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import java.util.concurrent.ConcurrentHashMap; import com.mogujie.ares.lib.storage.CachePool; import redis.clients.jedis.Jedis; /** * * @Description: 缓存连接相关的管理类,针对不同业务会有多个连接池,单例 * @author shitou - shitou[at]mogujie.com * @date 2013-7-21 下午5:45:18 * */ public class CacheManager { private ConcurrentHashMap<String, CachePool> cachePool = new ConcurrentHashMap<String, CachePool>(); // 多个池子 private static CacheManager cacheManagerInstance = new CacheManager(); private Properties cacheProperties; private boolean isLanuch = false; public static CacheManager getInstance() { if(cacheManagerInstance == null) { cacheManagerInstance = new CacheManager(); } return cacheManagerInstance; } private CacheManager() { this.cacheProperties = ConfigureManager.getInstance().getCacheConfig(); launch(); } /** * @Description: 初始化 */ private void launch() { if( ! isLanuch) { //shutDown(); String needLaunchPoolInstance = cacheProperties.getProperty("instances"); String[] needLaunchPools = needLaunchPoolInstance.split(","); for(String instance : needLaunchPools) { //获取配置 String redisHost = cacheProperties.getProperty(instance + "_host"); Integer redisPort = Integer.valueOf(cacheProperties.getProperty(instance + "_port")); Integer redisDB = Integer.valueOf(cacheProperties.getProperty(instance + "_db")); //实例化,启动,并塞入Hashmap中 CachePool cachePoolInstance = new CachePool(redisHost, redisPort, redisDB); cachePoolInstance.launch(); cachePool.put(instance, cachePoolInstance); } isLanuch = true; } } /** * @Description: 关闭所有连接池 */ public void shutDown() { if(this.cachePool.size() > 0) { Iterator<Entry<String, CachePool>> iterator = this.cachePool.entrySet().iterator(); while(iterator.hasNext()) { Map.Entry<String, CachePool> hashEntry = iterator.next(); CachePool poolInstance = hashEntry.getValue(); poolInstance.destory(); cachePool.remove(hashEntry.getKey()); } cachePool.clear(); } } /** * @Description: 从指定的链接池中获取一个链接 * @param poolName 连接池的名字 * @return */ public Jedis getResource(CachePoolName poolName) { String strName = poolName.toString(); return getJedisResource(strName); } /** * @Description: 释放一个链接 * @param poolName 连接所在的连接池 * @param jedis 连接 */ public void returnResource(CachePoolName poolName, Jedis jedis) { if(jedis == null) { return ; } String strName = poolName.toString(); returnJedisResource(strName, jedis); } /** * * @Description: 具体释放连接操作 * @param poolName * @param jedisInstance */ private void returnJedisResource(String poolName, Jedis jedisInstance) { CachePool pool = cachePool.get(poolName); if(pool != null) { pool.returnResource(jedisInstance); } } /** * * @Description: 具体获取连接操作 * @param instanceName * @return */ private Jedis getJedisResource(String instanceName) { Jedis jedisResource = null; CachePool pool = cachePool.get(instanceName); if(pool != null) { jedisResource = pool.getResource(); } return jedisResource; } /** * * @Description: 连接池的名字 * @author ziye - ziye[at]mogujie.com * @date 2013-7-21 下午6:37:06 * */ public enum CachePoolName { counter, // 所有计数器 unread, // 未读计数器 // cinfo, //用户信息(消息通知用的). // cinfo_push, // 推送cinfo group_counter } }
mit
flesire/ontrack
ontrack-ui/src/main/java/net/nemerosa/ontrack/boot/ui/UserController.java
7109
package net.nemerosa.ontrack.boot.ui; import net.nemerosa.ontrack.extension.api.ExtensionManager; import net.nemerosa.ontrack.extension.api.UserMenuExtension; import net.nemerosa.ontrack.model.Ack; import net.nemerosa.ontrack.model.form.Form; import net.nemerosa.ontrack.model.form.Password; import net.nemerosa.ontrack.model.form.YesNo; import net.nemerosa.ontrack.model.labels.LabelManagement; import net.nemerosa.ontrack.model.security.*; import net.nemerosa.ontrack.model.support.Action; import net.nemerosa.ontrack.model.support.PasswordChange; import net.nemerosa.ontrack.ui.controller.AbstractResourceController; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.security.access.AccessDeniedException; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; import java.util.Collection; import static org.springframework.web.servlet.mvc.method.annotation.MvcUriComponentsBuilder.on; @RestController @RequestMapping("/user") public class UserController extends AbstractResourceController { private final SecurityService securityService; private final UserService userService; private final ExtensionManager extensionManager; @Autowired public UserController(SecurityService securityService, UserService userService, ExtensionManager extensionManager) { this.securityService = securityService; this.userService = userService; this.extensionManager = extensionManager; } @RequestMapping(value = "", method = RequestMethod.GET) public ConnectedAccount getCurrentUser() { // Gets the current account Account account = securityService.getCurrentAccount(); // Account present if (account != null) { return toLoggedAccount(account); } // Not logged else { return toAnonymousAccount(); } } @RequestMapping(value = "login", method = RequestMethod.GET) public Form loginForm() { return Form.create() .name() .password() .with(YesNo.of("rememberMe").label("Remember me").value(false)) ; } @RequestMapping(value = "login", method = RequestMethod.POST) public ConnectedAccount login() { // Gets the current account Account account = securityService.getCurrentAccount(); // If not logged, rejects if (account == null) { throw new AccessDeniedException("Login required."); } // Already logged else { return toLoggedAccount(account); } } @RequestMapping(value = "logged-out", method = RequestMethod.GET) @ResponseStatus(HttpStatus.NO_CONTENT) public void loggedOut() { } @RequestMapping(value = "password", method = RequestMethod.GET) public Form getChangePasswordForm() { return Form.create() .with( Password.of("oldPassword") .label("Old password") .help("You need your old password in order to change it. If you do not remember it, " + "you'll have to contact an administrator who can change it for you.") ) .with( Password.of("newPassword") .label("New password") .withConfirmation() ) ; } @RequestMapping(value = "password", method = RequestMethod.POST) public Ack changePassword(@RequestBody @Valid PasswordChange input) { return userService.changePassword(input); } // Resource assemblers private ConnectedAccount toAnonymousAccount() { return ConnectedAccount.none(isAuthenticationRequired()); } private boolean isAuthenticationRequired() { return !securityService.getSecuritySettings().isGrantProjectViewToAll(); } private ConnectedAccount toLoggedAccount(Account account) { return userMenu(ConnectedAccount.of(isAuthenticationRequired(), account)); } private ConnectedAccount userMenu(ConnectedAccount user) { // Settings if (securityService.isGlobalFunctionGranted(GlobalSettings.class)) { user.add(Action.of("settings", "Settings", "settings")); } // Changing his password if (user.getAccount().getAuthenticationSource().isAllowingPasswordChange()) { user.add( Action.form( "user-password", "Change password", uri(on(getClass()).getChangePasswordForm()) ) ); } // Account management if (securityService.isGlobalFunctionGranted(AccountManagement.class) || securityService.isGlobalFunctionGranted(AccountGroupManagement.class)) { user.add(Action.of("admin-accounts", "Account management", "admin-accounts")); } // Management of predefined validation stamps and promotion levels if (securityService.isGlobalFunctionGranted(GlobalSettings.class)) { user.add(Action.of("admin-predefined-validation-stamps", "Predefined validation stamps", "admin-predefined-validation-stamps")); user.add(Action.of("admin-predefined-promotion-levels", "Predefined promotion levels", "admin-predefined-promotion-levels")); } // Management of labels if (securityService.isGlobalFunctionGranted(LabelManagement.class)) { user.add(Action.of("admin-labels", "Labels", "admin-labels")); } // Contributions from extensions ConnectedAccount contributed = userMenuExtensions(user); // Admin tools if (securityService.isGlobalFunctionGranted(ApplicationManagement.class)) { contributed.add(Action.of("admin-health", "System health", "admin-health")); contributed.add(Action.of("admin-extensions", "System extensions", "admin-extensions")); contributed.add(Action.of("admin-jobs", "System jobs", "admin-jobs")); contributed.add(Action.of("admin-log-entries", "Log entries", "admin-log-entries")); } // OK return contributed; } private ConnectedAccount userMenuExtensions(ConnectedAccount user) { // Gets the list of user menu extensions Collection<UserMenuExtension> extensions = extensionManager.getExtensions(UserMenuExtension.class); // For each extension for (UserMenuExtension extension : extensions) { // Granted? Class<? extends GlobalFunction> fn = extension.getGlobalFunction(); if (fn == null || securityService.isGlobalFunctionGranted(fn)) { // Adds the menu entry // Prepends the extension ID user.add(resolveExtensionAction(extension)); } } // OK return user; } }
mit
rainu/jsimpleshell-rc
src/main/java/de/raysha/lib/jsimpleshell/rc/model/ReadLine.java
823
package de.raysha.lib.jsimpleshell.rc.model; import java.io.Serializable; import de.raysha.lib.net.scs.model.Message; import de.raysha.lib.net.scs.model.serialize.ObjectSerializer; public class ReadLine implements Message, Serializable { private static final long serialVersionUID = -8663702268357746032L; private String prompt; private Character mask; public ReadLine(String prompt) { this.prompt = prompt; } public ReadLine(String prompt, Character mask) { this.prompt = prompt; this.mask = mask; } public String getPrompt() { return prompt; } public void setPrompt(String prompt) { this.prompt = prompt; } public Character getMask() { return mask; } public void setMask(Character mask) { this.mask = mask; } public static class Serializer extends ObjectSerializer<ReadLine> { } }
mit
zbeboy/ISY
src/main/java/top/zbeboy/isy/domain/tables/records/OauthClientDetailsRecord.java
14036
/* * This file is generated by jOOQ. */ package top.zbeboy.isy.domain.tables.records; import javax.annotation.Generated; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import org.jooq.Field; import org.jooq.Record1; import org.jooq.Record11; import org.jooq.Row11; import org.jooq.impl.UpdatableRecordImpl; import top.zbeboy.isy.domain.tables.OauthClientDetails; /** * This class is generated by jOOQ. */ @Generated( value = { "http://www.jooq.org", "jOOQ version:3.10.7" }, comments = "This class is generated by jOOQ" ) @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class OauthClientDetailsRecord extends UpdatableRecordImpl<OauthClientDetailsRecord> implements Record11<String, String, String, String, String, String, String, Integer, Integer, String, String> { private static final long serialVersionUID = 863693141; /** * Setter for <code>isy.oauth_client_details.client_id</code>. */ public void setClientId(String value) { set(0, value); } /** * Getter for <code>isy.oauth_client_details.client_id</code>. */ @NotNull @Size(max = 256) public String getClientId() { return (String) get(0); } /** * Setter for <code>isy.oauth_client_details.resource_ids</code>. */ public void setResourceIds(String value) { set(1, value); } /** * Getter for <code>isy.oauth_client_details.resource_ids</code>. */ @Size(max = 256) public String getResourceIds() { return (String) get(1); } /** * Setter for <code>isy.oauth_client_details.client_secret</code>. */ public void setClientSecret(String value) { set(2, value); } /** * Getter for <code>isy.oauth_client_details.client_secret</code>. */ @Size(max = 256) public String getClientSecret() { return (String) get(2); } /** * Setter for <code>isy.oauth_client_details.scope</code>. */ public void setScope(String value) { set(3, value); } /** * Getter for <code>isy.oauth_client_details.scope</code>. */ @Size(max = 256) public String getScope() { return (String) get(3); } /** * Setter for <code>isy.oauth_client_details.authorized_grant_types</code>. */ public void setAuthorizedGrantTypes(String value) { set(4, value); } /** * Getter for <code>isy.oauth_client_details.authorized_grant_types</code>. */ @Size(max = 256) public String getAuthorizedGrantTypes() { return (String) get(4); } /** * Setter for <code>isy.oauth_client_details.web_server_redirect_uri</code>. */ public void setWebServerRedirectUri(String value) { set(5, value); } /** * Getter for <code>isy.oauth_client_details.web_server_redirect_uri</code>. */ @Size(max = 256) public String getWebServerRedirectUri() { return (String) get(5); } /** * Setter for <code>isy.oauth_client_details.authorities</code>. */ public void setAuthorities(String value) { set(6, value); } /** * Getter for <code>isy.oauth_client_details.authorities</code>. */ @Size(max = 256) public String getAuthorities() { return (String) get(6); } /** * Setter for <code>isy.oauth_client_details.access_token_validity</code>. */ public void setAccessTokenValidity(Integer value) { set(7, value); } /** * Getter for <code>isy.oauth_client_details.access_token_validity</code>. */ public Integer getAccessTokenValidity() { return (Integer) get(7); } /** * Setter for <code>isy.oauth_client_details.refresh_token_validity</code>. */ public void setRefreshTokenValidity(Integer value) { set(8, value); } /** * Getter for <code>isy.oauth_client_details.refresh_token_validity</code>. */ public Integer getRefreshTokenValidity() { return (Integer) get(8); } /** * Setter for <code>isy.oauth_client_details.additional_information</code>. */ public void setAdditionalInformation(String value) { set(9, value); } /** * Getter for <code>isy.oauth_client_details.additional_information</code>. */ @Size(max = 4096) public String getAdditionalInformation() { return (String) get(9); } /** * Setter for <code>isy.oauth_client_details.autoapprove</code>. */ public void setAutoapprove(String value) { set(10, value); } /** * Getter for <code>isy.oauth_client_details.autoapprove</code>. */ @Size(max = 256) public String getAutoapprove() { return (String) get(10); } // ------------------------------------------------------------------------- // Primary key information // ------------------------------------------------------------------------- /** * {@inheritDoc} */ @Override public Record1<String> key() { return (Record1) super.key(); } // ------------------------------------------------------------------------- // Record11 type implementation // ------------------------------------------------------------------------- /** * {@inheritDoc} */ @Override public Row11<String, String, String, String, String, String, String, Integer, Integer, String, String> fieldsRow() { return (Row11) super.fieldsRow(); } /** * {@inheritDoc} */ @Override public Row11<String, String, String, String, String, String, String, Integer, Integer, String, String> valuesRow() { return (Row11) super.valuesRow(); } /** * {@inheritDoc} */ @Override public Field<String> field1() { return OauthClientDetails.OAUTH_CLIENT_DETAILS.CLIENT_ID; } /** * {@inheritDoc} */ @Override public Field<String> field2() { return OauthClientDetails.OAUTH_CLIENT_DETAILS.RESOURCE_IDS; } /** * {@inheritDoc} */ @Override public Field<String> field3() { return OauthClientDetails.OAUTH_CLIENT_DETAILS.CLIENT_SECRET; } /** * {@inheritDoc} */ @Override public Field<String> field4() { return OauthClientDetails.OAUTH_CLIENT_DETAILS.SCOPE; } /** * {@inheritDoc} */ @Override public Field<String> field5() { return OauthClientDetails.OAUTH_CLIENT_DETAILS.AUTHORIZED_GRANT_TYPES; } /** * {@inheritDoc} */ @Override public Field<String> field6() { return OauthClientDetails.OAUTH_CLIENT_DETAILS.WEB_SERVER_REDIRECT_URI; } /** * {@inheritDoc} */ @Override public Field<String> field7() { return OauthClientDetails.OAUTH_CLIENT_DETAILS.AUTHORITIES; } /** * {@inheritDoc} */ @Override public Field<Integer> field8() { return OauthClientDetails.OAUTH_CLIENT_DETAILS.ACCESS_TOKEN_VALIDITY; } /** * {@inheritDoc} */ @Override public Field<Integer> field9() { return OauthClientDetails.OAUTH_CLIENT_DETAILS.REFRESH_TOKEN_VALIDITY; } /** * {@inheritDoc} */ @Override public Field<String> field10() { return OauthClientDetails.OAUTH_CLIENT_DETAILS.ADDITIONAL_INFORMATION; } /** * {@inheritDoc} */ @Override public Field<String> field11() { return OauthClientDetails.OAUTH_CLIENT_DETAILS.AUTOAPPROVE; } /** * {@inheritDoc} */ @Override public String component1() { return getClientId(); } /** * {@inheritDoc} */ @Override public String component2() { return getResourceIds(); } /** * {@inheritDoc} */ @Override public String component3() { return getClientSecret(); } /** * {@inheritDoc} */ @Override public String component4() { return getScope(); } /** * {@inheritDoc} */ @Override public String component5() { return getAuthorizedGrantTypes(); } /** * {@inheritDoc} */ @Override public String component6() { return getWebServerRedirectUri(); } /** * {@inheritDoc} */ @Override public String component7() { return getAuthorities(); } /** * {@inheritDoc} */ @Override public Integer component8() { return getAccessTokenValidity(); } /** * {@inheritDoc} */ @Override public Integer component9() { return getRefreshTokenValidity(); } /** * {@inheritDoc} */ @Override public String component10() { return getAdditionalInformation(); } /** * {@inheritDoc} */ @Override public String component11() { return getAutoapprove(); } /** * {@inheritDoc} */ @Override public String value1() { return getClientId(); } /** * {@inheritDoc} */ @Override public String value2() { return getResourceIds(); } /** * {@inheritDoc} */ @Override public String value3() { return getClientSecret(); } /** * {@inheritDoc} */ @Override public String value4() { return getScope(); } /** * {@inheritDoc} */ @Override public String value5() { return getAuthorizedGrantTypes(); } /** * {@inheritDoc} */ @Override public String value6() { return getWebServerRedirectUri(); } /** * {@inheritDoc} */ @Override public String value7() { return getAuthorities(); } /** * {@inheritDoc} */ @Override public Integer value8() { return getAccessTokenValidity(); } /** * {@inheritDoc} */ @Override public Integer value9() { return getRefreshTokenValidity(); } /** * {@inheritDoc} */ @Override public String value10() { return getAdditionalInformation(); } /** * {@inheritDoc} */ @Override public String value11() { return getAutoapprove(); } /** * {@inheritDoc} */ @Override public OauthClientDetailsRecord value1(String value) { setClientId(value); return this; } /** * {@inheritDoc} */ @Override public OauthClientDetailsRecord value2(String value) { setResourceIds(value); return this; } /** * {@inheritDoc} */ @Override public OauthClientDetailsRecord value3(String value) { setClientSecret(value); return this; } /** * {@inheritDoc} */ @Override public OauthClientDetailsRecord value4(String value) { setScope(value); return this; } /** * {@inheritDoc} */ @Override public OauthClientDetailsRecord value5(String value) { setAuthorizedGrantTypes(value); return this; } /** * {@inheritDoc} */ @Override public OauthClientDetailsRecord value6(String value) { setWebServerRedirectUri(value); return this; } /** * {@inheritDoc} */ @Override public OauthClientDetailsRecord value7(String value) { setAuthorities(value); return this; } /** * {@inheritDoc} */ @Override public OauthClientDetailsRecord value8(Integer value) { setAccessTokenValidity(value); return this; } /** * {@inheritDoc} */ @Override public OauthClientDetailsRecord value9(Integer value) { setRefreshTokenValidity(value); return this; } /** * {@inheritDoc} */ @Override public OauthClientDetailsRecord value10(String value) { setAdditionalInformation(value); return this; } /** * {@inheritDoc} */ @Override public OauthClientDetailsRecord value11(String value) { setAutoapprove(value); return this; } /** * {@inheritDoc} */ @Override public OauthClientDetailsRecord values(String value1, String value2, String value3, String value4, String value5, String value6, String value7, Integer value8, Integer value9, String value10, String value11) { value1(value1); value2(value2); value3(value3); value4(value4); value5(value5); value6(value6); value7(value7); value8(value8); value9(value9); value10(value10); value11(value11); return this; } // ------------------------------------------------------------------------- // Constructors // ------------------------------------------------------------------------- /** * Create a detached OauthClientDetailsRecord */ public OauthClientDetailsRecord() { super(OauthClientDetails.OAUTH_CLIENT_DETAILS); } /** * Create a detached, initialised OauthClientDetailsRecord */ public OauthClientDetailsRecord(String clientId, String resourceIds, String clientSecret, String scope, String authorizedGrantTypes, String webServerRedirectUri, String authorities, Integer accessTokenValidity, Integer refreshTokenValidity, String additionalInformation, String autoapprove) { super(OauthClientDetails.OAUTH_CLIENT_DETAILS); set(0, clientId); set(1, resourceIds); set(2, clientSecret); set(3, scope); set(4, authorizedGrantTypes); set(5, webServerRedirectUri); set(6, authorities); set(7, accessTokenValidity); set(8, refreshTokenValidity); set(9, additionalInformation); set(10, autoapprove); } }
mit
octavioturra/react-native-alt-beacon
example/android/app/src/main/java/com/example/MainActivity.java
1114
package com.example; import com.facebook.react.ReactActivity; import com.facebook.react.ReactPackage; import com.facebook.react.shell.MainReactPackage; import br.com.fraguto.rnabeacon.RNABeaconPackage; import java.util.Arrays; import java.util.List; public class MainActivity extends ReactActivity { /** * Returns the name of the main component registered from JavaScript. * This is used to schedule rendering of the component. */ @Override protected String getMainComponentName() { return "example"; } /** * Returns whether dev mode should be enabled. * This enables e.g. the dev menu. */ @Override protected boolean getUseDeveloperSupport() { return BuildConfig.DEBUG; } /** * A list of packages used by the app. If the app uses additional views * or modules besides the default ones, add more packages here. */ @Override protected List<ReactPackage> getPackages() { return Arrays.<ReactPackage>asList( new MainReactPackage(), new RNABeaconPackage() ); } }
mit
OpenMods/OpenPeripheral-Integration
src/main/java/openperipheral/integration/vanilla/EntityZombieMetaProvider.java
651
package openperipheral.integration.vanilla; import com.google.common.collect.Maps; import java.util.Map; import net.minecraft.entity.monster.EntityZombie; import net.minecraft.util.Vec3; import openperipheral.api.helpers.EntityMetaProviderSimple; public class EntityZombieMetaProvider extends EntityMetaProviderSimple<EntityZombie> { @Override public String getKey() { return "zombie"; } @Override public Object getMeta(EntityZombie target, Vec3 relativePos) { Map<String, Object> map = Maps.newHashMap(); map.put("isVillagerZombie", target.isVillager()); map.put("convertingToVillager", target.isConverting()); return map; } }
mit
PriitPaluoja/TabletScanner
src/main/java/ee/scanner/tablet/dto/UserWrapperDTO.java
355
package ee.scanner.tablet.dto; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import javax.validation.Valid; import java.util.ArrayList; import java.util.List; @Data @AllArgsConstructor @NoArgsConstructor public class UserWrapperDTO { @Valid private List<UserManagementDTO> users = new ArrayList<>(); }
mit
markovandooren/jnome
src/org/aikodi/java/core/expression/invocation/JavaInfixOperatorInvocation.java
695
package org.aikodi.java.core.expression.invocation; import org.aikodi.chameleon.core.lookup.DeclarationSelector; import org.aikodi.chameleon.core.reference.CrossReferenceTarget; import org.aikodi.chameleon.support.member.simplename.operator.infix.InfixOperator; import org.aikodi.chameleon.support.member.simplename.operator.infix.InfixOperatorInvocation; public class JavaInfixOperatorInvocation extends InfixOperatorInvocation { public JavaInfixOperatorInvocation(String name, CrossReferenceTarget target) { super(name,target); } @Override public DeclarationSelector<InfixOperator> createSelector() { return new JavaMethodSelector<InfixOperator>(this,InfixOperator.class); } }
mit
rafalimaz/CatchML
DSL/SEChecker/src/br/ufc/great/expression/ContextProposition.java
1509
package br.ufc.great.expression; import br.ufc.great.expression.exception.EvaluationException; import br.ufc.great.model.Assignment; import br.ufc.great.model.Environment; import choco.Choco; import choco.kernel.model.constraints.Constraint; import choco.kernel.model.variables.integer.IntegerVariable; public class ContextProposition extends ContextPredicate { private String name; public ContextProposition(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Constraint toChocoModel() { Environment converter = Environment.getInstance(); return Choco.eq(1, converter.getChocoVar(this.getName())); } public IntegerVariable toChocoVar() { Environment converter = Environment.getInstance(); return converter.getChocoVar(this.getName()); } public boolean eval(Assignment assignment) throws EvaluationException { if (!assignment.hasSymbol(this.getName())) { throw new EvaluationException("The symbol \"" + this.toString() + "\" is not found in the assignment."); } return assignment.getValuationOf(this.getName()); } public String toString() { return this.name; } public boolean equals(Object obj) { boolean result = false; if (obj != null && obj instanceof ContextProposition) { ContextProposition objCP = (ContextProposition) obj; result = this.name.equals(objCP.getName()); } return result; } }
mit
Sotanna/Quartz-Server
src/main/java/org/quartzpowered/protocol/data/ChatPosition.java
1568
/* * This file is a component of Quartz Powered, this license makes sure any work * associated with Quartz Powered, must follow the conditions of the license included. * * The MIT License (MIT) * * Copyright (c) 2015 Quartz Powered * * 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.quartzpowered.protocol.data; public enum ChatPosition { CHAT, SYSTEM, ACTION_BAR; public int getId() { return ordinal(); } public static ChatPosition fromId(int id) { return values()[id]; } }
mit
accelazh/ProspectDict
guestUserInterface/personalWordBook/PersonalWordDialog.java
1371
package guestUserInterface.personalWordBook; import java.awt.*; import java.awt.event.*; import javax.swing.*; import libraryManager.*; import libraryInterface.*; public class PersonalWordDialog extends JDialog implements WindowListener { private PersonalWordPanel wordPanel; public PersonalWordDialog(int index) { wordPanel=new PersonalWordPanel(index, this); PersonalLibrary libP=PersonalLibraryManager.getLibraryAccountor().get(index); if(libP!=null) { this.setTitle(libP.getName()); } getContentPane().add(wordPanel); setSize(520,400); this.addWindowListener(this); setVisible(true); } public void windowActivated(WindowEvent e) { // TODO Auto-generated method stub } public void windowClosed(WindowEvent e) { // TODO Auto-generated method stub } public void windowClosing(WindowEvent e) { PersonalLibraryManager.getLibraryAccountor().writeCurrentPersonalLibraries(); } public void windowDeactivated(WindowEvent e) { // TODO Auto-generated method stub } public void windowDeiconified(WindowEvent e) { // TODO Auto-generated method stub } public void windowIconified(WindowEvent e) { // TODO Auto-generated method stub } public void windowOpened(WindowEvent e) { // TODO Auto-generated method stub } }
mit
venizeng/lifeix-bz-common
src/main/java/com/lifeix/bz/common/module/like/util/LikeUtil.java
872
package com.lifeix.bz.common.module.like.util; import java.util.ArrayList; import java.util.List; import org.springframework.util.CollectionUtils; import com.lifeix.bz.common.module.like.dao.LikeDao.LikeRecord; import com.lifeix.bz.common.module.like.model.Like; public class LikeUtil { public static String createLikeRecordId(String type,String source,String target){ return type + "#" + source + "#" + target; } public static List<Like> getLike(String type,List<LikeRecord> result) { if (CollectionUtils.isEmpty(result)) { return null; } List<Like> likes = new ArrayList<>(); for (LikeRecord likeRecord : result) { Like like = new Like(); like.setType(type); like.setTarget(likeRecord.getTarget()); like.setLikeNum(likeRecord.getLikeNum()); like.setUnlikeNum(likeRecord.getUnlikeNum()); likes.add(like); } return likes; } }
mit
chilimannen/onegram-android
app/src/main/java/com/github/codingchili/api/Request.java
780
package com.github.codingchili.api; /** * @author Robin Duda * * Request object required by the ClientProtocol interface. */ public class Request { private String query; private Method method; private String resource; private String host; public String getHost() { return host; } public String getResource() { return resource; } public Method getMethod() { return method; } public String getQuery() { return query; } public Request(String query, Method method, String resource, String host) { this.query = query; this.method = method; this.host = host; this.resource = resource; } public int getSize() { return query.length(); } }
mit
clom/Jmdwiki
test/IntegrationTest.java
698
import org.junit.*; import play.mvc.*; import play.test.*; import static play.test.Helpers.*; import static org.junit.Assert.*; import static org.fluentlenium.core.filter.FilterConstructor.*; public class IntegrationTest { /** * add your integration test here * in this example we just check if the welcome page is being shown */ /** * Play welcome page will not be shown. @Test public void test() { running(testServer(3333, fakeApplication(inMemoryDatabase())), HTMLUNIT, browser -> { browser.goTo("http://localhost:3333"); assertTrue(browser.pageSource().contains("Your new application is ready.")); }); } */ }
mit
danfunk/MindTrails
kaiser/src/main/java/edu/virginia/psyc/kaiser/persistence/OA.java
3551
package edu.virginia.psyc.kaiser.persistence; import edu.virginia.psyc.kaiser.domain.KaiserStudy; import lombok.Data; import lombok.EqualsAndHashCode; import org.mindtrails.domain.Participant; import org.mindtrails.domain.data.DoNotDelete; import org.mindtrails.domain.questionnaire.LinkedQuestionnaireData; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; import javax.validation.constraints.NotNull; import java.util.Date; import java.util.HashMap; import java.util.Map; /** * This Oasis questionnaire is used over time in the study to determine * participant progress. So while it can be exported through the admin * panel, the data should not be deleted. To help make things a little * safer, we obscure the names of the fields while the data is stored in * the database. */ @Entity @Table(name="OA") @Data @EqualsAndHashCode(callSuper = true) @DoNotDelete public class OA extends LinkedQuestionnaireData implements Comparable<OA> { private static final Logger LOG = LoggerFactory.getLogger(OA.class); public static int NO_ANSWER = 555; public static final int MAX_SCORE = 4; protected String sessionId; @Column(name="AXF") @NotNull private Integer anxious_freq; @Column(name="AXS") @NotNull private Integer anxious_sev; @Column(name="AVO") @NotNull private Integer avoid; @Column(name="WRK") @NotNull private Integer interfere; @Column(name="SOC") @NotNull private Integer interfere_social; public OA(int anxious_freq, int anxious_sev, int avoid, int interfere, int interfere_social) { this.anxious_freq=anxious_freq; this.anxious_sev = anxious_sev; this.avoid = avoid; this.interfere = interfere; this.interfere_social = interfere_social; this.date = new Date(); } public OA(){} public double score() { int sum = 0; double total = 0.0; if(anxious_freq != NO_ANSWER) { sum += anxious_freq; total++;} if(anxious_sev != NO_ANSWER) { sum += anxious_sev; total++;} if(avoid != NO_ANSWER) { sum += avoid; total++;} if(interfere != NO_ANSWER) { sum += interfere; total++;} if(interfere_social != NO_ANSWER) { sum += interfere_social; total++;} if (total == 0) return 0; return(sum / total) * 5; } public boolean eligible() { return(this.score() >= 6 ); } private boolean noAnswers() { return( anxious_freq == NO_ANSWER && anxious_sev == NO_ANSWER && avoid == NO_ANSWER && interfere == NO_ANSWER && interfere_social == NO_ANSWER ); } public boolean atRisk(OA original) { if(original.noAnswers()) return false; return (score() / original.score()) > 1.5; } public double getIncrease(OA original) { return (score() / original.score()); } @Override public int compareTo(OA o) { return date.compareTo(o.date); } @Override public Map<String,Object> modelAttributes(Participant p) { Map<String, Object> attributes = new HashMap<>(); if (p.getStudy() instanceof KaiserStudy) { KaiserStudy study = (KaiserStudy) p.getStudy(); attributes.put("inSessions", study.inSession()); } else { attributes.put("inSessions", false); } return attributes; } }
mit
kosiacz3q/StrgWar
src/StrgWar/map/changeable/ChangeableMap.java
779
package StrgWar.map.changeable; import java.util.ArrayList; import javafx.geometry.Point2D; import javafx.scene.shape.Rectangle; public class ChangeableMap { public ChangeableMap() { Nodes = new ArrayList<ChangeableNode>(); } public final ArrayList<ChangeableNode> Nodes; public ChangeableNode Find(String name) { for (ChangeableNode node : Nodes) if (node.GetMapElementName().compareTo(name) == 0) return node; return null; } public ChangeableNode FindByPoint(Point2D point) { for (ChangeableNode node : Nodes) { if (new Rectangle(node.GetPosition().getX() - node.GetRadius() / 2, node.GetPosition().getY() - node.GetRadius() / 2, node.GetRadius(), node.GetRadius()).contains(point)) { return node; } } return null; } }
mit
kaliatech/template-java-spring-webapp
workspace_java/myproj-main-webapp/src/main/java/com/mycompany/myproj/main/services/RemoteRemote1ServiceImpl.java
571
package com.mycompany.myproj.main.services; import java.rmi.RemoteException; import java.util.Date; import org.slf4j.Logger; import org.springframework.stereotype.Service; import com.mycompany.myproj.remote1.RemoteRemote1Service; @Service public class RemoteRemote1ServiceImpl implements RemoteRemote1Service { private final Logger logger = org.slf4j.LoggerFactory.getLogger(this.getClass()); @Override public String getTest1() throws RemoteException { logger.info("getTest1"); return "Response from remote1 service:" + new Date().getTime(); } }
mit
guilherme-otran/projector
core/src/main/java/us/guihouse/projector/projection/ProjectionManager.java
1726
/* * 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 us.guihouse.projector.projection; import java.awt.Font; import java.io.File; import javafx.beans.property.ReadOnlyProperty; import us.guihouse.projector.projection.models.BackgroundModel; import us.guihouse.projector.projection.text.WrappedText; import us.guihouse.projector.projection.text.WrapperFactory; import us.guihouse.projector.projection.video.ProjectionPlayer; /** * * @author 15096134 */ public interface ProjectionManager { void setText(WrappedText text); Font getTextFont(); void setTextFont(Font font); void addTextWrapperChangeListener(TextWrapperFactoryChangeListener wrapperChangeListener); ProjectionWebView createWebView(); ProjectionImage createImage(); void setProjectable(Projectable webView); WrapperFactory getWrapperFactory(); BackgroundModel getBackgroundModel(); ReadOnlyProperty<Projectable> projectableProperty(); void setBackgroundModel(BackgroundModel background); void setFullScreen(boolean fullScreen); void setCropBackground(boolean selected); ProjectionPlayer createPlayer(); boolean getDarkenBackground(); void setDarkenBackground(boolean darkenBg); void stop(Projectable projectable); void setMusicForBackground(Integer musicId, File preferred); boolean getCropBackground(); void setChromaPaddingBottom(int paddingBottom); void setChromaMinPaddingBottom(int paddingBottom); void setChromaFontSize(int fontSize); }
mit
palatable/lambda
src/main/java/com/jnape/palatable/lambda/adt/Try.java
18193
package com.jnape.palatable.lambda.adt; import com.jnape.palatable.lambda.adt.coproduct.CoProduct2; import com.jnape.palatable.lambda.functions.Fn0; import com.jnape.palatable.lambda.functions.Fn1; import com.jnape.palatable.lambda.functions.recursion.RecursiveResult; import com.jnape.palatable.lambda.functions.builtin.fn1.Downcast; import com.jnape.palatable.lambda.functions.specialized.Pure; import com.jnape.palatable.lambda.functions.specialized.SideEffect; import com.jnape.palatable.lambda.functor.Applicative; import com.jnape.palatable.lambda.functor.builtin.Lazy; import com.jnape.palatable.lambda.io.IO; import com.jnape.palatable.lambda.monad.Monad; import com.jnape.palatable.lambda.monad.MonadError; import com.jnape.palatable.lambda.monad.MonadRec; import com.jnape.palatable.lambda.traversable.Traversable; import java.util.Objects; import static com.jnape.palatable.lambda.adt.Maybe.nothing; import static com.jnape.palatable.lambda.adt.Unit.UNIT; import static com.jnape.palatable.lambda.functions.builtin.fn1.Constantly.constantly; import static com.jnape.palatable.lambda.functions.builtin.fn1.Id.id; import static com.jnape.palatable.lambda.functions.builtin.fn1.Upcast.upcast; import static com.jnape.palatable.lambda.functions.recursion.RecursiveResult.terminate; import static com.jnape.palatable.lambda.functions.recursion.Trampoline.trampoline; import static com.jnape.palatable.lambda.functor.builtin.Lazy.lazy; import static com.jnape.palatable.lambda.internal.Runtime.throwChecked; /** * A {@link Monad} of the evaluation outcome of an expression that might throw. Try/catch/finally semantics map to * <code>trying</code>/<code>catching</code>/<code>ensuring</code>, respectively. * * @param <A> the possibly successful expression result * @see Either */ public abstract class Try<A> implements MonadError<Throwable, A, Try<?>>, MonadRec<A, Try<?>>, Traversable<A, Try<?>>, CoProduct2<Throwable, A, Try<A>> { private Try() { } /** * Catch any instance of <code>throwableType</code> and map it to a success value. * * @param <S> the {@link Throwable} (sub)type * @param throwableType the {@link Throwable} (sub)type to be caught * @param recoveryFn the function mapping the {@link Throwable} to the result * @return a new {@link Try} instance around either the original successful result or the mapped result */ public final <S extends Throwable> Try<A> catching(Class<S> throwableType, Fn1<? super S, ? extends A> recoveryFn) { return catching(throwableType::isInstance, t -> recoveryFn.apply(Downcast.<S, Throwable>downcast(t))); } /** * Catch any thrown <code>T</code> satisfying <code>predicate</code> and map it to a success value. * * @param predicate the predicate * @param recoveryFn the function mapping the {@link Throwable} to the result * @return a new {@link Try} instance around either the original successful result or the mapped result */ public final Try<A> catching(Fn1<? super Throwable, ? extends Boolean> predicate, Fn1<? super Throwable, ? extends A> recoveryFn) { return match(t -> predicate.apply(t) ? success(recoveryFn.apply(t)) : failure(t), Try::success); } /** * Run the provided runnable regardless of whether this is a success or a failure (the {@link Try} analog to * <code>finally</code>. * <p> * If the runnable runs successfully, the result is preserved as is. If the runnable itself throws, and the result * was a success, the result becomes a failure over the newly-thrown {@link Throwable}. If the result was a failure * over some {@link Throwable} <code>t1</code>, and the runnable throws a new {@link Throwable} <code>t2</code>, the * result is a failure over <code>t1</code> with <code>t2</code> added to <code>t1</code> as a suppressed exception. * * @param sideEffect the runnable block of code to execute * @return the same {@link Try} instance if runnable completes successfully; otherwise, a {@link Try} conforming to * rules above */ public final Try<A> ensuring(SideEffect sideEffect) { return this.<Try<A>>match(t -> trying(sideEffect) .<Try<A>>fmap(constantly(failure(t))) .recover(t2 -> { t.addSuppressed(t2); return failure(t); }), a -> trying(sideEffect).fmap(constantly(a))); } /** * If this is a success, return the wrapped value. Otherwise, apply the {@link Throwable} to <code>fn</code> and * return the result. * * @param fn the function mapping the potential {@link Throwable} <code>T</code> to <code>A</code> * @return a success value */ public final A recover(Fn1<? super Throwable, ? extends A> fn) { return match(fn, id()); } /** * If this is a failure, return the wrapped value. Otherwise, apply the success value to <code>fn</code> and return * the result. * * @param fn the function mapping the potential <code>A</code> to <code>T</code> * @return a failure value */ public final Throwable forfeit(Fn1<? super A, ? extends Throwable> fn) { return match(id(), fn); } /** * If this is a success value, return it. Otherwise, rethrow the captured failure. * * @param <T> a declarable exception type used for catching checked exceptions * @return possibly the success value * @throws T anything that the call site may want to explicitly catch or indicate could be thrown */ public final <T extends Throwable> A orThrow() throws T { try { return orThrow(id()); } catch (Throwable t) { throw throwChecked(t); } } /** * If this is a success value, return it. Otherwise, transform the captured failure with <code>fn</code> and throw * the result. * * @param fn the {@link Throwable} transformation * @param <T> the type of the thrown {@link Throwable} * @return possibly the success value * @throws T the transformation output */ public abstract <T extends Throwable> A orThrow(Fn1<? super Throwable, ? extends T> fn) throws T; /** * If this is a success, wrap the value in a {@link Maybe#just} and return it. Otherwise, return {@link * Maybe#nothing()}. * * @return {@link Maybe} the success value */ public final Maybe<A> toMaybe() { return match(__ -> nothing(), Maybe::just); } /** * If this is a success, wrap the value in a {@link Either#right} and return it. Otherwise, return the {@link * Throwable} in an {@link Either#left}. * * @return {@link Either} the success value or the {@link Throwable} */ public final Either<Throwable, A> toEither() { return toEither(id()); } /** * If this is a success, wrap the value in a {@link Either#right} and return it. Otherwise, apply the mapping * function to the failure {@link Throwable}, re-wrap it in an {@link Either#left}, and return it. * * @param <L> the {@link Either} left parameter type * @param fn the mapping function * @return {@link Either} the success value or the mapped left value */ public final <L> Either<L, A> toEither(Fn1<? super Throwable, ? extends L> fn) { return match(fn.fmap(Either::left), Either::right); } /** * {@inheritDoc} */ @Override public Try<A> throwError(Throwable throwable) { return failure(throwable); } /** * {@inheritDoc} */ @Override public Try<A> catchError(Fn1<? super Throwable, ? extends Monad<A, Try<?>>> recoveryFn) { return match(t -> recoveryFn.apply(t).coerce(), Try::success); } /** * {@inheritDoc} */ @Override public <B> Try<B> fmap(Fn1<? super A, ? extends B> fn) { return MonadError.super.<B>fmap(fn).coerce(); } /** * {@inheritDoc} */ @Override public <B> Try<B> flatMap(Fn1<? super A, ? extends Monad<B, Try<?>>> f) { return match(Try::failure, a -> f.apply(a).coerce()); } /** * {@inheritDoc} */ @Override public <B> Try<B> pure(B b) { return success(b); } /** * {@inheritDoc} */ @Override public <B> Try<B> zip(Applicative<Fn1<? super A, ? extends B>, Try<?>> appFn) { return MonadError.super.zip(appFn).coerce(); } /** * {@inheritDoc} */ @Override public <B> Lazy<Try<B>> lazyZip(Lazy<? extends Applicative<Fn1<? super A, ? extends B>, Try<?>>> lazyAppFn) { return match(f -> lazy(failure(f)), s -> lazyAppFn.fmap(tryF -> tryF.<B>fmap(f -> f.apply(s)).coerce())); } /** * {@inheritDoc} */ @Override public <B> Try<B> discardL(Applicative<B, Try<?>> appB) { return MonadError.super.discardL(appB).coerce(); } /** * {@inheritDoc} */ @Override public <B> Try<A> discardR(Applicative<B, Try<?>> appB) { return MonadError.super.discardR(appB).coerce(); } /** * {@inheritDoc} */ @Override public <B> Try<B> trampolineM(Fn1<? super A, ? extends MonadRec<RecursiveResult<A, B>, Try<?>>> fn) { return flatMap(trampoline(a -> fn.apply(a).<Try<RecursiveResult<A, B>>>coerce().match( t -> terminate(failure(t)), aOrB -> aOrB.fmap(Try::success) ))); } /** * {@inheritDoc} */ @Override @SuppressWarnings("unchecked") public <B, App extends Applicative<?, App>, TravB extends Traversable<B, Try<?>>, AppTrav extends Applicative<TravB, App>> AppTrav traverse(Fn1<? super A, ? extends Applicative<B, App>> fn, Fn1<? super TravB, ? extends AppTrav> pure) { return match(t -> pure.apply((TravB) failure(t)), a -> fn.apply(a).fmap(Try::success).<TravB>fmap(Applicative::coerce).coerce()); } /** * Static factory method for creating a success value. * * @param a the wrapped value * @param <A> the success parameter type * @return a success value of a */ public static <A> Try<A> success(A a) { return new Success<>(a); } /** * Static factory method for creating a failure value. * * @param t the {@link Throwable} * @param <A> the success parameter type * @return a failure value of t */ public static <A> Try<A> failure(Throwable t) { return new Failure<>(t); } /** * Execute <code>supplier</code>, returning a success <code>A</code> or a failure of the thrown {@link Throwable}. * * @param supplier the supplier * @param <A> the possible success type * @return a new {@link Try} around either a successful A result or the thrown {@link Throwable} */ public static <A> Try<A> trying(Fn0<? extends A> supplier) { try { return success(supplier.apply()); } catch (Throwable t) { return failure(t); } } /** * Execute <code>runnable</code>, returning a success {@link Unit} or a failure of the thrown {@link Throwable}. * * @param sideEffect the runnable * @return a new {@link Try} around either a successful {@link Unit} result or the thrown {@link Throwable} */ public static Try<Unit> trying(SideEffect sideEffect) { return trying(() -> { IO.io(sideEffect).unsafePerformIO(); return UNIT; }); } /** * Given a <code>{@link Fn0}&lt;{@link AutoCloseable}&gt;</code> <code>aSupplier</code> and an {@link Fn1} * <code>fn</code>, apply <code>fn</code> to the result of <code>aSupplier</code>, ensuring that the result has its * {@link AutoCloseable#close() close} method invoked, regardless of the outcome. * <p> * If the resource creation process throws, the function body throws, or the * {@link AutoCloseable#close() close method} throws, the result is a failure. If both the function body and the * {@link AutoCloseable#close() close method} throw, the result is a failure over the function body * {@link Throwable} with the {@link AutoCloseable#close() close method} {@link Throwable} added as a * {@link Throwable#addSuppressed(Throwable) suppressed} {@link Throwable}. If only the * {@link AutoCloseable#close() close method} throws, the result is a failure over that {@link Throwable}. * <p> * Note that <code>withResources</code> calls can be nested, in which case all of the above specified exception * handling applies, where closing the previously created resource is considered part of the body of the next * <code>withResources</code> calls, and {@link Throwable Throwables} are considered suppressed in the same manner. * Additionally, {@link AutoCloseable#close() close methods} are invoked in the inverse order of resource creation. * <p> * This is {@link Try}'s equivalent of * <a href="https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html" target="_top"> * try-with-resources</a>, introduced in Java 7. * * @param fn0 the resource supplier * @param fn the function body * @param <A> the resource type * @param <B> the function return type * @return a {@link Try} representing the result of the function's application to the resource */ @SuppressWarnings("try") public static <A extends AutoCloseable, B> Try<B> withResources( Fn0<? extends A> fn0, Fn1<? super A, ? extends Try<? extends B>> fn) { return trying(() -> { try (A resource = fn0.apply()) { return fn.apply(resource).<B>fmap(upcast()); } }).flatMap(id()); } /** * Convenience overload of {@link Try#withResources(Fn0, Fn1) withResources} that cascades dependent resource * creation via nested calls. * * @param fn0 the first resource supplier * @param bFn the dependent resource function * @param fn the function body * @param <A> the first resource type * @param <B> the second resource type * @param <C> the function return type * @return a {@link Try} representing the result of the function's application to the dependent resource */ public static <A extends AutoCloseable, B extends AutoCloseable, C> Try<C> withResources( Fn0<? extends A> fn0, Fn1<? super A, ? extends B> bFn, Fn1<? super B, ? extends Try<? extends C>> fn) { return withResources(fn0, a -> withResources(() -> bFn.apply(a), fn::apply)); } /** * Convenience overload of {@link Try#withResources(Fn0, Fn1, Fn1) withResources} that * cascades * two dependent resource creations via nested calls. * * @param fn0 the first resource supplier * @param bFn the second resource function * @param cFn the final resource function * @param fn the function body * @param <A> the first resource type * @param <B> the second resource type * @param <C> the final resource type * @param <D> the function return type * @return a {@link Try} representing the result of the function's application to the final dependent resource */ public static <A extends AutoCloseable, B extends AutoCloseable, C extends AutoCloseable, D> Try<D> withResources( Fn0<? extends A> fn0, Fn1<? super A, ? extends B> bFn, Fn1<? super B, ? extends C> cFn, Fn1<? super C, ? extends Try<? extends D>> fn) { return withResources(fn0, bFn, b -> withResources(() -> cFn.apply(b), fn::apply)); } /** * The canonical {@link Pure} instance for {@link Try}. * * @return the {@link Pure} instance */ public static Pure<Try<?>> pureTry() { return Try::success; } private static final class Failure<A> extends Try<A> { private final Throwable t; private Failure(Throwable t) { this.t = t; } @Override public <T extends Throwable> A orThrow(Fn1<? super Throwable, ? extends T> fn) throws T { throw fn.apply(t); } @Override public <R> R match(Fn1<? super Throwable, ? extends R> aFn, Fn1<? super A, ? extends R> bFn) { return aFn.apply(t); } @Override public boolean equals(Object other) { return other instanceof Failure && Objects.equals(t, ((Failure) other).t); } @Override public int hashCode() { return Objects.hash(t); } @Override public String toString() { return "Failure{" + "t=" + t + '}'; } } private static final class Success<A> extends Try<A> { private final A a; private Success(A a) { this.a = a; } @Override public <T extends Throwable> A orThrow(Fn1<? super Throwable, ? extends T> fn) { return a; } @Override public <R> R match(Fn1<? super Throwable, ? extends R> aFn, Fn1<? super A, ? extends R> bFn) { return bFn.apply(a); } @Override public boolean equals(Object other) { return other instanceof Success && Objects.equals(a, ((Success) other).a); } @Override public int hashCode() { return Objects.hash(a); } @Override public String toString() { return "Success{" + "a=" + a + '}'; } } }
mit
CharkeyQK/AlgorithmDataStructure
src/cn/simastudio/charkey/learning/simulatestack/SimulateSysStack.java
2135
/* * The MIT License (MIT) * * Copyright (c) 2013-2017 Charkey. * * 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 cn.simastudio.charkey.learning.simulatestack; /** * <p>Recursion to Stack, 防止栈溢出</p> * <p>Created by Charkey on 2016/7/22.</p> */ public class SimulateSysStack { private static int recursion1(int n) { if (n <= 1) { return 1; } else { return n * recursion1(n - 1); } } private static int recursion2(int n) { boolean back = false; int res = 1; int[] stack = new int[n]; int front = -1; do { if (!back) { if (n <= 1) { res = 1; back = true; continue; } stack[++front] = n--; } else { res *= stack[front--]; } } while (front >= 0); return res; } public static void main(String[] args) { System.out.println(recursion1(10)); System.out.println(recursion2(10)); } }
mit
CS2103AUG2016-T11-C1/main
src/main/java/seedu/tasklist/commons/core/Config.java
3496
package seedu.tasklist.commons.core; import java.io.FileWriter; import java.io.IOException; import java.util.Objects; import java.util.logging.Level; import org.json.JSONException; import org.json.simple.JSONObject; import org.json.simple.parser.*; /** * Config values used by the app */ public class Config { public static final String DEFAULT_CONFIG_FILE = "config.json"; // Config values customizable through config file private String appTitle = "Lazyman's Friend"; private Level logLevel = Level.INFO; private String userPrefsFilePath = "preferences.json"; private String taskListFilePath = "data/tasklist.xml"; private String taskListName = "MyTaskList"; public Config() { } public String getAppTitle() { return appTitle; } public void setAppTitle(String appTitle) { this.appTitle = appTitle; } public Level getLogLevel() { return logLevel; } public void setLogLevel(Level logLevel) { this.logLevel = logLevel; } public String getUserPrefsFilePath() { return userPrefsFilePath; } public void setUserPrefsFilePath(String userPrefsFilePath) { this.userPrefsFilePath = userPrefsFilePath; } /* @@author A0135769N */ public String getTaskListFilePath() { return taskListFilePath; } // Method replaces the existing file path with the new file path specified by user. public void setTaskListFilePath(String taskListFilePath) throws JSONException, IOException, ParseException { JSONObject obj = new JSONObject(); obj.put("taskListFilePath", taskListFilePath); obj.put("userPrefsFilePath", "preferences.json"); obj.put("appTitle", "Lazyman's Friend"); obj.put("logLevel", "INFO"); obj.put("taskListName", "MyTaskList"); try (FileWriter file = new FileWriter("config.json")) { file.write(obj.toJSONString()); System.out.println("Successfully Copied JSON Object to File..."); System.out.println("\nJSON Object: " + obj); } this.taskListFilePath = taskListFilePath; } public String getTaskListName() { return taskListName; } public void setTaskListName(String taskListName) { this.taskListName = taskListName; } @Override public boolean equals(Object other) { if (other == this){ return true; } if (!(other instanceof Config)){ //this handles null as well. return false; } Config o = (Config)other; return Objects.equals(appTitle, o.appTitle) && Objects.equals(logLevel, o.logLevel) && Objects.equals(userPrefsFilePath, o.userPrefsFilePath) && Objects.equals(taskListFilePath, o.taskListFilePath) && Objects.equals(taskListName, o.taskListName); } @Override public int hashCode() { return Objects.hash(appTitle, logLevel, userPrefsFilePath, taskListFilePath, taskListName); } @Override public String toString(){ StringBuilder sb = new StringBuilder(); sb.append("App title : " + appTitle); sb.append("\nCurrent log level : " + logLevel); sb.append("\nPreference file Location : " + userPrefsFilePath); sb.append("\nLocal data file location : " + taskListFilePath); sb.append("\nTaskList name : " + taskListName); return sb.toString(); } }
mit
rekbun/leetcode
src/leetcode/RemoveDuplicatesFromListII.java
862
package leetcode; /* http://oj.leetcode.com/problems/remove-duplicates-from-sorted-list-ii/ */ public class RemoveDuplicatesFromListII { public static ListNode deleteDuplicates(ListNode root) { if (root == null) { return root; } ListNode ret = new ListNode(root.val); ListNode prev = null; ListNode retItr = ret; root=root.next; boolean duplicate = false; while (root != null) { if (root.val == retItr.val) { duplicate = true; } else { if (duplicate) { retItr = prev; } if(retItr==null) { ret=new ListNode(root.val); retItr=ret; }else { retItr.next = new ListNode(root.val); prev = retItr; retItr = retItr.next; } duplicate =false; } root=root.next; } if (duplicate) { if(prev!=null) { prev.next = null; }else { return null; } } return ret; }}
mit
Nexmo/nexmo-java-sdk
src/main/java/com/vonage/client/account/PricingRequest.java
878
/* * Copyright 2020 Vonage * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.vonage.client.account; public class PricingRequest { private String countryCode; public PricingRequest(String countryCode) { this.countryCode = countryCode; } public String getCountryCode() { return countryCode; } }
mit
bemisguided/atreus
src/test/java/org/atreus/core/tests/entities/errors/InvalidMapStrategyTestEntity.java
2737
/** * The MIT License * * Copyright (c) 2014 Martin Crawford and contributors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.atreus.core.tests.entities.errors; import org.atreus.core.annotations.*; import org.atreus.impl.types.cql.StringTypeStrategy; import java.util.Map; /** * InvalidMapStrategyTestEntity * * @author Martin Crawford */ @AtreusEntity public class InvalidMapStrategyTestEntity { // Constants ---------------------------------------------------------------------------------------------- Constants // Instance Variables ---------------------------------------------------------------------------- Instance Variables @AtreusPrimaryKey private String id; @AtreusFieldType(StringTypeStrategy.class) @AtreusCollection(type = String.class) @AtreusMap(key = String.class) private Map mapField; // Constructors ---------------------------------------------------------------------------------------- Constructors // Public Methods ------------------------------------------------------------------------------------ Public Methods // Protected Methods ------------------------------------------------------------------------------ Protected Methods // Private Methods ---------------------------------------------------------------------------------- Private Methods // Getters & Setters ------------------------------------------------------------------------------ Getters & Setters public String getId() { return id; } public void setId(String id) { this.id = id; } public Map getMapField() { return mapField; } public void setMapField(Map mapField) { this.mapField = mapField; } } // end of class
mit
pentestershubham/Playstack
Playstack Android Application/Playstack/Task/com/main/TaskSelectiveStatus.java
845
package com.main; import java.util.HashMap; import java.util.Map; import com.shubham.server.main.WSBaseTask; import com.shubham.service.MyService; public class TaskSelectiveStatus implements WSBaseTask{ Map<String, Boolean> list = new HashMap<>(); @Override public Object work(String[] args) { list.clear(); list.put("home", true); list.put("download", true); list.put("music", MyService.database.getBoolean("music")); list.put("gallery", MyService.database.getBoolean("gallery")); list.put("contact", MyService.database.getBoolean("contacts")); list.put("call-log", MyService.database.getBoolean("call_log")); list.put("file", MyService.database.getBoolean("file")); list.put("app", MyService.database.getBoolean("app")); list.put("sms", MyService.database.getBoolean("sms")); return list; } }
mit
mmithril/XChange
xchange-atlasats/src/test/java/org/knowm/xchange/atlasats/AtlasJacksonConfigureListener.java
423
package org.knowm.xchange.atlasats; import si.mazi.rescu.serialization.jackson.JacksonConfigureListener; import com.fasterxml.jackson.core.JsonParser.Feature; import com.fasterxml.jackson.databind.ObjectMapper; public class AtlasJacksonConfigureListener implements JacksonConfigureListener { @Override public void configureObjectMapper(ObjectMapper arg0) { arg0.configure(Feature.ALLOW_COMMENTS, true); } }
mit