text
stringlengths
7
1.01M
package Cementacion; import Controlador.CtrlDatos; import Modelo.Datos; import Vista.FrmCapturaDatos; import Vista.FrmDatosAlumnos; import Vista.FrmDatosFinal; import Vista.FrmMenu; public class CRUDMVC { public static void main(String[] args) { FrmCapturaDatos frmD = new FrmCapturaDatos(); FrmDatosFinal frmF = new FrmDatosFinal(); FrmMenu frmM = new FrmMenu(); FrmDatosAlumnos frmDA = new FrmDatosAlumnos(); Datos mod = new Datos(); CtrlDatos ctrlD = new CtrlDatos(mod, frmD, frmF, frmM, frmDA); ctrlD.iniciarMenu(); } }
/** * 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.hadoop.hdfs.shortcircuit; import java.io.BufferedOutputStream; import java.io.Closeable; import java.io.DataOutputStream; import java.io.EOFException; import java.io.FileInputStream; import java.io.IOException; import java.util.HashMap; import java.util.Map.Entry; import java.util.TreeMap; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; import org.apache.commons.lang.mutable.MutableBoolean; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.hdfs.ExtendedBlockId; import org.apache.hadoop.hdfs.net.DomainPeer; import org.apache.hadoop.hdfs.protocol.DatanodeInfo; import org.apache.hadoop.hdfs.protocol.datatransfer.DataTransferProtocol; import org.apache.hadoop.hdfs.protocol.datatransfer.Sender; import org.apache.hadoop.hdfs.protocol.proto.DataTransferProtos.ShortCircuitShmResponseProto; import org.apache.hadoop.hdfs.protocolPB.PBHelperClient; import org.apache.hadoop.hdfs.shortcircuit.ShortCircuitShm.ShmId; import org.apache.hadoop.hdfs.shortcircuit.ShortCircuitShm.Slot; import org.apache.hadoop.net.unix.DomainSocket; import org.apache.hadoop.net.unix.DomainSocketWatcher; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Manages short-circuit memory segments for an HDFS client. * * Clients are responsible for requesting and releasing shared memory segments used * for communicating with the DataNode. The client will try to allocate new slots * in the set of existing segments, falling back to getting a new segment from the * DataNode via {@link DataTransferProtocol#requestShortCircuitFds}. * * The counterpart to this class on the DataNode is {@link ShortCircuitRegistry}. * See {@link ShortCircuitRegistry} for more information on the communication protocol. */ @InterfaceAudience.Private public class DfsClientShmManager implements Closeable { private static final Logger LOG = LoggerFactory.getLogger( DfsClientShmManager.class); /** * Manages short-circuit memory segments that pertain to a given DataNode. */ class EndpointShmManager { /** * The datanode we're managing. */ private final DatanodeInfo datanode; /** * Shared memory segments which have no empty slots. * * Protected by the manager lock. */ private final TreeMap<ShmId, DfsClientShm> full = new TreeMap<ShmId, DfsClientShm>(); /** * Shared memory segments which have at least one empty slot. * * Protected by the manager lock. */ private final TreeMap<ShmId, DfsClientShm> notFull = new TreeMap<ShmId, DfsClientShm>(); /** * True if this datanode doesn't support short-circuit shared memory * segments. * * Protected by the manager lock. */ private boolean disabled = false; /** * True if we're in the process of loading a shared memory segment from * this DataNode. * * Protected by the manager lock. */ private boolean loading = false; EndpointShmManager (DatanodeInfo datanode) { this.datanode = datanode; } /** * Pull a slot out of a preexisting shared memory segment. * * Must be called with the manager lock held. * * @param blockId The blockId to put inside the Slot object. * * @return null if none of our shared memory segments contain a * free slot; the slot object otherwise. */ private Slot allocSlotFromExistingShm(ExtendedBlockId blockId) { if (notFull.isEmpty()) { return null; } Entry<ShmId, DfsClientShm> entry = notFull.firstEntry(); DfsClientShm shm = entry.getValue(); ShmId shmId = shm.getShmId(); Slot slot = shm.allocAndRegisterSlot(blockId); if (shm.isFull()) { if (LOG.isTraceEnabled()) { LOG.trace(this + ": pulled the last slot " + slot.getSlotIdx() + " out of " + shm); } DfsClientShm removedShm = notFull.remove(shmId); Preconditions.checkState(removedShm == shm); full.put(shmId, shm); } else { if (LOG.isTraceEnabled()) { LOG.trace(this + ": pulled slot " + slot.getSlotIdx() + " out of " + shm); } } return slot; } /** * Ask the DataNode for a new shared memory segment. This function must be * called with the manager lock held. We will release the lock while * communicating with the DataNode. * * @param clientName The current client name. * @param peer The peer to use to talk to the DataNode. * * @return Null if the DataNode does not support shared memory * segments, or experienced an error creating the * shm. The shared memory segment itself on success. * @throws IOException If there was an error communicating over the socket. * We will not throw an IOException unless the socket * itself (or the network) is the problem. */ private DfsClientShm requestNewShm(String clientName, DomainPeer peer) throws IOException { final DataOutputStream out = new DataOutputStream( new BufferedOutputStream(peer.getOutputStream())); new Sender(out).requestShortCircuitShm(clientName); ShortCircuitShmResponseProto resp = ShortCircuitShmResponseProto.parseFrom( PBHelperClient.vintPrefixed(peer.getInputStream())); String error = resp.hasError() ? resp.getError() : "(unknown)"; switch (resp.getStatus()) { case SUCCESS: DomainSocket sock = peer.getDomainSocket(); byte buf[] = new byte[1]; FileInputStream fis[] = new FileInputStream[1]; if (sock.recvFileInputStreams(fis, buf, 0, buf.length) < 0) { throw new EOFException("got EOF while trying to transfer the " + "file descriptor for the shared memory segment."); } if (fis[0] == null) { throw new IOException("the datanode " + datanode + " failed to " + "pass a file descriptor for the shared memory segment."); } try { DfsClientShm shm = new DfsClientShm(PBHelperClient.convert(resp.getId()), fis[0], this, peer); if (LOG.isTraceEnabled()) { LOG.trace(this + ": createNewShm: created " + shm); } return shm; } finally { try { fis[0].close(); } catch (Throwable e) { LOG.debug("Exception in closing " + fis[0], e); } } case ERROR_UNSUPPORTED: // The DataNode just does not support short-circuit shared memory // access, and we should stop asking. LOG.info(this + ": datanode does not support short-circuit " + "shared memory access: " + error); disabled = true; return null; default: // The datanode experienced some kind of unexpected error when trying to // create the short-circuit shared memory segment. LOG.warn(this + ": error requesting short-circuit shared memory " + "access: " + error); return null; } } /** * Allocate a new shared memory slot connected to this datanode. * * Must be called with the EndpointShmManager lock held. * * @param peer The peer to use to talk to the DataNode. * @param usedPeer (out param) Will be set to true if we used the peer. * When a peer is used * * @param clientName The client name. * @param blockId The block ID to use. * @return null if the DataNode does not support shared memory * segments, or experienced an error creating the * shm. The shared memory segment itself on success. * @throws IOException If there was an error communicating over the socket. */ Slot allocSlot(DomainPeer peer, MutableBoolean usedPeer, String clientName, ExtendedBlockId blockId) throws IOException { while (true) { if (closed) { if (LOG.isTraceEnabled()) { LOG.trace(this + ": the DfsClientShmManager has been closed."); } return null; } if (disabled) { if (LOG.isTraceEnabled()) { LOG.trace(this + ": shared memory segment access is disabled."); } return null; } // Try to use an existing slot. Slot slot = allocSlotFromExistingShm(blockId); if (slot != null) { return slot; } // There are no free slots. If someone is loading more slots, wait // for that to finish. if (loading) { if (LOG.isTraceEnabled()) { LOG.trace(this + ": waiting for loading to finish..."); } finishedLoading.awaitUninterruptibly(); } else { // Otherwise, load the slot ourselves. loading = true; lock.unlock(); DfsClientShm shm; try { shm = requestNewShm(clientName, peer); if (shm == null) continue; // See #{DfsClientShmManager#domainSocketWatcher} for details // about why we do this before retaking the manager lock. domainSocketWatcher.add(peer.getDomainSocket(), shm); // The DomainPeer is now our responsibility, and should not be // closed by the caller. usedPeer.setValue(true); } finally { lock.lock(); loading = false; finishedLoading.signalAll(); } if (shm.isDisconnected()) { // If the peer closed immediately after the shared memory segment // was created, the DomainSocketWatcher callback might already have // fired and marked the shm as disconnected. In this case, we // obviously don't want to add the SharedMemorySegment to our list // of valid not-full segments. if (LOG.isDebugEnabled()) { LOG.debug(this + ": the UNIX domain socket associated with " + "this short-circuit memory closed before we could make " + "use of the shm."); } } else { notFull.put(shm.getShmId(), shm); } } } } /** * Stop tracking a slot. * * Must be called with the EndpointShmManager lock held. * * @param slot The slot to release. */ void freeSlot(Slot slot) { DfsClientShm shm = (DfsClientShm)slot.getShm(); shm.unregisterSlot(slot.getSlotIdx()); if (shm.isDisconnected()) { // Stale shared memory segments should not be tracked here. Preconditions.checkState(!full.containsKey(shm.getShmId())); Preconditions.checkState(!notFull.containsKey(shm.getShmId())); if (shm.isEmpty()) { if (LOG.isTraceEnabled()) { LOG.trace(this + ": freeing empty stale " + shm); } shm.free(); } } else { ShmId shmId = shm.getShmId(); full.remove(shmId); // The shm can't be full if we just freed a slot. if (shm.isEmpty()) { notFull.remove(shmId); // If the shared memory segment is now empty, we call shutdown(2) on // the UNIX domain socket associated with it. The DomainSocketWatcher, // which is watching this socket, will call DfsClientShm#handle, // cleaning up this shared memory segment. // // See #{DfsClientShmManager#domainSocketWatcher} for details about why // we don't want to call DomainSocketWatcher#remove directly here. // // Note that we could experience 'fragmentation' here, where the // DFSClient allocates a bunch of slots in different shared memory // segments, and then frees most of them, but never fully empties out // any segment. We make some attempt to avoid this fragmentation by // always allocating new slots out of the shared memory segment with the // lowest ID, but it could still occur. In most workloads, // fragmentation should not be a major concern, since it doesn't impact // peak file descriptor usage or the speed of allocation. if (LOG.isTraceEnabled()) { LOG.trace(this + ": shutting down UNIX domain socket for " + "empty " + shm); } shutdown(shm); } else { notFull.put(shmId, shm); } } } /** * Unregister a shared memory segment. * * Once a segment is unregistered, we will not allocate any more slots * inside that segment. * * The DomainSocketWatcher calls this while holding the DomainSocketWatcher * lock. * * @param shmId The ID of the shared memory segment to unregister. */ void unregisterShm(ShmId shmId) { lock.lock(); try { full.remove(shmId); notFull.remove(shmId); } finally { lock.unlock(); } } @Override public String toString() { return String.format("EndpointShmManager(%s, parent=%s)", datanode, DfsClientShmManager.this); } PerDatanodeVisitorInfo getVisitorInfo() { return new PerDatanodeVisitorInfo(full, notFull, disabled); } final void shutdown(DfsClientShm shm) { try { shm.getPeer().getDomainSocket().shutdown(); } catch (IOException e) { LOG.warn(this + ": error shutting down shm: got IOException calling " + "shutdown(SHUT_RDWR)", e); } } } private boolean closed = false; private final ReentrantLock lock = new ReentrantLock(); /** * A condition variable which is signalled when we finish loading a segment * from the Datanode. */ private final Condition finishedLoading = lock.newCondition(); /** * Information about each Datanode. */ private final HashMap<DatanodeInfo, EndpointShmManager> datanodes = new HashMap<DatanodeInfo, EndpointShmManager>(1); /** * The DomainSocketWatcher which keeps track of the UNIX domain socket * associated with each shared memory segment. * * Note: because the DomainSocketWatcher makes callbacks into this * DfsClientShmManager object, you must MUST NOT attempt to take the * DomainSocketWatcher lock while holding the DfsClientShmManager lock, * or else deadlock might result. This means that most DomainSocketWatcher * methods are off-limits unless you release the manager lock first. */ private final DomainSocketWatcher domainSocketWatcher; DfsClientShmManager(int interruptCheckPeriodMs) throws IOException { this.domainSocketWatcher = new DomainSocketWatcher(interruptCheckPeriodMs, "client"); } public Slot allocSlot(DatanodeInfo datanode, DomainPeer peer, MutableBoolean usedPeer, ExtendedBlockId blockId, String clientName) throws IOException { lock.lock(); try { if (closed) { LOG.trace(this + ": the DfsClientShmManager isclosed."); return null; } EndpointShmManager shmManager = datanodes.get(datanode); if (shmManager == null) { shmManager = new EndpointShmManager(datanode); datanodes.put(datanode, shmManager); } return shmManager.allocSlot(peer, usedPeer, clientName, blockId); } finally { lock.unlock(); } } public void freeSlot(Slot slot) { lock.lock(); try { DfsClientShm shm = (DfsClientShm)slot.getShm(); shm.getEndpointShmManager().freeSlot(slot); } finally { lock.unlock(); } } @VisibleForTesting public static class PerDatanodeVisitorInfo { public final TreeMap<ShmId, DfsClientShm> full; public final TreeMap<ShmId, DfsClientShm> notFull; public final boolean disabled; PerDatanodeVisitorInfo(TreeMap<ShmId, DfsClientShm> full, TreeMap<ShmId, DfsClientShm> notFull, boolean disabled) { this.full = full; this.notFull = notFull; this.disabled = disabled; } } @VisibleForTesting public interface Visitor { void visit(HashMap<DatanodeInfo, PerDatanodeVisitorInfo> info) throws IOException; } @VisibleForTesting public void visit(Visitor visitor) throws IOException { lock.lock(); try { HashMap<DatanodeInfo, PerDatanodeVisitorInfo> info = new HashMap<DatanodeInfo, PerDatanodeVisitorInfo>(); for (Entry<DatanodeInfo, EndpointShmManager> entry : datanodes.entrySet()) { info.put(entry.getKey(), entry.getValue().getVisitorInfo()); } visitor.visit(info); } finally { lock.unlock(); } } /** * Close the DfsClientShmManager. */ @Override public void close() throws IOException { lock.lock(); try { if (closed) return; closed = true; } finally { lock.unlock(); } // When closed, the domainSocketWatcher will issue callbacks that mark // all the outstanding DfsClientShm segments as stale. try { domainSocketWatcher.close(); } catch (Throwable e) { LOG.debug("Exception in closing " + domainSocketWatcher, e); } } @Override public String toString() { return String.format("ShortCircuitShmManager(%08x)", System.identityHashCode(this)); } @VisibleForTesting public DomainSocketWatcher getDomainSocketWatcher() { return domainSocketWatcher; } }
package com.example.application.views.list; import com.example.application.data.entity.Company; import com.example.application.data.entity.Contact; import com.example.application.data.entity.Status; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicReference; public class ContactFormTest { private List<Company> companies; private List<Status> statuses; private Contact marcUsher; private Company company1; private Company company2; private Status status1; private Status status2; @Before public void setupData() { companies = new ArrayList<>(); company1 = new Company(); company1.setName("Vaadin Ltd"); company2 = new Company(); company2.setName("IT Mill"); companies.add(company1); companies.add(company2); statuses = new ArrayList<>(); status1 = new Status(); status1.setName("Status 1"); status2 = new Status(); status2.setName("Status 2"); statuses.add(status1); statuses.add(status2); marcUsher = new Contact(); marcUsher.setFirstName("Marc"); marcUsher.setLastName("Usher"); marcUsher.setEmail("marc@usher.com"); marcUsher.setStatus(status1); marcUsher.setCompany(company2); } @Test public void formFieldsPopulated() { ContactForm form = new ContactForm(companies, statuses); form.setContact(marcUsher); Assert.assertEquals("Marc", form.firstName.getValue()); Assert.assertEquals("Usher", form.lastName.getValue()); Assert.assertEquals("marc@usher.com", form.email.getValue()); Assert.assertEquals(company2, form.company.getValue()); Assert.assertEquals(status1, form.status.getValue()); } @Test public void saveEventHasCorrectValues() { ContactForm form = new ContactForm(companies, statuses); Contact contact = new Contact(); form.setContact(contact); form.firstName.setValue("John"); form.lastName.setValue("Doe"); form.company.setValue(company1); form.email.setValue("john@doe.com"); form.status.setValue(status2); AtomicReference<Contact> savedContactRef = new AtomicReference<>(null); form.addListener(ContactForm.SaveEvent.class, e -> { savedContactRef.set(e.getContact()); }); form.save.click(); Contact savedContact = savedContactRef.get(); Assert.assertEquals("John", savedContact.getFirstName()); Assert.assertEquals("Doe", savedContact.getLastName()); Assert.assertEquals("john@doe.com", savedContact.getEmail()); Assert.assertEquals(company1, savedContact.getCompany()); Assert.assertEquals(status2, savedContact.getStatus()); } }
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/* * 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. */ end_comment begin_package package|package name|org operator|. name|apache operator|. name|hive operator|. name|ptest operator|. name|execution operator|. name|conf package|; end_package begin_import import|import name|java operator|. name|io operator|. name|File import|; end_import begin_import import|import name|java operator|. name|util operator|. name|Collection import|; end_import begin_comment comment|// Exists primarily to allow for easier unit tests. end_comment begin_interface specifier|public interface|interface name|FileListProvider block|{ name|Collection argument_list|< name|File argument_list|> name|listFiles parameter_list|( name|File name|directory parameter_list|, name|String index|[] name|extensions parameter_list|, name|boolean name|recursive parameter_list|) function_decl|; block|} end_interface end_unit
package com.github.semres.babelnet; import com.github.semres.SemRes; import com.github.semres.SynsetSerializer; import com.github.semres.Synset; import it.uniroma1.lcl.babelnet.BabelSynsetID; import it.uniroma1.lcl.babelnet.InvalidBabelSynsetIDException; import org.eclipse.rdf4j.model.*; import org.eclipse.rdf4j.model.impl.LinkedHashModel; import org.eclipse.rdf4j.model.impl.SimpleValueFactory; import org.eclipse.rdf4j.model.vocabulary.RDF; import org.eclipse.rdf4j.model.vocabulary.RDFS; import org.eclipse.rdf4j.query.BindingSet; import org.eclipse.rdf4j.query.QueryLanguage; import org.eclipse.rdf4j.query.TupleQuery; import org.eclipse.rdf4j.query.TupleQueryResult; import org.eclipse.rdf4j.repository.Repository; import org.eclipse.rdf4j.repository.RepositoryConnection; import org.eclipse.rdf4j.sail.memory.model.BooleanMemLiteral; import java.time.LocalDateTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.Date; import java.util.HashSet; import java.util.Set; public class BabelNetSynsetSerializer extends SynsetSerializer { public BabelNetSynsetSerializer(String baseIri) { super(baseIri); } @Override public Model synsetToRdf(Synset synset) { if (!(synset instanceof BabelNetSynset)) { throw new IllegalArgumentException(); } Model model = new LinkedHashModel(); ValueFactory factory = SimpleValueFactory.getInstance(); IRI synsetIri = factory.createIRI(baseIri + "synsets/" + synset.getId()); model.add(synsetIri, RDF.TYPE, getSynsetClassIri()); Literal id = factory.createLiteral(synset.getId()); model.add(synsetIri, SemRes.ID, id); Literal representation = factory.createLiteral(synset.getRepresentation()); model.add(factory.createStatement(synsetIri, RDFS.LABEL, representation)); if (synset.getDescription() != null) { Literal description = factory.createLiteral(synset.getDescription()); model.add(factory.createStatement(synsetIri, RDFS.COMMENT, description)); } if (synset.getLastEditedTime() != null) { model.add(synsetIri, SemRes.LAST_EDITED, factory.createLiteral(Date.from(synset.getLastEditedTime().atZone(ZoneId.systemDefault()).toInstant()))); } for (String removedRelation : ((BabelNetSynset) synset).getRemovedRelations()) { IRI removedRelationIRI = factory.createIRI(baseIri + "synsets/" + synset.getId() + "/removedRelations/" + removedRelation); model.add(factory.createStatement(removedRelationIRI, SemRes.ID, factory.createLiteral(removedRelation))); model.add(factory.createStatement(synsetIri, CommonIRI.REMOVED_RELATION, removedRelationIRI)); } // Add information if BabelNet edges has been downloaded. model.add(synsetIri, CommonIRI.EDGES_DOWNLOADED, factory.createLiteral(((BabelNetSynset) synset).isDownloadedWithEdges())); return model; } @Override public BabelNetSynset rdfToSynset(String synsetId, Repository repository) { ValueFactory factory = SimpleValueFactory.getInstance(); return rdfToSynset(factory.createIRI(baseIri + "synsets/" + synsetId), repository); } @Override public BabelNetSynset rdfToSynset(IRI synsetIri, Repository repository) { BabelNetSynset synset; boolean edgesLoaded; try (RepositoryConnection conn = repository.getConnection()) { // Get synset representation, id, description and the flag if the edges from BabelNet were loaded or not String queryString = String.format("SELECT ?id ?representation ?edgesLoaded ?description ?lastEdited " + "WHERE { <%1$s> <%2$s> ?id . <%1$s> <%3$s> ?representation . <%1$s> <%4$s> ?edgesLoaded . " + "OPTIONAL { <%1$s> <%5$s> ?description } . OPTIONAL { <%1$s> <%6$s> ?lastEdited }}", synsetIri.stringValue(), SemRes.ID, RDFS.LABEL, CommonIRI.EDGES_DOWNLOADED, RDFS.COMMENT, SemRes.LAST_EDITED); TupleQuery tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString); String id; String representation; String description = null; LocalDateTime lastEdited = null; try (TupleQueryResult result = tupleQuery.evaluate()) { if (result.hasNext()) { BindingSet bindingSet = result.next(); id = bindingSet.getValue("id").stringValue(); representation = bindingSet.getValue("representation").stringValue(); edgesLoaded = ((BooleanMemLiteral) bindingSet.getValue("edgesLoaded")).booleanValue(); if (bindingSet.getValue("description") != null) { description = bindingSet.getValue("description").stringValue(); } if (bindingSet.getValue("lastEdited") != null) { lastEdited = LocalDateTime.parse(bindingSet.getValue("lastEdited").stringValue(), DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX")); } } else { return null; } } // Get removed relations queryString = String.format("SELECT ?removedRelationId WHERE { <%s> <%s> ?removedRelation . ?removedRelation <%s> ?removedRelationId }", synsetIri.stringValue(), CommonIRI.REMOVED_RELATION, SemRes.ID); tupleQuery = conn.prepareTupleQuery(QueryLanguage.SPARQL, queryString); Set<String> removedRelations = new HashSet<>(); try (TupleQueryResult result = tupleQuery.evaluate()) { while (result.hasNext()) { BindingSet bindingSet = result.next(); try { BabelSynsetID removedRelation = new BabelSynsetID(bindingSet.getValue("removedRelationId").stringValue()); removedRelations.add(removedRelation.toString()); } catch (InvalidBabelSynsetIDException e) { throw new Error("Invalid BabelNet ID"); } } } synset = new BabelNetSynset(representation, id, description, removedRelations, edgesLoaded, lastEdited); } return synset; } @Override public String getSynsetClass() { return "com.github.semres.babelnet.BabelNetSynset"; } @Override public IRI getSynsetClassIri() { return CommonIRI.BABELNET_SYNSET; } }
package Zoo.Food; public class Vegetables extends Food { public String GetFood() { return "vegetables"; } }
/** * Copyright (c) 2014, * Charles Prud'homme (TASC, INRIA Rennes, LINA CNRS UMR 6241), * Jean-Guillaume Fages (COSLING S.A.S.). * 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 the <organization> 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 <COPYRIGHT HOLDER> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.chocosolver.solver.constraints.nary.nValue.amnv.graph; import gnu.trove.map.hash.THashMap; import org.chocosolver.solver.Solver; import org.chocosolver.solver.variables.IntVar; import org.chocosolver.util.objects.setDataStructures.ISet; /** * Intersection Graph * * @author Jean-Guillaume Fages * @since 01/01/2014 */ public class Gi extends G { //*********************************************************************************** // VARIABLES //*********************************************************************************** IntVar[] X; //*********************************************************************************** // CONSTRUCTORS //*********************************************************************************** /** * Creates the intersection graph of X * * @param X integer variable */ public Gi(IntVar[] X) { super(X[0].getSolver(), X.length); this.X = X; } //*********************************************************************************** // ALGORITHMS //*********************************************************************************** public void build() { int n = getNbMaxNodes(); for (int i = 0; i < n; i++) { getNeighOf(i).clear(); } for (int i = 0; i < n; i++) { for (int i2 = i + 1; i2 < n; i2++) { if (intersect(i, i2)) { addEdge(i, i2); } } } } public void update() { int n = getNbMaxNodes(); for (int i = 0; i < n; i++) { update(i); } } public void update(int i) { ISet nei = getNeighOf(i); for (int j = nei.getFirstElement(); j >= 0; j = nei.getNextElement()) { if (!intersect(i, j)) { removeEdge(i, j); } } } protected boolean intersect(int i, int j) { IntVar x = X[i]; IntVar y = X[j]; if (x.getLB() > y.getUB() || y.getLB() > x.getUB()) { return false; } int ub = x.getUB(); for (int val = x.getLB(); val <= ub; val = x.nextValue(val)) { if (y.contains(val)) { return true; } } return false; } @Override public void duplicate(Solver solver, THashMap<Object, Object> identitymap) { if (!identitymap.containsKey(this)) { int size = this.X.length; IntVar[] aVars = new IntVar[size]; for (int i = 0; i < size; i++) { this.X[i].duplicate(solver, identitymap); aVars[i] = (IntVar) identitymap.get(this.X[i]); } identitymap.put(this, new Gi(aVars)); } } }
/* * 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.tugraz.sysds.test.integration.functions.misc; import java.util.HashMap; import org.junit.Assert; import org.junit.Test; import org.tugraz.sysds.api.DMLScript; import org.tugraz.sysds.common.Types.ExecMode; import org.tugraz.sysds.hops.OptimizerUtils; import org.tugraz.sysds.lops.LopProperties.ExecType; import org.tugraz.sysds.runtime.matrix.data.MatrixValue.CellIndex; import org.tugraz.sysds.test.AutomatedTestBase; import org.tugraz.sysds.test.TestConfiguration; import org.tugraz.sysds.test.TestUtils; /** * Regression test for function recompile-once issue with literal replacement. * */ public class RewriteFuseBinaryOpChainTest extends AutomatedTestBase { private static final String TEST_NAME1 = "RewriteFuseBinaryOpChainTest1"; //+* (X+s*Y) private static final String TEST_NAME2 = "RewriteFuseBinaryOpChainTest2"; //-* (X-s*Y) private static final String TEST_NAME3 = "RewriteFuseBinaryOpChainTest3"; //+* (s*Y+X) private static final String TEST_NAME4 = "RewriteFuseBinaryOpChainTest4"; //outer(X, s*Y, "+") not applied private static final String TEST_DIR = "functions/misc/"; private static final String TEST_CLASS_DIR = TEST_DIR + RewriteFuseBinaryOpChainTest.class.getSimpleName() + "/"; private static final double eps = Math.pow(10, -10); @Override public void setUp() { TestUtils.clearAssertionInformation(); addTestConfiguration( TEST_NAME1, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME1, new String[] { "R" }) ); addTestConfiguration( TEST_NAME2, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME2, new String[] { "R" }) ); addTestConfiguration( TEST_NAME3, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME3, new String[] { "R" }) ); addTestConfiguration( TEST_NAME4, new TestConfiguration(TEST_CLASS_DIR, TEST_NAME4, new String[] { "R" }) ); } @Test public void testFuseBinaryPlusNoRewriteCP() { testFuseBinaryChain( TEST_NAME1, false, ExecType.CP ); } @Test public void testFuseBinaryPlusRewriteCP() { testFuseBinaryChain( TEST_NAME1, true, ExecType.CP); } @Test public void testFuseBinaryMinusNoRewriteCP() { testFuseBinaryChain( TEST_NAME2, false, ExecType.CP ); } @Test public void testFuseBinaryMinusRewriteCP() { testFuseBinaryChain( TEST_NAME2, true, ExecType.CP ); } @Test public void testFuseBinaryPlus2NoRewriteCP() { testFuseBinaryChain( TEST_NAME3, false, ExecType.CP ); } @Test public void testFuseBinaryPlus2RewriteCP() { testFuseBinaryChain( TEST_NAME3, true, ExecType.CP ); } @Test public void testFuseBinaryPlusNoRewriteSP() { testFuseBinaryChain( TEST_NAME1, false, ExecType.SPARK ); } @Test public void testFuseBinaryPlusRewriteSP() { testFuseBinaryChain( TEST_NAME1, true, ExecType.SPARK ); } @Test public void testFuseBinaryMinusNoRewriteSP() { testFuseBinaryChain( TEST_NAME2, false, ExecType.SPARK ); } @Test public void testFuseBinaryMinusRewriteSP() { testFuseBinaryChain( TEST_NAME2, true, ExecType.SPARK ); } @Test public void testFuseBinaryPlus2NoRewriteSP() { testFuseBinaryChain( TEST_NAME3, false, ExecType.SPARK ); } @Test public void testFuseBinaryPlus2RewriteSP() { testFuseBinaryChain( TEST_NAME3, true, ExecType.SPARK ); } //negative tests @Test public void testOuterBinaryPlusNoRewriteCP() { testFuseBinaryChain( TEST_NAME4, false, ExecType.CP ); } @Test public void testOuterBinaryPlusRewriteCP() { testFuseBinaryChain( TEST_NAME4, true, ExecType.CP); } private void testFuseBinaryChain( String testname, boolean rewrites, ExecType instType ) { ExecMode platformOld = rtplatform; switch( instType ){ case SPARK: rtplatform = ExecMode.SPARK; break; default: rtplatform = ExecMode.HYBRID; break; } boolean sparkConfigOld = DMLScript.USE_LOCAL_SPARK_CONFIG; if( rtplatform == ExecMode.SPARK ) DMLScript.USE_LOCAL_SPARK_CONFIG = true; boolean rewritesOld = OptimizerUtils.ALLOW_ALGEBRAIC_SIMPLIFICATION; OptimizerUtils.ALLOW_ALGEBRAIC_SIMPLIFICATION = rewrites; try { TestConfiguration config = getTestConfiguration(testname); loadTestConfiguration(config); String HOME = SCRIPT_DIR + TEST_DIR; fullDMLScriptName = HOME + testname + ".dml"; programArgs = new String[]{"-explain", "-stats","-args", output("S") }; fullRScriptName = HOME + testname + ".R"; rCmd = getRCmd(inputDir(), expectedDir()); runTest(true, false, null, -1); runRScript(true); //compare matrices HashMap<CellIndex, Double> dmlfile = readDMLMatrixFromHDFS("S"); HashMap<CellIndex, Double> rfile = readRMatrixFromFS("S"); Assert.assertTrue(TestUtils.compareMatrices(dmlfile, rfile, eps, "Stat-DML", "Stat-R")); } finally { OptimizerUtils.ALLOW_ALGEBRAIC_SIMPLIFICATION = rewritesOld; rtplatform = platformOld; DMLScript.USE_LOCAL_SPARK_CONFIG = sparkConfigOld; } } }
/* * Copyright 2015-2020 Amazon.com, Inc. or its affiliates. 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://aws.amazon.com/apache2.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.amazonaws.services.codedeploy.model; import java.io.Serializable; import javax.annotation.Generated; /** * <p> * Represents the output of a DeleteGitHubAccountToken operation. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/codedeploy-2014-10-06/DeleteGitHubAccountToken" * target="_top">AWS API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DeleteGitHubAccountTokenResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable { /** * <p> * The name of the GitHub account connection that was deleted. * </p> */ private String tokenName; /** * <p> * The name of the GitHub account connection that was deleted. * </p> * * @param tokenName * The name of the GitHub account connection that was deleted. */ public void setTokenName(String tokenName) { this.tokenName = tokenName; } /** * <p> * The name of the GitHub account connection that was deleted. * </p> * * @return The name of the GitHub account connection that was deleted. */ public String getTokenName() { return this.tokenName; } /** * <p> * The name of the GitHub account connection that was deleted. * </p> * * @param tokenName * The name of the GitHub account connection that was deleted. * @return Returns a reference to this object so that method calls can be chained together. */ public DeleteGitHubAccountTokenResult withTokenName(String tokenName) { setTokenName(tokenName); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getTokenName() != null) sb.append("TokenName: ").append(getTokenName()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DeleteGitHubAccountTokenResult == false) return false; DeleteGitHubAccountTokenResult other = (DeleteGitHubAccountTokenResult) obj; if (other.getTokenName() == null ^ this.getTokenName() == null) return false; if (other.getTokenName() != null && other.getTokenName().equals(this.getTokenName()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getTokenName() == null) ? 0 : getTokenName().hashCode()); return hashCode; } @Override public DeleteGitHubAccountTokenResult clone() { try { return (DeleteGitHubAccountTokenResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
/* * MIT License * * Copyright (c) 2021 MASES s.r.l. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /************************************************************************************** * <auto-generated> * This code was generated from a template using JCOReflector * * Manual changes to this file may cause unexpected behavior in your application. * Manual changes to this file will be overwritten if the code is regenerated. * </auto-generated> *************************************************************************************/ package system.windows.media.animation; import org.mases.jcobridge.*; import org.mases.jcobridge.netreflection.*; import java.util.ArrayList; // Import section import system.windows.media.animation.Rotation3DKeyFrame; import system.windows.media.media3d.Rotation3D; import system.windows.media.animation.KeyTime; /** * The base .NET class managing System.Windows.Media.Animation.LinearRotation3DKeyFrame, PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35. * <p> * * See: <a href="https://docs.microsoft.com/en-us/dotnet/api/System.Windows.Media.Animation.LinearRotation3DKeyFrame" target="_top">https://docs.microsoft.com/en-us/dotnet/api/System.Windows.Media.Animation.LinearRotation3DKeyFrame</a> */ public class LinearRotation3DKeyFrame extends Rotation3DKeyFrame { /** * Fully assembly qualified name: PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35 */ public static final String assemblyFullName = "PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; /** * Assembly name: PresentationCore */ public static final String assemblyShortName = "PresentationCore"; /** * Qualified class name: System.Windows.Media.Animation.LinearRotation3DKeyFrame */ public static final String className = "System.Windows.Media.Animation.LinearRotation3DKeyFrame"; static JCOBridge bridge = JCOBridgeInstance.getInstance(assemblyFullName); /** * The type managed from JCOBridge. See {@link JCType} */ public static JCType classType = createType(); static JCEnum enumInstance = null; JCObject classInstance = null; static JCType createType() { try { String classToCreate = className + ", " + (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName); if (JCOReflector.getDebug()) JCOReflector.writeLog("Creating %s", classToCreate); JCType typeCreated = bridge.GetType(classToCreate); if (JCOReflector.getDebug()) JCOReflector.writeLog("Created: %s", (typeCreated != null) ? typeCreated.toString() : "Returned null value"); return typeCreated; } catch (JCException e) { JCOReflector.writeLog(e); return null; } } void addReference(String ref) throws Throwable { try { bridge.AddReference(ref); } catch (JCNativeException jcne) { throw translateException(jcne); } } /** * Internal constructor. Use with caution */ public LinearRotation3DKeyFrame(java.lang.Object instance) throws Throwable { super(instance); if (instance instanceof JCObject) { classInstance = (JCObject) instance; } else throw new Exception("Cannot manage object, it is not a JCObject"); } public String getJCOAssemblyName() { return assemblyFullName; } public String getJCOClassName() { return className; } public String getJCOObjectName() { return className + ", " + (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName); } public java.lang.Object getJCOInstance() { return classInstance; } public void setJCOInstance(JCObject instance) { classInstance = instance; super.setJCOInstance(classInstance); } public JCType getJCOType() { return classType; } /** * Try to cast the {@link IJCOBridgeReflected} instance into {@link LinearRotation3DKeyFrame}, a cast assert is made to check if types are compatible. * @param from {@link IJCOBridgeReflected} instance to be casted * @return {@link LinearRotation3DKeyFrame} instance * @throws java.lang.Throwable in case of error during cast operation */ public static LinearRotation3DKeyFrame cast(IJCOBridgeReflected from) throws Throwable { NetType.AssertCast(classType, from); return new LinearRotation3DKeyFrame(from.getJCOInstance()); } // Constructors section public LinearRotation3DKeyFrame() throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.InvalidOperationException, system.ArgumentNullException, system.componentmodel.InvalidEnumArgumentException, system.componentmodel.Win32Exception { try { // add reference to assemblyName.dll file addReference(JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName); setJCOInstance((JCObject)classType.NewObject()); } catch (JCNativeException jcne) { throw translateException(jcne); } } public LinearRotation3DKeyFrame(Rotation3D value) throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.InvalidOperationException, system.ArgumentNullException, system.componentmodel.Win32Exception, system.IndexOutOfRangeException, system.FormatException { try { // add reference to assemblyName.dll file addReference(JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName); setJCOInstance((JCObject)classType.NewObject(value == null ? null : value.getJCOInstance())); } catch (JCNativeException jcne) { throw translateException(jcne); } } public LinearRotation3DKeyFrame(Rotation3D value, KeyTime keyTime) throws Throwable, system.ArgumentException, system.ArgumentOutOfRangeException, system.InvalidOperationException, system.ArgumentNullException, system.componentmodel.Win32Exception, system.IndexOutOfRangeException, system.FormatException { try { // add reference to assemblyName.dll file addReference(JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName); setJCOInstance((JCObject)classType.NewObject(value == null ? null : value.getJCOInstance(), keyTime == null ? null : keyTime.getJCOInstance())); } catch (JCNativeException jcne) { throw translateException(jcne); } } // Methods section // Properties section // Instance Events section }
/* Copyright Statement: * * This software/firmware and related documentation ("MediaTek Software") are * protected under relevant copyright laws. The information contained herein is * confidential and proprietary to MediaTek Inc. and/or its licensors. Without * the prior written permission of MediaTek inc. and/or its licensors, any * reproduction, modification, use or disclosure of MediaTek Software, and * information contained herein, in whole or in part, shall be strictly * prohibited. * * MediaTek Inc. (C) 2010. All rights reserved. * * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE") * RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER * ON AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR * NONINFRINGEMENT. NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH * RESPECT TO THE SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, * INCORPORATED IN, OR SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES * TO LOOK ONLY TO SUCH THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. * RECEIVER EXPRESSLY ACKNOWLEDGES THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO * OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES CONTAINED IN MEDIATEK * SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE * RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S * ENTIRE AND CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE * RELEASED HEREUNDER WILL BE, AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE * MEDIATEK SOFTWARE AT ISSUE, OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE * CHARGE PAID BY RECEIVER TO MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE. * * The following software/firmware and/or related documentation ("MediaTek * Software") have been modified by MediaTek Inc. All revisions are subject to * any receiver's applicable license agreements with MediaTek Inc. */ package com.mediatek.fmradio.tests; import java.io.File; import com.jayway.android.robotium.solo.Solo; import android.app.ActionBar; import android.app.AlertDialog; import android.app.Instrumentation; import android.app.Instrumentation.ActivityMonitor; import android.content.Context; import android.database.Cursor; import android.media.AudioManager; import android.media.AudioManager.OnAudioFocusChangeListener; import android.net.Uri; import android.test.ActivityInstrumentationTestCase2; import android.util.Log; import android.view.KeyEvent; import android.view.MenuInflater; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.TextView; import com.mediatek.fmradio.FmRadioActivity; import com.mediatek.fmradio.FmRadioFavorite; import com.mediatek.fmradio.FmRadioUtils; import com.mediatek.fmradio.FmRadioStation; import com.mediatek.fmradio.R; public class FmRadioActivityTest extends ActivityInstrumentationTestCase2<FmRadioActivity> { private Instrumentation mInstrumentation = null; private Solo mSolo = null; private Context mContext = null; private ActivityMonitor mActivityMonitor = null; private ActionBar mActionBar = null; private FmRadioActivity mFmRadioActivity = null; private FmRadioFavorite mFmRadioFavorite = null; private AudioManager mAudioManager = null; private OnAudioFocusChangeListener mFMAudioFocusChangeListener = null; // bottom bar private ImageButton mButtonDecrease = null; private ImageButton mButtonPrevStation = null; private ImageButton mButtonNextStation = null; private ImageButton mButtonIncrease = null; // private ImageButton mButtonPlayStop = null; private MenuInflater mMenuInflater = null; // the star private ImageButton mButtonAddToFavorite = null; // record bar private ImageButton mButtonRecord = null; private ImageButton mButtonStop = null; private ImageButton mButtonPlayback = null; private AlertDialog mDialogRDSSetting = null; private Button mButtonRecordSave = null; private EditText mEditTextRecordName = null; private static final String CONTENTURI = "content://com.mediatek.fmradio.FmRadioContentProvider/station"; private TextView mTextViewFrequency = null; private static final int CHECK_TIME = 100; private static final int SHORT_TIME = 2000; private static final int ONE_SECOND = 1000; private static final int EXECUTE_TIME = 500; private static final int TIMEOUT = 5000; private static final int WAIT_TEAR_DOWN = 3000; private static final int WAIT_MOUNT_UNMOUNT = 7000; private static final int RECORDING_FILE_TIME = 10000; private static final long SEARCH_TIME = 20000; private static final int CONVERT_RATE = 10; private static final int TUNE_STEP = 1; private static final String TAG = "FmRadioFunctionTest"; public FmRadioActivityTest() { super("com.mediatek.fmradio", FmRadioActivity.class); } public FmRadioActivityTest(String pkg, Class<FmRadioActivity> activityClass) { super("com.mediatek.fmradio", FmRadioActivity.class); } @Override protected void setUp() { try { super.setUp(); } catch (Exception e) { e.printStackTrace(); } setActivityInitialTouchMode(false); mInstrumentation = this.getInstrumentation(); assertNotNull(mInstrumentation); mFmRadioActivity = getActivity(); assertNotNull(mFmRadioActivity); mSolo = new Solo(getInstrumentation(), mFmRadioActivity); mContext = mFmRadioActivity.getApplicationContext(); mAudioManager = (AudioManager) mFmRadioActivity.getSystemService(mContext.AUDIO_SERVICE); waitForPowerupWithTimeout(TIMEOUT); //waitForInitedWithTimeout(TIMEOUT); mButtonDecrease = (ImageButton) mFmRadioActivity.findViewById(R.id.button_decrease); mButtonPrevStation = (ImageButton) mFmRadioActivity.findViewById(R.id.button_prevstation); mButtonNextStation = (ImageButton) mFmRadioActivity.findViewById(R.id.button_nextstation); mButtonIncrease = (ImageButton) mFmRadioActivity.findViewById(R.id.button_increase); mButtonAddToFavorite = (ImageButton) mFmRadioActivity .findViewById(R.id.button_add_to_favorite); mButtonRecord = (ImageButton) mFmRadioActivity.findViewById(R.id.btn_record); mButtonStop = (ImageButton) mFmRadioActivity.findViewById(R.id.btn_stop); mButtonPlayback = (ImageButton) mFmRadioActivity.findViewById(R.id.btn_playback); mTextViewFrequency = (TextView) mFmRadioActivity .findViewById(R.id.station_value); } // click play/stop button. public void testCase01_PowerUpAndPowerDown() { boolean isPlaying = false; // test FM power down makeFMPowerUp(); mInstrumentation.waitForIdleSync(); FmRadioTestCaseUtil.requestFocusGain(mAudioManager); mSolo.sleep(SHORT_TIME); checkFMStopState(); // test FM power up mInstrumentation .invokeMenuActionSync(mFmRadioActivity, R.id.fm_power, 0); mInstrumentation.waitForIdleSync(); mSolo.sleep(SHORT_TIME); checkFMPlayingState(); } // click speaker/earphone menu item. public void testCase02_SwitchSpeakerAndEarphone() { if (!mButtonDecrease.isEnabled()) { makeFMPowerUp(); } String earphone = mFmRadioActivity.getString(R.string.optmenu_earphone); String speaker = mFmRadioActivity.getString(R.string.optmenu_speaker); // test FM switch to speaker switchSpeaker(); mSolo.sleep(EXECUTE_TIME); mInstrumentation .invokeMenuActionSync(mFmRadioActivity, R.id.fm_menu, 0); assertTrue(mSolo.searchText(earphone)); mSolo.goBack(); // test FM switch to earphone switchEarphone(); mSolo.sleep(EXECUTE_TIME); mInstrumentation .invokeMenuActionSync(mFmRadioActivity, R.id.fm_menu, 0); assertTrue(mSolo.searchText(speaker)); mSolo.goBack(); } // click favorite star. public void testCase03_AddDeleteFavoriteChannels() { int station = 0; // test add channel as favorite station = FmRadioTestCaseUtil.getStationFromUI(mTextViewFrequency); deleteChannelFromFavorite(station); clickView(mButtonAddToFavorite); mInstrumentation.waitForIdleSync(); mSolo.sleep(SHORT_TIME); assertTrue(FmRadioStation.isFavoriteStation(mFmRadioActivity, station)); // test delete channel from favorite station = FmRadioTestCaseUtil.getStationFromUI(mTextViewFrequency); addChannelAsFavorite(station); clickView(mButtonAddToFavorite); mInstrumentation.waitForIdleSync(); mSolo.sleep(SHORT_TIME); assertFalse(FmRadioStation.isFavoriteStation(mFmRadioActivity, station)); } // click tune frequency. public void testCase04_TuneFrequency() { int tuneStation = 0, currentStation = 0; if (!mButtonDecrease.isEnabled()) { makeFMPowerUp(); } // test decrease 0.1 MHZ tuneStation = FmRadioTestCaseUtil.getStationFromUI(mTextViewFrequency); clickView(mButtonDecrease); mInstrumentation.waitForIdleSync(); tuneStation -= TUNE_STEP; if (tuneStation < FmRadioTestCaseUtil.LOWEST_STATION) { tuneStation = FmRadioTestCaseUtil.HIGHEST_STATION; } // add sleep time, because instrumentation waitForIdleSync just wait for // UI thread end, must wait for all hardware and database operation end mSolo.sleep(SHORT_TIME); currentStation = FmRadioStation.getCurrentStation(mFmRadioActivity); assertEquals(tuneStation, currentStation); // add to favorite testCase03_AddDeleteFavoriteChannels(); // test increase 0.1 MHZ tuneStation = FmRadioTestCaseUtil.getStationFromUI(mTextViewFrequency); clickView(mButtonIncrease); mInstrumentation.waitForIdleSync(); tuneStation += TUNE_STEP; if (tuneStation > FmRadioTestCaseUtil.HIGHEST_STATION) { tuneStation = FmRadioTestCaseUtil.LOWEST_STATION; } mSolo.sleep(SHORT_TIME); currentStation = FmRadioStation.getCurrentStation(mFmRadioActivity); assertEquals(tuneStation, currentStation); } // click tune station public void testCase05_SwitchChannel() { int oldStation = 0, stationFromUI = 0, stationFromDB = 0; if (!mButtonPrevStation.isEnabled()) { makeFMPowerUp(); } // test seek previous station oldStation = FmRadioTestCaseUtil.getStationFromUI(mTextViewFrequency); clickView(mButtonPrevStation); mInstrumentation.waitForIdleSync(); mSolo.sleep(TIMEOUT); stationFromUI = FmRadioTestCaseUtil .getStationFromUI(mTextViewFrequency); // check station change assertTrue(oldStation != stationFromUI); // test seek next station oldStation = FmRadioTestCaseUtil.getStationFromUI(mTextViewFrequency); clickView(mButtonNextStation); mInstrumentation.waitForIdleSync(); mSolo.sleep(TIMEOUT); stationFromUI = FmRadioTestCaseUtil .getStationFromUI(mTextViewFrequency); // check station change assertTrue(oldStation != stationFromUI); } // click cancel when search channel. click back key when search channel. public void testCase06_CancelChannelSearch() { // check cancel scan when power up startScanWhenPowerUp(); checkCancelScan(); checkFMPlayingState(); } // search channel and tune to one station. public void testCase07_SearchChannels() { // check scan when power up startScanWhenPowerUp(); checkFinishScan(); } // enter channel list activity public void testCase08_EnterChannelList() { Log.d(TAG, ">>> testCase08_EnterChannelList"); if (!mButtonDecrease.isEnabled()) { makeFMPowerUp(); } mActivityMonitor = new ActivityMonitor( "com.mediatek.fmradio.FmRadioFavorite", null, false); mInstrumentation.addMonitor(mActivityMonitor); mInstrumentation.invokeMenuActionSync(mFmRadioActivity, R.id.fm_channel_list, 0); mFmRadioFavorite = (FmRadioFavorite) mActivityMonitor .waitForActivityWithTimeout(TIMEOUT); assertNotNull(mFmRadioFavorite); mSolo.sleep(SHORT_TIME); Uri uri = Uri.parse(CONTENTURI); Cursor c = mFmRadioFavorite.getContentResolver().query( uri, new String[] { FmRadioStation.Station._ID, FmRadioStation.Station.COLUMN_STATION_FREQ, FmRadioStation.Station.COLUMN_STATION_TYPE }, null, null, null); assertTrue(c != null && c.getCount() > 0); Log.d(TAG, "testCase08_EnterChannelList count:" + c.getCount()); try { if (c != null) { c.moveToFirst(); while (!c.isAfterLast()) { int stationFreq = c.getInt(1); int stationType = c.getInt(2); if ((FmRadioStation.STATION_TYPE_FAVORITE == stationType) || (FmRadioStation.STATION_TYPE_SEARCHED == stationType)) { Log.d(TAG, "testCase08_EnterChannelList stationFreq:" + stationFreq + ", stationType:" + stationType); assertTrue(FmRadioTestCaseUtil.isExistInChannelList( mFmRadioFavorite, stationFreq)); } c.moveToNext(); } } } catch (Exception e) { e.printStackTrace(); } finally { if (c != null) { c.close(); } } mInstrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK); Log.d(TAG, "<<< testCase08_EnterChannelList"); } // when play fm, audio focus loss, and stop fm public void testCase09_CheckFocusLoss() { mInstrumentation.waitForIdleSync(); makeFMPowerDown(); // check when power up, music get focus, fm power down //mInstrumentation // .invokeMenuActionSync(mFmRadioActivity, R.id.fm_power, 0); //mInstrumentation.waitForIdleSync(); mSolo.sleep(EXECUTE_TIME); //FmRadioTestCaseUtil.requestFocusGain(mAudioManager); //mInstrumentation.waitForIdleSync(); checkFMStopState(); //mSolo.sleep(SHORT_TIME); mSolo.sleep(SHORT_TIME); // fm is power up, check when fm is searching, focus is loss, fm power down startScanWhenPowerUp(); mSolo.sleep(SHORT_TIME); FmRadioTestCaseUtil.requestFocusGain(mAudioManager); mInstrumentation.waitForIdleSync(); mSolo.sleep(TIMEOUT); // check music is active, fm is power down checkFMStopState(); } public void testCase10_EnterRecordingMode() { enterRecordingMode(); mSolo.sleep(SHORT_TIME); checkRecordNotSaveIdle(); mInstrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK); mInstrumentation.waitForIdleSync(); checkFMPlayingState(); } // recording, discard, save. public void testCase11_RecordingAndSave() { enterRecordingMode(); mSolo.sleep(SHORT_TIME); // judge whether enter recording mode checkRecordNotSaveIdle(); // test recording clickView(mButtonRecord); mInstrumentation.waitForIdleSync(); mSolo.sleep(SHORT_TIME); checkRecordingState(); // make recording time have 3 seconds mSolo.sleep(SHORT_TIME); // test stop reocording and save recording file clickView(mButtonStop); mInstrumentation.waitForIdleSync(); mSolo.sleep(SHORT_TIME); checkRecordingStopState(); // enter some illegal characters mEditTextRecordName = (EditText) mSolo.getView(R.id.fm_recording_text); String fileName = mEditTextRecordName.getText().toString(); mSolo.clearEditText(mEditTextRecordName); mSolo.enterText(mEditTextRecordName, "test:"); mInstrumentation.waitForIdleSync(); mSolo.sleep(SHORT_TIME); mButtonRecordSave = (Button) mSolo.getView(R.id.fm_recording_btn_save); assertFalse(mButtonRecordSave.isEnabled()); // enter some legal characters mSolo.clearEditText(mEditTextRecordName); mSolo.enterText(mEditTextRecordName, fileName); mInstrumentation.waitForIdleSync(); mSolo.sleep(SHORT_TIME); assertTrue(mButtonRecordSave.isEnabled()); // click discard not save file mSolo.clickOnButton(mContext.getString(R.string.btn_discard_recording)); mInstrumentation.waitForIdleSync(); mSolo.sleep(SHORT_TIME); checkRecordNotSaveIdle(); // recording and make focus at OK button of save recording dialog clickView(mButtonRecord); mInstrumentation.waitForIdleSync(); mSolo.sleep(SHORT_TIME); checkRecordingState(); // make recording time have 3 seconds mSolo.sleep(SHORT_TIME); // test stop reocording and save recording file clickView(mButtonStop); mInstrumentation.waitForIdleSync(); mSolo.sleep(SHORT_TIME); checkRecordingStopState(); // click OK button of save recording dialog mSolo.clickOnButton(mContext.getString(R.string.btn_save_recording)); mInstrumentation.waitForIdleSync(); mSolo.sleep(SHORT_TIME); checkRecordHasSavedIdle(); mInstrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK); mInstrumentation.waitForIdleSync(); } // recording and playback. public void testCase12_RecordingAndPlayBack() { enterRecordingMode(); mSolo.sleep(TIMEOUT); // judge whether enter recording mode checkRecordNotSaveIdle(); // test recording clickView(mButtonRecord); mInstrumentation.waitForIdleSync(); mSolo.sleep(SHORT_TIME); checkRecordingState(); // make recording time have 3 seconds mSolo.sleep(SHORT_TIME); // test stop reocording and save recording file clickView(mButtonStop); mInstrumentation.waitForIdleSync(); mSolo.sleep(SHORT_TIME); checkRecordingStopState(); // click OK button of save recording dialog mSolo.clickOnButton(mContext.getString(R.string.btn_save_recording)); mInstrumentation.waitForIdleSync(); mSolo.sleep(SHORT_TIME); checkRecordHasSavedIdle(); // test playback recording file clickView(mButtonPlayback); mInstrumentation.waitForIdleSync(); mSolo.sleep(EXECUTE_TIME); checkPlayingBackState(); mSolo.sleep(TIMEOUT); checkPlayingBackFinished(); mSolo.sleep(SHORT_TIME); mInstrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK); mInstrumentation.waitForIdleSync(); } // test fm recreate when scan, and fm is powerup state. public void testCase14_relaunchFmWhenCancelScan() { Log.d(TAG, ">>> testCase14_relaunchFmWhenCancelScan"); int oldStation = FmRadioTestCaseUtil.getStationFromUI(mTextViewFrequency); String cancel = mFmRadioActivity.getString(R.string.btn_cancel); // test cancel scan checkRelaunchWhenScan(); // mInstrumentation.waitForIdleSync(); mSolo.clickOnButton(cancel); //mInstrumentation.waitForIdleSync(); mSolo.sleep(SHORT_TIME); checkFMPlayingState(); int stationFromUI = FmRadioTestCaseUtil .getStationFromUI(mTextViewFrequency); // check station not change assertTrue(oldStation == stationFromUI); checkRelaunchWhenScan(); checkFinishScan(); } // mount, unmount sd card when recording /*public void testCase15_mountUnmountWhenRecording() { FmRadioTestCaseUtil.mountSDCard(mContext); mInstrumentation.waitForIdleSync(); mSolo.sleep(WAIT_MOUNT_UNMOUNT); mSolo.sleep(SHORT_TIME); enterRecordingMode(); mSolo.sleep(SHORT_TIME); checkRecordNotSaveIdle(); String toastStartRecord = mContext.getString(R.string.toast_start_recording); String toastSdCardMiss = mContext.getString(R.string.toast_sdcard_missing); String save = mFmRadioActivity.getString(R.string.btn_save_recording); String discard = mFmRadioActivity.getString(R.string.btn_discard_recording); // unmount sd card when recording clickView(mButtonRecord); assertTrue(mSolo.waitForText(toastStartRecord, 0, SHORT_TIME)); mSolo.sleep(SHORT_TIME); FmRadioTestCaseUtil.unmountSDCard(mContext); mInstrumentation.waitForIdleSync(); mSolo.sleep(WAIT_MOUNT_UNMOUNT); assertFalse(mSolo.searchButton(save, true)); checkRecordNotSaveIdle(); // click record after unmount clickView(mButtonRecord); assertTrue(mSolo.waitForText(toastSdCardMiss)); checkRecordNotSaveIdle(); // check mount sd card and stop recording, popup save dialog, then unmount sd card FmRadioTestCaseUtil.mountSDCard(mContext); mInstrumentation.waitForIdleSync(); mSolo.sleep(WAIT_MOUNT_UNMOUNT); clickView(mButtonRecord); assertTrue(mSolo.waitForText(toastStartRecord, 0, SHORT_TIME)); mSolo.sleep(SHORT_TIME); clickView(mButtonStop); mInstrumentation.waitForIdleSync(); assertTrue(mSolo.searchButton(save, true)); FmRadioTestCaseUtil.unmountSDCard(mContext); mInstrumentation.waitForIdleSync(); mSolo.sleep(WAIT_MOUNT_UNMOUNT); assertFalse(mSolo.searchButton(save, true)); // mount sdcard finally FmRadioTestCaseUtil.mountSDCard(mContext); mInstrumentation.waitForIdleSync(); mSolo.sleep(WAIT_MOUNT_UNMOUNT); mInstrumentation.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK); mInstrumentation.waitForIdleSync(); } // mount, unmount sd card when recording public void testCase16_mountUnmountWhenPlayback() { // mount sdcard first FmRadioTestCaseUtil.mountSDCard(mContext); mInstrumentation.waitForIdleSync(); mSolo.sleep(WAIT_MOUNT_UNMOUNT); // record some and playback String save = mContext.getString(R.string.btn_save_recording); String error = mContext.getString(R.string.toast_player_internal_error); mSolo.sleep(SHORT_TIME); enterRecordingMode(); mSolo.sleep(SHORT_TIME); clickView(mButtonRecord); mInstrumentation.waitForIdleSync(); mSolo.sleep(RECORDING_FILE_TIME); clickView(mButtonStop); mInstrumentation.waitForIdleSync(); assertTrue(mSolo.searchButton(save, true)); mInstrumentation.waitForIdleSync(); mSolo.sleep(SHORT_TIME); mSolo.clickOnButton(save); mSolo.sleep(SHORT_TIME); clickView(mButtonPlayback); mInstrumentation.waitForIdleSync(); mSolo.sleep(SHORT_TIME); // unmount sd card FmRadioTestCaseUtil.unmountSDCard(mContext); mInstrumentation.waitForIdleSync(); assertTrue(mSolo.waitForText(error, 0, WAIT_MOUNT_UNMOUNT)); mSolo.sleep(WAIT_MOUNT_UNMOUNT); checkRecordNotSaveIdle(); mSolo.sleep(SHORT_TIME); // mount sdcard finally FmRadioTestCaseUtil.mountSDCard(mContext); mInstrumentation.waitForIdleSync(); mSolo.sleep(WAIT_MOUNT_UNMOUNT); }*/ // check fm exit when power up state public void testCase17_FmExit() { boolean isPlaying = false; // test FM power down makeFMPowerUp(); mInstrumentation.waitForIdleSync(); mSolo.sleep(SHORT_TIME); // test FM power up mInstrumentation .invokeMenuActionSync(mFmRadioActivity, R.id.fm_power, 0); mSolo.sleep(SHORT_TIME); } // check fm back key when power down state public void testCase18_FmBackKeyExit() { boolean isPlaying = false; makeFMPowerUp(); mInstrumentation.waitForIdleSync(); FmRadioTestCaseUtil.requestFocusGain(mAudioManager); mSolo.sleep(SHORT_TIME); checkFMStopState(); mSolo.goBack(); mSolo.sleep(SHORT_TIME); } // check fm tune from channel list public void testCase19_relaunchFmTuneToStation() { boolean isPlaying = false; makeFMPowerUp(); // add to favorite int station = 0; // test add channel as favorite station = FmRadioTestCaseUtil.getStationFromUI(mTextViewFrequency); deleteChannelFromFavorite(station); clickView(mButtonAddToFavorite); mInstrumentation.waitForIdleSync(); mSolo.sleep(SHORT_TIME); assertTrue(FmRadioStation.isFavoriteStation(mFmRadioActivity, station)); // test FM power up mInstrumentation .invokeMenuActionSync(mFmRadioActivity, R.id.fm_channel_list, 0); mSolo.sleep(SHORT_TIME); mInstrumentation.waitForIdleSync(); FmRadioTestCaseUtil.requestFocusGain(mAudioManager); mSolo.sleep(SHORT_TIME); relaunchFm(); mFmRadioFavorite = (FmRadioFavorite) mSolo.getCurrentActivity(); mSolo = new Solo(mInstrumentation, mFmRadioFavorite); mContext = mFmRadioFavorite.getApplicationContext(); station = FmRadioTestCaseUtil.getStationFromUI(mTextViewFrequency); String pStation = String.valueOf((float) station / CONVERT_RATE); mSolo.clickOnText(pStation); mInstrumentation.waitForIdleSync(); // delete favorite deleteChannelFromFavorite(station); mSolo.sleep(SHORT_TIME); checkFMPlayingState(); } // recorder. save same name recorder file public void testCase20_saveRecorderWithSameName() { enterRecordingMode(); File sdDir = new File(FmRadioUtils.getDefaultStoragePath()); File recordingFile = new File(sdDir.getPath() + "/FM Recording", "recorder_file.ogg"); if (recordingFile.exists()) { recordingFile.delete(); } mSolo.sleep(SHORT_TIME); // record some and playback String save = mContext.getString(R.string.btn_save_recording); String error = mContext.getString(R.string.toast_player_internal_error); // save recorder file clickView(mButtonRecord); mInstrumentation.waitForIdleSync(); mSolo.sleep(SHORT_TIME); clickView(mButtonStop); mInstrumentation.waitForIdleSync(); assertTrue(mSolo.searchButton(save, true)); mInstrumentation.waitForIdleSync(); EditText editText = (EditText) mSolo.getView(R.id.fm_recording_text); mSolo.clearEditText(editText); mSolo.enterText(editText, "recorder_file"); mInstrumentation.waitForIdleSync(); InputMethodManager inputMethodManager = (InputMethodManager) mSolo.getCurrentActivity().getSystemService(Context.INPUT_METHOD_SERVICE); inputMethodManager.toggleSoftInput(0, 0); mSolo.clickOnButton(save); mSolo.sleep(SHORT_TIME); // save recorder file with same name clickView(mButtonRecord); mInstrumentation.waitForIdleSync(); mSolo.sleep(SHORT_TIME); clickView(mButtonStop); mInstrumentation.waitForIdleSync(); assertTrue(mSolo.searchButton(save, true)); mInstrumentation.waitForIdleSync(); editText = (EditText) mSolo.getView(R.id.fm_recording_text); mSolo.clearEditText(editText); mSolo.enterText(editText, "recorder_file"); mInstrumentation.waitForIdleSync(); InputMethodManager inputMethodManager2 = (InputMethodManager) mSolo.getCurrentActivity().getSystemService(Context.INPUT_METHOD_SERVICE); inputMethodManager2.toggleSoftInput(0, 0); mSolo.clickOnButton(save); // check file has exist String hasFile = mContext.getString(R.string.already_exists); assertTrue(mSolo.waitForText(hasFile, 0, SHORT_TIME)); // discard save record file String discard = mFmRadioActivity.getString(R.string.btn_discard_recording); mSolo.clickOnButton(discard); mInstrumentation.waitForIdleSync(); // File sdDir = new File(FmRadioUtils.getInternalStoragePath()); // File recordingFile = new File(sdDir.getPath() + "/FM Recording", "recorder_file"); if (recordingFile.exists()) { recordingFile.delete(); } checkRecordNotSaveIdle(); } // check scan dialog, and fm is powerup sate when recreate private void checkRelaunchWhenScan() { Log.d(TAG, ">>> checkRelaunchWhenScan"); startScanWhenPowerUp(); //mSolo.sleep(ONE_SECOND); String cancel = mFmRadioActivity.getString(R.string.btn_cancel); boolean isVisible = mSolo.searchButton(cancel, true); assertTrue(isVisible); //relaunch after start scan relaunchFm(); //mInstrumentation.waitForIdleSync(); mSolo.sleep(ONE_SECOND); Log.d(TAG, "current activity:" + mSolo.getCurrentActivity().getComponentName()); initialRel(); mSolo.sleep(ONE_SECOND); //check dialog is shown after relaunch isVisible = mSolo.searchButton(cancel, true); assertTrue(isVisible); Log.d(TAG, "<<< checkRelaunchWhenScan"); } private void relaunchFm() { mSolo.getCurrentActivity().runOnUiThread(new Runnable() { @Override public void run() { Log.d(TAG, "sub thread relaunchFm start"); mSolo.getCurrentActivity().recreate(); Log.d(TAG, "sub thread relaunchFm end"); } }); } private void enterRecordingMode() { if (!mButtonDecrease.isEnabled()) { makeFMPowerUp(); } mInstrumentation .invokeMenuActionSync(mFmRadioActivity, R.id.fm_menu, 0); mSolo.sleep(EXECUTE_TIME); String record = mFmRadioActivity.getString(R.string.optmenu_record); mSolo.clickOnText(record); mInstrumentation.waitForIdleSync(); } // check ui and state when no recording file saved. public void checkRecordNotSaveIdle() { assertTrue(mButtonRecord.isEnabled()); assertFalse(mButtonPlayback.isEnabled()); assertFalse(mButtonStop.isEnabled()); assertTrue(mButtonAddToFavorite.getVisibility() == View.GONE); } // check ui and state while recording. public void checkRecordingState() { assertFalse(mButtonRecord.isEnabled()); assertFalse(mButtonPlayback.isEnabled()); assertTrue(mButtonStop.isEnabled()); assertTrue(mButtonAddToFavorite.getVisibility() == View.GONE); } // check ui and state when recording stop public void checkRecordingStopState() { mButtonRecordSave = (Button) mSolo.getView(R.id.fm_recording_btn_save); assertTrue(mButtonRecordSave.isEnabled()); assertTrue(mButtonAddToFavorite.getVisibility() == View.GONE); } // check ui and state when save an recording file. public void checkRecordHasSavedIdle() { assertTrue(mButtonRecord.isEnabled()); assertTrue(mButtonPlayback.isEnabled()); assertFalse(mButtonStop.isEnabled()); assertTrue(mButtonAddToFavorite.getVisibility() == View.GONE); } // check ui and state while playing back an recordfing file. public void checkPlayingBackState() { assertFalse(mButtonRecord.isEnabled()); assertFalse(mButtonPlayback.isEnabled()); assertTrue(mButtonStop.isEnabled()); assertTrue(mButtonAddToFavorite.getVisibility() == View.GONE); } // check ui and state when play back an recording file finish. public void checkPlayingBackFinished() { assertTrue(mButtonRecord.isEnabled()); assertTrue(mButtonPlayback.isEnabled()); assertFalse(mButtonStop.isEnabled()); assertTrue(mButtonAddToFavorite.getVisibility() == View.GONE); } // check state, if cancel scan public void checkCancelScan() { mSolo.sleep(SHORT_TIME); String cancel = mFmRadioActivity.getString(R.string.btn_cancel); mSolo.clickOnText(cancel); mInstrumentation.waitForIdleSync(); int currentStation = (Integer) FmRadioTestCaseUtil .getVariableFromActivity(mFmRadioActivity, "mCurrentStation"); assertEquals(currentStation, FmRadioTestCaseUtil.getStationFromUI(mTextViewFrequency)); mSolo.sleep(SHORT_TIME); } // check state, if finish scan public void checkFinishScan() { Log.d(TAG, ">>> checkFinishScan"); //mInstrumentation.waitForIdleSync(); mActivityMonitor = mInstrumentation.addMonitor( FmRadioFavorite.class.getName(), null, false); Log.d(TAG, "current activity:" + mSolo.getCurrentActivity().getComponentName()); mFmRadioFavorite = (FmRadioFavorite) mInstrumentation .waitForMonitorWithTimeout(mActivityMonitor, SEARCH_TIME); mSolo.sleep(SHORT_TIME); Log.d(TAG, "mFmRadioFavorite is " + mFmRadioFavorite); assertNotNull(mFmRadioFavorite); // test data in database. Uri uri = Uri.parse(CONTENTURI); Cursor c = mFmRadioFavorite.getContentResolver().query( uri, new String[] { FmRadioStation.Station._ID, FmRadioStation.Station.COLUMN_STATION_FREQ, FmRadioStation.Station.COLUMN_STATION_TYPE }, null, null, null); assertTrue(c != null && c.getCount() > 0); int stationFreq = 0; int stationType = 0; if (c != null) { c.moveToFirst(); while (!c.isAfterLast()) { stationFreq = c.getInt(1); stationType = c.getInt(2); Log.d(TAG, "station =" + stationFreq); if (FmRadioStation.STATION_TYPE_SEARCHED == stationType) { assertTrue(FmRadioTestCaseUtil.isExistInChannelList( mFmRadioFavorite, stationFreq)); } c.moveToNext(); } } if (c != null) { c.close(); } // click the last station in listview to play. String pStation = String.valueOf((float) stationFreq / CONVERT_RATE); mSolo.clickOnText(pStation); mInstrumentation.waitForIdleSync(); mSolo.sleep(SHORT_TIME); assertEquals(stationFreq, FmRadioTestCaseUtil.getStationFromUI(mTextViewFrequency)); checkFMPlayingState(); } private void switchEarphone() { if (!mButtonDecrease.isEnabled()) { makeFMPowerUp(); } mInstrumentation .invokeMenuActionSync(mFmRadioActivity, R.id.fm_menu, 0); String earphone = mFmRadioActivity.getString(R.string.optmenu_earphone); mSolo.clickOnText(earphone); mInstrumentation.waitForIdleSync(); } private void switchSpeaker() { if (!mButtonDecrease.isEnabled()) { makeFMPowerUp(); } mInstrumentation .invokeMenuActionSync(mFmRadioActivity, R.id.fm_menu, 0); String speaker = mFmRadioActivity.getString(R.string.optmenu_speaker); mSolo.clickOnText(speaker); mInstrumentation.waitForIdleSync(); } private void deleteChannelFromFavorite(int station) { if (FmRadioStation.isFavoriteStation(mFmRadioActivity, station)) { clickView(mButtonAddToFavorite); mInstrumentation.waitForIdleSync(); mSolo.sleep(SHORT_TIME); } } private void addChannelAsFavorite(int station) { if (!FmRadioStation.isFavoriteStation(mFmRadioActivity, station)) { clickView(mButtonAddToFavorite); mInstrumentation.waitForIdleSync(); mSolo.sleep(SHORT_TIME); } } private void makeFMPowerUp() { boolean isPlaying = false; isPlaying = (Boolean) FmRadioTestCaseUtil.getVariableFromActivity( mFmRadioActivity, "mIsPlaying"); if (!isPlaying) { mInstrumentation .invokeMenuActionSync(mFmRadioActivity, R.id.fm_power, 0); } //mInstrumentation.waitForIdleSync(); mSolo.sleep(TIMEOUT); } private void makeFMPowerDown() { boolean isPlaying = true; isPlaying = (Boolean) FmRadioTestCaseUtil.getVariableFromActivity( mFmRadioActivity, "mIsPlaying"); if (isPlaying) { FmRadioTestCaseUtil.requestFocusGain(mAudioManager); } mInstrumentation.waitForIdleSync(); mSolo.sleep(SHORT_TIME); } private void clickView(final View view) { try { runTestOnUiThread(new Runnable() { @Override public void run() { view.performClick(); } }); } catch (Throwable t) { t.printStackTrace(); } } private void waitForInitedWithTimeout(long timeOut) { long startTime = System.currentTimeMillis(); boolean isInited = (Boolean) FmRadioTestCaseUtil .getVariableFromMethod(mFmRadioActivity, "isServiceInited"); while (!isInited) { if (System.currentTimeMillis() - startTime > timeOut) { break; } mSolo.sleep(CHECK_TIME); } } private void waitForPowerupWithTimeout(long timeOut) { long startTime = System.currentTimeMillis(); boolean isPlaying = (Boolean) FmRadioTestCaseUtil .getVariableFromActivity(mFmRadioActivity, "mIsPlaying"); while (!isPlaying) { if (System.currentTimeMillis() - startTime > timeOut) { break; } mSolo.sleep(CHECK_TIME); } } // start scan when power up state private void startScanWhenPowerUp() { if (!mButtonDecrease.isEnabled()) { makeFMPowerUp(); } mInstrumentation .invokeMenuActionSync(mFmRadioActivity, R.id.fm_menu, 0); mInstrumentation.waitForIdleSync(); mSolo.sleep(ONE_SECOND); String search = mFmRadioActivity.getString(R.string.optmenu_search); mSolo.clickOnText(search); } // check play FM layout button enable public void checkFMPlayingState() { assertTrue(mButtonDecrease.isEnabled()); assertTrue(mButtonIncrease.isEnabled()); assertTrue(mButtonNextStation.isEnabled()); assertTrue(mButtonPrevStation.isEnabled()); } // check play FM layout button enable public void checkFMStopState() { assertFalse(mButtonDecrease.isEnabled()); assertFalse(mButtonPrevStation.isEnabled()); assertFalse(mButtonNextStation.isEnabled()); assertFalse(mButtonIncrease.isEnabled()); } public void initialRel() { mFmRadioActivity = (FmRadioActivity) mSolo.getCurrentActivity(); mSolo = new Solo(mInstrumentation, mFmRadioActivity); mContext = mFmRadioActivity.getApplicationContext(); assertNotNull(mFmRadioActivity); mButtonPrevStation = (ImageButton) mFmRadioActivity.findViewById(R.id.button_prevstation); mButtonNextStation = (ImageButton) mFmRadioActivity.findViewById(R.id.button_nextstation); mButtonDecrease = (ImageButton) mFmRadioActivity.findViewById(R.id.button_decrease); mButtonIncrease = (ImageButton) mFmRadioActivity.findViewById(R.id.button_increase); mButtonAddToFavorite = (ImageButton) mFmRadioActivity .findViewById(R.id.button_add_to_favorite); mTextViewFrequency = (TextView) mFmRadioActivity .findViewById(R.id.station_value); } @Override protected void tearDown() { mSolo.finishOpenedActivities(); mInstrumentation.waitForIdleSync(); FmRadioTestCaseUtil.sleep(WAIT_TEAR_DOWN); try { mSolo.finalize(); } catch (Throwable t) { t.printStackTrace(); } try { super.tearDown(); } catch (Exception e) { e.printStackTrace(); } } }
/******************************************************************************* * Copyright (c) 2015-2016, WSO2.Telco Inc. (http://www.wso2telco.com) All Rights Reserved. * * WSO2.Telco Inc. licences 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.wso2telco.core.dbutils.exception; public enum ServiceError implements ThrowableError { SERVICE_ERROR_OCCURED("SVC0001", "A service error occurred. Error code is %1"), INVALID_INPUT_VALUE("SVC0002", "Invalid input value for message part %1"), INVALID_ADDRESS("SVC0004", "No valid addresses provided in message part %1"); private String code; private String message; private ServiceError(String code, String message) { this.code = code; this.message = message; } @Override public String getMessage() { return message; } @Override public String getCode() { return code; } }
package ca.ubc.ece.salt.pangor.original.js.learn.statements; import ca.ubc.ece.salt.gumtree.ast.ClassifiedASTNode; import ca.ubc.ece.salt.pangor.original.analysis.SourceCodeFileAnalysis; import ca.ubc.ece.salt.pangor.original.analysis.SourceCodeFileChange; import ca.ubc.ece.salt.pangor.original.cfg.CFG; import java.util.List; import java.util.Map; import org.deri.iris.api.basics.IPredicate; import org.deri.iris.storage.IRelation; import org.mozilla.javascript.ast.AstRoot; public class StatementScriptAnalysis extends SourceCodeFileAnalysis { public void analyze(SourceCodeFileChange sourceCodeFileChange, Map<IPredicate, IRelation> facts, ClassifiedASTNode root, List<CFG> cfgs) throws Exception { if (!(root instanceof AstRoot)) { throw new IllegalArgumentException("The AST must be parsed from Eclipse JDT."); } AstRoot script = (AstRoot)root; StatementAnalysisVisitor.getLearningFacts(facts, sourceCodeFileChange, script, null, true); } }
package edu.suda.ada.core; import org.ethereum.util.ByteUtil; import org.ethereum.vm.program.InternalTransaction; /** * Created by LiYang on 2016/11/28. */ public class SimpleInternalTransaction extends SimpleBasicTransaction { private String parentHash; private int deep; private int index; private boolean rejected = false; private String note; public SimpleInternalTransaction(InternalTransaction internalTransaction) { setTransaction(internalTransaction); this.parentHash = ByteUtil.toHexString(internalTransaction.getParentHash()); this.deep = internalTransaction.getDeep(); this.index = internalTransaction.getIndex(); this.rejected = internalTransaction.isRejected(); this.note = internalTransaction.getNote(); } public String getParentHash() { return parentHash; } public void setParentHash(String parentHash) { this.parentHash = parentHash; } public int getDeep() { return deep; } public void setDeep(int deep) { this.deep = deep; } public int getIndex() { return index; } public void setIndex(int index) { this.index = index; } public boolean isRejected() { return rejected; } public void setRejected(boolean rejected) { this.rejected = rejected; } public String getNote() { return note; } public void setNote(String note) { this.note = note; } }
/*! * Copyright (C) 2017 by Hitachi Vantara : http://www.pentaho.com * * 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.apache.hop.vfs.gs; import org.apache.commons.vfs2.Capability; import org.apache.commons.vfs2.FileName; import org.apache.commons.vfs2.FileSystem; import org.apache.commons.vfs2.FileSystemException; import org.apache.commons.vfs2.FileSystemOptions; import org.apache.commons.vfs2.provider.AbstractOriginatingFileProvider; import java.util.Arrays; import java.util.Collection; import java.util.Collections; public class GoogleDriveFileProvider extends AbstractOriginatingFileProvider { public static final String SCHEME = "googledrive"; public static final String DISPLAY_NAME = "Google Drive"; protected static final Collection<Capability> capabilities = Collections.unmodifiableCollection( Arrays.asList( new Capability[] { Capability.CREATE, Capability.DELETE, Capability.RENAME, Capability.GET_TYPE, Capability.LIST_CHILDREN, Capability.READ_CONTENT, Capability.URI, Capability.WRITE_CONTENT, Capability.GET_LAST_MODIFIED, Capability.RANDOM_ACCESS_READ } ) ); public FileSystem doCreateFileSystem( FileName fileName, FileSystemOptions fileSystemOptions ) throws FileSystemException { return new GoogleDriveFileSystem( fileName, fileSystemOptions ); } public Collection<Capability> getCapabilities() { return capabilities; } }
/** * Copyright 2011 Rogier Oudshoorn * <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 org.dd4t.core.factories.impl; /** * Backwards compatibility class * @author Rogier Oudshoorn * */ @Deprecated public class GenericPageFactory extends PageFactoryImpl { }
package org.basex.query.func; import static org.basex.query.QueryError.*; import static org.basex.query.QueryText.*; import org.basex.query.*; import org.basex.query.ann.*; import org.basex.query.expr.*; import org.basex.query.util.*; import org.basex.query.value.*; import org.basex.query.value.item.*; import org.basex.query.value.node.*; import org.basex.query.var.*; import org.basex.util.*; import org.basex.util.hash.*; /** * Function call for user-defined functions. * * @author BaseX Team 2005-19, BSD License * @author Christian Gruen */ public final class StaticFuncCall extends FuncCall { /** Static context of this function call. */ private final StaticContext sc; /** Function name. */ final QNm name; /** Function reference. */ StaticFunc func; /** * Function call constructor. * @param name function name * @param args arguments * @param sc static context * @param info input info */ public StaticFuncCall(final QNm name, final Expr[] args, final StaticContext sc, final InputInfo info) { this(name, args, sc, null, info); } /** * Copy constructor. * @param name function name * @param args arguments * @param sc static context * @param func referenced function (can be {@code null}) * @param info input info */ private StaticFuncCall(final QNm name, final Expr[] args, final StaticContext sc, final StaticFunc func, final InputInfo info) { super(info, args); this.sc = sc; this.name = name; this.func = func; } @Override public Expr compile(final CompileContext cc) throws QueryException { super.compile(cc); checkVisible(); // compile mutually recursive functions func.comp(cc); // try to inline the function final Expr in = func.inline(exprs, cc); if(in != null) return in; exprType.assign(func.seqType()); return this; } @Override public StaticFuncCall optimize(final CompileContext cc) { // do not inline a static function after compilation as it must be recursive return this; } @Override public StaticFuncCall copy(final CompileContext cc, final IntObjMap<Var> vm) { return copyType(new StaticFuncCall(name, Arr.copyAll(cc, vm, exprs), sc, func, info)); } /** * Initializes the function and checks for visibility. * @param sf function reference * @return self reference * @throws QueryException query exception */ public StaticFuncCall init(final StaticFunc sf) throws QueryException { func = sf; checkVisible(); return this; } /** * Checks if the called function is visible * (i.e., has no private annotation or is in the same namespace). * @throws QueryException query exception */ private void checkVisible() throws QueryException { if(func.anns.contains(Annotation.PRIVATE) && !func.sc.baseURI().eq(sc.baseURI())) throw FUNCPRIVATE_X.get(info, name.string()); } /** * Returns the called function if already known. * @return the function or {@code null} */ public StaticFunc func() { return func; } @Override public boolean isVacuous() { return func.isVacuousBody(); } @Override public boolean has(final Flag... flags) { // check arguments, which will be evaluated previous to the function body if(super.has(flags)) return true; // function code: position or context references of expression body have no effect if(Flag.POS.in(flags) || Flag.CTX.in(flags)) return false; // function code: check for updates if(Flag.UPD.in(flags) && func.updating()) return true; // check remaining flags final Flag[] flgs = Flag.UPD.remove(flags); return flgs.length != 0 && func.has(flgs); } @Override public boolean accept(final ASTVisitor visitor) { return visitor.staticFuncCall(this) && super.accept(visitor); } @Override public StaticFunc evalFunc(final QueryContext qc) { return func; } @Override Value[] evalArgs(final QueryContext qc) throws QueryException { final int al = exprs.length; final Value[] args = new Value[al]; for(int a = 0; a < al; ++a) args[a] = exprs[a].value(qc); return args; } @Override public boolean equals(final Object obj) { if(this == obj) return true; if(!(obj instanceof StaticFuncCall)) return false; final StaticFuncCall s = (StaticFuncCall) obj; return name.eq(s.name) && func == s.func && super.equals(obj); } @Override public void plan(final FElem plan) { addPlan(plan, planElem(NAME, name.string(), TCL, tco), exprs); } @Override public String description() { return "function"; } @Override public String toString() { return Strings.concat(name.prefixId(), toString(SEP)); } }
// -------------------------------------------------------------------------------- // Copyright 2002-2022 Echo Three, LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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.echothree.control.user.campaign.common.spec; import com.echothree.util.common.form.BaseSpec; public interface CampaignTermSpec extends BaseSpec { String getCampaignTermName(); void setCampaignTermName(String campaignTermName); }
package com.doctor.commons; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.hamcrest.core.IsEqual; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; public class ReflectionUtilsTest { @Rule public ExpectedException expectedException = ExpectedException.none(); @Test public void test_newInstance_默认构造函数调用() throws Throwable { @SuppressWarnings("unchecked") Map<String, String> map = ReflectionUtils.newInstance(HashMap.class); Assert.assertTrue(map.isEmpty()); String string = ReflectionUtils.newInstance(String.class); Assert.assertThat(string, IsEqual.equalTo("")); } @Test public void test_newInstance_私有默认构造函数调用() throws Throwable { expectedException.expect(IllegalAccessException.class); ReflectionUtils.newInstance(TestClass.class, false); } @Test public void test_newInstance_私有默认构造函数调用_true() throws Throwable { ReflectionUtils.newInstance(TestClass.class); ReflectionUtils.newInstance(TestClass.class); } @Test public void test_newInstance_带参构造函数调用() throws Throwable { Integer integer = ReflectionUtils.newInstance(Integer.class, new Class<?>[] { int.class }, new Object[] { 2 }); Assert.assertThat(integer, IsEqual.equalTo(Integer.valueOf(2))); integer = ReflectionUtils.newInstance(Integer.class, new Class<?>[] { int.class }, new Object[] { 2 }); Assert.assertThat(integer, IsEqual.equalTo(Integer.valueOf(2))); TestClass testClass = ReflectionUtils.newInstance(TestClass.class, new Class<?>[] { int.class }, new Object[] { 3 }); Assert.assertThat(testClass.getIndex(), IsEqual.equalTo(3)); } @Test public void test_getMethodSignature() throws NoSuchMethodException, SecurityException { Method method = TestClass.class.getMethod("getIndex"); String methodSignature = ReflectionUtils.getMethodSignature(method); Assert.assertThat(methodSignature, IsEqual.equalTo("int#getIndex")); method = TestClass.class.getMethod("setIndex", int.class); methodSignature = ReflectionUtils.getMethodSignature(method); Assert.assertThat(methodSignature, IsEqual.equalTo("void#setIndex:int")); } @Test public void test_() { Set<Method> findCandidateMethods = ReflectionUtils.findCandidateMethods(TestClass.class, "getIndex"); System.out.println(findCandidateMethods); } private static class TestClass { private int index = -1; private TestClass() { } public TestClass(int index) { this.index = index; } public int getIndex() { return index; } public int getIndex(short in) { return index; } public void setIndex(int index) { this.index = index; } } }
package apavlov; /** * The interface Store - have methods add, delete, update. * * @param <T> This describes my type parameter * * @author Pavlov Artem * @since 17.09.2017 */ public interface Store<T extends Base> { /** * The method add new element to base. * * @param value - value; */ void add(T value); /** * The method delete element to base. * * @param value - value; * @return false - if is not edit; true - if is edit; */ boolean delete(T value); /** * The method edit element to base. * * @param oldElement - element for edit; * @param newElement - new element; * @return old element; */ T update(T oldElement, T newElement); }
public class Item { ///Atributos private int naSala; private int quantidade; ///Métodos public Item(){ quantidade = 0; } public Item(int naSala){ this.naSala = naSala; quantidade = 0; } public int getNaSala() { return naSala; } public void setNaSala(int naSala) { this.naSala = naSala; } public int getQuantidade() { return quantidade; } public void setQuantidade(int quantidade) { this.quantidade = quantidade; } }
/* * Copyright 2018 The GraphicsFuzz Project 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.graphicsfuzz.common.util; import com.graphicsfuzz.common.ast.TranslationUnit; import com.graphicsfuzz.common.ast.visitors.AstBuilder; import com.graphicsfuzz.common.glslversion.ShadingLanguageVersion; import com.graphicsfuzz.parser.GLSLLexer; import com.graphicsfuzz.parser.GLSLParser; import com.graphicsfuzz.parser.GLSLParser.Translation_unitContext; import com.graphicsfuzz.util.ExecHelper; import com.graphicsfuzz.util.ExecResult; import com.graphicsfuzz.util.ToolPaths; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.nio.charset.StandardCharsets; import java.util.Optional; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.antlr.v4.runtime.ANTLRInputStream; import org.antlr.v4.runtime.BailErrorStrategy; import org.antlr.v4.runtime.CommonTokenStream; import org.antlr.v4.runtime.atn.LexerATNSimulator; import org.antlr.v4.runtime.atn.ParserATNSimulator; import org.antlr.v4.runtime.atn.PredictionContextCache; import org.antlr.v4.runtime.atn.PredictionMode; import org.antlr.v4.runtime.misc.ParseCancellationException; import org.antlr.v4.runtime.tree.ParseTreeListener; import org.apache.commons.io.FileUtils; import org.apache.commons.io.FilenameUtils; public class ParseHelper { public static final String END_OF_GRAPHICSFUZZ_DEFINES = "// END OF GENERATED HEADER"; public static Optional<TranslationUnit> maybeParseShader(File shader) throws IOException, ParseTimeoutException, InterruptedException, GlslParserException { return shader.isFile() ? Optional.of(parse(shader)) : Optional.empty(); } public static synchronized TranslationUnit parse(File file) throws IOException, ParseTimeoutException, InterruptedException, GlslParserException { return parseInputStream(new ByteArrayInputStream(FileUtils.readFileToByteArray(file)), ShaderKind.fromExtension(FilenameUtils.getExtension(file.getName()))); } public static synchronized TranslationUnit parse(String string, ShaderKind shaderKind) throws IOException, ParseTimeoutException, InterruptedException, GlslParserException { return parseInputStream(new ByteArrayInputStream(string.getBytes(StandardCharsets.UTF_8)), shaderKind); } /** * Parses a shader from a given string. The shader is assumed to be a fragment shader; * typically the shader kind is unimportant when we parse from strings. * @param string The shader text to be parsed. * @return The parsed shader. * @throws IOException Thrown if parsing leads to an IO exception. * @throws ParseTimeoutException Thrown if parsing takes to long. */ public static synchronized TranslationUnit parse(String string) throws IOException, ParseTimeoutException, InterruptedException, GlslParserException { return parse(string, ShaderKind.FRAGMENT); } private static synchronized TranslationUnit parseInputStream(InputStream input, ShaderKind shaderKind) throws IOException, ParseTimeoutException, InterruptedException, GlslParserException { final boolean hasWebGlHint = checkForWebGlHint(input); // Strip special GraphicsFuzz defines and run preprocessor final InputStream preprocessedInput = preprocess(stripGraphicsFuzzDefines(input), shaderKind); // Parse the preprocessed shader final int timeLimit = 60; ParseTreeListener listener = new TimeoutParseTreeListener( System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(timeLimit)); Translation_unitContext ctx; try { try { ctx = tryFastParse(preprocessedInput, listener); } catch (ParseCancellationException exception) { preprocessedInput.reset(); ctx = slowParse(preprocessedInput, listener); } } catch (ParseTimeoutRuntimeException exception) { throw new ParseTimeoutException(exception); } return AstBuilder.getTranslationUnit(ctx, shaderKind, hasWebGlHint); } private static boolean checkForWebGlHint(InputStream input) throws IOException { try (BufferedReader br = new BufferedReader(new InputStreamReader(input))) { if (br.readLine() == null) { return false; } final String maybeHint = br.readLine(); if (maybeHint == null) { return false; } return ShadingLanguageVersion.isWebGlHint(maybeHint); } finally { input.reset(); } } private static InputStream preprocess(InputStream inputStream, ShaderKind shaderKind) throws IOException, InterruptedException { // Preprocess the shader using glslangValidator final ExecResult preprocessorResult = new ExecHelper().exec(ExecHelper.RedirectType.TO_BUFFER, null, false, inputStream, ToolPaths.glslangValidator(), "-E", "--stdin", "-S", shaderKind.getFileExtension()); if (preprocessorResult.res != 0) { throw new RuntimeException("Preprocessing failed with exit code " + preprocessorResult.res + ": " + preprocessorResult.stderr); } return new ByteArrayInputStream(preprocessorResult.stdout .toString().getBytes(StandardCharsets.UTF_8)); } private static Translation_unitContext tryFastParse( InputStream inputStream, ParseTreeListener listener) throws IOException { GLSLParser parser = getParser(inputStream, listener); parser.setErrorHandler(new BailErrorStrategy()); parser.getInterpreter().setPredictionMode(PredictionMode.SLL); Translation_unitContext result = parser.translation_unit(); parser.getInterpreter().clearDFA(); return result; } private static Translation_unitContext slowParse( InputStream inputStream, ParseTreeListener listener) throws IOException, GlslParserException { GLSLParser parser = getParser(inputStream, listener); try { Translation_unitContext tu = parser.translation_unit(); if (parser.getNumberOfSyntaxErrors() > 0) { throw new GlslParserException(parser); } return tu; } finally { parser.getInterpreter().clearDFA(); } } private static GLSLParser getParser( InputStream inputStream, ParseTreeListener listener) throws IOException { ANTLRInputStream input = new ANTLRInputStream(inputStream); GLSLLexer lexer = new GLSLLexer(input); PredictionContextCache cache = new PredictionContextCache(); lexer.setInterpreter( new LexerATNSimulator(lexer, lexer.getATN(), lexer.getInterpreter().decisionToDFA, cache)); CommonTokenStream tokens = new CommonTokenStream(lexer); GLSLParser parser = new GLSLParser(tokens); // Remove error listeners, otherwise errors get output to the console. parser.removeErrorListeners(); if (listener != null) { parser.addParseListener(listener); } parser.setInterpreter( new ParserATNSimulator(parser, parser.getATN(), parser.getInterpreter().decisionToDFA, cache)); return parser; } static InputStream stripGraphicsFuzzDefines(InputStream inputStream) throws IOException { if (!containsEndOfGraphicsFuzzDefines(inputStream)) { return inputStream; } ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try ( BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(outputStream)); BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) { boolean passedEndOfGraphicsFuzzDefines = false; String line; while ((line = br.readLine()) != null) { if (passedEndOfGraphicsFuzzDefines || isVersion(line) || ShadingLanguageVersion.isWebGlHint(line)) { bw.write(line + "\n"); } else { if (line.trim().startsWith(END_OF_GRAPHICSFUZZ_DEFINES)) { passedEndOfGraphicsFuzzDefines = true; } } } } byte[] fileContents = outputStream.toByteArray(); return new ByteArrayInputStream(fileContents); } private static boolean isVersion(String line) { Pattern pattern = Pattern.compile("\\s*#\\s*version\\s*\\d+\\s*\\w*\\s*"); Matcher matcher = pattern.matcher(line); return matcher.find(); } private static boolean containsEndOfGraphicsFuzzDefines(InputStream inputStream) throws IOException { boolean result = false; try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) { String line; while ((line = br.readLine()) != null) { if (line.trim().startsWith(END_OF_GRAPHICSFUZZ_DEFINES)) { result = true; break; } } } // Reset the input stream so that we can consume it again once we know the answer to the // question of whether the GraphicsFuzz defines are present. inputStream.reset(); return result; } }
package ch.epfl.sweng.GyroDraw.home; /** * Enum modelling a friends request state. */ public enum FriendsRequestState { SENT, RECEIVED, FRIENDS; /** * Builds a {@link FriendsRequestState} value from the given integer. * * @param integer the integer corresponding to the desired enum value * @return an enum value * @throws IllegalArgumentException if the given integer does not correspond to a state */ public static FriendsRequestState fromInteger(int integer) { switch (integer) { case 0: return SENT; case 1: return RECEIVED; case 2: return FRIENDS; default: throw new IllegalArgumentException(integer + " does not correspond to a state"); } } }
// // ======================================================================== // Copyright (c) 1995-2021 Mort Bay Consulting Pty Ltd and others. // // This program and the accompanying materials are made available under the // terms of the Eclipse Public License v. 2.0 which is available at // https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0 // which is available at https://www.apache.org/licenses/LICENSE-2.0. // // SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 // ======================================================================== // package org.eclipse.jetty.apache.jsp; import java.net.URL; import java.util.Collection; import jakarta.servlet.ServletContext; import org.apache.jasper.servlet.TldPreScanned; import org.apache.tomcat.util.descriptor.tld.TldResourcePath; /** * JettyTldPreScanned * * Change to TldPreScanned to not require that the tlds have been * pre-scanned from a jar file, but rather may be files in the * file system. * * This is important for running in the jetty maven plugin * environment in multi-module builds, where modules that contain tlds * may be in the reactor at the same time as a webapp being run with the * plugin. That means that the tlds will be used from their location in * the file system, rather than from their assembled jar. */ public class JettyTldPreScanned extends TldPreScanned { private final Collection<URL> _jettyPreScannedURLs; public JettyTldPreScanned(ServletContext context, boolean namespaceAware, boolean validation, boolean blockExternal, Collection<URL> preScannedTlds) { super(context, namespaceAware, validation, blockExternal, preScannedTlds); _jettyPreScannedURLs = preScannedTlds; } @Override public void scanJars() { if (_jettyPreScannedURLs != null) { for (URL url : _jettyPreScannedURLs) { String str = url.toExternalForm(); int a = str.indexOf("jar:"); int b = str.indexOf("META-INF"); if (b < 0) throw new IllegalStateException("Bad tld url: " + str); String path = str.substring(b); if (a >= 0) { int c = str.indexOf("!/"); String fileUrl = str.substring(a + 4, c); try { parseTld(new TldResourcePath(new URL(fileUrl), null, path)); } catch (Exception e) { throw new IllegalStateException(e); } } else { try { parseTld(new TldResourcePath(url, null, null)); } catch (Exception e) { throw new IllegalStateException(e); } } } } } }
package openeye.logic; import com.google.common.base.Strings; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import java.io.File; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.ProtocolException; import java.net.UnknownHostException; import java.util.Enumeration; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.minecraft.world.World; import net.minecraft.world.storage.ISaveHandler; import openeye.Log; import openeye.logic.Sanitizer.ITransformer; public class Sanitizers { public static final int PRIORITY_SAVE_DIR = 1300; public static final int PRIORITY_MINECRAFT_DIR = 1200; public static final int PRIORITY_WORK_DIR = 1100; public static final int PRIORITY_HOME = 1000; public static final int PRIORITY_SAVE_DIR_NAME = 900; public static final int PRIORITY_WORLD_NAME = 800; public static final int PRIORITY_LOCAL_IP = 700; public static final int PRIORITY_IP_PORT = 600; public static final int PRIORITY_LOCAL_HOST = 500; public static final int PRIORITY_LOCAL_PLAYER = 400; public static final int PRIORITY_PLAYER_NAME = 300; public static final int PRIORITY_PLAYER_ID = 200; public static final int PRIORITY_SYSTEM_USER = 100; static class SimpleReplace implements ITransformer { private final String target; private final String value; public SimpleReplace(String target, String value) { this.target = target; this.value = value; } @Override public String transform(String input) { return input.replace(target, value); } @Override public String toString() { return String.format("'%s'->'%s'", target, value); } } private static class PropertyReplace extends Sanitizers.SimpleReplace { public PropertyReplace(String property, String value) { super(System.getProperty(property), value); } } private static class PathReplace implements ITransformer { private final String targetNormal; private final String targetReversed; private final String targetDoubled; private final String value; public PathReplace(String target, String value) { this.targetNormal = target; if (File.separatorChar == '\\') { targetReversed = targetNormal.replace('\\', '/'); targetDoubled = targetNormal.replace("\\", "\\\\"); } else if (File.separatorChar == '/') { targetReversed = targetNormal.replace('/', '\\'); targetDoubled = targetNormal.replace("/", "\\\\"); } else { targetReversed = null; targetDoubled = null; } this.value = value; } @Override public String transform(String input) { input = input.replace(targetNormal, value); if (targetReversed != null) input = input.replace(targetReversed, value); if (targetDoubled != null) input = input.replace(targetDoubled, value); return input; } @Override public String toString() { return String.format("path '%s'->'%s'", targetNormal, value); } } private static class SimpleRegexReplace implements ITransformer { private final Pattern pattern; private final String replacement; public SimpleRegexReplace(String pattern, String replacement) { this.pattern = Pattern.compile(pattern); this.replacement = replacement; } @Override public String transform(String input) { Matcher match = pattern.matcher(input); return match.replaceAll(replacement); } @Override public String toString() { return "regex: " + replacement; } } private static final Set<String> ALREADY_REPLACED = Sets.newHashSet(); private static final Set<String> DONT_REPLACE = Sets.newHashSet(); static { DONT_REPLACE.add("player"); DONT_REPLACE.add("MpServer"); DONT_REPLACE.add("none"); DONT_REPLACE.add("null"); } private static final Map<Class<? extends Throwable>, Sanitizer> THROWABLE_SANITIZERS = Maps.newHashMap(); public static final Sanitizer mainSanitizer = new Sanitizer(); public static void addThrowableSanitizer(Class<? extends Throwable> cls, Sanitizer sanitizer) { THROWABLE_SANITIZERS.put(cls, sanitizer); } public static Sanitizer getSanitizerForThrowable(Class<? extends Throwable> cls) { Sanitizer result = THROWABLE_SANITIZERS.get(cls); return result != null? result : mainSanitizer; } public static ITransformer path(String target, String value) { if (!Strings.isNullOrEmpty(target)) return new PathReplace(target, value); return null; } public static ITransformer pathNoDuplicate(String target, String value) { if (!Strings.isNullOrEmpty(target) && !ALREADY_REPLACED.contains(target)) { ALREADY_REPLACED.add(target); return new PathReplace(target, value); } return null; } public static ITransformer replace(Object target, String value) { if (target != null) { String s = target.toString(); if (s != null && s.length() > 2 && !DONT_REPLACE.contains(s)) return new Sanitizers.SimpleReplace(s, value); } return null; } public static ITransformer replaceNoDuplicates(Object target, String value) { if (target != null) { String s = target.toString(); if (s != null && s.length() > 2 && !ALREADY_REPLACED.contains(s) && !DONT_REPLACE.contains(s)) { ALREADY_REPLACED.add(s); return new Sanitizers.SimpleReplace(s, value); } } return null; } private static void addLocalAddresses() { Set<String> ips = Sets.newHashSet(); Set<String> hosts = Sets.newHashSet(); try { Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); while (interfaces.hasMoreElements()) { NetworkInterface intf = interfaces.nextElement(); Enumeration<InetAddress> addresses = intf.getInetAddresses(); while (addresses.hasMoreElements()) { InetAddress address = addresses.nextElement(); if (address != null) { ips.add(address.getHostAddress()); String host = address.getHostName(); if (!ips.contains(host)) hosts.add(host); } } } } catch (Throwable t) { Log.warn(t, "Failed to get local IP adresses for sanitization"); } for (String ip : ips) mainSanitizer.addPre(PRIORITY_LOCAL_IP, replace(ip, "[local ip]")); for (String host : hosts) mainSanitizer.addPre(PRIORITY_LOCAL_HOST, replace(host, "[host]")); mainSanitizer.addPre(PRIORITY_IP_PORT, new SimpleRegexReplace("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}[:~]\\d+", "[ip+port]")); } public static void addWorldNames(World world) { final ISaveHandler saveHandler = world.getSaveHandler(); final File worldDirectory = saveHandler.getWorldDirectory(); if (worldDirectory != null) { final String worldDir = worldDirectory.getName(); mainSanitizer.addPre(PRIORITY_SAVE_DIR_NAME, replaceNoDuplicates(worldDir, "[save dir]")); } try { File dummy = saveHandler.getMapFileFromName("dummy"); if (dummy != null) { String parent = dummy.getParentFile().getParent(); if (parent != null) mainSanitizer.addPre(PRIORITY_SAVE_DIR, pathNoDuplicate(parent, "[save dir]")); } } catch (Throwable t) { Log.warn(t, "Failed to get sanitizer name for world"); } String worldName = world.getWorldInfo().getWorldName(); mainSanitizer.addPre(PRIORITY_WORLD_NAME, replaceNoDuplicates(worldName, "[world name]")); } static { addLocalAddresses(); mainSanitizer.addPre(PRIORITY_WORK_DIR, new PathReplace(System.getProperty("user.dir"), "[workdir]")); mainSanitizer.addPre(PRIORITY_HOME, new PathReplace(System.getProperty("user.home"), "[home]")); mainSanitizer.addPre(PRIORITY_SYSTEM_USER, new PropertyReplace("user.name", "[user]")); Sanitizer ipSanitizer = new Sanitizer(mainSanitizer); ipSanitizer.addPre(1000, new SimpleRegexReplace("\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}", "[ip]")); addThrowableSanitizer(ProtocolException.class, ipSanitizer); addThrowableSanitizer(UnknownHostException.class, ipSanitizer); } public static void addMinecraftPath(File mcLocation) { mainSanitizer.addPre(PRIORITY_MINECRAFT_DIR, path(mcLocation.getAbsolutePath(), "[minecraft_dir]")); } public static void addPlayerName(String username) { mainSanitizer.addPre(PRIORITY_LOCAL_PLAYER, Sanitizers.replace(username, "[local player]")); } }
/* 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.pluto.container.driver; import javax.servlet.annotation.WebInitParam; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; /** * Dummy servlet to allow "legacy" portlets with web.xml files specifying PortletServlet to deploy properly. * The real portlet servlet is PortletServlet3, which is deployed through the servlet container * initializer. * * @see PortletServlet3 * @see PortletContainerInitializer * @author Scott Nicklous */ @WebServlet( name = "AboutPortlet", initParams = {@WebInitParam(name = "portlet-name", value = "AboutPortlet")}, loadOnStartup = 1 ) public class PortletServlet extends HttpServlet { private static final long serialVersionUID = -2550104981099637033L; }
package contest.codejam; import java.io.*; import java.util.*; public class GCJ_2018_Round_1C_A { static BufferedReader br; static PrintWriter out; static StringTokenizer st; static int T, N, L; public static void main(String[] args) throws IOException { br = new BufferedReader(new InputStreamReader(System.in)); out = new PrintWriter(new OutputStreamWriter(System.out)); // br = new BufferedReader(new FileReader("in.txt")); // out = new PrintWriter(new FileWriter("out.txt")); T = readInt(); for (int t = 1; t <= T; t++) { N = readInt(); L = readInt(); String[] words = new String[N]; HashSet<String> s = new HashSet<String>(); for (int i = 0; i < N; i++) { words[i] = next(); s.add(words[i]); } boolean valid = false; for (int i = 0; i < N; i++) { for (int j = i + 1; j < N; j++) { if (!words[i].equals(words[j]) && !valid) { for (int k = 0; k < L; k++) { if (words[i].charAt(k) != words[j].charAt(k)) { String word = words[i].substring(0, k) + words[j].charAt(k) + words[i].substring(k + 1, L); if (!s.contains(word)) { out.printf("Case #%d: %s%n", t, word); valid = true; break; } } } } } } if (!valid) { out.printf("Case #%d: -%n", t); } } out.close(); } static String next() throws IOException { while (st == null || !st.hasMoreTokens()) st = new StringTokenizer(br.readLine().trim()); return st.nextToken(); } static long readLong() throws IOException { return Long.parseLong(next()); } static int readInt() throws IOException { return Integer.parseInt(next()); } static double readDouble() throws IOException { return Double.parseDouble(next()); } static char readCharacter() throws IOException { return next().charAt(0); } static String readLine() throws IOException { return br.readLine().trim(); } }
// Copyright (C) 2013 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 com.google.gerrit.server.schema; import com.google.inject.Inject; import com.google.inject.Provider; import com.google.inject.ProvisionException; public class Schema_83 extends SchemaVersion { @Inject Schema_83() { super(new Provider<SchemaVersion>() { @Override public SchemaVersion get() { throw new ProvisionException("Upgrade first to 2.8 or 2.9"); } }); } }
package org.hzero.iam.domain.entity; import java.util.Date; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import org.hzero.starter.keyencrypt.core.Encrypt; import io.choerodon.mybatis.annotation.ModifyAudit; import io.choerodon.mybatis.annotation.VersionAudit; import io.choerodon.mybatis.domain.AuditDomain; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; /** * 实体:LdapHistory * * @author bojiangzhou 2019/08/02 */ @ApiModel("Ldap") @VersionAudit @ModifyAudit @Table(name = "oauth_ldap_history") public class LdapHistory extends AuditDomain { public static final String ENCRYPT_KEY = "LdapHistory"; public static final String FIELD_LDAP_ID = "ldapId"; public static final String FIELD_SYNC_END_TIME = "syncEndTime"; @Id @GeneratedValue @ApiModelProperty(value = "主键") @Encrypt private Long id; @ApiModelProperty(value = "LDAP 主键") @Encrypt private Long ldapId; @ApiModelProperty(value = "上次同步新增用户个数") private Long newUserCount; @ApiModelProperty(value = "同步成功用户个数") private Long updateUserCount; @ApiModelProperty(value = "同步失败用户个数") private Long errorUserCount; @ApiModelProperty(value = "上次同步开始时间") private Date syncBeginTime; @ApiModelProperty(value = "上次同步结束时间") private Date syncEndTime; @ApiModelProperty(value = "同步类型") private String syncType; private Long tenantId; public Long getTenantId() { return tenantId; } public LdapHistory setTenantId(Long tenantId) { this.tenantId = tenantId; return this; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getLdapId() { return ldapId; } public void setLdapId(Long ldapId) { this.ldapId = ldapId; } public Long getNewUserCount() { return newUserCount; } public void setNewUserCount(Long newUserCount) { this.newUserCount = newUserCount; } public Long getUpdateUserCount() { return updateUserCount; } public void setUpdateUserCount(Long updateUserCount) { this.updateUserCount = updateUserCount; } public Long getErrorUserCount() { return errorUserCount; } public void setErrorUserCount(Long errorUserCount) { this.errorUserCount = errorUserCount; } public Date getSyncBeginTime() { return syncBeginTime; } public void setSyncBeginTime(Date syncBeginTime) { this.syncBeginTime = syncBeginTime; } public Date getSyncEndTime() { return syncEndTime; } public void setSyncEndTime(Date syncEndTime) { this.syncEndTime = syncEndTime; } public String getSyncType() { return syncType; } public void setSyncType(String syncType) { this.syncType = syncType; } }
package org.bson; public abstract interface BSONObject { public abstract java.lang.Object put(java.lang.String arg0, java.lang.Object arg1); public abstract void putAll(org.bson.BSONObject arg0); public abstract void putAll(java.util.Map arg0); public abstract java.lang.Object get(java.lang.String arg0); public abstract java.util.Map toMap(); public abstract java.lang.Object removeField(java.lang.String arg0); public abstract boolean containsKey(java.lang.String arg0); public abstract boolean containsField(java.lang.String arg0); public abstract java.util.Set<java.lang.String> keySet(); }
/* * @(#)IMSManifestDocument.java * Copyright © 2020 Werner Randelshofer, Switzerland. MIT License. */ package ch.randelshofer.scorm.cam; import ch.randelshofer.util.IdentifierGenerator; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.net.MalformedURLException; import java.net.URL; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; /** * Represents a top-level SCORM 1.2 CAM 'manifest' element. * <p> * The 'manifest' element is the top-level element of a content package. * <p> * A 'manifest' element has a structure as shown below. * Square brackets [ ] denote zero or one occurences. * Braces { } denote zero or more occurences. * Text in <b>bold</b> denotes non-terminal symbols. * <pre> * <b>manifest</b> ::= &lt;manifest identifier=<b>ID</b> * [version=<b>string</b>] * [xml:base=<b>string</b>]&gt; * [<b>metadata</b>] * <b>organizations</b> * <b>resources</b> * {<b>manifest</b>} * &lt;/manifest&gt; * </pre> * Reference: * ADL (2001). Advanced Distributed Learning. * Sharable Content Object Reference Model (SCORM(TM)) Version 1.2. * The SCORM Content Aggregation Model. October 1, 2001. * Internet (2003-01-20): http://www.adlnet.org * * @author Werner Randelshofer * @version 1.3 2006-10-10 Parse with XML namespaces. * <br>1.2 2006-05-26 Skip hidden files. * <br>1.1.6 2004-01-19 Comments updated. * <br> 1.1.5 2003-11-05 Method exportToJavaScript assigns the CAM to * the existing variable LMS.cam instead of creating a new variable named LMSCAM. * <br>1.0 2003-10-29 Variable fileNames uses a Set to store the file names * instead of a Map. Also changed all corresponding method signatures from Map * to Set. * <br>0.20 2003-05-19 Method getContentDirectory added. * <br>0.19 2003-03-26 exportToJavaScript revised. * <br>0.17 2003-03-18 Naming conventions streamlined with JavaScript code * of the LMS. Method getManifestURL added. * <br>0.1 2003-02-02 Created. */ public class IMSManifestDocument extends ManifestElement { private final static long serialVersionUID = 1L; private File pifFile; private File contentPackageFile; /** * Stores all filenames in the PIF or in * the Content Package as String objects. * Each String object represents a path relative to the pifFile or * the contentPackageFile. * The separator used to delimit path elements is the '/' (slash) * character. */ private HashSet<String> fileNames; /** * Creates a new instance of CAMModel */ public IMSManifestDocument() { } public void setPIFFile(File pif) { pifFile = pif; contentPackageFile = null; } public File getPIFFile() { return pifFile; } public void setContentPackage(File dir) { contentPackageFile = dir; pifFile = null; } public File getContentPackage() { return contentPackageFile; } public URL getManifestURL() { URL url; try { if (pifFile != null) { url = new URL("jar:" + pifFile.toURI() + "!imsmanifest.xml"); } else { url = new URL(contentPackageFile.toURI().toURL(), "imsmanifest.xml"); } } catch (MalformedURLException e) { InternalError error = new InternalError("Unable to create URL:"); error.initCause(e); throw error; } return url; } /** * Adds the contents of the XML stream to this model. * For peak performance, the input stream should be buffered. */ public void readXML(InputStream in) throws IOException, SAXException, ParserConfigurationException { // The DOM Document. DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); Document doc = factory.newDocumentBuilder().parse(in); // Read the "manifest" element Element elem = doc.getDocumentElement(); parse(elem); } /** * Exports this CAM subtree to JavaScript using the specified PrintWriter. * * @param out The output stream. * @param depth The current depth of the tree (used for indention). * @param gen The identifier generator used to generate short(er) identifiers * whithin the JavaScript. */ public void exportToJavaScript(PrintWriter out, int depth, IdentifierGenerator gen) throws IOException { indent(out, depth); if (depth == 0) { out.print("API.cam = "); } out.println("new ManifestElement(\"" + gen.getIdentifier(getIdentifier(), getIdentifier()) + "\",\"" + getVersion() + "\","); getOrganizationsElement().exportToJavaScript(out, depth + 1, gen); out.println(); indent(out, depth + 1); out.println(","); getResourcesElement().exportToJavaScript(out, depth + 1, gen); out.println(); indent(out, depth); if (depth == 0) { out.println(");"); } else { out.print(")"); } } /* public void compressIdentifiers() { int count = 0; HashMap map = new HashMap(); Enumeration enum = preorderEnumeration(); while (enum.hasMoreElements()) { CAMElement element = (CAMElement) enum.nextElement(); if (element.getIdentifier() != null) { map.put(element.getIdentifier(), Integer.toString(count++, Character.MAX_RADIX)); } } enum = preorderEnumeration(); while (enum.hasMoreElements()) { CAMElement element = (CAMElement) enum.nextElement(); element.updateIdentifiers(map); } }*/ /** * This method returns all filenames in the PIF or in * the Content Package as String objects. * Each String object represents a path relative to the pifFile or * the contentPackageFile. * The separator used to delimit path elements is the '/' (slash) * character. * * @return Returns an unmodifiable Set. */ public Set<String> getFileNames() { if (fileNames == null) { fileNames = new HashSet<>(); if (pifFile != null) { ZipInputStream zipin = null; try { zipin = new ZipInputStream( new BufferedInputStream( new FileInputStream(pifFile) )); ZipEntry entry = null; while ((entry = zipin.getNextEntry()) != null) { if (!entry.isDirectory()) { fileNames.add(entry.getName()); } } } catch (IOException e) { e.printStackTrace(); } finally { if (zipin != null) { try { zipin.close(); } catch (IOException e2) { } } } } else if (contentPackageFile != null) { addDirectorySubtree(contentPackageFile, contentPackageFile, fileNames); } } return Collections.unmodifiableSet(fileNames); } private void addDirectorySubtree(File root, File subdir, Set<String> fileNames) { String rootName = root.toString(); File[] dir = subdir.listFiles(); if (dir != null) { for (int i = 0; i < dir.length; i++) { if (!dir[i].isHidden()) { if (dir[i].isDirectory()) { addDirectorySubtree(root, dir[i], fileNames); } else { String relativePath = dir[i].toString().replace(File.separatorChar, '/').substring(rootName.length() + 1); fileNames.add(relativePath); } } } } } }
/* * 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.cassandra.tools; import org.junit.Test; import org.junit.runner.RunWith; import org.apache.cassandra.OrderedJUnit4ClassRunner; @RunWith(OrderedJUnit4ClassRunner.class) public class StandaloneUpgraderTest extends ToolsTester { @Test public void testStandaloneUpgrader_NoArgs() { runTool(1, "org.apache.cassandra.tools.StandaloneUpgrader"); assertNoUnexpectedThreadsStarted(null, null); assertSchemaNotLoaded(); assertCLSMNotLoaded(); assertSystemKSNotLoaded(); assertKeyspaceNotLoaded(); assertServerNotLoaded(); } @Test public void testStandaloneUpgrader_WithArgs() { runTool(0, "org.apache.cassandra.tools.StandaloneUpgrader", "--debug", "system_schema", "tables"); assertNoUnexpectedThreadsStarted(EXPECTED_THREADS_WITH_SCHEMA, OPTIONAL_THREADS_WITH_SCHEMA); assertSchemaLoaded(); assertServerNotLoaded(); } }
// // 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.cloud.hypervisor.kvm.resource.wrapper; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.List; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.libvirt.Connect; import org.libvirt.StorageVol; import org.mockito.InOrder; import org.mockito.Mockito; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import com.cloud.agent.api.MigrateCommand.MigrateDiskInfo; import com.cloud.agent.api.MigrateCommand.MigrateDiskInfo.DiskType; import com.cloud.agent.api.MigrateCommand.MigrateDiskInfo.DriverType; import com.cloud.agent.api.MigrateCommand.MigrateDiskInfo.Source; import com.cloud.hypervisor.kvm.resource.LibvirtComputingResource; import com.cloud.hypervisor.kvm.resource.LibvirtConnection; import com.cloud.hypervisor.kvm.resource.LibvirtVMDef.DiskDef; import com.cloud.utils.exception.CloudRuntimeException; @RunWith(PowerMockRunner.class) @PrepareForTest({LibvirtConnection.class, LibvirtMigrateCommandWrapper.class}) public class LibvirtMigrateCommandWrapperTest { String fullfile = "<domain type='kvm' id='4'>\n" + " <name>i-6-6-VM</name>\n" + " <uuid>f197b32b-8da2-4a57-bb8a-d01bacc5cd33</uuid>\n" + " <description>Other PV (64-bit)</description>\n" + " <memory unit='KiB'>262144</memory>\n" + " <currentMemory unit='KiB'>262144</currentMemory>\n" + " <vcpu placement='static'>1</vcpu>\n" + " <cputune>\n" + " <shares>100</shares>\n" + " </cputune>\n" + " <resource>\n" + " <partition>/machine</partition>\n" + " </resource>\n" + " <sysinfo type='smbios'>\n" + " <system>\n" + " <entry name='manufacturer'>Apache Software Foundation</entry>\n" + " <entry name='product'>CloudStack KVM Hypervisor</entry>\n" + " <entry name='uuid'>f197b32b-8da2-4a57-bb8a-d01bacc5cd33</entry>\n" + " </system>\n" + " </sysinfo>\n" + " <os>\n" + " <type arch='x86_64' machine='pc-i440fx-rhel7.0.0'>hvm</type>\n" + " <boot dev='cdrom'/>\n" + " <boot dev='hd'/>\n" + " <smbios mode='sysinfo'/>\n" + " </os>\n" + " <features>\n" + " <acpi/>\n" + " <apic/>\n" + " <pae/>\n" + " </features>\n" + " <clock offset='utc'>\n" + " <timer name='kvmclock'/>\n" + " </clock>\n" + " <on_poweroff>destroy</on_poweroff>\n" + " <on_reboot>restart</on_reboot>\n" + " <on_crash>destroy</on_crash>\n" + " <devices>\n" + " <emulator>/usr/libexec/qemu-kvm</emulator>\n" + " <disk type='file' device='disk'>\n" + " <driver name='qemu' type='qcow2' cache='none'/>\n" + " <source file='/mnt/812ea6a3-7ad0-30f4-9cab-01e3f2985b98/4650a2f7-fce5-48e2-beaa-bcdf063194e6'/>\n" + " <backingStore type='file' index='1'>\n" + " <format type='raw'/>\n" + " <source file='/mnt/812ea6a3-7ad0-30f4-9cab-01e3f2985b98/bb4d4df4-c004-11e5-94ed-5254001daa61'/>\n" + " <backingStore/>\n" + " </backingStore>\n" + " <target dev='vda' bus='virtio'/>\n" + " <serial>4650a2f7fce548e2beaa</serial>\n" + " <alias name='virtio-disk0'/>\n" + " <address type='pci' domain='0x0000' bus='0x00' slot='0x04' function='0x0'/>\n" + " </disk>\n" + " <disk type='file' device='cdrom'>\n" + " <driver name='qemu' type='raw' cache='none'/>\n" + " <backingStore/>\n" + " <target dev='hdc' bus='ide'/>\n" + " <readonly/>\n" + " <alias name='ide0-1-0'/>\n" + " <address type='drive' controller='0' bus='1' target='0' unit='0'/>\n" + " </disk>\n" + " <controller type='usb' index='0'>\n" + " <alias name='usb'/>\n" + " <address type='pci' domain='0x0000' bus='0x00' slot='0x01' function='0x2'/>\n" + " </controller>\n" + " <controller type='pci' index='0' model='pci-root'>\n" + " <alias name='pci.0'/>\n" + " </controller>\n" + " <controller type='ide' index='0'>\n" + " <alias name='ide'/>\n" + " <address type='pci' domain='0x0000' bus='0x00' slot='0x01' function='0x1'/>\n" + " </controller>\n" + " <interface type='bridge'>\n" + " <mac address='06:fe:b4:00:00:06'/>\n" + " <source bridge='breth0-50'/>\n" + " <bandwidth>\n" + " <inbound average='25600' peak='25600'/>\n" + " <outbound average='25600' peak='25600'/>\n" + " </bandwidth>\n" + " <target dev='vnet4'/>\n" + " <model type='virtio'/>\n" + " <alias name='net0'/>\n" + " <address type='pci' domain='0x0000' bus='0x00' slot='0x03' function='0x0'/>\n" + " </interface>\n" + " <serial type='pty'>\n" + " <source path='/dev/pts/2'/>\n" + " <target port='0'/>\n" + " <alias name='serial0'/>\n" + " </serial>\n" + " <console type='pty' tty='/dev/pts/2'>\n" + " <source path='/dev/pts/2'/>\n" + " <target type='serial' port='0'/>\n" + " <alias name='serial0'/>\n" + " </console>\n" + " <input type='tablet' bus='usb'>\n" + " <alias name='input0'/>\n" + " </input>\n" + " <input type='mouse' bus='ps2'/>\n" + " <input type='keyboard' bus='ps2'/>\n" + " <graphics type='vnc' port='5902' autoport='yes' listen='192.168.22.22'>\n" + " <listen type='address' address='192.168.22.22'/>\n" + " </graphics>\n" + " <video>\n" + " <model type='cirrus' vram='16384' heads='1'/>\n" + " <alias name='video0'/>\n" + " <address type='pci' domain='0x0000' bus='0x00' slot='0x02' function='0x0'/>\n" + " </video>\n" + " <memballoon model='none'>\n" + " <alias name='balloon0'/>\n" + " </memballoon>\n" + " </devices>\n" + "</domain>"; String targetfile = "<domain type='kvm' id='4'>\n" + " <name>i-6-6-VM</name>\n" + " <uuid>f197b32b-8da2-4a57-bb8a-d01bacc5cd33</uuid>\n" + " <description>Other PV (64-bit)</description>\n" + " <memory unit='KiB'>262144</memory>\n" + " <currentMemory unit='KiB'>262144</currentMemory>\n" + " <vcpu placement='static'>1</vcpu>\n" + " <cputune>\n" + " <shares>100</shares>\n" + " </cputune>\n" + " <resource>\n" + " <partition>/machine</partition>\n" + " </resource>\n" + " <sysinfo type='smbios'>\n" + " <system>\n" + " <entry name='manufacturer'>Apache Software Foundation</entry>\n" + " <entry name='product'>CloudStack KVM Hypervisor</entry>\n" + " <entry name='uuid'>f197b32b-8da2-4a57-bb8a-d01bacc5cd33</entry>\n" + " </system>\n" + " </sysinfo>\n" + " <os>\n" + " <type arch='x86_64' machine='pc-i440fx-rhel7.0.0'>hvm</type>\n" + " <boot dev='cdrom'/>\n" + " <boot dev='hd'/>\n" + " <smbios mode='sysinfo'/>\n" + " </os>\n" + " <features>\n" + " <acpi/>\n" + " <apic/>\n" + " <pae/>\n" + " </features>\n" + " <clock offset='utc'>\n" + " <timer name='kvmclock'/>\n" + " </clock>\n" + " <on_poweroff>destroy</on_poweroff>\n" + " <on_reboot>restart</on_reboot>\n" + " <on_crash>destroy</on_crash>\n" + " <devices>\n" + " <emulator>/usr/libexec/qemu-kvm</emulator>\n" + " <disk type='file' device='disk'>\n" + " <driver name='qemu' type='qcow2' cache='none'/>\n" + " <source file='/mnt/812ea6a3-7ad0-30f4-9cab-01e3f2985b98/4650a2f7-fce5-48e2-beaa-bcdf063194e6'/>\n" + " <backingStore type='file' index='1'>\n" + " <format type='raw'/>\n" + " <source file='/mnt/812ea6a3-7ad0-30f4-9cab-01e3f2985b98/bb4d4df4-c004-11e5-94ed-5254001daa61'/>\n" + " <backingStore/>\n" + " </backingStore>\n" + " <target dev='vda' bus='virtio'/>\n" + " <serial>4650a2f7fce548e2beaa</serial>\n" + " <alias name='virtio-disk0'/>\n" + " <address type='pci' domain='0x0000' bus='0x00' slot='0x04' function='0x0'/>\n" + " </disk>\n" + " <disk type='file' device='cdrom'>\n" + " <driver name='qemu' type='raw' cache='none'/>\n" + " <backingStore/>\n" + " <target dev='hdc' bus='ide'/>\n" + " <readonly/>\n" + " <alias name='ide0-1-0'/>\n" + " <address type='drive' controller='0' bus='1' target='0' unit='0'/>\n" + " </disk>\n" + " <controller type='usb' index='0'>\n" + " <alias name='usb'/>\n" + " <address type='pci' domain='0x0000' bus='0x00' slot='0x01' function='0x2'/>\n" + " </controller>\n" + " <controller type='pci' index='0' model='pci-root'>\n" + " <alias name='pci.0'/>\n" + " </controller>\n" + " <controller type='ide' index='0'>\n" + " <alias name='ide'/>\n" + " <address type='pci' domain='0x0000' bus='0x00' slot='0x01' function='0x1'/>\n" + " </controller>\n" + " <interface type='bridge'>\n" + " <mac address='06:fe:b4:00:00:06'/>\n" + " <source bridge='breth0-50'/>\n" + " <bandwidth>\n" + " <inbound average='25600' peak='25600'/>\n" + " <outbound average='25600' peak='25600'/>\n" + " </bandwidth>\n" + " <target dev='vnet4'/>\n" + " <model type='virtio'/>\n" + " <alias name='net0'/>\n" + " <address type='pci' domain='0x0000' bus='0x00' slot='0x03' function='0x0'/>\n" + " </interface>\n" + " <serial type='pty'>\n" + " <source path='/dev/pts/2'/>\n" + " <target port='0'/>\n" + " <alias name='serial0'/>\n" + " </serial>\n" + " <console type='pty' tty='/dev/pts/2'>\n" + " <source path='/dev/pts/2'/>\n" + " <target type='serial' port='0'/>\n" + " <alias name='serial0'/>\n" + " </console>\n" + " <input type='tablet' bus='usb'>\n" + " <alias name='input0'/>\n" + " </input>\n" + " <input type='mouse' bus='ps2'/>\n" + " <input type='keyboard' bus='ps2'/>\n" + " <graphics type='vnc' port='5902' autoport='yes' listen='192.168.22.21'>\n" + " <listen type='address' address='192.168.22.21'/>\n" + " </graphics>\n" + " <video>\n" + " <model type='cirrus' vram='16384' heads='1'/>\n" + " <alias name='video0'/>\n" + " <address type='pci' domain='0x0000' bus='0x00' slot='0x02' function='0x0'/>\n" + " </video>\n" + " <memballoon model='none'>\n" + " <alias name='balloon0'/>\n" + " </memballoon>\n" + " </devices>\n" + "</domain>"; LibvirtMigrateCommandWrapper libvirtMigrateCmdWrapper = new LibvirtMigrateCommandWrapper(); @Test public void testReplaceIpForVNCInDescFile() { final String targetIp = "192.168.22.21"; final String result = libvirtMigrateCmdWrapper.replaceIpForVNCInDescFile(fullfile, targetIp); assertTrue("transformation does not live up to expectation:\n" + result, targetfile.equals(result)); } @Test public void testReplaceIpForVNCInDesc() { final String xmlDesc = "<domain type='kvm' id='3'>" + " <devices>" + " <graphics type='vnc' port='5900' autoport='yes' listen='10.10.10.1'>" + " <listen type='address' address='10.10.10.1'/>" + " </graphics>" + " </devices>" + "</domain>"; final String expectedXmlDesc = "<domain type='kvm' id='3'>" + " <devices>" + " <graphics type='vnc' port='5900' autoport='yes' listen='10.10.10.10'>" + " <listen type='address' address='10.10.10.10'/>" + " </graphics>" + " </devices>" + "</domain>"; final String targetIp = "10.10.10.10"; final String result = libvirtMigrateCmdWrapper.replaceIpForVNCInDescFile(xmlDesc, targetIp); assertTrue("transformation does not live up to expectation:\n" + result, expectedXmlDesc.equals(result)); } @Test public void testReplaceFqdnForVNCInDesc() { final String xmlDesc = "<domain type='kvm' id='3'>" + " <devices>" + " <graphics type='vnc' port='5900' autoport='yes' listen='localhost.local'>" + " <listen type='address' address='localhost.local'/>" + " </graphics>" + " </devices>" + "</domain>"; final String expectedXmlDesc = "<domain type='kvm' id='3'>" + " <devices>" + " <graphics type='vnc' port='5900' autoport='yes' listen='localhost.localdomain'>" + " <listen type='address' address='localhost.localdomain'/>" + " </graphics>" + " </devices>" + "</domain>"; final String targetIp = "localhost.localdomain"; final String result = libvirtMigrateCmdWrapper.replaceIpForVNCInDescFile(xmlDesc, targetIp); assertTrue("transformation does not live up to expectation:\n" + result, expectedXmlDesc.equals(result)); } @Test public void testMigrationUri() { final String ip = "10.1.1.1"; LibvirtComputingResource lcr = new LibvirtComputingResource(); if (lcr.isHostSecured()) { assertEquals(libvirtMigrateCmdWrapper.createMigrationURI(ip, lcr), String.format("qemu+tls://%s/system", ip)); } else { assertEquals(libvirtMigrateCmdWrapper.createMigrationURI(ip, lcr), String.format("qemu+tcp://%s/system", ip)); } } @Test(expected = CloudRuntimeException.class) public void testMigrationUriException() { libvirtMigrateCmdWrapper.createMigrationURI(null, new LibvirtComputingResource()); } @Test public void deleteLocalVolumeTest() throws Exception { PowerMockito.mockStatic(LibvirtConnection.class); Connect conn = Mockito.mock(Connect.class); PowerMockito.doReturn(conn).when(LibvirtConnection.class, "getConnection"); StorageVol storageVolLookupByPath = Mockito.mock(StorageVol.class); Mockito.when(conn.storageVolLookupByPath("localPath")).thenReturn(storageVolLookupByPath); libvirtMigrateCmdWrapper.deleteLocalVolume("localPath"); PowerMockito.verifyStatic(Mockito.times(1)); LibvirtConnection.getConnection(); InOrder inOrder = Mockito.inOrder(conn, storageVolLookupByPath); inOrder.verify(conn, Mockito.times(1)).storageVolLookupByPath("localPath"); inOrder.verify(storageVolLookupByPath, Mockito.times(1)).delete(0); } @Test public void searchDiskDefOnMigrateDiskInfoListTest() { configureAndVerifyTestSearchDiskDefOnMigrateDiskInfoList("f3d49ecc-870c-475a-89fa-fd0124420a9b", "/var/lib/libvirt/images/f3d49ecc-870c-475a-89fa-fd0124420a9b", false); } @Test public void searchDiskDefOnMigrateDiskInfoListTestExpectNull() { configureAndVerifyTestSearchDiskDefOnMigrateDiskInfoList("f3d49ecc-870c-475a-89fa-fd0124420a9b", "/var/lib/libvirt/images/f3d49ecc-870c-89fa-fd0124420a9b", true); } private void configureAndVerifyTestSearchDiskDefOnMigrateDiskInfoList(String serialNumber, String diskPath, boolean isExpectedDiskInfoNull) { MigrateDiskInfo migrateDiskInfo = new MigrateDiskInfo(serialNumber, DiskType.FILE, DriverType.QCOW2, Source.FILE, "sourceText"); List<MigrateDiskInfo> migrateDiskInfoList = new ArrayList<>(); migrateDiskInfoList.add(migrateDiskInfo); DiskDef disk = new DiskDef(); disk.setDiskPath(diskPath); MigrateDiskInfo returnedMigrateDiskInfo = libvirtMigrateCmdWrapper.searchDiskDefOnMigrateDiskInfoList(migrateDiskInfoList, disk); if (isExpectedDiskInfoNull) Assert.assertEquals(null, returnedMigrateDiskInfo); else Assert.assertEquals(migrateDiskInfo, returnedMigrateDiskInfo); } @Test public void deleteOrDisconnectDisksOnSourcePoolTest() { LibvirtMigrateCommandWrapper spyLibvirtMigrateCmdWrapper = PowerMockito.spy(libvirtMigrateCmdWrapper); Mockito.doNothing().when(spyLibvirtMigrateCmdWrapper).deleteLocalVolume("volPath"); List<MigrateDiskInfo> migrateDiskInfoList = new ArrayList<>(); MigrateDiskInfo migrateDiskInfo0 = createMigrateDiskInfo(true); MigrateDiskInfo migrateDiskInfo2 = createMigrateDiskInfo(false); List<DiskDef> disks = new ArrayList<>(); DiskDef diskDef0 = new DiskDef(); DiskDef diskDef1 = new DiskDef(); DiskDef diskDef2 = new DiskDef(); diskDef0.setDiskPath("volPath"); disks.add(diskDef0); disks.add(diskDef1); disks.add(diskDef2); LibvirtComputingResource libvirtComputingResource = Mockito.spy(new LibvirtComputingResource()); Mockito.doReturn(true).when(libvirtComputingResource).cleanupDisk(diskDef1); Mockito.doReturn(migrateDiskInfo0).when(spyLibvirtMigrateCmdWrapper).searchDiskDefOnMigrateDiskInfoList(migrateDiskInfoList, diskDef0); Mockito.doReturn(null).when(spyLibvirtMigrateCmdWrapper).searchDiskDefOnMigrateDiskInfoList(migrateDiskInfoList, diskDef1); Mockito.doReturn(migrateDiskInfo2).when(spyLibvirtMigrateCmdWrapper).searchDiskDefOnMigrateDiskInfoList(migrateDiskInfoList, diskDef2); spyLibvirtMigrateCmdWrapper.deleteOrDisconnectDisksOnSourcePool(libvirtComputingResource, migrateDiskInfoList, disks); InOrder inOrder = Mockito.inOrder(spyLibvirtMigrateCmdWrapper, libvirtComputingResource); inOrderVerifyDeleteOrDisconnect(inOrder, spyLibvirtMigrateCmdWrapper, libvirtComputingResource, migrateDiskInfoList, diskDef0, 1, 0); inOrderVerifyDeleteOrDisconnect(inOrder, spyLibvirtMigrateCmdWrapper, libvirtComputingResource, migrateDiskInfoList, diskDef1, 0, 1); inOrderVerifyDeleteOrDisconnect(inOrder, spyLibvirtMigrateCmdWrapper, libvirtComputingResource, migrateDiskInfoList, diskDef2, 0, 1); } private MigrateDiskInfo createMigrateDiskInfo(boolean isSourceDiskOnStorageFileSystem) { MigrateDiskInfo migrateDiskInfo = new MigrateDiskInfo("serialNumber", DiskType.FILE, DriverType.QCOW2, Source.FILE, "sourceText"); migrateDiskInfo.setSourceDiskOnStorageFileSystem(isSourceDiskOnStorageFileSystem); return migrateDiskInfo; } private void inOrderVerifyDeleteOrDisconnect(InOrder inOrder, LibvirtMigrateCommandWrapper lw, LibvirtComputingResource virtResource, List<MigrateDiskInfo> diskInfoList, DiskDef disk, int timesDelete, int timesCleanup) { inOrder.verify(lw).searchDiskDefOnMigrateDiskInfoList(diskInfoList, disk); inOrder.verify(lw, Mockito.times(timesDelete)).deleteLocalVolume("volPath"); inOrder.verify(virtResource, Mockito.times(timesCleanup)).cleanupDisk(disk); } }
package com.dieam.reactnativepushnotification.modules; import android.app.Activity; import android.app.Application; import android.app.NotificationManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.core.app.NotificationManagerCompat; import com.dieam.reactnativepushnotification.helpers.ApplicationBadgeHelper; import com.facebook.react.bridge.ActivityEventListener; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.Callback; import com.facebook.react.bridge.Promise; import com.facebook.react.bridge.ReactApplicationContext; import com.facebook.react.bridge.ReactContext; import com.facebook.react.bridge.ReactContextBaseJavaModule; import com.facebook.react.bridge.ReactMethod; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.WritableArray; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.WritableMap; import java.io.IOException; import java.security.SecureRandom; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import android.util.Log; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.messaging.FirebaseMessaging; public class RNPushNotification extends ReactContextBaseJavaModule implements ActivityEventListener { public static final String LOG_TAG = "RNPushNotification";// all logging should use this tag public static final String KEY_TEXT_REPLY = "key_text_reply"; public interface RNIntentHandler { void onNewIntent(Intent intent); @Nullable Bundle getBundleFromIntent(Intent intent); } public static ArrayList<RNIntentHandler> IntentHandlers = new ArrayList(); private RNPushNotificationHelper mRNPushNotificationHelper; private final SecureRandom mRandomNumberGenerator = new SecureRandom(); private RNPushNotificationJsDelivery mJsDelivery; public RNPushNotification(ReactApplicationContext reactContext) { super(reactContext); reactContext.addActivityEventListener(this); Application applicationContext = (Application) reactContext.getApplicationContext(); // The @ReactNative methods use this mRNPushNotificationHelper = new RNPushNotificationHelper(applicationContext); // This is used to delivery callbacks to JS mJsDelivery = new RNPushNotificationJsDelivery(reactContext); } @Override public String getName() { return "ReactNativePushNotification"; } @Override public Map<String, Object> getConstants() { final Map<String, Object> constants = new HashMap<>(); return constants; } private Bundle getBundleFromIntent(Intent intent) { Bundle bundle = null; if (intent.hasExtra("notification")) { bundle = intent.getBundleExtra("notification"); intent.removeExtra("notification"); } else if (intent.hasExtra("google.message_id")) { bundle = new Bundle(); bundle.putBundle("data", intent.getExtras()); intent.removeExtra("google.message_id"); } if (bundle == null) { for (RNIntentHandler handler : IntentHandlers) { bundle = handler.getBundleFromIntent(intent); } } if(null != bundle && !bundle.getBoolean("foreground", false) && !bundle.containsKey("userInteraction")) { bundle.putBoolean("userInteraction", true); } return bundle; } @Override public void onNewIntent(Intent intent) { for (RNIntentHandler handler : IntentHandlers) { handler.onNewIntent(intent); } Bundle bundle = this.getBundleFromIntent(intent); if (bundle != null) { mJsDelivery.notifyNotification(bundle); } } @ReactMethod public void invokeApp(ReadableMap data) { Bundle bundle = null; if (data != null) { bundle = Arguments.toBundle(data); } mRNPushNotificationHelper.invokeApp(bundle); } @ReactMethod public void checkPermissions(Promise promise) { ReactContext reactContext = getReactApplicationContext(); NotificationManagerCompat managerCompat = NotificationManagerCompat.from(reactContext); promise.resolve(managerCompat.areNotificationsEnabled()); } @ReactMethod public void requestPermissions() { final RNPushNotificationJsDelivery fMjsDelivery = mJsDelivery; FirebaseMessaging.getInstance().getToken() .addOnCompleteListener(new OnCompleteListener<String>() { @Override public void onComplete(@NonNull Task<String> task) { if (!task.isSuccessful()) { Log.e(LOG_TAG, "exception", task.getException()); return; } WritableMap params = Arguments.createMap(); params.putString("deviceToken", task.getResult()); fMjsDelivery.sendEvent("remoteNotificationsRegistered", params); } }); } @ReactMethod public void subscribeToTopic(String topic) { FirebaseMessaging.getInstance().subscribeToTopic(topic); } @ReactMethod public void unsubscribeFromTopic(String topic) { FirebaseMessaging.getInstance().unsubscribeFromTopic(topic); } @ReactMethod public void presentLocalNotification(ReadableMap details) { Bundle bundle = Arguments.toBundle(details); // If notification ID is not provided by the user, generate one at random if (bundle.getString("id") == null) { bundle.putString("id", String.valueOf(mRandomNumberGenerator.nextInt())); } mRNPushNotificationHelper.sendToNotificationCentre(bundle); } @ReactMethod public void scheduleLocalNotification(ReadableMap details) { Bundle bundle = Arguments.toBundle(details); // If notification ID is not provided by the user, generate one at random if (bundle.getString("id") == null) { bundle.putString("id", String.valueOf(mRandomNumberGenerator.nextInt())); } mRNPushNotificationHelper.sendNotificationScheduled(bundle); } @ReactMethod public void getInitialNotification(Promise promise) { WritableMap params = Arguments.createMap(); Activity activity = getCurrentActivity(); if (activity != null) { Bundle bundle = this.getBundleFromIntent(activity.getIntent()); if (bundle != null) { bundle.putBoolean("foreground", false); String bundleString = mJsDelivery.convertJSON(bundle); params.putString("dataJSON", bundleString); } } promise.resolve(params); } @ReactMethod public void setApplicationIconBadgeNumber(int number) { ApplicationBadgeHelper.INSTANCE.setApplicationIconBadgeNumber(getReactApplicationContext(), number); } // removed @Override temporarily just to get it working on different versions of RN public void onActivityResult(Activity activity, int requestCode, int resultCode, Intent data) { onActivityResult(requestCode, resultCode, data); } // removed @Override temporarily just to get it working on different versions of RN public void onActivityResult(int requestCode, int resultCode, Intent data) { // Ignored, required to implement ActivityEventListener for RN 0.33 } @ReactMethod /** * Cancels all scheduled local notifications, and removes all entries from the notification * centre. * */ public void cancelAllLocalNotifications() { mRNPushNotificationHelper.cancelAllScheduledNotifications(); mRNPushNotificationHelper.clearNotifications(); } @ReactMethod /** * Cancel scheduled notification, and remove notification from the notification centre. * */ public void cancelLocalNotification(String notification_id) { mRNPushNotificationHelper.cancelScheduledNotification(notification_id); } @ReactMethod /** * Clear notification from the notification centre. */ public void clearLocalNotification(String tag, int notificationID) { mRNPushNotificationHelper.clearNotification(tag, notificationID); } @ReactMethod /** * Clears all notifications from the notification center * */ public void removeAllDeliveredNotifications() { mRNPushNotificationHelper.clearNotifications(); } @ReactMethod /** * Returns a list of all notifications currently in the Notification Center */ public void getDeliveredNotifications(Callback callback) { callback.invoke(mRNPushNotificationHelper.getDeliveredNotifications()); } @ReactMethod /** * Returns a list of all currently scheduled notifications */ public void getScheduledLocalNotifications(Callback callback) { callback.invoke(mRNPushNotificationHelper.getScheduledLocalNotifications()); } @ReactMethod /** * Removes notifications from the Notification Center, whose id matches * an element in the provided array */ public void removeDeliveredNotifications(ReadableArray identifiers) { mRNPushNotificationHelper.clearDeliveredNotifications(identifiers); } @ReactMethod /** * Unregister for all remote notifications received */ public void abandonPermissions() { FirebaseMessaging.getInstance().deleteToken(); Log.i(LOG_TAG, "InstanceID deleted"); } @ReactMethod /** * List all channels id */ public void getChannels(Callback callback) { WritableArray array = Arguments.fromList(mRNPushNotificationHelper.listChannels()); if(callback != null) { callback.invoke(array); } } @ReactMethod /** * Check if channel exists with a given id */ public void channelExists(String channel_id, Callback callback) { boolean exists = mRNPushNotificationHelper.channelExists(channel_id); if(callback != null) { callback.invoke(exists); } } @ReactMethod /** * Creates a channel if it does not already exist. Returns whether the channel was created. */ public void createChannel(ReadableMap channelInfo, Callback callback) { boolean created = mRNPushNotificationHelper.createChannel(channelInfo); if(callback != null) { callback.invoke(created); } } @ReactMethod /** * Check if channel is blocked with a given id */ public void channelBlocked(String channel_id, Callback callback) { boolean blocked = mRNPushNotificationHelper.channelBlocked(channel_id); if(callback != null) { callback.invoke(blocked); } } @ReactMethod /** * Delete channel with a given id */ public void deleteChannel(String channel_id) { mRNPushNotificationHelper.deleteChannel(channel_id); } }
package com.planet_ink.coffee_mud.Abilities.Fighter; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.collections.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Libraries.interfaces.ExpertiseLibrary; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.util.*; /* Copyright 2014-2018 Bo Zimmerman 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. */ public class Fighter_WeaponSharpening extends FighterSkill { @Override public String ID() { return "Fighter_WeaponSharpening"; } private final static String localizedName = CMLib.lang().L("Weapon Sharpening"); @Override public String name() { return localizedName; } protected String displayString="Sharpening"; @Override public String displayText() { return L("("+displayString+")"); } private static final String[] triggerStrings =I(new String[] {"WEAPONSHARPENING","SHARPEN"}); @Override public int abstractQuality() { return Ability.QUALITY_INDIFFERENT; } @Override public String[] triggerStrings() { return triggerStrings; } @Override protected int canAffectCode() { return Ability.CAN_ITEMS; } @Override protected int canTargetCode() { return Ability.CAN_ITEMS; } @Override public int maxRange() { return adjustedMaxInvokerRange(0); } @Override public int classificationCode() { return Ability.ACODE_SKILL|Ability.DOMAIN_WEAPON_USE; } @Override public int usageType() { return USAGE_MANA; } protected final static int TICKS_TO_SHARPEN=8; protected Item weapon=null; protected int damageBonus = 1; @Override public void setMiscText(String newMiscText) { super.setMiscText(newMiscText); if(newMiscText.length()>0) damageBonus=CMath.s_int(newMiscText); } @Override public boolean tick(Tickable ticking, int tickID) { if(affected instanceof MOB) { final MOB mob=(MOB)affected; if((weapon==null)||(weapon.owner()!=affected)||(weapon.amDestroyed())||(!CMLib.flags().isInTheGame(mob, true))||(mob.location()==null)) { weapon=null; unInvoke(); return false; } if((this.tickDown % 2)==0) { mob.location().show(mob, weapon, CMMsg.MSG_HANDS, L("<S-NAME> continue(s) sharpening <T-NAME> (@x1).",CMath.toPct(CMath.div((TICKS_TO_SHARPEN-tickDown+1),TICKS_TO_SHARPEN)))); } } else if(affected instanceof Item) { final Item weapon=(Item)affected; if((weapon==null) ||(weapon.amDestroyed()) ||(weapon.subjectToWearAndTear()&&(weapon.usesRemaining()<95))) { this.weapon=null; unInvoke(); return false; } } return super.tick(ticking, tickID); } @Override public void unInvoke() { if(canBeUninvoked()) { if((affected instanceof MOB) &&(weapon != null) &&(!weapon.amDestroyed())) { final MOB mob=(MOB)affected; beneficialAffect(mob,weapon,0,0); final Ability A=weapon.fetchEffect(ID()); if(A!=null) { A.setMiscText(text()); A.makeLongLasting(); } weapon.recoverPhyStats(); if(mob.location()!=null) mob.location().recoverRoomStats(); mob.tell(mob,weapon,null,L("You have finished sharpening <T-NAME>.")); weapon = null; } else if((affected instanceof Item) &&(!((Item)affected).amDestroyed()) &&(((Item)affected).owner() instanceof MOB)) { final MOB M=(MOB)((Item)affected).owner(); if((!M.amDead())&&(CMLib.flags().isInTheGame(M,true))&&(!((Item)affected).amWearingAt(Wearable.IN_INVENTORY))) M.tell(M,affected,null,L("<T-NAME> no longer seem(s) quite as sharp.")); } } super.unInvoke(); } @Override public void affectPhyStats(Physical affected, PhyStats stats) { if((affected instanceof Item)&&(damageBonus>0)&&(((Item)affected).owner() instanceof MOB)) { stats.setDamage(stats.damage()+damageBonus); stats.addAmbiance("^w*^?"); } } @Override public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel) { if(mob.fetchEffect(ID())!=null) { mob.tell(L("You are already sharpening something.")); return false; } final Item weapon=super.getTarget(mob,null,givenTarget,null,commands,Wearable.FILTER_ANY); if(weapon==null) return false; if(!(weapon instanceof Weapon)) { mob.tell(mob,weapon,null,L("<T-NAME> is not a weapon.")); return false; } if(weapon.fetchEffect(ID())!=null) { mob.tell(mob,weapon,null,L("<T-NAME> is already sharp.")); return false; } boolean isSharpenable; switch(((Weapon)weapon).weaponClassification()) { case Weapon.CLASS_AXE: case Weapon.CLASS_DAGGER: case Weapon.CLASS_EDGED: case Weapon.CLASS_SWORD: case Weapon.CLASS_POLEARM: isSharpenable=true; break; case Weapon.CLASS_FLAILED: case Weapon.CLASS_RANGED: case Weapon.CLASS_THROWN: switch(((Weapon)weapon).weaponDamageType()) { case Weapon.TYPE_PIERCING: case Weapon.TYPE_SLASHING: isSharpenable=true; break; default: isSharpenable=false; break; } break; default: isSharpenable=false; break; } if(!isSharpenable) { mob.tell(mob,weapon,null,L("<T-NAME> can not be sharpened with this skill.")); return false; } if((weapon.subjectToWearAndTear())&&(weapon.usesRemaining()<95)) { mob.tell(mob,weapon,null,L("<T-NAME> needs repairing first.")); return false; } if((!auto)&&(mob.isInCombat())) { mob.tell(L("You are a bit too busy to do that right now.")); return false; } final int bonus=(int)Math.round(CMath.mul(0.10+(0.10*getXLEVELLevel(mob)),weapon.phyStats().damage())); if(bonus<1) { mob.tell(mob,weapon,null,L("<T-NAME> is too weak of a weapon to provide any more benefit from sharpening.")); return false; } if(!super.invoke(mob,commands,givenTarget,auto,asLevel)) return false; final boolean success=proficiencyCheck(mob,0,auto); if(success) { final String str=auto?L("<T-NAME> looks sharper!"):L("<S-NAME> start(s) sharpening <T-NAMESELF>."); final CMMsg msg=CMClass.getMsg(mob,weapon,this,CMMsg.MSG_NOISYMOVEMENT,str); if(mob.location().okMessage(mob,msg)) { displayString="Sharpening "+weapon.name(); mob.location().send(mob,msg); if(auto) { beneficialAffect(mob,weapon,asLevel,0); final Ability A=weapon.fetchEffect(ID()); if(A!=null) { A.setMiscText(""+bonus); A.makeLongLasting(); } weapon.recoverPhyStats(); mob.location().recoverRoomStats(); } else { beneficialAffect(mob,mob,asLevel,TICKS_TO_SHARPEN); final Fighter_WeaponSharpening A=(Fighter_WeaponSharpening)mob.fetchEffect(ID()); if(A != null) { A.weapon=weapon; A.setMiscText(""+bonus); } } } } else return beneficialVisualFizzle(mob,weapon,L("<S-NAME> attempt(s) to tweak <T-NAME>, but just can't get it quite right.")); return success; } }
/* You can modify and use this source freely only for the development of application related Live2D. (c) Live2D Inc. All rights reserved. */ package jp.live2d.framework; /* * 画面の操作による行列を扱う。 * */ public final class L2DViewMatrix extends L2DMatrix44 { private float max; private float min; private float screenLeft; // デバイスに対応する論理座標上の範囲 private float screenRight; private float screenTop; private float screenBottom; private float maxLeft; // 論理座標上の移動可能範囲(ここからははみ出さない) private float maxRight; private float maxTop; private float maxBottom; public L2DViewMatrix() { max = 1f; min = 1f; } public final float getMaxScale() { return max; } public final float getMinScale() { return min; } public final boolean isMaxScale() { return getScaleX() == max; } public final void setMaxScale(float v) { max = v; } public final boolean isMinScale() { return getScaleX() == min; } public final void setMinScale(float v) { min = v; } /* * 移動量の計算。 * 移動後の座標が最大範囲をはみ出さないようにする * @param shiftX * @param shiftY */ public final void adjustTranslate(float shiftX, float shiftY) { if (tr[0] * maxLeft + (tr[12] + shiftX) > screenLeft) shiftX = screenLeft - tr[0] * maxLeft - tr[12]; if (tr[0] * maxRight + (tr[12] + shiftX) < screenRight) shiftX = screenRight - tr[0] * maxRight - tr[12]; if (tr[5] * maxTop + (tr[13] + shiftY) < screenTop) shiftY = screenTop - tr[5] * maxTop - tr[13]; if (tr[5] * maxBottom + (tr[13] + shiftY) > screenBottom) shiftY = screenBottom - tr[5] * maxBottom - tr[13]; float tr1[] = {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, shiftX, shiftY, 0, 1}; mul(tr1, tr, tr); } /* * 拡大率の計算。 * 設定された範囲をはみ出さないようにする。 */ public final void adjustScale(float cx, float cy, float scale) { float targetScale = scale * tr[0]; if (targetScale < min) { if (tr[0] > 0) scale = min / tr[0]; } else if (targetScale > max) { if (tr[0] > 0) scale = max / tr[0]; } float tr1[] = {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1}; float tr2[] = {scale, 0, 0, 0, 0, scale, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1}; float tr3[] = {1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, -cx, -cy, 0, 1}; mul(tr3, tr, tr); mul(tr2, tr, tr); mul(tr1, tr, tr); } /* * デバイスに対応する論理座標上の範囲の設定 * @param left * @param right * @param bottom * @param top */ public final void setScreenRect(float left, float right, float bottom, float top) { screenLeft = left; screenRight = right; screenTop = top; screenBottom = bottom; } /* * 論理座標上の移動可能範囲の設定 * @param left * @param right * @param bottom * @param top */ public final void setMaxScreenRect(float left, float right, float bottom, float top) { maxLeft = left; maxRight = right; maxTop = top; maxBottom = bottom; } public final float getScreenLeft() { return screenLeft; } public final float getScreenRight() { return screenRight; } public final float getScreenBottom() { return screenBottom; } public final float getScreenTop() { return screenTop; } public final float getMaxLeft() { return maxLeft; } public final float getMaxRight() { return maxRight; } public final float getMaxBottom() { return maxBottom; } public final float getMaxTop() { return maxTop; } }
package com.ironant.common.base; import android.content.Intent; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import androidx.databinding.DataBindingUtil; import androidx.databinding.ViewDataBinding; import androidx.fragment.app.FragmentActivity; import androidx.lifecycle.LifecycleObserver; import androidx.lifecycle.ViewModel; import androidx.lifecycle.ViewModelProvider; import com.afollestad.materialdialogs.MaterialDialog; import com.ironant.common.utils.LogUtil; import com.ironant.common.utils.MaterialDialogUtils; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; /** * Created by goldze on 2017/6/15. * 一个拥有DataBinding框架的基Activity * 这里根据项目业务可以换成你自己熟悉的BaseActivity, 但是需要继承RxAppCompatActivity,方便LifecycleProvider管理生命周期 */ public abstract class BaseActivity<V extends ViewDataBinding, VM extends BaseViewModel> extends AppCompatActivity { protected V binding; protected VM viewModel; private int viewModelId; private volatile MaterialDialog dialog; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //页面接受的参数方法 //私有的初始化Databinding和ViewModel方法 initViewDataBinding(savedInstanceState); } /** * 注入绑定 */ private void initViewDataBinding(Bundle savedInstanceState) { //DataBindingUtil类需要在project的build中配置 dataBinding {enabled true }, 同步后会自动关联android.databinding包 binding = DataBindingUtil.setContentView(this, initContentView(savedInstanceState)); viewModelId = initVariableId(); viewModel = initViewModel(); if (viewModel == null) { Class modelClass; Type type = getClass().getGenericSuperclass(); if (type instanceof ParameterizedType) { modelClass = (Class) ((ParameterizedType) type).getActualTypeArguments()[1]; } else { //如果没有指定泛型参数,则默认使用BaseViewModel modelClass = BaseViewModel.class; } viewModel = (VM) createViewModel(this, modelClass); } //关联ViewModel initData(); binding.setVariable(viewModelId, viewModel); //让ViewModel拥有View的生命周期感应 getLifecycle().addObserver(viewModel); viewModel.isShowDialogData.observe(this, new androidx.lifecycle.Observer<Boolean>() { // @Override public void onChanged(Boolean showD) { if (!showD) { dismissDialog(); } else { showDialog("登陆"); } } }); } protected abstract void initData(); //刷新布局 public void refreshLayout() { if (viewModel != null) { binding.setVariable(viewModelId, viewModel); } } public synchronized void showDialog(String title) { if (dialog != null) { dialog = dialog.getBuilder().title(title).build(); if (!dialog.isShowing()) { // LogUtil.e("dialog 没有显示"); dialog.show(); } else { // LogUtil.e("dialog 显示"); } } else { // LogUtil.e("dialog 没有隐藏"); MaterialDialog.Builder builder = MaterialDialogUtils.showIndeterminateProgressDialog(this, title, true); dialog = builder.show(); } } public void dismissDialog() { if (dialog != null && dialog.isShowing()) { dialog.dismiss(); } } @Override protected void onDestroy() { super.onDestroy(); //解除Messenger注册 // Messenger.getDefault().unregister(viewModel); if (binding != null) { binding.unbind(); } } /** * 跳转页面 * * @param clz 所跳转的目的Activity类 */ public void startActivity(Class<?> clz) { startActivity(new Intent(this, clz)); } /** * 跳转页面 * * @param clz 所跳转的目的Activity类 * @param bundle 跳转所携带的信息 */ public void startActivity(Class<?> clz, Bundle bundle) { Intent intent = new Intent(this, clz); if (bundle != null) { intent.putExtras(bundle); } startActivity(intent); } /** * 跳转容器页面 * * @param canonicalName 规范名 : Fragment.class.getCanonicalName() * @param bundle 跳转所携带的信息 */ // public void startContainerActivity(String canonicalName, Bundle bundle) { // Intent intent = new Intent(this, ContainerActivity.class); // intent.putExtra(ContainerActivity.FRAGMENT, canonicalName); // if (bundle != null) { // intent.putExtra(ContainerActivity.BUNDLE, bundle); // } // startActivity(intent); // } /** * 初始化根布局 * * @return 布局layout的id */ public abstract int initContentView(Bundle savedInstanceState); /** * 初始化ViewModel的id * * @return BR的id */ public abstract int initVariableId(); /** * 初始化ViewModel * * @return 继承BaseViewModel的ViewModel */ public VM initViewModel() { return null; } /** * 创建ViewModel * * @param cls * @param <T> * @return */ public <T extends ViewModel> T createViewModel(FragmentActivity activity, Class<T> cls) { return new ViewModelProvider(this, new ViewModelProvider.AndroidViewModelFactory(activity.getApplication())).get(cls); } // }
/** * Copyright (C) 2018-2021 Expedia, 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.expediagroup.streamplatform.streamregistry.graphql.model.inputs; import lombok.Builder; import lombok.Value; @Value @Builder public class PrincipalInput { String name; }
/** * Copyright (C) 2017 Black Duck Software, Inc. * http://www.blackducksoftware.com/ * * * 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.blackducksoftware.integration.hub.detect.interactive.mode; import org.springframework.stereotype.Component; @Component public class OfflineInteractiveMode extends InteractiveMode { @Override public void interact() { printWelcome(); final Boolean scan = askYesOrNo("Would you like run a CLI scan?"); if (!scan) { setProperty("hubSignatureScannerDisabled", "true"); } if (scan) { final Boolean customScanner = askYesOrNo("Would you like to provide a custom scanner?"); if (customScanner) { final Boolean downloadCustomScanner = askYesOrNo("Would you like to download the custom scanner?"); if (downloadCustomScanner) { setPropertyFromQuestion("hubSignatureScannerHostUrl", "What is the scanner host url?"); } else { setPropertyFromQuestion("hubSignatureScannerOfflineLocalPath", "What is the location of your offline scanner?"); } } } performStandardOutflow(); } }
package solutions; import java.util.ArrayList; import java.util.Scanner; import java.io.PrintWriter; public class TaskA { public void solve(int testNumber, Scanner in, PrintWriter out) { int n = in.nextInt(); String row = in.next(); ArrayList<Integer> arr = new ArrayList<>(); int count = 0; for (int i = 0; i < n; ++i) { char cur = row.charAt(i); if (cur == 'B') { count++; if (i == n-1) arr.add(count); } else { if (count != 0) arr.add(count); count = 0; } } out.println(arr.size()); for (Integer nb : arr) out.print(nb + " "); } }
package com.syscxp.header.rest; import org.springframework.http.HttpMethod; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import static com.syscxp.header.rest.RESTConstant.EMPTY_STRING; /** * Created by xing5 on 2016/12/7. */ @Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface RestRequest { String path(); String[] optionalPaths() default {}; HttpMethod method(); boolean isAction() default false; String action() default EMPTY_STRING; String[] optionalActions() default {}; String parameterName() default EMPTY_STRING; String[] mappingFields() default {}; Class responseClass(); String category() default EMPTY_STRING; }
/* * ServeStream: A HTTP stream browser/player for Android * Copyright 2013 William Seemann * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this.getActivity() 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 net.sourceforge.servestream.fragment; import java.util.ArrayList; import java.util.List; import net.sourceforge.servestream.transport.AbsTransport; import net.sourceforge.servestream.transport.TransportFactory; import net.sourceforge.servestream.utils.LoadingDialog; import net.sourceforge.servestream.utils.LoadingDialog.LoadingDialogListener; import net.sourceforge.servestream.utils.MusicUtils; import net.sourceforge.servestream.utils.OverflowClickListener; import net.sourceforge.servestream.utils.RateDialog; import net.sourceforge.servestream.utils.UriBeanLoader; import net.sourceforge.servestream.R; import net.sourceforge.servestream.activity.AddUrlActivity; import net.sourceforge.servestream.activity.BluetoothOptionsActivity; import net.sourceforge.servestream.activity.UriEditorActivity; import net.sourceforge.servestream.adapter.UrlListAdapter; import net.sourceforge.servestream.alarm.Alarm; import net.sourceforge.servestream.bean.UriBean; import net.sourceforge.servestream.dbutils.StreamDatabase; import net.sourceforge.servestream.utils.PreferenceConstants; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.bluetooth.BluetoothAdapter; import android.content.BroadcastReceiver; import android.content.ContentResolver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences.Editor; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.preference.PreferenceManager; import android.support.v4.app.DialogFragment; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.support.v4.app.ListFragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.Loader; import android.support.v7.widget.PopupMenu; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import android.widget.Toast; import android.widget.AdapterView.OnItemClickListener; import net.sourceforge.servestream.utils.DetermineActionTask; public class UrlListFragment extends ListFragment implements DetermineActionTask.MusicRetrieverPreparedListener, LoadingDialogListener, OverflowClickListener, LoaderManager.LoaderCallbacks<List<UriBean>> { public final static String TAG = UrlListFragment.class.getName(); public static final String UPDATE_LIST = "net.sourceforge.servestream.updatelist"; private final static String LOADING_DIALOG = "loading_dialog"; private final static String RATE_DIALOG = "rate_dialog"; public static final String ARG_TARGET_URI = "target_uri"; private StreamDatabase mStreamdb = null; private SharedPreferences mPreferences = null; private DetermineActionTask mDetermineActionTask; private UrlListAdapter mAdapter; private BrowseIntentListener mListener; private UriBean mSelectedMenuItem; private int mId = 0; @SuppressLint("HandlerLeak") private Handler mQueueHandler = new Handler() { @Override public void handleMessage(Message msg) { MusicUtils.addToCurrentPlaylist(UrlListFragment.this.getActivity(), (long []) msg.obj); } }; @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mListener = (BrowseIntentListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement BrowseIntentListener"); } // connect with streams database and populate list mStreamdb = new StreamDatabase(getActivity()); } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); setHasOptionsMenu(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_uri_list, container, false); ListView list = (ListView) view.findViewById(android.R.id.list); list.setEmptyView(view.findViewById(android.R.id.empty)); return view; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); mPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity()); ListView list = getListView(); list.setOnItemClickListener(new OnItemClickListener() { public synchronized void onItemClick(AdapterView<?> parent, View view, int position, long id) { UriBean uriBean = (UriBean) parent.getItemAtPosition(position); processUri(uriBean.getUri().toString()); } }); mAdapter = new UrlListAdapter(getActivity(), new ArrayList<UriBean>(), this); setListAdapter(mAdapter); } @Override public void onActivityCreated (Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (getArguments().getString(ARG_TARGET_URI) != null) { String targetUri = getArguments().getString(ARG_TARGET_URI); processUri(targetUri); getArguments().putString("target_uri", null); } else { // see if the user wants to rate the application after 5 uses int rateApplicationFlag = mPreferences.getInt(PreferenceConstants.RATE_APPLICATION_FLAG, 0); if (rateApplicationFlag != -1) { rateApplicationFlag++; Editor ed = mPreferences.edit(); ed.putInt(PreferenceConstants.RATE_APPLICATION_FLAG, rateApplicationFlag); ed.commit(); if (rateApplicationFlag == 10) { showDialog(RATE_DIALOG); } } } } @Override public void onStart() { super.onStart(); IntentFilter f = new IntentFilter(); f.addAction(UPDATE_LIST); getActivity().registerReceiver(mUpdateListListener, f); } @Override public void onResume() { super.onResume(); updateList(); } @Override public void onStop() { super.onStop(); getActivity().unregisterReceiver(mUpdateListListener); } @Override public void onDetach () { super.onDetach(); mStreamdb.close(); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.url_list, menu); super.onCreateOptionsMenu(menu, inflater); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case (R.id.menu_item_add): startActivity(new Intent(getActivity(), AddUrlActivity.class)); return true; default: return super.onOptionsItemSelected(item); } } private boolean processUri(String input) { Uri uri = TransportFactory.getUri(input); if (uri == null) { return false; } UriBean uriBean = TransportFactory.findUri(mStreamdb, uri); if (uriBean == null) { uriBean = TransportFactory.getTransport(uri.getScheme()).createUri(uri); AbsTransport transport = TransportFactory.getTransport(uriBean.getProtocol()); transport.setUri(uriBean); if (mPreferences.getBoolean(PreferenceConstants.AUTOSAVE, true)) { mStreamdb.saveUri(uriBean); updateList(); } } showDialog(LOADING_DIALOG); mDetermineActionTask = new DetermineActionTask(getActivity(), uriBean, this); mDetermineActionTask.execute(); return true; } public void updateList() { getLoaderManager().initLoader(mId++, null, this); } private void showUrlNotOpenedToast() { Toast.makeText(this.getActivity(), R.string.url_not_opened_message, Toast.LENGTH_SHORT).show(); } @Override public void onMusicRetrieverPrepared(String action, UriBean uri, long[] list) { dismissDialog(LOADING_DIALOG); if (action.equals(DetermineActionTask.URL_ACTION_UNDETERMINED)) { showUrlNotOpenedToast(); } else if (action.equals(DetermineActionTask.URL_ACTION_BROWSE)) { if (mPreferences.getBoolean(PreferenceConstants.AUTOSAVE, true)) { mStreamdb.touchUri(uri); } mListener.browseToUri(uri.getScrubbedUri()); } else if (action.equals(DetermineActionTask.URL_ACTION_PLAY)) { if (mPreferences.getBoolean(PreferenceConstants.AUTOSAVE, true)) { mStreamdb.touchUri(uri); } MusicUtils.playAll(getActivity(), list, 0); } } private void showDialog(String tag) { // DialogFragment.show() will take care of adding the fragment // in a transaction. We also want to remove any currently showing // dialog, so make our own transaction and take care of that here. FragmentTransaction ft = getChildFragmentManager().beginTransaction(); Fragment prev = getChildFragmentManager().findFragmentByTag(tag); if (prev != null) { ft.remove(prev); } DialogFragment newFragment = null; // Create and show the dialog. if (tag.equals(LOADING_DIALOG)) { newFragment = LoadingDialog.newInstance(this, getString(R.string.opening_url_message)); } else if (tag.equals(RATE_DIALOG)) { newFragment = RateDialog.newInstance(); } ft.add(0, newFragment, tag); ft.commitAllowingStateLoss(); } private void dismissDialog(String tag) { FragmentTransaction ft = getChildFragmentManager().beginTransaction(); DialogFragment prev = (DialogFragment) getChildFragmentManager().findFragmentByTag(tag); if (prev != null) { prev.dismiss(); ft.remove(prev); } ft.commitAllowingStateLoss(); } @Override public void onLoadingDialogCancelled(DialogFragment dialog) { if (mDetermineActionTask != null) { mDetermineActionTask.cancel(true); mDetermineActionTask = null; } } private BroadcastReceiver mUpdateListListener = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { updateList(); } }; // Container Activity must implement this interface public interface BrowseIntentListener { public void browseToUri(Uri uri); } private void showPopup(View v, UriBean uri) { mSelectedMenuItem = uri; PopupMenu popup = new PopupMenu(getActivity(), v); Menu menu = popup.getMenu(); MenuInflater inflater = popup.getMenuInflater(); inflater.inflate(R.menu.uri_list_uri_actions, menu); BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (bluetoothAdapter == null) { menu.removeItem(R.id.menu_autostart_on_bluetooth); } popup.setOnMenuItemClickListener(mPopupMenuOnMenuItemClickListener); popup.show(); } private PopupMenu.OnMenuItemClickListener mPopupMenuOnMenuItemClickListener = new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { Intent intent; switch (item.getItemId()) { case R.id.menu_item_edit: intent = new Intent(getActivity(), UriEditorActivity.class); intent.putExtra(Intent.EXTRA_TITLE, mSelectedMenuItem.getId()); getActivity().startActivity(intent); return true; case R.id.menu_item_delete: // prompt user to make sure they really want this.getActivity() new AlertDialog.Builder(getActivity()) .setMessage(getString(R.string.url_delete_confirmation_msg, mSelectedMenuItem.getNickname())) .setPositiveButton(R.string.confirm_label, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { mStreamdb.deleteUri(mSelectedMenuItem); ContentResolver resolver = getActivity().getContentResolver(); resolver.update( Alarm.Columns.CONTENT_URI, null, null, new String[] { String.valueOf(mSelectedMenuItem.getId()) }); updateList(); } }) .setNegativeButton(R.string.cancel_label, null).create().show(); return true; case R.id.menu_item_add_to_playlist_label: MusicUtils.addToCurrentPlaylistFromURL(getActivity(), mSelectedMenuItem, mQueueHandler); return true; case R.id.menu_item_share: String url = mSelectedMenuItem.getUri().toString(); String appName = getString(R.string.app_name); intent = new Intent(Intent.ACTION_SEND); intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_TEXT, getString(R.string.share_signature, url, appName)); startActivity(Intent.createChooser(intent, getString(R.string.share_label))); return true; case R.id.menu_autostart_on_bluetooth: SharedPreferences prefs = getActivity().getSharedPreferences(BluetoothOptionsActivity.PREFS_NAME, Context.MODE_PRIVATE); Editor editor = prefs.edit(); editor.putString(BluetoothOptionsActivity.PREF_AUTOSTART_STREAM, mSelectedMenuItem.getUri().toString()); editor.commit(); return true; default: return false; } } }; @Override public void onClick(View view, UriBean uri) { showPopup(view, uri); } @Override public Loader<List<UriBean>> onCreateLoader(int id, Bundle args) { // This is called when a new Loader needs to be created. This // sample only has one Loader with no arguments, so it is simple. return new UriBeanLoader(getActivity()); } @Override public void onLoadFinished(Loader<List<UriBean>> loader, List<UriBean> data) { // Set the new data in the adapter. mAdapter.clear(); for (int i = 0; i < data.size(); i++) { mAdapter.add(data.get(i)); } } @Override public void onLoaderReset(Loader<List<UriBean>> loader) { // Clear the data in the adapter. mAdapter.clear(); } }
package com.isheihei.mall.member.dao; import com.isheihei.mall.member.entity.UndoLogEntity; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; /** * * * @author YazhouTown * @email yazhoutown@gmail.com * @date 2021-07-01 21:54:13 */ @Mapper public interface UndoLogDao extends BaseMapper<UndoLogEntity> { }
/* * Copyright (c) 2017 - 2019, SmartDeviceLink Consortium, 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 the SmartDeviceLink Consortium, Inc. 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. */ package com.smartdevicelink.streaming; import com.smartdevicelink.protocol.ProtocolMessage; public interface IStreamListener { void sendStreamPacket(ProtocolMessage pm); }
/* * MIT License * * Copyright (c) 2022 MASES s.r.l. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /************************************************************************************** * <auto-generated> * This code was generated from a template using JCOReflector * * Manual changes to this file may cause unexpected behavior in your application. * Manual changes to this file will be overwritten if the code is regenerated. * </auto-generated> *************************************************************************************/ package microsoft.visualbasic.compilerservices; import org.mases.jcobridge.*; import org.mases.jcobridge.netreflection.*; import java.util.ArrayList; // Import section /** * The base .NET class managing Microsoft.VisualBasic.CompilerServices.ObjectFlowControl, Microsoft.VisualBasic.Core, Version=10.0.6.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a. * <p> * * See: <a href="https://docs.microsoft.com/en-us/dotnet/api/Microsoft.VisualBasic.CompilerServices.ObjectFlowControl" target="_top">https://docs.microsoft.com/en-us/dotnet/api/Microsoft.VisualBasic.CompilerServices.ObjectFlowControl</a> */ public class ObjectFlowControl extends NetObject { /** * Fully assembly qualified name: Microsoft.VisualBasic.Core, Version=10.0.6.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a */ public static final String assemblyFullName = "Microsoft.VisualBasic.Core, Version=10.0.6.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; /** * Assembly name: Microsoft.VisualBasic.Core */ public static final String assemblyShortName = "Microsoft.VisualBasic.Core"; /** * Qualified class name: Microsoft.VisualBasic.CompilerServices.ObjectFlowControl */ public static final String className = "Microsoft.VisualBasic.CompilerServices.ObjectFlowControl"; static JCOBridge bridge = JCOBridgeInstance.getInstance(assemblyFullName); /** * The type managed from JCOBridge. See {@link JCType} */ public static JCType classType = createType(); static JCEnum enumInstance = null; JCObject classInstance = null; static JCType createType() { try { String classToCreate = className + ", " + (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName); if (JCOReflector.getDebug()) JCOReflector.writeLog("Creating %s", classToCreate); JCType typeCreated = bridge.GetType(classToCreate); if (JCOReflector.getDebug()) JCOReflector.writeLog("Created: %s", (typeCreated != null) ? typeCreated.toString() : "Returned null value"); return typeCreated; } catch (JCException e) { JCOReflector.writeLog(e); return null; } } void addReference(String ref) throws Throwable { try { bridge.AddReference(ref); } catch (JCNativeException jcne) { throw translateException(jcne); } } /** * Internal constructor. Use with caution */ public ObjectFlowControl(java.lang.Object instance) throws Throwable { super(instance); if (instance instanceof JCObject) { classInstance = (JCObject) instance; } else throw new Exception("Cannot manage object, it is not a JCObject"); } public String getJCOAssemblyName() { return assemblyFullName; } public String getJCOClassName() { return className; } public String getJCOObjectName() { return className + ", " + (JCOReflector.getUseFullAssemblyName() ? assemblyFullName : assemblyShortName); } public java.lang.Object getJCOInstance() { return classInstance; } public void setJCOInstance(JCObject instance) { classInstance = instance; super.setJCOInstance(classInstance); } public JCType getJCOType() { return classType; } /** * Try to cast the {@link IJCOBridgeReflected} instance into {@link ObjectFlowControl}, a cast assert is made to check if types are compatible. * @param from {@link IJCOBridgeReflected} instance to be casted * @return {@link ObjectFlowControl} instance * @throws java.lang.Throwable in case of error during cast operation */ public static ObjectFlowControl cast(IJCOBridgeReflected from) throws Throwable { NetType.AssertCast(classType, from); return new ObjectFlowControl(from.getJCOInstance()); } // Constructors section public ObjectFlowControl() throws Throwable { } // Methods section public static void CheckForSyncLockOnValueType(NetObject Expression) throws Throwable, system.ArgumentNullException, system.ArgumentException, system.ArgumentOutOfRangeException, system.globalization.CultureNotFoundException, system.PlatformNotSupportedException, system.OutOfMemoryException, system.runtime.interopservices.ExternalException, system.NotSupportedException, system.InvalidOperationException, system.IndexOutOfRangeException { if (classType == null) throw new UnsupportedOperationException("classType is null."); try { classType.Invoke("CheckForSyncLockOnValueType", Expression == null ? null : Expression.getJCOInstance()); } catch (JCNativeException jcne) { throw translateException(jcne); } } // Properties section // Instance Events section }
/* * Copyright 2015-2016 Red Hat, Inc, and individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.hal.client.configuration.subsystem.elytron; import org.jboss.hal.core.CrudOperations; import org.jboss.hal.core.finder.PreviewAttributes; import org.jboss.hal.core.finder.PreviewContent; import org.jboss.hal.core.finder.StaticItem; import org.jboss.hal.dmr.ModelNode; import org.jboss.hal.resources.Resources; import static java.util.Arrays.asList; class ElytronSubsystemPreview extends PreviewContent<StaticItem> { private final CrudOperations crud; private final PreviewAttributes<ModelNode> attributes; @SuppressWarnings("HardCodedStringLiteral") ElytronSubsystemPreview(CrudOperations crud, Resources resources) { super(resources.constants().globalSettings()); this.crud = crud; this.attributes = new PreviewAttributes<>(new ModelNode(), asList("default-authentication-context", "disallowed-providers", "initial-providers", "final-providers", "security-properties" )); previewBuilder().addAll(attributes); } @Override public void update(final StaticItem item) { crud.read(AddressTemplates.ELYTRON_SUBSYSTEM_TEMPLATE, attributes::refresh); } }
package hr.fer.zemris.java.hw13; import java.util.ArrayList; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; /** * Utility class which provides some functional methods when working with * {@link Map} objects. * * @author dbrcina * */ public class MapUtil { /** * Sorts <code>map</code> by values in <b>descending</b> order. * * @param <K> key type. * @param <V> value type. * @param map map. * @return sorted map. */ public static <K, V extends Comparable<? super V>> Map<K, V> sortByValueDesc(Map<K, V> map) { Comparator<V> descending = (v1, v2) -> v2.compareTo(v1); List<Entry<K, V>> list = new ArrayList<>(map.entrySet()); list.sort(Entry.comparingByValue(descending)); Map<K, V> result = new LinkedHashMap<>(); for (Entry<K, V> entry : list) { result.put(entry.getKey(), entry.getValue()); } return result; } }
/** * 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.pinot.common.tier; /** * Interface for the storage type of the tier */ public interface TierStorage { /** * Returns the type of the storage (e.g. PINOT_SERVER) */ String getType(); }
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.opensearch.discovery.ec2; import com.carrotsearch.randomizedtesting.annotations.Name; import com.carrotsearch.randomizedtesting.annotations.ParametersFactory; import org.opensearch.test.rest.yaml.ClientYamlTestCandidate; import org.opensearch.test.rest.yaml.OpenSearchClientYamlSuiteTestCase; public class AmazonEC2DiscoveryClientYamlTestSuiteIT extends OpenSearchClientYamlSuiteTestCase { public AmazonEC2DiscoveryClientYamlTestSuiteIT(@Name("yaml") ClientYamlTestCandidate testCandidate) { super(testCandidate); } @ParametersFactory public static Iterable<Object[]> parameters() throws Exception { return createParameters(); } }
package jean.peptide; import java.io.File; import jam.app.JamHome; import jam.io.LineReader; import jam.matrix.MatrixUtil; import jam.util.RegexUtil; final class RIMReader { private final File file; private final double[][] matrix; private RIMReader(File file) { this.file = file; this.matrix = MatrixUtil.square(Residue.countNative(), Double.NaN); } static double[][] readSparse(File file) { RIMReader reader = new RIMReader(file); return reader.readSparse(); } private double[][] readSparse() { LineReader reader = LineReader.open(file); try { for (String line : reader) parseLine(line); } finally { reader.close(); } return matrix; } private void parseLine(String line) { line = line.trim(); if (line.isEmpty()) return; String[] fields = RegexUtil.split(RegexUtil.COMMA, line, 3); Residue res1 = Residue.valueOf(fields[0]); Residue res2 = Residue.valueOf(fields[1]); double bind = Double.parseDouble(fields[2]); int index1 = res1.ordinal(); int index2 = res2.ordinal(); matrix[index1][index2] = bind; matrix[index2][index1] = bind; } }
package com.intel.mtwilson.security.jpa; import com.intel.mtwilson.datatypes.Role; import com.intel.mtwilson.ms.controller.ApiClientX509JpaController; import com.intel.mtwilson.ms.data.ApiClientX509; import com.intel.mtwilson.ms.data.ApiRoleX509; import com.intel.mtwilson.security.core.PublicKeyUserFinder; import com.intel.mtwilson.security.core.PublicKeyUserInfo; import com.intel.mtwilson.security.core.X509UserFinder; import com.intel.mtwilson.security.core.X509UserInfo; import java.io.ByteArrayInputStream; import java.security.KeyFactory; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; import java.security.spec.InvalidKeySpecException; import java.security.spec.X509EncodedKeySpec; import java.util.ArrayList; import java.util.Collection; import javax.persistence.EntityManagerFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * It was labeled business logic but it's very closely tied to the JPA layer. * * Secret key lookup provider for the authentication filter that secures * the REST API. * * @since 0.5.1 * @author jbuhacoff */ public class ApiClientX509BO implements X509UserFinder, PublicKeyUserFinder { private static Logger log = LoggerFactory.getLogger(ApiClientX509BO.class); private ApiClientX509JpaController controller; public ApiClientX509BO(EntityManagerFactory factory) { controller = new ApiClientX509JpaController(factory); } private ApiClientX509 getApiClientByFingerprint(byte[] fingerprint) { ApiClientX509 apiClient = controller.findEnabledApiClientX509ByFingerprint(fingerprint); return apiClient; } private Certificate getCertificate(byte[] certificateBytes) { if( certificateBytes != null ) { try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate cert = (X509Certificate)cf.generateCertificate(new ByteArrayInputStream(certificateBytes)); return cert; } catch (CertificateException ex) { log.error("Cannot load certificate", ex); return null; } } return null; } // commenting out unused function (6/11 1.2) /* private PublicKey getPublicKey(byte[] publicKeyBytes) { if( publicKeyBytes != null ) { try { KeyFactory kf = KeyFactory.getInstance("RSA"); X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicKeyBytes); PublicKey publicKey = (PublicKey)kf.generatePublic(keySpec); return publicKey; } catch (InvalidKeySpecException ex) { log.error("Cannot load public key from database", ex); return null; } catch (NoSuchAlgorithmException ex) { log.error("Cannot load public key from database", ex); return null; } } return null; } */ @Override public X509UserInfo getUserForX509Identity(byte[] fingerprint) { ApiClientX509 apiClient = getApiClientByFingerprint(fingerprint); if( apiClient == null ) { return null; } X509UserInfo userInfo = new X509UserInfo(); userInfo.certificate = getCertificate(apiClient.getCertificate()); // Let us add the display name of the user too String tempUserName = apiClient.getName(); // Since we need to ignore the comma character before the OU, the to index is being subtracted by 2 userInfo.loginName = tempUserName.substring(tempUserName.indexOf("CN=") + 3, tempUserName.indexOf("OU=")-1); // userInfo.publicKey = userInfo.certificate.getPublicKey(); // apiClient.getCertificate().getPublicKey(); userInfo.fingerprint = fingerprint; Collection<ApiRoleX509> roles = apiClient.getApiRoleX509Collection(); ArrayList<Role> allowedRoles = new ArrayList<Role>(); for( ApiRoleX509 role : roles ) { String roleName = role.getApiRoleX509PK().getRole(); try { allowedRoles.add(Role.valueOf(roleName)); } catch(IllegalArgumentException e) { // we ignore unsupported roles, but log the error log.error("Unsupported role name ("+roleName+") assigned to "+apiClient.getName(), e); } } userInfo.roles = allowedRoles.toArray(new Role[0]); return userInfo; } /** * For now we are using the same X509 table for both "X509" and "PublicKey" * authentication schemes. The "PublicKey" scheme just needs the public key, * the "X509" needs the entire certificate. To be normal they should be * in separate tables. * @param fingerprint * @return */ @Override public PublicKeyUserInfo getUserForIdentity(byte[] fingerprint) { X509UserInfo x509 = getUserForX509Identity(fingerprint); if( x509 == null ) { return null; } PublicKeyUserInfo userInfo = new PublicKeyUserInfo(); userInfo.fingerprint = fingerprint; if( x509.certificate != null ) { userInfo.publicKey = x509.certificate.getPublicKey(); } userInfo.roles = x509.roles; return userInfo; } }
/** * Copyright 2015-2017 Knowm Inc. (http://knowm.org) and contributors. * Copyright 2011-2015 Xeiam LLC (http://xeiam.com) and contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.knowm.xchart; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; /** * This class can be used to create histogram * * @author timmolter */ public class Histogram { private List<Double> xAxisData; // bin centers private List<Double> yAxisData; // frequency counts private final Collection<? extends Number> originalData; private final int numBins; private final double min; private final double max; /** * Constructor * * @param data * @param numBins */ public Histogram(Collection<? extends Number> data, int numBins) { this.numBins = numBins; this.originalData = data; Double tempMax = -Double.MAX_VALUE; Double tempMin = Double.MAX_VALUE; for (Number number : data) { double value = number.doubleValue(); if (value > tempMax) { tempMax = value; } if (value < tempMin) { tempMin = value; } } max = tempMax; min = tempMin; init(); } /** * Constructor * * @param data * @param numBins * @param min * @param max */ public Histogram(Collection<? extends Number> data, int numBins, double min, double max) { this.numBins = numBins; this.originalData = data; this.min = min; this.max = max; init(); } private void init() { double[] tempYAxisData = new double[numBins]; final double binSize = (max - min) / numBins; // y axis data Iterator<? extends Number> itr = originalData.iterator(); while (itr.hasNext()) { double doubleValue = itr.next().doubleValue(); int bin = (int) ((doubleValue - min) / binSize); // changed this from numBins if (bin < 0) { /* this data is smaller than min */ // System.out.println("less than"); } else if (doubleValue == max) { // the value falls exactly on the max value tempYAxisData[bin - 1] += 1; } else if (bin > numBins || bin == numBins) { /* this data point is bigger than max */ // System.out.println("greater than"); } else { tempYAxisData[bin] += 1; } } yAxisData = new ArrayList<Double>(numBins); for (double d : tempYAxisData) { yAxisData.add(d); } // x axis data xAxisData = new ArrayList<Double>(numBins); for (int i = 0; i < numBins; i++) { xAxisData.add(((i * (max - min)) / numBins + min) + binSize / 2); } } public List<Double> getxAxisData() { return xAxisData; } public List<Double> getyAxisData() { return yAxisData; } public Collection<? extends Number> getOriginalData() { return originalData; } public int getNumBins() { return numBins; } public double getMin() { return min; } public double getMax() { return max; } }
/* * Copyright (c) 2020. https://rxmicro.io * * 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 io.rxmicro.examples.data.r2dbc.postgresql.returntypes.insert; import io.reactivex.rxjava3.core.Maybe; import io.rxmicro.data.sql.VariableValues; import io.rxmicro.data.sql.model.EntityFieldList; import io.rxmicro.data.sql.model.EntityFieldMap; import io.rxmicro.data.sql.operation.Insert; import io.rxmicro.data.sql.r2dbc.postgresql.PostgreSQLRepository; import io.rxmicro.examples.data.r2dbc.postgresql.returntypes.model.Account; @PostgreSQLRepository @VariableValues({ "${table}", "account" }) public interface InsertOneEntityFieldsUsingMaybeRepository { @Insert("INSERT INTO ${table}(first_name, last_name) VALUES(?,?) ON CONFLICT DO NOTHING RETURNING *") Maybe<Account> insert01(String firstName, String lastName); @Insert("INSERT INTO ${table}(first_name, last_name) VALUES(?,?) ON CONFLICT DO NOTHING RETURNING first_name, last_name") Maybe<EntityFieldMap> insert02(String firstName, String lastName); @Insert("INSERT INTO ${table}(first_name, last_name) VALUES(?,?) ON CONFLICT DO NOTHING RETURNING first_name, last_name") Maybe<EntityFieldList> insert03(String firstName, String lastName); }
/* * 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.cls.v20201016.models; import com.tencentcloudapi.common.AbstractModel; import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.Expose; import java.util.HashMap; public class MachineGroupInfo extends AbstractModel{ /** * 机器组ID */ @SerializedName("GroupId") @Expose private String GroupId; /** * 机器组名称 */ @SerializedName("GroupName") @Expose private String GroupName; /** * 机器组类型 */ @SerializedName("MachineGroupType") @Expose private MachineGroupTypeInfo MachineGroupType; /** * 创建时间 */ @SerializedName("CreateTime") @Expose private String CreateTime; /** * 机器组绑定的标签列表 注意:此字段可能返回 null,表示取不到有效值。 */ @SerializedName("Tags") @Expose private Tag [] Tags; /** * 是否开启机器组自动更新 注意:此字段可能返回 null,表示取不到有效值。 */ @SerializedName("AutoUpdate") @Expose private String AutoUpdate; /** * 升级开始时间,建议业务低峰期升级LogListener 注意:此字段可能返回 null,表示取不到有效值。 */ @SerializedName("UpdateStartTime") @Expose private String UpdateStartTime; /** * 升级结束时间,建议业务低峰期升级LogListener 注意:此字段可能返回 null,表示取不到有效值。 */ @SerializedName("UpdateEndTime") @Expose private String UpdateEndTime; /** * 是否开启服务日志,用于记录因Loglistener 服务自身产生的log,开启后,会创建内部日志集cls_service_logging和日志主题loglistener_status,loglistener_alarm,loglistener_business,不产生计费 注意:此字段可能返回 null,表示取不到有效值。 */ @SerializedName("ServiceLogging") @Expose private Boolean ServiceLogging; /** * Get 机器组ID * @return GroupId 机器组ID */ public String getGroupId() { return this.GroupId; } /** * Set 机器组ID * @param GroupId 机器组ID */ public void setGroupId(String GroupId) { this.GroupId = GroupId; } /** * Get 机器组名称 * @return GroupName 机器组名称 */ public String getGroupName() { return this.GroupName; } /** * Set 机器组名称 * @param GroupName 机器组名称 */ public void setGroupName(String GroupName) { this.GroupName = GroupName; } /** * Get 机器组类型 * @return MachineGroupType 机器组类型 */ public MachineGroupTypeInfo getMachineGroupType() { return this.MachineGroupType; } /** * Set 机器组类型 * @param MachineGroupType 机器组类型 */ public void setMachineGroupType(MachineGroupTypeInfo MachineGroupType) { this.MachineGroupType = MachineGroupType; } /** * Get 创建时间 * @return CreateTime 创建时间 */ public String getCreateTime() { return this.CreateTime; } /** * Set 创建时间 * @param CreateTime 创建时间 */ public void setCreateTime(String CreateTime) { this.CreateTime = CreateTime; } /** * Get 机器组绑定的标签列表 注意:此字段可能返回 null,表示取不到有效值。 * @return Tags 机器组绑定的标签列表 注意:此字段可能返回 null,表示取不到有效值。 */ public Tag [] getTags() { return this.Tags; } /** * Set 机器组绑定的标签列表 注意:此字段可能返回 null,表示取不到有效值。 * @param Tags 机器组绑定的标签列表 注意:此字段可能返回 null,表示取不到有效值。 */ public void setTags(Tag [] Tags) { this.Tags = Tags; } /** * Get 是否开启机器组自动更新 注意:此字段可能返回 null,表示取不到有效值。 * @return AutoUpdate 是否开启机器组自动更新 注意:此字段可能返回 null,表示取不到有效值。 */ public String getAutoUpdate() { return this.AutoUpdate; } /** * Set 是否开启机器组自动更新 注意:此字段可能返回 null,表示取不到有效值。 * @param AutoUpdate 是否开启机器组自动更新 注意:此字段可能返回 null,表示取不到有效值。 */ public void setAutoUpdate(String AutoUpdate) { this.AutoUpdate = AutoUpdate; } /** * Get 升级开始时间,建议业务低峰期升级LogListener 注意:此字段可能返回 null,表示取不到有效值。 * @return UpdateStartTime 升级开始时间,建议业务低峰期升级LogListener 注意:此字段可能返回 null,表示取不到有效值。 */ public String getUpdateStartTime() { return this.UpdateStartTime; } /** * Set 升级开始时间,建议业务低峰期升级LogListener 注意:此字段可能返回 null,表示取不到有效值。 * @param UpdateStartTime 升级开始时间,建议业务低峰期升级LogListener 注意:此字段可能返回 null,表示取不到有效值。 */ public void setUpdateStartTime(String UpdateStartTime) { this.UpdateStartTime = UpdateStartTime; } /** * Get 升级结束时间,建议业务低峰期升级LogListener 注意:此字段可能返回 null,表示取不到有效值。 * @return UpdateEndTime 升级结束时间,建议业务低峰期升级LogListener 注意:此字段可能返回 null,表示取不到有效值。 */ public String getUpdateEndTime() { return this.UpdateEndTime; } /** * Set 升级结束时间,建议业务低峰期升级LogListener 注意:此字段可能返回 null,表示取不到有效值。 * @param UpdateEndTime 升级结束时间,建议业务低峰期升级LogListener 注意:此字段可能返回 null,表示取不到有效值。 */ public void setUpdateEndTime(String UpdateEndTime) { this.UpdateEndTime = UpdateEndTime; } /** * Get 是否开启服务日志,用于记录因Loglistener 服务自身产生的log,开启后,会创建内部日志集cls_service_logging和日志主题loglistener_status,loglistener_alarm,loglistener_business,不产生计费 注意:此字段可能返回 null,表示取不到有效值。 * @return ServiceLogging 是否开启服务日志,用于记录因Loglistener 服务自身产生的log,开启后,会创建内部日志集cls_service_logging和日志主题loglistener_status,loglistener_alarm,loglistener_business,不产生计费 注意:此字段可能返回 null,表示取不到有效值。 */ public Boolean getServiceLogging() { return this.ServiceLogging; } /** * Set 是否开启服务日志,用于记录因Loglistener 服务自身产生的log,开启后,会创建内部日志集cls_service_logging和日志主题loglistener_status,loglistener_alarm,loglistener_business,不产生计费 注意:此字段可能返回 null,表示取不到有效值。 * @param ServiceLogging 是否开启服务日志,用于记录因Loglistener 服务自身产生的log,开启后,会创建内部日志集cls_service_logging和日志主题loglistener_status,loglistener_alarm,loglistener_business,不产生计费 注意:此字段可能返回 null,表示取不到有效值。 */ public void setServiceLogging(Boolean ServiceLogging) { this.ServiceLogging = ServiceLogging; } public MachineGroupInfo() { } /** * 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 MachineGroupInfo(MachineGroupInfo source) { if (source.GroupId != null) { this.GroupId = new String(source.GroupId); } if (source.GroupName != null) { this.GroupName = new String(source.GroupName); } if (source.MachineGroupType != null) { this.MachineGroupType = new MachineGroupTypeInfo(source.MachineGroupType); } if (source.CreateTime != null) { this.CreateTime = new String(source.CreateTime); } if (source.Tags != null) { this.Tags = new Tag[source.Tags.length]; for (int i = 0; i < source.Tags.length; i++) { this.Tags[i] = new Tag(source.Tags[i]); } } if (source.AutoUpdate != null) { this.AutoUpdate = new String(source.AutoUpdate); } if (source.UpdateStartTime != null) { this.UpdateStartTime = new String(source.UpdateStartTime); } if (source.UpdateEndTime != null) { this.UpdateEndTime = new String(source.UpdateEndTime); } if (source.ServiceLogging != null) { this.ServiceLogging = new Boolean(source.ServiceLogging); } } /** * Internal implementation, normal users should not use it. */ public void toMap(HashMap<String, String> map, String prefix) { this.setParamSimple(map, prefix + "GroupId", this.GroupId); this.setParamSimple(map, prefix + "GroupName", this.GroupName); this.setParamObj(map, prefix + "MachineGroupType.", this.MachineGroupType); this.setParamSimple(map, prefix + "CreateTime", this.CreateTime); this.setParamArrayObj(map, prefix + "Tags.", this.Tags); this.setParamSimple(map, prefix + "AutoUpdate", this.AutoUpdate); this.setParamSimple(map, prefix + "UpdateStartTime", this.UpdateStartTime); this.setParamSimple(map, prefix + "UpdateEndTime", this.UpdateEndTime); this.setParamSimple(map, prefix + "ServiceLogging", this.ServiceLogging); } }
package com.ddxlabs.girgrat.entity.component; import com.artemis.Component; import org.mini2Dx.core.engine.geom.CollisionBox; import org.mini2Dx.core.engine.geom.CollisionCircle; /** * Created on 4/19/2017. */ public class Sphere extends Component { private CollisionCircle sphere; public Sphere() { } public Sphere(float radius) { sphere = new CollisionCircle(0,0 , radius); } public Sphere(float radius, float initialXpos, float initialYpos) { sphere = new CollisionCircle(initialXpos, initialYpos, radius); } public CollisionCircle getCircle() { return sphere; } }
package result.model; import lombok.*; import javax.persistence.*; import java.io.Serializable; import java.util.Objects; @Data @AllArgsConstructor @NoArgsConstructor @Embeddable public class RecipeCompositeKey implements Serializable { @Column(name = "ingredient_id") private Long ingredientId; @Column(name = "meal_id") private Long mealId; @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof RecipeCompositeKey)) return false; RecipeCompositeKey that = (RecipeCompositeKey) o; return ingredientId.equals(that.ingredientId) && mealId.equals(that.mealId); } @Override public int hashCode() { return Objects.hash(ingredientId, mealId); } }
/* * Copyright 2016 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.kie.workbench.common.stunner.core.definition.annotation; import org.kie.workbench.common.stunner.core.definition.builder.Builder; import org.kie.workbench.common.stunner.core.definition.builder.VoidBuilder; import org.kie.workbench.common.stunner.core.factory.graph.ElementFactory; import java.lang.annotation.*; @Inherited @Retention( RetentionPolicy.RUNTIME ) @Target( { ElementType.TYPE } ) public @interface DefinitionSet { Class<?>[] definitions(); Class<? extends Builder<?>> builder() default VoidBuilder.class; Class<? extends ElementFactory> graphFactory(); }
/** * 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.fineract.infrastructure.core.exceptionmapper; import com.google.gson.stream.MalformedJsonException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import javax.ws.rs.ext.ExceptionMapper; import javax.ws.rs.ext.Provider; import org.apache.fineract.infrastructure.core.data.ApiParameterError; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; /** * An {@link ExceptionMapper} to map {@link MalformedJsonException} thrown by * platform into a HTTP API friendly format. */ @Provider @Component @Scope("singleton") public class MalformedJsonExceptionMapper implements ExceptionMapper<MalformedJsonException> { @Override public Response toResponse(@SuppressWarnings("unused") final MalformedJsonException exception) { final String globalisationMessageCode = "error.msg.invalid.request.body"; final String defaultUserMessage = "The JSON provided in the body of the request is invalid or missing."; final ApiParameterError error = ApiParameterError.generalError(globalisationMessageCode, defaultUserMessage); return Response.status(Status.BAD_REQUEST).entity(error).type(MediaType.APPLICATION_JSON).build(); } }
package virtualRobot.components; //com.qualcomm.robotcore.hardware.Servo;import com.qualcomm.robotcore.hardware.Servo; /** * Created by Alex on 9/30/2015. * The virtual servo component */ public class Servo { private volatile double position; public synchronized double getPosition() { double retVal = 0; synchronized (this) { retVal = position; } return retVal; } public synchronized void setPosition(double position) { position = Math.max (Math.min(position, 1), 0); synchronized (this) { this.position = position; } } }
package org.spongepowered.asm.lib; public abstract class ClassVisitor { protected final int api; protected ClassVisitor cv; public ClassVisitor(final int a1) { this(a1, null); } public ClassVisitor(final int a1, final ClassVisitor a2) { super(); if (a1 != 262144 && a1 != 327680) { throw new IllegalArgumentException(); } this.api = a1; this.cv = a2; } public void visit(final int a1, final int a2, final String a3, final String a4, final String a5, final String[] a6) { if (this.cv != null) { this.cv.visit(a1, a2, a3, a4, a5, a6); } } public void visitSource(final String a1, final String a2) { if (this.cv != null) { this.cv.visitSource(a1, a2); } } public void visitOuterClass(final String a1, final String a2, final String a3) { if (this.cv != null) { this.cv.visitOuterClass(a1, a2, a3); } } public AnnotationVisitor visitAnnotation(final String a1, final boolean a2) { if (this.cv != null) { return this.cv.visitAnnotation(a1, a2); } return null; } public AnnotationVisitor visitTypeAnnotation(final int a1, final TypePath a2, final String a3, final boolean a4) { if (this.api < 327680) { throw new RuntimeException(); } if (this.cv != null) { return this.cv.visitTypeAnnotation(a1, a2, a3, a4); } return null; } public void visitAttribute(final Attribute a1) { if (this.cv != null) { this.cv.visitAttribute(a1); } } public void visitInnerClass(final String a1, final String a2, final String a3, final int a4) { if (this.cv != null) { this.cv.visitInnerClass(a1, a2, a3, a4); } } public FieldVisitor visitField(final int a1, final String a2, final String a3, final String a4, final Object a5) { if (this.cv != null) { return this.cv.visitField(a1, a2, a3, a4, a5); } return null; } public MethodVisitor visitMethod(final int a1, final String a2, final String a3, final String a4, final String[] a5) { if (this.cv != null) { return this.cv.visitMethod(a1, a2, a3, a4, a5); } return null; } public void visitEnd() { if (this.cv != null) { this.cv.visitEnd(); } } }
package seedu.student; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Map; import java.util.Objects; import java.util.logging.Logger; import javafx.application.Application; import seedu.student.commons.core.LogsCenter; import seedu.student.commons.util.FileUtil; /** * Represents the parsed command-line parameters given to the application. */ public class AppParameters { private static final Logger logger = LogsCenter.getLogger(AppParameters.class); private Path configPath; public Path getConfigPath() { return configPath; } public void setConfigPath(Path configPath) { this.configPath = configPath; } /** * Parses the application command-line parameters. */ public static AppParameters parse(Application.Parameters parameters) { AppParameters appParameters = new AppParameters(); Map<String, String> namedParameters = parameters.getNamed(); String configPathParameter = namedParameters.get("config"); if (configPathParameter != null && !FileUtil.isValidPath(configPathParameter)) { logger.warning("Invalid config path " + configPathParameter + ". Using default config path."); configPathParameter = null; } appParameters.setConfigPath(configPathParameter != null ? Paths.get(configPathParameter) : null); return appParameters; } @Override public boolean equals(Object other) { if (other == this) { return true; } if (!(other instanceof AppParameters)) { return false; } AppParameters otherAppParameters = (AppParameters) other; return Objects.equals(getConfigPath(), otherAppParameters.getConfigPath()); } @Override public int hashCode() { return configPath.hashCode(); } }
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/* * 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. */ end_comment begin_package package|package name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|regionserver operator|. name|wal package|; end_package begin_import import|import static name|org operator|. name|junit operator|. name|Assert operator|. name|assertNull import|; end_import begin_import import|import static name|org operator|. name|mockito operator|. name|Mockito operator|. name|mock import|; end_import begin_import import|import static name|org operator|. name|mockito operator|. name|Mockito operator|. name|when import|; end_import begin_import import|import name|java operator|. name|io operator|. name|IOException import|; end_import begin_import import|import name|java operator|. name|io operator|. name|UncheckedIOException import|; end_import begin_import import|import name|java operator|. name|util operator|. name|List import|; end_import begin_import import|import name|java operator|. name|util operator|. name|NavigableMap import|; end_import begin_import import|import name|java operator|. name|util operator|. name|TreeMap import|; end_import begin_import import|import name|java operator|. name|util operator|. name|concurrent operator|. name|CompletableFuture import|; end_import begin_import import|import name|java operator|. name|util operator|. name|concurrent operator|. name|atomic operator|. name|AtomicInteger import|; end_import begin_import import|import name|java operator|. name|util operator|. name|concurrent operator|. name|atomic operator|. name|AtomicReference import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|conf operator|. name|Configuration import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|fs operator|. name|FileSystem import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|fs operator|. name|Path import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|HBaseClassTestRule import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|HConstants import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|KeyValue import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|TableName import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|client operator|. name|ColumnFamilyDescriptorBuilder import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|client operator|. name|RegionInfo import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|client operator|. name|RegionInfoBuilder import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|client operator|. name|TableDescriptor import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|client operator|. name|TableDescriptorBuilder import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|regionserver operator|. name|LogRoller import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|regionserver operator|. name|MultiVersionConcurrencyControl import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|regionserver operator|. name|RegionServerServices import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|regionserver operator|. name|SequenceId import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|testclassification operator|. name|LargeTests import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|testclassification operator|. name|RegionServerTests import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|util operator|. name|Bytes import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|util operator|. name|CommonFSUtils import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|util operator|. name|FutureUtils import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|util operator|. name|Threads import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|wal operator|. name|WALEdit import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|wal operator|. name|WALKey import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|wal operator|. name|WALKeyImpl import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|hbase operator|. name|wal operator|. name|WALProvider operator|. name|AsyncWriter import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|AfterClass import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|BeforeClass import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|ClassRule import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|Test import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|experimental operator|. name|categories operator|. name|Category import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hbase operator|. name|thirdparty operator|. name|io operator|. name|netty operator|. name|channel operator|. name|Channel import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hbase operator|. name|thirdparty operator|. name|io operator|. name|netty operator|. name|channel operator|. name|EventLoopGroup import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hbase operator|. name|thirdparty operator|. name|io operator|. name|netty operator|. name|channel operator|. name|nio operator|. name|NioEventLoopGroup import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hbase operator|. name|thirdparty operator|. name|io operator|. name|netty operator|. name|channel operator|. name|socket operator|. name|nio operator|. name|NioSocketChannel import|; end_import begin_comment comment|/** * Provides AsyncFSWAL test cases. */ end_comment begin_class annotation|@ name|Category argument_list|( block|{ name|RegionServerTests operator|. name|class block|, name|LargeTests operator|. name|class block|} argument_list|) specifier|public class|class name|TestAsyncFSWAL extends|extends name|AbstractTestFSWAL block|{ annotation|@ name|ClassRule specifier|public specifier|static specifier|final name|HBaseClassTestRule name|CLASS_RULE init|= name|HBaseClassTestRule operator|. name|forClass argument_list|( name|TestAsyncFSWAL operator|. name|class argument_list|) decl_stmt|; specifier|private specifier|static name|EventLoopGroup name|GROUP decl_stmt|; specifier|private specifier|static name|Class argument_list|< name|? extends|extends name|Channel argument_list|> name|CHANNEL_CLASS decl_stmt|; annotation|@ name|BeforeClass specifier|public specifier|static name|void name|setUpBeforeClass parameter_list|() throws|throws name|Exception block|{ name|GROUP operator|= operator|new name|NioEventLoopGroup argument_list|( literal|1 argument_list|, name|Threads operator|. name|newDaemonThreadFactory argument_list|( literal|"TestAsyncFSWAL" argument_list|) argument_list|) expr_stmt|; name|CHANNEL_CLASS operator|= name|NioSocketChannel operator|. name|class expr_stmt|; name|AbstractTestFSWAL operator|. name|setUpBeforeClass argument_list|() expr_stmt|; block|} annotation|@ name|AfterClass specifier|public specifier|static name|void name|tearDownAfterClass parameter_list|() throws|throws name|Exception block|{ name|AbstractTestFSWAL operator|. name|tearDownAfterClass argument_list|() expr_stmt|; name|GROUP operator|. name|shutdownGracefully argument_list|() expr_stmt|; block|} annotation|@ name|Override specifier|protected name|AbstractFSWAL argument_list|< name|? argument_list|> name|newWAL parameter_list|( name|FileSystem name|fs parameter_list|, name|Path name|rootDir parameter_list|, name|String name|logDir parameter_list|, name|String name|archiveDir parameter_list|, name|Configuration name|conf parameter_list|, name|List argument_list|< name|WALActionsListener argument_list|> name|listeners parameter_list|, name|boolean name|failIfWALExists parameter_list|, name|String name|prefix parameter_list|, name|String name|suffix parameter_list|) throws|throws name|IOException block|{ name|AsyncFSWAL name|wal init|= operator|new name|AsyncFSWAL argument_list|( name|fs argument_list|, name|rootDir argument_list|, name|logDir argument_list|, name|archiveDir argument_list|, name|conf argument_list|, name|listeners argument_list|, name|failIfWALExists argument_list|, name|prefix argument_list|, name|suffix argument_list|, name|GROUP argument_list|, name|CHANNEL_CLASS argument_list|) decl_stmt|; name|wal operator|. name|init argument_list|() expr_stmt|; return|return name|wal return|; block|} annotation|@ name|Override specifier|protected name|AbstractFSWAL argument_list|< name|? argument_list|> name|newSlowWAL parameter_list|( name|FileSystem name|fs parameter_list|, name|Path name|rootDir parameter_list|, name|String name|logDir parameter_list|, name|String name|archiveDir parameter_list|, name|Configuration name|conf parameter_list|, name|List argument_list|< name|WALActionsListener argument_list|> name|listeners parameter_list|, name|boolean name|failIfWALExists parameter_list|, name|String name|prefix parameter_list|, name|String name|suffix parameter_list|, specifier|final name|Runnable name|action parameter_list|) throws|throws name|IOException block|{ name|AsyncFSWAL name|wal init|= operator|new name|AsyncFSWAL argument_list|( name|fs argument_list|, name|rootDir argument_list|, name|logDir argument_list|, name|archiveDir argument_list|, name|conf argument_list|, name|listeners argument_list|, name|failIfWALExists argument_list|, name|prefix argument_list|, name|suffix argument_list|, name|GROUP argument_list|, name|CHANNEL_CLASS argument_list|) block|{ annotation|@ name|Override specifier|protected name|void name|atHeadOfRingBufferEventHandlerAppend parameter_list|() block|{ name|action operator|. name|run argument_list|() expr_stmt|; name|super operator|. name|atHeadOfRingBufferEventHandlerAppend argument_list|() expr_stmt|; block|} block|} decl_stmt|; name|wal operator|. name|init argument_list|() expr_stmt|; return|return name|wal return|; block|} annotation|@ name|Test specifier|public name|void name|testBrokenWriter parameter_list|() throws|throws name|Exception block|{ name|RegionServerServices name|services init|= name|mock argument_list|( name|RegionServerServices operator|. name|class argument_list|) decl_stmt|; name|when argument_list|( name|services operator|. name|getConfiguration argument_list|() argument_list|) operator|. name|thenReturn argument_list|( name|CONF argument_list|) expr_stmt|; name|TableDescriptor name|td init|= name|TableDescriptorBuilder operator|. name|newBuilder argument_list|( name|TableName operator|. name|valueOf argument_list|( literal|"table" argument_list|) argument_list|) operator|. name|setColumnFamily argument_list|( name|ColumnFamilyDescriptorBuilder operator|. name|of argument_list|( literal|"row" argument_list|) argument_list|) operator|. name|build argument_list|() decl_stmt|; name|RegionInfo name|ri init|= name|RegionInfoBuilder operator|. name|newBuilder argument_list|( name|td operator|. name|getTableName argument_list|() argument_list|) operator|. name|build argument_list|() decl_stmt|; name|MultiVersionConcurrencyControl name|mvcc init|= operator|new name|MultiVersionConcurrencyControl argument_list|() decl_stmt|; name|NavigableMap argument_list|< name|byte index|[] argument_list|, name|Integer argument_list|> name|scopes init|= operator|new name|TreeMap argument_list|<> argument_list|( name|Bytes operator|. name|BYTES_COMPARATOR argument_list|) decl_stmt|; for|for control|( name|byte index|[] name|fam range|: name|td operator|. name|getColumnFamilyNames argument_list|() control|) block|{ name|scopes operator|. name|put argument_list|( name|fam argument_list|, literal|0 argument_list|) expr_stmt|; block|} name|long name|timestamp init|= name|System operator|. name|currentTimeMillis argument_list|() decl_stmt|; name|String name|testName init|= name|currentTest operator|. name|getMethodName argument_list|() decl_stmt|; name|AtomicInteger name|failedCount init|= operator|new name|AtomicInteger argument_list|( literal|0 argument_list|) decl_stmt|; try|try init|( name|LogRoller name|roller init|= operator|new name|LogRoller argument_list|( name|services argument_list|) init|; name|AsyncFSWAL name|wal operator|= operator|new name|AsyncFSWAL argument_list|( name|FS argument_list|, name|CommonFSUtils operator|. name|getWALRootDir argument_list|( name|CONF argument_list|) argument_list|, name|DIR operator|. name|toString argument_list|() argument_list|, name|testName argument_list|, name|CONF argument_list|, literal|null argument_list|, literal|true argument_list|, literal|null argument_list|, literal|null argument_list|, name|GROUP argument_list|, name|CHANNEL_CLASS argument_list|) block|{ annotation|@ name|Override specifier|protected name|AsyncWriter name|createWriterInstance parameter_list|( name|Path name|path parameter_list|) throws|throws name|IOException block|{ name|AsyncWriter name|writer init|= name|super operator|. name|createWriterInstance argument_list|( name|path argument_list|) decl_stmt|; return|return operator|new name|AsyncWriter argument_list|() block|{ annotation|@ name|Override specifier|public name|void name|close parameter_list|() throws|throws name|IOException block|{ name|writer operator|. name|close argument_list|() expr_stmt|; block|} annotation|@ name|Override specifier|public name|long name|getLength parameter_list|() block|{ return|return name|writer operator|. name|getLength argument_list|() return|; block|} annotation|@ name|Override specifier|public name|CompletableFuture argument_list|< name|Long argument_list|> name|sync parameter_list|( name|boolean name|forceSync parameter_list|) block|{ name|CompletableFuture argument_list|< name|Long argument_list|> name|result init|= name|writer operator|. name|sync argument_list|( name|forceSync argument_list|) decl_stmt|; if|if condition|( name|failedCount operator|. name|incrementAndGet argument_list|() operator|< literal|1000 condition|) block|{ name|CompletableFuture argument_list|< name|Long argument_list|> name|future init|= operator|new name|CompletableFuture argument_list|<> argument_list|() decl_stmt|; name|FutureUtils operator|. name|addListener argument_list|( name|result argument_list|, parameter_list|( name|r parameter_list|, name|e parameter_list|) lambda|-> name|future operator|. name|completeExceptionally argument_list|( operator|new name|IOException argument_list|( literal|"Inject Error" argument_list|) argument_list|) argument_list|) expr_stmt|; return|return name|future return|; block|} else|else block|{ return|return name|result return|; block|} block|} annotation|@ name|Override specifier|public name|void name|append parameter_list|( name|Entry name|entry parameter_list|) block|{ name|writer operator|. name|append argument_list|( name|entry argument_list|) expr_stmt|; block|} block|} return|; block|} block|} init|) block|{ name|wal operator|. name|init argument_list|() expr_stmt|; name|roller operator|. name|addWAL argument_list|( name|wal argument_list|) expr_stmt|; name|roller operator|. name|start argument_list|() expr_stmt|; name|int name|numThreads init|= literal|10 decl_stmt|; name|AtomicReference argument_list|< name|Exception argument_list|> name|error init|= operator|new name|AtomicReference argument_list|<> argument_list|() decl_stmt|; name|Thread index|[] name|threads init|= operator|new name|Thread index|[ name|numThreads index|] decl_stmt|; for|for control|( name|int name|i init|= literal|0 init|; name|i operator|< literal|10 condition|; name|i operator|++ control|) block|{ specifier|final name|int name|index init|= name|i decl_stmt|; name|threads index|[ name|index index|] operator|= operator|new name|Thread argument_list|( literal|"Write-Thread-" operator|+ name|index argument_list|) block|{ annotation|@ name|Override specifier|public name|void name|run parameter_list|() block|{ name|byte index|[] name|row init|= name|Bytes operator|. name|toBytes argument_list|( literal|"row" operator|+ name|index argument_list|) decl_stmt|; name|WALEdit name|cols init|= operator|new name|WALEdit argument_list|() decl_stmt|; name|cols operator|. name|add argument_list|( operator|new name|KeyValue argument_list|( name|row argument_list|, name|row argument_list|, name|row argument_list|, name|timestamp operator|+ name|index argument_list|, name|row argument_list|) argument_list|) expr_stmt|; name|WALKeyImpl name|key init|= operator|new name|WALKeyImpl argument_list|( name|ri operator|. name|getEncodedNameAsBytes argument_list|() argument_list|, name|td operator|. name|getTableName argument_list|() argument_list|, name|SequenceId operator|. name|NO_SEQUENCE_ID argument_list|, name|timestamp argument_list|, name|WALKey operator|. name|EMPTY_UUIDS argument_list|, name|HConstants operator|. name|NO_NONCE argument_list|, name|HConstants operator|. name|NO_NONCE argument_list|, name|mvcc argument_list|, name|scopes argument_list|) decl_stmt|; try|try block|{ name|wal operator|. name|append argument_list|( name|ri argument_list|, name|key argument_list|, name|cols argument_list|, literal|true argument_list|) expr_stmt|; block|} catch|catch parameter_list|( name|IOException name|e parameter_list|) block|{ comment|// should not happen throw|throw operator|new name|UncheckedIOException argument_list|( name|e argument_list|) throw|; block|} try|try block|{ name|wal operator|. name|sync argument_list|() expr_stmt|; block|} catch|catch parameter_list|( name|IOException name|e parameter_list|) block|{ name|error operator|. name|set argument_list|( name|e argument_list|) expr_stmt|; block|} block|} block|} expr_stmt|; block|} for|for control|( name|Thread name|t range|: name|threads control|) block|{ name|t operator|. name|start argument_list|() expr_stmt|; block|} for|for control|( name|Thread name|t range|: name|threads control|) block|{ name|t operator|. name|join argument_list|() expr_stmt|; block|} name|assertNull argument_list|( name|error operator|. name|get argument_list|() argument_list|) expr_stmt|; block|} block|} block|} end_class end_unit
/* * Copyright (C) 2016 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 com.android.settings.development; import android.content.ComponentName; import android.content.Context; import android.content.pm.PackageManager; import android.provider.Settings; import android.os.UserManager; import android.support.v14.preference.SwitchPreference; import android.support.v7.preference.Preference; import android.support.v7.preference.PreferenceScreen; import com.android.settings.testutils.SettingsRobolectricTestRunner; import com.android.settings.TestConfig; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.robolectric.annotation.Config; import org.robolectric.shadows.ShadowApplication; import static com.google.common.truth.Truth.assertThat; import static org.mockito.Answers.RETURNS_DEEP_STUBS; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @RunWith(SettingsRobolectricTestRunner.class) @Config(manifest = TestConfig.MANIFEST_PATH, sdk = TestConfig.SDK_VERSION) public class BugReportInPowerPreferenceControllerTest { @Mock(answer = RETURNS_DEEP_STUBS) private PreferenceScreen mScreen; @Mock private UserManager mUserManager; @Mock private PackageManager mPackageManager; private Context mContext; private SwitchPreference mPreference; private BugReportInPowerPreferenceController mController; @Before public void setUp() { MockitoAnnotations.initMocks(this); ShadowApplication shadowContext = ShadowApplication.getInstance(); shadowContext.setSystemService(Context.USER_SERVICE, mUserManager); mContext = spy(shadowContext.getApplicationContext()); when(mContext.getPackageManager()).thenReturn(mPackageManager); mPreference = new SwitchPreference(mContext); when(mScreen.findPreference(anyString())).thenReturn(mPreference); mController = new BugReportInPowerPreferenceController(mContext); mPreference.setKey(mController.getPreferenceKey()); } @Test public void displayPreference_hasDebugRestriction_shouldRemovePreference() { when(mUserManager.hasUserRestriction(anyString())).thenReturn(true); when(mScreen.getPreferenceCount()).thenReturn(1); when(mScreen.getPreference(0)).thenReturn(mPreference); mController.displayPreference(mScreen); verify(mScreen).removePreference(any(Preference.class)); } @Test public void displayPreference_noDebugRestriction_shouldNotRemovePreference() { when(mUserManager.hasUserRestriction(anyString())).thenReturn(false); mController.displayPreference(mScreen); verify(mScreen, never()).removePreference(any(Preference.class)); } @Test public void enablePreference_hasDebugRestriction_shouldNotEnable() { when(mUserManager.hasUserRestriction(anyString())).thenReturn(true); mController.displayPreference(mScreen); mPreference.setEnabled(false); mController.enablePreference(true); assertThat(mPreference.isEnabled()).isFalse(); } @Test public void enablePreference_noDebugRestriction_shouldEnable() { when(mUserManager.hasUserRestriction(anyString())).thenReturn(false); mController.displayPreference(mScreen); mPreference.setEnabled(false); mController.enablePreference(true); assertThat(mPreference.isEnabled()).isTrue(); } @Test public void resetPreference_shouldUncheck() { when(mUserManager.hasUserRestriction(anyString())).thenReturn(false); mController.displayPreference(mScreen); mPreference.setChecked(true); mController.resetPreference(); assertThat(mPreference.isChecked()).isFalse(); } @Test public void handlePreferenceTreeClick_shouldUpdateSettings() { when(mUserManager.hasUserRestriction(anyString())).thenReturn(false); Settings.Secure.putInt(mContext.getContentResolver(), Settings.Global.BUGREPORT_IN_POWER_MENU, 0); mPreference.setChecked(true); mController.displayPreference(mScreen); mController.handlePreferenceTreeClick(mPreference); assertThat(Settings.Secure.getInt(mContext.getContentResolver(), Settings.Global.BUGREPORT_IN_POWER_MENU, 0)).isEqualTo(1); } @Test public void updateState_settingsOn_shouldCheck() { when(mUserManager.hasUserRestriction(anyString())).thenReturn(false); Settings.Secure.putInt(mContext.getContentResolver(), Settings.Global.BUGREPORT_IN_POWER_MENU, 1); mPreference.setChecked(false); mController.displayPreference(mScreen); mController.updateState(mPreference); assertThat(mPreference.isChecked()).isTrue(); } @Test public void updateState_settingsOff_shouldUncheck() { when(mUserManager.hasUserRestriction(anyString())).thenReturn(false); Settings.Secure.putInt(mContext.getContentResolver(), Settings.Global.BUGREPORT_IN_POWER_MENU, 0); mPreference.setChecked(true); mController.displayPreference(mScreen); mController.updateState(mPreference); assertThat(mPreference.isChecked()).isFalse(); } @Test public void updateBugreportOptions_shouldEnable() { when(mUserManager.hasUserRestriction(anyString())).thenReturn(false); mPreference.setEnabled(false); mController.displayPreference(mScreen); mController.updateBugreportOptions(); assertThat(mPreference.isEnabled()).isTrue(); } @Test public void updateBugreportOptions_shouldEnableBugReportStorage() { final ComponentName componentName = new ComponentName("com.android.shell", "com.android.shell.BugreportStorageProvider"); when(mUserManager.hasUserRestriction(anyString())).thenReturn(false); mController.displayPreference(mScreen); mController.updateBugreportOptions(); verify(mPackageManager).setComponentEnabledSetting(eq(componentName), anyInt(), anyInt()); } }
/* * */ package fuzzyAutomaton.diagram.edit.policies; import org.eclipse.emf.ecore.EAnnotation; import org.eclipse.gef.commands.Command; import org.eclipse.gmf.runtime.diagram.core.commands.DeleteCommand; import org.eclipse.gmf.runtime.emf.commands.core.command.CompositeTransactionalCommand; import org.eclipse.gmf.runtime.emf.type.core.commands.DestroyElementCommand; import org.eclipse.gmf.runtime.emf.type.core.requests.DestroyElementRequest; import org.eclipse.gmf.runtime.notation.View; /** * @generated */ public class OutputItemSemanticEditPolicy extends fuzzyAutomaton.diagram.edit.policies.FuzzyAutomatonBaseItemSemanticEditPolicy { /** * @generated */ public OutputItemSemanticEditPolicy() { super(fuzzyAutomaton.diagram.providers.FuzzyAutomatonElementTypes.Output_3003); } /** * @generated */ protected Command getDestroyElementCommand(DestroyElementRequest req) { View view = (View) getHost().getModel(); CompositeTransactionalCommand cmd = new CompositeTransactionalCommand(getEditingDomain(), null); cmd.setTransactionNestingEnabled(false); EAnnotation annotation = view.getEAnnotation("Shortcut"); //$NON-NLS-1$ if (annotation == null) { // there are indirectly referenced children, need extra commands: false addDestroyShortcutsCommand(cmd, view); // delete host element cmd.add(new DestroyElementCommand(req)); } else { cmd.add(new DeleteCommand(getEditingDomain(), view)); } return getGEFWrapper(cmd.reduce()); } }
/* * Copyright (c) 2019-2020 GeyserMC. http://geysermc.org * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * @author GeyserMC * @link https://github.com/GeyserMC/GeyserConnect */ package org.geysermc.connect.utils; import com.nukkitx.math.vector.Vector2f; import com.nukkitx.math.vector.Vector3f; import com.nukkitx.math.vector.Vector3i; import com.nukkitx.protocol.bedrock.BedrockServerSession; import com.nukkitx.protocol.bedrock.data.*; import com.nukkitx.protocol.bedrock.packet.*; import it.unimi.dsi.fastutil.longs.Long2ObjectMap; import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; import lombok.Getter; import lombok.Setter; import org.geysermc.connect.GeyserConnect; import org.geysermc.connect.MasterServer; import org.geysermc.connect.proxy.GeyserProxySession; import org.geysermc.connect.ui.FormID; import org.geysermc.connect.ui.UIHandler; import org.geysermc.connector.GeyserConnector; import org.geysermc.connector.common.AuthType; import org.geysermc.connector.network.UpstreamPacketHandler; import org.geysermc.connector.network.session.auth.AuthData; import org.geysermc.connector.network.session.auth.BedrockClientData; import org.geysermc.connector.registry.BlockRegistries; import org.geysermc.connector.registry.Registries; import org.geysermc.connector.registry.type.ItemMappings; import org.geysermc.connector.utils.DimensionUtils; import org.geysermc.cumulus.Form; import java.util.ArrayList; import java.util.List; @Getter public class Player { private final AuthData authData; private final BedrockServerSession session; private final List<Server> servers = new ArrayList<>(); private final Long2ObjectMap<ModalFormRequestPacket> forms = new Long2ObjectOpenHashMap<>(); private Form currentWindow; private FormID currentWindowId; @Setter private Server currentServer; @Setter private BedrockClientData clientData; @Setter private ServerCategory serverCategory; public Player(AuthData authData, BedrockServerSession session) { this.authData = authData; this.session = session; // Should fetch the servers from some form of db if (MasterServer.getInstance().getGeyserConnectConfig().getCustomServers().isEnabled()) { servers.addAll(MasterServer.getInstance().getStorageManager().loadServers(this)); } } /** * Send a few different packets to get the client to load in */ public void sendStartGame() { ItemMappings itemMappings = Registries.ITEMS.forVersion(session.getPacketCodec().getProtocolVersion()); // A lot of this likely doesn't need to be changed StartGamePacket startGamePacket = new StartGamePacket(); startGamePacket.setUniqueEntityId(1); startGamePacket.setRuntimeEntityId(1); startGamePacket.setPlayerGameType(GameType.CREATIVE); startGamePacket.setPlayerPosition(Vector3f.from(0, 64 + 2, 0)); startGamePacket.setRotation(Vector2f.ONE); startGamePacket.setSeed(-1); startGamePacket.setDimensionId(2); startGamePacket.setGeneratorId(1); startGamePacket.setLevelGameType(GameType.CREATIVE); startGamePacket.setDifficulty(0); startGamePacket.setDefaultSpawn(Vector3i.ZERO); startGamePacket.setAchievementsDisabled(true); startGamePacket.setCurrentTick(-1); startGamePacket.setEduEditionOffers(0); startGamePacket.setEduFeaturesEnabled(false); startGamePacket.setRainLevel(0); startGamePacket.setLightningLevel(0); startGamePacket.setMultiplayerGame(true); startGamePacket.setBroadcastingToLan(true); startGamePacket.getGamerules().add(new GameRuleData<>("showcoordinates", true)); startGamePacket.setPlatformBroadcastMode(GamePublishSetting.PUBLIC); startGamePacket.setXblBroadcastMode(GamePublishSetting.PUBLIC); startGamePacket.setCommandsEnabled(true); startGamePacket.setTexturePacksRequired(false); startGamePacket.setBonusChestEnabled(false); startGamePacket.setStartingWithMap(false); startGamePacket.setTrustingPlayers(true); startGamePacket.setDefaultPlayerPermission(PlayerPermission.VISITOR); startGamePacket.setServerChunkTickRange(4); startGamePacket.setBehaviorPackLocked(false); startGamePacket.setResourcePackLocked(false); startGamePacket.setFromLockedWorldTemplate(false); startGamePacket.setUsingMsaGamertagsOnly(false); startGamePacket.setFromWorldTemplate(false); startGamePacket.setWorldTemplateOptionLocked(false); startGamePacket.setLevelId(""); startGamePacket.setLevelName("GeyserConnect"); startGamePacket.setPremiumWorldTemplateId(""); startGamePacket.setCurrentTick(0); startGamePacket.setEnchantmentSeed(0); startGamePacket.setMultiplayerCorrelationId(""); startGamePacket.setItemEntries(itemMappings.getItemEntries()); startGamePacket.setInventoriesServerAuthoritative(true); startGamePacket.setServerEngine(""); SyncedPlayerMovementSettings settings = new SyncedPlayerMovementSettings(); settings.setMovementMode(AuthoritativeMovementMode.CLIENT); settings.setRewindHistorySize(0); settings.setServerAuthoritativeBlockBreaking(false); startGamePacket.setPlayerMovementSettings(settings); startGamePacket.setVanillaVersion("*"); session.sendPacket(startGamePacket); if (itemMappings.getFurnaceMinecartData() != null) { ItemComponentPacket itemComponentPacket = new ItemComponentPacket(); itemComponentPacket.getItems().add(itemMappings.getFurnaceMinecartData()); session.sendPacket(itemComponentPacket); } // Send an empty chunk LevelChunkPacket data = new LevelChunkPacket(); data.setChunkX(0); data.setChunkZ(0); data.setSubChunksLength(0); data.setData(PaletteManger.EMPTY_LEVEL_CHUNK_DATA); data.setCachingEnabled(false); session.sendPacket(data); // Send the biomes BiomeDefinitionListPacket biomeDefinitionListPacket = new BiomeDefinitionListPacket(); biomeDefinitionListPacket.setDefinitions(Registries.BIOMES_NBT.get()); session.sendPacket(biomeDefinitionListPacket); AvailableEntityIdentifiersPacket entityPacket = new AvailableEntityIdentifiersPacket(); entityPacket.setIdentifiers(Registries.ENTITY_IDENTIFIERS.get()); session.sendPacket(entityPacket); // Send a CreativeContentPacket - required for 1.16.100 CreativeContentPacket creativeContentPacket = new CreativeContentPacket(); creativeContentPacket.setContents(itemMappings.getCreativeItems()); session.sendPacket(creativeContentPacket); // Let the client know the player can spawn PlayStatusPacket playStatusPacket = new PlayStatusPacket(); playStatusPacket.setStatus(PlayStatusPacket.Status.PLAYER_SPAWN); session.sendPacket(playStatusPacket); // Freeze the player SetEntityMotionPacket setEntityMotionPacket = new SetEntityMotionPacket(); setEntityMotionPacket.setRuntimeEntityId(1); setEntityMotionPacket.setMotion(Vector3f.ZERO); session.sendPacket(setEntityMotionPacket); } /** * Send a window with the specified id and content * Also cache it against the player for later use * * @param id The {@link FormID} to use for the form * @param window The {@link Form} to turn into json and send */ public void sendWindow(FormID id, Form window) { this.currentWindow = window; this.currentWindowId = id; ModalFormRequestPacket modalFormRequestPacket = new ModalFormRequestPacket(); modalFormRequestPacket.setFormId(id.ordinal()); modalFormRequestPacket.setFormData(window.getJsonData()); session.sendPacket(modalFormRequestPacket); // This packet is used to fix the image loading bug NetworkStackLatencyPacket networkStackLatencyPacket = new NetworkStackLatencyPacket(); networkStackLatencyPacket.setFromServer(true); networkStackLatencyPacket.setTimestamp(System.currentTimeMillis()); session.sendPacket(networkStackLatencyPacket); } public void resendWindow() { sendWindow(currentWindowId, currentWindow); } /** * Send the player to the Geyser proxy server or straight to the bedrock server if it is */ public void connectToProxy() { if (currentServer.isBedrock()) { TransferPacket transferPacket = new TransferPacket(); transferPacket.setAddress(currentServer.getAddress()); transferPacket.setPort(currentServer.getPort()); session.sendPacket(transferPacket); } else { GeyserProxySession geyserSession = new GeyserProxySession(GeyserConnector.getInstance(), session, MasterServer.getInstance().getEventLoopGroup().next()); session.setPacketHandler(new UpstreamPacketHandler(GeyserConnector.getInstance(), geyserSession)); geyserSession.getUpstream().getSession().setPacketCodec(session.getPacketCodec()); // Set the block translation based off of version geyserSession.setBlockMappings(BlockRegistries.BLOCKS.forVersion(session.getPacketCodec().getProtocolVersion())); geyserSession.setItemMappings(Registries.ITEMS.forVersion(session.getPacketCodec().getProtocolVersion())); geyserSession.setAuthData(authData); geyserSession.setClientData(clientData); geyserSession.setDimension(DimensionUtils.THE_END); geyserSession.setRemoteAddress(currentServer.getAddress()); geyserSession.setRemotePort(currentServer.getPort()); geyserSession.setRemoteAuthType(currentServer.isOnline() ? AuthType.ONLINE : AuthType.OFFLINE); // Tell Geyser to handle the login SetLocalPlayerAsInitializedPacket initializedPacket = new SetLocalPlayerAsInitializedPacket(); initializedPacket.setRuntimeEntityId(geyserSession.getPlayerEntity().getGeyserId()); session.getPacketHandler().handle(initializedPacket); } } public void sendToServer(Server server) { // Tell the user we are connecting them // This wont show up in a lot of cases as the client connects quite quickly if (!server.isOnline()) { sendWindow(FormID.CONNECTING, UIHandler.getWaitingScreen(server)); } // Send the user over to the server setCurrentServer(server); connectToProxy(); } public List<Server> getCurrentServers() { if (serverCategory == ServerCategory.CUSTOM) { return servers; } return MasterServer.getInstance().getServers(serverCategory); } }
/* * Copyright (c) 2019 Masafumi Fujimaru * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.github.jhorology.bitwig.ext.impl; import com.bitwig.extension.callback.ObjectValueChangedCallback; import com.github.jhorology.bitwig.ext.IdValuePair; import com.github.jhorology.bitwig.ext.api.ObservedDirectParameterValue; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * An implementation of Value that reports observed direct parameter. * @param <T> type of raw value. */ public class ObservedDirectParameterValueImpl<T> implements ObservedDirectParameterValue<T> { private final Map<String, IdValuePair<String, T>> paramsCache; private List<String> observedIds; private final List<ObjectValueChangedCallback<IdValuePair<String, T>>> callbacks; private int subscribeCount; private final boolean notifyValuesOnSetIds; /** * Constructor. * @param name */ ObservedDirectParameterValueImpl(boolean notifyValuesOnSetIds) { this.paramsCache = new LinkedHashMap<>(); this.callbacks = new ArrayList<>(); this.notifyValuesOnSetIds = notifyValuesOnSetIds; this.observedIds = Collections.emptyList(); } /** * {@inheritDoc} */ @Override public void setObservedIds(String[] ids) { this.observedIds = ids != null ? Arrays.asList(ids) : Collections.emptyList(); if (isSubscribed() && notifyValuesOnSetIds) { notifyValues(); } } /** * {@inheritDoc} */ @Override public T get(String id) { IdValuePair<String, T> v = paramsCache.get(id); return v != null ? v.getValue() : null; } /** * {@inheritDoc} */ @Override public List<IdValuePair<String, T>> values() { return observedIds .stream() .map(paramsCache::get) .collect(Collectors.toList()); } /** * {@inheritDoc} */ @Override public void markInterested() { subscribe(); } /** * {@inheritDoc} */ @Override public boolean isSubscribed() { return subscribeCount > 0; } /** * {@inheritDoc} */ @Override @Deprecated public void setIsSubscribed(boolean subscribed) {} /** * {@inheritDoc} */ @Override public void subscribe() { subscribeCount++; } /** * {@inheritDoc} */ @Override public void unsubscribe() { if (subscribeCount > 0) { subscribeCount--; } } /** * {@inheritDoc} */ @Override public void addValueObserver( ObjectValueChangedCallback<IdValuePair<String, T>> callback ) { callbacks.add(callback); } /** * Notify observed device is changed */ void deviceChanged() { paramsCache.clear(); } /** * Notify observed values to observers. */ void notifyValues() { values().forEach(this::valueChanged); } /** * put or update direct parameter value. * @param id * @param value */ void put(String id, T value) { IdValuePair<String, T> v = paramsCache.get(id); if (v != null) { v.setValue(value); } else { v = new IdValuePair<>(id, value); paramsCache.put(id, v); } if (isSubscribed() && observedIds.contains(id)) { valueChanged(v); } } private void valueChanged(IdValuePair<String, T> v) { callbacks.forEach(cb -> cb.valueChanged(v)); } }
package com.atguigu.gulimall.product; import com.atguigu.gulimall.product.entity.BrandEntity; import com.atguigu.gulimall.product.service.BrandService; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import javax.annotation.Resource; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.util.List; @SpringBootTest class GulimallProductApplicationTests { @Autowired BrandService brandService; @Test void contextLoads() { // BrandEntity brandEntity = new BrandEntity(); // brandEntity.setBrandId(1L); // brandEntity.setDescript("华为"); // brandEntity.setName("华为"); // 添加 // brandService.save(brandEntity); // System.out.println("保存成功..."); // 修改 // brandService.updateById(brandEntity); // 查询 // BrandEntity byId = brandService.getById(1); // System.out.println(byId); List<BrandEntity> list = brandService.list(new QueryWrapper<BrandEntity>().eq("brand_id", 1L)); list.forEach(System.out::println); } }
/* * Copyright (C) 2016-2022 Objectos Software LTDA. * * 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 br.com.objectos.css.parser.select; import br.com.objectos.core.object.ToString; import br.com.objectos.core.string.Strings; import br.com.objectos.css.Css; import br.com.objectos.css.select.AttributeSelector; import br.com.objectos.css.select.AttributeValueOperator; import br.com.objectos.css.select.AttributeValueSelector; import br.com.objectos.css.select.ClassSelector; import br.com.objectos.css.select.IdSelector; import br.com.objectos.css.select.SelectorFactory; import br.com.objectos.css.select.TypeSelector; import br.com.objectos.css.select.TypeSelectors; class IdentToken implements HasStringValue { private final String value; IdentToken(String first, String rest) { this(first + Strings.nullToEmpty(rest)); } private IdentToken(String value) { this.value = value; } // @VisibleForTesting static IdentToken of(String value) { return new IdentToken(value); } public final AttributeSelector asAttributeSelector() { return Css.attr(value); } public final AttributeValueSelector asAttributeValueSelector( AttributeValueOperator operator, HasStringValue theValue) { return SelectorFactory.attr(value, operator, theValue.stringValue()); } public final ClassSelector asClassSelector() { return Css.cn(value); } public final IdSelector asIdSelector() { return Css.id(value); } public final TypeSelector asTypeSelector() { return TypeSelectors.getByName(value); } @Override public final boolean equals(Object obj) { if (!(obj instanceof IdentToken)) { return false; } IdentToken that = (IdentToken) obj; return value.equals(that.value); } @Override public final int hashCode() { return value.hashCode(); } @Override public final String stringValue() { return value; } @Override public final String toString() { return ToString.toString(this, "", value); } }
/* * Copyright 2016-2021 Amazon.com, Inc. or its affiliates. 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://aws.amazon.com/apache2.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.amazonaws.services.machinelearning.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <p> * Describes the real-time endpoint information for an <code>MLModel</code>. * </p> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class RealtimeEndpointInfo implements Serializable, Cloneable, StructuredPojo { /** * <p> * The maximum processing rate for the real-time endpoint for <code>MLModel</code>, measured in incoming requests * per second. * </p> */ private Integer peakRequestsPerSecond; /** * <p> * The time that the request to create the real-time endpoint for the <code>MLModel</code> was received. The time is * expressed in epoch time. * </p> */ private java.util.Date createdAt; /** * <p> * The URI that specifies where to send real-time prediction requests for the <code>MLModel</code>. * </p> * <note><title>Note</title> * <p> * The application must wait until the real-time endpoint is ready before using this URI. * </p> * </note> */ private String endpointUrl; /** * <p> * The current status of the real-time endpoint for the <code>MLModel</code>. This element can have one of the * following values: * </p> * <ul> * <li> <code>NONE</code> - Endpoint does not exist or was previously deleted.</li> * <li> <code>READY</code> - Endpoint is ready to be used for real-time predictions.</li> * <li> <code>UPDATING</code> - Updating/creating the endpoint.</li> * </ul> */ private String endpointStatus; /** * <p> * The maximum processing rate for the real-time endpoint for <code>MLModel</code>, measured in incoming requests * per second. * </p> * * @param peakRequestsPerSecond * The maximum processing rate for the real-time endpoint for <code>MLModel</code>, measured in incoming * requests per second. */ public void setPeakRequestsPerSecond(Integer peakRequestsPerSecond) { this.peakRequestsPerSecond = peakRequestsPerSecond; } /** * <p> * The maximum processing rate for the real-time endpoint for <code>MLModel</code>, measured in incoming requests * per second. * </p> * * @return The maximum processing rate for the real-time endpoint for <code>MLModel</code>, measured in incoming * requests per second. */ public Integer getPeakRequestsPerSecond() { return this.peakRequestsPerSecond; } /** * <p> * The maximum processing rate for the real-time endpoint for <code>MLModel</code>, measured in incoming requests * per second. * </p> * * @param peakRequestsPerSecond * The maximum processing rate for the real-time endpoint for <code>MLModel</code>, measured in incoming * requests per second. * @return Returns a reference to this object so that method calls can be chained together. */ public RealtimeEndpointInfo withPeakRequestsPerSecond(Integer peakRequestsPerSecond) { setPeakRequestsPerSecond(peakRequestsPerSecond); return this; } /** * <p> * The time that the request to create the real-time endpoint for the <code>MLModel</code> was received. The time is * expressed in epoch time. * </p> * * @param createdAt * The time that the request to create the real-time endpoint for the <code>MLModel</code> was received. The * time is expressed in epoch time. */ public void setCreatedAt(java.util.Date createdAt) { this.createdAt = createdAt; } /** * <p> * The time that the request to create the real-time endpoint for the <code>MLModel</code> was received. The time is * expressed in epoch time. * </p> * * @return The time that the request to create the real-time endpoint for the <code>MLModel</code> was received. The * time is expressed in epoch time. */ public java.util.Date getCreatedAt() { return this.createdAt; } /** * <p> * The time that the request to create the real-time endpoint for the <code>MLModel</code> was received. The time is * expressed in epoch time. * </p> * * @param createdAt * The time that the request to create the real-time endpoint for the <code>MLModel</code> was received. The * time is expressed in epoch time. * @return Returns a reference to this object so that method calls can be chained together. */ public RealtimeEndpointInfo withCreatedAt(java.util.Date createdAt) { setCreatedAt(createdAt); return this; } /** * <p> * The URI that specifies where to send real-time prediction requests for the <code>MLModel</code>. * </p> * <note><title>Note</title> * <p> * The application must wait until the real-time endpoint is ready before using this URI. * </p> * </note> * * @param endpointUrl * The URI that specifies where to send real-time prediction requests for the <code>MLModel</code>.</p> * <note><title>Note</title> * <p> * The application must wait until the real-time endpoint is ready before using this URI. * </p> */ public void setEndpointUrl(String endpointUrl) { this.endpointUrl = endpointUrl; } /** * <p> * The URI that specifies where to send real-time prediction requests for the <code>MLModel</code>. * </p> * <note><title>Note</title> * <p> * The application must wait until the real-time endpoint is ready before using this URI. * </p> * </note> * * @return The URI that specifies where to send real-time prediction requests for the <code>MLModel</code>.</p> * <note><title>Note</title> * <p> * The application must wait until the real-time endpoint is ready before using this URI. * </p> */ public String getEndpointUrl() { return this.endpointUrl; } /** * <p> * The URI that specifies where to send real-time prediction requests for the <code>MLModel</code>. * </p> * <note><title>Note</title> * <p> * The application must wait until the real-time endpoint is ready before using this URI. * </p> * </note> * * @param endpointUrl * The URI that specifies where to send real-time prediction requests for the <code>MLModel</code>.</p> * <note><title>Note</title> * <p> * The application must wait until the real-time endpoint is ready before using this URI. * </p> * @return Returns a reference to this object so that method calls can be chained together. */ public RealtimeEndpointInfo withEndpointUrl(String endpointUrl) { setEndpointUrl(endpointUrl); return this; } /** * <p> * The current status of the real-time endpoint for the <code>MLModel</code>. This element can have one of the * following values: * </p> * <ul> * <li> <code>NONE</code> - Endpoint does not exist or was previously deleted.</li> * <li> <code>READY</code> - Endpoint is ready to be used for real-time predictions.</li> * <li> <code>UPDATING</code> - Updating/creating the endpoint.</li> * </ul> * * @param endpointStatus * The current status of the real-time endpoint for the <code>MLModel</code>. This element can have one of * the following values: </p> * <ul> * <li> <code>NONE</code> - Endpoint does not exist or was previously deleted.</li> * <li> <code>READY</code> - Endpoint is ready to be used for real-time predictions.</li> * <li> <code>UPDATING</code> - Updating/creating the endpoint.</li> * @see RealtimeEndpointStatus */ public void setEndpointStatus(String endpointStatus) { this.endpointStatus = endpointStatus; } /** * <p> * The current status of the real-time endpoint for the <code>MLModel</code>. This element can have one of the * following values: * </p> * <ul> * <li> <code>NONE</code> - Endpoint does not exist or was previously deleted.</li> * <li> <code>READY</code> - Endpoint is ready to be used for real-time predictions.</li> * <li> <code>UPDATING</code> - Updating/creating the endpoint.</li> * </ul> * * @return The current status of the real-time endpoint for the <code>MLModel</code>. This element can have one of * the following values: </p> * <ul> * <li> <code>NONE</code> - Endpoint does not exist or was previously deleted.</li> * <li> <code>READY</code> - Endpoint is ready to be used for real-time predictions.</li> * <li> <code>UPDATING</code> - Updating/creating the endpoint.</li> * @see RealtimeEndpointStatus */ public String getEndpointStatus() { return this.endpointStatus; } /** * <p> * The current status of the real-time endpoint for the <code>MLModel</code>. This element can have one of the * following values: * </p> * <ul> * <li> <code>NONE</code> - Endpoint does not exist or was previously deleted.</li> * <li> <code>READY</code> - Endpoint is ready to be used for real-time predictions.</li> * <li> <code>UPDATING</code> - Updating/creating the endpoint.</li> * </ul> * * @param endpointStatus * The current status of the real-time endpoint for the <code>MLModel</code>. This element can have one of * the following values: </p> * <ul> * <li> <code>NONE</code> - Endpoint does not exist or was previously deleted.</li> * <li> <code>READY</code> - Endpoint is ready to be used for real-time predictions.</li> * <li> <code>UPDATING</code> - Updating/creating the endpoint.</li> * @return Returns a reference to this object so that method calls can be chained together. * @see RealtimeEndpointStatus */ public RealtimeEndpointInfo withEndpointStatus(String endpointStatus) { setEndpointStatus(endpointStatus); return this; } /** * <p> * The current status of the real-time endpoint for the <code>MLModel</code>. This element can have one of the * following values: * </p> * <ul> * <li> <code>NONE</code> - Endpoint does not exist or was previously deleted.</li> * <li> <code>READY</code> - Endpoint is ready to be used for real-time predictions.</li> * <li> <code>UPDATING</code> - Updating/creating the endpoint.</li> * </ul> * * @param endpointStatus * The current status of the real-time endpoint for the <code>MLModel</code>. This element can have one of * the following values: </p> * <ul> * <li> <code>NONE</code> - Endpoint does not exist or was previously deleted.</li> * <li> <code>READY</code> - Endpoint is ready to be used for real-time predictions.</li> * <li> <code>UPDATING</code> - Updating/creating the endpoint.</li> * @see RealtimeEndpointStatus */ public void setEndpointStatus(RealtimeEndpointStatus endpointStatus) { withEndpointStatus(endpointStatus); } /** * <p> * The current status of the real-time endpoint for the <code>MLModel</code>. This element can have one of the * following values: * </p> * <ul> * <li> <code>NONE</code> - Endpoint does not exist or was previously deleted.</li> * <li> <code>READY</code> - Endpoint is ready to be used for real-time predictions.</li> * <li> <code>UPDATING</code> - Updating/creating the endpoint.</li> * </ul> * * @param endpointStatus * The current status of the real-time endpoint for the <code>MLModel</code>. This element can have one of * the following values: </p> * <ul> * <li> <code>NONE</code> - Endpoint does not exist or was previously deleted.</li> * <li> <code>READY</code> - Endpoint is ready to be used for real-time predictions.</li> * <li> <code>UPDATING</code> - Updating/creating the endpoint.</li> * @return Returns a reference to this object so that method calls can be chained together. * @see RealtimeEndpointStatus */ public RealtimeEndpointInfo withEndpointStatus(RealtimeEndpointStatus endpointStatus) { this.endpointStatus = endpointStatus.toString(); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getPeakRequestsPerSecond() != null) sb.append("PeakRequestsPerSecond: ").append(getPeakRequestsPerSecond()).append(","); if (getCreatedAt() != null) sb.append("CreatedAt: ").append(getCreatedAt()).append(","); if (getEndpointUrl() != null) sb.append("EndpointUrl: ").append(getEndpointUrl()).append(","); if (getEndpointStatus() != null) sb.append("EndpointStatus: ").append(getEndpointStatus()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof RealtimeEndpointInfo == false) return false; RealtimeEndpointInfo other = (RealtimeEndpointInfo) obj; if (other.getPeakRequestsPerSecond() == null ^ this.getPeakRequestsPerSecond() == null) return false; if (other.getPeakRequestsPerSecond() != null && other.getPeakRequestsPerSecond().equals(this.getPeakRequestsPerSecond()) == false) return false; if (other.getCreatedAt() == null ^ this.getCreatedAt() == null) return false; if (other.getCreatedAt() != null && other.getCreatedAt().equals(this.getCreatedAt()) == false) return false; if (other.getEndpointUrl() == null ^ this.getEndpointUrl() == null) return false; if (other.getEndpointUrl() != null && other.getEndpointUrl().equals(this.getEndpointUrl()) == false) return false; if (other.getEndpointStatus() == null ^ this.getEndpointStatus() == null) return false; if (other.getEndpointStatus() != null && other.getEndpointStatus().equals(this.getEndpointStatus()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getPeakRequestsPerSecond() == null) ? 0 : getPeakRequestsPerSecond().hashCode()); hashCode = prime * hashCode + ((getCreatedAt() == null) ? 0 : getCreatedAt().hashCode()); hashCode = prime * hashCode + ((getEndpointUrl() == null) ? 0 : getEndpointUrl().hashCode()); hashCode = prime * hashCode + ((getEndpointStatus() == null) ? 0 : getEndpointStatus().hashCode()); return hashCode; } @Override public RealtimeEndpointInfo clone() { try { return (RealtimeEndpointInfo) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.machinelearning.model.transform.RealtimeEndpointInfoMarshaller.getInstance().marshall(this, protocolMarshaller); } }
/* * Copyright 2008-2009 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 net.hasor.core.spi; import java.util.EventListener; import java.util.List; /** * SPI 仲裁器:当同一个 SPI bind 了多个 SpiListener 就可以利用仲裁处理更多需求。 * - notify 方式下,仲裁帮助决定哪些 SPI 可以被调用。同时可以决定那个 SPI 的返回值被最终采用。 * - chain 方式下,仲裁帮助决定哪些 SPI 可以被调用,和 SPI 的调用顺序。 * @version : 2020-04-19 * @author 赵永春 (zyc@hasor.net) */ public interface SpiJudge { /** 默认裁决:1.所有 SPI 监听器,全部执行;2.结果只取最后一个。*/ public final static SpiJudge DEFAULT = new SpiJudge() { }; /** 调用仲裁 */ public default <T extends EventListener> List<T> judgeSpi(List<T> spiList) { return spiList; } /** 结果仲裁 */ public default <R> R judgeResult(List<R> result, R defaultResult) { return (result == null || result.isEmpty()) ? defaultResult : result.get(result.size() - 1); } }
/* * 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.flink.runtime.dispatcher.runner; import org.apache.flink.util.Preconditions; import java.util.ArrayDeque; import java.util.Arrays; import java.util.Queue; import java.util.UUID; class TestingDispatcherLeaderProcessFactory implements DispatcherLeaderProcessFactory { private final Queue<TestingDispatcherLeaderProcess> processes; private TestingDispatcherLeaderProcessFactory(Queue<TestingDispatcherLeaderProcess> processes) { this.processes = processes; } @Override public TestingDispatcherLeaderProcess create(UUID leaderSessionID) { if (processes.isEmpty()) { return TestingDispatcherLeaderProcess.newBuilder(leaderSessionID).build(); } else { final TestingDispatcherLeaderProcess nextProcess = processes.poll(); Preconditions.checkState(leaderSessionID.equals(nextProcess.getLeaderSessionId())); return nextProcess; } } public static TestingDispatcherLeaderProcessFactory from( TestingDispatcherLeaderProcess... processes) { return new TestingDispatcherLeaderProcessFactory( new ArrayDeque<>(Arrays.asList(processes))); } public static TestingDispatcherLeaderProcessFactory defaultValue() { return new TestingDispatcherLeaderProcessFactory(new ArrayDeque<>(0)); } }
package com.events.codeWithUtkarsh.eventconsumer.model; import java.math.BigDecimal; public class OrderItem { private String name; private int quantity; private BigDecimal price; public OrderItem(String name, int quantity, BigDecimal price) { super(); this.name = name; this.quantity = quantity; this.price = price; } public OrderItem() { // TODO Auto-generated constructor stub } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getQuantity() { return quantity; } public void setQuantity(int quantity) { this.quantity = quantity; } public BigDecimal getPrice() { return price; } public void setPrice(BigDecimal price) { this.price = price; } }
/* * Tencent is pleased to support the open source community by making VasSonic available. * * Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved. * Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at * * https://opensource.org/licenses/BSD-3-Clause * * 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.tencent.sonic.demo; import android.annotation.TargetApi; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.text.TextUtils; import android.view.View; import android.view.WindowManager; import android.webkit.WebResourceRequest; import android.webkit.WebResourceResponse; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.Toast; import com.tencent.sonic.R; import com.tencent.sonic.sdk.SonicCacheInterceptor; import com.tencent.sonic.sdk.SonicConfig; import com.tencent.sonic.sdk.SonicConstants; import com.tencent.sonic.sdk.SonicEngine; import com.tencent.sonic.sdk.SonicSession; import com.tencent.sonic.sdk.SonicSessionConfig; import com.tencent.sonic.sdk.SonicSessionConnection; import com.tencent.sonic.sdk.SonicSessionConnectionInterceptor; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.lang.ref.WeakReference; import java.util.HashMap; import java.util.List; import java.util.Map; /** * A demo browser activity * In this demo there are three modes, * sonic mode: sonic mode means webview loads html by sonic, * offline mode: offline mode means webview loads html from local offline packages, * default mode: default mode means webview loads html in the normal way. * */ public class BrowserActivity extends Activity { public final static String PARAM_URL = "param_url"; public final static String PARAM_MODE = "param_mode"; private SonicSession sonicSession; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); String url = intent.getStringExtra(PARAM_URL); int mode = intent.getIntExtra(PARAM_MODE, -1); if (TextUtils.isEmpty(url) || -1 == mode) { finish(); return; } getWindow().addFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED); // init sonic engine if necessary, or maybe u can do this when application created if (!SonicEngine.isGetInstanceAllowed()) { SonicEngine.createInstance(new SonicRuntimeImpl(getApplication()), new SonicConfig.Builder().build()); } SonicSessionClientImpl sonicSessionClient = null; // if it's sonic mode , startup sonic session at first time if (MainActivity.MODE_DEFAULT != mode) { // sonic mode SonicSessionConfig.Builder sessionConfigBuilder = new SonicSessionConfig.Builder(); sessionConfigBuilder.setSupportLocalServer(true); // if it's offline pkg mode, we need to intercept the session connection if (MainActivity.MODE_SONIC_WITH_OFFLINE_CACHE == mode) { sessionConfigBuilder.setCacheInterceptor(new SonicCacheInterceptor(null) { @Override public String getCacheData(SonicSession session) { return null; // offline pkg does not need cache } }); sessionConfigBuilder.setConnectionInterceptor(new SonicSessionConnectionInterceptor() { @Override public SonicSessionConnection getConnection(SonicSession session, Intent intent) { return new OfflinePkgSessionConnection(BrowserActivity.this, session, intent); } }); } // create sonic session and run sonic flow sonicSession = SonicEngine.getInstance().createSession(url, sessionConfigBuilder.build()); if (null != sonicSession) { sonicSession.bindClient(sonicSessionClient = new SonicSessionClientImpl()); } else { // this only happen when a same sonic session is already running, // u can comment following codes to feedback as a default mode. // throw new UnknownError("create session fail!"); Toast.makeText(this, "create sonic session fail!", Toast.LENGTH_LONG).show(); } } // start init flow ... // in the real world, the init flow may cost a long time as startup // runtime、init configs.... setContentView(R.layout.activity_browser); // 动态刷新 FloatingActionButton btnFab = (FloatingActionButton) findViewById(R.id.btn_refresh); btnFab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (sonicSession != null) { sonicSession.refresh(); Toast.makeText(BrowserActivity.this,"sonicSession refresh",Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(BrowserActivity.this,"sonicSession is null",Toast.LENGTH_SHORT).show(); } } }); // init webview WebView webView = (WebView) findViewById(R.id.webview); webView.setWebViewClient(new WebViewClient() { @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); if (sonicSession != null) { sonicSession.getSessionClient().pageFinish(url); } } @TargetApi(21) @Override public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) { return shouldInterceptRequest(view, request.getUrl().toString()); } @Override public WebResourceResponse shouldInterceptRequest(WebView view, String url) { if (sonicSession != null) { return (WebResourceResponse) sonicSession.getSessionClient().requestResource(url); } return null; } }); WebSettings webSettings = webView.getSettings(); // add java script interface // note:if api level lower than 17(android 4.2), addJavascriptInterface has security // issue, please use x5 or see https://developer.android.com/reference/android/webkit/ // WebView.html#addJavascriptInterface(java.lang.Object, java.lang.String) webSettings.setJavaScriptEnabled(true); webView.removeJavascriptInterface("searchBoxJavaBridge_"); intent.putExtra(SonicJavaScriptInterface.PARAM_LOAD_URL_TIME, System.currentTimeMillis()); webView.addJavascriptInterface(new SonicJavaScriptInterface(sonicSessionClient, intent), "sonic"); // init webview settings webSettings.setAllowContentAccess(true); webSettings.setDatabaseEnabled(true); webSettings.setDomStorageEnabled(true); webSettings.setAppCacheEnabled(true); webSettings.setSavePassword(false); webSettings.setSaveFormData(false); webSettings.setUseWideViewPort(true); webSettings.setLoadWithOverviewMode(true); // webview is ready now, just tell session client to bind if (sonicSessionClient != null) { sonicSessionClient.bindWebView(webView); sonicSessionClient.clientReady(); } else { // default mode webView.loadUrl(url); } } @Override public void onBackPressed() { super.onBackPressed(); } @Override protected void onDestroy() { if (null != sonicSession) { sonicSession.destroy(); sonicSession = null; } super.onDestroy(); } /** * 本地离线html */ private static class OfflinePkgSessionConnection extends SonicSessionConnection { private final WeakReference<Context> context; public OfflinePkgSessionConnection(Context context, SonicSession session, Intent intent) { super(session, intent); this.context = new WeakReference<Context>(context); } @Override protected int internalConnect() { Context ctx = context.get(); if (null != ctx) { try { InputStream offlineHtmlInputStream = ctx.getAssets().open("sonic-demo-index.html"); responseStream = new BufferedInputStream(offlineHtmlInputStream); return SonicConstants.ERROR_CODE_SUCCESS; } catch (Throwable e) { e.printStackTrace(); } } return SonicConstants.ERROR_CODE_UNKNOWN; } @Override protected BufferedInputStream internalGetResponseStream() { return responseStream; } @Override protected String internalGetCustomHeadFieldEtag() { return SonicSessionConnection.CUSTOM_HEAD_FILED_ETAG; } @Override public void disconnect() { if (null != responseStream) { try { responseStream.close(); } catch (IOException e) { e.printStackTrace(); } } } @Override public int getResponseCode() { return 200; } @Override public Map<String, List<String>> getResponseHeaderFields() { return new HashMap<>(0); } @Override public String getResponseHeaderField(String key) { return ""; } } }
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.ads.googleads.v7.services.stub; import com.google.ads.googleads.v7.resources.AdGroupExtensionSetting; import com.google.ads.googleads.v7.services.GetAdGroupExtensionSettingRequest; import com.google.ads.googleads.v7.services.MutateAdGroupExtensionSettingsRequest; import com.google.ads.googleads.v7.services.MutateAdGroupExtensionSettingsResponse; import com.google.api.gax.core.BackgroundResource; import com.google.api.gax.rpc.UnaryCallable; import javax.annotation.Generated; // AUTO-GENERATED DOCUMENTATION AND CLASS. /** * Base stub class for the AdGroupExtensionSettingService service API. * * <p>This class is for advanced usage and reflects the underlying API directly. */ @Generated("by gapic-generator-java") public abstract class AdGroupExtensionSettingServiceStub implements BackgroundResource { public UnaryCallable<GetAdGroupExtensionSettingRequest, AdGroupExtensionSetting> getAdGroupExtensionSettingCallable() { throw new UnsupportedOperationException( "Not implemented: getAdGroupExtensionSettingCallable()"); } public UnaryCallable< MutateAdGroupExtensionSettingsRequest, MutateAdGroupExtensionSettingsResponse> mutateAdGroupExtensionSettingsCallable() { throw new UnsupportedOperationException( "Not implemented: mutateAdGroupExtensionSettingsCallable()"); } @Override public abstract void close(); }
/* * Copyright 2019,2020,2021 yoyosource * 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 yapion.packet; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import yapion.annotations.api.InternalAPI; import yapion.utils.IdentifierUtils; import yapion.utils.ReflectionsUtils; import java.io.IOException; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Method; import java.lang.reflect.Parameter; import java.util.*; import java.util.function.Predicate; @Slf4j public class YAPIONPacketReceiver { private final Map<String, YAPIONPacketHandler<?>> handlerMap = new HashMap<>(); private final Map<String, Set<Predicate<YAPIONPacket>>> filterMap = new HashMap<>(); private final Set<Predicate<YAPIONPacket>> packetFilters = new HashSet<>(); @RequiredArgsConstructor public enum Handler { /** * Used when any {@link Handler} except {@link #HEART_BEAT} or {@link #LOST_HEART_BEAT} threw an exception. */ ERROR("@error", null), /** * Used when any user handlers threw an exception. */ EXCEPTION("@exception", ERROR), /** * Used when a packet has an unknown {@link IdentifierUtils#TYPE_IDENTIFIER}. */ UNKNOWN_PACKET("@unknown", ERROR), /** * Used when a packet has been filtered by a {@link Predicate<YAPIONPacket>} */ FILTERED("@filtered", ERROR), /** * Used when some data was dropped. */ DROP("@drop", ERROR), /** * Used when deserialization to an YAPIONPacket failed with an exception. */ DESERIALIZE_EXCEPTION("@deserialize", ERROR), /** * Used when anything while checking the incoming data failed. */ HANDLE_FAILED("@handle", ERROR), /** * Used when an heartbeat packet arrived. */ HEART_BEAT("@heartbeat", EXCEPTION), /** * Used when the heartbeat packet was not received in the given amount of time. */ LOST_HEART_BEAT("@lost_heartbeat", EXCEPTION), @InternalAPI USER("", EXCEPTION); private static final Handler[] HANDLERS = values(); private final String identifier; private final Handler onException; } /** * Creates an YAPIONPacketReceiver */ public YAPIONPacketReceiver() { for (Handler handler : Handler.HANDLERS) { handlerMap.put(handler.identifier, yapionPacket -> {}); } registerMethodStuff(); } private void registerMethodStuff() { Class<?> current = this.getClass(); while (current != YAPIONPacketReceiver.class) { Method[] methods = current.getDeclaredMethods(); for (Method method : methods) { Filter filter = method.getAnnotation(Filter.class); if (filter != null) { if (method.getReturnType() != boolean.class) { continue; } Parameter[] parameters = method.getParameters(); if (parameters.length != 1) { continue; } Parameter parameter = parameters[0]; if (!YAPIONPacket.class.isAssignableFrom(parameter.getType())) { continue; } if (parameter.getType() == YAPIONPacket.class) { log.debug("Registering method '{}' as global filter", method); addPacketFilter(yapionPacket -> { return (boolean) ReflectionsUtils.invokeMethodObjectSystem(method, this, yapionPacket).get(); }); } else { log.debug("Registering method '{}' as filter for '{}'", method, parameter.getType()); addPacketFilter((Class<? extends YAPIONPacket>) parameter.getType(), yapionPacket -> { return (boolean) ReflectionsUtils.invokeMethodObjectSystem(method, this, yapionPacket).get(); }); } } PacketHandler packetHandler = method.getAnnotation(PacketHandler.class); if (packetHandler != null) { if (method.getReturnType() != void.class) { continue; } Parameter[] parameters = method.getParameters(); if (parameters.length != 1) { continue; } Parameter parameter = parameters[0]; if (!YAPIONPacket.class.isAssignableFrom(parameter.getType())) { continue; } log.debug("Registering method '{}' as handler for '{}'", method, parameter.getType()); add((Class<? extends YAPIONPacket>) parameter.getType(), yapionPacket -> { ReflectionsUtils.invokeMethodObjectSystem(method, this, yapionPacket); }); } OtherHandler otherHandler = method.getAnnotation(OtherHandler.class); if (otherHandler != null) { if (method.getReturnType() != void.class) { continue; } Parameter[] parameters = method.getParameters(); if (parameters.length != 1) { continue; } Parameter parameter = parameters[0]; if (parameter.getType() != YAPIONPacket.class) { continue; } log.debug("Registering method '{}' as otherHandler for '{}'", method, Arrays.toString(otherHandler.value())); for (Handler handler : otherHandler.value()) { setHandler(handler, yapionPacket -> { ReflectionsUtils.invokeMethodObjectSystem(method, this, yapionPacket); }); } } } current = current.getSuperclass(); } } /** * Add an YAPIONPacketHandler for a specified packetType to handle. * If either the packetType or yapionPacketHandler is {@code null} * this method throws an YAPIONPacketException. * * @param packetType the packet to handle * @param yapionPacketHandler the handler which handles the specified packet */ public <T extends YAPIONPacket> YAPIONPacketReceiver add(@NonNull Class<T> packetType, @NonNull YAPIONPacketHandler<T> yapionPacketHandler) { handlerMap.put(packetType.getTypeName(), yapionPacketHandler); filterMap.put(packetType.getTypeName(), new HashSet<>()); return this; } public <T extends YAPIONPacket> YAPIONPacketReceiver remove(@NonNull Class<T> packetType) { handlerMap.remove(packetType.getTypeName()); filterMap.remove(packetType.getTypeName()); return this; } /** * Set the SpecialHandler {@link YAPIONPacketHandler} to do something. * * @param yapionPacketHandler the {@link YAPIONPacketHandler} to set */ public YAPIONPacketReceiver setHandler(@NonNull Handler handler, @NonNull YAPIONPacketHandler<YAPIONPacket> yapionPacketHandler) { if (handler == Handler.USER) { throw new SecurityException(); } handlerMap.put(handler.identifier, yapionPacketHandler); return this; } public YAPIONPacketReceiver addPacketFilter(@NonNull Predicate<YAPIONPacket> yapionPacketFilter) { packetFilters.add(yapionPacketFilter); return this; } public <T extends YAPIONPacket> YAPIONPacketReceiver addPacketFilter(@NonNull Class<T> packetType, @NonNull Predicate<T> yapionPacketFilter) { if (!filterMap.containsKey(packetType.getTypeName())) { throw new SecurityException("Packet Type needs to have a YAPIONPacketHandler before declaring filters"); } filterMap.get(packetType.getTypeName()).add((Predicate<YAPIONPacket>) yapionPacketFilter); return this; } /** * Handles an YAPIONPacket by calling the specified yapionPacketHandler * for the type of the packet. If the packet type is not found the * "@error" handler gets called. If any exception gets thrown the * special "@exception" handler is called. If this also throws an * exception this method will log the exception as a warning. * * @param yapionPacket to handle */ public void handle(@NonNull YAPIONPacket yapionPacket) { String type = yapionPacket.getType(); if (!handlerMap.containsKey(type)) { handle(yapionPacket, Handler.UNKNOWN_PACKET); return; } if (packetFilters.stream().anyMatch(yapionPacketFilter -> yapionPacketFilter.test(yapionPacket))) { handle(yapionPacket, Handler.FILTERED); return; } if (filterMap.get(type).stream().anyMatch(yapionPacketFilter -> yapionPacketFilter.test(yapionPacket))) { handle(yapionPacket, Handler.FILTERED); return; } handlePacket(yapionPacket, handlerMap.get(type), Handler.USER); } void handle(YAPIONPacket yapionPacket, Handler handler) { handlePacket(yapionPacket, handlerMap.get(handler.identifier), handler); } private void handlePacket(YAPIONPacket yapionPacket, YAPIONPacketHandler handler, Handler currentHandler) { Runnable runnable = () -> { try { handler.handlePacket(yapionPacket); } catch (Exception e) { log.warn(String.format("Current packet handler executing type '%s' threw an exception. Current handler is %s.", yapionPacket.getType(), currentHandler.name()), e.getCause()); yapionPacket.setException(e); if (handler.closeOnException() && yapionPacket.getYAPIONPacketStream() != null) { try { yapionPacket.getYAPIONPacketStream().close(); } catch (IOException ex) { // Ignored } return; } if (handler.ignoreException()) { return; } if (currentHandler.onException == null) { throw new SecurityException(yapionPacket.getException().getMessage(), yapionPacket.getException()); } handlePacket(yapionPacket, handlerMap.get(currentHandler.onException.identifier), currentHandler.onException); } }; if (handler.runThread()) { Thread thread = new Thread(runnable); thread.setName("Packet handler Thread (" + yapionPacket.getType() + ")"); thread.setDaemon(handler.daemonThread()); thread.start(); } else { runnable.run(); } } @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) protected @interface Filter { } @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) protected @interface PacketHandler { } @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) protected @interface OtherHandler { Handler[] value(); } }
package com.rohan.dsa.foundations.patterns; import java.util.Scanner; /* E D E C D E B C D E A B C D E How many rows? 4 (N) How many columns? i row number What to print? starting character beginning with E and incrementing on every column count */ public class Pattern16 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int numRows = scanner.nextInt(); int i = 0; while (i < numRows) { char startingChar = (char) ('E' - i); int j = 0; while (j <= i) { char ch = (char) (startingChar + j); System.out.print(ch + " "); j++; } System.out.println(); i++; } } }
package com.mikepenz.iconics.sample; import android.app.Application; import com.mikepenz.google_material_typeface_library.GoogleMaterial; import com.mikepenz.iconics.Iconics; import com.mikepenz.iconics.sample.typeface.CustomFont; import com.mikepenz.meteocons_typeface_library.Meteoconcs; public class CustomApplication extends Application { @Override public void onCreate() { super.onCreate(); Iconics.registerFont(new Meteoconcs()); Iconics.registerFont(new GoogleMaterial()); Iconics.registerFont(new CustomFont()); } }
package com.dalim.esprit.api.directory; import java.util.ArrayList; import java.util.List; public class EsRoles { private List<String> roles = new ArrayList<>(); public List<String> getRoles() { return roles; } }
/* * Copyright 2016 Yan Zhenjie. * * 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.yanzhenjie.album; import android.app.Activity; import android.app.Fragment; import android.content.Context; import android.util.Log; import com.yanzhenjie.album.api.AlbumMultipleWrapper; import com.yanzhenjie.album.api.AlbumSingleWrapper; import com.yanzhenjie.album.api.BasicGalleryWrapper; import com.yanzhenjie.album.api.GalleryAlbumWrapper; import com.yanzhenjie.album.api.GalleryWrapper; import com.yanzhenjie.album.api.ImageCameraWrapper; import com.yanzhenjie.album.api.ImageMultipleWrapper; import com.yanzhenjie.album.api.ImageSingleWrapper; import com.yanzhenjie.album.api.VideoCameraWrapper; import com.yanzhenjie.album.api.VideoMultipleWrapper; import com.yanzhenjie.album.api.VideoSingleWrapper; import com.yanzhenjie.album.api.camera.AlbumCamera; import com.yanzhenjie.album.api.camera.Camera; import com.yanzhenjie.album.api.choice.AlbumChoice; import com.yanzhenjie.album.api.choice.Choice; import com.yanzhenjie.album.api.choice.ImageChoice; import com.yanzhenjie.album.api.choice.VideoChoice; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import androidx.annotation.IntDef; import androidx.annotation.NonNull; import androidx.annotation.Nullable; /** * <p>Entrance.</p> * Created by Yan Zhenjie on 2016/10/23. */ public final class Album { // All. public static final String KEY_INPUT_WIDGET = "KEY_INPUT_WIDGET"; public static final String KEY_INPUT_CHECKED_LIST = "KEY_INPUT_CHECKED_LIST"; // Album. public static final String KEY_INPUT_FUNCTION = "KEY_INPUT_FUNCTION"; public static final int FUNCTION_CHOICE_IMAGE = 0; public static final int FUNCTION_CHOICE_VIDEO = 1; public static final int FUNCTION_CHOICE_ALBUM = 2; public static final int FUNCTION_CAMERA_IMAGE = 0; public static final int FUNCTION_CAMERA_VIDEO = 1; public static final String KEY_INPUT_CHOICE_MODE = "KEY_INPUT_CHOICE_MODE"; public static final int MODE_MULTIPLE = 1; public static final int MODE_SINGLE = 2; public static final String KEY_INPUT_COLUMN_COUNT = "KEY_INPUT_COLUMN_COUNT"; public static final String KEY_INPUT_ALLOW_CAMERA = "KEY_INPUT_ALLOW_CAMERA"; public static final String KEY_INPUT_LIMIT_COUNT = "KEY_INPUT_LIMIT_COUNT"; // Gallery. public static final String KEY_INPUT_CURRENT_POSITION = "KEY_INPUT_CURRENT_POSITION"; public static final String KEY_INPUT_GALLERY_CHECKABLE = "KEY_INPUT_GALLERY_CHECKABLE"; // Camera. public static final String KEY_INPUT_FILE_PATH = "KEY_INPUT_FILE_PATH"; public static final String KEY_INPUT_CAMERA_QUALITY = "KEY_INPUT_CAMERA_QUALITY"; public static final String KEY_INPUT_CAMERA_DURATION = "KEY_INPUT_CAMERA_DURATION"; public static final String KEY_INPUT_CAMERA_BYTES = "KEY_INPUT_CAMERA_BYTES"; // Filter. public static final String KEY_INPUT_FILTER_VISIBILITY = "KEY_INPUT_FILTER_VISIBILITY"; @IntDef({FUNCTION_CHOICE_IMAGE, FUNCTION_CHOICE_VIDEO, FUNCTION_CHOICE_ALBUM}) @Retention(RetentionPolicy.SOURCE) public @interface ChoiceFunction { } @IntDef({FUNCTION_CAMERA_IMAGE, FUNCTION_CAMERA_VIDEO}) @Retention(RetentionPolicy.SOURCE) public @interface CameraFunction { } @IntDef({MODE_MULTIPLE, MODE_SINGLE}) @Retention(RetentionPolicy.SOURCE) public @interface ChoiceMode { } private static AlbumConfig sAlbumConfig; /** * Initialize Album. * * @param albumConfig {@link AlbumConfig}. */ public static void initialize(@Nullable AlbumConfig albumConfig) { if (sAlbumConfig == null) { sAlbumConfig = albumConfig; } else { Log.w("Album", new IllegalStateException("Illegal operation, only allowed to configure once.")); } } /** * Get the album configuration. */ @NonNull public static AlbumConfig getAlbumConfig() { if (sAlbumConfig == null) { sAlbumConfig = AlbumConfig.newBuilder(null).build(); } return sAlbumConfig; } /** * Open the camera from the activity. */ @NonNull public static Camera<ImageCameraWrapper, VideoCameraWrapper> camera(@NonNull Context context) { return new AlbumCamera(context); } /** * Select images. */ @NonNull public static Choice<ImageMultipleWrapper, ImageSingleWrapper> image(@NonNull Context context) { return new ImageChoice(context); } /** * Select videos. */ @NonNull public static Choice<VideoMultipleWrapper, VideoSingleWrapper> video(@NonNull Context context) { return new VideoChoice(context); } /** * Select images and videos. */ @NonNull public static Choice<AlbumMultipleWrapper, AlbumSingleWrapper> album(@NonNull Context context) { return new AlbumChoice(context); } /** * Preview picture. */ @NonNull public static GalleryWrapper gallery(@NonNull Context context) { return new GalleryWrapper(context); } /** * Preview Album. */ @NonNull public static GalleryAlbumWrapper galleryAlbum(@NonNull Context context) { return new GalleryAlbumWrapper(context); } /** * Open the camera from the activity. */ @NonNull public static Camera<ImageCameraWrapper, VideoCameraWrapper> camera(@NonNull Activity activity) { return new AlbumCamera(activity); } /** * Select images. */ @NonNull public static Choice<ImageMultipleWrapper, ImageSingleWrapper> image(@NonNull Activity activity) { return new ImageChoice(activity); } /** * Select videos. */ @NonNull public static Choice<VideoMultipleWrapper, VideoSingleWrapper> video(@NonNull Activity activity) { return new VideoChoice(activity); } /** * Select images and videos. */ @NonNull public static Choice<AlbumMultipleWrapper, AlbumSingleWrapper> album(@NonNull Activity activity) { return new AlbumChoice(activity); } /** * Preview picture. */ @NonNull public static BasicGalleryWrapper<GalleryWrapper, String, String, String> gallery(@NonNull Activity activity) { return new GalleryWrapper(activity); } /** * Preview Album. */ @NonNull public static BasicGalleryWrapper<GalleryAlbumWrapper, AlbumFile, String, AlbumFile> galleryAlbum(@NonNull Activity activity) { return new GalleryAlbumWrapper(activity); } /** * Open the camera from the activity. */ @NonNull public static Camera<ImageCameraWrapper, VideoCameraWrapper> camera(@NonNull Fragment fragment) { return new AlbumCamera(fragment.getActivity()); } /** * Select images. */ @NonNull public static Choice<ImageMultipleWrapper, ImageSingleWrapper> image(@NonNull Fragment fragment) { return new ImageChoice(fragment.getActivity()); } /** * Select videos. */ @NonNull public static Choice<VideoMultipleWrapper, VideoSingleWrapper> video(@NonNull Fragment fragment) { return new VideoChoice(fragment.getActivity()); } /** * Select images and videos. */ @NonNull public static Choice<AlbumMultipleWrapper, AlbumSingleWrapper> album(@NonNull Fragment fragment) { return new AlbumChoice(fragment.getActivity()); } /** * Preview picture. */ @NonNull public static BasicGalleryWrapper<GalleryWrapper, String, String, String> gallery(@NonNull Fragment fragment) { return new GalleryWrapper(fragment.getActivity()); } /** * Preview Album. */ @NonNull public static BasicGalleryWrapper<GalleryAlbumWrapper, AlbumFile, String, AlbumFile> galleryAlbum(@NonNull Fragment fragment) { return new GalleryAlbumWrapper(fragment.getActivity()); } /** * Open the camera from the activity. */ @NonNull public static Camera<ImageCameraWrapper, VideoCameraWrapper> camera(@NonNull androidx.fragment.app.Fragment fragment) { return new AlbumCamera(fragment.getContext()); } /** * Select images. */ @NonNull public static Choice<ImageMultipleWrapper, ImageSingleWrapper> image(@NonNull androidx.fragment.app.Fragment fragment) { return new ImageChoice(fragment.getContext()); } /** * Select videos. */ @NonNull public static Choice<VideoMultipleWrapper, VideoSingleWrapper> video(@NonNull androidx.fragment.app.Fragment fragment) { return new VideoChoice(fragment.getContext()); } /** * Select images and videos. */ @NonNull public static Choice<AlbumMultipleWrapper, AlbumSingleWrapper> album(@NonNull androidx.fragment.app.Fragment fragment) { return new AlbumChoice(fragment.getContext()); } /** * Preview picture. */ @NonNull public static BasicGalleryWrapper<GalleryWrapper, String, String, String> gallery(@NonNull androidx.fragment.app.Fragment fragment) { return new GalleryWrapper(fragment.getContext()); } /** * Preview Album. */ @NonNull public static BasicGalleryWrapper<GalleryAlbumWrapper, AlbumFile, String, AlbumFile> galleryAlbum(@NonNull androidx.fragment.app.Fragment fragment) { return new GalleryAlbumWrapper(fragment.getContext()); } }
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.documentapi.messagebus; import com.yahoo.concurrent.ThreadFactoryFactory; import com.yahoo.document.select.parser.ParseException; import com.yahoo.documentapi.AsyncParameters; import com.yahoo.documentapi.DocumentAccess; import com.yahoo.documentapi.DocumentAccessException; import com.yahoo.documentapi.SubscriptionParameters; import com.yahoo.documentapi.SubscriptionSession; import com.yahoo.documentapi.SyncParameters; import com.yahoo.documentapi.VisitorDestinationParameters; import com.yahoo.documentapi.VisitorParameters; import com.yahoo.documentapi.messagebus.protocol.DocumentProtocol; import com.yahoo.messagebus.MessageBus; import com.yahoo.messagebus.NetworkMessageBus; import com.yahoo.messagebus.RPCMessageBus; import com.yahoo.messagebus.network.Network; import com.yahoo.messagebus.network.local.LocalNetwork; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.logging.Level; import java.util.logging.Logger; /** * This class implements the {@link DocumentAccess} interface using message bus for communication. * * @author Einar Rosenvinge * @author bratseth */ public class MessageBusDocumentAccess extends DocumentAccess { private static final Logger log = Logger.getLogger(MessageBusDocumentAccess.class.getName()); private final NetworkMessageBus bus; private final MessageBusParams params; // TODO: make pool size configurable? ScheduledExecutorService is not dynamic private final ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors(), ThreadFactoryFactory.getDaemonThreadFactory("mbus.access.scheduler")); /** * Creates a new document access using default values for all parameters. */ public MessageBusDocumentAccess() { this(new MessageBusParams()); } /** * Creates a new document access using the supplied parameters. * * @param params All parameters for construction. */ public MessageBusDocumentAccess(MessageBusParams params) { super(params); this.params = params; try { com.yahoo.messagebus.MessageBusParams mbusParams = new com.yahoo.messagebus.MessageBusParams(params.getMessageBusParams()); mbusParams.addProtocol(new DocumentProtocol(getDocumentTypeManager(), params.getProtocolConfigId(), params.getLoadTypes())); if (System.getProperty("vespa.local", "false").equals("true")) { // set by Application when running locally LocalNetwork network = new LocalNetwork(); bus = new NetworkMessageBus(network, new MessageBus(network, mbusParams)); } else { if (params.getRPCNetworkParams().getSlobroksConfig() != null && mbusParams.getMessageBusConfig() != null) bus = new RPCMessageBus(mbusParams, params.getRPCNetworkParams()); else { log.log(Level.FINE, () -> "Setting up self-subscription to config because explicit config was missing; try to avoid this in containers"); bus = new RPCMessageBus(mbusParams, params.getRPCNetworkParams(), params.getRoutingConfigId()); } } } catch (Exception e) { throw new DocumentAccessException(e); } } private MessageBus messageBus() { return bus.getMessageBus(); } @Override public void shutdown() { super.shutdown(); bus.destroy(); scheduledExecutorService.shutdownNow(); } @Override public MessageBusSyncSession createSyncSession(SyncParameters parameters) { return new MessageBusSyncSession(parameters, messageBus(), this.params); } @Override public MessageBusAsyncSession createAsyncSession(AsyncParameters parameters) { return new MessageBusAsyncSession(parameters, messageBus(), this.params); } @Override public MessageBusVisitorSession createVisitorSession(VisitorParameters params) throws ParseException, IllegalArgumentException { MessageBusVisitorSession session = MessageBusVisitorSession.createForMessageBus( messageBus(), scheduledExecutorService, params); session.start(); return session; } @Override public MessageBusVisitorDestinationSession createVisitorDestinationSession(VisitorDestinationParameters params) { return new MessageBusVisitorDestinationSession(params, bus.getMessageBus()); } @Override public SubscriptionSession createSubscription(SubscriptionParameters parameters) { throw new UnsupportedOperationException("Subscriptions not supported."); } @Override public SubscriptionSession openSubscription(SubscriptionParameters parameters) { throw new UnsupportedOperationException("Subscriptions not supported."); } /** Returns the internal message bus object so that clients can use it directly. */ public MessageBus getMessageBus() { return messageBus(); } /** * Returns the network layer of the internal message bus object so that clients can use it directly. This may seem * abit arbitrary, but the fact is that the RPCNetwork actually implements the IMirror API as well as exposing the * SystemState object. */ public Network getNetwork() { return bus.getNetwork(); } /** * Returns the parameter object that controls the underlying message bus. Changes to these parameters do not affect * previously created sessions. */ public MessageBusParams getParams() { return params; } }
package com.atguigu.gulimall.search.service; import com.atguigu.common.to.es.SkuEsModel; import java.io.IOException; import java.util.List; public interface ProductSaveService { Boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException; }
/* * Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 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 * * 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.wso2.micro.integrator.security.user.core.internal; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.osgi.service.component.ComponentContext; import org.wso2.micro.core.Constants; import org.wso2.micro.integrator.core.services.CarbonServerConfigurationService; import org.wso2.micro.integrator.security.user.api.RealmConfiguration; import org.wso2.micro.integrator.security.user.api.UserStoreManager; import org.wso2.micro.integrator.security.user.core.UserStoreConfigConstants; import org.wso2.micro.integrator.security.user.core.claim.ClaimManager; import org.wso2.micro.integrator.security.user.core.claim.ClaimManagerFactory; import org.wso2.micro.integrator.security.user.core.jdbc.JDBCUserStoreManager; import org.wso2.micro.integrator.security.user.core.ldap.ActiveDirectoryUserStoreManager; import org.wso2.micro.integrator.security.user.core.ldap.ReadOnlyLDAPUserStoreManager; import org.wso2.micro.integrator.security.user.core.ldap.ReadWriteLDAPUserStoreManager; import org.wso2.micro.integrator.security.user.core.service.RealmService; import org.wso2.micro.integrator.security.user.core.tracker.UserStoreManagerRegistry; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; //@Component(name = "user.store.mgt.dscomponent", immediate = true) public class UserStoreMgtDSComponent { private static Log log = LogFactory.getLog(UserStoreMgtDSComponent.class); private static RealmService realmService; private static CarbonServerConfigurationService serverConfigurationService = null; private static ClaimManagerFactory claimManagerFactory = null; public static RealmService getRealmService() { return realmService; } // @Reference(name = "user.realmservice.default", cardinality = ReferenceCardinality.MANDATORY, // policy = ReferencePolicy.DYNAMIC, unbind = "unsetRealmService") protected void setRealmService(RealmService rlmService) { realmService = rlmService; } public static CarbonServerConfigurationService getServerConfigurationService() { return UserStoreMgtDSComponent.serverConfigurationService; } // @Reference(name = "server.configuration.service", cardinality = ReferenceCardinality.MANDATORY, // policy = ReferencePolicy.DYNAMIC, unbind = "unsetServerConfigurationService") protected void setServerConfigurationService(CarbonServerConfigurationService serverConfigurationService) { UserStoreMgtDSComponent.serverConfigurationService = serverConfigurationService; } // @Activate protected void activate(ComponentContext ctxt) { if (Boolean.parseBoolean(System.getProperty("NonUserCoreMode"))) { log.debug("UserCore component activated in NonUserCoreMode Mode"); return; } try { // We assume this component gets activated by super tenant UserStoreManager jdbcUserStoreManager = new JDBCUserStoreManager(); ctxt.getBundleContext().registerService(UserStoreManager.class.getName(), jdbcUserStoreManager, null); UserStoreManager readWriteLDAPUserStoreManager = new ReadWriteLDAPUserStoreManager(); ctxt.getBundleContext().registerService(UserStoreManager.class.getName(), readWriteLDAPUserStoreManager, null); UserStoreManager readOnlyLDAPUserStoreManager = new ReadOnlyLDAPUserStoreManager(); ctxt.getBundleContext().registerService(UserStoreManager.class.getName(), readOnlyLDAPUserStoreManager, null); UserStoreManager activeDirectoryUserStoreManager = new ActiveDirectoryUserStoreManager(); ctxt.getBundleContext().registerService(UserStoreManager.class.getName(), activeDirectoryUserStoreManager, null); UserStoreManagerRegistry.init(ctxt.getBundleContext()); log.info("Carbon UserStoreMgtDSComponent activated successfully."); } catch (Exception e) { log.error("Failed to activate Carbon UserStoreMgtDSComponent ", e); } } // @Deactivate protected void deactivate(ComponentContext ctxt) { if (log.isDebugEnabled()) { log.debug("Carbon UserStoreMgtDSComponent is deactivated "); } } protected void unsetRealmService(RealmService realmService) { realmService = null; } protected void unsetServerConfigurationService(CarbonServerConfigurationService serverConfigurationService) { if (log.isDebugEnabled()) { log.debug("Unsetting the ServerConfigurationService"); } UserStoreMgtDSComponent.serverConfigurationService = null; } public static ClaimManagerFactory getClaimManagerFactory() { return UserStoreMgtDSComponent.claimManagerFactory; } // @Reference(name = "claim.mgt.component", cardinality = ReferenceCardinality.OPTIONAL, // policy = ReferencePolicy.DYNAMIC, unbind = "unsetClaimManagerFactory") protected void setClaimManagerFactory(ClaimManagerFactory claimManagerFactory) { this.claimManagerFactory = claimManagerFactory; try { if (claimManagerFactory.createClaimManager(Constants.SUPER_TENANT_ID) != null) { ClaimManager claimManager = claimManagerFactory.createClaimManager(Constants.SUPER_TENANT_ID); setClaimManager(realmService.getBootstrapRealm(), claimManager); setClaimManager(realmService.getBootstrapRealm().getUserStoreManager(), claimManager); RealmConfiguration secondaryRealmConfiguration = realmService.getBootstrapRealm() .getRealmConfiguration().getSecondaryRealmConfig(); if (secondaryRealmConfiguration != null) { do { String userDomain = secondaryRealmConfiguration.getUserStoreProperty(UserStoreConfigConstants .DOMAIN_NAME); setClaimManager(realmService.getBootstrapRealm().getUserStoreManager() .getSecondaryUserStoreManager(userDomain), claimManager); secondaryRealmConfiguration = secondaryRealmConfiguration.getSecondaryRealmConfig(); } while (secondaryRealmConfiguration != null); } } } catch (Exception e) { log.error("Error while setting claim manager from claim manager factory"); } } protected void unsetClaimManagerFactory(ClaimManagerFactory claimManagerFactory) { UserStoreMgtDSComponent.claimManagerFactory = null; } private void setClaimManager(Object object, ClaimManager claimManager) { try { Class<?> currentClass = object.getClass(); Method method = null; while (currentClass != null && method == null) { try { method = currentClass.getDeclaredMethod("setClaimManager", ClaimManager.class); } catch (NoSuchMethodException e) { // method not present - try super class currentClass = currentClass.getSuperclass(); } } if (method != null) { method.setAccessible(true); method.invoke(object, claimManager); log.info("Claim manager set for " + object.getClass()); method.setAccessible(false); } else { throw new NoSuchMethodException(); } } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { log.error("No claim manager setter found for " + object.getClass() + " or its supper classes"); } } }
/** * Copyright 2009-2019 the original author or authors. * <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 org.apache.ibatis.parsing; import java.io.InputStream; import java.io.Reader; import java.io.StringReader; import java.util.ArrayList; import java.util.List; import java.util.Properties; import javax.xml.XMLConstants; import javax.xml.namespace.QName; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathFactory; import org.apache.ibatis.builder.BuilderException; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.EntityResolver; import org.xml.sax.ErrorHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; /** * @author Clinton Begin * @author Kazuki Shimizu * <p> * 解析XML核心类 * <p> * XMLConfigBuilder, XMLMapperBuilder、XMLStatementBuilder都是使用XPathParser的解析器 */ public class XPathParser { private final Document document; private boolean validation; private EntityResolver entityResolver; private Properties variables; private XPath xpath; public XPathParser(String xml) { commonConstructor(false, null, null); this.document = createDocument(new InputSource(new StringReader(xml))); } public XPathParser(Reader reader) { commonConstructor(false, null, null); this.document = createDocument(new InputSource(reader)); } public XPathParser(InputStream inputStream) { commonConstructor(false, null, null); this.document = createDocument(new InputSource(inputStream)); } public XPathParser(Document document) { commonConstructor(false, null, null); this.document = document; } public XPathParser(String xml, boolean validation) { commonConstructor(validation, null, null); this.document = createDocument(new InputSource(new StringReader(xml))); } public XPathParser(Reader reader, boolean validation) { commonConstructor(validation, null, null); this.document = createDocument(new InputSource(reader)); } public XPathParser(InputStream inputStream, boolean validation) { commonConstructor(validation, null, null); this.document = createDocument(new InputSource(inputStream)); } public XPathParser(Document document, boolean validation) { commonConstructor(validation, null, null); this.document = document; } public XPathParser(String xml, boolean validation, Properties variables) { commonConstructor(validation, variables, null); this.document = createDocument(new InputSource(new StringReader(xml))); } public XPathParser(Reader reader, boolean validation, Properties variables) { commonConstructor(validation, variables, null); this.document = createDocument(new InputSource(reader)); } public XPathParser(InputStream inputStream, boolean validation, Properties variables) { commonConstructor(validation, variables, null); this.document = createDocument(new InputSource(inputStream)); } public XPathParser(Document document, boolean validation, Properties variables) { commonConstructor(validation, variables, null); this.document = document; } public XPathParser(String xml, boolean validation, Properties variables, EntityResolver entityResolver) { commonConstructor(validation, variables, entityResolver); this.document = createDocument(new InputSource(new StringReader(xml))); } public XPathParser(Reader reader, boolean validation, Properties variables, EntityResolver entityResolver) { commonConstructor(validation, variables, entityResolver); this.document = createDocument(new InputSource(reader)); } public XPathParser(InputStream inputStream, boolean validation, Properties variables, EntityResolver entityResolver) { commonConstructor(validation, variables, entityResolver); this.document = createDocument(new InputSource(inputStream)); } public XPathParser(Document document, boolean validation, Properties variables, EntityResolver entityResolver) { commonConstructor(validation, variables, entityResolver); this.document = document; } public void setVariables(Properties variables) { this.variables = variables; } public String evalString(String expression) { return evalString(document, expression); } public String evalString(Object root, String expression) { String result = (String) evaluate(expression, root, XPathConstants.STRING); result = PropertyParser.parse(result, variables); return result; } public Boolean evalBoolean(String expression) { return evalBoolean(document, expression); } public Boolean evalBoolean(Object root, String expression) { return (Boolean) evaluate(expression, root, XPathConstants.BOOLEAN); } public Short evalShort(String expression) { return evalShort(document, expression); } public Short evalShort(Object root, String expression) { return Short.valueOf(evalString(root, expression)); } public Integer evalInteger(String expression) { return evalInteger(document, expression); } public Integer evalInteger(Object root, String expression) { return Integer.valueOf(evalString(root, expression)); } public Long evalLong(String expression) { return evalLong(document, expression); } public Long evalLong(Object root, String expression) { return Long.valueOf(evalString(root, expression)); } public Float evalFloat(String expression) { return evalFloat(document, expression); } public Float evalFloat(Object root, String expression) { return Float.valueOf(evalString(root, expression)); } public Double evalDouble(String expression) { return evalDouble(document, expression); } public Double evalDouble(Object root, String expression) { return (Double) evaluate(expression, root, XPathConstants.NUMBER); } public List<XNode> evalNodes(String expression) { return evalNodes(document, expression); } public List<XNode> evalNodes(Object root, String expression) { List<XNode> xnodes = new ArrayList<>(); NodeList nodes = (NodeList) evaluate(expression, root, XPathConstants.NODESET); for (int i = 0; i < nodes.getLength(); i++) { xnodes.add(new XNode(this, nodes.item(i), variables)); } return xnodes; } public XNode evalNode(String expression) { return evalNode(document, expression); } public XNode evalNode(Object root, String expression) { Node node = (Node) evaluate(expression, root, XPathConstants.NODE); if (node == null) { return null; } return new XNode(this, node, variables); } private Object evaluate(String expression, Object root, QName returnType) { try { return xpath.evaluate(expression, root, returnType); } catch (Exception e) { throw new BuilderException("Error evaluating XPath. Cause: " + e, e); } } private Document createDocument(InputSource inputSource) { // important: this must only be called AFTER common constructor try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); factory.setValidating(validation); factory.setNamespaceAware(false); factory.setIgnoringComments(true); factory.setIgnoringElementContentWhitespace(false); factory.setCoalescing(false); factory.setExpandEntityReferences(true); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setEntityResolver(entityResolver); builder.setErrorHandler(new ErrorHandler() { @Override public void error(SAXParseException exception) throws SAXException { throw exception; } @Override public void fatalError(SAXParseException exception) throws SAXException { throw exception; } @Override public void warning(SAXParseException exception) throws SAXException { // NOP } }); return builder.parse(inputSource); } catch (Exception e) { throw new BuilderException("Error creating document instance. Cause: " + e, e); } } private void commonConstructor(boolean validation, Properties variables, EntityResolver entityResolver) { this.validation = validation; this.entityResolver = entityResolver; this.variables = variables; XPathFactory factory = XPathFactory.newInstance(); this.xpath = factory.newXPath(); } }
/* * Copyright (c) 2015 Spotify AB. * * 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.spotify.heroic.aggregation; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.auto.value.AutoValue; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import java.util.List; import java.util.Optional; @AutoValue public abstract class Group implements Aggregation { public static Group createFromAggregation( Optional<List<String>> grouping, Optional<Aggregation> aggregation ) { return create(grouping, aggregation.map(AggregationOrList::fromAggregation)); } @JsonCreator public static Group create( @JsonProperty("of") Optional<List<String>> grouping, @JsonProperty("each") Optional<AggregationOrList> aggregation ) { return new AutoValue_Group(grouping, aggregation); } public static final String NAME = "group"; public static final String ALL = "*"; @JsonProperty("of") abstract Optional<List<String>> grouping(); @JsonProperty("each") abstract Optional<AggregationOrList> aggregation(); @Override public final GroupInstance apply(final AggregationContext context) { final AggregationInstance instance = aggregation() .flatMap(AggregationOrList::toAggregation) .orElse(Empty.INSTANCE) .apply(context); final Optional<List<String>> of = this.grouping().map(o -> { final ImmutableSet.Builder<String> b = ImmutableSet.builder(); b.addAll(o).addAll(context.requiredTags()); return ImmutableList.copyOf(b.build()); }); return new GroupInstance(of, instance); } }
package com.react_native_with_typescript_redux; import android.content.Intent; import com.facebook.react.ReactActivity; public class MainActivity extends ReactActivity { @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); MainApplication.getCallbackManager().onActivityResult(requestCode, resultCode, data); } /** * Returns the name of the main component registered from JavaScript. * This is used to schedule rendering of the component. */ @Override protected String getMainComponentName() { return "react_native_with_typescript_redux"; } }
/* * Copyright 2012-2020 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.loadbalancer.core; import java.util.List; import java.util.Random; import java.util.concurrent.atomic.AtomicInteger; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import reactor.core.publisher.Mono; import org.springframework.beans.factory.ObjectProvider; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.loadbalancer.reactive.DefaultResponse; import org.springframework.cloud.client.loadbalancer.reactive.EmptyResponse; import org.springframework.cloud.client.loadbalancer.reactive.Request; import org.springframework.cloud.client.loadbalancer.reactive.Response; /** * A Round-Robin-based implementation of {@link ReactorServiceInstanceLoadBalancer}. * * @author Spencer Gibb * @author Olga Maciaszek-Sharma */ public class RoundRobinLoadBalancer implements ReactorServiceInstanceLoadBalancer { private static final Log log = LogFactory.getLog(RoundRobinLoadBalancer.class); private final AtomicInteger position; @Deprecated private ObjectProvider<ServiceInstanceSupplier> serviceInstanceSupplier; private ObjectProvider<ServiceInstanceListSupplier> serviceInstanceListSupplierProvider; private final String serviceId; /** * @param serviceId id of the service for which to choose an instance * @param serviceInstanceSupplier a provider of {@link ServiceInstanceSupplier} that * will be used to get available instances * @deprecated Use {@link #RoundRobinLoadBalancer(ObjectProvider, String)}} instead. */ @Deprecated public RoundRobinLoadBalancer(String serviceId, ObjectProvider<ServiceInstanceSupplier> serviceInstanceSupplier) { this(serviceId, serviceInstanceSupplier, new Random().nextInt(1000)); } /** * @param serviceInstanceListSupplierProvider a provider of * {@link ServiceInstanceListSupplier} that will be used to get available instances * @param serviceId id of the service for which to choose an instance */ public RoundRobinLoadBalancer( ObjectProvider<ServiceInstanceListSupplier> serviceInstanceListSupplierProvider, String serviceId) { this(serviceInstanceListSupplierProvider, serviceId, new Random().nextInt(1000)); } /** * @param serviceInstanceListSupplierProvider a provider of * {@link ServiceInstanceListSupplier} that will be used to get available instances * @param serviceId id of the service for which to choose an instance * @param seedPosition Round Robin element position marker */ public RoundRobinLoadBalancer( ObjectProvider<ServiceInstanceListSupplier> serviceInstanceListSupplierProvider, String serviceId, int seedPosition) { this.serviceId = serviceId; this.serviceInstanceListSupplierProvider = serviceInstanceListSupplierProvider; this.position = new AtomicInteger(seedPosition); } /** * @param serviceId id of the service for which to choose an instance * @param serviceInstanceSupplier a provider of {@link ServiceInstanceSupplier} that * will be used to get available instances * @param seedPosition Round Robin element position marker * @deprecated Use {@link #RoundRobinLoadBalancer(ObjectProvider, String, int)}} * instead. */ @Deprecated public RoundRobinLoadBalancer(String serviceId, ObjectProvider<ServiceInstanceSupplier> serviceInstanceSupplier, int seedPosition) { this.serviceId = serviceId; this.serviceInstanceSupplier = serviceInstanceSupplier; this.position = new AtomicInteger(seedPosition); } @SuppressWarnings("rawtypes") @Override // see original // https://github.com/Netflix/ocelli/blob/master/ocelli-core/ // src/main/java/netflix/ocelli/loadbalancer/RoundRobinLoadBalancer.java public Mono<Response<ServiceInstance>> choose(Request request) { // TODO: move supplier to Request? // Temporary conditional logic till deprecated members are removed. if (serviceInstanceListSupplierProvider != null) { ServiceInstanceListSupplier supplier = serviceInstanceListSupplierProvider .getIfAvailable(NoopServiceInstanceListSupplier::new); return supplier.get().next().map(this::getInstanceResponse); } ServiceInstanceSupplier supplier = this.serviceInstanceSupplier .getIfAvailable(NoopServiceInstanceSupplier::new); return supplier.get().collectList().map(this::getInstanceResponse); } private Response<ServiceInstance> getInstanceResponse( List<ServiceInstance> instances) { if (instances.isEmpty()) { log.warn("No servers available for service: " + this.serviceId); return new EmptyResponse(); } // TODO: enforce order? int pos = Math.abs(this.position.incrementAndGet()); ServiceInstance instance = instances.get(pos % instances.size()); return new DefaultResponse(instance); } }
/* * Copyright 2016-2020 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.vault.authentication; import java.util.HashMap; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; import org.springframework.vault.authentication.AppRoleAuthenticationOptions.RoleId; import org.springframework.vault.authentication.AppRoleAuthenticationOptions.SecretId; import org.springframework.vault.authentication.AppRoleTokens.AbsentSecretId; import org.springframework.vault.authentication.AppRoleTokens.Provided; import org.springframework.vault.authentication.AppRoleTokens.Pull; import org.springframework.vault.authentication.AppRoleTokens.Wrapped; import org.springframework.vault.authentication.AuthenticationSteps.Node; import org.springframework.vault.client.VaultHttpHeaders; import org.springframework.vault.client.VaultResponses; import org.springframework.vault.support.VaultResponse; import org.springframework.vault.support.VaultToken; import org.springframework.web.client.HttpStatusCodeException; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestOperations; import static org.springframework.vault.authentication.AuthenticationSteps.HttpRequestBuilder.get; import static org.springframework.vault.authentication.AuthenticationSteps.HttpRequestBuilder.method; import static org.springframework.vault.authentication.AuthenticationSteps.HttpRequestBuilder.post; import static org.springframework.vault.authentication.AuthenticationUtil.getLoginPath; /** * AppRole implementation of {@link ClientAuthentication}. RoleId and SecretId (optional) * are sent in the login request to Vault to obtain a {@link VaultToken}. * <p> * {@link AppRoleAuthentication} can be configured for push and pull mode by setting * {@link AppRoleAuthenticationOptions#getSecretId()}. * * @author Mark Paluch * @author Vincent Le Nair * @author Christophe Tafani-Dereeper * @see AppRoleAuthenticationOptions * @see RestOperations * @see <a href="https://www.vaultproject.io/docs/auth/approle.html">Auth Backend: * AppRole</a> */ public class AppRoleAuthentication implements ClientAuthentication, AuthenticationStepsFactory { private static final Log logger = LogFactory.getLog(AppRoleAuthentication.class); private final AppRoleAuthenticationOptions options; private final RestOperations restOperations; /** * Create a {@link AppRoleAuthentication} using {@link AppRoleAuthenticationOptions} * and {@link RestOperations}. * @param options must not be {@literal null}. * @param restOperations must not be {@literal null}. */ public AppRoleAuthentication(AppRoleAuthenticationOptions options, RestOperations restOperations) { Assert.notNull(options, "AppRoleAuthenticationOptions must not be null"); Assert.notNull(restOperations, "RestOperations must not be null"); this.options = options; this.restOperations = restOperations; } /** * Creates a {@link AuthenticationSteps} for AppRole authentication given * {@link AppRoleAuthenticationOptions}. * @param options must not be {@literal null}. * @return {@link AuthenticationSteps} for AppRole authentication. * @since 2.0 */ public static AuthenticationSteps createAuthenticationSteps(AppRoleAuthenticationOptions options) { Assert.notNull(options, "AppRoleAuthenticationOptions must not be null"); RoleId roleId = options.getRoleId(); SecretId secretId = options.getSecretId(); return getAuthenticationSteps(options, roleId, secretId).login(getLoginPath(options.getPath())); } private static Node<Map<String, String>> getAuthenticationSteps(AppRoleAuthenticationOptions options, RoleId roleId, SecretId secretId) { Node<String> roleIdSteps = getRoleIdSteps(options, roleId); Node<String> secretIdSteps = getSecretIdSteps(options, secretId); return roleIdSteps.zipWith(secretIdSteps).map(it -> getAppRoleLoginBody(it.getLeft(), it.getRight())); } private static Node<String> getRoleIdSteps(AppRoleAuthenticationOptions options, RoleId roleId) { if (roleId instanceof Provided) { return AuthenticationSteps.fromSupplier(((Provided) roleId)::getValue); } if (roleId instanceof Pull) { HttpHeaders headers = createHttpHeaders(((Pull) roleId).getInitialToken()); return AuthenticationSteps .fromHttpRequest(get(getRoleIdIdPath(options)).with(headers).as(VaultResponse.class)) .map(vaultResponse -> (String) vaultResponse.getRequiredData().get("role_id")); } if (roleId instanceof Wrapped) { return unwrapResponse(options.getUnwrappingEndpoints(), ((Wrapped) roleId).getInitialToken()) .map(vaultResponse -> (String) vaultResponse.getRequiredData().get("role_id")); } throw new IllegalArgumentException("Unknown RoleId configuration: " + roleId); } private static Node<String> getSecretIdSteps(AppRoleAuthenticationOptions options, SecretId secretId) { if (secretId instanceof Provided) { return AuthenticationSteps.fromSupplier(((Provided) secretId)::getValue); } if (secretId instanceof Pull) { HttpHeaders headers = createHttpHeaders(((Pull) secretId).getInitialToken()); return AuthenticationSteps .fromHttpRequest(post(getSecretIdPath(options)).with(headers).as(VaultResponse.class)) .map(vaultResponse -> (String) vaultResponse.getRequiredData().get("secret_id")); } if (secretId instanceof Wrapped) { return unwrapResponse(options.getUnwrappingEndpoints(), ((Wrapped) secretId).getInitialToken()) .map(vaultResponse -> (String) vaultResponse.getRequiredData().get("secret_id")); } throw new IllegalArgumentException("Unknown SecretId configuration: " + secretId); } private static Node<VaultResponse> unwrapResponse(UnwrappingEndpoints unwrappingEndpoints, VaultToken token) { return AuthenticationSteps .fromHttpRequest(method(unwrappingEndpoints.getUnwrapRequestMethod(), unwrappingEndpoints.getPath()) .with(createHttpHeaders(token)).as(VaultResponse.class)) .map(unwrappingEndpoints::unwrap); } @Override public VaultToken login() { return createTokenUsingAppRole(); } @Override public AuthenticationSteps getAuthenticationSteps() { return createAuthenticationSteps(this.options); } private VaultToken createTokenUsingAppRole() { Map<String, String> login = getAppRoleLoginBody(this.options.getRoleId(), this.options.getSecretId()); try { VaultResponse response = this.restOperations.postForObject(getLoginPath(this.options.getPath()), login, VaultResponse.class); Assert.state(response != null && response.getAuth() != null, "Auth field must not be null"); logger.debug("Login successful using AppRole authentication"); return LoginTokenUtil.from(response.getAuth()); } catch (RestClientException e) { throw VaultLoginException.create("AppRole", e); } } private String getRoleId(RoleId roleId) throws VaultLoginException { if (roleId instanceof Provided) { return ((Provided) roleId).getValue(); } if (roleId instanceof Pull) { VaultToken token = ((Pull) roleId).getInitialToken(); try { ResponseEntity<VaultResponse> entity = this.restOperations.exchange(getRoleIdIdPath(this.options), HttpMethod.GET, createHttpEntity(token), VaultResponse.class); return (String) entity.getBody().getRequiredData().get("role_id"); } catch (HttpStatusCodeException e) { throw new VaultLoginException(String.format("Cannot get Role id using AppRole: %s", VaultResponses.getError(e.getResponseBodyAsString())), e); } } if (roleId instanceof Wrapped) { VaultToken token = ((Wrapped) roleId).getInitialToken(); try { UnwrappingEndpoints unwrappingEndpoints = this.options.getUnwrappingEndpoints(); ResponseEntity<VaultResponse> entity = this.restOperations.exchange(unwrappingEndpoints.getPath(), unwrappingEndpoints.getUnwrapRequestMethod(), createHttpEntity(token), VaultResponse.class); VaultResponse response = unwrappingEndpoints.unwrap(entity.getBody()); return (String) response.getRequiredData().get("role_id"); } catch (HttpStatusCodeException e) { throw new VaultLoginException(String.format("Cannot unwrap Role id using AppRole: %s", VaultResponses.getError(e.getResponseBodyAsString())), e); } } throw new IllegalArgumentException("Unknown RoleId configuration: " + roleId); } private String getSecretId(SecretId secretId) throws VaultLoginException { if (secretId instanceof Provided) { return ((Provided) secretId).getValue(); } if (secretId instanceof Pull) { VaultToken token = ((Pull) secretId).getInitialToken(); try { VaultResponse response = this.restOperations.postForObject(getSecretIdPath(this.options), createHttpEntity(token), VaultResponse.class); return (String) response.getRequiredData().get("secret_id"); } catch (HttpStatusCodeException e) { throw new VaultLoginException(String.format("Cannot get Secret id using AppRole: %s", VaultResponses.getError(e.getResponseBodyAsString())), e); } } if (secretId instanceof Wrapped) { VaultToken token = ((Wrapped) secretId).getInitialToken(); try { UnwrappingEndpoints unwrappingEndpoints = this.options.getUnwrappingEndpoints(); ResponseEntity<VaultResponse> entity = this.restOperations.exchange(unwrappingEndpoints.getPath(), unwrappingEndpoints.getUnwrapRequestMethod(), createHttpEntity(token), VaultResponse.class); VaultResponse response = unwrappingEndpoints.unwrap(entity.getBody()); return (String) response.getRequiredData().get("secret_id"); } catch (HttpStatusCodeException e) { throw new VaultLoginException(String.format("Cannot unwrap Role id using AppRole: %s", VaultResponses.getError(e.getResponseBodyAsString())), e); } } throw new IllegalArgumentException("Unknown SecretId configuration: " + secretId); } private static HttpHeaders createHttpHeaders(VaultToken token) { HttpHeaders headers = new HttpHeaders(); headers.set(VaultHttpHeaders.VAULT_TOKEN, token.getToken()); return headers; } private static HttpEntity<String> createHttpEntity(VaultToken token) { return new HttpEntity<String>(null, createHttpHeaders(token)); } private Map<String, String> getAppRoleLoginBody(RoleId roleId, SecretId secretId) { Map<String, String> login = new HashMap<>(); login.put("role_id", getRoleId(roleId)); if (!ClassUtils.isAssignableValue(AbsentSecretId.class, secretId)) { login.put("secret_id", getSecretId(secretId)); } return login; } private static Map<String, String> getAppRoleLoginBody(String roleId, @Nullable String secretId) { Map<String, String> login = new HashMap<>(); login.put("role_id", roleId); if (secretId != null) { login.put("secret_id", secretId); } return login; } private static String getSecretIdPath(AppRoleAuthenticationOptions options) { return String.format("auth/%s/role/%s/secret-id", options.getPath(), options.getAppRole()); } private static String getRoleIdIdPath(AppRoleAuthenticationOptions options) { return String.format("auth/%s/role/%s/role-id", options.getPath(), options.getAppRole()); } }
/*- * * * Copyright 2015 Skymind,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.deeplearning4j.models.embeddings.loader; import org.deeplearning4j.exception.DL4JInvalidInputException; import org.deeplearning4j.models.embeddings.learning.impl.elements.CBOW; import org.deeplearning4j.models.embeddings.learning.impl.elements.SkipGram; import org.deeplearning4j.models.word2vec.StaticWord2Vec; import org.deeplearning4j.text.tokenization.tokenizer.TokenPreProcess; import org.deeplearning4j.text.tokenization.tokenizerfactory.TokenizerFactory; import org.deeplearning4j.util.OneTimeLogger; import org.nd4j.compression.impl.NoOp; import org.nd4j.linalg.exception.ND4JIllegalStateException; import org.nd4j.shade.jackson.databind.DeserializationFeature; import org.nd4j.shade.jackson.databind.MapperFeature; import org.nd4j.shade.jackson.databind.ObjectMapper; import org.nd4j.shade.jackson.databind.SerializationFeature; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.NonNull; import org.apache.commons.codec.binary.Base64; import org.apache.commons.compress.compressors.gzip.GzipUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.io.LineIterator; import org.apache.commons.io.output.*; import org.deeplearning4j.berkeley.Pair; import org.deeplearning4j.models.embeddings.WeightLookupTable; import org.deeplearning4j.models.embeddings.inmemory.InMemoryLookupTable; import org.deeplearning4j.models.embeddings.reader.impl.BasicModelUtils; import org.deeplearning4j.models.embeddings.wordvectors.WordVectors; import org.deeplearning4j.models.embeddings.wordvectors.WordVectorsImpl; import org.deeplearning4j.models.glove.Glove; import org.deeplearning4j.models.paragraphvectors.ParagraphVectors; import org.deeplearning4j.models.sequencevectors.SequenceVectors; import org.deeplearning4j.models.sequencevectors.interfaces.SequenceElementFactory; import org.deeplearning4j.models.sequencevectors.sequence.SequenceElement; import org.deeplearning4j.models.sequencevectors.serialization.VocabWordFactory; import org.deeplearning4j.models.word2vec.VocabWord; import org.deeplearning4j.models.word2vec.Word2Vec; import org.deeplearning4j.models.word2vec.wordstore.VocabCache; import org.deeplearning4j.models.word2vec.wordstore.VocabularyHolder; import org.deeplearning4j.models.word2vec.wordstore.VocabularyWord; import org.deeplearning4j.models.word2vec.wordstore.inmemory.AbstractCache; import org.deeplearning4j.models.word2vec.wordstore.inmemory.InMemoryLookupCache; import org.deeplearning4j.text.documentiterator.LabelsSource; import org.deeplearning4j.text.sentenceiterator.BasicLineIterator; import org.nd4j.linalg.api.ndarray.INDArray; import org.nd4j.linalg.factory.Nd4j; import org.nd4j.linalg.ops.transforms.Transforms; import org.nd4j.storage.CompressedRamStorage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import java.util.zip.GZIPInputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipOutputStream; // FIXME: remove that /** * This is utility class, providing various methods for WordVectors serialization * * @author Adam Gibson * @author raver119 */ public class WordVectorSerializer { private static final boolean DEFAULT_LINEBREAKS = false; private static final boolean HAS_HEADER = true; private static final int MAX_SIZE = 50; private static final String whitespaceReplacement = "_Az92_"; private static final Logger log = LoggerFactory.getLogger(WordVectorSerializer.class); private WordVectorSerializer() {} /** * Loads the google model * * Deprecation note: Please, consider using readWord2VecModel() or loadStaticModel() method instead * * @param modelFile * the path to the google model * @param binary * read from binary file format (if set to true) or from text file format. * @return the loaded model * @throws IOException */ @Deprecated public static Word2Vec loadGoogleModel(File modelFile, boolean binary) throws IOException { return loadGoogleModel(modelFile, binary, DEFAULT_LINEBREAKS); } /** * Loads the Google model. * * Deprecation note: Please, consider using readWord2VecModel() or loadStaticModel() method instead * * @param modelFile * the input file * @param binary * read from binary or text file format * @param lineBreaks * if true, the input file is expected to terminate each line with a line break. This * is typically the case for files created with recent versions of Word2Vec, but not * for the downloadable model files. * @return a {@link Word2Vec} object * @throws IOException * @author Carsten Schnober */ @Deprecated public static Word2Vec loadGoogleModel(File modelFile, boolean binary, boolean lineBreaks) throws IOException { return binary ? readBinaryModel(modelFile, lineBreaks, true) : WordVectorSerializer.fromPair(loadTxt(modelFile)); } /** * * Loads the Google model without normalization being applied. * * PLEASE NOTE: Use this method only if you understand why you need not-normalized model. In all other cases please use loadGoogleModel() instead. * * Deprecation note: Please, consider using readWord2VecModel() or loadStaticModel() method instead * * @param modelFile * @param binary * @param lineBreaks * @return * @throws IOException */ @Deprecated public static WordVectors loadGoogleModelNonNormalized(File modelFile, boolean binary, boolean lineBreaks) throws IOException { return binary ? readBinaryModel(modelFile, lineBreaks, false) : WordVectorSerializer.fromPair(loadTxt(modelFile)); } /** * @param modelFile * @return * @throws FileNotFoundException * @throws IOException * @throws NumberFormatException */ private static Word2Vec readTextModel(File modelFile) throws IOException, NumberFormatException { InMemoryLookupTable lookupTable; VocabCache cache; INDArray syn0; Word2Vec ret = new Word2Vec(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(GzipUtils.isCompressedFilename(modelFile.getName()) ? new GZIPInputStream(new FileInputStream(modelFile)) : new FileInputStream(modelFile), "UTF-8"))) { String line = reader.readLine(); String[] initial = line.split(" "); int words = Integer.parseInt(initial[0]); int layerSize = Integer.parseInt(initial[1]); syn0 = Nd4j.create(words, layerSize); cache = new InMemoryLookupCache(false); int currLine = 0; while ((line = reader.readLine()) != null) { String[] split = line.split(" "); assert split.length == layerSize + 1; String word = split[0].replaceAll(whitespaceReplacement, " "); float[] vector = new float[split.length - 1]; for (int i = 1; i < split.length; i++) { vector[i - 1] = Float.parseFloat(split[i]); } syn0.putRow(currLine, Nd4j.create(vector)); cache.addWordToIndex(cache.numWords(), word); cache.addToken(new VocabWord(1, word)); cache.putVocabWord(word); currLine++; } lookupTable = (InMemoryLookupTable) new InMemoryLookupTable.Builder().cache(cache).vectorLength(layerSize) .build(); lookupTable.setSyn0(syn0); ret.setVocab(cache); ret.setLookupTable(lookupTable); } return ret; } /** * Read a binary word2vec file. * * @param modelFile * the File to read * @param linebreaks * if true, the reader expects each word/vector to be in a separate line, terminated * by a line break * @return a {@link Word2Vec model} * @throws NumberFormatException * @throws IOException * @throws FileNotFoundException */ private static Word2Vec readBinaryModel(File modelFile, boolean linebreaks, boolean normalize) throws NumberFormatException, IOException { InMemoryLookupTable<VocabWord> lookupTable; VocabCache<VocabWord> cache; INDArray syn0; int words, size; int originalFreq = Nd4j.getMemoryManager().getOccasionalGcFrequency(); boolean originalPeriodic = Nd4j.getMemoryManager().isPeriodicGcActive(); if (originalPeriodic) Nd4j.getMemoryManager().togglePeriodicGc(false); Nd4j.getMemoryManager().setOccasionalGcFrequency(50000); try (BufferedInputStream bis = new BufferedInputStream(GzipUtils.isCompressedFilename(modelFile.getName()) ? new GZIPInputStream(new FileInputStream(modelFile)) : new FileInputStream(modelFile)); DataInputStream dis = new DataInputStream(bis)) { words = Integer.parseInt(readString(dis)); size = Integer.parseInt(readString(dis)); syn0 = Nd4j.create(words, size); cache = new AbstractCache<>(); printOutProjectedMemoryUse(words, size, 1); lookupTable = (InMemoryLookupTable<VocabWord>) new InMemoryLookupTable.Builder<VocabWord>().cache(cache) .useHierarchicSoftmax(false).vectorLength(size).build(); String word; float[] vector = new float[size]; for (int i = 0; i < words; i++) { word = readString(dis); log.trace("Loading " + word + " with word " + i); for (int j = 0; j < size; j++) { vector[j] = readFloat(dis); } syn0.putRow(i, normalize ? Transforms.unitVec(Nd4j.create(vector)) : Nd4j.create(vector)); VocabWord vw = new VocabWord(1.0, word); vw.setIndex(cache.numWords()); cache.addToken(vw); cache.addWordToIndex(vw.getIndex(), vw.getLabel()); cache.putVocabWord(word); if (linebreaks) { dis.readByte(); // line break } Nd4j.getMemoryManager().invokeGcOccasionally(); } } finally { if (originalPeriodic) Nd4j.getMemoryManager().togglePeriodicGc(true); Nd4j.getMemoryManager().setOccasionalGcFrequency(originalFreq); } lookupTable.setSyn0(syn0); Word2Vec ret = new Word2Vec.Builder().useHierarchicSoftmax(false).resetModel(false).layerSize(syn0.columns()) .allowParallelTokenization(true).elementsLearningAlgorithm(new SkipGram<VocabWord>()) .learningRate(0.025).windowSize(5).workers(1).build(); ret.setVocab(cache); ret.setLookupTable(lookupTable); return ret; } /** * Read a float from a data input stream Credit to: * https://github.com/NLPchina/Word2VEC_java/blob/master/src/com/ansj/vec/Word2VEC.java * * @param is * @return * @throws IOException */ public static float readFloat(InputStream is) throws IOException { byte[] bytes = new byte[4]; is.read(bytes); return getFloat(bytes); } /** * Read a string from a data input stream Credit to: * https://github.com/NLPchina/Word2VEC_java/blob/master/src/com/ansj/vec/Word2VEC.java * * @param b * @return * @throws IOException */ public static float getFloat(byte[] b) { int accum = 0; accum = accum | (b[0] & 0xff) << 0; accum = accum | (b[1] & 0xff) << 8; accum = accum | (b[2] & 0xff) << 16; accum = accum | (b[3] & 0xff) << 24; return Float.intBitsToFloat(accum); } /** * Read a string from a data input stream Credit to: * https://github.com/NLPchina/Word2VEC_java/blob/master/src/com/ansj/vec/Word2VEC.java * * @param dis * @return * @throws IOException */ public static String readString(DataInputStream dis) throws IOException { byte[] bytes = new byte[MAX_SIZE]; byte b = dis.readByte(); int i = -1; StringBuilder sb = new StringBuilder(); while (b != 32 && b != 10) { i++; bytes[i] = b; b = dis.readByte(); if (i == 49) { sb.append(new String(bytes, "UTF-8")); i = -1; bytes = new byte[MAX_SIZE]; } } sb.append(new String(bytes, 0, i + 1, "UTF-8")); return sb.toString(); } /** * This mehod writes word vectors to the given path. * Please note: this method doesn't load whole vocab/lookupTable into memory, so it's able to process large vocabularies served over network. * * @param lookupTable * @param path * @param <T> */ public static <T extends SequenceElement> void writeWordVectors(WeightLookupTable<T> lookupTable, String path) throws IOException { try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(path))) { writeWordVectors(lookupTable, bos); } catch (Exception e) { throw new RuntimeException(e); } } /** * This mehod writes word vectors to the given file. * Please note: this method doesn't load whole vocab/lookupTable into memory, so it's able to process large vocabularies served over network. * * @param lookupTable * @param file * @param <T> */ public static <T extends SequenceElement> void writeWordVectors(WeightLookupTable<T> lookupTable, File file) throws IOException { try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file))) { writeWordVectors(lookupTable, bos); } catch (Exception e) { throw new RuntimeException(e); } } /** * This mehod writes word vectors to the given OutputStream. * Please note: this method doesn't load whole vocab/lookupTable into memory, so it's able to process large vocabularies served over network. * * @param lookupTable * @param stream * @param <T> * @throws IOException */ public static <T extends SequenceElement> void writeWordVectors(WeightLookupTable<T> lookupTable, OutputStream stream) throws IOException { VocabCache<T> vocabCache = lookupTable.getVocabCache(); PrintWriter writer = new PrintWriter(new OutputStreamWriter(stream, "UTF-8")); // saving header as "NUM_WORDS VECTOR_SIZE NUM_DOCS" String str = vocabCache.numWords() + " " + lookupTable.layerSize() + " " + vocabCache.totalNumberOfDocs(); log.debug("Saving header: {}", str); writer.println(str); // saving vocab content for (int x = 0; x < vocabCache.numWords(); x++) { T element = vocabCache.elementAtIndex(x); StringBuilder builder = new StringBuilder(); builder.append(encodeB64(element.getLabel())).append(" "); INDArray vec = lookupTable.vector(element.getLabel()); for (int i = 0; i < vec.length(); i++) { builder.append(vec.getDouble(i)); if (i < vec.length() - 1) builder.append(" "); } writer.println(builder.toString()); } writer.flush(); writer.close(); } /** * This method saves paragraph vectors to the given file. * * @param vectors * @param path */ @Deprecated public static void writeWordVectors(@NonNull ParagraphVectors vectors, @NonNull File path) { try (BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(path))) { writeWordVectors(vectors, fos); } catch (Exception e) { throw new RuntimeException(e); } } /** * This method saves paragraph vectors to the given path. * * @param vectors * @param path */ @Deprecated public static void writeWordVectors(@NonNull ParagraphVectors vectors, @NonNull String path) { try (BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(path))) { writeWordVectors(vectors, fos); } catch (Exception e) { throw new RuntimeException(e); } } /** * This method saves ParagraphVectors model into compressed zip file * * @param file */ public static void writeParagraphVectors(ParagraphVectors vectors, File file) { try (FileOutputStream fos = new FileOutputStream(file); BufferedOutputStream stream = new BufferedOutputStream(fos)) { writeParagraphVectors(vectors, stream); } catch (Exception e) { throw new RuntimeException(e); } } /** * This method saves ParagraphVectors model into compressed zip file located at path * * @param path */ public static void writeParagraphVectors(ParagraphVectors vectors, String path) { writeParagraphVectors(vectors, new File(path)); } /** * This method saves Word2Vec model into compressed zip file and sends it to output stream * PLEASE NOTE: This method saves FULL model, including syn0 AND syn1 * */ public static void writeWord2VecModel(Word2Vec vectors, File file) { try (FileOutputStream fos = new FileOutputStream(file); BufferedOutputStream stream = new BufferedOutputStream(fos)) { writeWord2VecModel(vectors, stream); } catch (Exception e) { throw new RuntimeException(e); } } /** * This method saves Word2Vec model into compressed zip file and sends it to output stream * PLEASE NOTE: This method saves FULL model, including syn0 AND syn1 * */ public static void writeWord2VecModel(Word2Vec vectors, String path) { writeWord2VecModel(vectors, new File(path)); } /** * This method saves Word2Vec model into compressed zip file and sends it to output stream * PLEASE NOTE: This method saves FULL model, including syn0 AND syn1 * */ public static void writeWord2VecModel(Word2Vec vectors, OutputStream stream) throws IOException { ZipOutputStream zipfile = new ZipOutputStream(new BufferedOutputStream(new CloseShieldOutputStream(stream))); ZipEntry syn0 = new ZipEntry("syn0.txt"); zipfile.putNextEntry(syn0); // writing out syn0 File tempFileSyn0 = File.createTempFile("word2vec", "0"); tempFileSyn0.deleteOnExit(); writeWordVectors(vectors.lookupTable(), tempFileSyn0); BufferedInputStream fis = new BufferedInputStream(new FileInputStream(tempFileSyn0)); writeEntry(fis, zipfile); fis.close(); // writing out syn1 File tempFileSyn1 = File.createTempFile("word2vec", "1"); tempFileSyn1.deleteOnExit(); INDArray syn1 = ((InMemoryLookupTable<VocabWord>) vectors.getLookupTable()).getSyn1(); if (syn1 != null) try (PrintWriter writer = new PrintWriter(new FileWriter(tempFileSyn1))) { for (int x = 0; x < syn1.rows(); x++) { INDArray row = syn1.getRow(x); StringBuilder builder = new StringBuilder(); for (int i = 0; i < row.length(); i++) { builder.append(row.getDouble(i)).append(" "); } writer.println(builder.toString().trim()); } } ZipEntry zSyn1 = new ZipEntry("syn1.txt"); zipfile.putNextEntry(zSyn1); fis = new BufferedInputStream(new FileInputStream(tempFileSyn1)); writeEntry(fis, zipfile); fis.close(); // writing out syn1 File tempFileSyn1Neg = File.createTempFile("word2vec", "n"); tempFileSyn1Neg.deleteOnExit(); INDArray syn1Neg = ((InMemoryLookupTable<VocabWord>) vectors.getLookupTable()).getSyn1Neg(); if (syn1Neg != null) try (PrintWriter writer = new PrintWriter(new FileWriter(tempFileSyn1Neg))) { for (int x = 0; x < syn1Neg.rows(); x++) { INDArray row = syn1Neg.getRow(x); StringBuilder builder = new StringBuilder(); for (int i = 0; i < row.length(); i++) { builder.append(row.getDouble(i)).append(" "); } writer.println(builder.toString().trim()); } } ZipEntry zSyn1Neg = new ZipEntry("syn1Neg.txt"); zipfile.putNextEntry(zSyn1Neg); fis = new BufferedInputStream(new FileInputStream(tempFileSyn1Neg)); writeEntry(fis, zipfile); fis.close(); File tempFileCodes = File.createTempFile("word2vec", "h"); tempFileCodes.deleteOnExit(); ZipEntry hC = new ZipEntry("codes.txt"); zipfile.putNextEntry(hC); // writing out huffman tree try (PrintWriter writer = new PrintWriter(new FileWriter(tempFileCodes))) { for (int i = 0; i < vectors.getVocab().numWords(); i++) { VocabWord word = vectors.getVocab().elementAtIndex(i); StringBuilder builder = new StringBuilder(encodeB64(word.getLabel())).append(" "); for (int code : word.getCodes()) { builder.append(code).append(" "); } writer.println(builder.toString().trim()); } } fis = new BufferedInputStream(new FileInputStream(tempFileCodes)); writeEntry(fis, zipfile); fis.close(); File tempFileHuffman = File.createTempFile("word2vec", "h"); tempFileHuffman.deleteOnExit(); ZipEntry hP = new ZipEntry("huffman.txt"); zipfile.putNextEntry(hP); // writing out huffman tree try (PrintWriter writer = new PrintWriter(new FileWriter(tempFileHuffman))) { for (int i = 0; i < vectors.getVocab().numWords(); i++) { VocabWord word = vectors.getVocab().elementAtIndex(i); StringBuilder builder = new StringBuilder(encodeB64(word.getLabel())).append(" "); for (int point : word.getPoints()) { builder.append(point).append(" "); } writer.println(builder.toString().trim()); } } fis = new BufferedInputStream(new FileInputStream(tempFileHuffman)); writeEntry(fis, zipfile); fis.close(); File tempFileFreqs = File.createTempFile("word2vec", "f"); tempFileFreqs.deleteOnExit(); ZipEntry hF = new ZipEntry("frequencies.txt"); zipfile.putNextEntry(hF); // writing out word frequencies try (PrintWriter writer = new PrintWriter(new FileWriter(tempFileFreqs))) { for (int i = 0; i < vectors.getVocab().numWords(); i++) { VocabWord word = vectors.getVocab().elementAtIndex(i); StringBuilder builder = new StringBuilder(encodeB64(word.getLabel())).append(" ") .append(word.getElementFrequency()).append(" ") .append(vectors.getVocab().docAppearedIn(word.getLabel())); writer.println(builder.toString().trim()); } } fis = new BufferedInputStream(new FileInputStream(tempFileFreqs)); writeEntry(fis, zipfile); fis.close(); ZipEntry config = new ZipEntry("config.json"); zipfile.putNextEntry(config); //log.info("Current config: {}", vectors.getConfiguration().toJson()); writeEntry(new ByteArrayInputStream(vectors.getConfiguration().toJson().getBytes()), zipfile); zipfile.flush(); zipfile.close(); try { tempFileCodes.delete(); tempFileFreqs.delete(); tempFileHuffman.delete(); tempFileSyn0.delete(); tempFileSyn1.delete(); tempFileSyn1Neg.delete(); } catch (Exception e) { // } } /** * This method saves ParagraphVectors model into compressed zip file and sends it to output stream */ public static void writeParagraphVectors(ParagraphVectors vectors, OutputStream stream) throws IOException { ZipOutputStream zipfile = new ZipOutputStream(new BufferedOutputStream(new CloseShieldOutputStream(stream))); ZipEntry syn0 = new ZipEntry("syn0.txt"); zipfile.putNextEntry(syn0); // writing out syn0 File tempFileSyn0 = File.createTempFile("paravec", "0"); tempFileSyn0.deleteOnExit(); writeWordVectors(vectors.lookupTable(), tempFileSyn0); BufferedInputStream fis = new BufferedInputStream(new FileInputStream(tempFileSyn0)); writeEntry(fis, zipfile); fis.close(); // writing out syn1 File tempFileSyn1 = File.createTempFile("paravec", "1"); tempFileSyn1.deleteOnExit(); INDArray syn1 = ((InMemoryLookupTable<VocabWord>) vectors.getLookupTable()).getSyn1(); if (syn1 != null) try (PrintWriter writer = new PrintWriter(new FileWriter(tempFileSyn1))) { for (int x = 0; x < syn1.rows(); x++) { INDArray row = syn1.getRow(x); StringBuilder builder = new StringBuilder(); for (int i = 0; i < row.length(); i++) { builder.append(row.getDouble(i)).append(" "); } writer.println(builder.toString().trim()); } } ZipEntry zSyn1 = new ZipEntry("syn1.txt"); zipfile.putNextEntry(zSyn1); fis = new BufferedInputStream(new FileInputStream(tempFileSyn1)); writeEntry(fis, zipfile); fis.close(); File tempFileCodes = File.createTempFile("paravec", "h"); tempFileCodes.deleteOnExit(); ZipEntry hC = new ZipEntry("codes.txt"); zipfile.putNextEntry(hC); // writing out huffman tree try (PrintWriter writer = new PrintWriter(new FileWriter(tempFileCodes))) { for (int i = 0; i < vectors.getVocab().numWords(); i++) { VocabWord word = vectors.getVocab().elementAtIndex(i); StringBuilder builder = new StringBuilder(encodeB64(word.getLabel())).append(" "); for (int code : word.getCodes()) { builder.append(code).append(" "); } writer.println(builder.toString().trim()); } } fis = new BufferedInputStream(new FileInputStream(tempFileCodes)); writeEntry(fis, zipfile); fis.close(); File tempFileHuffman = File.createTempFile("paravec", "h"); tempFileHuffman.deleteOnExit(); ZipEntry hP = new ZipEntry("huffman.txt"); zipfile.putNextEntry(hP); // writing out huffman tree try (PrintWriter writer = new PrintWriter(new FileWriter(tempFileHuffman))) { for (int i = 0; i < vectors.getVocab().numWords(); i++) { VocabWord word = vectors.getVocab().elementAtIndex(i); StringBuilder builder = new StringBuilder(encodeB64(word.getLabel())).append(" "); for (int point : word.getPoints()) { builder.append(point).append(" "); } writer.println(builder.toString().trim()); } } fis = new BufferedInputStream(new FileInputStream(tempFileHuffman)); writeEntry(fis, zipfile); fis.close(); ZipEntry config = new ZipEntry("config.json"); zipfile.putNextEntry(config); writeEntry(new ByteArrayInputStream(vectors.getConfiguration().toJson().getBytes()), zipfile); ZipEntry labels = new ZipEntry("labels.txt"); zipfile.putNextEntry(labels); StringBuilder builder = new StringBuilder(); for (VocabWord word : vectors.getVocab().tokens()) { if (word.isLabel()) builder.append(encodeB64(word.getLabel())).append("\n"); } writeEntry(new ByteArrayInputStream(builder.toString().trim().getBytes()), zipfile); ZipEntry hF = new ZipEntry("frequencies.txt"); zipfile.putNextEntry(hF); File tempFileFreqs = File.createTempFile("paravec", "h"); tempFileFreqs.deleteOnExit(); // writing out word frequencies try (PrintWriter writer = new PrintWriter(new FileWriter(tempFileFreqs))) { for (int i = 0; i < vectors.getVocab().numWords(); i++) { VocabWord word = vectors.getVocab().elementAtIndex(i); builder = new StringBuilder(encodeB64(word.getLabel())).append(" ").append(word.getElementFrequency()) .append(" ").append(vectors.getVocab().docAppearedIn(word.getLabel())); writer.println(builder.toString().trim()); } } fis = new BufferedInputStream(new FileInputStream(tempFileFreqs)); writeEntry(fis, zipfile); fis.close(); zipfile.flush(); zipfile.close(); } /** * This method restores ParagraphVectors model previously saved with writeParagraphVectors() * * @return */ public static ParagraphVectors readParagraphVectors(String path) throws IOException { return readParagraphVectors(new File(path)); } /** * This method restores ParagraphVectors model previously saved with writeParagraphVectors() * * @return */ public static ParagraphVectors readParagraphVectors(File file) throws IOException { File tmpFileL = File.createTempFile("paravec", "l"); tmpFileL.deleteOnExit(); Word2Vec w2v = readWord2Vec(file); // and "convert" it to ParaVec model + optionally trying to restore labels information ParagraphVectors vectors = new ParagraphVectors.Builder(w2v.getConfiguration()).vocabCache(w2v.getVocab()) .lookupTable(w2v.getLookupTable()).resetModel(false).build(); ZipFile zipFile = new ZipFile(file); // now we try to restore labels information ZipEntry labels = zipFile.getEntry("labels.txt"); if (labels != null) { InputStream stream = zipFile.getInputStream(labels); Files.copy(stream, Paths.get(tmpFileL.getAbsolutePath()), StandardCopyOption.REPLACE_EXISTING); try (BufferedReader reader = new BufferedReader(new FileReader(tmpFileL))) { String line; while ((line = reader.readLine()) != null) { VocabWord word = vectors.getVocab().tokenFor(decodeB64(line.trim())); if (word != null) { word.markAsLabel(true); } } } } vectors.extractLabels(); return vectors; } /** * This method restores Word2Vec model previously saved with writeWord2VecModel * * PLEASE NOTE: This method loads FULL model, so don't use it if you're only going to use weights. * * @param file * @return * @throws IOException */ @Deprecated public static Word2Vec readWord2Vec(File file) throws IOException { File tmpFileSyn0 = File.createTempFile("word2vec", "0"); File tmpFileSyn1 = File.createTempFile("word2vec", "1"); File tmpFileC = File.createTempFile("word2vec", "c"); File tmpFileH = File.createTempFile("word2vec", "h"); File tmpFileF = File.createTempFile("word2vec", "f"); tmpFileSyn0.deleteOnExit(); tmpFileSyn1.deleteOnExit(); tmpFileH.deleteOnExit(); tmpFileC.deleteOnExit(); tmpFileF.deleteOnExit(); int originalFreq = Nd4j.getMemoryManager().getOccasionalGcFrequency(); boolean originalPeriodic = Nd4j.getMemoryManager().isPeriodicGcActive(); if (originalPeriodic) Nd4j.getMemoryManager().togglePeriodicGc(false); Nd4j.getMemoryManager().setOccasionalGcFrequency(50000); try { ZipFile zipFile = new ZipFile(file); ZipEntry syn0 = zipFile.getEntry("syn0.txt"); InputStream stream = zipFile.getInputStream(syn0); Files.copy(stream, Paths.get(tmpFileSyn0.getAbsolutePath()), StandardCopyOption.REPLACE_EXISTING); ZipEntry syn1 = zipFile.getEntry("syn1.txt"); stream = zipFile.getInputStream(syn1); Files.copy(stream, Paths.get(tmpFileSyn1.getAbsolutePath()), StandardCopyOption.REPLACE_EXISTING); ZipEntry codes = zipFile.getEntry("codes.txt"); stream = zipFile.getInputStream(codes); Files.copy(stream, Paths.get(tmpFileC.getAbsolutePath()), StandardCopyOption.REPLACE_EXISTING); ZipEntry huffman = zipFile.getEntry("huffman.txt"); stream = zipFile.getInputStream(huffman); Files.copy(stream, Paths.get(tmpFileH.getAbsolutePath()), StandardCopyOption.REPLACE_EXISTING); ZipEntry config = zipFile.getEntry("config.json"); stream = zipFile.getInputStream(config); StringBuilder builder = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream))) { String line; while ((line = reader.readLine()) != null) { builder.append(line); } } VectorsConfiguration configuration = VectorsConfiguration.fromJson(builder.toString().trim()); // we read first 4 files as w2v model Word2Vec w2v = readWord2VecFromText(tmpFileSyn0, tmpFileSyn1, tmpFileC, tmpFileH, configuration); // we read frequencies from frequencies.txt, however it's possible that we might not have this file ZipEntry frequencies = zipFile.getEntry("frequencies.txt"); if (frequencies != null) { stream = zipFile.getInputStream(frequencies); try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream))) { String line; while ((line = reader.readLine()) != null) { String[] split = line.split(" "); VocabWord word = w2v.getVocab().tokenFor(decodeB64(split[0])); word.setElementFrequency((long) Double.parseDouble(split[1])); word.setSequencesCount((long) Double.parseDouble(split[2])); } } } ZipEntry zsyn1Neg = zipFile.getEntry("syn1Neg.txt"); if (zsyn1Neg != null) { stream = zipFile.getInputStream(zsyn1Neg); try (InputStreamReader isr = new InputStreamReader(stream); BufferedReader reader = new BufferedReader(isr)) { String line = null; List<INDArray> rows = new ArrayList<>(); while ((line = reader.readLine()) != null) { String[] split = line.split(" "); double array[] = new double[split.length]; for (int i = 0; i < split.length; i++) { array[i] = Double.parseDouble(split[i]); } rows.add(Nd4j.create(array)); } // it's possible to have full model without syn1Neg if (rows.size() > 0) { INDArray syn1Neg = Nd4j.vstack(rows); ((InMemoryLookupTable) w2v.getLookupTable()).setSyn1Neg(syn1Neg); } } } return w2v; } finally { if (originalPeriodic) Nd4j.getMemoryManager().togglePeriodicGc(true); Nd4j.getMemoryManager().setOccasionalGcFrequency(originalFreq); } } /** * This method restores ParagraphVectors model previously saved with writeParagraphVectors() * * @return */ public static ParagraphVectors readParagraphVectors(InputStream stream) throws IOException { File tmpFile = File.createTempFile("restore", "paravec"); Files.copy(stream, Paths.get(tmpFile.getAbsolutePath()), StandardCopyOption.REPLACE_EXISTING); return readParagraphVectors(tmpFile); } private static void writeEntry(InputStream inputStream, ZipOutputStream zipStream) throws IOException { byte[] bytes = new byte[1024]; int bytesRead; while ((bytesRead = inputStream.read(bytes)) != -1) { zipStream.write(bytes, 0, bytesRead); } } /** * This method allows you to read ParagraphVectors from externaly originated vectors and syn1. * So, technically this method is compatible with any other w2v implementation * * @param vectors text file with words and their wieghts, aka Syn0 * @param hs text file HS layers, aka Syn1 * @param h_codes text file with Huffman tree codes * @param h_points text file with Huffman tree points * @return */ public static Word2Vec readWord2VecFromText(@NonNull File vectors, @NonNull File hs, @NonNull File h_codes, @NonNull File h_points, @NonNull VectorsConfiguration configuration) throws IOException { // first we load syn0 Pair<InMemoryLookupTable, VocabCache> pair = loadTxt(vectors); InMemoryLookupTable lookupTable = pair.getFirst(); lookupTable.setNegative(configuration.getNegative()); if (configuration.getNegative() > 0) lookupTable.initNegative(); VocabCache<VocabWord> vocab = (VocabCache<VocabWord>) pair.getSecond(); // now we load syn1 BufferedReader reader = new BufferedReader(new FileReader(hs)); String line = null; List<INDArray> rows = new ArrayList<>(); while ((line = reader.readLine()) != null) { String[] split = line.split(" "); double array[] = new double[split.length]; for (int i = 0; i < split.length; i++) { array[i] = Double.parseDouble(split[i]); } rows.add(Nd4j.create(array)); } reader.close(); // it's possible to have full model without syn1 if (rows.size() > 0) { INDArray syn1 = Nd4j.vstack(rows); lookupTable.setSyn1(syn1); } // now we transform mappings into huffman tree points reader = new BufferedReader(new FileReader(h_points)); while ((line = reader.readLine()) != null) { String[] split = line.split(" "); VocabWord word = vocab.wordFor(decodeB64(split[0])); List<Integer> points = new ArrayList<>(); for (int i = 1; i < split.length; i++) { points.add(Integer.parseInt(split[i])); } word.setPoints(points); } reader.close(); // now we transform mappings into huffman tree codes reader = new BufferedReader(new FileReader(h_codes)); while ((line = reader.readLine()) != null) { String[] split = line.split(" "); VocabWord word = vocab.wordFor(decodeB64(split[0])); List<Byte> codes = new ArrayList<>(); for (int i = 1; i < split.length; i++) { codes.add(Byte.parseByte(split[i])); } word.setCodes(codes); word.setCodeLength((short) codes.size()); } reader.close(); Word2Vec.Builder builder = new Word2Vec.Builder(configuration).vocabCache(vocab).lookupTable(lookupTable) .resetModel(false); TokenizerFactory factory = getTokenizerFactory(configuration); if (factory != null) builder.tokenizerFactory(factory); Word2Vec w2v = builder.build(); return w2v; } /** * Restores previously serialized ParagraphVectors model * * Deprecation note: Please, consider using readParagraphVectors() method instead * * @param path Path to file that contains previously serialized model * @return */ @Deprecated public static ParagraphVectors readParagraphVectorsFromText(@NonNull String path) { return readParagraphVectorsFromText(new File(path)); } /** * Restores previously serialized ParagraphVectors model * * Deprecation note: Please, consider using readParagraphVectors() method instead * * @param file File that contains previously serialized model * @return */ @Deprecated public static ParagraphVectors readParagraphVectorsFromText(@NonNull File file) { try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) { return readParagraphVectorsFromText(bis); } catch (Exception e) { throw new RuntimeException(e); } } /** * Restores previously serialized ParagraphVectors model * * Deprecation note: Please, consider using readParagraphVectors() method instead * * @param stream InputStream that contains previously serialized model * @return */ @Deprecated public static ParagraphVectors readParagraphVectorsFromText(@NonNull InputStream stream) { try { BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8")); ArrayList<String> labels = new ArrayList<>(); ArrayList<INDArray> arrays = new ArrayList<>(); VocabCache<VocabWord> vocabCache = new AbstractCache.Builder<VocabWord>().build(); String line = ""; while ((line = reader.readLine()) != null) { String[] split = line.split(" "); split[1] = split[1].replaceAll(whitespaceReplacement, " "); VocabWord word = new VocabWord(1.0, split[1]); if (split[0].equals("L")) { // we have label element here word.setSpecial(true); word.markAsLabel(true); labels.add(word.getLabel()); } else if (split[0].equals("E")) { // we have usual element, aka word here word.setSpecial(false); word.markAsLabel(false); } else throw new IllegalStateException( "Source stream doesn't looks like ParagraphVectors serialized model"); // this particular line is just for backward compatibility with InMemoryLookupCache word.setIndex(vocabCache.numWords()); vocabCache.addToken(word); vocabCache.addWordToIndex(word.getIndex(), word.getLabel()); // backward compatibility code vocabCache.putVocabWord(word.getLabel()); float[] vector = new float[split.length - 2]; for (int i = 2; i < split.length; i++) { vector[i - 2] = Float.parseFloat(split[i]); } INDArray row = Nd4j.create(vector); arrays.add(row); } // now we create syn0 matrix, using previously fetched rows /*INDArray syn = Nd4j.create(new int[]{arrays.size(), arrays.get(0).columns()}); for (int i = 0; i < syn.rows(); i++) { syn.putRow(i, arrays.get(i)); }*/ INDArray syn = Nd4j.vstack(arrays); InMemoryLookupTable<VocabWord> lookupTable = (InMemoryLookupTable<VocabWord>) new InMemoryLookupTable.Builder<VocabWord>() .vectorLength(arrays.get(0).columns()).useAdaGrad(false).cache(vocabCache) .build(); Nd4j.clearNans(syn); lookupTable.setSyn0(syn); LabelsSource source = new LabelsSource(labels); ParagraphVectors vectors = new ParagraphVectors.Builder().labelsSource(source).vocabCache(vocabCache) .lookupTable(lookupTable).modelUtils(new BasicModelUtils<VocabWord>()).build(); try { reader.close(); } catch (Exception e) { } vectors.extractLabels(); return vectors; } catch (Exception e) { throw new RuntimeException(e); } } /** * This method saves GloVe model to the given output stream. * * @param vectors GloVe model to be saved * @param file path where model should be saved to */ public static void writeWordVectors(@NonNull Glove vectors, @NonNull File file) { try (BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(file))) { writeWordVectors(vectors, fos); } catch (Exception e) { throw new RuntimeException(e); } } /** * This method saves GloVe model to the given output stream. * * @param vectors GloVe model to be saved * @param path path where model should be saved to */ public static void writeWordVectors(@NonNull Glove vectors, @NonNull String path) { try (BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(path))) { writeWordVectors(vectors, fos); } catch (Exception e) { throw new RuntimeException(e); } } /** * This method saves GloVe model to the given OutputStream * * @param vectors GloVe model to be saved * @param stream OutputStream where model should be saved to */ public static void writeWordVectors(@NonNull Glove vectors, @NonNull OutputStream stream) { try { writeWordVectors(vectors.lookupTable(), stream); } catch (Exception e) { throw new RuntimeException(e); } } /** * This method saves paragraph vectors to the given output stream. * * @param vectors * @param stream */ @Deprecated public static void writeWordVectors(ParagraphVectors vectors, OutputStream stream) { try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stream, "UTF-8"))) { /* This method acts similary to w2v csv serialization, except of additional tag for labels */ VocabCache<VocabWord> vocabCache = vectors.getVocab(); for (VocabWord word : vocabCache.vocabWords()) { StringBuilder builder = new StringBuilder(); builder.append(word.isLabel() ? "L" : "E").append(" "); builder.append(word.getLabel().replaceAll(" ", whitespaceReplacement)).append(" "); INDArray vector = vectors.getWordVectorMatrix(word.getLabel()); for (int j = 0; j < vector.length(); j++) { builder.append(vector.getDouble(j)); if (j < vector.length() - 1) { builder.append(" "); } } writer.write(builder.append("\n").toString()); } writer.flush(); writer.close(); } catch (Exception e) { throw new RuntimeException(e); } } /** * Writes the word vectors to the given path. Note that this assumes an in memory cache * * @param lookupTable * @param cache * * @param path * the path to write * @throws IOException */ @Deprecated public static void writeWordVectors(InMemoryLookupTable lookupTable, InMemoryLookupCache cache, String path) throws IOException { BufferedWriter write = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(new File(path), false), "UTF-8")); for (int i = 0; i < lookupTable.getSyn0().rows(); i++) { String word = cache.wordAtIndex(i); if (word == null) { continue; } StringBuilder sb = new StringBuilder(); sb.append(word.replaceAll(" ", whitespaceReplacement)); sb.append(" "); INDArray wordVector = lookupTable.vector(word); for (int j = 0; j < wordVector.length(); j++) { sb.append(wordVector.getDouble(j)); if (j < wordVector.length() - 1) { sb.append(" "); } } sb.append("\n"); write.write(sb.toString()); } write.flush(); write.close(); } private static ObjectMapper getModelMapper() { ObjectMapper ret = new ObjectMapper(); ret.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); ret.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); ret.configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true); ret.enable(SerializationFeature.INDENT_OUTPUT); return ret; } /** * Saves full Word2Vec model in the way, that allows model updates without being rebuilt from scratches * * Deprecation note: Please, consider using writeWord2VecModel() method instead * * @param vec - The Word2Vec instance to be saved * @param path - the path for json to be saved */ @Deprecated public static void writeFullModel(@NonNull Word2Vec vec, @NonNull String path) { /* Basically we need to save: 1. WeightLookupTable, especially syn0 and syn1 matrices 2. VocabCache, including only WordCounts 3. Settings from Word2Vect model: workers, layers, etc. */ PrintWriter printWriter = null; try { printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(path), "UTF-8")); } catch (Exception e) { throw new RuntimeException(e); } WeightLookupTable<VocabWord> lookupTable = vec.getLookupTable(); VocabCache<VocabWord> vocabCache = vec.getVocab(); // ((InMemoryLookupTable) lookupTable).getVocab(); //vec.getVocab(); if (!(lookupTable instanceof InMemoryLookupTable)) throw new IllegalStateException("At this moment only InMemoryLookupTable is supported."); VectorsConfiguration conf = vec.getConfiguration(); conf.setVocabSize(vocabCache.numWords()); printWriter.println(conf.toJson()); //log.info("Word2Vec conf. JSON: " + conf.toJson()); /* We have the following map: Line 0 - VectorsConfiguration JSON string Line 1 - expTable Line 2 - table All following lines are vocab/weight lookup table saved line by line as VocabularyWord JSON representation */ // actually we don't need expTable, since it produces exact results on subsequent runs untill you dont modify expTable size :) // saving ExpTable just for "special case in future" StringBuilder builder = new StringBuilder(); for (int x = 0; x < ((InMemoryLookupTable) lookupTable).getExpTable().length; x++) { builder.append(((InMemoryLookupTable) lookupTable).getExpTable()[x]).append(" "); } printWriter.println(builder.toString().trim()); // saving table, available only if negative sampling is used if (conf.getNegative() > 0 && ((InMemoryLookupTable) lookupTable).getTable() != null) { builder = new StringBuilder(); for (int x = 0; x < ((InMemoryLookupTable) lookupTable).getTable().columns(); x++) { builder.append(((InMemoryLookupTable) lookupTable).getTable().getDouble(x)).append(" "); } printWriter.println(builder.toString().trim()); } else printWriter.println(""); List<VocabWord> words = new ArrayList<>(vocabCache.vocabWords()); for (SequenceElement word : words) { VocabularyWord vw = new VocabularyWord(word.getLabel()); vw.setCount(vocabCache.wordFrequency(word.getLabel())); vw.setHuffmanNode(VocabularyHolder.buildNode(word.getCodes(), word.getPoints(), word.getCodeLength(), word.getIndex())); // writing down syn0 INDArray syn0 = ((InMemoryLookupTable) lookupTable).getSyn0().getRow(vocabCache.indexOf(word.getLabel())); double[] dsyn0 = new double[syn0.columns()]; for (int x = 0; x < conf.getLayersSize(); x++) { dsyn0[x] = syn0.getDouble(x); } vw.setSyn0(dsyn0); // writing down syn1 INDArray syn1 = ((InMemoryLookupTable) lookupTable).getSyn1().getRow(vocabCache.indexOf(word.getLabel())); double[] dsyn1 = new double[syn1.columns()]; for (int x = 0; x < syn1.columns(); x++) { dsyn1[x] = syn1.getDouble(x); } vw.setSyn1(dsyn1); // writing down syn1Neg, if negative sampling is used if (conf.getNegative() > 0 && ((InMemoryLookupTable) lookupTable).getSyn1Neg() != null) { INDArray syn1Neg = ((InMemoryLookupTable) lookupTable).getSyn1Neg() .getRow(vocabCache.indexOf(word.getLabel())); double[] dsyn1Neg = new double[syn1Neg.columns()]; for (int x = 0; x < syn1Neg.columns(); x++) { dsyn1Neg[x] = syn1Neg.getDouble(x); } vw.setSyn1Neg(dsyn1Neg); } // in case of UseAdaGrad == true - we should save gradients for each word in vocab if (conf.isUseAdaGrad() && ((InMemoryLookupTable) lookupTable).isUseAdaGrad()) { INDArray gradient = word.getHistoricalGradient(); if (gradient == null) gradient = Nd4j.zeros(word.getCodes().size()); double ada[] = new double[gradient.columns()]; for (int x = 0; x < gradient.columns(); x++) { ada[x] = gradient.getDouble(x); } vw.setHistoricalGradient(ada); } printWriter.println(vw.toJson()); } // at this moment we have whole vocab serialized printWriter.flush(); printWriter.close(); } /** * This method loads full w2v model, previously saved with writeFullMethod call * * Deprecation note: Please, consider using readWord2VecModel() or loadStaticModel() method instead * * @param path - path to previously stored w2v json model * @return - Word2Vec instance */ @Deprecated public static Word2Vec loadFullModel(@NonNull String path) throws FileNotFoundException { /* // TODO: implementation is in process We need to restore: 1. WeightLookupTable, including syn0 and syn1 matrices 2. VocabCache + mark it as SPECIAL, to avoid accidental word removals */ BasicLineIterator iterator = new BasicLineIterator(new File(path)); // first 3 lines should be processed separately String confJson = iterator.nextSentence(); log.info("Word2Vec conf. JSON: " + confJson); VectorsConfiguration configuration = VectorsConfiguration.fromJson(confJson); // actually we dont need expTable, since it produces exact results on subsequent runs untill you dont modify expTable size :) String eTable = iterator.nextSentence(); double[] expTable; String nTable = iterator.nextSentence(); if (configuration.getNegative() > 0) { // TODO: we probably should parse negTable, but it's not required until vocab changes are introduced. Since on the predefined vocab it will produce exact nTable, the same goes for expTable btw. } /* Since we're restoring vocab from previously serialized model, we can expect minWordFrequency appliance in its vocabulary, so it should NOT be truncated. That's why i'm setting minWordFrequency to configuration value, but applying SPECIAL to each word, to avoid truncation */ VocabularyHolder holder = new VocabularyHolder.Builder().minWordFrequency(configuration.getMinWordFrequency()) .hugeModelExpected(configuration.isHugeModelExpected()) .scavengerActivationThreshold(configuration.getScavengerActivationThreshold()) .scavengerRetentionDelay(configuration.getScavengerRetentionDelay()).build(); AtomicInteger counter = new AtomicInteger(0); AbstractCache<VocabWord> vocabCache = new AbstractCache.Builder<VocabWord>().build(); while (iterator.hasNext()) { // log.info("got line: " + iterator.nextSentence()); String wordJson = iterator.nextSentence(); VocabularyWord word = VocabularyWord.fromJson(wordJson); word.setSpecial(true); VocabWord vw = new VocabWord(word.getCount(), word.getWord()); vw.setIndex(counter.getAndIncrement()); vw.setIndex(word.getHuffmanNode().getIdx()); vw.setCodeLength(word.getHuffmanNode().getLength()); vw.setPoints(arrayToList(word.getHuffmanNode().getPoint(), word.getHuffmanNode().getLength())); vw.setCodes(arrayToList(word.getHuffmanNode().getCode(), word.getHuffmanNode().getLength())); vocabCache.addToken(vw); vocabCache.addWordToIndex(vw.getIndex(), vw.getLabel()); vocabCache.putVocabWord(vw.getWord()); } // at this moment vocab is restored, and it's time to rebuild Huffman tree // since word counters are equal, huffman tree will be equal too //holder.updateHuffmanCodes(); // we definitely don't need UNK word in this scenarion // holder.transferBackToVocabCache(vocabCache, false); // now, it's time to transfer syn0/syn1/syn1 neg values InMemoryLookupTable lookupTable = (InMemoryLookupTable) new InMemoryLookupTable.Builder().negative(configuration.getNegative()) .useAdaGrad(configuration.isUseAdaGrad()).lr(configuration.getLearningRate()) .cache(vocabCache).vectorLength(configuration.getLayersSize()).build(); // we create all arrays lookupTable.resetWeights(true); iterator.reset(); // we should skip 3 lines from file iterator.nextSentence(); iterator.nextSentence(); iterator.nextSentence(); // now, for each word from vocabHolder we'll just transfer actual values while (iterator.hasNext()) { String wordJson = iterator.nextSentence(); VocabularyWord word = VocabularyWord.fromJson(wordJson); // syn0 transfer INDArray syn0 = lookupTable.getSyn0().getRow(vocabCache.indexOf(word.getWord())); syn0.assign(Nd4j.create(word.getSyn0())); // syn1 transfer // syn1 values are being accessed via tree points, but since our goal is just deserialization - we can just push it row by row INDArray syn1 = lookupTable.getSyn1().getRow(vocabCache.indexOf(word.getWord())); syn1.assign(Nd4j.create(word.getSyn1())); // syn1Neg transfer if (configuration.getNegative() > 0) { INDArray syn1Neg = lookupTable.getSyn1Neg().getRow(vocabCache.indexOf(word.getWord())); syn1Neg.assign(Nd4j.create(word.getSyn1Neg())); } } Word2Vec vec = new Word2Vec.Builder(configuration).vocabCache(vocabCache).lookupTable(lookupTable) .resetModel(false).build(); vec.setModelUtils(new BasicModelUtils()); return vec; } /** * Writes the word vectors to the given path. Note that this assumes an in memory cache * * @param vec * the word2vec to write * @param path * the path to write * @throws IOException */ @Deprecated public static void writeWordVectors(@NonNull Word2Vec vec, @NonNull String path) throws IOException { BufferedWriter write = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(new File(path), false), "UTF-8")); writeWordVectors(vec, write); write.flush(); write.close(); } /** * Writes the word vectors to the given path. Note that this assumes an in memory cache * * @param vec * the word2vec to write * @param file * the file to write * @throws IOException */ @Deprecated public static void writeWordVectors(@NonNull Word2Vec vec, @NonNull File file) throws IOException { BufferedWriter write = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8")); writeWordVectors(vec, write); write.flush(); write.close(); } /** * Writes the word vectors to the given OutputStream. Note that this assumes an in memory cache. * * @param vec * the word2vec to write * @param outputStream - OutputStream, where all data should be sent to * the path to write * @throws IOException */ @Deprecated public static void writeWordVectors(@NonNull Word2Vec vec, @NonNull OutputStream outputStream) throws IOException { BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8")); writeWordVectors(vec, writer); writer.flush(); writer.close(); } /** * Writes the word vectors to the given BufferedWriter. Note that this assumes an in memory cache. * BufferedWriter can be writer to local file, or hdfs file, or any compatible to java target. * * @param vec * the word2vec to write * @param writer - BufferedWriter, where all data should be written to * the path to write * @throws IOException */ @Deprecated public static void writeWordVectors(@NonNull Word2Vec vec, @NonNull BufferedWriter writer) throws IOException { int words = 0; String str = vec.getVocab().numWords() + " " + vec.getLayerSize() + " " + vec.getVocab().totalNumberOfDocs(); log.debug("Saving header: {}", str); writer.write(str + "\n"); for (String word : vec.vocab().words()) { if (word == null) { continue; } StringBuilder sb = new StringBuilder(); sb.append(word.replaceAll(" ", whitespaceReplacement)); sb.append(" "); INDArray wordVector = vec.getWordVectorMatrix(word); for (int j = 0; j < wordVector.length(); j++) { sb.append(wordVector.getDouble(j)); if (j < wordVector.length() - 1) { sb.append(" "); } } sb.append("\n"); writer.write(sb.toString()); words++; } try { writer.flush(); } catch (Exception e) { } log.info("Wrote " + words + " with size of " + vec.lookupTable().layerSize()); } /** * Load word vectors for the given vocab and table * * @param table * the weights to use * @param vocab * the vocab to use * @return wordvectors based on the given parameters */ public static WordVectors fromTableAndVocab(WeightLookupTable table, VocabCache vocab) { WordVectorsImpl vectors = new WordVectorsImpl(); vectors.setLookupTable(table); vectors.setVocab(vocab); vectors.setModelUtils(new BasicModelUtils()); return vectors; } /** * Load word vectors from the given pair * * @param pair * the given pair * @return a read only word vectors impl based on the given lookup table and vocab */ public static Word2Vec fromPair(Pair<InMemoryLookupTable, VocabCache> pair) { Word2Vec vectors = new Word2Vec(); vectors.setLookupTable(pair.getFirst()); vectors.setVocab(pair.getSecond()); vectors.setModelUtils(new BasicModelUtils()); return vectors; } /** * Loads an in memory cache from the given path (sets syn0 and the vocab) * * Deprecation note: Please, consider using readWord2VecModel() or loadStaticModel() method instead * * @param vectorsFile * the path of the file to load\ * @return * @throws FileNotFoundException * if the file does not exist */ @Deprecated public static WordVectors loadTxtVectors(File vectorsFile) throws FileNotFoundException, UnsupportedEncodingException { Pair<InMemoryLookupTable, VocabCache> pair = loadTxt(vectorsFile); return fromPair(pair); } /** * Loads an in memory cache from the given path (sets syn0 and the vocab) * * @param vectorsFile the path of the file to load * @return a Pair holding the lookup table and the vocab cache. * @throws FileNotFoundException if the input file does not exist */ public static Pair<InMemoryLookupTable, VocabCache> loadTxt(File vectorsFile) throws FileNotFoundException, UnsupportedEncodingException { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(vectorsFile), "UTF-8")); AbstractCache cache = new AbstractCache<>(); LineIterator iter = IOUtils.lineIterator(reader); String line = null; boolean hasHeader = false; if (iter.hasNext()) { line = iter.nextLine(); // skip header line //look for spaces if (!line.contains(" ")) { log.debug("Skipping first line"); hasHeader = true; } else { // we should check for something that looks like proper word vectors here. i.e: 1 word at the 0 position, and bunch of floats further String[] split = line.split(" "); try { long[] header = new long[split.length]; for (int x = 0; x < split.length; x++) { header[x] = Long.parseLong(split[x]); } if (split.length < 4) hasHeader = true; // now we know, if that's all ints - it's just a header // [0] - number of words // [1] - vectorSize // [2] - number of documents <-- DL4j-only value if (split.length == 3) cache.incrementTotalDocCount(header[2]); printOutProjectedMemoryUse(header[0], (int) header[1], 1); hasHeader = true; try { reader.close(); } catch (Exception ex) { } } catch (Exception e) { // if any conversion exception hits - that'll be considered header hasHeader = false; } } } //reposition buffer to be one line ahead if (hasHeader) { line = ""; iter.close(); reader = new BufferedReader(new FileReader(vectorsFile)); iter = IOUtils.lineIterator(reader); iter.nextLine(); } List<INDArray> arrays = new ArrayList<>(); while (iter.hasNext()) { if (line.isEmpty()) line = iter.nextLine(); String[] split = line.split(" "); String word = decodeB64(split[0]); //split[0].replaceAll(whitespaceReplacement, " "); VocabWord word1 = new VocabWord(1.0, word); word1.setIndex(cache.numWords()); cache.addToken(word1); cache.addWordToIndex(word1.getIndex(), word); cache.putVocabWord(word); float[] vector = new float[split.length - 1]; for (int i = 1; i < split.length; i++) { vector[i - 1] = Float.parseFloat(split[i]); } INDArray row = Nd4j.create(vector); arrays.add(row); // workaround for skipped first row line = ""; } INDArray syn = Nd4j.vstack(arrays); InMemoryLookupTable lookupTable = (InMemoryLookupTable) new InMemoryLookupTable.Builder().vectorLength(arrays.get(0).columns()) .useAdaGrad(false).cache(cache).useHierarchicSoftmax(false).build(); if (Nd4j.ENFORCE_NUMERICAL_STABILITY) Nd4j.clearNans(syn); lookupTable.setSyn0(syn); iter.close(); try { reader.close(); } catch (Exception e) { } return new Pair<>(lookupTable, (VocabCache) cache); } /** * This method can be used to load previously saved model from InputStream (like a HDFS-stream) * * Deprecation note: Please, consider using readWord2VecModel() or loadStaticModel() method instead * * @param stream InputStream that contains previously serialized model * @param skipFirstLine Set this TRUE if first line contains csv header, FALSE otherwise * @return * @throws IOException */ @Deprecated public static WordVectors loadTxtVectors(@NonNull InputStream stream, boolean skipFirstLine) throws IOException { AbstractCache<VocabWord> cache = new AbstractCache.Builder<VocabWord>().build(); BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); String line = ""; List<INDArray> arrays = new ArrayList<>(); if (skipFirstLine) reader.readLine(); while ((line = reader.readLine()) != null) { String[] split = line.split(" "); String word = split[0].replaceAll(whitespaceReplacement, " "); VocabWord word1 = new VocabWord(1.0, word); word1.setIndex(cache.numWords()); cache.addToken(word1); cache.addWordToIndex(word1.getIndex(), word); cache.putVocabWord(word); float[] vector = new float[split.length - 1]; for (int i = 1; i < split.length; i++) { vector[i - 1] = Float.parseFloat(split[i]); } INDArray row = Nd4j.create(vector); arrays.add(row); } InMemoryLookupTable<VocabWord> lookupTable = (InMemoryLookupTable<VocabWord>) new InMemoryLookupTable.Builder<VocabWord>() .vectorLength(arrays.get(0).columns()).cache(cache).build(); INDArray syn = Nd4j.vstack(arrays); Nd4j.clearNans(syn); lookupTable.setSyn0(syn); return fromPair(Pair.makePair((InMemoryLookupTable) lookupTable, (VocabCache) cache)); } /** * Write the tsne format * * @param vec * the word vectors to use for labeling * @param tsne * the tsne array to write * @param csv * the file to use * @throws Exception */ public static void writeTsneFormat(Glove vec, INDArray tsne, File csv) throws Exception { BufferedWriter write = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(csv), "UTF-8")); int words = 0; InMemoryLookupCache l = (InMemoryLookupCache) vec.vocab(); for (String word : vec.vocab().words()) { if (word == null) { continue; } StringBuilder sb = new StringBuilder(); INDArray wordVector = tsne.getRow(l.wordFor(word).getIndex()); for (int j = 0; j < wordVector.length(); j++) { sb.append(wordVector.getDouble(j)); if (j < wordVector.length() - 1) { sb.append(","); } } sb.append(","); sb.append(word.replaceAll(" ", whitespaceReplacement)); sb.append(" "); sb.append("\n"); write.write(sb.toString()); } log.info("Wrote " + words + " with size of " + vec.lookupTable().layerSize()); write.flush(); write.close(); } /** * Write the tsne format * * @param vec * the word vectors to use for labeling * @param tsne * the tsne array to write * @param csv * the file to use * @throws Exception */ public static void writeTsneFormat(Word2Vec vec, INDArray tsne, File csv) throws Exception { BufferedWriter write = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(csv), "UTF-8")); int words = 0; InMemoryLookupCache l = (InMemoryLookupCache) vec.vocab(); for (String word : vec.vocab().words()) { if (word == null) { continue; } StringBuilder sb = new StringBuilder(); INDArray wordVector = tsne.getRow(l.wordFor(word).getIndex()); for (int j = 0; j < wordVector.length(); j++) { sb.append(wordVector.getDouble(j)); if (j < wordVector.length() - 1) { sb.append(","); } } sb.append(","); sb.append(word.replaceAll(" ", whitespaceReplacement)); sb.append(" "); sb.append("\n"); write.write(sb.toString()); } log.info("Wrote " + words + " with size of " + vec.lookupTable().layerSize()); write.flush(); write.close(); } /** * This method is used only for VocabCache compatibility purposes * @param array * @param codeLen * @return */ private static List<Byte> arrayToList(byte[] array, int codeLen) { List<Byte> result = new ArrayList<>(); for (int x = 0; x < codeLen; x++) { result.add(array[x]); } return result; } private static byte[] listToArray(List<Byte> code) { byte[] array = new byte[40]; for (int x = 0; x < code.size(); x++) { array[x] = code.get(x).byteValue(); } return array; } private static int[] listToArray(List<Integer> points, int codeLen) { int[] array = new int[points.size()]; for (int x = 0; x < points.size(); x++) { array[x] = points.get(x).intValue(); } return array; } /** * This method is used only for VocabCache compatibility purposes * @param array * @param codeLen * @return */ private static List<Integer> arrayToList(int[] array, int codeLen) { List<Integer> result = new ArrayList<>(); for (int x = 0; x < codeLen; x++) { result.add(array[x]); } return result; } /** * This method saves specified SequenceVectors model to target file path * * @param vectors SequenceVectors model * @param factory SequenceElementFactory implementation for your objects * @param path Target output file path * @param <T> */ public static <T extends SequenceElement> void writeSequenceVectors(@NonNull SequenceVectors<T> vectors, @NonNull SequenceElementFactory<T> factory, @NonNull String path) throws IOException { try (BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(path))) { writeSequenceVectors(vectors, factory, fos); } } /** * This method saves specified SequenceVectors model to target file * * @param vectors SequenceVectors model * @param factory SequenceElementFactory implementation for your objects * @param file Target output file * @param <T> */ public static <T extends SequenceElement> void writeSequenceVectors(@NonNull SequenceVectors<T> vectors, @NonNull SequenceElementFactory<T> factory, @NonNull File file) throws IOException { writeSequenceVectors(vectors, factory, new FileOutputStream(file)); } /** * This method saves specified SequenceVectors model to target OutputStream * * @param vectors SequenceVectors model * @param factory SequenceElementFactory implementation for your objects * @param stream Target output stream * @param <T> */ public static <T extends SequenceElement> void writeSequenceVectors(@NonNull SequenceVectors<T> vectors, @NonNull SequenceElementFactory<T> factory, @NonNull OutputStream stream) throws IOException { WeightLookupTable<T> lookupTable = vectors.getLookupTable(); VocabCache<T> vocabCache = vectors.getVocab(); PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream, "UTF-8"))); // at first line we save VectorsConfiguration writer.write(vectors.getConfiguration().toEncodedJson()); // now we have elements one by one for (int x = 0; x < vocabCache.numWords(); x++) { T element = vocabCache.elementAtIndex(x); String json = factory.serialize(element); INDArray d = Nd4j.create(1); double[] vector = lookupTable.vector(element.getLabel()).dup().data().asDouble(); ElementPair pair = new ElementPair(json, vector); writer.println(pair.toEncodedJson()); writer.flush(); } writer.flush(); writer.close(); } /** * This method loads previously saved SequenceVectors model from File * * @param factory * @param file * @param <T> * @return */ public static <T extends SequenceElement> SequenceVectors<T> readSequenceVectors( @NonNull SequenceElementFactory<T> factory, @NonNull File file) throws IOException { return readSequenceVectors(factory, new FileInputStream(file)); } /** * This method loads previously saved SequenceVectors model from InputStream * * @param factory * @param stream * @param <T> * @return */ public static <T extends SequenceElement> SequenceVectors<T> readSequenceVectors( @NonNull SequenceElementFactory<T> factory, @NonNull InputStream stream) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8")); // at first we load vectors configuration String line = reader.readLine(); VectorsConfiguration configuration = VectorsConfiguration.fromJson(new String(Base64.decodeBase64(line), "UTF-8")); AbstractCache<T> vocabCache = new AbstractCache.Builder<T>().build(); List<INDArray> rows = new ArrayList<>(); while ((line = reader.readLine()) != null) { if (line.isEmpty()) // skip empty line continue; ElementPair pair = ElementPair.fromEncodedJson(line); T element = factory.deserialize(pair.getObject()); rows.add(Nd4j.create(pair.getVector())); vocabCache.addToken(element); vocabCache.addWordToIndex(element.getIndex(), element.getLabel()); } reader.close(); InMemoryLookupTable<T> lookupTable = (InMemoryLookupTable<T>) new InMemoryLookupTable.Builder<T>() .vectorLength(rows.get(0).columns()).cache(vocabCache).build(); // fix: add vocab cache /* * INDArray syn0 = Nd4j.create(rows.size(), rows.get(0).columns()); for (int x = 0; x < rows.size(); x++) { * syn0.putRow(x, rows.get(x)); } */ INDArray syn0 = Nd4j.vstack(rows); lookupTable.setSyn0(syn0); SequenceVectors<T> vectors = new SequenceVectors.Builder<T>(configuration).vocabCache(vocabCache) .lookupTable(lookupTable).resetModel(false).build(); return vectors; } /** * This method saves vocab cache to provided File. * Please note: it saves only vocab content, so it's suitable mostly for BagOfWords/TF-IDF vectorizers * * @param vocabCache * @param file * @throws UnsupportedEncodingException */ public static void writeVocabCache(@NonNull VocabCache<VocabWord> vocabCache, @NonNull File file) throws IOException { writeVocabCache(vocabCache, new FileOutputStream(file)); } /** * This method saves vocab cache to provided OutputStream. * Please note: it saves only vocab content, so it's suitable mostly for BagOfWords/TF-IDF vectorizers * * @param vocabCache * @param stream * @throws UnsupportedEncodingException */ public static void writeVocabCache(@NonNull VocabCache<VocabWord> vocabCache, @NonNull OutputStream stream) throws IOException { PrintWriter writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(stream, "UTF-8"))); for (int x = 0; x < vocabCache.numWords(); x++) { VocabWord word = vocabCache.elementAtIndex(x); writer.println(word.toJSON()); } writer.flush(); writer.close(); } /** * This method reads vocab cache from provided file. * Please note: it reads only vocab content, so it's suitable mostly for BagOfWords/TF-IDF vectorizers * * @param file * @return * @throws IOException */ public static VocabCache<VocabWord> readVocabCache(@NonNull File file) throws IOException { return readVocabCache(new FileInputStream(file)); } /** * This method reads vocab cache from provided InputStream. * Please note: it reads only vocab content, so it's suitable mostly for BagOfWords/TF-IDF vectorizers * * @param stream * @return * @throws IOException */ public static VocabCache<VocabWord> readVocabCache(@NonNull InputStream stream) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8")); AbstractCache<VocabWord> vocabCache = new AbstractCache.Builder<VocabWord>().build(); VocabWordFactory factory = new VocabWordFactory(); String line = ""; while ((line = reader.readLine()) != null) { VocabWord word = factory.deserialize(line); vocabCache.addToken(word); vocabCache.addWordToIndex(word.getIndex(), word.getLabel()); } return vocabCache; } /** * This is utility holder class */ @Data @NoArgsConstructor @AllArgsConstructor private static class ElementPair { private String object; private double[] vector; /** * This utility method serializes ElementPair into JSON + packs it into Base64-encoded string * * @return */ protected String toEncodedJson() { ObjectMapper mapper = SequenceElement.mapper(); Base64 base64 = new Base64(Integer.MAX_VALUE); try { String json = mapper.writeValueAsString(this); String output = base64.encodeAsString(json.getBytes("UTF-8")); return output; } catch (Exception e) { throw new RuntimeException(e); } } /** * This utility method returns ElementPair from Base64-encoded string * * @param encoded * @return */ protected static ElementPair fromEncodedJson(String encoded) { ObjectMapper mapper = SequenceElement.mapper(); try { String decoded = new String(Base64.decodeBase64(encoded), "UTF-8"); return mapper.readValue(decoded, ElementPair.class); } catch (IOException e) { throw new RuntimeException(e); } } } /** * This method * 1) Binary model, either compressed or not. Like well-known Google Model * 2) Popular CSV word2vec text format * 3) DL4j compressed format * * Please note: Only weights will be loaded by this method. * * @param file * @return */ public static Word2Vec readWord2VecModel(@NonNull File file) { return readWord2VecModel(file, false); } /** * This method * 1) Binary model, either compressed or not. Like well-known Google Model * 2) Popular CSV word2vec text format * 3) DL4j compressed format * * Please note: Only weights will be loaded by this method. * * @param path * @return */ public static Word2Vec readWord2VecModel(String path) { return readWord2VecModel(new File(path)); } /** * This method * 1) Binary model, either compressed or not. Like well-known Google Model * 2) Popular CSV word2vec text format * 3) DL4j compressed format * * Please note: if extended data isn't available, only weights will be loaded instead. * * @param path * @param extendedModel if TRUE, we'll try to load HS states & Huffman tree info, if FALSE, only weights will be loaded * @return */ public static Word2Vec readWord2VecModel(String path, boolean extendedModel) { return readWord2VecModel(new File(path), extendedModel); } /** * This method * 1) Binary model, either compressed or not. Like well-known Google Model * 2) Popular CSV word2vec text format * 3) DL4j compressed format * * Please note: if extended data isn't available, only weights will be loaded instead. * * @param file * @param extendedModel if TRUE, we'll try to load HS states & Huffman tree info, if FALSE, only weights will be loaded * @return */ public static Word2Vec readWord2VecModel(@NonNull File file, boolean extendedModel) { InMemoryLookupTable<VocabWord> lookupTable = new InMemoryLookupTable<>(); AbstractCache<VocabWord> vocabCache = new AbstractCache<>(); Word2Vec vec; INDArray syn0 = null; VectorsConfiguration configuration = new VectorsConfiguration(); if (!file.exists() || !file.isFile()) throw new ND4JIllegalStateException("File [" + file.getAbsolutePath() + "] doesn't exist"); int originalFreq = Nd4j.getMemoryManager().getOccasionalGcFrequency(); boolean originalPeriodic = Nd4j.getMemoryManager().isPeriodicGcActive(); if (originalPeriodic) Nd4j.getMemoryManager().togglePeriodicGc(false); Nd4j.getMemoryManager().setOccasionalGcFrequency(50000); // try to load zip format try { if (extendedModel) { log.debug("Trying full model restoration..."); // this method just loads full compressed model if (originalPeriodic) Nd4j.getMemoryManager().togglePeriodicGc(true); Nd4j.getMemoryManager().setOccasionalGcFrequency(originalFreq); return readWord2Vec(file); } else { log.debug("Trying simplified model restoration..."); File tmpFileSyn0 = File.createTempFile("word2vec", "syn"); tmpFileSyn0.deleteOnExit(); File tmpFileConfig = File.createTempFile("word2vec", "config"); tmpFileConfig.deleteOnExit(); // we don't need full model, so we go directly to syn0 file ZipFile zipFile = new ZipFile(file); ZipEntry syn = zipFile.getEntry("syn0.txt"); InputStream stream = zipFile.getInputStream(syn); Files.copy(stream, Paths.get(tmpFileSyn0.getAbsolutePath()), StandardCopyOption.REPLACE_EXISTING); // now we're restoring configuration saved earlier ZipEntry config = zipFile.getEntry("config.json"); if (config != null) { stream = zipFile.getInputStream(config); StringBuilder builder = new StringBuilder(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream))) { String line; while ((line = reader.readLine()) != null) { builder.append(line); } } configuration = VectorsConfiguration.fromJson(builder.toString().trim()); } ZipEntry ve = zipFile.getEntry("frequencies.txt"); if (ve != null) { stream = zipFile.getInputStream(ve); AtomicInteger cnt = new AtomicInteger(0); try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream))) { String line; while ((line = reader.readLine()) != null) { String[] split = line.split(" "); VocabWord word = new VocabWord(Double.valueOf(split[1]), decodeB64(split[0])); word.setIndex(cnt.getAndIncrement()); word.incrementSequencesCount(Long.valueOf(split[2])); vocabCache.addToken(word); vocabCache.addWordToIndex(word.getIndex(), word.getLabel()); Nd4j.getMemoryManager().invokeGcOccasionally(); } } } List<INDArray> rows = new ArrayList<>(); // basically read up everything, call vstacl and then return model try (Reader reader = new CSVReader(tmpFileSyn0)) { AtomicInteger cnt = new AtomicInteger(0); while (reader.hasNext()) { Pair<VocabWord, float[]> pair = reader.next(); VocabWord word = pair.getFirst(); INDArray vector = Nd4j.create(pair.getSecond()); if (ve != null) { if (syn0 == null) syn0 = Nd4j.create(vocabCache.numWords(), vector.length()); syn0.getRow(cnt.getAndIncrement()).assign(vector); } else { rows.add(vector); vocabCache.addToken(word); vocabCache.addWordToIndex(word.getIndex(), word.getLabel()); } Nd4j.getMemoryManager().invokeGcOccasionally(); } } catch (Exception e) { throw new RuntimeException(e); } finally { if (originalPeriodic) Nd4j.getMemoryManager().togglePeriodicGc(true); Nd4j.getMemoryManager().setOccasionalGcFrequency(originalFreq); } if (syn0 == null && vocabCache.numWords() > 0) syn0 = Nd4j.vstack(rows); if (syn0 == null) { log.error("Can't build syn0 table"); throw new DL4JInvalidInputException("Can't build syn0 table"); } lookupTable = new InMemoryLookupTable.Builder<VocabWord>().cache(vocabCache) .vectorLength(syn0.columns()).useHierarchicSoftmax(false).useAdaGrad(false).build(); lookupTable.setSyn0(syn0); try { tmpFileSyn0.delete(); tmpFileConfig.delete(); } catch (Exception e) { // } } } catch (Exception e) { // let's try to load this file as csv file try { log.debug("Trying CSV model restoration..."); Pair<InMemoryLookupTable, VocabCache> pair = loadTxt(file); lookupTable = pair.getFirst(); vocabCache = (AbstractCache<VocabWord>) pair.getSecond(); } catch (Exception ex) { // we fallback to trying binary model instead try { log.debug("Trying binary model restoration..."); if (originalPeriodic) Nd4j.getMemoryManager().togglePeriodicGc(true); Nd4j.getMemoryManager().setOccasionalGcFrequency(originalFreq); vec = loadGoogleModel(file, true, true); return vec; } catch (Exception ey) { // try to load without linebreaks try { if (originalPeriodic) Nd4j.getMemoryManager().togglePeriodicGc(true); Nd4j.getMemoryManager().setOccasionalGcFrequency(originalFreq); vec = loadGoogleModel(file, true, false); return vec; } catch (Exception ez) { throw new RuntimeException( "Unable to guess input file format. Please use corresponding loader directly"); } } } } Word2Vec.Builder builder = new Word2Vec.Builder(configuration).lookupTable(lookupTable).useAdaGrad(false) .vocabCache(vocabCache).layerSize(lookupTable.layerSize()) // we don't use hs here, because model is incomplete .useHierarchicSoftmax(false).resetModel(false); /* Trying to restore TokenizerFactory & TokenPreProcessor */ TokenizerFactory factory = getTokenizerFactory(configuration); if (factory != null) builder.tokenizerFactory(factory); vec = builder.build(); return vec; } protected static TokenizerFactory getTokenizerFactory(VectorsConfiguration configuration) { if (configuration == null) return null; if (configuration != null && configuration.getTokenizerFactory() != null && !configuration.getTokenizerFactory().isEmpty()) { try { TokenizerFactory factory = (TokenizerFactory) Class.forName(configuration.getTokenizerFactory()).newInstance(); if (configuration.getTokenPreProcessor() != null && !configuration.getTokenPreProcessor().isEmpty()) { TokenPreProcess preProcessor = (TokenPreProcess) Class.forName(configuration.getTokenPreProcessor()).newInstance(); factory.setTokenPreProcessor(preProcessor); } return factory; } catch (Exception e) { log.error("Can't instantiate saved TokenizerFactory: {}", configuration.getTokenizerFactory()); } } return null; } /** * This method restores previously saved w2v model. File can be in one of the following formats: * 1) Binary model, either compressed or not. Like well-known Google Model * 2) Popular CSV word2vec text format * 3) DL4j compressed format * * In return you get StaticWord2Vec model, which might be used as lookup table only in multi-gpu environment. * * @param file File should point to previously saved w2v model * @return */ // TODO: this method needs better name :) public static WordVectors loadStaticModel(File file) { if (!file.exists() || file.isDirectory()) throw new RuntimeException( new FileNotFoundException("File [" + file.getAbsolutePath() + "] was not found")); int originalFreq = Nd4j.getMemoryManager().getOccasionalGcFrequency(); boolean originalPeriodic = Nd4j.getMemoryManager().isPeriodicGcActive(); if (originalPeriodic) Nd4j.getMemoryManager().togglePeriodicGc(false); Nd4j.getMemoryManager().setOccasionalGcFrequency(50000); CompressedRamStorage<Integer> storage = new CompressedRamStorage.Builder<Integer>().useInplaceCompression(false) .setCompressor(new NoOp()).emulateIsAbsent(false).build(); VocabCache<VocabWord> vocabCache = new AbstractCache.Builder<VocabWord>().build(); // now we need to define which file format we have here // if zip - that's dl4j format try { log.debug("Trying DL4j format..."); File tmpFileSyn0 = File.createTempFile("word2vec", "syn"); tmpFileSyn0.deleteOnExit(); ZipFile zipFile = new ZipFile(file); ZipEntry syn0 = zipFile.getEntry("syn0.txt"); InputStream stream = zipFile.getInputStream(syn0); Files.copy(stream, Paths.get(tmpFileSyn0.getAbsolutePath()), StandardCopyOption.REPLACE_EXISTING); storage.clear(); try (Reader reader = new CSVReader(tmpFileSyn0)) { while (reader.hasNext()) { Pair<VocabWord, float[]> pair = reader.next(); VocabWord word = pair.getFirst(); storage.store(word.getIndex(), pair.getSecond()); vocabCache.addToken(word); vocabCache.addWordToIndex(word.getIndex(), word.getLabel()); Nd4j.getMemoryManager().invokeGcOccasionally(); } } catch (Exception e) { throw new RuntimeException(e); } finally { if (originalPeriodic) Nd4j.getMemoryManager().togglePeriodicGc(true); Nd4j.getMemoryManager().setOccasionalGcFrequency(originalFreq); try { tmpFileSyn0.delete(); } catch (Exception e) { // } } } catch (Exception e) { // try { // try to load file as text csv vocabCache = new AbstractCache.Builder<VocabWord>().build(); storage.clear(); log.debug("Trying CSVReader..."); try (Reader reader = new CSVReader(file)) { while (reader.hasNext()) { Pair<VocabWord, float[]> pair = reader.next(); VocabWord word = pair.getFirst(); storage.store(word.getIndex(), pair.getSecond()); vocabCache.addToken(word); vocabCache.addWordToIndex(word.getIndex(), word.getLabel()); Nd4j.getMemoryManager().invokeGcOccasionally(); } } catch (Exception ef) { // we throw away this exception, and trying to load data as binary model throw new RuntimeException(ef); } finally { if (originalPeriodic) Nd4j.getMemoryManager().togglePeriodicGc(true); Nd4j.getMemoryManager().setOccasionalGcFrequency(originalFreq); } } catch (Exception ex) { // otherwise it's probably google model. which might be compressed or not log.debug("Trying BinaryReader..."); vocabCache = new AbstractCache.Builder<VocabWord>().build(); storage.clear(); try (Reader reader = new BinaryReader(file)) { while (reader.hasNext()) { Pair<VocabWord, float[]> pair = reader.next(); VocabWord word = pair.getFirst(); storage.store(word.getIndex(), pair.getSecond()); vocabCache.addToken(word); vocabCache.addWordToIndex(word.getIndex(), word.getLabel()); Nd4j.getMemoryManager().invokeGcOccasionally(); } } catch (Exception ez) { throw new RuntimeException("Unable to guess input file format"); } finally { if (originalPeriodic) Nd4j.getMemoryManager().togglePeriodicGc(true); Nd4j.getMemoryManager().setOccasionalGcFrequency(originalFreq); } } finally { if (originalPeriodic) Nd4j.getMemoryManager().togglePeriodicGc(true); Nd4j.getMemoryManager().setOccasionalGcFrequency(originalFreq); } } StaticWord2Vec word2Vec = new StaticWord2Vec.Builder(storage, vocabCache).build(); return word2Vec; } protected interface Reader extends AutoCloseable { boolean hasNext(); Pair<VocabWord, float[]> next(); } protected static class BinaryReader implements Reader { protected DataInputStream stream; protected String nextWord; protected int numWords; protected int vectorLength; protected AtomicInteger idxCounter = new AtomicInteger(0); protected BinaryReader(@NonNull File file) { try { stream = new DataInputStream(new BufferedInputStream(GzipUtils.isCompressedFilename(file.getName()) ? new GZIPInputStream(new FileInputStream(file)) : new FileInputStream(file))); numWords = Integer.parseInt(readString(stream)); vectorLength = Integer.parseInt(readString(stream)); } catch (Exception e) { throw new RuntimeException(e); } } @Override public boolean hasNext() { return idxCounter.get() < numWords; } @Override public Pair<VocabWord, float[]> next() { try { String word = readString(stream); VocabWord element = new VocabWord(1.0, word); element.setIndex(idxCounter.getAndIncrement()); float[] vector = new float[vectorLength]; for (int i = 0; i < vectorLength; i++) { vector[i] = readFloat(stream); } return Pair.makePair(element, vector); } catch (Exception e) { throw new RuntimeException(e); } } @Override public void close() throws Exception { if (stream != null) stream.close(); } } protected static class CSVReader implements Reader { private BufferedReader reader; private AtomicInteger idxCounter = new AtomicInteger(0); private String nextLine; protected CSVReader(@NonNull File file) { try { reader = new BufferedReader(new FileReader(file)); nextLine = reader.readLine(); // checking if there's header inside String[] split = nextLine.split(" "); try { if (Integer.parseInt(split[0]) > 0 && split.length <= 5) { // this is header. skip it. nextLine = reader.readLine(); } } catch (Exception e) { // this is proper string, do nothing } } catch (Exception e) { throw new RuntimeException(e); } } public boolean hasNext() { return nextLine != null; } public Pair<VocabWord, float[]> next() { String[] split = nextLine.split(" "); VocabWord word = new VocabWord(1.0, decodeB64(split[0])); word.setIndex(idxCounter.getAndIncrement()); float[] vector = new float[split.length - 1]; for (int i = 1; i < split.length; i++) { vector[i - 1] = Float.parseFloat(split[i]); } try { nextLine = reader.readLine(); } catch (Exception e) { nextLine = null; } return Pair.makePair(word, vector); } @Override public void close() throws Exception { if (reader != null) reader.close(); } } public static String encodeB64(String word) { try { return "B64:" + Base64.encodeBase64String(word.getBytes("UTF-8")).replaceAll("(\r|\n)", ""); } catch (Exception e) { throw new RuntimeException(e); } } public static String decodeB64(String word) { if (word.startsWith("B64:")) { String arp = word.replaceFirst("B64:", ""); try { return new String(Base64.decodeBase64(arp), "UTF-8"); } catch (Exception e) { throw new RuntimeException(e); } } else return word; } public static void printOutProjectedMemoryUse(long numWords, int vectorLength, int numTables) { double memSize = numWords * vectorLength * Nd4j.sizeOfDataType() * numTables; String sfx; double value; if (memSize < 1024 * 1024L) { sfx = "KB"; value = memSize / 1024; } if (memSize < 1024 * 1024L * 1024L) { sfx = "MB"; value = memSize / 1024 / 1024; } else { sfx = "GB"; value = memSize / 1024 / 1024 / 1024; } OneTimeLogger.info(log,"Projected memory use for model: [{} {}]", String.format("%.2f", value), sfx); } }
// This file is auto-generated, don't edit it. Thanks. package com.aliyun.hosting.mode.models; import com.aliyun.tea.*; /** * list share request */ public class ListShareRequest extends TeaModel { @NameInMap("headers") public java.util.Map<String, String> headers; // creator @NameInMap("creator") public String creator; @NameInMap("drive_id") @Validation(pattern = "[0-9]+") public String driveId; // limit @NameInMap("limit") public Integer limit; // marker @NameInMap("marker") public String marker; // Owner @NameInMap("owner") public String owner; // share_file_path @NameInMap("share_file_path") public String shareFilePath; public static ListShareRequest build(java.util.Map<String, ?> map) throws Exception { ListShareRequest self = new ListShareRequest(); return TeaModel.build(map, self); } public ListShareRequest setHeaders(java.util.Map<String, String> headers) { this.headers = headers; return this; } public java.util.Map<String, String> getHeaders() { return this.headers; } public ListShareRequest setCreator(String creator) { this.creator = creator; return this; } public String getCreator() { return this.creator; } public ListShareRequest setDriveId(String driveId) { this.driveId = driveId; return this; } public String getDriveId() { return this.driveId; } public ListShareRequest setLimit(Integer limit) { this.limit = limit; return this; } public Integer getLimit() { return this.limit; } public ListShareRequest setMarker(String marker) { this.marker = marker; return this; } public String getMarker() { return this.marker; } public ListShareRequest setOwner(String owner) { this.owner = owner; return this; } public String getOwner() { return this.owner; } public ListShareRequest setShareFilePath(String shareFilePath) { this.shareFilePath = shareFilePath; return this; } public String getShareFilePath() { return this.shareFilePath; } }
/* * Workspace API * Agent API * * OpenAPI spec version: 9.0.000.97.4639 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package com.genesys.internal.workspace.model; import java.util.Objects; import java.util.Arrays; import com.genesys.internal.workspace.model.Field; import com.google.gson.TypeAdapter; import com.google.gson.annotations.JsonAdapter; import com.google.gson.annotations.SerializedName; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * CallingList */ @javax.annotation.Generated(value = "io.swagger.codegen.languages.JavaClientCodegen", date = "2022-03-03T19:45:16.214Z") public class CallingList { @SerializedName("name") private String name = null; @SerializedName("fields") private List<Field> fields = null; public CallingList name(String name) { this.name = name; return this; } /** * name of the calling list * @return name **/ @ApiModelProperty(value = "name of the calling list") public String getName() { return name; } public void setName(String name) { this.name = name; } public CallingList fields(List<Field> fields) { this.fields = fields; return this; } public CallingList addFieldsItem(Field fieldsItem) { if (this.fields == null) { this.fields = new ArrayList<Field>(); } this.fields.add(fieldsItem); return this; } /** * Get fields * @return fields **/ @ApiModelProperty(value = "") public List<Field> getFields() { return fields; } public void setFields(List<Field> fields) { this.fields = fields; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CallingList callingList = (CallingList) o; return Objects.equals(this.name, callingList.name) && Objects.equals(this.fields, callingList.fields); } @Override public int hashCode() { return Objects.hash(name, fields); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class CallingList {\n"); sb.append(" name: ").append(toIndentedString(name)).append("\n"); sb.append(" fields: ").append(toIndentedString(fields)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
package org.jzy3d.chart; import org.jzy3d.chart.factories.IChartFactory; import org.jzy3d.maths.Dimension; import org.jzy3d.plot3d.primitives.Drawable; import org.jzy3d.plot3d.primitives.axis.layout.IAxisLayout; import org.jzy3d.plot3d.rendering.canvas.Quality; import org.jzy3d.plot3d.rendering.legends.colorbars.AWTColorbarLegend; import org.jzy3d.plot3d.rendering.view.AWTRenderer2d; import org.jzy3d.plot3d.rendering.view.AWTView; public class AWTChart extends Chart { public AWTChart(IChartFactory components, Quality quality) { super(components, quality); } protected AWTChart() { super(); } public void addRenderer(AWTRenderer2d renderer2d) { getAWTView().addRenderer2d(renderer2d); } public void removeRenderer(AWTRenderer2d renderer2d) { getAWTView().removeRenderer2d(renderer2d); } public AWTView getAWTView() { return (AWTView) view; } public AWTColorbarLegend colorbar(Drawable drawable) { return colorbar(drawable, new Dimension(100, 600), getView().getAxis().getLayout()); } public AWTColorbarLegend colorbar(Drawable drawable, IAxisLayout layout) { return colorbar(drawable, new Dimension(100, 600), layout); } public AWTColorbarLegend colorbar(Drawable drawable, Dimension d, IAxisLayout layout) { AWTColorbarLegend cbar = new AWTColorbarLegend(drawable, layout); cbar.setMinimumSize(d); drawable.setLegend(cbar); return cbar; } }
/* * Copyright (C) 2005 - 2014 TIBCO Software Inc. All rights reserved. * http://www.jaspersoft.com. * * Unless you have purchased a commercial license agreement from Jaspersoft, * the following license terms apply: * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.jaspersoft.jasperserver.api.engine.scheduling.domain; import com.jaspersoft.jasperserver.api.JasperServerAPI; import com.jaspersoft.jasperserver.api.engine.scheduling.domain.jaxb.DateToStringXmlAdapter; import com.jaspersoft.jasperserver.api.engine.scheduling.domain.jaxb.ReportJobStateXmlAdapter; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import java.io.Serializable; import java.util.Date; /** * Execution runtime information provided by the scheduled for active jobs. * * @author Lucian Chirita (lucianc@users.sourceforge.net) * @version $Id: ReportJobRuntimeInformation.java 47331 2014-07-18 09:13:06Z kklein $ * @since 1.0 * @see ReportJobSummary#getRuntimeInformation() */ @JasperServerAPI @XmlRootElement(name = "state") public class ReportJobRuntimeInformation implements Serializable { private static final long serialVersionUID = 1L; /** * Job execution state that indicates that the trigger for the job was not * found or was in an unknown state. * * @see #getState() */ public static final byte STATE_UNKNOWN = 0; /** * Job execution state that indicates that the trigger for the job is * waiting for the next execution. * * @see #getState() */ public static final byte STATE_NORMAL = 1; /** * Job execution state that indicates that the job is currently running. * * @see #getState() */ public static final byte STATE_EXECUTING = 2; /** * Job execution state that indicates that the trigger for the job has * been paused in the scheduler. * * @see #getState() */ public static final byte STATE_PAUSED = 3; /** * Job execution state that indicates that the job has no remaining * executions. * * @see #getState() */ public static final byte STATE_COMPLETE = 4; /** * Job execution state that indicates that the scheduler has encountered * a system error when attempting to execute the job. * * @see #getState() */ public static final byte STATE_ERROR = 5; private Byte state; private Date previousFireTime; private Date nextFireTime; /** * Creates an empty object. */ public ReportJobRuntimeInformation() { } /** * Returns the next job fire time, or <code>null</code> if the job is at the * last execution. * * @return the next job fire time */ @XmlJavaTypeAdapter(DateToStringXmlAdapter.class) public Date getNextFireTime() { return nextFireTime; } /** * Sets the job next fire time. * * @param nextFireTime the next fire time for the job */ public void setNextFireTime(Date nextFireTime) { this.nextFireTime = nextFireTime; } /** * Returns the previous job fire time, or <code>null</code> if the job * hasn't been yet executed. * * @return the job previous fire time */ @XmlJavaTypeAdapter(DateToStringXmlAdapter.class) public Date getPreviousFireTime() { return previousFireTime; } /** * Sets the job previous fire time. * * @param previousFireTime the previous fire time of the job */ public void setPreviousFireTime(Date previousFireTime) { this.previousFireTime = previousFireTime; } /** * Returns the execution state of the job trigger. * * @return one of the <code>STATE_*</code> constants */ @XmlJavaTypeAdapter(ReportJobStateXmlAdapter.class) @XmlElement(name = "value") public Byte getStateCode() { return state; } /** * Returns the execution state of the job trigger. * * @return one of the <code>STATE_*</code> constants * @deprecated use #getStateCode() instead */ @XmlTransient public byte getState() { return getStateCode(); } /** * Sets the execution state of the job trigger. * * @param state one of the <code>STATE_*</code> constants * @deprecated use #setStateCode(Byte state) instead */ public void setState(byte state) { setStateCode(state); } /** * Sets the execution state of the job trigger. * * @param state one of the <code>STATE_*</code> constants */ public void setStateCode(Byte state) { this.state = state; } }
package com.cn.decorator; public class IPhone implements MobilePhone{ @Override public void call() { System.out.println("IPhone call!"); } @Override public void photo() { System.out.println("Iphone photo!"); } }
/* * Licensed to GraphHopper GmbH under one or more contributor * license agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. * * GraphHopper GmbH 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.graphhopper.routing.weighting; import com.graphhopper.routing.util.FlagEncoder; import com.graphhopper.routing.util.HintsMap; import com.graphhopper.util.EdgeIteratorState; /** * @author Peter Karich */ public abstract class AbstractWeighting implements Weighting { protected final FlagEncoder flagEncoder; public AbstractWeighting(FlagEncoder encoder) { this.flagEncoder = encoder; if (!flagEncoder.isRegistered()) throw new IllegalStateException("Make sure you add the FlagEncoder " + flagEncoder + " to an EncodingManager before using it elsewhere"); if (!isValidName(getName())) throw new IllegalStateException("Not a valid name for a Weighting: " + getName()); } @Override public long calcMillis(EdgeIteratorState edgeState, boolean reverse, int prevOrNextEdgeId) { long flags = edgeState.getFlags(); if (reverse && !flagEncoder.isBackward(flags) || !reverse && !flagEncoder.isForward(flags)) throw new IllegalStateException("Calculating time should not require to read speed from edge in wrong direction. " + "Reverse:" + reverse + ", fwd:" + flagEncoder.isForward(flags) + ", bwd:" + flagEncoder.isBackward(flags)); double speed = reverse ? flagEncoder.getReverseSpeed(flags) : flagEncoder.getSpeed(flags); if (Double.isInfinite(speed) || Double.isNaN(speed) || speed < 0) throw new IllegalStateException("Invalid speed stored in edge! " + speed); if (speed == 0) throw new IllegalStateException("Speed cannot be 0 for unblocked edge, use access properties to mark edge blocked! Should only occur for shortest path calculation. See #242."); return (long) (edgeState.getDistance() * 3600 / speed); } @Override public boolean matches(HintsMap reqMap) { return getName().equals(reqMap.getWeighting()) && flagEncoder.toString().equals(reqMap.getVehicle()); } @Override public FlagEncoder getFlagEncoder() { return flagEncoder; } @Override public int hashCode() { int hash = 7; hash = 71 * hash + toString().hashCode(); return hash; } @Override public boolean equals(Object obj) { if (obj == null) return false; if (getClass() != obj.getClass()) return false; final Weighting other = (Weighting) obj; return toString().equals(other.toString()); } static final boolean isValidName(String name) { if (name == null || name.isEmpty()) return false; return name.matches("[\\|_a-z]+"); } /** * Replaces all characters which are not numbers, characters or underscores with underscores */ public static String weightingToFileName(Weighting w) { return w.toString().toLowerCase().replaceAll("\\|", "_"); } @Override public String toString() { return getName() + "|" + flagEncoder; } }
package co.yixiang.modules.activity.service.impl; import co.yixiang.modules.activity.domain.YxUserExtract; import co.yixiang.modules.activity.repository.YxUserExtractRepository; import co.yixiang.modules.activity.service.YxUserExtractService; import co.yixiang.modules.activity.service.dto.YxUserExtractDTO; import co.yixiang.modules.activity.service.dto.YxUserExtractQueryCriteria; import co.yixiang.modules.activity.service.mapper.YxUserExtractMapper; import co.yixiang.utils.PageUtil; import co.yixiang.utils.QueryHelp; import co.yixiang.utils.ValidationUtil; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import java.util.List; import java.util.Map; import java.util.Optional; /** * @author hupeng * @date 2019-11-14 */ @Service @Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class) public class YxUserExtractServiceImpl implements YxUserExtractService { private final YxUserExtractRepository yxUserExtractRepository; private final YxUserExtractMapper yxUserExtractMapper; public YxUserExtractServiceImpl(YxUserExtractRepository yxUserExtractRepository, YxUserExtractMapper yxUserExtractMapper) { this.yxUserExtractRepository = yxUserExtractRepository; this.yxUserExtractMapper = yxUserExtractMapper; } @Override public Map<String,Object> queryAll(YxUserExtractQueryCriteria criteria, Pageable pageable){ Page<YxUserExtract> page = yxUserExtractRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable); return PageUtil.toPage(page.map(yxUserExtractMapper::toDto)); } @Override public List<YxUserExtractDTO> queryAll(YxUserExtractQueryCriteria criteria){ return yxUserExtractMapper.toDto(yxUserExtractRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder))); } @Override public YxUserExtractDTO findById(Integer id) { Optional<YxUserExtract> yxUserExtract = yxUserExtractRepository.findById(id); ValidationUtil.isNull(yxUserExtract,"YxUserExtract","id",id); return yxUserExtractMapper.toDto(yxUserExtract.get()); } @Override @Transactional(rollbackFor = Exception.class) public YxUserExtractDTO create(YxUserExtract resources) { return yxUserExtractMapper.toDto(yxUserExtractRepository.save(resources)); } @Override @Transactional(rollbackFor = Exception.class) public void update(YxUserExtract resources) { Optional<YxUserExtract> optionalYxUserExtract = yxUserExtractRepository.findById(resources.getId()); ValidationUtil.isNull( optionalYxUserExtract,"YxUserExtract","id",resources.getId()); YxUserExtract yxUserExtract = optionalYxUserExtract.get(); yxUserExtract.copy(resources); yxUserExtractRepository.save(yxUserExtract); } @Override @Transactional(rollbackFor = Exception.class) public void delete(Integer id) { yxUserExtractRepository.deleteById(id); } }
/* * Copyright 2015-2102 RonCoo(http://www.roncoo.com) Group. * * 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.roncoo.pay.user.service; /** * 生成编号service接口 * 龙果学院:www.roncoo.com * * @author:zenghao */ public interface BuildNoService { /** * 获取用户编号 **/ String buildUserNo(); /** * 获取账户编号 **/ String buildAccountNo(); /** * 获取支付流水号 **/ String buildTrxNo(); /** * 获取银行订单号 **/ String buildBankOrderNo(); /** * 获取对账批次号 **/ String buildReconciliationNo(); }
/* * Copyright 2016 Piotr Raszkowski * * 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 pl.raszkowski.sporttrackersconnector.garminconnect; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import pl.raszkowski.sporttrackersconnector.JsonTestHelper; import pl.raszkowski.sporttrackersconnector.configuration.ConnectorsConfiguration; import pl.raszkowski.sporttrackersconnector.json.ResponseJsonParser; import pl.raszkowski.sporttrackersconnector.rest.GetParameters; import pl.raszkowski.sporttrackersconnector.rest.RESTExecutor; import com.google.gson.JsonArray; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.mockito.Matchers.any; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; public class GarminAPIHandlerTest { private static final String ACTIVITY_SEARCH_SERVICE = "ACTIVITY_SEARCH_SERVICE"; private static final String ACTIVITIES_RESOURCE = "activities"; private static final String RESPONSE = "{ RESPONSE }"; private RESTExecutor restExecutor; @Mock private ConnectorsConfiguration connectorsConfiguration; @Mock private ResponseJsonParser responseJsonParser; @InjectMocks private GarminAPIHandler garminAPIHandler; @Before public void setUp() { restExecutor = mock(RESTExecutor.class); garminAPIHandler = new GarminAPIHandler(restExecutor); MockitoAnnotations.initMocks(this); doReturn(RESPONSE).when(restExecutor).executeGET(eq(ACTIVITY_SEARCH_SERVICE), eq(ACTIVITIES_RESOURCE), any(GetParameters.class)); doReturn(ACTIVITY_SEARCH_SERVICE).when(connectorsConfiguration).getGarminConnectRESTActivitySearchService(); } @Test public void getActivitiesWhenEmptyJson() { doReturn(JsonTestHelper.readJsonObject("{}")).when(responseJsonParser).parseAsJsonObject(RESPONSE); JsonArray json = garminAPIHandler.getActivities(0, 20); assertNotNull(json); assertEquals(0, json.size()); } @Test public void getActivitiesWhenNoResultsElement() { doReturn(JsonTestHelper.readJsonObject("{ response : \"content\"}")).when(responseJsonParser).parseAsJsonObject(RESPONSE); JsonArray json = garminAPIHandler.getActivities(0, 20); assertNotNull(json); assertEquals(0, json.size()); } @Test public void getActivitiesWhenNoActivitiesElement() { doReturn(JsonTestHelper.readJsonObject("{ results : {}}")).when(responseJsonParser).parseAsJsonObject(RESPONSE); JsonArray json = garminAPIHandler.getActivities(0, 20); assertNotNull(json); assertEquals(0, json.size()); } @Test public void getActivitiesWhenEmptyActivities() { doReturn(JsonTestHelper.readJsonObject("{ results : { activities : [] } }")).when(responseJsonParser).parseAsJsonObject(RESPONSE); JsonArray json = garminAPIHandler.getActivities(0, 20); assertNotNull(json); assertEquals(0, json.size()); } @Test public void getActivitiesWhenNotEmptyActivities() { doReturn(JsonTestHelper.readJsonObject("{ results : { activities : [{}] } }")).when(responseJsonParser).parseAsJsonObject(RESPONSE); JsonArray json = garminAPIHandler.getActivities(0, 20); assertNotNull(json); assertEquals(1, json.size()); } }
package io.cdep.cdep.yml; /* * Copyright 2017 Google 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. */ import io.cdep.annotations.NotNull; import io.cdep.cdep.yml.cdepmanifest.Archive; import io.cdep.cdep.yml.cdepmanifest.CxxLanguageFeatures; import net.java.quickcheck.Generator; import static io.cdep.cdep.yml.ArchiveGenerator.Kind.missing; import static net.java.quickcheck.generator.CombinedGenerators.arrays; import static net.java.quickcheck.generator.PrimitiveGenerators.*; public class ArchiveGenerator implements Generator<Archive> { @NotNull final public Generator<Kind> kind = enumValues(Kind.class); @NotNull final public Generator<String> file = new ShortFilenameGenerator(); @NotNull final public Generator<String> sha256 = strings(); @NotNull final public Generator<Long> size = longs(); @NotNull final public Generator<String> include = strings(); @NotNull final public Generator<CxxLanguageFeatures[]> requires = arrays(enumValues(CxxLanguageFeatures.class), CxxLanguageFeatures.class); @Override public Archive next() { if (kind.next() == missing) { return null; } return new Archive( file.next(), sha256.next(), size.next(), include.next(), requires.next() ); } enum Kind { missing, random } }
/* * Copyright 2012-2018 Amazon.com, Inc. or its affiliates. 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://aws.amazon.com/apache2.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.amazonaws.services.medialive.model; import javax.annotation.Generated; /** * Placeholder documentation for M3u8TimedMetadataBehavior */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public enum M3u8TimedMetadataBehavior { NO_PASSTHROUGH("NO_PASSTHROUGH"), PASSTHROUGH("PASSTHROUGH"); private String value; private M3u8TimedMetadataBehavior(String value) { this.value = value; } @Override public String toString() { return this.value; } /** * Use this in place of valueOf. * * @param value * real value * @return M3u8TimedMetadataBehavior corresponding to the value * * @throws IllegalArgumentException * If the specified value does not map to one of the known values in this enum. */ public static M3u8TimedMetadataBehavior fromValue(String value) { if (value == null || "".equals(value)) { throw new IllegalArgumentException("Value cannot be null or empty!"); } for (M3u8TimedMetadataBehavior enumEntry : M3u8TimedMetadataBehavior.values()) { if (enumEntry.toString().equals(value)) { return enumEntry; } } throw new IllegalArgumentException("Cannot create enum from " + value + " value!"); } }
package com.sunRays.controller; import java.util.List; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import com.sunRays.bean.MenuItemDto; import com.sunRays.model.MenuItem; import com.sunRays.service.MenuItemService; @Component @Scope("prototype") @Path("/menuItems") public class MenuItemJSONProvider { @Autowired private MenuItemService menuItemService; @GET @Path("/get/{menuId}") @Produces(MediaType.APPLICATION_JSON) public MenuItem get(@PathParam ("menuId") String menuId){ MenuItem mi= null; try{ if(menuId!=null && menuId.length()>0) mi=menuItemService.get(Integer.parseInt(menuId)); } catch (IllegalArgumentException e) { throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity( e.getMessage() ).build()); } return mi; } @GET @Path("/listMenu") @Produces(MediaType.APPLICATION_JSON) //@RequestMapping(value = "/listMenu", method = RequestMethod.GET,produces = MediaType.APPLICATION_JSON_VALUE) //@ResponseBody //@ResponseStatus(HttpStatus.OK) public List<MenuItem> getMenuItemList(){ return menuItemService.getMenuItemList(); } //@RequestMapping(value = "/save", method = RequestMethod.POST) @POST @Path("/save") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public List<MenuItem> update(MenuItemDto menuItem){ menuItemService.update(beanToModel(menuItem)); return getMenuItemList(); // ResponseBuilder builder = new ResponseBuilderImpl(); // Creates a ResponseBuilder // builder.header("content-type", "application/json"); // Sets the header of the return data // builder.status(Response.Status.OK); // Sets the response code as a 200 // builder.header("Access-Control-Allow-Origin", "*"); // Allows Cross Domain Requests from any origin // builder.entity(menuItem); // Adds your result data to the Response // return builder.build(); // Creates the Response } //@RequestMapping(value = "/delete", method = RequestMethod.POST) @POST @Path("/delete") @Consumes(MediaType.APPLICATION_JSON) public void delete(MenuItemDto menuItem){ menuItemService.delete(beanToModel(menuItem)); } private MenuItem beanToModel(MenuItemDto menuItemDto){ MenuItem menuItem=new MenuItem(); if(menuItemDto.getMenuId()!=null && menuItemDto.getMenuId().length()>0) menuItem.setMenuId(Integer.parseInt(menuItemDto.getMenuId())); menuItem.setMenuName(menuItemDto.getMenuName()); menuItem.setCategory(menuItemDto.getCategory()); menuItem.setImageId(menuItemDto.getImageId()); System.out.println("id: "+menuItem.getMenuId()); System.out.println("name: "+menuItem.getMenuName()); System.out.println("cat: "+menuItem.getCategory()); System.out.println("image: "+menuItem.getImageId()); return menuItem; } }