hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
b98c3fe45760983480657437bd76f809da0e1d16
5,784
package de.xstampp.service.project.service.data; import java.sql.Timestamp; import java.time.Instant; import java.util.List; import java.util.Map; import java.util.UUID; import de.xstampp.service.project.data.entity.User; import de.xstampp.service.project.service.dao.iface.IUserDAO; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import de.xstampp.common.dto.mock.Filter; import de.xstampp.common.service.SecurityService; import de.xstampp.service.project.data.dto.ConversionRequestDTO; import de.xstampp.service.project.data.entity.EntityDependentKey; import de.xstampp.service.project.data.entity.Conversion; import de.xstampp.service.project.service.dao.iface.ILastIdDAO; import de.xstampp.service.project.service.dao.iface.IConversionDAO; import de.xstampp.service.project.service.dao.iface.SortOrder; @Service @Transactional public class ConversionDataService { @Autowired IConversionDAO conversionDAO; @Autowired SecurityService security; @Autowired ILastIdDAO lastIdDAO; @Autowired IUserDAO userDAO; /** * Generates a new Conversion with a new ID and the given parameters * * @param request the conversion request DTO with the parameters to set * @param projectId the assigned project ID * @param actuatorId the assigned actuator ID * @return returns the new Conversion */ public Conversion createConversion(ConversionRequestDTO request, UUID projectId, int actuatorId) { int conversionId = lastIdDAO.getNewIdForConversion(projectId, actuatorId); Conversion conversion = new Conversion(new EntityDependentKey(projectId, actuatorId, conversionId)); conversion.setConversion(request.getConversion()); conversion.setControlActionId(request.getControlActionId()); conversion.setLastEditNow(security.getContext().getUserId()); userDAO.makePersistent(new User(security.getContext().getUserId(), security.getContext().getDisplayName())); conversion.setState(request.getState()); Conversion result = conversionDAO.makePersistent(conversion); return result; } /** * Edits an existing conversion * * @param request the new conversion containing all attributes including the * edited values * @param conversionId the ID of the existing conversion to be edited * @param actuatorId the ID of the assigned actuator * @param projectId the project ID of the assigned process * @return returns the edited conversion including all changes */ public Conversion editConversion(ConversionRequestDTO request, UUID projectId, int actuatorId, int conversionId) { Conversion conversion = new Conversion(new EntityDependentKey(projectId, actuatorId, conversionId)); conversion.setConversion(request.getConversion()); conversion.setControlActionId(request.getControlActionId()); conversion.setLastEditNow(security.getContext().getUserId()); userDAO.makePersistent(new User(security.getContext().getUserId(), security.getContext().getDisplayName())); conversion.setState(request.getState()); conversion.setLockExpirationTime(Timestamp.from(Instant.now())); Conversion result = conversionDAO.updateExisting(conversion); return result; } /** * deletes a conversion * * @param conversionId the conversion ID * @param actuatorId the actuator ID * @param projectId the assigned project ID * @return returns true if the conversion was deleted successfully */ public boolean deleteConversion(UUID projectId, int actuatorId, int conversionId) { EntityDependentKey key = new EntityDependentKey(projectId, actuatorId, conversionId); Conversion conversion = conversionDAO.findById(key, false); if (conversion != null) { conversionDAO.makeTransient(conversion); return true; } return false; } /** * Get Conversion by id * * @param conversionId the conversion ID * @param projectId the project ID * @param actuatorId the actuator ID * @return the conversion for the given ID */ public Conversion getConversionById(UUID projectId, int actuatorId, int conversionId) { EntityDependentKey key = new EntityDependentKey(projectId, actuatorId, conversionId); return conversionDAO.findById(key, false); } /** * returns a list of conversions paged by the given parameters * * @param projectId the assigned project ID * @param actuatorId the assigned actuator ID * @param filter currently not used * @param orderBy the parameter name for which the result should be * ordered * @param orderDirection the order direction (ASC or DESC) * @param amount returns only the first X results * @param from skips the first X results * @return returns a list of conversions filtered by the given criteria */ public List<Conversion> getAllConversions(UUID projectId, int actuatorId, Filter filter, String orderBy, SortOrder orderDirection, Integer amount, Integer from) { Map<String, SortOrder> sortOrder = Map.of(orderBy, SortOrder.ASC); if (amount != null && from != null) { return conversionDAO.getConversionsByActuatorId(projectId, actuatorId, amount, from); } else { return conversionDAO.getConversionsByActuatorId(projectId, actuatorId, 0, 1000); } } }
41.314286
134
0.705048
04bc78bd0b36c1abdf22b0b742117e0f2dbf1134
1,764
/****************************************************************** * File: ValueGeoPoint.java * Created by: Dave Reynolds * Created on: 1 Dec 2014 * * (c) Copyright 2014, Epimorphics Limited * *****************************************************************/ package com.epimorphics.dclib.values; import com.epimorphics.geo.GeoPoint; import org.apache.jena.graph.Node; /** * A value which represents a geographic point. * Should normally only be used within expressions not returned as a final binding. * * @author <a href="mailto:dave@epimorphics.com">Dave Reynolds</a> */ public class ValueGeoPoint extends ValueBase<GeoPoint> { public ValueGeoPoint(GeoPoint value) { super(value); } @Override public Node asNode() { // No default RDF mapping return null; } @Override public String getDatatype() { // No default RDF mapping return null; } public Value getEasting() { return new ValueNumber( value.getEasting() ); } public Value getNorthing() { return new ValueNumber( value.getNorthing() ); } public Value getLat() { return new ValueNumber( value.getLat() ); } public Value getLon() { return new ValueNumber( value.getLon() ); } public Value getLatLiteral() { return new ValueNode( value.getLatLiteral().asNode() ); } public Value getLonLiteral() { return new ValueNode( value.getLonLiteral().asNode() ); } public Value getGridRef() { return new ValueString( value.getGridRefString() ); } public Value getGridRef(int digits) { return new ValueString( value.getGridRefString(digits) ); } }
24.5
83
0.577098
05c05288c1ea111649b08ca5bab0438d3b7e1960
6,815
package org.recap.repository.jpa; import org.apache.commons.lang3.time.DateUtils; import org.junit.Test; import org.recap.BaseTestCase; import org.recap.model.jpa.BibliographicEntity; import org.recap.model.jpa.HoldingsEntity; import org.recap.model.jpa.ItemEntity; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import java.util.Arrays; import java.util.Date; import java.util.List; import java.util.Random; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; /** * Created by pvsubrah on 6/21/16. */ public class BibliographicDetailsRepositoryUT extends BaseTestCase { @Autowired BibliographicDetailsRepository bibliographicDetailsRepository; @Autowired HoldingsDetailsRepository holdingsDetailsRepository; @Autowired ItemDetailsRepository itemDetailsRepository; @PersistenceContext private EntityManager entityManager; @Test public void saveAndFindBibHoldingsItemEntity() throws Exception { assertNotNull(bibliographicDetailsRepository); assertNotNull(holdingsDetailsRepository); assertNotNull(entityManager); Random random = new Random(); String owningInstitutionBibId = String.valueOf(random.nextInt()); int owningInstitutionId = 1; Page<BibliographicEntity> byOwningInstitutionId = bibliographicDetailsRepository.findByOwningInstitutionIdAndIsDeletedFalse(PageRequest.of(0, 10), owningInstitutionId); BibliographicEntity bibliographicEntity = new BibliographicEntity(); bibliographicEntity.setContent("Mock Bib Content".getBytes()); bibliographicEntity.setCreatedDate(new Date()); bibliographicEntity.setCreatedBy("etl"); bibliographicEntity.setLastUpdatedBy("etl"); bibliographicEntity.setLastUpdatedDate(new Date()); bibliographicEntity.setOwningInstitutionBibId(owningInstitutionBibId); bibliographicEntity.setOwningInstitutionId(owningInstitutionId); bibliographicEntity.setDeleted(false); HoldingsEntity holdingsEntity = new HoldingsEntity(); holdingsEntity.setContent("mock holdings".getBytes()); holdingsEntity.setCreatedDate(new Date()); holdingsEntity.setCreatedBy("etl"); holdingsEntity.setLastUpdatedDate(new Date()); holdingsEntity.setLastUpdatedBy("etl"); holdingsEntity.setOwningInstitutionId(owningInstitutionId); holdingsEntity.setOwningInstitutionHoldingsId(String.valueOf(random.nextInt())); holdingsEntity.setOwningInstitutionId(1); ItemEntity itemEntity = new ItemEntity(); itemEntity.setCallNumberType("0"); itemEntity.setCallNumber("callNum"); itemEntity.setCreatedDate(new Date()); itemEntity.setCreatedBy("etl"); itemEntity.setLastUpdatedDate(new Date()); itemEntity.setLastUpdatedBy("etl"); itemEntity.setBarcode("1231"); itemEntity.setOwningInstitutionItemId(".i1231"); itemEntity.setOwningInstitutionId(1); itemEntity.setCollectionGroupId(1); itemEntity.setCustomerCode("PA"); itemEntity.setItemAvailabilityStatusId(1); itemEntity.setImsLocationId(1); itemEntity.setHoldingsEntities(Arrays.asList(holdingsEntity)); bibliographicEntity.setHoldingsEntities(Arrays.asList(holdingsEntity)); bibliographicEntity.setItemEntities(Arrays.asList(itemEntity)); BibliographicEntity savedBibliographicEntity = bibliographicDetailsRepository.saveAndFlush(bibliographicEntity); entityManager.refresh(savedBibliographicEntity); // assertNotNull(savedBibliographicEntity); // assertNotNull(savedBibliographicEntity.getBibliographicId()); Long countByOwningInstitutionIdAfterAdd = bibliographicDetailsRepository.countByOwningInstitutionIdAndIsDeletedFalse(owningInstitutionId); assertTrue(countByOwningInstitutionIdAfterAdd > byOwningInstitutionId.getTotalElements()); List<BibliographicEntity> byOwningInstitutionBibId = bibliographicDetailsRepository.findByOwningInstitutionBibId(owningInstitutionBibId); assertNotNull(byOwningInstitutionBibId); assertTrue(byOwningInstitutionBibId.size() > 0); BibliographicEntity byOwningInstitutionIdAndOwningInstitutionBibId = bibliographicDetailsRepository.findByOwningInstitutionIdAndOwningInstitutionBibIdAndIsDeletedFalse(owningInstitutionId, owningInstitutionBibId); assertNotNull(byOwningInstitutionIdAndOwningInstitutionBibId); /*BibliographicPK bibliographicPK = new BibliographicPK(); bibliographicPK.setOwningInstitutionId(owningInstitutionId); bibliographicPK.setOwningInstitutionBibId(owningInstitutionBibId); BibliographicEntity entity = bibliographicDetailsRepository.getOne(bibliographicPK); assertNotNull(entity); */ assertNotNull(holdingsDetailsRepository); HoldingsEntity savedHoldingsEntity = savedBibliographicEntity.getHoldingsEntities().get(0); assertNotNull(savedHoldingsEntity); assertNotNull(savedHoldingsEntity.getId()); HoldingsEntity byHoldingsId = holdingsDetailsRepository.findById(savedHoldingsEntity.getId()).orElse(null); assertNotNull(byHoldingsId); assertNotNull(itemDetailsRepository); ItemEntity savedItemEntity = savedBibliographicEntity.getItemEntities().get(0); assertNotNull(savedItemEntity); assertNotNull(savedItemEntity.getId()); ItemEntity byItemId = itemDetailsRepository.findById(savedItemEntity.getId()).orElse(null); assertNotNull(byItemId); } @Test public void countByOwningInstitutionCode() throws Exception { Long bibCount = bibliographicDetailsRepository.countByOwningInstitutionCodeAndIsDeletedFalse("PUL"); assertNotNull(bibCount); } @Test public void findByLastUpdatedDateAfter() throws Exception { Date fromDate = DateUtils.addDays(new Date(), -1); Page<BibliographicEntity> byCreatedDateAfterAndIsDeletedFalse = bibliographicDetailsRepository.findByLastUpdatedDateAfter(PageRequest.of(0, 10), fromDate); assertNotNull(byCreatedDateAfterAndIsDeletedFalse); } @Test public void findByOwningInstitutionIdAndLastUpdatedDateAfter() throws Exception { Date fromDate = DateUtils.addDays(new Date(), -1); Page<BibliographicEntity> byCreatedDateAfterAndIsDeletedFalse = bibliographicDetailsRepository.findByOwningInstitutionIdAndLastUpdatedDateAfter(PageRequest.of(0, 10), 1, fromDate); assertNotNull(byCreatedDateAfterAndIsDeletedFalse); } }
44.835526
221
0.770213
34ff6b65bea57271f617f607406ed22846c1ea23
826
package org.sekka.api; import org.jetbrains.annotations.Nullable; import org.sekka.api.server.Server; import org.sekka.api.world.World; import java.util.UUID; public final class Sekka { private static Server server; public static final String MOD_ID = "sekka"; public static final String MOD_NAME = "Sekka"; public static final String MOD_VERSION = "0.0.1"; private Sekka() { } public static Server getServer() { return server; } public static World getWorld(@Nullable UUID uuid) { if (server != null && uuid != null) return server.getWorld(uuid); return null; } public static World getWorld(String levelName) { if (server != null && levelName != null && !levelName.isEmpty()) return server.getWorld(levelName); return null; } }
24.294118
107
0.663438
389dd0ff6bcbc43f2b20329c1239010f3431eb5c
1,749
/* * 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 br.com.argonavis.javaeesecurity.facade; import br.com.argonavis.javaeesecurity.entity.Usuario; import java.util.List; import java.util.logging.Logger; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; /** * * @author helderdarocha */ @Stateless public class UsuarioFacade extends AbstractFacade<Usuario> { @PersistenceContext(unitName = "JavaEESecurityPU") private EntityManager em; @Override protected EntityManager getEntityManager() { return em; } public UsuarioFacade() { super(Usuario.class); } public Usuario findByName(String userid) { Query q = em.createQuery("select u from Usuario u where u.userid = :userid", Usuario.class); q.setParameter("userid", userid); return (Usuario)q.getSingleResult(); } public List<Usuario> findByNames(String[] names) { StringBuilder builder = new StringBuilder(); builder.append("("); for(int i = 0; i < names.length; i++) { builder.append("'").append(names[i]).append("'"); if(i < names.length-1) { builder.append(","); } } builder.append(")"); String inclause = builder.toString(); return em.createQuery("select u from Usuario u where u.userid in"+inclause, Usuario.class).getResultList(); } private static final Logger LOG = Logger.getLogger(UsuarioFacade.class.getName()); }
30.155172
115
0.656375
a3ba091e7dffe7d0442b8e8b9508dec0e2c5aeec
4,581
/* * Copyright (c) 2011-2017, Numdata BV, The Netherlands. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of Numdata nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL NUMDATA BV BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.numdata.jnlp; import javax.xml.stream.*; /** * Describes an additional piece of related content, such as a readme * file, help pages, or links to registration pages. The application is * asking that this content be included in its desktop integration. * * @author Peter S. Heijnen */ public class JnlpRelatedContent extends JnlpElement { /** * Reference to the related content. */ private String _href = null; /** * Name of the related content. */ private String _title = null; /** * A short description of the related content. */ private String _description = null; /** * Icon that can be used to identify the related content to the user. */ private JnlpIcon _icon = null; /** * Get reference to the related content. * * @return Reference to the related content. */ public String getHref() { return _href; } /** * Get reference to the related content. * * @param href Reference to the related content. */ public void setHref( final String href ) { _href = href; } /** * Get name of related content. * * @return Name of related content. */ public String getTitle() { return _title; } /** * Get name of related content. * * @param title Name of related content. */ public void setTitle( final String title ) { _title = title; } /** * Get name of related content. * * @return Name of related content. */ public String getDescription() { return _description; } /** * Get name of related content. * * @param description Name of related content. */ public void setDescription( final String description ) { _description = description; } /** * Get icon to identify related content to the user. * * @return Icon to identify related content to the user. */ public JnlpIcon getIcon() { return _icon; } /** * Get icon to identify related content to the user. * * @param icon Icon to identify related content to the user. */ public void setIcon( final JnlpIcon icon ) { _icon = icon; } @Override public void write( final XMLStreamWriter out ) throws XMLStreamException { final String title = getTitle(); final String description = getDescription(); final JnlpIcon icon = getIcon(); final boolean emptyRelatedContentElement = ( title == null ) && ( description == null ) && ( icon == null ); if ( emptyRelatedContentElement ) { out.writeEmptyElement( "related-content" ); } else { out.writeStartElement( "related-content" ); } writeMandatoryAttribute( out, "href", getHref() ); writeOptionalTextElement( out, "title", title ); writeOptionalTextElement( out, "description", description ); if ( icon != null ) { icon.write( out ); } if ( !emptyRelatedContentElement ) { out.writeEndElement(); } } @Override public void read( final XMLStreamReader in ) throws XMLStreamException { throw new UnsupportedOperationException( "Not implemented yet." ); } }
25.032787
110
0.695263
b4a01282e809bee3a41e999fc10311840c4f9e22
387
// Sort Colors // Counting Sort // 时间复杂度O(n),空间复杂度O(1) public class Solution { public void sortColors(int[] nums) { int[] counts = new int[3]; // 记录每个颜色出现的次数 for (int i = 0; i < nums.length; i++) counts[nums[i]]++; for (int i = 0, index = 0; i < 3; i++) for (int j = 0; j < counts[i]; j++) nums[index++] = i; } }
24.1875
49
0.475452
a36fdf9308e4aa333788f5f273486dea962c7a79
1,164
package coding.challenge; import coding.challenge.filesystem.Directory; import coding.challenge.filesystem.File; public class Main { public static void main(String[] args) { /* D:/ | ----Docs | | | ----summer.txt | ----winter.txt ----Today | ----spring.txt */ Directory root = new Directory("D", null); Directory docs = new Directory("Docs", root); Directory today = new Directory("Today", root); File doc1 = new File("summer.txt", docs); File doc2 = new File("winter.txt", docs); File doc3 = new File("spring.txt", today); doc1.setContent("This is a summer doc"); doc2.setContent("This is a winter doc done last year"); doc3.setContent("This is a spring doc done today"); System.out.println("D root full path: " + root.getFullPath()); System.out.println("Docs directory full path: " + docs.getFullPath()); System.out.println("doc3.txt file full path: " + doc3.getFullPath()); } }
29.1
78
0.531787
22b98441646a5e28abbf684a43a2ce6402dc9653
1,492
/* * 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 com.cse.StudyCafe_management_system.server; import java.io.*; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author anht0 */ public class Server_SalesSearch implements SearchInformation { @Override public ArrayList<String> infoSearch(){ ArrayList<String> resultFile = new ArrayList<>(); try { <<<<<<< HEAD FileInputStream input=new FileInputStream("C:\\Users\\anht0\\Pay.txt"); ======= FileInputStream input=new FileInputStream("./Pay.txt"); >>>>>>> origin/hyeontaek InputStreamReader reader=new InputStreamReader(input,"UTF-8"); BufferedReader br =new BufferedReader(reader); // BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\anht0\\Pay.txt")); while (true) { String line = br.readLine(); if (line == null) { break; } resultFile.add(line); } br.close(); } catch (FileNotFoundException e) { System.out.println("파일이 없습니다!"); } catch (IOException ex) { Logger.getLogger(Server_SalesSearch.class.getName()).log(Level.SEVERE, null, ex); } return resultFile; } }
32.434783
98
0.607239
4d79b1a053ca5442a9e5e18c986eaed710384176
1,072
package de.codecentric.reedelk.platform.module.deserializer; import org.osgi.framework.Bundle; import java.net.URL; import java.util.Collections; import java.util.Enumeration; import java.util.List; public class BundleDeserializer extends AbstractModuleDeserializer { private static final boolean RECURSIVE = true; private final Bundle bundle; public BundleDeserializer(Bundle bundle) { this.bundle = bundle; } @Override protected List<URL> getResources(String directory) { return getResourcesWithFilePattern(directory, "*"); } @Override protected List<URL> getResources(String directory, String fileExtension) { return getResourcesWithFilePattern(directory, "*." + fileExtension); } private List<URL> getResourcesWithFilePattern(String directory, String filePattern) { Enumeration<URL> entryPaths = bundle.findEntries(directory, filePattern, RECURSIVE); return entryPaths == null ? Collections.emptyList() : Collections.list(entryPaths); } }
28.972973
92
0.715485
b46a8d64dd2102847387ad2d92c019a3be4189b2
1,607
package net.naari3.offershud.mixin; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import net.naari3.offershud.OffersHUD; import net.naari3.offershud.MerchantInfo; import net.fabricmc.fabric.api.client.networking.v1.ClientPlayNetworking; import net.minecraft.client.network.ClientPlayNetworkHandler; import net.minecraft.network.packet.c2s.play.CloseHandledScreenC2SPacket; import net.minecraft.network.packet.s2c.play.OpenScreenS2CPacket; import net.minecraft.network.packet.s2c.play.SetTradeOffersS2CPacket; import net.minecraft.screen.ScreenHandlerType; @Mixin(ClientPlayNetworkHandler.class) abstract class ReceiveTradeOfferPacket { @Inject(at = @At("HEAD"), method = "onSetTradeOffers", cancellable = true) public void onSetTradeOffers(SetTradeOffersS2CPacket packet, CallbackInfo ci) { MerchantInfo.getInfo().setOffers(packet.getOffers()); if (!OffersHUD.getOpenWindow()) { ci.cancel(); } } @Inject(at = @At("HEAD"), method = "onOpenScreen", cancellable = true) public void onOpenScreen(OpenScreenS2CPacket packet, CallbackInfo ci) { var type = packet.getScreenHandlerType(); if (!OffersHUD.getOpenWindow() && type == ScreenHandlerType.MERCHANT) { ci.cancel(); ClientPlayNetworking.getSender() .sendPacket(new CloseHandledScreenC2SPacket(packet.getSyncId())); } } }
42.289474
86
0.729932
d9629f975f793fa3b08c9346a5fa1a847793649e
4,048
/** * Copyright (C) 2011-2020 Red Hat, Inc. (https://github.com/Commonjava/indy) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.commonjava.indy.subsys.cassandra.config; import org.commonjava.indy.conf.IndyConfigInfo; import org.commonjava.propulsor.config.annotation.ConfigName; import org.commonjava.propulsor.config.annotation.SectionName; import javax.enterprise.context.ApplicationScoped; import java.io.InputStream; @SectionName( "cassandra" ) @ApplicationScoped public class CassandraConfig implements IndyConfigInfo { private Boolean enabled = Boolean.FALSE; private String cassandraHost; private Integer cassandraPort; private String cassandraUser; private String cassandraPass; private int connectTimeoutMillis = 60000; private int readTimeoutMillis = 60000; private int readRetries = 3; private int writeRetries = 3; public CassandraConfig() { } public Boolean isEnabled() { return enabled; } @ConfigName( "enabled" ) public void setEnabled( Boolean enabled ) { this.enabled = enabled; } private static final String DEFAULT_CASSANDRA_HOST = "localhost"; private static final int DEFAULT_CASSANDRA_PORT = 9042; @ConfigName( "cassandra.host" ) public void setCassandraHost( String host ) { cassandraHost = host; } @ConfigName( "cassandra.port" ) public void setCassandraPort( Integer port ) { cassandraPort = port; } @ConfigName( "cassandra.user" ) public void setCassandraUser( String cassandraUser ) { this.cassandraUser = cassandraUser; } @ConfigName( "cassandra.pass" ) public void setCassandraPass( String cassandraPass ) { this.cassandraPass = cassandraPass; } public String getCassandraHost() { return cassandraHost == null ? DEFAULT_CASSANDRA_HOST : cassandraHost; } public Integer getCassandraPort() { return cassandraPort == null ? DEFAULT_CASSANDRA_PORT : cassandraPort; } public String getCassandraUser() { return cassandraUser; } public String getCassandraPass() { return cassandraPass; } public int getConnectTimeoutMillis() { return connectTimeoutMillis; } @ConfigName( "cassandra.connect.timeout.millis" ) public void setConnectTimeoutMillis( int connectTimeoutMillis ) { this.connectTimeoutMillis = connectTimeoutMillis; } public int getReadTimeoutMillis() { return readTimeoutMillis; } @ConfigName( "cassandra.read.timeout.millis" ) public void setReadTimeoutMillis( int readTimeoutMillis ) { this.readTimeoutMillis = readTimeoutMillis; } public int getReadRetries() { return readRetries; } @ConfigName( "cassandra.read.retries" ) public void setReadRetries( int readRetries ) { this.readRetries = readRetries; } public int getWriteRetries() { return writeRetries; } @ConfigName( "cassandra.write.retries" ) public void setWriteRetries( int writeRetries ) { this.writeRetries = writeRetries; } @Override public String getDefaultConfigFileName() { return "default-cassandra.conf"; } @Override public InputStream getDefaultConfig() { return Thread.currentThread().getContextClassLoader().getResourceAsStream( "default-cassandra.conf" ); } }
24.095238
110
0.681324
8d60cb3ea41d1f9f59d967e1f77f11ffca509f82
1,342
package com.nd.android.rxjavademo.data.impl.schedulers; import android.content.Context; import android.content.Intent; import android.support.annotation.StringRes; import com.nd.android.rxjavademo.R; import com.nd.android.rxjavademo.activity.schedulers.SchedulersActivity; import com.nd.android.rxjavademo.data.IMainListData; /** * MainListData_Schedulers * <p/> * Created by HuangYK on 16/8/30. */ public class MainListData_Schedulers implements IMainListData { @Override @StringRes public int getMainTitle() { return R.string.str_mainlist_schedulers; } @Override public int getSubTitle() { return R.string.str_mainlist_schedulers; } @Override public void starActivity(Context context) { Intent intent = new Intent(context, SchedulersActivity.class); context.startActivity(intent); } // @Override // public int compareTo(@NonNull Object another) { // if (!(another instanceof IMainListData)) { // return 1; // } // IMainListData anotherData = (IMainListData) another; // // if (this.getSubTitle() > anotherData.getSubTitle()) { // return 1; // } else if (this.getSubTitle() < anotherData.getSubTitle()) { // return -1; // } else { // return 0; // } // } }
26.313725
72
0.652757
11f28256a20f1036066d9390b62597c30d4dcd77
7,972
package ml.bigbrains.tinkoff.tinkoffe3capiclient; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.extern.slf4j.Slf4j; import ml.bigbrains.tinkoff.tinkoffe3capiclient.model.*; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.utils.URIBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import ru.CryptoPro.JCP.JCP; import ru.tinkoff.crypto.mapi.CryptoMapi; import ru.tinkoff.crypto.mapi.RsaCryptoMapi; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.security.*; import java.security.spec.PKCS8EncodedKeySpec; import java.util.ArrayList; import java.util.Base64; import java.util.List; import java.util.Map; @Slf4j public class TinkoffClient { private String baseUrl; public TinkoffClient(String baseUrl) { this.baseUrl = baseUrl; } public void signed(SignedRequest signedRequest, String keyStoreInstanceName, String keyName, String x509SerialNumber) { CryptoMapi crypto = new CryptoMapi(); String data = crypto.concatValues(signedRequest.getMapForSign()); byte[] digestData = null; byte[] signature = null; try { digestData = crypto.calcDigest(JCP.GOST_DIGEST_2012_256_NAME, data.getBytes(Charset.forName("UTF-8"))); KeyStore store = KeyStore.getInstance(keyStoreInstanceName); store.load(null, null); Key test = store.getKey(keyName, null); signature = crypto.calcSignature(JCP.GOST_EL_SIGN_NAME, (PrivateKey) test, digestData); } catch (Exception e) { log.error("Error in calc digest or sign for request",e); } signedRequest.setDigestValue( Base64.getEncoder().encodeToString(digestData)); signedRequest.setSignatureValue(Base64.getEncoder().encodeToString( signature)); signedRequest.setX509SerialNumber(x509SerialNumber); } public void signedRSA(SignedRequest signedRequest, String publicKeyBase64, String x509SerialNumber) { RsaCryptoMapi crypto = new RsaCryptoMapi(); String data = crypto.concatValues(signedRequest.getMapForSign()); byte[] digestData = null; byte[] signature = null; try { final PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(org.apache.commons.codec.binary.Base64.decodeBase64(publicKeyBase64)); PrivateKey privateKey = KeyFactory.getInstance("RSA").generatePrivate(pkcs8EncodedKeySpec); digestData = crypto.calcDigest(data.getBytes(StandardCharsets.UTF_8)); signature = crypto.calcSignature(privateKey, digestData); } catch (Exception e) { log.error("Error in calc RSA digest or sign for request",e); } signedRequest.setDigestValue( Base64.getEncoder().encodeToString(digestData)); signedRequest.setSignatureValue(Base64.getEncoder().encodeToString( signature)); signedRequest.setX509SerialNumber(x509SerialNumber); } public GenericResponse post(String url, SignedRequest request) throws IOException { try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) { log.debug("Делаем POST запрос в TINKOFF по адресу: "+baseUrl+"/e2c/"+url); URIBuilder builder = new URIBuilder(baseUrl).setPath("/e2c/"+url); URI uri = builder.build(); HttpPost httpPost = new HttpPost(uri); List<NameValuePair> params = new ArrayList<>(); for(Map.Entry<String,String> param: request.getAllParams().entrySet()) { params.add(new BasicNameValuePair(param.getKey(), param.getValue())); } httpPost.setHeader("Content-type","application/x-www-form-urlencoded"); httpPost.setEntity(new UrlEncodedFormEntity(params)); log.debug("URI: "+httpPost.getURI()); log.debug("HttpEntry: "+httpPost.getEntity()); CloseableHttpResponse httpResponse = httpClient.execute(httpPost); String entity = EntityUtils.toString(httpResponse.getEntity()); if (httpResponse.getStatusLine().getStatusCode() != 200) { log.error("Ошибка в ответе на запрос: "+httpResponse.toString()); } ObjectMapper mapper = new ObjectMapper(); return mapper.readValue(entity, GenericResponse.class); } catch (URISyntaxException e) { log.error("Ошибка в построении запроса",e); return null; } } public List<GetCardListResponse> postGetCardList(SignedRequest request) throws IOException { try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) { URIBuilder builder = new URIBuilder(baseUrl).setPath("/e2c/GetCardList"); URI uri = builder.build(); HttpPost httpPost = new HttpPost(uri); List<NameValuePair> params = new ArrayList<>(); for(Map.Entry<String,String> param: request.getAllParams().entrySet()) { params.add(new BasicNameValuePair(param.getKey(), param.getValue())); } httpPost.setHeader("Content-type","application/x-www-form-urlencoded"); httpPost.setEntity(new UrlEncodedFormEntity(params)); log.debug("URI: "+httpPost.getURI()); log.debug("HttpEntry: "+httpPost.getEntity()); CloseableHttpResponse httpResponse = httpClient.execute(httpPost); String entity = EntityUtils.toString(httpResponse.getEntity()); if (httpResponse.getStatusLine().getStatusCode() != 200) { log.error("Ошибка в ответе на запрос: "+httpResponse.toString()); } ObjectMapper mapper = new ObjectMapper(); return mapper.readValue(entity, mapper.getTypeFactory().constructCollectionType(List.class, GetCardListResponse.class)); } catch (URISyntaxException e) { log.error("Ошибка в построении запроса",e); return null; } } public GetAccountInfoResponse postAccountInfo(SignedRequest request) throws IOException { try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) { URIBuilder builder = new URIBuilder(baseUrl).setPath("/e2c/"+"GetAccountInfo"); URI uri = builder.build(); HttpPost httpPost = new HttpPost(uri); List<NameValuePair> params = new ArrayList<>(); for(Map.Entry<String,String> param: request.getAllParams().entrySet()) { params.add(new BasicNameValuePair(param.getKey(), param.getValue())); } httpPost.setHeader("Content-type","application/x-www-form-urlencoded"); httpPost.setEntity(new UrlEncodedFormEntity(params)); log.debug("URI: "+httpPost.getURI()); log.debug("HttpEntry: "+httpPost.getEntity()); CloseableHttpResponse httpResponse = httpClient.execute(httpPost); String entity = EntityUtils.toString(httpResponse.getEntity()); if (httpResponse.getStatusLine().getStatusCode() != 200) { log.error("Ошибка в ответе на запрос: "+httpResponse.toString()); } ObjectMapper mapper = new ObjectMapper(); return mapper.readValue(entity, GetAccountInfoResponse.class); } catch (URISyntaxException e) { log.error("Ошибка в построении запроса",e); return null; } } }
43.802198
154
0.666332
f35101a0499961db722ba45cfe6b1ecd0cbd40ef
4,057
/* * Copyright (C) 2012 Google Inc. * tracksPlayed * 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 interactivespaces.service.audio.player.jukebox; import interactivespaces.configuration.Configuration; import interactivespaces.service.audio.player.AudioRepository; import interactivespaces.service.audio.player.AudioTrackPlayer; import interactivespaces.service.audio.player.AudioTrackPlayerFactory; import interactivespaces.service.audio.player.PlayableAudioTrack; import org.apache.commons.logging.Log; import java.util.Collection; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; /** * A {@link JukeboxOperation} which shuffles from the repository. * * @author Keith M. Hughes */ public class ShuffleJukeboxOperation extends BaseJukeboxOperation { /** * The shuffle is running. */ private boolean isRunning; /** * Tracks which have already been played. */ private Collection<PlayableAudioTrack> tracksAlreadyPlayed; /** * Music repository to get a new track. */ private AudioRepository musicRepository; /** * The track player for the track */ private AudioTrackPlayer player; /** * Current track being played. */ private PlayableAudioTrack currentTrack; /** * The runnable which will check on the track player. */ private Runnable runnable; /** * Handle for periodic task scanning the player. */ private ScheduledFuture<?> playingFuture; public ShuffleJukeboxOperation(Collection<PlayableAudioTrack> tracksAlreadyPlayed, Configuration configuration, AudioRepository musicRepository, AudioTrackPlayerFactory trackPlayerFactory, ScheduledExecutorService executor, AudioJukeboxListener listener, Log log) { super(configuration, trackPlayerFactory, executor, listener, log); this.tracksAlreadyPlayed = tracksAlreadyPlayed; this.musicRepository = musicRepository; isRunning = false; runnable = new Runnable() { @Override public void run() { checkPlayer(); } }; } @Override public synchronized void start() { log.info("Starting music jukebox shuffle play"); if (!isRunning) { playingFuture = executor.scheduleAtFixedRate(runnable, 0, 500, TimeUnit.MILLISECONDS); isRunning = true; } } @Override public void pause() { log.warn("Currently no way to pause playing"); } @Override public synchronized void stop() { log.info("Stopping music jukebox shuffle play " + isRunning); if (isRunning) { playingFuture.cancel(true); if (player != null && player.isPlaying()) { player.stop(); player = null; } isRunning = false; } } @Override public synchronized boolean isRunning() { return isRunning; } /** * Check how the player is doing. */ private synchronized void checkPlayer() { if (player != null) { if (player.isPlaying()) { return; } else { player = null; listener.onJukeboxTrackStop(this, currentTrack); } } try { currentTrack = musicRepository.getRandomTrack(tracksAlreadyPlayed); tracksAlreadyPlayed.add(currentTrack); player = trackPlayerFactory.newTrackPlayer(currentTrack, configuration, log); player.start(0, 0); listener.onJukeboxTrackStart(this, currentTrack); } catch (Exception e) { log.error(String.format("Could not start up track %s", currentTrack), e); } } }
26.86755
92
0.70668
46db162247016e782193c8e035ff364111ecc3bd
4,995
/* * Licensed under the MIT License * * Copyright (c) 2020 Mahdi Jaberzadeh Ansari * * you may not use this file except in compliance with the License. * * 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.mjzsoft.odata; /** * Runner class is responsible for checking the database tables and if they are empty feeds them based on {Entity}.csv files inside the `resources\mockdata\` directory. */ import com.opencsv.CSVReader; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.reflect.Constructor; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; import com.mjzsoft.odata.repositories.BaseRepository; import com.mjzsoft.odata.services.BaseService; import com.mjzsoft.odata.utils.SpringContextsUtil; @Component public class Runner implements CommandLineRunner { public static final String COMMA_DELIMITER = ","; private static final Logger logger = LoggerFactory.getLogger(Runner.class); private List<BaseService<?>> services; private List<BaseRepository<?, ?>> repositories; @Autowired public Runner(List<BaseService<?>> services, List<BaseRepository<?, ?>> repositories) { this.services = services; // sort the repositories based on their sequences // the sequences are representing the foreign keys dependencies between models // As much as the sequence value is lower, the equivalent model must be fed first. Collections.sort(repositories, (r1, r2) -> { return r1.sequence() - r2.sequence(); }); this.repositories = repositories; } @Override public void run(String... args) throws Exception { for (@SuppressWarnings("rawtypes") BaseRepository repo : repositories) { this.fillRepository(repo); } } @SuppressWarnings({ "rawtypes", "unchecked" }) private void fillRepository(BaseRepository repository) { // checks if the table is empty then if (repository.count() == 0) { // get the related model for that repository Class type = repository.getType(); // if type is not set in the child repository then return if (type == null) return; // try to find the csv file related to the entity model String entityName = type.getSimpleName(); logger.info(entityName + " table in Database is still empty. Adding some sample records from csv file."); try { InputStream inputStream = getClass().getClassLoader() .getResourceAsStream("mockdata/" + entityName + ".csv"); // if it fails to find the csv file will throw an exception if (inputStream == null) { logger.warn("Couldn't find `" + entityName + ".csv` file in the `/resources/mockdata/` folder!"); throw new IllegalArgumentException("file not found! " + entityName + ".csv"); } // otherwise starts to read the csv values and fill the entity InputStreamReader streamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8); BufferedReader bufferedReader = new BufferedReader(streamReader); CSVReader csvReader = new CSVReader(bufferedReader); String[] line; boolean firstLine = true; List<String> columns = null; while ((line = csvReader.readNext()) != null) { String[] values = line; // skip the first line as it is columns name! if (firstLine) { firstLine = false; columns = Arrays.asList(values); continue; } // from the second line of the csv file try { // make an entity Constructor<?> constructor = type.getConstructor(); Object object = constructor.newInstance(); // for each value in the line call the `SpringContextsUtil.updateColumn` static function // to fill the property for (int i = 0; i < values.length && i < columns.size(); i++) { String column = columns.get(i); Object value = values[i]; SpringContextsUtil.updateColumn(type, object, column, value, services); } // commit the changes to DB repository.save(object); } catch (Exception e) { e.printStackTrace(); logger.error("Line " + Thread.currentThread().getStackTrace()[1].getLineNumber() + ": " + e.toString()); break; } } // close the CSV reader stream csvReader.close(); // close the buffer reader stream bufferedReader.close(); } catch (Exception e) { logger.error("Line " + Thread.currentThread().getStackTrace()[1].getLineNumber() + ": " + e.toString()); } } } }
35.935252
170
0.704505
b06582f1e70167608c946a57ac621a83d3dfbc3d
3,049
/* * Copyright 2016 Randy Nott * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.rnott.mock.handler; import java.util.HashMap; import java.util.Map; import org.rnott.mock.Endpoint; import org.rnott.mock.Response; /** * TODO: document ResponseHandler * */ public class ResponseFactory { static Map<String, Class<? extends ResponseHandler>> implementations = new HashMap<String, Class<? extends ResponseHandler>>(); static Map<Endpoint, ResponseHandler> handlers = new HashMap<Endpoint, ResponseHandler>(); // cause handler classes to load so that they register // TODO: automatically discover response handler implementations private static void bootstrap() { Class<?> [] classes = { SequentialResponseHandler.class, RandomResponseHandler.class, RateResponseHandler.class, ParameterMatchingResponseHandler.class }; for ( Class<?> c : classes ) { try { Class.forName( c.getName() ); } catch ( Throwable ignore ) {} } } /** * Register a handler implementation. * <p> * @param key the key to identify the handler (case-insensitive). The endpoint handler attribute * is used to select a handler and must match the key for that handler to be selected. * @param impl the handler class which will be instantiated at most once per endpoint. */ static void register( String key, Class<? extends ResponseHandler> impl ) { implementations.put( key == null ? null : key.toLowerCase(), impl ); } /** * Select one of the configured responses for responding to a request. * <p> * @param endpoint the requested endpoint. * @return the request to respond with or <code>null</code> if no response * is appropriate. */ public static Response getResponse( Endpoint endpoint ) { if ( implementations.size() == 0 ) { bootstrap(); } Response response = null; // find appropriate handler ResponseHandler handler = handlers.get( endpoint ); if ( handler == null ) { String key = endpoint.getHandlerType(); Class<? extends ResponseHandler> impl = implementations.get( key == null ? null : key.toLowerCase() ); if ( impl != null ) { try { handler = impl.newInstance(); handlers.put( endpoint, handler ); } catch ( Throwable t ) {} } } if ( handler != null ) { response = handler.getResponse( endpoint ); } // no response assigned yet so simply use the first one if ( response == null && endpoint.getResponses().size() > 0 ) { response = endpoint.getResponses().get( 0 ); } return response; } }
30.49
105
0.697278
ae3bc7ff60c7e1f6ad14174a77ea5b31eb6e095b
1,013
package com.ruoyi.product.mapper; import com.ruoyi.product.domain.Temperature; import org.apache.ibatis.annotations.Param; import java.util.List; /** * @author chenm * @create 2019-08-02 10:21 */ public interface TemperatureMapper { Integer insertTemperature(Temperature temperature); List<Temperature> selectTemperatureList(Temperature temperature); List<Temperature> selectTemperatureListProductIdIsNull(Temperature temperature); Temperature selectTemperatureById(Long teId); Integer updateTemperature(Temperature temperature); Integer deleteTemperatureByIds(Long[] ids); Integer deleteByproductId(Long productId); public List<Temperature> selectByIds(@Param("ids") String ids); int insertListTemp(@Param("temperatureList")List<Temperature> temperatureList,@Param("productId")Long productId); Temperature selectTemperatureByLineIdLastTime(@Param("lineId") Long lineId); List<Temperature> selectTemperatureTemplate(@Param("lineId") Long lineId); }
28.138889
118
0.7769
0ef32f6347ba8e11e5db7d588eb1fbe0db87bf09
5,515
package com.humane.application; import java.io.ByteArrayInputStream; import java.io.IOException; import com.humane.application.views.database.DatabaseView; import com.vaadin.flow.component.button.Button; import com.vaadin.flow.component.button.ButtonVariant; import com.vaadin.flow.component.charts.model.VerticalAlign; import com.vaadin.flow.component.combobox.ComboBox; import com.vaadin.flow.component.datepicker.DatePicker; import com.vaadin.flow.component.formlayout.FormLayout; import com.vaadin.flow.component.grid.Grid; import com.vaadin.flow.component.grid.HeaderRow; import com.vaadin.flow.component.html.Div; import com.vaadin.flow.component.html.Label; import com.vaadin.flow.component.html.NativeButton; import com.vaadin.flow.component.html.Span; import com.vaadin.flow.component.notification.Notification; import com.vaadin.flow.component.notification.Notification.Position; import com.vaadin.flow.component.orderedlayout.HorizontalLayout; import com.vaadin.flow.component.orderedlayout.VerticalLayout; import com.vaadin.flow.component.textfield.TextField; import com.vaadin.flow.data.binder.Binder; import com.vaadin.flow.data.converter.StringToIntegerConverter; import com.vaadin.flow.server.StreamResource; import org.vaadin.olli.FileDownloadWrapper; public class AnimalForm extends FormLayout { /** * */ private static final long serialVersionUID = 1L; private TextField name = new TextField("Name"); private ComboBox<AnimalStatus> status = new ComboBox<>("Status"); private DatePicker birthDate = new DatePicker("Birthdate"); private ComboBox<DogBreed> breed = new ComboBox<>("Breed"); private TextField weight = new TextField("Weight"); private ComboBox<Gender> gender = new ComboBox<>("Gender"); private ComboBox<Color> color = new ComboBox<>("Color"); private ComboBox<Spayed> spayed = new ComboBox<>("Spayed/Neutered"); private Grid<VaccineRecord> vacGrid = new Grid<>(VaccineRecord.class); private Button save = new Button("Save"); private Button delete = new Button("Delete"); private Button download = new Button("Download"); private Binder<Animal> binder = new Binder<>(Animal.class); private DatabaseView databaseView; private AnimalService service = AnimalService.getInstance(); private FileDownloadWrapper buttonWrapper; public AnimalForm(DatabaseView databaseView) { this.databaseView = databaseView; status.setItems(AnimalStatus.values()); breed.setItems(DogBreed.values()); gender.setItems(Gender.values()); color.setItems(Color.values()); spayed.setItems(Spayed.values()); save.addThemeVariants(ButtonVariant.LUMO_PRIMARY); save.addClickListener(event -> save()); delete.addClickListener(event -> delete()); HorizontalLayout buttons = new HorizontalLayout(save, delete, download); Span content = new Span("Do you want to download?"); NativeButton buttonConfirm = new NativeButton("Yes"); NativeButton buttonClose = new NativeButton("No"); Notification notification = new Notification(content); notification.setDuration(3000); buttonClose.addClickListener(event -> notification.close()); notification.setPosition(Position.MIDDLE); download.addClickListener(event -> download()); download.addClickListener(event -> notification.open()); // File Download Wrapper Initialization try { byte[] animalPdf = CreateRecordPDF.createPDF(new Animal()).toByteArray(); buttonWrapper = new FileDownloadWrapper( new StreamResource("error.pdf", () -> new ByteArrayInputStream(animalPdf))); buttonWrapper.wrapComponent(buttonConfirm); notification.add(buttonWrapper, buttonClose); //buttons.add(buttonWrapper); //download.addClickListener(event-> download(buttonWrapper)); } catch(IOException e) { e.printStackTrace(); } // Label for Vaccine records Label vacLabel = new Label("Vaccine Records"); VerticalLayout vacComp = new VerticalLayout(vacLabel, vacGrid); add(name, status, birthDate, breed, weight, gender, color, spayed, vacComp, buttons); binder.forField(weight) .withConverter(new StringToIntegerConverter("Please enter number")) .bind(Animal::getWeight, Animal::setWeight); binder.bindInstanceFields(this); } public void setAnimal(Animal animal) { binder.setBean(animal); if (animal == null) { setVisible(false); } else { setVisible(true); name.focus(); } } private void save() { Animal animal = binder.getBean(); service.save(animal); databaseView.updateList(); setAnimal(null); } private void delete() { Animal animal = binder.getBean(); service.delete(animal); databaseView.updateList(); setAnimal(null); } private void download() { Animal animal = binder.getBean(); try { byte[] pdf = CreateRecordPDF.createPDF(animal).toByteArray(); buttonWrapper.setResource(new StreamResource(animal.getName()+".pdf", () -> new ByteArrayInputStream(pdf))); // FileDownloadWrapper link = new FileDownloadWrapper("animal.pdf", () -> pdf); } catch(IOException e) { e.printStackTrace(); } } }
39.113475
120
0.690662
48098012256fdbab61f1ae4530e89920984b4f36
474
package optifine; import java.lang.reflect.Field; public class FieldLocatorFixed implements IFieldLocator { private Field field; public FieldLocatorFixed(Field p_i37_1_) { this.field = p_i37_1_; } public Field getField() { return this.field; } } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\optifine\FieldLocatorFixed.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
22.571429
129
0.696203
10f08b51741b62b6e2af0df448b30e4c5e78f214
36,885
package collectors; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.util.Arrays; import housing.Model; /************************************************************************************************** * Class to write output to files * * @author daniel, Adrian Carro * *************************************************************************************************/ public class Recorder { //------------------// //----- Fields -----// //------------------// private String outputFolder; private PrintWriter outfile; private PrintWriter qualityBandPriceFile; // writes the expected price per quality, i.e. adjusted private PrintWriter qualityBandPriceExpectedFile; private PrintWriter HPI; private PrintWriter top10NetTotalWealthShare; private PrintWriter palmerIndex; private PrintWriter numberBankruptcies; private PrintWriter shareEmptyHouses; private PrintWriter BTLMarketShare; private PrintWriter financialWealth; private PrintWriter totalConsumption; private PrintWriter incomeConsumption; private PrintWriter financialConsumption; private PrintWriter grossHousingWealthConsumption; private PrintWriter debtConsumption; private PrintWriter savingDeleveraging; private PrintWriter consumptionToIncome; private PrintWriter ooLTI; private PrintWriter btlLTV; private PrintWriter creditGrowth; private PrintWriter debtToIncome; private PrintWriter ooDebtToIncome; private PrintWriter mortgageApprovals; private PrintWriter housingTransactions; private PrintWriter advancesToFTBs; private PrintWriter advancesToBTL; private PrintWriter advancesToHomeMovers; private PrintWriter priceToIncome; private PrintWriter rentalYield; private PrintWriter housePriceGrowth; private PrintWriter interestRateSpread; private PrintWriter newCredit; private PrintWriter prinRepRegular; private PrintWriter prinRepSale; private PrintWriter ooLTVAboveMedian; private PrintWriter ooLTV; //------------------------// //----- Constructors -----// //------------------------// public Recorder(String outputFolder) { this.outputFolder = outputFolder; } //-------------------// //----- Methods -----// //-------------------// public void openMultiRunFiles(boolean recordCoreIndicators) { // If recording of core indicators is active... if(recordCoreIndicators) { // ...try opening necessary files try { HPI = new PrintWriter(outputFolder + "coreIndicator-HPI.csv", "UTF-8"); top10NetTotalWealthShare = new PrintWriter(outputFolder + "coreIndicator-top10NetTotalWealthShare.csv", "UTF-8"); palmerIndex = new PrintWriter(outputFolder + "coreIndicator-palmerIndex.csv", "UTF-8"); numberBankruptcies = new PrintWriter(outputFolder + "coreIndicator-numberBankruptcies.csv", "UTF-8"); shareEmptyHouses = new PrintWriter(outputFolder + "coreIndicator-shareEmptyHouses.csv", "UTF-8"); BTLMarketShare = new PrintWriter(outputFolder + "coreIndicator-BTLMarketShare.csv", "UTF-8"); financialWealth = new PrintWriter(outputFolder + "coreIndicator-financialWealth.csv", "UTF-8"); totalConsumption = new PrintWriter(outputFolder + "coreIndicator-totalConsumption.csv", "UTF-8"); incomeConsumption = new PrintWriter(outputFolder + "coreIndicator-incomeConsumption.csv", "UTF-8"); financialConsumption = new PrintWriter(outputFolder + "coreIndicator-financialConsumption.csv", "UTF-8"); grossHousingWealthConsumption = new PrintWriter(outputFolder + "coreIndicator-grossHousingWealthConsumption.csv", "UTF-8"); debtConsumption = new PrintWriter(outputFolder + "coreIndicator-debtConsumption.csv", "UTF-8"); savingDeleveraging = new PrintWriter(outputFolder + "coreIndicator-savingDeleveraging.csv", "UTF-8"); consumptionToIncome = new PrintWriter(outputFolder + "coreIndicator-consumptionToIncome.csv", "UTF-8"); ooLTI = new PrintWriter(outputFolder + "coreIndicator-ooLTI.csv", "UTF-8"); btlLTV = new PrintWriter(outputFolder + "coreIndicator-btlLTV.csv", "UTF-8"); creditGrowth = new PrintWriter(outputFolder + "coreIndicator-creditGrowth.csv", "UTF-8"); debtToIncome = new PrintWriter(outputFolder + "coreIndicator-debtToIncome.csv", "UTF-8"); ooDebtToIncome = new PrintWriter(outputFolder + "coreIndicator-ooDebtToIncome.csv", "UTF-8"); mortgageApprovals = new PrintWriter(outputFolder + "coreIndicator-mortgageApprovals.csv", "UTF-8"); housingTransactions = new PrintWriter(outputFolder + "coreIndicator-housingTransactions.csv", "UTF-8"); advancesToFTBs = new PrintWriter(outputFolder + "coreIndicator-advancesToFTB.csv", "UTF-8"); advancesToBTL = new PrintWriter(outputFolder + "coreIndicator-advancesToBTL.csv", "UTF-8"); advancesToHomeMovers = new PrintWriter(outputFolder + "coreIndicator-advancesToMovers.csv", "UTF-8"); priceToIncome = new PrintWriter(outputFolder + "coreIndicator-priceToIncome.csv", "UTF-8"); rentalYield = new PrintWriter(outputFolder + "coreIndicator-rentalYield.csv", "UTF-8"); housePriceGrowth = new PrintWriter(outputFolder + "coreIndicator-housePriceGrowth.csv", "UTF-8"); interestRateSpread = new PrintWriter(outputFolder + "coreIndicator-interestRateSpread.csv", "UTF-8"); ooLTVAboveMedian = new PrintWriter(outputFolder + "coreIndicator-ooLTVAboveMedian.csv", "UTF-8"); ooLTV = new PrintWriter(outputFolder + "coreIndicator-ooLTV.csv", "UTF-8"); } catch (FileNotFoundException | UnsupportedEncodingException e) { e.printStackTrace(); } } } public void openSingleRunFiles(int nRun, boolean recordOutfile, boolean recordQualityBandPrice, int nQualityBands) { // Try opening general output file and write first row header with column names if (recordOutfile) { try { outfile = new PrintWriter(outputFolder + "Output-run" + nRun + ".csv", "UTF-8"); outfile.println("Model time, " // Number of households of each type + "nNonBTLSocialHousing, nFTBSocialHousing, nBTLSocialHousing, nSocialHousing, nRenting, nNonOwner, " + "nInFirstHome, nSSB, " + "nNonBTLOwnerOccupier, nBTLOwnerOccupier, nOwnerOccupier, nActiveBTL, nBTL, nNonBTLBankrupt, " + "nBTLBankrupt, TotalPopulation, " // Numbers of houses of each type + "HousingStock, nNewBuild, nUnsoldNewBuild, nEmptyHouses, BTLStockFraction, " // House sale market data + "Sale HPI, Sale AnnualHPA, Sale AvBidPrice, Sale AvOfferPrice, Sale AvSalePrice, " + "Sale ExAvSalePrice, Sale AvMonthsOnMarket, Sale ExpAvMonthsOnMarket, Sale averageQualitySold, Sale nBuyers, Sale nFTBBuyers, " + "Sale nBTLBuyers, Sale nSellers, Sale nNewSellers, Sale nBTLSellers, Sale nSales, " + "Sale nNonBTLBidsAboveExpAvSalePrice, Sale nBTLBidsAboveExpAvSalePrice, Sale nSalesToBTL, " + "Sale nSalesToFTB, " // Rental market data + "Rental HPI, Rental AnnualHPA, Rental AvBidPrice, Rental AvOfferPrice, Rental AvSalePrice, " + "Rental AvMonthsOnMarket, Rental ExpAvMonthsOnMarket, Rental nBuyers, Rental nSellers, " + "Rental nSales, Rental ExpAvFlowYield, " // Credit data + "nRegisteredMortgages, " //RUBEN additional variables + "MonthlyDisposableIncome, DepositsEndPeriod, " + "BankBalancesVeryBeginningOfPeriod, monthlyTotalGrossIncome, monthlyTotalNetIncome, monthlyGrossEmploymentIncome, monthlyDividendIncome, monthlyTaxesPaid, " + "monthlyInsurancePaid, socialHousingRent, BankBalancesBeforeConsumption, BankBalancesEndowed, " + "totalConsumption, totalIncomeConsumption, totalFinancialWealthConsumption, " + "totalHousingWealthConsumption, totalDebtConsumption, totalSavingForDeleveraging, totalSaving, totalCredit, " + "totalPrincipalRepayment, totalPrincipalRepaymentsDueToHouseSale, totalPrincipalPaidBackForInheritance, totalInterestRepayment, totalRentalPayments, " + "totalBankruptcyCashInjection, totalDebtReliefDueToDeceasedHousehold, " + "creditSupplyTarget, newlyPaidDownPayments, cashPayments, newlyIssuedCredit, nNegativeEquity, " + "LTV FTB, LTV OO, LTV BTL, interestRateSpread, moneyOutflowToConstructionSector, " + "macropruLTVOnOff, medianDebtServiceRatio, medianDebtServiceRatioAdjusted, vulHH medianDSR, vulHH medianDSR adjusted, %vulHH of indebtedHH, medianAge vulHH, medianAge nonVulHH, Top 10% wealth share, " // agent-specific aggregate consumption total and per Agent-class + "activeBTLConsumption, avActiveBTLConsumption, SSBConsumption, avSSBConsumption, " + "inFirstHomeConsumption, avInFirstHomeConsumption, renterConsumption, avRenterConsumption, " // // agent-specific consumption parameters by inducer + "avBTLIncomeConsumption, avBTLFinancialWealthConsumption, avBTLNetHousingWealthConsumption, " + "avSSBIncomeConsumption, avSSBFinancialWealthConsumption, avSSBNetHousingWealthConsumption, " + "avInFirstHomeIncomeConsumption, avInFirstHomeFinancialWealthConsumption, avInFirstHomeNetHousingWealthConsumtpion, " + "avrenterIncomeConsumption, avrenterFinancialWealthConsumption, avRenterNetHousingWealthConsumption, " + "EAD DSR>30%, EAD DSR>35%, EAD DSR>70%, EAD FM with BLC20%, EAD FM with BLC40%, EAD FM with BLC70%, " + "EAD Ampudia (X*BLC 6m), EAD Ampudia (X*medIncome Y*m), HH with less than 1500p, low-deposit HH Consumption, low-deposit HH Saving, " + "nVulHH (X*medIncome Y*m), nVul activeBTL (X*medIncome Y*m), nVul inFirstHome (X*medIncome Y*m), nVul SSB (X*medIncome Y*m), " + "EAD Ampudia aBTL (X*medIncome Y*m), EAD Ampudia inFirstHome (X*medIncome Y*m), EAD Ampudia SSB (X*medIncome Y*m)," // + "unemp nVulHH (70%BLC 24m), unemp nVul activeBTL (70%BLC 24m),unemp nVul inFirstHome (70%BLC 24m), unemp nVul SSB (70%BLC 24m), " // + "unemp EAD Ampudia aBTL (70%BLC 24m), unemp EAD Ampudia inFirstHome (70%BLC 24m), unemp EAD Ampudia SSB (70%BLC 24m)" // the varible names are not consistent with what they measure - this is just to + "nVulHH (DSR>35%), nVul activeBTL (DSR>35%),nVul inFirstHome (DSR>35%), nVul SSB (DSR>35%)," + "totalDebt aBTL (DSR>35%), totalDebt inFirstHome (DSR>35%), totalDebt SSB (DSR>35%)," + "vulnerable by purchase, vulnerable by dissaving, vulnerable by other, non-vulnerable by sale, non-vulnerable by saving, non-vulnerable by other," + "Vulnerable By Purchase BTL, Vulnerable By Purchase SSB, Vulnerable By Purchase InFirstHome," + "Vulnerable By Consumption BTL, Vulnerable By Consumption SSB, Vulnerable By Consumption InFirstHome," + "Vulnerable By Other BTL, Vulnerable By Other SSB, Vulnerable By Other InFirstHome," + "Non-Vulnerable Because Sale BTL, Non-Vulnerable Because Sale SSB, Non-Vulnerable Because Sale InFirstHome, Non-Vulnerable Because Sale Now-Renters," + "Non-Vulnerable Because Saving BTL, Non-Vulnerable Because Saving SSB, Non-Vulnerable Because Saving InFirstHome, Non-Vulnerable Because Saving Now-Renters," + "Non-Vulnerable Because Other BTL, Non-Vulnerable Because Other SSB, Non-Vulnerable Because Other InFirstHome, Non-Vulnerable Because Other Now-Renters," + "nowVul Purchase, nowVul Dissaving, nowVul Other, nowVul Purchase BTL, nowVul Dissaving BTL, nowVul Other BTL," + "nowVul Purchase SSB, nowVul Dissaving SSB, nowVul Other SSB, nowVul Purchase FTB, nowVul Dissaving FTB, nowVul Other FTB" ); } catch (FileNotFoundException | UnsupportedEncodingException e) { e.printStackTrace(); } } // If recording of quality band prices is active... if(recordQualityBandPrice) { // ...try opening output file and write first row header with column names try { qualityBandPriceFile = new PrintWriter(outputFolder + "QualityBandPrice-run" + nRun + ".csv", "UTF-8"); StringBuilder str = new StringBuilder(); str.append(String.format("Time, Q%d", 0)); for (int i = 1; i < nQualityBands; i++) { str.append(String.format(", Q%d", i)); } qualityBandPriceFile.println(str); // .. try opening output file for the adjusted prices per quality and write the first row with column names qualityBandPriceExpectedFile = new PrintWriter(outputFolder + "QualityBandPriceExpected-run" + nRun + ".csv", "UTF-8"); qualityBandPriceExpectedFile.println(str); } catch (FileNotFoundException | UnsupportedEncodingException e) { e.printStackTrace(); } } } public void writeTimeStampResults(boolean recordOutfile, boolean recordCoreIndicators, int time, boolean recordQualityBandPrice) { if (recordCoreIndicators) { // If not at the first point in time... if (time > 0) { // ...write value separation for core indicators (except for time 0) HPI.print(", "); top10NetTotalWealthShare.print(", "); palmerIndex.print(", "); numberBankruptcies.print(", "); shareEmptyHouses.print(", "); BTLMarketShare.print(", "); financialWealth.print(", "); totalConsumption.print(", "); incomeConsumption.print(", "); financialConsumption.print(", "); grossHousingWealthConsumption.print(", "); debtConsumption.print(", "); savingDeleveraging.print(", "); consumptionToIncome.print(", "); ooLTI.print(", "); btlLTV.print(", "); creditGrowth.print(", "); debtToIncome.print(", "); ooDebtToIncome.print(", "); mortgageApprovals.print(", "); housingTransactions.print(", "); advancesToFTBs.print(", "); advancesToBTL.print(", "); advancesToHomeMovers.print(", "); priceToIncome.print(", "); rentalYield.print(", "); housePriceGrowth.print(", "); interestRateSpread.print(", "); ooLTVAboveMedian.print(", "); ooLTV.print(", "); } // Write core indicators results HPI.print(Model.coreIndicators.getHPI()); top10NetTotalWealthShare.print(Model.coreIndicators.getS90TotalNetWealth()); palmerIndex.print(Model.coreIndicators.getPalmerIndex()); numberBankruptcies.print(Model.coreIndicators.getNumberBankruptcies()); shareEmptyHouses.print(Model.coreIndicators.getShareEmptyHouses()); BTLMarketShare.print(Model.coreIndicators.getBTLMarketShare()); financialWealth.print(Model.coreIndicators.getTotalFinancialWealth()); totalConsumption.print(Model.coreIndicators.getTotalConsumption()); incomeConsumption.print(Model.coreIndicators.getTotalIncomeConsumption()); financialConsumption.print(Model.coreIndicators.getTotalFinancialConsumption()); grossHousingWealthConsumption.print(Model.coreIndicators.getTotalGrossHousingWealthConsumption()); debtConsumption.print(Model.coreIndicators.getDebtConsumption()); savingDeleveraging.print(Model.coreIndicators.getSavingForDeleveraging()); consumptionToIncome.print(Model.coreIndicators.getConsumptionOverIncome()); ooLTI.print(Model.coreIndicators.getOwnerOccupierLTIMeanAboveMedian()); btlLTV.print(Model.coreIndicators.getBuyToLetLTVMean()); creditGrowth.print(Model.coreIndicators.getHouseholdCreditGrowth()); debtToIncome.print(Model.coreIndicators.getDebtToIncome()); ooDebtToIncome.print(Model.coreIndicators.getOODebtToIncome()); mortgageApprovals.print(Model.coreIndicators.getMortgageApprovals()); housingTransactions.print(Model.coreIndicators.getHousingTransactions()); advancesToFTBs.print(Model.coreIndicators.getAdvancesToFTBs()); advancesToBTL.print(Model.coreIndicators.getAdvancesToBTL()); advancesToHomeMovers.print(Model.coreIndicators.getAdvancesToHomeMovers()); priceToIncome.print(Model.coreIndicators.getPriceToIncome()); rentalYield.print(Model.coreIndicators.getAvStockYield()); housePriceGrowth.print(Model.coreIndicators.getQoQHousePriceGrowth()); interestRateSpread.print(Model.coreIndicators.getInterestRateSpread()); ooLTVAboveMedian.print(Model.coreIndicators.getOwnerOccupierLTVMeanAboveMedian()); ooLTV.print(Model.coreIndicators.getOwnerOccupierLTVMean()); } // Write general output results to output file if (recordOutfile) { outfile.println(time + ", " + // Number of households of each type Model.householdStats.getnNonBTLHomeless() + ", " + Model.householdStats.getnFTBinSocialHousing() + ", " + Model.householdStats.getnBTLHomeless() + ", " + Model.householdStats.getnHomeless() + ", " + Model.householdStats.getnRenting() + ", " + Model.householdStats.getnNonOwner() + ", " + Model.householdStats.getnInFirstHome() + ", " + Model.householdStats.getnSSB() + ", " + Model.householdStats.getnNonBTLOwnerOccupier() + ", " + Model.householdStats.getnBTLOwnerOccupier() + ", " + Model.householdStats.getnOwnerOccupier() + ", " + Model.householdStats.getnActiveBTL() + ", " + Model.householdStats.getnBTL() + ", " + Model.householdStats.getnNonBTLBankruptcies() + ", " + Model.householdStats.getnBTLBankruptcies() + ", " + Model.households.size() + ", " + // Numbers of houses of each type Model.construction.getHousingStock() + ", " + Model.construction.getnNewBuild() + ", " + Model.housingMarketStats.getnUnsoldNewBuild() + ", " + Model.householdStats.getnEmptyHouses() + ", " + Model.householdStats.getBTLStockFraction() + ", " + // House sale market data Model.housingMarketStats.getHPI() + ", " + Model.housingMarketStats.getAnnualHPA() + ", " + Model.housingMarketStats.getAvBidPrice() + ", " + Model.housingMarketStats.getAvOfferPrice() + ", " + Model.housingMarketStats.getAvSalePrice() + ", " + Model.housingMarketStats.getExpAvSalePrice() + ", " + Model.housingMarketStats.getAvMonthsOnMarket() + ", " + Model.housingMarketStats.getExpAvMonthsOnMarket() + ", " + Model.housingMarketStats.getAverageHouseSaleQuality() + ", " + Model.housingMarketStats.getnBuyers() + ", " + Model.housingMarketStats.getnFTBBuyers() + ", " + Model.housingMarketStats.getnBTLBuyers() + ", " + Model.housingMarketStats.getnSellers() + ", " + Model.housingMarketStats.getnNewSellers() + ", " + Model.housingMarketStats.getnBTLSellers() + ", " + Model.housingMarketStats.getnSales() + ", " + Model.householdStats.getnNonBTLBidsAboveExpAvSalePrice() + ", " + Model.householdStats.getnBTLBidsAboveExpAvSalePrice() + ", " + Model.housingMarketStats.getnSalesToBTL() + ", " + Model.housingMarketStats.getnSalesToFTB() + ", " + // Rental market data Model.rentalMarketStats.getHPI() + ", " + Model.rentalMarketStats.getAnnualHPA() + ", " + Model.rentalMarketStats.getAvBidPrice() + ", " + Model.rentalMarketStats.getAvOfferPrice() + ", " + Model.rentalMarketStats.getAvSalePrice() + ", " + Model.rentalMarketStats.getAvMonthsOnMarket() + ", " + Model.rentalMarketStats.getExpAvMonthsOnMarket() + ", " + Model.rentalMarketStats.getnBuyers() + ", " + Model.rentalMarketStats.getnSellers() + ", " + Model.rentalMarketStats.getnSales() + ", " + Model.rentalMarketStats.getExpAvFlowYield() + ", " + // Credit data Model.creditSupply.getnRegisteredMortgages() + ", " + //RUBEN additional variables Model.householdStats.getTotalMonthlyDisposableIncome() + ", " + Model.householdStats.getTotalBankBalancesEndPeriod() + ", " + Model.householdStats.getTotalBankBalancesVeryBeginningOfPeriod() + ", " + (Model.householdStats.getOwnerOccupierAnnualisedTotalIncome()/Model.config.constants.MONTHS_IN_YEAR + Model.householdStats.getActiveBTLAnnualisedTotalIncome()/Model.config.constants.MONTHS_IN_YEAR + Model.householdStats.getNonOwnerAnnualisedTotalIncome()/Model.config.constants.MONTHS_IN_YEAR) + ", " + (Model.householdStats.getOwnerOccupierMonthlyNetIncome() + Model.householdStats.getActiveMonthlyNetIncome() + Model.householdStats.getNonOwnerMonthlyNetIncome()) + ", " + Model.householdStats.getMonthlyGrossEmploymentIncome() + ", " + Model.householdStats.getMonthlyTotalDividendIncome() + ", " + Model.householdStats.getTotalMonthlyTaxesPaid() + ", " + Model.householdStats.getTotalMonthlyNICPaid() + ", " + Model.householdStats.getTotalSocialHousingRent() + ", " + Model.householdStats.getTotalBankBalancesBeforeConsumption() + ", " + Model.householdStats.getTotalBankBalanceEndowment() + ", " + Model.householdStats.getTotalConsumption() + ", " + Model.householdStats.getIncomeConsumption() + ", " + Model.householdStats.getFinancialWealthConsumption() + ", " + Model.householdStats.getHousingWealthConsumption() + ", " + Model.householdStats.getDebtConsumption() + ", " + Model.householdStats.getTotalSavingForDeleveraging() + ", " + Model.householdStats.getTotalSaving() + ", " + (Model.creditSupply.totalBTLCredit + Model.creditSupply.totalOOCredit) + ", " + Model.householdStats.getTotalPrincipalRepayments() + ", " + Model.householdStats.getTotalPrincipalRepaymentsDueToHouseSale() + ", " + Model.householdStats.getTotalPrincipalRepaymentDeceasedHouseholds() + ", " + Model.householdStats.getTotalInterestRepayments() + ", " + Model.householdStats.getTotalRentalPayments() + ", " + Model.householdStats.getTotalBankruptcyCashInjection() + ", " + Model.householdStats.getTotalDebtReliefOfDeceasedHouseholds() + ", " + Model.bank.creditSupplyTarget(Model.households.size()) + ", " + Model.creditSupply.getNewlyPaidDownPayments() + ", " + Model.creditSupply.getCashPayments() + ", " + Model.creditSupply.getNewlyIssuedCredit() + ", " + Model.householdStats.getNNegativeEquity() + ", " + Model.bank.getLoanToValueLimit(true, true) + ", " + Model.bank.getLoanToValueLimit(false, true) + ", " + Model.bank.getLoanToValueLimit(false, false) + ", " + // divide by 100 as the interest rate in core indicators is calculated as percentage Model.coreIndicators.getInterestRateSpread()/100 + ", " + Model.housingMarketStats.getMoneyToConstructionSector() + ", " + Model.centralBank.getCentralBankLTVsOnOff() + ", " + Model.householdStats.getMedianDebtServiceRatio() + ", " + Model.householdStats.getMedianDebtServiceRatioAdjusted() + ", " + Model.householdStats.getMedianDSRVulnerableHouseholds() + ", " + Model.householdStats.getMedianDSRVulnerableHouseholdsAdjusted() + ", " + ((double)Model.householdStats.getHouseholdsVulnerableAmpudiaMeasure2() / (double)Model.householdStats.getIndebtedHouseholds()) + ", " + Model.householdStats.getMedianAgeVulnerableHouseholds() + ", " + Model.householdStats.getMedianAgeNonVulnerableHouseholds() + ", " + Model.coreIndicators.getS90TotalNetWealth() + ", " + // additional consumption parameters // active BTL total and per BTL investor (Model.householdStats.getActiveBTLIncomeConsumption() + Model.householdStats.getActiveBTLFinancialWealthConsumption() + Model.householdStats.getActiveBTLNetHousingWealthConsumption()) +", " + ((Model.householdStats.getActiveBTLIncomeConsumption() + Model.householdStats.getActiveBTLFinancialWealthConsumption() + Model.householdStats.getActiveBTLNetHousingWealthConsumption()) / Model.householdStats.getnActiveBTL()) +", " + // SSB total and per household (Model.householdStats.getSSBIncomeConsumption() + Model.householdStats.getSSBFinancialWealthConsumption() + Model.householdStats.getSSBNetHousingWealthConsumption()) +", " + ((Model.householdStats.getSSBIncomeConsumption() + Model.householdStats.getSSBFinancialWealthConsumption() + Model.householdStats.getSSBNetHousingWealthConsumption()) / Model.householdStats.getnSSB()) +", " + // inFirstHome total and per Houshold (Model.householdStats.getInFirstHomeIncomeConsumption() + Model.householdStats.getInFirstHomeFinancialWealthConsumption() + Model.householdStats.getInFirstHomeNetHousingWealthConsumption()) +", " + ((Model.householdStats.getInFirstHomeIncomeConsumption() + Model.householdStats.getInFirstHomeFinancialWealthConsumption() + Model.householdStats.getInFirstHomeNetHousingWealthConsumption()) / Model.householdStats.getnInFirstHome()) +", " + // renter consumption total and per household (Model.householdStats.getRenterIncomeConsumption() + Model.householdStats.getRenterFinancialWealthConsumption() + Model.householdStats.getRenterNetHousingWealthConsumption()) +", " + ((Model.householdStats.getRenterIncomeConsumption() + Model.householdStats.getRenterFinancialWealthConsumption() + Model.householdStats.getRenterNetHousingWealthConsumption()) / Model.householdStats.getnNonOwner()) +", " + // detailed per household consumption by consumption inducer (Model.householdStats.getActiveBTLIncomeConsumption() / Model.householdStats.getnActiveBTL()) +", " + (Model.householdStats.getActiveBTLFinancialWealthConsumption() / Model.householdStats.getnActiveBTL()) +", " + (Model.householdStats.getActiveBTLNetHousingWealthConsumption() / Model.householdStats.getnActiveBTL()) +", " + (Model.householdStats.getSSBIncomeConsumption() / Model.householdStats.getnSSB()) +", " + (Model.householdStats.getSSBFinancialWealthConsumption() / Model.householdStats.getnSSB()) +", " + (Model.householdStats.getSSBNetHousingWealthConsumption() / Model.householdStats.getnSSB()) +", " + (Model.householdStats.getInFirstHomeIncomeConsumption() / Model.householdStats.getnInFirstHome()) +", " + (Model.householdStats.getInFirstHomeFinancialWealthConsumption() / Model.householdStats.getnInFirstHome()) +", " + (Model.householdStats.getInFirstHomeNetHousingWealthConsumption() / Model.householdStats.getnInFirstHome()) +", " + (Model.householdStats.getRenterIncomeConsumption() / Model.householdStats.getnNonOwner()) +", " + (Model.householdStats.getRenterFinancialWealthConsumption() / Model.householdStats.getnNonOwner()) +", " + (Model.householdStats.getRenterNetHousingWealthConsumption() / Model.householdStats.getnNonOwner()) +", " + // Measures for exposure at default Model.householdStats.getExposureAtDefaultDSR30() +", " + Model.householdStats.getExposureAtDefaultDSR35() +", " + Model.householdStats.getExposureAtDefaultDSR70() +", " + Model.householdStats.getExposureAtDefaultFinancialMarginBLC20() +", " + Model.householdStats.getExposureAtDefaultFinancialMarginBLC40() +", " + Model.householdStats.getExposureAtDefaultFinancialMarginBLC70() +", " + // Ampudia measures Model.householdStats.getExposureAtDefaultAmpudiaMeasure1() +", " + Model.householdStats.getExposureAtDefaultAmpudiaMeasure2() +", " + // households with less than X pounds as deposits Model.householdStats.getHouseholdsWithLessThan1500p() +", " + Model.householdStats.getLowDepositHouseholdConsumption() +", " + Model.householdStats.getLowDepositHouseholdSaving() +", " + Model.householdStats.getHouseholdsVulnerableAmpudiaMeasure2() + ", " + Model.householdStats.getActiveBTLVulnerable() + ", " + Model.householdStats.getInFirstHomeVulnerable() + ", " + Model.householdStats.getSSBVulnerable() + ", " + Model.householdStats.getActiveBTLEAD() + ", " + Model.householdStats.getInFirstHomeEAD() + ", " + Model.householdStats.getSSBEAD() + ", " + Model.householdStats.getUnemploymentHouseholdsVulnerableAmpudiaMeasure2() + ", " + Model.householdStats.getUnemploymentActiveBTLVulnerable() + ", " + Model.householdStats.getUnemploymentinFirstHomeVulnerable() + ", " + Model.householdStats.getUnemploymentSSBVulnerable() + ", " + // Model.householdStats.getUnemploymentExposureAtDefaultAmpudiaMeasure2() + ", " + Model.householdStats.getUnemploymentActiveBTLEAD() + ", " + Model.householdStats.getUnemploymentinFirstHomeEAD() + ", " + Model.householdStats.getUnemploymentSSBEAD() + ", " + Model.householdStats.getVulnerableByPurchase() + ", " + Model.householdStats.getVulnerableByConsumption() + ", " + Model.householdStats.getVulnerableByOther() + ", " + Model.householdStats.getNotVulnerableBecauseSale() +", " + Model.householdStats.getNotVulnerableBecauseSaving() +", " + Model.householdStats.getNotVulnerableBecauseOther() + ", " + // agent-specific vulnerability causes Model.householdStats.getVulnerableByPurchaseBTL() + ", " + Model.householdStats.getVulnerableByPurchaseSSB() + ", " + Model.householdStats.getVulnerableByPurchaseInFirstHome() + ", " + Model.householdStats.getVulnerableByConsumptionBTL() + ", " + Model.householdStats.getVulnerableByConsumptionSSB() + ", " + Model.householdStats.getVulnerableByConsumptionInFirstHome() + ", " + Model.householdStats.getVulnerableByOtherBTL() + ", " + Model.householdStats.getVulnerableByOtherSSB() + ", " + Model.householdStats.getVulnerableByOtherInFirstHome() + ", " + Model.householdStats.getNotVulnerableBecauseSaleBTL() + ", " + Model.householdStats.getNotVulnerableBecauseSaleSSB() + ", " + Model.householdStats.getNotVulnerableBecauseSaleInFirstHome() + ", " + Model.householdStats.getNotVulnerableBecauseSaleOthers() + ", " + Model.householdStats.getNotVulnerableBecauseSavingBTL() + ", " + Model.householdStats.getNotVulnerableBecauseSavingSSB() + ", " + Model.householdStats.getNotVulnerableBecauseSavingInFirstHome() + ", " + Model.householdStats.getNotVulnerableBecauseSavingOthers() + ", " + Model.householdStats.getNotVulnerableBecauseOtherBTL() + ", " + Model.householdStats.getNotVulnerableBecauseOtherSSB() + ", " + Model.householdStats.getNotVulnerableBecauseOtherInFirstHome() + ", " + Model.householdStats.getNotVulnerableBecauseOtherOthers() + ", " + Model.householdStats.getNowVulnerableByPurchase() + ", " + Model.householdStats.getNowVulnerableByDissaving() + ", " + Model.householdStats.getNowVulnerableByOther() + ", " + Model.householdStats.getNowVulnerableByPurchaseBTL() + ", " + Model.householdStats.getNowVulnerableByDissavingBTL() + ", " + Model.householdStats.getNowVulnerableByOtherBTL() + ", " + Model.householdStats.getNowVulnerableByPurchaseSSB() + ", " + Model.householdStats.getNowVulnerableByDissavingSSB() + ", " + Model.householdStats.getNowVulnerableByOtherSSB() + ", " + Model.householdStats.getNowVulnerableByPurchaseFTB() + ", " + Model.householdStats.getNowVulnerableByDissavingFTB() + ", " + Model.householdStats.getNowVulnerableByOtherFTB() ); } // Write quality band prices to file if (recordQualityBandPrice) { String str = Arrays.toString(Model.housingMarketStats.getAvSalePricePerQuality()); str = str.substring(1, str.length() - 1); qualityBandPriceFile.println(time + ", " + str); // write the expected average sale price to string String str2 = Arrays.toString(Model.housingMarketStats.getExpAvSalePricePerQuality()); str2 = str2.substring(1, str2.length() - 1); qualityBandPriceExpectedFile.println(time + ", " + str2); } } public void finishRun(boolean recordOutfile, boolean recordCoreIndicators, boolean recordQualityBandPrice) { if (recordCoreIndicators) { HPI.println(""); top10NetTotalWealthShare.println(""); palmerIndex.println(""); numberBankruptcies.println(""); shareEmptyHouses.println(""); BTLMarketShare.println(""); financialWealth.println(""); totalConsumption.println(""); incomeConsumption.println(""); financialConsumption.println(""); grossHousingWealthConsumption.println(""); debtConsumption.println(""); savingDeleveraging.println(""); consumptionToIncome.println(""); ooLTI.println(""); btlLTV.println(""); creditGrowth.println(""); debtToIncome.println(""); ooDebtToIncome.println(""); mortgageApprovals.println(""); housingTransactions.println(""); advancesToFTBs.println(""); advancesToBTL.println(""); advancesToHomeMovers.println(""); priceToIncome.println(""); rentalYield.println(""); housePriceGrowth.println(""); interestRateSpread.println(""); ooLTVAboveMedian.println(""); ooLTV.println(""); } if (recordOutfile) outfile.close(); if (recordQualityBandPrice) { qualityBandPriceFile.close(); qualityBandPriceExpectedFile.close(); } } public void finish(boolean recordCoreIndicators) { if (recordCoreIndicators) { HPI.close(); top10NetTotalWealthShare.close(); palmerIndex.close(); numberBankruptcies.close(); shareEmptyHouses.close(); BTLMarketShare.close(); financialWealth.close(); totalConsumption.close(); incomeConsumption.close(); financialConsumption.close(); grossHousingWealthConsumption.close(); debtConsumption.close(); savingDeleveraging.close(); consumptionToIncome.close(); ooLTI.close(); btlLTV.close(); creditGrowth.close(); debtToIncome.close(); ooDebtToIncome.close(); mortgageApprovals.close(); housingTransactions.close(); advancesToFTBs.close(); advancesToBTL.close(); advancesToHomeMovers.close(); priceToIncome.close(); rentalYield.close(); housePriceGrowth.close(); interestRateSpread.close(); ooLTVAboveMedian.close(); ooLTV.close(); } } }
57.81348
211
0.655388
e265efb53ac70c5eb6b502b90ef98521439d5861
10,261
/* Copyright 2015 Intel Corporation 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.intel.xdk.display; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaInterface; import org.apache.cordova.CordovaPlugin; import org.apache.cordova.CordovaWebView; import org.json.JSONArray; import org.json.JSONException; import android.app.Activity; import android.graphics.Color; import android.graphics.PixelFormat; import android.util.DisplayMetrics; import android.util.Log; import android.view.SurfaceHolder; import android.view.View; import android.view.ViewGroup; import android.webkit.JavascriptInterface; import android.widget.LinearLayout; @SuppressWarnings("deprecation") public class Display extends CordovaPlugin { public static boolean debug = true; private float forcedscale = -1; private int checkCount = 0; private Activity activity = null; public CameraPreview arView; public Display(){ } @Override public void initialize(CordovaInterface cordova, CordovaWebView webView) { super.initialize(cordova, webView); //get convenience reference to activity activity = cordova.getActivity(); // activity.runOnUiThread(new Runnable() { // public void run() { // if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // try { // Method m = WebView.class.getMethod("setWebContentsDebuggingEnabled", boolean.class); // m.invoke(WebView.class, true); // } catch (Exception e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // } // } // }); } /** * Executes the request and returns PluginResult. * * @param action The action to execute. * @param args JSONArray of arguments for the plugin. * @param callbackContext The callback context used when calling back into JavaScript. * @return True when the action was valid, false otherwise. */ public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { if (action.equals("")) { // JSONObject r = new JSONObject(); // r.put("cookies", new JSONObject(getCookies())); // r.put("mediacache", new JSONArray(getMediaCache())); // r.put("mediacache_dir", cachedMediaDirectory.getAbsolutePath()); // callbackContext.success(r); } else if (action.equals("startAR")) { startAR(); } else if (action.equals("stopAR")) { stopAR(); } else { return false; } return true; } //-------------------------------------------------------------------------- // LOCAL METHODS //-------------------------------------------------------------------------- //defer @JavascriptInterface public void startAR() { arView = CameraPreview.newInstance(activity.getApplicationContext()); arView.setVisibility(View.INVISIBLE); arView.height = 100; arView.width = 100; //no way to get current background color? arView.setBackgroundColor(Color.TRANSPARENT); SurfaceHolder sfhTrackHolder = arView.getHolder(); sfhTrackHolder.setFormat(PixelFormat.TRANSPARENT); sfhTrackHolder.setKeepScreenOn(true); sfhTrackHolder.setFixedSize(100, 100); activity.runOnUiThread(new Runnable() { public void run() { //activity.addContentView(arView, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT, 0.0F)); //activity.addContentView(arView, new LinearLayout.LayoutParams(400, 500, 0.0F)); ViewGroup rootView = (ViewGroup)webView.getParent().getParent(); rootView.addView(arView, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT)); rootView.bringChildToFront((View)webView.getParent()); arView.setVisibility(View.VISIBLE); arView.showCamera(); webView.bringToFront(); webView.setBackgroundColor(0x00000000); LinearLayout ll = (LinearLayout)webView.getParent(); ll.setBackgroundColor(0x00000000); View activityView = activity.getCurrentFocus(); } }); } @JavascriptInterface public void stopAR() { activity.runOnUiThread(new Runnable() { public void run() { arView.setVisibility(View.INVISIBLE); arView.hideCamera(); } }); } //start hacks for HTC Incredible // @JavascriptInterface // public void forceScale(final float scale) { // checkCount = 3;//check 3 times then bail (this is for the picture listener so it doesnt run forever) // forceScaleInternal(scale); // checkScale(); // //webview.addPictureListener(); // } // // Method setScaleWithoutCheck, setNewZoomScale/*Gingerbread*/, setScaleTo/*Froyo*/; // private void forceScaleInternal(/*final*/ float scale) { // forcedscale = scale; // activity.runOnUiThread(new Runnable() { // public void run() { // webview.setInitialScale(Math.round((forcedscale*100))); // } // }); // // try { // Method fnGetMinZoomScale = activity.remoteWebView.getClass().getMethod("fnGetMinZoomScale"); // if (fnGetMinZoomScale != null) { // Float minz = (Float) fnGetMinZoomScale.invoke(activity.remoteWebView, (Object[]) null); // if(scale < minz) { // scale = minz.floatValue(); // } // } // } catch (NoSuchMethodException e) { // } catch (IllegalAccessException e) { // } catch (InvocationTargetException e) { // } // // try { // if(setScaleWithoutCheck == null) setScaleWithoutCheck = webview.getClass().getMethod("setScaleWithoutCheck", boolean.class); // if (setScaleWithoutCheck != null) { // setScaleWithoutCheck.invoke(webview, true); // } // } catch (NoSuchMethodException e) { // } catch (IllegalAccessException e) { // } catch (InvocationTargetException e) { // } // try { // if(setScaleTo == null) setScaleTo = webview.getClass().getMethod("setScaleTo", float.class, boolean.class, boolean.class); // if (setScaleTo != null) { // setScaleTo.invoke(webview, scale, true, true); // if(Debug.isDebuggerConnected()) Log.i("[appMobi2]", "setScaleTo called with " + scale); // //if forceScale succeeded, hold onto scale // AppMobiDisplay.this.forcedscale = scale; // } else{ // if(Debug.isDebuggerConnected()) Log.i("[appMobi2]", "setScaleTo not called"); // } // } catch (NoSuchMethodException e) { // } catch (IllegalAccessException e) { // } catch (InvocationTargetException e) { // } // try { // if(setNewZoomScale == null) setNewZoomScale = webview.getClass().getMethod("setNewZoomScale", float.class, boolean.class, boolean.class); // if (setNewZoomScale != null) { // setNewZoomScale.invoke(webview, scale, true, true); // if(Debug.isDebuggerConnected()) Log.i("[appMobi2]", "setNewZoomScale called with " + scale); // //if forceScale succeeded, hold onto scale // AppMobiDisplay.this.forcedscale = scale; // } else{ // if(Debug.isDebuggerConnected()) Log.i("[appMobi2]", "setNewZoomScale not called"); // } // } catch (NoSuchMethodException e) { // } catch (IllegalAccessException e) { // } catch (InvocationTargetException e) { // } // activity.runOnUiThread(new Runnable() { // public void run() { // webview.invalidate(); // } // }); // } // // public void checkScale() { // checkCount--; // // activity.runOnUiThread(new Runnable() { // public void run() { // try { // Thread.sleep(200); // } catch (InterruptedException e) { // } // // float newScale = activity.appView.getScale(); // if(Debug.isDebuggerConnected()) Log.i("[appMobi2]", "checkScale called with " + newScale +", requestedScale is " + forcedscale); // if(forcedscale!=-1 && newScale!=forcedscale) { // forceScaleInternal(forcedscale); // if(Debug.isDebuggerConnected()) Log.i("[appMobi2]", "checkScale calling forceScaleInternal with " + forcedscale); // } else if(newScale==forcedscale){ // checkCount = 0; // webview.removePictureListener(); // } // // if(Debug.isDebuggerConnected()) Log.i("[appMobi2]", "checkCount:"+checkCount); // if(checkCount<1) { // webview.removePictureListener(); // } // } // }); // } //end hacks for HTC Incredible }
39.92607
159
0.567976
4f41756fa600a2f51a7d6be713924dbbc0674bf3
928
package engineer.thomas_werner.euler; public class Problem9 { public static void main(String[] args) { System.out.println(new Problem9().findPythagoreanTriplet()); } private long findPythagoreanTriplet() { for(int c=1; c<1_000; c++) for(int b=1; b<c; b++) for(int a=1; a<b; a++) if(isPythagoreanTriplet(a,b,c) && isTargetTriplet(a,b,c)) return getResult(a,b,c); return 0; } private boolean isPythagoreanTriplet(final int a, final int b, final int c) { return (a < b) && (b < c) && (a * a + b * b == c * c); } private boolean isTargetTriplet(final int a, final int b, final int c) { return 1_000 == a + b + c; } private long getResult(final int a, final int b, final int c) { System.out.println("a: " + a +", b: " + b +", c: " +c); return a * b * c; } }
29
81
0.532328
c4ace66bfc02aaf0c25070d3ea6805128250fc51
13,316
/* * Copyright (C) 2004 Derek James and Philip Tucker * * This file is part of ANJI (Another NEAT Java Implementation). * * ANJI is free software; you can redistribute it and/or modify it under the terms of the GNU * General Public License as published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See * the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with this program; if * not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA * 02111-1307 USA * * created by Philip Tucker on Feb 16, 2003 */ package com.anji.neat; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Random; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import org.apache.log4j.Logger; import org.jgap.Allele; import org.jgap.ChromosomeMaterial; /** * Utility class capturing functionality pertaining to NEAT neuron and connection genes. * * @author Philip Tucker */ public class NeatChromosomeUtility { private static Logger logger = Logger.getLogger( NeatChromosomeUtility.class ); /** * factory method to construct chromosome material for neural net with specified input and * output dimension, JGAP/NEAT configuration, and amount of connectivity * * @param newNumInputs * @param newNumHidden * @param newNumOutputs * @param config * @param fullyConnected all layers fully connected if true, not connected at all otherwise * @return ChromosomeMaterial */ public static ChromosomeMaterial newSampleChromosomeMaterial( short newNumInputs, short newNumHidden, short newNumOutputs, NeatConfiguration config, boolean fullyConnected, double connectedPercentage ) { return new ChromosomeMaterial( initAlleles( newNumInputs, newNumHidden, newNumOutputs, config, fullyConnected, connectedPercentage ) ); } /** * @param connAlleles <code>Collection</code> contains <code>ConnectionA</code> llele * objects * @param destNeuronInnovationIds <code>Collection</code> contains Long objects * @return <code>Collection</code> containing <code>ConnectionAllele</code> objects, those * in <code>connAlleles</code> whose destination neuron is in * <code>destNeuronInnovationIds</code> */ public static Collection extractConnectionAllelesForDestNeurons( Collection connAlleles, Collection destNeuronInnovationIds ) { Collection result = new ArrayList(); // for every connection ... Iterator connIter = connAlleles.iterator(); while ( connIter.hasNext() ) { ConnectionAllele cAllele = (ConnectionAllele) connIter.next(); if ( destNeuronInnovationIds.contains( cAllele.getDestNeuronId() ) ) result.add( cAllele ); } return result; } /** * @param connAlleles <code>Collection</code> contains ConnectionGene objects * @param srcNeuronInnovationIds <code>Collection</code> contains Long objects * @return <code>Collection</code> containing ConnectionGene objects, those in connGenes whose * source neuron is srcNeuronGene */ public static Collection extractConnectionAllelesForSrcNeurons( Collection connAlleles, Collection srcNeuronInnovationIds ) { Collection result = new ArrayList(); // for every connection ... Iterator connIter = connAlleles.iterator(); while ( connIter.hasNext() ) { ConnectionAllele connAllele = (ConnectionAllele) connIter.next(); if ( srcNeuronInnovationIds.contains( connAllele.getSrcNeuronId() ) ) result.add( connAllele ); } return result; } /** * constructs genes for neural net with specified input and output dimension, JGAP/NEAT * configuration, and amount of connectivity * * @param numInputs * @param numHidden * @param numOutputs * @param config * @param fullyConnected all layers fully connected if true, not connected at all otherwise * @return List contains Allele objects */ private static List initAlleles( short numInputs, short numHidden, short numOutputs, NeatConfiguration config, boolean fullyConnected, double connectedPercentage ) { List inNeurons = new ArrayList( numInputs ); List outNeurons = new ArrayList( numOutputs ); List hidNeurons = new ArrayList( numHidden ); List conns = new ArrayList(); // input neurons for ( int i = 0; i < numInputs; ++i ) inNeurons.add( config.newNeuronAllele( NeuronType.INPUT ) ); // output neurons for ( int j = 0; j < numOutputs; ++j ) { NeuronAllele outNeuron = config.newNeuronAllele( NeuronType.OUTPUT ); outNeurons.add( outNeuron ); if(connectedPercentage > 0.0) { // Random chance to add connections between in->out Random rand = config.getRandomGenerator(); for(int e1 = 0; e1 < numInputs; e1++) { if(rand.nextDouble() < connectedPercentage) { NeuronAllele srcNeuronAllele = (NeuronAllele) inNeurons.get( e1 ); ConnectionAllele c = config.newConnectionAllele( srcNeuronAllele.getInnovationId(), outNeuron.getInnovationId() ); c.setToRandomValue( config.getRandomGenerator() ); conns.add( c ); } } } else if ( fullyConnected && ( numHidden == 0 ) ) { // in->out connections for ( int i = 0; i < numInputs; ++i ) { NeuronAllele srcNeuronAllele = (NeuronAllele) inNeurons.get( i ); ConnectionAllele c = config.newConnectionAllele( srcNeuronAllele.getInnovationId(), outNeuron.getInnovationId() ); if ( config != null ) c.setToRandomValue( config.getRandomGenerator() ); conns.add( c ); } } } // hidden neurons if ( fullyConnected ) { for ( int k = 0; k < numHidden; ++k ) { NeuronAllele hidNeuron = config.newNeuronAllele( NeuronType.HIDDEN ); hidNeurons.add( hidNeuron ); // in->hid connections for ( int i = 0; i < numInputs; ++i ) { NeuronAllele srcNeuronAllele = (NeuronAllele) inNeurons.get( i ); ConnectionAllele c = config.newConnectionAllele( srcNeuronAllele.getInnovationId(), hidNeuron.getInnovationId() ); if ( config != null ) c.setToRandomValue( config.getRandomGenerator() ); conns.add( c ); } // hid->out connections for ( int j = 0; j < numOutputs; ++j ) { NeuronAllele destNeuronAllele = (NeuronAllele) outNeurons.get( j ); ConnectionAllele c = config.newConnectionAllele( hidNeuron.getInnovationId(), destNeuronAllele.getInnovationId() ); if ( config != null ) c.setToRandomValue( config.getRandomGenerator() ); conns.add( c ); } } } else if ( numHidden > 0 ) { logger.warn( "ignoring intial topology hidden neurons, not fully connected" ); } List result = new ArrayList(); result.addAll( inNeurons ); result.addAll( outNeurons ); result.addAll( hidNeurons ); result.addAll( conns ); Collections.sort( result ); return result; } /** * return all neurons in <code>alleles</code> as <code>SortedMap</code> * * @param alleles <code>Collection</code> contains <code>Allele</code> objects * @return <code>SortedMap</code> containing key <code>Long</code> innovation id, value * <code>NeuronGene</code> objects * @see NeatChromosomeUtility#getNeuronMap(Collection, NeuronType) */ public static SortedMap getNeuronMap( Collection alleles ) { return getNeuronMap( alleles, null ); } /** * return all neurons in <code>genes</code> as <code>List</code> * * @param alleles <code>Collection</code> contains <code>Allele</code> objects * @return <code>List</code> containing <code>NeuronGene</code> objects * @see NeatChromosomeUtility#getNeuronList(Collection, NeuronType) */ public static List getNeuronList( Collection alleles ) { return getNeuronList( alleles, null ); } /** * if type == null, returns all neurons in <code>alleles</code>; otherwise, returns only * neurons of <code>type</code> * * @param alleles <code>Collection</code> contains <code>Allele</code> objects * @param type * @return SortedMap contains key Long innovation id, value NeuronGene objects */ public static SortedMap getNeuronMap( Collection alleles, NeuronType type ) { TreeMap result = new TreeMap(); Iterator iter = alleles.iterator(); while ( iter.hasNext() ) { Allele allele = (Allele) iter.next(); if ( allele instanceof NeuronAllele ) { NeuronAllele neuronAllele = (NeuronAllele) allele; Long id = neuronAllele.getInnovationId(); // sanity check if ( result.containsKey( id ) ) throw new IllegalArgumentException( "chromosome contains duplicate neuron gene: " + allele.toString() ); if ( ( type == null ) || neuronAllele.isType( type ) ) result.put( id, allele ); } } return result; } /** * if type == null, returns all neuron genes in <code>genes</code>; otherwise, returns only * neuron genes of type * * @param alleles <code>Collection</code> contains gene objects * @param type * @return <code>List</code> contains <code>NeuronAllele</code> objects */ public static List getNeuronList( Collection alleles, NeuronType type ) { List result = new ArrayList(); Iterator iter = alleles.iterator(); while ( iter.hasNext() ) { Allele allele = (Allele) iter.next(); if ( allele instanceof NeuronAllele ) { NeuronAllele nAllele = (NeuronAllele) allele; // sanity check if ( result.contains( nAllele ) ) throw new IllegalArgumentException( "chromosome contains duplicate neuron gene: " + allele.toString() ); if ( ( type == null ) || nAllele.isType( type ) ) result.add( allele ); } } return result; } /** * returns all connections in <code>alleles</code> as <code>SortedMap</code> * * @param alleles <code>SortedSet</code> contains <code>Allele</code> objects * @return <code>SortedMap</code> containing key <code>Long</code> innovation id, value * <code>ConnectionAllele</code> objects */ public static SortedMap getConnectionMap( Set alleles ) { TreeMap result = new TreeMap(); Iterator iter = alleles.iterator(); while ( iter.hasNext() ) { Allele allele = (Allele) iter.next(); if ( allele instanceof ConnectionAllele ) { ConnectionAllele connAllele = (ConnectionAllele) allele; Long id = connAllele.getInnovationId(); // sanity check if ( result.containsKey( id ) ) throw new IllegalArgumentException( "chromosome contains duplicate connection gene: " + allele.toString() ); result.put( id, allele ); } } return result; } /** * returns all connection genes in <code>genes</code> as <code>List</code> * * @param alleles <code>Collection</code> contains gene objects * @return <code>List</code> containing <code>ConnectionGene</code> objects */ public static List getConnectionList( Collection alleles ) { List result = new ArrayList(); Iterator iter = alleles.iterator(); while ( iter.hasNext() ) { Allele allele = (Allele) iter.next(); if ( allele instanceof ConnectionAllele ) { // sanity check if ( result.contains( allele ) ) throw new IllegalArgumentException( "chromosome contains duplicate connection gene: " + allele.toString() ); result.add( allele ); } } return result; } /** * non-recursive starting point for recursive search * * @param srcNeuronId * @param destNeuronId * @param connGenes * @return true if <code>srcNeuronId</code> and <code>destNeuronId</code> are connected * @see NeatChromosomeUtility#neuronsAreConnected(Long, Long, Collection, Set) */ public static boolean neuronsAreConnected( Long srcNeuronId, Long destNeuronId, Collection connGenes ) { return neuronsAreConnected( srcNeuronId, destNeuronId, connGenes, new HashSet() ); } /** * Recursively searches <code>allConnGenes</code> to determines if the network contains a * directed path from <code>srcNeuronId</code> to <code>destNeuronId</code> are connected. * For efficiency, we pass in <code>alreadyTraversedConnGeneIds</code> to eliminate redundant * searching. * * @param srcNeuronId * @param destNeuronId * @param allConnAlleles <code>Collection</code> contains <code>ConnectionGene</code> * objects * @param alreadyTraversedConnIds <code>Set</code> contains <code>Long</code> connection ID * objects * @return returns true if neurons are the same, or a path lies between src and dest in * connGenes connected graph */ private static boolean neuronsAreConnected( Long srcNeuronId, Long destNeuronId, Collection allConnAlleles, Set alreadyTraversedConnIds ) { // TODO - make connGenes Map key on srcNeuronId // Recursively searches connections to see if src and dest are connected if ( alreadyTraversedConnIds.contains( srcNeuronId ) ) return false; alreadyTraversedConnIds.add( srcNeuronId ); if ( srcNeuronId.equals( destNeuronId ) ) return true; Iterator connIter = allConnAlleles.iterator(); while ( connIter.hasNext() ) { ConnectionAllele connAllele = (ConnectionAllele) connIter.next(); if ( ( connAllele.getSrcNeuronId().equals( connAllele.getDestNeuronId() ) == false ) && ( connAllele.getSrcNeuronId().equals( srcNeuronId ) ) ) { if ( neuronsAreConnected( connAllele.getDestNeuronId(), destNeuronId, allConnAlleles, alreadyTraversedConnIds ) ) return true; } } return false; } }
34.408269
123
0.725068
5564eb92e162e018f39d61ffde09308046810abe
1,404
package com.example.injector.circular; import java.util.Objects; import javaemul.internal.annotations.DoNotInline; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.processing.Generated; @Generated("sting.processor.StingProcessor") final class Sting_SupplierBrokenDirectCircularDependencyModel implements SupplierBrokenDirectCircularDependencyModel { @Nullable private Object node1; @Nullable private Object node2; Sting_SupplierBrokenDirectCircularDependencyModel() { } @Nonnull @DoNotInline private synchronized Object node1() { if ( null == node1 ) { node1 = Objects.requireNonNull( SupplierBrokenDirectCircularDependencyModel_Sting_MyModel2.create(() -> node2()) ); } assert null != node1; return node1; } @Nonnull @DoNotInline private synchronized Object node2() { if ( null == node2 ) { node2 = Objects.requireNonNull( SupplierBrokenDirectCircularDependencyModel_Sting_MyModel1.create(node1()) ); } assert null != node2; return node2; } @Override public SupplierBrokenDirectCircularDependencyModel.MyModel1 getMyModel1() { return (SupplierBrokenDirectCircularDependencyModel.MyModel1) node2(); } @Override public SupplierBrokenDirectCircularDependencyModel.MyModel2 getMyModel2() { return (SupplierBrokenDirectCircularDependencyModel.MyModel2) node1(); } }
28.08
121
0.769943
1949b06d27047d75860774c75a6954af5fbbce72
17,065
package com.kevinrei.chronotrack; import android.Manifest; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.support.v4.app.ActivityCompat; import android.support.v4.app.NavUtils; import android.support.v4.content.ContextCompat; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.util.Patterns; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.Spinner; import android.widget.Toast; import com.soundcloud.android.crop.Crop; import com.squareup.picasso.Picasso; import java.io.File; import java.util.Arrays; import java.util.UUID; public class NewGameActivity extends AppCompatActivity { /** Action code */ private static final int REQUEST_EXTERNAL_READ_PERMISSION = 0; /** Database and data values*/ private MySQLiteHelper db; private int flag; int appId; String gameTitle; String gameImage; String gameCategory; String staminaUnit; int recoveryRate; int maxStamina; /** Widgets and Fields */ protected View mView; protected LinearLayout mMobileLayout; protected EditText mTitle; protected ImageView mImage; protected Spinner mCategory; protected EditText mUnit; protected EditText mRecovery; protected EditText mStamina; /** Image */ private String imgContent = ""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_new_game); mView = findViewById(R.id.main_content); db = new MySQLiteHelper(this); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); // Set back (home) navigation if (getSupportActionBar() != null) { getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_home); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } mMobileLayout = (LinearLayout) findViewById(R.id.layout_mobile); mTitle = (EditText) findViewById(R.id.hint_title); mImage = (ImageView) findViewById(R.id.img_game); mCategory = (Spinner) findViewById(R.id.spn_category); mUnit = (EditText) findViewById(R.id.hint_unit); mRecovery = (EditText) findViewById(R.id.hint_rate); mStamina = (EditText) findViewById(R.id.hint_max); // Get the intent and its flag, which is 1 or 2. // 1 means an installed activity is being added. // 2 means a game detail is being edited. Intent i = getIntent(); flag = i.getIntExtra("flag", 0); Log.d("flag", String.valueOf(flag)); mImage.setOnClickListener(mImageClickListener); ArrayAdapter<CharSequence> categoryAdapter = ArrayAdapter.createFromResource( this, R.array.category_array, android.R.layout.simple_spinner_item); categoryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mCategory.setAdapter(categoryAdapter); if (flag == 1) { // An installed app was selected String appTitle = i.getStringExtra("app_title"); String appIcon = i.getStringExtra("app_icon"); mTitle.setText(appTitle); imgContent = appIcon; Picasso.with(getApplicationContext()).load(imgContent).into(mImage); mCategory.setEnabled(false); } else if (flag == 2) { // A game is being edited toolbar.setTitle("Edit Game"); getExistingGameData(i); } // Do not show Snackbar when activity is created else { mCategory.setSelection(0, false); mCategory.setOnItemSelectedListener(mMobileListener); } } @Override protected void onSaveInstanceState(Bundle savedInstanceState) { super.onSaveInstanceState(savedInstanceState); savedInstanceState.putString("mTitle", mTitle.getText().toString()); savedInstanceState.putString("mImage", imgContent); savedInstanceState.putInt("mCategory", mCategory.getSelectedItemPosition()); savedInstanceState.putString("mUnit", mUnit.getText().toString()); savedInstanceState.putString("mRecovery", mRecovery.getText().toString()); savedInstanceState.putString("mStamina", mStamina.getText().toString()); } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); mTitle.setText(savedInstanceState.getString("mTitle")); imgContent = savedInstanceState.getString("mImage"); Picasso.with(getApplicationContext()).load(imgContent).into(mImage); mCategory.setSelection(savedInstanceState.getInt("mCategory"), false); mUnit.setText(savedInstanceState.getString("mUnit")); mRecovery.setText(savedInstanceState.getString("mRecovery")); mStamina.setText(savedInstanceState.getString("mStamina")); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_new_game, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == android.R.id.home) { NavUtils.navigateUpFromSameTask(this); return true; } else if (id == R.id.action_save) { if (isEmpty(mTitle)) { Snackbar.make(mView, getString(R.string.unfilled_title), Snackbar.LENGTH_SHORT).show(); return false; } else { updateGameLibrary(); Intent resultIntent = new Intent(); resultIntent.putExtra("game_title", gameTitle); setResult(RESULT_OK, resultIntent); finish(); } return true; } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { super.onBackPressed(); } @Override public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { switch (requestCode) { case REQUEST_EXTERNAL_READ_PERMISSION: { // If request is cancelled, the result arrays are empty. if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // permission was granted, yay! Crop.pickImage(this); } else { // permission denied, boo! Picasso.with(getApplicationContext()).load(R.mipmap.ic_launcher).into(mImage); } } } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == Crop.REQUEST_PICK && resultCode == RESULT_OK) { beginCrop(data.getData()); } else if (requestCode == Crop.REQUEST_CROP) { handleCrop(resultCode, data); } } /** Listeners */ // Create an AlertDialog when the image is clicked private View.OnClickListener mImageClickListener = new View.OnClickListener() { @Override public void onClick(View v) { CharSequence[] options = new CharSequence[] { "Select image from external storage", "Retrieve image from URL" }; AlertDialog.Builder mBuilder = new AlertDialog.Builder(v.getContext()); mBuilder.setTitle("Icon options"); mBuilder.setCancelable(false); mBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); mBuilder.setItems(options, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (which == 0) { Log.d("Image", "Select image from external storage"); checkExternalPermissionThenStart(); } else { Log.d("Image", "Retrieve image from URL"); showImageURLDialog(); } } }); mBuilder.show(); } }; private AdapterView.OnItemSelectedListener mMobileListener = new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { // It is a mobile game if (position == 0) { mMobileLayout.setVisibility(View.VISIBLE); } // Not a mobile game else { mMobileLayout.setVisibility(View.GONE); } } @Override public void onNothingSelected(AdapterView<?> parent) { } }; /** Custom methods */ // Check if the EditText field is empty private boolean isEmpty(EditText editText) { return editText.getText().toString().trim().length() == 0; } // Get the recovery rate integer value (in seconds) private int getRateValue(EditText rate) { int value; if (isEmpty(rate)) { value = 0; } else { value = Integer.parseInt(rate.getText().toString()); } return value * 60; } private void getExistingGameData(Intent i) { Game game = i.getParcelableExtra("game"); appId = game.getId(); String appTitle = game.getTitle(); String appIcon = game.getImage(); String appCategory = game.getCategory(); Log.d("Category", appCategory); if (appCategory.equals("Mobile game")) { String appUnit = game.getUnit(); int appRecovery = game.getRecoveryRate() / 60; int appMax = game.getMaxStamina(); mUnit.setHint(appUnit); mRecovery.setHint(String.valueOf(appRecovery)); mStamina.setHint(String.valueOf(appMax)); } mTitle.setHint(appTitle); imgContent = appIcon; Picasso.with(getApplicationContext()).load(imgContent).into(mImage); String[] categoryArray = getResources().getStringArray(R.array.category_array); mCategory.setSelection(Arrays.asList(categoryArray).indexOf(appCategory), false); } // Update the database with the new game private void updateGameLibrary() { // Title gameTitle = mTitle.getText().toString(); // Image if (imgContent == null) { gameImage = ""; } else { gameImage = imgContent; } // Category gameCategory = mCategory.getSelectedItem().toString(); // Unit if (isEmpty(mUnit)) { staminaUnit = "Stamina"; } else { staminaUnit = mUnit.getText().toString(); } // Recovery rate recoveryRate = getRateValue(mRecovery); // Maximum stamina if (isEmpty(mStamina)) { maxStamina = 0; } else { maxStamina = Integer.parseInt(mStamina.getText().toString()); } Game game = new Game(); game.setTitle(gameTitle); game.setImage(gameImage); game.setCategory(gameCategory); game.setUnit(staminaUnit); game.setRecoveryRate(recoveryRate); game.setMaxStamina(maxStamina); if (flag == 2) { db.updateGame(game, appId); } else { db.addGame(game); } notifyGameAdapter(game); } private void checkExternalPermissionThenStart() { if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) { // Show an explanation to the user *asynchronously* -- don't block // this thread waiting for the user's response! After the user // sees the explanation, try again to request the permission. } else { // No explanation needed, we can request the permission. ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_EXTERNAL_READ_PERMISSION); } } else { Crop.pickImage(this); } } private void showImageURLDialog() { AlertDialog.Builder mBuilder = new AlertDialog.Builder(this); LayoutInflater mInflater = this.getLayoutInflater(); final View mDialogView = mInflater.inflate(R.layout.dialog_image_url, null); mBuilder.setView(mDialogView); final EditText editURL = (EditText) mDialogView.findViewById(R.id.img_url); mBuilder.setTitle("Enter Image URL") .setNegativeButton("Cancel", null) .setPositiveButton("Save", null); final AlertDialog mDialog = mBuilder.create(); mDialog.setOnShowListener(new DialogInterface.OnShowListener() { @Override public void onShow(DialogInterface dialog) { Button cancel = mDialog.getButton(AlertDialog.BUTTON_NEGATIVE); cancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mDialog.cancel(); } }); Button save = mDialog.getButton(AlertDialog.BUTTON_POSITIVE); save.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (isEmpty(editURL)) { Toast.makeText(getApplicationContext(), getString(R.string.unfilled_url), Toast.LENGTH_SHORT).show(); } else { String url = editURL.getText().toString(); if (Patterns.WEB_URL.matcher(url).matches()) { imgContent = url; Picasso.with(getApplicationContext()).load(url).into(mImage); mDialog.dismiss(); } else { Toast.makeText(getApplicationContext(), getString(R.string.invalid_url), Toast.LENGTH_SHORT).show(); } } } }); } }); mDialog.show(); } public void notifyGameAdapter(Game game) { int position = GameAdapter.games.size(); GameAdapter.games.add(position, game); GameListFragment.mGameAdapter.notifyItemInserted(position); GameListFragment.mGameAdapter.notifyItemRangeChanged(0, position); } /** android-crop */ private void beginCrop(Uri source) { // Unique identifier for each cached uri String cacheID = UUID.randomUUID().toString().replaceAll("-", ""); Uri destination = Uri.fromFile(new File(getCacheDir(), cacheID)); Crop.of(source, destination).asSquare().start(this); } private void handleCrop(int resultCode, Intent result) { if (resultCode == RESULT_OK) { Uri output = Crop.getOutput(result); Log.d("icon", output.toString()); Picasso.with(getApplicationContext()).load(output).into(mImage); imgContent = output.toString(); } else if (resultCode == Crop.RESULT_ERROR) { Snackbar.make(mView, Crop.getError(result).getMessage(), Snackbar.LENGTH_SHORT).show(); } } }
34.897751
107
0.599004
d03df5746ff1a84d30d359b9f2ceabbb547a6642
334
package com.travelbank.knit.generators; import com.travelbank.knit.KnitResponse; /** * Generator that accepts 1 parameter. * * @param <K> type of the {@link KnitResponse} body. * * @see ValueGenerator * @author Omer Ozer */ public interface Generator1<T,K> extends ValueGenerator { KnitResponse<T> generate(K param1); }
19.647059
57
0.721557
dbf6549aef46db1b6123271069aba2d6f23655c8
3,956
/* * Copyright 2006 Webmedia Group Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.araneaframework.uilib.form.control; import org.araneaframework.uilib.event.OnClickEventListener; import org.araneaframework.uilib.event.StandardControlEventListenerAdapter; import org.araneaframework.uilib.support.DataType; /** * This class represents a button. * * @author Jevgeni Kabanov (ekabanov@araneaframework.org) */ public class ButtonControl extends BaseControl<String> { protected StandardControlEventListenerAdapter eventHelper = new StandardControlEventListenerAdapter(); /** * Creates a new button control. */ public ButtonControl() {} /** * Creates a new button control with given "onClick" event listener. * * @param onClickEventListener The listener that listens to click events of this button. * @since 2.0 */ public ButtonControl(OnClickEventListener onClickEventListener) { addOnClickEventListener(onClickEventListener); } @Override public boolean isRead() { return true; } /** * Adds an "onClick" listener. * * @param onClickEventListener {@link OnClickEventListener} which is called when the control is clicked. * * @see StandardControlEventListenerAdapter#addOnClickEventListener(OnClickEventListener) */ public void addOnClickEventListener(OnClickEventListener onClickEventListener) { this.eventHelper.addOnClickEventListener(onClickEventListener); } /** * Removes the given "onClick" listener from the registered "onClick" listeners. * * @param onClickEventListener {@link OnClickEventListener} which is called when the control is clicked. * * @see StandardControlEventListenerAdapter#removeOnClickEventListener(OnClickEventListener) * @since 2.0 */ public void removeOnClickEventListener(OnClickEventListener onClickEventListener) { this.eventHelper.removeOnClickEventListener(onClickEventListener); } /** * Discards all registered "onClick" listeners. * * @see StandardControlEventListenerAdapter#clearOnClickEventListeners() * @since 2.0 */ public void clearOnClickEventListeners() { this.eventHelper.clearOnClickEventListeners(); } /** * Returns null, because <code>ButtonControl</code> does not have any data. * * @return <code>null</code>. */ public DataType getRawValueType() { return null; } @Override protected void init() throws Exception { super.init(); setGlobalEventListener(this.eventHelper); } /** * Empty method. Button control is not interested in conversion and validation. */ @Override public void convertAndValidate() {} @Override public ViewModel getViewModel() { return new ViewModel(); } /** * Represents a <code>ButtonControl</code> view model. * * @author Jevgeni Kabanov (ekabanov@araneaframework.org) * */ public class ViewModel extends BaseControl<String>.ViewModel { private boolean hasOnClickEventListeners; /** * Takes an outer class snapshot. */ public ViewModel() { this.hasOnClickEventListeners = ButtonControl.this.eventHelper.hasOnClickEventListeners(); } /** * Returns whether any onClick events have been registered. * * @return whether any onClick events have been registered. */ public boolean isOnClickEventRegistered() { return this.hasOnClickEventListeners; } } }
28.666667
106
0.726997
a05ef8c25fc79aa1c119d7d53b53a842e1dabbee
3,086
/******************************************************************************* * Copyright (c) 2016 Alex Shapiro - github.com/shpralex * This program and the accompanying materials * are made available under the terms of the The MIT License (MIT) * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. *******************************************************************************/ package com.sproutlife.model.seed; import java.awt.Point; import com.sproutlife.model.rotations.Rotation; import com.sproutlife.model.rotations.Rotations; public class BitPattern { protected int[][] bitPattern; protected Point onBit = null; public BitPattern() { } public BitPattern(int[][] bitPattern) { this.bitPattern = bitPattern; } public BitPattern(int[][] bitPattern, boolean xySwitch) { if (xySwitch) { this.bitPattern = xySwitch(bitPattern); } else { this.bitPattern = bitPattern; } } public int getWidth() { return bitPattern.length; } public int getWidth(Rotation r) { if (r.getAngle()==0 || r.getAngle()==2) { return getWidth(); } return getHeight(); } public int getHeight() { return bitPattern[0].length; } public int getHeight(Rotation r) { if (r.getAngle()==0 || r.getAngle()==2) { return getHeight(); } return getWidth(); } boolean getBit(int x, int y) { return bitPattern[x][y]==1; } boolean getBit(int x, int y, Rotation r) { Point rp = Rotations.fromBoard(new Point(x,y), this, r); return getBit(rp.x, rp.y); } public Point getCenter() { return new Point((getWidth()-1)/2,(getHeight()-1)/2); } public Point getCenter(Rotation r) { return Rotations.toBoard(getCenter(), this, r); } public Point getOnBit() { if (this.onBit!=null) { return this.onBit; } else { for (int x=0;x<getWidth();x++) { for (int y=0;y<getHeight();y++) { if (getBit(x,y)) { this.onBit = new Point(x,y); return onBit; } } } } return null; } public Point getOnBit(Rotation r) { return Rotations.toBoard(getOnBit(), this, r); } public static int[][] xySwitch(int[][] shape) { if (shape.length==0) { return new int[0][0]; } int[][] newShape = new int[shape[0].length][shape.length]; for (int i=0;i<shape.length;i++) { for (int j=0;j<shape[0].length;j++) { newShape[j][i] = shape[i][j]; } } return newShape; } }
26.376068
81
0.477641
704383c6bfa715e30458cc2e387508cc0c44d07a
959
package no.nav.foreldrepenger.fordel.web.app.metrics; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; import javax.enterprise.context.ApplicationScoped; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.core.Response; import io.prometheus.client.CollectorRegistry; import io.swagger.v3.oas.annotations.Operation; @Path("/metrics") @ApplicationScoped public class PrometheusRestService { @GET @Operation(tags = "metrics", hidden = true) @Path("/prometheus") public Response prometheus() { try (final Writer writer = new StringWriter()) { TextFormatter.write004(writer, CollectorRegistry.defaultRegistry.metricFamilySamples()); return Response.ok().encoding("UTF-8").entity(writer.toString()).header("content-type", TextFormatter.CONTENT_TYPE_004).build(); } catch (IOException e) { throw new IllegalStateException(e); } } }
29.96875
140
0.719499
97b4ad698f15499aeacc6ced0d3915c1fc67f9e3
1,606
package eu.dirk.haase.bean.hierarchy; import eu.dirk.haase.bean.MwsBeanImpl; import eu.dirk.haase.test.MwsTestContextConfiguration; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.annotation.Resource; @RunWith(SpringJUnit4ClassRunner.class) @MwsTestContextConfiguration(beanCategories = {"One", "Two"}, enableAnnotationBasedConfiguration = false) @ActiveProfiles("my-profile") public class MyTest implements ApplicationContextAware { private ApplicationContext applicationContext; @Resource(name = "eins") private MwsBeanImpl eins; @Resource(name = "zwei") private MwsBeanImpl zwei; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } // @Resource(name = "vier") // private MwsBeanImpl vier; @Test public void test_one_ctx() { System.out.println("eins: " + this.applicationContext.getBean("eins")); } @Test public void test_two_ctx() { System.out.println("zwei: " + this.applicationContext.getBean("zwei")); } @Test public void test_one() { System.out.println("eins: " + eins); } @Test public void test_two() { System.out.println("zwei: " + zwei); } }
28.678571
105
0.734745
8b4668df5f39ec76897ce1e79831c42f77d04721
11,027
/* * (C) Copyright 2013, 2015 Wojciech Mruczkiewicz * * 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. * * Contributors: * Wojciech Mruczkiewicz */ package pl.mrwojtek.sensrec.app; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.os.Handler; import android.os.IBinder; import android.os.PowerManager; import android.os.SystemClock; import android.support.annotation.Nullable; import android.support.v7.app.NotificationCompat; import android.util.Log; import pl.mrwojtek.sensrec.SensorsRecorder; /** * Android service to keep the app running. */ public class RecordingService extends Service implements SensorsRecorder.OnRecordingListener { public static final String ACTION_PAUSE_RECORDING = "pl.mrwojtek.sensrec.PauseRecording"; public static final String ACTION_START_RECORDING = "pl.mrwojtek.sensrec.StartRecording"; public static final String ACTION_STOP_RECORDING = "pl.mrwojtek.sensrec.StopRecording"; private static final String TAG = "SensRec"; private static final int NOTIFICATION_ID = 1; private static final int MINIMUM_DELAY = 300; private static final int SECOND = 1000; private static final int MINUTE = 60; private static final int HOUR = 60; protected static SensorsRecorder recorder; protected PendingIntent contentIntent; protected PendingIntent startIntent; protected PendingIntent stopIntent; protected PendingIntent pauseIntent; protected NotificationCompat.Builder notificationBuilder; protected Handler uiHandler; protected Runnable recordingRunnable; protected PowerManager.WakeLock wakeLock; protected int lastStartId; public static SensorsRecorder getRecorder(Context context) { if (recorder == null) { recorder = new SensorsRecorder(context); } return recorder; } public static void startService(Context context, String action) { Intent intent = new Intent(context, RecordingService.class); intent.setAction(action); context.startService(intent); } public static String getTimeText(Context context, int stringId, long duration) { duration /= SECOND; long seconds = duration % MINUTE; duration /= MINUTE; long minutes = duration % HOUR; long hours = duration / HOUR; return context.getString(stringId, hours, minutes, seconds); } @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { lastStartId = startId; if (intent != null) { if (ACTION_START_RECORDING.equals(intent.getAction())) { Log.i(TAG, "onStartCommand " + lastStartId + " START"); recorder.start(); onStarted(); return START_REDELIVER_INTENT; } else if (ACTION_STOP_RECORDING.equals(intent.getAction())) { Log.i(TAG, "onStopCommand " + lastStartId + " STOP"); recorder.stop(); onStopped(); return START_REDELIVER_INTENT; } else if (ACTION_PAUSE_RECORDING.equals(intent.getAction())) { Log.i(TAG, "onPauseCommand " + lastStartId + " PAUSE"); recorder.pause(); onPaused(); return START_REDELIVER_INTENT; } } if (!recorder.isActive()) { Log.i(TAG, "onStartCommand " + lastStartId + " OTHER"); stopSelf(lastStartId); } return START_REDELIVER_INTENT; } @Override public void onCreate() { super.onCreate(); getRecorder(this).addOnRecordingListener(this, false); } @Override public void onDestroy() { recorder.removeOnRecordingListener(this); super.onDestroy(); } @Override public void onStarted() { Log.i(TAG, "onStarted " + lastStartId); takeWakeLock(); notificationBuilder = null; startForeground(NOTIFICATION_ID, getNotification()); startNotificationClock(); } @Override public void onStopped() { Log.i(TAG, "onStopped " + lastStartId); stopNotificationClock(); stopForeground(true); notificationBuilder = null; stopSelf(lastStartId); releaseWakeLock(); updateNotification(); } @Override public void onPaused() { Log.i(TAG, "onPaused " + lastStartId); stopNotificationClock(); stopForeground(false); notificationBuilder = null; stopSelf(lastStartId); releaseWakeLock(); updateNotification(); } @Override public void onOutput(boolean saving, boolean streaming) { if (notificationBuilder != null) { notificationBuilder.setContentText(getNotificationText()); updateNotification(); } } public void takeWakeLock() { if (wakeLock == null) { Log.i(TAG, "takeWakeLock " + lastStartId); PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE); wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG); wakeLock.acquire(); } } public void releaseWakeLock() { if (wakeLock != null) { Log.i(TAG, "releaseWakeLock " + lastStartId); wakeLock.release(); wakeLock = null; } } private void startNotificationClock() { if (uiHandler == null) { recordingRunnable = new Runnable() { @Override public void run() { long duration = scheduleUpdate(); updateNotification(duration); } }; uiHandler = new Handler(getMainLooper()); scheduleUpdate(); } } private long scheduleUpdate() { long duration = recorder.getDuration(SystemClock.elapsedRealtime()); long delay = (SECOND - (duration % SECOND)) % SECOND; uiHandler.postDelayed(recordingRunnable, (delay < MINIMUM_DELAY ? SECOND : 0) + delay + 1); return duration; } private void stopNotificationClock() { if (uiHandler != null) { uiHandler.removeCallbacks(recordingRunnable); uiHandler = null; } } private void updateNotification() { updateNotification(recorder.getDuration(SystemClock.elapsedRealtime())); } private void updateNotification(long duration) { Log.d(TAG, "notification update " + duration); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); if (recorder.isActive()) { notificationManager.notify(NOTIFICATION_ID, getNotification(duration)); } else { notificationManager.cancel(NOTIFICATION_ID); } } private Notification getNotification() { return getNotification(recorder.getDuration(SystemClock.elapsedRealtime())); } private Notification getNotification(long duration) { if (notificationBuilder == null) { notificationBuilder = new NotificationCompat.Builder(this); notificationBuilder.setSmallIcon(R.drawable.ic_stat_sens_rec); notificationBuilder.setContentText(getNotificationText()); notificationBuilder.setContentIntent(getContentIntent()); // and FLAG_NO_CLEAR if (recorder.isActive()) { notificationBuilder.addAction(R.drawable.ic_stop_white_24dp, getString(R.string.record_stop), getStopIntent()); } if (recorder.isPaused()) { notificationBuilder.addAction(R.drawable.ic_fiber_manual_record_white_24dp, getString(R.string.record_restart), getStartIntent()); } else if (recorder.isActive()) { notificationBuilder.addAction(R.drawable.ic_pause_white_24dp, getString(R.string.record_pause), getPauseIntent()); } } notificationBuilder.setContentTitle( getTimeText(this, R.string.record_notification_clock, duration)); return notificationBuilder.build(); } private String getNotificationText() { if (recorder.isSaving() && recorder.isStreaming()) { return getString(R.string.output_saving_streaming); } else if (recorder.isSaving()) { return getString(R.string.output_saving); } else if (recorder.isStreaming()) { return getString(R.string.output_streaming); } else { return getString(R.string.output_disabled); } } public PendingIntent getContentIntent() { if (contentIntent == null) { Intent intent = new Intent(this, RecordsActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK); contentIntent = PendingIntent.getActivity( this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); } return contentIntent; } public PendingIntent getStartIntent() { if (startIntent == null) { Intent intent = new Intent(this, RecordingService.class); intent.setAction(ACTION_START_RECORDING); startIntent = PendingIntent.getService( this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); } return startIntent; } public PendingIntent getStopIntent() { if (stopIntent == null) { Intent intent = new Intent(this, RecordingService.class); intent.setAction(ACTION_STOP_RECORDING); stopIntent = PendingIntent.getService( this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); } return stopIntent; } public PendingIntent getPauseIntent() { if (pauseIntent == null) { Intent intent = new Intent(this, RecordingService.class); intent.setAction(ACTION_PAUSE_RECORDING); pauseIntent = PendingIntent.getService( this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); } return pauseIntent; } }
34.567398
95
0.634896
bf88f34a01173ead4c4ca6fc0ffa6a116c17bf2b
1,494
package au.org.garvan.vsal.beacon.entity; import javax.xml.bind.annotation.XmlRootElement; import java.util.List; @XmlRootElement(name = "ssvs-beacon-response") public class BeaconResponseSSVS { private CoreQuery coreQuery; private Long ssvsTimeMs; // ms private List<Variant> variants; private Long total; // total # variants private Error error; public BeaconResponseSSVS() { // needed for JAXB } public BeaconResponseSSVS(CoreQuery coreQuery, Long ssvsTimeMs, List<Variant> variants, Long total, Error error) { this.coreQuery = coreQuery; this.ssvsTimeMs = ssvsTimeMs; this.variants = variants; this.total = total; this.error = error; } public CoreQuery getCoreQuery() { return coreQuery; } public void setCoreQuery(CoreQuery coreQuery) { this.coreQuery = coreQuery; } public Long getSsvsTimeMs() { return ssvsTimeMs; } public void setSsvsTimeMs(Long ssvsTimeMs) { this.ssvsTimeMs = ssvsTimeMs; } public List<Variant> getVariants() { return variants; } public void setVariants(List<Variant> variants) { this.variants = variants; } public Long getTotal() { return total; } public void setTotal(Long total) { this.total = total; } public Error getError() { return error; } public void setError(Error error) { this.error = error; } }
22.636364
118
0.637216
7069ec6d48113ebff657cd6a283fd19093507849
650
package org.jahia.modules.jahiaauth.service; import java.io.Serializable; public class MappedProperty implements Serializable { private MappedPropertyInfo info; private Serializable value; public MappedPropertyInfo getInfo() { return info; } public void setInfo(MappedPropertyInfo info) { this.info = info; } public Object getValue() { return value; } public void setValue(Object value) { this.value = (Serializable) value; } public MappedProperty(MappedPropertyInfo info, Object value) { this.info = info; this.value = (Serializable) value; } }
20.967742
66
0.663077
d5a9f365f9e62e5ef05cb43c0ad5ae836d058436
2,176
// BSD License (http://lemurproject.org/galago-license) package org.lemurproject.galago.core.retrieval.extents; import org.junit.Test; import org.lemurproject.galago.core.retrieval.iterator.ThresholdIterator; import org.lemurproject.galago.core.retrieval.processing.ScoringContext; import org.lemurproject.galago.core.retrieval.query.NodeParameters; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** * * @author marc */ public class ThresholdIteratorTest { private static final int[] docsA = new int[]{5, 10, 15, 20}; private static final double[] scoresA = new double[]{1.0, 2.0, 3.0, 4.0}; @Test public void testA() throws Exception { FakeScoreIterator inner = new FakeScoreIterator(docsA, scoresA); ScoringContext dc = new ScoringContext(); NodeParameters dummyParameters = new NodeParameters(); dummyParameters.set("raw", 2.5); ThresholdIterator iterator = new ThresholdIterator(dummyParameters, inner); assertFalse(iterator.isDone()); dc.document = iterator.currentCandidate(); assertTrue(iterator.hasMatch(dc)); assertFalse(iterator.indicator(dc)); iterator.movePast(docsA[0]); assertFalse(iterator.isDone()); dc.document = iterator.currentCandidate(); assertTrue(iterator.hasMatch(dc)); assertFalse(iterator.indicator(dc)); iterator.movePast(docsA[1]); assertFalse(iterator.isDone()); dc.document = iterator.currentCandidate(); assertTrue(iterator.hasMatch(dc)); assertTrue(iterator.indicator(dc)); iterator.movePast(docsA[2]); assertFalse(iterator.isDone()); dc.document = iterator.currentCandidate(); assertTrue(iterator.hasMatch(dc)); assertTrue(iterator.indicator(dc)); iterator.movePast(docsA[3]); assertTrue(iterator.isDone()); iterator.reset(); dc.document = iterator.currentCandidate(); assertTrue(iterator.hasMatch(dc)); assertFalse(iterator.indicator(dc)); iterator.movePast(docsA[2]); assertFalse(iterator.isDone()); dc.document = iterator.currentCandidate(); assertTrue(iterator.hasMatch(dc)); assertTrue(iterator.indicator(dc)); } }
32
79
0.723346
29537ac1e85a62450ecd98e8c7d5ede9542e18e2
397
public class InicioDeJogo extends Comunicado{ private String nomeDoUsuario; public InicioDeJogo(String nome) throws Exception{ if(nome == null || nome.length() == 0) throw new Exception("O nome do usuário não pode ser nulo e nem vazio."); this.nomeDoUsuario = nome; } public String getNomeUsuario(){ return this.nomeDoUsuario; } }
18.045455
84
0.639798
49079c0b6b4fb0b801a038428dc929377367a3e6
2,976
package com.bergerkiller.generated.net.minecraft.server; import com.bergerkiller.mountiplex.reflection.util.StaticInitHelper; import com.bergerkiller.mountiplex.reflection.declarations.Template; import com.bergerkiller.bukkit.common.wrappers.HumanHand; /** * Instance wrapper handle for type <b>net.minecraft.server.PacketPlayInSettings</b>. * To access members without creating a handle type, use the static {@link #T} member. * New handles can be created from raw instances using {@link #createHandle(Object)}. */ public abstract class PacketPlayInSettingsHandle extends PacketHandle { /** @See {@link PacketPlayInSettingsClass} */ public static final PacketPlayInSettingsClass T = new PacketPlayInSettingsClass(); static final StaticInitHelper _init_helper = new StaticInitHelper(PacketPlayInSettingsHandle.class, "net.minecraft.server.PacketPlayInSettings", com.bergerkiller.bukkit.common.Common.TEMPLATE_RESOLVER); /* ============================================================================== */ public static PacketPlayInSettingsHandle createHandle(Object handleInstance) { return T.createHandle(handleInstance); } /* ============================================================================== */ public HumanHand getMainHand() { if (T.mainHand.isAvailable()) { return T.mainHand.get(getRaw()); } else { return HumanHand.RIGHT; } } public void setMainHand(HumanHand mainHand) { if (T.mainHand.isAvailable()) { T.mainHand.set(getRaw(), mainHand); } } public abstract String getLocale(); public abstract void setLocale(String value); public abstract int getView(); public abstract void setView(int value); public abstract Object getChatVisibility(); public abstract void setChatVisibility(Object value); public abstract boolean isEnableColors(); public abstract void setEnableColors(boolean value); public abstract int getModelPartFlags(); public abstract void setModelPartFlags(int value); /** * Stores class members for <b>net.minecraft.server.PacketPlayInSettings</b>. * Methods, fields, and constructors can be used without using Handle Objects. */ public static final class PacketPlayInSettingsClass extends Template.Class<PacketPlayInSettingsHandle> { public final Template.Field<String> locale = new Template.Field<String>(); public final Template.Field.Integer view = new Template.Field.Integer(); public final Template.Field.Converted<Object> chatVisibility = new Template.Field.Converted<Object>(); public final Template.Field.Boolean enableColors = new Template.Field.Boolean(); public final Template.Field.Integer modelPartFlags = new Template.Field.Integer(); @Template.Optional public final Template.Field.Converted<HumanHand> mainHand = new Template.Field.Converted<HumanHand>(); } }
45.090909
206
0.69254
2d9b3ed7b2923a5c0dc33c95a6fae6864bc69917
2,072
/*- * ==========================LICENSE_START================================= * PolyGenesis Platform * ======================================================================== * Copyright (C) 2015 - 2019 Christos Tsakostas, OREGOR LTD * ======================================================================== * 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. * ===========================LICENSE_END================================== */ package io.polygenesis.core; /** * The type Data type transformer. * * @author Christos Tsakostas */ public interface DataTypeTransformer { /** * Convert string. * * @param dataType the data type * @return the string */ String convert(String dataType); /** * Gets modifier public. * * @return the modifier public */ String getModifierPublic(); /** * Gets modifier protected. * * @return the modifier protected */ String getModifierProtected(); /** * Gets modifier private. * * @return the modifier private */ String getModifierPrivate(); /** * Gets modifier private final. * * @return the modifier private final */ String getModifierPrivateFinal(); /** * Gets modifier abstract. * * @return the modifier abstract */ String getModifierAbstract(); /** * Gets void. * * @return the void */ String getVoid(); /** * Gets array of elements. * * @param elementDataType the element data type * @return the array of elements */ String getArrayOfElements(String elementDataType); }
23.545455
75
0.581564
6e114fbe2a46cdd71958b65a3307d0843775c93c
714
package main; import java.awt.Image; import java.io.File; import java.io.IOException; import java.util.ArrayList; import javax.imageio.ImageIO; public class Animation { private int speed; public ArrayList<Image> sprites = new ArrayList<Image>(); public Animation(int speed){ this.setSpeed(speed); } public void add(String path){ Image img; try{ img = ImageIO.read(new File(path)); sprites.add(img); }catch(IOException e){ e.printStackTrace(); } } public void startAnimation(){ try { Thread.sleep(this.speed); } catch (InterruptedException e) { e.printStackTrace(); } } public int getSpeed() {return speed;} public void setSpeed(int speed) {this.speed = speed;} }
18.307692
58
0.696078
f86322fcba319ac137e1fdacf25545006c6ff00e
2,425
package net.shmin.auth.handler.impl; import net.shmin.auth.handler.IRequestHandler; import net.shmin.core.util.CodecUtil; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Enumeration; import java.util.List; import static net.shmin.core.Constant.VERIFY_CODE; /** * 验证签名值 * Created by benjamin on 9/11/14. */ @Component public class ValidCodeRequestHandler implements IRequestHandler { @Override public boolean handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { String sortedParam = sortedParam(request); // 对比签名值 // String clientHashValue = request.getHeader(VERIFY_CODE); // 无参 if (sortedParam == null || sortedParam.isEmpty()) { return true; } else { String hashValue = CodecUtil.md5hex(sortedParam); return hashValue.equals(clientHashValue); } } /** * 将请求参数按照英文首字母排序 * example: a=b&ab=c&d=e * 客户端也要按照此排序规则对request做签名值,(参照sina的oauth实现(少许修改),http://open.weibo.com/wiki/Oauth) * 然后对比md5值 * * @param request * @return */ private String sortedParam(HttpServletRequest request) throws IOException { String contentType = request.getContentType(); // 目前只验证表单类型的数据 if (contentType.contains("application/www-x-form-urlencoded")){ List<String> params = new ArrayList<String>(); Enumeration<String> enumeration = request.getParameterNames(); while (enumeration.hasMoreElements()) { params.add(enumeration.nextElement()); } Collections.sort(params, String.CASE_INSENSITIVE_ORDER); StringBuilder stringBuilder = new StringBuilder(); for (String paramName : params) { stringBuilder.append(paramName); stringBuilder.append("="); stringBuilder.append(request.getParameter(paramName)); stringBuilder.append("&"); } if (stringBuilder.toString().isEmpty()) { return null; } return stringBuilder.toString().substring(0, stringBuilder.length() - 1); } return null; } }
33.680556
109
0.645773
a2353817277c0679788841223f2af33772b4acb0
2,205
/* -*- Mode: Java; c-basic-offset: 4; tab-width: 20; indent-tabs-mode: nil; -*- * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.gecko.gfx; import org.mozilla.gecko.mozglue.DirectBufferAllocator; import android.graphics.Bitmap; import java.nio.ByteBuffer; /** A Cairo image that simply saves a buffer of pixel data. */ public class BufferedCairoImage extends CairoImage { private ByteBuffer mBuffer; private IntSize mSize; private int mFormat; private boolean mNeedToFreeBuffer; /** Creates a buffered Cairo image from a byte buffer. */ public BufferedCairoImage(ByteBuffer inBuffer, int inWidth, int inHeight, int inFormat) { setBuffer(inBuffer, inWidth, inHeight, inFormat); } /** Creates a buffered Cairo image from an Android bitmap. */ public BufferedCairoImage(Bitmap bitmap) { setBitmap(bitmap); } private void freeBuffer() { if (mNeedToFreeBuffer) DirectBufferAllocator.free(mBuffer); mNeedToFreeBuffer = false; mBuffer = null; } protected void finalize() throws Throwable { try { freeBuffer(); } finally { super.finalize(); } } @Override public ByteBuffer getBuffer() { return mBuffer; } @Override public IntSize getSize() { return mSize; } @Override public int getFormat() { return mFormat; } public void setBuffer(ByteBuffer buffer, int width, int height, int format) { freeBuffer(); mBuffer = buffer; mSize = new IntSize(width, height); mFormat = format; } public void setBitmap(Bitmap bitmap) { mFormat = CairoUtils.bitmapConfigToCairoFormat(bitmap.getConfig()); mSize = new IntSize(bitmap.getWidth(), bitmap.getHeight()); mNeedToFreeBuffer = true; int bpp = CairoUtils.bitsPerPixelForCairoFormat(mFormat); mBuffer = DirectBufferAllocator.allocate(mSize.getArea() * bpp); bitmap.copyPixelsToBuffer(mBuffer.asIntBuffer()); } }
31.056338
93
0.664399
ece40244aca4f01c39d638ff2e13f27dea0a037d
319
package crimereport.crimes; public class Geometry { private String type = "Point"; private double[] coordinates; public String getType() { return type; } public double[] getCoordinates() { return coordinates; } public void setCoordinates(double[] coordinates) { this.coordinates = coordinates; } }
15.95
51
0.714734
b91b31836385fadc205aaf60602759483054d878
4,547
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ignite.spi.communication.tcp; import java.net.SocketException; import org.apache.ignite.IgniteCache; import org.apache.ignite.cluster.ClusterState; import org.apache.ignite.cluster.ClusterTopologyException; import org.apache.ignite.configuration.CacheConfiguration; import org.apache.ignite.configuration.IgniteConfiguration; import org.apache.ignite.failure.StopNodeFailureHandler; import org.apache.ignite.internal.IgniteEx; import org.apache.ignite.internal.IgniteKernal; import org.apache.ignite.internal.util.typedef.internal.U; import org.apache.ignite.spi.communication.CommunicationSpi; import org.apache.ignite.spi.communication.tcp.internal.ConnectionClientPool; import org.apache.ignite.spi.communication.tcp.internal.GridNioServerWrapper; import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest; import org.apache.ignite.transactions.Transaction; import org.junit.Test; import static org.apache.ignite.cache.CacheAtomicityMode.TRANSACTIONAL; import static org.apache.ignite.cache.CacheMode.PARTITIONED; import static org.apache.ignite.testframework.GridTestUtils.waitForCondition; import static org.apache.ignite.transactions.TransactionConcurrency.PESSIMISTIC; import static org.apache.ignite.transactions.TransactionIsolation.REPEATABLE_READ; /** * Test class for error "Too many open files" when in {@link TcpCommunicationSpi}. */ public class TooManyOpenFilesTcpCommunicationSpiTest extends GridCommonAbstractTest { /** {@inheritDoc} */ @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception { return super.getConfiguration(igniteInstanceName) .setFailureHandler(new StopNodeFailureHandler()) .setConsistentId(igniteInstanceName) .setCacheConfiguration( new CacheConfiguration<>(DEFAULT_CACHE_NAME) .setAtomicityMode(TRANSACTIONAL) .setBackups(1) .setCacheMode(PARTITIONED) ); } /** {@inheritDoc} */ @Override protected void beforeTest() throws Exception { super.beforeTest(); stopAllGrids(); } /** {@inheritDoc} */ @Override protected void afterTest() throws Exception { stopAllGrids(); super.afterTest(); } /** * Test checks that node will fail in case of error "Too many open files" in {@link TcpCommunicationSpi}. * * @throws Exception If failed. */ @Test public void testTooManyOpenFilesErr() throws Exception { IgniteEx crd = startGrids(3); crd.cluster().state(ClusterState.ACTIVE); IgniteEx stopNode = grid(2); CommunicationSpi stopNodeSpi = stopNode.context().config().getCommunicationSpi(); ConnectionClientPool connPool = U.field(stopNodeSpi, "clientPool"); GridNioServerWrapper nioSrvWrapper = U.field(stopNodeSpi, "nioSrvWrapper"); IgniteEx txNode = grid(1); try (Transaction tx = txNode.transactions().txStart(PESSIMISTIC, REPEATABLE_READ, 60_000, 4)) { IgniteCache<Object, Object> cache = txNode.cache(DEFAULT_CACHE_NAME); cache.put(0, 1); nioSrvWrapper.socketChannelFactory(() -> { throw new SocketException("Too many open files"); }); connPool.forceCloseConnection(txNode.localNode().id()); cache.put(1, 2); cache.put(2, 3); cache.put(3, 4); // hungs here. tx.commit(); } catch (ClusterTopologyException e) { log.error("Error wait commit", e); } assertTrue(waitForCondition(((IgniteKernal)stopNode)::isStopping, 60_000)); } }
38.863248
109
0.711678
7a407f6e35ec57808ff81fb43c32cff49c6d5798
2,729
package com.pivotal.pcf.mysqlweb; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; import com.pivotal.pcf.mysqlweb.controller.LoginController; import com.pivotal.pcf.mysqlweb.controller.TableController; import org.junit.Before; import org.junit.Test; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Bean; import org.springframework.http.MediaType; import org.springframework.test.context.junit.jupiter.SpringExtension; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import org.springframework.boot.test.context.TestConfiguration; // FIXME What does this test want to be? A client integration test? A mock controller test? // Obviously latter is not as heavy-weight. Would need to intro @MockBean for controller service dependencies. @Disabled @ExtendWith(SpringExtension.class) @SpringBootTest(classes = { PivotalMySqlWebTestApplication.class }) public class WebUITests { @Autowired private WebApplicationContext ctx; private MockMvc mockMvc; @Before public void setUp() { this.mockMvc = MockMvcBuilders.webAppContextSetup(ctx).build(); } @Test public void testLoginPage() throws Exception { mockMvc.perform(get("/").accept(MediaType.TEXT_HTML)) //.andDo(print()) .andExpect(status().isOk()) .andExpect(view().name("login")); } @Test public void testLoginMySQL() throws Exception { mockMvc.perform(post("/login") .param("username", "pas") .param("password", "pas") .param("url", "jdbc:mysql://localhost:3306/employees") .accept(MediaType.TEXT_HTML)) //.andDo(print()) .andExpect(status().isOk()) .andExpect(view().name("main")); } @TestConfiguration static class TestControllerConfiguration { @Bean public LoginController loginController() { return new LoginController(); } @Bean public TableController tableController() { return new TableController(); } } }
37.383562
110
0.71528
bc6b0f0ff698548c91ca2f60528cae8841297fcb
2,358
/* * Copyright (c) 2001-2003 Regents of the University of California. * All rights reserved. * * See the file LICENSE included in this distribution for details. */ package bamboo.router; import java.math.BigInteger; import java.util.Iterator; import java.util.LinkedList; import ostore.network.NetworkMessage; import ostore.util.InputBuffer; import ostore.util.NodeId; import ostore.util.OutputBuffer; import ostore.util.QSException; import ostore.util.QuickSerializable; /** * IterRouteResp. * * @author Sean C. Rhea * @version $Id: IterRouteResp.java,v 1.6 2003/10/05 18:22:11 srhea Exp $ */ public class IterRouteResp extends NetworkMessage { public BigInteger dest; public BigInteger src; public long app_id; public boolean intermediate_upcall; public QuickSerializable payload; public NeighborInfo next_hop; public IterRouteResp (NodeId n, BigInteger s, BigInteger d, long a, boolean u, QuickSerializable p, NeighborInfo nh) { super (n, false); src = s; dest = d; app_id = a; payload = p; intermediate_upcall = u; next_hop = nh; } public IterRouteResp (InputBuffer buffer) throws QSException { super (buffer); src = buffer.nextBigInteger (); dest = buffer.nextBigInteger (); app_id = buffer.nextLong (); intermediate_upcall = buffer.nextBoolean (); payload = buffer.nextObject (); next_hop = new NeighborInfo (buffer); } public void serialize (OutputBuffer buffer) { super.serialize (buffer); buffer.add (src); buffer.add (dest); buffer.add (app_id); buffer.add (intermediate_upcall); buffer.add (payload); next_hop.serialize (buffer); } public Object clone () throws CloneNotSupportedException { IterRouteResp result = (IterRouteResp) super.clone (); result.src = src; result.dest = dest; result.app_id = app_id; result.intermediate_upcall = intermediate_upcall; result.payload = payload; result.next_hop = next_hop; return result; } public String toString () { return "(IterRouteResp " + super.toString() + " src=" + bamboo.util.GuidTools.guid_to_string(src) + " dest=" + bamboo.util.GuidTools.guid_to_string(dest) + " app_id=" + app_id + " intermediate_upcall=" + intermediate_upcall + " payload=" + payload + " next_hop=" + next_hop + ")"; } }
27.103448
73
0.69296
bdd14a7125200d266f2a734d020334f307d7b109
305
package domain.bed.exception; public class InvalidDateWithoutMinCapacityException extends AirbnbException { public InvalidDateWithoutMinCapacityException() { super( "ARRIVAL_DATE_WITHOUT_MINIMAL_CAPACITY", "a minimal capacity should be provided along with the arrival date"); } }
30.5
77
0.777049
09ac4434e6012b275574c50b970dd522b824f5cf
1,511
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ____ _ _____ _ * / ___| _ __ _ __(_)_ __ __ |_ _| _ _ __| |__ ___ * \___ \| '_ \| '__| | '_ \ / _` || || | | | '__| '_ \ / _ \ * ___) | |_) | | | | | | | (_| || || |_| | | | |_) | (_) | * |____/| .__/|_| |_|_| |_|\__, ||_| \__,_|_| |_.__/ \___/ * |_| |___/ https://github.com/yingzhuo/spring-turbo * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ package spring.turbo.module.captcha.google.renderer; import java.util.Random; /** * @since 1.0.0 */ public class RandomYBestFitTextRenderer extends AbstractTextRenderer { @Override protected void arrangeCharacters(int width, int height, TextString ts) { double widthRemaining = (width - ts.getWidth() - leftMargin - rightMargin) / ts.getCharacters().size(); double vmiddle = height / 2; double x = leftMargin + widthRemaining / 2; Random r = new Random(); height -= topMargin + bottomMargin; for (TextCharacter tc : ts.getCharacters()) { double heightRemaining = height - tc.getHeight(); double y = vmiddle + 0.35 * tc.getAscent() + (1 - 2 * r.nextDouble()) * heightRemaining; tc.setX(x); tc.setY(y); x += tc.getWidth() + widthRemaining; } } }
43.171429
121
0.434811
13d99b3ffc1888996df25b9c79666c09441843c8
4,660
package validbst; import jdk.nashorn.internal.ir.ThrowNode; import java.util.*; public class ValidBST { public static void main(String[] args) { Solution solution = new Solution(); //System.out.println(solution.minDepth(TreeNode.instance())); System.out.println(solution.generateParenthesis(3)); } static class Solution { public boolean isValidBST(TreeNode root) { //return performTraversals(root); return help(root, null, null); } //方法一 private final Stack<Integer> stack = new Stack<>(); private boolean performTraversals(TreeNode root) { boolean a1 = true, a2 = true; if (root != null) { a1 = performTraversals(root.left); if (stack.empty()) { stack.push(root.val); } else { if (stack.peek() >= root.val) { return false; } else { stack.push(root.val); } } a2 = performTraversals(root.right); } return a1 && a2; } //方法二 private boolean help(TreeNode root, Integer min, Integer max) { if (root == null) return true; if (min != null && min >= root.val) return false; if (max != null && max <= root.val) return false; return help(root.right, root.val, max) && help(root.left, min, root.val); } //二叉树层序遍历 public List<List<Integer>> levelOrder(TreeNode root) { List<List<Integer>> lists = new ArrayList<>(); if (root == null) return lists; Queue<TreeNode> queue = new LinkedList<>(); queue.add(root); while (!queue.isEmpty()) { List<Integer> list = new ArrayList<>(); int size = queue.size(); for (int i = 0; i < size; i++) { TreeNode treeNode = queue.poll(); list.add(treeNode.val); if (treeNode.left != null) queue.add(treeNode.left); if (treeNode.right != null) queue.add(treeNode.right); } lists.add(list); } return lists; } //二叉树的最大深度 public int maxDepth(TreeNode root) { if (root == null) return 0; Queue<TreeNode> queue = new LinkedList<>(); queue.add(root); int count = 0; while (!queue.isEmpty()) { int size = queue.size(); for (int i = 0; i < size; i++) { TreeNode treeNode = queue.poll(); if (treeNode.left != null) queue.add(treeNode.left); if (treeNode.right != null) queue.add(treeNode.right); } count++; } return count; } //二叉树的最小深度 public int minDepth(TreeNode root) { //广度优先搜索 /*if (root == null) return 0; Queue<TreeNode> queue = new LinkedList<>(); queue.add(root); int count = 0; while (!queue.isEmpty()) { count++; int size = queue.size(); for (int i = 0; i < size; i++) { TreeNode treeNode = queue.poll(); if (treeNode.left != null) queue.add(treeNode.left); if (treeNode.right != null) queue.add(treeNode.right); if (treeNode.left == null && treeNode.right == null) return count; } } return count;*/ //深度优先搜索 if (root == null) return 0; int left = minDepth(root.left); int right = minDepth(root.right); return (left == 0 || right == 0) ? left + right + 1 : Math.min(left, right) + 1; } //括号生成 public List<String> generateParenthesis(int n) { List<String> result = new ArrayList<>(); generateOneByOne("", result, n, n); return result; } public void generateOneByOne(String sublist, List<String> result, int left, int right) { if (left == 0 && right == 0) { result.add(sublist); return; } if (left > 0) { generateOneByOne(sublist + "(", result, left - 1, right); } if (right > left) { generateOneByOne(sublist + ")", result, left, right - 1); } } } }
34.264706
96
0.463519
24157262f7f800f2696546f9f562b6f41d6f65ad
1,023
package com.custom_computing_ic.maxdeep.kernel.conv2d; import com.custom_computing_ic.maxdeep.kernel.conv2d.lib.Conv2DKernel; import com.custom_computing_ic.maxdeep.lib.BinarizedDotProduct; import com.maxeler.maxcompiler.v2.kernelcompiler.KernelBase; import com.maxeler.maxcompiler.v2.kernelcompiler.types.base.DFEType; import com.maxeler.maxcompiler.v2.kernelcompiler.types.base.DFEVar; import com.maxeler.maxcompiler.v2.kernelcompiler.types.composite.DFEVector; public class BinarizedConv2DKernel extends Conv2DKernel { public BinarizedConv2DKernel(KernelBase<?> owner, ConvLayerParameters cp) { super(owner, cp, dfeUInt(1), 0); } @Override public DFEVar dotprod(DFEVector<DFEVar> ifmap, DFEVector<DFEVar> coeff) { BinarizedDotProduct bdp = new BinarizedDotProduct(getOwner(), cp.K * cp.K); bdp.setInputs(ifmap, coeff); return bdp.getOutput(); } @Override public DFEType getOfmapScalarT() { if (cp.BW == 1) return BinarizedDotProduct.getOutT(cp.K * cp.K); return T; } }
34.1
79
0.773216
458fca8a4a6d881aae77d5123050eb73974cc90c
1,942
package com.tencent.business; import com.tencent.common.Util; import com.tencent.protocol.red_backage_protocol.RedPackageReqData; import com.tencent.protocol.red_backage_protocol.RedPackageResData; import com.tencent.protocol.refund_protocol.RefundReqData; import com.tencent.protocol.refund_protocol.RefundResData; import com.tencent.result.RedPackageResult; import com.tencent.result.RefundResult; import com.tencent.result.ResultStatus; import com.tencent.service.IServiceRequest; import com.tencent.service.RedPackageService; import com.tencent.service.RefundService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Created by WANGHJ on 2018-11-08. */ public class RedPackageBusiness { public RedPackageBusiness(IServiceRequest serviceRequest){ redPackageService = new RedPackageService(serviceRequest); } private static final Logger logger = LoggerFactory.getLogger(RefundBusiness.class); private RedPackageService redPackageService; /** * 发红包请求 * @param redPackageReqData 这个数据对象里面包含了API要求提交的各种数据字段 * */ public RedPackageResult run(RedPackageReqData redPackageReqData){ RedPackageResult result = new RedPackageResult(); String resString = redPackageService.request(redPackageReqData); RedPackageResData resData = (RedPackageResData) Util.getObjectFromXML(resString,RedPackageResData.class); if(resData==null){ result.setStatus(ResultStatus.UNKNOW); result.setMsg("系统未知错误"); }else{ if(resData.isSuccess()){ result.setStatus(ResultStatus.SUCCESS); result.setMsg("发送成功"); }else{ result.setStatus(ResultStatus.FAIL); result.setMsg(resData.getErrMsg()); } } return result; } public void setRefundService(RedPackageService service) { redPackageService = service; } }
33.482759
113
0.720391
39b235b4b07cad4c132b6c4324de875f29b0760c
1,257
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInsight.generation; import com.intellij.psi.PsiClass; import com.intellij.psi.util.PsiFormatUtil; import com.intellij.psi.util.PsiFormatUtilBase; import com.intellij.ui.SimpleColoredComponent; import org.jetbrains.annotations.NotNull; import javax.swing.*; public class RecordConstructorMember implements ClassMember { private final PsiClass myRecord; private final boolean myCompact; public RecordConstructorMember(PsiClass aRecord, boolean compact) { myRecord = aRecord; myCompact = compact; } @Override public MemberChooserObject getParentNodeDelegate() { final String text = PsiFormatUtil.formatClass(myRecord, PsiFormatUtilBase.SHOW_NAME | PsiFormatUtilBase.SHOW_FQ_NAME); return new PsiDocCommentOwnerMemberChooserObject(myRecord, text, myRecord.getIcon(0)); } @Override public void renderTreeNode(SimpleColoredComponent component, JTree tree) { } public boolean isCompact() { return myCompact; } @NotNull @Override public String getText() { return myCompact ? "Compact constructor" : "Canonical constructor"; } }
29.928571
140
0.77327
96db544392b3265b0749a97e3881298ad73eac70
291
package pack.util; public class ErrorLog { public static void print(String error){ Output.newLine(); Output.println("ERROR: " + error); for(StackTraceElement ste : Thread.currentThread().getStackTrace()) { Output.println(ste + ""); } Output.flush(); System.exit(1); } }
20.785714
71
0.670103
fffe71236591bbc69a0bfa49a29e31aa6705d6b4
3,407
package com.convious.pricingapi; import com.convious.pricingapi.events.InventoryEvent; import com.convious.pricingapi.transport.*; import java.net.URI; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.concurrent.CompletableFuture; public class PricingApiClient { private final HttpService httpService; private final Configuration configuration; public static final String pricingApiVersion = "1.0.0"; public static final String inventoryApiVersion = "1.0.0"; public PricingApiClient(HttpService httpService, Configuration configuration) { this.httpService = httpService; this.configuration = configuration; } public static PricingApiClient create(String clientId, String clientSecret) { var config = Configuration.defaultConfiguration(); return new PricingApiClient( new AuthenticatedHttpService( new JsonHttpService(), new HttpAuthService(config.authEndpoint(), clientId, clientSecret) ), config ); } private <T> CompletableFuture<T> post(HttpRequest request, Class<T> cls) { return httpService.post(request) .thenApply(response -> { if (response.status() < 200 || response.status() > 299) { throw new PricingClientException(String.format("Request to %s returned status code %d and body %s", request.uri(), response.status(), response.body())); } return Json.deserialize(response.body(), cls); }); } public CompletableFuture postEventsAsync(InventoryEvent[] events) { return post( new HttpRequest( URI.create(configuration.inventoryEndpoint() + "/events"), Arrays.stream(events).map(EventEnvelope::new).toArray(EventEnvelope[]::new), new HashMap<>() {{ put("Content-Type", List.of("application/json")); put("Accept-Version", List.of(inventoryApiVersion)); }} ), Void.class ); } public CompletableFuture postEventAsync(InventoryEvent event) { return postEventsAsync(new InventoryEvent[] { event }); } public void postEvents(InventoryEvent[] events) { postEventsAsync(events).join(); } public void postEvent(InventoryEvent event) { postEventAsync(event).join(); } public CompletableFuture<PricingResponse> getPricesAsync(PricingRequest request) { return post( new HttpRequest( URI.create(configuration.pricingEndpoint() + "/api/price/rtp"), request, new HashMap<>() {{ put("Content-Type", List.of("application/json")); put("Accept", List.of("application/json")); put("Accept-Version", List.of(pricingApiVersion)); }} ), PricingResponse.class ); } public PricingResponse getPrices(PricingRequest request) { return getPricesAsync(request).join(); } }
38.280899
177
0.57059
f2dbf2fad78596a77bdf08b7618b5fd64013e6db
275
package io.mindjet.jetgear.mvvm.viewinterface; import android.content.Context; import android.databinding.ViewDataBinding; /** * Created by Jet on 2/17/17. */ public interface ViewInterface<V extends ViewDataBinding> { Context getContext(); V getBinding(); }
16.176471
59
0.741818
263f32ccc7c7ef3aae99ee5f3221843848abd941
5,273
package remote; import enums.MessageType; import io.netty.channel.ChannelHandlerContext; import lombok.extern.log4j.Log4j2; import manager.BrokerManager; import manager.TopicManager; import message.*; import model.BrokerData; import netty.protocal.RemotingCommand; import netty.server.NettyServerHandler; import utils.Broker; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; /** * @author Zexho * @date 2021/12/15 3:59 PM */ @Log4j2 public class NameSrvRemotingHandler extends NettyServerHandler { private final BrokerManager brokerManager = BrokerManager.getInstance(); private final TopicManager topicManager = TopicManager.getInstance(); @Override public void channelRead(ChannelHandlerContext ctx, Object msg) { RemotingCommand cmd = (RemotingCommand) msg; RemotingCommand response = this.processCommand(cmd); ctx.writeAndFlush(response); } private RemotingCommand processCommand(RemotingCommand command) { log.debug("nameserver process command. cmd = {}", command); MessageType messageType = MessageType.get(command.getProperty(PropertiesKeys.MESSAGE_TYPE)); assert messageType != null; RemotingCommand resp = new RemotingCommand(); Message respMessage = new Message(command.getBody().getMsgId()); switch (messageType) { case Register_Broker: log.info("[NameServer] broker register => {}", command.getBody()); this.doRegisterBroker(command); int brokerId = Integer.parseInt(command.getProperty(PropertiesKeys.BROKER_ID)); if (Broker.isMaster(brokerId)) { respMessage.setBody(true); } else { // broker为slave,返回master的路由信息 String clusterName = command.getProperty(PropertiesKeys.CLUSTER_NAME); String brokerName = command.getProperty(PropertiesKeys.BROKER_NAME); BrokerData masterData = brokerManager.getMasterData(clusterName, brokerName); respMessage.setBody(masterData); } resp.addProperties(PropertiesKeys.MESSAGE_TYPE, MessageType.Register_Broker_Resp.type); resp.setBody(respMessage); break; case Get_Topic_Route: String topic = command.getProperty(PropertiesKeys.TOPIC); log.info("[NameServer] get topic route info => {}", topic); TopicRouteInfos topicRouteInfos = this.doGetTopicRouteData(topic); resp.addProperties(PropertiesKeys.MESSAGE_TYPE, MessageType.Get_Topic_Route.type); respMessage.setBody(topicRouteInfos); resp.setBody(respMessage); break; default: throw new RuntimeException("message type error: " + messageType); } return resp; } private void doRegisterBroker(RemotingCommand command) { String clusterName = command.getProperty(PropertiesKeys.CLUSTER_NAME); String brokerName = command.getProperty(PropertiesKeys.BROKER_NAME); String brokerHost = command.getProperty(PropertiesKeys.BROKER_HOST); int brokerId = Integer.parseInt(command.getProperty(PropertiesKeys.BROKER_ID)); int brokerPort = Integer.parseInt(command.getProperty(PropertiesKeys.BROKER_PORT)); brokerManager.addBroker(brokerName, brokerHost, brokerPort, brokerId, clusterName); // master要保存topic的消息,slave不用 if (Broker.isMaster(brokerId)) { Message message = command.getBody(); ConfigBody body = (ConfigBody) message.getBody(); List<TopicUnit> topics = body.getTopics(); topicManager.addTopic(clusterName, brokerName, topics); } } private TopicRouteInfos doGetTopicRouteData(String topic) { log.info("Get topic:{} route data", topic); Map<String, Set<String>> clusterBrokerMap = this.topicManager.getBrokerNameByTopic(topic); List<TopicRouteInfo> topicRouteInfoList = new LinkedList<>(); clusterBrokerMap.forEach((clusterName, set) -> { set.forEach((brokerName) -> { BrokerData brokerData = this.brokerManager.getMasterData(clusterName, brokerName); this.topicManager.getTopicsByBrokerName(clusterName, brokerName).stream() .filter(tu -> tu.getTopic().equals(topic)) .forEach(tu -> { TopicRouteInfo tri = new TopicRouteInfo(); tri.setBrokerName(brokerData.getBrokerName()); tri.setClusterName(brokerData.getClusterName()); tri.setBrokerHost(brokerData.getBrokerHost()); tri.setBrokerPort(brokerData.getBrokerPort()); tri.setBrokerId(brokerData.getBrokerId()); tri.setTopic(tu.getTopic()); tri.setQueueNum(tu.getQueue()); topicRouteInfoList.add(tri); }); }); }); return new TopicRouteInfos(topicRouteInfoList); } }
45.068376
103
0.636639
11e83910623aeff538ef6fcb1cdb16713d50a18d
8,391
package org.bian.dto; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import javax.validation.Valid; /** * BQCollateralLiquidationInitiateInputModel */ public class BQCollateralLiquidationInitiateInputModel { private String collateralAssetLiquidationProcedureInstanceReference = null; private Object collateralLiquidationInitiateActionRecord = null; private String collateralLiquidationPreconditions = null; private String collateralLiquidationBusinessUnitEmployeeReference = null; private String collateralLiquidationWorkSchedule = null; private String collateralLiquidationPostconditions = null; private String collateralLiquidationCollateralLiquidationServiceType = null; private String collateralLiquidationCollateralLiquidationServiceDescription = null; private String collateralLiquidationCollateralLiquidationServiceInputsandOuputs = null; private String collateralLiquidationCollateralLiquidationServiceWorkProduct = null; private String collateralLiquidationCollateralLiquidationServiceName = null; /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::ISO20022andUNCEFACT::Identifier general-info: Reference to the parent Collateral Asset Liquidation Procedure instance * @return collateralAssetLiquidationProcedureInstanceReference **/ public String getCollateralAssetLiquidationProcedureInstanceReference() { return collateralAssetLiquidationProcedureInstanceReference; } public void setCollateralAssetLiquidationProcedureInstanceReference(String collateralAssetLiquidationProcedureInstanceReference) { this.collateralAssetLiquidationProcedureInstanceReference = collateralAssetLiquidationProcedureInstanceReference; } /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Binary general-info: The Initiate service call input and output record * @return collateralLiquidationInitiateActionRecord **/ public Object getCollateralLiquidationInitiateActionRecord() { return collateralLiquidationInitiateActionRecord; } public void setCollateralLiquidationInitiateActionRecord(Object collateralLiquidationInitiateActionRecord) { this.collateralLiquidationInitiateActionRecord = collateralLiquidationInitiateActionRecord; } /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: The required status/situation and or tasks that need to be completed prior to the initiation of the workstep * @return collateralLiquidationPreconditions **/ public String getCollateralLiquidationPreconditions() { return collateralLiquidationPreconditions; } public void setCollateralLiquidationPreconditions(String collateralLiquidationPreconditions) { this.collateralLiquidationPreconditions = collateralLiquidationPreconditions; } /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::ISO20022andUNCEFACT::Identifier general-info: The operating unit/employee responsible for the workstep * @return collateralLiquidationBusinessUnitEmployeeReference **/ public String getCollateralLiquidationBusinessUnitEmployeeReference() { return collateralLiquidationBusinessUnitEmployeeReference; } public void setCollateralLiquidationBusinessUnitEmployeeReference(String collateralLiquidationBusinessUnitEmployeeReference) { this.collateralLiquidationBusinessUnitEmployeeReference = collateralLiquidationBusinessUnitEmployeeReference; } /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: The timing and key actions/milestones making up the workstep * @return collateralLiquidationWorkSchedule **/ public String getCollateralLiquidationWorkSchedule() { return collateralLiquidationWorkSchedule; } public void setCollateralLiquidationWorkSchedule(String collateralLiquidationWorkSchedule) { this.collateralLiquidationWorkSchedule = collateralLiquidationWorkSchedule; } /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: The completion status and reference to subsequent actions that may be triggered on completion of the workstep * @return collateralLiquidationPostconditions **/ public String getCollateralLiquidationPostconditions() { return collateralLiquidationPostconditions; } public void setCollateralLiquidationPostconditions(String collateralLiquidationPostconditions) { this.collateralLiquidationPostconditions = collateralLiquidationPostconditions; } /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: Reference to the specific business service type * @return collateralLiquidationCollateralLiquidationServiceType **/ public String getCollateralLiquidationCollateralLiquidationServiceType() { return collateralLiquidationCollateralLiquidationServiceType; } public void setCollateralLiquidationCollateralLiquidationServiceType(String collateralLiquidationCollateralLiquidationServiceType) { this.collateralLiquidationCollateralLiquidationServiceType = collateralLiquidationCollateralLiquidationServiceType; } /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: Description of the performed business service * @return collateralLiquidationCollateralLiquidationServiceDescription **/ public String getCollateralLiquidationCollateralLiquidationServiceDescription() { return collateralLiquidationCollateralLiquidationServiceDescription; } public void setCollateralLiquidationCollateralLiquidationServiceDescription(String collateralLiquidationCollateralLiquidationServiceDescription) { this.collateralLiquidationCollateralLiquidationServiceDescription = collateralLiquidationCollateralLiquidationServiceDescription; } /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: Mandatory and optional inputs and output information for the business service * @return collateralLiquidationCollateralLiquidationServiceInputsandOuputs **/ public String getCollateralLiquidationCollateralLiquidationServiceInputsandOuputs() { return collateralLiquidationCollateralLiquidationServiceInputsandOuputs; } public void setCollateralLiquidationCollateralLiquidationServiceInputsandOuputs(String collateralLiquidationCollateralLiquidationServiceInputsandOuputs) { this.collateralLiquidationCollateralLiquidationServiceInputsandOuputs = collateralLiquidationCollateralLiquidationServiceInputsandOuputs; } /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: Documentation, meeting schedules, notes, reasearch. calculations and any other work products produced by the business service * @return collateralLiquidationCollateralLiquidationServiceWorkProduct **/ public String getCollateralLiquidationCollateralLiquidationServiceWorkProduct() { return collateralLiquidationCollateralLiquidationServiceWorkProduct; } public void setCollateralLiquidationCollateralLiquidationServiceWorkProduct(String collateralLiquidationCollateralLiquidationServiceWorkProduct) { this.collateralLiquidationCollateralLiquidationServiceWorkProduct = collateralLiquidationCollateralLiquidationServiceWorkProduct; } /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: * @return collateralLiquidationCollateralLiquidationServiceName **/ public String getCollateralLiquidationCollateralLiquidationServiceName() { return collateralLiquidationCollateralLiquidationServiceName; } public void setCollateralLiquidationCollateralLiquidationServiceName(String collateralLiquidationCollateralLiquidationServiceName) { this.collateralLiquidationCollateralLiquidationServiceName = collateralLiquidationCollateralLiquidationServiceName; } }
43.476684
248
0.835657
02a38f8aef3a6d2c9c89ea89853fe037295c8f22
982
package com.deigon.lanpartypicker; import com.deigon.lanpartypicker.domain.LanPartyUser; import com.deigon.lanpartypicker.repositories.UserRepository; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; @Service public class UserDetailServiceImpl implements UserDetailsService { private UserRepository userRepository; public UserDetailServiceImpl(UserRepository userRepository) { this.userRepository = userRepository; } @Override public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException { LanPartyUser byUsername = userRepository.getByUsername(s); if (byUsername == null){ throw new UsernameNotFoundException("User not found in system"); } return byUsername; } }
35.071429
86
0.787169
63c9048ea4015ba914adf87ba277841b3d7115bc
20,015
package superstartrek; import static org.junit.Assert.*; import org.junit.Test; import org.mockito.AdditionalMatchers; import superstartrek.client.activities.combat.CombatHandler; import superstartrek.client.activities.combat.CombatHandler.partTarget; import superstartrek.client.activities.klingons.Klingon; import superstartrek.client.activities.klingons.Klingon.ShipClass; import superstartrek.client.activities.messages.MessageHandler; import superstartrek.client.activities.navigation.NavigationHandler; import superstartrek.client.bus.Events; import superstartrek.client.control.QuadrantActivationHandler; import superstartrek.client.model.Location; import superstartrek.client.model.Quadrant; import superstartrek.client.model.Star; import superstartrek.client.model.StarBase; import superstartrek.client.model.Thing; import superstartrek.client.model.Vessel; import superstartrek.client.model.Weapon; import superstartrek.client.model.Enterprise.ShieldDirection; import superstartrek.client.model.Star.StarClass; import superstartrek.client.utils.BrowserAPI; import static org.mockito.Matchers.any; import static org.mockito.Mockito.*; import java.util.HashSet; import java.util.List; public class TestEnterprise extends BaseTest { @Test public void testDamageTorpedos() { MessageHandler handler = mock(MessageHandler.class); bus.addHandler(Events.MESSAGE_POSTED, handler); enterprise.damageTorpedos(); assertFalse(enterprise.getTorpedos().isOperational()); verify(handler).messagePosted(eq("Torpedo bay damaged"), eq("enterprise-damaged")); } @Test public void testDamagePhasers() { MessageHandler handler = mock(MessageHandler.class); bus.addHandler(Events.MESSAGE_POSTED, handler); enterprise.damagePhasers(); assertTrue(enterprise.getPhasers().isOperational()); assertEquals(21, enterprise.getPhasers().getCurrentUpperBound(), 0.1); enterprise.damagePhasers(); assertTrue(enterprise.getPhasers().isOperational()); assertEquals(12, enterprise.getPhasers().getCurrentUpperBound(), 0.1); enterprise.damagePhasers(); assertTrue(enterprise.getPhasers().isOperational()); assertEquals(3, enterprise.getPhasers().getCurrentUpperBound(), 0.1); enterprise.damagePhasers(); assertEquals(0, enterprise.getPhasers().getCurrentUpperBound(), 0.1); assertFalse(enterprise.getPhasers().isOperational()); verify(handler, times(4)).messagePosted(eq("Phaser banks damaged"), eq("enterprise-damaged")); } @Test public void testDamageImpulse() { MessageHandler handler = mock(MessageHandler.class); bus.addHandler(Events.MESSAGE_POSTED, handler); enterprise.damageImpulse(); assertTrue(enterprise.getImpulse().isOperational()); assertEquals(2, enterprise.getImpulse().getCurrentUpperBound(), 0.1); enterprise.damageImpulse(); assertTrue(enterprise.getImpulse().isOperational()); assertEquals(1, enterprise.getImpulse().getCurrentUpperBound(), 0.1); enterprise.damageImpulse(); assertFalse(enterprise.getImpulse().isOperational()); assertEquals(0, enterprise.getImpulse().getCurrentUpperBound(), 0.1); verify(handler, times(3)).messagePosted(eq("Impulse drive damaged"), eq("enterprise-damaged")); } @Test public void testNavigateTo() { Quadrant quadrant = new Quadrant("q 1 2", 1, 2); starMap.setQuadrant(quadrant); enterprise.setQuadrant(quadrant); enterprise.setLocation(Location.location(0, 0)); bus.addHandler(Events.THING_MOVED, new NavigationHandler() { @Override public void thingMoved(Thing thing, Quadrant qFrom, Location lFrom, Quadrant qTo, Location lTo) { assertEquals(enterprise, thing); assertEquals(quadrant, qFrom); assertEquals(quadrant, qTo); assertEquals(Location.location(2, 2), lTo); } }); // necessary call to findReachableSectors in order to populate reachability map enterprise.findReachableSectors(); enterprise.navigateTo(Location.location(2, 2)); assertEquals(0, enterprise.getImpulse().getValue(), 0.5); assertEquals(Location.location(2, 2), enterprise.getLocation()); assertEquals(1, bus.getFiredCount(Events.THING_MOVED)); } @Test public void testWarpTo() { Quadrant quadrant = new Quadrant("q 1 2", 1, 2); starMap.setQuadrant(quadrant); enterprise.setQuadrant(quadrant); enterprise.setLocation(Location.location(0, 0)); application.browserAPI = mock(BrowserAPI.class); when(application.browserAPI.nextInt(any(int.class))).thenReturn(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1); // path between source and target needs to exist for collision check starMap.setQuadrant(new Quadrant("_", 2, 3)); // quadrants around target need to exist because exploration flag is set for (int x = 3 - 1; x <= 3 + 1; x++) for (int y = 4 - 1; y <= 4 + 1; y++) starMap.setQuadrant(new Quadrant("_", x, y)); Quadrant targetQuadrant = starMap.getQuadrant(3, 4); starMap.setQuadrant(targetQuadrant); bus.addHandler(Events.QUADRANT_ACTIVATED, new QuadrantActivationHandler() { @Override public void onActiveQuadrantChanged(Quadrant oldQuadrant, Quadrant newQuadrant) { assertEquals(quadrant, oldQuadrant); assertEquals(targetQuadrant, newQuadrant); } }); enterprise.warpTo(targetQuadrant, null); assertEquals(1, bus.getFiredCount(Events.QUADRANT_ACTIVATED)); } @Test public void testFirePhasers() { application.browserAPI = mock(BrowserAPI.class); when(application.browserAPI.nextDouble()).thenReturn(0.5, 0.6, 0.1, 0.3, 0.3); Quadrant quadrant = new Quadrant("q 1 2", 1, 2); starMap.setQuadrant(quadrant); enterprise.setQuadrant(quadrant); Klingon klingon = new Klingon(ShipClass.BirdOfPrey); klingon.setLocation(Location.location(1, 1)); quadrant.add(klingon); klingon.registerActionHandlers(); klingon.uncloak(); CombatHandler handler = mock(CombatHandler.class); bus.addHandler(Events.BEFORE_FIRE, handler); assertEquals(100, klingon.getShields().getValue(), 0.1); enterprise.firePhasersAt(klingon.getLocation(), false, partTarget.none); assertEquals(89, klingon.getShields().getValue(), 10); assertEquals(1, bus.getFiredCount(Events.BEFORE_FIRE)); // TODO: damage probably wrong verify(handler, times(1)).onFire(same(quadrant), same(enterprise), same(klingon), eq(Weapon.phaser), AdditionalMatchers.eq(8.5, 1), eq(false), eq(partTarget.none)); } @Test public void testFirePhasers_precision_shot() { application.browserAPI = mock(BrowserAPI.class); when(application.browserAPI.nextDouble()).thenReturn(0.5, 0.6, 0.1, 0.3, 0.3); Quadrant quadrant = new Quadrant("q 1 2", 1, 2); starMap.setQuadrant(quadrant); enterprise.setQuadrant(quadrant); quadrant.add(enterprise); Klingon klingon = new Klingon(ShipClass.BirdOfPrey); klingon.setLocation(Location.location(1, 1)); quadrant.add(klingon); klingon.registerActionHandlers(); klingon.uncloak(); CombatHandler handler = mock(CombatHandler.class); bus.addHandler(Events.BEFORE_FIRE, handler); assertEquals(100, klingon.getShields().getValue(), 0.1); enterprise.firePhasersAt(klingon.getLocation(), false, partTarget.propulsion); assertEquals(89, klingon.getShields().getValue(), 10); assertEquals(1, bus.getFiredCount(Events.BEFORE_FIRE)); // TODO: damage probably wrong verify(handler, times(1)).onFire(same(quadrant), same(enterprise), same(klingon), eq(Weapon.phaser), AdditionalMatchers.eq(4, 1), eq(false), eq(partTarget.propulsion)); } @Test public void test_FirePhasers_negative() { application.browserAPI = mock(BrowserAPI.class); when(application.browserAPI.nextDouble()).thenReturn(0.5, 0.6, 0.1, 0.3, 0.3); Quadrant quadrant = new Quadrant("q 1 2", 1, 2); starMap.setQuadrant(quadrant); enterprise.setQuadrant(quadrant); quadrant.add(enterprise); Klingon klingon = new Klingon(ShipClass.BirdOfPrey); klingon.setLocation(Location.location(1, 1)); quadrant.add(klingon); klingon.registerActionHandlers(); klingon.uncloak(); CombatHandler handler = mock(CombatHandler.class); MessageHandler messageHandler = mock(MessageHandler.class); bus.addHandler(Events.BEFORE_FIRE, handler); bus.addHandler(Events.MESSAGE_POSTED, messageHandler); enterprise.getReactor().setValue(0); assertEquals(100, klingon.getShields().getValue(), 0.1); enterprise.firePhasersAt(klingon.getLocation(), false, partTarget.none); assertEquals(100, klingon.getShields().getValue(), 10); assertEquals(0, bus.getFiredCount(Events.BEFORE_FIRE)); // TODO: damage probably wrong verify(handler, times(0)).onFire(same(quadrant), same(enterprise), same(klingon), eq(Weapon.phaser), AdditionalMatchers.eq(21, 1), eq(false), eq(partTarget.none)); verify(messageHandler).messagePosted("Insufficient reactor output", "info"); } @Test public void testFireTorpedos() { application.browserAPI = mock(BrowserAPI.class); when(application.browserAPI.nextDouble()).thenReturn(0.5, 0.6, 0.1, 0.3, 0.3); Quadrant quadrant = new Quadrant("q 1 2", 1, 2); starMap.setQuadrant(quadrant); enterprise.setQuadrant(quadrant); Klingon klingon = new Klingon(ShipClass.BirdOfPrey); quadrant.add(klingon); klingon.setLocation(Location.location(1, 1)); klingon.registerActionHandlers(); klingon.uncloak(); CombatHandler handler = mock(CombatHandler.class); bus.addHandler(Events.BEFORE_FIRE, handler); bus.addHandler(Events.AFTER_FIRE, handler); assertEquals(100, klingon.getShields().getValue(), 0.1); enterprise.fireTorpedosAt(klingon.getLocation()); assertEquals(50, klingon.getShields().getValue(), 75); assertEquals(1, bus.getFiredCount(Events.AFTER_FIRE)); verify(handler, times(1)).onFire(quadrant, enterprise, klingon, Weapon.torpedo, 25, false, partTarget.none); verify(handler, times(1)).afterFire(quadrant, enterprise, klingon, Weapon.torpedo, 25, false); } @Test public void test_getReachableSectors() { Quadrant quadrant = new Quadrant("q 1 2", 1, 2); starMap.setQuadrant(quadrant); enterprise.setQuadrant(quadrant); enterprise.setLocation(Location.location(4, 4)); starMap.enterprise = enterprise; quadrant.add(new Star(1, 6, StarClass.A)); quadrant.add(new Star(2, 6, StarClass.A)); quadrant.add(new Star(3, 6, StarClass.A)); quadrant.add(new Star(5, 6, StarClass.A)); quadrant.add(new Star(6, 6, StarClass.A)); quadrant.add(new Star(7, 6, StarClass.A)); quadrant.add(new Star(4, 3, StarClass.A)); List<Location> list = enterprise.findReachableSectors(); assertTrue(list.contains(Location.location(4, 5))); assertTrue(list.contains(Location.location(4, 6))); assertTrue(list.contains(Location.location(5, 5))); assertTrue(list.contains(Location.location(3, 3))); assertTrue(list.contains(Location.location(3, 4))); assertTrue(list.contains(Location.location(5, 4))); assertFalse(list.contains(Location.location(5, 6))); assertFalse(list.contains(Location.location(3, 6))); // check for duplicates assertEquals(new HashSet<>(list).size(), list.size()); assertEquals(19, list.size()); } @Test public void test_isDamaged() { assertFalse(enterprise.isDamaged()); enterprise.damagePhasers(); assertTrue(enterprise.isDamaged()); } @Test public void test_canFirePhaserAt() { Quadrant quadrant = new Quadrant("q 1 2", 1, 2); starMap.setQuadrant(quadrant); enterprise.setQuadrant(quadrant); enterprise.setLocation(Location.location(4, 4)); quadrant.add(enterprise); Star star = new Star(3, 3, Star.StarClass.A); quadrant.add(star); Klingon klingon = new Klingon(Klingon.ShipClass.BirdOfPrey); klingon.setLocation(Location.location(5, 5)); quadrant.add(klingon); assertEquals("There is nothing at 7:7", enterprise.canFirePhaserAt(Location.location(7, 7))); assertEquals("Phasers can target only enemy vessels", enterprise.canFirePhaserAt(star.getLocation())); klingon.getCloak().setValue(true); assertEquals("There is nothing at 5:5", enterprise.canFirePhaserAt(klingon.getLocation())); klingon.uncloak(); assertNull(null, enterprise.canFirePhaserAt(klingon.getLocation())); } @Test public void test_autoAim() { Klingon klingon = new Klingon(Klingon.ShipClass.BirdOfPrey); klingon.setLocation(Location.location(5, 5)); klingon.uncloak(); enterprise.setLocation(Location.location(4, 4)); quadrant.add(klingon); bus.addHandler(Events.BEFORE_FIRE, new CombatHandler() { @Override public void onFire(Quadrant quadrant, Vessel actor, Thing target, Weapon weapon, double damage, boolean wasAutoFire, partTarget part) { assertEquals(klingon, target); assertEquals(enterprise, actor); assertEquals(8.5, damage, 1); assertEquals(partTarget.none, part); } }); bus.addHandler(Events.AFTER_FIRE, new CombatHandler() { @Override public void afterFire(Quadrant quadrant, Vessel actor, Thing target, Weapon weapon, double damage, boolean wasAutoFire) { assertEquals(klingon, target); assertEquals(enterprise, actor); assertEquals(8.5, damage, 1); } }); enterprise.autoAim(); assertEquals(1, bus.getFiredCount(Events.BEFORE_FIRE)); assertEquals(1, bus.getFiredCount(Events.AFTER_FIRE)); } @Test public void testDockWithStarbase() { enterprise.setLocation(Location.location(1, 1)); enterprise.getPhasers().damage(10, starMap.getStarDate()); enterprise.getAntimatter().decrease(10); enterprise.getTorpedos().damage(1, starMap.getStarDate()); enterprise.getImpulse().damage(1, starMap.getStarDate()); quadrant.setStarBase(new StarBase(Location.location(3, 3))); bus.addHandler(Events.THING_MOVED, new NavigationHandler() { @Override public void thingMoved(Thing thing, Quadrant qFrom, Location lFrom, Quadrant qTo, Location lTo) { assertEquals(enterprise, thing); assertEquals(quadrant, qFrom); assertEquals(Location.location(1, 1), lFrom); assertEquals(quadrant, qTo); assertEquals(Location.location(4, 4), lTo); } }); when(browser.nextDouble()).thenReturn(0.0); when(browser.nextInt(any(int.class))).thenReturn(1, 1, 2, 2, 5); enterprise.dockInStarbase(); assertEquals(1, bus.getFiredCount(Events.THING_MOVED)); assertEquals(Location.location(4, 4), enterprise.getLocation()); assertEquals(1, bus.getFiredCount(Events.ENTERPRISE_REPAIRED)); assertEquals(enterprise.getTorpedos().getMaximum(), enterprise.getTorpedos().getValue(), 0.1); } @Test public void test_applyDamage() { when(browser.nextDouble()).thenReturn(1.0); assertEquals(60, enterprise.getShields().getValue(), 0.1); enterprise.applyDamage(30); assertEquals(50.1, enterprise.getShields().getValue(), 0.1); } @Test public void test_onFire_no_directional_shield() { when(browser.nextDouble()).thenReturn(1.0); Klingon klingon = new Klingon(ShipClass.BirdOfPrey); quadrant.add(klingon); klingon.setLocation(Location.location(1, 1)); klingon.registerActionHandlers(); klingon.uncloak(); enterprise.onFire(quadrant, klingon, enterprise, Weapon.disruptor, klingon.getDisruptor().getValue(), false, partTarget.none); assertEquals(56, enterprise.getShields().getValue(), 0.1); } @Test public void test_onFire_with_directional_shield_side_fire() { assertEquals(enterprise.getLocation(), Location.location(0, 0)); when(browser.nextDouble()).thenReturn(1.0); Klingon klingon = new Klingon(ShipClass.BirdOfPrey); klingon.setLocation(Location.location(1, 0)); quadrant.add(klingon); klingon.registerActionHandlers(); klingon.uncloak(); enterprise.setShieldDirection(ShieldDirection.north); enterprise.onFire(quadrant, klingon, enterprise, Weapon.disruptor, klingon.getDisruptor().getValue(), false, partTarget.none); assertEquals(55.4, enterprise.getShields().getValue(), 0.1); } @Test public void test_onFire_with_directional_shield_rear_fire() { assertEquals(enterprise.getLocation(), Location.location(0, 0)); when(browser.nextDouble()).thenReturn(1.0); Klingon klingon = new Klingon(ShipClass.BirdOfPrey); klingon.setLocation(Location.location(0, 1)); quadrant.add(klingon); klingon.registerActionHandlers(); klingon.uncloak(); enterprise.setShieldDirection(ShieldDirection.north); enterprise.onFire(quadrant, klingon, enterprise, Weapon.disruptor, klingon.getDisruptor().getValue(), false, partTarget.none); assertEquals(54.1, enterprise.getShields().getValue(), 0.1); } @Test public void test_onFire_with_directional_shield_front_fire() { enterprise.setLocation(Location.location(0, 2)); assertEquals(enterprise.getLocation(), Location.location(0, 2)); when(browser.nextDouble()).thenReturn(1.0); Klingon klingon = new Klingon(ShipClass.BirdOfPrey); klingon.setLocation(Location.location(0, 1)); quadrant.add(klingon); klingon.registerActionHandlers(); klingon.uncloak(); enterprise.setShieldDirection(ShieldDirection.north); enterprise.onFire(quadrant, klingon, enterprise, Weapon.disruptor, klingon.getDisruptor().getValue(), false, partTarget.none); assertEquals(56.75, enterprise.getShields().getValue(), 0.1); } @Test public void test_computeDirectionalShieldEfficiency() { enterprise.setLocation(Location.location(1, 1)); assertEquals(0.75, enterprise.computeDirectionalShieldEfficiency(ShieldDirection.omni, Location.location(1, 0)), 0.1); assertEquals(0.75, enterprise.computeDirectionalShieldEfficiency(ShieldDirection.omni, Location.location(1, 0)), 0.1); assertEquals(1.0, enterprise.computeDirectionalShieldEfficiency(ShieldDirection.north, Location.location(1, 0)), 0.1); assertEquals(0.0, enterprise.computeDirectionalShieldEfficiency(ShieldDirection.south, Location.location(1, 0)), 0.1); assertEquals(0.5, enterprise.computeDirectionalShieldEfficiency(ShieldDirection.west, Location.location(1, 0)), 0.1); assertEquals(1.0, enterprise.computeDirectionalShieldEfficiency(ShieldDirection.west, Location.location(0, 1)), 0.1); } @Test public void test_toggleShields_no_klingons() { assertEquals(ShieldDirection.omni, enterprise.getShieldDirection()); enterprise.toggleShields(); //1st toggle in turn returns best direction assertEquals(ShieldDirection.omni, enterprise.getShieldDirection()); enterprise.toggleShields(); assertEquals(ShieldDirection.north, enterprise.getShieldDirection()); enterprise.toggleShields(); assertEquals(ShieldDirection.east, enterprise.getShieldDirection()); enterprise.toggleShields(); assertEquals(ShieldDirection.south, enterprise.getShieldDirection()); enterprise.toggleShields(); assertEquals(ShieldDirection.west, enterprise.getShieldDirection()); enterprise.toggleShields(); assertEquals(ShieldDirection.omni, enterprise.getShieldDirection()); } @Test public void test_toggleShields_with_klingons() { Klingon k = new Klingon(ShipClass.BirdOfPrey); k.uncloak(); k.setLocation(Location.location(1, 0)); quadrant.add(k); assertEquals(ShieldDirection.omni, enterprise.getShieldDirection()); enterprise.toggleShields(); assertEquals(ShieldDirection.east, enterprise.getShieldDirection()); enterprise.toggleShields(); assertEquals(ShieldDirection.south, enterprise.getShieldDirection()); enterprise.toggleShields(); assertEquals(ShieldDirection.west, enterprise.getShieldDirection()); enterprise.toggleShields(); assertEquals(ShieldDirection.omni, enterprise.getShieldDirection()); } @Test public void test_toggleShields_with_klingons2() { quadrant.remove(enterprise); enterprise.setLocation(Location.location(3, 3)); quadrant.add(enterprise); Klingon k = new Klingon(ShipClass.BirdOfPrey); k.uncloak(); k.setLocation(Location.location(2, 4)); quadrant.add(k); assertEquals(ShieldDirection.omni, enterprise.getShieldDirection()); enterprise.toggleShields(); //1st toggle in turn returns best direction; 2nd will rotate shield around assertEquals(ShieldDirection.omni, enterprise.getShieldDirection()); enterprise.toggleShields(); assertEquals(ShieldDirection.north, enterprise.getShieldDirection()); enterprise.toggleShields(); assertEquals(ShieldDirection.east, enterprise.getShieldDirection()); } }
37.62218
114
0.755783
5763dd17448e448382baba944b61c262e04022a3
1,978
/*<license> Copyright 2007 - $Date$ by the authors mentioned below. 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. </license>*/ package org.ppwcode.util.collection_I; import static org.ppwcode.metainfo_I.License.Type.APACHE_V2; import java.util.Collection; import java.util.Set; import org.ppwcode.metainfo_I.Copyright; import org.ppwcode.metainfo_I.License; import org.ppwcode.metainfo_I.vcs.SvnInfo; /** * Unmodifiable {@link Set} general code. * * @author Jan Dockx */ @Copyright("2007 - $Date$, PeopleWare n.v.") @License(APACHE_V2) @SvnInfo(revision = "$Revision$", date = "$Date$") public abstract class AbstractUnmodifiableSet<E> extends AbstractUnmodifiableCollection<E> implements Set<E> { @Override public boolean equals(Object other) { if (other == this) { return true; } try { @SuppressWarnings("unchecked") Collection<E> cOther = (Collection<E>)other; if (size() != cOther.size()) { return false; } for (E e : cOther) { if (! contains(e)) { return false; } } for (E e : this) { if (! cOther.contains(e)) { return false; } } return true; } catch (ClassCastException ccExc) { return false; } } @Override public final int hashCode() { // sum of element hash codes int acc = 0; for (E e : this) { if (e != null) { acc += e.hashCode(); } } return acc; } }
23.831325
72
0.646613
90a2f7312b3acf90b94450f91753cd32a500b08e
916
package org.rapidpm.vaadin.sessionplanner; import static java.util.Collections.unmodifiableSet; import static org.rapidpm.vaadin.sessionplanner.SessionPlannerApplication.APPLICATION_ROOT; import java.util.HashSet; import java.util.Set; import javax.enterprise.context.ApplicationScoped; import javax.ws.rs.ApplicationPath; import javax.ws.rs.core.Application; import org.rapidpm.vaadin.sessionplanner.services.security.SecurityServiceResource; import org.rapidpm.vaadin.sessionplanner.services.session.SessionServiceResource; @ApplicationScoped @ApplicationPath(APPLICATION_ROOT) public class SessionPlannerApplication extends Application { public static final String APPLICATION_ROOT = "/"; @Override public Set<Class<?>> getClasses() { Set<Class<?>> set = new HashSet<>(); set.add(SecurityServiceResource.class); set.add(SessionServiceResource.class); return unmodifiableSet(set); } }
32.714286
91
0.810044
6c103182ff277785d1c2e8a6a49e14d536999863
4,819
package com.github.assisstion.ModulePack.logging; import java.awt.BorderLayout; import java.awt.Color; import java.util.List; import java.util.function.Consumer; import java.util.logging.Logger; import javax.lang.model.SourceVersion; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.JScrollPane; import javax.swing.JTextPane; import javax.swing.SwingWorker; import javax.swing.text.BadLocationException; import javax.swing.text.DefaultCaret; import javax.swing.text.Style; import javax.swing.text.StyleConstants; import javax.swing.text.StyledDocument; import com.github.assisstion.ModulePack.Pair; import com.github.assisstion.ModulePack.annotation.CompileVersion; import com.github.assisstion.ModulePack.annotation.Dependency; @Dependency(Pair.class) @CompileVersion(SourceVersion.RELEASE_8) // Consumer<T> public class LoggerPane extends JPanel implements Consumer<String>{ public Logger log; private static final long serialVersionUID = 1022490441168101112L; protected JTextPane textPane; private JScrollPane scrollPane; protected LogWorker worker; protected ProgressWorker progress; private JProgressBar progressBar; protected Style style; protected StyledDocument document; //protected String separator; protected Color color = Color.BLACK; protected String separator; protected boolean reverseOrder; public LoggerPane(Logger log, boolean showProgress, boolean reverseOrder){ this(log, showProgress, "\n", reverseOrder); } public LoggerPane(Logger log, boolean showProgress, String separator){ this(log, showProgress, separator, false); } public LoggerPane(Logger log, boolean showProgress){ this(log, showProgress, "\n", false); } /** * Create the frame. */ public LoggerPane(Logger log, boolean showProgress, String separator, boolean reverseOrder){ //setTitle(); setLayout(new BorderLayout(0, 0)); this.log = log; this.reverseOrder = reverseOrder; LogHandler handler = new LogHandler(this); log.addHandler(handler); scrollPane = new JScrollPane(); add(scrollPane); textPane = new JTextPane(); scrollPane.setViewportView(textPane); textPane.setEditable(false); progressBar = new JProgressBar(0, 0); progressBar.setEnabled(false); progressBar.setStringPainted(false); if(showProgress){ add(progressBar, BorderLayout.SOUTH); } if(!reverseOrder){ DefaultCaret caret = (DefaultCaret) textPane.getCaret(); caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE); } else{ DefaultCaret caret = (DefaultCaret) textPane.getCaret(); caret.setUpdatePolicy(DefaultCaret.NEVER_UPDATE); } document = textPane.getStyledDocument(); style = document.addStyle("text-style", null); StyleConstants.setForeground(style, Color.BLACK); worker = new LogWorker(); progress = new ProgressWorker(); this.separator = separator; } /* public void setSeparator(String separator){ this.separator = separator; } public String getSeparator(){ return separator; } */ public void setProgress(Pair<Integer, Integer> values){ progress.push(values); } public class LogWorker extends SwingWorker<Object, Pair<String, Color>>{ protected void push(Pair<String, Color> message){ publish(message); } @Override protected Object doInBackground() throws Exception{ return null; } @Override protected void process(List<Pair<String, Color>> messages){ for(Pair<String, Color> messageOne : messages){ String tempSeparator = ""; if(!textPane.getText().equals("")){ tempSeparator = separator; } StyleConstants.setForeground(style, messageOne.getValueTwo()); try{ if(reverseOrder){ document.insertString(0, messageOne.getValueOne() + tempSeparator, style); } else{ document.insertString(document.getLength(), tempSeparator + messageOne.getValueOne(), style); } } catch(BadLocationException e){ // TODO Auto-generated catch block e.printStackTrace(); } } } } public class ProgressWorker extends SwingWorker<Object, Pair<Integer, Integer>>{ protected void push(Pair<Integer, Integer> progress){ publish(progress); } @Override protected Object doInBackground() throws Exception{ return null; } @Override protected void process(List<Pair<Integer, Integer>> integerPairs){ for(Pair<Integer, Integer> pairOne : integerPairs){ if(pairOne.getValueTwo().equals(0)){ progressBar.setEnabled(false); progressBar.setStringPainted(false); } else{ progressBar.setEnabled(true); progressBar.setStringPainted(true); } progressBar.setValue(pairOne.getValueOne()); progressBar.setMaximum(pairOne.getValueTwo()); } } } @Override public void accept(String t){ worker.push(new Pair<String, Color>(t, color)); } }
25.908602
93
0.739573
b3f630d33984bb0ca7ff41ca7e8e0ddf208fda43
2,220
/* * Copyright 2016 Hammock and its contributors * * 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 ws.ament.hammock.rabbitmq; import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.MetricsCollector; import com.rabbitmq.client.impl.StandardMetricsCollector; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.FileAsset; import org.jboss.shrinkwrap.api.spec.JavaArchive; import org.junit.Test; import org.junit.runner.RunWith; import javax.enterprise.inject.spi.Extension; import javax.inject.Inject; import java.io.File; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; @RunWith(Arquillian.class) public class RabbitMQConfigurationTest { @Deployment public static JavaArchive create() { return ShrinkWrap.create(JavaArchive.class) .addClasses(RabbitMQConfiguration.class, ConnectionFactoryProducer.class) .addPackage("io.astefanutti.metrics.cdi") .addAsServiceProviderAndClasses(Extension.class) .addAsManifestResource(new FileAsset(new File("src/main/resources/META-INF/beans.xml")), "beans.xml"); } @Inject private ConnectionFactory connectionFactory; @Inject private MetricsCollector metricsCollector; @Test public void shouldCreateAConnectionFactory() { assertNotNull(connectionFactory); } @Test public void shouldHaveInjectedCollector() { assertNotNull(metricsCollector); assertTrue(metricsCollector instanceof StandardMetricsCollector); } }
33.134328
118
0.753604
2b001c6fb28b4eb389fd81f7d2dc57f7658e2ff6
518
package uk.ac.ebi.ep.unisave.config; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; /** * * @author Joseph */ @Configuration @ConfigurationProperties(prefix = "couchbase") @Getter @Setter @NoArgsConstructor public class CouchbaseProperties { private String adminUser, adminPassword, host, bucket, password, versionBucket, versionPassword; }
23.545455
100
0.80888
11f5a4d2ec09eb7e92bbd934475f42930aa9b39b
588
package org.pes.onecemulator.service; import org.pes.onecemulator.entity.Act; import org.pes.onecemulator.exception.NotFoundException; import org.pes.onecemulator.exception.ValidationException; import org.pes.onecemulator.model.internal.ActModel; import java.util.List; import java.util.UUID; public interface ActService { Act getById(UUID id) throws NotFoundException; List<Act> list(); Act create(ActModel model) throws NotFoundException, ValidationException; Act update(ActModel model) throws NotFoundException, ValidationException; void delete(UUID id); }
25.565217
77
0.794218
98009fa4548dd268a24c42fb8bdbddf2fbf67352
127,100
/* * Copyright 2020 Google LLC * * 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 * * https://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. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/aiplatform/v1/index_endpoint.proto package com.google.cloud.aiplatform.v1; /** * * * <pre> * A deployment of an Index. IndexEndpoints contain one or more DeployedIndexes. * </pre> * * Protobuf type {@code google.cloud.aiplatform.v1.DeployedIndex} */ public final class DeployedIndex extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.aiplatform.v1.DeployedIndex) DeployedIndexOrBuilder { private static final long serialVersionUID = 0L; // Use DeployedIndex.newBuilder() to construct. private DeployedIndex(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private DeployedIndex() { id_ = ""; index_ = ""; displayName_ = ""; reservedIpRanges_ = com.google.protobuf.LazyStringArrayList.EMPTY; deploymentGroup_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new DeployedIndex(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private DeployedIndex( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); id_ = s; break; } case 18: { java.lang.String s = input.readStringRequireUtf8(); index_ = s; break; } case 26: { java.lang.String s = input.readStringRequireUtf8(); displayName_ = s; break; } case 34: { com.google.protobuf.Timestamp.Builder subBuilder = null; if (createTime_ != null) { subBuilder = createTime_.toBuilder(); } createTime_ = input.readMessage(com.google.protobuf.Timestamp.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(createTime_); createTime_ = subBuilder.buildPartial(); } break; } case 42: { com.google.cloud.aiplatform.v1.IndexPrivateEndpoints.Builder subBuilder = null; if (privateEndpoints_ != null) { subBuilder = privateEndpoints_.toBuilder(); } privateEndpoints_ = input.readMessage( com.google.cloud.aiplatform.v1.IndexPrivateEndpoints.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(privateEndpoints_); privateEndpoints_ = subBuilder.buildPartial(); } break; } case 50: { com.google.protobuf.Timestamp.Builder subBuilder = null; if (indexSyncTime_ != null) { subBuilder = indexSyncTime_.toBuilder(); } indexSyncTime_ = input.readMessage(com.google.protobuf.Timestamp.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(indexSyncTime_); indexSyncTime_ = subBuilder.buildPartial(); } break; } case 58: { com.google.cloud.aiplatform.v1.AutomaticResources.Builder subBuilder = null; if (automaticResources_ != null) { subBuilder = automaticResources_.toBuilder(); } automaticResources_ = input.readMessage( com.google.cloud.aiplatform.v1.AutomaticResources.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(automaticResources_); automaticResources_ = subBuilder.buildPartial(); } break; } case 64: { enableAccessLogging_ = input.readBool(); break; } case 74: { com.google.cloud.aiplatform.v1.DeployedIndexAuthConfig.Builder subBuilder = null; if (deployedIndexAuthConfig_ != null) { subBuilder = deployedIndexAuthConfig_.toBuilder(); } deployedIndexAuthConfig_ = input.readMessage( com.google.cloud.aiplatform.v1.DeployedIndexAuthConfig.parser(), extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(deployedIndexAuthConfig_); deployedIndexAuthConfig_ = subBuilder.buildPartial(); } break; } case 82: { java.lang.String s = input.readStringRequireUtf8(); if (!((mutable_bitField0_ & 0x00000001) != 0)) { reservedIpRanges_ = new com.google.protobuf.LazyStringArrayList(); mutable_bitField0_ |= 0x00000001; } reservedIpRanges_.add(s); break; } case 90: { java.lang.String s = input.readStringRequireUtf8(); deploymentGroup_ = s; break; } default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000001) != 0)) { reservedIpRanges_ = reservedIpRanges_.getUnmodifiableView(); } this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.aiplatform.v1.IndexEndpointProto .internal_static_google_cloud_aiplatform_v1_DeployedIndex_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.aiplatform.v1.IndexEndpointProto .internal_static_google_cloud_aiplatform_v1_DeployedIndex_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.aiplatform.v1.DeployedIndex.class, com.google.cloud.aiplatform.v1.DeployedIndex.Builder.class); } public static final int ID_FIELD_NUMBER = 1; private volatile java.lang.Object id_; /** * * * <pre> * Required. The user specified ID of the DeployedIndex. * The ID can be up to 128 characters long and must start with a letter and * only contain letters, numbers, and underscores. * The ID must be unique within the project it is created in. * </pre> * * <code>string id = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The id. */ @java.lang.Override public java.lang.String getId() { java.lang.Object ref = id_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); id_ = s; return s; } } /** * * * <pre> * Required. The user specified ID of the DeployedIndex. * The ID can be up to 128 characters long and must start with a letter and * only contain letters, numbers, and underscores. * The ID must be unique within the project it is created in. * </pre> * * <code>string id = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for id. */ @java.lang.Override public com.google.protobuf.ByteString getIdBytes() { java.lang.Object ref = id_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); id_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int INDEX_FIELD_NUMBER = 2; private volatile java.lang.Object index_; /** * * * <pre> * Required. The name of the Index this is the deployment of. * We may refer to this Index as the DeployedIndex's "original" Index. * </pre> * * <code> * string index = 2 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The index. */ @java.lang.Override public java.lang.String getIndex() { java.lang.Object ref = index_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); index_ = s; return s; } } /** * * * <pre> * Required. The name of the Index this is the deployment of. * We may refer to this Index as the DeployedIndex's "original" Index. * </pre> * * <code> * string index = 2 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for index. */ @java.lang.Override public com.google.protobuf.ByteString getIndexBytes() { java.lang.Object ref = index_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); index_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int DISPLAY_NAME_FIELD_NUMBER = 3; private volatile java.lang.Object displayName_; /** * * * <pre> * The display name of the DeployedIndex. If not provided upon creation, * the Index's display_name is used. * </pre> * * <code>string display_name = 3;</code> * * @return The displayName. */ @java.lang.Override public java.lang.String getDisplayName() { java.lang.Object ref = displayName_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); displayName_ = s; return s; } } /** * * * <pre> * The display name of the DeployedIndex. If not provided upon creation, * the Index's display_name is used. * </pre> * * <code>string display_name = 3;</code> * * @return The bytes for displayName. */ @java.lang.Override public com.google.protobuf.ByteString getDisplayNameBytes() { java.lang.Object ref = displayName_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); displayName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int CREATE_TIME_FIELD_NUMBER = 4; private com.google.protobuf.Timestamp createTime_; /** * * * <pre> * Output only. Timestamp when the DeployedIndex was created. * </pre> * * <code>.google.protobuf.Timestamp create_time = 4 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return Whether the createTime field is set. */ @java.lang.Override public boolean hasCreateTime() { return createTime_ != null; } /** * * * <pre> * Output only. Timestamp when the DeployedIndex was created. * </pre> * * <code>.google.protobuf.Timestamp create_time = 4 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return The createTime. */ @java.lang.Override public com.google.protobuf.Timestamp getCreateTime() { return createTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : createTime_; } /** * * * <pre> * Output only. Timestamp when the DeployedIndex was created. * </pre> * * <code>.google.protobuf.Timestamp create_time = 4 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ @java.lang.Override public com.google.protobuf.TimestampOrBuilder getCreateTimeOrBuilder() { return getCreateTime(); } public static final int PRIVATE_ENDPOINTS_FIELD_NUMBER = 5; private com.google.cloud.aiplatform.v1.IndexPrivateEndpoints privateEndpoints_; /** * * * <pre> * Output only. Provides paths for users to send requests directly to the deployed index * services running on Cloud via private services access. This field is * populated if [network][google.cloud.aiplatform.v1.IndexEndpoint.network] is configured. * </pre> * * <code> * .google.cloud.aiplatform.v1.IndexPrivateEndpoints private_endpoints = 5 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return Whether the privateEndpoints field is set. */ @java.lang.Override public boolean hasPrivateEndpoints() { return privateEndpoints_ != null; } /** * * * <pre> * Output only. Provides paths for users to send requests directly to the deployed index * services running on Cloud via private services access. This field is * populated if [network][google.cloud.aiplatform.v1.IndexEndpoint.network] is configured. * </pre> * * <code> * .google.cloud.aiplatform.v1.IndexPrivateEndpoints private_endpoints = 5 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return The privateEndpoints. */ @java.lang.Override public com.google.cloud.aiplatform.v1.IndexPrivateEndpoints getPrivateEndpoints() { return privateEndpoints_ == null ? com.google.cloud.aiplatform.v1.IndexPrivateEndpoints.getDefaultInstance() : privateEndpoints_; } /** * * * <pre> * Output only. Provides paths for users to send requests directly to the deployed index * services running on Cloud via private services access. This field is * populated if [network][google.cloud.aiplatform.v1.IndexEndpoint.network] is configured. * </pre> * * <code> * .google.cloud.aiplatform.v1.IndexPrivateEndpoints private_endpoints = 5 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ @java.lang.Override public com.google.cloud.aiplatform.v1.IndexPrivateEndpointsOrBuilder getPrivateEndpointsOrBuilder() { return getPrivateEndpoints(); } public static final int INDEX_SYNC_TIME_FIELD_NUMBER = 6; private com.google.protobuf.Timestamp indexSyncTime_; /** * * * <pre> * Output only. The DeployedIndex may depend on various data on its original Index. * Additionally when certain changes to the original Index are being done * (e.g. when what the Index contains is being changed) the DeployedIndex may * be asynchronously updated in the background to reflect this changes. * If this timestamp's value is at least the [Index.update_time][google.cloud.aiplatform.v1.Index.update_time] of the * original Index, it means that this DeployedIndex and the original Index are * in sync. If this timestamp is older, then to see which updates this * DeployedIndex already contains (and which not), one must * [list][Operations.ListOperations] [Operations][Operation] * [working][Operation.name] on the original Index. Only * the successfully completed Operations with * [Operations.metadata.generic_metadata.update_time] * [google.cloud.aiplatform.v1.GenericOperationMetadata.update_time] * equal or before this sync time are contained in this DeployedIndex. * </pre> * * <code> * .google.protobuf.Timestamp index_sync_time = 6 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return Whether the indexSyncTime field is set. */ @java.lang.Override public boolean hasIndexSyncTime() { return indexSyncTime_ != null; } /** * * * <pre> * Output only. The DeployedIndex may depend on various data on its original Index. * Additionally when certain changes to the original Index are being done * (e.g. when what the Index contains is being changed) the DeployedIndex may * be asynchronously updated in the background to reflect this changes. * If this timestamp's value is at least the [Index.update_time][google.cloud.aiplatform.v1.Index.update_time] of the * original Index, it means that this DeployedIndex and the original Index are * in sync. If this timestamp is older, then to see which updates this * DeployedIndex already contains (and which not), one must * [list][Operations.ListOperations] [Operations][Operation] * [working][Operation.name] on the original Index. Only * the successfully completed Operations with * [Operations.metadata.generic_metadata.update_time] * [google.cloud.aiplatform.v1.GenericOperationMetadata.update_time] * equal or before this sync time are contained in this DeployedIndex. * </pre> * * <code> * .google.protobuf.Timestamp index_sync_time = 6 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return The indexSyncTime. */ @java.lang.Override public com.google.protobuf.Timestamp getIndexSyncTime() { return indexSyncTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : indexSyncTime_; } /** * * * <pre> * Output only. The DeployedIndex may depend on various data on its original Index. * Additionally when certain changes to the original Index are being done * (e.g. when what the Index contains is being changed) the DeployedIndex may * be asynchronously updated in the background to reflect this changes. * If this timestamp's value is at least the [Index.update_time][google.cloud.aiplatform.v1.Index.update_time] of the * original Index, it means that this DeployedIndex and the original Index are * in sync. If this timestamp is older, then to see which updates this * DeployedIndex already contains (and which not), one must * [list][Operations.ListOperations] [Operations][Operation] * [working][Operation.name] on the original Index. Only * the successfully completed Operations with * [Operations.metadata.generic_metadata.update_time] * [google.cloud.aiplatform.v1.GenericOperationMetadata.update_time] * equal or before this sync time are contained in this DeployedIndex. * </pre> * * <code> * .google.protobuf.Timestamp index_sync_time = 6 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ @java.lang.Override public com.google.protobuf.TimestampOrBuilder getIndexSyncTimeOrBuilder() { return getIndexSyncTime(); } public static final int AUTOMATIC_RESOURCES_FIELD_NUMBER = 7; private com.google.cloud.aiplatform.v1.AutomaticResources automaticResources_; /** * * * <pre> * Optional. A description of resources that the DeployedIndex uses, which to large * degree are decided by Vertex AI, and optionally allows only a modest * additional configuration. * If min_replica_count is not set, the default value is 2 (we don't provide * SLA when min_replica_count=1). If max_replica_count is not set, the * default value is min_replica_count. The max allowed replica count is * 1000. * </pre> * * <code> * .google.cloud.aiplatform.v1.AutomaticResources automatic_resources = 7 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return Whether the automaticResources field is set. */ @java.lang.Override public boolean hasAutomaticResources() { return automaticResources_ != null; } /** * * * <pre> * Optional. A description of resources that the DeployedIndex uses, which to large * degree are decided by Vertex AI, and optionally allows only a modest * additional configuration. * If min_replica_count is not set, the default value is 2 (we don't provide * SLA when min_replica_count=1). If max_replica_count is not set, the * default value is min_replica_count. The max allowed replica count is * 1000. * </pre> * * <code> * .google.cloud.aiplatform.v1.AutomaticResources automatic_resources = 7 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return The automaticResources. */ @java.lang.Override public com.google.cloud.aiplatform.v1.AutomaticResources getAutomaticResources() { return automaticResources_ == null ? com.google.cloud.aiplatform.v1.AutomaticResources.getDefaultInstance() : automaticResources_; } /** * * * <pre> * Optional. A description of resources that the DeployedIndex uses, which to large * degree are decided by Vertex AI, and optionally allows only a modest * additional configuration. * If min_replica_count is not set, the default value is 2 (we don't provide * SLA when min_replica_count=1). If max_replica_count is not set, the * default value is min_replica_count. The max allowed replica count is * 1000. * </pre> * * <code> * .google.cloud.aiplatform.v1.AutomaticResources automatic_resources = 7 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ @java.lang.Override public com.google.cloud.aiplatform.v1.AutomaticResourcesOrBuilder getAutomaticResourcesOrBuilder() { return getAutomaticResources(); } public static final int ENABLE_ACCESS_LOGGING_FIELD_NUMBER = 8; private boolean enableAccessLogging_; /** * * * <pre> * Optional. If true, private endpoint's access logs are sent to StackDriver Logging. * These logs are like standard server access logs, containing * information like timestamp and latency for each MatchRequest. * Note that Stackdriver logs may incur a cost, especially if the deployed * index receives a high queries per second rate (QPS). * Estimate your costs before enabling this option. * </pre> * * <code>bool enable_access_logging = 8 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The enableAccessLogging. */ @java.lang.Override public boolean getEnableAccessLogging() { return enableAccessLogging_; } public static final int DEPLOYED_INDEX_AUTH_CONFIG_FIELD_NUMBER = 9; private com.google.cloud.aiplatform.v1.DeployedIndexAuthConfig deployedIndexAuthConfig_; /** * * * <pre> * Optional. If set, the authentication is enabled for the private endpoint. * </pre> * * <code> * .google.cloud.aiplatform.v1.DeployedIndexAuthConfig deployed_index_auth_config = 9 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return Whether the deployedIndexAuthConfig field is set. */ @java.lang.Override public boolean hasDeployedIndexAuthConfig() { return deployedIndexAuthConfig_ != null; } /** * * * <pre> * Optional. If set, the authentication is enabled for the private endpoint. * </pre> * * <code> * .google.cloud.aiplatform.v1.DeployedIndexAuthConfig deployed_index_auth_config = 9 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return The deployedIndexAuthConfig. */ @java.lang.Override public com.google.cloud.aiplatform.v1.DeployedIndexAuthConfig getDeployedIndexAuthConfig() { return deployedIndexAuthConfig_ == null ? com.google.cloud.aiplatform.v1.DeployedIndexAuthConfig.getDefaultInstance() : deployedIndexAuthConfig_; } /** * * * <pre> * Optional. If set, the authentication is enabled for the private endpoint. * </pre> * * <code> * .google.cloud.aiplatform.v1.DeployedIndexAuthConfig deployed_index_auth_config = 9 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ @java.lang.Override public com.google.cloud.aiplatform.v1.DeployedIndexAuthConfigOrBuilder getDeployedIndexAuthConfigOrBuilder() { return getDeployedIndexAuthConfig(); } public static final int RESERVED_IP_RANGES_FIELD_NUMBER = 10; private com.google.protobuf.LazyStringList reservedIpRanges_; /** * * * <pre> * Optional. A list of reserved ip ranges under the VPC network that can be * used for this DeployedIndex. * If set, we will deploy the index within the provided ip ranges. Otherwise, * the index might be deployed to any ip ranges under the provided VPC * network. * The value sohuld be the name of the address * (https://cloud.google.com/compute/docs/reference/rest/v1/addresses) * Example: 'vertex-ai-ip-range'. * </pre> * * <code>repeated string reserved_ip_ranges = 10 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return A list containing the reservedIpRanges. */ public com.google.protobuf.ProtocolStringList getReservedIpRangesList() { return reservedIpRanges_; } /** * * * <pre> * Optional. A list of reserved ip ranges under the VPC network that can be * used for this DeployedIndex. * If set, we will deploy the index within the provided ip ranges. Otherwise, * the index might be deployed to any ip ranges under the provided VPC * network. * The value sohuld be the name of the address * (https://cloud.google.com/compute/docs/reference/rest/v1/addresses) * Example: 'vertex-ai-ip-range'. * </pre> * * <code>repeated string reserved_ip_ranges = 10 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The count of reservedIpRanges. */ public int getReservedIpRangesCount() { return reservedIpRanges_.size(); } /** * * * <pre> * Optional. A list of reserved ip ranges under the VPC network that can be * used for this DeployedIndex. * If set, we will deploy the index within the provided ip ranges. Otherwise, * the index might be deployed to any ip ranges under the provided VPC * network. * The value sohuld be the name of the address * (https://cloud.google.com/compute/docs/reference/rest/v1/addresses) * Example: 'vertex-ai-ip-range'. * </pre> * * <code>repeated string reserved_ip_ranges = 10 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param index The index of the element to return. * @return The reservedIpRanges at the given index. */ public java.lang.String getReservedIpRanges(int index) { return reservedIpRanges_.get(index); } /** * * * <pre> * Optional. A list of reserved ip ranges under the VPC network that can be * used for this DeployedIndex. * If set, we will deploy the index within the provided ip ranges. Otherwise, * the index might be deployed to any ip ranges under the provided VPC * network. * The value sohuld be the name of the address * (https://cloud.google.com/compute/docs/reference/rest/v1/addresses) * Example: 'vertex-ai-ip-range'. * </pre> * * <code>repeated string reserved_ip_ranges = 10 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param index The index of the value to return. * @return The bytes of the reservedIpRanges at the given index. */ public com.google.protobuf.ByteString getReservedIpRangesBytes(int index) { return reservedIpRanges_.getByteString(index); } public static final int DEPLOYMENT_GROUP_FIELD_NUMBER = 11; private volatile java.lang.Object deploymentGroup_; /** * * * <pre> * Optional. The deployment group can be no longer than 64 characters (eg: * 'test', 'prod'). If not set, we will use the 'default' deployment group. * Creating `deployment_groups` with `reserved_ip_ranges` is a recommended * practice when the peered network has multiple peering ranges. This creates * your deployments from predictable IP spaces for easier traffic * administration. Also, one deployment_group (except 'default') can only be * used with the same reserved_ip_ranges which means if the deployment_group * has been used with reserved_ip_ranges: [a, b, c], using it with [a, b] or * [d, e] is disallowed. * Note: we only support up to 5 deployment groups(not including 'default'). * </pre> * * <code>string deployment_group = 11 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The deploymentGroup. */ @java.lang.Override public java.lang.String getDeploymentGroup() { java.lang.Object ref = deploymentGroup_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); deploymentGroup_ = s; return s; } } /** * * * <pre> * Optional. The deployment group can be no longer than 64 characters (eg: * 'test', 'prod'). If not set, we will use the 'default' deployment group. * Creating `deployment_groups` with `reserved_ip_ranges` is a recommended * practice when the peered network has multiple peering ranges. This creates * your deployments from predictable IP spaces for easier traffic * administration. Also, one deployment_group (except 'default') can only be * used with the same reserved_ip_ranges which means if the deployment_group * has been used with reserved_ip_ranges: [a, b, c], using it with [a, b] or * [d, e] is disallowed. * Note: we only support up to 5 deployment groups(not including 'default'). * </pre> * * <code>string deployment_group = 11 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for deploymentGroup. */ @java.lang.Override public com.google.protobuf.ByteString getDeploymentGroupBytes() { java.lang.Object ref = deploymentGroup_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); deploymentGroup_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(id_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, id_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(index_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 2, index_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(displayName_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 3, displayName_); } if (createTime_ != null) { output.writeMessage(4, getCreateTime()); } if (privateEndpoints_ != null) { output.writeMessage(5, getPrivateEndpoints()); } if (indexSyncTime_ != null) { output.writeMessage(6, getIndexSyncTime()); } if (automaticResources_ != null) { output.writeMessage(7, getAutomaticResources()); } if (enableAccessLogging_ != false) { output.writeBool(8, enableAccessLogging_); } if (deployedIndexAuthConfig_ != null) { output.writeMessage(9, getDeployedIndexAuthConfig()); } for (int i = 0; i < reservedIpRanges_.size(); i++) { com.google.protobuf.GeneratedMessageV3.writeString(output, 10, reservedIpRanges_.getRaw(i)); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(deploymentGroup_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 11, deploymentGroup_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(id_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, id_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(index_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(2, index_); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(displayName_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(3, displayName_); } if (createTime_ != null) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(4, getCreateTime()); } if (privateEndpoints_ != null) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(5, getPrivateEndpoints()); } if (indexSyncTime_ != null) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(6, getIndexSyncTime()); } if (automaticResources_ != null) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(7, getAutomaticResources()); } if (enableAccessLogging_ != false) { size += com.google.protobuf.CodedOutputStream.computeBoolSize(8, enableAccessLogging_); } if (deployedIndexAuthConfig_ != null) { size += com.google.protobuf.CodedOutputStream.computeMessageSize(9, getDeployedIndexAuthConfig()); } { int dataSize = 0; for (int i = 0; i < reservedIpRanges_.size(); i++) { dataSize += computeStringSizeNoTag(reservedIpRanges_.getRaw(i)); } size += dataSize; size += 1 * getReservedIpRangesList().size(); } if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(deploymentGroup_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(11, deploymentGroup_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.aiplatform.v1.DeployedIndex)) { return super.equals(obj); } com.google.cloud.aiplatform.v1.DeployedIndex other = (com.google.cloud.aiplatform.v1.DeployedIndex) obj; if (!getId().equals(other.getId())) return false; if (!getIndex().equals(other.getIndex())) return false; if (!getDisplayName().equals(other.getDisplayName())) return false; if (hasCreateTime() != other.hasCreateTime()) return false; if (hasCreateTime()) { if (!getCreateTime().equals(other.getCreateTime())) return false; } if (hasPrivateEndpoints() != other.hasPrivateEndpoints()) return false; if (hasPrivateEndpoints()) { if (!getPrivateEndpoints().equals(other.getPrivateEndpoints())) return false; } if (hasIndexSyncTime() != other.hasIndexSyncTime()) return false; if (hasIndexSyncTime()) { if (!getIndexSyncTime().equals(other.getIndexSyncTime())) return false; } if (hasAutomaticResources() != other.hasAutomaticResources()) return false; if (hasAutomaticResources()) { if (!getAutomaticResources().equals(other.getAutomaticResources())) return false; } if (getEnableAccessLogging() != other.getEnableAccessLogging()) return false; if (hasDeployedIndexAuthConfig() != other.hasDeployedIndexAuthConfig()) return false; if (hasDeployedIndexAuthConfig()) { if (!getDeployedIndexAuthConfig().equals(other.getDeployedIndexAuthConfig())) return false; } if (!getReservedIpRangesList().equals(other.getReservedIpRangesList())) return false; if (!getDeploymentGroup().equals(other.getDeploymentGroup())) return false; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + ID_FIELD_NUMBER; hash = (53 * hash) + getId().hashCode(); hash = (37 * hash) + INDEX_FIELD_NUMBER; hash = (53 * hash) + getIndex().hashCode(); hash = (37 * hash) + DISPLAY_NAME_FIELD_NUMBER; hash = (53 * hash) + getDisplayName().hashCode(); if (hasCreateTime()) { hash = (37 * hash) + CREATE_TIME_FIELD_NUMBER; hash = (53 * hash) + getCreateTime().hashCode(); } if (hasPrivateEndpoints()) { hash = (37 * hash) + PRIVATE_ENDPOINTS_FIELD_NUMBER; hash = (53 * hash) + getPrivateEndpoints().hashCode(); } if (hasIndexSyncTime()) { hash = (37 * hash) + INDEX_SYNC_TIME_FIELD_NUMBER; hash = (53 * hash) + getIndexSyncTime().hashCode(); } if (hasAutomaticResources()) { hash = (37 * hash) + AUTOMATIC_RESOURCES_FIELD_NUMBER; hash = (53 * hash) + getAutomaticResources().hashCode(); } hash = (37 * hash) + ENABLE_ACCESS_LOGGING_FIELD_NUMBER; hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(getEnableAccessLogging()); if (hasDeployedIndexAuthConfig()) { hash = (37 * hash) + DEPLOYED_INDEX_AUTH_CONFIG_FIELD_NUMBER; hash = (53 * hash) + getDeployedIndexAuthConfig().hashCode(); } if (getReservedIpRangesCount() > 0) { hash = (37 * hash) + RESERVED_IP_RANGES_FIELD_NUMBER; hash = (53 * hash) + getReservedIpRangesList().hashCode(); } hash = (37 * hash) + DEPLOYMENT_GROUP_FIELD_NUMBER; hash = (53 * hash) + getDeploymentGroup().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.aiplatform.v1.DeployedIndex parseFrom(java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1.DeployedIndex parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.aiplatform.v1.DeployedIndex parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1.DeployedIndex parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.aiplatform.v1.DeployedIndex parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.aiplatform.v1.DeployedIndex parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.aiplatform.v1.DeployedIndex parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1.DeployedIndex parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.aiplatform.v1.DeployedIndex parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1.DeployedIndex parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.aiplatform.v1.DeployedIndex parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.aiplatform.v1.DeployedIndex parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.cloud.aiplatform.v1.DeployedIndex prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * A deployment of an Index. IndexEndpoints contain one or more DeployedIndexes. * </pre> * * Protobuf type {@code google.cloud.aiplatform.v1.DeployedIndex} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.aiplatform.v1.DeployedIndex) com.google.cloud.aiplatform.v1.DeployedIndexOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.aiplatform.v1.IndexEndpointProto .internal_static_google_cloud_aiplatform_v1_DeployedIndex_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.aiplatform.v1.IndexEndpointProto .internal_static_google_cloud_aiplatform_v1_DeployedIndex_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.aiplatform.v1.DeployedIndex.class, com.google.cloud.aiplatform.v1.DeployedIndex.Builder.class); } // Construct using com.google.cloud.aiplatform.v1.DeployedIndex.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {} } @java.lang.Override public Builder clear() { super.clear(); id_ = ""; index_ = ""; displayName_ = ""; if (createTimeBuilder_ == null) { createTime_ = null; } else { createTime_ = null; createTimeBuilder_ = null; } if (privateEndpointsBuilder_ == null) { privateEndpoints_ = null; } else { privateEndpoints_ = null; privateEndpointsBuilder_ = null; } if (indexSyncTimeBuilder_ == null) { indexSyncTime_ = null; } else { indexSyncTime_ = null; indexSyncTimeBuilder_ = null; } if (automaticResourcesBuilder_ == null) { automaticResources_ = null; } else { automaticResources_ = null; automaticResourcesBuilder_ = null; } enableAccessLogging_ = false; if (deployedIndexAuthConfigBuilder_ == null) { deployedIndexAuthConfig_ = null; } else { deployedIndexAuthConfig_ = null; deployedIndexAuthConfigBuilder_ = null; } reservedIpRanges_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000001); deploymentGroup_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.aiplatform.v1.IndexEndpointProto .internal_static_google_cloud_aiplatform_v1_DeployedIndex_descriptor; } @java.lang.Override public com.google.cloud.aiplatform.v1.DeployedIndex getDefaultInstanceForType() { return com.google.cloud.aiplatform.v1.DeployedIndex.getDefaultInstance(); } @java.lang.Override public com.google.cloud.aiplatform.v1.DeployedIndex build() { com.google.cloud.aiplatform.v1.DeployedIndex result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.aiplatform.v1.DeployedIndex buildPartial() { com.google.cloud.aiplatform.v1.DeployedIndex result = new com.google.cloud.aiplatform.v1.DeployedIndex(this); int from_bitField0_ = bitField0_; result.id_ = id_; result.index_ = index_; result.displayName_ = displayName_; if (createTimeBuilder_ == null) { result.createTime_ = createTime_; } else { result.createTime_ = createTimeBuilder_.build(); } if (privateEndpointsBuilder_ == null) { result.privateEndpoints_ = privateEndpoints_; } else { result.privateEndpoints_ = privateEndpointsBuilder_.build(); } if (indexSyncTimeBuilder_ == null) { result.indexSyncTime_ = indexSyncTime_; } else { result.indexSyncTime_ = indexSyncTimeBuilder_.build(); } if (automaticResourcesBuilder_ == null) { result.automaticResources_ = automaticResources_; } else { result.automaticResources_ = automaticResourcesBuilder_.build(); } result.enableAccessLogging_ = enableAccessLogging_; if (deployedIndexAuthConfigBuilder_ == null) { result.deployedIndexAuthConfig_ = deployedIndexAuthConfig_; } else { result.deployedIndexAuthConfig_ = deployedIndexAuthConfigBuilder_.build(); } if (((bitField0_ & 0x00000001) != 0)) { reservedIpRanges_ = reservedIpRanges_.getUnmodifiableView(); bitField0_ = (bitField0_ & ~0x00000001); } result.reservedIpRanges_ = reservedIpRanges_; result.deploymentGroup_ = deploymentGroup_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.aiplatform.v1.DeployedIndex) { return mergeFrom((com.google.cloud.aiplatform.v1.DeployedIndex) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.aiplatform.v1.DeployedIndex other) { if (other == com.google.cloud.aiplatform.v1.DeployedIndex.getDefaultInstance()) return this; if (!other.getId().isEmpty()) { id_ = other.id_; onChanged(); } if (!other.getIndex().isEmpty()) { index_ = other.index_; onChanged(); } if (!other.getDisplayName().isEmpty()) { displayName_ = other.displayName_; onChanged(); } if (other.hasCreateTime()) { mergeCreateTime(other.getCreateTime()); } if (other.hasPrivateEndpoints()) { mergePrivateEndpoints(other.getPrivateEndpoints()); } if (other.hasIndexSyncTime()) { mergeIndexSyncTime(other.getIndexSyncTime()); } if (other.hasAutomaticResources()) { mergeAutomaticResources(other.getAutomaticResources()); } if (other.getEnableAccessLogging() != false) { setEnableAccessLogging(other.getEnableAccessLogging()); } if (other.hasDeployedIndexAuthConfig()) { mergeDeployedIndexAuthConfig(other.getDeployedIndexAuthConfig()); } if (!other.reservedIpRanges_.isEmpty()) { if (reservedIpRanges_.isEmpty()) { reservedIpRanges_ = other.reservedIpRanges_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureReservedIpRangesIsMutable(); reservedIpRanges_.addAll(other.reservedIpRanges_); } onChanged(); } if (!other.getDeploymentGroup().isEmpty()) { deploymentGroup_ = other.deploymentGroup_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.cloud.aiplatform.v1.DeployedIndex parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.cloud.aiplatform.v1.DeployedIndex) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private java.lang.Object id_ = ""; /** * * * <pre> * Required. The user specified ID of the DeployedIndex. * The ID can be up to 128 characters long and must start with a letter and * only contain letters, numbers, and underscores. * The ID must be unique within the project it is created in. * </pre> * * <code>string id = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The id. */ public java.lang.String getId() { java.lang.Object ref = id_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); id_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The user specified ID of the DeployedIndex. * The ID can be up to 128 characters long and must start with a letter and * only contain letters, numbers, and underscores. * The ID must be unique within the project it is created in. * </pre> * * <code>string id = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return The bytes for id. */ public com.google.protobuf.ByteString getIdBytes() { java.lang.Object ref = id_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); id_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The user specified ID of the DeployedIndex. * The ID can be up to 128 characters long and must start with a letter and * only contain letters, numbers, and underscores. * The ID must be unique within the project it is created in. * </pre> * * <code>string id = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The id to set. * @return This builder for chaining. */ public Builder setId(java.lang.String value) { if (value == null) { throw new NullPointerException(); } id_ = value; onChanged(); return this; } /** * * * <pre> * Required. The user specified ID of the DeployedIndex. * The ID can be up to 128 characters long and must start with a letter and * only contain letters, numbers, and underscores. * The ID must be unique within the project it is created in. * </pre> * * <code>string id = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @return This builder for chaining. */ public Builder clearId() { id_ = getDefaultInstance().getId(); onChanged(); return this; } /** * * * <pre> * Required. The user specified ID of the DeployedIndex. * The ID can be up to 128 characters long and must start with a letter and * only contain letters, numbers, and underscores. * The ID must be unique within the project it is created in. * </pre> * * <code>string id = 1 [(.google.api.field_behavior) = REQUIRED];</code> * * @param value The bytes for id to set. * @return This builder for chaining. */ public Builder setIdBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); id_ = value; onChanged(); return this; } private java.lang.Object index_ = ""; /** * * * <pre> * Required. The name of the Index this is the deployment of. * We may refer to this Index as the DeployedIndex's "original" Index. * </pre> * * <code> * string index = 2 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The index. */ public java.lang.String getIndex() { java.lang.Object ref = index_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); index_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Required. The name of the Index this is the deployment of. * We may refer to this Index as the DeployedIndex's "original" Index. * </pre> * * <code> * string index = 2 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return The bytes for index. */ public com.google.protobuf.ByteString getIndexBytes() { java.lang.Object ref = index_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); index_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Required. The name of the Index this is the deployment of. * We may refer to this Index as the DeployedIndex's "original" Index. * </pre> * * <code> * string index = 2 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The index to set. * @return This builder for chaining. */ public Builder setIndex(java.lang.String value) { if (value == null) { throw new NullPointerException(); } index_ = value; onChanged(); return this; } /** * * * <pre> * Required. The name of the Index this is the deployment of. * We may refer to this Index as the DeployedIndex's "original" Index. * </pre> * * <code> * string index = 2 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @return This builder for chaining. */ public Builder clearIndex() { index_ = getDefaultInstance().getIndex(); onChanged(); return this; } /** * * * <pre> * Required. The name of the Index this is the deployment of. * We may refer to this Index as the DeployedIndex's "original" Index. * </pre> * * <code> * string index = 2 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... } * </code> * * @param value The bytes for index to set. * @return This builder for chaining. */ public Builder setIndexBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); index_ = value; onChanged(); return this; } private java.lang.Object displayName_ = ""; /** * * * <pre> * The display name of the DeployedIndex. If not provided upon creation, * the Index's display_name is used. * </pre> * * <code>string display_name = 3;</code> * * @return The displayName. */ public java.lang.String getDisplayName() { java.lang.Object ref = displayName_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); displayName_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * The display name of the DeployedIndex. If not provided upon creation, * the Index's display_name is used. * </pre> * * <code>string display_name = 3;</code> * * @return The bytes for displayName. */ public com.google.protobuf.ByteString getDisplayNameBytes() { java.lang.Object ref = displayName_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); displayName_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * The display name of the DeployedIndex. If not provided upon creation, * the Index's display_name is used. * </pre> * * <code>string display_name = 3;</code> * * @param value The displayName to set. * @return This builder for chaining. */ public Builder setDisplayName(java.lang.String value) { if (value == null) { throw new NullPointerException(); } displayName_ = value; onChanged(); return this; } /** * * * <pre> * The display name of the DeployedIndex. If not provided upon creation, * the Index's display_name is used. * </pre> * * <code>string display_name = 3;</code> * * @return This builder for chaining. */ public Builder clearDisplayName() { displayName_ = getDefaultInstance().getDisplayName(); onChanged(); return this; } /** * * * <pre> * The display name of the DeployedIndex. If not provided upon creation, * the Index's display_name is used. * </pre> * * <code>string display_name = 3;</code> * * @param value The bytes for displayName to set. * @return This builder for chaining. */ public Builder setDisplayNameBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); displayName_ = value; onChanged(); return this; } private com.google.protobuf.Timestamp createTime_; private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> createTimeBuilder_; /** * * * <pre> * Output only. Timestamp when the DeployedIndex was created. * </pre> * * <code> * .google.protobuf.Timestamp create_time = 4 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return Whether the createTime field is set. */ public boolean hasCreateTime() { return createTimeBuilder_ != null || createTime_ != null; } /** * * * <pre> * Output only. Timestamp when the DeployedIndex was created. * </pre> * * <code> * .google.protobuf.Timestamp create_time = 4 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return The createTime. */ public com.google.protobuf.Timestamp getCreateTime() { if (createTimeBuilder_ == null) { return createTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : createTime_; } else { return createTimeBuilder_.getMessage(); } } /** * * * <pre> * Output only. Timestamp when the DeployedIndex was created. * </pre> * * <code> * .google.protobuf.Timestamp create_time = 4 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder setCreateTime(com.google.protobuf.Timestamp value) { if (createTimeBuilder_ == null) { if (value == null) { throw new NullPointerException(); } createTime_ = value; onChanged(); } else { createTimeBuilder_.setMessage(value); } return this; } /** * * * <pre> * Output only. Timestamp when the DeployedIndex was created. * </pre> * * <code> * .google.protobuf.Timestamp create_time = 4 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder setCreateTime(com.google.protobuf.Timestamp.Builder builderForValue) { if (createTimeBuilder_ == null) { createTime_ = builderForValue.build(); onChanged(); } else { createTimeBuilder_.setMessage(builderForValue.build()); } return this; } /** * * * <pre> * Output only. Timestamp when the DeployedIndex was created. * </pre> * * <code> * .google.protobuf.Timestamp create_time = 4 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder mergeCreateTime(com.google.protobuf.Timestamp value) { if (createTimeBuilder_ == null) { if (createTime_ != null) { createTime_ = com.google.protobuf.Timestamp.newBuilder(createTime_).mergeFrom(value).buildPartial(); } else { createTime_ = value; } onChanged(); } else { createTimeBuilder_.mergeFrom(value); } return this; } /** * * * <pre> * Output only. Timestamp when the DeployedIndex was created. * </pre> * * <code> * .google.protobuf.Timestamp create_time = 4 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder clearCreateTime() { if (createTimeBuilder_ == null) { createTime_ = null; onChanged(); } else { createTime_ = null; createTimeBuilder_ = null; } return this; } /** * * * <pre> * Output only. Timestamp when the DeployedIndex was created. * </pre> * * <code> * .google.protobuf.Timestamp create_time = 4 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public com.google.protobuf.Timestamp.Builder getCreateTimeBuilder() { onChanged(); return getCreateTimeFieldBuilder().getBuilder(); } /** * * * <pre> * Output only. Timestamp when the DeployedIndex was created. * </pre> * * <code> * .google.protobuf.Timestamp create_time = 4 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public com.google.protobuf.TimestampOrBuilder getCreateTimeOrBuilder() { if (createTimeBuilder_ != null) { return createTimeBuilder_.getMessageOrBuilder(); } else { return createTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : createTime_; } } /** * * * <pre> * Output only. Timestamp when the DeployedIndex was created. * </pre> * * <code> * .google.protobuf.Timestamp create_time = 4 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> getCreateTimeFieldBuilder() { if (createTimeBuilder_ == null) { createTimeBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder>( getCreateTime(), getParentForChildren(), isClean()); createTime_ = null; } return createTimeBuilder_; } private com.google.cloud.aiplatform.v1.IndexPrivateEndpoints privateEndpoints_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.aiplatform.v1.IndexPrivateEndpoints, com.google.cloud.aiplatform.v1.IndexPrivateEndpoints.Builder, com.google.cloud.aiplatform.v1.IndexPrivateEndpointsOrBuilder> privateEndpointsBuilder_; /** * * * <pre> * Output only. Provides paths for users to send requests directly to the deployed index * services running on Cloud via private services access. This field is * populated if [network][google.cloud.aiplatform.v1.IndexEndpoint.network] is configured. * </pre> * * <code> * .google.cloud.aiplatform.v1.IndexPrivateEndpoints private_endpoints = 5 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return Whether the privateEndpoints field is set. */ public boolean hasPrivateEndpoints() { return privateEndpointsBuilder_ != null || privateEndpoints_ != null; } /** * * * <pre> * Output only. Provides paths for users to send requests directly to the deployed index * services running on Cloud via private services access. This field is * populated if [network][google.cloud.aiplatform.v1.IndexEndpoint.network] is configured. * </pre> * * <code> * .google.cloud.aiplatform.v1.IndexPrivateEndpoints private_endpoints = 5 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return The privateEndpoints. */ public com.google.cloud.aiplatform.v1.IndexPrivateEndpoints getPrivateEndpoints() { if (privateEndpointsBuilder_ == null) { return privateEndpoints_ == null ? com.google.cloud.aiplatform.v1.IndexPrivateEndpoints.getDefaultInstance() : privateEndpoints_; } else { return privateEndpointsBuilder_.getMessage(); } } /** * * * <pre> * Output only. Provides paths for users to send requests directly to the deployed index * services running on Cloud via private services access. This field is * populated if [network][google.cloud.aiplatform.v1.IndexEndpoint.network] is configured. * </pre> * * <code> * .google.cloud.aiplatform.v1.IndexPrivateEndpoints private_endpoints = 5 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder setPrivateEndpoints(com.google.cloud.aiplatform.v1.IndexPrivateEndpoints value) { if (privateEndpointsBuilder_ == null) { if (value == null) { throw new NullPointerException(); } privateEndpoints_ = value; onChanged(); } else { privateEndpointsBuilder_.setMessage(value); } return this; } /** * * * <pre> * Output only. Provides paths for users to send requests directly to the deployed index * services running on Cloud via private services access. This field is * populated if [network][google.cloud.aiplatform.v1.IndexEndpoint.network] is configured. * </pre> * * <code> * .google.cloud.aiplatform.v1.IndexPrivateEndpoints private_endpoints = 5 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder setPrivateEndpoints( com.google.cloud.aiplatform.v1.IndexPrivateEndpoints.Builder builderForValue) { if (privateEndpointsBuilder_ == null) { privateEndpoints_ = builderForValue.build(); onChanged(); } else { privateEndpointsBuilder_.setMessage(builderForValue.build()); } return this; } /** * * * <pre> * Output only. Provides paths for users to send requests directly to the deployed index * services running on Cloud via private services access. This field is * populated if [network][google.cloud.aiplatform.v1.IndexEndpoint.network] is configured. * </pre> * * <code> * .google.cloud.aiplatform.v1.IndexPrivateEndpoints private_endpoints = 5 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder mergePrivateEndpoints( com.google.cloud.aiplatform.v1.IndexPrivateEndpoints value) { if (privateEndpointsBuilder_ == null) { if (privateEndpoints_ != null) { privateEndpoints_ = com.google.cloud.aiplatform.v1.IndexPrivateEndpoints.newBuilder(privateEndpoints_) .mergeFrom(value) .buildPartial(); } else { privateEndpoints_ = value; } onChanged(); } else { privateEndpointsBuilder_.mergeFrom(value); } return this; } /** * * * <pre> * Output only. Provides paths for users to send requests directly to the deployed index * services running on Cloud via private services access. This field is * populated if [network][google.cloud.aiplatform.v1.IndexEndpoint.network] is configured. * </pre> * * <code> * .google.cloud.aiplatform.v1.IndexPrivateEndpoints private_endpoints = 5 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder clearPrivateEndpoints() { if (privateEndpointsBuilder_ == null) { privateEndpoints_ = null; onChanged(); } else { privateEndpoints_ = null; privateEndpointsBuilder_ = null; } return this; } /** * * * <pre> * Output only. Provides paths for users to send requests directly to the deployed index * services running on Cloud via private services access. This field is * populated if [network][google.cloud.aiplatform.v1.IndexEndpoint.network] is configured. * </pre> * * <code> * .google.cloud.aiplatform.v1.IndexPrivateEndpoints private_endpoints = 5 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public com.google.cloud.aiplatform.v1.IndexPrivateEndpoints.Builder getPrivateEndpointsBuilder() { onChanged(); return getPrivateEndpointsFieldBuilder().getBuilder(); } /** * * * <pre> * Output only. Provides paths for users to send requests directly to the deployed index * services running on Cloud via private services access. This field is * populated if [network][google.cloud.aiplatform.v1.IndexEndpoint.network] is configured. * </pre> * * <code> * .google.cloud.aiplatform.v1.IndexPrivateEndpoints private_endpoints = 5 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public com.google.cloud.aiplatform.v1.IndexPrivateEndpointsOrBuilder getPrivateEndpointsOrBuilder() { if (privateEndpointsBuilder_ != null) { return privateEndpointsBuilder_.getMessageOrBuilder(); } else { return privateEndpoints_ == null ? com.google.cloud.aiplatform.v1.IndexPrivateEndpoints.getDefaultInstance() : privateEndpoints_; } } /** * * * <pre> * Output only. Provides paths for users to send requests directly to the deployed index * services running on Cloud via private services access. This field is * populated if [network][google.cloud.aiplatform.v1.IndexEndpoint.network] is configured. * </pre> * * <code> * .google.cloud.aiplatform.v1.IndexPrivateEndpoints private_endpoints = 5 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.aiplatform.v1.IndexPrivateEndpoints, com.google.cloud.aiplatform.v1.IndexPrivateEndpoints.Builder, com.google.cloud.aiplatform.v1.IndexPrivateEndpointsOrBuilder> getPrivateEndpointsFieldBuilder() { if (privateEndpointsBuilder_ == null) { privateEndpointsBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.aiplatform.v1.IndexPrivateEndpoints, com.google.cloud.aiplatform.v1.IndexPrivateEndpoints.Builder, com.google.cloud.aiplatform.v1.IndexPrivateEndpointsOrBuilder>( getPrivateEndpoints(), getParentForChildren(), isClean()); privateEndpoints_ = null; } return privateEndpointsBuilder_; } private com.google.protobuf.Timestamp indexSyncTime_; private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> indexSyncTimeBuilder_; /** * * * <pre> * Output only. The DeployedIndex may depend on various data on its original Index. * Additionally when certain changes to the original Index are being done * (e.g. when what the Index contains is being changed) the DeployedIndex may * be asynchronously updated in the background to reflect this changes. * If this timestamp's value is at least the [Index.update_time][google.cloud.aiplatform.v1.Index.update_time] of the * original Index, it means that this DeployedIndex and the original Index are * in sync. If this timestamp is older, then to see which updates this * DeployedIndex already contains (and which not), one must * [list][Operations.ListOperations] [Operations][Operation] * [working][Operation.name] on the original Index. Only * the successfully completed Operations with * [Operations.metadata.generic_metadata.update_time] * [google.cloud.aiplatform.v1.GenericOperationMetadata.update_time] * equal or before this sync time are contained in this DeployedIndex. * </pre> * * <code> * .google.protobuf.Timestamp index_sync_time = 6 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return Whether the indexSyncTime field is set. */ public boolean hasIndexSyncTime() { return indexSyncTimeBuilder_ != null || indexSyncTime_ != null; } /** * * * <pre> * Output only. The DeployedIndex may depend on various data on its original Index. * Additionally when certain changes to the original Index are being done * (e.g. when what the Index contains is being changed) the DeployedIndex may * be asynchronously updated in the background to reflect this changes. * If this timestamp's value is at least the [Index.update_time][google.cloud.aiplatform.v1.Index.update_time] of the * original Index, it means that this DeployedIndex and the original Index are * in sync. If this timestamp is older, then to see which updates this * DeployedIndex already contains (and which not), one must * [list][Operations.ListOperations] [Operations][Operation] * [working][Operation.name] on the original Index. Only * the successfully completed Operations with * [Operations.metadata.generic_metadata.update_time] * [google.cloud.aiplatform.v1.GenericOperationMetadata.update_time] * equal or before this sync time are contained in this DeployedIndex. * </pre> * * <code> * .google.protobuf.Timestamp index_sync_time = 6 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> * * @return The indexSyncTime. */ public com.google.protobuf.Timestamp getIndexSyncTime() { if (indexSyncTimeBuilder_ == null) { return indexSyncTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : indexSyncTime_; } else { return indexSyncTimeBuilder_.getMessage(); } } /** * * * <pre> * Output only. The DeployedIndex may depend on various data on its original Index. * Additionally when certain changes to the original Index are being done * (e.g. when what the Index contains is being changed) the DeployedIndex may * be asynchronously updated in the background to reflect this changes. * If this timestamp's value is at least the [Index.update_time][google.cloud.aiplatform.v1.Index.update_time] of the * original Index, it means that this DeployedIndex and the original Index are * in sync. If this timestamp is older, then to see which updates this * DeployedIndex already contains (and which not), one must * [list][Operations.ListOperations] [Operations][Operation] * [working][Operation.name] on the original Index. Only * the successfully completed Operations with * [Operations.metadata.generic_metadata.update_time] * [google.cloud.aiplatform.v1.GenericOperationMetadata.update_time] * equal or before this sync time are contained in this DeployedIndex. * </pre> * * <code> * .google.protobuf.Timestamp index_sync_time = 6 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder setIndexSyncTime(com.google.protobuf.Timestamp value) { if (indexSyncTimeBuilder_ == null) { if (value == null) { throw new NullPointerException(); } indexSyncTime_ = value; onChanged(); } else { indexSyncTimeBuilder_.setMessage(value); } return this; } /** * * * <pre> * Output only. The DeployedIndex may depend on various data on its original Index. * Additionally when certain changes to the original Index are being done * (e.g. when what the Index contains is being changed) the DeployedIndex may * be asynchronously updated in the background to reflect this changes. * If this timestamp's value is at least the [Index.update_time][google.cloud.aiplatform.v1.Index.update_time] of the * original Index, it means that this DeployedIndex and the original Index are * in sync. If this timestamp is older, then to see which updates this * DeployedIndex already contains (and which not), one must * [list][Operations.ListOperations] [Operations][Operation] * [working][Operation.name] on the original Index. Only * the successfully completed Operations with * [Operations.metadata.generic_metadata.update_time] * [google.cloud.aiplatform.v1.GenericOperationMetadata.update_time] * equal or before this sync time are contained in this DeployedIndex. * </pre> * * <code> * .google.protobuf.Timestamp index_sync_time = 6 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder setIndexSyncTime(com.google.protobuf.Timestamp.Builder builderForValue) { if (indexSyncTimeBuilder_ == null) { indexSyncTime_ = builderForValue.build(); onChanged(); } else { indexSyncTimeBuilder_.setMessage(builderForValue.build()); } return this; } /** * * * <pre> * Output only. The DeployedIndex may depend on various data on its original Index. * Additionally when certain changes to the original Index are being done * (e.g. when what the Index contains is being changed) the DeployedIndex may * be asynchronously updated in the background to reflect this changes. * If this timestamp's value is at least the [Index.update_time][google.cloud.aiplatform.v1.Index.update_time] of the * original Index, it means that this DeployedIndex and the original Index are * in sync. If this timestamp is older, then to see which updates this * DeployedIndex already contains (and which not), one must * [list][Operations.ListOperations] [Operations][Operation] * [working][Operation.name] on the original Index. Only * the successfully completed Operations with * [Operations.metadata.generic_metadata.update_time] * [google.cloud.aiplatform.v1.GenericOperationMetadata.update_time] * equal or before this sync time are contained in this DeployedIndex. * </pre> * * <code> * .google.protobuf.Timestamp index_sync_time = 6 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder mergeIndexSyncTime(com.google.protobuf.Timestamp value) { if (indexSyncTimeBuilder_ == null) { if (indexSyncTime_ != null) { indexSyncTime_ = com.google.protobuf.Timestamp.newBuilder(indexSyncTime_) .mergeFrom(value) .buildPartial(); } else { indexSyncTime_ = value; } onChanged(); } else { indexSyncTimeBuilder_.mergeFrom(value); } return this; } /** * * * <pre> * Output only. The DeployedIndex may depend on various data on its original Index. * Additionally when certain changes to the original Index are being done * (e.g. when what the Index contains is being changed) the DeployedIndex may * be asynchronously updated in the background to reflect this changes. * If this timestamp's value is at least the [Index.update_time][google.cloud.aiplatform.v1.Index.update_time] of the * original Index, it means that this DeployedIndex and the original Index are * in sync. If this timestamp is older, then to see which updates this * DeployedIndex already contains (and which not), one must * [list][Operations.ListOperations] [Operations][Operation] * [working][Operation.name] on the original Index. Only * the successfully completed Operations with * [Operations.metadata.generic_metadata.update_time] * [google.cloud.aiplatform.v1.GenericOperationMetadata.update_time] * equal or before this sync time are contained in this DeployedIndex. * </pre> * * <code> * .google.protobuf.Timestamp index_sync_time = 6 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public Builder clearIndexSyncTime() { if (indexSyncTimeBuilder_ == null) { indexSyncTime_ = null; onChanged(); } else { indexSyncTime_ = null; indexSyncTimeBuilder_ = null; } return this; } /** * * * <pre> * Output only. The DeployedIndex may depend on various data on its original Index. * Additionally when certain changes to the original Index are being done * (e.g. when what the Index contains is being changed) the DeployedIndex may * be asynchronously updated in the background to reflect this changes. * If this timestamp's value is at least the [Index.update_time][google.cloud.aiplatform.v1.Index.update_time] of the * original Index, it means that this DeployedIndex and the original Index are * in sync. If this timestamp is older, then to see which updates this * DeployedIndex already contains (and which not), one must * [list][Operations.ListOperations] [Operations][Operation] * [working][Operation.name] on the original Index. Only * the successfully completed Operations with * [Operations.metadata.generic_metadata.update_time] * [google.cloud.aiplatform.v1.GenericOperationMetadata.update_time] * equal or before this sync time are contained in this DeployedIndex. * </pre> * * <code> * .google.protobuf.Timestamp index_sync_time = 6 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public com.google.protobuf.Timestamp.Builder getIndexSyncTimeBuilder() { onChanged(); return getIndexSyncTimeFieldBuilder().getBuilder(); } /** * * * <pre> * Output only. The DeployedIndex may depend on various data on its original Index. * Additionally when certain changes to the original Index are being done * (e.g. when what the Index contains is being changed) the DeployedIndex may * be asynchronously updated in the background to reflect this changes. * If this timestamp's value is at least the [Index.update_time][google.cloud.aiplatform.v1.Index.update_time] of the * original Index, it means that this DeployedIndex and the original Index are * in sync. If this timestamp is older, then to see which updates this * DeployedIndex already contains (and which not), one must * [list][Operations.ListOperations] [Operations][Operation] * [working][Operation.name] on the original Index. Only * the successfully completed Operations with * [Operations.metadata.generic_metadata.update_time] * [google.cloud.aiplatform.v1.GenericOperationMetadata.update_time] * equal or before this sync time are contained in this DeployedIndex. * </pre> * * <code> * .google.protobuf.Timestamp index_sync_time = 6 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ public com.google.protobuf.TimestampOrBuilder getIndexSyncTimeOrBuilder() { if (indexSyncTimeBuilder_ != null) { return indexSyncTimeBuilder_.getMessageOrBuilder(); } else { return indexSyncTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : indexSyncTime_; } } /** * * * <pre> * Output only. The DeployedIndex may depend on various data on its original Index. * Additionally when certain changes to the original Index are being done * (e.g. when what the Index contains is being changed) the DeployedIndex may * be asynchronously updated in the background to reflect this changes. * If this timestamp's value is at least the [Index.update_time][google.cloud.aiplatform.v1.Index.update_time] of the * original Index, it means that this DeployedIndex and the original Index are * in sync. If this timestamp is older, then to see which updates this * DeployedIndex already contains (and which not), one must * [list][Operations.ListOperations] [Operations][Operation] * [working][Operation.name] on the original Index. Only * the successfully completed Operations with * [Operations.metadata.generic_metadata.update_time] * [google.cloud.aiplatform.v1.GenericOperationMetadata.update_time] * equal or before this sync time are contained in this DeployedIndex. * </pre> * * <code> * .google.protobuf.Timestamp index_sync_time = 6 [(.google.api.field_behavior) = OUTPUT_ONLY]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder> getIndexSyncTimeFieldBuilder() { if (indexSyncTimeBuilder_ == null) { indexSyncTimeBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.protobuf.Timestamp, com.google.protobuf.Timestamp.Builder, com.google.protobuf.TimestampOrBuilder>( getIndexSyncTime(), getParentForChildren(), isClean()); indexSyncTime_ = null; } return indexSyncTimeBuilder_; } private com.google.cloud.aiplatform.v1.AutomaticResources automaticResources_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.aiplatform.v1.AutomaticResources, com.google.cloud.aiplatform.v1.AutomaticResources.Builder, com.google.cloud.aiplatform.v1.AutomaticResourcesOrBuilder> automaticResourcesBuilder_; /** * * * <pre> * Optional. A description of resources that the DeployedIndex uses, which to large * degree are decided by Vertex AI, and optionally allows only a modest * additional configuration. * If min_replica_count is not set, the default value is 2 (we don't provide * SLA when min_replica_count=1). If max_replica_count is not set, the * default value is min_replica_count. The max allowed replica count is * 1000. * </pre> * * <code> * .google.cloud.aiplatform.v1.AutomaticResources automatic_resources = 7 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return Whether the automaticResources field is set. */ public boolean hasAutomaticResources() { return automaticResourcesBuilder_ != null || automaticResources_ != null; } /** * * * <pre> * Optional. A description of resources that the DeployedIndex uses, which to large * degree are decided by Vertex AI, and optionally allows only a modest * additional configuration. * If min_replica_count is not set, the default value is 2 (we don't provide * SLA when min_replica_count=1). If max_replica_count is not set, the * default value is min_replica_count. The max allowed replica count is * 1000. * </pre> * * <code> * .google.cloud.aiplatform.v1.AutomaticResources automatic_resources = 7 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return The automaticResources. */ public com.google.cloud.aiplatform.v1.AutomaticResources getAutomaticResources() { if (automaticResourcesBuilder_ == null) { return automaticResources_ == null ? com.google.cloud.aiplatform.v1.AutomaticResources.getDefaultInstance() : automaticResources_; } else { return automaticResourcesBuilder_.getMessage(); } } /** * * * <pre> * Optional. A description of resources that the DeployedIndex uses, which to large * degree are decided by Vertex AI, and optionally allows only a modest * additional configuration. * If min_replica_count is not set, the default value is 2 (we don't provide * SLA when min_replica_count=1). If max_replica_count is not set, the * default value is min_replica_count. The max allowed replica count is * 1000. * </pre> * * <code> * .google.cloud.aiplatform.v1.AutomaticResources automatic_resources = 7 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public Builder setAutomaticResources(com.google.cloud.aiplatform.v1.AutomaticResources value) { if (automaticResourcesBuilder_ == null) { if (value == null) { throw new NullPointerException(); } automaticResources_ = value; onChanged(); } else { automaticResourcesBuilder_.setMessage(value); } return this; } /** * * * <pre> * Optional. A description of resources that the DeployedIndex uses, which to large * degree are decided by Vertex AI, and optionally allows only a modest * additional configuration. * If min_replica_count is not set, the default value is 2 (we don't provide * SLA when min_replica_count=1). If max_replica_count is not set, the * default value is min_replica_count. The max allowed replica count is * 1000. * </pre> * * <code> * .google.cloud.aiplatform.v1.AutomaticResources automatic_resources = 7 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public Builder setAutomaticResources( com.google.cloud.aiplatform.v1.AutomaticResources.Builder builderForValue) { if (automaticResourcesBuilder_ == null) { automaticResources_ = builderForValue.build(); onChanged(); } else { automaticResourcesBuilder_.setMessage(builderForValue.build()); } return this; } /** * * * <pre> * Optional. A description of resources that the DeployedIndex uses, which to large * degree are decided by Vertex AI, and optionally allows only a modest * additional configuration. * If min_replica_count is not set, the default value is 2 (we don't provide * SLA when min_replica_count=1). If max_replica_count is not set, the * default value is min_replica_count. The max allowed replica count is * 1000. * </pre> * * <code> * .google.cloud.aiplatform.v1.AutomaticResources automatic_resources = 7 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public Builder mergeAutomaticResources( com.google.cloud.aiplatform.v1.AutomaticResources value) { if (automaticResourcesBuilder_ == null) { if (automaticResources_ != null) { automaticResources_ = com.google.cloud.aiplatform.v1.AutomaticResources.newBuilder(automaticResources_) .mergeFrom(value) .buildPartial(); } else { automaticResources_ = value; } onChanged(); } else { automaticResourcesBuilder_.mergeFrom(value); } return this; } /** * * * <pre> * Optional. A description of resources that the DeployedIndex uses, which to large * degree are decided by Vertex AI, and optionally allows only a modest * additional configuration. * If min_replica_count is not set, the default value is 2 (we don't provide * SLA when min_replica_count=1). If max_replica_count is not set, the * default value is min_replica_count. The max allowed replica count is * 1000. * </pre> * * <code> * .google.cloud.aiplatform.v1.AutomaticResources automatic_resources = 7 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public Builder clearAutomaticResources() { if (automaticResourcesBuilder_ == null) { automaticResources_ = null; onChanged(); } else { automaticResources_ = null; automaticResourcesBuilder_ = null; } return this; } /** * * * <pre> * Optional. A description of resources that the DeployedIndex uses, which to large * degree are decided by Vertex AI, and optionally allows only a modest * additional configuration. * If min_replica_count is not set, the default value is 2 (we don't provide * SLA when min_replica_count=1). If max_replica_count is not set, the * default value is min_replica_count. The max allowed replica count is * 1000. * </pre> * * <code> * .google.cloud.aiplatform.v1.AutomaticResources automatic_resources = 7 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public com.google.cloud.aiplatform.v1.AutomaticResources.Builder getAutomaticResourcesBuilder() { onChanged(); return getAutomaticResourcesFieldBuilder().getBuilder(); } /** * * * <pre> * Optional. A description of resources that the DeployedIndex uses, which to large * degree are decided by Vertex AI, and optionally allows only a modest * additional configuration. * If min_replica_count is not set, the default value is 2 (we don't provide * SLA when min_replica_count=1). If max_replica_count is not set, the * default value is min_replica_count. The max allowed replica count is * 1000. * </pre> * * <code> * .google.cloud.aiplatform.v1.AutomaticResources automatic_resources = 7 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public com.google.cloud.aiplatform.v1.AutomaticResourcesOrBuilder getAutomaticResourcesOrBuilder() { if (automaticResourcesBuilder_ != null) { return automaticResourcesBuilder_.getMessageOrBuilder(); } else { return automaticResources_ == null ? com.google.cloud.aiplatform.v1.AutomaticResources.getDefaultInstance() : automaticResources_; } } /** * * * <pre> * Optional. A description of resources that the DeployedIndex uses, which to large * degree are decided by Vertex AI, and optionally allows only a modest * additional configuration. * If min_replica_count is not set, the default value is 2 (we don't provide * SLA when min_replica_count=1). If max_replica_count is not set, the * default value is min_replica_count. The max allowed replica count is * 1000. * </pre> * * <code> * .google.cloud.aiplatform.v1.AutomaticResources automatic_resources = 7 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.aiplatform.v1.AutomaticResources, com.google.cloud.aiplatform.v1.AutomaticResources.Builder, com.google.cloud.aiplatform.v1.AutomaticResourcesOrBuilder> getAutomaticResourcesFieldBuilder() { if (automaticResourcesBuilder_ == null) { automaticResourcesBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.aiplatform.v1.AutomaticResources, com.google.cloud.aiplatform.v1.AutomaticResources.Builder, com.google.cloud.aiplatform.v1.AutomaticResourcesOrBuilder>( getAutomaticResources(), getParentForChildren(), isClean()); automaticResources_ = null; } return automaticResourcesBuilder_; } private boolean enableAccessLogging_; /** * * * <pre> * Optional. If true, private endpoint's access logs are sent to StackDriver Logging. * These logs are like standard server access logs, containing * information like timestamp and latency for each MatchRequest. * Note that Stackdriver logs may incur a cost, especially if the deployed * index receives a high queries per second rate (QPS). * Estimate your costs before enabling this option. * </pre> * * <code>bool enable_access_logging = 8 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The enableAccessLogging. */ @java.lang.Override public boolean getEnableAccessLogging() { return enableAccessLogging_; } /** * * * <pre> * Optional. If true, private endpoint's access logs are sent to StackDriver Logging. * These logs are like standard server access logs, containing * information like timestamp and latency for each MatchRequest. * Note that Stackdriver logs may incur a cost, especially if the deployed * index receives a high queries per second rate (QPS). * Estimate your costs before enabling this option. * </pre> * * <code>bool enable_access_logging = 8 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The enableAccessLogging to set. * @return This builder for chaining. */ public Builder setEnableAccessLogging(boolean value) { enableAccessLogging_ = value; onChanged(); return this; } /** * * * <pre> * Optional. If true, private endpoint's access logs are sent to StackDriver Logging. * These logs are like standard server access logs, containing * information like timestamp and latency for each MatchRequest. * Note that Stackdriver logs may incur a cost, especially if the deployed * index receives a high queries per second rate (QPS). * Estimate your costs before enabling this option. * </pre> * * <code>bool enable_access_logging = 8 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearEnableAccessLogging() { enableAccessLogging_ = false; onChanged(); return this; } private com.google.cloud.aiplatform.v1.DeployedIndexAuthConfig deployedIndexAuthConfig_; private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.aiplatform.v1.DeployedIndexAuthConfig, com.google.cloud.aiplatform.v1.DeployedIndexAuthConfig.Builder, com.google.cloud.aiplatform.v1.DeployedIndexAuthConfigOrBuilder> deployedIndexAuthConfigBuilder_; /** * * * <pre> * Optional. If set, the authentication is enabled for the private endpoint. * </pre> * * <code> * .google.cloud.aiplatform.v1.DeployedIndexAuthConfig deployed_index_auth_config = 9 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return Whether the deployedIndexAuthConfig field is set. */ public boolean hasDeployedIndexAuthConfig() { return deployedIndexAuthConfigBuilder_ != null || deployedIndexAuthConfig_ != null; } /** * * * <pre> * Optional. If set, the authentication is enabled for the private endpoint. * </pre> * * <code> * .google.cloud.aiplatform.v1.DeployedIndexAuthConfig deployed_index_auth_config = 9 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return The deployedIndexAuthConfig. */ public com.google.cloud.aiplatform.v1.DeployedIndexAuthConfig getDeployedIndexAuthConfig() { if (deployedIndexAuthConfigBuilder_ == null) { return deployedIndexAuthConfig_ == null ? com.google.cloud.aiplatform.v1.DeployedIndexAuthConfig.getDefaultInstance() : deployedIndexAuthConfig_; } else { return deployedIndexAuthConfigBuilder_.getMessage(); } } /** * * * <pre> * Optional. If set, the authentication is enabled for the private endpoint. * </pre> * * <code> * .google.cloud.aiplatform.v1.DeployedIndexAuthConfig deployed_index_auth_config = 9 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public Builder setDeployedIndexAuthConfig( com.google.cloud.aiplatform.v1.DeployedIndexAuthConfig value) { if (deployedIndexAuthConfigBuilder_ == null) { if (value == null) { throw new NullPointerException(); } deployedIndexAuthConfig_ = value; onChanged(); } else { deployedIndexAuthConfigBuilder_.setMessage(value); } return this; } /** * * * <pre> * Optional. If set, the authentication is enabled for the private endpoint. * </pre> * * <code> * .google.cloud.aiplatform.v1.DeployedIndexAuthConfig deployed_index_auth_config = 9 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public Builder setDeployedIndexAuthConfig( com.google.cloud.aiplatform.v1.DeployedIndexAuthConfig.Builder builderForValue) { if (deployedIndexAuthConfigBuilder_ == null) { deployedIndexAuthConfig_ = builderForValue.build(); onChanged(); } else { deployedIndexAuthConfigBuilder_.setMessage(builderForValue.build()); } return this; } /** * * * <pre> * Optional. If set, the authentication is enabled for the private endpoint. * </pre> * * <code> * .google.cloud.aiplatform.v1.DeployedIndexAuthConfig deployed_index_auth_config = 9 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public Builder mergeDeployedIndexAuthConfig( com.google.cloud.aiplatform.v1.DeployedIndexAuthConfig value) { if (deployedIndexAuthConfigBuilder_ == null) { if (deployedIndexAuthConfig_ != null) { deployedIndexAuthConfig_ = com.google.cloud.aiplatform.v1.DeployedIndexAuthConfig.newBuilder( deployedIndexAuthConfig_) .mergeFrom(value) .buildPartial(); } else { deployedIndexAuthConfig_ = value; } onChanged(); } else { deployedIndexAuthConfigBuilder_.mergeFrom(value); } return this; } /** * * * <pre> * Optional. If set, the authentication is enabled for the private endpoint. * </pre> * * <code> * .google.cloud.aiplatform.v1.DeployedIndexAuthConfig deployed_index_auth_config = 9 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public Builder clearDeployedIndexAuthConfig() { if (deployedIndexAuthConfigBuilder_ == null) { deployedIndexAuthConfig_ = null; onChanged(); } else { deployedIndexAuthConfig_ = null; deployedIndexAuthConfigBuilder_ = null; } return this; } /** * * * <pre> * Optional. If set, the authentication is enabled for the private endpoint. * </pre> * * <code> * .google.cloud.aiplatform.v1.DeployedIndexAuthConfig deployed_index_auth_config = 9 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public com.google.cloud.aiplatform.v1.DeployedIndexAuthConfig.Builder getDeployedIndexAuthConfigBuilder() { onChanged(); return getDeployedIndexAuthConfigFieldBuilder().getBuilder(); } /** * * * <pre> * Optional. If set, the authentication is enabled for the private endpoint. * </pre> * * <code> * .google.cloud.aiplatform.v1.DeployedIndexAuthConfig deployed_index_auth_config = 9 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ public com.google.cloud.aiplatform.v1.DeployedIndexAuthConfigOrBuilder getDeployedIndexAuthConfigOrBuilder() { if (deployedIndexAuthConfigBuilder_ != null) { return deployedIndexAuthConfigBuilder_.getMessageOrBuilder(); } else { return deployedIndexAuthConfig_ == null ? com.google.cloud.aiplatform.v1.DeployedIndexAuthConfig.getDefaultInstance() : deployedIndexAuthConfig_; } } /** * * * <pre> * Optional. If set, the authentication is enabled for the private endpoint. * </pre> * * <code> * .google.cloud.aiplatform.v1.DeployedIndexAuthConfig deployed_index_auth_config = 9 [(.google.api.field_behavior) = OPTIONAL]; * </code> */ private com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.aiplatform.v1.DeployedIndexAuthConfig, com.google.cloud.aiplatform.v1.DeployedIndexAuthConfig.Builder, com.google.cloud.aiplatform.v1.DeployedIndexAuthConfigOrBuilder> getDeployedIndexAuthConfigFieldBuilder() { if (deployedIndexAuthConfigBuilder_ == null) { deployedIndexAuthConfigBuilder_ = new com.google.protobuf.SingleFieldBuilderV3< com.google.cloud.aiplatform.v1.DeployedIndexAuthConfig, com.google.cloud.aiplatform.v1.DeployedIndexAuthConfig.Builder, com.google.cloud.aiplatform.v1.DeployedIndexAuthConfigOrBuilder>( getDeployedIndexAuthConfig(), getParentForChildren(), isClean()); deployedIndexAuthConfig_ = null; } return deployedIndexAuthConfigBuilder_; } private com.google.protobuf.LazyStringList reservedIpRanges_ = com.google.protobuf.LazyStringArrayList.EMPTY; private void ensureReservedIpRangesIsMutable() { if (!((bitField0_ & 0x00000001) != 0)) { reservedIpRanges_ = new com.google.protobuf.LazyStringArrayList(reservedIpRanges_); bitField0_ |= 0x00000001; } } /** * * * <pre> * Optional. A list of reserved ip ranges under the VPC network that can be * used for this DeployedIndex. * If set, we will deploy the index within the provided ip ranges. Otherwise, * the index might be deployed to any ip ranges under the provided VPC * network. * The value sohuld be the name of the address * (https://cloud.google.com/compute/docs/reference/rest/v1/addresses) * Example: 'vertex-ai-ip-range'. * </pre> * * <code>repeated string reserved_ip_ranges = 10 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return A list containing the reservedIpRanges. */ public com.google.protobuf.ProtocolStringList getReservedIpRangesList() { return reservedIpRanges_.getUnmodifiableView(); } /** * * * <pre> * Optional. A list of reserved ip ranges under the VPC network that can be * used for this DeployedIndex. * If set, we will deploy the index within the provided ip ranges. Otherwise, * the index might be deployed to any ip ranges under the provided VPC * network. * The value sohuld be the name of the address * (https://cloud.google.com/compute/docs/reference/rest/v1/addresses) * Example: 'vertex-ai-ip-range'. * </pre> * * <code>repeated string reserved_ip_ranges = 10 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return The count of reservedIpRanges. */ public int getReservedIpRangesCount() { return reservedIpRanges_.size(); } /** * * * <pre> * Optional. A list of reserved ip ranges under the VPC network that can be * used for this DeployedIndex. * If set, we will deploy the index within the provided ip ranges. Otherwise, * the index might be deployed to any ip ranges under the provided VPC * network. * The value sohuld be the name of the address * (https://cloud.google.com/compute/docs/reference/rest/v1/addresses) * Example: 'vertex-ai-ip-range'. * </pre> * * <code>repeated string reserved_ip_ranges = 10 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @param index The index of the element to return. * @return The reservedIpRanges at the given index. */ public java.lang.String getReservedIpRanges(int index) { return reservedIpRanges_.get(index); } /** * * * <pre> * Optional. A list of reserved ip ranges under the VPC network that can be * used for this DeployedIndex. * If set, we will deploy the index within the provided ip ranges. Otherwise, * the index might be deployed to any ip ranges under the provided VPC * network. * The value sohuld be the name of the address * (https://cloud.google.com/compute/docs/reference/rest/v1/addresses) * Example: 'vertex-ai-ip-range'. * </pre> * * <code>repeated string reserved_ip_ranges = 10 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @param index The index of the value to return. * @return The bytes of the reservedIpRanges at the given index. */ public com.google.protobuf.ByteString getReservedIpRangesBytes(int index) { return reservedIpRanges_.getByteString(index); } /** * * * <pre> * Optional. A list of reserved ip ranges under the VPC network that can be * used for this DeployedIndex. * If set, we will deploy the index within the provided ip ranges. Otherwise, * the index might be deployed to any ip ranges under the provided VPC * network. * The value sohuld be the name of the address * (https://cloud.google.com/compute/docs/reference/rest/v1/addresses) * Example: 'vertex-ai-ip-range'. * </pre> * * <code>repeated string reserved_ip_ranges = 10 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @param index The index to set the value at. * @param value The reservedIpRanges to set. * @return This builder for chaining. */ public Builder setReservedIpRanges(int index, java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureReservedIpRangesIsMutable(); reservedIpRanges_.set(index, value); onChanged(); return this; } /** * * * <pre> * Optional. A list of reserved ip ranges under the VPC network that can be * used for this DeployedIndex. * If set, we will deploy the index within the provided ip ranges. Otherwise, * the index might be deployed to any ip ranges under the provided VPC * network. * The value sohuld be the name of the address * (https://cloud.google.com/compute/docs/reference/rest/v1/addresses) * Example: 'vertex-ai-ip-range'. * </pre> * * <code>repeated string reserved_ip_ranges = 10 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @param value The reservedIpRanges to add. * @return This builder for chaining. */ public Builder addReservedIpRanges(java.lang.String value) { if (value == null) { throw new NullPointerException(); } ensureReservedIpRangesIsMutable(); reservedIpRanges_.add(value); onChanged(); return this; } /** * * * <pre> * Optional. A list of reserved ip ranges under the VPC network that can be * used for this DeployedIndex. * If set, we will deploy the index within the provided ip ranges. Otherwise, * the index might be deployed to any ip ranges under the provided VPC * network. * The value sohuld be the name of the address * (https://cloud.google.com/compute/docs/reference/rest/v1/addresses) * Example: 'vertex-ai-ip-range'. * </pre> * * <code>repeated string reserved_ip_ranges = 10 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @param values The reservedIpRanges to add. * @return This builder for chaining. */ public Builder addAllReservedIpRanges(java.lang.Iterable<java.lang.String> values) { ensureReservedIpRangesIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll(values, reservedIpRanges_); onChanged(); return this; } /** * * * <pre> * Optional. A list of reserved ip ranges under the VPC network that can be * used for this DeployedIndex. * If set, we will deploy the index within the provided ip ranges. Otherwise, * the index might be deployed to any ip ranges under the provided VPC * network. * The value sohuld be the name of the address * (https://cloud.google.com/compute/docs/reference/rest/v1/addresses) * Example: 'vertex-ai-ip-range'. * </pre> * * <code>repeated string reserved_ip_ranges = 10 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @return This builder for chaining. */ public Builder clearReservedIpRanges() { reservedIpRanges_ = com.google.protobuf.LazyStringArrayList.EMPTY; bitField0_ = (bitField0_ & ~0x00000001); onChanged(); return this; } /** * * * <pre> * Optional. A list of reserved ip ranges under the VPC network that can be * used for this DeployedIndex. * If set, we will deploy the index within the provided ip ranges. Otherwise, * the index might be deployed to any ip ranges under the provided VPC * network. * The value sohuld be the name of the address * (https://cloud.google.com/compute/docs/reference/rest/v1/addresses) * Example: 'vertex-ai-ip-range'. * </pre> * * <code>repeated string reserved_ip_ranges = 10 [(.google.api.field_behavior) = OPTIONAL]; * </code> * * @param value The bytes of the reservedIpRanges to add. * @return This builder for chaining. */ public Builder addReservedIpRangesBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); ensureReservedIpRangesIsMutable(); reservedIpRanges_.add(value); onChanged(); return this; } private java.lang.Object deploymentGroup_ = ""; /** * * * <pre> * Optional. The deployment group can be no longer than 64 characters (eg: * 'test', 'prod'). If not set, we will use the 'default' deployment group. * Creating `deployment_groups` with `reserved_ip_ranges` is a recommended * practice when the peered network has multiple peering ranges. This creates * your deployments from predictable IP spaces for easier traffic * administration. Also, one deployment_group (except 'default') can only be * used with the same reserved_ip_ranges which means if the deployment_group * has been used with reserved_ip_ranges: [a, b, c], using it with [a, b] or * [d, e] is disallowed. * Note: we only support up to 5 deployment groups(not including 'default'). * </pre> * * <code>string deployment_group = 11 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The deploymentGroup. */ public java.lang.String getDeploymentGroup() { java.lang.Object ref = deploymentGroup_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); deploymentGroup_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * Optional. The deployment group can be no longer than 64 characters (eg: * 'test', 'prod'). If not set, we will use the 'default' deployment group. * Creating `deployment_groups` with `reserved_ip_ranges` is a recommended * practice when the peered network has multiple peering ranges. This creates * your deployments from predictable IP spaces for easier traffic * administration. Also, one deployment_group (except 'default') can only be * used with the same reserved_ip_ranges which means if the deployment_group * has been used with reserved_ip_ranges: [a, b, c], using it with [a, b] or * [d, e] is disallowed. * Note: we only support up to 5 deployment groups(not including 'default'). * </pre> * * <code>string deployment_group = 11 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return The bytes for deploymentGroup. */ public com.google.protobuf.ByteString getDeploymentGroupBytes() { java.lang.Object ref = deploymentGroup_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); deploymentGroup_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * Optional. The deployment group can be no longer than 64 characters (eg: * 'test', 'prod'). If not set, we will use the 'default' deployment group. * Creating `deployment_groups` with `reserved_ip_ranges` is a recommended * practice when the peered network has multiple peering ranges. This creates * your deployments from predictable IP spaces for easier traffic * administration. Also, one deployment_group (except 'default') can only be * used with the same reserved_ip_ranges which means if the deployment_group * has been used with reserved_ip_ranges: [a, b, c], using it with [a, b] or * [d, e] is disallowed. * Note: we only support up to 5 deployment groups(not including 'default'). * </pre> * * <code>string deployment_group = 11 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The deploymentGroup to set. * @return This builder for chaining. */ public Builder setDeploymentGroup(java.lang.String value) { if (value == null) { throw new NullPointerException(); } deploymentGroup_ = value; onChanged(); return this; } /** * * * <pre> * Optional. The deployment group can be no longer than 64 characters (eg: * 'test', 'prod'). If not set, we will use the 'default' deployment group. * Creating `deployment_groups` with `reserved_ip_ranges` is a recommended * practice when the peered network has multiple peering ranges. This creates * your deployments from predictable IP spaces for easier traffic * administration. Also, one deployment_group (except 'default') can only be * used with the same reserved_ip_ranges which means if the deployment_group * has been used with reserved_ip_ranges: [a, b, c], using it with [a, b] or * [d, e] is disallowed. * Note: we only support up to 5 deployment groups(not including 'default'). * </pre> * * <code>string deployment_group = 11 [(.google.api.field_behavior) = OPTIONAL];</code> * * @return This builder for chaining. */ public Builder clearDeploymentGroup() { deploymentGroup_ = getDefaultInstance().getDeploymentGroup(); onChanged(); return this; } /** * * * <pre> * Optional. The deployment group can be no longer than 64 characters (eg: * 'test', 'prod'). If not set, we will use the 'default' deployment group. * Creating `deployment_groups` with `reserved_ip_ranges` is a recommended * practice when the peered network has multiple peering ranges. This creates * your deployments from predictable IP spaces for easier traffic * administration. Also, one deployment_group (except 'default') can only be * used with the same reserved_ip_ranges which means if the deployment_group * has been used with reserved_ip_ranges: [a, b, c], using it with [a, b] or * [d, e] is disallowed. * Note: we only support up to 5 deployment groups(not including 'default'). * </pre> * * <code>string deployment_group = 11 [(.google.api.field_behavior) = OPTIONAL];</code> * * @param value The bytes for deploymentGroup to set. * @return This builder for chaining. */ public Builder setDeploymentGroupBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); deploymentGroup_ = value; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.aiplatform.v1.DeployedIndex) } // @@protoc_insertion_point(class_scope:google.cloud.aiplatform.v1.DeployedIndex) private static final com.google.cloud.aiplatform.v1.DeployedIndex DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.aiplatform.v1.DeployedIndex(); } public static com.google.cloud.aiplatform.v1.DeployedIndex getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<DeployedIndex> PARSER = new com.google.protobuf.AbstractParser<DeployedIndex>() { @java.lang.Override public DeployedIndex parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new DeployedIndex(input, extensionRegistry); } }; public static com.google.protobuf.Parser<DeployedIndex> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<DeployedIndex> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.aiplatform.v1.DeployedIndex getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
35.873553
132
0.655673
9ababd3f4d700939b2fd4a5607d19de4fc9697c3
3,992
package com.example.noweb.thirdParty; import org.assertj.core.util.Lists; import org.junit.jupiter.api.Test; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; /** * <p>Hamcrest第三方测试包</p> * * 使用第三方测试包,好处就是测试方法更多一些,逻辑更清晰 * springboot test类库同时提供AssertJ 和 Hamcrest的支持,实际上AssertJ依赖于Hamcrest * * Created by hanqf on 2020/8/28 16:30. * <p> * is : 是否匹配单一规则,方法参数是规则时可以不加is * anyOf : 是否匹配任意规则 * allOf : 是否匹配全部规则 * * 参考:https://www.jianshu.com/p/e7d4c3bdac6e */ public class HamcrestAssertionTests { @Test void assertWithHamcrestMatcher() { //下面三种方法是等价的,可以用于简单类型的比较 assertThat(2 + 1, is(equalTo(3))); assertThat(2 + 1, equalTo(3)); //不加is,直接使用规则 assertThat(2 + 1, is(3)); //参数不是规则,需要使用is //不匹配 assertThat(2 + 1, not(4)); String str = "firstName"; assertThat("测试失败,没有以特定字符串开头", str, is(startsWith("first"))); assertThat("测试失败,没有以特定字符串结尾", str, is(endsWith("me"))); assertThat(str, is(containsString("Na"))); //类似OR的效果,匹配任意验证都测试通过 assertThat(str, anyOf(startsWith("first"), containsString("Na"), endsWith("me"))); //类似AND的效果,匹配全部验证则测试通过 assertThat(str, allOf(startsWith("first"), containsString("Na"), endsWith("me"))); //判断两个对象是否为同一个实体 assertThat(str, sameInstance(str)); String str1 = "text"; String str2 = " text "; //去除两边空格后比较是否相当,中间的空格不能去掉的 assertThat(str1, is(equalToCompressingWhiteSpace(str2))); assertThat("test", equalToIgnoringCase("Test")); //忽略大小写 String strEmpty = ""; assertThat(strEmpty, emptyString()); // 空字符串 assertThat(strEmpty, emptyOrNullString()); // 空字符串或者null assertThat(1, greaterThan(0)); // 大于 assertThat(5, greaterThanOrEqualTo(5)); //大于等于 assertThat(-1, lessThan(0)); // 小于 assertThat(-1, lessThanOrEqualTo(5)); // 小于等于 //集合 List<String> collection = Lists.newArrayList("ab", "cd", "ef"); assertThat(collection, hasSize(3)); assertThat(collection, hasItem("cd")); assertThat(collection, not(hasItem("zz"))); assertThat(collection, hasItems("cd", "ab")); // 检查多个元素是否在集合中,不区分顺序 assertThat(collection, containsInAnyOrder("cd", "ab", "ef")); // 检查多个元素是否在集合中,不区分顺序 List<String> collectionEmpty = Lists.newArrayList(); assertThat(collectionEmpty, empty()); // 用于检查集合是否为空,注意这里集合对象不能是null String[] array = new String[]{}; assertThat(array, emptyArray()); // 用于检查数组是否为空,注意这里数组对象不能是null Map<String, String> maps = new HashMap<>(); assertThat(maps, equalTo(Collections.EMPTY_MAP)); Iterable<String> iterable = Lists.newArrayList(); assertThat(iterable, emptyIterable()); Iterable<String> list = Lists.newArrayList("ab", "cd", "ef"); assertThat(list, iterableWithSize(3)); //检查每一项是否为空,这里对集合中的每一个元素执行验证方法 assertThat(list, everyItem(notNullValue())); City city = new City("shenzhen", "CA"); assertThat(city, hasProperty("state")); assertThat(city, hasProperty("state", equalTo("CA"))); // 判断是否存在某个属性,并且是否存在某个特性值 City city1 = new City("San Francisco", "CA"); City city2 = new City("San Francisco", "CA"); assertThat(city1, samePropertyValuesAs(city2)); } public class City { String name; String state; public City(String name, String state) { this.name = name; this.state = state; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getState() { return state; } public void setState(String state) { this.state = state; } } }
28.719424
91
0.615481
9c6ba5c4c745e943bf72c111db81a038e41d2895
430
package org.gosky.paradise.refreshlayout; import android.view.View; /** * @author galaxy captain * @date 2015/12/28 */ public abstract class RefreshView { public abstract View createView(); /** * 普通状态 */ public abstract void onNomarlState(int offset); /** * 可执行状态 */ public abstract void onExecState(int offset); /** * 加载中 */ public abstract void onDoState(); }
14.827586
51
0.611628
39151b6fea71d655fe51668065c17156c87ed440
496
package com.hbb.legou.item.controller; import com.hbb.legou.core.controller.BaseController; import com.hbb.legou.item.entity.Sku; import com.hbb.legou.item.service.ISkuService; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/item/sku") @CrossOrigin public class SkuController extends BaseController<ISkuService, Sku> { }
31
69
0.832661
09a1bb54bff08e0b0374e12931ff55046e8defe1
1,172
package com.ffan.smartlife.msite.receiver; import org.apache.kafka.clients.consumer.ConsumerRecord; import org.apache.kafka.clients.consumer.ConsumerRecords; import org.apache.kafka.clients.consumer.KafkaConsumer; import java.util.Arrays; import java.util.Properties; public class Main { public static void main(String[] args) { Properties properties = new Properties(); properties.put("bootstrap.servers", "localhost:9092"); properties.put("group.id", "mSite"); properties.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); properties.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer"); KafkaConsumer<String, String> consumer = new KafkaConsumer<String, String>(properties); consumer.subscribe(Arrays.asList("diving1")); boolean running = true; while (running) { ConsumerRecords<String, String> records = consumer.poll(100); for (ConsumerRecord<String, String> record : records) { System.out.println(record.value()); } } consumer.close(); } }
31.675676
105
0.682594
5a21d30d05451bb262a13f3298d512a722c5c27b
1,307
// @formatter:off /* * Unlicensed, generated by javafx.ftl */ package javafx.scene.text; /** * {@link Font}建構器。 * * @author JarReflectionDataLoader-1.0.0 * @version jfxrt.jar * @param <Z> 要建構的物件型態(需繼承{@link Font}) * @param <B> 建構器本身的型態(需繼承{@link FontMaker}) */ @javax.annotation.Generated("Generated by javafx.ftl") @SuppressWarnings("all") public class FontMaker<Z extends Font, B extends FontMaker<Z, B>> extends jxtn.jfx.makers.AbstractMaker<Z, B> implements FontMakerExt<Z, B> { @Override public void applyTo(Z instance) { super.applyTo(instance); } /** * 建構{@link Font}物件。 * * @return 新的{@link Font}物件實體 */ @SuppressWarnings("unchecked") public Font build(double arg0) { Font instance = new Font(arg0); this.applyTo((Z) instance); this.doAfterBuild((Z) instance); return instance; } /** * 建構{@link Font}物件。 * * @return 新的{@link Font}物件實體 */ @SuppressWarnings("unchecked") public Font build(java.lang.String arg0, double arg1) { Font instance = new Font(arg0, arg1); this.applyTo((Z) instance); this.doAfterBuild((Z) instance); return instance; } }
22.929825
66
0.576894
ddf07c25da4604bd0de902d0ac8f9e824bface40
21,181
package com.github.siboxd.fatturapa.model.invoicebody.payment; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import org.simpleframework.xml.Element; import org.simpleframework.xml.Order; import org.simpleframework.xml.Root; /** * Contains the details to make the payment */ @Root(name = "DettaglioPagamento") @Order(elements = {"Beneficiario", "ModalitaPagamento", "DataRiferimentoTerminiPagamento", "GiorniTerminiPagamento", "DataScadenzaPagamento", "ImportoPagamento", "CodUfficioPostale", "CognomeQuietanzante", "NomeQuietanzante", "CFQuietanzante", "TitoloQuietanzante", "IstitutoFinanziario", "IBAN", "ABI", "CAB", "BIC", "ScontoPagamentoAnticipato", "DataLimitePagamentoAnticipato", "PenalitaPagamentiRitardati", "DataDecorrenzaPenale", "CodicePagamento"}) public final class DettaglioPagamento { @Element(name = "Beneficiario", required = false) private String beneficiario; @Element(name = "ModalitaPagamento") private ModalitaPagamento modalitaPagamento; @Element(name = "DataRiferimentoTerminiPagamento", required = false) private String dataRiferimentoTerminiPagamento; @Element(name = "GiorniTerminiPagamento", required = false) private String giorniTerminiPagamento; @Element(name = "DataScadenzaPagamento", required = false) private String dataScadenzaPagamento; @Element(name = "ImportoPagamento") private String importoPagamento; @Element(name = "CodUfficioPostale", required = false) private String codUfficioPostale; @Element(name = "CognomeQuietanzante", required = false) private String cognomeQuietanzante; @Element(name = "NomeQuietanzante", required = false) private String nomeQuietanzante; @Element(name = "CFQuietanzante", required = false) private String cfQuietanzante; @Element(name = "TitoloQuietanzante", required = false) private String titoloQuietanzante; @Element(name = "IstitutoFinanziario", required = false) private String istitutoFinanziario; @Element(name = "IBAN", required = false) private String iban; @Element(name = "ABI", required = false) private String abi; @Element(name = "CAB", required = false) private String cab; @Element(name = "BIC", required = false) private String bic; @Element(name = "ScontoPagamentoAnticipato", required = false) private String scontoPagamentoAnticipato; @Element(name = "DataLimitePagamentoAnticipato", required = false) private String dataLimitePagamentoAnticipato; @Element(name = "PenalitaPagamentiRitardati", required = false) private String penalitaPagamentiRitardati; @Element(name = "DataDecorrenzaPenale", required = false) private String dataDecorrenzaPenale; @Element(name = "CodicePagamento", required = false) private String codicePagamento; /** * NOTE: Left for reflective usage by SimpleXML framework!! */ @SuppressWarnings("unused") private DettaglioPagamento() { } private DettaglioPagamento(@NonNull final Builder builder) { beneficiario = builder.beneficiario; modalitaPagamento = builder.modalitaPagamento; dataRiferimentoTerminiPagamento = builder.dataRiferimentoTerminiPagamento; giorniTerminiPagamento = builder.giorniTerminiPagamento; dataScadenzaPagamento = builder.dataScadenzaPagamento; importoPagamento = builder.importoPagamento; codUfficioPostale = builder.codUfficioPostale; cognomeQuietanzante = builder.cognomeQuietanzante; nomeQuietanzante = builder.nomeQuietanzante; cfQuietanzante = builder.cfQuietanzante; titoloQuietanzante = builder.titoloQuietanzante; istitutoFinanziario = builder.istitutoFinanziario; iban = builder.iban; abi = builder.abi; cab = builder.cab; bic = builder.bic; scontoPagamentoAnticipato = builder.scontoPagamentoAnticipato; dataLimitePagamentoAnticipato = builder.dataLimitePagamentoAnticipato; penalitaPagamentiRitardati = builder.penalitaPagamentiRitardati; dataDecorrenzaPenale = builder.dataDecorrenzaPenale; codicePagamento = builder.codicePagamento; } @Nullable public String getBeneficiario() { return beneficiario; } @NonNull public ModalitaPagamento getModalitaPagamento() { return modalitaPagamento; } @Nullable public String getDataRiferimentoTerminiPagamento() { return dataRiferimentoTerminiPagamento; } @Nullable public String getGiorniTerminiPagamento() { return giorniTerminiPagamento; } @Nullable public String getDataScadenzaPagamento() { return dataScadenzaPagamento; } @NonNull public String getImportoPagamento() { return importoPagamento; } @Nullable public String getCodUfficioPostale() { return codUfficioPostale; } @Nullable public String getCognomeQuietanzante() { return cognomeQuietanzante; } @Nullable public String getNomeQuietanzante() { return nomeQuietanzante; } @Nullable public String getCfQuietanzante() { return cfQuietanzante; } @Nullable public String getTitoloQuietanzante() { return titoloQuietanzante; } @Nullable public String getIstitutoFinanziario() { return istitutoFinanziario; } @Nullable public String getIban() { return iban; } @Nullable public String getAbi() { return abi; } @Nullable public String getCab() { return cab; } @Nullable public String getBic() { return bic; } @Nullable public String getScontoPagamentoAnticipato() { return scontoPagamentoAnticipato; } @Nullable public String getDataLimitePagamentoAnticipato() { return dataLimitePagamentoAnticipato; } @Nullable public String getPenalitaPagamentiRitardati() { return penalitaPagamentiRitardati; } @Nullable public String getDataDecorrenzaPenale() { return dataDecorrenzaPenale; } @Nullable public String getCodicePagamento() { return codicePagamento; } /** * {@code DettaglioPagamento} builder static inner class. */ public static final class Builder { private String beneficiario; private ModalitaPagamento modalitaPagamento; private String dataRiferimentoTerminiPagamento; private String giorniTerminiPagamento; private String dataScadenzaPagamento; private String importoPagamento; private String codUfficioPostale; private String cognomeQuietanzante; private String nomeQuietanzante; private String cfQuietanzante; private String titoloQuietanzante; private String istitutoFinanziario; private String iban; private String abi; private String cab; private String bic; private String scontoPagamentoAnticipato; private String dataLimitePagamentoAnticipato; private String penalitaPagamentiRitardati; private String dataDecorrenzaPenale; private String codicePagamento; /** * Requires non-optional fields * * @param modalitaPagamento The payment method * @param importoPagamento Used to indicate the amount of the payment.<p> * The field must contain a numeric value consisting of an integer * and two decimal places. The decimals, separated by the whole with * the dot character ("."), Must always be indicated even if zero * (eg: 2585.00). */ public Builder(@NonNull final ModalitaPagamento modalitaPagamento, @NonNull final String importoPagamento) { this.modalitaPagamento = modalitaPagamento; this.importoPagamento = importoPagamento; } public Builder(@NonNull final DettaglioPagamento copy) { this(copy.getModalitaPagamento(), copy.getImportoPagamento()); this.beneficiario = copy.getBeneficiario(); this.dataRiferimentoTerminiPagamento = copy.getDataRiferimentoTerminiPagamento(); this.giorniTerminiPagamento = copy.getGiorniTerminiPagamento(); this.dataScadenzaPagamento = copy.getDataScadenzaPagamento(); this.codUfficioPostale = copy.getCodUfficioPostale(); this.cognomeQuietanzante = copy.getCognomeQuietanzante(); this.nomeQuietanzante = copy.getNomeQuietanzante(); this.cfQuietanzante = copy.getCfQuietanzante(); this.titoloQuietanzante = copy.getTitoloQuietanzante(); this.istitutoFinanziario = copy.getIstitutoFinanziario(); this.iban = copy.getIban(); this.abi = copy.getAbi(); this.cab = copy.getCab(); this.bic = copy.getBic(); this.scontoPagamentoAnticipato = copy.getScontoPagamentoAnticipato(); this.dataLimitePagamentoAnticipato = copy.getDataLimitePagamentoAnticipato(); this.penalitaPagamentiRitardati = copy.getPenalitaPagamentiRitardati(); this.dataDecorrenzaPenale = copy.getDataDecorrenzaPenale(); this.codicePagamento = copy.getCodicePagamento(); } /** * It is used to indicate the personal details of the payee, if different from the seller. * * @param beneficiario no particular criteria is established */ public Builder beneficiario(@Nullable final String beneficiario) { this.beneficiario = beneficiario; return this; } public Builder modalitaPagamento(@NonNull final ModalitaPagamento modalitaPagamento) { this.modalitaPagamento = modalitaPagamento; return this; } /** * It is used to indicate the date from which the payment terms start. * * @param dataRiferimentoTerminiPagamento The field must contain the start date of payment * terms in YYYY-MM-DD format (ISO 8601: 2004 standard). */ public Builder dataRiferimentoTerminiPagamento(@Nullable final String dataRiferimentoTerminiPagamento) { this.dataRiferimentoTerminiPagamento = dataRiferimentoTerminiPagamento; return this; } /** * It is used to indicate the starting date of the payment starting from the date indicated in * the DataRiferimentoTerminiPagamento field * * @param giorniTerminiPagamento The field must contain a numerical value and is 0 in the case * of immediate payments. */ public Builder giorniTerminiPagamento(@Nullable final String giorniTerminiPagamento) { this.giorniTerminiPagamento = giorniTerminiPagamento; return this; } /** * Used to indicate the payment due date. * <br><br> * <b>Note:</b> To be valued only if it is payment in installments * (field CondizioniPagamento = "TP01"). * * @param dataScadenzaPagamento The field must contain the payment due date in YYYY-MM-DD * format (ISO 8601: 2004 standard). */ public Builder dataScadenzaPagamento(@Nullable final String dataScadenzaPagamento) { this.dataScadenzaPagamento = dataScadenzaPagamento; return this; } /** * Used to indicate the amount of the payment. * * @param importoPagamento The field must contain a numeric value consisting of an integer * and two decimal places. The decimals, separated by the whole with * the dot character ("."), Must always be indicated even if zero * (eg: 2585.00). */ public Builder importoPagamento(@NonNull final String importoPagamento) { this.importoPagamento = importoPagamento; return this; } /** * It is used to indicate the code of the post office that is the recipient of the payment if, * as a method of payment, one has been chosen that requires knowledge of it. * <br><br> * <b>Note:</b> To be valued only if the method of payment requires the indication of the * post office * * @param codUfficioPostale no particular criteria is established */ public Builder codUfficioPostale(@Nullable final String codUfficioPostale) { this.codUfficioPostale = codUfficioPostale; return this; } /** * It is used to indicate the surname of the receiving subject that must appear for the withdrawal of * the cash. * <br><br> * <b>Note:</b> To be valued only if the payment method is in cash or by bank transfer. * * @param cognomeQuietanzante The field must contain the surname of the receiving subject. */ public Builder cognomeQuietanzante(@Nullable final String cognomeQuietanzante) { this.cognomeQuietanzante = cognomeQuietanzante; return this; } /** * It is used to indicate the name of the receiving subject that must appear for the withdrawal of * the cash. * <br><br> * <b>Note:</b> To be valued only if the payment method is in cash or by bank transfer. * * @param nomeQuietanzante The field must contain the name of the receiving subject. */ public Builder nomeQuietanzante(@Nullable final String nomeQuietanzante) { this.nomeQuietanzante = nomeQuietanzante; return this; } /** * It is used to indicate the fiscal code of the receiving subject that must appear for the withdrawal of * the cash. * <br><br> * <b>Note:</b> To be valued only if the payment method is in cash or by bank transfer. * * @param cfQuietanzante The field must contain the fiscal code of the receiving subject. */ public Builder cfQuietanzante(@Nullable final String cfQuietanzante) { this.cfQuietanzante = cfQuietanzante; return this; } /** * It constitutes a completion of the personal data concerning the receiving subject. * * @param titoloQuietanzante no particular criteria is established */ public Builder titoloQuietanzante(@Nullable final String titoloQuietanzante) { this.titoloQuietanzante = titoloQuietanzante; return this; } /** * It is used to identify the credit institution that is the recipient of the payment, if one * of the methods of payment has been chosen that presupposes its indication. * * @param istitutoFinanziario The field must contain the name of the financial institution */ public Builder istitutoFinanziario(@Nullable final String istitutoFinanziario) { this.istitutoFinanziario = istitutoFinanziario; return this; } /** * It is used to identify the International Bank Account Number, better known in the abbreviated * form IBAN, an international standard used to uniquely identify a bank user. * <br><br> * <b>Note:</b> To be valued only if the payment method requires an indication * * @param iban The field must contain an IBAN code. */ public Builder iban(@Nullable final String iban) { this.iban = iban; return this; } /** * It is used to indicate the ABI (Italian Banking Association) code, which represents the bank. * <br><br> * <b>Note:</b> To be valued only if, in the presence of a payment method that requires the * indication of the bank, the IBAN code has not been indicated * * @param abi The field must contain a numeric value of 5 digits. */ public Builder abi(@Nullable final String abi) { this.abi = abi; return this; } /** * It is used to indicate the CAB code (Bank Start Code), the number representing the agency/branch * of the credit institution identified by the ABI code. * <br><br> * <b>Note:</b> To be valued only if, in the presence of a payment method that requires the * indication of the bank, the IBAN code has not been indicated. * * @param cab The field must contain a numeric value of 5 digits. */ public Builder cab(@Nullable final String cab) { this.cab = cab; return this; } /** * It is used to indicate the BIC (Bank Identifier Code) or SWIFT, a code that identifies the * bank of the beneficiary and is used in international payments by almost all the banks in * the world * <br><br> * <b>Note:</b> To be valued only if the payment method requires an indication. * * @param bic The field must contain a minimum of 8 and a maximum of 11 alphanumeric characters. */ public Builder bic(@Nullable final String bic) { this.bic = bic; return this; } /** * It is used to indicate the amount of the discount applied in case of prepayment. * * @param scontoPagamentoAnticipato The field must contain a numeric value consisting of an * integer and two decimal places. The decimals, separated by * the whole with the dot character ("."), Must always be * indicated even if zero (eg: 85.00). */ public Builder scontoPagamentoAnticipato(@Nullable final String scontoPagamentoAnticipato) { this.scontoPagamentoAnticipato = scontoPagamentoAnticipato; return this; } /** * Indicates the deadline for making the prepayment. * * @param dataLimitePagamentoAnticipato The field must contain the pre-defined payment deadline * in YYYY-MM-DD format (ISO 8601: 2004 standard). */ public Builder dataLimitePagamentoAnticipato(@Nullable final String dataLimitePagamentoAnticipato) { this.dataLimitePagamentoAnticipato = dataLimitePagamentoAnticipato; return this; } /** * It is used to indicate the amount of the penalty due in case of late payment * * @param penalitaPagamentiRitardati The field must contain a numeric value consisting of an * integer and two decimal places. The decimals, separated * by the whole with the dot character ("."), Must always * be indicated even if zero (eg: 45.00). */ public Builder penalitaPagamentiRitardati(@Nullable final String penalitaPagamentiRitardati) { this.penalitaPagamentiRitardati = penalitaPagamentiRitardati; return this; } /** * It serves to indicate the starting date of the penalty. * * @param dataDecorrenzaPenale The field must contain the pre-defined payment deadline * in YYYY-MM-DD format (ISO 8601: 2004 standard). */ public Builder dataDecorrenzaPenale(@Nullable final String dataDecorrenzaPenale) { this.dataDecorrenzaPenale = dataDecorrenzaPenale; return this; } /** * It is used to facilitate automatic reconciliation of collections by the seller if this * information is then reported, from the transferee / client, to the payment information. * * @param codicePagamento It can be enhanced with an alphanumeric code with a maximum length * of 60 characters. */ public Builder codicePagamento(@Nullable final String codicePagamento) { this.codicePagamento = codicePagamento; return this; } /** * Returns a {@code DettaglioPagamento} built from the parameters previously set. * * @return a {@code DettaglioPagamento} built with parameters of this {@code DettaglioPagamento.Builder} */ public DettaglioPagamento build() { return new DettaglioPagamento(this); } } }
38.510909
113
0.635853
6e119501d2fcaaab8b2cee75ec073e53fb53bad8
1,934
package io.zxnnet.model; import io.zxnnet.view.RepoInfo; import javafx.scene.control.TextInputDialog; import org.eclipse.jgit.api.Git; import java.io.File; import java.util.Optional; public class CloneProject { public static RepoInfo Clone(File file) throws Exception { if (file != null && file.exists()){ TextInputDialog dialog = new TextInputDialog(); dialog.setTitle("Input Repo UrL"); dialog.setHeaderText("Input Your "); dialog.setContentText("Please enter your Repo Location:"); Optional<String> result = dialog.showAndWait(); final String[] URLocation = new String[1]; result.ifPresent(name -> { URLocation[0] = name; System.out.println("UrL: " + name); }); //这里是设置文件名,这样不会导致克隆一堆文件到用户的目录中 String url = URLocation[0]; int index = url.lastIndexOf("/"); int dotindex = url.lastIndexOf("."); char[] ch = url.toCharArray(); String flodername = String.copyValueOf(ch, index + 1, dotindex - index - 1); String dirpath = file.getAbsolutePath() + File.separator + flodername; File dir =new File(dirpath); System.out.println(URLocation[0]); if (dir.exists() && dir.isDirectory()){ return null; } else{ try (Git answer = Git.cloneRepository() .setURI(URLocation[0]) .setDirectory(dir) .call()){ answer.close(); System.out.println("Having repo: " + answer.getRepository().getDirectory()); RepoInfo repoInfo = SetRepoInfo.set(answer.getRepository().getDirectory()); return repoInfo; } } }else { return null; } } }
33.929825
96
0.537229
9a0bc85a48ef46b0f90175d9dbf00e20d2caa90a
2,064
package org.apache.ideaplugin.plugin; import com.intellij.openapi.actionSystem.*; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.project.Project; import javax.swing.*; /* * Copyright 2004,2005 The Apache Software Foundation. * * 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. * * */ /** * Author: Deepal Jayasinghe * Date: Sep 24, 2005 * Time: 10:22:08 AM */ public class Axis2PluginAction extends AnAction { private ImageIcon myIcon; public Axis2PluginAction() { super("GC", "Axis2 plugins", null); } public void actionPerformed(AnActionEvent anActionEvent) { Application application = ApplicationManager.getApplication(); Project project = (Project) anActionEvent.getDataContext().getData(DataConstants.PROJECT); Axis2IdeaPlugin axis2component = (Axis2IdeaPlugin) application.getComponent(Axis2IdeaPlugin.class); axis2component.showTool(project); } public void update(AnActionEvent event) { super.update(event); Presentation presentation = event.getPresentation(); if (ActionPlaces.MAIN_TOOLBAR.equals(event.getPlace())) { if (myIcon == null) { java.net.URL resource = Axis2PluginAction.class.getResource("/icons/icon.png"); myIcon = new ImageIcon(resource); } presentation.setIcon(myIcon); } } }
32.761905
99
0.678295
96ffa50ba47523dbb3b41bdcfd7bff6cc9b70dd0
1,169
package basic.tree; import static org.junit.Assert.assertArrayEquals; import org.junit.Before; import org.junit.Test; import util.BiTreeListAdaptor; import util.NumberUtil; import datastructure.IBiList; public class BiTree2BiListTransformerTest { private BiTreeListAdaptor<Integer> tree; private int[] ascending, descending; //必须是二叉排序树 @Before public void initData(){ tree = new BiTreeListAdaptor<Integer>(6, new BiTreeListAdaptor<Integer>(4, new BiTreeListAdaptor<Integer>(3, null, null), new BiTreeListAdaptor<Integer>(5, null, null)), new BiTreeListAdaptor<Integer>(8, new BiTreeListAdaptor<Integer>(7, null, null), new BiTreeListAdaptor<Integer>(9, null, null))); ascending = new int[]{3, 4, 5, 6, 7, 8, 9}; descending = new int[]{9, 8, 7, 6, 5, 4, 3}; } @Test public void test() { IBiList<Integer> list = new BiTree2BiListTransformer<Integer>().transform(tree); assertArrayEquals(ascending, NumberUtil.fromObjects(list.toList(true).toArray(new Integer[ascending.length]))); assertArrayEquals(descending, NumberUtil.fromObjects(list.toList(false).toArray(new Integer[descending.length]))); } }
30.763158
118
0.730539
6e0430be5a1d8e2e490540fd5c6f0a07264ea37d
1,165
import java.awt.Component; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.awt.print.PageFormat; import java.awt.print.Printable; import java.awt.print.PrinterException; import java.awt.print.PrinterJob; public class Print { static Component gui; public static void PrintImage(Component c) { gui = c; try { PrinterJob pjob = PrinterJob.getPrinterJob(); if (pjob.printDialog() == false) return; pjob.setPrintable(new PrintObject()); pjob.print(); } catch (Exception e) {e.printStackTrace();} } } class PrintObject implements Printable { @Override public int print(Graphics graphics, PageFormat pageFormat, int seiten) throws PrinterException { if (seiten > 0) return NO_SUCH_PAGE; try { BufferedImage img = Save.paintComponent(Print.gui); Graphics2D g2 = (Graphics2D) graphics; g2.drawImage(img, 120, 160,Print.gui.getWidth()-400,Print.gui.getHeight()-470, null); } catch (Exception e) {return NO_SUCH_PAGE;} return PAGE_EXISTS; } }
23.3
97
0.656652
e3011d01fefc19d97311f91c5ed674151524d900
2,254
package com.lgy.biz.order; import com.alibaba.fastjson.JSONObject; import com.lgy.common.core.domain.CommonResponse; import com.lgy.es.EsSearchEngine; import com.lgy.model.EsPage; import org.elasticsearch.index.query.QueryBuilder; import org.springframework.stereotype.Service; import java.util.List; import java.util.Map; /** * @Description 订单搜索 * @Author LGy * @Date 2020/5/8 14:16 **/ @Service public class OrderEsSearchEngine extends EsSearchEngine { private static final String INDEX = "order_main"; private static final String TYPE = "order_main"; /** * 通过ID获取数据 * * @param id 数据ID * @param fields 需要显示的字段,逗号分隔(缺省为全部字段) * @return 执行结果 */ public Map<String, Object> searchDataById(String id, String fields) { return searchDataById(INDEX, TYPE, id, fields); } /** * 数据添加,正定ID * * @param jsonObject 要增加的数据 * @param id 数据ID * @return 执行结果 */ public CommonResponse<String> addData(JSONObject jsonObject, String id) { return addData(jsonObject, INDEX, TYPE, id); } /** * 批量插入 * * @param orders 订单信息 */ public void bulkInsert(List<Map> orders) { bulkInsert(orders, INDEX, TYPE); } /** * 通过ID 更新数据 * * @param jsonObject 要增加的数据 * @param id 数据ID */ public void updateDataById(JSONObject jsonObject, String id) { updateDataById(jsonObject, INDEX, TYPE, id); } /** * 通过ID删除数据 * * @param id 数据ID * @return 执行结果 */ public CommonResponse<String> deleteDataById(String id) { return deleteDataById(INDEX, TYPE, id); } /** * 使用分词查询,并分页 * * @param startPage 当前页 * @param pageSize 每页显示条数 * @param query 查询条件 * @param fields 需要显示的字段,逗号分隔(缺省为全部字段) * @param sortField 排序字段 * @param highlightField 高亮字段 * @return 执行结果 */ public EsPage searchDataPage(int startPage, int pageSize, QueryBuilder query, String fields, String sortField, String highlightField) { return searchDataPage(INDEX, TYPE, startPage, pageSize, query, fields, sortField, highlightField); } }
23.726316
106
0.612245
06c4ba0c282008f5b12eec9258aea49300e166f2
477
/* * @test /nodynamiccopyright/ * @bug 8264843 * @summary Javac crashes with NullPointerException when finding unencoded XML in <pre> tag * @library .. * @modules jdk.javadoc/jdk.javadoc.internal.doclint * @build DocLintTester * @run main DocLintTester -Xmsgs -ref UnknownTagTest.out UnknownTagTest.java */ /** * This is an <unknown> tag. * This is an <unknown a=b> tag with attributes. * This is an <unknown/> self-closing tag. */ public class UnknownTagTest { }
26.5
91
0.716981
55d66a5c58d025f4371f7135e408a1b37b24b530
3,092
package pass.worker; import com.rabbitmq.client.AMQP; import com.rabbitmq.client.Channel; import com.rabbitmq.client.DefaultConsumer; import com.rabbitmq.client.Envelope; import com.rabbitmq.client.ShutdownSignalException; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import pass.core.scheduling.BaseTask; import pass.core.scheduling.StatusUpdater; import pass.core.scheduling.TaskSpecification; import pass.core.scheduling.distributed.Job; public class JobConsumer extends DefaultConsumer { private static final Logger LOGGER = Logger.getLogger(JobConsumer.class.getName()); private final StatusUpdater statusUpdater; private volatile boolean canceled; private volatile boolean processing; public JobConsumer(Channel channel, StatusUpdater statusUpdater) { super(channel); this.statusUpdater = statusUpdater; this.canceled = false; this.processing = false; } private void log(String msg) { LOGGER.log(Level.INFO, "[C{0}] {1}", new Object[] {getChannel().getChannelNumber(), msg}); } public boolean isProcessing() { return processing; } @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { if (!canceled) { processing = true; try { Job job = Job.deserialize(body); if (job == null) { log("Could not deserialize job spec"); return; } TaskSpecification spec = job.getTaskSpec(); log("+New job: " + job.getTaskId().toString() + " " + spec.toString()); BaseTask task = spec.makeCorrespondingTask(job.getTaskId(), statusUpdater); if (task == null) { log("Could not create the corresponding task for " + spec.toString()); return; } task.run(); log("-Job done: " + spec.toString()); } finally { getChannel().basicAck(envelope.getDeliveryTag(), false); processing = false; } } else { log("Cannot handle new delivery, already canceled!"); } } @Override public void handleCancelOk(String consumerTag) { this.canceled = true; log("CancelOk"); } @Override public void handleShutdownSignal(String consumerTag, ShutdownSignalException sig) { log("Shutdown signal received" + ", reason: " + sig.getReason().protocolMethodName() + ", initiated by broker: " + !sig.isInitiatedByApplication()); } }
31.232323
87
0.551746
6d0426593ed181450db662dff48f016b63b59391
5,212
package com.anhel; //https://medium.com/dtechlog/%D0%B0%D0%BB%D0%B3%D0%BE%D1%80%D0%B8%D1%82%D0%BC%D1%8B-%D1%85%D1%8D%D1%88-%D1%84%D1%83%D0%BD%D0%BA%D1%86%D0%B8%D1%8F-sha-256-9862302f942f public class SHA256 { public static byte[] encode(byte[] data) { int h0 = 0x6a09e667; int h1 = 0xbb67ae85; int h2 = 0x3c6ef372; int h3 = 0xa54ff53a; int h4 = 0x510e527f; int h5 = 0x9b05688c; int h6 = 0x1f83d9ab; int h7 = 0x5be0cd19; int[] k = { 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2}; int messageLength = data.length; //length in bytes long messageBitsLength = messageLength * 8; //length in bits byte[] withOne = new byte[messageLength+1]; System.arraycopy(data, 0, withOne, 0, messageLength); withOne[withOne.length - 1] = (byte) 0x80; //append 1 int newLength = withOne.length*8; //get new length in bits while (newLength % 512 != 448) { newLength += 8; } //size of block with appended zeros byte[] withZero = new byte[newLength/8]; System.arraycopy(withOne, 0 , withZero, 0, withOne.length); //add 64 bits for original length byte[] output = new byte[withZero.length + 8]; for (int i = 0; i < 8; i++) { output[output.length -1 - i] = (byte) ((messageBitsLength >>> (8 * i)) & 0xFF); } System.arraycopy(withZero, 0 , output, 0, withZero.length); int size = output.length; int numChunks = size * 8 /512; for (int i = 0; i < numChunks; i++) { int[] w = new int[64]; //divide chunk into 16 32 bit words for (int j = 0; j < 16; j++) { w[j] = ((output[i*512/8 + 4*j] << 24) & 0xFF000000) | ((output[i*512/8 + 4*j+1] << 16) & 0x00FF0000); w[j] |= ((output[i*512/8 + 4*j+2] << 8) & 0xFF00) | (output[i*512/8 + 4*j+3] & 0xFF); } for (int j = 16; j < 64; j++) { int s0 = rightRotate(w[j-15], 7) ^ rightRotate(w[j-15], 18) ^ (w[j-15] >>> 3); int s1 = rightRotate(w[j-2], 17) ^ rightRotate(w[j-2], 19) ^ (w[j-2] >>> 10); w[j] = w[j-16] + s0 + w[j-7] + s1; } //initialize working variables int a = h0; int b = h1; int c = h2; int d = h3; int e = h4; int f = h5; int g = h6; int h = h7; for (int j = 0; j < 64; j++) { int S1 = rightRotate(e, 6) ^ rightRotate(e, 11) ^ rightRotate(e, 25); int ch = (e & f) ^ (~e & g); int temp1 = h + S1 + ch + k[j] + w[j]; int S0 = rightRotate(a, 2) ^ rightRotate(a, 13) ^ rightRotate(a, 22); int maj = (a & b) ^ (a & c) ^ (b & c); int temp2 = S0 + maj; h = g; g = f; f = e; e = d + temp1; d = c; c = b; b = a; a = temp1 + temp2; } h0 = h0 + a; h1 = h1 + b; h2 = h2 + c; h3 = h3 + d; h4 = h4 + e; h5 = h5 + f; h6 = h6 + g; h7 = h7 + h; } byte[] hash = new byte[32]; for (int j = 0; j < 4; j++) { hash[j] = (byte) ((h0 >>> 24-j*8) & 0xFF); } for (int j = 0; j < 4; j++) { hash[j+4] = (byte) ((h1 >>> 24-j*8) & 0xFF); } for (int j = 0; j < 4; j++) { hash[j+8] = (byte) ((h2 >>> 24-j*8) & 0xFF); } for (int j = 0; j < 4; j++) { hash[j+12] = (byte) ((h3 >>> 24-j*8) & 0xFF); } for (int j = 0; j < 4; j++) { hash[j+16] = (byte) ((h4 >>> 24-j*8) & 0xFF); } for (int j = 0; j < 4; j++) { hash[j+20] = (byte) ((h5 >>> 24-j*8) & 0xFF); } for (int j = 0; j < 4; j++) { hash[j+24] = (byte) ((h6 >>> 24-j*8) & 0xFF); } for (int j = 0; j < 4; j++) { hash[j+28] = (byte) ((h7 >>> 24-j*8) & 0xFF); } return hash; } private static int rightRotate(int n, int d) { return (n >>> d) | (n << (32 - d)); } }
36.194444
167
0.46297
1c9be3b943a68b26c81729ace99873a6f0b2959b
1,589
package day_three; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; class Student { String name; int rollNo; Student(String name, int rollNo) { this.name = name; this.rollNo = rollNo; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getRollNo() { return rollNo; } public void setRollNo(int rollNo) { this.rollNo = rollNo; } } class SortByName implements Comparator<Student> { public int compare(Student a, Student b) { return a.name.compareToIgnoreCase(b.name); } } class SortByRollNo implements Comparator<Student> { public int compare(Student a, Student b) { return a.rollNo - b.rollNo; } } public class ComparatorPractice { public static void main(String[] args) { List<Student> students = new ArrayList<>(); students.add(new Student("siddharth", 5)); students.add(new Student("Aayush", 41)); students.add(new Student("Kushagra", 10)); students.add(new Student("Piyush", 28)); students.add(new Student("Dikshita", 22)); System.out.println("Sorting by name!"); Collections.sort(students, new SortByName()); for (Student st: students) { System.out.println(st.rollNo); System.out.println(st.name); System.out.println(); } System.out.println("Sorting by roll no!"); Collections.sort(students, new SortByRollNo()); for (Student st: students) { System.out.println(st.rollNo); System.out.println(st.name); System.out.println(); } } }
20.371795
53
0.677785
011d36914fc3653e04cb56b35df82dfd56964f80
3,681
/** * Copyright 2014 Netflix, Inc. * * 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.netflix.raigad.scheduler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; /** * {@link ThreadPoolExecutor} that will block in the {@code submit()} method * until the task can be successfully added to the queue. */ public class BlockingSubmitThreadPoolExecutor extends ThreadPoolExecutor { private static final long DEFAULT_SLEEP = 100; private static final long DEFAULT_KEEP_ALIVE = 100; private static final Logger logger = LoggerFactory.getLogger(BlockingSubmitThreadPoolExecutor.class); private BlockingQueue<Runnable> queue; private long giveupTime; private AtomicInteger active; public BlockingSubmitThreadPoolExecutor(int maximumPoolSize, BlockingQueue<Runnable> workQueue, long timeoutAdding) { super(maximumPoolSize, maximumPoolSize, DEFAULT_KEEP_ALIVE, TimeUnit.SECONDS, workQueue); this.queue = workQueue; this.giveupTime = timeoutAdding; this.active = new AtomicInteger(0); } /** * This is a thread safe way to avoid rejection exception... this is * implemented because we might want to hold the incoming requests till * there is a free thread. */ @Override public <T> Future<T> submit(Callable<T> task) { synchronized (this) { active.incrementAndGet(); long timeout = 0; while (queue.remainingCapacity() == 0) { try { if (timeout <= giveupTime) { Thread.sleep(DEFAULT_SLEEP); timeout += DEFAULT_SLEEP; } else { throw new RuntimeException("Timed out because TPE is too busy..."); } } catch (InterruptedException e) { throw new RuntimeException(e); } } return super.submit(task); } } @Override protected void afterExecute(Runnable r, Throwable t) { super.afterExecute(r, t); active.decrementAndGet(); } /** * blocking call to test if the threads are done or not. */ public void sleepTillEmpty() { long timeout = 0; while (!queue.isEmpty() || (active.get() > 0)) { try { if (timeout <= giveupTime) { Thread.sleep(DEFAULT_SLEEP); timeout += DEFAULT_SLEEP; logger.debug("After Sleeping for empty: {}, Count: {}", +queue.size(), active.get()); } else { throw new RuntimeException("Timed out because TPE is too busy..."); } } catch (InterruptedException e) { throw new RuntimeException(e); } } } }
31.461538
119
0.575115
e4fa251fa42be250a2afc9ed186d99d88c3ef08b
2,976
package org.js4ms.ip; /* * #%L * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * IPNoOperationOption.java [org.js4ms.jsdk:ip] * %% * Copyright (C) 2009 - 2014 Cisco Systems, Inc. * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import java.nio.ByteBuffer; import java.util.logging.Level; import org.js4ms.common.exception.ParseException; /** * Represents an IP No-Operation Option (Option 1). * Typically used to adjust alignment of subsequent options. * The Type field has the following value: * Copy=1|0, Class=0, Option=1 * * <pre> * +-+-+-+-+-+-+-+-+ * |?|0 0|0 0 0 0 1| * +-+-+-+-+-+-+-+-+ * </pre> * * @author Gregory Bumgardner (gbumgard) */ public final class IPNoOperationOption extends IPSingleByteHeaderOption { /*-- Inner Classes ------------------------------------------------------*/ /** * */ public static class Parser implements IPHeaderOption.ParserType { @Override public IPHeaderOption parse(final ByteBuffer buffer) throws ParseException { return new IPNoOperationOption(buffer); } @Override public Object getKey() { return IPNoOperationOption.OPTION_CODE; } } /*-- Static Variables ---------------------------------------------------*/ /** */ public static final int OPTION_CLASS = 0; /** */ public static final int OPTION_NUMBER = 1; /** */ public static final byte OPTION_CODE = OPTION_CLASS | OPTION_NUMBER; /*-- Member Functions ---------------------------------------------------*/ /** * */ public IPNoOperationOption() { super(OPTION_CODE); if (logger.isLoggable(Level.FINER)) { logger.finer(this.log.entry("IPNoOperationOption.IPNoOperationOption")); } } /** * @param copyFlag */ public IPNoOperationOption(final boolean copyFlag) { super(copyFlag, OPTION_CLASS, OPTION_NUMBER); if (logger.isLoggable(Level.FINER)) { logger.finer(this.log.entry("IPNoOperationOption.IPNoOperationOption", copyFlag)); } } /** * @param buffer */ public IPNoOperationOption(final ByteBuffer buffer) { super(buffer); if (logger.isLoggable(Level.FINER)) { logger.finer(this.log.entry("IPNoOperationOption.IPNoOperationOption", buffer)); } } }
25.878261
94
0.594758
f99cc9a76171568a163b272059de26663e209592
2,722
package pe.asomapps.popularmovies.ui.adapters; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import java.util.List; import pe.asomapps.popularmovies.R; import pe.asomapps.popularmovies.ui.utils.SortOptionItem; /** * @author Danihelsan */ public class SortOptionsAdapter extends BaseAdapter{ private final int resLayoutId = R.layout.item_sortoptions_spinner; private final int resLayoutDropdownId = R.layout.item_sortoptions_dropdown_spinner; private List<Sortable> items; private int selectedPosition; public SortOptionsAdapter(List<Sortable> items){ this.items = items; } @Override public int getCount() { return items.size(); } @Override public Sortable getItem(int i) { return items.get(i); } @Override public long getItemId(int i){ Sortable sortable = getItem(i); return sortable.getItemId(); } @Override public View getView(int i, View view, ViewGroup viewGroup) { if (view == null) { view = LayoutInflater.from(viewGroup.getContext()).inflate(resLayoutId, viewGroup, false); } TextView textView = (TextView) view.findViewById(android.R.id.text1); textView.setText(getItem(i).getLabel()); return view; } @Override public View getDropDownView(int position, View convertView, ViewGroup viewGroup) { if (convertView == null) { convertView = LayoutInflater.from(viewGroup.getContext()).inflate(resLayoutDropdownId, viewGroup, false); } TextView normalTextView = (TextView) convertView.findViewById(android.R.id.text1); normalTextView.setText(getItem(position).getLabel()); return convertView; } public Sortable getSortOption(int position) { return getItem(position); } public void updateFavoriteItem(boolean withFavorited, String optionName) { boolean favoriteFound = false; for (Sortable item : items){ if (item.getValue()==null){ favoriteFound = true; if (!withFavorited){ items.remove(item); } notifyDataSetChanged(); break; } } if (!favoriteFound && withFavorited){ items.add(new SortOptionItem(optionName, null)); notifyDataSetChanged(); } } public interface Sortable { long getItemId(); CharSequence getLabel(); Object getValue(); boolean getVisible(); void setVisibility(boolean visible); } }
28.061856
117
0.64144
c62bae4bf9c85fd16477a92bac1132dede4b851b
1,711
package connect.ui.activity.chat.bean; import android.text.TextUtils; import java.io.Serializable; import protos.Connect; /** * Created by pujin on 2017/3/24. */ public class AdBean implements Serializable{ private String title; private String content; private int category;//0:link 1:upgrade private long createTime; private String url; private String conversUrl; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public int getCategory() { return category; } public void setCategory(int category) { this.category = category; } public long getCreateTime() { return createTime; } public void setCreateTime(long createTime) { this.createTime = createTime; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getConversUrl() { return conversUrl; } public void setConversUrl(String conversUrl) { this.conversUrl = conversUrl; } public void transSystemAd(Connect.Announcement announcement){ setCategory(announcement.getCategory()); setContent(TextUtils.isEmpty(announcement.getContent())?announcement.getDesc():announcement.getContent()); setConversUrl(announcement.getCoversUrl()); setCreateTime((long)announcement.getCreatedAt()); setTitle(announcement.getTitle()); setUrl(announcement.getUrl()); } }
21.935897
114
0.649328
7810472cd3f3f47635b2d0f05c5f8d2a7e52fd5a
722
package test.io.smallrye.openapi.runtime.scanner.jakarta; import jakarta.ws.rs.DefaultValue; import jakarta.ws.rs.GET; import jakarta.ws.rs.Path; import jakarta.ws.rs.Produces; import jakarta.ws.rs.QueryParam; import jakarta.ws.rs.core.MediaType; import org.eclipse.microprofile.openapi.annotations.parameters.Parameter; @Path(value = "/common-target-method") public class CommonTargetMethodParameterResource { @DefaultValue(value = "10") @QueryParam(value = "limit") @Parameter(description = "Description of the limit query parameter") public void setLimit(int limit) { } @GET @Produces(value = MediaType.APPLICATION_JSON) public String[] getRecords() { return null; } }
25.785714
73
0.736842
4c614feaa695987321f9d9b6110854030c91c9f0
72
/** * * */ /** * @author franck * */ module wcs_nfs_dicoutils { }
7.2
26
0.486111
198057f4804acb279cdaf3b0d31dce46d6a9e60c
4,415
package com.cesurazure.crm.controller; import com.cesurazure.crm.controller.impl.IAssignLeadController; import com.cesurazure.crm.model.AssignCRM; import com.cesurazure.crm.model.AssignLead; import com.cesurazure.crm.model.Lead; import com.cesurazure.crm.service.impl.IAssignCRMService; import com.cesurazure.crm.service.impl.IAssignLeadService; import com.cesurazure.crm.service.impl.IBusinessService; import com.cesurazure.crm.service.impl.ICRMUserService; import com.cesurazure.crm.service.impl.ILeadService; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.ModelAndView; @RestController public class AssignLeadController implements IAssignLeadController { @Autowired IAssignLeadService assignLeadService; @Autowired ILeadService leadService; @Autowired IBusinessService businessService; @Autowired ICRMUserService crmuserService; @Autowired IAssignCRMService assignCRMService; @Override @RequestMapping(value = "/assignLeadSave") public ModelAndView save(HttpServletRequest request) { System.out.println("*********** Hitted ***********"); assignLeadService.save(request); // Work is not done here return new ModelAndView("redirect:/assignLead"); } @Override public ModelAndView edit(int id) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public ModelAndView update(HttpServletRequest request) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public ModelAndView delete(int id) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public List<AssignLead> getAll() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } // To create Rest API @RequestMapping(value = "/getLead/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public String getLead(@PathVariable("id") int id) { System.out.println("...................... " + id); GsonBuilder gson = new GsonBuilder(); Gson g = gson.create(); Lead lead = leadService.getById(id); return g.toJson(lead); } @RequestMapping(value = "/getBusineeByLead/{crmID}", method = RequestMethod.GET) public AssignCRM getBusineeByLead(@PathVariable("crmID") String crmID) { System.out.println("...................... " + crmID); AssignCRM crm = assignCRMService.getByCRMId(crmID); System.out.println(".......... " + crm.getBusinessName()); // GsonBuilder gson = new GsonBuilder(); // Gson g = gson.create(); // Lead lead = leadService.getById(id); return crm; } //YENI EFFORT // To create Rest API for ASSIGNCRM @RequestMapping(value = "/getAssignCRM/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public String getAssignCRM(@PathVariable("id") int id) { System.out.println("...................... " + id); GsonBuilder gson = new GsonBuilder(); Gson g = gson.create(); AssignCRM assignCRM = assignCRMService.getById(id); return g.toJson(assignCRM); } @RequestMapping(value = "/assignLead") public ModelAndView hello5() { List<AssignCRM> assignCRMs = assignCRMService.getAll(); List<Lead> leadlist = leadService.getAll(); Map<String, Object> map = new HashMap<String, Object>(); map.put("assignCRMs", assignCRMs); map.put("leadlist", leadlist); return new ModelAndView("assign/assign_lead", "map", map); } }
37.10084
135
0.700113
5566746203ec8afd26ea672c4e8e8b143d39b54d
13,702
package uk.co.nyakeh.papertrail; import android.app.SearchManager; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.provider.SearchRecentSuggestions; import android.support.design.widget.FloatingActionButton; import android.support.v4.view.MenuItemCompat; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.SearchView; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.squareup.picasso.Picasso; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.net.URLEncoder; import java.util.Iterator; public class SearchActivity extends AppCompatActivity { private String mBookCreationStatus; private String mSearchQuery; private RecyclerView mSearchResultsRecyclerView; private SearchResultsAdapter mSearchResultsAdapter; private SearchRecentSuggestions mRecentSuggestions = new SearchRecentSuggestions(this, SuggestionProvider.AUTHORITY, SuggestionProvider.MODE); private FloatingActionButton mShowMoreResultsButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_search); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); handleIntent(getIntent()); Bundle extras = getIntent().getExtras(); mBookCreationStatus = extras.getString(Constants.ARG_BOOK_CREATION_STATUS); mSearchResultsRecyclerView = (RecyclerView) findViewById(R.id.search_results); mSearchResultsRecyclerView.setLayoutManager(new LinearLayoutManager(this)); RecyclerView.ItemDecoration itemDecoration = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST); mSearchResultsRecyclerView.addItemDecoration(itemDecoration); if (mSearchResultsAdapter == null) { mSearchResultsAdapter = new SearchResultsAdapter(new JSONArray()); mSearchResultsRecyclerView.setAdapter(mSearchResultsAdapter); } Button mManualAddBookButton = (Button) findViewById(R.id.search_manual_add); mManualAddBookButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Book book = new Book(mBookCreationStatus); Intent intent = new Intent(SearchActivity.this, CreateBookActivity.class); intent.putExtra(Constants.ARG_NEW_BOOK, new Gson().toJson(book)); startActivity(intent); } }); mShowMoreResultsButton = (FloatingActionButton) findViewById(R.id.search_show_more); mShowMoreResultsButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { new BookSearch().execute(mSearchQuery, "20"); mShowMoreResultsButton.setVisibility(View.INVISIBLE); } }); } @Override protected void onNewIntent(Intent intent) { setIntent(intent); handleIntent(intent); } private void handleIntent(Intent intent) { if (Intent.ACTION_SEARCH.equals(intent.getAction())) { mSearchQuery = intent.getStringExtra(SearchManager.QUERY); mSearchResultsAdapter.setBooks(new JSONArray()); mSearchResultsAdapter.notifyDataSetChanged(); new BookSearch().execute(mSearchQuery, "0"); mRecentSuggestions.saveRecentQuery(mSearchQuery, null); } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.search, menu); SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); MenuItem searchItem = menu.findItem(R.id.menu_item_search); searchItem.expandActionView(); SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem); searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName())); searchView.setSubmitButtonEnabled(true); MenuItemCompat.setOnActionExpandListener(searchItem, new MenuItemCompat.OnActionExpandListener() { @Override public boolean onMenuItemActionCollapse(MenuItem item) { finish(); return false; } @Override public boolean onMenuItemActionExpand(MenuItem item) { return true; } }); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); return true; default: return super.onOptionsItemSelected(item); } } @Override public void onBackPressed() { this.finish(); super.onBackPressed(); } private class BookSearch extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... params) { String xml = ""; URL url; HttpURLConnection urlConnection; String queryString = params[0]; String startIndex = params[1]; try { url = new URL("https://www.googleapis.com/books/v1/volumes?q=" + URLEncoder.encode(queryString, "UTF-8") + "&filter=ebooks&maxResults=20&printType=books&showPreorders=true&startIndex=" + startIndex + "&key=" + getString(R.string.google_books_api_key)); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setReadTimeout(10000); urlConnection.setConnectTimeout(15000); urlConnection.setRequestMethod("GET"); urlConnection.setDoInput(true); InputStream in = urlConnection.getInputStream(); InputStreamReader isw = new InputStreamReader(in); BufferedReader br = new BufferedReader(isw); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } br.close(); xml = sb.toString(); } catch (Exception exception) { exception.printStackTrace(); } return xml; } @Override protected void onPostExecute(String result) { //Log.d("Raw results: ", result); if (result.equals("")) { //getSupportActionBar().setSubtitle("Sorry, we failed to retrieve any results."); mSearchResultsAdapter.setBooks(new JSONArray()); mSearchResultsAdapter.notifyDataSetChanged(); } else { JSONObject resultObject; try { resultObject = new JSONObject(result); JSONArray bookArray = resultObject.getJSONArray("items"); mSearchResultsAdapter.addBooks(bookArray); mSearchResultsAdapter.notifyDataSetChanged(); } catch (Exception exception) { exception.printStackTrace(); } } } } private class SearchResultHolder extends RecyclerView.ViewHolder implements View.OnClickListener { private Book mSearchResult; private ImageView mImageView; private TextView mTitleTextView; private TextView mAuthorTextView; private TextView mIsbnTextView; public SearchResultHolder(View itemView) { super(itemView); itemView.setOnClickListener(this); mImageView = (ImageView) itemView.findViewById(R.id.list_item_book_image); mTitleTextView = (TextView) itemView.findViewById(R.id.list_item_book_title); mAuthorTextView = (TextView) itemView.findViewById(R.id.list_item_book_author); mIsbnTextView = (TextView) itemView.findViewById(R.id.list_item_book_date_finished); } private void bindSearchResult(JSONObject book) { String title = ""; StringBuilder authorBuilder = new StringBuilder(""); String isbn = ""; String imageUrl = ""; int pageCount = 100; String description = ""; try { JSONObject volumeObject = book.getJSONObject("volumeInfo"); try { title = volumeObject.getString("title"); } catch (Exception e) { } try { JSONArray authorArray = volumeObject.getJSONArray("authors"); for (int i = 0; i < authorArray.length(); i++) { if (i > 0) { authorBuilder.append(", "); } authorBuilder.append(authorArray.getString(i)); } } catch (Exception e) { } try { JSONArray isbnArray = volumeObject.getJSONArray("industryIdentifiers"); for (int i = 0; i < isbnArray.length(); i++) { JSONObject isbnObject = isbnArray.getJSONObject(i); if (isbnObject.getString("type").equals("ISBN_10")) { isbn = isbnObject.getString("identifier"); } } } catch (Exception e) { } try { imageUrl = volumeObject.getJSONObject("imageLinks").getString("thumbnail"); String safePicassoImageUrl = (imageUrl.isEmpty()) ? "fail_gracefully_pls" : imageUrl; Picasso.with(SearchActivity.this) .load(safePicassoImageUrl) .placeholder(R.drawable.books) .error(R.drawable.books) .into(mImageView); } catch (Exception e) { } try { String pageCountString = volumeObject.getString("pageCount"); if (!pageCountString.isEmpty()) { pageCount = Integer.parseInt(pageCountString); } } catch (Exception e) { } try { description = volumeObject.getString("description"); } catch (Exception e) { } mSearchResult = new Book(mBookCreationStatus, title, authorBuilder.toString(), isbn, pageCount, imageUrl, description); } catch (JSONException e) { e.printStackTrace(); } mTitleTextView.setText(mSearchResult.getTitle()); mAuthorTextView.setText(mSearchResult.getAuthor()); mIsbnTextView.setText(mSearchResult.getISBN()); } @Override public void onClick(View view) { Intent intent = new Intent(SearchActivity.this, CreateBookActivity.class); intent.putExtra(Constants.ARG_NEW_BOOK, new Gson().toJson(mSearchResult)); startActivity(intent); } } private class SearchResultsAdapter extends RecyclerView.Adapter<SearchResultHolder> { private JSONArray mSearchResults; public SearchResultsAdapter(JSONArray searchResults) { mSearchResults = searchResults; } @Override public SearchResultHolder onCreateViewHolder(ViewGroup parent, int i) { LayoutInflater layoutInflater = LayoutInflater.from(SearchActivity.this); View view = layoutInflater.inflate(R.layout.list_item_search_result, parent, false); return new SearchResultHolder(view); } @Override public void onBindViewHolder(SearchResultHolder searchResultHolder, int position) { JSONObject searchResult = null; try { searchResult = (JSONObject) mSearchResults.get(position); } catch (Exception exception) { exception.printStackTrace(); } searchResultHolder.bindSearchResult(searchResult); } @Override public int getItemCount() { return mSearchResults.length(); } public void setBooks(JSONArray searchResults) { mSearchResults = searchResults; } public void addBooks(JSONArray searchResults) throws JSONException { if (mSearchResults.length() == 0){ mShowMoreResultsButton.setVisibility(View.VISIBLE); } for (int i = 0; i < searchResults.length(); i++) { mSearchResults.put(searchResults.getJSONObject(i)) ; } } } }
39.831395
268
0.613633
9ba57a4a44d6a2db4faef9aba0b4974d2f0e3708
1,411
package org.smartregister.p2p.model; import android.arch.persistence.room.Database; import android.arch.persistence.room.Room; import android.arch.persistence.room.RoomDatabase; import android.content.Context; import android.support.annotation.NonNull; import android.text.SpannableStringBuilder; import com.commonsware.cwac.saferoom.SafeHelperFactory; import org.smartregister.p2p.model.dao.P2pReceivedHistoryDao; import org.smartregister.p2p.model.dao.SendingDeviceDao; /** * Created by Ephraim Kigamba - ekigamba@ona.io on 26/03/2019 */ @Database(entities = {SendingDevice.class, P2pReceivedHistory.class}, version = 1) public abstract class AppDatabase extends RoomDatabase { private static AppDatabase instance; public static final String DB_NAME = "p2p"; public static AppDatabase getInstance(@NonNull Context context, @NonNull String passphrase) { if (instance == null) { SafeHelperFactory safeHelperFactory = SafeHelperFactory.fromUser(new SpannableStringBuilder(passphrase)); instance = Room.databaseBuilder(context.getApplicationContext(), AppDatabase.class, DB_NAME) .openHelperFactory(safeHelperFactory) .build(); } return instance; } public abstract SendingDeviceDao sendingDeviceDao(); public abstract P2pReceivedHistoryDao p2pReceivedHistoryDao(); }
32.813953
117
0.744153
d9baa658bcdfe67e608852f635636194bfb92221
963
package com.twotoasters.clusterkraf; import com.google.android.gms.maps.model.Marker; /** * Because Clusterkraf must set its own OnMarkerClickListener on the GoogleMap * it is managing, and because the GoogleMap can only have one * OnMarkerClickListener, Clusterkraf passes the event downstream to its users. */ public interface OnMarkerClickDownstreamListener { /** * @param marker * The Marker object that was clicked. * @param clusterPoint * The ClusterPoint object representing the Marker that was * clicked. In case you have manually added Marker objects * directly to the map, bypassing Clusterkraf, this will be null * if the clicked Marker object was added manually. * @return true if you have fully consumed the event, or false if * Clusterkraf still needs to carry out the configured action. */ boolean onMarkerClick(Marker marker, ClusterPoint clusterPoint); }
40.125
79
0.721703
10a0cdc0b6202242e8c07dcaa12f251df78842b7
1,351
/** * 本项目采用《JFinal 俱乐部授权协议》,保护知识产权,就是在保护我们自己身处的行业。 * * Copyright (c) 2011-2021, jfinal.com */ package com.jfinal.admin.demo; import com.jfinal.admin.common.BaseController; import com.jfinal.core.Path; import static com.jfinal.admin.demo.Icons.*; /** * 后续版本添加更多组件演示,如 bootstrap 4 组件 */ @Path("/admin/demo") public class DemoAdminController extends BaseController { /** * 集成 echarts 图表 * 文档 https://echarts.apache.org/examples/zh/index.html */ public void echarts() { render("echarts.html"); } /** * 集成 font awesome 图标 * 一共展示 939 个图标,少部分图标同时存在于多个分类,所以会有重复 */ public void fontAwesome() { set("webAppIcons", webAppIcons); set("accessibilityIcons", accessibilityIcons); set("handIcons", handIcons); set("transportationIcons", transportationIcons); set("genderIcons", genderIcons); set("fileTypeIcons", fileTypeIcons); set("spinnerIcons", spinnerIcons); set("formControlIcons", formControlIcons); set("paymentIcons", paymentIcons); set("chartIcons", chartIcons); set("currencyIcons", currencyIcons); set("textEditorIcons", textEditorIcons); set("directionalIcons", directionalIcons); set("videoPlayerIcons", videoPlayerIcons); set("brandIcons", brandIcons); set("medicalIcons", medicalIcons); // set("newIcons", newIcons); // 新增的图标在上述相应的分类中已经放入,不再展示 render("font_awesome.html"); } }
25.490566
59
0.715766
75069bada1af39cf0e20c1c9020872e2eeda0e57
467
package com.bolt.alexa.skill.model; public class RestaurantSearchResponse{ private final boolean foundMatch; private final Restaurant[] foundRestaurants; public RestaurantSearchResponse(boolean foundMatch, Restaurant[] foundRestaurants) { super(); this.foundMatch = foundMatch; this.foundRestaurants = foundRestaurants; } public boolean isFoundMatch() { return foundMatch; } public Restaurant[] getFoundRestaurants() { return foundRestaurants; } }
25.944444
85
0.785867
696b2d361749f1d1859226c03a0d1dca7d850b43
6,390
package io.g740.pigeon.biz.service.handler.account; import io.g740.commons.exception.impl.AuthAccountNotFoundException; import io.g740.commons.exception.impl.ResourceDuplicateException; import io.g740.commons.exception.impl.ResourceNotFoundException; import io.g740.commons.exception.impl.ServiceException; import io.g740.commons.types.BaseDo; import io.g740.commons.types.Handler; import io.g740.commons.types.UserInfo; import io.g740.pigeon.biz.object.dto.account.AccountProfileDto; import io.g740.pigeon.biz.object.dto.account.CreateAccountDto; import io.g740.pigeon.biz.object.dto.account.UpdateAccountDto; import io.g740.pigeon.biz.object.entity.account.CredentialDo; import io.g740.pigeon.biz.object.entity.account.MembershipDo; import io.g740.pigeon.biz.object.entity.account.UserDo; import io.g740.pigeon.biz.persistence.jpa.account.CredentialRepository; import io.g740.pigeon.biz.persistence.jpa.account.MembershipRepository; import io.g740.pigeon.biz.persistence.jpa.account.UserRepository; import org.apache.commons.codec.digest.DigestUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; import java.util.Date; import java.util.List; /** * @author bbottong */ @Handler public class AccountHandler { @Autowired private UserRepository userRepository; @Autowired private MembershipRepository membershipRepository; @Autowired private CredentialRepository credentialRepository; @Transactional(rollbackFor = Exception.class) public AccountProfileDto createAccount(CreateAccountDto createAccountDto, UserInfo operationUserInfo) throws ServiceException { boolean existsDuplicate = this.userRepository.existsByUsername(createAccountDto.getUsername()); if (existsDuplicate) { throw new ResourceDuplicateException(UserDo.RESOURCE_NAME + ":" + createAccountDto.getUsername()); } UserDo userDo = new UserDo(); userDo.setUsername(createAccountDto.getUsername()); userDo.setEnabled(createAccountDto.getEnabled()); BaseDo.create(userDo, operationUserInfo.getUsername(), new Date()); this.userRepository.save(userDo); CredentialDo credentialDo = new CredentialDo(); credentialDo.setUsername(userDo.getUsername()); credentialDo.setCredential(DigestUtils.sha256Hex(createAccountDto.getPassword())); BaseDo.create(credentialDo, operationUserInfo.getUsername(), new Date()); this.credentialRepository.save(credentialDo); MembershipDo membershipDo = new MembershipDo(); membershipDo.setUsername(userDo.getUsername()); membershipDo.setRole(createAccountDto.getRole()); BaseDo.create(membershipDo, operationUserInfo.getUsername(), new Date()); this.membershipRepository.save(membershipDo); return getAccountProfile(userDo.getUsername(), operationUserInfo); } @Transactional(rollbackFor = Exception.class) public AccountProfileDto updateAccount(UpdateAccountDto updateAccountDto, UserInfo operationUserInfo) throws ServiceException { UserDo userDo = this.userRepository.findByUsername(updateAccountDto.getUsername()); if (userDo == null) { throw new ResourceNotFoundException(UserDo.RESOURCE_NAME + ":" + updateAccountDto.getUsername()); } MembershipDo membershipDo = this.membershipRepository.findByUsername(updateAccountDto.getUsername()); if (membershipDo == null) { throw new ResourceNotFoundException(MembershipDo.RESOURCE_NAME + ":" + updateAccountDto.getUsername()); } boolean requiredToUpdateUserDo = false; if (updateAccountDto.getEnabled() != null && !updateAccountDto.getEnabled().equals(userDo.getEnabled())) { requiredToUpdateUserDo = true; userDo.setEnabled(updateAccountDto.getEnabled()); } if (requiredToUpdateUserDo) { BaseDo.update(userDo, operationUserInfo.getUsername(), new Date()); this.userRepository.save(userDo); } boolean requiredToUpdateMembershipDo = false; if (updateAccountDto.getRole() != null && !updateAccountDto.getRole().equalsIgnoreCase(membershipDo.getRole())) { requiredToUpdateMembershipDo = true; membershipDo.setRole(updateAccountDto.getRole()); } if (requiredToUpdateMembershipDo) { BaseDo.update(membershipDo, operationUserInfo.getUsername(), new Date()); this.membershipRepository.save(membershipDo); } return getAccountProfile(userDo.getUsername(), operationUserInfo); } public AccountProfileDto getAccountProfile(String username, UserInfo operationUserInfo) throws ServiceException { UserDo userDo = this.userRepository.findByUsername(username); if (userDo == null) { throw new AuthAccountNotFoundException(username); } AccountProfileDto accountProfileDto = new AccountProfileDto(); accountProfileDto.setUsername(username); accountProfileDto.setEmailAddress(userDo.getEmailAddress()); accountProfileDto.setPhone(userDo.getPhone()); accountProfileDto.setEnabled(userDo.getEnabled()); accountProfileDto.setCreateTimestamp(userDo.getCreateTimestamp()); // 获取用户membership MembershipDo membershipDo = this.membershipRepository.findByUsername(username); if (membershipDo != null) { accountProfileDto.setRole(membershipDo.getRole()); } return accountProfileDto; } public List<String> queryUsername(String username, UserInfo operationUserInfo) throws ServiceException { return this.userRepository.fuzzyQueryByUsername(username); } @Transactional(rollbackFor = Exception.class) public void deleteAccount(String username, UserInfo operationUserInfo) throws ServiceException { UserDo userDo = this.userRepository.findByUsername(username); if (userDo == null) { throw new AuthAccountNotFoundException(username); } userDo.setDeleted(true); BaseDo.update(userDo, operationUserInfo.getUsername(), new Date()); this.userRepository.save(userDo); } }
43.767123
117
0.72097
7d16511371c3cb9fac722f064bea155bdcd0b5ca
7,161
/* * Copyright (c) 2010-2018. Axon Framework * * 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. */ /* * Copyright (c) 2010-2017. Axon Framework * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.axonframework.extensions.springcloud; import org.springframework.boot.context.properties.ConfigurationProperties; /** * Defines the properties for the Distributed Command Bus, when automatically configured in the Application Context. */ @ConfigurationProperties(prefix = "axon.distributed") public class DistributedCommandBusProperties { /** * Enables Distributed Command Bus configuration for this application. */ private boolean enabled = false; /** * Sets the loadFactor for this node to join with. The loadFactor sets the relative load this node will * receive compared to other nodes in the cluster. Defaults to 100. */ private int loadFactor = 100; private SpringCloudProperties springCloud = new SpringCloudProperties(); /** * Indicates whether the (auto-configuration) of the Distributed Command Bus is enabled. * * @return whether the (auto-configuration) of the Distributed Command Bus is enabled. */ public boolean isEnabled() { return enabled; } /** * Enables (if {@code true}) or disables (if {@code false}, default) the auto-configuration of a Distributed * Command Bus instance in the application context. * * @param enabled whether to enable Distributed Command Bus configuration. */ public void setEnabled(boolean enabled) { this.enabled = enabled; } /** * Returns the load factor for this instance of the Distributed Command Bus (default 100). * * @return the load factor for this instance of the Distributed Command Bus. */ public int getLoadFactor() { return loadFactor; } /** * Sets the load factor for this instance of the Distributed Command Bus (default 100). * * @param loadFactor the load factor for this instance of the Distributed Command Bus. */ public void setLoadFactor(int loadFactor) { this.loadFactor = loadFactor; } /** * Returns the Spring Cloud configuration to use (if Spring Cloud is on the classpath). * * @return the Spring Cloud configuration to use. */ public SpringCloudProperties getSpringCloud() { return springCloud; } /** * Sets the Spring Cloud configuration to use (if Spring Cloud is on the classpath). * * @param springCloud the Spring Cloud configuration to use. */ public void setSpringCloud(SpringCloudProperties springCloud) { this.springCloud = springCloud; } public static class SpringCloudProperties { /** * Enable a HTTP GET fallback strategy for retrieving the message routing information from other nodes in a * distributed Axon set up. Defaults to "true". */ private boolean fallbackToHttpGet = true; /** * The URL used to perform HTTP GET requests on for retrieving another nodes message routing information in a * distributed Axon set up. Defaults to "/message-routing-information". */ private String fallbackUrl = "/message-routing-information"; /** * The optional name of the spring cloud service instance metdata property, * that does contain the contextroot path of the service. */ private String contextRootMetadataPropertyName; /** * Indicates whether to fall back to HTTP GET when retrieving Instance Meta Data from the Discovery Server * fails. * * @return whether to fall back to HTTP GET when retrieving Instance Meta Data from the Discovery Server fails. */ public boolean isFallbackToHttpGet() { return fallbackToHttpGet; } /** * Whether to fall back to HTTP GET when retrieving Instance Meta Data from the Discovery Server fails. * * @param fallbackToHttpGet whether to fall back to HTTP GET when retrieving Instance Meta Data from the * Discovery Server fails. */ public void setFallbackToHttpGet(boolean fallbackToHttpGet) { this.fallbackToHttpGet = fallbackToHttpGet; } /** * Returns the URL relative to the host's root to retrieve Instance Meta Data from. This is also the address * where this node will expose its own Instance Meta Data. * * @return the URL relative to the host's root to retrieve Instance Meta Data from. */ public String getFallbackUrl() { return fallbackUrl; } /** * Sets the URL relative to the host's root to retrieve Instance Meta Data from. This is also the address * where this node will expose its own Instance Meta Data. * * @param fallbackUrl the URL relative to the host's root to retrieve Instance Meta Data from. */ public void setFallbackUrl(String fallbackUrl) { this.fallbackUrl = fallbackUrl; } /** * Returns the optional name of the spring cloud service instance metadata property, * that does contain the contextroot path of the service. * * @return the optional name of the spring cloud service instance metadata property, * that does contain the contextroot path of the service. */ public String getContextRootMetadataPropertyName() { return contextRootMetadataPropertyName; } /** * @param contextRootMetadataPropertyName the optional name of the spring cloud service instance metdata property, * that does contain the contextroot path of the service. */ public void setContextRootMetadataPropertyName(String contextRootMetadataPropertyName) { this.contextRootMetadataPropertyName = contextRootMetadataPropertyName; } } }
37.689474
122
0.668063
028d6b431d9d7bdcfba39c6d2d664dc18745192e
6,013
package org.example.controller; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.DatePicker; import javafx.scene.control.TextField; import org.example.App; import org.example.model.*; import java.net.URL; import java.time.Duration; import java.time.LocalDateTime; import java.util.Map; import java.util.ResourceBundle; public class PaymentViewController implements IReceiveData , Initializable { @FXML private TextField txt_nomprenom; @FXML private TextField txt_typem; @FXML private TextField txt_matricule; @FXML private TextField txt_parking; @FXML private TextField txt_num_place; @FXML private DatePicker dateE; @FXML private TextField txt_timee; @FXML private DatePicker dateS; @FXML private TextField txt_times; @FXML private TextField txt_prix; @FXML private Button Submit; @FXML private Button Annuler; private Voiture voiture; private TypeMember type_membre; private Member membre; private Reservation reservation; private Place place; private Parking parking; @FXML void onClickAnnuler(ActionEvent event) { App.viewController.navigateTo("historique.fxml"); } @FXML void onClickSubmit(ActionEvent event) { reservation.setPayment_state(1); reservation.setState(1); reservation.update(); App.viewController.navigateTo("historique.fxml"); } @Override public void initialize(URL url, ResourceBundle resourceBundle) { } @Override public void setData(Map<String, Object> data) { if (data.containsKey("matricule")) { String matricule = (String) data.get("matricule"); onReceiveMatricule(matricule); return; } if(data.containsKey("id_reservation")){ int id_reservation = (int) data.get("id_reservation"); onReceiveReservation(id_reservation); return; } } private void onReceiveMatricule(String matricule) { Voiture v = new Voiture(); v.setMatricule(matricule); if(!v.readByMatricule()){ return; } Member m = new Member(); m.setId(v.getId_m()); if(!m.read()){ return; } TypeMember tm = new TypeMember(); tm.setId(m.getId_member_type()); if(!tm.read()){ return; } //select last reservation Reservation r = new Reservation(); r.setId_V(v.getId()); if(!r.readByVoiture()){ return; } Place p = new Place(); p.setId(r.getId_place()); if(!p.read()){ return; } Parking pk = new Parking(); pk.setId(p.getId_parking()); if(!pk.read()){ return; } this.voiture = v; this.membre = m; this.type_membre = tm; this.reservation = r; this.place = p; this.parking = pk; this.loadForm(); } private void onReceiveReservation(int id_reservation) { Reservation r = new Reservation(); r.setId(id_reservation); if(!r.read()){ return; } Voiture v = new Voiture(); v.setId(r.getId_V()); if(!v.read()){ return; } Member m = new Member(); m.setId(v.getId_m()); if(!m.read()){ return; } TypeMember tm = new TypeMember(); tm.setId(m.getId_member_type()); if(!tm.read()){ return; } Place p = new Place(); p.setId(r.getId_place()); if(!p.read()){ return; } Parking pk = new Parking(); pk.setId(p.getId_parking()); if(!pk.read()){ return; } this.voiture = v; this.membre = m; this.type_membre = tm; this.reservation = r; this.place = p; this.parking = pk; this.loadForm(); } private void loadForm() { if(voiture == null){ return; } if(membre == null){ return; } if(type_membre == null){ return; } if(reservation == null){ return; } txt_matricule.setText(voiture.getMatricule()); txt_nomprenom.setText(membre.getName() + " " + membre.getPrenom()); txt_parking.setText(parking.getName()); txt_num_place.setText(place.getId()+""); txt_typem.setText(type_membre.getLebelle()); dateE.setValue(reservation.getDate_debut().toLocalDate()); txt_timee.setText( reservation.getDate_debut().getHour() +":" +reservation.getDate_debut().getMinute()); //calculer le prix reservation.setDate_fin(LocalDateTime.now()); reservation.setPrix(price()); dateS.setValue(reservation.getDate_fin().toLocalDate()); txt_times.setText( reservation.getDate_fin().getHour() +":" +reservation.getDate_fin().getMinute()); txt_prix.setText(reservation.getPrix()+""); } public float price(){ Duration duration = Duration.between(reservation.getDate_debut(),reservation.getDate_fin()); float prix = 2; if(place.getTypePlaceStr().equals("gold")){ prix = 5; } else if (place.getTypePlaceStr().equals("silver")){ prix = 3; } prix *= duration.toHours()+1; if(membre.getMemberTypeStr().equals("gold")){ prix -= prix * .30F; } else if (membre.getMemberTypeStr().equals("silver")){ prix -= prix * .15F; } return prix; } }
21.945255
100
0.552969
52175e47ae1c41f5af200ed5972d8ede6ccf2a1e
8,683
package algorithms.planner; import models.agents.Agent; import models.facilities.Facility; import models.facilities.Rack; import models.maps.GridCell; import models.warehouses.Warehouse; import utils.Constants; import utils.Constants.*; import utils.Utility; /** * This {@code PlanNode} class represents a state node in the search tree of the * planning algorithm. */ public class PlanNode implements Comparable<PlanNode> { // // Static Variables & Methods // /** * The {@code Warehouse} holding the map grid to plan into. */ private static Warehouse warehouse = Warehouse.getInstance(); /** * The source {@code Agent}. */ private static Agent source; /** * The target {@code Facility} of the {@code Agent}. */ private static Facility target; /** * Array holding the direction leading to every state. */ private static int[][][] par; /** * Initializes the planning state. * <p> * This function should be called once before running the planning algorithm. * * @param src the source {@code Agent}. * @param dst the destination {@code Facility}. */ public static void initializes(Agent src, Facility dst) { int rows = warehouse.getRows(); int cols = warehouse.getCols(); source = src; target = dst; par = new int[rows][cols][Constants.DIR_COUNT]; for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { for (int d : Constants.DIRECTIONS) { par[i][j][d] = -1; } } } } // =============================================================================================== // // Member Variables // /** * The row position of the {@code Agent} in the this simulation state. */ public int row; /** * The column position of the {@code Agent} in the this simulation state. */ public int col; /** * The direction of the {@code Agent} in the this simulation state. */ public int dir; /** * The direction of the parent state leading to this state. */ public int parDir; /** * The weight of the state. That is, the distance from the initial state to this {@code state}. */ public int weight; // =============================================================================================== // // Member Methods // /** * Constructs a new {@code PlanNode} object. * * @param row the row position of the {@code Agent}. * @param col the row position of the {@code Agent}. * @param dir the current direction of the {@code Agent}. */ public PlanNode(int row, int col, int dir) { this(row, col, dir, Constants.DIR_RIGHT, 0); } /** * Constructs a new {@code PlanNode} object. * * @param row the row position of the {@code Agent}. * @param col the row position of the {@code Agent}. * @param dir the direction of the {@code Agent}. * @param parDir the direction of the parent state. * @param weight the weight of the new state. */ private PlanNode(int row, int col, int dir, int parDir, int weight) { this.row = row; this.col = col; this.dir = dir; this.parDir = parDir; this.weight = weight; } /** * Checks whether this state node is the initial state node. * That is, whether it has the same position and direction of the source {@code Agent}. * * @return {@code true} if it is an initial node; {@code false} otherwise. */ public boolean isInitial() { return source.isCoincide(row, col); } /** * Checks whether this state node is the finial state node. * That is, whether it has the same position of the target {@code Facility}. * * @return {@code true} if it is a final node; {@code false} otherwise. */ public boolean isFinal() { return target.isCoincide(row, col); } /** * Checks whether it is possible to further explore and expand this plan node or not. * * @return {@code true} if it is possible to explore; {@code false} otherwise. */ public boolean canVisit() { // First of all return if out of warehouse boundaries if (warehouse.isOutBound(row, col)) { return false; } // Get this state cell GridCell cell = warehouse.get(row, col); // Skip if already visited or blocked cell if (isVisited() || cell.isBlocked()) { return false; } // Cannot pass on a rack cell if currently the agent is loading another one if (source.isLoaded() && cell.getType() == CellType.RACK) { Rack rack = (Rack) cell.getFacility(); return rack.isBound(); } // The state is empty so we can explore it return true; } /** * Checks whether this state node has been visited before or not. * * @return {@code true} if already visited; {@code false} otherwise. */ public boolean isVisited() { return (par[row][col][dir] != -1); } /** * Marks this state node as visited. */ public void visit() { par[row][col][dir] = parDir; } /** * Calculates the next state if moving in the given direction. * * @param d the direction to move in. * * @return the next state {@code PlanNode}. */ public PlanNode next(int d) { int r = row + Constants.DIR_ROW[d]; int c = col + Constants.DIR_COL[d]; return new PlanNode(r, c, d, dir, weight + Utility.getRotationsCount(d, dir) + 1); } /** * Calculates the previous state if moving in the best calculated direction * of the planning algorithm in reverse manner. * * @return the previous state {@code PlanNode}. */ public PlanNode previous() { int r = row - Constants.DIR_ROW[dir]; int c = col - Constants.DIR_COL[dir]; return new PlanNode(r, c, parDir, par[r][c][parDir], weight - Utility.getRotationsCount(parDir, dir) - 1); } /** * Updates the cost of this state by adding more weight if it holds * an idle agent. */ public void updateWeight() { Agent blockingAgent = warehouse.get(row, col).getAgent(); if (blockingAgent == null || blockingAgent.isActive()) { return; } weight += 1; } /** * Calculates the heuristic score to reach the target state. * * @return the heuristic score. */ public int heuristic() { return target.getDistanceTo(row, col); } /** * Calculates and return the total estimated cost to reach the target from the initial location. * That is, the f(s) function of the A* algorithm. * <p> * f(s) = g(s) + h(s), where: * f(s) is the total estimated cost to reach the target from the initial location, * g(s) the actual cost to reach the current state from the initial location, and * h(s) the estimated cost to reach the target from the current state. * * @return the total estimated cost. */ public int totalCost() { return weight + heuristic(); } /** * Compares whether some other object is less than, equal to, or greater than this one. * * @param obj the reference object with which to compare. * * @return a negative integer, zero, or a positive integer as this object * is less than, equal to, or greater than the specified object. */ @Override public int compareTo(PlanNode obj) { long lhs = totalCost(); long rhs = obj.totalCost(); if (lhs == rhs) { return 0; } return lhs < rhs ? -1 : 1; } /** * Returns a string representation of this {@code PlanNode}. * In general, the toString method returns a string that "textually represents" this object. * * @return a string representation of this {@code PlanNode}. */ @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("PlanNode: {"); builder.append(" pos: ").append("(").append(row).append(", ").append(col).append(")").append(","); builder.append(" dir: ").append(dir).append(","); builder.append(" dir: ").append(dir); builder.append(" weight: ").append(weight).append(","); builder.append(" }"); return builder.toString(); } }
28.943333
114
0.569619
e46e03fce75e7fb0d770ff200fa7c69afed17f04
184
package com.xyh.enjoyweather.util; /** * Created by 向阳湖 on 2016/3/7. */ public interface HttpCallbackListener { void onFinish(String reponse); void onError(Exception e); }
16.727273
39
0.706522
81bf5317aa2159c588f785533c947f7e4b86a66b
7,885
package de.datenkraken.datenkrake.ui.util; import android.content.Context; import android.graphics.Canvas; import android.graphics.ColorFilter; import android.graphics.PixelFormat; import android.graphics.drawable.Drawable; import android.text.Html; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import com.bumptech.glide.Glide; import com.bumptech.glide.request.Request; import com.bumptech.glide.request.target.SizeReadyCallback; import com.bumptech.glide.request.target.Target; import com.bumptech.glide.request.transition.Transition; import java.lang.ref.WeakReference; /** * Extracts Image from {@link de.datenkraken.datenkrake.model.Source} * and displays it in a TextView using Glide. <br> * Implements Html.ImageGetter. * * @author Tobias Kröll - tobias.kroell@stud.tu-darmstadt.de */ public class GlideImageGetter implements Html.ImageGetter { private final WeakReference<Context> context; final TextView textView; /** * Constructor for the GlideImageGetter. <br> * Display an Image from a Html text in a TextView. * * @param context used by Glide to display the image. * @param target of Image to be displayed in. */ public GlideImageGetter(Context context, TextView target) { this.context = new WeakReference<>(context); textView = target; } /** * Loads the Image given as a url string into a Drawable. <br> * Creates a new {@link DrawablePlaceholder} and loads the image form the given url into it. * * @param url of Image. * @return Drawable with the image or null, if context or url are null. */ @Override public Drawable getDrawable(String url) { DrawablePlaceholder drawable = new DrawablePlaceholder(); if (context.get() != null && url != null) { Glide.with(context.get()) .asDrawable() .load(url) .into(drawable); return drawable; } else { return null; } } /** * Drawable that implements Target. <br> * Calculates the size of the drawable used in the TextView. * The drawable is loaded into a TextView. */ private class DrawablePlaceholder extends Drawable implements Target<Drawable> { private Drawable drawable; @Nullable private Request request; @Nullable private ColorFilter colorFilter; /** * Sets the drawable to be loaded and calculates size and bounds of the drawable. * Also sets the color filter, and loads the drawable into the TextView. * * @param drawable to be loaded into TextView. */ private void setDrawable(Drawable drawable) { this.drawable = drawable; // drawable can also be null if (drawable != null) { int drawableWidth = drawable.getIntrinsicWidth(); int drawableHeight = drawable.getIntrinsicHeight(); int maxWidth = textView.getMeasuredWidth(); if (drawableWidth > maxWidth) { int calculatedHeight = maxWidth * drawableHeight / drawableWidth; drawable.setBounds(0, 0, maxWidth, calculatedHeight); setBounds(0, 0, maxWidth, calculatedHeight); } else { drawable.setBounds(0, 0, drawableWidth, drawableHeight); setBounds(0, 0, drawableWidth, drawableHeight); } drawable.setColorFilter(this.colorFilter); } // Refresh view object textView.setText(textView.getText()); } /** * Upon start of the loading of the image, sets a placeholder image into the drawable. * * @param placeholder to be loaded. */ @Override public void onLoadStarted(@Nullable Drawable placeholder) { setDrawable(placeholder); } /** * When the loading of the image fails, loads an backup image. * * @param errorDrawable image to be loaded, when loading of wanted image fails. */ @Override public void onLoadFailed(@Nullable Drawable errorDrawable) { setDrawable(errorDrawable); } /** * Loads the image into the drawable, when the image is ready. * * @param resource to be loaded into the drawable. * @param transition animation for image, not used here. */ @Override public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) { setDrawable(resource); } /** * Sets a placeholder, when the loading is cleared. * * @param placeholder to be set for drawable. */ @Override public void onLoadCleared(@Nullable Drawable placeholder) { setDrawable(placeholder); } /** * Sets the sizeof a callback. * Uses the original sizes of the image. * * @param cb callback for which the size should be set. */ @Override public void getSize(@NonNull SizeReadyCallback cb) { cb.onSizeReady(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL); } /** * Removes the SizeReadyCallback. Not used here. * * @param cb to be removed. */ @Override public void removeCallback(@NonNull SizeReadyCallback cb) { // Do nothing, we never retain a reference to the callback. } /** * Sets the Glide request for the drawable. * * @param request to be set for the drawable. */ @Override public void setRequest(@Nullable Request request) { this.request = request; } /** * Gets the Glide request of the drawable. * * @return Glide request of the drawable. */ @Nullable @Override public Request getRequest() { return this.request; } /** * Called on start of the class. Not used here. */ @Override public void onStart() { } /** * Called on stop of the class. Not used here. */ @Override public void onStop() { } /** * Called on destruction of the class. Not used here. */ @Override public void onDestroy() { } /** * Draws the drawable onto a given canvas. * * @param canvas for drawable to be drawn on, can not be null. */ @Override public void draw(@NonNull Canvas canvas) { if (drawable != null) { drawable.draw(canvas); } } /** * Sets alpha value of the drawable. Not used here. * * @param alpha value to be set. */ @Override public void setAlpha(int alpha) { } /** * Sets a color filter for the drawable. * * @param colorFilter to be used on the drawable. */ @Override public void setColorFilter(@Nullable ColorFilter colorFilter) { this.colorFilter = colorFilter; if (drawable != null) { drawable.setColorFilter(colorFilter); } } /** * Gets the opacity or alpha value of the drawable. * * @return int displaying the alpha value. */ @Override public int getOpacity() { return (drawable == null) ? PixelFormat.UNKNOWN : drawable.getAlpha(); } } }
29.754717
116
0.57565
699b70bd8019843dc54758413f3b3c3ccca09041
13,622
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.cloudata.core.commitlog.pipe; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FilenameFilter; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.cloudata.core.common.Constants; import org.cloudata.core.common.CStopWatch; /** * @author sangchul 하나의 CommitLogFileChannel 인스턴스는 Tablet하나를 가리킨다. 따라서 만일 하나의 * tablet에 동시에 변경 요청이 수신 될 경우 두개 이상의 Pipe가 동시에 하나의 CommitLogFileChannel * 인스턴스에 접근할 수 있다. 따라서 적절한 동기화가 필요하다. 이를테면 쓰기 작업 시 seq 번호를 부여해서 쓰기 순서도 * 맞춰야 한다. */ public class CommitLogFileChannel { // STATIC FUNCTIONS & VARIABLES private static final Log LOG = LogFactory.getLog(CommitLogFileChannel.class); private static ReentrantReadWriteLock mapLock = new ReentrantReadWriteLock(); private static HashMap<String, CommitLogFileChannel> channelMap = new HashMap<String, CommitLogFileChannel>(); private static FileChannelCullerThread fileChannelCuller; static { fileChannelCuller = new FileChannelCullerThread(); fileChannelCuller.setDaemon(true); fileChannelCuller.setName("FileChannelCuller"); fileChannelCuller.start(); } public static CommitLogFileChannel openChannel(String dirName, String path, String fileName) throws IOException { CommitLogFileChannel ch = null; String key = getLogFileName(dirName, fileName); mapLock.readLock().lock(); try { if ((ch = channelMap.get(key)) != null) { ch.numPipes.incrementAndGet(); return ch; } } finally { mapLock.readLock().unlock(); } mapLock.writeLock().lock(); try { if ((ch = channelMap.get(key)) == null) { LOG.debug("create file channel. dirName[" + dirName + "], fileName[" + fileName + "]"); ch = new CommitLogFileChannel(dirName, path, fileName); channelMap.put(key, ch); } } finally { ch.numPipes.incrementAndGet(); mapLock.writeLock().unlock(); } // by sangchul // all the threads which tried to make new instance should call this method // because of waiting for instance initialization. ch.init(); return ch; } public static void closeChannel(CommitLogFileChannel ch) throws IOException { mapLock.readLock().lock(); try { if (ch.numPipes.decrementAndGet() > 0) { return; } } finally { mapLock.readLock().unlock(); } String key = ch.logFileName; boolean close = false; mapLock.writeLock().lock(); try { if (ch.numPipes.get() <= 0) { LOG.debug("close file channel. key[" + key + "]"); channelMap.remove(key); close = true; } } finally { mapLock.writeLock().unlock(); if (close) { ch.internalClose(); } } } public static void backup(String dirName, String path, String fileName) throws IOException { CommitLogFileChannel ch = openChannel(dirName, path, fileName); try { ch.backup(); } finally { closeChannel(ch); } } public static long mark(String dirName, String path, String fileName) throws IOException { CommitLogFileChannel ch = openChannel(dirName, path, fileName); try { return ch.mark(); } finally { closeChannel(ch); } } public static void cancelLastMark(String dirName, String path, String fileName) throws IOException { CommitLogFileChannel ch = openChannel(dirName, path, fileName); try { ch.cancelLastMark(); } finally { closeChannel(ch); } } public static long readLastIndex(FileChannel ch) throws IOException { ByteBuffer buf = ByteBuffer.allocate(Long.SIZE / 8); long chSize = ch.size(); if (chSize > 0) { ch.position(chSize > (Long.SIZE / 8) ? chSize - (Long.SIZE / 8) : 0); ch.read(buf); buf.flip(); return buf.getLong(); } else { return 0; } } public static String getLogFileName(String dirName, String fileName) { return dirName + "_" + fileName; } public static String getIndexFileName(String dirName, String fileName) { return dirName + "_" + Constants.PIPE_IDX_FILE_NAME + "_" + fileName; } // MEMBER FUNCTIONS & VARIABLES FileChannel channel; FileChannel indexChannel; long rollbackIndex; final String indexFileFullPath; final String logFileFullPath; final String logFileName; final String dirName; final ByteBuffer lengthBuffer = ByteBuffer.allocate(4); final File parentDir; AtomicInteger numPipes = new AtomicInteger(0); ByteBuffer indexBuf = ByteBuffer.allocate(Long.SIZE / 8); private CommitLogFileChannel(String dirName, String path, String fileName) throws IOException { this.dirName = dirName; this.parentDir = new File(path); this.logFileName = getLogFileName(dirName, fileName); this.logFileFullPath = parentDir.getAbsolutePath() + File.separator + logFileName; this.indexFileFullPath = parentDir.getAbsolutePath() + File.separator + getIndexFileName(dirName, fileName); } synchronized void init() throws IOException { if (channel != null) { return; } FileOutputStream fos = null; //NStopWatch watch = new NStopWatch(); try { fos = new FileOutputStream(logFileFullPath, true); //watch.stopAndReportIfExceed(LOG); } catch (FileNotFoundException e) { if (parentDir.exists() == false && parentDir.mkdirs() == false && parentDir.exists() == false) { throw new IOException("Making directory to " + parentDir.getAbsolutePath() + " is fail"); } fos = new FileOutputStream(logFileFullPath, true); //watch.stopAndReportIfExceed(LOG); } channel = fos.getChannel(); fos = new FileOutputStream(indexFileFullPath, true); //watch.stopAndReportIfExceed(LOG); indexChannel = fos.getChannel(); numPipes.incrementAndGet(); fileChannelCuller.append(this); } public synchronized boolean isOpen() { if (channel == null) { return false; } return channel.isOpen(); } ByteBuffer headerBuf = ByteBuffer.allocate(4); private long lastActivity; public synchronized void write(ByteBuffer[] bufferArray) throws IOException { // by sangchul // check whether this CommitLogFileChannel is initialized or not. // If not, this thread should initialize the instance and then continue writing. // Or, it is possible for other thread to initialize the instance, and then // this thread should wait for the thread finishing initialization. init(); //NStopWatch watch = new NStopWatch(); //watch.start("actualWriting", 1000); try { headerBuf.putInt(getTotalLengthOf(bufferArray)); headerBuf.flip(); channel.write(headerBuf); headerBuf.clear(); channel.write(bufferArray); } catch(IOException e) { LOG.warn("fail to write log. full path [" + logFileFullPath + "]", e); internalClose(); throw e; } finally { //watch.stopAndReportIfExceed(LOG); lastActivity = System.currentTimeMillis(); } } private int getTotalLengthOf(ByteBuffer[] bufferArray) { int totalLength = 0; for (ByteBuffer buf : bufferArray) { totalLength += buf.limit(); } return totalLength; } private void internalClose() throws IOException { if (isOpen()) { channel.close(); channel = null; indexChannel.close(); indexChannel = null; } } public synchronized void removeFile() { try { internalClose(); } catch (IOException e) { LOG.warn("closing file before removing is fail", e); } File file = new File(logFileFullPath); if (file.exists()) { if (file.delete()) { LOG.info("commit log file [" + file.getPath() + "] is deleted"); } else { LOG.warn("tried to delete commit log file but it is NOT deleted."); } } else { LOG.info("attemped to remove file [" + file.getPath() + "], but not exists"); } } public synchronized long getFileSize() throws IOException { File file = new File(logFileFullPath); return file.length(); } private synchronized long mark() throws IOException { if (!isOpen()) { return -1; } long size = channel.size(); indexBuf.clear(); indexBuf.putLong(size); indexBuf.flip(); indexChannel.write(indexBuf); indexBuf.clear(); return size; } private synchronized void cancelLastMark() throws IOException { if (!isOpen()) { return; } try { channel.truncate(readLastIndex(indexChannel)); } catch(Exception e) { LOG.warn("Fail to truncate channel", e); } long pos = indexChannel.size() - Long.SIZE / 8; if (pos < 0) { pos = 0; } indexChannel.truncate(pos); } public synchronized void backup() throws IOException { long beforeClose = System.currentTimeMillis(); try { internalClose(); } catch (IOException e) { LOG.warn("closing file before backing up is fail", e); } long beforeRename = System.currentTimeMillis(); File file = new File(logFileFullPath); if (!file.renameTo(new File(parentDir, file.getName() + "_" + System.currentTimeMillis()))) { throw new IOException("fail to backup [" + file.getAbsolutePath() + "]"); } long beforeInit = System.currentTimeMillis(); init(); long finish = System.currentTimeMillis(); if ((finish - beforeInit) >= 100) { LOG.info("too long time to init : " + (finish - beforeInit) + "ms"); } else if ((beforeInit - beforeRename) >= 100) { LOG.info("too long time to rename : " + (beforeInit - beforeRename) + "ms"); } else if ((beforeRename - beforeClose) >= 100) { LOG.info("too long time to close : " + (beforeRename - beforeClose) + "ms"); } } public synchronized void restoreLastLog() throws IOException { try { internalClose(); } catch (IOException e) { LOG.warn("closing file in restoring file is fail", e); } File lastLogFile = null; long lastModified = 0l; if (parentDir.listFiles() != null) { for (File file : parentDir.listFiles()) { if (lastLogFile == null) { lastLogFile = file; continue; } if (lastModified < file.lastModified() && lastLogFile.getName().equals(logFileName) == false) { lastModified = file.lastModified(); lastLogFile = file; } } lastLogFile.renameTo(new File(parentDir, logFileName)); } init(); } public synchronized void removeBackupFiles() { File[] fileList = parentDir.listFiles(new FilenameFilter() { public boolean accept(File dir, String name) { return name.equals(logFileName) == false; } }); if (fileList != null) { for (File file : fileList) { LOG.info("remove backup file [" + file.getAbsolutePath() + "]"); if (!file.delete()) { LOG.warn("fail to remove backup file [" + file.getAbsolutePath() + "]"); } } } } public synchronized boolean isExpired() { return System.currentTimeMillis() - lastActivity > 30000; } } class FileChannelCullerThread extends Thread { private static final Log LOG = LogFactory.getLog(FileChannelCullerThread.class); LinkedList<CommitLogFileChannel> channelList = new LinkedList<CommitLogFileChannel>(); public void run() { while(true) { try { Thread.sleep(10000); } catch (InterruptedException e) { LOG.info("FileChannelCullerThread is done"); break; } ArrayList<CommitLogFileChannel> expiredList = new ArrayList<CommitLogFileChannel>(); synchronized(channelList) { Iterator<CommitLogFileChannel> iter = channelList.iterator(); while(iter.hasNext()) { CommitLogFileChannel ch = iter.next(); if (ch.isExpired()) { expiredList.add(ch); iter.remove(); } } } for(CommitLogFileChannel ch : expiredList) { try { CommitLogFileChannel.closeChannel(ch); } catch (IOException e) { LOG.warn("exception in file channel culler thread", e); } } } } public void append(CommitLogFileChannel ch) { synchronized(channelList) { channelList.addLast(ch); } } }
29.044776
102
0.647188
457859e4dd721a96c1c15f55e77cd83d9c4bde13
2,694
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.pimslims.crystallization.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.pimslims.dao.ReadableVersion; import org.pimslims.model.experiment.Instrument; /** * * @author ian */ public class ListImagersServlet extends XtalPIMSServlet { /** * */ private static final long serialVersionUID = 8821496942115654304L; /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request * servlet request * @param response * servlet response * @throws javax.servlet.ServletException * @throws java.io.IOException */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/json"); PrintWriter out = response.getWriter(); ReadableVersion version = this.getReadableVersion(request, response); try { JSONArray array = new JSONArray(); for (final Instrument instrument : version.getAll(Instrument.class, 0, 100)) { JSONObject obj = new JSONObject(); // location1.setId(instrument.getDbId()); obj.put("name", instrument.getName()); // location1.setPressure(instrument.getPressure()); obj.put("temperature", instrument.getTemperature()); array.add(obj); } JSONObject object = new JSONObject(); object.put("imagers", array); out.print(object); } finally { version.close(); } } // <editor-fold defaultstate="collapsed" // desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request * servlet request * @param response * servlet response */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request * servlet request * @param response * servlet response */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. */ public String getServletInfo() { return "Short description"; } // </editor-fold> }
26.411765
82
0.700074