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
33785512416d4208adc0152aae4f5d120eefdf01
16,637
/* * 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 Coltrol_Base; import Coltrol_Base.exceptions.IllegalOrphanException; import Coltrol_Base.exceptions.NonexistentEntityException; import Coltrol_Base.exceptions.PreexistingEntityException; import java.io.Serializable; import javax.persistence.Query; import javax.persistence.EntityNotFoundException; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Root; import Entidades_Base.Equipo; import Entidades_Base.Paises; import Entidades_Base.Gol; import Entidades_Base.Jugador; import Entidades_Base.JugadorPK; import java.util.ArrayList; import java.util.Collection; import Entidades_Base.Tarjeta; import java.math.BigDecimal; import java.util.List; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; /** * * @author danih */ public class JugadorJpaController implements Serializable { public JugadorJpaController(EntityManagerFactory emf) { this.emf = emf; } private EntityManagerFactory emf = null; public EntityManager getEntityManager() { return emf.createEntityManager(); } public void create(Jugador jugador) throws PreexistingEntityException, Exception { if (jugador.getJugadorPK() == null) { jugador.setJugadorPK(new JugadorPK()); } if (jugador.getGolCollection() == null) { jugador.setGolCollection(new ArrayList<Gol>()); } if (jugador.getTarjetaCollection() == null) { jugador.setTarjetaCollection(new ArrayList<Tarjeta>()); } BigDecimal idEq = jugador.getEquipo().getIdEquipo(); //---------------------------------------------------modifiqué esto -- dhas jugador.getJugadorPK().setEquipoIdEquipo(idEq.toBigInteger()); EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); Equipo equipo = jugador.getEquipo(); if (equipo != null) { equipo = em.getReference(equipo.getClass(), equipo.getIdEquipo()); jugador.setEquipo(equipo); } Paises lugarNacimiento = jugador.getLugarNacimiento(); if (lugarNacimiento != null) { lugarNacimiento = em.getReference(lugarNacimiento.getClass(), lugarNacimiento.getIdPais()); jugador.setLugarNacimiento(lugarNacimiento); } Collection<Gol> attachedGolCollection = new ArrayList<Gol>(); for (Gol golCollectionGolToAttach : jugador.getGolCollection()) { golCollectionGolToAttach = em.getReference(golCollectionGolToAttach.getClass(), golCollectionGolToAttach.getGolPK()); attachedGolCollection.add(golCollectionGolToAttach); } jugador.setGolCollection(attachedGolCollection); Collection<Tarjeta> attachedTarjetaCollection = new ArrayList<Tarjeta>(); for (Tarjeta tarjetaCollectionTarjetaToAttach : jugador.getTarjetaCollection()) { tarjetaCollectionTarjetaToAttach = em.getReference(tarjetaCollectionTarjetaToAttach.getClass(), tarjetaCollectionTarjetaToAttach.getTarjetaPK()); attachedTarjetaCollection.add(tarjetaCollectionTarjetaToAttach); } jugador.setTarjetaCollection(attachedTarjetaCollection); em.persist(jugador); if (equipo != null) { equipo.getJugadorCollection().add(jugador); equipo = em.merge(equipo); } if (lugarNacimiento != null) { lugarNacimiento.getJugadorCollection().add(jugador); lugarNacimiento = em.merge(lugarNacimiento); } for (Gol golCollectionGol : jugador.getGolCollection()) { Jugador oldJugadorOfGolCollectionGol = golCollectionGol.getJugador(); golCollectionGol.setJugador(jugador); golCollectionGol = em.merge(golCollectionGol); if (oldJugadorOfGolCollectionGol != null) { oldJugadorOfGolCollectionGol.getGolCollection().remove(golCollectionGol); oldJugadorOfGolCollectionGol = em.merge(oldJugadorOfGolCollectionGol); } } for (Tarjeta tarjetaCollectionTarjeta : jugador.getTarjetaCollection()) { Jugador oldJugadorOfTarjetaCollectionTarjeta = tarjetaCollectionTarjeta.getJugador(); tarjetaCollectionTarjeta.setJugador(jugador); tarjetaCollectionTarjeta = em.merge(tarjetaCollectionTarjeta); if (oldJugadorOfTarjetaCollectionTarjeta != null) { oldJugadorOfTarjetaCollectionTarjeta.getTarjetaCollection().remove(tarjetaCollectionTarjeta); oldJugadorOfTarjetaCollectionTarjeta = em.merge(oldJugadorOfTarjetaCollectionTarjeta); } } em.getTransaction().commit(); } catch (Exception ex) { if (findJugador(jugador.getJugadorPK()) != null) { throw new PreexistingEntityException("Jugador " + jugador + " already exists.", ex); } throw ex; } finally { if (em != null) { em.close(); } } } public void edit(Jugador jugador) throws IllegalOrphanException, NonexistentEntityException, Exception { BigDecimal idEq = jugador.getEquipo().getIdEquipo(); //---------------------------------------------------modifiqué esto -- dhas jugador.getJugadorPK().setEquipoIdEquipo(idEq.toBigInteger()); EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); Jugador persistentJugador = em.find(Jugador.class, jugador.getJugadorPK()); Equipo equipoOld = persistentJugador.getEquipo(); Equipo equipoNew = jugador.getEquipo(); Paises lugarNacimientoOld = persistentJugador.getLugarNacimiento(); Paises lugarNacimientoNew = jugador.getLugarNacimiento(); Collection<Gol> golCollectionOld = persistentJugador.getGolCollection(); Collection<Gol> golCollectionNew = jugador.getGolCollection(); Collection<Tarjeta> tarjetaCollectionOld = persistentJugador.getTarjetaCollection(); Collection<Tarjeta> tarjetaCollectionNew = jugador.getTarjetaCollection(); List<String> illegalOrphanMessages = null; for (Gol golCollectionOldGol : golCollectionOld) { if (!golCollectionNew.contains(golCollectionOldGol)) { if (illegalOrphanMessages == null) { illegalOrphanMessages = new ArrayList<String>(); } illegalOrphanMessages.add("You must retain Gol " + golCollectionOldGol + " since its jugador field is not nullable."); } } for (Tarjeta tarjetaCollectionOldTarjeta : tarjetaCollectionOld) { if (!tarjetaCollectionNew.contains(tarjetaCollectionOldTarjeta)) { if (illegalOrphanMessages == null) { illegalOrphanMessages = new ArrayList<String>(); } illegalOrphanMessages.add("You must retain Tarjeta " + tarjetaCollectionOldTarjeta + " since its jugador field is not nullable."); } } if (illegalOrphanMessages != null) { throw new IllegalOrphanException(illegalOrphanMessages); } if (equipoNew != null) { equipoNew = em.getReference(equipoNew.getClass(), equipoNew.getIdEquipo()); jugador.setEquipo(equipoNew); } if (lugarNacimientoNew != null) { lugarNacimientoNew = em.getReference(lugarNacimientoNew.getClass(), lugarNacimientoNew.getIdPais()); jugador.setLugarNacimiento(lugarNacimientoNew); } Collection<Gol> attachedGolCollectionNew = new ArrayList<Gol>(); for (Gol golCollectionNewGolToAttach : golCollectionNew) { golCollectionNewGolToAttach = em.getReference(golCollectionNewGolToAttach.getClass(), golCollectionNewGolToAttach.getGolPK()); attachedGolCollectionNew.add(golCollectionNewGolToAttach); } golCollectionNew = attachedGolCollectionNew; jugador.setGolCollection(golCollectionNew); Collection<Tarjeta> attachedTarjetaCollectionNew = new ArrayList<Tarjeta>(); for (Tarjeta tarjetaCollectionNewTarjetaToAttach : tarjetaCollectionNew) { tarjetaCollectionNewTarjetaToAttach = em.getReference(tarjetaCollectionNewTarjetaToAttach.getClass(), tarjetaCollectionNewTarjetaToAttach.getTarjetaPK()); attachedTarjetaCollectionNew.add(tarjetaCollectionNewTarjetaToAttach); } tarjetaCollectionNew = attachedTarjetaCollectionNew; jugador.setTarjetaCollection(tarjetaCollectionNew); jugador = em.merge(jugador); if (equipoOld != null && !equipoOld.equals(equipoNew)) { equipoOld.getJugadorCollection().remove(jugador); equipoOld = em.merge(equipoOld); } if (equipoNew != null && !equipoNew.equals(equipoOld)) { equipoNew.getJugadorCollection().add(jugador); equipoNew = em.merge(equipoNew); } if (lugarNacimientoOld != null && !lugarNacimientoOld.equals(lugarNacimientoNew)) { lugarNacimientoOld.getJugadorCollection().remove(jugador); lugarNacimientoOld = em.merge(lugarNacimientoOld); } if (lugarNacimientoNew != null && !lugarNacimientoNew.equals(lugarNacimientoOld)) { lugarNacimientoNew.getJugadorCollection().add(jugador); lugarNacimientoNew = em.merge(lugarNacimientoNew); } for (Gol golCollectionNewGol : golCollectionNew) { if (!golCollectionOld.contains(golCollectionNewGol)) { Jugador oldJugadorOfGolCollectionNewGol = golCollectionNewGol.getJugador(); golCollectionNewGol.setJugador(jugador); golCollectionNewGol = em.merge(golCollectionNewGol); if (oldJugadorOfGolCollectionNewGol != null && !oldJugadorOfGolCollectionNewGol.equals(jugador)) { oldJugadorOfGolCollectionNewGol.getGolCollection().remove(golCollectionNewGol); oldJugadorOfGolCollectionNewGol = em.merge(oldJugadorOfGolCollectionNewGol); } } } for (Tarjeta tarjetaCollectionNewTarjeta : tarjetaCollectionNew) { if (!tarjetaCollectionOld.contains(tarjetaCollectionNewTarjeta)) { Jugador oldJugadorOfTarjetaCollectionNewTarjeta = tarjetaCollectionNewTarjeta.getJugador(); tarjetaCollectionNewTarjeta.setJugador(jugador); tarjetaCollectionNewTarjeta = em.merge(tarjetaCollectionNewTarjeta); if (oldJugadorOfTarjetaCollectionNewTarjeta != null && !oldJugadorOfTarjetaCollectionNewTarjeta.equals(jugador)) { oldJugadorOfTarjetaCollectionNewTarjeta.getTarjetaCollection().remove(tarjetaCollectionNewTarjeta); oldJugadorOfTarjetaCollectionNewTarjeta = em.merge(oldJugadorOfTarjetaCollectionNewTarjeta); } } } em.getTransaction().commit(); } catch (Exception ex) { String msg = ex.getLocalizedMessage(); if (msg == null || msg.length() == 0) { JugadorPK id = jugador.getJugadorPK(); if (findJugador(id) == null) { throw new NonexistentEntityException("The jugador with id " + id + " no longer exists."); } } throw ex; } finally { if (em != null) { em.close(); } } } public void destroy(JugadorPK id) throws IllegalOrphanException, NonexistentEntityException { EntityManager em = null; try { em = getEntityManager(); em.getTransaction().begin(); Jugador jugador; try { jugador = em.getReference(Jugador.class, id); jugador.getJugadorPK(); } catch (EntityNotFoundException enfe) { throw new NonexistentEntityException("The jugador with id " + id + " no longer exists.", enfe); } List<String> illegalOrphanMessages = null; Collection<Gol> golCollectionOrphanCheck = jugador.getGolCollection(); for (Gol golCollectionOrphanCheckGol : golCollectionOrphanCheck) { if (illegalOrphanMessages == null) { illegalOrphanMessages = new ArrayList<String>(); } illegalOrphanMessages.add("This Jugador (" + jugador + ") cannot be destroyed since the Gol " + golCollectionOrphanCheckGol + " in its golCollection field has a non-nullable jugador field."); } Collection<Tarjeta> tarjetaCollectionOrphanCheck = jugador.getTarjetaCollection(); for (Tarjeta tarjetaCollectionOrphanCheckTarjeta : tarjetaCollectionOrphanCheck) { if (illegalOrphanMessages == null) { illegalOrphanMessages = new ArrayList<String>(); } illegalOrphanMessages.add("This Jugador (" + jugador + ") cannot be destroyed since the Tarjeta " + tarjetaCollectionOrphanCheckTarjeta + " in its tarjetaCollection field has a non-nullable jugador field."); } if (illegalOrphanMessages != null) { throw new IllegalOrphanException(illegalOrphanMessages); } Equipo equipo = jugador.getEquipo(); if (equipo != null) { equipo.getJugadorCollection().remove(jugador); equipo = em.merge(equipo); } Paises lugarNacimiento = jugador.getLugarNacimiento(); if (lugarNacimiento != null) { lugarNacimiento.getJugadorCollection().remove(jugador); lugarNacimiento = em.merge(lugarNacimiento); } em.remove(jugador); em.getTransaction().commit(); } finally { if (em != null) { em.close(); } } } public List<Jugador> findJugadorEntities() { return findJugadorEntities(true, -1, -1); } public List<Jugador> findJugadorEntities(int maxResults, int firstResult) { return findJugadorEntities(false, maxResults, firstResult); } private List<Jugador> findJugadorEntities(boolean all, int maxResults, int firstResult) { EntityManager em = getEntityManager(); try { CriteriaQuery cq = em.getCriteriaBuilder().createQuery(); cq.select(cq.from(Jugador.class)); Query q = em.createQuery(cq); if (!all) { q.setMaxResults(maxResults); q.setFirstResult(firstResult); } return q.getResultList(); } finally { em.close(); } } public Jugador findJugador(JugadorPK id) { EntityManager em = getEntityManager(); try { return em.find(Jugador.class, id); } finally { em.close(); } } public int getJugadorCount() { EntityManager em = getEntityManager(); try { CriteriaQuery cq = em.getCriteriaBuilder().createQuery(); Root<Jugador> rt = cq.from(Jugador.class); cq.select(em.getCriteriaBuilder().count(rt)); Query q = em.createQuery(cq); return ((Long) q.getSingleResult()).intValue(); } finally { em.close(); } } }
49.811377
224
0.605037
46fb9e38d85df9397977cd135e8fa986e97ea99b
3,886
/* * 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.aliyuncs.sofa.transform.v20190815; import java.util.ArrayList; import java.util.List; import com.aliyuncs.sofa.model.v20190815.QueryLinkefabricFabricMsgbinginginfoResponse; import com.aliyuncs.sofa.model.v20190815.QueryLinkefabricFabricMsgbinginginfoResponse.DataItem; import com.aliyuncs.transform.UnmarshallerContext; public class QueryLinkefabricFabricMsgbinginginfoResponseUnmarshaller { public static QueryLinkefabricFabricMsgbinginginfoResponse unmarshall(QueryLinkefabricFabricMsgbinginginfoResponse queryLinkefabricFabricMsgbinginginfoResponse, UnmarshallerContext _ctx) { queryLinkefabricFabricMsgbinginginfoResponse.setRequestId(_ctx.stringValue("QueryLinkefabricFabricMsgbinginginfoResponse.RequestId")); queryLinkefabricFabricMsgbinginginfoResponse.setResultCode(_ctx.stringValue("QueryLinkefabricFabricMsgbinginginfoResponse.ResultCode")); queryLinkefabricFabricMsgbinginginfoResponse.setResultMessage(_ctx.stringValue("QueryLinkefabricFabricMsgbinginginfoResponse.ResultMessage")); queryLinkefabricFabricMsgbinginginfoResponse.setMessage(_ctx.stringValue("QueryLinkefabricFabricMsgbinginginfoResponse.Message")); queryLinkefabricFabricMsgbinginginfoResponse.setResponseStatusCode(_ctx.longValue("QueryLinkefabricFabricMsgbinginginfoResponse.ResponseStatusCode")); queryLinkefabricFabricMsgbinginginfoResponse.setSuccess(_ctx.booleanValue("QueryLinkefabricFabricMsgbinginginfoResponse.Success")); List<DataItem> data = new ArrayList<DataItem>(); for (int i = 0; i < _ctx.lengthValue("QueryLinkefabricFabricMsgbinginginfoResponse.Data.Length"); i++) { DataItem dataItem = new DataItem(); dataItem.setAction(_ctx.stringValue("QueryLinkefabricFabricMsgbinginginfoResponse.Data["+ i +"].Action")); dataItem.setAppName(_ctx.stringValue("QueryLinkefabricFabricMsgbinginginfoResponse.Data["+ i +"].AppName")); dataItem.setClusterName(_ctx.stringValue("QueryLinkefabricFabricMsgbinginginfoResponse.Data["+ i +"].ClusterName")); dataItem.setEventcode(_ctx.stringValue("QueryLinkefabricFabricMsgbinginginfoResponse.Data["+ i +"].Eventcode")); dataItem.setExchangeType(_ctx.stringValue("QueryLinkefabricFabricMsgbinginginfoResponse.Data["+ i +"].ExchangeType")); dataItem.setExpression(_ctx.stringValue("QueryLinkefabricFabricMsgbinginginfoResponse.Data["+ i +"].Expression")); dataItem.setFilterType(_ctx.stringValue("QueryLinkefabricFabricMsgbinginginfoResponse.Data["+ i +"].FilterType")); dataItem.setFilterValue(_ctx.stringValue("QueryLinkefabricFabricMsgbinginginfoResponse.Data["+ i +"].FilterValue")); dataItem.setGroup(_ctx.stringValue("QueryLinkefabricFabricMsgbinginginfoResponse.Data["+ i +"].Group")); dataItem.setPersistence(_ctx.booleanValue("QueryLinkefabricFabricMsgbinginginfoResponse.Data["+ i +"].Persistence")); dataItem.setRoomInfo(_ctx.stringValue("QueryLinkefabricFabricMsgbinginginfoResponse.Data["+ i +"].RoomInfo")); dataItem.setTopic(_ctx.stringValue("QueryLinkefabricFabricMsgbinginginfoResponse.Data["+ i +"].Topic")); dataItem.setZoneInfo(_ctx.stringValue("QueryLinkefabricFabricMsgbinginginfoResponse.Data["+ i +"].ZoneInfo")); data.add(dataItem); } queryLinkefabricFabricMsgbinginginfoResponse.setData(data); return queryLinkefabricFabricMsgbinginginfoResponse; } }
65.864407
189
0.818065
fab1bd51c2bc972f2dfbb88db1a5e47f949d6d5f
1,790
package lesson.eventlistener.panel; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import javax.swing.JFrame; public class GameWindow extends JFrame implements KeyListener { private static GamePanel gamePanel; /** * */ private static final long serialVersionUID = 3706026480807280471L; public GameWindow() { /* * Adds a component JPanel to the JFrame. We will do the painting on this. You * can add other components like buttons and panels to this. But lets start with * just a panel. */ add(gamePanel = new GamePanel()); // Sets so that the window do not have any borders. setUndecorated(true); // Sets so that we can't change the size off the window. setResizable(false); // Lets set it on top of everything like games generally are. setAlwaysOnTop(true); // Add's the listeners needed to change the window. addKeyListener(this); addKeyListener(gamePanel); /* * Causes this Window to be sized to fit the preferred size and layouts of its * subcomponents. */ pack(); // Shows or hides this Window. setVisible(true); } @Override public void keyPressed(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_ESCAPE) { /* * Write to the terminal if we press the esc button and then close the program * using id 0 saying that the closing of the program went well and natural. * Sometimes when u use get an error you want to close the program in this case * use the id 1. There are many more id's but I'm not going to go through it. */ System.out.println("Exit program!"); System.exit(0); } } @Override public void keyReleased(KeyEvent e) { // TODO Auto-generated method stub } @Override public void keyTyped(KeyEvent e) { // TODO Auto-generated method stub } }
25.942029
82
0.705587
c6f69e9f6c0073c1cd5ecada4f1941bbbca6f5f0
567
package application; import com.google.common.collect.ImmutableSet; import java.util.Set; import static application.Stage.LOCAL; public class Config { public static Stage stage = LOCAL; public static final float MIN_NET_WORTH = 25000; public static final float MAX_INFLUENCED_BUY = 3000; public static final Set<String> TWITCH_CHANNELS = ImmutableSet.of("#stockstream", "#moneytesting"); public static final String RH_UN = System.getenv("ROBINHOOD_USERNAME"); public static final String RH_PW = System.getenv("ROBINHOOD_PASSWORD"); }
25.772727
103
0.758377
8a4736b65ab15d8659834e59d37c520130d7e533
7,784
package seedu.deliverymans.model.database; import static java.util.Objects.requireNonNull; import static seedu.deliverymans.model.deliveryman.deliverymanstatus.UniqueStatusList.DELIVERING_STATUS; import java.util.List; import javafx.collections.ObservableList; import seedu.deliverymans.model.Name; import seedu.deliverymans.model.deliveryman.Deliveryman; import seedu.deliverymans.model.deliveryman.UniqueDeliverymanList; import seedu.deliverymans.model.deliveryman.deliverymanstatistics.StatisticsManager; import seedu.deliverymans.model.deliveryman.deliverymanstatistics.StatisticsRecordCard; import seedu.deliverymans.model.deliveryman.deliverymanstatus.StatusManager; import seedu.deliverymans.model.deliveryman.exceptions.InvalidStatusChangeException; import seedu.deliverymans.model.deliveryman.exceptions.NoMoreAvailableDeliverymanException; import seedu.deliverymans.model.deliveryman.exceptions.UnableToDeleteDeliveringDeliverymanException; /** * Wraps all Deliverymen data at the deliverymen-database level * Duplicates are not allowed (by .isSameDeliveryman comparison) */ public class DeliverymenDatabase implements ReadOnlyDeliverymenDatabase { private final UniqueDeliverymanList deliverymen; private final StatusManager statusManager; private final StatisticsManager statisticsManager; { deliverymen = new UniqueDeliverymanList(); statusManager = new StatusManager(); statisticsManager = new StatisticsManager(); } public DeliverymenDatabase() { } /** * Creates a DeliverymenDatabase using the Deliverymen in the {@code toBeCopied} */ public DeliverymenDatabase(ReadOnlyDeliverymenDatabase toBeCopied) { this(); resetData(toBeCopied); } /** * Replaces the contents of the deliverymen list with {@code deliverymen}. * {@code deliverymen} must not contain duplicate deliverymen. */ public void setDeliverymen(List<Deliveryman> deliverymen) { this.deliverymen.setDeliverymen(deliverymen); } /** * Resets the existing data of this {@code DeliverymenDatabase} with {@code newData}. */ public void resetData(ReadOnlyDeliverymenDatabase newData) { requireNonNull(newData); setDeliverymen(newData.getDeliverymenList()); statusManager.initStatusLists(deliverymen); } // ========== Basic functions related to deliverymen ========================================================== /** * Returns true if a deliveryman with the same identity as {@code deliveryman} exists in the deliverymen database. */ public boolean hasDeliveryman(Deliveryman man) { requireNonNull(man); return deliverymen.contains(man); } /** * Adds a deliveryman to the deliverymen database. * The deliveryman must not already exist in the deliverymen database. */ public void addDeliveryman(Deliveryman man) { deliverymen.add(man); statusManager.addUnavailableMan(man); } /** * Replaces the given deliveryman {@code target} in the list with {@code editedDeliveryman}. * {@code target} must exist in the deliveryman database. * The deliveryman identity of {@code editedDeliveryman} must not be the same as another existing deliveryman in the * deliverymen database. */ public void setDeliveryman(Deliveryman target, Deliveryman editedDeliveryman) { requireNonNull(editedDeliveryman); deliverymen.setDeliveryman(target, editedDeliveryman); statusManager.removeDeliveryman(target); statusManager.addUnavailableMan(editedDeliveryman); statusManager.updateStatusOf(editedDeliveryman, target.getStatus().getDescription()); } /** * Removes {@code key} from this {@code DeliverymenDatabase}. * {@code key} must exist in the deliverymen database. */ public void removeDeliveryman(Deliveryman key) throws UnableToDeleteDeliveringDeliverymanException { if (key.getStatus().getDescription().equals(DELIVERING_STATUS)) { throw new UnableToDeleteDeliveringDeliverymanException(); } deliverymen.remove(key); statusManager.removeDeliveryman(key); } // ========= Methods related to lists command ================================================================= /** * Lists all the available deliverymen; */ public ObservableList<Deliveryman> getAvailableDeliverymenList() { return statusManager.listAvailableMen(); } /** * Lists all the delivering deliverymen. */ public ObservableList<Deliveryman> getDeliveringDeliverymenList() { return statusManager.listDeliveringMen(); } /** * Lists all the unavailable deliverymen. */ public ObservableList<Deliveryman> getUnavailableDeliverymenList() { return statusManager.listUnavailableMen(); } // ========== Methods related to Order ==================================================================== /** * Retrieves the name of an available deliveryman for OrderManager for the purpose of delivering an order. */ public Name getAvailableDeliveryman() throws NoMoreAvailableDeliverymanException { Deliveryman target = statusManager.getAvailableDeliveryman(); Deliveryman editedDeliveryman = statusManager.orderAssigned(target); deliverymen.setDeliveryman(target, editedDeliveryman); return editedDeliveryman.getName(); } /** * Updates the deliveryman status to be AVAILABLE after there is changes to an order * (ie. completed or deleted an order). */ public void updateDeliverymanStatusAfterChangesToOrder(Name name) { getDeliverymenList().stream() .filter(d -> d.getName().equals(name)) .findAny() .ifPresent(deliveryman -> deliverymen.setDeliveryman(deliveryman, statusManager.updateDeliverymanStatusAfterChangesToOrder(deliveryman))); } /** * Switches the deliveryman status from AVAILABLE to UNAVAILABLE, or vice versa. */ public Deliveryman switchDeliverymanStatus(Deliveryman target) throws InvalidStatusChangeException { Deliveryman editedDeliveryman = statusManager.switchDeliverymanStatus(target); deliverymen.setDeliveryman(target, editedDeliveryman); return editedDeliveryman; } // ========== Methods related to Statistics ================================================================ /** * Analyzes the status lists to compute statistics regarding the current status of deliverymen. * Passes the status lists from status manager to statistics manager to do analysis. * @return StatisticsRecordCard with the computed analysis and statistics */ public StatisticsRecordCard analyzeDeliverymenStatus() { return statisticsManager.analyzeStatusLists(statusManager.listAvailableMen(), statusManager.listUnavailableMen(), statusManager.listDeliveringMen()); } // ========== util methods ================================================================================= @Override public String toString() { return deliverymen.asUnmodifiableObservableList().size() + " deliverymen"; } @Override public ObservableList<Deliveryman> getDeliverymenList() { return deliverymen.asUnmodifiableObservableList(); } @Override public boolean equals(Object other) { return other == this || (other instanceof DeliverymenDatabase && deliverymen.equals(((DeliverymenDatabase) other).deliverymen)); } @Override public int hashCode() { return deliverymen.hashCode(); } }
38.534653
120
0.682939
49f7ab9e76ac0f582af65de0d6c6f014a0ffbdf4
3,220
/* * Copyright (c) 2014, Cloudera, Inc. All Rights Reserved. * * Cloudera, Inc. 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 * * This software 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.cloudera.oryx.common.math; import java.util.Collection; import org.apache.commons.math3.linear.Array2DRowRealMatrix; import org.apache.commons.math3.linear.RealMatrix; import org.apache.commons.math3.random.RandomGenerator; /** * Utility class with simple vector-related operations. */ public final class VectorMath { private VectorMath() {} /** * @return dot product of the two given arrays * @param x one array * @param y the other array */ public static double dot(float[] x, float[] y) { int length = x.length; double dot = 0.0; for (int i = 0; i < length; i++) { dot += x[i] * y[i]; } return dot; } /** * @param x vector for whom norm to be calculated * @return the L2 norm of vector x */ public static double norm(float[] x) { double total = 0.0; for (float f : x) { total += f * f; } return Math.sqrt(total); } /** * @param x vector for whom norm to be calculated * @return the L2 norm of vector x */ public static double norm(double[] x) { double total = 0.0; for (double d : x) { total += d * d; } return Math.sqrt(total); } /** * @param M tall, skinny matrix * @return MT * M as a dense matrix */ public static RealMatrix transposeTimesSelf(Collection<float[]> M) { if (M == null || M.isEmpty()) { return null; } int features = 0; RealMatrix result = null; for (float[] vector : M) { if (result == null) { features = vector.length; result = new Array2DRowRealMatrix(features, features); } for (int row = 0; row < features; row++) { float rowValue = vector[row]; for (int col = 0; col < features; col++) { result.addToEntry(row, col, rowValue * vector[col]); } } } return result; } /** * @param values numeric values as {@link String}s * @return values parsed as {@code double[]} */ public static double[] parseVector(String[] values) { double[] doubles = new double[values.length]; for (int i = 0; i < values.length; i++) { doubles[i] = Double.parseDouble(values[i]); } return doubles; } /** * @param features dimension of vector * @param random random number generator * @return vector whose direction from the origin is chosen uniformly at random, but which is not normalized */ public static float[] randomVectorF(int features, RandomGenerator random) { float[] vector = new float[features]; for (int i = 0; i < features; i++) { vector[i] = (float) random.nextGaussian(); } return vector; } }
27.058824
110
0.626087
1ed65b5a5ccf6d0a556eaedc88f4b61d6e414c84
6,175
package ca.corefacility.bioinformatics.irida.security.permissions.metadata; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.stereotype.Component; import ca.corefacility.bioinformatics.irida.model.enums.ProjectMetadataRole; import ca.corefacility.bioinformatics.irida.model.joins.impl.ProjectUserJoin; import ca.corefacility.bioinformatics.irida.model.project.Project; import ca.corefacility.bioinformatics.irida.model.sample.MetadataTemplateField; import ca.corefacility.bioinformatics.irida.model.sample.metadata.MetadataEntry; import ca.corefacility.bioinformatics.irida.model.sample.metadata.MetadataRestriction; import ca.corefacility.bioinformatics.irida.model.sample.metadata.ProjectMetadataResponse; import ca.corefacility.bioinformatics.irida.model.user.Role; import ca.corefacility.bioinformatics.irida.model.user.User; import ca.corefacility.bioinformatics.irida.model.user.group.UserGroupProjectJoin; import ca.corefacility.bioinformatics.irida.repositories.joins.project.ProjectUserJoinRepository; import ca.corefacility.bioinformatics.irida.repositories.joins.project.UserGroupProjectJoinRepository; import ca.corefacility.bioinformatics.irida.repositories.sample.MetadataRestrictionRepository; import ca.corefacility.bioinformatics.irida.repositories.user.UserRepository; import ca.corefacility.bioinformatics.irida.security.permissions.BasePermission; /** * Permission for checking that a user should have access to the given {@link MetadataTemplateField}s in a * {@link ProjectMetadataResponse}. This will check the user's role on the project and whether they're in a group. */ @Component public class ReadProjectMetadataResponsePermission implements BasePermission<ProjectMetadataResponse> { public static final String PERMISSION_PROVIDED = "readProjectMetadataResponse"; private UserRepository userRepository; private ProjectUserJoinRepository projectUserJoinRepository; private UserGroupProjectJoinRepository userGroupProjectJoinRepository; private MetadataRestrictionRepository metadataRestrictionRepository; @Autowired public ReadProjectMetadataResponsePermission(UserRepository userRepository, ProjectUserJoinRepository projectUserJoinRepository, UserGroupProjectJoinRepository userGroupProjectJoinRepository, MetadataRestrictionRepository metadataRestrictionRepository) { this.userRepository = userRepository; this.projectUserJoinRepository = projectUserJoinRepository; this.userGroupProjectJoinRepository = userGroupProjectJoinRepository; this.metadataRestrictionRepository = metadataRestrictionRepository; } @Override public String getPermissionProvided() { return PERMISSION_PROVIDED; } @Override public boolean isAllowed(Authentication authentication, Object targetDomainObject) { //ensure the object we're checking is a ProjectMetadataResponse if (!(targetDomainObject instanceof ProjectMetadataResponse)) { throw new IllegalArgumentException( "Object is not a ProjectMetadataResponse: " + targetDomainObject.getClass()); } ProjectMetadataResponse metadataResponse = (ProjectMetadataResponse) targetDomainObject; //get the user & project User user = userRepository.loadUserByUsername(authentication.getName()); Project project = metadataResponse.getProject(); //get the user's role on the project and check if they're in a group ProjectUserJoin projectJoinForUser = projectUserJoinRepository.getProjectJoinForUser(project, user); List<UserGroupProjectJoin> groupsForProjectAndUser = userGroupProjectJoinRepository.findGroupsForProjectAndUser( project, user); //find the maxiumum metadata role for the user on the project between the user and group permissions ProjectMetadataRole userProjectRole = ProjectMetadataRole.getMaxRoleForProjectAndGroups(projectJoinForUser, groupsForProjectAndUser); //if the user isn't on the project but is an admin, treat them as a project owner if (userProjectRole == null && user.getSystemRole() .equals(Role.ROLE_ADMIN)) { userProjectRole = ProjectMetadataRole.LEVEL_4; } //if the role is _still_ null, then they're not allowed to read if (userProjectRole == null) { return false; } //get the metadata restrictions on the project List<MetadataRestriction> restrictionForProject = metadataRestrictionRepository.getRestrictionForProject( project); Map<MetadataTemplateField, MetadataRestriction> restrictionMap = restrictionForProject.stream() .collect(Collectors.toMap(MetadataRestriction::getField, field -> field)); //go through the metadata being returned and get a distinct collection of the fields Map<Long, Set<MetadataEntry>> metadata = metadataResponse.getMetadata(); Set<MetadataTemplateField> fields = new HashSet<>(); for (Set<MetadataEntry> entries : metadata.values()) { for (MetadataEntry entry : entries) { fields.add(entry.getField()); } } /* * for each field check if the set of fields contain any they shouldn't be able to read. * this will return true if the user is allowed to read all the fields in the set. */ final ProjectMetadataRole finalUserProjectRole = userProjectRole; //need a final copy of this role because its being used in the lambda below boolean allFieldsValid = fields.stream() .filter(field -> { //if we have a restriction on a field, compare it against the user's role on the project if (restrictionMap.containsKey(field)) { MetadataRestriction metadataRestriction = restrictionMap.get(field); ProjectMetadataRole restrictionRole = metadataRestriction.getLevel(); /* * Compare the restriction level to the user's role. If user's role is less, return the unauthorized field. */ return finalUserProjectRole.getLevel() < restrictionRole.getLevel(); } else { //if there's no restriction set for the field, all users can view return false; } }) .findAny() .isEmpty(); return allFieldsValid; } }
45.404412
143
0.804211
c22bb7ce767e3a7d16abeba14cbd4846e4b452ad
1,886
/* By: facug91 From: http://coj.uci.cu/24h/problem.xhtml?abb=1136 Name: Prime Generator Number: 1136 Date: 05/10/2013 */ import java.util.ArrayList; import java.util.Scanner; public class Main { public static void main (String[] args) { Scanner stdin = new Scanner(System.in); int t = stdin.nextInt(); boolean[] daux = new boolean[32001]; //raiz cuadrada de mil millones + 1 ArrayList<Integer> d = new ArrayList<Integer>(); for (int n=3; n<=179; n+=2) { //178 raiz cuadrada de 31622 if (!daux[n]) { for (int p=n*3; p<=32000; p+=n*2) { daux[p] = true; } } } for (int i=3; i<32000; i+=2){ if (!daux[i]) d.add(i); } for (int i=0; i<t; i++) { int originalBegin = stdin.nextInt(); int begin = originalBegin; if (originalBegin % 2 == 0) //guarda el ingreso original, pero si es par lo incrementa begin = originalBegin + 1; if (begin == 1) //si el ingreso original era 1, lo pasa a 3 begin = 3; int end = stdin.nextInt(); int dif = end - begin; int sqrt = (int) Math.sqrt(end) + 1; boolean[] primo = new boolean[dif+1]; int ind = 0; int act; while (d.get(ind) <= sqrt) { act = d.get(ind); if ((begin%act == 0) && (begin != act)) { for (int l=begin; l<=end; l+=act) { primo[l - begin] = true; } } else { if (begin < act) { for (int l=(begin+(act-(begin%act)+act)); l<=end; l+=act) { primo[l - begin] = true; } } else { for (int l=(begin+(act-(begin%act))); l<=end; l+=act) { primo[l - begin] = true; } } } ind++; } if ((originalBegin == 1) || (originalBegin == 2)) { System.out.println("2"); } for (int m=begin; m<=end; m+=2) { if (!primo[m-begin]) { System.out.println(m); } } System.out.println(); } stdin.close(); } }
21.191011
89
0.532874
d6d39dbab650f5b65d6f1947aa778142e9a558b2
732
package com.github.lesach.client.engine.json; import com.github.lesach.client.DOrderTime; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.deser.std.StdDeserializer; import java.io.IOException; public class DOrderTimeDeserializer extends StdDeserializer<DOrderTime> { public DOrderTimeDeserializer() { super(DOrderTime.class); } @Override public DOrderTime deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { return DConvert.getDOrderTime(jp.readValueAs(String.class)); } }
33.272727
77
0.788251
69a2ebadc67e4d686f6e25fb5cf3984e9dbccd4b
875
package com.eu.habbo.messages.incoming.rooms; import com.eu.habbo.Emulator; import com.eu.habbo.habbohotel.achievements.AchievementManager; import com.eu.habbo.habbohotel.rooms.Room; import com.eu.habbo.messages.incoming.MessageHandler; import com.eu.habbo.messages.outgoing.rooms.RoomFilterWordsComposer; public class RequestRoomWordFilterEvent extends MessageHandler { @Override public void handle() throws Exception { Room room = Emulator.getGameEnvironment().getRoomManager().getRoom(this.packet.readInt()); if(room != null && room.hasRights(this.client.getHabbo())) { this.client.sendResponse(new RoomFilterWordsComposer(room)); AchievementManager.progressAchievement(this.client.getHabbo(), Emulator.getGameEnvironment().getAchievementManager().getAchievement("SelfModRoomFilterSeen")); } } }
36.458333
170
0.752
500a1ecd631a652b8736639854149025ed0a6f34
6,392
package net.minecraft.block.state; import com.google.common.collect.Lists; import java.util.List; import net.minecraft.block.Block; import net.minecraft.block.BlockPistonBase; import net.minecraft.block.material.Material; import net.minecraft.init.Blocks; import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.world.World; public class BlockPistonStructureHelper { private final World field_177261_a; private final BlockPos field_177259_b; private final BlockPos field_177260_c; private final EnumFacing field_177257_d; private final List<BlockPos> field_177258_e = Lists.<BlockPos>newArrayList(); private final List<BlockPos> field_177256_f = Lists.<BlockPos>newArrayList(); public BlockPistonStructureHelper(World p_i45664_1_, BlockPos p_i45664_2_, EnumFacing p_i45664_3_, boolean p_i45664_4_) { this.field_177261_a = p_i45664_1_; this.field_177259_b = p_i45664_2_; if(p_i45664_4_) { this.field_177257_d = p_i45664_3_; this.field_177260_c = p_i45664_2_.func_177972_a(p_i45664_3_); } else { this.field_177257_d = p_i45664_3_.func_176734_d(); this.field_177260_c = p_i45664_2_.func_177967_a(p_i45664_3_, 2); } } public boolean func_177253_a() { this.field_177258_e.clear(); this.field_177256_f.clear(); Block block = this.field_177261_a.func_180495_p(this.field_177260_c).func_177230_c(); if(!BlockPistonBase.func_180696_a(block, this.field_177261_a, this.field_177260_c, this.field_177257_d, false)) { if(block.func_149656_h() != 1) { return false; } else { this.field_177256_f.add(this.field_177260_c); return true; } } else if(!this.func_177251_a(this.field_177260_c)) { return false; } else { for(int i = 0; i < this.field_177258_e.size(); ++i) { BlockPos blockpos = (BlockPos)this.field_177258_e.get(i); if(this.field_177261_a.func_180495_p(blockpos).func_177230_c() == Blocks.field_180399_cE && !this.func_177250_b(blockpos)) { return false; } } return true; } } private boolean func_177251_a(BlockPos p_177251_1_) { Block block = this.field_177261_a.func_180495_p(p_177251_1_).func_177230_c(); if(block.func_149688_o() == Material.field_151579_a) { return true; } else if(!BlockPistonBase.func_180696_a(block, this.field_177261_a, p_177251_1_, this.field_177257_d, false)) { return true; } else if(p_177251_1_.equals(this.field_177259_b)) { return true; } else if(this.field_177258_e.contains(p_177251_1_)) { return true; } else { int i = 1; if(i + this.field_177258_e.size() > 12) { return false; } else { while(block == Blocks.field_180399_cE) { BlockPos blockpos = p_177251_1_.func_177967_a(this.field_177257_d.func_176734_d(), i); block = this.field_177261_a.func_180495_p(blockpos).func_177230_c(); if(block.func_149688_o() == Material.field_151579_a || !BlockPistonBase.func_180696_a(block, this.field_177261_a, blockpos, this.field_177257_d, false) || blockpos.equals(this.field_177259_b)) { break; } ++i; if(i + this.field_177258_e.size() > 12) { return false; } } int i1 = 0; for(int j = i - 1; j >= 0; --j) { this.field_177258_e.add(p_177251_1_.func_177967_a(this.field_177257_d.func_176734_d(), j)); ++i1; } int j1 = 1; while(true) { BlockPos blockpos1 = p_177251_1_.func_177967_a(this.field_177257_d, j1); int k = this.field_177258_e.indexOf(blockpos1); if(k > -1) { this.func_177255_a(i1, k); for(int l = 0; l <= k + i1; ++l) { BlockPos blockpos2 = (BlockPos)this.field_177258_e.get(l); if(this.field_177261_a.func_180495_p(blockpos2).func_177230_c() == Blocks.field_180399_cE && !this.func_177250_b(blockpos2)) { return false; } } return true; } block = this.field_177261_a.func_180495_p(blockpos1).func_177230_c(); if(block.func_149688_o() == Material.field_151579_a) { return true; } if(!BlockPistonBase.func_180696_a(block, this.field_177261_a, blockpos1, this.field_177257_d, true) || blockpos1.equals(this.field_177259_b)) { return false; } if(block.func_149656_h() == 1) { this.field_177256_f.add(blockpos1); return true; } if(this.field_177258_e.size() >= 12) { return false; } this.field_177258_e.add(blockpos1); ++i1; ++j1; } } } } private void func_177255_a(int p_177255_1_, int p_177255_2_) { List<BlockPos> list = Lists.<BlockPos>newArrayList(); List<BlockPos> list1 = Lists.<BlockPos>newArrayList(); List<BlockPos> list2 = Lists.<BlockPos>newArrayList(); list.addAll(this.field_177258_e.subList(0, p_177255_2_)); list1.addAll(this.field_177258_e.subList(this.field_177258_e.size() - p_177255_1_, this.field_177258_e.size())); list2.addAll(this.field_177258_e.subList(p_177255_2_, this.field_177258_e.size() - p_177255_1_)); this.field_177258_e.clear(); this.field_177258_e.addAll(list); this.field_177258_e.addAll(list1); this.field_177258_e.addAll(list2); } private boolean func_177250_b(BlockPos p_177250_1_) { for(EnumFacing enumfacing : EnumFacing.values()) { if(enumfacing.func_176740_k() != this.field_177257_d.func_176740_k() && !this.func_177251_a(p_177250_1_.func_177972_a(enumfacing))) { return false; } } return true; } public List<BlockPos> func_177254_c() { return this.field_177258_e; } public List<BlockPos> func_177252_d() { return this.field_177256_f; } }
37.822485
209
0.615144
e00f3eb56b53129b52b4e484300c3fdf2ce744e8
516
package Example1; /** * Created by User on 26/05/2017. */ public class Test { public static void main(String[] args) { Triangle triangle = new Triangle(7, 4, 5, "yellow", true); System.out.println(triangle.getArea()); System.out.println(); System.out.println(triangle.getPerimeter()); System.out.println(); System.out.println(triangle.dateCreated); System.out.println("\n"); System.out.println(triangle.toString()); } }
25.8
67
0.593023
5d5f7e4bc81dec5f927a82f705b8cfdc01908b31
420
/* https://binarysearch.com/problems/High-Frequency */ import java.util.*; class Solution { public int solve(int[] nums) { Map<Integer, Integer> map = new HashMap<>(); int maxFreq = 0; for (int i = 0; i < nums.length; i++) { map.put(nums[i], map.getOrDefault(nums[i], 0) + 1); maxFreq = Math.max(maxFreq, map.get(nums[i])); } return maxFreq; } }
26.25
63
0.542857
2f8fcb8fe05c053a51fe65f417325dbc05476b66
2,302
package com.challenge.demo.service; import com.challenge.demo.bean.*; import com.challenge.demo.dto.QuestionDTO; import com.challenge.demo.dto.ResultDTO; import com.challenge.demo.repo.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import java.util.Optional; import java.util.UUID; @Service public class AssignServiceImplement implements AssignService { @Autowired SiteRepository siteRepository; @Autowired UserRepository userRepository; @Autowired QuestionRepository questionRepository; @Autowired QuestionAnswerRepository qaRepository; @Autowired ResultRepository resultRepository; @Override public ResponseEntity<QuestionDTO> AssignOneQuestion(UUID siteUUID, UUID userUUID) { Long siteId = siteRepository.findBySiteUUID(siteUUID).getSiteId(); Long userId = userRepository.findByUserUUID(userUUID).getUserId(); Question question = questionRepository.findAssignOneQuestion(siteId, userId); if (question == null) { resultRepository.resetQuestionList(userId); question = questionRepository .findAssignOneQuestion(siteId, userId); } if (question == null) return ResponseEntity.notFound().build(); QuestionDTO questionDTO = QuestionDTO.build(question); return new ResponseEntity<>(questionDTO, HttpStatus.FOUND); } @Override public ResponseEntity<ResultDTO> saveResult(UUID userUUID, ResultDTO resultDTO) { Optional<Question> question = questionRepository.findById(resultDTO.getQuestionId()); Optional<QuestionAnswer> questionAnswer = qaRepository.findById(resultDTO.getQuestionAnswerId()); User user = userRepository.findByUserUUID(userUUID); Result result = new Result(); if (user != null && question.isPresent() && questionAnswer.isPresent()) { result = ResultDTO.transform(resultDTO, question.get(), questionAnswer.get(), user); return new ResponseEntity<>(ResultDTO.build(resultRepository.save(result)), HttpStatus.CREATED); } return ResponseEntity.notFound().build(); } }
33.852941
108
0.726759
5081b0303ba6d30f9fffcaab1a347b999a690787
286
package com.lenis0012.bukkit.npc; public enum EquipmentSlot { HELMET(4), CHESTPLATE(3), LEGGINGS(2), BOOTS(1), HAND(0); private final int id; private EquipmentSlot(int id) { this.id = id; } public int getId() { return id; } }
14.3
35
0.562937
77f95fb8fb1e454828bbe58c7e51c1fdf009bb01
1,658
package io.dockstore.webservice.core; import java.util.Collections; import java.util.List; import org.junit.Assert; import org.junit.Test; public class Sha256ConverterTest { @Test public void convertToDatabaseColumn() { final Sha256Converter sha256Converter = new Sha256Converter(); final String fakeDigest = "1234567890"; final List<Checksum> checksums = sha256Converter.convertToEntityAttribute("\\x" + fakeDigest); Assert.assertNull(sha256Converter.convertToDatabaseColumn(checksums)); Assert.assertNull(sha256Converter.convertToDatabaseColumn(Collections.emptyList())); } @Test public void convertToEntityAttribute() { final Sha256Converter sha256Converter = new Sha256Converter(); Assert.assertEquals(0, sha256Converter.convertToEntityAttribute(null).size()); final String fakeDigest = "1234567890"; final List<Checksum> checksums = sha256Converter.convertToEntityAttribute("\\x" + fakeDigest); Assert.assertEquals(1, checksums.size()); final Checksum checksum = checksums.get(0); Assert.assertEquals(SourceFile.SHA_TYPE, checksum.getType()); Assert.assertEquals(fakeDigest, checksum.getChecksum()); // Shouldn't be any digests in DB without leading \x, but just in case final List<Checksum> checksums2 = sha256Converter.convertToEntityAttribute(fakeDigest); Assert.assertEquals(1, checksums2.size()); final Checksum checksum2 = checksums.get(0); Assert.assertEquals(SourceFile.SHA_TYPE, checksum2.getType()); Assert.assertEquals(fakeDigest, checksum2.getChecksum()); } }
43.631579
102
0.724367
0e62021feadd90bb2b97795e760dc317614381cf
9,224
/* * Copyright 2018 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.titus.master.scheduler.constraint; import java.util.Map; import java.util.Optional; import java.util.Set; import javax.inject.Inject; import javax.inject.Singleton; import com.netflix.fenzo.TaskRequest; import com.netflix.fenzo.TaskTrackerState; import com.netflix.fenzo.VirtualMachineCurrentState; import com.netflix.fenzo.queues.QueuableTask; import com.netflix.titus.api.agent.model.AgentInstance; import com.netflix.titus.api.agent.model.AgentInstanceGroup; import com.netflix.titus.api.agent.model.InstanceGroupLifecycleState; import com.netflix.titus.api.agent.model.InstanceLifecycleState; import com.netflix.titus.api.agent.service.AgentManagementService; import com.netflix.titus.api.agent.service.AgentStatusMonitor; import com.netflix.titus.api.model.Tier; import com.netflix.titus.common.util.CollectionsExt; import com.netflix.titus.master.scheduler.SchedulerAttributes; import com.netflix.titus.master.scheduler.SchedulerConfiguration; import com.netflix.titus.master.scheduler.SchedulerUtils; import static com.netflix.titus.master.scheduler.SchedulerUtils.getTier; /** * A system constraint that integrates with agent management in order to determine whether or a not a task * should be placed. */ @Singleton public class AgentManagementConstraint implements SystemConstraint { public static final String NAME = "AgentManagementConstraint"; private static final Result INSTANCE_GROUP_NOT_FOUND = new Result(false, "Instance group not found"); private static final Result INSTANCE_GROUP_NOT_ACTIVE = new Result(false, "Instance group is not active or phased out"); private static final Result INSTANCE_GROUP_TIER_MISMATCH = new Result(false, "Task cannot run on instance group tier"); private static final Result INSTANCE_GROUP_DOES_NOT_HAVE_GPUS = new Result(false, "Instance group does not have gpus"); private static final Result INSTANCE_GROUP_CANNOT_RUN_NON_GPU_TASKS = new Result(false, "Instance group does not run non gpu tasks"); private static final Result INSTANCE_NOT_FOUND = new Result(false, "Instance not found"); private static final Result INSTANCE_NOT_STARTED = new Result(false, "Instance not in Started state"); private static final Result INSTANCE_UNHEALTHY = new Result(false, "Unhealthy agent"); private static final Result SYSTEM_NO_PLACEMENT = new Result(false, "Cannot place on instance group or agent instance due to systemNoPlacement attribute"); private static final Result NO_PLACEMENT = new Result(false, "Cannot place on instance group or agent instance due to noPlacement attribute"); private static final Result TRUE_RESULT = new Result(true, null); private static final Set<String> FAILURE_REASONS = CollectionsExt.asSet( INSTANCE_GROUP_NOT_FOUND.getFailureReason(), INSTANCE_GROUP_NOT_ACTIVE.getFailureReason(), INSTANCE_GROUP_TIER_MISMATCH.getFailureReason(), INSTANCE_GROUP_DOES_NOT_HAVE_GPUS.getFailureReason(), INSTANCE_GROUP_CANNOT_RUN_NON_GPU_TASKS.getFailureReason(), INSTANCE_NOT_FOUND.getFailureReason(), INSTANCE_NOT_STARTED.getFailureReason(), INSTANCE_UNHEALTHY.getFailureReason(), SYSTEM_NO_PLACEMENT.getFailureReason(), NO_PLACEMENT.getFailureReason() ); private final SchedulerConfiguration schedulerConfiguration; private final AgentManagementService agentManagementService; private final AgentStatusMonitor agentStatusMonitor; @Inject public AgentManagementConstraint(SchedulerConfiguration schedulerConfiguration, AgentManagementService agentManagementService, AgentStatusMonitor agentStatusMonitor) { this.schedulerConfiguration = schedulerConfiguration; this.agentManagementService = agentManagementService; this.agentStatusMonitor = agentStatusMonitor; } @Override public String getName() { return NAME; } @Override public Result evaluate(TaskRequest taskRequest, VirtualMachineCurrentState targetVM, TaskTrackerState taskTrackerState) { Optional<AgentInstance> instanceOpt = SchedulerUtils.findInstance(agentManagementService, schedulerConfiguration.getInstanceAttributeName(), targetVM); if (!instanceOpt.isPresent()) { return INSTANCE_NOT_FOUND; } AgentInstance instance = instanceOpt.get(); String instanceGroupId = instance.getInstanceGroupId(); Optional<AgentInstanceGroup> instanceGroupOpt = agentManagementService.findInstanceGroup(instanceGroupId); if (!instanceGroupOpt.isPresent()) { return INSTANCE_GROUP_NOT_FOUND; } Result instanceGroupEvaluationResult = evaluateInstanceGroup(taskRequest, instanceGroupOpt.get()); if (instanceGroupEvaluationResult != TRUE_RESULT) { return instanceGroupEvaluationResult; } Result InstanceEvaluationResult = evaluateInstance(instance); if (InstanceEvaluationResult != TRUE_RESULT) { return InstanceEvaluationResult; } return TRUE_RESULT; } public static boolean isAgentManagementConstraintReason(String reason) { return reason != null && FAILURE_REASONS.contains(reason); } private Result evaluateInstanceGroup(TaskRequest taskRequest, AgentInstanceGroup instanceGroup) { InstanceGroupLifecycleState state = instanceGroup.getLifecycleStatus().getState(); //TODO safer way to know what is active? if (state != InstanceGroupLifecycleState.Active && state != InstanceGroupLifecycleState.PhasedOut) { return INSTANCE_GROUP_NOT_ACTIVE; } Result instanceGroupAttributesResult = evaluateInstanceGroupAttributes(instanceGroup); if (instanceGroupAttributesResult != TRUE_RESULT) { return instanceGroupAttributesResult; } Tier tier = getTier((QueuableTask) taskRequest); if (instanceGroup.getTier() != tier) { return INSTANCE_GROUP_TIER_MISMATCH; } //TODO read job resource dimensions when we get rid of v2 boolean gpuTask = taskRequestsGpu(taskRequest); boolean gpuAgent = instanceGroup.getResourceDimension().getGpu() > 0; if (gpuTask && !gpuAgent) { return INSTANCE_GROUP_DOES_NOT_HAVE_GPUS; } if (!gpuTask && gpuAgent) { return INSTANCE_GROUP_CANNOT_RUN_NON_GPU_TASKS; } return TRUE_RESULT; } private Result evaluateInstance(AgentInstance instance) { InstanceLifecycleState state = instance.getLifecycleStatus().getState(); if (state != InstanceLifecycleState.Started) { return INSTANCE_NOT_STARTED; } Result instanceAttributesResult = evaluateAgentInstanceAttributes(instance); if (instanceAttributesResult != TRUE_RESULT) { return instanceAttributesResult; } if (!agentStatusMonitor.isHealthy(instance.getId())) { return INSTANCE_UNHEALTHY; } return TRUE_RESULT; } private boolean taskRequestsGpu(TaskRequest taskRequest) { Map<String, Double> scalars = taskRequest.getScalarRequests(); if (scalars != null && !scalars.isEmpty()) { final Double gpu = scalars.get("gpu"); return gpu != null && gpu >= 1.0; } return false; } private Result evaluateInstanceGroupAttributes(AgentInstanceGroup instanceGroup) { Map<String, String> attributes = instanceGroup.getAttributes(); boolean systemNoPlacement = Boolean.parseBoolean(attributes.get(SchedulerAttributes.SYSTEM_NO_PLACEMENT)); if (systemNoPlacement) { return SYSTEM_NO_PLACEMENT; } boolean noPlacement = Boolean.parseBoolean(attributes.get(SchedulerAttributes.NO_PLACEMENT)); if (noPlacement) { return NO_PLACEMENT; } return TRUE_RESULT; } private Result evaluateAgentInstanceAttributes(AgentInstance agentInstance) { Map<String, String> attributes = agentInstance.getAttributes(); boolean systemNoPlacement = Boolean.parseBoolean(attributes.get(SchedulerAttributes.SYSTEM_NO_PLACEMENT)); if (systemNoPlacement) { return SYSTEM_NO_PLACEMENT; } boolean noPlacement = Boolean.parseBoolean(attributes.get(SchedulerAttributes.NO_PLACEMENT)); if (noPlacement) { return NO_PLACEMENT; } return TRUE_RESULT; } }
42.506912
159
0.725282
efa79a9b360e4c677afa302166a05c1fdb41f197
6,374
package com.gentics.mesh.core.schema; import static com.gentics.mesh.test.TestDataProvider.PROJECT_NAME; import static com.gentics.mesh.test.TestSize.FULL; import java.util.Arrays; import org.junit.Test; import com.gentics.mesh.core.rest.micronode.MicronodeResponse; import com.gentics.mesh.core.rest.microschema.impl.MicroschemaResponse; import com.gentics.mesh.core.rest.node.FieldMap; import com.gentics.mesh.core.rest.node.NodeCreateRequest; import com.gentics.mesh.core.rest.node.NodeResponse; import com.gentics.mesh.core.rest.node.field.impl.BooleanFieldImpl; import com.gentics.mesh.core.rest.node.field.impl.DateFieldImpl; import com.gentics.mesh.core.rest.node.field.impl.HtmlFieldImpl; import com.gentics.mesh.core.rest.node.field.impl.NodeFieldImpl; import com.gentics.mesh.core.rest.node.field.impl.NumberFieldImpl; import com.gentics.mesh.core.rest.node.field.impl.StringFieldImpl; import com.gentics.mesh.core.rest.node.field.list.impl.BooleanFieldListImpl; import com.gentics.mesh.core.rest.node.field.list.impl.DateFieldListImpl; import com.gentics.mesh.core.rest.node.field.list.impl.HtmlFieldListImpl; import com.gentics.mesh.core.rest.node.field.list.impl.MicronodeFieldListImpl; import com.gentics.mesh.core.rest.node.field.list.impl.NodeFieldListImpl; import com.gentics.mesh.core.rest.node.field.list.impl.NodeFieldListItemImpl; import com.gentics.mesh.core.rest.node.field.list.impl.NumberFieldListImpl; import com.gentics.mesh.core.rest.node.field.list.impl.StringFieldListImpl; import com.gentics.mesh.core.rest.schema.impl.BinaryFieldSchemaImpl; import com.gentics.mesh.core.rest.schema.impl.BooleanFieldSchemaImpl; import com.gentics.mesh.core.rest.schema.impl.DateFieldSchemaImpl; import com.gentics.mesh.core.rest.schema.impl.HtmlFieldSchemaImpl; import com.gentics.mesh.core.rest.schema.impl.ListFieldSchemaImpl; import com.gentics.mesh.core.rest.schema.impl.MicronodeFieldSchemaImpl; import com.gentics.mesh.core.rest.schema.impl.MicroschemaReferenceImpl; import com.gentics.mesh.core.rest.schema.impl.NodeFieldSchemaImpl; import com.gentics.mesh.core.rest.schema.impl.NumberFieldSchemaImpl; import com.gentics.mesh.core.rest.schema.impl.SchemaCreateRequest; import com.gentics.mesh.core.rest.schema.impl.SchemaResponse; import com.gentics.mesh.core.rest.schema.impl.StringFieldSchemaImpl; import com.gentics.mesh.test.context.AbstractMeshTest; import com.gentics.mesh.test.context.MeshTestSetting; @MeshTestSetting(testSize = FULL, startServer = true, clusterMode = false) public class MicronodeMigrationAllFieldsTest extends AbstractMeshTest { public static final String SCHEMA_NAME = "AllFields"; @Test public void testMigration() { grantAdminRole(); createSchema(); createAllFieldsNode(); updateMicroschema(); } private SchemaResponse createSchema() { SchemaCreateRequest request = new SchemaCreateRequest() .setName(SCHEMA_NAME) .setFields(Arrays.asList( new StringFieldSchemaImpl().setName("string"), new NumberFieldSchemaImpl().setName("number"), new BooleanFieldSchemaImpl().setName("boolean"), new DateFieldSchemaImpl().setName("date"), new HtmlFieldSchemaImpl().setName("html"), new NodeFieldSchemaImpl().setName("node"), new BinaryFieldSchemaImpl().setName("binary"), new MicronodeFieldSchemaImpl().setName("micronode"), new ListFieldSchemaImpl() .setListType("string").setName("liststring"), new ListFieldSchemaImpl() .setListType("number").setName("listnumber"), new ListFieldSchemaImpl() .setListType("date").setName("listdate"), new ListFieldSchemaImpl() .setListType("boolean").setName("listboolean"), new ListFieldSchemaImpl() .setListType("html").setName("listhtml"), new ListFieldSchemaImpl() .setListType("node").setName("listnode"), new ListFieldSchemaImpl() .setListType("micronode").setName("listmicronode") )); SchemaResponse schemaResponse = client().createSchema(request).blockingGet(); client().assignSchemaToProject(PROJECT_NAME, schemaResponse.getUuid()).blockingAwait(); return schemaResponse; } private NodeResponse createAllFieldsNode() { NodeCreateRequest request = new NodeCreateRequest(); request.setLanguage("en"); request.setSchemaName(SCHEMA_NAME); request.setParentNodeUuid(folderUuid()); FieldMap fields = request.getFields(); MicronodeResponse micronode = new MicronodeResponse(); micronode.setMicroschema(new MicroschemaReferenceImpl().setName("vcard")); FieldMap micronodeFields = micronode.getFields(); micronodeFields.putString("firstName", "John"); micronodeFields.putString("lastName", "Doe"); fields.put("micronode", micronode); fields.put("listmicronode", new MicronodeFieldListImpl().setItems(Arrays.asList( micronode, micronode ))); fields.put("string", new StringFieldImpl().setString("example")); fields.put("number", new NumberFieldImpl().setNumber(1234)); fields.put("boolean", new BooleanFieldImpl().setValue(false)); fields.put("date", new DateFieldImpl().setDate("2020-02-21T12:40:00Z")); fields.put("html", new HtmlFieldImpl().setHTML("<p>example</p>")); fields.put("node", new NodeFieldImpl().setUuid(folderUuid())); fields.put("liststring", new StringFieldListImpl().setItems(Arrays.asList( "example1", "example2" ))); fields.put("listnumber", new NumberFieldListImpl().setItems(Arrays.asList( 123, 456 ))); fields.put("listdate", new DateFieldListImpl().setItems(Arrays.asList( "2020-02-21T12:40:00Z", "2020-02-22T12:40:00Z" ))); fields.put("listboolean", new BooleanFieldListImpl().setItems(Arrays.asList( false, true ))); fields.put("listhtml", new HtmlFieldListImpl().setItems(Arrays.asList( "<p>example1</p>", "<p>example2</p>" ))); fields.put("listnode", new NodeFieldListImpl().setItems(Arrays.asList( new NodeFieldListItemImpl().setUuid(folderUuid()), new NodeFieldListItemImpl().setUuid(folderUuid()) ))); return client().createNode(PROJECT_NAME, request).blockingGet(); } private void updateMicroschema() { MicroschemaResponse microschema = client().findMicroschemas().blockingGet().getData().get(0); microschema.getFields().add(new StringFieldSchemaImpl().setName("additionalStringField")); waitForJob(() -> { client().updateMicroschema(microschema.getUuid(), microschema.toRequest()).blockingAwait(); }); } }
42.211921
95
0.770944
472e8712c8d75d64f8d039dfb55a733eaa9bff19
1,051
package dauroi.photoeditor.task; import dauroi.photoeditor.listener.ApplyFilterListener; import dauroi.photoeditor.ui.activity.ImageProcessingActivity; import android.graphics.Bitmap; import android.os.AsyncTask; public class ApplyFilterTask extends AsyncTask<Void, Void, Bitmap> { private ImageProcessingActivity mActivity; private ApplyFilterListener mListener; public ApplyFilterTask(ImageProcessingActivity activity, ApplyFilterListener listener) { mActivity = activity; mListener = listener; } @Override protected void onPreExecute() { super.onPreExecute(); mActivity.hideAllMenus(); mActivity.showProgress(true); } @Override protected Bitmap doInBackground(Void... params) { return mListener.applyFilter(); } @Override protected void onPostExecute(Bitmap result) { super.onPostExecute(result); if (result != null) { mActivity.setImage(result, true); } // go to filter mode mActivity.selectAction(0); mActivity.showProgress(false); mActivity.showAllMenus(); mListener.onFinishFiltering(); } }
24.44186
68
0.775452
2c1710f2913b173a7faa3fb478b78654f93939d7
149
package org.futuristic.petclinic.service; import org.futuristic.petclinic.model.Pet; public interface PetService extends CrudService<Pet, Long>{ }
21.285714
59
0.818792
89f37e80a02b2cd1246c6a26f3661b5c7ebc75ad
20,332
/* Copyright (c) 2018 by ScaleOut Software, 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 org.springframework.session.soss; import com.scaleoutsoftware.soss.client.*; import com.scaleoutsoftware.soss.client.da.*; import com.scaleoutsoftware.soss.client.da.ReadOptions; import com.scaleoutsoftware.soss.client.query.EqualFilter; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.expression.Expression; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.session.FindByIndexNameSessionRepository; import org.springframework.session.Session; import org.springframework.session.soss.config.annotation.web.http.EnableScaleoutHttpSession; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.time.Duration; import java.time.Instant; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; /** * A {@link org.springframework.session.SessionRepository} implementation that is backed by ScaleOut StateServer's * NamedCache API. This implementation does not support publishing events. * * <p> * Integrating with the {@link ScaleoutSessionRepository} is very easy. Inside your application code, simply add * a basic configuration class with the {@link EnableScaleoutHttpSession} * annotation. * </p> * * <p> * Optionally, you can set the cache name and the timeout for sessions. By default, the cache name used is * "SpringSessionRepo" and the session timeout is 30 minutes and locking is enabled. * </p> */ public class ScaleoutSessionRepository implements FindByIndexNameSessionRepository<ScaleoutSession> { private static final Log logger = LogFactory.getLog(ScaleoutSessionRepository.class); // spring integration helper classes and attributes static final PrincipalNameResolver PRINCIPAL_NAME_RESOLVER = new PrincipalNameResolver(); private static final String SPRING_SECURITY_CONTEXT = "SPRING_SECURITY_CONTEXT"; // reasonable defaults for a session repository /** * Default namespace to store sessions. */ public static final String DEF_CACHE_NAME = "SpringSessionRepo"; /** * Default locking value. */ public static final boolean DEF_USE_LOCKING = true; /** * default remote read-pending retry interval. */ public static final int DEF_REMOTE_READPENDING_RETRY_INTERVAL = 10; /** * default remote read-pending retries. */ public static final int DEF_REMOTE_READPENDING_RETRIES = 2400; /** * */ public static final String DEF_UNASSIGNED = "UNASSIGNED"; // the NamedCache to use for query private final NamedCache _cache; // helper objects for locking private final ConcurrentHashMap<String, DataAccessor> _sessionAccessors; private final HashSet<ReadOptions> _readOptions; private final CreatePolicy _createPolicy; // private member configuration variables private final Duration _maxInactiveTime; private final boolean _useLocking; private final int _remoteReadPendingInterval; private final int _remoteReadPendingRetries; /** * Instantiates the ScaleOutSessionRepository. * @param cacheName the cache name to store {@link org.springframework.session.soss.ScaleoutSession}s * @param maxInactiveTime the max inactive time of a session * @param useLocking if the scaleout repository is using locking * @param remoteStoreName the name of the remote store (used for GeoServer Pro pull replication). * @param remoteReadPendingInterval in case of a WAN failure, the interval in ms to wait when a remote read is pending * @param remoteReadRetries in case of a WAN failure, the number of times to retry a remote read */ public ScaleoutSessionRepository(String cacheName, Duration maxInactiveTime, boolean useLocking, String remoteStoreName, int remoteReadPendingInterval, int remoteReadRetries) { _maxInactiveTime = maxInactiveTime; _useLocking = useLocking; _sessionAccessors = new ConcurrentHashMap<>(); _remoteReadPendingInterval = remoteReadPendingInterval; _remoteReadPendingRetries = remoteReadRetries; // setup a new create policy _createPolicy = new CreatePolicy(); _createPolicy.setTimeout(TimeSpan.fromMinutes(maxInactiveTime.toMinutes())); if(remoteStoreName.compareTo(ScaleoutSessionRepository.DEF_UNASSIGNED) != 0) { _createPolicy.setDefaultCoherencyPolicy(new NotifyCoherencyPolicy()); } // setup a new set of read options for a DataAccessor that uses locking _readOptions = new HashSet<>(); _readOptions.add(ReadOptions.ObjectMayNotExist); // don't throw "ObjectNotFound" exceptions -- return null. _readOptions.add(ReadOptions.ReturnCachedObjectIfValid); // use the client cache if(remoteStoreName.compareTo(ScaleoutSessionRepository.DEF_UNASSIGNED) != 0) { _readOptions.add(ReadOptions.ReadRemoteObject); } if(_useLocking) { _readOptions.add(ReadOptions.LockObject); // if the object exists, lock the object } try { _cache = CacheFactory.getCache(cacheName); StateServerKey.setDefaultAppId(StateServerKey.appNameToId(cacheName)); if(remoteStoreName.compareTo(ScaleoutSessionRepository.DEF_UNASSIGNED) != 0) { List<RemoteStore> stores = new LinkedList<>(); stores.add(new RemoteStore(remoteStoreName)); _cache.setRemoteStores(stores); } } catch (StateServerException e) { logger.error("Couldn't create namespace."); throw new RuntimeException(e); } catch (NamedCacheException e) { logger.error("Couldn't create NamedCache."); throw new RuntimeException(e); } } /** * Creates a new ScaleOut session. * @return a new ScaleOut Session */ @Override public ScaleoutSession createSession() { return new ScaleoutSession(Instant.now(), _maxInactiveTime); } /** * Saves a {@link org.springframework.session.soss.ScaleoutSession}. * @param session the session to save */ @Override public void save(ScaleoutSession session) { if(session == null) return; List<String> oldIds = session.oldIds(); // if the session is new, or we have old sessions -- which means the key has changed -- // then we need to create the session and if necessary remove the old sessions. if(session.isNew() || oldIds != null) { saveNewSession(session, oldIds); } else { // if the session is not new, we need to update saveExistingSession(session); } } /** * Finds a session based on the session id or null if no {@link org.springframework.session.soss.ScaleoutSession} with that ID exists. * @param id the id of the session to find * @return the associated {@link org.springframework.session.soss.ScaleoutSession} with the parameter id or NULL */ @Override public ScaleoutSession findById(String id) { if(id == null) return null; return retrieveSession(id); } /** * Deletes a {@link org.springframework.session.soss.ScaleoutSession} from the * configured NamedCache with the parameter session id. * @param id the session id to delete */ @Override public void deleteById(String id) { if(id == null) return; delete(id); } /** * Retrieves a HashMap correlating session IDs to {@link org.springframework.session.soss.ScaleoutSession}. * @param indexName the principal name * @param indexValue the desired value * @return a hashmap containing all sessions associated with the configured index name and parameter index value or an empty map */ @Override public Map<String, ScaleoutSession> findByIndexNameAndIndexValue(String indexName, String indexValue) { if(!PRINCIPAL_NAME_INDEX_NAME.equals(indexName) || indexValue == null) { return Collections.emptyMap(); } else { Set<CachedObjectId<ScaleoutSession>> keys = null; try { keys = _cache.queryKeys(ScaleoutSession.class, new EqualFilter("principalNameIndexName", indexValue)); } catch (NamedCacheException e) { logger.error("Error thrown querying keys.", e); } if(keys != null) { Map<String, ScaleoutSession> map = new HashMap<>(); for(CachedObjectId<ScaleoutSession> key : keys) { try { map.put(key.getKeyString(), _cache.get(key)); } catch (NamedCacheException e) { logger.error("Error thrown retrieving object.", e); } } return map; } } return null; } // private helper method to hash a string to a 32-byte key private byte[] hashStringKey(String id) { try { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(id.getBytes()); return md.digest(); } catch (NoSuchAlgorithmException e) { return null; } } // private helper method to remove old sessions private void removeOldSessions(List<String> oldIds) { if(oldIds != null) { for(String id : oldIds){ try { // will handle local cleanup for local DAs delete(id); } catch (Exception e) { logger.error("Exception thrown while deleting old session.", e); } } } } // private helper method to retrieve a session private ScaleoutSession retrieveSession(String id) { int remoteReadAttempt = 0; // create or retrieve a DA DataAccessor da = null; if(_useLocking) { da = _sessionAccessors.get(id); } if(da == null) { da = getDA(id); } // perform read ReadResult readResult = null; do { try { if(da != null) readResult = da.read(_readOptions); } catch (ObjectLockedException ole) { // If the object is locked, it means two threads tried to retrieve the same session and some other thread // won. In case the other thread is local to this client, we will retrieve the correct DA and retry. // If another client won (i.e. some other instance of the session repository has the lock), we will keep // re-trying the read until we can successfully read and lock the session. if(_useLocking) { DataAccessor tempDa = _sessionAccessors.get(id); if (tempDa != null) { da = tempDa; } } else { // with locking disabled an ObjectLockedException should not occur -- log the error and return null logger.error(ole); return null; } } catch (ReadThroughPendingException rtpe) { // If a read through pending exception is thrown, it means the session is on a remote store and the // local store is in process of pulling the object to the local store. In this case, we simply retry the // read and lock according to the configured number of retries and retry interval. remoteReadAttempt++; if (remoteReadAttempt >= _remoteReadPendingRetries) { logger.error("read through pending timed-out."); return null; } else try { Thread.sleep(_remoteReadPendingInterval); } catch (InterruptedException e1) { throw new RuntimeException("Unexpected error while waiting to retry"); } } catch (StateServerException e) { logger.error(e); return null; } } while(readResult == null); // read completed -- and if locking is enabled, the object is locked -- any exception from this point on means we need to // release the lock (IOException, or ClassCastException). The finally block is used for lock cleanup and // keeping track of the DA that holds the correct lock ticket. boolean releaseLock = false; try { ScaleoutSession session = retrieveSessionFromReadResult(readResult); if(session != null) { if(session.isExpired()) { // the session is expired, delete it and return null delete(id); return null; } else { // mark the session session.setLastAccessedTime(Instant.now()); session.markTouched(); } } return session; } catch (Exception e) { releaseLock = _useLocking; return null; } finally { // if an exception occurred, we need to cleanup, i.e., release the stateserver lock and remove the local // DA from the table if(releaseLock) { try { da.releaseLock(); } catch (StateServerException e) { logger.warn(e); } } else if(_useLocking) { // make sure the proper DA is in the local table _sessionAccessors.put(id, da); } } } // private helper method to create a DA private DataAccessor getDA(String id) { if(id == null) return null; try { StateServerKey key = new StateServerKey(hashStringKey(id)); key.setKeyString(id); DataAccessor da = new DataAccessor(key); da.setLockedWhenReading(_useLocking); return da; } catch (StateServerException e) { logger.error(e); return null; } } // private helper method to create a new session in stateserver private void saveNewSession(ScaleoutSession session, List<String> oldSessionIds) { session.resolveQueryableAttributes(); try { DataAccessor da = getDA(session.getId()); session.markTouched(); if(da != null) da.create(_createPolicy, session); } catch (ObjectExistsException oee) { logger.warn(oee); saveExistingSession(session); } catch (StateServerException e) { logger.error("Exception thrown while saving new session", e); } finally { removeOldSessions(oldSessionIds); } } // private helper method to save an existing session -- i.e. update the session. private void saveExistingSession(ScaleoutSession session) { DataAccessor da = null; boolean releaseLock = false; boolean removeSessionAccessor = false; boolean foundSessionAccessorWithLock = false; try { do { // If we're updating a session, that means we've found an existing session (i.e. session.isNew() == false). // so, we need to retrieve the DA we used to retrieve the session if(_useLocking) { da = _sessionAccessors.get(session.getId()); foundSessionAccessorWithLock = (da != null); } // Even when we're unlocking, it's possible to call "save" multiple times -- in which case, we need to create // a new DA to perform the update because the session is no longer locked and we don't have a local DA. We // also need to create a DA if locking is turned off. if(da == null) { da = getDA(session.getId()); } // it's always safe to call update and unlock even when locking is disabled or we don't have a lock ticket try { if(da != null) { da.update(session, true); removeSessionAccessor = true; break; } } catch(ObjectLockedException ole) { logger.warn("object locked, retrying."); } } while(true); } catch (StateServerException e) { logger.error("Error thrown saving session.", e); releaseLock = foundSessionAccessorWithLock; } finally { try { // cleanup if an exception occurred if(releaseLock) { da.releaseLock(); } // cleanup to remove the existing DA if(removeSessionAccessor) { _sessionAccessors.remove(session.getId()); } } catch (Exception e) { logger.error(e); } } } // private helper to extract a session object from a DA read result private ScaleoutSession retrieveSessionFromReadResult(ReadResult result) throws IOException, ClassNotFoundException { Object obj = null; byte[] serializedSession = null; if(result != null) { if(result.getStatus() != StateServerResult.Success) { return null; } else if(result.isCachedObjectValid()) { obj = result.getCachedObject(); } else { serializedSession = result.getBytes(); } } if (obj != null) { return (ScaleoutSession) obj; } ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(serializedSession)); obj = ois.readObject(); ois.close(); return (ScaleoutSession) obj; } // private helper method to delete a session and handles local cleanup private void delete(String s) { if(s == null) return; try { DataAccessor da = null; if(_useLocking) { da = _sessionAccessors.remove(s); } if(da == null) { da = getDA(s); } da.delete(); } catch (StateServerException e) { logger.error("Error thrown deleting session.", e); } } /** * Static helper class to resolve the PRINCIPAL_NAME_INDEX_NAME OR SPRING_SECURITY_CONTEXT. This class is used to * set the principal name (annotated SossIndexAttribute method) in {@link org.springframework.session.soss.ScaleoutSession}. */ static class PrincipalNameResolver { private SpelExpressionParser parser = new SpelExpressionParser(); public String resolvePrincipal(Session session) { String principalName = session.getAttribute(PRINCIPAL_NAME_INDEX_NAME); if (principalName != null) { return principalName; } Object authentication = session.getAttribute(SPRING_SECURITY_CONTEXT); if (authentication != null) { Expression expression = this.parser.parseExpression("authentication?.name"); return expression.getValue(authentication, String.class); } return null; } } }
40.501992
180
0.614893
b0f60de45fd248ee761f28d7a6ea2e6a1f636ce0
4,741
package io.configrd.core.util; import java.net.URI; import org.junit.Assert; import org.junit.Test; import io.configrd.core.util.URIBuilder; public class TestURIBuilder { @Test public void testExtendPathAtBuild() { URIBuilder builder = URIBuilder.create("classpath:root/first/second/third/file.properties"); Assert.assertEquals(URI.create("classpath:root/first/second/third/file.properties"), builder.build()); Assert.assertEquals(URI.create("classpath:root/first/second/third/file.properties"), builder.build("")); Assert.assertEquals(URI.create("classpath:root/first/second/third/fourth/file.properties"), builder.build("/fourth")); Assert.assertEquals(URI.create("classpath:root/first/second/third/fourth/file2.properties"), builder.build("/fourth/file2.properties")); Assert.assertEquals(URI.create("classpath:root/first/second/third/fourth/file2.properties"), builder.build("fourth/file2.properties")); builder = URIBuilder.create("file://tmp/configrd/test/configrd-demo"); Assert.assertEquals(URI.create("file://tmp/configrd/test/configrd-demo/env/dev/custom/default.properties"), builder.build("env/dev/custom/default.properties")); } @Test public void testURIBuilder() { Assert.assertEquals(URI.create("file:first/second/third/file.properties"), URIBuilder.create() .setScheme("file").setPath("first/second/third").setFileName("file.properties").build()); Assert.assertEquals(URI.create("file:/first/second/third/file.properties"), URIBuilder.create() .setScheme("file").setPath("/first/second/third").setFileName("file.properties").build()); Assert.assertEquals(URI.create("file:/first/second/third"), URIBuilder.create().setScheme("file").setPath("/first/second/third").build()); Assert.assertEquals( URI.create("file://user:pass@localhost:1234/first/second/third/file.properties"), URIBuilder.create().setScheme("file").setPath("/first/second/third").setHost("localhost") .setPort(1234).setUsername("user").setPassword("pass").setFileName("file.properties") .build()); Assert.assertEquals(URI.create("file://user:pass@/first/second/third/file.properties"), URIBuilder.create().setScheme("file").setPath("/first/second/third").setUsername("user") .setPassword("pass").setFileName("file.properties").build()); Assert.assertEquals(URI.create("file:file.properties"), URIBuilder.create().setScheme("file").setFileName("file.properties").build()); Assert.assertEquals(URI.create("file:/file.properties"), URIBuilder.create().setScheme("file").setFileName("file.properties").setPath("/").build()); Assert.assertEquals(URI.create("http://host:12345/first/second/third/file.properties#custom,simple"), URIBuilder.create().setScheme("http").setHost("host").setPort(12345) .setPath("first/second/third").setFileName("file.properties") .setFragment("custom", "simple").build()); } @Test public void testURIBuilderWithBaseURI() { URI uri = URI.create("file://user:pass@host:1234/first/second/third/file.properties"); Assert.assertEquals(uri, URIBuilder.create(uri).build()); Assert.assertEquals( URI.create("file://user:pass@host:1234/first/second/third/replaced.properties"), URIBuilder.create(uri).setFileName("replaced.properties").build()); Assert.assertEquals(URI.create("file://user:pass@host:1234/first/second/replaced.properties"), URIBuilder.create(uri).setPath("/first/second/").setFileName("replaced.properties") .build()); Assert.assertEquals(URI.create("file://user:pass@host:1234/first/second/"), URIBuilder.create(uri).setPath("/first/second/").setFileName("").build()); Assert.assertEquals(URI.create("file://user:pass@host:9999/first/second/"), URIBuilder.create(uri).setPath("/first/second/").setFileName("").setPort(9999).build()); Assert.assertEquals( URI.create("classpath://user2:pass2@host:1234/first/second/third/file.properties"), URIBuilder.create(uri).setScheme("classpath").setPath("/first/second/third") .setUsername("user2").setPassword("pass2").setFileName("file.properties").build()); Assert.assertEquals( URI.create("classpath://user:pass@host:1234/first/second/third/file2.properties"), URIBuilder.create(uri).setScheme("classpath").setFileName("file2.properties").build()); Assert.assertEquals(URI.create("file://user:pass@host:1234/file2.properties"), URIBuilder.create(uri).setPath("").setFileName("file2.properties").setPath("/").build()); } }
43.898148
111
0.696056
fb007b0ca318179f2ab98da7b02aee567b4db779
54,142
/* * Fatture in Cloud API v2 - API Reference * Connect your software with Fatture in Cloud, the invoicing platform chosen by more than 400.000 businesses in Italy. The Fatture in Cloud API is based on REST, and makes possible to interact with the user related data prior authorization via OAuth2 protocol. * * The version of the OpenAPI document: 2.0.16 * Contact: [email protected] * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package it.fattureincloud.sdk.api; import com.google.gson.reflect.TypeToken; import it.fattureincloud.sdk.ApiCallback; import it.fattureincloud.sdk.ApiClient; import it.fattureincloud.sdk.ApiException; import it.fattureincloud.sdk.ApiResponse; import it.fattureincloud.sdk.Configuration; import it.fattureincloud.sdk.Pair; import it.fattureincloud.sdk.model.CreateF24Request; import it.fattureincloud.sdk.model.CreateF24Response; import it.fattureincloud.sdk.model.GetF24Response; import it.fattureincloud.sdk.model.ListF24Response; import it.fattureincloud.sdk.model.ModifyF24Request; import it.fattureincloud.sdk.model.ModifyF24Response; import it.fattureincloud.sdk.model.UploadF24AttachmentResponse; import java.io.File; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class TaxesApi { private ApiClient localVarApiClient; private int localHostIndex; private String localCustomBaseUrl; public TaxesApi() { this(Configuration.getDefaultApiClient()); } public TaxesApi(ApiClient apiClient) { this.localVarApiClient = apiClient; } public ApiClient getApiClient() { return localVarApiClient; } public void setApiClient(ApiClient apiClient) { this.localVarApiClient = apiClient; } public int getHostIndex() { return localHostIndex; } public void setHostIndex(int hostIndex) { this.localHostIndex = hostIndex; } public String getCustomBaseUrl() { return localCustomBaseUrl; } public void setCustomBaseUrl(String customBaseUrl) { this.localCustomBaseUrl = customBaseUrl; } /** * Build call for createF24 * * @param companyId The ID of the company. (required) * @param createF24Request The F24 to create (optional) * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object * @http.response.details * <table border="1"> * <caption>Response Details</caption> * <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> * <tr><td> 200 </td><td> The created F24 </td><td> - </td></tr> * <tr><td> 401 </td><td> Unauthorized </td><td> - </td></tr> * <tr><td> 404 </td><td> Not Found </td><td> - </td></tr> * </table> */ public okhttp3.Call createF24Call( Integer companyId, CreateF24Request createF24Request, final ApiCallback _callback) throws ApiException { String basePath = null; // Operation Servers String[] localBasePaths = new String[] {}; // Determine Base Path to Use if (localCustomBaseUrl != null) { basePath = localCustomBaseUrl; } else if (localBasePaths.length > 0) { basePath = localBasePaths[localHostIndex]; } else { basePath = null; } Object localVarPostBody = createF24Request; // create path and map variables String localVarPath = "/c/{company_id}/taxes" .replaceAll( "\\{" + "company_id" + "\\}", localVarApiClient.escapeString(companyId.toString())); List<Pair> localVarQueryParams = new ArrayList<Pair>(); List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>(); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); Map<String, String> localVarCookieParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = {"application/json"}; final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) { localVarHeaderParams.put("Accept", localVarAccept); } final String[] localVarContentTypes = {"application/json"}; final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); if (localVarContentType != null) { localVarHeaderParams.put("Content-Type", localVarContentType); } String[] localVarAuthNames = new String[] {"OAuth2AuthenticationCodeFlow"}; return localVarApiClient.buildCall( basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") private okhttp3.Call createF24ValidateBeforeCall( Integer companyId, CreateF24Request createF24Request, final ApiCallback _callback) throws ApiException { // verify the required parameter 'companyId' is set if (companyId == null) { throw new ApiException( "Missing the required parameter 'companyId' when calling createF24(Async)"); } okhttp3.Call localVarCall = createF24Call(companyId, createF24Request, _callback); return localVarCall; } /** * Create F24 Creates a new F24. * * @param companyId The ID of the company. (required) * @param createF24Request The F24 to create (optional) * @return CreateF24Response * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the * response body * @http.response.details * <table border="1"> * <caption>Response Details</caption> * <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> * <tr><td> 200 </td><td> The created F24 </td><td> - </td></tr> * <tr><td> 401 </td><td> Unauthorized </td><td> - </td></tr> * <tr><td> 404 </td><td> Not Found </td><td> - </td></tr> * </table> */ public CreateF24Response createF24(Integer companyId, CreateF24Request createF24Request) throws ApiException { ApiResponse<CreateF24Response> localVarResp = createF24WithHttpInfo(companyId, createF24Request); return localVarResp.getData(); } /** * Create F24 Creates a new F24. * * @param companyId The ID of the company. (required) * @param createF24Request The F24 to create (optional) * @return ApiResponse&lt;CreateF24Response&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the * response body * @http.response.details * <table border="1"> * <caption>Response Details</caption> * <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> * <tr><td> 200 </td><td> The created F24 </td><td> - </td></tr> * <tr><td> 401 </td><td> Unauthorized </td><td> - </td></tr> * <tr><td> 404 </td><td> Not Found </td><td> - </td></tr> * </table> */ public ApiResponse<CreateF24Response> createF24WithHttpInfo( Integer companyId, CreateF24Request createF24Request) throws ApiException { okhttp3.Call localVarCall = createF24ValidateBeforeCall(companyId, createF24Request, null); Type localVarReturnType = new TypeToken<CreateF24Response>() {}.getType(); return localVarApiClient.execute(localVarCall, localVarReturnType); } /** * Create F24 (asynchronously) Creates a new F24. * * @param companyId The ID of the company. (required) * @param createF24Request The F24 to create (optional) * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object * @http.response.details * <table border="1"> * <caption>Response Details</caption> * <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> * <tr><td> 200 </td><td> The created F24 </td><td> - </td></tr> * <tr><td> 401 </td><td> Unauthorized </td><td> - </td></tr> * <tr><td> 404 </td><td> Not Found </td><td> - </td></tr> * </table> */ public okhttp3.Call createF24Async( Integer companyId, CreateF24Request createF24Request, final ApiCallback<CreateF24Response> _callback) throws ApiException { okhttp3.Call localVarCall = createF24ValidateBeforeCall(companyId, createF24Request, _callback); Type localVarReturnType = new TypeToken<CreateF24Response>() {}.getType(); localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); return localVarCall; } /** * Build call for deleteF24 * * @param companyId The ID of the company. (required) * @param documentId The ID of the document. (required) * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object * @http.response.details * <table border="1"> * <caption>Response Details</caption> * <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> * <tr><td> 200 </td><td> Document removed. </td><td> - </td></tr> * <tr><td> 401 </td><td> Unauthorized </td><td> - </td></tr> * <tr><td> 404 </td><td> Not Found </td><td> - </td></tr> * </table> */ public okhttp3.Call deleteF24Call( Integer companyId, Integer documentId, final ApiCallback _callback) throws ApiException { String basePath = null; // Operation Servers String[] localBasePaths = new String[] {}; // Determine Base Path to Use if (localCustomBaseUrl != null) { basePath = localCustomBaseUrl; } else if (localBasePaths.length > 0) { basePath = localBasePaths[localHostIndex]; } else { basePath = null; } Object localVarPostBody = null; // create path and map variables String localVarPath = "/c/{company_id}/taxes/{document_id}" .replaceAll( "\\{" + "company_id" + "\\}", localVarApiClient.escapeString(companyId.toString())) .replaceAll( "\\{" + "document_id" + "\\}", localVarApiClient.escapeString(documentId.toString())); List<Pair> localVarQueryParams = new ArrayList<Pair>(); List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>(); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); Map<String, String> localVarCookieParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = {}; final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) { localVarHeaderParams.put("Accept", localVarAccept); } final String[] localVarContentTypes = {}; final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); if (localVarContentType != null) { localVarHeaderParams.put("Content-Type", localVarContentType); } String[] localVarAuthNames = new String[] {"OAuth2AuthenticationCodeFlow"}; return localVarApiClient.buildCall( basePath, localVarPath, "DELETE", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") private okhttp3.Call deleteF24ValidateBeforeCall( Integer companyId, Integer documentId, final ApiCallback _callback) throws ApiException { // verify the required parameter 'companyId' is set if (companyId == null) { throw new ApiException( "Missing the required parameter 'companyId' when calling deleteF24(Async)"); } // verify the required parameter 'documentId' is set if (documentId == null) { throw new ApiException( "Missing the required parameter 'documentId' when calling deleteF24(Async)"); } okhttp3.Call localVarCall = deleteF24Call(companyId, documentId, _callback); return localVarCall; } /** * Delete F24 Removes the specified F24. * * @param companyId The ID of the company. (required) * @param documentId The ID of the document. (required) * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the * response body * @http.response.details * <table border="1"> * <caption>Response Details</caption> * <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> * <tr><td> 200 </td><td> Document removed. </td><td> - </td></tr> * <tr><td> 401 </td><td> Unauthorized </td><td> - </td></tr> * <tr><td> 404 </td><td> Not Found </td><td> - </td></tr> * </table> */ public void deleteF24(Integer companyId, Integer documentId) throws ApiException { deleteF24WithHttpInfo(companyId, documentId); } /** * Delete F24 Removes the specified F24. * * @param companyId The ID of the company. (required) * @param documentId The ID of the document. (required) * @return ApiResponse&lt;Void&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the * response body * @http.response.details * <table border="1"> * <caption>Response Details</caption> * <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> * <tr><td> 200 </td><td> Document removed. </td><td> - </td></tr> * <tr><td> 401 </td><td> Unauthorized </td><td> - </td></tr> * <tr><td> 404 </td><td> Not Found </td><td> - </td></tr> * </table> */ public ApiResponse<Void> deleteF24WithHttpInfo(Integer companyId, Integer documentId) throws ApiException { okhttp3.Call localVarCall = deleteF24ValidateBeforeCall(companyId, documentId, null); return localVarApiClient.execute(localVarCall); } /** * Delete F24 (asynchronously) Removes the specified F24. * * @param companyId The ID of the company. (required) * @param documentId The ID of the document. (required) * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object * @http.response.details * <table border="1"> * <caption>Response Details</caption> * <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> * <tr><td> 200 </td><td> Document removed. </td><td> - </td></tr> * <tr><td> 401 </td><td> Unauthorized </td><td> - </td></tr> * <tr><td> 404 </td><td> Not Found </td><td> - </td></tr> * </table> */ public okhttp3.Call deleteF24Async( Integer companyId, Integer documentId, final ApiCallback<Void> _callback) throws ApiException { okhttp3.Call localVarCall = deleteF24ValidateBeforeCall(companyId, documentId, _callback); localVarApiClient.executeAsync(localVarCall, _callback); return localVarCall; } /** * Build call for deleteF24Attachment * * @param companyId The ID of the company. (required) * @param documentId The ID of the document. (required) * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object * @http.response.details * <table border="1"> * <caption>Response Details</caption> * <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> * <tr><td> 200 </td><td> File Removed. </td><td> - </td></tr> * <tr><td> 401 </td><td> Unauthorized </td><td> - </td></tr> * <tr><td> 404 </td><td> Not Found </td><td> - </td></tr> * </table> */ public okhttp3.Call deleteF24AttachmentCall( Integer companyId, Integer documentId, final ApiCallback _callback) throws ApiException { String basePath = null; // Operation Servers String[] localBasePaths = new String[] {}; // Determine Base Path to Use if (localCustomBaseUrl != null) { basePath = localCustomBaseUrl; } else if (localBasePaths.length > 0) { basePath = localBasePaths[localHostIndex]; } else { basePath = null; } Object localVarPostBody = null; // create path and map variables String localVarPath = "/c/{company_id}/taxes/{document_id}/attachment" .replaceAll( "\\{" + "company_id" + "\\}", localVarApiClient.escapeString(companyId.toString())) .replaceAll( "\\{" + "document_id" + "\\}", localVarApiClient.escapeString(documentId.toString())); List<Pair> localVarQueryParams = new ArrayList<Pair>(); List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>(); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); Map<String, String> localVarCookieParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = {}; final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) { localVarHeaderParams.put("Accept", localVarAccept); } final String[] localVarContentTypes = {}; final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); if (localVarContentType != null) { localVarHeaderParams.put("Content-Type", localVarContentType); } String[] localVarAuthNames = new String[] {"OAuth2AuthenticationCodeFlow"}; return localVarApiClient.buildCall( basePath, localVarPath, "DELETE", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") private okhttp3.Call deleteF24AttachmentValidateBeforeCall( Integer companyId, Integer documentId, final ApiCallback _callback) throws ApiException { // verify the required parameter 'companyId' is set if (companyId == null) { throw new ApiException( "Missing the required parameter 'companyId' when calling deleteF24Attachment(Async)"); } // verify the required parameter 'documentId' is set if (documentId == null) { throw new ApiException( "Missing the required parameter 'documentId' when calling deleteF24Attachment(Async)"); } okhttp3.Call localVarCall = deleteF24AttachmentCall(companyId, documentId, _callback); return localVarCall; } /** * Delete F24 Attachment Removes the attachment of the specified F24. * * @param companyId The ID of the company. (required) * @param documentId The ID of the document. (required) * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the * response body * @http.response.details * <table border="1"> * <caption>Response Details</caption> * <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> * <tr><td> 200 </td><td> File Removed. </td><td> - </td></tr> * <tr><td> 401 </td><td> Unauthorized </td><td> - </td></tr> * <tr><td> 404 </td><td> Not Found </td><td> - </td></tr> * </table> */ public void deleteF24Attachment(Integer companyId, Integer documentId) throws ApiException { deleteF24AttachmentWithHttpInfo(companyId, documentId); } /** * Delete F24 Attachment Removes the attachment of the specified F24. * * @param companyId The ID of the company. (required) * @param documentId The ID of the document. (required) * @return ApiResponse&lt;Void&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the * response body * @http.response.details * <table border="1"> * <caption>Response Details</caption> * <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> * <tr><td> 200 </td><td> File Removed. </td><td> - </td></tr> * <tr><td> 401 </td><td> Unauthorized </td><td> - </td></tr> * <tr><td> 404 </td><td> Not Found </td><td> - </td></tr> * </table> */ public ApiResponse<Void> deleteF24AttachmentWithHttpInfo(Integer companyId, Integer documentId) throws ApiException { okhttp3.Call localVarCall = deleteF24AttachmentValidateBeforeCall(companyId, documentId, null); return localVarApiClient.execute(localVarCall); } /** * Delete F24 Attachment (asynchronously) Removes the attachment of the specified F24. * * @param companyId The ID of the company. (required) * @param documentId The ID of the document. (required) * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object * @http.response.details * <table border="1"> * <caption>Response Details</caption> * <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> * <tr><td> 200 </td><td> File Removed. </td><td> - </td></tr> * <tr><td> 401 </td><td> Unauthorized </td><td> - </td></tr> * <tr><td> 404 </td><td> Not Found </td><td> - </td></tr> * </table> */ public okhttp3.Call deleteF24AttachmentAsync( Integer companyId, Integer documentId, final ApiCallback<Void> _callback) throws ApiException { okhttp3.Call localVarCall = deleteF24AttachmentValidateBeforeCall(companyId, documentId, _callback); localVarApiClient.executeAsync(localVarCall, _callback); return localVarCall; } /** * Build call for getF24 * * @param companyId The ID of the company. (required) * @param documentId The ID of the document. (required) * @param fields List of comma-separated fields. (optional) * @param fieldset Name of the fieldset. (optional) * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object * @http.response.details * <table border="1"> * <caption>Response Details</caption> * <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> * <tr><td> 200 </td><td> The F24 </td><td> - </td></tr> * <tr><td> 401 </td><td> Unauthorized </td><td> - </td></tr> * <tr><td> 404 </td><td> Not Found </td><td> - </td></tr> * </table> */ public okhttp3.Call getF24Call( Integer companyId, Integer documentId, String fields, String fieldset, final ApiCallback _callback) throws ApiException { String basePath = null; // Operation Servers String[] localBasePaths = new String[] {}; // Determine Base Path to Use if (localCustomBaseUrl != null) { basePath = localCustomBaseUrl; } else if (localBasePaths.length > 0) { basePath = localBasePaths[localHostIndex]; } else { basePath = null; } Object localVarPostBody = null; // create path and map variables String localVarPath = "/c/{company_id}/taxes/{document_id}" .replaceAll( "\\{" + "company_id" + "\\}", localVarApiClient.escapeString(companyId.toString())) .replaceAll( "\\{" + "document_id" + "\\}", localVarApiClient.escapeString(documentId.toString())); List<Pair> localVarQueryParams = new ArrayList<Pair>(); List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>(); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); Map<String, String> localVarCookieParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); if (fields != null) { localVarQueryParams.addAll(localVarApiClient.parameterToPair("fields", fields)); } if (fieldset != null) { localVarQueryParams.addAll(localVarApiClient.parameterToPair("fieldset", fieldset)); } final String[] localVarAccepts = {"application/json"}; final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) { localVarHeaderParams.put("Accept", localVarAccept); } final String[] localVarContentTypes = {}; final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); if (localVarContentType != null) { localVarHeaderParams.put("Content-Type", localVarContentType); } String[] localVarAuthNames = new String[] {"OAuth2AuthenticationCodeFlow"}; return localVarApiClient.buildCall( basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") private okhttp3.Call getF24ValidateBeforeCall( Integer companyId, Integer documentId, String fields, String fieldset, final ApiCallback _callback) throws ApiException { // verify the required parameter 'companyId' is set if (companyId == null) { throw new ApiException( "Missing the required parameter 'companyId' when calling getF24(Async)"); } // verify the required parameter 'documentId' is set if (documentId == null) { throw new ApiException( "Missing the required parameter 'documentId' when calling getF24(Async)"); } okhttp3.Call localVarCall = getF24Call(companyId, documentId, fields, fieldset, _callback); return localVarCall; } /** * Get F24 Gets the specified F24. * * @param companyId The ID of the company. (required) * @param documentId The ID of the document. (required) * @param fields List of comma-separated fields. (optional) * @param fieldset Name of the fieldset. (optional) * @return GetF24Response * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the * response body * @http.response.details * <table border="1"> * <caption>Response Details</caption> * <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> * <tr><td> 200 </td><td> The F24 </td><td> - </td></tr> * <tr><td> 401 </td><td> Unauthorized </td><td> - </td></tr> * <tr><td> 404 </td><td> Not Found </td><td> - </td></tr> * </table> */ public GetF24Response getF24( Integer companyId, Integer documentId, String fields, String fieldset) throws ApiException { ApiResponse<GetF24Response> localVarResp = getF24WithHttpInfo(companyId, documentId, fields, fieldset); return localVarResp.getData(); } /** * Get F24 Gets the specified F24. * * @param companyId The ID of the company. (required) * @param documentId The ID of the document. (required) * @param fields List of comma-separated fields. (optional) * @param fieldset Name of the fieldset. (optional) * @return ApiResponse&lt;GetF24Response&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the * response body * @http.response.details * <table border="1"> * <caption>Response Details</caption> * <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> * <tr><td> 200 </td><td> The F24 </td><td> - </td></tr> * <tr><td> 401 </td><td> Unauthorized </td><td> - </td></tr> * <tr><td> 404 </td><td> Not Found </td><td> - </td></tr> * </table> */ public ApiResponse<GetF24Response> getF24WithHttpInfo( Integer companyId, Integer documentId, String fields, String fieldset) throws ApiException { okhttp3.Call localVarCall = getF24ValidateBeforeCall(companyId, documentId, fields, fieldset, null); Type localVarReturnType = new TypeToken<GetF24Response>() {}.getType(); return localVarApiClient.execute(localVarCall, localVarReturnType); } /** * Get F24 (asynchronously) Gets the specified F24. * * @param companyId The ID of the company. (required) * @param documentId The ID of the document. (required) * @param fields List of comma-separated fields. (optional) * @param fieldset Name of the fieldset. (optional) * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object * @http.response.details * <table border="1"> * <caption>Response Details</caption> * <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> * <tr><td> 200 </td><td> The F24 </td><td> - </td></tr> * <tr><td> 401 </td><td> Unauthorized </td><td> - </td></tr> * <tr><td> 404 </td><td> Not Found </td><td> - </td></tr> * </table> */ public okhttp3.Call getF24Async( Integer companyId, Integer documentId, String fields, String fieldset, final ApiCallback<GetF24Response> _callback) throws ApiException { okhttp3.Call localVarCall = getF24ValidateBeforeCall(companyId, documentId, fields, fieldset, _callback); Type localVarReturnType = new TypeToken<GetF24Response>() {}.getType(); localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); return localVarCall; } /** * Build call for listF24 * * @param companyId The ID of the company. (required) * @param fields List of comma-separated fields. (optional) * @param fieldset Name of the fieldset. (optional) * @param sort List of comma-separated fields for result sorting (minus for desc sorting). * (optional) * @param page The page to retrieve. (optional, default to 1) * @param perPage The size of the page. (optional, default to 5) * @param q Query for filtering the results. (optional) * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object * @http.response.details * <table border="1"> * <caption>Response Details</caption> * <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> * <tr><td> 200 </td><td> Results list. </td><td> - </td></tr> * <tr><td> 401 </td><td> Unauthorized </td><td> - </td></tr> * </table> */ public okhttp3.Call listF24Call( Integer companyId, String fields, String fieldset, String sort, Integer page, Integer perPage, String q, final ApiCallback _callback) throws ApiException { String basePath = null; // Operation Servers String[] localBasePaths = new String[] {}; // Determine Base Path to Use if (localCustomBaseUrl != null) { basePath = localCustomBaseUrl; } else if (localBasePaths.length > 0) { basePath = localBasePaths[localHostIndex]; } else { basePath = null; } Object localVarPostBody = null; // create path and map variables String localVarPath = "/c/{company_id}/taxes" .replaceAll( "\\{" + "company_id" + "\\}", localVarApiClient.escapeString(companyId.toString())); List<Pair> localVarQueryParams = new ArrayList<Pair>(); List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>(); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); Map<String, String> localVarCookieParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); if (fields != null) { localVarQueryParams.addAll(localVarApiClient.parameterToPair("fields", fields)); } if (fieldset != null) { localVarQueryParams.addAll(localVarApiClient.parameterToPair("fieldset", fieldset)); } if (sort != null) { localVarQueryParams.addAll(localVarApiClient.parameterToPair("sort", sort)); } if (page != null) { localVarQueryParams.addAll(localVarApiClient.parameterToPair("page", page)); } if (perPage != null) { localVarQueryParams.addAll(localVarApiClient.parameterToPair("per_page", perPage)); } if (q != null) { localVarQueryParams.addAll(localVarApiClient.parameterToPair("q", q)); } final String[] localVarAccepts = {"application/json"}; final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) { localVarHeaderParams.put("Accept", localVarAccept); } final String[] localVarContentTypes = {}; final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); if (localVarContentType != null) { localVarHeaderParams.put("Content-Type", localVarContentType); } String[] localVarAuthNames = new String[] {"OAuth2AuthenticationCodeFlow"}; return localVarApiClient.buildCall( basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") private okhttp3.Call listF24ValidateBeforeCall( Integer companyId, String fields, String fieldset, String sort, Integer page, Integer perPage, String q, final ApiCallback _callback) throws ApiException { // verify the required parameter 'companyId' is set if (companyId == null) { throw new ApiException( "Missing the required parameter 'companyId' when calling listF24(Async)"); } okhttp3.Call localVarCall = listF24Call(companyId, fields, fieldset, sort, page, perPage, q, _callback); return localVarCall; } /** * List F24 Lists the F24s. * * @param companyId The ID of the company. (required) * @param fields List of comma-separated fields. (optional) * @param fieldset Name of the fieldset. (optional) * @param sort List of comma-separated fields for result sorting (minus for desc sorting). * (optional) * @param page The page to retrieve. (optional, default to 1) * @param perPage The size of the page. (optional, default to 5) * @param q Query for filtering the results. (optional) * @return ListF24Response * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the * response body * @http.response.details * <table border="1"> * <caption>Response Details</caption> * <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> * <tr><td> 200 </td><td> Results list. </td><td> - </td></tr> * <tr><td> 401 </td><td> Unauthorized </td><td> - </td></tr> * </table> */ public ListF24Response listF24( Integer companyId, String fields, String fieldset, String sort, Integer page, Integer perPage, String q) throws ApiException { ApiResponse<ListF24Response> localVarResp = listF24WithHttpInfo(companyId, fields, fieldset, sort, page, perPage, q); return localVarResp.getData(); } /** * List F24 Lists the F24s. * * @param companyId The ID of the company. (required) * @param fields List of comma-separated fields. (optional) * @param fieldset Name of the fieldset. (optional) * @param sort List of comma-separated fields for result sorting (minus for desc sorting). * (optional) * @param page The page to retrieve. (optional, default to 1) * @param perPage The size of the page. (optional, default to 5) * @param q Query for filtering the results. (optional) * @return ApiResponse&lt;ListF24Response&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the * response body * @http.response.details * <table border="1"> * <caption>Response Details</caption> * <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> * <tr><td> 200 </td><td> Results list. </td><td> - </td></tr> * <tr><td> 401 </td><td> Unauthorized </td><td> - </td></tr> * </table> */ public ApiResponse<ListF24Response> listF24WithHttpInfo( Integer companyId, String fields, String fieldset, String sort, Integer page, Integer perPage, String q) throws ApiException { okhttp3.Call localVarCall = listF24ValidateBeforeCall(companyId, fields, fieldset, sort, page, perPage, q, null); Type localVarReturnType = new TypeToken<ListF24Response>() {}.getType(); return localVarApiClient.execute(localVarCall, localVarReturnType); } /** * List F24 (asynchronously) Lists the F24s. * * @param companyId The ID of the company. (required) * @param fields List of comma-separated fields. (optional) * @param fieldset Name of the fieldset. (optional) * @param sort List of comma-separated fields for result sorting (minus for desc sorting). * (optional) * @param page The page to retrieve. (optional, default to 1) * @param perPage The size of the page. (optional, default to 5) * @param q Query for filtering the results. (optional) * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object * @http.response.details * <table border="1"> * <caption>Response Details</caption> * <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> * <tr><td> 200 </td><td> Results list. </td><td> - </td></tr> * <tr><td> 401 </td><td> Unauthorized </td><td> - </td></tr> * </table> */ public okhttp3.Call listF24Async( Integer companyId, String fields, String fieldset, String sort, Integer page, Integer perPage, String q, final ApiCallback<ListF24Response> _callback) throws ApiException { okhttp3.Call localVarCall = listF24ValidateBeforeCall(companyId, fields, fieldset, sort, page, perPage, q, _callback); Type localVarReturnType = new TypeToken<ListF24Response>() {}.getType(); localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); return localVarCall; } /** * Build call for modifyF24 * * @param companyId The ID of the company. (required) * @param documentId The ID of the document. (required) * @param modifyF24Request The F24 (optional) * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object * @http.response.details * <table border="1"> * <caption>Response Details</caption> * <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> * <tr><td> 200 </td><td> The modified F24 </td><td> - </td></tr> * <tr><td> 401 </td><td> Unauthorized </td><td> - </td></tr> * <tr><td> 404 </td><td> Not Found </td><td> - </td></tr> * </table> */ public okhttp3.Call modifyF24Call( Integer companyId, Integer documentId, ModifyF24Request modifyF24Request, final ApiCallback _callback) throws ApiException { String basePath = null; // Operation Servers String[] localBasePaths = new String[] {}; // Determine Base Path to Use if (localCustomBaseUrl != null) { basePath = localCustomBaseUrl; } else if (localBasePaths.length > 0) { basePath = localBasePaths[localHostIndex]; } else { basePath = null; } Object localVarPostBody = modifyF24Request; // create path and map variables String localVarPath = "/c/{company_id}/taxes/{document_id}" .replaceAll( "\\{" + "company_id" + "\\}", localVarApiClient.escapeString(companyId.toString())) .replaceAll( "\\{" + "document_id" + "\\}", localVarApiClient.escapeString(documentId.toString())); List<Pair> localVarQueryParams = new ArrayList<Pair>(); List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>(); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); Map<String, String> localVarCookieParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); final String[] localVarAccepts = {"application/json"}; final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) { localVarHeaderParams.put("Accept", localVarAccept); } final String[] localVarContentTypes = {"application/json"}; final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); if (localVarContentType != null) { localVarHeaderParams.put("Content-Type", localVarContentType); } String[] localVarAuthNames = new String[] {"OAuth2AuthenticationCodeFlow"}; return localVarApiClient.buildCall( basePath, localVarPath, "PUT", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") private okhttp3.Call modifyF24ValidateBeforeCall( Integer companyId, Integer documentId, ModifyF24Request modifyF24Request, final ApiCallback _callback) throws ApiException { // verify the required parameter 'companyId' is set if (companyId == null) { throw new ApiException( "Missing the required parameter 'companyId' when calling modifyF24(Async)"); } // verify the required parameter 'documentId' is set if (documentId == null) { throw new ApiException( "Missing the required parameter 'documentId' when calling modifyF24(Async)"); } okhttp3.Call localVarCall = modifyF24Call(companyId, documentId, modifyF24Request, _callback); return localVarCall; } /** * Modify F24 Modifies the specified F24. * * @param companyId The ID of the company. (required) * @param documentId The ID of the document. (required) * @param modifyF24Request The F24 (optional) * @return ModifyF24Response * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the * response body * @http.response.details * <table border="1"> * <caption>Response Details</caption> * <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> * <tr><td> 200 </td><td> The modified F24 </td><td> - </td></tr> * <tr><td> 401 </td><td> Unauthorized </td><td> - </td></tr> * <tr><td> 404 </td><td> Not Found </td><td> - </td></tr> * </table> */ public ModifyF24Response modifyF24( Integer companyId, Integer documentId, ModifyF24Request modifyF24Request) throws ApiException { ApiResponse<ModifyF24Response> localVarResp = modifyF24WithHttpInfo(companyId, documentId, modifyF24Request); return localVarResp.getData(); } /** * Modify F24 Modifies the specified F24. * * @param companyId The ID of the company. (required) * @param documentId The ID of the document. (required) * @param modifyF24Request The F24 (optional) * @return ApiResponse&lt;ModifyF24Response&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the * response body * @http.response.details * <table border="1"> * <caption>Response Details</caption> * <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> * <tr><td> 200 </td><td> The modified F24 </td><td> - </td></tr> * <tr><td> 401 </td><td> Unauthorized </td><td> - </td></tr> * <tr><td> 404 </td><td> Not Found </td><td> - </td></tr> * </table> */ public ApiResponse<ModifyF24Response> modifyF24WithHttpInfo( Integer companyId, Integer documentId, ModifyF24Request modifyF24Request) throws ApiException { okhttp3.Call localVarCall = modifyF24ValidateBeforeCall(companyId, documentId, modifyF24Request, null); Type localVarReturnType = new TypeToken<ModifyF24Response>() {}.getType(); return localVarApiClient.execute(localVarCall, localVarReturnType); } /** * Modify F24 (asynchronously) Modifies the specified F24. * * @param companyId The ID of the company. (required) * @param documentId The ID of the document. (required) * @param modifyF24Request The F24 (optional) * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object * @http.response.details * <table border="1"> * <caption>Response Details</caption> * <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> * <tr><td> 200 </td><td> The modified F24 </td><td> - </td></tr> * <tr><td> 401 </td><td> Unauthorized </td><td> - </td></tr> * <tr><td> 404 </td><td> Not Found </td><td> - </td></tr> * </table> */ public okhttp3.Call modifyF24Async( Integer companyId, Integer documentId, ModifyF24Request modifyF24Request, final ApiCallback<ModifyF24Response> _callback) throws ApiException { okhttp3.Call localVarCall = modifyF24ValidateBeforeCall(companyId, documentId, modifyF24Request, _callback); Type localVarReturnType = new TypeToken<ModifyF24Response>() {}.getType(); localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); return localVarCall; } /** * Build call for uploadF24Attachment * * @param companyId The ID of the company. (required) * @param filename Name of the file. (optional) * @param attachment Valid format: .png, .jpg, .gif, .pdf, .zip, .xls, .xlsx, .doc, .docx * (optional) * @param _callback Callback for upload/download progress * @return Call to execute * @throws ApiException If fail to serialize the request body object * @http.response.details * <table border="1"> * <caption>Response Details</caption> * <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> * <tr><td> 200 </td><td> Attachment Token. </td><td> - </td></tr> * </table> */ public okhttp3.Call uploadF24AttachmentCall( Integer companyId, String filename, File attachment, final ApiCallback _callback) throws ApiException { String basePath = null; // Operation Servers String[] localBasePaths = new String[] {}; // Determine Base Path to Use if (localCustomBaseUrl != null) { basePath = localCustomBaseUrl; } else if (localBasePaths.length > 0) { basePath = localBasePaths[localHostIndex]; } else { basePath = null; } Object localVarPostBody = null; // create path and map variables String localVarPath = "/c/{company_id}/taxes/attachment" .replaceAll( "\\{" + "company_id" + "\\}", localVarApiClient.escapeString(companyId.toString())); List<Pair> localVarQueryParams = new ArrayList<Pair>(); List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>(); Map<String, String> localVarHeaderParams = new HashMap<String, String>(); Map<String, String> localVarCookieParams = new HashMap<String, String>(); Map<String, Object> localVarFormParams = new HashMap<String, Object>(); if (filename != null) { localVarFormParams.put("filename", filename); } if (attachment != null) { localVarFormParams.put("attachment", attachment); } final String[] localVarAccepts = {"application/json"}; final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); if (localVarAccept != null) { localVarHeaderParams.put("Accept", localVarAccept); } final String[] localVarContentTypes = {"multipart/form-data"}; final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); if (localVarContentType != null) { localVarHeaderParams.put("Content-Type", localVarContentType); } String[] localVarAuthNames = new String[] {"OAuth2AuthenticationCodeFlow"}; return localVarApiClient.buildCall( basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") private okhttp3.Call uploadF24AttachmentValidateBeforeCall( Integer companyId, String filename, File attachment, final ApiCallback _callback) throws ApiException { // verify the required parameter 'companyId' is set if (companyId == null) { throw new ApiException( "Missing the required parameter 'companyId' when calling uploadF24Attachment(Async)"); } okhttp3.Call localVarCall = uploadF24AttachmentCall(companyId, filename, attachment, _callback); return localVarCall; } /** * Upload F24 Attachment Uploads an attachment destined to a F24. The actual association between * the document and the attachment must be implemented separately, using the returned token. * * @param companyId The ID of the company. (required) * @param filename Name of the file. (optional) * @param attachment Valid format: .png, .jpg, .gif, .pdf, .zip, .xls, .xlsx, .doc, .docx * (optional) * @return UploadF24AttachmentResponse * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the * response body * @http.response.details * <table border="1"> * <caption>Response Details</caption> * <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> * <tr><td> 200 </td><td> Attachment Token. </td><td> - </td></tr> * </table> */ public UploadF24AttachmentResponse uploadF24Attachment( Integer companyId, String filename, File attachment) throws ApiException { ApiResponse<UploadF24AttachmentResponse> localVarResp = uploadF24AttachmentWithHttpInfo(companyId, filename, attachment); return localVarResp.getData(); } /** * Upload F24 Attachment Uploads an attachment destined to a F24. The actual association between * the document and the attachment must be implemented separately, using the returned token. * * @param companyId The ID of the company. (required) * @param filename Name of the file. (optional) * @param attachment Valid format: .png, .jpg, .gif, .pdf, .zip, .xls, .xlsx, .doc, .docx * (optional) * @return ApiResponse&lt;UploadF24AttachmentResponse&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the * response body * @http.response.details * <table border="1"> * <caption>Response Details</caption> * <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> * <tr><td> 200 </td><td> Attachment Token. </td><td> - </td></tr> * </table> */ public ApiResponse<UploadF24AttachmentResponse> uploadF24AttachmentWithHttpInfo( Integer companyId, String filename, File attachment) throws ApiException { okhttp3.Call localVarCall = uploadF24AttachmentValidateBeforeCall(companyId, filename, attachment, null); Type localVarReturnType = new TypeToken<UploadF24AttachmentResponse>() {}.getType(); return localVarApiClient.execute(localVarCall, localVarReturnType); } /** * Upload F24 Attachment (asynchronously) Uploads an attachment destined to a F24. The actual * association between the document and the attachment must be implemented separately, using the * returned token. * * @param companyId The ID of the company. (required) * @param filename Name of the file. (optional) * @param attachment Valid format: .png, .jpg, .gif, .pdf, .zip, .xls, .xlsx, .doc, .docx * (optional) * @param _callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object * @http.response.details * <table border="1"> * <caption>Response Details</caption> * <tr><td> Status Code </td><td> Description </td><td> Response Headers </td></tr> * <tr><td> 200 </td><td> Attachment Token. </td><td> - </td></tr> * </table> */ public okhttp3.Call uploadF24AttachmentAsync( Integer companyId, String filename, File attachment, final ApiCallback<UploadF24AttachmentResponse> _callback) throws ApiException { okhttp3.Call localVarCall = uploadF24AttachmentValidateBeforeCall(companyId, filename, attachment, _callback); Type localVarReturnType = new TypeToken<UploadF24AttachmentResponse>() {}.getType(); localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); return localVarCall; } }
38.562678
263
0.667356
1543f95aa97dc618711d458559dddf2106c31f90
330
package de.thaso.fum.web.ra.api; import javax.resource.ResourceException; import javax.resource.cci.Connection; public interface FumConnection extends Connection{ FumWebLoginUser findLoginUser(final String loginName); Long storeLoginUser(final FumWebLoginUser loginUser); void close() throws ResourceException; }
23.571429
58
0.80303
a85665e9b1d7895bb6b406efd0f036c639705135
4,450
package net.sf.l2j.gameserver.data.manager; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; import net.sf.l2j.commons.logging.CLogger; import net.sf.l2j.L2DatabaseFactory; import net.sf.l2j.gameserver.idfactory.IdFactory; import net.sf.l2j.gameserver.model.World; import net.sf.l2j.gameserver.model.actor.Player; import net.sf.l2j.gameserver.model.holder.IntIntHolder; /** * Custom wedding system implementation.<br> * <br> * Loads and stores couples using {@link IntIntHolder}, id being requesterId and value being partnerId. */ public class CoupleManager { private static final CLogger LOGGER = new CLogger(CoupleManager.class.getName()); private static final String LOAD_COUPLES = "SELECT * FROM mods_wedding"; private static final String DELETE_COUPLES = "DELETE FROM mods_wedding"; private static final String ADD_COUPLE = "INSERT INTO mods_wedding (id, requesterId, partnerId) VALUES (?,?,?)"; private final Map<Integer, IntIntHolder> _couples = new ConcurrentHashMap<>(); protected CoupleManager() { try (Connection con = L2DatabaseFactory.getInstance().getConnection(); PreparedStatement ps = con.prepareStatement(LOAD_COUPLES); ResultSet rs = ps.executeQuery()) { while (rs.next()) _couples.put(rs.getInt("id"), new IntIntHolder(rs.getInt("requesterId"), rs.getInt("partnerId"))); } catch (Exception e) { LOGGER.error("Couldn't load couples.", e); } LOGGER.info("Loaded {} couples.", _couples.size()); } public final Map<Integer, IntIntHolder> getCouples() { return _couples; } public final IntIntHolder getCouple(int coupleId) { return _couples.get(coupleId); } /** * Add a couple to the couples map. Both players must be logged. * @param requester : The wedding requester. * @param partner : The wedding partner. */ public void addCouple(Player requester, Player partner) { if (requester == null || partner == null) return; final int coupleId = IdFactory.getInstance().getNextId(); _couples.put(coupleId, new IntIntHolder(requester.getObjectId(), partner.getObjectId())); requester.setCoupleId(coupleId); partner.setCoupleId(coupleId); } /** * Delete the couple. If players are logged, reset wedding variables. * @param coupleId : The couple id to delete. */ public void deleteCouple(int coupleId) { final IntIntHolder couple = _couples.remove(coupleId); if (couple == null) return; // Inform and reset the couple id of requester. final Player requester = World.getInstance().getPlayer(couple.getId()); if (requester != null) { requester.setCoupleId(0); requester.sendMessage("You are now divorced."); } // Inform and reset the couple id of partner. final Player partner = World.getInstance().getPlayer(couple.getValue()); if (partner != null) { partner.setCoupleId(0); partner.sendMessage("You are now divorced."); } // Release the couple id. IdFactory.getInstance().releaseId(coupleId); } /** * Save all couples on shutdown. Delete previous SQL infos. */ public void save() { try (Connection con = L2DatabaseFactory.getInstance().getConnection()) { try (PreparedStatement ps = con.prepareStatement(DELETE_COUPLES)) { ps.execute(); } try (PreparedStatement ps = con.prepareStatement(ADD_COUPLE)) { for (Entry<Integer, IntIntHolder> coupleEntry : _couples.entrySet()) { final IntIntHolder couple = coupleEntry.getValue(); ps.setInt(1, coupleEntry.getKey()); ps.setInt(2, couple.getId()); ps.setInt(3, couple.getValue()); ps.addBatch(); } ps.executeBatch(); } } catch (Exception e) { LOGGER.error("Couldn't add a couple.", e); } } /** * @param coupleId : The couple id to check. * @param objectId : The player objectId to check. * @return the partner objectId, or 0 if not found. */ public final int getPartnerId(int coupleId, int objectId) { final IntIntHolder couple = _couples.get(coupleId); if (couple == null) return 0; return (couple.getId() == objectId) ? couple.getValue() : couple.getId(); } public static final CoupleManager getInstance() { return SingletonHolder.INSTANCE; } private static class SingletonHolder { protected static final CoupleManager INSTANCE = new CoupleManager(); } }
27.469136
113
0.706517
b390a4a368dc2ac21251ab7a6d5c3cf5b6ff4b26
2,798
package com.moeee.streambenchmark; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.OptionalInt; import java.util.Random; import java.util.concurrent.TimeUnit; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.Measurement; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.OutputTimeUnit; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.Warmup; /** * Title: StreamBenchmark<br> * Description: 找到最大的数<br> * Create DateTime: 2017年06月08日 上午11:02 <br> * * @author MoEee */ @State(Scope.Benchmark) @BenchmarkMode(Mode.AverageTime) @OutputTimeUnit(TimeUnit.MILLISECONDS) @Fork(2) @Measurement(iterations = 5) @Warmup(iterations = 5) public class StreamBenchmark { int size = 1000000; List<Integer> integers = null; @Setup public void setup1() { integers = new ArrayList<>(size); populate(integers); } public void populate(List<Integer> list) { Random random = new Random(); for (int i = 0; i < size; i++) { list.add(random.nextInt(1000000)); } } //@Benchmark public int forIndexTrans() { int max = Integer.MIN_VALUE; for (int i = 0; i < size; i++) { max = Math.max(max, integers.get(i)); } return max; } @Benchmark public int forEnhancedTrans() { int max = Integer.MIN_VALUE; for (Integer n : integers) { max = Math.max(max, n); } return max; } //@Benchmark public int iteratorTrans() { int max = Integer.MIN_VALUE; for (Iterator<Integer> it = integers.iterator(); it.hasNext(); ) { max = Math.max(max, it.next()); } return max; } //@Benchmark public int forEachLambdaTrans() { final Wrapper wrapper = new Wrapper(); wrapper.inner = Integer.MIN_VALUE; integers.forEach(i -> helper(i, wrapper)); return wrapper.inner.intValue(); } public static class Wrapper { public Integer inner; } private int helper(int i, Wrapper wrapper) { wrapper.inner = Math.max(i, wrapper.inner); return wrapper.inner; } @Benchmark public int serialStreamTrans() { OptionalInt max = integers.stream().mapToInt(i -> i.intValue()).max(); return max.getAsInt(); } @Benchmark public int parallelStreamTrans() { OptionalInt max = integers.parallelStream().mapToInt(i -> i.intValue()).max(); return max.getAsInt(); } }
25.907407
86
0.63867
e0873e7508422fb2cf891613591ba8da9676e786
3,294
package biz.t0ugh.neusoup2.service.impl; import biz.t0ugh.neusoup2.Neusoup2ApplicationTests; import biz.t0ugh.neusoup2.pojo.Article; import biz.t0ugh.neusoup2.service.ArticleService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.transaction.annotation.Transactional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.annotation.Resource; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import static org.junit.jupiter.api.Assertions.*; @Transactional class ArticleServiceImplTest extends Neusoup2ApplicationTests { private static final Logger logger = LoggerFactory.getLogger(ArticleServiceImplTest.class); List<Article> articleList = new ArrayList<>(); @Resource ArticleService articleService; @BeforeEach void setUp() { for(int i = 0; i < 15; i++){ Article article = new Article(); article.setArticleLike(i); article.setArticleTime(new Timestamp(System.currentTimeMillis() + i * 1000000)); article.setArticleContent(""+i); article.setUserId(1); article.setArticleTags(""+i); article.setArticleUnlike(i); articleList.add(article); } } @Test void getArticle() { Article article = articleList.get(0); articleService.insertArticle(article); assertNotEquals(0, article.getArticleId()); Article dbArticle = articleService.getArticle(article.getArticleId()); assertNotNull(dbArticle); String updateContent = "noteAndNote"; article.setArticleContent(updateContent); articleService.updateArticle(article); assertEquals(updateContent, article.getArticleContent()); articleService.deleteArticle(article); dbArticle = articleService.getArticle(article.getArticleId()); assertNull(dbArticle); } @Test void rankArticleByLike() { for (Article article:articleList) { articleService.insertArticle(article); } List<Article> articleListRankedByLike = articleService.rankArticleByLike(1,10); assertEquals(10, articleListRankedByLike.size()); Article maxArticle = Collections.max(articleListRankedByLike, Comparator.comparingInt(Article::getArticleLike)); assertEquals(maxArticle, articleListRankedByLike.get(0)); for (Article article:articleList) { articleService.deleteArticle(article); } } @Test void rankArticleByTime() { for (Article article:articleList) { logger.info(article.getArticleTime().toString()); articleService.insertArticle(article); } List<Article> articleListRankedByTime = articleService.rankArticleByTime(1,10); assertEquals(10, articleListRankedByTime.size()); Article maxArticle = Collections.max(articleListRankedByTime, Comparator.comparingInt(Article::getArticleLike)); assertEquals(maxArticle.getArticleId(), articleListRankedByTime.get(0).getArticleId()); for (Article article:articleList) { articleService.deleteArticle(article); } } }
32.613861
120
0.697328
b29244ac8d2361c8f9f41f619476737d92033a44
522
//,temp,WordpressServicePostsAdapter.java,66,72,temp,WordpressServicePagesAdapter.java,67,72 //,3 public class xxx { @Override public Post retrieve(Integer postId, Context context, String password) { LOGGER.debug("Calling retrievePosts: postId {}; postContext: {}", postId, context); checkArgument(postId > 0, "Please provide a non zero post id"); checkNotNull(context, "Provide a post context"); return getSpi().retrieve(this.getApiVersion(), postId, context, password); } };
43.5
92
0.701149
80c1b2fbe42f2ed983a5f59a8d33e6244769f051
902
package com.github.vvinston.functional; import javax.annotation.Nonnull; import java.util.List; import java.util.function.BiConsumer; import java.util.function.BiPredicate; public final class ConditionalBiConsumerBuilderStepTwo<INPUT1, INPUT2> { private final List<Tuple<BiPredicate<INPUT1, INPUT2>, BiConsumer<INPUT1, INPUT2>>> cases; ConditionalBiConsumerBuilderStepTwo(@Nonnull final List<Tuple<BiPredicate<INPUT1, INPUT2>, BiConsumer<INPUT1, INPUT2>>> cases) { this.cases = cases; } public ConditionalBiConsumerBuilderStepThree<INPUT1, INPUT2> consumeWhen(@Nonnull final BiPredicate<INPUT1, INPUT2> predicate) { return new ConditionalBiConsumerBuilderStepThree<>(predicate, cases); } public BiConsumer<INPUT1, INPUT2> otherwise(@Nonnull final BiConsumer<INPUT1, INPUT2> otherwise) { return new ConditionalBiConsumer<>(cases, otherwise); } }
39.217391
132
0.768293
0272e51eb10ec35adb1547ae6aef8d05809a912b
2,162
package com.unbright.query.extension.handler; import com.unbright.query.extension.annotation.OrStatement; import com.unbright.query.extension.annotation.QueryColumn; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.reflect.FieldUtils; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; /** * Created with IDEA * ProjectName: mplus-helper * Date: 2020/4/17 * Time: 11:33 * * @author WZP * @version v1.0 */ @Slf4j class ObjectUtil { static List<Field> filterColumns(Class<?> clazz, Object obj, boolean isOr) { List<Field> fields = FieldUtils.getFieldsListWithAnnotation(clazz, QueryColumn.class); OrStatement statement = clazz.getAnnotation(OrStatement.class); if (statement == null) { return isOr ? new ArrayList<>(0) : fields; } String[] fieldNames = statement.value(); return fields.stream().filter(field -> !isOr ^ checkFieldInOr(field, fieldNames)) .filter(field -> !field.getAnnotation(QueryColumn.class).sort()) .filter(field -> Objects.nonNull(getValue(field, obj))) .collect(Collectors.toList()); } static List<Field> filterSortColumns(Class<?> clazz, Object obj) { List<Field> fields = FieldUtils.getFieldsListWithAnnotation(clazz, QueryColumn.class); return fields.stream().filter(field -> field.getAnnotation(QueryColumn.class).sort()) .filter(field -> Objects.nonNull(getValue(field, obj))) .collect(Collectors.toList()); } static boolean checkFieldInOr(Field field, String[] fieldNames) { return StringUtils.isAllBlank(fieldNames) || Arrays.asList(fieldNames).contains(field.getName()); } static Object getValue(Field field, Object obj) { try { return FieldUtils.readField(field, obj, true); } catch (IllegalAccessException ex) { log.error("获取字段值异常 ====> ", ex); return null; } } }
34.870968
94
0.666975
88fd80743e2e716ee2ccf1670780c4e863fa2820
1,153
package top.huzhurong.fuck.spring.bean; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; import java.io.Serializable; /** * @author [email protected] * @since 2018/12/2 */ public class PortBean implements FactoryBean<ProtocolPort>, InitializingBean,Serializable { public PortBean() { } public PortBean(Integer port) { this.port = port; } private Integer port; private ProtocolPort protocolPort; @Override public void afterPropertiesSet() { protocolPort = new ProtocolPort(); protocolPort.setPort(port); } @Override public ProtocolPort getObject() { return this.protocolPort; } @Override public Class<?> getObjectType() { return ProtocolPort.class; } public Integer getPort() { return port; } public void setPort(Integer port) { this.port = port; } public ProtocolPort getProtocolPort() { return protocolPort; } public void setProtocolPort(ProtocolPort protocolPort) { this.protocolPort = protocolPort; } }
20.589286
91
0.666088
9e75b837c62c6e6a4754c22a3d48d648e94ef10f
2,070
package com.reactive.demo.dvdrental.data.mapper; import com.reactive.demo.dvdrental.api.model.*; import com.reactive.demo.dvdrental.api.request.ActorRequest; import com.reactive.demo.dvdrental.api.request.AddressRequest; import com.reactive.demo.dvdrental.api.request.FilmRequest; import com.reactive.demo.dvdrental.data.entity.*; import org.mapstruct.Mapper; import org.mapstruct.Mapping; import org.mapstruct.Named; import org.mapstruct.factory.Mappers; import java.util.ArrayList; @Mapper(componentModel = "spring") public interface GenericMapper { GenericMapper INSTANCE = Mappers.getMapper(GenericMapper.class); StaffModel convert(Staff staff); Staff convertToStaff(StaffCoreModel staffCoreModel); ActorModel actorToActorModel(Actor actor); AddressModel addressToAddressModel(Address address); CityModel cityToCityModel(City city); CountryModel countryToCountryModel(Country country); CustomerModel customerToCustomerModel(Customer customer); FilmModel filmToFilmModel(Film film); FilmCategoryModel toFilmCategoryModel(FilmCategory filmCategory); InventoryModel toInventoryModel(Inventory inventory); LanguageModel toLanguageModel(Language language); PaymentModel toPaymentModel(Payment payment); RentalModel toRentalModel(Rental rental); StoreModel toStoreModel(Store store); Actor actorModelToActor(ActorModel actorModel); Actor actorRequestToActor(ActorRequest actorModel); Address addressRequestToAddress(AddressRequest addressRequest); @Mapping( source = "specialFeaturesList", target = "specialFeatures", qualifiedByName = "getSpecialFeatures") Film filmRequestToFilm(FilmRequest filmRequest); @Named("getSpecialFeatures") default String[] getSpecialFeatures(ArrayList<String> specialFeatures) { return specialFeatures.stream().toArray(String[]::new); // return specialFeatures.toArray(new String[0]); // return specialFeatures.stream().collect(Collectors.joining(",", "{", "}")); } }
31.363636
86
0.765217
9f0eef77a4f241f46d1aa58ac8a49913dcdb4269
737
package com.nirajaky.lifecycle; public class Samosa { private double price; public double getPrice() { return price; } public void setPrice(double price) { System.out.println("setting price of Samosa"); this.price = price; } public Samosa() { super(); } public Samosa(double price) { this.price = price; } @Override public String toString() { return "Samosa{" + "price=" + price + '}'; } public void init(){ System.out.println("In init method of Samosa"); } public void destroy(){ System.out.println("In destroy Method of Samosa"); } }
20.472222
59
0.518318
7e2499943e22d3932acd02782c364dd6d3233ced
3,263
package com.robin.core.compress.util; import com.robin.core.base.util.Const; import com.robin.core.base.util.FileUtils; import org.anarres.lzo.*; import org.apache.commons.compress.compressors.bzip2.BZip2CompressorOutputStream; import org.tukaani.xz.LZMA2Options; import org.tukaani.xz.LZMAOutputStream; import org.xerial.snappy.SnappyOutputStream; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.List; import java.util.zip.GZIPOutputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; /** * <p>Project: frame</p> * <p> * <p>Description:CompressEncoder</p> * <p> * <p>Copyright: Copyright (c) 2016 create at 2016年12月27日</p> * <p> * <p>Company: TW_DEV</p> * * @author robinjim * @version 1.0 */ public class CompressEncoder { private CompressEncoder(){ } /** *wrap OutputStream with specify compress Format (Zip file can only support One file) * @param path file path * @param rawstream raw outputstream * @return wrap outputStream */ public static OutputStream getOutputStreamByCompressType(String path,OutputStream rawstream) throws IOException{ OutputStream outputStream=null; List<String> suffixList=new ArrayList<String>(); String fileName= FileUtils.parseFileFormat(path,suffixList); Const.CompressType type=FileUtils.getFileCompressType(suffixList); if(!type.equals(Const.CompressType.COMPRESS_TYPE_NONE)){ if(type.equals(Const.CompressType.COMPRESS_TYPE_GZ)){ outputStream=new GZIPOutputStream(wrapOutputStream(rawstream)); }else if(type.equals(Const.CompressType.COMPRESS_TYPE_BZ2)){ outputStream=new BZip2CompressorOutputStream(wrapOutputStream(rawstream)); }else if(type.equals(Const.CompressType.COMPRESS_TYPE_LZO)){ LzoAlgorithm algorithm = LzoAlgorithm.LZO1X; LzoCompressor compressor = LzoLibrary.getInstance().newCompressor(algorithm, null); outputStream = new LzoOutputStream(wrapOutputStream(rawstream), compressor); }else if(type.equals(Const.CompressType.COMPRESS_TYPE_SNAPPY)){ outputStream=new SnappyOutputStream(wrapOutputStream(rawstream)); }else if(type.equals(Const.CompressType.COMPRESS_TYPE_ZIP)){ ZipOutputStream stream1=new ZipOutputStream(wrapOutputStream(rawstream)); stream1.putNextEntry(new ZipEntry(fileName)); outputStream=stream1; }else if(type.equals(Const.CompressType.COMPRESS_TYPE_LZMA)){ outputStream=new LZMAOutputStream(wrapOutputStream(rawstream),new LZMA2Options(),false); } }else{ //no compress outputStream=rawstream; } return outputStream; } private static OutputStream wrapOutputStream(OutputStream outputStream){ OutputStream out=null; if(outputStream instanceof BufferedOutputStream){ out=outputStream; }else{ out=new BufferedOutputStream(outputStream); } return out; } }
38.845238
116
0.692614
e49be80c85afaac267cc51a50dd6df293f6eb27d
9,681
/* * #%L * mosaic-drivers-stubs-amqp * %% * Copyright (C) 2010 - 2013 Institute e-Austria Timisoara (Romania) * %% * 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% */ package eu.mosaic_cloud.drivers.queue.amqp.component; import java.io.IOException; import java.net.InetAddress; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.util.HashMap; import java.util.Map; import eu.mosaic_cloud.components.core.ComponentAcquireReply; import eu.mosaic_cloud.components.core.ComponentCallReference; import eu.mosaic_cloud.components.core.ComponentCallReply; import eu.mosaic_cloud.components.core.ComponentCallRequest; import eu.mosaic_cloud.components.core.ComponentController; import eu.mosaic_cloud.components.core.ComponentEnvironment; import eu.mosaic_cloud.components.core.ComponentIdentifier; import eu.mosaic_cloud.drivers.ConfigProperties; import eu.mosaic_cloud.drivers.component.AbstractDriverComponentCallbacks; import eu.mosaic_cloud.drivers.queue.amqp.interop.AmqpStub; import eu.mosaic_cloud.interoperability.implementations.zeromq.ZeroMqChannel; import eu.mosaic_cloud.platform.implementation.v2.configuration.ConfigUtils; import eu.mosaic_cloud.platform.implementation.v2.configuration.PropertyTypeConfiguration; import eu.mosaic_cloud.platform.interop.specs.amqp.AmqpSession; import eu.mosaic_cloud.platform.v2.configuration.Configuration; import eu.mosaic_cloud.platform.v2.configuration.ConfigurationIdentifier; import eu.mosaic_cloud.tools.callbacks.core.CallbackCompletion; import com.google.common.base.Preconditions; /** * This callback class enables the AMQP driver to be exposed as a component. Upon initialization it will look for a RabbitMQ * server and will create a driver object for the server. * * @author Georgiana Macariu */ public final class AmqpDriverComponentCallbacks extends AbstractDriverComponentCallbacks { /** * Creates a driver callback. */ public AmqpDriverComponentCallbacks (final ComponentEnvironment context) { super (context); try { final Configuration configuration = PropertyTypeConfiguration.create (AmqpDriverComponentCallbacks.class.getResourceAsStream ("driver-component.properties")); this.setDriverConfiguration (configuration); this.resourceGroup = ComponentIdentifier.resolve (ConfigUtils.resolveParameter (this.getDriverConfiguration (), ConfigProperties.AmqpDriverComponentCallbacks_0, String.class, "")); this.selfGroup = ComponentIdentifier.resolve (ConfigUtils.resolveParameter (this.getDriverConfiguration (), ConfigProperties.AmqpDriverComponentCallbacks_1, String.class, "")); this.status = Status.Created; } catch (final IOException e) { this.exceptions.traceIgnoredException (e); } } @Override public final CallbackCompletion<Void> acquireReturned (final ComponentController component, final ComponentAcquireReply reply) { throw (new IllegalStateException ()); } @Override public CallbackCompletion<Void> called (final ComponentController component, final ComponentCallRequest request) { Preconditions.checkState (this.component == component); Preconditions.checkState ((this.status != Status.Terminated) && (this.status != Status.Unregistered)); if (this.status == Status.Registered) { if (request.operation.equals (ConfigProperties.AmqpDriverComponentCallbacks_5)) { String channelEndpoint = ConfigUtils.resolveParameter (this.getDriverConfiguration (), ConfigProperties.AmqpDriverComponentCallbacks_3, String.class, ""); // FIXME: These parameters should be determined through //-- component "resource acquire" operations. //-- Also this hack reduces the number of driver instances of //-- the same type to one per VM. try { if (System.getenv ("mosaic_node_ip") != null) { channelEndpoint = channelEndpoint.replace ("0.0.0.0", System.getenv ("mosaic_node_ip")); } else { channelEndpoint = channelEndpoint.replace ("0.0.0.0", InetAddress.getLocalHost ().getHostAddress ()); } } catch (final UnknownHostException e) { this.exceptions.traceIgnoredException (e); } final String channelId = ConfigUtils.resolveParameter (this.getDriverConfiguration (), ConfigProperties.AmqpDriverComponentCallbacks_4, String.class, ""); final Map<String, String> outcome = new HashMap<String, String> (); outcome.put ("channelEndpoint", channelEndpoint); outcome.put ("channelIdentifier", channelId); final ComponentCallReply reply = ComponentCallReply.create (true, outcome, ByteBuffer.allocate (0), request.reference); component.callReturn (reply); } else { throw new UnsupportedOperationException (); } } else { throw new UnsupportedOperationException (); } return null; } @Override public CallbackCompletion<Void> callReturned (final ComponentController component, final ComponentCallReply reply) { Preconditions.checkState (this.component == component); if ((this.pendingReference == reply.reference) && (this.status == Status.WaitingResourceResolved)) { String rabbitmqTransport; String brokerIp; Integer brokerPort; String user; String password; String virtualHost; if (reply.ok && (reply.outputsOrError instanceof Map)) { final Map<?, ?> outputs = (Map<?, ?>) reply.outputsOrError; rabbitmqTransport = (String) outputs.get ("transport"); brokerIp = (String) outputs.get ("ip"); brokerPort = (Integer) outputs.get ("port"); if (!"tcp".equals (rabbitmqTransport) || (brokerIp == null) || (brokerPort == null)) { this.terminate (); this.logger.error ("failed resolving RabbitMQ broker endpoint: `" + reply.outputsOrError + "`; terminating!"); throw new IllegalStateException (); } user = (String) outputs.get ("username"); password = (String) outputs.get ("password"); virtualHost = (String) outputs.get ("virtualHost"); user = user != null ? user : ""; password = password != null ? password : ""; virtualHost = virtualHost != null ? virtualHost : ""; this.logger.debug ("Resolved RabbitMQ on " + brokerIp + ":" + brokerPort + " user = " + user + " password = " + password + " vhost = " + virtualHost); this.configureDriver (brokerIp, brokerPort.toString (), user, password, virtualHost); } if (this.selfGroup != null) { this.pendingReference = ComponentCallReference.create (); this.status = Status.Unregistered; this.component.register (this.selfGroup, this.pendingReference); } } else { throw new IllegalStateException (); } return null; } @Override public CallbackCompletion<Void> initialized (final ComponentController component) { Preconditions.checkState (this.component == null); Preconditions.checkState (this.status == Status.Created); this.component = component; final ComponentCallReference callReference = ComponentCallReference.create (); this.pendingReference = callReference; this.status = Status.WaitingResourceResolved; this.component.call (this.resourceGroup, ComponentCallRequest.create (ConfigProperties.AmqpDriverComponentCallbacks_2, null, callReference)); this.logger.trace ("AMQP driver callback initialized."); return null; } @Override public CallbackCompletion<Void> registerReturned (final ComponentController component, final ComponentCallReference reference, final boolean registerOk) { Preconditions.checkState (this.component == component); if (this.pendingReference == reference) { if (!registerOk) { final Exception e = new Exception ("failed registering to group; terminating!"); this.exceptions.traceDeferredException (e); this.component.terminate (); throw (new IllegalStateException (e)); } this.logger.info ("AMQP driver callback registered to group " + this.selfGroup); this.status = Status.Registered; // NOTE: create stub and interop channel final String channelId = ConfigProperties.AmqpDriverComponentCallbacks_4; final String channelEndpoint = ConfigProperties.AmqpDriverComponentCallbacks_3; final ZeroMqChannel driverChannel = this.createDriverChannel (channelId, channelEndpoint, AmqpSession.DRIVER); this.stub = AmqpStub.create (this.getDriverConfiguration (), driverChannel, this.threading); } else { throw new IllegalStateException (); } return null; } private void configureDriver (final String brokerIp, final String port, final String user, final String pass, final String vHost) { try { this.getDriverConfiguration ().addParameter (ConfigurationIdentifier.resolveRelative (ConfigProperties.AmqpDriver_1), brokerIp); this.getDriverConfiguration ().addParameter (ConfigurationIdentifier.resolveRelative (ConfigProperties.AmqpDriver_2), port); this.getDriverConfiguration ().addParameter (ConfigurationIdentifier.resolveRelative (ConfigProperties.AmqpDriver_3), user); this.getDriverConfiguration ().addParameter (ConfigurationIdentifier.resolveRelative (ConfigProperties.AmqpDriver_4), pass); this.getDriverConfiguration ().addParameter (ConfigurationIdentifier.resolveRelative (ConfigProperties.AmqpDriver_5), vHost); } catch (final NullPointerException e) { this.exceptions.traceIgnoredException (e); } } }
47.22439
183
0.762421
a707433f6877f0bb61cbbafd0edc5c301fa00a99
4,360
/* * 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.wicket.security.swarm; import org.apache.wicket.security.WaspWebApplication; import org.apache.wicket.security.actions.ActionFactory; import org.apache.wicket.security.actions.WaspActionFactory; import org.apache.wicket.security.strategies.StrategyFactory; import org.apache.wicket.security.swarm.actions.SwarmActionFactory; import org.apache.wicket.security.swarm.strategies.SwarmStrategyFactory; /** * A default webapp. It sets up the strategy and action factories and triggers the hive * setup. but you must remember to call super in the init or do your own factory setups. * * @author marrink */ public abstract class SwarmWebApplication extends WaspWebApplication { private WaspActionFactory actionFactory; private StrategyFactory strategyFactory; /** * @see org.apache.wicket.security.WaspWebApplication#setupActionFactory() */ @Override protected void setupActionFactory() { setActionFactory(new SwarmActionFactory(getClass().getName() + ":" + getHiveKey())); } /** * Allows the {@link ActionFactory} field to be set once. * * @param factory * the actionfactory * @throws IllegalStateException * if the factory is set more than once. */ protected final void setActionFactory(WaspActionFactory factory) { if (actionFactory == null) actionFactory = factory; else throw new IllegalStateException("Can not initialize ActionFactory more then once"); } /** * @see org.apache.wicket.security.WaspWebApplication#setupStrategyFactory() */ @Override protected void setupStrategyFactory() { setStrategyFactory(new SwarmStrategyFactory(getHiveKey())); } /** * Allows the {@link StrategyFactory} field to be set once. * * @param factory * the strategyfactory * @throws IllegalStateException * if the factory is set more than once. */ protected final void setStrategyFactory(StrategyFactory factory) { if (strategyFactory == null) strategyFactory = factory; else throw new IllegalStateException("Can not initialize StrategyFactory more then once"); } /** * triggers the setup of the factories and the hive. Please remember to call * super.init when you override this method. * * @see org.apache.wicket.security.WaspWebApplication#init() */ @Override protected void init() { setupActionFactory(); setUpHive(); setupStrategyFactory(); } /** * Set up a Hive for this Application. For Example<br> * <code> * PolicyFileHiveFactory factory = new PolicyFileHiveFactory(); * factory.addPolicyFile("/policy.hive"); * HiveMind.registerHive(getHiveKey(), factory); * </code> Note that you must setup the actionfactory before you can setup the hive. * Note that the hive is not automatically unregistered since there is a chance you * want to share it with another webapp. If you want to unregister the hive please do * so in the {@link #onDestroy()} */ protected abstract void setUpHive(); /** * @see org.apache.wicket.security.WaspApplication#getActionFactory() */ public WaspActionFactory getActionFactory() { return actionFactory; } /** * @see org.apache.wicket.security.WaspApplication#getStrategyFactory() */ public StrategyFactory getStrategyFactory() { return strategyFactory; } /** * Returns the key to specify the hive. * * @return the key */ protected abstract Object getHiveKey(); }
31.142857
89
0.713073
cd9854748d5e49c94df128d0bc77b4f11948e5ad
105
package net.distortsm.api.element; public enum ActivationAnimationStyle { MODELSWAP, KEYFRAME }
15
38
0.761905
789800d2575abfd6eb51d5b4a1b54c23dd44e834
2,210
package iftorrent.daos.daoCategoria; /** * * * A classe <b>Categoria</b> serve para representar uma linha da tabela * categoria do banco de dados. * * @author Eduardo Toffolo * * */ public class Categoria { /** * Um inteiro que representa a chave primária única do objeto.<br> */ private int id_categoria; /** * Um inteiro que representa a chave primária de uma subcategoria.<br> */ private int fk_categoria; /** * * * Construtor vazio. * * */ public Categoria() { } /** * * * Construtor que inicializa todos os atributos. * * @param id_categoria Um inteiro que representa a chave primária do objeto * (única).<br> * @param fk_categoria Um inteiro que representa a chave primária de uma * subcategoria.<br> * * */ public Categoria(int id_categoria, int fk_categoria) { this.id_categoria = id_categoria; this.fk_categoria = fk_categoria; } /** * * * Getter da chave primária do objeto. * * @return Um inteiro que representa a chave primária do objeto.<br> * * */ public int getId_categoria() { return id_categoria; } /** * * * Setter da chave primária do objeto. * * @param id_categoria Um inteiro que representa a chave primária do objeto.<br> * * */ public void setId_categoria(int id_categoria) { this.id_categoria = id_categoria; } /** * * * Getter da subcategoria do objeto. * * @return Um inteiro que representa a chave primária de uma * subcategoria.<br> * * */ public int getFk_categoria() { return fk_categoria; } /** * * * Setter da subcategoria do objeto. * * @param fk_categoria Um inteiro que representa a chave primária de uma * subcategoria.<br> * * */ public void setFk_categoria(int fk_categoria) { this.fk_categoria = fk_categoria; } }
20.654206
85
0.538914
6db911f835f47e9f76dcea86e23c350b3a005a6e
6,367
/* * Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencentcloudapi.cdb.v20170320.models; import com.tencentcloudapi.common.AbstractModel; import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.Expose; import java.util.HashMap; public class AccountInfo extends AbstractModel{ /** * Account remarks */ @SerializedName("Notes") @Expose private String Notes; /** * Account domain name */ @SerializedName("Host") @Expose private String Host; /** * Account name */ @SerializedName("User") @Expose private String User; /** * Account information modification time */ @SerializedName("ModifyTime") @Expose private String ModifyTime; /** * Password modification time */ @SerializedName("ModifyPasswordTime") @Expose private String ModifyPasswordTime; /** * This parameter is no longer supported. */ @SerializedName("CreateTime") @Expose private String CreateTime; /** * The maximum number of instance connections supported by an account */ @SerializedName("MaxUserConnections") @Expose private Long MaxUserConnections; /** * Get Account remarks * @return Notes Account remarks */ public String getNotes() { return this.Notes; } /** * Set Account remarks * @param Notes Account remarks */ public void setNotes(String Notes) { this.Notes = Notes; } /** * Get Account domain name * @return Host Account domain name */ public String getHost() { return this.Host; } /** * Set Account domain name * @param Host Account domain name */ public void setHost(String Host) { this.Host = Host; } /** * Get Account name * @return User Account name */ public String getUser() { return this.User; } /** * Set Account name * @param User Account name */ public void setUser(String User) { this.User = User; } /** * Get Account information modification time * @return ModifyTime Account information modification time */ public String getModifyTime() { return this.ModifyTime; } /** * Set Account information modification time * @param ModifyTime Account information modification time */ public void setModifyTime(String ModifyTime) { this.ModifyTime = ModifyTime; } /** * Get Password modification time * @return ModifyPasswordTime Password modification time */ public String getModifyPasswordTime() { return this.ModifyPasswordTime; } /** * Set Password modification time * @param ModifyPasswordTime Password modification time */ public void setModifyPasswordTime(String ModifyPasswordTime) { this.ModifyPasswordTime = ModifyPasswordTime; } /** * Get This parameter is no longer supported. * @return CreateTime This parameter is no longer supported. */ public String getCreateTime() { return this.CreateTime; } /** * Set This parameter is no longer supported. * @param CreateTime This parameter is no longer supported. */ public void setCreateTime(String CreateTime) { this.CreateTime = CreateTime; } /** * Get The maximum number of instance connections supported by an account * @return MaxUserConnections The maximum number of instance connections supported by an account */ public Long getMaxUserConnections() { return this.MaxUserConnections; } /** * Set The maximum number of instance connections supported by an account * @param MaxUserConnections The maximum number of instance connections supported by an account */ public void setMaxUserConnections(Long MaxUserConnections) { this.MaxUserConnections = MaxUserConnections; } public AccountInfo() { } /** * NOTE: Any ambiguous key set via .set("AnyKey", "value") will be a shallow copy, * and any explicit key, i.e Foo, set via .setFoo("value") will be a deep copy. */ public AccountInfo(AccountInfo source) { if (source.Notes != null) { this.Notes = new String(source.Notes); } if (source.Host != null) { this.Host = new String(source.Host); } if (source.User != null) { this.User = new String(source.User); } if (source.ModifyTime != null) { this.ModifyTime = new String(source.ModifyTime); } if (source.ModifyPasswordTime != null) { this.ModifyPasswordTime = new String(source.ModifyPasswordTime); } if (source.CreateTime != null) { this.CreateTime = new String(source.CreateTime); } if (source.MaxUserConnections != null) { this.MaxUserConnections = new Long(source.MaxUserConnections); } } /** * Internal implementation, normal users should not use it. */ public void toMap(HashMap<String, String> map, String prefix) { this.setParamSimple(map, prefix + "Notes", this.Notes); this.setParamSimple(map, prefix + "Host", this.Host); this.setParamSimple(map, prefix + "User", this.User); this.setParamSimple(map, prefix + "ModifyTime", this.ModifyTime); this.setParamSimple(map, prefix + "ModifyPasswordTime", this.ModifyPasswordTime); this.setParamSimple(map, prefix + "CreateTime", this.CreateTime); this.setParamSimple(map, prefix + "MaxUserConnections", this.MaxUserConnections); } }
27.32618
100
0.637349
f4df5f2e7cbbc7b3b5b04f37e0ac3be2275d09fa
3,427
package org.deeplearning4j.rl4j.policy; import org.deeplearning4j.gym.StepReply; import org.deeplearning4j.rl4j.learning.HistoryProcessor; import org.deeplearning4j.rl4j.learning.IHistoryProcessor; import org.deeplearning4j.rl4j.learning.Learning; import org.deeplearning4j.rl4j.learning.sync.Transition; import org.deeplearning4j.rl4j.mdp.MDP; import org.deeplearning4j.rl4j.network.NeuralNet; import org.deeplearning4j.rl4j.space.ActionSpace; import org.deeplearning4j.rl4j.space.Encodable; import org.nd4j.linalg.api.ndarray.INDArray; import org.nd4j.linalg.util.ArrayUtil; /** * @author rubenfiszel ([email protected]) 7/18/16. * * Abstract class common to all policies * * A Policy responsability is to choose the next action given a state */ public abstract class Policy<O extends Encodable, A> { public abstract NeuralNet getNeuralNet(); public abstract A nextAction(INDArray input); public <AS extends ActionSpace<A>> double play(MDP<O, A, AS> mdp) { return play(mdp, (IHistoryProcessor)null); } public <AS extends ActionSpace<A>> double play(MDP<O, A, AS> mdp, HistoryProcessor.Configuration conf) { return play(mdp, new HistoryProcessor(conf)); } public <AS extends ActionSpace<A>> double play(MDP<O, A, AS> mdp, IHistoryProcessor hp) { getNeuralNet().reset(); Learning.InitMdp<O> initMdp = Learning.initMdp(mdp, hp); O obs = initMdp.getLastObs(); double reward = initMdp.getReward(); A lastAction = mdp.getActionSpace().noOp(); A action; int step = initMdp.getSteps(); INDArray[] history = null; while (!mdp.isDone()) { INDArray input = Learning.getInput(mdp, obs); boolean isHistoryProcessor = hp != null; if (isHistoryProcessor) hp.record(input); int skipFrame = isHistoryProcessor ? hp.getConf().getSkipFrame() : 1; if (step % skipFrame != 0) { action = lastAction; } else { if (history == null) { if (isHistoryProcessor) { hp.add(input); history = hp.getHistory(); } else history = new INDArray[] {input}; } INDArray hstack = Transition.concat(history); if (isHistoryProcessor) { hstack.muli(1.0 / hp.getScale()); } if (getNeuralNet().isRecurrent()) { //flatten everything for the RNN hstack = hstack.reshape(Learning.makeShape(1, ArrayUtil.toInts(hstack.shape()), 1)); } else { if (hstack.shape().length > 2) hstack = hstack.reshape(Learning.makeShape(1, ArrayUtil.toInts(hstack.shape()))); } action = nextAction(hstack); } lastAction = action; StepReply<O> stepReply = mdp.step(action); reward += stepReply.getReward(); if (isHistoryProcessor) hp.add(Learning.getInput(mdp, stepReply.getObservation())); history = isHistoryProcessor ? hp.getHistory() : new INDArray[] {Learning.getInput(mdp, stepReply.getObservation())}; step++; } return reward; } }
33.930693
108
0.590896
32491a1272abbbd2a0b4a2fbdf87f82f4b7ed9cd
348
package com.example.wang.learncontext; import android.app.Application; /** * Created by wang on 2015/8/12. */ public class App extends Application { private String textData="default"; public void setTextData(String textData) { this.textData = textData; } public String getTextData() { return textData; } }
18.315789
46
0.672414
ea7e5a43c96653bc052e5e00bee34355aab1e439
1,206
package com.example.takahirom.sandboxapp; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; public class LeakActivity extends AppCompatActivity { private static LeakActivity leakActivity; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_leak); leakActivity = this; } @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_leak, 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(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
29.414634
80
0.688226
4cb247a6085ef4b729c2bf8d2c2dcf942d13938b
3,872
package org.d2rq.values; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.regex.Pattern; import org.d2rq.db.ResultRow; import org.d2rq.db.expr.Expression; import org.d2rq.db.op.OrderOp.OrderSpec; import org.d2rq.db.op.ProjectionSpec; import org.d2rq.db.op.DatabaseOp; import org.d2rq.db.renamer.Renamer; import org.d2rq.db.vendor.Vendor; import org.d2rq.nodes.NodeSetFilter; /** * @author Richard Cyganiak ([email protected]) */ public class DecoratingValueMaker implements ValueMaker { public static ValueConstraint maxLengthConstraint(final int maxLength) { return new ValueConstraint() { public boolean matches(String value) { return value == null || value.length() <= maxLength; } public String toString() { return "maxLength=" + maxLength; } }; } public static ValueConstraint containsConstraint(final String containsSubstring) { return new ValueConstraint() { public boolean matches(String value) { return value == null || value.indexOf(containsSubstring) >= 0; } public String toString() { return "contains='" + containsSubstring + "'"; } }; } public static ValueConstraint regexConstraint(final String regex) { final Pattern pattern = Pattern.compile(regex); return new ValueConstraint() { public boolean matches(String value) { return value == null || pattern.matcher(value).matches(); } public String toString() { return "regex='" + regex + "'"; } }; } private ValueMaker base; private List<ValueConstraint> constraints; private Translator translator; public DecoratingValueMaker(ValueMaker base, List<ValueConstraint> constraints) { this(base, constraints, Translator.IDENTITY); } public DecoratingValueMaker(ValueMaker base, List<ValueConstraint> constraints, Translator translator) { this.base = base; this.constraints = constraints; this.translator = translator; } public String makeValue(ResultRow row) { return this.translator.toRDFValue(this.base.makeValue(row)); } public Object makeValueObject(ResultRow row) { try { throw new Exception("mple DecoratingValueMaker not supposed to return Object:p"); } catch (Exception e) { System.out.println(e.getMessage()); e.printStackTrace(); } return NULL; } public void describeSelf(NodeSetFilter c) { c.setUsesTranslator(translator); this.base.describeSelf(c); } public boolean matches(String value) { for (ValueConstraint constraint: constraints) { if (!constraint.matches(value)) { return false; } } String dbValue = translator.toDBValue(value); if (dbValue == null) { return false; } return base.matches(dbValue); } public Expression valueExpression(String value, DatabaseOp table, Vendor vendor) { if (!matches(value)) return Expression.FALSE; return base.valueExpression(translator.toDBValue(value), table, vendor); } public Set<ProjectionSpec> projectionSpecs() { return this.base.projectionSpecs(); } public ValueMaker rename(Renamer renamer) { return new DecoratingValueMaker(this.base.rename(renamer), this.constraints, this.translator); } public List<OrderSpec> orderSpecs(boolean ascending) { return base.orderSpecs(ascending); } public interface ValueConstraint { boolean matches(String value); } public String toString() { StringBuffer result = new StringBuffer(); if (!this.translator.equals(Translator.IDENTITY)) { result.append(this.translator); result.append("("); } result.append(this.base.toString()); Iterator<ValueConstraint> it = this.constraints.iterator(); if (it.hasNext()) { result.append(":"); } while (it.hasNext()) { result.append(it.next()); if (it.hasNext()) { result.append("&&"); } } if (!this.translator.equals(Translator.IDENTITY)) { result.append(")"); } return result.toString(); } }
27.267606
105
0.71875
3bfbbd4bcc83e4e3bf13bb048e12ed3c3d99488c
1,203
package com.mixiaoxiao.android.util; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; public class MxxNetworkUtil { /** * 检测网络是否可用 * * @param context * 上下文 * @return true 表示有网络连接 false表示没有可用网络连接 */ public static boolean isNetworkAvailable(Context context) { ConnectivityManager connectivity = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); if (connectivity == null) { return false; } else { NetworkInfo[] info = connectivity.getAllNetworkInfo(); if (info != null) { for (int i = 0; i < info.length; i++) { if (info[i].getState() == NetworkInfo.State.CONNECTED) { return true; } } } } return false; } /** * 王斌增加,用于判断是否是wifi 网络 * * @param context * @return 是否WIFI网络 */ public static boolean isWifiConnect(Context context) { ConnectivityManager cm = (ConnectivityManager) context .getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkINfo = cm.getActiveNetworkInfo(); if (networkINfo != null && networkINfo.getType() == ConnectivityManager.TYPE_WIFI) { return true; } return false; } }
23.134615
66
0.686617
2fbe2eb31a70c78e33597c10f022ba4a39a0a5df
364
package ooga.model.actions; import ooga.model.EntityModel; public class SetBoundedRight extends Action { private boolean boundedRight; public SetBoundedRight(String parameter) { super(parameter); boundedRight = Boolean.parseBoolean(param); } @Override public void execute(EntityModel entity) { entity.setBoundedRight(boundedRight); } }
20.222222
47
0.755495
f76fa58f1885a74bbe049f1f05ea07c9dc2755b9
11,319
package com.hdyg.common.util.pay; import android.content.Context; import com.google.gson.Gson; import com.hdyg.common.bean.WxOpenBean; import com.hdyg.common.bean.WxPayBean; import com.hdyg.common.bean.WxShareBean; import com.hdyg.common.httpUtil.okhttp.CallBackUtil; import com.hdyg.common.httpUtil.okhttp.OkhttpUtil; import com.hdyg.common.util.LogUtils; import com.hdyg.common.util.StringUtil; import com.hdyg.common.util.ThreadUtil; import com.hdyg.common.util.ToastUtil; import com.tencent.mm.opensdk.constants.ConstantsAPI; import com.tencent.mm.opensdk.modelbase.BaseResp; import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram; import com.tencent.mm.opensdk.modelmsg.SendAuth; import com.tencent.mm.opensdk.modelmsg.SendMessageToWX; import com.tencent.mm.opensdk.modelmsg.WXMediaMessage; import com.tencent.mm.opensdk.modelmsg.WXWebpageObject; import com.tencent.mm.opensdk.modelpay.PayReq; import com.tencent.mm.opensdk.openapi.IWXAPI; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; import org.json.JSONObject; import java.lang.ref.WeakReference; import okhttp3.Call; /** * @author CZB * @describe 微信工具 授权/分享/支付/打开小程序 * @time 2020/4/9 11:42 */ public class WxPayBuilder { private Context mContext; private String mAppId; private WxPayBean mBean; private WxShareBean mShareBean; private WxOpenBean mOpenBean; private OpenCallback mOpenCallback; private PayCallback mPayCallback; private ShareCallback mShareCallback; private AuthCallback mAuthCallback; //SendMessageToWX.Req.WXSceneSession 对话 //SendMessageToWX.Req.WXSceneTimeline 朋友圈 //SendMessageToWX.Req.WXSceneFavorite 收藏 private int mTargetScene = SendMessageToWX.Req.WXSceneSession;//默认分享到对话 public WxPayBuilder(Context context, String appId) { mContext = context; mAppId = appId; WxApiWrapper.getInstance().setAppID(appId); EventBus.getDefault().register(this); } public WxPayBuilder setPayParam(WxPayBean bean) { mBean = bean; return this; } public WxPayBuilder setPayCallback(PayCallback callback) { mPayCallback = new WeakReference<>(callback).get(); return this; } public WxPayBuilder setShareParam(WxShareBean bean) { mShareBean = bean; return this; } public WxPayBuilder setShareType(int shareType) { mTargetScene = shareType; return this; } public WxPayBuilder setShareCallback(ShareCallback callback) { mShareCallback = new WeakReference<>(callback).get(); return this; } public WxPayBuilder setOpenParam(WxOpenBean bean) { mOpenBean = bean; return this; } public WxPayBuilder setOpenCallback(OpenCallback callback) { mOpenCallback = new WeakReference<>(callback).get(); return this; } public WxPayBuilder setAuthCallback(AuthCallback callback) { mAuthCallback = new WeakReference<>(callback).get(); return this; } /** * 授权 */ public void auth() { SendAuth.Req req = new SendAuth.Req(); req.scope = "snsapi_userinfo"; req.state = "auth_apk"; IWXAPI wxApi = WxApiWrapper.getInstance().getWxApi(); if (wxApi == null) { ToastUtil.show("授权失败"); return; } boolean result = wxApi.sendReq(req); if (!result) { ToastUtil.show("授权失败"); } } /** * 支付 */ public void pay() { PayReq request = new PayReq(); LogUtils.d("发送支付的appid==>" + mBean.appid); request.appId = mBean.appid; request.partnerId = mBean.partnerid; request.prepayId = mBean.prepayid; request.packageValue = mBean.packageStr; request.nonceStr = mBean.noncestr; request.timeStamp = mBean.timestamp; request.sign = mBean.sign; IWXAPI wxApi = WxApiWrapper.getInstance().getWxApi(); if (wxApi == null) { ToastUtil.show("支付失败"); return; } boolean result = wxApi.sendReq(request); if (!result) { ToastUtil.show("支付失败"); } } /** * 分享 */ public void share() { ThreadUtil.runOnSubThread(() -> { //初始化一个WXWebpageObject,填写url WXWebpageObject webpage = new WXWebpageObject(); webpage.webpageUrl = mShareBean.url; //用 WXWebpageObject 对象初始化一个 WXMediaMessage 对象 WXMediaMessage msg = new WXMediaMessage(webpage); msg.title = mShareBean.title; msg.description = mShareBean.des; msg.thumbData = StringUtil.getHtmlByteArray(mShareBean.logo); //构造一个Req SendMessageToWX.Req req = new SendMessageToWX.Req(); req.transaction = buildTransaction("webpage"); req.message = msg; req.scene = mTargetScene; req.userOpenId = mShareBean.openid; //调用api接口,发送数据到微信 IWXAPI wxApi = WxApiWrapper.getInstance().getWxApi(); wxApi.sendReq(req); }); } /** * 打开小程序 */ public void openMiniProgram(){ WXLaunchMiniProgram.Req req = new WXLaunchMiniProgram.Req(); req.userName = mOpenBean.userName; // 填小程序原始id req.path = mOpenBean.path; ////拉起小程序页面的可带参路径,不填默认拉起小程序首页,对于小游戏,可以只传入 query 部分,来实现传参效果,如:传入 "?foo=bar"。 req.miniprogramType = mOpenBean.miniprogramType;// 开发版1,体验版2和正式版0 //调用api接口,发送数据到微信 IWXAPI wxApi = WxApiWrapper.getInstance().getWxApi(); wxApi.sendReq(req); } private String buildTransaction(final String type) { return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis(); } @Subscribe(threadMode = ThreadMode.MAIN) public void onPayResponse(BaseResp resp) { LogUtils.e("resp---微信回调---->" + resp.errCode); String result; if (mPayCallback != null) { //支付 if (resp.getType() == ConstantsAPI.COMMAND_PAY_BY_WX) { switch (resp.errCode) { case BaseResp.ErrCode.ERR_OK://成功 result = "支付成功"; mPayCallback.onSuccess(); break; case BaseResp.ErrCode.ERR_COMM://签名错误、未注册APPID、项目设置APPID不正确、注册的APPID与设置的不匹配、其他异常等 result = "签名错误"; mPayCallback.onFailed(result); break; case BaseResp.ErrCode.ERR_USER_CANCEL: result = "支付取消"; mPayCallback.onFailed(result); break; default: result = "支付失败"; mPayCallback.onFailed(result); break; } mPayCallback = null; } } if (mAuthCallback != null) { //授权 if (resp.getType() == ConstantsAPI.COMMAND_SENDAUTH) { switch (resp.errCode) { case BaseResp.ErrCode.ERR_OK://成功 result = "授权成功"; SendAuth.Resp authResp = (SendAuth.Resp) resp; final String code = authResp.code; mAuthCallback.onSuccess(code); break; case BaseResp.ErrCode.ERR_COMM://签名错误、未注册APPID、项目设置APPID不正确、注册的APPID与设置的不匹配、其他异常等 result = "签名错误"; mAuthCallback.onFailed(result); break; case BaseResp.ErrCode.ERR_USER_CANCEL: result = "授权取消"; mAuthCallback.onFailed(result); break; default: result = "授权失败"; mAuthCallback.onFailed(result); break; } mAuthCallback = null; } } if (mShareCallback != null) { //分享 if (resp.getType() == ConstantsAPI.COMMAND_SENDMESSAGE_TO_WX) { switch (resp.errCode) { case BaseResp.ErrCode.ERR_OK://成功 result = "分享成功"; mShareCallback.onShareSuccess(); break; case BaseResp.ErrCode.ERR_COMM://签名错误、未注册APPID、项目设置APPID不正确、注册的APPID与设置的不匹配、其他异常等 result = "签名错误"; mShareCallback.onShareFailed(result); break; case BaseResp.ErrCode.ERR_USER_CANCEL: result = "分享取消"; mShareCallback.onShareCancle(result); break; default: result = "分享失败"; mShareCallback.onShareFailed(result); break; } mShareCallback = null; } } if (mOpenCallback != null) { //小程序回退到APP if (resp.getType() == ConstantsAPI.COMMAND_LAUNCH_WX_MINIPROGRAM) { WXLaunchMiniProgram.Resp launchMiniProResp = (WXLaunchMiniProgram.Resp) resp; String extraData =launchMiniProResp.extMsg; mOpenCallback.onSuccess(extraData); mOpenCallback = null; } } mContext = null; EventBus.getDefault().unregister(this); } //获取用户信息 private void getUserInfo(String code){ //获取授权 String mSecret = ""; String loginUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+mAppId+"&secret="+mSecret+"&code="+code+"&grant_type=authorization_code"; OkhttpUtil.okHttpGet(loginUrl, new CallBackUtil.CallBackString() { @Override public void onFailure(Call call, Exception e) { LogUtils.e("AccessCode Fail==>"+e.getMessage()); } @Override public void onResponse(String response) { try { JSONObject jsonObject = new JSONObject(response); String access = jsonObject.getString("access_token"); String openId = jsonObject.getString("openid"); //获取个人信息 String getUserInfo = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access + "&openid=" + openId; OkhttpUtil.okHttpGet(getUserInfo, new CallBackString() { @Override public void onFailure(Call call, Exception e) { LogUtils.e("UserInfo Fail==>"+e.getMessage()); } @Override public void onResponse(String response) { LogUtils.d("UserInfo Success==>"+response); } }); }catch (Exception e){ LogUtils.e("GetUserInfo Exception==>"+new Gson().toJson(e)); } } }); } }
35.59434
158
0.559767
0cf7cc10c5acb0bf7b3e5a6e4c235117529d16a4
14,745
/* * 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.commons.dbcp; import java.io.PrintWriter; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.PreparedStatement; import java.sql.SQLException; import java.sql.SQLWarning; import java.sql.Statement; import java.util.Map; import java.util.NoSuchElementException; import javax.sql.DataSource; import org.apache.commons.pool.ObjectPool; /** * A simple {@link DataSource} implementation that obtains * {@link Connection}s from the specified {@link ObjectPool}. * * @author Rodney Waldhoff * @author Glenn L. Nielsen * @author James House * @author Dirk Verbeeck * @version $Revision: 907443 $ $Date: 2010-02-07 11:44:20 -0500 (Sun, 07 Feb 2010) $ */ public class PoolingDataSource implements DataSource { /** Controls access to the underlying connection */ private boolean accessToUnderlyingConnectionAllowed = false; public PoolingDataSource() { this(null); } public PoolingDataSource(ObjectPool pool) { _pool = pool; } public void setPool(ObjectPool pool) throws IllegalStateException, NullPointerException { if(null != _pool) { throw new IllegalStateException("Pool already set"); } else if(null == pool) { throw new NullPointerException("Pool must not be null."); } else { _pool = pool; } } /** * Returns the value of the accessToUnderlyingConnectionAllowed property. * * @return true if access to the underlying is allowed, false otherwise. */ public boolean isAccessToUnderlyingConnectionAllowed() { return this.accessToUnderlyingConnectionAllowed; } /** * Sets the value of the accessToUnderlyingConnectionAllowed property. * It controls if the PoolGuard allows access to the underlying connection. * (Default: false) * * @param allow Access to the underlying connection is granted when true. */ public void setAccessToUnderlyingConnectionAllowed(boolean allow) { this.accessToUnderlyingConnectionAllowed = allow; } /* public boolean isWrapperFor(Class<?> iface) throws SQLException { return false; } public <T> T unwrap(Class<T> iface) throws SQLException { throw new SQLException("PoolingDataSource is not a wrapper."); } */ //--- DataSource methods ----------------------------------------- /** * Return a {@link java.sql.Connection} from my pool, * according to the contract specified by {@link ObjectPool#borrowObject}. */ public Connection getConnection() throws SQLException { try { Connection conn = (Connection)(_pool.borrowObject()); if (conn != null) { conn = new PoolGuardConnectionWrapper(conn); } return conn; } catch(SQLException e) { throw e; } catch(NoSuchElementException e) { throw new SQLNestedException("Cannot get a connection, pool error " + e.getMessage(), e); } catch(RuntimeException e) { throw e; } catch(Exception e) { throw new SQLNestedException("Cannot get a connection, general error", e); } } /** * Throws {@link UnsupportedOperationException} * @throws UnsupportedOperationException */ public Connection getConnection(String uname, String passwd) throws SQLException { throw new UnsupportedOperationException(); } /** * Returns my log writer. * @return my log writer * @see DataSource#getLogWriter */ public PrintWriter getLogWriter() { return _logWriter; } /** * Throws {@link UnsupportedOperationException}. * @throws UnsupportedOperationException As this * implementation does not support this feature. */ public int getLoginTimeout() { throw new UnsupportedOperationException("Login timeout is not supported."); } /** * Throws {@link UnsupportedOperationException}. * @throws UnsupportedOperationException As this * implementation does not support this feature. */ public void setLoginTimeout(int seconds) { throw new UnsupportedOperationException("Login timeout is not supported."); } /** * Sets my log writer. * @see DataSource#setLogWriter */ public void setLogWriter(PrintWriter out) { _logWriter = out; } /** My log writer. */ protected PrintWriter _logWriter = null; protected ObjectPool _pool = null; /** * PoolGuardConnectionWrapper is a Connection wrapper that makes sure a * closed connection cannot be used anymore. */ private class PoolGuardConnectionWrapper extends DelegatingConnection { private Connection delegate; PoolGuardConnectionWrapper(Connection delegate) { super(delegate); this.delegate = delegate; } protected void checkOpen() throws SQLException { if(delegate == null) { throw new SQLException("Connection is closed."); } } public void close() throws SQLException { if (delegate != null) { this.delegate.close(); this.delegate = null; super.setDelegate(null); } } public boolean isClosed() throws SQLException { if (delegate == null) { return true; } return delegate.isClosed(); } public void clearWarnings() throws SQLException { checkOpen(); delegate.clearWarnings(); } public void commit() throws SQLException { checkOpen(); delegate.commit(); } public Statement createStatement() throws SQLException { checkOpen(); return new DelegatingStatement(this, delegate.createStatement()); } public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { checkOpen(); return new DelegatingStatement(this, delegate.createStatement(resultSetType, resultSetConcurrency)); } public boolean innermostDelegateEquals(Connection c) { Connection innerCon = super.getInnermostDelegate(); if (innerCon == null) { return c == null; } else { return innerCon.equals(c); } } public boolean getAutoCommit() throws SQLException { checkOpen(); return delegate.getAutoCommit(); } public String getCatalog() throws SQLException { checkOpen(); return delegate.getCatalog(); } public DatabaseMetaData getMetaData() throws SQLException { checkOpen(); return delegate.getMetaData(); } public int getTransactionIsolation() throws SQLException { checkOpen(); return delegate.getTransactionIsolation(); } public Map getTypeMap() throws SQLException { checkOpen(); return delegate.getTypeMap(); } public SQLWarning getWarnings() throws SQLException { checkOpen(); return delegate.getWarnings(); } public int hashCode() { if (delegate == null){ return 0; } return delegate.hashCode(); } public boolean equals(Object obj) { if (obj == null) { return false; } if (obj == this) { return true; } // Use superclass accessor to skip access test Connection conn = super.getInnermostDelegate(); if (conn == null) { return false; } if (obj instanceof DelegatingConnection) { DelegatingConnection c = (DelegatingConnection) obj; return c.innermostDelegateEquals(conn); } else { return conn.equals(obj); } } public boolean isReadOnly() throws SQLException { checkOpen(); return delegate.isReadOnly(); } public String nativeSQL(String sql) throws SQLException { checkOpen(); return delegate.nativeSQL(sql); } public CallableStatement prepareCall(String sql) throws SQLException { checkOpen(); return new DelegatingCallableStatement(this, delegate.prepareCall(sql)); } public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { checkOpen(); return new DelegatingCallableStatement(this, delegate.prepareCall(sql, resultSetType, resultSetConcurrency)); } public PreparedStatement prepareStatement(String sql) throws SQLException { checkOpen(); return new DelegatingPreparedStatement(this, delegate.prepareStatement(sql)); } public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { checkOpen(); return new DelegatingPreparedStatement(this, delegate.prepareStatement(sql, resultSetType, resultSetConcurrency)); } public void rollback() throws SQLException { checkOpen(); delegate.rollback(); } public void setAutoCommit(boolean autoCommit) throws SQLException { checkOpen(); delegate.setAutoCommit(autoCommit); } public void setCatalog(String catalog) throws SQLException { checkOpen(); delegate.setCatalog(catalog); } public void setReadOnly(boolean readOnly) throws SQLException { checkOpen(); delegate.setReadOnly(readOnly); } public void setTransactionIsolation(int level) throws SQLException { checkOpen(); delegate.setTransactionIsolation(level); } public void setTypeMap(Map map) throws SQLException { checkOpen(); delegate.setTypeMap(map); } public String toString() { if (delegate == null){ return "NULL"; } return delegate.toString(); } public int getHoldability() throws SQLException { checkOpen(); return delegate.getHoldability(); } public void setHoldability(int holdability) throws SQLException { checkOpen(); delegate.setHoldability(holdability); } public java.sql.Savepoint setSavepoint() throws SQLException { checkOpen(); return delegate.setSavepoint(); } public java.sql.Savepoint setSavepoint(String name) throws SQLException { checkOpen(); return delegate.setSavepoint(name); } public void releaseSavepoint(java.sql.Savepoint savepoint) throws SQLException { checkOpen(); delegate.releaseSavepoint(savepoint); } public void rollback(java.sql.Savepoint savepoint) throws SQLException { checkOpen(); delegate.rollback(savepoint); } public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { checkOpen(); return new DelegatingStatement(this, delegate.createStatement(resultSetType, resultSetConcurrency, resultSetHoldability)); } public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { checkOpen(); return new DelegatingCallableStatement(this, delegate.prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability)); } public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { checkOpen(); return new DelegatingPreparedStatement(this, delegate.prepareStatement(sql, autoGeneratedKeys)); } public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { checkOpen(); return new DelegatingPreparedStatement(this,delegate.prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability)); } public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { checkOpen(); return new DelegatingPreparedStatement(this, delegate.prepareStatement(sql, columnIndexes)); } public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { checkOpen(); return new DelegatingPreparedStatement(this, delegate.prepareStatement(sql, columnNames)); } /** * @see org.apache.commons.dbcp.DelegatingConnection#getDelegate() */ public Connection getDelegate() { if (isAccessToUnderlyingConnectionAllowed()) { return super.getDelegate(); } else { return null; } } /** * @see org.apache.commons.dbcp.DelegatingConnection#getInnermostDelegate() */ public Connection getInnermostDelegate() { if (isAccessToUnderlyingConnectionAllowed()) { return super.getInnermostDelegate(); } else { return null; } } } }
33.435374
154
0.620278
96689baa50008f23917a1c3ff6018848aa7c69d4
7,491
package edu.angelo.midtermprojectgupton; import java.util.Random; /** * Tracker for a Minesweeper game. * @author Nickolas Gupton */ public class MinesweeperTracker { /** * int: ROW_COUNT | The number of rows in the current game of Minesweeper. */ public final int ROW_COUNT; /** * int: COL_COUNT | The number of columns in the current game of Minesweeper. */ public final int COL_COUNT; /** * int: NUM_MINES | The number of mines in the current game of Minesweeper. * Calculated as (ROW_COUNT * COL_COUNT)/6. */ public final int NUM_MINES; /** * int[][]: gameBoard | The board of the current game, 9's are mines, other numbers are the number of mines around them. */ private final int[][] gameBoard; /** * boolean[][]: shown | True if the specified row and column has been shown. */ private final boolean[][] shown; /** * boolean[][]: flagged | True if the specified row and column has been flagged. */ private final boolean[][] flagged; /** * boolean: gameLost | Tracks if the current game has been lost. */ private boolean gameLost = false; /** * boolean: gameWon | Tracks if the current game has been won. */ private boolean gameWon = false; /** * boolean: flagging | Tracks if the player is currently flagging a tile. * Resets back to false after a tile has been flagged. */ private boolean isFlagging = false; /** * Random: rdm | Generates random numbers, used for mine placement. */ private static final Random rdm = new Random(); /** * Creates a new MinesweeperTracker object. * @param rows int: Number of rows to create on the game board. * @param cols int: Number of columns to create on the game board. */ public MinesweeperTracker(int rows, int cols) { ROW_COUNT = rows; COL_COUNT = cols; NUM_MINES = (ROW_COUNT * COL_COUNT) / 6; gameBoard = generateNewBoard(); shown = new boolean[ROW_COUNT][COL_COUNT]; flagged = new boolean[ROW_COUNT][COL_COUNT]; } /** * Generates a new board in this Minesweeper Object. * @return int[][]: The game board to use for this Minesweeper Object. */ private int[][] generateNewBoard() { int[][] newBoard = new int[ROW_COUNT][COL_COUNT]; // Place mines randomly. for (int i = 0; i < NUM_MINES; i++) { int row = rdm.nextInt(ROW_COUNT); int col = rdm.nextInt(COL_COUNT); // If it is already a mine try again. if (newBoard[row][col] != 9) { newBoard[row][col] = 9; } else { i--; } } for (int r = 0; r < ROW_COUNT; r++) { for (int c = 0; c < COL_COUNT; c++) { // If it is a mine don't change it. if (newBoard[r][c] != 9) { int count = 0; // Look at the tiles around the current one to check for mines. for (int i = r - 1; i < r + 2; i++) { for (int k = c - 1; k < c + 2; k++) { try { // Make sure you aren't checking the current tile // and that the tile your'e looking at is actually a mine. if ((i != r || k != c) && newBoard[i][k] == 9) { count++; } } catch (ArrayIndexOutOfBoundsException e) { // Do nothing. } } } newBoard[r][c] = count; } } } return newBoard; } /** * Clicks a tile to reveal what is there, calls itself recursively for 0's. * @param row int: The row to click. * @param col int: The column to click. */ public void click(int row, int col) { // If the player has lost, won, or the tile is already shown ignore the click. if (hasLost() || hasWon() || shown[row][col]) return; if (isFlagging()) { flagged[row][col] = !flagged[row][col]; isFlagging = false; return; } // If this tile is flagged ignore the click. if (flagged[row][col]) return; // If its a mine the game has been lost. if (gameBoard[row][col] == 9) { gameLost = true; } shown[row][col] = true; // If there is no mines around this tile we can show the ones around it safely. if (gameBoard[row][col] == 0) { for (int i = row - 1; i < row + 2; i++) { for (int k = col - 1; k < col + 2; k++) { try { if (!shown[i][k]) { click(i, k); } } catch (ArrayIndexOutOfBoundsException e) { // Do nothing. } } } } // After the player clicks we want to check if they have won. checkForWin(); } /** * Gets the value of the specified tile. * @param row int: Row to return. * @param col int: Column to return. * @return String: The value of the tile. If its shown it will be the number, mines will be *, unknowns will be #, flags will be ^. */ public String getSquare(int row, int col) { if (shown[row][col]) { return gameBoard[row][col] == 9 ? "*" : String.valueOf(gameBoard[row][col]); } else if (flagged[row][col]) { return "^"; } else { return "#"; } } /** * Checks if the game has been lost. * @return boolean: True if the game has been lost. */ public boolean hasLost() { return gameLost; } /** * Checks the game for a win. Sets gameWon to true if every tile that isn't a mine has been shown. */ private void checkForWin() { for (int r = 0; r < gameBoard.length; r++) { for (int c = 0; c < gameBoard[r].length; c++) { if (gameBoard[r][c] != 9 && !shown[r][c]) { return; } } } gameWon = true; } /** * Checks if the game has been won. * @return boolean: True if the game has been won. */ public boolean hasWon() { return gameWon; } /** * Toggles the flagging variable. */ public void toggleFlagging() { isFlagging = !isFlagging; } /** * Checks if the player is currently flagging. * @return boolean: True if the player is flagging. */ public boolean isFlagging() { return isFlagging; } /** * Builds a string from the current game board. * @return String: The current game board with tiles hidden. */ @Override public String toString() { StringBuilder sb = new StringBuilder(); for (int[] row : gameBoard) { sb.append("["); for (int col : row) { sb.append(col); sb.append(" "); } sb.append("\b]\n"); } return sb.toString(); } }
29.492126
135
0.495928
6d605b981ae9a6dfdf5f2ce9d8afabb7baf873fa
352
package com.hankcs.hanlp.dependency.perceptron.parser; import junit.framework.TestCase; import java.io.IOException; public class KBeamArcEagerDependencyParserTest extends TestCase { public void testLoad() throws IOException, ClassNotFoundException { KBeamArcEagerDependencyParser parser = new KBeamArcEagerDependencyParser(); } }
27.076923
83
0.798295
def572283fc8ff6b30848817a9a2b43c47d27dba
2,888
package com.github.eugenelesnov; import lombok.NonNull; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.function.Function; import static com.github.eugenelesnov.Util.normalize; import static com.github.eugenelesnov.Util.orderByAscValue; /** * Implementation of Levenshtein distance calculating * * @author Eugene Lesnov */ public class Levenshtein { /** * Method to search token in {@link Collection<T>} * * @param precision precision * @param token search token * @param source collection for searching * @param function functional interface describing the way to get string * @return map with a {@link T} as a key and precision (Levenshtein distance) as a value */ public static <T> Map<T, Integer> levenshteinSearch(int precision, @NonNull String token, @NonNull Collection<T> source, Function<T, String> function) { if (token.isEmpty()) { throw new IllegalStateException("Search token must not be empty"); } if (source.isEmpty()) { return Collections.emptyMap(); } if (precision <= 0) { throw new IllegalStateException("The precision must be positive"); } Map<T, Integer> matched = new HashMap<>(); source.forEach(s -> { String appliedToken = function.apply(s); int distance = levenshtein(appliedToken, token); if (distance <= precision) { matched.put(s, distance); } }); return orderByAscValue(matched); } /** * Method to calculate Levenshtein distance between two strings * * @param str1 first string * @param str2 second string * @return Levenshtein distance */ public static int levenshtein(@NonNull String str1, @NonNull String str2) { if (str1.equals(str2)) { return 0; } str1 = normalize(str1); str2 = normalize(str2); int str1Length = str1.length(); int str2Length = str2.length(); int[] cost = new int[str2.length() + 1]; for (int j = 0; j < cost.length; j++) { cost[j] = j; } for (int i = 1; i <= str1Length; i++) { cost[0] = i; int nw = i - 1; for (int j = 1; j <= str2Length; j++) { int cj; int min = Math.min(cost[j], cost[j - 1]); if (str1.charAt(i - 1) == str2.charAt(j - 1)) { cj = Math.min(1 + min, nw); } else { cj = Math.min(1 + min, nw + 1); } nw = cost[j]; cost[j] = cj; } } return cost[str2Length]; } }
27.769231
118
0.541898
ace131f9b899553b053297d792dccfa4affc3414
1,726
/////////////////////////////////////////////////////////// // // Description : Importing Matrix Module To Accept Matrix And Check Whether The Matrix Is Sparse Matrix Or Not // Input : Int // Output : Int // Author : Prasad Dangare // Date : 4 June 2021 // /////////////////////////////////////////////////////////// import java.util.*; import Marvellous.Matrix; class Demo extends Matrix { public Demo(int iRow, int iCol) { super(iRow,iCol); } boolean ChkSparse() { int i = 0, j = 0; int iCnt = 0, iCntzero = 0; for(i = 0; i < Arr.length; i++) { for(j = 0; j < Arr[i].length; j++) { if(Arr[i][j] == 0) { iCntzero++; } else { iCnt++; } } } if(iCntzero > iCnt) { return true; } else { return false; } } } class Assignment52_5 { public static void main(String str[]) { Scanner sobj = new Scanner(System.in); System.out.println("Enter number of rows"); int row = sobj.nextInt(); System.out.println("Enter number of columns"); int col = sobj.nextInt(); Demo dobj = new Demo(row,col); dobj.Accept(); dobj.Display(); boolean bRet = dobj.ChkSparse(); if(bRet == true) { System.out.println("Its An Sparse Matrix "); } else { System.out.println("Its Not An Sparse Matrix "); } System.gc(); } }
21.575
114
0.409038
670a35dc13dbe9235b676292dbbc7934a87f9530
7,217
package com.jd.living.screen.settings; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.Preference; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import com.jd.living.R; import com.jd.living.Search; import com.jd.living.database.DatabaseHelper; import com.jd.living.util.StringUtil; import org.androidannotations.annotations.Bean; import org.androidannotations.annotations.EFragment; import java.util.HashSet; import java.util.Set; @EFragment public class SearchPreferencesFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener { @Bean DatabaseHelper databaseHelper; @Bean Search search; private SharedPreferences preferences; private boolean isValid = true; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); addPreferencesFromResource(R.xml.search_preferences); preferences = getPreferenceManager().getSharedPreferences(); preferences.registerOnSharedPreferenceChangeListener(this); setSummaryForTypeList(preferences); setSummaryForObjectList(preferences); setSummary(preferences, SearchPreferenceKey.PREFERENCE_LOCATION); setSummary(preferences, SearchPreferenceKey.PREFERENCE_RENT_MAX); checkMinMaxAmount(""); checkMinMax(""); setSummaryForBuildingTypes(preferences, SearchPreferenceKey.PREFERENCE_BUILDING_TYPE); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.search_preferences, menu); super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.actions_start_search: if (isValid) { databaseHelper.launchSearch(); } return true; case R.id.action_clear_search: return true; default: return super.onOptionsItemSelected(item); } } @Override public void onDestroy() { super.onDestroy(); preferences.unregisterOnSharedPreferenceChangeListener(this); } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { if (key.equals(SearchPreferenceKey.PREFERENCE_LOCATION) || key.equals(SearchPreferenceKey.PREFERENCE_RENT_MAX)) { setSummary(sharedPreferences, key); } else if (key.equals(SearchPreferenceKey.PREFERENCE_ROOM_MIN_NUMBERS) || key.equals(SearchPreferenceKey.PREFERENCE_ROOM_MAX_NUMBERS)) { checkMinMax(key); } else if (key.equals(SearchPreferenceKey.PREFERENCE_AMOUNT_MAX) || key.equals(SearchPreferenceKey.PREFERENCE_AMOUNT_MIN)) { checkMinMaxAmount(key); } else if (key.equals(SearchPreferenceKey.PREFERENCE_BUILDING_TYPE)) { setSummaryForBuildingTypes(sharedPreferences, key); } else if (key.equals(SearchPreferenceKey.PREFERENCE_BUILD_TYPE)) { setSummaryForTypeList(sharedPreferences); } else if (key.equals(SearchPreferenceKey.PREFERENCE_OBJECT_TYPE)) { setSummaryForObjectList(sharedPreferences); } } private void checkMinMaxAmount(String key) { boolean result = false; int max = Integer.valueOf(search.getMaxAmount(true)); int min = Integer.valueOf(search.getMinAmount(true)); if (min < max || min == 0 || max == 0) { result = true; setSummary(SearchPreferenceKey.PREFERENCE_AMOUNT_MIN, search.getMinAmount(false)); setSummary(SearchPreferenceKey.PREFERENCE_AMOUNT_MAX, search.getMaxAmount(false)); } else if (key.equals(SearchPreferenceKey.PREFERENCE_AMOUNT_MAX)) { setSummary(SearchPreferenceKey.PREFERENCE_AMOUNT_MAX, "Max value needs to be bigger then min"); } else if (key.equals(SearchPreferenceKey.PREFERENCE_AMOUNT_MIN)) { setSummary(SearchPreferenceKey.PREFERENCE_AMOUNT_MIN, "Min value needs to be smaller then max"); } else { setSummary(SearchPreferenceKey.PREFERENCE_AMOUNT_MAX, "Max value needs to be bigger then min"); setSummary(SearchPreferenceKey.PREFERENCE_AMOUNT_MIN, "Min value needs to be smaller then max"); } isValid = result; } private void checkMinMax(String key) { int max = Integer.valueOf(search.getMaxRooms(false)); int min = Integer.valueOf(search.getMinRooms()); if (min <= max) { setSummary(SearchPreferenceKey.PREFERENCE_ROOM_MIN_NUMBERS, String.valueOf(min)); setSummary(SearchPreferenceKey.PREFERENCE_ROOM_MAX_NUMBERS, max == 5 ? "5+" : String.valueOf(max)); } else if (key.equals(SearchPreferenceKey.PREFERENCE_ROOM_MAX_NUMBERS)) { setSummary(SearchPreferenceKey.PREFERENCE_ROOM_MAX_NUMBERS, "Max value needs to be bigger then min"); } else if (key.equals(SearchPreferenceKey.PREFERENCE_ROOM_MIN_NUMBERS)) { setSummary(SearchPreferenceKey.PREFERENCE_ROOM_MIN_NUMBERS, "Min value needs to be smaller then max"); } else { setSummary(SearchPreferenceKey.PREFERENCE_ROOM_MAX_NUMBERS, "Max value needs to be bigger then min"); setSummary(SearchPreferenceKey.PREFERENCE_ROOM_MIN_NUMBERS, "Min value needs to be smaller then max"); } isValid = (min <= max); } private void setSummary(SharedPreferences sharedPreferences, String key) { setSummary(key, sharedPreferences.getString(key, "")); } private void setSummaryForObjectList(SharedPreferences sharedPreferences) { String[] names = getResources().getStringArray(R.array.build_object_strings); String[] types = getResources().getStringArray(R.array.build_object); setSummaryForList(sharedPreferences, SearchPreferenceKey.PREFERENCE_OBJECT_TYPE, names, types); } private void setSummaryForTypeList(SharedPreferences sharedPreferences) { String[] names = getResources().getStringArray(R.array.build_types_strings); String[] types = getResources().getStringArray(R.array.build_types); setSummaryForList(sharedPreferences, SearchPreferenceKey.PREFERENCE_BUILD_TYPE, names, types); } private void setSummaryForList(SharedPreferences sharedPreferences, String key, String[] names, String[] types) { String text = StringUtil.getText(sharedPreferences.getString(key, ""), names, types); setSummary(key, text); } private void setSummary(String key, String summary) { findPreference(key).setSummary(summary); } private void setSummaryForBuildingTypes(SharedPreferences sharedPreferences, String key) { Preference pref = findPreference(key); Set<String> set = sharedPreferences.getStringSet(key, new HashSet<String>()); pref.setSummary(StringUtil.getBuildingTypes(getActivity(), set.toArray(new String[]{}))); } }
41.716763
129
0.705833
5667937e1f45220714cb09f64f64ab2b37e7d5da
2,424
/******************************************************************************* * Copyright 2016 Intuit * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.intuit.wasabi.cassandra.datastax.health; import com.codahale.metrics.health.HealthCheck; import com.datastax.driver.core.Session; import com.datastax.driver.core.exceptions.NoHostAvailableException; import org.slf4j.Logger; import static org.slf4j.LoggerFactory.getLogger; /** * Cassandra healthcheck class */ public class DefaultCassandraHealthCheck extends HealthCheck { public static final String SELECT_NOW_FROM_SYSTEM_LOCAL = "SELECT now() FROM system.local"; private static final Logger LOGGER = getLogger(DefaultCassandraHealthCheck.class); /** * {@inheritDoc} */ private Session session; // private PreparedStatement preparedStatement; public DefaultCassandraHealthCheck(Session session) { super(); this.session = session; // this.preparedStatement = this.session.prepare(SELECT_NOW_FROM_SYSTEM_LOCAL) // .setConsistencyLevel(ConsistencyLevel.LOCAL_ONE) // .disableTracing(); } // // BoundStatement getBoundedStatemen(){ // return new BoundStatement(preparedStatement); // } /** * @return Result of healthy or unhealthy based on the cql statement */ @Override public Result check() { boolean res = false; String msg = ""; try { // this.session.execute( getBoundedStatemen() ); this.session.execute(SELECT_NOW_FROM_SYSTEM_LOCAL); res = true; } catch (NoHostAvailableException ex) { LOGGER.error("No hosts available", ex); msg = ex.getMessage(); } return res ? Result.healthy() : Result.unhealthy(msg); } }
35.130435
95
0.642327
1632539ab5cab1f6c727a4d36f95621ee76bc7e5
761
/* Copyright (c) 2014 Boundless and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Distribution License v1.0 * which accompanies this distribution, and is available at * https://www.eclipse.org/org/documents/edl-v10.html * * Contributors: * Gabriel Roldan (Boundless) - initial implementation */ package org.locationtech.geogig.di; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; /** * Identifies a type that the injector only instantiates once. Not inherited. */ @Documented @Retention(RUNTIME) @Inherited public @interface Singleton { }
30.44
78
0.78318
85359b6b3f2702d9eb1cc426b3abb7e82d714d53
121
package com.hatchetstudios.sound; public class Music extends Audio { public Music(String name) { super(name); } }
12.1
34
0.719008
b3969fa2c234cba07f89e1b5fbd9f7e2673ae7c0
12,182
/* * Copyright 2017 Bartosz Lipinski * * 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 cortado; import android.support.test.espresso.matcher.ViewMatchers; import android.view.View; import org.hamcrest.Matcher; final class Chunks { // Suppress default constructor for noninstantiability private Chunks() { throw new AssertionError(); } static final class AssignableFrom extends CombinedChunk<Class<? extends View>> { @Override public Matcher<View> matcher(Class<? extends View> chunkValue) { return ViewMatchers.isAssignableFrom(chunkValue); } } static final class ClassName extends CombinedChunk<Matcher<String>> { @Override public Matcher<View> matcher(Matcher<String> chunkValue) { return ViewMatchers.withClassName(chunkValue); } } static final class IsDisplayed extends ElementaryChunk<Boolean> { @Override public Matcher<View> matcher(Boolean chunkValue) { return ViewMatchers.isDisplayed(); } } static final class IsCompletelyDisplayed extends ElementaryChunk<Boolean> { @Override public Matcher<View> matcher(Boolean chunkValue) { return ViewMatchers.isCompletelyDisplayed(); } } static final class IsDisplayingAtLeast extends CombinedChunk<Integer> { @Override public Matcher<View> matcher(Integer chunkValue) { return ViewMatchers.isDisplayingAtLeast(chunkValue); } } static final class IsEnabled extends ElementaryChunk<Boolean> { @Override public Matcher<View> matcher(Boolean chunkValue) { return ViewMatchers.isEnabled(); } } static final class IsFocusable extends ElementaryChunk<Boolean> { @Override public Matcher<View> matcher(Boolean chunkValue) { return ViewMatchers.isFocusable(); } } static final class HasFocus extends ElementaryChunk<Boolean> { @Override public Matcher<View> matcher(Boolean chunkValue) { return ViewMatchers.hasFocus(); } } static final class IsSelected extends ElementaryChunk<Boolean> { @Override public Matcher<View> matcher(Boolean chunkValue) { return ViewMatchers.isSelected(); } } static final class HasSibling extends CombinedChunk<Matcher<View>> { @Override public Matcher<View> matcher(Matcher<View> chunkValue) { return ViewMatchers.hasSibling(chunkValue); } } static final class WithContentDescription_Resource extends CombinedChunk<Integer> { @Override public Matcher<View> matcher(Integer chunkValue) { return ViewMatchers.withContentDescription(chunkValue); } } static final class WithContentDescription_String extends CombinedChunk<String> { @Override public Matcher<View> matcher(String chunkValue) { return ViewMatchers.withContentDescription(chunkValue); } } static final class WithContentDescription_Matcher extends CombinedChunk<Matcher<? extends CharSequence>> { @Override public Matcher<View> matcher(Matcher<? extends CharSequence> chunkValue) { return ViewMatchers.withContentDescription(chunkValue); } } static final class WithId_Resource extends CombinedChunk<Integer> { @Override public Matcher<View> matcher(Integer chunkValue) { return ViewMatchers.withId(chunkValue); } } static final class WithId_Matcher extends CombinedChunk<Matcher<Integer>> { @Override public Matcher<View> matcher(Matcher<Integer> chunkValue) { return ViewMatchers.withId(chunkValue); } } static final class WithResourceName_String extends CombinedChunk<String> { @Override public Matcher<View> matcher(String chunkValue) { return ViewMatchers.withResourceName(chunkValue); } } static final class WithResourceName_Matcher extends CombinedChunk<Matcher<String>> { @Override public Matcher<View> matcher(Matcher<String> chunkValue) { return ViewMatchers.withResourceName(chunkValue); } } static final class WithTagKey extends CombinedChunk<Integer> { @Override public Matcher<View> matcher(Integer chunkValue) { return ViewMatchers.withTagKey(chunkValue); } } static final class WithTagKey_Matcher extends CombinedChunk<TagKeyArgs> { @Override public Matcher<View> matcher(TagKeyArgs chunkValue) { return ViewMatchers.withTagKey(chunkValue.key, chunkValue.matcher); } } static final class WithTagValue extends CombinedChunk<Matcher<Object>> { @Override public Matcher<View> matcher(Matcher<Object> chunkValue) { return ViewMatchers.withTagValue(chunkValue); } } static final class WithText_String extends CombinedChunk<String> { @Override public Matcher<View> matcher(String chunkValue) { return ViewMatchers.withText(chunkValue); } } static final class WithText_Matcher extends CombinedChunk<Matcher<String>> { @Override public Matcher<View> matcher(Matcher<String> chunkValue) { return ViewMatchers.withText(chunkValue); } } static final class WithText_Resource extends CombinedChunk<Integer> { @Override public Matcher<View> matcher(Integer chunkValue) { return ViewMatchers.withText(chunkValue); } } static final class WithHint_String extends CombinedChunk<String> { @Override public Matcher<View> matcher(String chunkValue) { return ViewMatchers.withHint(chunkValue); } } static final class WithHint_Matcher extends CombinedChunk<Matcher<String>> { @Override public Matcher<View> matcher(Matcher<String> chunkValue) { return ViewMatchers.withHint(chunkValue); } } static final class WithHint_Resource extends CombinedChunk<Integer> { @Override public Matcher<View> matcher(Integer chunkValue) { return ViewMatchers.withHint(chunkValue); } } static final class IsChecked extends ElementaryChunk<Boolean> { @Override public Matcher<View> matcher(Boolean chunkValue) { return ViewMatchers.isChecked(); } } static final class IsNotChecked extends ElementaryChunk<Boolean> { @Override public Matcher<View> matcher(Boolean chunkValue) { return ViewMatchers.isNotChecked(); } } static final class HasContentDescription extends ElementaryChunk<Boolean> { @Override public Matcher<View> matcher(Boolean chunkValue) { return ViewMatchers.hasContentDescription(); } } static final class HasDescendant extends CombinedChunk<Matcher<View>> { @Override public Matcher<View> matcher(Matcher<View> chunkValue) { return ViewMatchers.hasDescendant(chunkValue); } } static final class IsClickable extends ElementaryChunk<Boolean> { @Override public Matcher<View> matcher(Boolean chunkValue) { return ViewMatchers.isClickable(); } } static final class IsDescendantOfA extends CombinedChunk<Matcher<View>> { @Override public Matcher<View> matcher(Matcher<View> chunkValue) { return ViewMatchers.isDescendantOfA(chunkValue); } } static final class WithEffectiveVisibility extends CombinedChunk<ViewMatchers.Visibility> { @Override public Matcher<View> matcher(ViewMatchers.Visibility chunkValue) { return ViewMatchers.withEffectiveVisibility(chunkValue); } } static final class WithParent extends CombinedChunk<Matcher<View>> { @Override public Matcher<View> matcher(Matcher<View> chunkValue) { return ViewMatchers.withParent(chunkValue); } } static final class WithChild extends CombinedChunk<Matcher<View>> { @Override public Matcher<View> matcher(Matcher<View> chunkValue) { return ViewMatchers.withChild(chunkValue); } } static final class IsRoot extends ElementaryChunk<Boolean> { @Override public Matcher<View> matcher(Boolean chunkValue) { return ViewMatchers.isRoot(); } } static final class SupportsInputMethods extends ElementaryChunk<Boolean> { @Override public Matcher<View> matcher(Boolean chunkValue) { return ViewMatchers.supportsInputMethods(); } } static final class HasImeAction_Integer extends CombinedChunk<Integer> { @Override public Matcher<View> matcher(Integer chunkValue) { return ViewMatchers.hasImeAction(chunkValue); } } static final class HasImeAction_Matcher extends CombinedChunk<Matcher<Integer>> { @Override public Matcher<View> matcher(Matcher<Integer> chunkValue) { return ViewMatchers.hasImeAction(chunkValue); } } static final class HasLinks extends ElementaryChunk<Boolean> { @Override public Matcher<View> matcher(Boolean chunkValue) { return ViewMatchers.hasLinks(); } } static final class WithSpinnerText_Resource extends CombinedChunk<Integer> { @Override public Matcher<View> matcher(Integer chunkValue) { return ViewMatchers.withSpinnerText(chunkValue); } } static final class WithSpinnerText_Matcher extends CombinedChunk<Matcher<String>> { @Override public Matcher<View> matcher(Matcher<String> chunkValue) { return ViewMatchers.withSpinnerText(chunkValue); } } static final class WithSpinnerText_String extends CombinedChunk<String> { @Override public Matcher<View> matcher(String chunkValue) { return ViewMatchers.withSpinnerText(chunkValue); } } static final class IsJavascriptEnabled extends ElementaryChunk<Boolean> { @Override public Matcher<View> matcher(Boolean chunkValue) { return ViewMatchers.isJavascriptEnabled(); } } static final class HasErrorText_Matcher extends CombinedChunk<Matcher<String>> { @Override public Matcher<View> matcher(Matcher<String> chunkValue) { return ViewMatchers.hasErrorText(chunkValue); } } static final class HasErrorText_String extends CombinedChunk<String> { @Override public Matcher<View> matcher(String chunkValue) { return ViewMatchers.hasErrorText(chunkValue); } } static final class WithInputType extends CombinedChunk<Integer> { @Override public Matcher<View> matcher(Integer chunkValue) { return ViewMatchers.withInputType(chunkValue); } } static final class Matching extends CombinedChunk<Matcher<View>> { @Override public Matcher<View> matcher(Matcher<View> chunkValue) { return chunkValue; } } static final class TagKeyArgs { public int key; public org.hamcrest.Matcher<Object> matcher; public TagKeyArgs(int key, Matcher<Object> matcher) { this.key = key; this.matcher = matcher; } } }
32.14248
110
0.661796
562393532c091be2f743055859ca241e810f7d14
2,467
package com.believeyourself.leetcode.mergeTwoSortedLists; import com.believeyourself.leetcode.domain.ListNode; /** * 21. Merge Two Sorted Lists * Merge two sorted linked lists and return it as a new list. F * <p> * Example: * <p> * Input: 1->2->4, 1->3->4 * Output: 1->1->2->3->4->4 */ public class MergeTwoSortedLists { /** * 解题思路 * 1. 构建一个新的链表,维护两个指针,使用拉链法对两个链表节点进行选取。 * * @param l1 链表1 * @param l2 链表2 * @return 新的链表 */ public ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode newListNode = new ListNode(0); ListNode currNode = newListNode; while (l1 != null && l2 != null) { while (l1 != null && l1.val <= l2.val) { currNode.next = l1; currNode = currNode.next; l1 = l1.next; } while (l2 != null && l1 != null && l2.val < l1.val) { currNode.next = l2; currNode = currNode.next; l2 = l2.next; } } if (l1 != null) { currNode.next = l1; } if (l2 != null) { currNode.next = l2; } return newListNode.next; } /** * 解题思路:leetcode solution * 1. 使用递归法合并两个链表 * * @param l1 链表1 * @param l2 链表2 * @return 新的链表 */ public ListNode mergeTwoListsUsingRecursion(ListNode l1, ListNode l2) { if (l1 == null) { return l2; } if (l2 == null) { return l1; } if (l1.val < l2.val) { l1.next = mergeTwoListsUsingRecursion(l1.next, l2); return l1; } else { l2.next = mergeTwoListsUsingRecursion(l1, l2.next); return l2; } } public static void main(String[] args) { ListNode l1 = new ListNode(1); l1.next = new ListNode(2); l1.next.next = new ListNode(4); l1.next.next.next = new ListNode(5); l1.next.next.next.next = new ListNode(6); l1.next.next.next.next.next = new ListNode(8); ListNode l2 = new ListNode(1); l2.next = new ListNode(3); l2.next.next = new ListNode(4); l2.next.next.next = new ListNode(7); l2.next.next.next.next = new ListNode(9); l2.next.next.next.next.next = new ListNode(10); System.out.println(new MergeTwoSortedLists().mergeTwoListsUsingRecursion(l1, l2)); } }
25.968421
90
0.520876
836a0d6bafd2459636a23b3b75f883014c3cd9e0
1,573
package com.github.scribejava.apis.fitbit; import com.github.scribejava.core.model.OAuth2AccessTokenErrorResponse; import com.github.scribejava.core.model.Response; import com.github.scribejava.core.oauth2.OAuth2Error; import java.io.IOException; import org.junit.Test; import static org.junit.Assert.assertThrows; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertEquals; import org.junit.function.ThrowingRunnable; public class FitBitJsonTokenExtractorTest { private static final String ERROR_DESCRIPTION = "Authorization code invalid: " + "cbb1c11b23209011e89be71201fa6381464dc0af " + "Visit https://dev.fitbit.com/docs/oauth2 for more information " + "on the Fitbit Web API authorization process."; private static final String ERROR_JSON = "{\"errors\":[{\"errorType\":\"invalid_grant\",\"message\":\"" + ERROR_DESCRIPTION + "\"}],\"success\":false}"; @Test public void testErrorExtraction() throws IOException { final FitBitJsonTokenExtractor extractor = new FitBitJsonTokenExtractor(); final OAuth2AccessTokenErrorResponse thrown = assertThrows(OAuth2AccessTokenErrorResponse.class, new ThrowingRunnable() { @Override public void run() throws Throwable { extractor.generateError(new Response(403, null, null, ERROR_JSON)); } }); assertSame(OAuth2Error.INVALID_GRANT, thrown.getError()); assertEquals(ERROR_DESCRIPTION, thrown.getErrorDescription()); } }
40.333333
107
0.713287
6d85f6c0e737e1d25af32af1f2806b2caf1fb07e
3,655
package org.hl7.fhir.r4.model.codesystems; /* Copyright (c) 2011+, HL7, Inc. 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 HL7 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 THE COPYRIGHT HOLDER OR CONTRIBUTORS 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. */ // Generated on Sat, Mar 3, 2018 18:00-0500 for FHIR v3.2.0 import org.hl7.fhir.r4.model.EnumFactory; public class V3ContextControlEnumFactory implements EnumFactory<V3ContextControl> { public V3ContextControl fromCode(String codeString) throws IllegalArgumentException { if (codeString == null || "".equals(codeString)) return null; if ("_ContextControlAdditive".equals(codeString)) return V3ContextControl._CONTEXTCONTROLADDITIVE; if ("AN".equals(codeString)) return V3ContextControl.AN; if ("AP".equals(codeString)) return V3ContextControl.AP; if ("_ContextControlNonPropagating".equals(codeString)) return V3ContextControl._CONTEXTCONTROLNONPROPAGATING; if ("ON".equals(codeString)) return V3ContextControl.ON; if ("_ContextControlOverriding".equals(codeString)) return V3ContextControl._CONTEXTCONTROLOVERRIDING; if ("OP".equals(codeString)) return V3ContextControl.OP; if ("_ContextControlPropagating".equals(codeString)) return V3ContextControl._CONTEXTCONTROLPROPAGATING; throw new IllegalArgumentException("Unknown V3ContextControl code '"+codeString+"'"); } public String toCode(V3ContextControl code) { if (code == V3ContextControl._CONTEXTCONTROLADDITIVE) return "_ContextControlAdditive"; if (code == V3ContextControl.AN) return "AN"; if (code == V3ContextControl.AP) return "AP"; if (code == V3ContextControl._CONTEXTCONTROLNONPROPAGATING) return "_ContextControlNonPropagating"; if (code == V3ContextControl.ON) return "ON"; if (code == V3ContextControl._CONTEXTCONTROLOVERRIDING) return "_ContextControlOverriding"; if (code == V3ContextControl.OP) return "OP"; if (code == V3ContextControl._CONTEXTCONTROLPROPAGATING) return "_ContextControlPropagating"; return "?"; } public String toSystem(V3ContextControl code) { return code.getSystem(); } }
42.011494
90
0.725581
617f761b55f5ab2bced47c1bc93dc018e470f902
17,986
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.data.tables; import com.azure.core.http.HttpClient; import com.azure.core.http.policy.ExponentialBackoff; import com.azure.core.http.policy.HttpLogDetailLevel; import com.azure.core.http.policy.HttpLogOptions; import com.azure.core.http.policy.HttpPipelinePolicy; import com.azure.core.http.policy.RetryPolicy; import com.azure.core.http.rest.PagedResponse; import com.azure.core.http.rest.Response; import com.azure.core.test.TestBase; import com.azure.data.tables.models.ListTablesOptions; import com.azure.data.tables.models.TableEntity; import com.azure.data.tables.models.TableItem; import com.azure.data.tables.models.TableServiceCorsRule; import com.azure.data.tables.models.TableServiceException; import com.azure.data.tables.models.TableServiceLogging; import com.azure.data.tables.models.TableServiceMetrics; import com.azure.data.tables.models.TableServiceProperties; import com.azure.data.tables.models.TableServiceRetentionPolicy; import com.azure.data.tables.models.TableServiceStatistics; import com.azure.data.tables.sas.TableAccountSasPermission; import com.azure.data.tables.sas.TableAccountSasResourceType; import com.azure.data.tables.sas.TableAccountSasService; import com.azure.data.tables.sas.TableAccountSasSignatureValues; import com.azure.data.tables.sas.TableSasIpRange; import com.azure.data.tables.sas.TableSasProtocol; import org.junit.jupiter.api.Assumptions; import org.junit.jupiter.api.Test; import reactor.test.StepVerifier; import java.net.URI; import java.net.URISyntaxException; import java.time.Duration; import java.time.OffsetDateTime; import java.time.ZoneOffset; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.StringJoiner; import static com.azure.data.tables.TestUtils.assertPropertiesEquals; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; /** * Tests methods for {@link TableServiceClient}. */ public class TableServiceClientTest extends TestBase { private static final HttpClient DEFAULT_HTTP_CLIENT = HttpClient.createDefault(); private static final boolean IS_COSMOS_TEST = TestUtils.isCosmosTest(); private TableServiceClient serviceClient; private HttpPipelinePolicy recordPolicy; private HttpClient playbackClient; @Override protected void beforeTest() { final String connectionString = TestUtils.getConnectionString(interceptorManager.isPlaybackMode()); final TableServiceClientBuilder builder = new TableServiceClientBuilder() .connectionString(connectionString) .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)); if (interceptorManager.isPlaybackMode()) { playbackClient = interceptorManager.getPlaybackClient(); builder.httpClient(playbackClient); } else { builder.httpClient(DEFAULT_HTTP_CLIENT); if (!interceptorManager.isLiveMode()) { recordPolicy = interceptorManager.getRecordPolicy(); builder.addPolicy(recordPolicy); } } serviceClient = builder.buildClient(); } @Test void serviceCreateTable() { // Arrange String tableName = testResourceNamer.randomName("test", 20); // Act & Assert assertNotNull(serviceClient.createTable(tableName)); } @Test void serviceCreateTableWithResponse() { // Arrange String tableName = testResourceNamer.randomName("test", 20); // Act & Assert assertNotNull(serviceClient.createTableWithResponse(tableName, null, null).getValue()); } @Test void serviceCreateTableFailsIfExists() { // Arrange String tableName = testResourceNamer.randomName("test", 20); serviceClient.createTable(tableName); // Act & Assert assertThrows(TableServiceException.class, () -> serviceClient.createTable(tableName)); } @Test void serviceCreateTableIfNotExists() { // Arrange String tableName = testResourceNamer.randomName("test", 20); // Act & Assert assertNotNull(serviceClient.createTableIfNotExists(tableName)); } @Test void serviceCreateTableIfNotExistsSucceedsIfExists() { // Arrange String tableName = testResourceNamer.randomName("test", 20); serviceClient.createTable(tableName); //Act & Assert assertNull(serviceClient.createTableIfNotExists(tableName)); } @Test void serviceCreateTableIfNotExistsWithResponse() { // Arrange String tableName = testResourceNamer.randomName("test", 20); int expectedStatusCode = 204; //Act & Assert final Response<TableClient> response = serviceClient.createTableIfNotExistsWithResponse(tableName, null, null); assertEquals(expectedStatusCode, response.getStatusCode()); assertNotNull(response.getValue()); } @Test void serviceCreateTableIfNotExistsWithResponseSucceedsIfExists() { // Arrange String tableName = testResourceNamer.randomName("test", 20); int expectedStatusCode = 409; serviceClient.createTable(tableName); //Act & Assert final Response<TableClient> response = serviceClient.createTableIfNotExistsWithResponse(tableName, null, null); assertEquals(expectedStatusCode, response.getStatusCode()); assertNull(response.getValue()); } @Test void serviceDeleteTable() { // Arrange final String tableName = testResourceNamer.randomName("test", 20); serviceClient.createTable(tableName); //Act & Assert assertDoesNotThrow(() -> serviceClient.deleteTable(tableName)); } @Test void serviceDeleteNonExistingTable() { // Arrange final String tableName = testResourceNamer.randomName("test", 20); //Act & Assert assertDoesNotThrow(() -> serviceClient.createTable(tableName)); } @Test void serviceDeleteTableWithResponse() { // Arrange String tableName = testResourceNamer.randomName("test", 20); int expectedStatusCode = 204; serviceClient.createTable(tableName); //Act & Assert assertEquals(expectedStatusCode, serviceClient.deleteTableWithResponse(tableName, null, null).getStatusCode()); } @Test void serviceDeleteNonExistingTableWithResponse() { // Arrange String tableName = testResourceNamer.randomName("test", 20); int expectedStatusCode = 404; //Act & Assert assertEquals(expectedStatusCode, serviceClient.deleteTableWithResponse(tableName, null, null).getStatusCode()); } @Test void serviceListTables() { // Arrange final String tableName = testResourceNamer.randomName("test", 20); final String tableName2 = testResourceNamer.randomName("test", 20); serviceClient.createTable(tableName); serviceClient.createTable(tableName2); // Act & Assert Iterator<PagedResponse<TableItem>> iterator = serviceClient.listTables().iterableByPage().iterator(); assertTrue(iterator.hasNext()); assertTrue(2 <= iterator.next().getValue().size()); } @Test void serviceListTablesWithFilter() { // Arrange final String tableName = testResourceNamer.randomName("test", 20); final String tableName2 = testResourceNamer.randomName("test", 20); ListTablesOptions options = new ListTablesOptions().setFilter("TableName eq '" + tableName + "'"); serviceClient.createTable(tableName); serviceClient.createTable(tableName2); // Act & Assert serviceClient.listTables(options, null, null) .forEach(tableItem -> assertEquals(tableName, tableItem.getName())); } @Test void serviceListTablesWithTop() { // Arrange final String tableName = testResourceNamer.randomName("test", 20); final String tableName2 = testResourceNamer.randomName("test", 20); final String tableName3 = testResourceNamer.randomName("test", 20); ListTablesOptions options = new ListTablesOptions().setTop(2); serviceClient.createTable(tableName); serviceClient.createTable(tableName2); serviceClient.createTable(tableName3); // Act & Assert Iterator<PagedResponse<TableItem>> iterator = serviceClient.listTables(options, null, null).iterableByPage().iterator(); assertTrue(iterator.hasNext()); assertEquals(2, iterator.next().getValue().size()); } @Test void serviceGetTableClient() { // Arrange final String tableName = testResourceNamer.randomName("test", 20); serviceClient.createTable(tableName); TableClient tableClient = serviceClient.getTableClient(tableName); // Act & Assert TableClientTest.getEntityWithResponseImpl(tableClient, this.testResourceNamer); } @Test public void generateAccountSasTokenWithMinimumParameters() { final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableAccountSasPermission permissions = TableAccountSasPermission.parse("r"); final TableAccountSasService services = new TableAccountSasService().setTableAccess(true); final TableAccountSasResourceType resourceTypes = new TableAccountSasResourceType().setObject(true); final TableSasProtocol protocol = TableSasProtocol.HTTPS_ONLY; final TableAccountSasSignatureValues sasSignatureValues = new TableAccountSasSignatureValues(expiryTime, permissions, services, resourceTypes) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()); final String sas = serviceClient.generateAccountSas(sasSignatureValues); assertTrue( sas.startsWith( "sv=2019-02-02" + "&ss=t" + "&srt=o" + "&se=2021-12-12T00%3A00%3A00Z" + "&sp=r" + "&spr=https" + "&sig=" ) ); } @Test public void generateAccountSasTokenWithAllParameters() { final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableAccountSasPermission permissions = TableAccountSasPermission.parse("rdau"); final TableAccountSasService services = new TableAccountSasService().setTableAccess(true); final TableAccountSasResourceType resourceTypes = new TableAccountSasResourceType().setObject(true); final TableSasProtocol protocol = TableSasProtocol.HTTPS_HTTP; final OffsetDateTime startTime = OffsetDateTime.of(2015, 1, 1, 0, 0, 0, 0, ZoneOffset.UTC); final TableSasIpRange ipRange = TableSasIpRange.parse("a-b"); final TableAccountSasSignatureValues sasSignatureValues = new TableAccountSasSignatureValues(expiryTime, permissions, services, resourceTypes) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()) .setStartTime(startTime) .setSasIpRange(ipRange); final String sas = serviceClient.generateAccountSas(sasSignatureValues); assertTrue( sas.startsWith( "sv=2019-02-02" + "&ss=t" + "&srt=o" + "&st=2015-01-01T00%3A00%3A00Z" + "&se=2021-12-12T00%3A00%3A00Z" + "&sp=rdau" + "&sip=a-b" + "&spr=https%2Chttp" + "&sig=" ) ); } @Test public void canUseSasTokenToCreateValidTableClient() { final OffsetDateTime expiryTime = OffsetDateTime.of(2021, 12, 12, 0, 0, 0, 0, ZoneOffset.UTC); final TableAccountSasPermission permissions = TableAccountSasPermission.parse("a"); final TableAccountSasService services = new TableAccountSasService().setTableAccess(true); final TableAccountSasResourceType resourceTypes = new TableAccountSasResourceType().setObject(true); final TableSasProtocol protocol = TableSasProtocol.HTTPS_ONLY; final TableAccountSasSignatureValues sasSignatureValues = new TableAccountSasSignatureValues(expiryTime, permissions, services, resourceTypes) .setProtocol(protocol) .setVersion(TableServiceVersion.V2019_02_02.getVersion()); final String sas = serviceClient.generateAccountSas(sasSignatureValues); final String tableName = testResourceNamer.randomName("test", 20); serviceClient.createTable(tableName); final TableClientBuilder tableClientBuilder = new TableClientBuilder() .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) .endpoint(serviceClient.getServiceEndpoint()) .sasToken(sas) .tableName(tableName); if (interceptorManager.isPlaybackMode()) { tableClientBuilder.httpClient(playbackClient); } else { tableClientBuilder.httpClient(DEFAULT_HTTP_CLIENT); if (!interceptorManager.isLiveMode()) { tableClientBuilder.addPolicy(recordPolicy); } tableClientBuilder.addPolicy(new RetryPolicy(new ExponentialBackoff(6, Duration.ofMillis(1500), Duration.ofSeconds(100)))); } // Create a new client authenticated with the SAS token. final TableAsyncClient tableAsyncClient = tableClientBuilder.buildAsyncClient(); final String partitionKeyValue = testResourceNamer.randomName("partitionKey", 20); final String rowKeyValue = testResourceNamer.randomName("rowKey", 20); final TableEntity entity = new TableEntity(partitionKeyValue, rowKeyValue); final int expectedStatusCode = 204; //Act & Assert StepVerifier.create(tableAsyncClient.createEntityWithResponse(entity)) .assertNext(response -> assertEquals(expectedStatusCode, response.getStatusCode())) .expectComplete() .verify(); } @Test public void setGetProperties() { Assumptions.assumeFalse(IS_COSMOS_TEST, "Setting and getting properties is not supported on Cosmos endpoints."); TableServiceRetentionPolicy retentionPolicy = new TableServiceRetentionPolicy() .setDaysToRetain(5) .setEnabled(true); TableServiceLogging logging = new TableServiceLogging() .setReadLogged(true) .setAnalyticsVersion("1.0") .setRetentionPolicy(retentionPolicy); List<TableServiceCorsRule> corsRules = new ArrayList<>(); corsRules.add(new TableServiceCorsRule() .setAllowedMethods("GET,PUT,HEAD") .setAllowedOrigins("*") .setAllowedHeaders("x-ms-version") .setExposedHeaders("x-ms-client-request-id") .setMaxAgeInSeconds(10)); TableServiceMetrics hourMetrics = new TableServiceMetrics() .setEnabled(true) .setVersion("1.0") .setRetentionPolicy(retentionPolicy) .setIncludeApis(true); TableServiceMetrics minuteMetrics = new TableServiceMetrics() .setEnabled(true) .setVersion("1.0") .setRetentionPolicy(retentionPolicy) .setIncludeApis(true); TableServiceProperties sentProperties = new TableServiceProperties() .setLogging(logging) .setCorsRules(corsRules) .setMinuteMetrics(minuteMetrics) .setHourMetrics(hourMetrics); Response<Void> response = serviceClient.setPropertiesWithResponse(sentProperties, null, null); assertNotNull(response.getHeaders().getValue("x-ms-request-id")); assertNotNull(response.getHeaders().getValue("x-ms-version")); sleepIfRunningAgainstService(20000); TableServiceProperties retrievedProperties = serviceClient.getProperties(); assertPropertiesEquals(sentProperties, retrievedProperties); } @Test public void getStatistics() throws URISyntaxException { Assumptions.assumeFalse(IS_COSMOS_TEST, "Getting statistics is not supported on Cosmos endpoints."); URI primaryEndpoint = new URI(serviceClient.getServiceEndpoint()); String[] hostParts = primaryEndpoint.getHost().split("\\."); StringJoiner secondaryHostJoiner = new StringJoiner("."); secondaryHostJoiner.add(hostParts[0] + "-secondary"); for (int i = 1; i < hostParts.length; i++) { secondaryHostJoiner.add(hostParts[i]); } String secondaryEndpoint = primaryEndpoint.getScheme() + "://" + secondaryHostJoiner; TableServiceClient secondaryClient = new TableServiceClientBuilder() .endpoint(secondaryEndpoint) .serviceVersion(serviceClient.getServiceVersion()) .pipeline(serviceClient.getHttpPipeline()) .buildClient(); TableServiceStatistics statistics = secondaryClient.getStatistics(); assertNotNull(statistics); assertNotNull(statistics.getGeoReplication()); assertNotNull(statistics.getGeoReplication().getStatus()); assertNotNull(statistics.getGeoReplication().getLastSyncTime()); } }
39.356674
119
0.6857
33559de9f36259d73f22896107ad41770a89f187
710
package com.anggrayudi.materialpreference.sample.billing; public final class DonationItem { public String sku; public String title; public String price; private DonationItem(String sku, String title, String price) { this.sku = sku; this.title = title; this.price = price; } public static DonationItem[] items = { new DonationItem("good", "Good job!", "$0.99"), new DonationItem("love", "I love it!", "$1.99"), new DonationItem("perfect", "Perfect!", "$2.99"), new DonationItem("saved_my_life", "You saved my life", "$4.99"), new DonationItem("stfu", "Shut up and take my money!", "$6.99") }; }
30.869565
76
0.594366
965c52a5edf69006cf215c3e6d702533fc9f9930
7,513
package com.kirbybanman.travelclaimer; /* * Copyright 2015 Kirby Banman * * 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. */ import java.util.Date; import com.kirbybanman.travelclaimer.adapter.CategoryAdapter; import com.kirbybanman.travelclaimer.adapter.CurrencyAdapter; import com.kirbybanman.travelclaimer.core.TravelClaimerActivity; import com.kirbybanman.travelclaimer.interfaces.DateSetter; import com.kirbybanman.travelclaimer.model.Claim; import com.kirbybanman.travelclaimer.model.Expense; import com.kirbybanman.travelclaimer.view.ExpenseStringRenderer; import android.app.DialogFragment; import android.content.Intent; import android.os.Bundle; import android.text.InputFilter; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnKeyListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; /** * Activity for editing all details of an Expense. * * @author kdbanman * */ public class ExpenseActivity extends TravelClaimerActivity { private Claim claim; private Expense expense; private TextView dateText; private TextView descriptionText; private EditText amountText; private Spinner categorySpinner; private Spinner currencySpinner; private CategoryAdapter categoryAdapter; private CurrencyAdapter currencyAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_expense); dateText = (TextView) findViewById(R.id.ExpenseDateText); descriptionText = (TextView) findViewById(R.id.ExpenseDescriptionText); descriptionText.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { expense.setDescription(descriptionText.getText().toString()); return false; } }); amountText = (EditText) findViewById(R.id.ExpenseAmountNumber); amountText.setFilters(new InputFilter[] {new CurrencyInputFilter()}); amountText.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { try { expense.setAmount(Float.parseFloat(amountText.getText().toString())); } catch (NumberFormatException e) { Log.w("bad currency format", "could not convert float"); } return false; } }); categoryAdapter = new CategoryAdapter(this); currencyAdapter = new CurrencyAdapter(this); categorySpinner = (Spinner) findViewById(R.id.ExpenseCategorySpinner); categorySpinner.setAdapter(categoryAdapter); categorySpinner.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { // save the changes to the local attribute, but do // not mutate/save global state yet. expense.setCategory(categoryAdapter.get(position)); updateView(); } @Override public void onNothingSelected(AdapterView<?> parent) { // do nothing - claim unchanged } }); currencySpinner = (Spinner) findViewById(R.id.ExpenseCountryCodeSpinner); currencySpinner.setAdapter(currencyAdapter); currencySpinner.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { // save the changes to the local attribute, but do // not mutate/save global state yet. expense.setCurrency(currencyAdapter.get(position).toString()); updateView(); } @Override public void onNothingSelected(AdapterView<?> parent) { // do nothing - expense unchanged } }); } @Override protected void onResume() { super.onResume(); claim = getClaimFromIntent(); if (intentHasExpense()) expense = getExpenseFromIntent(); else expense = new Expense(); updateView(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.expense, 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 == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } /* * Render view elements according to local expense model state. */ private void updateView() { ExpenseStringRenderer expenseStrings = new ExpenseStringRenderer(expense); dateText.setText(expenseStrings.getDate()); descriptionText.setText(expense.getDescription()); amountText.setText(expenseStrings.getNumericalAmount()); categorySpinner.setSelection(categoryAdapter.indexOf(expense.getCategory())); currencySpinner.setSelection(currencyAdapter.indexOf(expense.getCurrency().toString())); } /* save our mutated local expense model if necessary, and * discard this activity. */ public void doneButtonClicked(View view) { // Text description is now confirmed. write it to local // model and the save that model globally. expense.setDescription(descriptionText.getText().toString()); // Detect if the expense is already known to the claim. // if it is, no need to explicitly add/replace it. otherwise we must. if (!claim.getExpenses().contains(expense)) claim.addExpense(expense); getApp().saveModel(); Intent intent = new Intent(this, ExpensesListActivity.class); finish(); startActivity(intent); } /* * Create dialog and use it to set the expense date. */ public void dateButtonClicked(View view) { DialogFragment frag = new DatePickerFragment(expense.getDate(), new DateSetter() { @Override public void setDate(Date date) { expense.setDate(date); dateText.setText(new ExpenseStringRenderer(expense).getDate()); } }); frag.show(getFragmentManager(), "expense_date"); } /* * Below are 3 obvious functions to inspect and extract data from the Intent. */ private Claim getClaimFromIntent() { int claimPosition = getIntent().getIntExtra("claimPosition", -1); try { return getApp().getClaimsList().get(claimPosition); } catch (IndexOutOfBoundsException e) { Log.e("intent fail", e.toString()); } return null; } private boolean intentHasExpense() { return getIntent().getIntExtra("expensePosition", -1) != -1; } private Expense getExpenseFromIntent() { int expensePosition = getIntent().getIntExtra("expensePosition", -1); try { return getClaimFromIntent().getExpenses().get(expensePosition); } catch (IndexOutOfBoundsException e) { Log.e("intent fail", e.toString()); } return null; } }
30.052
90
0.740583
d1201ec6b00602ab910d9bab1dc7fe7f991f5f99
380
package com.superfarmland; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; @FeignClient("manage-user") public interface UserFeignTest { @RequestMapping("/manage-user/HelloWordController/hellowordForFeign") String hellowordForFeign(); }
27.142857
73
0.821053
3cc3b434cb76d9539683b82380a7b684c34c072b
805
package puzzles; /** * People standing in a circle pass a sword and start killing the next one to * them. Who will be the one left at the end. * * @author shivam.maharshi */ public class CircularSwordKilling { /* * If number is power of 2, the one who started sword passing is the one who * will survive at the end. If it is not, then the one person who has the * sword when the remaining people left are exactly power of 2 will be the * answer. */ public static int solve(int n) { int k = getMaxPowerOf2Value(n); return 2 * (n - k) + 1; } public static int getMaxPowerOf2Value(int n) { int num = 1; while (num <= n) { num *= 2; } return num / 2; } public static void main(String[] args) { System.out.println(solve(100)); } }
23
78
0.63354
8938b495d83d62301d2186b83e0ac73cf3c3c4a0
930
package org.deeplearning4j.optimize; import java.io.Serializable; /** * * Training evaluator, used for determining early stop * * @author Adam Gibson */ public interface TrainingEvaluator extends Serializable { /** * Whether to terminate or not * @param epoch the current epoch * @return whether to terminate or not * on the given epoch */ boolean shouldStop(int epoch); public double improvementThreshold(); double patience(); /** * Amount patience should be increased when a new best threshold is hit * @return */ double patienceIncrease(); /** * The best validation loss so far * @return the best validation loss so far */ public double bestLoss(); /** * The number of epochs to test on * @return the number of epochs to test on */ public int validationEpochs(); public int miniBatchSize(); }
18.6
75
0.64086
af9b97ce2a475cdcebae846f2e4088e49a762d5a
692
package com.appointment.appointment.client; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; @Service public class CardRestTemplateClient { @Autowired RestTemplate restTemplate; public CardMapper getCardByCardCode(String cardCode) { ResponseEntity<CardMapper> result = restTemplate.exchange("http://cardservice/cards/{cardCode}", HttpMethod.GET, null, CardMapper.class, cardCode); return result.getBody(); } }
30.086957
98
0.745665
ff26489610435c9084b1622dce738fb94a6ae077
3,893
package com.gitee.swsk33.winfileselector; import java.awt.Color; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Font; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionAdapter; import java.net.URL; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; class NewDir { static int x; static int y; static String name; static JTextField jt = new JTextField(); /** * @wbp.parser.entryPoint */ @SuppressWarnings("deprecation") public void ndfr() { name = ""; Toolkit kit = Toolkit.getDefaultToolkit(); Dimension sc = kit.getScreenSize(); JDialog jd = new JDialog(); jd.setSize(320, 145); jd.setLocation(sc.width / 2 - 160, sc.height / 2 - 73); jd.setUndecorated(true); jd.setModal(true); URL bg = NewDir.class.getResource("/winfileselector/bg-newdirdf.png"); JLabel bl = new JLabel(new ImageIcon(bg)); // 把上面的图片对象加到一个名为bl的标签里 bl.setBounds(0, 0, jd.getWidth(), jd.getHeight()); // 设置标签大小 JPanel imagePanel = (JPanel) jd.getContentPane(); // 把内容窗格转化为JPanel,否则不能用方法setOpaque()来使内容窗格透明 ,使内容窗格透明后才能显示背景图片 imagePanel.setOpaque(false); // 把背景图片添加到分层窗格的最底层作为背景 jd.getLayeredPane().add(bl, new Integer(Integer.MIN_VALUE)); jd.addMouseListener(new MouseAdapter() { // 设置窗口可拖动,添加监听器 public void mousePressed(MouseEvent e) { // 获取点击鼠标时的坐标 x = e.getPoint().x; y = e.getPoint().y; } public void mouseReleased(MouseEvent e) { jd.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); } }); jd.addMouseMotionListener(new MouseMotionAdapter() { // 设置拖拽后,窗口的位置 public void mouseDragged(MouseEvent e) { jd.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR)); jd.setLocation(e.getXOnScreen() - x, e.getYOnScreen() - y); } }); JLabel title = new JLabel("新建文件夹"); title.setBackground(Color.YELLOW); title.setFont(new Font("黑体", Font.BOLD, 16)); title.setBounds(5, 5, 91, 18); JLabel na = new JLabel("名字:"); na.setFont(new Font("黑体", Font.BOLD, 15)); na.setBounds(23, 66, 48, 22); JButton ok = new JButton("确定"); ok.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { if (jt.getText().equals("")) { Runtime.getRuntime().exec("cmd /c echo msgbox \"请输入名称!\",64,\"ERROR\">alert.vbs && start alert.vbs && ping -n 2 127.1>nul && del alert.vbs"); } else if (jt.getText().contains("\\") || jt.getText().contains("/") || jt.getText().contains(":") || jt.getText().contains("*") || jt.getText().contains("?") || jt.getText().contains("\"") || jt.getText().contains("<") || jt.getText().contains(">") || jt.getText().contains("|")) { Runtime.getRuntime().exec("cmd /c echo msgbox \"文件夹名称不能包含非法字符(\\/:*?\"<>|)!\",64,\"ERROR\">alert.vbs && start alert.vbs && ping -n 2 127.1>nul && del alert.vbs"); } else { name = jt.getText().toString(); jd.dispose(); } } catch (Exception e1) { e1.printStackTrace(); } } }); ok.setContentAreaFilled(false); ok.setForeground(Color.BLUE); ok.setFont(new Font("等线", Font.BOLD, 15)); ok.setBounds(71, 104, 71, 27); JButton cancel = new JButton("取消"); cancel.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { jd.dispose(); } }); cancel.setContentAreaFilled(false); cancel.setForeground(Color.MAGENTA); cancel.setFont(new Font("等线", Font.BOLD, 15)); cancel.setBounds(189, 104, 71, 27); jt.setBounds(71, 65, 222, 27); JPanel jp = new JPanel(); jp.setOpaque(false); jp.setLayout(null); jp.add(title); jp.add(na); jp.add(jt); jp.add(ok); jp.add(cancel); jd.getContentPane().add(jp); jd.show(); } }
34.149123
287
0.675572
92153ff632c3542bd7bbf5375a5383658cd58953
3,856
/* * 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.tinkerpop4.gremlin.structure.io.gryo; import org.apache.tinkerpop4.gremlin.structure.Vertex; import org.apache.tinkerpop4.gremlin.structure.io.GraphWriter; import org.apache.tinkerpop4.gremlin.structure.util.Attachable; import org.apache.tinkerpop4.gremlin.structure.util.detached.DetachedVertex; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.HashMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicBoolean; import static org.junit.Assert.assertTrue; /** * @author Stephen Mallette (http://stephen.genoprime.com) */ public class GryoReaderWriterTest { @Test public void shouldBeAbleToReUseBuilderInDifferentThreads() throws Exception { final ByteArrayOutputStream os = new ByteArrayOutputStream(); final GraphWriter writer = GryoWriter.build().create(); writer.writeVertex(os, new DetachedVertex(1, "test", new HashMap<>())); os.close(); final byte[] bytes = os.toByteArray(); final CountDownLatch latch = new CountDownLatch(1); final AtomicBoolean assertProcess1 = new AtomicBoolean(false); final AtomicBoolean assertProcess2 = new AtomicBoolean(false); final AtomicBoolean assertProcess3 = new AtomicBoolean(false); // just one builder to re-use among threads final GryoReader.Builder builder = GryoReader.build(); final Thread process1 = new Thread(() -> { try { latch.await(); final GryoReader reader = builder.create(); final Vertex v = reader.readVertex(new ByteArrayInputStream(bytes), Attachable::get); assertProcess1.set(v.id().equals(1)); } catch (Exception ex) { throw new RuntimeException(ex); } }); final Thread process2 = new Thread(() -> { try { latch.await(); final GryoReader reader = builder.create(); final Vertex v = reader.readVertex(new ByteArrayInputStream(bytes), Attachable::get); assertProcess2.set(v.id().equals(1)); } catch (Exception ex) { throw new RuntimeException(ex); } }); final Thread process3 = new Thread(() -> { try { latch.await(); final GryoReader reader = builder.create(); final Vertex v = reader.readVertex(new ByteArrayInputStream(bytes), Attachable::get); assertProcess3.set(v.id().equals(1)); } catch (Exception ex) { throw new RuntimeException(ex); } }); process1.start(); process2.start(); process3.start(); latch.countDown(); process3.join(); process2.join(); process1.join(); assertTrue(assertProcess1.get()); assertTrue(assertProcess2.get()); assertTrue(assertProcess3.get()); } }
37.076923
101
0.651971
412729938c71ddcc380529c1247aedeb2f7f4a31
499
package edu.asu.qstore4s.repository; import org.springframework.data.neo4j.repository.GraphRepository; import org.springframework.transaction.annotation.Transactional; import edu.asu.qstore4s.domain.events.impl.RelationEvent; public interface RelationEventRepository extends GraphRepository<RelationEvent>{ RelationEvent findById(String id); /** * {@inheritDoc}} */ @Override @Transactional public <U extends RelationEvent> Iterable<U> save(Iterable<U> arg0); }
24.95
81
0.765531
871f12eaf0d084f242f19efdb3e54273be5eca53
5,597
/* * Copyright (C) 2013 salesforce.com, 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 org.auraframework.integration.test.modules.ui; import org.auraframework.integration.test.util.WebDriverTestCase; import org.auraframework.system.AuraContext.Mode; import org.auraframework.test.util.WebDriverUtil.BrowserType; import org.junit.Test; import org.openqa.selenium.By; /** * Runs the /moduletest/bootstrap.app app to verify module and aura/module interoperability works. */ public class ModulesBootstrapUITest extends WebDriverTestCase { private static final By BY_BUTTON_TOGGLE = By.cssSelector(".button-toggle"); private static final By BY_BUTTON_SET1 = By.cssSelector(".button-set1"); private static final By BY_BUTTON_SET2 = By.cssSelector(".button-set2"); private static final By BY_BUTTON_SET3 = By.cssSelector(".button-set3"); private static final By BY_A_RES1 = By.cssSelector(".a-res1"); private static final By BY_A_RES2 = By.cssSelector(".a-res2"); private static final By BY_A_RES3 = By.cssSelector(".a-res3"); private static final By BY_A_EXPR = By.cssSelector(".a-expr"); private static final By BY_M_LITERAL = By.cssSelector(".simple .m-literal"); private static final By BY_M_BOUND = By.cssSelector(".m-bound"); private static final By BY_M_UNBOUND = By.cssSelector(".m-unbound"); private static final By BY_M_EXPR = By.cssSelector(".m-expr"); @Test @TargetBrowsers({BrowserType.GOOGLECHROME}) // non-compat will fail in unsupported browsers public void testInteropMinified() throws Exception { open("/moduletest/bootstrap.app?aura.compat=0", Mode.SELENIUM); doInteropTest(); } @Test public void testInteropMinifiedCompat() throws Exception { open("/moduletest/bootstrap.app?aura.compat=1", Mode.SELENIUM); doInteropTest(); } @Test @TargetBrowsers({BrowserType.GOOGLECHROME}) // non-compat will fail in unsupported browsers public void testInteropDev() throws Exception { open("/moduletest/bootstrap.app?aura.compat=0", Mode.DEV); doInteropTest(); } @Test public void testInteropDevCompat() throws Exception { open("/moduletest/bootstrap.app?aura.compat=1", Mode.DEV); doInteropTest(); } private void doInteropTest() { // check initial state assertEquals("I'm modules!", findDomElement(By.cssSelector(".i-am-modules")).getText()); assertState( "I'm v.test", "I'm v.test2", "I'm v.test3", "I'm v.test3!!", "Literal: Hi!", "Bound: I'm v.test", "Unbound: I'm v.test2", "Expression: I'm v.test3!!"); // press "Set v.test" findDomElement(BY_BUTTON_SET1).click(); assertState( "v.test | 1", "I'm v.test2", "I'm v.test3", "I'm v.test3!!", "Literal: Hi!", "Bound: v.test | 1", "Unbound: I'm v.test2", "Expression: I'm v.test3!!"); // press "Set v.test2" findDomElement(BY_BUTTON_SET2).click(); assertState( "v.test | 1", "v.test2 | 2", "I'm v.test3", "I'm v.test3!!", "Literal: Hi!", "Bound: v.test | 1", "Unbound: I'm v.test2", "Expression: I'm v.test3!!"); // press "Set v.test3" findDomElement(BY_BUTTON_SET3).click(); assertState( "v.test | 1", "v.test2 | 2", "v.test3 | 3", "v.test3 | 3!!", "Literal: Hi!", "Bound: v.test | 1", "Unbound: I'm v.test2", "Expression: v.test3 | 3!!"); // toogle aura:if to hide/show component findDomElement(BY_BUTTON_TOGGLE).click(); waitForCondition("return $A.getRoot().find('simple') === undefined"); findDomElement(BY_BUTTON_TOGGLE).click(); waitForCondition("return $A.getRoot().find('simple') !== undefined"); // iteration should display multiple module components assertTrue(findDomElements(By.cssSelector(".modules-container")).size() > 1); } private void assertState(String aRes1, String aRes2, String aRes3, String aExpr, String mLiteral, String mBound, String mUnbound, String mExpr) { assertEquals(aRes1, findDomElement(BY_A_RES1).getText()); assertEquals(aRes2, findDomElement(BY_A_RES2).getText()); assertEquals(aRes3, findDomElement(BY_A_RES3).getText()); assertEquals(aExpr, findDomElement(BY_A_EXPR).getText()); assertEquals(mLiteral, findDomElement(BY_M_LITERAL).getText()); assertEquals(mBound, findDomElement(BY_M_BOUND).getText()); assertEquals(mUnbound, findDomElement(BY_M_UNBOUND).getText()); assertEquals(mExpr, findDomElement(BY_M_EXPR).getText()); } }
40.266187
116
0.619618
9757abb71f8c4fce35ccd1a5e8a7cf708afc9925
2,202
package com.egglibrary.spring; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import com.egglibrary.spring.service.UsuarioService; @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired public UsuarioService usv; @Bean public BCryptPasswordEncoder passwordEncoder(){ BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder(); return bCryptPasswordEncoder; } @Autowired protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{ auth .userDetailsService(usv) .passwordEncoder(passwordEncoder()); } @Override protected void configure(HttpSecurity http) throws Exception { http .csrf().disable() .authorizeRequests() .antMatchers("/gestion/**","/adm/**").hasRole("USER_ADMIN") .antMatchers("/login*","/","/assets/**").permitAll() .and() .formLogin() .loginPage("/login") .loginProcessingUrl("/perform_login") .usernameParameter("username") .passwordParameter("password") .defaultSuccessUrl("/",true) .failureUrl("/login?error") .and() .logout() .logoutUrl("/logout") .logoutSuccessUrl("/login?logout") .permitAll(); } }
36.098361
107
0.637148
13b1c18c1546d1fd3be85976ae3c952d17d87fc6
1,996
/* * Copyright 2019 Red Hat, Inc. and/or its affiliates. * * 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.optaplanner.core.impl.score.stream.drools.common; import java.util.function.Supplier; import org.drools.model.Declaration; import org.drools.model.PatternDSL; public final class DroolsInferredMetadata<A> implements DroolsMetadata<DroolsLogicalTuple, A> { private final Declaration<DroolsLogicalTuple> variableDeclaration; private final Supplier<PatternDSL.PatternDef<DroolsLogicalTuple>> patternBuilder; private final int itemId; DroolsInferredMetadata(Declaration<DroolsLogicalTuple> variableDeclaration, Supplier<PatternDSL.PatternDef<DroolsLogicalTuple>> patternBuilder, int itemId) { this.variableDeclaration = variableDeclaration; this.patternBuilder = patternBuilder; this.itemId = itemId; } @Override public A extract(DroolsLogicalTuple container) { return container.getItem(itemId); } @Override public Declaration<DroolsLogicalTuple> getVariableDeclaration() { return variableDeclaration; } @Override public PatternDSL.PatternDef<DroolsLogicalTuple> buildPattern() { return patternBuilder.get(); } @Override public DroolsInferredMetadata<A> substitute(Supplier<PatternDSL.PatternDef<DroolsLogicalTuple>> patternBuilder) { return new DroolsInferredMetadata<>(variableDeclaration, patternBuilder, itemId); } }
34.413793
117
0.748497
52374e87f93e5dabf3225911ebce603095e3b9ee
5,010
package com.nbs.iais.ms.meta.referential.db.service.agent; import com.nbs.iais.ms.common.db.domains.interfaces.gsim.group.base.Agent; import com.nbs.iais.ms.common.db.service.tests.ServiceTest; import com.nbs.iais.ms.common.enums.AgentType; import com.nbs.iais.ms.common.enums.Language; import com.nbs.iais.ms.meta.referential.common.messageing.commands.agent.CreateAgentCommand; import com.nbs.iais.ms.meta.referential.common.messageing.commands.agent.DeleteAgentCommand; import com.nbs.iais.ms.meta.referential.common.messageing.commands.agent.UpdateAgentCommand; import com.nbs.iais.ms.meta.referential.db.domains.gsim.AgentEntity; import com.nbs.iais.ms.meta.referential.db.repositories.AgentRepository; import com.nbs.iais.ms.meta.referential.db.services.AgentCommandService; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import java.util.Optional; public class AgentCommandServiceTest extends ServiceTest { @Mock private AgentRepository agentRepository; @InjectMocks private AgentCommandService service; @Test public void createAgentTest() { //setup final String jwt = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJyb2xlIjoiQURNSU4iLCJpc3MiOiJpYWlzIiwibmFtZSI6IkZsb3JpYW4gTmlrYSIsImV4cCI6MTU4NjE4MzUwNSwiaWF0IjoxNTg2MTc5OTA1LCJ1c2VyIjoxfQ.xs5EaJie5DsmrUBRoUSHysKUoKXuuuKJ-8YPGIk1OqU"; final CreateAgentCommand command = CreateAgentCommand.create(jwt, "Name", "Description", AgentType.INDIVIDUAL, "[email protected]", 1L, 1L, Language.ENG); final AgentEntity agent = new AgentEntity(); agent.setId(2L); agent.setName(command.getName(), command.getLanguage()); agent.setDescription(command.getDescription(), command.getLanguage()); agent.setType(command.getType()); agent.setAccount(command.getAccount()); final AgentEntity parent = new AgentEntity(); parent.setId(1L); parent.setName("Parent", command.getLanguage()); parent.setType(AgentType.DIVISION); agent.setParent(parent); Mockito.when(agentRepository.save(Mockito.any(AgentEntity.class))).thenReturn(agent); Mockito.when(agentRepository.findById(Mockito.eq(1L))).thenReturn(Optional.of(parent)); //call service.createAgent(command); //verify Mockito.verify(agentRepository, Mockito.atLeast(2)).save(Mockito.any(AgentEntity.class)); Mockito.verify(agentRepository).findById(Mockito.eq(1L)); } @Test public void updateAgentTest() { //setup final String jwt = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJyb2xlIjoiQURNSU4iLCJpc3MiOiJpYWlzIiwibmFtZSI6IkZsb3JpYW4gTmlrYSIsImV4cCI6MTU4NjE4MzUwNSwiaWF0IjoxNTg2MTc5OTA1LCJ1c2VyIjoxfQ.xs5EaJie5DsmrUBRoUSHysKUoKXuuuKJ-8YPGIk1OqU"; final UpdateAgentCommand command = UpdateAgentCommand.create(jwt, 2L, "Name", "Description", AgentType.INDIVIDUAL, "[email protected]", 1L, 1L, null, null, null, Language.ENG); final AgentEntity agent = new AgentEntity(); agent.setId(2L); agent.setName(command.getName(), command.getLanguage()); agent.setDescription(command.getDescription(), command.getLanguage()); agent.setType(command.getType()); agent.setAccount(command.getAccount()); final AgentEntity parent = new AgentEntity(); parent.setId(1L); parent.setName("Parent", command.getLanguage()); parent.setType(AgentType.DIVISION); agent.setParent(parent); Mockito.when(agentRepository.save(Mockito.any(AgentEntity.class))).thenReturn(agent); Mockito.when(agentRepository.findById(Mockito.eq(1L))).thenReturn(Optional.of(parent)); Mockito.when(agentRepository.findById(Mockito.eq(2L))).thenReturn(Optional.of(agent)); //call service.updateAgent(command); //verify Mockito.verify(agentRepository).findById(Mockito.eq(1L)); Mockito.verify(agentRepository).findById(Mockito.eq(2L)); Mockito.verify(agentRepository).save(Mockito.any(AgentEntity.class)); } @Test public void deleteAgentTest() { //setup final String jwt = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJyb2xlIjoiQURNSU4iLCJpc3MiOiJpYWlzIiwibmFtZSI6IkZsb3JpYW4gTmlrYSIsImV4cCI6MTU4NjE4MzUwNSwiaWF0IjoxNTg2MTc5OTA1LCJ1c2VyIjoxfQ.xs5EaJie5DsmrUBRoUSHysKUoKXuuuKJ-8YPGIk1OqU"; final DeleteAgentCommand command = DeleteAgentCommand.create(jwt, 2L); final AgentEntity agent = new AgentEntity(); agent.setId(2L); Mockito.when(agentRepository.findById(Mockito.eq(2L))).thenReturn(Optional.of(agent)); Mockito.doNothing().when(agentRepository).delete(Mockito.any(AgentEntity.class)); //call service.deleteAgent(command); //verify Mockito.verify(agentRepository).findById(Mockito.eq(2L)); Mockito.verify(agentRepository).delete(Mockito.any(AgentEntity.class)); } }
42.820513
237
0.733733
873c262e87f77e0836f7bc601770b2ea5f282e5f
180
package com.jpeony.sunflower.server.service; /** * @author yihonglei */ public interface ServiceTest { /** * @author yihonglei */ void test(String content); }
15
44
0.638889
13d876033bade41989e981e93157bdfbe55218fa
31,819
/* * PropCylXY_Test.java * * Created on July 24, 2007, 10:53 PM * * $Id: PropCylXY_Test.java,v 1.1.1.1 2010/04/08 20:38:00 jeremy Exp $ */ package org.lcsim.recon.tracking.trfcylplane; import junit.framework.TestCase; import org.lcsim.recon.tracking.spacegeom.SpacePath; import org.lcsim.recon.tracking.spacegeom.SpacePoint; import org.lcsim.recon.tracking.trfbase.ETrack; import org.lcsim.recon.tracking.trfbase.PropDir; import org.lcsim.recon.tracking.trfbase.PropStat; import org.lcsim.recon.tracking.trfbase.Propagator; import org.lcsim.recon.tracking.trfbase.Surface; import org.lcsim.recon.tracking.trfbase.TrackDerivative; import org.lcsim.recon.tracking.trfbase.TrackError; import org.lcsim.recon.tracking.trfbase.TrackVector; import org.lcsim.recon.tracking.trfbase.VTrack; import org.lcsim.recon.tracking.trfcyl.SurfCylinder; import org.lcsim.recon.tracking.trfutil.Assert; import org.lcsim.recon.tracking.trfutil.TRFMath; import org.lcsim.recon.tracking.trfxyp.SurfXYPlane; /** * * @author Norman Graf */ public class PropCylXY_Test extends TestCase { private boolean debug; // Assign track parameter indices. private static final int IV = SurfXYPlane.IV; private static final int IZ = SurfXYPlane.IZ; private static final int IDVDU = SurfXYPlane.IDVDU; private static final int IDZDU = SurfXYPlane.IDZDU; private static final int IQP_XY = SurfXYPlane.IQP; private static final int IPHI = SurfCylinder.IPHI; private static final int IZ_CYL = SurfCylinder.IZ; private static final int IALF = SurfCylinder.IALF; private static final int ITLM = SurfCylinder.ITLM; private static final int IQPT = SurfCylinder.IQPT; //************************************************************************ // compare two tracks without errors private double compare(VTrack trv1,VTrack trv2) { Surface srf = trv2.surface(); Assert.assertTrue(trv1.surface().equals(srf)); double diff = srf.vecDiff(trv2.vector(),trv1.vector()).amax(); return diff; } //********************************************************************** // compare two tracks with errors private double[] compare(ETrack trv1,ETrack trv2 ) { double[] tmp = new double[2]; Surface srf = trv2.surface(); Assert.assertTrue(trv1.surface().equals(srf)); tmp[0] = srf.vecDiff(trv2.vector(),trv1.vector()).amax(); TrackError dfc = trv2.error().minus(trv1.error()); tmp[1] = dfc.amax(); return tmp; } /** Creates a new instance of PropCylXY_Test */ public void testPropCylXY() { String ok_prefix = "PropCylXY (I): "; String error_prefix = "PropCylXY test (E): "; if(debug) System.out.println( ok_prefix + "-------- Testing component PropCylXY. --------" ); if(debug) System.out.println( ok_prefix + "Test constructor." ); double BFIELD = 2.0; PropCylXY prop = new PropCylXY(BFIELD); if(debug) System.out.println( prop ); PropCylXY_Test tst = new PropCylXY_Test(); //******************************************************************** // Here we propagate some tracks both forward and backward and then // the same track forward and backward but using method // that we checked very thoroughly before. if(debug) System.out.println( ok_prefix + "Check against correct propagation." ); PropCylXY propcylxy = new PropCylXY(BFIELD/TRFMath.BFAC); double phi[] ={ Math.PI/5, Math.PI/6, Math.PI/6, 4/3*Math.PI, 5/3*Math.PI, 5/3*Math.PI }; double z[] ={ 1.5, -2.3, 0., 1.5, -1.5, 1.5 }; double alpha[] ={ 0.1, -0.1, 0., 0.2, -0.2, 0. }; double tlm[] ={ 2.3, -1.5, -2.3, 2.3, -2.3, 0. }; double qpt[] ={ 0.01, -0.01, 0.01, -0.01, -0.01, 0.01 }; double u2b[] ={ 6., 6., 6., 6., 6., 6. }; double phic2b[] ={ Math.PI/6., Math.PI/5., Math.PI/7., 5/3*Math.PI, 4/3*Math.PI, 7/4*Math.PI }; double u2[] ={ 15., 15., 15., 15., 15., 15. }; double phic2[] ={ Math.PI/6., Math.PI/5., Math.PI/7., 5/3*Math.PI, 4/3*Math.PI, 7/4*Math.PI }; double maxdiff = 1.e-10; double diff; int ntrk = 6; int i; for ( i=0; i<ntrk; ++i ) { if(debug) System.out.println( "********** Propagate track " + i + ". **********" ); PropStat pstat = new PropStat(); SurfCylinder scy1 = new SurfCylinder(10.); SurfXYPlane sxyp2 = new SurfXYPlane(u2[i],phic2[i]); SurfXYPlane sxyp2b= new SurfXYPlane(u2b[i],phic2b[i]); TrackVector vec1 = new TrackVector(); vec1.set(IPHI , phi[i]); // phi vec1.set(IZ_CYL , z[i]); // z vec1.set(IALF , alpha[i]); // alpha vec1.set(ITLM , tlm[i]); // tan(lambda) vec1.set(IQPT , qpt[i]); // q/pt VTrack trv1 = new VTrack(scy1.newPureSurface(),vec1); if(debug) System.out.println( "\n starting: " + trv1 ); VTrack trv2f = new VTrack(trv1); pstat = propcylxy.vecDirProp(trv2f,sxyp2,PropDir.FORWARD); Assert.assertTrue( pstat.forward() ); if(debug) System.out.println( "\n forward: " + trv2f ); VTrack trv2f_my = new VTrack(trv1); pstat = tst.vec_propcylxy(BFIELD,trv2f_my,sxyp2,PropDir.FORWARD); Assert.assertTrue( pstat.forward() ); if(debug) System.out.println( "\n forward my: " + trv2f_my ); diff = tst.compare(trv2f_my,trv2f); if(debug) System.out.println( "\n diff: " + diff ); Assert.assertTrue( diff < maxdiff ); VTrack trv2b = new VTrack(trv1); pstat = propcylxy.vecDirProp(trv2b,sxyp2b,PropDir.BACKWARD_MOVE); Assert.assertTrue( pstat.backward() ); if(debug) System.out.println( "\n backward: " + trv2b ); VTrack trv2b_my = new VTrack(trv1); pstat = tst.vec_propcylxy(BFIELD,trv2b_my,sxyp2b,PropDir.BACKWARD); Assert.assertTrue( pstat.backward() ); if(debug) System.out.println( "\n backward my: " + trv2b_my ); diff = tst.compare(trv2b_my,trv2b); if(debug) System.out.println( "\n diff: " + diff ); Assert.assertTrue( diff < maxdiff ); } //******************************************************************** // Repeat the above with errors. if(debug) System.out.println( ok_prefix + "Check against correct propagation with errors." ); double epp[] = { 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01 }; double epz[] = { 0.01, -0.01, 0.01, -0.01, 0.01, -0.01, 0.01 }; double ezz[] = { 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25 }; double epa[] = { 0.003, -0.003, 0.003, -0.003, 0.003, -0.003, 0.003 }; double eza[] = { 0.004, -0.004, 0.004, -0.004, 0.004, -0.004, 0.004 }; double eaa[] = { 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01 }; double epl[] = { 0.004, -0.004, 0.004, -0.004, 0.004, -0.004, 0.004 }; double eal[] = { 0.004, -0.004, 0.004, -0.004, 0.004, -0.004, 0.004 }; double ezl[] = { 0.004, -0.004, 0.004, -0.004, 0.004, -0.004, 0.004 }; double ell[] = { 0.02, 0.02, 0.02, 0.02, 0.02, 0.02, 0.02 }; double epc[] = { 0.004, -0.004, 0.004, -0.004, 0.004, -0.004, 0.004 }; double ezc[] = { 0.004, -0.004, 0.004, -0.004, 0.004, -0.004, 0.004 }; double eac[] = { 0.004, -0.004, 0.004, -0.004, 0.004, -0.004, 0.004 }; double elc[] = { 0.004, -0.004, 0.004, -0.004, 0.004, -0.004, 0.004 }; double ecc[] = { 0.01, 0.01, 0.01, 0.01, 0.01, 0.01, 0.01 }; maxdiff = 1.e-8; double ediff; ntrk = 6; for ( i=0; i<ntrk; ++i ) { if(debug) System.out.println( "********** Propagate track " + i + ". **********" ); PropStat pstat = new PropStat(); SurfCylinder scy1 = new SurfCylinder(10.); SurfXYPlane sxyp2 = new SurfXYPlane(u2[i],phic2[i]); SurfXYPlane sxyp2b = new SurfXYPlane(u2b[i],phic2b[i]); TrackVector vec1 = new TrackVector(); vec1.set(IPHI , phi[i]); // phi vec1.set(IZ_CYL , z[i]); // z vec1.set(IALF , alpha[i]); // alpha vec1.set(ITLM , tlm[i]); // tan(lambda) vec1.set(IQPT , qpt[i]); // q/pt TrackError err1 = new TrackError(); err1.set(IPHI,IPHI , epp[i]); err1.set(IPHI,IZ_CYL , epz[i]); err1.set(IZ_CYL,IZ_CYL , ezz[i]); err1.set(IPHI,IALF , epa[i]); err1.set(IZ_CYL,IALF , eza[i]); err1.set(IALF,IALF , eaa[i]); err1.set(IPHI,ITLM , epl[i]); err1.set(IZ_CYL,ITLM , ezl[i]); err1.set(IALF,ITLM , eal[i]); err1.set(ITLM,ITLM , ell[i]); err1.set(IPHI,IQPT , epc[i]); err1.set(IZ_CYL,IQPT , ezc[i]); err1.set(IALF,IQPT , eac[i]); err1.set(ITLM,IQPT , elc[i]); err1.set(IQPT,IQPT , ecc[i]); ETrack trv1 = new ETrack(scy1.newPureSurface(),vec1,err1); if(debug) System.out.println( "\n starting: " + trv1 ); ETrack trv2f = new ETrack(trv1); pstat = propcylxy.errDirProp(trv2f,sxyp2,PropDir.FORWARD); Assert.assertTrue( pstat.forward() ); if(debug) System.out.println( "\n forward: " + trv2f ); ETrack trv2f_my = new ETrack(trv1); TrackDerivative deriv = new TrackDerivative(); pstat = tst.vec_propcylxy(BFIELD,trv2f_my,sxyp2,PropDir.FORWARD,deriv); Assert.assertTrue( pstat.forward() ); TrackError err = trv2f_my.error(); trv2f_my.setError( err.Xform(deriv) ); if(debug) System.out.println( "\n forward my: " + trv2f_my ); double[] diffs = tst.compare(trv2f_my,trv2f); if(debug) System.out.println( "\n diff: " + diffs[0] + ' ' + "ediff: "+ diffs[1] ); Assert.assertTrue( diffs[0] < maxdiff ); Assert.assertTrue( diffs[1] < maxdiff ); ETrack trv2b = new ETrack(trv1); pstat = propcylxy.errDirProp(trv2b,sxyp2b,PropDir.BACKWARD); Assert.assertTrue( pstat.backward() ); if(debug) System.out.println( "\n backward: " + trv2b ); ETrack trv2b_my = new ETrack(trv1); pstat = tst.vec_propcylxy(BFIELD,trv2b_my,sxyp2b,PropDir.BACKWARD,deriv); Assert.assertTrue( pstat.backward() ); err = trv2b_my.error(); trv2b_my.setError( err.Xform(deriv) ); if(debug) System.out.println( "\n backward my: " + trv2b_my ); diffs = tst.compare(trv2b_my,trv2b); if(debug) System.out.println( "\n diff: " + diffs[0] + ' ' + "ediff: "+ diffs[1] ); Assert.assertTrue( diffs[0] < maxdiff ); Assert.assertTrue( diffs[1] < maxdiff ); } //******************************************************************** if(debug) System.out.println( ok_prefix + "Test cloning." ); Assert.assertTrue( prop.newPropagator() != null ); //******************************************************************** if(debug) System.out.println( ok_prefix + "Test the field." ); Assert.assertTrue( prop.bField() == 2.0 ); //******************************************************************** if(debug) System.out.println( ok_prefix + "Test Zero Field Propagation." ); { PropCylXY prop0 = new PropCylXY(0.0); if(debug) System.out.println( prop0 ); Assert.assertTrue( prop0.bField() == 0. ); double u = 10.; double phi2 = 0.1; Surface srf = new SurfCylinder(13.0); VTrack trv0 = new VTrack(srf); TrackVector vec = new TrackVector(); vec.set(SurfCylinder.IPHI, phi2+0.1); vec.set(SurfCylinder.IZ, 10.); vec.set(SurfCylinder.IALF, 0.1); vec.set(SurfCylinder.ITLM, 2.); vec.set(SurfCylinder.IQPT, 0.); trv0.setVector(vec); trv0.setForward(); Surface srf_to = new SurfXYPlane(u,phi2); VTrack trv = new VTrack(trv0); VTrack trv_der = new VTrack(trv); PropStat pstat = prop0.vecDirProp(trv,srf_to,PropDir.NEAREST); if(debug) System.out.println("trv= \n"+trv+'\n'); Assert.assertTrue( pstat.success() ); Assert.assertTrue( pstat.backward() ); Assert.assertTrue(trv.surface().pureEqual(srf_to)); check_zero_propagation(trv0,trv,pstat); check_derivatives(prop0,trv_der,srf_to); } //******************************************************************** if(debug) System.out.println( ok_prefix + "------------- All tests passed. -------------" ); //******************************************************************** } // Very well tested Cyl-XY propagator. Each new one can be tested against it PropStat vec_propcylxy( double B, VTrack trv, Surface srf, PropDir dir ) { TrackDerivative deriv = null; return vec_propcylxy(B, trv, srf, dir, deriv); } PropStat vec_propcylxy( double B, VTrack trv, Surface srf, PropDir dir, TrackDerivative deriv ) { // construct return status PropStat pstat = new PropStat(); // fetch the originating surface and vector Surface srf1 = trv.surface(); // TrackVector vec1 = trv.vector(); // Check origin is a Cylinder. Assert.assertTrue( srf1.pureType().equals(SurfCylinder.staticType()) ); if (! srf1.pureType( ).equals(SurfCylinder.staticType()) ) return pstat; SurfCylinder scy1 = ( SurfCylinder ) srf1; // Fetch the R of the cylinder and the starting track vector. int ir = SurfCylinder.RADIUS; double Rcyl = scy1.parameter(ir); TrackVector vec = trv.vector(); double c1 = vec.get(IPHI); // phi double c2 = vec.get(IZ); // z double c3 = vec.get(IALF); // alpha double c4 = vec.get(ITLM); // tan(lambda) double c5 = vec.get(IQPT); // q/pt // Check destination is a XYPlane. Assert.assertTrue( srf.pureType().equals(SurfXYPlane.staticType()) ); if ( !srf.pureType( ).equals(SurfXYPlane.staticType()) ) return pstat; SurfXYPlane sxyp2 = ( SurfXYPlane ) srf; // Fetch the u and phi of the plane. int iphi = SurfXYPlane.NORMPHI; int idist = SurfXYPlane.DISTNORM; double phi_n = sxyp2.parameter(iphi); double u_n = sxyp2.parameter(idist); // rotate coordinate system on phi_n c1 -= phi_n; if(c1 < 0.) c1 += TRFMath.TWOPI; double cos_c1 = Math.cos(c1); double u = Rcyl*cos_c1; double sin_c1 = Math.sin(c1); double cos_dir = Math.cos(c1+c3); double sin_dir = Math.sin(c1+c3); double c4_hat2 = 1+c4*c4; double c4_hat = Math.sqrt(c4_hat2); // check if du == 0 ( that is track moves parallel to the destination plane ) // du = pt*cos_dir if(cos_dir/c5 == 0.) return pstat; double tan_dir = sin_dir/cos_dir; double b1 = Rcyl*sin_c1; double b2 = c2; double b3 = tan_dir; double b4 = c4/cos_dir; double b5 = c5/c4_hat; int sign_du = 0; if(cos_dir > 0) sign_du = 1; if(cos_dir < 0) sign_du = -1; double b3_hat = Math.sqrt(1 + b3*b3); double b34_hat = Math.sqrt(1 + b3*b3 + b4*b4); double b3_hat2 = b3_hat*b3_hat; double b34_hat2 = b34_hat*b34_hat; double r = 1/(b5*B)*b3_hat/b34_hat; double cosphi = -b3*sign_du/b3_hat; double sinphi = sign_du/b3_hat; double rsinphi = 1./(b5*B)*sign_du/b34_hat; double rcosphi = -b3/(b5*B)*sign_du/b34_hat; double du = u_n - u; double norm = du/r - cosphi; // cyl-xy propagation failed : noway to the new plane if(Math.abs(norm)>1.) return pstat; double cat = Math.sqrt(1.-norm*norm); int sign_dphi = 0; if (dir.equals(PropDir.NEAREST)) { if(debug) System.out.println("PropCylXY._vec_prop: Propagation in NEAREST direction is undefined"); System.exit(1); } else if (dir.equals(PropDir.FORWARD)) { if(b5>0.) sign_dphi = 1; if(b5<0.) sign_dphi = -1; } else if (dir.equals(PropDir.BACKWARD)) { if(b5>0.) sign_dphi = -1; if(b5<0.) sign_dphi = 1; } else { if(debug) System.out.println("PropCylXY._vec_prop: Unknown direction." ); System.exit(1); } int sign_cat = 0; if(du*sign_dphi*b5>0.) sign_cat = 1; if(du*sign_dphi*b5<0.) sign_cat = -1; if(du == 0.) { if(sinphi >=0. ) sign_cat = 1; if(sinphi < 0. ) sign_cat = -1; } double sin_dphi = norm*sinphi + cat*cosphi*sign_cat; double cos_dphi = -norm*cosphi + cat*sinphi*sign_cat; int sign_sindphi = 0; if(sin_dphi> 0.) sign_sindphi = 1; if(sin_dphi< 0.) sign_sindphi = -1; if(sin_dphi == 0.) sign_sindphi = sign_dphi; double dphi = Math.PI*(sign_dphi - sign_sindphi) + sign_sindphi*Math.acos(cos_dphi); // check if dun == 0 ( that is track moves parallel to the destination plane) double du_n_du = cos_dphi - b3*sin_dphi; if(du_n_du==0.) return pstat; double a_hat_dphi = 1./du_n_du; double a_hat_dphi2 = a_hat_dphi*a_hat_dphi; double c_hat_dphi = sin_dphi + b3*cos_dphi ; double b1_n = b1 + rsinphi*(1-cos_dphi) - rcosphi*sin_dphi; double b2_n = b2 + b4/(b5*B)*sign_du/b34_hat*dphi; double b3_n = c_hat_dphi*a_hat_dphi; double b4_n = b4*a_hat_dphi; double b5_n = b5; int sign_dun = 0; if(du_n_du*sign_du > 0) sign_dun = 1; if(du_n_du*sign_du < 0) sign_dun = -1; vec.set(IV , b1_n); vec.set(IZ , b2_n); vec.set(IDVDU , b3_n); vec.set(IDZDU , b4_n); vec.set(IQP_XY , b5_n); // Set the return status. if (dir.equals(PropDir.FORWARD)) { pstat.setForward(); } else if (dir.equals(PropDir.BACKWARD)) { pstat.setBackward(); } // Update trv trv.setSurface(srf.newPureSurface()); trv.setVector(vec); // set new direction of the track if(sign_dun == 1) trv.setForward(); if(sign_dun == -1) trv.setBackward(); // exit now if user did not ask for error matrix. if (deriv == null ) return pstat; // du_dc double du_dc1 = -Rcyl*sin_c1; // db1_dc double db1_dc1 = Rcyl*cos_c1; // db2_dc double db2_dc2 = 1.; // db3_dc double db3_dc1 = 1./(cos_dir*cos_dir); double db3_dc3 = 1./(cos_dir*cos_dir); // db4_dc double db4_dc1 = b4*tan_dir; double db4_dc3 = b4*tan_dir; double db4_dc4 = 1/cos_dir; // db5_dc double db5_dc4 = -c4*c5/(c4_hat*c4_hat2); double db5_dc5 = 1./c4_hat; // dr_db double dr_db3 = r*b3*b4*b4/(b3_hat2*b34_hat2); double dr_db4 = -r*b4/b34_hat2; double dr_db5 = -r/b5; // dcosphi_db double dcosphi_db3 = - sign_du/b3_hat - cosphi*b3/b3_hat2; // dsinphi_db double dsinphi_db3 = - sinphi*b3/b3_hat2; // dcat_db double dcat_db3 = norm/cat*(du/(r*r)*dr_db3 + dcosphi_db3 ); double dcat_db4 = norm/cat* du/(r*r)*dr_db4; double dcat_db5 = norm/cat* du/(r*r)*dr_db5; double dcat_du = norm/(cat*r); // dnorm_db double dnorm_db3 = - du/(r*r)*dr_db3 - dcosphi_db3; double dnorm_db4 = - du/(r*r)*dr_db4; double dnorm_db5 = - du/(r*r)*dr_db5; double dnorm_du = - 1./r; // dcos_dphi_db double dcos_dphi_db3 = - cosphi*dnorm_db3 - norm*dcosphi_db3 + sign_cat*(sinphi*dcat_db3 + cat*dsinphi_db3); double dcos_dphi_db4 = - cosphi*dnorm_db4 + sign_cat*sinphi*dcat_db4; double dcos_dphi_db5 = - cosphi*dnorm_db5 + sign_cat*sinphi*dcat_db5; double dcos_dphi_du = - cosphi*dnorm_du + sign_cat*sinphi*dcat_du; // dsin_dphi_db double dsin_dphi_db3 = sinphi*dnorm_db3 + norm*dsinphi_db3 + sign_cat*(cosphi*dcat_db3 + cat*dcosphi_db3); double dsin_dphi_db4 = sinphi*dnorm_db4 + sign_cat*cosphi*dcat_db4; double dsin_dphi_db5 = sinphi*dnorm_db5 + sign_cat*cosphi*dcat_db5; double dsin_dphi_du = sinphi*dnorm_du + sign_cat*cosphi*dcat_du; // ddphi_db double ddphi_db3; double ddphi_db4; double ddphi_db5; double ddphi_du; if(Math.abs(sin_dphi)>0.5) { ddphi_db3 = - dcos_dphi_db3/sin_dphi; ddphi_db4 = - dcos_dphi_db4/sin_dphi; ddphi_db5 = - dcos_dphi_db5/sin_dphi; ddphi_du = - dcos_dphi_du /sin_dphi; } else { ddphi_db3 = dsin_dphi_db3/cos_dphi; ddphi_db4 = dsin_dphi_db4/cos_dphi; ddphi_db5 = dsin_dphi_db5/cos_dphi; ddphi_du = dsin_dphi_du /cos_dphi; } // da_hat_dphi_db double da_hat_dphi_db3 = - a_hat_dphi2* (dcos_dphi_db3 - sin_dphi - b3*dsin_dphi_db3); double da_hat_dphi_db4 = - a_hat_dphi2*(dcos_dphi_db4 - b3*dsin_dphi_db4); double da_hat_dphi_db5 = - a_hat_dphi2*(dcos_dphi_db5 - b3*dsin_dphi_db5); double da_hat_dphi_du = - a_hat_dphi2*(dcos_dphi_du - b3*dsin_dphi_du ); // dc_hat_dphi_db double dc_hat_dphi_db3 = b3*dcos_dphi_db3 + dsin_dphi_db3 + cos_dphi; double dc_hat_dphi_db4 = b3*dcos_dphi_db4 + dsin_dphi_db4; double dc_hat_dphi_db5 = b3*dcos_dphi_db5 + dsin_dphi_db5; double dc_hat_dphi_du = b3*dcos_dphi_du + dsin_dphi_du ; // db1_n_db double db1_n_db1 = 1; double db1_n_db3 = (dr_db3*sinphi+r*dsinphi_db3)*(1-cos_dphi) - rsinphi*dcos_dphi_db3 - dr_db3*cosphi*sin_dphi - r*dcosphi_db3*sin_dphi - rcosphi*dsin_dphi_db3; double db1_n_db4 = dr_db4*sinphi*(1-cos_dphi) - rsinphi*dcos_dphi_db4 - dr_db4*cosphi*sin_dphi - rcosphi*dsin_dphi_db4; double db1_n_db5 = dr_db5*sinphi*(1-cos_dphi) - rsinphi*dcos_dphi_db5 - dr_db5*cosphi*sin_dphi - rcosphi*dsin_dphi_db5; double db1_n_du = - rsinphi*dcos_dphi_du - rcosphi*dsin_dphi_du; // db2_n_db double db2_n_db2 = 1.; double db2_n_db3 = 1./(b5*B)*b4*sign_du/b34_hat* ( - dphi*b3/b34_hat2 + ddphi_db3); double db2_n_db4 = 1./(b5*B)*sign_du/b34_hat* ( - dphi*b4*b4/b34_hat2 + b4*ddphi_db4 + dphi ); double db2_n_db5 = 1./(b5*B)*b4*sign_du/b34_hat*( ddphi_db5 - dphi/b5); double db2_n_du = 1./(b5*B)*b4*sign_du/b34_hat*ddphi_du; // db3_n_db double db3_n_db3 = a_hat_dphi*dc_hat_dphi_db3 + da_hat_dphi_db3*c_hat_dphi; double db3_n_db4 = a_hat_dphi*dc_hat_dphi_db4 + da_hat_dphi_db4*c_hat_dphi; double db3_n_db5 = a_hat_dphi*dc_hat_dphi_db5 + da_hat_dphi_db5*c_hat_dphi; double db3_n_du = a_hat_dphi*dc_hat_dphi_du + da_hat_dphi_du *c_hat_dphi; // db4_n_db double db4_n_db3 = b4*da_hat_dphi_db3; double db4_n_db4 = b4*da_hat_dphi_db4 + a_hat_dphi; double db4_n_db5 = b4*da_hat_dphi_db5; double db4_n_du = b4*da_hat_dphi_du; // db5_n_db // double db5_n_db5 = 1.; // db1_n_dc double db1_n_dc1 = db1_n_du * du_dc1 + db1_n_db1*db1_dc1 + db1_n_db3*db3_dc1 + db1_n_db4*db4_dc1; double db1_n_dc2 = 0.; double db1_n_dc3 = db1_n_db3*db3_dc3 + db1_n_db4*db4_dc3; double db1_n_dc4 = db1_n_db4*db4_dc4 + db1_n_db5*db5_dc4; double db1_n_dc5 = db1_n_db5*db5_dc5; // db2_n_dc double db2_n_dc1 = db2_n_du * du_dc1 + db2_n_db3*db3_dc1 + db2_n_db4*db4_dc1; double db2_n_dc2 = db2_n_db2 * db2_dc2; double db2_n_dc3 = db2_n_db3*db3_dc3 + db2_n_db4*db4_dc3; double db2_n_dc4 = db2_n_db4*db4_dc4 + db2_n_db5*db5_dc4; double db2_n_dc5 = db2_n_db5*db5_dc5; // db3_n_dc double db3_n_dc1 = db3_n_du * du_dc1 + db3_n_db3*db3_dc1 + db3_n_db4*db4_dc1; double db3_n_dc2 = 0.; double db3_n_dc3 = db3_n_db3*db3_dc3 + db3_n_db4*db4_dc3; double db3_n_dc4 = db3_n_db4*db4_dc4 + db3_n_db5*db5_dc4; double db3_n_dc5 = db3_n_db5*db5_dc5; // db4_n_dc double db4_n_dc1 = db4_n_du * du_dc1 + db4_n_db3*db3_dc1 + db4_n_db4*db4_dc1; double db4_n_dc2 = 0.; double db4_n_dc3 = db4_n_db3*db3_dc3 + db4_n_db4*db4_dc3; double db4_n_dc4 = db4_n_db4*db4_dc4 + db4_n_db5*db5_dc4; double db4_n_dc5 = db4_n_db5*db5_dc5; // db5_n_dc double db5_n_dc1 = 0.; double db5_n_dc2 = 0.; double db5_n_dc3 = 0.; double db5_n_dc4 = db5_dc4; double db5_n_dc5 = db5_dc5; deriv.set(IV,IPHI , db1_n_dc1); deriv.set(IV,IZ_CYL , db1_n_dc2); deriv.set(IV,IALF , db1_n_dc3); deriv.set(IV,ITLM , db1_n_dc4); deriv.set(IV,IQPT , db1_n_dc5); deriv.set(IZ,IPHI , db2_n_dc1); deriv.set(IZ,IZ_CYL , db2_n_dc2); deriv.set(IZ,IALF , db2_n_dc3); deriv.set(IZ,ITLM , db2_n_dc4); deriv.set(IZ,IQPT , db2_n_dc5); deriv.set(IDVDU,IPHI , db3_n_dc1); deriv.set(IDVDU,IZ_CYL , db3_n_dc2); deriv.set(IDVDU,IALF , db3_n_dc3); deriv.set(IDVDU,ITLM , db3_n_dc4); deriv.set(IDVDU,IQPT , db3_n_dc5); deriv.set(IDZDU,IPHI , db4_n_dc1); deriv.set(IDZDU,IZ_CYL , db4_n_dc2); deriv.set(IDZDU,IALF , db4_n_dc3); deriv.set(IDZDU,ITLM , db4_n_dc4); deriv.set(IDZDU,IQPT , db4_n_dc5); deriv.set(IQP_XY,IPHI , db5_n_dc1); deriv.set(IQP_XY,IZ_CYL , db5_n_dc2); deriv.set(IQP_XY,IALF , db5_n_dc3); deriv.set(IQP_XY,ITLM , db5_n_dc4); deriv.set(IQP_XY,IQPT , db5_n_dc5); return pstat; } static void check_zero_propagation( VTrack trv0, VTrack trv, PropStat pstat) { SpacePoint sp = trv.spacePoint(); SpacePoint sp0 = trv0.spacePoint(); SpacePath sv = trv.spacePath(); SpacePath sv0 = trv0.spacePath(); Assert.assertTrue( Math.abs(sv0.dx() - sv.dx())<1e-7 ); Assert.assertTrue( Math.abs(sv0.dy() - sv.dy())<1e-7 ); Assert.assertTrue( Math.abs(sv0.dz() - sv.dz())<1e-7 ); double x0 = sp0.x(); double y0 = sp0.y(); double z0 = sp0.z(); double x1 = sp.x(); double y1 = sp.y(); double z1 = sp.z(); double dx = sv.dx(); double dy = sv.dy(); double dz = sv.dz(); double prod = dx*(x1-x0)+dy*(y1-y0)+dz*(z1-z0); double moda = Math.sqrt((x1-x0)*(x1-x0)+(y1-y0)*(y1-y0) + (z1-z0)*(z1-z0)); double modb = Math.sqrt(dx*dx+dy*dy+dz*dz); double st = pstat.pathDistance(); // Assert.assertTrue( Math.abs(prod-st) < 1.e-7 ); // Assert.assertTrue( Math.abs(Math.abs(prod) - moda*modb) < 1.e-7 ); } static void check_derivatives( Propagator prop, VTrack trv0, Surface srf) { for(int i=0;i<4;++i) for(int j=0;j<4;++j) check_derivative(prop,trv0,srf,i,j); } static void check_derivative( Propagator prop, VTrack trv0, Surface srf,int i,int j) { double dx = 1.e-3; VTrack trv = new VTrack(trv0); TrackVector vec = trv.vector(); boolean forward = trv0.isForward(); VTrack trv_0 = new VTrack(trv0); TrackDerivative der = new TrackDerivative(); PropStat pstat = prop.vecProp(trv_0,srf,der); Assert.assertTrue(pstat.success()); TrackVector tmp = new TrackVector(vec); tmp.set(j, tmp.get(j)+dx); trv.setVector(tmp); if(forward) trv.setForward(); else trv.setBackward(); VTrack trv_pl = new VTrack(trv); pstat = prop.vecProp(trv_pl,srf); Assert.assertTrue(pstat.success()); TrackVector vecpl = trv_pl.vector(); tmp = new TrackVector(vec); tmp.set(j,tmp.get(j)-dx); trv.setVector(tmp); if(forward) trv.setForward(); else trv.setBackward(); VTrack trv_mn = new VTrack(trv); pstat = prop.vecProp(trv_mn,srf); Assert.assertTrue(pstat.success()); TrackVector vecmn = trv_mn.vector(); double dy = (vecpl.get(i)-vecmn.get(i))/2.; double dydx = dy/dx; double didj = der.get(i,j); if( Math.abs(didj) > 1e-10 ) Assert.assertTrue( Math.abs((dydx - didj)/didj) < 1e-4 ); else Assert.assertTrue( Math.abs(dydx) < 1e-4 ); } }
38.198079
111
0.519941
3d92a9840832c0115e150368b020cc88db367bc7
8,460
package com.example.littlethoughts; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.Menu; import android.view.MenuItem; import android.view.inputmethod.InputMethodManager; import android.widget.Toast; import androidx.appcompat.app.ActionBar; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.core.view.GravityCompat; import androidx.drawerlayout.widget.DrawerLayout; import androidx.fragment.app.Fragment; import androidx.viewpager.widget.ViewPager; import com.example.littlethoughts.adapter.FragmentAdapter; import com.example.littlethoughts.fragement.MenuFragment; import com.example.littlethoughts.fragement.ThoughtsFragment; import com.example.littlethoughts.fragement.TodoFragment; import com.example.littlethoughts.service.ReminderService; import com.example.littlethoughts.utils.Logger; import com.example.littlethoughts.widget.AddEditDialog; import com.example.littlethoughts.widget.EnsureDialog; import com.google.android.material.appbar.CollapsingToolbarLayout; import com.google.android.material.floatingactionbutton.FloatingActionButton; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { private ViewPager viewPager; private TodoFragment todoFragment; private ThoughtsFragment thoughtsFragment; public DrawerLayout drawerLayout; private FloatingActionButton floatingActionButton; public InputMethodManager inputMethodManager; CollapsingToolbarLayout toolbarLayout; public static boolean isInputing = false; private int groupId = 0; private int childId = 0; private boolean isFirstTime = true; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); init(); floatingActionButton.setOnClickListener(v -> { if (groupId != -1 && childId != -1) { if (groupId == 0) { isInputing = true; todoFragment.addTodoItem(); floatingActionButton.hide(); } else if (groupId == 1) { thoughtsFragment.addLittleThought(); floatingActionButton.hide(); } else { drawerLayout.openDrawer(GravityCompat.START); Toast.makeText(this, R.string.introduction, Toast.LENGTH_SHORT).show(); } } else { drawerLayout.openDrawer(GravityCompat.START); Toast.makeText(this, R.string.introduction, Toast.LENGTH_SHORT).show(); } }); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); actionBar.setHomeAsUpIndicator(R.drawable.menu); } SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); groupId = sharedPreferences.getInt("group_id", -1); childId = sharedPreferences.getInt("child_id", -1); if (groupId != -1 || childId != -1) { changeList(groupId, childId); } else { changeList(0, 0); } } private void init() { drawerLayout = findViewById(R.id.drawer_layout); viewPager = findViewById(R.id.view_pager); floatingActionButton = findViewById(R.id.floating_button); toolbarLayout = findViewById(R.id.collapsing); todoFragment = new TodoFragment(); thoughtsFragment = new ThoughtsFragment(); List<Fragment> fragmentList = new ArrayList<>(); fragmentList.add(todoFragment); fragmentList.add(thoughtsFragment); viewPager.setAdapter(new FragmentAdapter(getSupportFragmentManager(), fragmentList)); inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE); } @Override protected void onResume() { super.onResume(); startService(new Intent(this, ReminderService.class)); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: drawerLayout.openDrawer(GravityCompat.START); break; case R.id.edit_list: if (groupId != -1) { new AddEditDialog(MainActivity.this, R.string.edit_list_name, "", R.string.sure_edit, null, str -> { MenuFragment.editChild(groupId, childId, str); toolbarLayout.setTitle(str); if (groupId == 0) { todoFragment.refreshListName(str); } else { thoughtsFragment.refreshListName(str); } }); } else { Toast.makeText(this, R.string.delete_without_select, Toast.LENGTH_SHORT).show(); } break; case R.id.remove_list: if (groupId != -1) { new EnsureDialog(MainActivity.this, R.string.delete_make_sure, R.string.delete_message, R.string.delete, () -> { if (groupId == 0) { todoFragment.removeList(); } else { thoughtsFragment.removeList(); } MenuFragment.removeChild(groupId, childId); toolbarLayout.setTitle("Little Thoughts"); Toast.makeText(MainActivity.this, R.string.delete, Toast.LENGTH_SHORT).show(); groupId = -1; childId = -1; }); } else { Toast.makeText(this, R.string.delete_without_select, Toast.LENGTH_SHORT).show(); } break; case R.id.exit: finish(); break; default: break; } return true; } @Override protected void onDestroy() { super.onDestroy(); SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit(); editor.putInt("group_id", groupId); Logger.d("group_id" + groupId); editor.putInt("child_id", childId); Logger.d("child_id" + childId); editor.apply(); } public void changeList(int groupId, int childPosition) { if (groupId == 0) { toolbarLayout.setTitle(todoFragment.getListName(childPosition)); if (isFirstTime) { isFirstTime = false; } else { if (this.groupId == groupId) todoFragment.refreshList(childPosition); } } else { toolbarLayout.setTitle(thoughtsFragment.getListName(childPosition)); if (isFirstTime) { isFirstTime = false; } else { if (this.groupId == groupId) thoughtsFragment.refreshList(childPosition); } } viewPager.setCurrentItem(groupId, false); this.groupId = groupId; this.childId = childPosition; } @Override public void onBackPressed() { if (isInputing) { todoFragment.hiddenAddLayout(); floatingActionButton.show(); isInputing = false; } else { super.onBackPressed(); } } public InputMethodManager getInputMethodManager() { return inputMethodManager; } public FloatingActionButton getFloatingActionButton() { return floatingActionButton; } }
36.153846
110
0.584515
cce893ea5e61220290bb8aa24a5ce0772ace3f92
310
package com.Feelfree2code.STA.subStructure; import com.Feelfree2code.STA.model.domain.CustomerDTO; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface ICustomerRepository extends JpaRepository<CustomerDTO, Integer> { }
31
82
0.854839
b6a8d1803fad9d31ca392713308a0f4d37147b2d
1,318
package org.apache.spark.deploy; class ApplicationDescription implements scala.Product, scala.Serializable { public java.lang.String name () { throw new RuntimeException(); } public scala.Option<java.lang.Object> maxCores () { throw new RuntimeException(); } public int memoryPerExecutorMB () { throw new RuntimeException(); } public org.apache.spark.deploy.Command command () { throw new RuntimeException(); } public java.lang.String appUiUrl () { throw new RuntimeException(); } public scala.Option<java.net.URI> eventLogDir () { throw new RuntimeException(); } public scala.Option<java.lang.String> eventLogCodec () { throw new RuntimeException(); } public scala.Option<java.lang.Object> coresPerExecutor () { throw new RuntimeException(); } public java.lang.String user () { throw new RuntimeException(); } // not preceding public ApplicationDescription (java.lang.String name, scala.Option<java.lang.Object> maxCores, int memoryPerExecutorMB, org.apache.spark.deploy.Command command, java.lang.String appUiUrl, scala.Option<java.net.URI> eventLogDir, scala.Option<java.lang.String> eventLogCodec, scala.Option<java.lang.Object> coresPerExecutor, java.lang.String user) { throw new RuntimeException(); } public java.lang.String toString () { throw new RuntimeException(); } }
82.375
383
0.754932
7611b489bb7970d067e0192cc565ea2af190a849
34,637
/* * 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.commons.collections4.map; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; import java.lang.ref.SoftReference; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import org.apache.commons.collections4.MapIterator; import org.apache.commons.collections4.keyvalue.DefaultMapEntry; /** * An abstract implementation of a hash-based map that allows the entries to * be removed by the garbage collector. * <p> * This class implements all the features necessary for a subclass reference * hash-based map. Key-value entries are stored in instances of the * <code>ReferenceEntry</code> class which can be overridden and replaced. * The iterators can similarly be replaced, without the need to replace the KeySet, * EntrySet and Values view classes. * <p> * Overridable methods are provided to change the default hashing behaviour, and * to change how entries are added to and removed from the map. Hopefully, all you * need for unusual subclasses is here. * <p> * When you construct an <code>AbstractReferenceMap</code>, you can specify what * kind of references are used to store the map's keys and values. * If non-hard references are used, then the garbage collector can remove * mappings if a key or value becomes unreachable, or if the JVM's memory is * running low. For information on how the different reference types behave, * see {@link Reference}. * <p> * Different types of references can be specified for keys and values. * The keys can be configured to be weak but the values hard, * in which case this class will behave like a * <a href="http://java.sun.com/j2se/1.4/docs/api/java/util/WeakHashMap.html"> * <code>WeakHashMap</code></a>. However, you can also specify hard keys and * weak values, or any other combination. The default constructor uses * hard keys and soft values, providing a memory-sensitive cache. * <p> * This {@link Map} implementation does <i>not</i> allow null elements. * Attempting to add a null key or value to the map will raise a * <code>NullPointerException</code>. * <p> * All the available iterators can be reset back to the start by casting to * <code>ResettableIterator</code> and calling <code>reset()</code>. * <p> * This implementation is not synchronized. * You can use {@link java.util.Collections#synchronizedMap} to * provide synchronized access to a <code>ReferenceMap</code>. * * @see java.lang.ref.Reference * @since 3.1 (extracted from ReferenceMap in 3.0) * @version $Id$ */ public abstract class AbstractReferenceMap<K, V> extends AbstractHashedMap<K, V> { /** * Reference type enum. */ public static enum ReferenceStrength { HARD(0), SOFT(1), WEAK(2); /** value */ public final int value; /** * Resolve enum from int. * @param value the int value * @return ReferenceType * @throws IllegalArgumentException if the specified value is invalid. */ public static ReferenceStrength resolve(final int value) { switch (value) { case 0: return HARD; case 1: return SOFT; case 2: return WEAK; default: throw new IllegalArgumentException(); } } private ReferenceStrength(final int value) { this.value = value; } } /** * The reference type for keys. */ private ReferenceStrength keyType; /** * The reference type for values. */ private ReferenceStrength valueType; /** * Should the value be automatically purged when the associated key has been collected? */ private boolean purgeValues; /** * ReferenceQueue used to eliminate stale mappings. * See purge. */ private transient ReferenceQueue<Object> queue; //----------------------------------------------------------------------- /** * Constructor used during deserialization. */ protected AbstractReferenceMap() { super(); } /** * Constructs a new empty map with the specified reference types, * load factor and initial capacity. * * @param keyType the type of reference to use for keys; * must be {@link ReferenceStrength#HARD HARD}, * {@link ReferenceStrength#SOFT SOFT}, * {@link ReferenceStrength#WEAK WEAK} * @param valueType the type of reference to use for values; * must be {@link ReferenceStrength#HARD}, * {@link ReferenceStrength#SOFT SOFT}, * {@link ReferenceStrength#WEAK WEAK} * @param capacity the initial capacity for the map * @param loadFactor the load factor for the map * @param purgeValues should the value be automatically purged when the * key is garbage collected */ protected AbstractReferenceMap( final ReferenceStrength keyType, final ReferenceStrength valueType, final int capacity, final float loadFactor, final boolean purgeValues) { super(capacity, loadFactor); this.keyType = keyType; this.valueType = valueType; this.purgeValues = purgeValues; } /** * Initialise this subclass during construction, cloning or deserialization. */ @Override protected void init() { queue = new ReferenceQueue<Object>(); } //----------------------------------------------------------------------- /** * Gets the size of the map. * * @return the size */ @Override public int size() { purgeBeforeRead(); return super.size(); } /** * Checks whether the map is currently empty. * * @return true if the map is currently size zero */ @Override public boolean isEmpty() { purgeBeforeRead(); return super.isEmpty(); } /** * Checks whether the map contains the specified key. * * @param key the key to search for * @return true if the map contains the key */ @Override public boolean containsKey(final Object key) { purgeBeforeRead(); final Entry<K, V> entry = getEntry(key); if (entry == null) { return false; } return entry.getValue() != null; } /** * Checks whether the map contains the specified value. * * @param value the value to search for * @return true if the map contains the value */ @Override public boolean containsValue(final Object value) { purgeBeforeRead(); if (value == null) { return false; } return super.containsValue(value); } /** * Gets the value mapped to the key specified. * * @param key the key * @return the mapped value, null if no match */ @Override public V get(final Object key) { purgeBeforeRead(); final Entry<K, V> entry = getEntry(key); if (entry == null) { return null; } return entry.getValue(); } /** * Puts a key-value mapping into this map. * Neither the key nor the value may be null. * * @param key the key to add, must not be null * @param value the value to add, must not be null * @return the value previously mapped to this key, null if none * @throws NullPointerException if either the key or value is null */ @Override public V put(final K key, final V value) { if (key == null) { throw new NullPointerException("null keys not allowed"); } if (value == null) { throw new NullPointerException("null values not allowed"); } purgeBeforeWrite(); return super.put(key, value); } /** * Removes the specified mapping from this map. * * @param key the mapping to remove * @return the value mapped to the removed key, null if key not in map */ @Override public V remove(final Object key) { if (key == null) { return null; } purgeBeforeWrite(); return super.remove(key); } /** * Clears this map. */ @Override public void clear() { super.clear(); while (queue.poll() != null) {} // drain the queue } //----------------------------------------------------------------------- /** * Gets a MapIterator over the reference map. * The iterator only returns valid key/value pairs. * * @return a map iterator */ @Override public MapIterator<K, V> mapIterator() { return new ReferenceMapIterator<K, V>(this); } /** * Returns a set view of this map's entries. * An iterator returned entry is valid until <code>next()</code> is called again. * The <code>setValue()</code> method on the <code>toArray</code> entries has no effect. * * @return a set view of this map's entries */ @Override public Set<Map.Entry<K, V>> entrySet() { if (entrySet == null) { entrySet = new ReferenceEntrySet<K, V>(this); } return entrySet; } /** * Returns a set view of this map's keys. * * @return a set view of this map's keys */ @Override public Set<K> keySet() { if (keySet == null) { keySet = new ReferenceKeySet<K>(this); } return keySet; } /** * Returns a collection view of this map's values. * * @return a set view of this map's values */ @Override public Collection<V> values() { if (values == null) { values = new ReferenceValues<V>(this); } return values; } //----------------------------------------------------------------------- /** * Purges stale mappings from this map before read operations. * <p> * This implementation calls {@link #purge()} to maintain a consistent state. */ protected void purgeBeforeRead() { purge(); } /** * Purges stale mappings from this map before write operations. * <p> * This implementation calls {@link #purge()} to maintain a consistent state. */ protected void purgeBeforeWrite() { purge(); } /** * Purges stale mappings from this map. * <p> * Note that this method is not synchronized! Special * care must be taken if, for instance, you want stale * mappings to be removed on a periodic basis by some * background thread. */ protected void purge() { Reference<?> ref = queue.poll(); while (ref != null) { purge(ref); ref = queue.poll(); } } /** * Purges the specified reference. * * @param ref the reference to purge */ protected void purge(final Reference<?> ref) { // The hashCode of the reference is the hashCode of the // mapping key, even if the reference refers to the // mapping value... final int hash = ref.hashCode(); final int index = hashIndex(hash, data.length); HashEntry<K, V> previous = null; HashEntry<K, V> entry = data[index]; while (entry != null) { if (((ReferenceEntry<K, V>) entry).purge(ref)) { if (previous == null) { data[index] = entry.next; } else { previous.next = entry.next; } this.size--; return; } previous = entry; entry = entry.next; } } //----------------------------------------------------------------------- /** * Gets the entry mapped to the key specified. * * @param key the key * @return the entry, null if no match */ @Override protected HashEntry<K, V> getEntry(final Object key) { if (key == null) { return null; } return super.getEntry(key); } /** * Gets the hash code for a MapEntry. * Subclasses can override this, for example to use the identityHashCode. * * @param key the key to get a hash code for, may be null * @param value the value to get a hash code for, may be null * @return the hash code, as per the MapEntry specification */ protected int hashEntry(final Object key, final Object value) { return (key == null ? 0 : key.hashCode()) ^ (value == null ? 0 : value.hashCode()); } /** * Compares two keys, in internal converted form, to see if they are equal. * <p> * This implementation converts the key from the entry to a real reference * before comparison. * * @param key1 the first key to compare passed in from outside * @param key2 the second key extracted from the entry via <code>entry.key</code> * @return true if equal */ @Override @SuppressWarnings("unchecked") protected boolean isEqualKey(final Object key1, Object key2) { key2 = keyType == ReferenceStrength.HARD ? key2 : ((Reference<K>) key2).get(); return key1 == key2 || key1.equals(key2); } /** * Creates a ReferenceEntry instead of a HashEntry. * * @param next the next entry in sequence * @param hashCode the hash code to use * @param key the key to store * @param value the value to store * @return the newly created entry */ @Override protected ReferenceEntry<K, V> createEntry(final HashEntry<K, V> next, final int hashCode, final K key, final V value) { return new ReferenceEntry<K, V>(this, next, hashCode, key, value); } /** * Creates an entry set iterator. * * @return the entrySet iterator */ @Override protected Iterator<Map.Entry<K, V>> createEntrySetIterator() { return new ReferenceEntrySetIterator<K, V>(this); } /** * Creates an key set iterator. * * @return the keySet iterator */ @Override protected Iterator<K> createKeySetIterator() { return new ReferenceKeySetIterator<K>(this); } /** * Creates an values iterator. * * @return the values iterator */ @Override protected Iterator<V> createValuesIterator() { return new ReferenceValuesIterator<V>(this); } //----------------------------------------------------------------------- /** * EntrySet implementation. */ static class ReferenceEntrySet<K, V> extends EntrySet<K, V> { protected ReferenceEntrySet(final AbstractHashedMap<K, V> parent) { super(parent); } @Override public Object[] toArray() { return toArray(new Object[size()]); } @Override public <T> T[] toArray(final T[] arr) { // special implementation to handle disappearing entries final ArrayList<Map.Entry<K, V>> list = new ArrayList<Map.Entry<K, V>>(size()); for (final Map.Entry<K, V> entry : this) { list.add(new DefaultMapEntry<K, V>(entry)); } return list.toArray(arr); } } //----------------------------------------------------------------------- /** * KeySet implementation. */ static class ReferenceKeySet<K> extends KeySet<K> { protected ReferenceKeySet(final AbstractHashedMap<K, ?> parent) { super(parent); } @Override public Object[] toArray() { return toArray(new Object[size()]); } @Override public <T> T[] toArray(final T[] arr) { // special implementation to handle disappearing keys final List<K> list = new ArrayList<K>(size()); for (final K key : this) { list.add(key); } return list.toArray(arr); } } //----------------------------------------------------------------------- /** * Values implementation. */ static class ReferenceValues<V> extends Values<V> { protected ReferenceValues(final AbstractHashedMap<?, V> parent) { super(parent); } @Override public Object[] toArray() { return toArray(new Object[size()]); } @Override public <T> T[] toArray(final T[] arr) { // special implementation to handle disappearing values final List<V> list = new ArrayList<V>(size()); for (final V value : this) { list.add(value); } return list.toArray(arr); } } //----------------------------------------------------------------------- /** * A MapEntry implementation for the map. * <p> * If getKey() or getValue() returns null, it means * the mapping is stale and should be removed. * * @since 3.1 */ protected static class ReferenceEntry<K, V> extends HashEntry<K, V> { /** The parent map */ private final AbstractReferenceMap<K, V> parent; /** * Creates a new entry object for the ReferenceMap. * * @param parent the parent map * @param next the next entry in the hash bucket * @param hashCode the hash code of the key * @param key the key * @param value the value */ public ReferenceEntry(final AbstractReferenceMap<K, V> parent, final HashEntry<K, V> next, final int hashCode, final K key, final V value) { super(next, hashCode, null, null); this.parent = parent; this.key = toReference(parent.keyType, key, hashCode); this.value = toReference(parent.valueType, value, hashCode); // the key hashCode is passed in deliberately } /** * Gets the key from the entry. * This method dereferences weak and soft keys and thus may return null. * * @return the key, which may be null if it was garbage collected */ @Override @SuppressWarnings("unchecked") public K getKey() { return (K) (parent.keyType == ReferenceStrength.HARD ? key : ((Reference<K>) key).get()); } /** * Gets the value from the entry. * This method dereferences weak and soft value and thus may return null. * * @return the value, which may be null if it was garbage collected */ @Override @SuppressWarnings("unchecked") public V getValue() { return (V) (parent.valueType == ReferenceStrength.HARD ? value : ((Reference<V>) value).get()); } /** * Sets the value of the entry. * * @param obj the object to store * @return the previous value */ @Override @SuppressWarnings("unchecked") public V setValue(final V obj) { final V old = getValue(); if (parent.valueType != ReferenceStrength.HARD) { ((Reference<V>) value).clear(); } value = toReference(parent.valueType, obj, hashCode); return old; } /** * Compares this map entry to another. * <p> * This implementation uses <code>isEqualKey</code> and * <code>isEqualValue</code> on the main map for comparison. * * @param obj the other map entry to compare to * @return true if equal, false if not */ @Override public boolean equals(final Object obj) { if (obj == this) { return true; } if (obj instanceof Map.Entry == false) { return false; } final Map.Entry<?, ?> entry = (Map.Entry<?, ?>)obj; final Object entryKey = entry.getKey(); // convert to hard reference final Object entryValue = entry.getValue(); // convert to hard reference if (entryKey == null || entryValue == null) { return false; } // compare using map methods, aiding identity subclass // note that key is direct access and value is via method return parent.isEqualKey(entryKey, key) && parent.isEqualValue(entryValue, getValue()); } /** * Gets the hashcode of the entry using temporary hard references. * <p> * This implementation uses <code>hashEntry</code> on the main map. * * @return the hashcode of the entry */ @Override public int hashCode() { return parent.hashEntry(getKey(), getValue()); } /** * Constructs a reference of the given type to the given referent. * The reference is registered with the queue for later purging. * * @param <T> the type of the referenced object * @param type HARD, SOFT or WEAK * @param referent the object to refer to * @param hash the hash code of the <i>key</i> of the mapping; * this number might be different from referent.hashCode() if * the referent represents a value and not a key * @return the reference to the object */ protected <T> Object toReference(final ReferenceStrength type, final T referent, final int hash) { if (type == ReferenceStrength.HARD) { return referent; } if (type == ReferenceStrength.SOFT) { return new SoftRef<T>(hash, referent, parent.queue); } if (type == ReferenceStrength.WEAK) { return new WeakRef<T>(hash, referent, parent.queue); } throw new Error(); } /** * Purges the specified reference * @param ref the reference to purge * @return true or false */ boolean purge(final Reference<?> ref) { boolean r = parent.keyType != ReferenceStrength.HARD && key == ref; r = r || parent.valueType != ReferenceStrength.HARD && value == ref; if (r) { if (parent.keyType != ReferenceStrength.HARD) { ((Reference<?>) key).clear(); } if (parent.valueType != ReferenceStrength.HARD) { ((Reference<?>) value).clear(); } else if (parent.purgeValues) { value = null; } } return r; } /** * Gets the next entry in the bucket. * * @return the next entry in the bucket */ protected ReferenceEntry<K, V> next() { return (ReferenceEntry<K, V>) next; } } //----------------------------------------------------------------------- /** * Base iterator class. */ static class ReferenceBaseIterator<K, V> { /** The parent map */ final AbstractReferenceMap<K, V> parent; // These fields keep track of where we are in the table. int index; ReferenceEntry<K, V> entry; ReferenceEntry<K, V> previous; // These Object fields provide hard references to the // current and next entry; this assures that if hasNext() // returns true, next() will actually return a valid element. K currentKey, nextKey; V currentValue, nextValue; int expectedModCount; public ReferenceBaseIterator(final AbstractReferenceMap<K, V> parent) { super(); this.parent = parent; index = parent.size() != 0 ? parent.data.length : 0; // have to do this here! size() invocation above // may have altered the modCount. expectedModCount = parent.modCount; } public boolean hasNext() { checkMod(); while (nextNull()) { ReferenceEntry<K, V> e = entry; int i = index; while (e == null && i > 0) { i--; e = (ReferenceEntry<K, V>) parent.data[i]; } entry = e; index = i; if (e == null) { currentKey = null; currentValue = null; return false; } nextKey = e.getKey(); nextValue = e.getValue(); if (nextNull()) { entry = entry.next(); } } return true; } private void checkMod() { if (parent.modCount != expectedModCount) { throw new ConcurrentModificationException(); } } private boolean nextNull() { return nextKey == null || nextValue == null; } protected ReferenceEntry<K, V> nextEntry() { checkMod(); if (nextNull() && !hasNext()) { throw new NoSuchElementException(); } previous = entry; entry = entry.next(); currentKey = nextKey; currentValue = nextValue; nextKey = null; nextValue = null; return previous; } protected ReferenceEntry<K, V> currentEntry() { checkMod(); return previous; } public void remove() { checkMod(); if (previous == null) { throw new IllegalStateException(); } parent.remove(currentKey); previous = null; currentKey = null; currentValue = null; expectedModCount = parent.modCount; } } /** * The EntrySet iterator. */ static class ReferenceEntrySetIterator<K, V> extends ReferenceBaseIterator<K, V> implements Iterator<Map.Entry<K, V>> { public ReferenceEntrySetIterator(final AbstractReferenceMap<K, V> parent) { super(parent); } public Map.Entry<K, V> next() { return nextEntry(); } } /** * The keySet iterator. */ static class ReferenceKeySetIterator<K> extends ReferenceBaseIterator<K, Object> implements Iterator<K> { @SuppressWarnings("unchecked") ReferenceKeySetIterator(final AbstractReferenceMap<K, ?> parent) { super((AbstractReferenceMap<K, Object>) parent); } public K next() { return nextEntry().getKey(); } } /** * The values iterator. */ static class ReferenceValuesIterator<V> extends ReferenceBaseIterator<Object, V> implements Iterator<V> { @SuppressWarnings("unchecked") ReferenceValuesIterator(final AbstractReferenceMap<?, V> parent) { super((AbstractReferenceMap<Object, V>) parent); } public V next() { return nextEntry().getValue(); } } /** * The MapIterator implementation. */ static class ReferenceMapIterator<K, V> extends ReferenceBaseIterator<K, V> implements MapIterator<K, V> { protected ReferenceMapIterator(final AbstractReferenceMap<K, V> parent) { super(parent); } public K next() { return nextEntry().getKey(); } public K getKey() { final HashEntry<K, V> current = currentEntry(); if (current == null) { throw new IllegalStateException(AbstractHashedMap.GETKEY_INVALID); } return current.getKey(); } public V getValue() { final HashEntry<K, V> current = currentEntry(); if (current == null) { throw new IllegalStateException(AbstractHashedMap.GETVALUE_INVALID); } return current.getValue(); } public V setValue(final V value) { final HashEntry<K, V> current = currentEntry(); if (current == null) { throw new IllegalStateException(AbstractHashedMap.SETVALUE_INVALID); } return current.setValue(value); } } //----------------------------------------------------------------------- // These two classes store the hashCode of the key of // of the mapping, so that after they're dequeued a quick // lookup of the bucket in the table can occur. /** * A soft reference holder. */ static class SoftRef<T> extends SoftReference<T> { /** the hashCode of the key (even if the reference points to a value) */ private final int hash; public SoftRef(final int hash, final T r, final ReferenceQueue<? super T> q) { super(r, q); this.hash = hash; } @Override public int hashCode() { return hash; } } /** * A weak reference holder. */ static class WeakRef<T> extends WeakReference<T> { /** the hashCode of the key (even if the reference points to a value) */ private final int hash; public WeakRef(final int hash, final T r, final ReferenceQueue<? super T> q) { super(r, q); this.hash = hash; } @Override public int hashCode() { return hash; } } //----------------------------------------------------------------------- /** * Replaces the superclass method to store the state of this class. * <p> * Serialization is not one of the JDK's nicest topics. Normal serialization will * initialise the superclass before the subclass. Sometimes however, this isn't * what you want, as in this case the <code>put()</code> method on read can be * affected by subclass state. * <p> * The solution adopted here is to serialize the state data of this class in * this protected method. This method must be called by the * <code>writeObject()</code> of the first serializable subclass. * <p> * Subclasses may override if they have a specific field that must be present * on read before this implementation will work. Generally, the read determines * what must be serialized here, if anything. * * @param out the output stream * @throws IOException if an error occurs while writing to the stream */ @Override protected void doWriteObject(final ObjectOutputStream out) throws IOException { out.writeInt(keyType.value); out.writeInt(valueType.value); out.writeBoolean(purgeValues); out.writeFloat(loadFactor); out.writeInt(data.length); for (final MapIterator<K, V> it = mapIterator(); it.hasNext();) { out.writeObject(it.next()); out.writeObject(it.getValue()); } out.writeObject(null); // null terminate map // do not call super.doWriteObject() as code there doesn't work for reference map } /** * Replaces the superclass method to read the state of this class. * <p> * Serialization is not one of the JDK's nicest topics. Normal serialization will * initialise the superclass before the subclass. Sometimes however, this isn't * what you want, as in this case the <code>put()</code> method on read can be * affected by subclass state. * <p> * The solution adopted here is to deserialize the state data of this class in * this protected method. This method must be called by the * <code>readObject()</code> of the first serializable subclass. * <p> * Subclasses may override if the subclass has a specific field that must be present * before <code>put()</code> or <code>calculateThreshold()</code> will work correctly. * * @param in the input stream * @throws IOException if an error occurs while reading from the stream * @throws ClassNotFoundException if an object read from the stream can not be loaded */ @Override @SuppressWarnings("unchecked") protected void doReadObject(final ObjectInputStream in) throws IOException, ClassNotFoundException { this.keyType = ReferenceStrength.resolve(in.readInt()); this.valueType = ReferenceStrength.resolve(in.readInt()); this.purgeValues = in.readBoolean(); this.loadFactor = in.readFloat(); final int capacity = in.readInt(); init(); data = new HashEntry[capacity]; while (true) { final K key = (K) in.readObject(); if (key == null) { break; } final V value = (V) in.readObject(); put(key, value); } threshold = calculateThreshold(data.length, loadFactor); // do not call super.doReadObject() as code there doesn't work for reference map } /** * Provided protected read-only access to the key type. * @param type the type to check against. * @return true if keyType has the specified type */ protected boolean isKeyType(ReferenceStrength type) { return this.keyType == type; } }
32.707271
118
0.56304
e4a1410d07b1dd3c21eb5bfd853caea3a796bbbd
1,636
package selfbot.commands.fun; import net.dv8tion.jda.core.events.message.MessageReceivedEvent; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import selfbot.utils.Command; import java.io.IOException; /* * @file AsciiCommand.java * @author Blue * @version 0.1 * @brief Write the given text as ASCII art */ public class AsciiCommand implements Command { @Override public boolean called(String[] args, MessageReceivedEvent event) { if(args.length == 0) {return false;} else return true; } @Override public void action(String[] args, MessageReceivedEvent event) { String query = new String(); for(String arg : args) { query += arg + "+ "; query = query.substring(0, query.length()-1); } OkHttpClient caller = new OkHttpClient(); Request request = new Request.Builder().url("http://artii.herokuapp.com/make?text=" + query).build(); try { Response response = caller.newCall(request).execute(); event.getMessage().editMessage("```\n" + response.body().string() + "\n```").queue(); } catch (IOException | NullPointerException e) { event.getMessage().editMessage("The artii.herokuapp.com API might be down at the moment").queue(); } catch (IllegalStateException e) { event.getMessage().editMessage("Message too big to be posted.").queue(); } } @Override public void executed(boolean success, MessageReceivedEvent event) { if(!success) { event.getMessage().delete().queue(); } } }
32.078431
110
0.634474
80cdb6836ed2cd9173c2a4a184b33a740928925b
6,393
package com.taobao.zeus.web.platform.client.module.jobmanager; import java.util.Iterator; import java.util.List; import com.google.gwt.user.client.History; import com.google.gwt.user.client.ui.HasWidgets; import com.taobao.zeus.web.platform.client.app.PlacePath; import com.taobao.zeus.web.platform.client.app.PlacePath.App; import com.taobao.zeus.web.platform.client.app.PlacePath.JobType; import com.taobao.zeus.web.platform.client.app.PlatformPlace.KV; import com.taobao.zeus.web.platform.client.module.jobmanager.event.TreeNodeChangeEvent; import com.taobao.zeus.web.platform.client.module.jobmanager.event.TreeNodeSelectEvent; import com.taobao.zeus.web.platform.client.util.Callback; import com.taobao.zeus.web.platform.client.util.PlatformContext; import com.taobao.zeus.web.platform.client.util.place.PlatformPlaceChangeEvent; public class JobManagerPresenterImpl implements JobManagerPresenter { private PlatformContext context; private JobManagerView jobManagerView; public JobManagerPresenterImpl(PlatformContext context){ this.context=context; context.getPlatformBus().addHandler(TreeNodeSelectEvent.type, new TreeNodeSelectEvent.TreeNodeSelectHandler() { public void onSelect(TreeNodeSelectEvent event) { //my tree final String providerKey = event.getProviderKey(); updateHistory(TreeKeyProviderTool.parseId(providerKey), getJobManagerView().isMyTreeActive() ? JobType.MyJob : JobType.SharedJob, TreeKeyProviderTool.parseIsJob(providerKey)); doSelect(providerKey); } }); context.getPlatformBus().addHandler(TreeNodeChangeEvent.TYPE, new TreeNodeChangeEvent.TreeNodeChangeHandler() { public void onJobUpdate(JobModel job,TreeNodeChangeEvent event) { List<GroupJobTreeModel> list=jobManagerView.getMyTreePanel().getTree().getStore().getAll(); for(GroupJobTreeModel model:list){ if(model.isJob() && model.getId().equals(job.getId())){ model.setName(job.getName()); break; } } list=jobManagerView.getAllTreePanel().getTree().getStore().getAll(); for(GroupJobTreeModel model:list){ if(model.isJob() && model.getId().equals(job.getId())){ model.setName(job.getName()); break; } } } public void onGroupUpdate(GroupModel group,TreeNodeChangeEvent event) { List<GroupJobTreeModel> list=jobManagerView.getMyTreePanel().getTree().getStore().getAll(); for(GroupJobTreeModel model:list){ if(model.isGroup() && model.getId().equals(group.getId())){ model.setName(group.getName()); break; } } list=jobManagerView.getAllTreePanel().getTree().getStore().getAll(); for(GroupJobTreeModel model:list){ if(model.isGroup() && model.getId().equals(group.getId())){ model.setName(group.getName()); break; } } } public void onChange(final TreeNodeChangeEvent event) { Callback callback=null; if(event.getNeedSelectProviderKey()!=null){ callback=new Callback() { @Override public void callback() { GroupJobTreeModel model=jobManagerView.getMyTreePanel().getTree().getStore().findModelWithKey(event.getNeedSelectProviderKey()); if(model!=null){ jobManagerView.getMyTreePanel().getTree().setExpanded(model, true); jobManagerView.getMyTreePanel().getTree().getSelectionModel().select(model, true); JobManagerPresenterImpl.this.context.getPlatformBus().fireEvent(new TreeNodeSelectEvent(event.getNeedSelectProviderKey())); } } }; } jobManagerView.getMyTreePanel().refresh(callback); jobManagerView.getAllTreePanel().refresh(); } }); context.getPlatformBus().registPlaceHandler(this); } @Override public void go(HasWidgets hasWidgets) { hasWidgets.add(getJobManagerView().asWidget()); } public JobManagerView getJobManagerView() { if(jobManagerView==null){ jobManagerView=new JobManagerViewImpl(this); } return jobManagerView; } @Override public void onSelect(String providerKey) { context.getPlatformBus().fireEvent(new TreeNodeSelectEvent(providerKey)); } @Override public PlatformContext getPlatformContext() { return context; } private void doSelect(final String providerKey) { GroupJobTreeModel myNeedSelect=jobManagerView.getMyTreePanel().getTree().getStore().findModelWithKey(providerKey); if(myNeedSelect!=null){ jobManagerView.getMyTreePanel().getTree().getSelectionModel().select(myNeedSelect, true); jobManagerView.getMyTreePanel().getTree().scrollIntoView(myNeedSelect); }else{ jobManagerView.getMyTreePanel().getTree().getSelectionModel().deselectAll(); } //all tree GroupJobTreeModel allNeedSelect=jobManagerView.getAllTreePanel().getTree().getStore().findModelWithKey(providerKey); if(allNeedSelect!=null){ jobManagerView.getAllTreePanel().getTree().getSelectionModel().select(allNeedSelect, true); jobManagerView.getAllTreePanel().getTree().scrollIntoView(allNeedSelect); }else{ jobManagerView.getAllTreePanel().getTree().getSelectionModel().deselectAll(); } } private void updateHistory(final String id, JobType type, boolean isJob) { if(isJob){ History.newItem(new PlacePath().toApp(App.Schedule) .toJobType(type) .toDisplayJob(id).create().getToken(), false); }else{ History.newItem(new PlacePath().toApp(App.Schedule) .toJobType(type) .toDisplayGroup(id).create().getToken(), false); } } @Override public void handle(PlatformPlaceChangeEvent event) { Iterator<KV> iterator = event.getNewPlace().iterator(); final String value = iterator.next().value; String key=null; if(iterator.hasNext()){ key=iterator.next().value; } if(value.equalsIgnoreCase(PlacePath.JobType.MyJob.toString())){ getJobManagerView().activeMyTreePanel(); }else{ getJobManagerView().activeAllTreePanel(); } if(key!=null){ doSelect(key); } } @Override public String getHandlerTag() { return TAG; } }
37.385965
135
0.686532
3de150b070eac84895900f76d7427f1736694213
6,745
/** * 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 com.streamsets.datacollector.main; import com.codahale.metrics.MetricRegistry; import com.streamsets.datacollector.main.RuntimeInfo; import com.streamsets.datacollector.main.RuntimeModule; import com.streamsets.datacollector.util.Configuration; import dagger.ObjectGraph; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import org.slf4j.Logger; import java.io.File; import java.io.FileWriter; import java.io.Writer; import java.net.URL; import java.net.URLClassLoader; import java.util.Arrays; import java.util.List; import java.util.Properties; import java.util.UUID; public class TestRuntimeInfo { @Before public void before() { System.setProperty(RuntimeModule.SDC_PROPERTY_PREFIX + RuntimeInfo.STATIC_WEB_DIR, "target/w"); System.setProperty(RuntimeModule.SDC_PROPERTY_PREFIX + RuntimeInfo.CONFIG_DIR, "target/x"); System.setProperty(RuntimeModule.SDC_PROPERTY_PREFIX + RuntimeInfo.LOG_DIR, "target/y"); System.setProperty(RuntimeModule.SDC_PROPERTY_PREFIX + RuntimeInfo.DATA_DIR, "target/z"); System.setProperty(RuntimeModule.SDC_PROPERTY_PREFIX + RuntimeInfo.RESOURCES_DIR, "target/R"); } @After public void cleanUp() { System.getProperties().remove(RuntimeModule.SDC_PROPERTY_PREFIX + RuntimeInfo.CONFIG_DIR); System.getProperties().remove(RuntimeModule.SDC_PROPERTY_PREFIX + RuntimeInfo.LOG_DIR); System.getProperties().remove(RuntimeModule.SDC_PROPERTY_PREFIX + RuntimeInfo.DATA_DIR); System.getProperties().remove(RuntimeModule.SDC_PROPERTY_PREFIX + RuntimeInfo.STATIC_WEB_DIR); System.getProperties().remove(RuntimeModule.SDC_PROPERTY_PREFIX + RuntimeInfo.RESOURCES_DIR); System.getProperties().remove(RuntimeModule.DATA_COLLECTOR_BASE_HTTP_URL); } @Test public void testInfoCustom() { System.setProperty(RuntimeModule.SDC_PROPERTY_PREFIX + RuntimeInfo.STATIC_WEB_DIR, "w"); System.setProperty(RuntimeModule.SDC_PROPERTY_PREFIX + RuntimeInfo.CONFIG_DIR, "x"); System.setProperty(RuntimeModule.SDC_PROPERTY_PREFIX + RuntimeInfo.LOG_DIR, "y"); System.setProperty(RuntimeModule.SDC_PROPERTY_PREFIX + RuntimeInfo.DATA_DIR, "z"); System.setProperty(RuntimeModule.SDC_PROPERTY_PREFIX + RuntimeInfo.RESOURCES_DIR, "r"); List<? extends ClassLoader> customCLs = Arrays.asList(new URLClassLoader(new URL[0], null)); RuntimeInfo info = new RuntimeInfo(RuntimeModule.SDC_PROPERTY_PREFIX, new MetricRegistry(), customCLs); Assert.assertEquals(System.getProperty("user.dir"), info.getRuntimeDir()); Assert.assertEquals("w", info.getStaticWebDir()); Assert.assertEquals("x", info.getConfigDir()); Assert.assertEquals("y", info.getLogDir()); Assert.assertEquals("z", info.getDataDir()); Assert.assertEquals("r", info.getResourcesDir()); Assert.assertEquals(customCLs, info.getStageLibraryClassLoaders()); Logger log = Mockito.mock(Logger.class); info.log(log); } @Test public void testAttributes() { RuntimeInfo info = new RuntimeInfo(RuntimeModule.SDC_PROPERTY_PREFIX, new MetricRegistry(), Arrays.asList(getClass().getClassLoader())); Assert.assertFalse(info.hasAttribute("a")); info.setAttribute("a", 1); Assert.assertTrue(info.hasAttribute("a")); Assert.assertEquals(1, info.getAttribute("a")); info.removeAttribute("a"); Assert.assertFalse(info.hasAttribute("a")); } @Test public void testDefaultIdAndBaseHttpUrl() { ObjectGraph og = ObjectGraph.create(RuntimeModule.class); RuntimeInfo info = og.get(RuntimeInfo.class); Assert.assertEquals("UNDEF", info.getBaseHttpUrl()); } @Test public void testMetrics() { ObjectGraph og = ObjectGraph.create(RuntimeModule.class); RuntimeInfo info = og.get(RuntimeInfo.class); Assert.assertNotNull(info.getMetrics()); } @Test public void testConfigIdAndBaseHttpUrl() throws Exception { File dir = new File("target", UUID.randomUUID().toString()); Assert.assertTrue(dir.mkdirs()); System.setProperty(RuntimeModule.SDC_PROPERTY_PREFIX + RuntimeInfo.CONFIG_DIR, dir.getAbsolutePath()); Properties props = new Properties(); props.setProperty(RuntimeModule.DATA_COLLECTOR_BASE_HTTP_URL, "HTTP"); Writer writer = new FileWriter(new File(dir, "sdc.properties")); props.store(writer, ""); writer.close(); ObjectGraph og = ObjectGraph.create(RuntimeModule.class); og.get(Configuration.class); RuntimeInfo info = og.get(RuntimeInfo.class); Assert.assertEquals("HTTP", info.getBaseHttpUrl()); } @Test public void testRuntimeInfoSdcId() { System.setProperty(RuntimeModule.SDC_PROPERTY_PREFIX + RuntimeInfo.STATIC_WEB_DIR, "w"); System.setProperty(RuntimeModule.SDC_PROPERTY_PREFIX + RuntimeInfo.CONFIG_DIR, "x"); System.setProperty(RuntimeModule.SDC_PROPERTY_PREFIX + RuntimeInfo.LOG_DIR, "y"); System.setProperty(RuntimeModule.SDC_PROPERTY_PREFIX + RuntimeInfo.RESOURCES_DIR, "r"); System.setProperty(RuntimeModule.SDC_PROPERTY_PREFIX + RuntimeInfo.DATA_DIR, new File("target", UUID.randomUUID().toString()).getAbsolutePath()); List<? extends ClassLoader> customCLs = Arrays.asList(new URLClassLoader(new URL[0], null)); RuntimeInfo info = new RuntimeInfo(RuntimeModule.SDC_PROPERTY_PREFIX, new MetricRegistry(), customCLs); info.init(); String id = info.getId(); Assert.assertNotNull(id); info = new RuntimeInfo(RuntimeModule.SDC_PROPERTY_PREFIX, new MetricRegistry(), customCLs); info.init(); Assert.assertEquals(id, info.getId()); System.setProperty(RuntimeModule.SDC_PROPERTY_PREFIX + RuntimeInfo.DATA_DIR, new File("target", UUID.randomUUID().toString()).getAbsolutePath()); info = new RuntimeInfo(RuntimeModule.SDC_PROPERTY_PREFIX, new MetricRegistry(), customCLs); info.init(); Assert.assertNotEquals(id, info.getId()); } }
43.798701
107
0.752557
741f2eb5370db8b27615244f61b2752fedf3b628
843
/******************************************************************************* * Copyright (C) 2019 Vulcalien * This code or part of it is licensed under MIT License by Vulcalien ******************************************************************************/ package vulc.ld44.level.tile; import vulc.ld44.gfx.Atlas; import vulc.ld44.gfx.Screen; import vulc.ld44.level.Level; import vulc.ld44.level.entity.Entity; import vulc.ld44.level.entity.Player; public class WinTile extends Tile { public WinTile(int id) { super(id); } public void render(Screen screen, Level level, int xt, int yt) { screen.renderSprite(Atlas.getTexture(14, 5), xt << T_SIZE, yt << T_SIZE); } public void onEnter(Level level, int xt, int yt, Entity e) { if(e instanceof Player) { Player player = (Player) e; player.wonLevel = true; } } }
27.193548
80
0.576512
f74684ee7842106ff3b5fabc690b2eb3a51bf48c
8,823
/* * Copyright 2011 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.launcher.daemon.registry; import org.gradle.api.logging.Logger; import org.gradle.api.logging.Logging; import org.gradle.api.specs.Spec; import org.gradle.cache.PersistentStateCache; import org.gradle.cache.internal.FileIntegrityViolationSuppressingPersistentStateCacheDecorator; import org.gradle.cache.internal.FileLockManager; import org.gradle.cache.internal.OnDemandFileAccess; import org.gradle.cache.internal.SimpleStateCache; import org.gradle.internal.nativeintegration.filesystem.Chmod; import org.gradle.internal.remote.Address; import org.gradle.launcher.daemon.context.DaemonContext; import java.io.File; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import static org.gradle.launcher.daemon.server.api.DaemonStateControl.State; import static org.gradle.launcher.daemon.server.api.DaemonStateControl.State.Canceled; import static org.gradle.launcher.daemon.server.api.DaemonStateControl.State.Idle; /** * Access to daemon registry files. Useful also for testing. */ public class PersistentDaemonRegistry implements DaemonRegistry { private final PersistentStateCache<DaemonRegistryContent> cache; private final Lock lock = new ReentrantLock(); private final File registryFile; private static final Logger LOGGER = Logging.getLogger(PersistentDaemonRegistry.class); public PersistentDaemonRegistry(File registryFile, FileLockManager fileLockManager, Chmod chmod) { this.registryFile = registryFile; cache = new FileIntegrityViolationSuppressingPersistentStateCacheDecorator<DaemonRegistryContent>( new SimpleStateCache<DaemonRegistryContent>( registryFile, new OnDemandFileAccess( registryFile, "daemon addresses registry", fileLockManager), DaemonRegistryContent.SERIALIZER, chmod )); } public List<DaemonInfo> getAll() { lock.lock(); try { DaemonRegistryContent content = cache.get(); if (content == null) { //when no daemon process has started yet return new LinkedList<DaemonInfo>(); } return content.getInfos(); } finally { lock.unlock(); } } public List<DaemonInfo> getIdle() { return getDaemonsMatching(new Spec<DaemonInfo>() { @Override public boolean isSatisfiedBy(DaemonInfo daemonInfo) { return daemonInfo.getState() == Idle; } }); } public List<DaemonInfo> getNotIdle() { return getDaemonsMatching(new Spec<DaemonInfo>() { @Override public boolean isSatisfiedBy(DaemonInfo daemonInfo) { return daemonInfo.getState() != Idle; } }); } public List<DaemonInfo> getCanceled() { return getDaemonsMatching(new Spec<DaemonInfo>() { @Override public boolean isSatisfiedBy(DaemonInfo daemonInfo) { return daemonInfo.getState() == Canceled; } }); } private List<DaemonInfo> getDaemonsMatching(Spec<DaemonInfo> spec) { lock.lock(); try { List<DaemonInfo> out = new LinkedList<DaemonInfo>(); List<DaemonInfo> all = getAll(); for (DaemonInfo d : all) { if (spec.isSatisfiedBy(d)) { out.add(d); } } return out; } finally { lock.unlock(); } } public void remove(final Address address) { lock.lock(); LOGGER.debug("Removing daemon address: {}", address); try { cache.update(new PersistentStateCache.UpdateAction<DaemonRegistryContent>() { public DaemonRegistryContent update(DaemonRegistryContent oldValue) { if (oldValue == null) { return oldValue; } oldValue.removeInfo(address); return oldValue; } }); } finally { lock.unlock(); } } public void markState(final Address address, final State state) { lock.lock(); LOGGER.debug("Marking busy by address: {}", address); try { cache.update(new PersistentStateCache.UpdateAction<DaemonRegistryContent>() { public DaemonRegistryContent update(DaemonRegistryContent oldValue) { DaemonInfo daemonInfo = oldValue != null ? oldValue.getInfo(address) : null; if (daemonInfo != null) { daemonInfo.setState(state); } // Else, has been removed by something else - ignore return oldValue; }}); } finally { lock.unlock(); } } @Override public void storeStopEvent(final DaemonStopEvent stopEvent) { lock.lock(); LOGGER.debug("Storing daemon stop event with timestamp {}", stopEvent.getTimestamp().getTime()); try { cache.update(new PersistentStateCache.UpdateAction<DaemonRegistryContent>() { public DaemonRegistryContent update(DaemonRegistryContent content) { if (content == null) { // registry doesn't exist yet content = new DaemonRegistryContent(); } content.addStopEvent(stopEvent); return content; } }); } finally { lock.unlock(); } } @Override public List<DaemonStopEvent> getStopEvents() { lock.lock(); LOGGER.debug("Getting daemon stop events"); try { DaemonRegistryContent content = cache.get(); if (content == null) { // no daemon process has started yet return new LinkedList<DaemonStopEvent>(); } return content.getStopEvents(); } finally { lock.unlock(); } } @Override public void removeStopEvents(final Collection<DaemonStopEvent> events) { lock.lock(); LOGGER.info("Removing {} daemon stop events from registry", events.size()); try { cache.update(new PersistentStateCache.UpdateAction<DaemonRegistryContent>() { public DaemonRegistryContent update(DaemonRegistryContent content) { if (content != null) { // no daemon process has started yet content.removeStopEvents(events); } return content; } }); } finally { lock.unlock(); } } public void store(final DaemonInfo info) { final Address address = info.getAddress(); final DaemonContext daemonContext = info.getContext(); final byte[] token = info.getToken(); final State state = info.getState(); lock.lock(); LOGGER.debug("Storing daemon address: {}, context: {}", address, daemonContext); try { cache.update(new PersistentStateCache.UpdateAction<DaemonRegistryContent>() { public DaemonRegistryContent update(DaemonRegistryContent oldValue) { if (oldValue == null) { //it means the registry didn't exist yet oldValue = new DaemonRegistryContent(); } DaemonInfo daemonInfo = new DaemonInfo(address, daemonContext, token, state); oldValue.setStatus(address, daemonInfo); return oldValue; } }); } finally { lock.unlock(); } } public String toString() { return String.format("PersistentDaemonRegistry[file=%s]", registryFile); } }
36.7625
106
0.591749
90510c28ab76ad19f27f442b9e0d279b3fdb117c
20,584
/* * Copyright (C) 2015 The Android Open Source Project * * 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 androidx.core.content.res; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import android.content.Context; import android.content.res.ColorStateList; import android.content.res.Resources; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.os.Build; import android.support.test.InstrumentationRegistry; import android.support.test.filters.SmallTest; import android.support.v4.testutils.TestUtils; import android.util.DisplayMetrics; import androidx.annotation.NonNull; import androidx.core.provider.FontsContractCompat; import androidx.core.provider.MockFontProvider; import androidx.core.test.R; import org.junit.Before; import org.junit.Test; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; @SmallTest public class ResourcesCompatTest { private Context mContext; private Resources mResources; @Before public void setup() { mContext = InstrumentationRegistry.getContext(); mResources = mContext.getResources(); MockFontProvider.prepareFontFiles(mContext); } @Test public void testGetColor() throws Throwable { assertEquals("Unthemed color load", ResourcesCompat.getColor(mResources, R.color.text_color, null), 0xFFFF8090); if (Build.VERSION.SDK_INT >= 23) { // The following tests are only expected to pass on v23+ devices. The result of // calling theme-aware getColor() in pre-v23 is undefined. final Resources.Theme yellowTheme = mResources.newTheme(); yellowTheme.applyStyle(R.style.YellowTheme, true); assertEquals("Themed yellow color load", 0xFFF0B000, ResourcesCompat.getColor(mResources, R.color.simple_themed_selector, yellowTheme)); final Resources.Theme lilacTheme = mResources.newTheme(); lilacTheme.applyStyle(R.style.LilacTheme, true); assertEquals("Themed lilac color load", 0xFFF080F0, ResourcesCompat.getColor(mResources, R.color.simple_themed_selector, lilacTheme)); } } @Test public void testGetColorStateList() throws Throwable { final ColorStateList unthemedColorStateList = ResourcesCompat.getColorStateList(mResources, R.color.complex_unthemed_selector, null); assertEquals("Unthemed color state list load: default", 0xFF70A0C0, unthemedColorStateList.getDefaultColor()); assertEquals("Unthemed color state list load: focused", 0xFF70B0F0, unthemedColorStateList.getColorForState( new int[]{android.R.attr.state_focused}, 0)); assertEquals("Unthemed color state list load: pressed", 0xFF6080B0, unthemedColorStateList.getColorForState( new int[]{android.R.attr.state_pressed}, 0)); if (Build.VERSION.SDK_INT >= 23) { // The following tests are only expected to pass on v23+ devices. The result of // calling theme-aware getColorStateList() in pre-v23 is undefined. final Resources.Theme yellowTheme = mResources.newTheme(); yellowTheme.applyStyle(R.style.YellowTheme, true); final ColorStateList themedYellowColorStateList = ResourcesCompat.getColorStateList(mResources, R.color.complex_themed_selector, yellowTheme); assertEquals("Themed yellow color state list load: default", 0xFFF0B000, themedYellowColorStateList.getDefaultColor()); assertEquals("Themed yellow color state list load: focused", 0xFFF0A020, themedYellowColorStateList.getColorForState( new int[]{android.R.attr.state_focused}, 0)); assertEquals("Themed yellow color state list load: pressed", 0xFFE0A040, themedYellowColorStateList.getColorForState( new int[]{android.R.attr.state_pressed}, 0)); final Resources.Theme lilacTheme = mResources.newTheme(); lilacTheme.applyStyle(R.style.LilacTheme, true); final ColorStateList themedLilacColorStateList = ResourcesCompat.getColorStateList(mResources, R.color.complex_themed_selector, lilacTheme); assertEquals("Themed lilac color state list load: default", 0xFFF080F0, themedLilacColorStateList.getDefaultColor()); assertEquals("Themed lilac color state list load: focused", 0xFFF070D0, themedLilacColorStateList.getColorForState( new int[]{android.R.attr.state_focused}, 0)); assertEquals("Themed lilac color state list load: pressed", 0xFFE070A0, themedLilacColorStateList.getColorForState( new int[]{android.R.attr.state_pressed}, 0)); } } @Test public void testGetDrawable() throws Throwable { final Drawable unthemedDrawable = ResourcesCompat.getDrawable(mResources, R.drawable.test_drawable_red, null); TestUtils.assertAllPixelsOfColor("Unthemed drawable load", unthemedDrawable, mResources.getColor(R.color.test_red)); if (Build.VERSION.SDK_INT >= 23) { // The following tests are only expected to pass on v23+ devices. The result of // calling theme-aware getDrawable() in pre-v23 is undefined. final Resources.Theme yellowTheme = mResources.newTheme(); yellowTheme.applyStyle(R.style.YellowTheme, true); final Drawable themedYellowDrawable = ResourcesCompat.getDrawable(mResources, R.drawable.themed_drawable, yellowTheme); TestUtils.assertAllPixelsOfColor("Themed yellow drawable load", themedYellowDrawable, 0xFFF0B000); final Resources.Theme lilacTheme = mResources.newTheme(); lilacTheme.applyStyle(R.style.LilacTheme, true); final Drawable themedLilacDrawable = ResourcesCompat.getDrawable(mResources, R.drawable.themed_drawable, lilacTheme); TestUtils.assertAllPixelsOfColor("Themed lilac drawable load", themedLilacDrawable, 0xFFF080F0); } } @Test public void testGetDrawableForDensityUnthemed() throws Throwable { // Density-aware drawable loading for now only works on raw bitmap drawables. // Different variants of density_aware_drawable are set up in the following way: // mdpi - 12x12 px which is 12x12 dip // hdpi - 21x21 px which is 14x14 dip // xhdpi - 32x32 px which is 16x16 dip // xxhdpi - 54x54 px which is 18x18 dip // The tests below (on v15+ devices) are checking that an unthemed density-aware // loading of raw bitmap drawables returns a drawable with matching intrinsic // dimensions. final Drawable unthemedDrawableForMediumDensity = ResourcesCompat.getDrawableForDensity(mResources, R.drawable.density_aware_drawable, DisplayMetrics.DENSITY_MEDIUM, null); // For pre-v15 devices we should get a drawable that corresponds to the density of the // current device. For v15+ devices we should get a drawable that corresponds to the // density requested in the API call. final int expectedSizeForMediumDensity = (Build.VERSION.SDK_INT < 15) ? mResources.getDimensionPixelSize(R.dimen.density_aware_size) : 12; assertEquals("Unthemed density-aware drawable load: medium width", expectedSizeForMediumDensity, unthemedDrawableForMediumDensity.getIntrinsicWidth()); assertEquals("Unthemed density-aware drawable load: medium height", expectedSizeForMediumDensity, unthemedDrawableForMediumDensity.getIntrinsicHeight()); final Drawable unthemedDrawableForHighDensity = ResourcesCompat.getDrawableForDensity(mResources, R.drawable.density_aware_drawable, DisplayMetrics.DENSITY_HIGH, null); // For pre-v15 devices we should get a drawable that corresponds to the density of the // current device. For v15+ devices we should get a drawable that corresponds to the // density requested in the API call. final int expectedSizeForHighDensity = (Build.VERSION.SDK_INT < 15) ? mResources.getDimensionPixelSize(R.dimen.density_aware_size) : 21; assertEquals("Unthemed density-aware drawable load: high width", expectedSizeForHighDensity, unthemedDrawableForHighDensity.getIntrinsicWidth()); assertEquals("Unthemed density-aware drawable load: high height", expectedSizeForHighDensity, unthemedDrawableForHighDensity.getIntrinsicHeight()); final Drawable unthemedDrawableForXHighDensity = ResourcesCompat.getDrawableForDensity(mResources, R.drawable.density_aware_drawable, DisplayMetrics.DENSITY_XHIGH, null); // For pre-v15 devices we should get a drawable that corresponds to the density of the // current device. For v15+ devices we should get a drawable that corresponds to the // density requested in the API call. final int expectedSizeForXHighDensity = (Build.VERSION.SDK_INT < 15) ? mResources.getDimensionPixelSize(R.dimen.density_aware_size) : 32; assertEquals("Unthemed density-aware drawable load: xhigh width", expectedSizeForXHighDensity, unthemedDrawableForXHighDensity.getIntrinsicWidth()); assertEquals("Unthemed density-aware drawable load: xhigh height", expectedSizeForXHighDensity, unthemedDrawableForXHighDensity.getIntrinsicHeight()); final Drawable unthemedDrawableForXXHighDensity = ResourcesCompat.getDrawableForDensity(mResources, R.drawable.density_aware_drawable, DisplayMetrics.DENSITY_XXHIGH, null); // For pre-v15 devices we should get a drawable that corresponds to the density of the // current device. For v15+ devices we should get a drawable that corresponds to the // density requested in the API call. final int expectedSizeForXXHighDensity = (Build.VERSION.SDK_INT < 15) ? mResources.getDimensionPixelSize(R.dimen.density_aware_size) : 54; assertEquals("Unthemed density-aware drawable load: xxhigh width", expectedSizeForXXHighDensity, unthemedDrawableForXXHighDensity.getIntrinsicWidth()); assertEquals("Unthemed density-aware drawable load: xxhigh height", expectedSizeForXXHighDensity, unthemedDrawableForXXHighDensity.getIntrinsicHeight()); } @Test public void testGetDrawableForDensityThemed() throws Throwable { if (Build.VERSION.SDK_INT < 21) { // The following tests are only expected to pass on v21+ devices. The result of // calling theme-aware getDrawableForDensity() in pre-v21 is undefined. return; } // Density- and theme-aware drawable loading for now only works partially. This test // checks only for theming of a tinted bitmap XML drawable, but not correct scaling. // Set up the two test themes, yellow and lilac. final Resources.Theme yellowTheme = mResources.newTheme(); yellowTheme.applyStyle(R.style.YellowTheme, true); final Resources.Theme lilacTheme = mResources.newTheme(); lilacTheme.applyStyle(R.style.LilacTheme, true); Drawable themedYellowDrawableForMediumDensity = ResourcesCompat.getDrawableForDensity(mResources, R.drawable.themed_bitmap, DisplayMetrics.DENSITY_MEDIUM, yellowTheme); // We should get a drawable that corresponds to the theme requested in the API call. TestUtils.assertAllPixelsOfColor("Themed yellow density-aware drawable load : medium color", themedYellowDrawableForMediumDensity, 0xFFF0B000); Drawable themedLilacDrawableForMediumDensity = ResourcesCompat.getDrawableForDensity(mResources, R.drawable.themed_bitmap, DisplayMetrics.DENSITY_MEDIUM, lilacTheme); // We should get a drawable that corresponds to the theme requested in the API call. TestUtils.assertAllPixelsOfColor("Themed lilac density-aware drawable load : medium color", themedLilacDrawableForMediumDensity, 0xFFF080F0); Drawable themedYellowDrawableForHighDensity = ResourcesCompat.getDrawableForDensity(mResources, R.drawable.themed_bitmap, DisplayMetrics.DENSITY_HIGH, yellowTheme); // We should get a drawable that corresponds to the theme requested in the API call. TestUtils.assertAllPixelsOfColor("Themed yellow density-aware drawable load : high color", themedYellowDrawableForHighDensity, 0xFFF0B000); Drawable themedLilacDrawableForHighDensity = ResourcesCompat.getDrawableForDensity(mResources, R.drawable.themed_bitmap, DisplayMetrics.DENSITY_HIGH, lilacTheme); // We should get a drawable that corresponds to the theme requested in the API call. TestUtils.assertAllPixelsOfColor("Themed lilac density-aware drawable load : high color", themedLilacDrawableForHighDensity, 0xFFF080F0); Drawable themedYellowDrawableForXHighDensity = ResourcesCompat.getDrawableForDensity(mResources, R.drawable.themed_bitmap, DisplayMetrics.DENSITY_XHIGH, yellowTheme); // We should get a drawable that corresponds to the theme requested in the API call. TestUtils.assertAllPixelsOfColor("Themed yellow density-aware drawable load : xhigh color", themedYellowDrawableForXHighDensity, 0xFFF0B000); Drawable themedLilacDrawableForXHighDensity = ResourcesCompat.getDrawableForDensity(mResources, R.drawable.themed_bitmap, DisplayMetrics.DENSITY_XHIGH, lilacTheme); // We should get a drawable that corresponds to the theme requested in the API call. TestUtils.assertAllPixelsOfColor("Themed lilac density-aware drawable load : xhigh color", themedLilacDrawableForXHighDensity, 0xFFF080F0); Drawable themedYellowDrawableForXXHighDensity = ResourcesCompat.getDrawableForDensity(mResources, R.drawable.themed_bitmap, DisplayMetrics.DENSITY_XXHIGH, yellowTheme); // We should get a drawable that corresponds to the theme requested in the API call. TestUtils.assertAllPixelsOfColor("Themed yellow density-aware drawable load : xxhigh color", themedYellowDrawableForXXHighDensity, 0xFFF0B000); Drawable themedLilacDrawableForXXHighDensity = ResourcesCompat.getDrawableForDensity(mResources, R.drawable.themed_bitmap, DisplayMetrics.DENSITY_XXHIGH, lilacTheme); // We should get a drawable that corresponds to the theme requested in the API call. TestUtils.assertAllPixelsOfColor("Themed lilac density-aware drawable load : xxhigh color", themedLilacDrawableForXXHighDensity, 0xFFF080F0); } @Test(expected = Resources.NotFoundException.class) public void testGetFont_invalidResourceId() { ResourcesCompat.getFont(mContext, -1); } @Test public void testGetFont_fontFile_sync() { Typeface font = ResourcesCompat.getFont(mContext, R.font.samplefont); assertNotNull(font); assertNotSame(Typeface.DEFAULT, font); } private static final class FontCallback extends ResourcesCompat.FontCallback { private final CountDownLatch mLatch; Typeface mTypeface; FontCallback(CountDownLatch latch) { mLatch = latch; } @Override public void onFontRetrieved(@NonNull Typeface typeface) { mTypeface = typeface; mLatch.countDown(); } @Override public void onFontRetrievalFailed(int reason) { mLatch.countDown(); } } @Test public void testGetFont_fontFile_async() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); final FontCallback callback = new FontCallback(latch); FontsContractCompat.resetCache(); ResourcesCompat.getFont(mContext, R.font.samplefont, callback, null); assertTrue(latch.await(5L, TimeUnit.SECONDS)); assertNotNull(callback.mTypeface); assertNotSame(Typeface.DEFAULT, callback.mTypeface); } @Test public void testGetFont_xmlFile_sync() { Typeface font = ResourcesCompat.getFont(mContext, R.font.samplexmlfont); assertNotNull(font); assertNotSame(Typeface.DEFAULT, font); } @Test public void testGetFont_xmlFile_async() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); final FontCallback callback = new FontCallback(latch); ResourcesCompat.getFont(mContext, R.font.samplexmlfont, callback, null); assertTrue(latch.await(5L, TimeUnit.SECONDS)); assertNotNull(callback.mTypeface); assertNotSame(Typeface.DEFAULT, callback.mTypeface); } @Test public void testGetFont_xmlProviderFile_sync() { Typeface font = ResourcesCompat.getFont(mContext, R.font.samplexmldownloadedfont); assertNotNull(font); assertNotSame(Typeface.DEFAULT, font); } @Test public void testGetFont_xmlProviderFile_async() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); final FontCallback callback = new FontCallback(latch); // Font provider non-blocking requests post on the calling thread so can't run on // the test thread as it doesn't have a Looper. InstrumentationRegistry.getInstrumentation().runOnMainSync(new Runnable() { @Override public void run() { ResourcesCompat.getFont(mContext, R.font.samplexmldownloadedfont, callback, null); } }); assertTrue(latch.await(5L, TimeUnit.SECONDS)); assertNotNull(callback.mTypeface); assertNotSame(Typeface.DEFAULT, callback.mTypeface); } @Test public void testGetFont_invalidXmlFile() { try { assertNull( ResourcesCompat.getFont(mContext, R.font.invalid_xmlfamily)); } catch (Resources.NotFoundException e) { // pass } try { assertNull(ResourcesCompat.getFont(mContext, R.font.invalid_xmlempty)); } catch (Resources.NotFoundException e) { // pass } } @Test public void testGetFont_fontFileIsCached() { Typeface font = ResourcesCompat.getFont(mContext, R.font.samplefont); Typeface font2 = ResourcesCompat.getFont(mContext, R.font.samplefont); assertSame(font, font2); } @Test public void testGetFont_xmlFileIsCached() { Typeface font = ResourcesCompat.getFont(mContext, R.font.samplexmlfont); Typeface font2 = ResourcesCompat.getFont(mContext, R.font.samplexmlfont); assertSame(font, font2); } }
48.206089
100
0.680917
a4413290e408122c0b85e525e2d7868c27aae3cc
6,398
/** * generated by Xtext 2.22.0 */ package org.sodalite.dsl.rM.impl; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.impl.MinimalEObjectImpl; import org.sodalite.dsl.rM.EPolicyType; import org.sodalite.dsl.rM.EPolicyTypeBody; import org.sodalite.dsl.rM.RMPackage; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>EPolicy Type</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link org.sodalite.dsl.rM.impl.EPolicyTypeImpl#getName <em>Name</em>}</li> * <li>{@link org.sodalite.dsl.rM.impl.EPolicyTypeImpl#getPolicy <em>Policy</em>}</li> * </ul> * * @generated */ public class EPolicyTypeImpl extends MinimalEObjectImpl.Container implements EPolicyType { /** * The default value of the '{@link #getName() <em>Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getName() * @generated * @ordered */ protected static final String NAME_EDEFAULT = null; /** * The cached value of the '{@link #getName() <em>Name</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getName() * @generated * @ordered */ protected String name = NAME_EDEFAULT; /** * The cached value of the '{@link #getPolicy() <em>Policy</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getPolicy() * @generated * @ordered */ protected EPolicyTypeBody policy; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected EPolicyTypeImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return RMPackage.Literals.EPOLICY_TYPE; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String getName() { return name; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void setName(String newName) { String oldName = name; name = newName; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, RMPackage.EPOLICY_TYPE__NAME, oldName, name)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public EPolicyTypeBody getPolicy() { return policy; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetPolicy(EPolicyTypeBody newPolicy, NotificationChain msgs) { EPolicyTypeBody oldPolicy = policy; policy = newPolicy; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, RMPackage.EPOLICY_TYPE__POLICY, oldPolicy, newPolicy); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void setPolicy(EPolicyTypeBody newPolicy) { if (newPolicy != policy) { NotificationChain msgs = null; if (policy != null) msgs = ((InternalEObject)policy).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - RMPackage.EPOLICY_TYPE__POLICY, null, msgs); if (newPolicy != null) msgs = ((InternalEObject)newPolicy).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - RMPackage.EPOLICY_TYPE__POLICY, null, msgs); msgs = basicSetPolicy(newPolicy, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, RMPackage.EPOLICY_TYPE__POLICY, newPolicy, newPolicy)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case RMPackage.EPOLICY_TYPE__POLICY: return basicSetPolicy(null, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case RMPackage.EPOLICY_TYPE__NAME: return getName(); case RMPackage.EPOLICY_TYPE__POLICY: return getPolicy(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case RMPackage.EPOLICY_TYPE__NAME: setName((String)newValue); return; case RMPackage.EPOLICY_TYPE__POLICY: setPolicy((EPolicyTypeBody)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case RMPackage.EPOLICY_TYPE__NAME: setName(NAME_EDEFAULT); return; case RMPackage.EPOLICY_TYPE__POLICY: setPolicy((EPolicyTypeBody)null); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case RMPackage.EPOLICY_TYPE__NAME: return NAME_EDEFAULT == null ? name != null : !NAME_EDEFAULT.equals(name); case RMPackage.EPOLICY_TYPE__POLICY: return policy != null; } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuilder result = new StringBuilder(super.toString()); result.append(" (name: "); result.append(name); result.append(')'); return result.toString(); } } //EPolicyTypeImpl
23.608856
139
0.618318
c99523972915fbc1cb3c0b61a1284b9684bde5c2
3,117
package com.example.laboratorio1; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; public class productoelegido extends AppCompatActivity { //Objetos que posee la activity TextView txvProducto, txvEspecificaciones, txvPrecio; EditText edtCantidad; Button btnComprar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_productoelegido); TextView categoria = findViewById(R.id.txvproducto); categoria.setText(getIntent().getStringExtra("categoria")); ImageView imagen = findViewById(R.id.imvImagen); imagen.setImageResource(getIntent().getIntExtra("imagen", 0)); TextView precio = findViewById(R.id.txvPrecio); precio.setText(getIntent().getStringExtra("precio")); TextView especificaciones = findViewById(R.id.txvEspecificaciones); especificaciones.setText(getIntent().getStringExtra("especificaciones")); //Obtenemos el valor de los objetos y los asignamos a las variables txvProducto = (TextView) findViewById(R.id.txvproducto); txvEspecificaciones = (TextView) findViewById(R.id.txvEspecificaciones); txvPrecio = (TextView) findViewById(R.id.txvPrecio); edtCantidad = (EditText)findViewById(R.id.edtCantidad); btnComprar = (Button)findViewById(R.id.btnComprar); //Creamos la instancia a la activity Comprar Producto btnComprar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //Indicar que se debe de llenar el campo de camtidad if (edtCantidad.getText().toString().isEmpty()){ edtCantidad.setError("Ingresar Cantidad"); return; } //Pasando valores de los campos a las variables para realizar el calculo int cantidad, precio, total; cantidad = Integer.parseInt(edtCantidad.getText().toString()); precio = Integer.parseInt(txvPrecio.getText().toString()); total = cantidad * precio; //Conexion a la activity Comprar Producto Intent comprar = new Intent(productoelegido.this, comprarProducto.class); //Enviando la informacion a la Activity Comprar Producto comprar.putExtra("producto", txvProducto.getText().toString()); comprar.putExtra("especificaciones", txvEspecificaciones.getText().toString()); comprar.putExtra("precio", "$ " + txvPrecio.getText().toString()); comprar.putExtra("cantidad", edtCantidad.getText().toString()); comprar.putExtra("total", "$ " + total); startActivity(comprar); } }); } }
38.481481
95
0.659609
8d620f310a89201b79b90329948ff8521ab5a972
860
package com.diancan.respositorys.mongo.doc; import com.diancan.domain.resto.mongo.Doc; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.mongodb.repository.DeleteQuery; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.data.mongodb.repository.Query; import java.util.List; public interface DocRepository extends MongoRepository<Doc,String> { @Query(value = "{'fileId' : {'$eq' : ?0}}") Doc findOneByFileId(String fileId); @DeleteQuery(value = "{'_id': {'$in' : ?0}}") void deleteMutipleByGivenIds(List<String> ids); @Query(value = "{$or: {filename: {$regex: ?0},{modify: {$regex: ?1}}}}") Page<Doc> findAllBy(String filename , String modify, Pageable pageable); void deleteDocByFileId(String fileId); }
33.076923
76
0.738372
061048d703a68f91d3b692fc1018b68fd2a4d441
2,607
package org.bitbucket.ioplus.clblas; /** * Created by przemek on 24/08/15. */ public class Level2 { /** * Matrix-vector product with a general rectangular matrix and float elements. * Matrix-vector products: * \( y \leftarrow \alpha A x + \beta y \) * \( y \leftarrow \alpha A^T x + \beta y \) * * @param order BlasOrder.ROW_MAJOR|COLUMN_MAJOR * @param transA How matrix A is to be transposed: BlasTrans.NO_TRANS|TRANS|CONJ_TRANS. * @param M Number of rows in matrix A. * @param N Number of columns in matrix A. * @param alpha The factor of matrix A. * @param A Buffer object storing matrix A. * @param lda Leading dimension of matrix A. It cannot be less than N if ROW_MAJOR. * @param x Buffer object storing vector x. * @param beta The factor of the vector y. * @param y Buffer object storing the vector y. **/ public static int sgemv(BlasOrder order, BlasTrans transA, int M, int N, float alpha, final float[] A, int lda, final float[] x, float beta, float[] y){ return BLAS.sgemv( order.ordinal(), transA.ordinal(), M, N, alpha, A, 0, lda, x, 0, 1, beta, y, 0, 1); } /** * vector-vector product with double elements and performs the rank 1 operation A <br> * Vector-vector products: <br> * \( A \leftarrow \alpha X Y^T + A \) * * @param order BlasOrder.ROW_MAJOR|COLUMN_MAJOR * @param M Number of rows in matrix A. * @param N Number of columns in matrix A. * @param alpha specifies the scalar alpha. * @param X Buffer object storing vector X. * @param Y Buffer object storing vector Y. * @param A Buffer object storing matrix A. On exit, A is overwritten by the updated matrix. * @param lda Leading dimension of matrix A. It cannot be less than N. **/ public static int sger(BlasOrder order, int M, int N, float alpha, final float[] X, final float[] Y, float[] A, int lda){ return BLAS.sger(BlasOrder.ROW_MAJOR.ordinal(), M, N, alpha, X, 0, 1, Y, 0, 1, A, 0, lda); } }
34.76
96
0.508631
0fcdd4d493ada51969a461c6f3bed9b9e09fb4cd
206
package me.santong.watermark.framework; /** * Created by santong. * At 16/5/20 18:14 */ public interface BaseView { void showProgress(); void hideProgress(); void showToast(String msg); }
14.714286
39
0.669903
b55591b91d27fb87cb41844d929f6a1440ca4aab
1,401
package com.akh.algorithms.sorting.practice; import static org.junit.Assert.assertArrayEquals; import java.util.Arrays; import org.junit.Test; public class SelectionSort extends AbstractSorter implements Sorter { @Override public int[] sortArray(int[] a) { for (int i = 0; i < a.length; i++) { int min = i; for (int j = i+1; j < a.length; j++) { if (a[j] < a[min]) { min = j; } } swap(a, i, min); } return a; } private void swap(int[] a, int i, int j) { int temp = a[i]; a[i] = a[j]; a[j] = temp; } @Test public void Test_101(){ int[] in = new int[] {7,1,5,3,6,4}; assertArrayEquals(new int[]{1,3,4,5,6,7}, sortArray(in)); System.out.println("Sorted Arr : "+Arrays.toString(in)); } @Test public void Test_102(){ int[] in = new int[] {}; assertArrayEquals(new int[]{}, sortArray(in)); System.out.println("Sorted Arr : "+Arrays.toString(in)); } @Test public void Test_103(){ int[] in = new int[] {200, 300, -100, -243, -453, 3, 387, 1093, 2}; int[] sorted = new int[]{200, 300, -100, -243, -453, 3, 387, 1093, 2}; Arrays.sort(sorted); assertArrayEquals(sorted, sortArray(in)); System.out.println("Sorted Arr : "+Arrays.toString(in)); } }
27.470588
78
0.528908
c71d805eb3ea71501978b7ee32e60c33eb2352fd
1,008
package org.motech.provider.repository.dao; import java.io.IOException; import org.codehaus.jackson.JsonNode; import org.codehaus.jackson.JsonParser; import org.codehaus.jackson.JsonProcessingException; import org.codehaus.jackson.ObjectCodec; import org.codehaus.jackson.map.DeserializationContext; import org.codehaus.jackson.map.JsonDeserializer; import org.motech.provider.repository.domain.MotechIdentifier; public class IdentifierDeserializer extends JsonDeserializer<MotechIdentifier> { //private Logger logger = LoggerFactory.getLogger("gates-ethiopia"); @Override public MotechIdentifier deserialize(JsonParser jsonParser, DeserializationContext arg1) throws IOException, JsonProcessingException { ObjectCodec oc = jsonParser.getCodec(); JsonNode node = oc.readTree(jsonParser); MotechIdentifier identifier = new MotechIdentifier(); identifier.setExternalId(node.get("externalId").getTextValue()); return identifier; } }
36
91
0.777778
5988d2a2fac77c9585c94c4fcb935c5e3683f05f
1,559
import java.util.Set; import java.util.LinkedHashSet; import java.util.Deque; import java.util.ArrayDeque; public class DepthFirstSearch{ public static void main(final String ... args){ final DepthFirstSearch bfs = new DepthFirstSearch(); final Node nodeA = bfs.new Node("A"); final Node nodeB = bfs.new Node("B"); final Node nodeC = bfs.new Node("C"); final Node nodeD = bfs.new Node("D"); final Node nodeE = bfs.new Node("E"); final Node nodeF = bfs.new Node("F"); nodeA.setOfChildNodes.add(nodeB); nodeA.setOfChildNodes.add(nodeF); nodeB.setOfChildNodes.add(nodeC); nodeB.setOfChildNodes.add(nodeD); nodeC.setOfChildNodes.add(nodeB); nodeC.setOfChildNodes.add(nodeA); nodeD.setOfChildNodes.add(nodeE); nodeE.setOfChildNodes.add(nodeB); depthFirstSearch(nodeA); } private class Node { private final String name; private final Set<Node> setOfChildNodes; private boolean isVisited; private Node(final String name){ this.name = name; this.setOfChildNodes = new LinkedHashSet<>(); } } private static void depthFirstSearch(final Node root){ final Deque<Node> stack = new ArrayDeque<>(); stack.push(root); while(!stack.isEmpty()){ final Node currentNode = stack.removeFirst(); System.out.format("Node %s.%n", currentNode.name); for(final Node childNode : currentNode.setOfChildNodes){ if(childNode.isVisited) continue; childNode.isVisited = true; stack.addFirst(childNode); } } } }
25.145161
60
0.676074
18dacc3eea5cf93e31bd0f452e0c0e72a9866873
1,721
/* * ****************************************************************************** * Copyright 2016-2017 Spectra Logic Corporation. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. * This file 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.spectralogic.dsbrowser.gui.util; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.stage.Modality; import javafx.stage.Stage; import javafx.stage.Window; public class Popup { public void show(final Parent parent, final String title, final Boolean resizeable, final Window window) { final Stage popup = new Stage(); popup.initOwner(window); popup.initModality(Modality.APPLICATION_MODAL); popup.setMaxWidth(1000); final Scene popupScene = new Scene(parent); popup.getIcons().add(new Image(StringConstants.DSB_ICON_PATH)); popup.setScene(popupScene); popup.setTitle(title); popup.setAlwaysOnTop(false); popup.setResizable(true); popup.showAndWait(); } public void show(final Parent parent, final String title, final Window window) { show(parent, title, false, window); } }
37.413043
110
0.638582
a2e135e5f92afe59adfab5c50de9aea399deb2d2
34,198
package com.ca.apim.gateway.cagatewayexport.util.policy; import com.ca.apim.gateway.cagatewayconfig.beans.*; import com.ca.apim.gateway.cagatewayconfig.util.IdGenerator; import com.ca.apim.gateway.cagatewayconfig.util.injection.InjectionRegistry; import com.ca.apim.gateway.cagatewayconfig.util.policy.PolicyXMLElements; import com.ca.apim.gateway.cagatewayconfig.util.xml.DocumentParseException; import com.ca.apim.gateway.cagatewayconfig.util.xml.DocumentTools; import com.ca.apim.gateway.cagatewayexport.tasks.explode.linker.LinkerException; import org.apache.commons.codec.binary.Base64; import org.jetbrains.annotations.NotNull; import org.junit.jupiter.api.Test; import org.testcontainers.shaded.com.google.common.collect.ImmutableMap; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import static com.ca.apim.gateway.cagatewayconfig.beans.Folder.ROOT_FOLDER; import static com.ca.apim.gateway.cagatewayconfig.beans.Folder.ROOT_FOLDER_ID; import static com.ca.apim.gateway.cagatewayconfig.beans.IdentityProvider.INTERNAL_IDP_ID; import static com.ca.apim.gateway.cagatewayconfig.beans.IdentityProvider.INTERNAL_IDP_NAME; import static com.ca.apim.gateway.cagatewayconfig.util.policy.PolicyXMLElements.*; import static com.ca.apim.gateway.cagatewayconfig.util.xml.DocumentUtils.*; import static org.apache.commons.codec.binary.Base64.encodeBase64String; import static org.junit.jupiter.api.Assertions.*; class PolicyXMLSimplifierTest { @Test void simplifySetVariable() throws DocumentParseException { Element setVariableAssertion = createSetVariableAssertionElement("my-var", "dGVzdGluZyBzaW1wbGlmeSBzZXQgdmFyaWFibGUgYXNzZXJ0aW9u"); String policyName = "policyName"; Bundle resultantBundle = new Bundle(); new SetVariableAssertionSimplifier() .simplifyAssertionElement( new PolicySimplifierContext( policyName, null, resultantBundle) .withAssertionElement(setVariableAssertion) ); Element expressionElement = getSingleElement(setVariableAssertion, EXPRESSION); assertEquals("testing simplify set variable assertion", expressionElement.getFirstChild().getTextContent()); NodeList base64ElementNodes = setVariableAssertion.getElementsByTagName(BASE_64_EXPRESSION); assertEquals(0, base64ElementNodes.getLength()); } @Test void simplifySetVariableInvalid() { Element setVariableAssertion = createSetVariableAssertionElement("ENV.gateway.test", Base64.encodeBase64String("test".getBytes())); String policyName = "policyName"; Bundle resultantBundle = new Bundle(); assertThrows(LinkerException.class, () -> new SetVariableAssertionSimplifier() .simplifyAssertionElement( new PolicySimplifierContext( policyName, null, resultantBundle) .withAssertionElement(setVariableAssertion) )); } @Test void simplifySetVariableExisting() { Element setVariableAssertion = createSetVariableAssertionElement("ENV.test", Base64.encodeBase64String("test".getBytes())); Bundle resultantBundle = new Bundle(); String policyName = "policyName"; ContextVariableEnvironmentProperty property = new ContextVariableEnvironmentProperty(policyName + ".test", "test"); resultantBundle.getContextVariableEnvironmentProperties().put(property.getName(), property); assertThrows(LinkerException.class, () -> new SetVariableAssertionSimplifier() .simplifyAssertionElement( new PolicySimplifierContext( policyName, null, resultantBundle) .withAssertionElement(setVariableAssertion) )); } @Test void simplifySetVariableWithBadEndingUnit() throws DocumentParseException { //The default Base64 decoder in java cannot decode this, but the commons-codec decoder can. Element setVariableAssertion = createSetVariableAssertionElement("my-var2", "ew0KICAgICAgICAgICAgICAgICJlcnJvciI6ImludmFsaWRfbWV0aG9kIiwNCiAgICAgICAgICAgICAgICAiZXJyb3JfZGVzY3JpcHRpb24iOiIke3JlcXVlc3QuaHR0cC5tZXRob2R9IG5vdCBwZXJtaXR0ZWQiDQogICAgICAgICAgICAgICAgfQ="); String policyName = "policyName"; Bundle resultantBundle = new Bundle(); new SetVariableAssertionSimplifier() .simplifyAssertionElement( new PolicySimplifierContext( policyName, null, resultantBundle) .withAssertionElement(setVariableAssertion) ); Element expressionElement = getSingleElement(setVariableAssertion, EXPRESSION); assertEquals( "{\r\n" + " &quot;error&quot;:&quot;invalid_method&quot;,\r\n" + " &quot;error_description&quot;:&quot;${request.http.method} not permitted&quot;\r\n" + " }", expressionElement.getFirstChild().getTextContent()); NodeList base64ElementNodes = setVariableAssertion.getElementsByTagName(BASE_64_EXPRESSION); assertEquals(0, base64ElementNodes.getLength()); } @Test void simplifySetVariableWithXMLContent() throws DocumentParseException { //The default Base64 decoder in java cannot decode this, but the commons-codec decoder can. Element setVariableAssertion = createSetVariableAssertionElement("userSession", "PHVzZXJzZXNzaW9uPgogPHVzZXI+PCFbQ0RBVEFbJHtjdXJyZW50LnVzZXJuYW1lfV1dPjwvdXNlcj4KIDxyb2xlPjwhW0NEQVRBWyR7Y3VycmVudC51c2VyLnJvbGV9XV0+PC9yb2xlPgogPGxvb2t1cFVzZXI+PCFbQ0RBVEFbJHtsb29rdXBVc2VyfV1dPjwvbG9va3VwVXNlcj4KIDxzeW5jaFRva2VuPjwhW0NEQVRBWyR7eHBhdGhTeW5jaFRva2VuLnJlc3VsdH1dXT48L3N5bmNoVG9rZW4+CjwvdXNlcnNlc3Npb24+"); String policyName = "policyName"; Bundle resultantBundle = new Bundle(); new SetVariableAssertionSimplifier() .simplifyAssertionElement( new PolicySimplifierContext( policyName, null, resultantBundle) .withAssertionElement(setVariableAssertion) ); Element expressionElement = getSingleElement(setVariableAssertion, EXPRESSION); assertEquals( "&lt;usersession&gt;\n" + " &lt;user&gt;&lt;![CDATA[${current.username}]]&gt;&lt;/user&gt;\n" + " &lt;role&gt;&lt;![CDATA[${current.user.role}]]&gt;&lt;/role&gt;\n" + " &lt;lookupUser&gt;&lt;![CDATA[${lookupUser}]]&gt;&lt;/lookupUser&gt;\n" + " &lt;synchToken&gt;&lt;![CDATA[${xpathSynchToken.result}]]&gt;&lt;/synchToken&gt;\n" + "&lt;/usersession&gt;", expressionElement.getFirstChild().getTextContent()); NodeList base64ElementNodes = setVariableAssertion.getElementsByTagName(BASE_64_EXPRESSION); assertEquals(0, base64ElementNodes.getLength()); } @Test void simplifyAuthenticationAssertion() throws DocumentParseException { String id = new IdGenerator().generate(); String testName = "test"; IdentityProvider identityProvider = new IdentityProvider.Builder() .id(id) .name(testName) .build(); Bundle bundle = new Bundle(); bundle.addEntity(identityProvider); Element authenticationAssertion = createAuthenticationAssertionElement(id); new AuthenticationAssertionSimplifier() .simplifyAssertionElement( new PolicySimplifierContext( "policy", bundle, null) .withAssertionElement(authenticationAssertion) ); assertEquals(testName, getSingleChildElementAttribute(authenticationAssertion, ID_PROV_NAME, STRING_VALUE)); assertNull(getSingleChildElement(authenticationAssertion, ID_PROV_OID, true)); } @Test void simplifyAuthenticationAssertionToInternalIDP() throws DocumentParseException { Element authenticationAssertion = createAuthenticationAssertionElement(INTERNAL_IDP_ID); new AuthenticationAssertionSimplifier() .simplifyAssertionElement( new PolicySimplifierContext( "policy", new Bundle(), null) .withAssertionElement(authenticationAssertion) ); assertEquals(INTERNAL_IDP_NAME, getSingleChildElementAttribute(authenticationAssertion, ID_PROV_NAME, STRING_VALUE)); assertNull(getSingleChildElement(authenticationAssertion, ID_PROV_OID, true)); } @Test void simplifyAuthenticationAssertionToMissingIDP() throws DocumentParseException { String id = new IdGenerator().generate(); Element authenticationAssertion = createAuthenticationAssertionElement(id); new AuthenticationAssertionSimplifier() .simplifyAssertionElement( new PolicySimplifierContext( "policy", new Bundle(), null) .withAssertionElement(authenticationAssertion) ); assertEquals(id, getSingleChildElementAttribute(authenticationAssertion, ID_PROV_OID, GOID_VALUE)); assertNull(getSingleChildElement(authenticationAssertion, ID_PROV_NAME, true)); } @Test void simplifySpecificUserAssertion() throws DocumentParseException { String id = new IdGenerator().generate(); String testName = "test"; IdentityProvider identityProvider = new IdentityProvider.Builder() .id(id) .name(testName) .build(); Bundle bundle = new Bundle(); bundle.addEntity(identityProvider); Element authenticationAssertion = createSpecificUserAssertionElement(id); new SpecificUserAssertionSimplifier() .simplifyAssertionElement( new PolicySimplifierContext( "policy", bundle, null) .withAssertionElement(authenticationAssertion) ); assertEquals(testName, getSingleChildElementAttribute(authenticationAssertion, ID_PROV_NAME, STRING_VALUE)); assertNull(getSingleChildElement(authenticationAssertion, ID_PROV_OID, true)); } @Test void simplifySpecificUserAssertionToInternalIDP() throws DocumentParseException { Element authenticationAssertion = createSpecificUserAssertionElement(INTERNAL_IDP_ID); new AuthenticationAssertionSimplifier() .simplifyAssertionElement( new PolicySimplifierContext( "policy", new Bundle(), null) .withAssertionElement(authenticationAssertion) ); assertEquals(INTERNAL_IDP_NAME, getSingleChildElementAttribute(authenticationAssertion, ID_PROV_NAME, STRING_VALUE)); assertNull(getSingleChildElement(authenticationAssertion, ID_PROV_OID, true)); } @Test void simplifySpecificUserAssertionToMissingIDP() throws DocumentParseException { String id = new IdGenerator().generate(); Element authenticationAssertion = createSpecificUserAssertionElement(id); new AuthenticationAssertionSimplifier() .simplifyAssertionElement( new PolicySimplifierContext( "policy", new Bundle(), null) .withAssertionElement(authenticationAssertion) ); assertEquals(id, getSingleChildElementAttribute(authenticationAssertion, ID_PROV_OID, GOID_VALUE)); assertNull(getSingleChildElement(authenticationAssertion, ID_PROV_NAME, true)); } @Test void simplifyJmsRoutingAssertion() throws DocumentParseException { String id = new IdGenerator().generate(); String name = "jms-test"; JmsDestination jmsDestination = new JmsDestination.Builder() .id(id) .name(name) .build(); Bundle bundle = new Bundle(); bundle.addEntity(jmsDestination); Element jmsRoutingAssertionEle = createJmsRoutingAssertion(id, name); new JmsRoutingAssertionSimplifier() .simplifyAssertionElement( new PolicySimplifierContext( "policy", bundle, null) .withAssertionElement(jmsRoutingAssertionEle) ); assertEquals(name, getSingleChildElementAttribute(jmsRoutingAssertionEle, JMS_ENDPOINT_NAME, STRING_VALUE)); assertNull(getSingleChildElement(jmsRoutingAssertionEle, JMS_ENDPOINT_OID, true)); } @Test void simplifyJmsRoutingAssertionMissingJmsDestination() throws DocumentParseException { String id = new IdGenerator().generate(); String name = "jms-test"; Element jmsRoutingAssertionEle = createJmsRoutingAssertion(id, name); new JmsRoutingAssertionSimplifier() .simplifyAssertionElement( new PolicySimplifierContext( "policy", new Bundle(), null) .withAssertionElement(jmsRoutingAssertionEle) ); assertEquals(name, getSingleChildElementAttribute(jmsRoutingAssertionEle, JMS_ENDPOINT_NAME, STRING_VALUE)); assertNull(getSingleChildElement(jmsRoutingAssertionEle, JMS_ENDPOINT_OID, true)); } @Test void simplifyIncludeAssertion() throws DocumentParseException { String id = new IdGenerator().generate(); String testName = "test"; Policy policy = new Policy.Builder() .setGuid(id) .setName(testName) .setParentFolderId(ROOT_FOLDER_ID) .build(); Bundle bundle = new Bundle(); bundle.addEntity(policy); bundle.addEntity(ROOT_FOLDER); FolderTree folderTree = new FolderTree(bundle.getEntities(Folder.class).values()); bundle.setFolderTree(folderTree); Bundle resultantBundle = new Bundle(); resultantBundle.addEntity(policy); Element includeAssertion = createIncludeAssertionElement(DocumentTools.INSTANCE.getDocumentBuilder().newDocument(), id); new IncludeAssertionSimplifier() .simplifyAssertionElement( new PolicySimplifierContext( testName, bundle, resultantBundle) .withAssertionElement(includeAssertion) ); assertEquals(testName, getSingleChildElementAttribute(includeAssertion, POLICY_GUID, "policyPath")); assertNull(getSingleChildElementAttribute(includeAssertion, POLICY_GUID, STRING_VALUE)); assertTrue(resultantBundle.getMissingEntities().isEmpty()); } @Test void simplifyIncludeAssertionMissingPolicy() throws DocumentParseException { String id = new IdGenerator().generate(); String testName = "test"; Bundle bundle = new Bundle(); Bundle resultantBundle = new Bundle(); bundle.addEntity(ROOT_FOLDER); FolderTree folderTree = new FolderTree(bundle.getEntities(Folder.class).values()); bundle.setFolderTree(folderTree); Element includeAssertion = createIncludeAssertionElement(DocumentTools.INSTANCE.getDocumentBuilder().newDocument(), id); new IncludeAssertionSimplifier() .simplifyAssertionElement( new PolicySimplifierContext( "policy", bundle, resultantBundle) .withAssertionElement(includeAssertion) ); assertNotEquals(testName, getSingleChildElementAttribute(includeAssertion, POLICY_GUID, "policyPath")); assertNull(getSingleChildElementAttribute(includeAssertion, POLICY_GUID, STRING_VALUE)); assertTrue(getSingleChildElementAttribute(includeAssertion, POLICY_GUID, "policyPath").startsWith("Policy#")); assertFalse(resultantBundle.getMissingEntities().isEmpty()); } @Test void simplifyIncludeAssertionMissingPolicyInResultantBundleOnly() throws DocumentParseException { String id = new IdGenerator().generate(); String testName = "test"; Policy policy = new Policy.Builder() .setGuid(id) .setName(testName) .setParentFolderId(ROOT_FOLDER_ID) .build(); Bundle bundle = new Bundle(); Bundle resultantBundle = new Bundle(); bundle.addEntity(ROOT_FOLDER); FolderTree folderTree = new FolderTree(bundle.getEntities(Folder.class).values()); bundle.setFolderTree(folderTree); bundle.addEntity(policy); Element includeAssertion = createIncludeAssertionElement(DocumentTools.INSTANCE.getDocumentBuilder().newDocument(), id); new IncludeAssertionSimplifier() .simplifyAssertionElement( new PolicySimplifierContext( "policy", bundle, resultantBundle) .withAssertionElement(includeAssertion) ); assertEquals(testName, getSingleChildElementAttribute(includeAssertion, POLICY_GUID, "policyPath")); assertNull(getSingleChildElementAttribute(includeAssertion, POLICY_GUID, STRING_VALUE)); assertFalse(resultantBundle.getMissingEntities().isEmpty()); assertNotNull(resultantBundle.getMissingEntities().get(policy.getId())); } @Test void simplifyPolicy() { String policyID = new IdGenerator().generate(); String testName = "test"; Policy policy = new Policy.Builder() .setGuid(policyID) .setName(testName) .setParentFolderId(ROOT_FOLDER_ID) .build(); Bundle bundle = new Bundle(); bundle.addEntity(policy); bundle.addEntity(ROOT_FOLDER); FolderTree folderTree = new FolderTree(bundle.getEntities(Folder.class).values()); bundle.setFolderTree(folderTree); Document document = DocumentTools.INSTANCE.getDocumentBuilder().newDocument(); Element policyXML = createElementWithChildren( document, "wsp:Policy", createIncludeAssertionElement(document, policyID) ); InjectionRegistry.getInstance(PolicyXMLSimplifier.class).simplifyPolicyXML(policyXML, policy.getName(), bundle, bundle); } @Test void simplifyHardcodedResponse() { Element hardcodedResponse = createHardcodedResponse(true); new HardcodedResponseAssertionSimplifier() .simplifyAssertionElement( new PolicySimplifierContext( "policy", null, null) .withAssertionElement(hardcodedResponse) ); assertEquals("Test", getSingleChildElementTextContent(hardcodedResponse, RESPONSE_BODY)); } @Test void simplifyHardcodedResponseNoBody() { Element hardcodedResponse = createHardcodedResponse(false); new HardcodedResponseAssertionSimplifier() .simplifyAssertionElement( new PolicySimplifierContext( "policy", null, null) .withAssertionElement(hardcodedResponse) ); assertNull(getSingleChildElementTextContent(hardcodedResponse, RESPONSE_BODY)); } @Test void simplifyEncapsulatedAssertion() throws DocumentParseException { Element encapsulatedAssertion = createEncapsulatedAssertion(); Bundle bundle = new Bundle(); Bundle resultantBundle = new Bundle(); Encass encass = new Encass(); encass.setGuid("Test Guid"); encass.setName("Test Name"); encass.setPolicyId("Policy"); Policy policy = new Policy(); policy.setId("Policy"); bundle.getEncasses().put(encass.getGuid(), encass); bundle.getPolicies().put(policy.getId(), policy); resultantBundle.getEncasses().put(encass.getGuid(), encass); resultantBundle.getPolicies().put(policy.getId(), policy); new EncapsulatedAssertionSimplifier() .simplifyAssertionElement( new PolicySimplifierContext( "Policy", bundle, resultantBundle) .withAssertionElement(encapsulatedAssertion) ); assertEquals("Test Name", encapsulatedAssertion.getAttribute("encassName")); assertNull(getSingleChildElement(encapsulatedAssertion, ENCAPSULATED_ASSERTION_CONFIG_NAME, true)); assertNull(getSingleChildElement(encapsulatedAssertion, ENCAPSULATED_ASSERTION_CONFIG_GUID, true)); assertTrue(resultantBundle.getMissingEntities().isEmpty()); } @Test void simplifyEncapsulatedAssertionMissingPolicy() throws DocumentParseException { Element encapsulatedAssertion = createEncapsulatedAssertion(); Bundle bundle = new Bundle(); Bundle resultantBundle = new Bundle(); Encass encass = new Encass(); encass.setGuid("Test Guid"); encass.setName("Test Name"); encass.setPolicyId("Policy"); bundle.getEncasses().put(encass.getGuid(), encass); resultantBundle.getEncasses().put(encass.getGuid(), encass); new EncapsulatedAssertionSimplifier() .simplifyAssertionElement( new PolicySimplifierContext( "Policy", bundle, resultantBundle) .withAssertionElement(encapsulatedAssertion) ); assertEquals("Test Name", encapsulatedAssertion.getAttribute("encassName")); assertNull(getSingleChildElement(encapsulatedAssertion, ENCAPSULATED_ASSERTION_CONFIG_NAME, true)); assertNull(getSingleChildElement(encapsulatedAssertion, ENCAPSULATED_ASSERTION_CONFIG_GUID, true)); assertNotNull(resultantBundle.getMissingEntities().get("Test Guid")); } @Test void simplifyEncapsulatedAssertionMissingEncass() throws DocumentParseException { Element encapsulatedAssertion = createEncapsulatedAssertion(); Bundle bundle = new Bundle(); Bundle resultantBundle = new Bundle(); new EncapsulatedAssertionSimplifier() .simplifyAssertionElement( new PolicySimplifierContext( "Policy", bundle, resultantBundle) .withAssertionElement(encapsulatedAssertion) ); assertEquals("Test Name", encapsulatedAssertion.getAttribute("encassName")); assertNull(getSingleChildElement(encapsulatedAssertion, ENCAPSULATED_ASSERTION_CONFIG_NAME, true)); assertNull(getSingleChildElement(encapsulatedAssertion, ENCAPSULATED_ASSERTION_CONFIG_GUID, true)); assertNotNull(resultantBundle.getMissingEntities().get("Test Guid")); } @Test void simplifyHttpRoutingAssertionForTrustedCert() throws DocumentParseException { final IdGenerator idGenerator = new IdGenerator(); Element httpRoutingAssertionElement = createHttpRoutingAssertionWithCerts(idGenerator); new HttpRoutingAssertionSimplifier() .simplifyAssertionElement( new PolicySimplifierContext( "policy", null, null) .withAssertionElement(httpRoutingAssertionElement) ); final Element trustedCertNameElement = getSingleChildElement(httpRoutingAssertionElement, TLS_TRUSTED_CERT_NAMES, true); assertNotNull(trustedCertNameElement); assertEquals(2, trustedCertNameElement.getChildNodes().getLength()); assertEquals("fake-cert-1", trustedCertNameElement.getChildNodes().item(0).getAttributes().getNamedItem(STRING_VALUE).getTextContent()); assertEquals("fake-cert-2", trustedCertNameElement.getChildNodes().item(1).getAttributes().getNamedItem(STRING_VALUE).getTextContent()); assertNull(getSingleChildElement(httpRoutingAssertionElement, TLS_TRUSTED_CERT_IDS, true)); } @Test void simplifyHttp2RoutingAssertionForClientConfig() throws DocumentParseException { final IdGenerator idGenerator = new IdGenerator(); Element http2RoutingAssertionElement = createHttp2RoutingAssertionWithClientConfig(idGenerator); new Http2AssertionSimplifier() .simplifyAssertionElement( new PolicySimplifierContext( "policy", null, null) .withAssertionElement(http2RoutingAssertionElement) ); final Element http2ClientConfigNameElement = getSingleChildElement(http2RoutingAssertionElement, HTTP2_CLIENT_CONFIG_NAME, true); assertNotNull(http2ClientConfigNameElement); assertEquals("http2client", http2ClientConfigNameElement.getAttributes().getNamedItem(STRING_VALUE).getTextContent()); assertNull(getSingleChildElement(http2RoutingAssertionElement, HTTP2_CLIENT_CONFIG_GOID, true)); } @Test void simplifyMqRoutingAssertion() throws DocumentParseException { final IdGenerator idGenerator = new IdGenerator(); Element mqRoutingAssertionElement = createMqRoutingAssertion(idGenerator); new MQRoutingAssertionSimplifier() .simplifyAssertionElement( new PolicySimplifierContext( "policy", null, null) .withAssertionElement(mqRoutingAssertionElement) ); assertNull(getSingleChildElement(mqRoutingAssertionElement, ACTIVE_CONNECTOR_GOID, true)); assertNull(getSingleChildElement(mqRoutingAssertionElement, ACTIVE_CONNECTOR_ID, true)); } @NotNull private Element createMqRoutingAssertion(final IdGenerator idGenerator) { Document document = DocumentTools.INSTANCE.getDocumentBuilder().newDocument(); Element activeConnectorGoidElement = createElementWithAttributes( document, ACTIVE_CONNECTOR_GOID, ImmutableMap.of(GOID_VALUE, idGenerator.generate()) ); Element activeConnectorIdElement = createElementWithAttributes( document, ACTIVE_CONNECTOR_ID, ImmutableMap.of(GOID_VALUE, idGenerator.generate()) ); return createElementWithChildren( document, MQ_ROUTING_ASSERTION, activeConnectorGoidElement, activeConnectorIdElement ); } @NotNull private Element createHttpRoutingAssertionWithCerts(final IdGenerator idGenerator) { Document document = DocumentTools.INSTANCE.getDocumentBuilder().newDocument(); Element trustedCertGoidsElement = createElementWithAttributesAndChildren( document, TLS_TRUSTED_CERT_IDS, ImmutableMap.of(GOID_ARRAY_VALUE, "included"), createElementWithAttribute(document, PolicyXMLElements.ITEM, GOID_VALUE, idGenerator.generate()), createElementWithAttribute(document, PolicyXMLElements.ITEM, GOID_VALUE, idGenerator.generate()) ); Element trustedCertNamesElement = createElementWithAttributesAndChildren( document, TLS_TRUSTED_CERT_NAMES, ImmutableMap.of("stringArrayValue", "included"), createElementWithAttribute(document, PolicyXMLElements.ITEM, STRING_VALUE, "fake-cert-1"), createElementWithAttribute(document, PolicyXMLElements.ITEM, STRING_VALUE, "fake-cert-2") ); return createElementWithChildren( document, HTTP_ROUTING_ASSERTION, trustedCertGoidsElement, trustedCertNamesElement ); } @NotNull private Element createHttp2RoutingAssertionWithClientConfig(final IdGenerator idGenerator) { Document document = DocumentTools.INSTANCE.getDocumentBuilder().newDocument(); return createElementWithChildren( document, HTTP2_ROUTING_ASSERTION, createElementWithAttribute(document, "L7p:ProtectedServiceUrl", STRING_VALUE, "http://apim-hugh-new.lvn.broadcom.net:90"), createElementWithAttribute(document, HTTP2_CLIENT_CONFIG_NAME, STRING_VALUE, "http2client"), createElementWithAttribute(document, HTTP2_CLIENT_CONFIG_GOID, STRING_VALUE, idGenerator.generate()) ); } @NotNull private Element createSetVariableAssertionElement(String variableName, String base64Data) { Document document = DocumentTools.INSTANCE.getDocumentBuilder().newDocument(); Element setVariableAssertion = document.createElement(SET_VARIABLE); document.appendChild(setVariableAssertion); Element base64Element = document.createElement(BASE_64_EXPRESSION); setVariableAssertion.appendChild(base64Element); base64Element.setAttribute(STRING_VALUE, base64Data); Element variableToSetElement = document.createElement(VARIABLE_TO_SET); setVariableAssertion.appendChild(variableToSetElement); variableToSetElement.setAttribute(STRING_VALUE, variableName); return setVariableAssertion; } @NotNull private Element createAuthenticationAssertionElement(String id) { Document document = DocumentTools.INSTANCE.getDocumentBuilder().newDocument(); return createElementWithChildren( document, AUTHENTICATION, createElementWithAttribute(document, ID_PROV_OID, GOID_VALUE, id), createElementWithAttribute(document, TARGET, "target", "RESPONSE") ); } @NotNull private Element createSpecificUserAssertionElement(String id) { Document document = DocumentTools.INSTANCE.getDocumentBuilder().newDocument(); return createElementWithChildren( document, AUTHENTICATION, createElementWithAttribute(document, ID_PROV_OID, GOID_VALUE, id), createElementWithAttribute(document, TARGET, "target", "RESPONSE") ); } @NotNull private Element createJmsRoutingAssertion(String id, String name) { Document document = DocumentTools.INSTANCE.getDocumentBuilder().newDocument(); return createElementWithChildren( document, JMS_ROUTING_ASSERTION, createElementWithAttribute(document, JMS_ENDPOINT_OID, GOID_VALUE, id), createElementWithAttribute(document, JMS_ENDPOINT_NAME, STRING_VALUE, name) ); } private Element createIncludeAssertionElement(Document document, String id) { return createElementWithChildren( document, INCLUDE, createElementWithAttribute(document, POLICY_GUID, STRING_VALUE, id) ); } private Element createHardcodedResponse(boolean body) { Document document = DocumentTools.INSTANCE.getDocumentBuilder().newDocument(); String base64 = encodeBase64String("Test".getBytes()); Element element = createElementWithChildren( document, HARDCODED_RESPONSE ); if (body) { element.appendChild(createElementWithAttribute(document, BASE_64_RESPONSE_BODY, STRING_VALUE, base64)); } return element; } private Element createEncapsulatedAssertion() { Document document = DocumentTools.INSTANCE.getDocumentBuilder().newDocument(); return createElementWithChildren( document, ENCAPSULATED, createElementWithAttribute(document, ENCAPSULATED_ASSERTION_CONFIG_GUID, STRING_VALUE, "Test Guid"), createElementWithAttribute(document, ENCAPSULATED_ASSERTION_CONFIG_NAME, STRING_VALUE, "Test Name") ); } }
47.497222
408
0.635797
3d9de158c15ae822e979e9b2c611399f909e469b
591
package com.android.AshenAndroid.server; import org.json.JSONObject; import java.nio.charset.Charset; import java.util.Map; public interface HTTPResponse { HTTPResponse setStatus(int status); HTTPResponse setContentType(String mimeType); HTTPResponse setContent(byte[] data); HTTPResponse setContent(JSONObject message); HTTPResponse setContent(Map<String,Object> message); HTTPResponse setEncoding(Charset charset); HTTPResponse sendRedirect(String to); HTTPResponse sendTemporaryRedirect(String to); void end(); boolean isClosed(); }
18.46875
56
0.751269
15d7fa0dac54a991a6a6473c6e0b1c12612fe860
210
package br.com.estacionamento.model; import br.com.estacionamento.commons.RepositoryBaseImpl; public class CartaoCreditoRepositoryImpl extends RepositoryBaseImpl implements CartaoCreditoRepositoryCustom { }
26.25
110
0.871429
515f1bf000dce8421f2015e4ccdd53142f31f14d
14,908
package com.leo.font.lib.compiler; import com.leo.font.lib.annotations.AutoScale; import com.leo.font.lib.compiler.NameStore; import com.leo.font.lib.compiler.ProcessingUtils; import com.mindorks.lib.annotations.BindView; import com.leo.font.lib.annotations.IgnoreScale; import com.leo.font.lib.annotations.Keep; import com.mindorks.lib.annotations.OnClick; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.JavaFile; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.TypeSpec; import java.io.IOException; import java.util.Arrays; import java.util.Set; import java.util.TreeSet; import javax.annotation.processing.AbstractProcessor; import javax.annotation.processing.Filer; import javax.annotation.processing.Messager; import javax.annotation.processing.ProcessingEnvironment; import javax.annotation.processing.RoundEnvironment; import javax.lang.model.element.Element; import javax.lang.model.element.ElementKind; import javax.lang.model.element.Modifier; import javax.lang.model.element.NestingKind; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.util.ElementFilter; import javax.lang.model.util.Elements; import javax.tools.Diagnostic; public class Processor extends AbstractProcessor { private Filer filer; private Messager messager; private Elements elementUtils; @Override public synchronized void init(ProcessingEnvironment processingEnv) { super.init(processingEnv); filer = processingEnv.getFiler(); messager = processingEnv.getMessager(); elementUtils = processingEnv.getElementUtils(); } /* * annotations: list of unique annotations that are getting processed */ @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { if (!roundEnv.processingOver()) { // find all the classes that uses the supported annotations Set<TypeElement> typeElements = ProcessingUtils.getTypeElementsToProcess( roundEnv.getRootElements(), annotations); // for each such class create a wrapper class for binding for (TypeElement typeElement : typeElements) { String packageName = elementUtils.getPackageOf(typeElement).getQualifiedName().toString(); String typeNameContainer = getParentChainType(typeElement); String typeName = getParentChain(typeElement); ClassName className = ClassName.get(packageName, typeNameContainer); ClassName generatedClassName = ClassName .get(packageName, NameStore.getGeneratedClassName(typeName)); // define the wrapper class TypeSpec.Builder classBuilder = TypeSpec.classBuilder(generatedClassName) .addModifiers(Modifier.PUBLIC) .addAnnotation(Keep.class); // add constructor classBuilder.addMethod(MethodSpec.constructorBuilder() .addModifiers(Modifier.PUBLIC) .addParameter(className, NameStore.Variable.CONTAINER) .addStatement("$N($N)", NameStore.Method.BIND_FONTS, NameStore.Variable.CONTAINER) // .addStatement("$N($N)", // NameStore.Method.BIND_ON_CLICKS, // NameStore.Variable.CONTAINER) .build()); // add method that maps the views with id MethodSpec.Builder bindViewsMethodBuilder = MethodSpec .methodBuilder(NameStore.Method.BIND_FONTS) .addModifiers(Modifier.PRIVATE) .returns(void.class) .addParameter(className, NameStore.Variable.CONTAINER); /* for (VariableElement variableElement : ElementFilter.fieldsIn(typeElement.getEnclosedElements())) { BindView bindView = variableElement.getAnnotation(BindView.class); if (bindView != null) { bindViewsMethodBuilder.addStatement("$N.$N = ($T)$N.findViewById($L)", NameStore.Variable.CONTAINER, variableElement.getSimpleName(), variableElement, NameStore.Variable.CONTAINER, bindView.value()); } }*/ ClassName fontManagerClassName = ClassName.get( NameStore.Package.FONT_MANAGER, NameStore.Class.FONT_MANAGER); for (VariableElement variableElement : ElementFilter.fieldsIn(typeElement.getEnclosedElements())) { AutoScale fontAutoScale = variableElement.getAnnotation(AutoScale.class); if (fontAutoScale != null) { if (fontAutoScale.isScale()) bindViewsMethodBuilder.addStatement("$T.applyScaleFont($N.$N)", fontManagerClassName, NameStore.Variable.CONTAINER, variableElement.getSimpleName()); } IgnoreScale fontIgnoreScale = variableElement.getAnnotation(IgnoreScale.class); if (fontIgnoreScale != null) { if (fontIgnoreScale.isIgnoreScale()) bindViewsMethodBuilder.addStatement("$T.applyScaleDownFont($N.$N)", fontManagerClassName, NameStore.Variable.CONTAINER, variableElement.getSimpleName()); } } classBuilder.addMethod(bindViewsMethodBuilder.build()); /* // add method that attaches the onClickListeners ClassName androidOnClickListenerClassName = ClassName.get( NameStore.Package.ANDROID_VIEW, NameStore.Class.ANDROID_VIEW, NameStore.Class.ANDROID_VIEW_ON_CLICK_LISTENER); ClassName androidViewClassName = ClassName.get( NameStore.Package.ANDROID_VIEW, NameStore.Class.ANDROID_VIEW); MethodSpec.Builder bindOnClicksMethodBuilder = MethodSpec .methodBuilder(NameStore.Method.BIND_ON_CLICKS) .addModifiers(Modifier.PRIVATE) .returns(void.class) .addParameter(className, NameStore.Variable.CONTAINER, Modifier.FINAL); for (ExecutableElement executableElement : ElementFilter.methodsIn(typeElement.getEnclosedElements())) { OnClick onClick = executableElement.getAnnotation(OnClick.class); if (onClick != null) { TypeSpec OnClickListenerClass = TypeSpec.anonymousClassBuilder("") .addSuperinterface(androidOnClickListenerClassName) .addMethod(MethodSpec.methodBuilder(NameStore.Method.ANDROID_VIEW_ON_CLICK) .addModifiers(Modifier.PUBLIC) .addParameter(androidViewClassName, NameStore.Variable.ANDROID_VIEW) .addStatement("$N.$N($N)", NameStore.Variable.CONTAINER, executableElement.getSimpleName(), NameStore.Variable.ANDROID_VIEW) .returns(void.class) .build()) .build(); bindOnClicksMethodBuilder.addStatement("$N.findViewById($L).setOnClickListener($L)", NameStore.Variable.CONTAINER, onClick.value(), OnClickListenerClass); } } classBuilder.addMethod(bindOnClicksMethodBuilder.build()); */ // write the defines class to a java file try { JavaFile.builder(packageName, classBuilder.build()) .build() .writeTo(filer); } catch (IOException e) { messager.printMessage(Diagnostic.Kind.ERROR, e.toString(), typeElement); } } } return true; } /* @Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { if (!roundEnv.processingOver()) { // find all the classes that uses the supported annotations Set<TypeElement> typeElements = ProcessingUtils.getTypeElementsToProcess( roundEnv.getRootElements(), annotations); // for each such class create a wrapper class for binding for (TypeElement typeElement : typeElements) { //String parentClass = getParentChain(typeElement); String packageName = elementUtils.getPackageOf(typeElement).getQualifiedName().toString(); String typeName = getParentChain(typeElement); String typeNameContainer = getParentChainType(typeElement); ClassName className = ClassName.get(packageName, typeNameContainer); messager.printMessage(Diagnostic.Kind.ERROR, className.toString(), typeElement); ClassName generatedClassName = ClassName .get(packageName, NameStore.getGeneratedClassName(typeName)); // define the wrapper class TypeSpec.Builder classBuilder = TypeSpec.classBuilder(generatedClassName) .addModifiers(Modifier.PUBLIC) .addAnnotation(Keep.class); // add constructor classBuilder.addMethod(MethodSpec.constructorBuilder() .addModifiers(Modifier.PUBLIC) .addParameter(className, NameStore.Variable.CONTAINER) .addStatement("$N($N)", NameStore.Method.BIND_FONTS, NameStore.Variable.CONTAINER) .build()); ClassName fontManagerClassName = ClassName.get( NameStore.Package.FONT_MANAGER, NameStore.Class.FONT_MANAGER); // add method that maps the views with id MethodSpec.Builder bindViewsMethodBuilder = MethodSpec .methodBuilder(NameStore.Method.BIND_FONTS) .addModifiers(Modifier.PRIVATE) .returns(void.class) .addParameter(className, NameStore.Variable.CONTAINER); for (VariableElement variableElement : ElementFilter.fieldsIn(typeElement.getEnclosedElements())) { AutoScale fontAutoScale = variableElement.getAnnotation(AutoScale.class); if (fontAutoScale != null) { if (fontAutoScale.isScale()) bindViewsMethodBuilder.addStatement("$T.applyScaleFont($N.$N)", fontManagerClassName, NameStore.Variable.CONTAINER, variableElement.getSimpleName()); } IgnoreScale fontIgnoreScale = variableElement.getAnnotation(IgnoreScale.class); if (fontIgnoreScale != null) { if (fontIgnoreScale.isIgnoreScale()) bindViewsMethodBuilder.addStatement("$T.applyScaleDownFont($N.$N)", fontManagerClassName, NameStore.Variable.CONTAINER, variableElement.getSimpleName()); } } classBuilder.addMethod(bindViewsMethodBuilder.build()); // write the defines class to a java file try { JavaFile.builder(packageName, classBuilder.build()) .build() .writeTo(filer); } catch (IOException e) { messager.printMessage(Diagnostic.Kind.ERROR, e.toString(), typeElement); } } } return true; } */ @Override public Set<String> getSupportedAnnotationTypes() { return new TreeSet<>(Arrays.asList( BindView.class.getCanonicalName(), OnClick.class.getCanonicalName(), AutoScale.class.getCanonicalName(), IgnoreScale.class.getCanonicalName(), Keep.class.getCanonicalName())); } private static String getParentChain(final TypeElement targetClass) { // if input is top level class return it // otherwise return the parent chain plus it if (targetClass.getNestingKind() == NestingKind.TOP_LEVEL) { return targetClass.getSimpleName().toString(); } else { final Element parent = targetClass.getEnclosingElement(); if (parent.getKind() != ElementKind.CLASS) { return null; //throw new RuntimeException("Cannot create parent chain. Non-class parent found."); } return (getParentChain((TypeElement) parent)) + "$" + targetClass.getSimpleName().toString(); } } private static String getParentChainType(final TypeElement targetClass) { // if input is top level class return it // otherwise return the parent chain plus it if (targetClass.getNestingKind() == NestingKind.TOP_LEVEL) { return targetClass.getSimpleName().toString(); } else { final Element parent = targetClass.getEnclosingElement(); if (parent.getKind() != ElementKind.CLASS) { return null; //throw new RuntimeException("Cannot create parent chain. Non-class parent found."); } return (getParentChain((TypeElement) parent)) + "." + targetClass.getSimpleName().toString(); } } }
48.402597
120
0.562114
7a8488025a6719b40fdf39d6a669f15b6f9f6ccb
1,616
package comicdoor.comicdoor.adapter; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.List; import comicdoor.comicdoor.R; import comicdoor.comicdoor.bean.PluginBean; /** * Created by max_3 on 2016/9/28. */ public class PluginCardAdapter extends RecyclerView.Adapter<PluginCardAdapter.PluginCardViewHolder>{ private List<PluginBean> plugin_list; public PluginCardAdapter(List<PluginBean> plugin_list){ this.plugin_list=plugin_list; } @Override public PluginCardViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.card_plugin, parent, false); return new PluginCardViewHolder(itemView); } @Override public void onBindViewHolder(PluginCardViewHolder holder, int position) { PluginBean bean=plugin_list.get(position); holder.plugin_name.setText(bean.getName()); holder.plugin_version.setText(bean.getVersion()); } @Override public int getItemCount() { return plugin_list.size(); } class PluginCardViewHolder extends RecyclerView.ViewHolder{ TextView plugin_name; TextView plugin_version; PluginCardViewHolder(View itemView) { super(itemView); plugin_name= (TextView) itemView.findViewById(R.id.plugin_name); plugin_version= (TextView) itemView.findViewById(R.id.plugin_version); } } }
29.381818
100
0.717822
36731fc05ecebff1a2eb0122ab3e67bd638f9eca
5,483
package edu.calpoly.isstracker; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Typeface; import android.os.Bundle; import android.view.Gravity; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import java.util.Locale; import edu.calpoly.isstracker.IssData.AsyncTaskCallback; import edu.calpoly.isstracker.IssData.IssData; import edu.calpoly.isstracker.IssData.Pojos.IssPosition; public class IssMapActivity extends DrawerActivity { private GoogleMap mMap; private IssData issData; private Marker issMarker; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); inflateContentAndInitNavDrawer(R.layout.activity_iss_map); // Obtain the SupportMapFragment and get notified when the map is ready to be used. final SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); mapFragment.getMapAsync(new OnMapReadyCallback() { @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; //for the info window mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() { @Override public View getInfoWindow(Marker arg0) { return null; } @Override public View getInfoContents(Marker marker) { LinearLayout info = new LinearLayout(IssMapActivity.this); info.setOrientation(LinearLayout.VERTICAL); TextView title = new TextView(IssMapActivity.this); title.setTextColor(Color.BLACK); title.setTypeface(Typeface.DEFAULT_BOLD); title.setGravity(Gravity.CENTER); title.setText(marker.getTitle()); TextView altitude = new TextView(IssMapActivity.this); altitude.setTextColor(Color.GRAY); altitude.setText("Altitude: " + String.format(Locale.getDefault(), "%.2f", issData.getPosition().getAltitude()) + " km"); TextView velocity = new TextView(IssMapActivity.this); velocity.setTextColor(Color.GRAY); velocity.setText("Velocity: " + String.format(Locale.getDefault(), "%.2f", issData.getPosition().getVelocity()) + " km/h"); info.addView(title); info.addView(altitude); info.addView(velocity); return info; } }); } }); issData = new IssData(); listenToIssPosition(); } public void listenToIssPosition(){ issData.listenToPositionRefreshing(new AsyncTaskCallback() { @Override public void done(IssData issData) { IssPosition position = issData.getPosition(); setPosition(position.getLatitude(), position.getLongitude()); } }); } public void setPosition(double latitude, double longitude) { if (mMap != null) { LatLng pos = new LatLng(latitude, longitude); if (issMarker == null) { Bitmap.Config conf = Bitmap.Config.ARGB_8888; Bitmap bmp = Bitmap.createBitmap(150, 150, conf); Canvas canvas = new Canvas(bmp); Paint color = new Paint(); color.setTextSize(30); color.setColor(Color.WHITE); BitmapFactory.Options opt = new BitmapFactory.Options(); opt.inMutable = true; Bitmap imageBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.iss_icon_for_map, opt); Bitmap resized = Bitmap.createScaledBitmap(imageBitmap, 130, 130, true); canvas.drawBitmap(resized, 10, 10, color); issMarker = mMap.addMarker(new MarkerOptions() .position(pos) .title("ISS") .icon(BitmapDescriptorFactory.fromBitmap(bmp)) .infoWindowAnchor(0.5f, 0.5f) .anchor(0.5f, 0.5f)); mMap.moveCamera(CameraUpdateFactory.newLatLng(pos)); } else { issMarker.setPosition(pos); } issMarker.showInfoWindow(); } } @Override protected void onResume() { super.onResume(); issData.startRefreshingPosition(); getNavigationView().setCheckedItem(R.id.map_activity); } @Override protected void onPause() { super.onPause(); issData.stopRefreshingPosition(); } }
38.076389
147
0.602772