text
stringlengths
7
1.01M
package com.vmware.vim25; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for VmRelocateSpecEvent complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="VmRelocateSpecEvent"> * &lt;complexContent> * &lt;extension base="{urn:vim25}VmEvent"> * &lt;sequence> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "VmRelocateSpecEvent") @XmlSeeAlso({ VmRelocateFailedEvent.class, VmRelocatedEvent.class, VmBeingRelocatedEvent.class }) public class VmRelocateSpecEvent extends VmEvent { }
/** */ package org.ecore.service.communicationPattern; import org.ecore.service.communicationObject.CommunicationObject; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Push Pattern</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * </p> * <ul> * <li>{@link org.ecore.service.communicationPattern.PushPattern#getDataType <em>Data Type</em>}</li> * </ul> * * @see org.ecore.service.communicationPattern.CommunicationPatternPackage#getPushPattern() * @model * @generated */ public interface PushPattern extends ForkingPattern { /** * Returns the value of the '<em><b>Data Type</b></em>' reference. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Data Type</em>' reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Data Type</em>' reference. * @see #setDataType(CommunicationObject) * @see org.ecore.service.communicationPattern.CommunicationPatternPackage#getPushPattern_DataType() * @model required="true" * @generated */ CommunicationObject getDataType(); /** * Sets the value of the '{@link org.ecore.service.communicationPattern.PushPattern#getDataType <em>Data Type</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Data Type</em>' reference. * @see #getDataType() * @generated */ void setDataType(CommunicationObject value); } // PushPattern
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. package com.yahoo.jdisc.application; import com.google.inject.AbstractModule; import com.google.inject.Injector; import com.google.inject.Module; import com.google.inject.name.Names; import com.yahoo.jdisc.test.TestDriver; import org.junit.Test; import org.osgi.framework.Bundle; import org.osgi.framework.BundleException; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * @author Simon Thoresen Hult */ public class GuiceRepositoryIntegrationTest { @Test public void requireThatInstallFromBundleWorks() throws Exception { MyModule module = new MyModule(); TestDriver driver = TestDriver.newSimpleApplicationInstance(module); ContainerBuilder builder = driver.newContainerBuilder(); List<Module> prev = new LinkedList<>(builder.guiceModules().collection()); BundleInstaller installer = new BundleInstaller(driver.osgiFramework()); Bundle bundle = installer.installAndStart("my-guice-module.jar").get(0); builder.guiceModules().install(bundle, "com.yahoo.jdisc.bundle.MyGuiceModule"); List<Module> next = new LinkedList<>(builder.guiceModules().collection()); next.removeAll(prev); assertEquals(1, next.size()); assertTrue(module.initLatch.await(60, TimeUnit.SECONDS)); assertNotNull(builder.guiceModules().getInstance(Injector.class)); assertTrue(module.configLatch.await(60, TimeUnit.SECONDS)); driver.close(); } @Test public void requireThatInstallAllFromBundleWorks() throws Exception { TestDriver driver = TestDriver.newSimpleApplicationInstance(new MyModule()); ContainerBuilder builder = driver.newContainerBuilder(); List<Module> prev = new LinkedList<>(builder.guiceModules().collection()); BundleInstaller installer = new BundleInstaller(driver.osgiFramework()); Bundle bundle = installer.installAndStart("my-guice-module.jar").get(0); builder.guiceModules().installAll(bundle, Arrays.asList("com.yahoo.jdisc.bundle.MyGuiceModule", "com.yahoo.jdisc.bundle.MyGuiceModule")); List<Module> next = new LinkedList<>(builder.guiceModules().collection()); next.removeAll(prev); assertEquals(2, next.size()); driver.close(); } @Test public void requireThatInstallUnknowClassThrows() throws BundleException, ClassNotFoundException { TestDriver driver = TestDriver.newSimpleApplicationInstance(new MyModule()); BundleInstaller installer = new BundleInstaller(driver.osgiFramework()); Bundle bundle = installer.installAndStart("my-guice-module.jar").get(0); ContainerBuilder builder = driver.newContainerBuilder(); try { builder.guiceModules().install(bundle, "class.not.Found"); fail(); } catch (ClassNotFoundException e) { } driver.close(); } private static class MyModule extends AbstractModule { final CountDownLatch initLatch = new CountDownLatch(1); final CountDownLatch configLatch = new CountDownLatch(1); @Override protected void configure() { bind(CountDownLatch.class).annotatedWith(Names.named("Init")).toInstance(initLatch); bind(CountDownLatch.class).annotatedWith(Names.named("Config")).toInstance(configLatch); } } }
package com.dope.gagong.bots.Protocols.ICommandProtocols; import com.dope.gagong.bots.Debug.Debug; import com.dope.gagong.bots.Utils.CreateTag; import com.dope.gagong.bots.Interfaces.ICommand; import com.dope.gagong.bots.Variables.Users; import com.dope.gagong.bots.Variables.Roles; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.entities.Role; import net.dv8tion.jda.api.events.message.MessageReceivedEvent; import java.awt.*; import java.time.Instant; import java.util.List; import java.util.Objects; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; public class SquadProtocol implements ICommand { private final CreateTag Tag = new CreateTag(); private final Users Users = new Users(); private final Roles Roles = new Roles(); @Override public boolean isCalled(String[] args, MessageReceivedEvent event) { return true; } @Override public void Protocol(String[] args, MessageReceivedEvent event) { String[] TAG = { Tag.asMember(Users.CrankTV), Tag.asMember(Users.Kewai), Tag.asMember(Users.zhoiak), Tag.asMember(Users.AD3RTRON), Tag.asMember(Users.Sumi), Tag.asMember(Users.era), Tag.asMember(Users.Fabio), Tag.asMember(Users.Gagong) }; List<Role> UR = Objects.requireNonNull(event.getMember()).getRoles(); AtomicBoolean state = new AtomicBoolean(false); UR.forEach(role -> { if (role.getId().equals(Roles.SQUAD)) state.set(true); }); if (state.get()) { StringBuilder squad = new StringBuilder(); for (String id: TAG) { squad.append(id).append(" "); } event.getTextChannel().sendMessage("WHERE MY SQUAD? " + squad).queue(); } else { EmbedBuilder log = new EmbedBuilder(); log.setTitle("ERROR: Wrong permissions!"); log.setDescription("Only **Squad** users can use this command!"); log.setAuthor(event.getAuthor().getName(), null, event.getAuthor().getAvatarUrl()); log.setColor(Color.red); log.setTimestamp(Instant.now()); event.getTextChannel().sendMessage(log.build()).queue(e -> e.delete().completeAfter(5, TimeUnit.SECONDS)); } } @Override public void isExecuted(boolean success, MessageReceivedEvent event) { Debug.p("SquadProtocol", "isExecuted", "Squad protocol: Done!"); } @Override public String getCommandName() { return "Squad"; } @Override public String helpAssist() { return null; } }
/* * Copyright (c) 2007-present, Stephen Colebourne & Michael Nascimento Santos * * 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 JSR-310 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 OWNER 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 org.threeten.extra; import static java.time.temporal.ChronoField.ERA; import static java.time.temporal.ChronoField.YEAR; import static java.time.temporal.ChronoField.YEAR_OF_ERA; import static java.time.temporal.ChronoUnit.CENTURIES; import static java.time.temporal.ChronoUnit.DECADES; import static java.time.temporal.ChronoUnit.ERAS; import static java.time.temporal.ChronoUnit.MILLENNIA; import static java.time.temporal.ChronoUnit.YEARS; import static java.time.temporal.IsoFields.DAY_OF_QUARTER; import static java.time.temporal.IsoFields.QUARTER_OF_YEAR; import static java.time.temporal.IsoFields.QUARTER_YEARS; import java.io.Serializable; import java.time.Clock; import java.time.DateTimeException; import java.time.LocalDate; import java.time.Month; import java.time.Period; import java.time.Year; import java.time.ZoneId; import java.time.chrono.Chronology; import java.time.chrono.IsoChronology; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatterBuilder; import java.time.format.DateTimeParseException; import java.time.format.SignStyle; import java.time.temporal.ChronoField; import java.time.temporal.ChronoUnit; import java.time.temporal.IsoFields; import java.time.temporal.Temporal; import java.time.temporal.TemporalAccessor; import java.time.temporal.TemporalAdjuster; import java.time.temporal.TemporalAmount; import java.time.temporal.TemporalField; import java.time.temporal.TemporalQueries; import java.time.temporal.TemporalQuery; import java.time.temporal.TemporalUnit; import java.time.temporal.UnsupportedTemporalTypeException; import java.time.temporal.ValueRange; import java.util.Objects; import java.util.stream.LongStream; import java.util.stream.Stream; import org.joda.convert.FromString; import org.joda.convert.ToString; /** * A year-quarter in the ISO-8601 calendar system, such as {@code 2007-Q2}. * <p> * {@code YearQuarter} is an immutable date-time object that represents the combination * of a year and quarter. Any field that can be derived from a year and quarter can be obtained. * A quarter is defined by {@link Quarter} and {@link Month#firstMonthOfQuarter()} - Q1, Q2, Q3 and Q4. * Q1 is January to March, Q2 is April to June, Q3 is July to September and Q4 is October to December. * <p> * This class does not store or represent a day, time or time-zone. * For example, the value "2nd quarter 2007" can be stored in a {@code YearQuarter}. * <p> * The ISO-8601 calendar system is the modern civil calendar system used today * in most of the world. It is equivalent to the proleptic Gregorian calendar * system, in which today's rules for leap years are applied for all time. * For most applications written today, the ISO-8601 rules are entirely suitable. * However, any application that makes use of historical dates, and requires them * to be accurate will find the ISO-8601 approach unsuitable. * Note that the ISO-8601 standard does not define or refer to quarters. * * <h3>Implementation Requirements:</h3> * This class is immutable and thread-safe. * <p> * This class must be treated as a value type. Do not synchronize, rely on the * identity hash code or use the distinction between equals() and ==. */ public final class YearQuarter implements Temporal, TemporalAdjuster, Comparable<YearQuarter>, Serializable { /** * Serialization version. */ private static final long serialVersionUID = 4183400860270640070L; /** * Parser. */ private static final DateTimeFormatter PARSER = new DateTimeFormatterBuilder() .parseCaseInsensitive() .appendValue(YEAR, 4, 10, SignStyle.EXCEEDS_PAD) .appendLiteral('-') .appendLiteral('Q') .appendValue(QUARTER_OF_YEAR, 1) .toFormatter(); /** * The year. */ private final int year; /** * The quarter-of-year, not null. */ private final Quarter quarter; //----------------------------------------------------------------------- /** * Obtains the current year-quarter from the system clock in the default time-zone. * <p> * This will query the {@link java.time.Clock#systemDefaultZone() system clock} in the default * time-zone to obtain the current year-quarter. * The zone and offset will be set based on the time-zone in the clock. * <p> * Using this method will prevent the ability to use an alternate clock for testing * because the clock is hard-coded. * * @return the current year-quarter using the system clock and default time-zone, not null */ public static YearQuarter now() { return now(Clock.systemDefaultZone()); } /** * Obtains the current year-quarter from the system clock in the specified time-zone. * <p> * This will query the {@link Clock#system(java.time.ZoneId) system clock} to obtain the current year-quarter. * Specifying the time-zone avoids dependence on the default time-zone. * <p> * Using this method will prevent the ability to use an alternate clock for testing * because the clock is hard-coded. * * @param zone the zone ID to use, not null * @return the current year-quarter using the system clock, not null */ public static YearQuarter now(ZoneId zone) { return now(Clock.system(zone)); } /** * Obtains the current year-quarter from the specified clock. * <p> * This will query the specified clock to obtain the current year-quarter. * Using this method allows the use of an alternate clock for testing. * The alternate clock may be introduced using {@link Clock dependency injection}. * * @param clock the clock to use, not null * @return the current year-quarter, not null */ public static YearQuarter now(Clock clock) { final LocalDate now = LocalDate.now(clock); // called once return YearQuarter.of(now.getYear(), Quarter.from(now.getMonth())); } //----------------------------------------------------------------------- /** * Obtains an instance of {@code YearQuarter} from a year and quarter. * * @param year the year to represent, from MIN_YEAR to MAX_YEAR * @param quarter the quarter-of-year to represent, not null * @return the year-quarter, not null * @throws DateTimeException if the year value is invalid */ public static YearQuarter of(int year, Quarter quarter) { YEAR.checkValidValue(year); Objects.requireNonNull(quarter, "quarter"); return new YearQuarter(year, quarter); } /** * Obtains an instance of {@code YearQuarter} from a year and quarter. * * @param year the year to represent, from MIN_YEAR to MAX_YEAR * @param quarter the quarter-of-year to represent, from 1 to 4 * @return the year-quarter, not null * @throws DateTimeException if either field value is invalid */ public static YearQuarter of(int year, int quarter) { YEAR.checkValidValue(year); return new YearQuarter(year, Quarter.of(quarter)); } //----------------------------------------------------------------------- /** * Obtains an instance of {@code YearQuarter} from a temporal object. * <p> * This obtains a year-quarter based on the specified temporal. * A {@code TemporalAccessor} represents an arbitrary set of date and time information, * which this factory converts to an instance of {@code YearQuarter}. * <p> * The conversion extracts the {@link ChronoField#YEAR YEAR} and * {@link IsoFields#QUARTER_OF_YEAR QUARTER_OF_YEAR} fields. * The extraction is only permitted if the temporal object has an ISO * chronology, or can be converted to a {@code LocalDate}. * <p> * This method matches the signature of the functional interface {@link TemporalQuery} * allowing it to be used in queries via method reference, {@code YearQuarter::from}. * * @param temporal the temporal object to convert, not null * @return the year-quarter, not null * @throws DateTimeException if unable to convert to a {@code YearQuarter} */ public static YearQuarter from(TemporalAccessor temporal) { if (temporal instanceof YearQuarter) { return (YearQuarter) temporal; } Objects.requireNonNull(temporal, "temporal"); try { if (IsoChronology.INSTANCE.equals(Chronology.from(temporal)) == false) { temporal = LocalDate.from(temporal); } // need to use getLong() as JDK Parsed class get() doesn't work properly int year = Math.toIntExact(temporal.getLong(YEAR)); int qoy = Math.toIntExact(temporal.getLong(QUARTER_OF_YEAR)); return of(year, qoy); } catch (DateTimeException ex) { throw new DateTimeException("Unable to obtain YearQuarter from TemporalAccessor: " + temporal + " of type " + temporal.getClass().getName(), ex); } } //----------------------------------------------------------------------- /** * Obtains an instance of {@code YearQuarter} from a text string such as {@code 2007-Q2}. * <p> * The string must represent a valid year-quarter. * The format must be {@code uuuu-'Q'Q} where the 'Q' is case insensitive. * Years outside the range 0000 to 9999 must be prefixed by the plus or minus symbol. * * @param text the text to parse such as "2007-Q2", not null * @return the parsed year-quarter, not null * @throws DateTimeParseException if the text cannot be parsed */ @FromString public static YearQuarter parse(CharSequence text) { return parse(text, PARSER); } /** * Obtains an instance of {@code YearQuarter} from a text string using a specific formatter. * <p> * The text is parsed using the formatter, returning a year-quarter. * * @param text the text to parse, not null * @param formatter the formatter to use, not null * @return the parsed year-quarter, not null * @throws DateTimeParseException if the text cannot be parsed */ public static YearQuarter parse(CharSequence text, DateTimeFormatter formatter) { Objects.requireNonNull(formatter, "formatter"); return formatter.parse(text, YearQuarter::from); } //----------------------------------------------------------------------- /** * Constructor. * * @param year the year to represent, validated from MIN_YEAR to MAX_YEAR * @param quarter the quarter-of-year to represent, validated not null */ private YearQuarter(int year, Quarter quarter) { this.year = year; this.quarter = quarter; } /** * Validates the input. * * @return the valid object, not null */ private Object readResolve() { return of(year, quarter); } /** * Returns a copy of this year-quarter with the new year and quarter, checking * to see if a new object is in fact required. * * @param newYear the year to represent, validated from MIN_YEAR to MAX_YEAR * @param newQuarter the quarter-of-year to represent, validated not null * @return the year-quarter, not null */ private YearQuarter with(int newYear, Quarter newQuarter) { if (year == newYear && quarter == newQuarter) { return this; } return new YearQuarter(newYear, newQuarter); } //----------------------------------------------------------------------- /** * Checks if the specified field is supported. * <p> * This checks if this year-quarter can be queried for the specified field. * If false, then calling the {@link #range(TemporalField) range}, * {@link #get(TemporalField) get} and {@link #with(TemporalField, long)} * methods will throw an exception. * <p> * If the field is a {@link ChronoField} then the query is implemented here. * The supported fields are: * <ul> * <li>{@code QUARTER_OF_YEAR} * <li>{@code YEAR_OF_ERA} * <li>{@code YEAR} * <li>{@code ERA} * </ul> * All other {@code ChronoField} instances will return false. * <p> * If the field is not a {@code ChronoField}, then the result of this method * is obtained by invoking {@code TemporalField.isSupportedBy(TemporalAccessor)} * passing {@code this} as the argument. * Whether the field is supported is determined by the field. * * @param field the field to check, null returns false * @return true if the field is supported on this year-quarter, false if not */ @Override public boolean isSupported(TemporalField field) { if (field == QUARTER_OF_YEAR) { return true; } else if (field instanceof ChronoField) { return field == YEAR || field == YEAR_OF_ERA || field == ERA; } return field != null && field.isSupportedBy(this); } /** * Checks if the specified unit is supported. * <p> * This checks if the specified unit can be added to, or subtracted from, this year-quarter. * If false, then calling the {@link #plus(long, TemporalUnit)} and * {@link #minus(long, TemporalUnit) minus} methods will throw an exception. * <p> * If the unit is a {@link ChronoUnit} then the query is implemented here. * The supported units are: * <ul> * <li>{@code QUARTER_YEARS} * <li>{@code YEARS} * <li>{@code DECADES} * <li>{@code CENTURIES} * <li>{@code MILLENNIA} * <li>{@code ERAS} * </ul> * All other {@code ChronoUnit} instances will return false. * <p> * If the unit is not a {@code ChronoUnit}, then the result of this method * is obtained by invoking {@code TemporalUnit.isSupportedBy(Temporal)} * passing {@code this} as the argument. * Whether the unit is supported is determined by the unit. * * @param unit the unit to check, null returns false * @return true if the unit can be added/subtracted, false if not */ @Override public boolean isSupported(TemporalUnit unit) { if (unit == QUARTER_YEARS) { return true; } else if (unit instanceof ChronoUnit) { return unit == YEARS || unit == DECADES || unit == CENTURIES || unit == MILLENNIA || unit == ERAS; } return unit != null && unit.isSupportedBy(this); } //----------------------------------------------------------------------- /** * Gets the range of valid values for the specified field. * <p> * The range object expresses the minimum and maximum valid values for a field. * This year-quarter is used to enhance the accuracy of the returned range. * If it is not possible to return the range, because the field is not supported * or for some other reason, an exception is thrown. * <p> * If the field is a {@link ChronoField} then the query is implemented here. * The {@link #isSupported(TemporalField) supported fields} will return * appropriate range instances. * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}. * <p> * If the field is not a {@code ChronoField}, then the result of this method * is obtained by invoking {@code TemporalField.rangeRefinedBy(TemporalAccessor)} * passing {@code this} as the argument. * Whether the range can be obtained is determined by the field. * * @param field the field to query the range for, not null * @return the range of valid values for the field, not null * @throws DateTimeException if the range for the field cannot be obtained * @throws UnsupportedTemporalTypeException if the field is not supported */ @Override public ValueRange range(TemporalField field) { if (field == QUARTER_OF_YEAR) { return QUARTER_OF_YEAR.range(); } if (field == YEAR_OF_ERA) { return (getYear() <= 0 ? ValueRange.of(1, Year.MAX_VALUE + 1) : ValueRange.of(1, Year.MAX_VALUE)); } return Temporal.super.range(field); } /** * Gets the value of the specified field from this year-quarter as an {@code int}. * <p> * This queries this year-quarter for the value for the specified field. * The returned value will always be within the valid range of values for the field. * If it is not possible to return the value, because the field is not supported * or for some other reason, an exception is thrown. * <p> * If the field is a {@link ChronoField} then the query is implemented here. * The {@link #isSupported(TemporalField) supported fields} will return valid * values based on this year-quarter,. * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}. * <p> * If the field is not a {@code ChronoField}, then the result of this method * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)} * passing {@code this} as the argument. Whether the value can be obtained, * and what the value represents, is determined by the field. * * @param field the field to get, not null * @return the value for the field * @throws DateTimeException if a value for the field cannot be obtained or * the value is outside the range of valid values for the field * @throws UnsupportedTemporalTypeException if the field is not supported or * the range of values exceeds an {@code int} * @throws ArithmeticException if numeric overflow occurs */ @Override public int get(TemporalField field) { if (field == QUARTER_OF_YEAR) { return quarter.getValue(); } else if (field instanceof ChronoField) { switch ((ChronoField) field) { case YEAR_OF_ERA: return (year < 1 ? 1 - year : year); case YEAR: return year; case ERA: return (year < 1 ? 0 : 1); default: throw new UnsupportedTemporalTypeException("Unsupported field: " + field); } } return Temporal.super.get(field); } /** * Gets the value of the specified field from this year-quarter as a {@code long}. * <p> * This queries this year-quarter for the value for the specified field. * If it is not possible to return the value, because the field is not supported * or for some other reason, an exception is thrown. * <p> * If the field is a {@link ChronoField} then the query is implemented here. * The {@link #isSupported(TemporalField) supported fields} will return valid * values based on this year-quarter. * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}. * <p> * If the field is not a {@code ChronoField}, then the result of this method * is obtained by invoking {@code TemporalField.getFrom(TemporalAccessor)} * passing {@code this} as the argument. Whether the value can be obtained, * and what the value represents, is determined by the field. * * @param field the field to get, not null * @return the value for the field * @throws DateTimeException if a value for the field cannot be obtained * @throws UnsupportedTemporalTypeException if the field is not supported * @throws ArithmeticException if numeric overflow occurs */ @Override public long getLong(TemporalField field) { if (field == QUARTER_OF_YEAR) { return quarter.getValue(); } else if (field instanceof ChronoField) { switch ((ChronoField) field) { case YEAR_OF_ERA: return (year < 1 ? 1 - year : year); case YEAR: return year; case ERA: return (year < 1 ? 0 : 1); default: throw new UnsupportedTemporalTypeException("Unsupported field: " + field); } } return field.getFrom(this); } private long getProlepticQuarter() { return year * 4L + (quarter.getValue() - 1); } //----------------------------------------------------------------------- /** * Gets the year field. * <p> * This method returns the primitive {@code int} value for the year. * <p> * The year returned by this method is proleptic as per {@code get(YEAR)}. * * @return the year, from MIN_YEAR to MAX_YEAR */ public int getYear() { return year; } /** * Gets the quarter-of-year field from 1 to 4. * <p> * This method returns the quarter as an {@code int} from 1 to 4. * Application code is frequently clearer if the enum {@link Quarter} * is used by calling {@link #getQuarter()}. * * @return the quarter-of-year, from 1 to 4 * @see #getQuarter() */ public int getQuarterValue() { return quarter.getValue(); } /** * Gets the quarter-of-year field using the {@code Quarter} enum. * <p> * This method returns the enum {@link Quarter} for the quarter. * This avoids confusion as to what {@code int} values mean. * If you need access to the primitive {@code int} value then the enum * provides the {@link Quarter#getValue() int value}. * * @return the quarter-of-year, not null * @see #getQuarterValue() */ public Quarter getQuarter() { return quarter; } //----------------------------------------------------------------------- /** * Checks if the year is a leap year, according to the ISO proleptic * calendar system rules. * <p> * This method applies the current rules for leap years across the whole time-line. * In general, a year is a leap year if it is divisible by four without * remainder. However, years divisible by 100, are not leap years, with * the exception of years divisible by 400 which are. * <p> * For example, 1904 is a leap year it is divisible by 4. * 1900 was not a leap year as it is divisible by 100, however 2000 was a * leap year as it is divisible by 400. * <p> * The calculation is proleptic - applying the same rules into the far future and far past. * This is historically inaccurate, but is correct for the ISO-8601 standard. * * @return true if the year is leap, false otherwise */ public boolean isLeapYear() { return IsoChronology.INSTANCE.isLeapYear(year); } /** * Checks if the day-of-quarter is valid for this year-quarter. * <p> * This method checks whether this year and quarter and the input day form * a valid date. * * @param dayOfQuarter the day-of-quarter to validate, from 1 to 92, invalid value returns false * @return true if the day is valid for this year-quarter */ public boolean isValidDay(int dayOfQuarter) { return dayOfQuarter >= 1 && dayOfQuarter <= lengthOfQuarter(); } /** * Returns the length of the quarter, taking account of the year. * <p> * This returns the length of the quarter in days. * * @return the length of the quarter in days, from 90 to 92 */ public int lengthOfQuarter() { return quarter.length(isLeapYear()); } /** * Returns the length of the year. * <p> * This returns the length of the year in days, either 365 or 366. * * @return 366 if the year is leap, 365 otherwise */ public int lengthOfYear() { return (isLeapYear() ? 366 : 365); } //----------------------------------------------------------------------- /** * Returns an adjusted copy of this year-quarter. * <p> * This returns a {@code YearQuarter} based on this one, with the year-quarter adjusted. * The adjustment takes place using the specified adjuster strategy object. * Read the documentation of the adjuster to understand what adjustment will be made. * <p> * A simple adjuster might simply set the one of the fields, such as the year field. * A more complex adjuster might set the year-quarter to the next quarter that * Halley's comet will pass the Earth. * <p> * The result of this method is obtained by invoking the * {@link TemporalAdjuster#adjustInto(Temporal)} method on the * specified adjuster passing {@code this} as the argument. * <p> * This instance is immutable and unaffected by this method call. * * @param adjuster the adjuster to use, not null * @return a {@code YearQuarter} based on {@code this} with the adjustment made, not null * @throws DateTimeException if the adjustment cannot be made * @throws ArithmeticException if numeric overflow occurs */ @Override public YearQuarter with(TemporalAdjuster adjuster) { return (YearQuarter) adjuster.adjustInto(this); } /** * Returns a copy of this year-quarter with the specified field set to a new value. * <p> * This returns a {@code YearQuarter} based on this one, with the value * for the specified field changed. * This can be used to change any supported field, such as the year or quarter. * If it is not possible to set the value, because the field is not supported or for * some other reason, an exception is thrown. * <p> * If the field is a {@link ChronoField} then the adjustment is implemented here. * The supported fields behave as follows: * <ul> * <li>{@code QUARTER_OF_YEAR} - * Returns a {@code YearQuarter} with the specified quarter-of-year. * The year will be unchanged. * <li>{@code YEAR_OF_ERA} - * Returns a {@code YearQuarter} with the specified year-of-era * The quarter and era will be unchanged. * <li>{@code YEAR} - * Returns a {@code YearQuarter} with the specified year. * The quarter will be unchanged. * <li>{@code ERA} - * Returns a {@code YearQuarter} with the specified era. * The quarter and year-of-era will be unchanged. * </ul> * <p> * In all cases, if the new value is outside the valid range of values for the field * then a {@code DateTimeException} will be thrown. * <p> * All other {@code ChronoField} instances will throw an {@code UnsupportedTemporalTypeException}. * <p> * If the field is not a {@code ChronoField}, then the result of this method * is obtained by invoking {@code TemporalField.adjustInto(Temporal, long)} * passing {@code this} as the argument. In this case, the field determines * whether and how to adjust the instant. * <p> * This instance is immutable and unaffected by this method call. * * @param field the field to set in the result, not null * @param newValue the new value of the field in the result * @return a {@code YearQuarter} based on {@code this} with the specified field set, not null * @throws DateTimeException if the field cannot be set * @throws UnsupportedTemporalTypeException if the field is not supported * @throws ArithmeticException if numeric overflow occurs */ @Override public YearQuarter with(TemporalField field, long newValue) { if (field == QUARTER_OF_YEAR) { return withQuarter(QUARTER_OF_YEAR.range().checkValidIntValue(newValue, QUARTER_OF_YEAR)); } else if (field instanceof ChronoField) { ChronoField f = (ChronoField) field; f.checkValidValue(newValue); switch (f) { case YEAR_OF_ERA: return withYear((int) (year < 1 ? 1 - newValue : newValue)); case YEAR: return withYear((int) newValue); case ERA: return (getLong(ERA) == newValue ? this : withYear(1 - year)); default: throw new UnsupportedTemporalTypeException("Unsupported field: " + field); } } return field.adjustInto(this, newValue); } //----------------------------------------------------------------------- /** * Returns a copy of this {@code YearQuarter} with the year altered. * <p> * This instance is immutable and unaffected by this method call. * * @param year the year to set in the returned year-quarter, from MIN_YEAR to MAX_YEAR * @return a {@code YearQuarter} based on this year-quarter with the requested year, not null * @throws DateTimeException if the year value is invalid */ public YearQuarter withYear(int year) { YEAR.checkValidValue(year); return with(year, quarter); } /** * Returns a copy of this {@code YearQuarter} with the quarter-of-year altered. * <p> * This instance is immutable and unaffected by this method call. * * @param quarter the quarter-of-year to set in the returned year-quarter, from 1 to 4 * @return a {@code YearQuarter} based on this year-quarter with the requested quarter, not null * @throws DateTimeException if the quarter-of-year value is invalid */ public YearQuarter withQuarter(int quarter) { QUARTER_OF_YEAR.range().checkValidValue(quarter, QUARTER_OF_YEAR); return with(year, Quarter.of(quarter)); } //----------------------------------------------------------------------- /** * Returns a copy of this year-quarter with the specified amount added. * <p> * This returns a {@code YearQuarter} based on this one, with the specified amount added. * The amount is typically {@link Period} but may be any other type implementing * the {@link TemporalAmount} interface. * <p> * The calculation is delegated to the amount object by calling * {@link TemporalAmount#addTo(Temporal)}. The amount implementation is free * to implement the addition in any way it wishes, however it typically * calls back to {@link #plus(long, TemporalUnit)}. Consult the documentation * of the amount implementation to determine if it can be successfully added. * <p> * This instance is immutable and unaffected by this method call. * * @param amountToAdd the amount to add, not null * @return a {@code YearQuarter} based on this year-quarter with the addition made, not null * @throws DateTimeException if the addition cannot be made * @throws ArithmeticException if numeric overflow occurs */ @Override public YearQuarter plus(TemporalAmount amountToAdd) { return (YearQuarter) amountToAdd.addTo(this); } /** * Returns a copy of this year-quarter with the specified amount added. * <p> * This returns a {@code YearQuarter} based on this one, with the amount * in terms of the unit added. If it is not possible to add the amount, because the * unit is not supported or for some other reason, an exception is thrown. * <p> * If the field is a {@link ChronoUnit} then the addition is implemented here. * The supported fields behave as follows: * <ul> * <li>{@code QUARTER_YEARS} - * Returns a {@code YearQuarter} with the specified number of quarters added. * This is equivalent to {@link #plusQuarters(long)}. * <li>{@code YEARS} - * Returns a {@code YearQuarter} with the specified number of years added. * This is equivalent to {@link #plusYears(long)}. * <li>{@code DECADES} - * Returns a {@code YearQuarter} with the specified number of decades added. * This is equivalent to calling {@link #plusYears(long)} with the amount * multiplied by 10. * <li>{@code CENTURIES} - * Returns a {@code YearQuarter} with the specified number of centuries added. * This is equivalent to calling {@link #plusYears(long)} with the amount * multiplied by 100. * <li>{@code MILLENNIA} - * Returns a {@code YearQuarter} with the specified number of millennia added. * This is equivalent to calling {@link #plusYears(long)} with the amount * multiplied by 1,000. * <li>{@code ERAS} - * Returns a {@code YearQuarter} with the specified number of eras added. * Only two eras are supported so the amount must be one, zero or minus one. * If the amount is non-zero then the year is changed such that the year-of-era * is unchanged. * </ul> * <p> * All other {@code ChronoUnit} instances will throw an {@code UnsupportedTemporalTypeException}. * <p> * If the field is not a {@code ChronoUnit}, then the result of this method * is obtained by invoking {@code TemporalUnit.addTo(Temporal, long)} * passing {@code this} as the argument. In this case, the unit determines * whether and how to perform the addition. * <p> * This instance is immutable and unaffected by this method call. * * @param amountToAdd the amount of the unit to add to the result, may be negative * @param unit the unit of the amount to add, not null * @return a {@code YearQuarter} based on this year-quarter with the specified amount added, not null * @throws DateTimeException if the addition cannot be made * @throws UnsupportedTemporalTypeException if the unit is not supported * @throws ArithmeticException if numeric overflow occurs */ @Override public YearQuarter plus(long amountToAdd, TemporalUnit unit) { if (unit == QUARTER_YEARS) { return plusQuarters(amountToAdd); } else if (unit instanceof ChronoUnit) { switch ((ChronoUnit) unit) { case YEARS: return plusYears(amountToAdd); case DECADES: return plusYears(Math.multiplyExact(amountToAdd, 10)); case CENTURIES: return plusYears(Math.multiplyExact(amountToAdd, 100)); case MILLENNIA: return plusYears(Math.multiplyExact(amountToAdd, 1000)); case ERAS: return with(ERA, Math.addExact(getLong(ERA), amountToAdd)); default: throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit); } } return unit.addTo(this, amountToAdd); } /** * Returns a copy of this year-quarter with the specified period in years added. * <p> * This instance is immutable and unaffected by this method call. * * @param yearsToAdd the years to add, may be negative * @return a {@code YearQuarter} based on this year-quarter with the years added, not null * @throws DateTimeException if the result exceeds the supported range */ public YearQuarter plusYears(long yearsToAdd) { if (yearsToAdd == 0) { return this; } int newYear = YEAR.checkValidIntValue(year + yearsToAdd); // safe overflow return with(newYear, quarter); } /** * Returns a copy of this year-quarter with the specified period in quarters added. * <p> * This instance is immutable and unaffected by this method call. * * @param quartersToAdd the quarters to add, may be negative * @return a {@code YearQuarter} based on this year-quarter with the quarters added, not null * @throws DateTimeException if the result exceeds the supported range */ public YearQuarter plusQuarters(long quartersToAdd) { if (quartersToAdd == 0) { return this; } long quarterCount = year * 4L + (quarter.getValue() - 1); long calcQuarters = quarterCount + quartersToAdd; // safe overflow int newYear = YEAR.checkValidIntValue(Math.floorDiv(calcQuarters, 4)); int newQuarter = (int) Math.floorMod(calcQuarters, 4) + 1; return with(newYear, Quarter.of(newQuarter)); } //----------------------------------------------------------------------- /** * Returns a copy of this year-quarter with the specified amount subtracted. * <p> * This returns a {@code YearQuarter} based on this one, with the specified amount subtracted. * The amount is typically {@link Period} but may be any other type implementing * the {@link TemporalAmount} interface. * <p> * The calculation is delegated to the amount object by calling * {@link TemporalAmount#subtractFrom(Temporal)}. The amount implementation is free * to implement the subtraction in any way it wishes, however it typically * calls back to {@link #minus(long, TemporalUnit)}. Consult the documentation * of the amount implementation to determine if it can be successfully subtracted. * <p> * This instance is immutable and unaffected by this method call. * * @param amountToSubtract the amount to subtract, not null * @return a {@code YearQuarter} based on this year-quarter with the subtraction made, not null * @throws DateTimeException if the subtraction cannot be made * @throws ArithmeticException if numeric overflow occurs */ @Override public YearQuarter minus(TemporalAmount amountToSubtract) { return (YearQuarter) amountToSubtract.subtractFrom(this); } /** * Returns a copy of this year-quarter with the specified amount subtracted. * <p> * This returns a {@code YearQuarter} based on this one, with the amount * in terms of the unit subtracted. If it is not possible to subtract the amount, * because the unit is not supported or for some other reason, an exception is thrown. * <p> * This method is equivalent to {@link #plus(long, TemporalUnit)} with the amount negated. * See that method for a full description of how addition, and thus subtraction, works. * <p> * This instance is immutable and unaffected by this method call. * * @param amountToSubtract the amount of the unit to subtract from the result, may be negative * @param unit the unit of the amount to subtract, not null * @return a {@code YearQuarter} based on this year-quarter with the specified amount subtracted, not null * @throws DateTimeException if the subtraction cannot be made * @throws UnsupportedTemporalTypeException if the unit is not supported * @throws ArithmeticException if numeric overflow occurs */ @Override public YearQuarter minus(long amountToSubtract, TemporalUnit unit) { return (amountToSubtract == Long.MIN_VALUE ? plus(Long.MAX_VALUE, unit).plus(1, unit) : plus(-amountToSubtract, unit)); } /** * Returns a copy of this year-quarter with the specified period in years subtracted. * <p> * This instance is immutable and unaffected by this method call. * * @param yearsToSubtract the years to subtract, may be negative * @return a {@code YearQuarter} based on this year-quarter with the years subtracted, not null * @throws DateTimeException if the result exceeds the supported range */ public YearQuarter minusYears(long yearsToSubtract) { return (yearsToSubtract == Long.MIN_VALUE ? plusYears(Long.MAX_VALUE).plusYears(1) : plusYears(-yearsToSubtract)); } /** * Returns a copy of this year-quarter with the specified period in quarters subtracted. * <p> * This instance is immutable and unaffected by this method call. * * @param quartersToSubtract the quarters to subtract, may be negative * @return a {@code YearQuarter} based on this year-quarter with the quarters subtracted, not null * @throws DateTimeException if the result exceeds the supported range */ public YearQuarter minusQuarters(long quartersToSubtract) { return (quartersToSubtract == Long.MIN_VALUE ? plusQuarters(Long.MAX_VALUE).plusQuarters(1) : plusQuarters(-quartersToSubtract)); } //----------------------------------------------------------------------- /** * Queries this year-quarter using the specified query. * <p> * This queries this year-quarter using the specified query strategy object. * The {@code TemporalQuery} object defines the logic to be used to * obtain the result. Read the documentation of the query to understand * what the result of this method will be. * <p> * The result of this method is obtained by invoking the * {@link TemporalQuery#queryFrom(TemporalAccessor)} method on the * specified query passing {@code this} as the argument. * * @param <R> the type of the result * @param query the query to invoke, not null * @return the query result, null may be returned (defined by the query) * @throws DateTimeException if unable to query (defined by the query) * @throws ArithmeticException if numeric overflow occurs (defined by the query) */ @SuppressWarnings("unchecked") @Override public <R> R query(TemporalQuery<R> query) { if (query == TemporalQueries.chronology()) { return (R) IsoChronology.INSTANCE; } else if (query == TemporalQueries.precision()) { return (R) QUARTER_YEARS; } return Temporal.super.query(query); } /** * Adjusts the specified temporal object to have this year-quarter. * <p> * This returns a temporal object of the same observable type as the input * with the year and quarter changed to be the same as this. * <p> * The adjustment is equivalent to using {@link Temporal#plus(long, TemporalUnit)} * passing the number of quarters to adjust by. * If the specified temporal object does not use the ISO calendar system then * a {@code DateTimeException} is thrown. * <p> * In most cases, it is clearer to reverse the calling pattern by using * {@link Temporal#with(TemporalAdjuster)}: * <pre> * // these two lines are equivalent, but the second approach is recommended * temporal = thisYearQuarter.adjustInto(temporal); * temporal = temporal.with(thisYearQuarter); * </pre> * <p> * This instance is immutable and unaffected by this method call. * * @param temporal the target object to be adjusted, not null * @return the adjusted object, not null * @throws DateTimeException if unable to make the adjustment * @throws ArithmeticException if numeric overflow occurs */ @Override public Temporal adjustInto(Temporal temporal) { if (Chronology.from(temporal).equals(IsoChronology.INSTANCE) == false) { throw new DateTimeException("Adjustment only supported on ISO date-time"); } long newProlepticQuarter = getProlepticQuarter(); long oldProlepticQuarter = temporal.get(YEAR) * 4L + (temporal.get(QUARTER_OF_YEAR) - 1); return temporal.plus(newProlepticQuarter - oldProlepticQuarter, QUARTER_YEARS); } /** * Calculates the amount of time until another year-quarter in terms of the specified unit. * <p> * This calculates the amount of time between two {@code YearQuarter} * objects in terms of a single {@code TemporalUnit}. * The start and end points are {@code this} and the specified year-quarter. * The result will be negative if the end is before the start. * The {@code Temporal} passed to this method is converted to a * {@code YearQuarter} using {@link #from(TemporalAccessor)}. * For example, the period in years between two year-quarters can be calculated * using {@code startYearQuarter.until(endYearQuarter, YEARS)}. * <p> * The calculation returns a whole number, representing the number of * complete units between the two year-quarters. * For example, the period in decades between 2012-Q3 and 2032-Q2 * will only be one decade as it is one quarter short of two decades. * <p> * There are two equivalent ways of using this method. * The first is to invoke this method. * The second is to use {@link TemporalUnit#between(Temporal, Temporal)}: * <pre> * // these two lines are equivalent * amount = start.until(end, QUARTER_YEARS); * amount = QUARTER_YEARS.between(start, end); * </pre> * The choice should be made based on which makes the code more readable. * <p> * The calculation is implemented in this method for {@link ChronoUnit}. * The units {@code QUARTER_YEARS}, {@code YEARS}, {@code DECADES}, * {@code CENTURIES}, {@code MILLENNIA} and {@code ERAS} are supported. * Other {@code ChronoUnit} values will throw an exception. * <p> * If the unit is not a {@code ChronoUnit}, then the result of this method * is obtained by invoking {@code TemporalUnit.between(Temporal, Temporal)} * passing {@code this} as the first argument and the converted input temporal * as the second argument. * <p> * This instance is immutable and unaffected by this method call. * * @param endExclusive the end date, exclusive, which is converted to a {@code YearQuarter}, not null * @param unit the unit to measure the amount in, not null * @return the amount of time between this year-quarter and the end year-quarter * @throws DateTimeException if the amount cannot be calculated, or the end * temporal cannot be converted to a {@code YearQuarter} * @throws UnsupportedTemporalTypeException if the unit is not supported * @throws ArithmeticException if numeric overflow occurs */ @Override public long until(Temporal endExclusive, TemporalUnit unit) { YearQuarter end = YearQuarter.from(endExclusive); long quartersUntil = end.getProlepticQuarter() - getProlepticQuarter(); // no overflow if (unit == QUARTER_YEARS) { return quartersUntil; } else if (unit instanceof ChronoUnit) { switch ((ChronoUnit) unit) { case YEARS: return quartersUntil / 4; case DECADES: return quartersUntil / 40; case CENTURIES: return quartersUntil / 400; case MILLENNIA: return quartersUntil / 4000; case ERAS: return end.getLong(ERA) - getLong(ERA); default: throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit); } } return unit.between(this, end); } /** * Returns a sequential ordered stream of year-quarter. The returned stream starts from this year-quarter * (inclusive) and goes to {@code endExclusive} (exclusive) by an incremental step of 1 {@code QUARTER_YEARS}. * <p> * This instance is immutable and unaffected by this method call. * * @param endExclusive the end year-quarter, exclusive, not null * @return a sequential {@code Stream} for the range of {@code YearQuarter} values * @throws IllegalArgumentException if end year-quarter is before this year-quarter */ public Stream<YearQuarter> quartersUntil(YearQuarter endExclusive) { if (endExclusive.isBefore(this)) { throw new IllegalArgumentException(endExclusive + " < " + this); } long intervalLength = until(endExclusive, QUARTER_YEARS); return LongStream.range(0, intervalLength).mapToObj(n -> plusQuarters(n)); } /** * Formats this year-quarter using the specified formatter. * <p> * This year-quarter will be passed to the formatter to produce a string. * * @param formatter the formatter to use, not null * @return the formatted year-quarter string, not null * @throws DateTimeException if an error occurs during printing */ public String format(DateTimeFormatter formatter) { Objects.requireNonNull(formatter, "formatter"); return formatter.format(this); } //----------------------------------------------------------------------- /** * Combines this year-quarter with a day-of-quarter to create a {@code LocalDate}. * <p> * This returns a {@code LocalDate} formed from this year-quarter and the specified day-of-quarter. * <p> * The day-of-quarter value must be valid for the year-quarter. * <p> * This method can be used as part of a chain to produce a date: * <pre> * LocalDate date = yearQuarter.atDay(day); * </pre> * * @param dayOfQuarter the day-of-quarter to use, from 1 to 92 * @return the date formed from this year-quarter and the specified day, not null * @throws DateTimeException if the day is invalid for the year-quarter * @see #isValidDay(int) */ public LocalDate atDay(int dayOfQuarter) { ValueRange.of(1, lengthOfQuarter()).checkValidValue(dayOfQuarter, DAY_OF_QUARTER); boolean leap = Year.isLeap(year); Month month = quarter.firstMonth(); while (dayOfQuarter > month.length(leap)) { dayOfQuarter -= month.length(leap); month = month.plus(1); } return LocalDate.of(year, month, dayOfQuarter); } /** * Returns a {@code LocalDate} at the end of the quarter. * <p> * This returns a {@code LocalDate} based on this year-quarter. * The day-of-quarter is set to the last valid day of the quarter, taking * into account leap years. * <p> * This method can be used as part of a chain to produce a date: * <pre> * LocalDate date = year.atQuarter(quarter).atEndOfQuarter(); * </pre> * * @return the last valid date of this year-quarter, not null */ public LocalDate atEndOfQuarter() { Month month = quarter.firstMonth().plus(2); return LocalDate.of(year, month, month.maxLength()); } //----------------------------------------------------------------------- /** * Compares this year-quarter to another * <p> * The comparison is based first on the value of the year, then on the value of the quarter. * It is "consistent with equals", as defined by {@link Comparable}. * * @param other the other year-quarter to compare to, not null * @return the comparator value, negative if less, positive if greater */ @Override public int compareTo(YearQuarter other) { int cmp = (year - other.year); if (cmp == 0) { cmp = quarter.compareTo(other.quarter); } return cmp; } /** * Is this year-quarter after the specified year-quarter. * * @param other the other year-quarter to compare to, not null * @return true if this is after the specified year-quarter */ public boolean isAfter(YearQuarter other) { return compareTo(other) > 0; } /** * Is this year-quarter before the specified year-quarter. * * @param other the other year-quarter to compare to, not null * @return true if this point is before the specified year-quarter */ public boolean isBefore(YearQuarter other) { return compareTo(other) < 0; } //----------------------------------------------------------------------- /** * Checks if this year-quarter is equal to another year-quarter. * <p> * The comparison is based on the time-line position of the year-quarters. * * @param obj the object to check, null returns false * @return true if this is equal to the other year-quarter */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj instanceof YearQuarter) { YearQuarter other = (YearQuarter) obj; return year == other.year && quarter == other.quarter; } return false; } /** * A hash code for this year-quarter. * * @return a suitable hash code */ @Override public int hashCode() { return year ^ (quarter.getValue() << 27); } //----------------------------------------------------------------------- /** * Outputs this year-quarter as a {@code String}, such as {@code 2007-Q2}. * <p> * The output will be in the format {@code uuuu-'Q'Q}: * * @return a string representation of this year-quarter, not null */ @Override @ToString public String toString() { int absYear = Math.abs(year); StringBuilder buf = new StringBuilder(10); if (absYear < 1000) { if (year < 0) { buf.append(year - 10000).deleteCharAt(1); } else { buf.append(year + 10000).deleteCharAt(0); } } else { if (year > 9999) { buf.append('+'); } buf.append(year); } return buf.append('-').append(quarter).toString(); } }
/******************************************************************************* * Copyright (c) 2015-2018 Skymind, Inc. * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available 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. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ package org.nd4j.linalg.factory; import com.google.common.base.Function; import com.google.common.primitives.Ints; import com.google.common.primitives.Longs; import lombok.NonNull; import lombok.val; import lombok.var; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.io.LineIterator; import org.apache.commons.lang3.ArrayUtils; import org.bytedeco.javacpp.*; import org.bytedeco.javacpp.indexer.*; import org.nd4j.autodiff.samediff.serde.FlatBuffersMapper; import org.nd4j.base.Preconditions; import org.nd4j.config.ND4JEnvironmentVars; import org.nd4j.config.ND4JSystemProperties; import org.nd4j.context.Nd4jContext; import org.nd4j.graph.FlatArray; import org.nd4j.linalg.api.blas.params.MMulTranspose; import org.nd4j.linalg.api.buffer.BaseDataBuffer; import org.nd4j.linalg.api.buffer.DataBuffer; import org.nd4j.linalg.api.buffer.DataType; import org.nd4j.linalg.api.buffer.DataTypeEx; import org.nd4j.linalg.api.buffer.factory.DataBufferFactory; import org.nd4j.linalg.api.buffer.factory.DefaultDataBufferFactory; import org.nd4j.linalg.api.buffer.util.DataTypeUtil; import org.nd4j.linalg.api.concurrency.AffinityManager; import org.nd4j.linalg.api.concurrency.BasicAffinityManager; import org.nd4j.linalg.api.instrumentation.InMemoryInstrumentation; import org.nd4j.linalg.api.instrumentation.Instrumentation; import org.nd4j.linalg.api.memory.MemoryWorkspace; import org.nd4j.linalg.api.memory.MemoryWorkspaceManager; import org.nd4j.linalg.api.ndarray.*; import org.nd4j.linalg.api.ops.CustomOp; import org.nd4j.linalg.api.ops.DynamicCustomOp; import org.nd4j.linalg.api.ops.Op; import org.nd4j.linalg.api.ops.OpContext; import org.nd4j.linalg.api.ops.executioner.DefaultOpExecutioner; import org.nd4j.linalg.api.ops.executioner.OpExecutioner; import org.nd4j.linalg.api.ops.impl.indexaccum.IMax; import org.nd4j.linalg.api.ops.impl.indexaccum.IMin; import org.nd4j.linalg.api.ops.impl.reduce.Mmul; import org.nd4j.linalg.api.ops.impl.scalar.ReplaceNans; import org.nd4j.linalg.api.ops.impl.reduce.TensorMmul; import org.nd4j.linalg.api.ops.impl.scatter.ScatterUpdate; import org.nd4j.linalg.api.ops.impl.shape.Diag; import org.nd4j.linalg.api.ops.impl.shape.DiagPart; import org.nd4j.linalg.api.ops.impl.shape.Stack; import org.nd4j.linalg.api.ops.impl.transforms.same.OldReverse; import org.nd4j.linalg.api.ops.random.custom.RandomExponential; import org.nd4j.linalg.api.ops.random.impl.*; import org.nd4j.linalg.api.rng.DefaultRandom; import org.nd4j.linalg.api.rng.distribution.Distribution; import org.nd4j.linalg.api.rng.distribution.factory.DefaultDistributionFactory; import org.nd4j.linalg.api.rng.distribution.factory.DistributionFactory; import org.nd4j.linalg.api.shape.LongShapeDescriptor; import org.nd4j.linalg.api.shape.Shape; import org.nd4j.linalg.api.shape.options.ArrayOptionsHelper; import org.nd4j.linalg.cache.BasicConstantHandler; import org.nd4j.linalg.cache.ConstantHandler; import org.nd4j.linalg.compression.BasicNDArrayCompressor; import org.nd4j.linalg.compression.CompressedDataBuffer; import org.nd4j.linalg.convolution.ConvolutionInstance; import org.nd4j.linalg.convolution.DefaultConvolutionInstance; import org.nd4j.linalg.env.EnvironmentalAction; import org.nd4j.linalg.exception.ND4JArraySizeException; import org.nd4j.linalg.exception.ND4JIllegalStateException; import org.nd4j.linalg.exception.ND4JUnknownDataTypeException; import org.nd4j.linalg.factory.Nd4jBackend.NoAvailableBackendException; import org.nd4j.linalg.memory.BasicMemoryManager; import org.nd4j.linalg.memory.MemoryManager; import org.nd4j.linalg.memory.deallocation.DeallocatorService; import org.nd4j.linalg.primitives.Pair; import org.nd4j.linalg.string.NDArrayStrings; import org.nd4j.linalg.util.ArrayUtil; import org.nd4j.tools.PropertyParser; import org.nd4j.versioncheck.VersionCheck; import java.io.*; import java.lang.ref.ReferenceQueue; import java.lang.reflect.Constructor; import java.math.BigDecimal; import java.nio.ByteBuffer; import java.nio.channels.Channels; import java.nio.channels.WritableByteChannel; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.ParseException; import java.util.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.logging.Logger; /** * Creation of ndarrays via classpath discovery. * * @author Adam Gibson */ public class Nd4j { public final static String DATA_BUFFER_OPS = "databufferfactory"; public final static String CONVOLUTION_OPS = "convops"; /**@deprecated Use {@link ND4JSystemProperties#DTYPE}*/ @Deprecated public final static String DTYPE = ND4JSystemProperties.DTYPE; public final static String BLAS_OPS = "blas.ops"; public final static String SPARSE_BLAS_OPS = "sparseblas.ops"; public final static String NATIVE_OPS = "native.ops"; public final static String ORDER_KEY = "ndarray.order"; public final static String NDARRAY_FACTORY_CLASS = "ndarrayfactory.class"; public final static String SPARSE_NDARRAY_FACTORY_CLASS = "sparsendarrayfactory.class"; public final static String OP_EXECUTIONER = "opexec"; public final static String OP_FACTORY = "opfactory"; public final static String DISTRIBUTION = "dist"; public final static String INSTRUMENTATION = "instrumentation"; public final static String INSTRUMENTATION_CLASS = "instrumentation.class"; public final static String SHAPEINFO_PROVIDER = "shapeinfoprovider"; public final static String SPARSEINFO_PROVIDER = "sparseinfoprovider"; public final static String CONSTANT_PROVIDER = "constantsprovider"; public final static String AFFINITY_MANAGER = "affinitymanager"; //disable toString() on compressed arrays for debugging. Should be off by default. public final static String COMPRESSION_DEBUG = "compressiondebug"; public final static String MEMORY_MANAGER = "memorymanager"; public final static String WORKSPACE_MANAGER = "workspacemanager"; public final static String RANDOM_PROVIDER = "random"; /**@deprecated Use {@link ND4JSystemProperties#LOG_INITIALIZATION}*/ @Deprecated public static final String LOG_INIT_ENV_PROPERTY = ND4JSystemProperties.LOG_INITIALIZATION; //the datatype used for allocating buffers protected static DataType dtype = DataType.FLOAT; //the allocation mode for the heap public static DataBuffer.AllocationMode alloc = DataBuffer.AllocationMode.HEAP; public static char ORDER = 'c'; public static double EPS_THRESHOLD = 1e-5; public static boolean shouldInstrument = false; private static boolean allowsOrder = false; public static boolean compressDebug = false; public static volatile boolean preventUnpack; public static Nd4jBackend backend; public static RandomFactory randomFactory; private static MemoryWorkspaceManager workspaceManager; private static DeallocatorService deallocatorService; private static final AtomicInteger numThreads = new AtomicInteger(-1); private static AtomicReference<DataType> defaultFloatingPointDataType; protected static Class<? extends MemoryWorkspaceManager> workspaceManagerClazz; protected static Class<? extends BlasWrapper> blasWrapperClazz; protected static Class<? extends BlasWrapper> sparseBlasWrapperClazz; protected static Class<? extends NDArrayFactory> ndArrayFactoryClazz; protected static Class<? extends NDArrayFactory> sparseNDArrayClazz; protected static Class<? extends ConvolutionInstance> convolutionInstanceClazz; protected static Class<? extends DataBufferFactory> dataBufferFactoryClazz; protected static Class<? extends OpExecutioner> opExecutionerClazz; protected static Class<? extends org.nd4j.linalg.api.rng.Random> randomClazz; protected static Class<? extends DistributionFactory> distributionFactoryClazz; protected static Class<? extends Instrumentation> instrumentationClazz; protected static Class<? extends BaseShapeInfoProvider> shapeInfoProviderClazz; protected static Class<? extends BaseSparseInfoProvider> sparseInfoProviderClazz; protected static Class<? extends BasicConstantHandler> constantProviderClazz; protected static Class<? extends BasicAffinityManager> affinityManagerClazz; protected static Class<? extends BasicMemoryManager> memoryManagerClazz; protected static DataBufferFactory DATA_BUFFER_FACTORY_INSTANCE; protected static BlasWrapper BLAS_WRAPPER_INSTANCE; protected static BlasWrapper SPARSE_BLAS_WRAPPER_INSTANCE; protected static NDArrayFactory INSTANCE; protected static NDArrayFactory SPARSE_INSTANCE; protected static ConvolutionInstance CONVOLUTION_INSTANCE; protected static OpExecutioner OP_EXECUTIONER_INSTANCE; protected static DistributionFactory DISTRIBUTION_FACTORY; protected static Instrumentation instrumentation; protected static ShapeInfoProvider shapeInfoProvider; protected static SparseInfoProvider sparseInfoProvider; protected static ConstantHandler constantHandler; protected static AffinityManager affinityManager; protected static MemoryManager memoryManager; protected static AtomicBoolean fallbackMode; protected static Properties props = new Properties(); protected static ReferenceQueue<INDArray> referenceQueue = new ReferenceQueue<>(); protected static ReferenceQueue<DataBuffer> bufferQueue = new ReferenceQueue<>(); private final static Logger logger = Logger.getLogger(Nd4j.class.getName()); protected static final INDArray[] EMPTY_ARRAYS = new INDArray[DataType.values().length]; static { fallbackMode = new AtomicBoolean(false); Nd4j nd4j = new Nd4j(); nd4j.initContext(); } public enum PadMode { CONSTANT, EDGE, LINEAR_RAMP, MAXIMUM, MEAN, MEDIAN, MINIMUM, REFLECT, SYMMETRIC, WRAP } /** * Pad the given ndarray to the size along each dimension * @param toPad the ndarray to pad * @param padWidth the width to pad along each dimension * @param padMode the mode to pad in * @return the padded ndarray * based on the specified mode */ public static INDArray pad(INDArray toPad, int[][] padWidth, PadMode padMode) { return pad(toPad, padWidth, ArrayUtil.zerosMatrix(toPad.shape()), padMode); } /** * Pad the given ndarray to the size along each dimension * @param toPad the ndarray to pad * @param padWidth the width to pad along each dimension * @param constantValues the values to append for each dimension * @param padMode the mode to pad in * @return the padded ndarray * based on the specified mode */ public static INDArray pad(INDArray toPad, int[][] padWidth, List<double[]> constantValues, PadMode padMode) { switch (padMode) { case CONSTANT: if (padWidth.length < toPad.rank()) throw new IllegalArgumentException("Please specify a pad width for each dimension"); List<int[]> sizes = new ArrayList<>(); for (int i = 0; i < toPad.rank(); i++) { sizes.add(padWidth[i]); } INDArray ret = toPad; for (int i = 0; i < toPad.rank(); i++) { int[] pad = sizes.get(i); double[] constant = constantValues.get(i); int padBefore = pad[0]; int padAfter = pad[1]; if (constant.length < 2) { double val = constant[0]; constant = new double[2]; constant[0] = val; constant[1] = val; } double beforeVal = constant[0]; double afterVal = constant[1]; ret = Nd4j.prepend(ret, padBefore, beforeVal, i); ret = Nd4j.append(ret, padAfter, afterVal, i); } return ret; default: throw new UnsupportedOperationException(); } } /** * Pad the given ndarray to the size along each dimension * @param toPad the ndarray to pad * @param padWidth the width to pad along each dimension * @param constantValues the values to append for each dimension * @param padMode the mode to pad in * @return the padded ndarray * based on the specified mode */ public static INDArray pad(INDArray toPad, int[] padWidth, List<double[]> constantValues, PadMode padMode) { switch (padMode) { case CONSTANT: if (padWidth.length < toPad.rank()) throw new IllegalArgumentException("Please specify a pad width for each dimension"); toPad = Nd4j.stripOnes(toPad); List<int[]> sizes = new ArrayList<>(); for (int i = 0; i < toPad.rank(); i++) { sizes.add(padWidth); } INDArray ret = toPad; for (int i = 0; i < toPad.rank(); i++) { int[] pad = sizes.get(i); double[] constant = constantValues.get(i); int padBefore = pad[0]; int padAfter = pad[1]; if (constant.length < 2) { double val = constant[0]; constant = new double[2]; constant[0] = val; constant[1] = val; } double beforeVal = constant[0]; double afterVal = constant[1]; ret = Nd4j.prepend(ret, padBefore, beforeVal, i); ret = Nd4j.append(ret, padAfter, afterVal, i); } return ret; default: throw new UnsupportedOperationException(); } } /** * Pad the given ndarray to the size along each dimension * @param toPad the ndarray to pad * @param padWidth the width to pad along each dimension * @param padMode the mode to pad in * @return the padded ndarray * based on the specified mode */ public static INDArray pad(INDArray toPad, int[] padWidth, PadMode padMode) { return pad(toPad, padWidth, ArrayUtil.zerosMatrix(padWidth), padMode); } /** * Append the given * array with the specified value size * along a particular axis * @param arr the array to append to * @param padAmount the pad amount of the array to be returned * @param val the value to append * @param axis the axis to append to * @return the newly created array */ public static INDArray append(INDArray arr, int padAmount, double val, int axis) { if (padAmount == 0) return arr; long[] paShape = ArrayUtil.copy(arr.shape()); if (axis < 0) axis = axis + arr.shape().length; paShape[axis] = padAmount; INDArray concatArray = Nd4j.valueArrayOf(paShape, val, arr.dataType()); return Nd4j.concat(axis, arr, concatArray); } /** * Append the given * array with the specified value size * along a particular axis * @param arr the array to append to * @param padAmount the pad amount of the array to be returned * @param val the value to append * @param axis the axis to append to * @return the newly created array */ public static INDArray prepend(INDArray arr, int padAmount, double val, int axis) { if (padAmount == 0) return arr; long[] paShape = ArrayUtil.copy(arr.shape()); if (axis < 0) axis = axis + arr.shape().length; paShape[axis] = padAmount; INDArray concatArr = Nd4j.valueArrayOf(paShape, val, arr.dataType()); return Nd4j.concat(axis, concatArr, arr); } /** * Expand the array dimensions. * This is equivalent to * adding a new axis dimension * @param input the input array * @param dimension the dimension to add the * new axis at * @return the array with the new axis dimension */ public static INDArray expandDims(INDArray input, int dimension) { if (dimension < 0) dimension += input.rank(); long[] shape = input.shape(); long[] indexes = new long[input.rank() + 1]; for (int i = 0; i < indexes.length; i++) indexes[i] = i < dimension ? shape[i] : i == dimension ? 1 : shape[i - 1]; return input.reshape(input.ordering(), indexes); } /** * Squeeze : removes a dimension of size 1 * @param input the input array * @param dimension the dimension to remove * @return the array with dimension removed */ public static INDArray squeeze(INDArray input, int dimension) { if (dimension < 0){ dimension += input.rank(); } long[] shape = input.shape(); Preconditions.checkState(shape[dimension] == 1, String.format("Squeeze: Only dimension of size 1 can be squeezed. " + "Attempted to squeeze dimension %d of array with shape %s (size %d).", dimension, ArrayUtils.toString(shape), shape[dimension])); long[] newShape = ArrayUtil.removeIndex(shape, dimension); return input.reshape(input.ordering(), newShape); } /** * Backend specific: * Returns whether specifying the order * for the blas impl is allowed (cblas) * @return true if the blas impl * can support specifying array order */ public static boolean allowsSpecifyOrdering() { return allowsOrder; } /** * In place shuffle of an ndarray * along a specified set of dimensions * @param toShuffle the ndarray to shuffle * @param random the random to use * @param dimension the dimension to do the shuffle * @return */ public static void shuffle(INDArray toShuffle, Random random, int... dimension) { INSTANCE.shuffle(toShuffle, random, dimension); } /** * In place shuffle of an ndarray * along a specified set of dimensions * @param toShuffle the ndarray to shuffle * @param dimension the dimension to do the shuffle * @return */ public static void shuffle(INDArray toShuffle, int... dimension) { //shuffle(toShuffle, new Random(), dimension); INSTANCE.shuffle(toShuffle, new Random(), dimension); } /** * Symmetric in place shuffle of an ndarray * along a specified set of dimensions * @param toShuffle the ndarray to shuffle * @param dimension the dimension to do the shuffle * @return */ public static void shuffle(Collection<INDArray> toShuffle, int... dimension) { //shuffle(toShuffle, new Random(), dimension); INSTANCE.shuffle(toShuffle, new Random(), dimension); } /** * Symmetric in place shuffle of an ndarray * along a specified set of dimensions * @param toShuffle the ndarray to shuffle * @param dimension the dimension to do the shuffle * @return */ public static void shuffle(Collection<INDArray> toShuffle, Random rnd, int... dimension) { //shuffle(toShuffle, new Random(), dimension); INSTANCE.shuffle(toShuffle, rnd, dimension); } /** * Symmetric in place shuffle of an ndarray * along a variable dimensions * * @param toShuffle the ndarray to shuffle * @param dimensions the dimension to do the shuffle. Please note - order matters here. * @return */ public static void shuffle(List<INDArray> toShuffle, Random rnd, List<int[]> dimensions) { INSTANCE.shuffle(toShuffle, rnd, dimensions); } /** * The reference queue used for cleaning up * ndarrays * * @return the reference queue for cleaning up ndarrays */ public static ReferenceQueue<INDArray> refQueue() { return referenceQueue; } /** * The reference queue used for cleaning up * databuffers * * @return the reference queue for cleaning up databuffers */ public static ReferenceQueue<DataBuffer> bufferRefQueue() { return bufferQueue; } /** * Gets the instrumentation instance * * @return the instrumentation instance */ public static Instrumentation getInstrumentation() { return instrumentation; } /** * Get the primary distributions * factory * * @return the primary distributions */ public static DistributionFactory getDistributions() { return DISTRIBUTION_FACTORY; } public static void setNdArrayFactoryClazz(Class<? extends NDArrayFactory> clazz) { ndArrayFactoryClazz = clazz; } public static void setSparseNDArrayClazz(Class<? extends NDArrayFactory> clazz) { sparseNDArrayClazz = clazz; } /** * Get the current random generator * * @return the current random generator */ public static org.nd4j.linalg.api.rng.Random getRandom() { return randomFactory.getRandom(); } /** * This method returns RandomFactory instance * * @return */ public static RandomFactory getRandomFactory() { return randomFactory; } /** * Get the convolution singleton * * @return the convolution singleton */ public static ConvolutionInstance getConvolution() { return CONVOLUTION_INSTANCE; } /** * Set a convolution instance * * @param convolutionInstance */ public static void setConvolution(ConvolutionInstance convolutionInstance) { if (convolutionInstance == null) throw new IllegalArgumentException("No null instances allowed"); CONVOLUTION_INSTANCE = convolutionInstance; } /** * Returns the shape of the ndarray * @param arr the array to get the shape of * @return the shape of tihs ndarray */ public static long[] shape(INDArray arr) { return arr.shape(); } /** * Create an ndarray based on the given data * @param sliceShape the shape of each slice * @param arrays the arrays of data to create * @return the ndarray of the specified shape where * number of slices is equal to array length and each * slice is the specified shape */ public static INDArray create(int[] sliceShape, float[]... arrays) { int slices = arrays.length; INDArray ret = Nd4j.create(ArrayUtil.combine(new int[] {slices}, sliceShape)); for (int i = 0; i < ret.slices(); i++) ret.putSlice(i, Nd4j.create(arrays[i]).reshape(ArrayUtil.toLongArray(sliceShape))); return ret; } public static INDArray create(LongShapeDescriptor descriptor) { return create(descriptor, true); } public static INDArray create(LongShapeDescriptor descriptor, boolean initialize) { if(descriptor.isEmpty()){ return Nd4j.empty(descriptor.dataType()); } if (initialize) return create(descriptor.dataType(), descriptor.getShape(), descriptor.getStride(), descriptor.getOrder()); else return createUninitialized(descriptor.dataType(), descriptor.getShape(), descriptor.getOrder()); } /** * Create an ndarray based on the given data * @param sliceShape the shape of each slice * @param arrays the arrays of data to create * @return the ndarray of the specified shape where * number of slices is equal to array length and each * slice is the specified shape */ public static INDArray create(int[] sliceShape, double[]... arrays) { int slices = arrays.length; INDArray ret = Nd4j.create(ArrayUtil.combine(new int[] {slices}, sliceShape)); for (int i = 0; i < ret.slices(); i++) ret.putSlice(i, Nd4j.create(arrays[i]).reshape(ArrayUtil.toLongArray(sliceShape))); return ret; } /** * Get the operation executioner instance * * @return the operation executioner instance */ public static OpExecutioner getExecutioner() { return OP_EXECUTIONER_INSTANCE; } /** * * @return */ public static DataBufferFactory getDataBufferFactory() { return DATA_BUFFER_FACTORY_INSTANCE; } /** * Given a sequence of Iterators over a transform of matrices, fill in all of * the matrices with the entries in the theta vector. Errors are * thrown if the theta vector does not exactly fill the matrices. */ public static void setParams(INDArray theta, Collection<INDArray>... matrices) { int index = 0; for (Collection<INDArray> matrixCollection : matrices) { for (INDArray matrix : matrixCollection) { INDArray linear = matrix.reshape(-1); for (int i = 0; i < matrix.length(); i++) { linear.putScalar(i, theta.getDouble(index)); index++; } } } if (index != theta.length()) { throw new AssertionError("Did not entirely use the theta vector"); } } /** * Roll the specified axis backwards, * until it lies in a given position. * Starting ends up being zero. * See numpy's rollaxis * @param a the array to roll * @param axis the axis to roll backwards * @return the rolled ndarray */ public static INDArray rollAxis(INDArray a, int axis) { return rollAxis(a, axis, 0); } /** * * @param arr * @param dimension * @return */ public static INDArray argMax(INDArray arr, int... dimension) { IMax imax = new IMax(arr, dimension); return Nd4j.getExecutioner().exec(imax); } /** * * @param arr * @param dimension * @return */ public static INDArray argMin(INDArray arr, int... dimension) { IMin imin = new IMin(arr, dimension); return Nd4j.getExecutioner().exec(imin); } /** * Roll the specified axis backwards, * until it lies in a given position. * See numpy's rollaxis * @param a the array to roll * @param axis the axis to roll backwards * @param start the starting point * @return the rolled ndarray */ public static INDArray rollAxis(INDArray a, int axis, int start) { if (axis < 0) axis += a.rank(); if (start < 0) start += a.rank(); if (axis == start) return a; if (axis < start) start--; if (!(axis >= 0 && axis < a.rank())) throw new IllegalArgumentException("Axis must be >= 0 && < start"); if (!(start >= 0 && axis < a.rank() + 1)) throw new IllegalArgumentException("Axis must be >= 0 && < start"); List<Integer> range = new ArrayList<>(Ints.asList(ArrayUtil.range(0, a.rank()))); range.remove(axis); range.add(start, axis); int[] newRange = Ints.toArray(range); return a.permute(newRange); } /** * Tensor matrix multiplication. * Both tensors must be the same rank * * @param a the left tensor * @param b the right tensor * @param result the result array * @param axes the axes for each array to do matrix multiply along * @return */ public static INDArray tensorMmul(INDArray a, INDArray b,INDArray result, int[][] axes) { int validationLength = Math.min(axes[0].length, axes[1].length); for (int i = 0; i < validationLength; i++) { if (a.size(axes[0][i]) != b.size(axes[1][i])) throw new IllegalArgumentException("Size of the given axes at each dimension must be the same size."); if (axes[0][i] < 0) axes[0][i] += a.rank(); if (axes[1][i] < 0) axes[1][i] += b.rank(); } List<Integer> listA = new ArrayList<>(); for (int i = 0; i < a.rank(); i++) { if (!Ints.contains(axes[0], i)) listA.add(i); } int[] newAxesA = Ints.concat(Ints.toArray(listA), axes[0]); List<Integer> listB = new ArrayList<>(); for (int i = 0; i < b.rank(); i++) { if (!Ints.contains(axes[1], i)) listB.add(i); } int[] newAxesB = Ints.concat(axes[1], Ints.toArray(listB)); int n2 = 1; int aLength = Math.min(a.rank(), axes[0].length); for (int i = 0; i < aLength; i++) { n2 *= a.size(axes[0][i]); } //if listA and listB are empty these donot initialize. //so initializing with {1} which will then get overriden if not empty long[] newShapeA = {-1, n2}; long[] oldShapeA; if (listA.size() == 0) { oldShapeA = new long[] {1}; } else { oldShapeA = Longs.toArray(listA); for (int i = 0; i < oldShapeA.length; i++) oldShapeA[i] = a.size((int) oldShapeA[i]); } int n3 = 1; int bNax = Math.min(b.rank(), axes[1].length); for (int i = 0; i < bNax; i++) { n3 *= b.size(axes[1][i]); } long[] newShapeB = {n3, -1}; long[] oldShapeB; if (listB.size() == 0) { oldShapeB = new long[] {1}; } else { oldShapeB = Longs.toArray(listB); for (int i = 0; i < oldShapeB.length; i++) oldShapeB[i] = b.size((int) oldShapeB[i]); } INDArray at = a.permute(newAxesA).reshape(newShapeA); INDArray bt = b.permute(newAxesB).reshape(newShapeB); INDArray ret = at.mmul(bt,result); long[] aPlusB = Longs.concat(oldShapeA, oldShapeB); return ret.reshape(aPlusB); } /** * Tensor matrix multiplication. * Both tensors must be the same rank * * @param a the left tensor * @param b the right tensor * @param axes the axes for each array to do matrix multiply along * @return */ public static INDArray tensorMmul(INDArray a, INDArray b, int[][] axes) { CustomOp op = DynamicCustomOp.builder("tensordot") .addInputs(a, b) .addIntegerArguments(axes[0].length) .addIntegerArguments(axes[0]) .addIntegerArguments(axes[1].length) .addIntegerArguments(axes[1]) .build(); List<LongShapeDescriptor> l = op.calculateOutputShape(); INDArray out = Nd4j.create(l.get(0).asDataType(a.dataType())); op.addOutputArgument(out); Nd4j.exec(op); return out; } /** * * matrix multiply: implements op(a)*op(b) * * where op(x) means transpose x (or not) depending on * setting of arguments transposea and transposeb.<br> * so gemm(a,b,false,false) == a.mmul(b), gemm(a,b,true,false) == a.transpose().mmul(b) etc. * @param a first matrix * @param b second matrix * @param transposeA if true: transpose matrix a before mmul * @param transposeB if true: transpose matrix b before mmul * @return result */ public static INDArray gemm(INDArray a, INDArray b, boolean transposeA, boolean transposeB) { long cRows = (transposeA ? a.columns() : a.rows()); long cCols = (transposeB ? b.rows() : b.columns()); INDArray c = Nd4j.createUninitialized(a.dataType(), new long[] {cRows, cCols}, 'f'); return gemm(a, b, c, transposeA, transposeB, 1.0, 0.0); } /** Matrix multiply: Implements c = alpha*op(a)*op(b) + beta*c where op(X) means transpose X (or not) * depending on setting of arguments transposeA and transposeB.<br> * Note that matrix c MUST be fortran order, have zero offset and have c.data().length == c.length(). * i.e., the result array must not be a view. An exception will be thrown otherwise.<br> * (Note: some views are allowed, if and only if they have f order and are contiguous in the buffer other than an * offset. Put another way, they must be f order and have strides identical to a non-view/default array of the same shape)<br> * Don't use this unless you know about level 3 blas and NDArray storage orders. * @param a First matrix * @param b Second matrix * @param c result matrix. Used in calculation (assuming beta != 0) and result is stored in this. f order, and not a view only * @param transposeA if true: transpose matrix a before mmul * @param transposeB if true: transpose matrix b before mmul * @return result, i.e., matrix c is returned for convenience */ public static INDArray gemm(INDArray a, INDArray b, INDArray c, boolean transposeA, boolean transposeB, double alpha, double beta) { //Note: some views have non-zero offset but 'default' strides (these are OK). And a 'c' order vector such as [10,1] is OK - same buffer as an 'f' order vector with same shape Preconditions.checkState(c.length() == 1 || c.ordering() == 'f' && Shape.hasDefaultStridesForShape(c) || c.isVectorOrScalar() && c.elementWiseStride() == 1, "C (result) array is not F order or is a view. Nd4j.gemm requires the result array to be F order " + "and not a view. C (result) array: [%ndSInfo]", c); getBlasWrapper().level3().gemm(a, b, c, transposeA, transposeB, alpha, beta); return c; } /** * Matrix multiplication/dot product * * Depending on inputs dimensionality output result might be different. * matrix x matrix = BLAS gemm * vector x matrix = BLAS gemm * vector x vector = BLAS dot * vector x scalar = element-wise mul * scalar x vector = element-wise mul * tensor x tensor = matrix multiplication using the last two dimensions * * Transpose operations only available where applicable. In the * tensor x tensor case it will be applied only to the last two dimensions. * * @param a First tensor * @param b Second tensor * @param result result matrix. * @param transposeA if true: transpose matrix a before mmul * @param transposeB if true: transpose matrix b before mmul * @param transposeResult if true: result matrix will be transposed * @return result, i.e., result matrix is returned for convenience */ public static INDArray matmul(INDArray a, INDArray b, INDArray result, boolean transposeA, boolean transposeB, boolean transposeResult){ final Mmul op = new Mmul(a, b, result, MMulTranspose.builder() .transposeA(transposeA) .transposeB(transposeB) .transposeResult(transposeResult).build()); return exec(op)[0]; } /** * Matrix multiplication/dot product * * @see #matmul(INDArray, INDArray, INDArray, boolean, boolean, boolean) */ public static INDArray matmul(INDArray a, INDArray b, INDArray result){ final Mmul op = new Mmul(a, b, result, null); return exec(op)[0]; } /** * Matrix multiplication/dot product * * @see #matmul(INDArray, INDArray, INDArray, boolean, boolean, boolean) */ public static INDArray matmul(INDArray a, INDArray b, boolean transposeA, boolean transposeB, boolean transposeResult){ return matmul(a, b, null, transposeA, transposeB, transposeResult); } /** * Matrix multiplication/dot product * * @see #matmul(INDArray, INDArray, INDArray, boolean, boolean, boolean) */ public static INDArray matmul(INDArray a, INDArray b){ return matmul(a,b, null); } /** * Given a sequence of Iterators over a transform of matrices, fill in all of * the matrices with the entries in the theta vector. Errors are * thrown if the theta vector does not exactly fill the matrices. */ public static void setParams(INDArray theta, Iterator<? extends INDArray>... matrices) { int index = 0; for (Iterator<? extends INDArray> matrixIterator : matrices) { while (matrixIterator.hasNext()) { INDArray matrix = matrixIterator.next().reshape(-1); for (int i = 0; i < matrix.length(); i++) { matrix.putScalar(i, theta.getDouble(index)); index++; } } } if (index != theta.length()) { throw new AssertionError("Did not entirely use the theta vector"); } } private static void logCreationIfNecessary(DataBuffer log) { if (shouldInstrument) Nd4j.getInstrumentation().log(log); } private static void logCreationIfNecessary(INDArray log) { if (shouldInstrument) Nd4j.getInstrumentation().log(log); } /** * The factory used for creating ndarrays * * @return the factory instance used for creating ndarrays */ public static NDArrayFactory factory() { return INSTANCE; } public static NDArrayFactory sparseFactory() { return SPARSE_INSTANCE; } public static INDArray cumsum(INDArray compute) { return compute.cumsum(Integer.MAX_VALUE); } public static INDArray max(INDArray compute) { return compute.max(Integer.MAX_VALUE); } public static INDArray min(INDArray compute) { return compute.min(Integer.MAX_VALUE); } public static INDArray prod(INDArray compute) { return compute.prod(Integer.MAX_VALUE); } public static INDArray normmax(INDArray compute) { return compute.normmax(Integer.MAX_VALUE); } public static INDArray norm2(INDArray compute) { return compute.norm2(Integer.MAX_VALUE); } public static INDArray norm1(INDArray compute) { return compute.norm1(Integer.MAX_VALUE); } public static INDArray std(INDArray compute) { return compute.std(Integer.MAX_VALUE); } public static INDArray var(INDArray compute) { return compute.var(Integer.MAX_VALUE); } public static INDArray sum(INDArray compute) { return compute.sum(Integer.MAX_VALUE); } public static INDArray mean(INDArray compute) { return compute.mean(Integer.MAX_VALUE); } public static INDArray cumsum(INDArray compute, int dimension) { return compute.cumsum(dimension); } public static INDArray max(INDArray compute, int dimension) { return compute.max(dimension); } public static INDArray min(INDArray compute, int dimension) { return compute.min(dimension); } public static INDArray prod(INDArray compute, int dimension) { return compute.prod(dimension); } public static INDArray normmax(INDArray compute, int dimension) { return compute.normmax(dimension); } public static INDArray norm2(INDArray compute, int dimension) { return compute.norm2(dimension); } public static INDArray norm1(INDArray compute, int dimension) { return compute.norm1(dimension); } public static INDArray std(INDArray compute, int dimension) { return compute.std(dimension); } public static INDArray var(INDArray compute, int dimension) { return compute.var(dimension); } public static INDArray sum(INDArray compute, int dimension) { return compute.sum(dimension); } public static INDArray mean(INDArray compute, int dimension) { return compute.mean(dimension); } /** * Create a view of a data buffer * that leverages the underlying storage of the buffer * with a new view * @param underlyingBuffer the underlying buffer * @param offset the offset for the view * @return the new view of the data buffer */ public static DataBuffer createBuffer(DataBuffer underlyingBuffer, long offset, long length) { return DATA_BUFFER_FACTORY_INSTANCE.create(underlyingBuffer, offset, length); } /** * * Create a buffer equal of length prod(shape) * * @param shape the shape of the buffer to create * @param type the opType to create * @return the created buffer */ public static DataBuffer createBuffer(int[] shape, DataType type, long offset) { int length = ArrayUtil.prod(shape); return type == DataType.DOUBLE ? createBuffer(new double[length], offset) : createBuffer(new float[length], offset); } /** * Creates a buffer of the specified opType * and length with the given byte buffer. * * This will wrap the buffer as a reference (no copy) * if the allocation opType is the same. * @param buffer the buffer to create from * @param type the opType of buffer to create * @param length the length of the buffer * @return */ public static DataBuffer createBuffer(ByteBuffer buffer, DataType type, int length, long offset) { switch (type) { case INT: return DATA_BUFFER_FACTORY_INSTANCE.createInt(offset, buffer, length); case DOUBLE: return DATA_BUFFER_FACTORY_INSTANCE.createDouble(offset, buffer, length); case FLOAT: return DATA_BUFFER_FACTORY_INSTANCE.createFloat(offset, buffer, length); default: throw new IllegalArgumentException("Illegal opType " + type); } } /** * Create a buffer based on the data opType * * @param data the data to create the buffer with * @return the created buffer */ public static DataBuffer createBuffer(byte[] data, int length, long offset) { DataBuffer ret; if (dataType() == DataType.DOUBLE) ret = DATA_BUFFER_FACTORY_INSTANCE.createDouble(offset, data, length); else ret = DATA_BUFFER_FACTORY_INSTANCE.createFloat(offset, data, length); logCreationIfNecessary(ret); return ret; } /** * Create a buffer equal of length prod(shape) * * @param data the shape of the buffer to create * @return the created buffer */ public static DataBuffer createBuffer(int[] data, long offset) { DataBuffer ret = createTypedBuffer(data, DataType.INT, Nd4j.getMemoryManager().getCurrentWorkspace()); logCreationIfNecessary(ret); return ret; } /** * Creates a buffer of the specified length based on the data opType * * @param length the length of te buffer * @return the buffer to create */ public static DataBuffer createBuffer(int length, long offset) { DataBuffer ret; if (dataType() == DataType.FLOAT) ret = DATA_BUFFER_FACTORY_INSTANCE.createFloat(offset, length); else if (dataType() == DataType.INT) ret = DATA_BUFFER_FACTORY_INSTANCE.createInt(offset, length); else if (dataType() == DataType.DOUBLE) ret = DATA_BUFFER_FACTORY_INSTANCE.createDouble(offset, length); else if (dataType() == DataType.HALF) ret = DATA_BUFFER_FACTORY_INSTANCE.createHalf(offset, length); else ret = null; logCreationIfNecessary(ret); return ret; } protected static Indexer getIndexerByType(Pointer pointer, DataType dataType) { switch (dataType) { case LONG: return LongIndexer.create((LongPointer) pointer); case INT: return IntIndexer.create((IntPointer) pointer); case SHORT: return ShortIndexer.create((ShortPointer) pointer); case BYTE: return ByteIndexer.create((BytePointer) pointer); case UBYTE: return UByteIndexer.create((BytePointer) pointer); case BOOL: return BooleanIndexer.create((BooleanPointer) pointer); case FLOAT: return FloatIndexer.create((FloatPointer) pointer); case HALF: return HalfIndexer.create((ShortPointer) pointer); case DOUBLE: return DoubleIndexer.create((DoublePointer) pointer); default: throw new UnsupportedOperationException(); } } public static DataBuffer createBuffer(@NonNull Pointer pointer, long length, @NonNull DataType dataType) { Pointer nPointer = null; switch (dataType) { case LONG: nPointer = new LongPointer(pointer); break; case INT: nPointer = new IntPointer(pointer); break; case SHORT: nPointer = new ShortPointer(pointer); break; case BYTE: nPointer = new BytePointer(pointer); break; case UBYTE: nPointer = new BytePointer(pointer); break; case BOOL: nPointer = new BooleanPointer(pointer); break; case FLOAT: nPointer = new FloatPointer(pointer); break; case HALF: nPointer = new ShortPointer(pointer); break; case DOUBLE: nPointer = new DoublePointer(pointer); break; default: throw new UnsupportedOperationException("Unsupported data type: " + dataType); } return DATA_BUFFER_FACTORY_INSTANCE.create(nPointer, dataType, length, getIndexerByType(nPointer, dataType)); } /** * Create a buffer based on the data opType * * @param data the data to create the buffer with * @return the created buffer */ public static DataBuffer createBuffer(float[] data, long offset) { val ndata = Arrays.copyOfRange(data, (int) offset, data.length); DataBuffer ret = createTypedBuffer(ndata, DataType.FLOAT, Nd4j.getMemoryManager().getCurrentWorkspace()); logCreationIfNecessary(ret); return ret; } /** * Create a buffer based on the data opType * * @param data the data to create the buffer with * @return the created buffer */ public static DataBuffer createBuffer(double[] data, long offset) { val ndata = Arrays.copyOfRange(data, (int) offset, data.length); DataBuffer ret = createTypedBuffer(ndata, DataType.DOUBLE, Nd4j.getMemoryManager().getCurrentWorkspace()); logCreationIfNecessary(ret); return ret; } /** * Create a buffer equal of length prod(shape) * * @param shape the shape of the buffer to create * @param type the opType to create * @return the created buffer */ public static DataBuffer createBuffer(int[] shape, DataType type) { long length = ArrayUtil.prodLong(shape); if (type == DataType.INT) return Nd4j.getMemoryManager().getCurrentWorkspace() == null ? DATA_BUFFER_FACTORY_INSTANCE.createInt(length, true) : DATA_BUFFER_FACTORY_INSTANCE.createInt(length, true, Nd4j.getMemoryManager().getCurrentWorkspace()); else if (type == DataType.LONG) return Nd4j.getMemoryManager().getCurrentWorkspace() == null ? DATA_BUFFER_FACTORY_INSTANCE.createLong(length, true) : DATA_BUFFER_FACTORY_INSTANCE.createLong(length, true, Nd4j.getMemoryManager().getCurrentWorkspace()); else if (type == DataType.HALF) return Nd4j.getMemoryManager().getCurrentWorkspace() == null ? DATA_BUFFER_FACTORY_INSTANCE.createHalf(length, true) : DATA_BUFFER_FACTORY_INSTANCE.createHalf(length, true, Nd4j.getMemoryManager().getCurrentWorkspace()); else if (type == DataType.DOUBLE) return Nd4j.getMemoryManager().getCurrentWorkspace() == null ? DATA_BUFFER_FACTORY_INSTANCE.createDouble(length, true) : DATA_BUFFER_FACTORY_INSTANCE.createDouble(length, true, Nd4j.getMemoryManager().getCurrentWorkspace()); else return Nd4j.getMemoryManager().getCurrentWorkspace() == null ? DATA_BUFFER_FACTORY_INSTANCE.createFloat(length, true) : DATA_BUFFER_FACTORY_INSTANCE.createFloat(length, true, Nd4j.getMemoryManager().getCurrentWorkspace()); } public static DataBuffer createBufferDetached(int[] shape, DataType type) { long length = ArrayUtil.prodLong(shape); if (type == DataType.INT) return DATA_BUFFER_FACTORY_INSTANCE.createInt(length); if (type == DataType.LONG) return DATA_BUFFER_FACTORY_INSTANCE.createLong(new long[]{length}); else if (type == DataType.HALF) return DATA_BUFFER_FACTORY_INSTANCE.createHalf(length); return type == DataType.DOUBLE ? DATA_BUFFER_FACTORY_INSTANCE.createDouble(length) : DATA_BUFFER_FACTORY_INSTANCE.createFloat(length); } public static DataBuffer createBuffer(long[] shape, DataType type) { long length = ArrayUtil.prodLong(shape); if (type == DataType.INT) return Nd4j.getMemoryManager().getCurrentWorkspace() == null ? DATA_BUFFER_FACTORY_INSTANCE.createInt(length, true) : DATA_BUFFER_FACTORY_INSTANCE.createInt(length, true, Nd4j.getMemoryManager().getCurrentWorkspace()); else if (type == DataType.LONG) return Nd4j.getMemoryManager().getCurrentWorkspace() == null ? DATA_BUFFER_FACTORY_INSTANCE.createLong(length, true) : DATA_BUFFER_FACTORY_INSTANCE.createLong(length, true, Nd4j.getMemoryManager().getCurrentWorkspace()); else if (type == DataType.HALF) return Nd4j.getMemoryManager().getCurrentWorkspace() == null ? DATA_BUFFER_FACTORY_INSTANCE.createHalf(length, true) : DATA_BUFFER_FACTORY_INSTANCE.createHalf(length, true, Nd4j.getMemoryManager().getCurrentWorkspace()); else if (type == DataType.DOUBLE) return Nd4j.getMemoryManager().getCurrentWorkspace() == null ? DATA_BUFFER_FACTORY_INSTANCE.createDouble(length, true) : DATA_BUFFER_FACTORY_INSTANCE.createDouble(length, true, Nd4j.getMemoryManager().getCurrentWorkspace()); else return Nd4j.getMemoryManager().getCurrentWorkspace() == null ? DATA_BUFFER_FACTORY_INSTANCE.createFloat(length, true) : DATA_BUFFER_FACTORY_INSTANCE.createFloat(length, true, Nd4j.getMemoryManager().getCurrentWorkspace()); } public static DataBuffer createBufferDetached(long[] shape, DataType type) { long length = ArrayUtil.prodLong(shape); switch (type){ case DOUBLE: DATA_BUFFER_FACTORY_INSTANCE.createDouble(length); case FLOAT: DATA_BUFFER_FACTORY_INSTANCE.createFloat(length); case HALF: return DATA_BUFFER_FACTORY_INSTANCE.createHalf(length); case LONG: return DATA_BUFFER_FACTORY_INSTANCE.createLong(length); case INT: return DATA_BUFFER_FACTORY_INSTANCE.createInt(length); case SHORT: case UBYTE: case BYTE: case BOOL: case UTF8: case COMPRESSED: case UNKNOWN: default: throw new UnsupportedOperationException("Cannot create type: " + type); } } /** * Creates a buffer of the specified opType * and length with the given byte buffer. * * This will wrap the buffer as a reference (no copy) * if the allocation opType is the same. * @param buffer the buffer to create from * @param type the opType of buffer to create * @param length the length of the buffer * @return */ public static DataBuffer createBuffer(ByteBuffer buffer, DataType type, int length) { switch (type) { case INT: return DATA_BUFFER_FACTORY_INSTANCE.createInt(buffer, length); case LONG: return DATA_BUFFER_FACTORY_INSTANCE.createLong(buffer, length); case DOUBLE: return DATA_BUFFER_FACTORY_INSTANCE.createDouble(buffer, length); case FLOAT: return DATA_BUFFER_FACTORY_INSTANCE.createFloat(buffer, length); case HALF: return DATA_BUFFER_FACTORY_INSTANCE.createHalf(buffer, length); default: throw new IllegalArgumentException("Illegal opType " + type); } } /** * Create a buffer based on the data opType * * @param data the data to create the buffer with * @return the created buffer */ public static DataBuffer createBuffer(byte[] data, int length) { DataBuffer ret; if (dataType() == DataType.DOUBLE) ret = DATA_BUFFER_FACTORY_INSTANCE.createDouble(data, length); else if (dataType() == DataType.HALF) ret = DATA_BUFFER_FACTORY_INSTANCE.createHalf(data, length); else ret = DATA_BUFFER_FACTORY_INSTANCE.createFloat(data, length); logCreationIfNecessary(ret); return ret; } /** * Create a buffer equal of length prod(shape) * * @param data the shape of the buffer to create * @return the created buffer */ public static DataBuffer createBuffer(int[] data) { DataBuffer ret; ret = Nd4j.getMemoryManager().getCurrentWorkspace() == null ? DATA_BUFFER_FACTORY_INSTANCE.createInt(data) : DATA_BUFFER_FACTORY_INSTANCE.createInt(data, Nd4j.getMemoryManager().getCurrentWorkspace()); logCreationIfNecessary(ret); return ret; } /** * Create a buffer equal of length prod(shape) * * @param data the shape of the buffer to create * @return the created buffer */ public static DataBuffer createBuffer(long[] data) { DataBuffer ret; ret = Nd4j.getMemoryManager().getCurrentWorkspace() == null ? DATA_BUFFER_FACTORY_INSTANCE.createLong(data) : DATA_BUFFER_FACTORY_INSTANCE.createLong(data, Nd4j.getMemoryManager().getCurrentWorkspace()); logCreationIfNecessary(ret); return ret; } /** * Create a buffer equal of length prod(shape). This method is NOT affected by workspaces * * @param data * @return */ public static DataBuffer createBufferDetached(int[] data) { DataBuffer ret; ret = DATA_BUFFER_FACTORY_INSTANCE.createInt(data); logCreationIfNecessary(ret); return ret; } /** * Create a buffer equal of length prod(shape). This method is NOT affected by workspaces * * @param data * @return */ public static DataBuffer createBufferDetached(long[] data) { DataBuffer ret; ret = DATA_BUFFER_FACTORY_INSTANCE.createLong(data); logCreationIfNecessary(ret); return ret; } /** * Creates a buffer of the specified length based on the data opType * * @param length the length of te buffer * @return the buffer to create */ public static DataBuffer createBuffer(long length) { return createBuffer(length, true); } /** * Create a data buffer * based on a pointer * with the given opType and length * @param pointer the pointer to create the buffer for * @param type the opType of pointer * @param length the length of the buffer * @param indexer the indexer to use * @return the data buffer based on the given parameters */ public static DataBuffer createBuffer(Pointer pointer, DataType type, long length, Indexer indexer) { return DATA_BUFFER_FACTORY_INSTANCE.create(pointer, type, length, indexer); } /** * * @param length * @param initialize * @return */ public static DataBuffer createBuffer(long length, boolean initialize) { DataBuffer ret = createBuffer(Nd4j.dataType(), length, initialize); logCreationIfNecessary(ret); return ret; } public static DataBuffer createBuffer(DataType dataType, long length, boolean initialize) { return Nd4j.getMemoryManager().getCurrentWorkspace() == null ? DATA_BUFFER_FACTORY_INSTANCE.create(dataType, length, initialize) : DATA_BUFFER_FACTORY_INSTANCE.create(dataType,length, initialize, Nd4j.getMemoryManager().getCurrentWorkspace()); } public static DataBuffer createBuffer(DataType dataType, long length, boolean initialize, MemoryWorkspace workspace) { return workspace == null ? DATA_BUFFER_FACTORY_INSTANCE.create(dataType, length, initialize) : DATA_BUFFER_FACTORY_INSTANCE.create(dataType,length, initialize, workspace); } /** * Create a buffer based on the data opType * * @param data the data to create the buffer with * @return the created buffer */ public static DataBuffer createBuffer(float[] data) { DataBuffer ret; //if (dataType() == DataType.FLOAT) ret = Nd4j.getMemoryManager().getCurrentWorkspace() == null ? DATA_BUFFER_FACTORY_INSTANCE.createFloat(data) : DATA_BUFFER_FACTORY_INSTANCE.createFloat(data, Nd4j.getMemoryManager().getCurrentWorkspace()); //else if (dataType() == DataType.HALF) // ret = Nd4j.getMemoryManager().getCurrentWorkspace() == null ? DATA_BUFFER_FACTORY_INSTANCE.createHalf(data): DATA_BUFFER_FACTORY_INSTANCE.createHalf(data, Nd4j.getMemoryManager().getCurrentWorkspace()); // else // ret = Nd4j.getMemoryManager().getCurrentWorkspace() == null ? DATA_BUFFER_FACTORY_INSTANCE.createDouble(ArrayUtil.toDoubles(data)) : DATA_BUFFER_FACTORY_INSTANCE.createDouble(ArrayUtil.toDoubles(data), Nd4j.getMemoryManager().getCurrentWorkspace()) ; logCreationIfNecessary(ret); return ret; } public static DataBuffer createBufferDetached(float[] data) { DataBuffer ret; //if (dataType() == DataType.FLOAT) ret = DATA_BUFFER_FACTORY_INSTANCE.createFloat(data); //else if (dataType() == DataType.HALF) // ret = DATA_BUFFER_FACTORY_INSTANCE.createHalf(data); // else // ret = DATA_BUFFER_FACTORY_INSTANCE.createDouble(ArrayUtil.toDoubles(data)); logCreationIfNecessary(ret); return ret; } public static DataBuffer createBufferDetached(double[] data) { DataBuffer ret; //if (dataType() == DataType.DOUBLE) ret = DATA_BUFFER_FACTORY_INSTANCE.createDouble(data); //else if (dataType() == DataType.HALF) // ret = DATA_BUFFER_FACTORY_INSTANCE.createHalf(ArrayUtil.toFloats(data)); // else // ret = DATA_BUFFER_FACTORY_INSTANCE.createFloat(ArrayUtil.toFloats(data)); logCreationIfNecessary(ret); return ret; } /** * Create a buffer based on the data opType * * @param data the data to create the buffer with * @return the created buffer */ public static DataBuffer createBuffer(double[] data) { DataBuffer ret; //if (dataType() == DataType.DOUBLE) ret = Nd4j.getMemoryManager().getCurrentWorkspace() == null ? DATA_BUFFER_FACTORY_INSTANCE.createDouble(data) : DATA_BUFFER_FACTORY_INSTANCE.createDouble(data, Nd4j.getMemoryManager().getCurrentWorkspace()); //else if (dataType() == DataType.HALF) // ret = Nd4j.getMemoryManager().getCurrentWorkspace() == null ? DATA_BUFFER_FACTORY_INSTANCE.createHalf(data) : DATA_BUFFER_FACTORY_INSTANCE.createHalf(ArrayUtil.toFloats(data), Nd4j.getMemoryManager().getCurrentWorkspace()); // else // ret = Nd4j.getMemoryManager().getCurrentWorkspace() == null ? DATA_BUFFER_FACTORY_INSTANCE.createFloat(ArrayUtil.toFloats(data)) : DATA_BUFFER_FACTORY_INSTANCE.createFloat(ArrayUtil.toFloats(data), Nd4j.getMemoryManager().getCurrentWorkspace()); // logCreationIfNecessary(ret); return ret; } /** * This method creates * @param data * @param dataType * @return */ public static DataBuffer createTypedBuffer(double[] data, DataType dataType) { val buffer = Nd4j.getMemoryManager().getCurrentWorkspace() == null ? DATA_BUFFER_FACTORY_INSTANCE.create(dataType, data.length, false) : DATA_BUFFER_FACTORY_INSTANCE.create(dataType, data.length, false, Nd4j.getMemoryManager().getCurrentWorkspace()); buffer.setData(data); return buffer; } public static DataBuffer createTypedBuffer(float[] data, DataType dataType) { val buffer = Nd4j.getMemoryManager().getCurrentWorkspace() == null ? DATA_BUFFER_FACTORY_INSTANCE.create(dataType, data.length, false) : DATA_BUFFER_FACTORY_INSTANCE.create(dataType, data.length, false, Nd4j.getMemoryManager().getCurrentWorkspace()); buffer.setData(data); return buffer; } public static DataBuffer createTypedBuffer(int[] data, DataType dataType) { val buffer = Nd4j.getMemoryManager().getCurrentWorkspace() == null ? DATA_BUFFER_FACTORY_INSTANCE.create(dataType, data.length, false) : DATA_BUFFER_FACTORY_INSTANCE.create(dataType, data.length, false, Nd4j.getMemoryManager().getCurrentWorkspace()); buffer.setData(data); return buffer; } public static DataBuffer createTypedBuffer(long[] data, DataType dataType) { val buffer = Nd4j.getMemoryManager().getCurrentWorkspace() == null ? DATA_BUFFER_FACTORY_INSTANCE.create(dataType, data.length, false) : DATA_BUFFER_FACTORY_INSTANCE.create(dataType, data.length, false, Nd4j.getMemoryManager().getCurrentWorkspace()); buffer.setData(data); return buffer; } public static DataBuffer createTypedBuffer(short[] data, DataType dataType) { val buffer = Nd4j.getMemoryManager().getCurrentWorkspace() == null ? DATA_BUFFER_FACTORY_INSTANCE.create(dataType, data.length, false) : DATA_BUFFER_FACTORY_INSTANCE.create(dataType, data.length, false, Nd4j.getMemoryManager().getCurrentWorkspace()); buffer.setData(data); return buffer; } public static DataBuffer createTypedBuffer(byte[] data, DataType dataType) { val buffer = Nd4j.getMemoryManager().getCurrentWorkspace() == null ? DATA_BUFFER_FACTORY_INSTANCE.create(dataType, data.length, false) : DATA_BUFFER_FACTORY_INSTANCE.create(dataType, data.length, false, Nd4j.getMemoryManager().getCurrentWorkspace()); buffer.setData(data); return buffer; } public static DataBuffer createTypedBuffer(boolean[] data, DataType dataType) { val buffer = Nd4j.getMemoryManager().getCurrentWorkspace() == null ? DATA_BUFFER_FACTORY_INSTANCE.create(dataType, data.length, false) : DATA_BUFFER_FACTORY_INSTANCE.create(dataType, data.length, false, Nd4j.getMemoryManager().getCurrentWorkspace()); buffer.setData(data); return buffer; } //////////////// public static DataBuffer createTypedBuffer(double[] data, DataType dataType, MemoryWorkspace workspace) { val buffer = workspace == null ? DATA_BUFFER_FACTORY_INSTANCE.create(dataType, data.length, false) : DATA_BUFFER_FACTORY_INSTANCE.create(dataType, data.length, false, workspace); buffer.setData(data); return buffer; } public static DataBuffer createTypedBuffer(float[] data, DataType dataType, MemoryWorkspace workspace) { val buffer = workspace == null ? DATA_BUFFER_FACTORY_INSTANCE.create(dataType, data.length, false) : DATA_BUFFER_FACTORY_INSTANCE.create(dataType, data.length, false, workspace); buffer.setData(data); return buffer; } public static DataBuffer createTypedBuffer(int[] data, DataType dataType, MemoryWorkspace workspace) { val buffer = workspace == null ? DATA_BUFFER_FACTORY_INSTANCE.create(dataType, data.length, false) : DATA_BUFFER_FACTORY_INSTANCE.create(dataType, data.length, false, workspace); buffer.setData(data); return buffer; } public static DataBuffer createTypedBuffer(long[] data, DataType dataType, MemoryWorkspace workspace) { val buffer = workspace == null ? DATA_BUFFER_FACTORY_INSTANCE.create(dataType, data.length, false) : DATA_BUFFER_FACTORY_INSTANCE.create(dataType, data.length, false, workspace); buffer.setData(data); return buffer; } public static DataBuffer createTypedBuffer(short[] data, DataType dataType, MemoryWorkspace workspace) { val buffer = workspace == null ? DATA_BUFFER_FACTORY_INSTANCE.create(dataType, data.length, false) : DATA_BUFFER_FACTORY_INSTANCE.create(dataType, data.length, false, workspace); buffer.setData(data); return buffer; } public static DataBuffer createTypedBuffer(byte[] data, DataType dataType, MemoryWorkspace workspace) { val buffer = workspace == null ? DATA_BUFFER_FACTORY_INSTANCE.create(dataType, data.length, false) : DATA_BUFFER_FACTORY_INSTANCE.create(dataType, data.length, false, workspace); buffer.setData(data); return buffer; } public static DataBuffer createTypedBuffer(boolean[] data, DataType dataType, MemoryWorkspace workspace) { val buffer = workspace == null ? DATA_BUFFER_FACTORY_INSTANCE.create(dataType, data.length, false) : DATA_BUFFER_FACTORY_INSTANCE.create(dataType, data.length, false, workspace); buffer.setData(data); return buffer; } //////////////// public static DataBuffer createTypedBufferDetached(double[] data, DataType dataType) { val buffer = DATA_BUFFER_FACTORY_INSTANCE.create(dataType, data.length, false); buffer.setData(data); return buffer; } public static DataBuffer createTypedBufferDetached(float[] data, DataType dataType) { val buffer = DATA_BUFFER_FACTORY_INSTANCE.create(dataType, data.length, false); buffer.setData(data); return buffer; } public static DataBuffer createTypedBufferDetached(int[] data, DataType dataType) { val buffer = DATA_BUFFER_FACTORY_INSTANCE.create(dataType, data.length, false); buffer.setData(data); return buffer; } public static DataBuffer createTypedBufferDetached(long[] data, DataType dataType) { val buffer = DATA_BUFFER_FACTORY_INSTANCE.create(dataType, data.length, false); buffer.setData(data); return buffer; } public static DataBuffer createTypedBufferDetached(short[] data, DataType dataType) { val buffer = DATA_BUFFER_FACTORY_INSTANCE.create(dataType, data.length, false); buffer.setData(data); return buffer; } public static DataBuffer createTypedBufferDetached(byte[] data, DataType dataType) { val buffer = DATA_BUFFER_FACTORY_INSTANCE.create(dataType, data.length, false); buffer.setData(data); return buffer; } public static DataBuffer createTypedBufferDetached(boolean[] data, DataType dataType) { val buffer = DATA_BUFFER_FACTORY_INSTANCE.create(dataType, data.length, false); buffer.setData(data); return buffer; } public static void setFactory(NDArrayFactory factory) { INSTANCE = factory; } public static void setSparseFactory(NDArrayFactory factory) { SPARSE_INSTANCE = factory; } /** * Returns the ordering of the ndarrays * * @return the ordering of the ndarrays */ public static Character order() { return factory().order(); } /** * Returns the data opType used for the runtime * * @return the datatype used for the runtime */ public static DataType dataType() { return DataTypeUtil.getDtypeFromContext(); } /** * DEPRECATED - use {@link #setDefaultDataTypes(DataType, DataType)} * This method sets dataType for the current JVM. * @param dType Data type to set * @deprecated use {@link #setDefaultDataTypes(DataType, DataType)}. Equivalent to {@code setDefaultDataTypes(dtype, (dtype.isFPType() ? dtype : defaultFloatingPointType()))} */ @Deprecated public static void setDataType(@NonNull DataType dtype) { setDefaultDataTypes(dtype, (dtype.isFPType() ? dtype : defaultFloatingPointType())); } /** * Set the default data types.<br> * The default data types are used for array creation methods where no data type is specified.<br> * When the user explicitly provides a datatype (such as in Nd4j.ones(DataType.FLOAT, 1, 10)) these default values * will not be used.<br> * defaultType: used in methods such as Nd4j.ones(1,10) and Nd4j.zeros(10).<br> * defaultFloatingPointType: used internally where a floating point array needs to be created, but no datatype is specified. * defaultFloatingPointType must be one of DOUBLE, FLOAT or HALF * * @param defaultType Default datatype for new arrays (used when no type is specified). * @param defaultFloatingPointType Default datatype for new floating point arrays (used when no type is specified. Must be one of DOUBLE, FLOAT or HALF */ public static void setDefaultDataTypes(@NonNull DataType defaultType, @NonNull DataType defaultFloatingPointType){ Preconditions.checkArgument(defaultFloatingPointType.isFPType(), "Invalid default floating point type: %s is not a floating point type", defaultFloatingPointType); DataTypeUtil.setDTypeForContext(defaultType); Nd4j.defaultFloatingPointDataType.set(defaultFloatingPointType); } /** * * @return */ public static Nd4jBackend getBackend() { return backend; } /** * * @return */ public static BlasWrapper getBlasWrapper() { return BLAS_WRAPPER_INSTANCE; } /** * * @return */ public static BlasWrapper getSparseBlasWrapper() { return SPARSE_BLAS_WRAPPER_INSTANCE; } /** * Sets the global blas wrapper * * @param factory */ public static void setBlasWrapper(BlasWrapper factory) { BLAS_WRAPPER_INSTANCE = factory; } /** * Sort an ndarray along a particular dimension.<br> * Note that the input array is modified in-place. * * @param ndarray the ndarray to sort * @param dimension the dimension to sort * @return the indices and the sorted ndarray (the original array, modified in-place) */ public static INDArray[] sortWithIndices(INDArray ndarray, int dimension, boolean ascending) { INDArray indices = Nd4j.create(ndarray.shape()); INDArray[] ret = new INDArray[2]; for (int i = 0; i < ndarray.vectorsAlongDimension(dimension); i++) { INDArray vec = ndarray.vectorAlongDimension(i, dimension); INDArray indexVector = indices.vectorAlongDimension(i, dimension); final Double[] data = new Double[(int) vec.length()]; final Double[] index = new Double[(int) vec.length()]; for (int j = 0; j < vec.length(); j++) { data[j] = vec.getDouble(j); index[j] = (double) j; } /** * Inject a comparator that sorts indices relative to * the actual values in the data. * This allows us to retain the indices * and how they were rearranged. */ Arrays.sort(index, new Comparator<Double>() { @Override public int compare(Double o1, Double o2) { int o = (int) o1.doubleValue(); int oo2 = (int) o2.doubleValue(); return Double.compare(data[o], data[oo2]); } }); if (ascending) for (int j = 0; j < vec.length(); j++) { vec.putScalar(j, data[(int) index[j].doubleValue()]); indexVector.putScalar(j, index[j]); } else { int count = data.length - 1; for (int j = 0; j < vec.length(); j++) { int currCount2 = count; count--; vec.putScalar(j, data[(int) index[currCount2].doubleValue()]); indexVector.putScalar(j, index[currCount2]); } } } ret[0] = indices; ret[1] = ndarray; return ret; } public static INDArray sort(INDArray ndarray, boolean ascending) { return getNDArrayFactory().sort(ndarray, !ascending); } /** * Sort an ndarray along a particular dimension<br> * Note that the input array is modified in-place. * * @param ndarray the ndarray to sort * @param dimension the dimension to sort * @return the sorted ndarray */ public static INDArray sort(INDArray ndarray, int dimension, boolean ascending) { return getNDArrayFactory().sort(ndarray, !ascending, dimension); } /**Sort (shuffle) the rows of a 2d array according to the value at a specified column. * Other than the order of the rows, each row is unmodified. Copy operation: original * INDArray is unmodified<br> * So if sorting the following on values of column 2 (ascending):<br> * [a b 2]<br> * [c d 0]<br> * [e f -3]<br> * Then output is<br> * [e f -3]<br> * [c d 0]<br> * [a b 2]<br> * @param in 2d array to sort * @param colIdx The column to sort on * @param ascending true if smallest-to-largest; false if largest-to-smallest * @return */ public static INDArray sortRows(final INDArray in, final int colIdx, final boolean ascending) { if (in.rank() != 2) throw new IllegalArgumentException("Cannot sort rows on non-2d matrix"); if (colIdx < 0 || colIdx >= in.columns()) throw new IllegalArgumentException("Cannot sort on values in column " + colIdx + ", nCols=" + in.columns()); if (in.rows() > Integer.MAX_VALUE) throw new ND4JArraySizeException(); INDArray out = Nd4j.create(in.data(), in.shape()); int nRows = (int) in.rows(); ArrayList<Integer> list = new ArrayList<Integer>(nRows); for (int i = 0; i < nRows; i++) list.add(i); Collections.sort(list, new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { if (ascending) return Double.compare(in.getDouble(o1, colIdx), in.getDouble(o2, colIdx)); else return -Double.compare(in.getDouble(o1, colIdx), in.getDouble(o2, colIdx)); } }); for (int i = 0; i < nRows; i++) { out.putRow(i, in.getRow(list.get(i))); } return out; } /**Sort (shuffle) the columns of a 2d array according to the value at a specified row. * Other than the order of the columns, each column is unmodified. Copy operation: original * INDArray is unmodified<br> * So if sorting the following on values of row 1 (ascending):<br> * [a b c]<br> * [1 -1 0]<br> * [d e f]<br> * Then output is<br> * [b c a]<br> * [-1 0 1]<br> * [e f d]<br> * @param in 2d array to sort * @param rowIdx The row to sort on * @param ascending true if smallest-to-largest; false if largest-to-smallest * @return */ public static INDArray sortColumns(final INDArray in, final int rowIdx, final boolean ascending) { if (in.rank() != 2) throw new IllegalArgumentException("Cannot sort columns on non-2d matrix"); if (rowIdx < 0 || rowIdx >= in.rows()) throw new IllegalArgumentException("Cannot sort on values in row " + rowIdx + ", nRows=" + in.rows()); if (in.columns() > Integer.MAX_VALUE) throw new ND4JArraySizeException(); INDArray out = Nd4j.create(in.shape()); int nCols = (int) in.columns(); ArrayList<Integer> list = new ArrayList<>(nCols); for (int i = 0; i < nCols; i++) list.add(i); Collections.sort(list, new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { if (ascending) return Double.compare(in.getDouble(rowIdx, o1), in.getDouble(rowIdx, o2)); else return -Double.compare(in.getDouble(rowIdx, o1), in.getDouble(rowIdx, o2)); } }); for (int i = 0; i < nCols; i++) { out.putColumn(i, in.getColumn(list.get(i))); } return out; } /** * Create an n x (shape) * ndarray where the ndarray is repeated num times * * @param n the ndarray to replicate * @param num the number of copies to repeat * @return the repeated ndarray */ public static INDArray repeat(INDArray n, int num) { List<INDArray> list = new ArrayList<>(); for (int i = 0; i < num; i++) list.add(n.dup()); long[] nShape = n.shape(); long[] shape = n.isColumnVector() ? new long[] {n.shape()[0]} : nShape; long[] retShape = Longs.concat(new long[] {num}, shape); return Nd4j.create(list, retShape); } /** * Generate a linearly spaced vector * * @param lower upper bound * @param num number of items in returned vector * @param step the step (incompatible with <b>upper</b>) * @return the linearly spaced vector */ public static INDArray linspace(@NonNull DataType dtype, long lower, long num, long step) { // for now we'll temporarily keep original impl if(num == 1) { return Nd4j.scalar(dtype, lower); } if (dtype.isIntType()) { long upper = lower + num * step; return linspaceWithCustomOpByRange((long) lower, upper, num, (long) step, dtype); } else if (dtype.isFPType()) { return Nd4j.getExecutioner().exec(new Linspace((double) lower, num, (double)step, dtype)); } else { throw new IllegalStateException("Illegal data type for linspace: " + dtype.toString()); } } /** * Generate a linearly spaced vector with default data type * * @param lower lower bound * @param upper upper bound * @param num number of items in returned vector * @return the linearly spaced vector */ public static INDArray linspace(long lower, long upper, long num) { return linspace(lower, upper, num, Nd4j.dataType()); } /** * Generate a linearly spaced vector * * @param lower lower bound * @param upper upper bound * @param num number of items in returned vector * @return the linearly spaced vector */ public static INDArray linspace(long lower, long upper, long num, @NonNull DataType dtype) { // for now we'll temporarily keep original impl if(lower == upper && num == 1) { return Nd4j.scalar(dtype, lower); } if (dtype.isIntType()) { return linspaceWithCustomOp((long)lower, (long)upper, (int)num, dtype); } else if (dtype.isFPType()) { return linspace((double) lower, (double)upper, (int) num, dtype); } else { throw new IllegalStateException("Illegal data type for linspace: " + dtype.toString()); } } /** * Generate a linearly spaced 1d vector of the specified datatype * * @param lower lower bound * @param step step between items * @param num number of resulting items * @return the linearly spaced vector */ public static INDArray linspace(@NonNull DataType dataType, double lower, double step, long num) { Preconditions.checkState(dataType.isFPType()); return Nd4j.getExecutioner().exec(new Linspace(lower, num, step, dataType)); } /** * Generate a linearly spaced 1d vector of the specified datatype * * @param lower lower bound * @param upper upper bound * @param num number of resulting items * @return the linearly spaced vector */ public static INDArray linspace( double lower, double upper, long num, @NonNull DataType dataType) { Preconditions.checkState(dataType.isFPType()); return Nd4j.getExecutioner().exec(new Linspace(lower, upper, num, dataType)); } private static INDArray linspaceWithCustomOp(long lower, long upper, int num, DataType dataType) { INDArray result = Nd4j.createUninitialized(dataType, new long[] {num}, Nd4j.order()); val op = DynamicCustomOp.builder("lin_space") .addInputs(Nd4j.scalar(lower), Nd4j.scalar(upper), Nd4j.scalar(num)) .addOutputs(result) .build(); Nd4j.getExecutioner().execAndReturn(op); return result; } private static INDArray linspaceWithCustomOpByRange(long lower, long upper, long num, long step, DataType dataType) { INDArray result = Nd4j.createUninitialized(dataType, new long[] {num}, Nd4j.order()); val op = DynamicCustomOp.builder("range") .addInputs(Nd4j.scalar(lower), Nd4j.scalar(upper), Nd4j.scalar(step)) .addOutputs(result) .build(); Nd4j.getExecutioner().execAndReturn(op); return result; } /** * Meshgrid op. Returns a pair of arrays where values are broadcast on a 2d grid.<br> * For example, if x = [1,2,3,4] and y = [5,6,7], then:<br> * out[0] =<br> * [1,2,3,4]<br> * [1,2,3,4]<br> * [1,2,3,4]<br> * <br> * out[1] =<br> * [5,5,5,5]<br> * [6,6,6,6]<br> * [7,7,7,7]<br> * <br> * * @param x X array input * @param y Y array input * @return INDArray[] of length 2, shape [y.length, x.length] */ public static INDArray[] meshgrid(@NonNull INDArray x, @NonNull INDArray y){ Preconditions.checkArgument(x.isVectorOrScalar(), "X must be a vector"); Preconditions.checkArgument(y.isVectorOrScalar(), "Y must be a vector"); if(y.dataType() != x.dataType()) y = y.castTo(x.dataType()); INDArray xOut = Nd4j.createUninitialized(x.dataType(), y.length(), x.length()); INDArray yOut = Nd4j.createUninitialized(x.dataType(), y.length(), x.length()); CustomOp op = DynamicCustomOp.builder("meshgrid") .addInputs(x, y) .addOutputs(xOut, yOut) .build(); Nd4j.getExecutioner().execAndReturn(op); return new INDArray[]{xOut, yOut}; } /** * Create a long row vector of all of the given ndarrays * @param matrices the matrices to create the flattened ndarray for * @return the flattened representation of * these ndarrays */ public static INDArray toFlattened(Collection<INDArray> matrices) { INDArray ret = INSTANCE.toFlattened(matrices); logCreationIfNecessary(ret); return ret; } /** * Create a long row vector of all of the given ndarrays * @param order the order in which to flatten the matrices * @param matrices the matrices to create the flattened ndarray for * @return the flattened representation of * these ndarrays */ public static INDArray toFlattened(char order, Collection<INDArray> matrices) { INDArray ret = INSTANCE.toFlattened(order, matrices); logCreationIfNecessary(ret); return ret; } /** * Create a long row vector of all of the given ndarrays * @param matrices the matrices to create the flattened ndarray for * @return the flattened representation of * these ndarrays */ public static INDArray toFlattened(int length, Iterator<? extends INDArray>... matrices) { INDArray ret = INSTANCE.toFlattened(length, matrices); logCreationIfNecessary(ret); return ret; } /** * Returns a column vector where each entry is the nth bilinear * product of the nth slices of the two tensors. */ public static INDArray bilinearProducts(INDArray curr, INDArray in) { return INSTANCE.bilinearProducts(curr, in); } /** * Create a long row vector of all of the given ndarrays * @param matrices the matrices to create the flattened ndarray for * @return the flattened representation of * these ndarrays */ public static INDArray toFlattened(INDArray... matrices) { return INSTANCE.toFlattened(matrices); } /** * Create a long row vector of all of the given ndarrays/ * @param order order in which to flatten ndarrays * @param matrices the matrices to create the flattened ndarray for * @return the flattened representation of * these ndarrays */ public static INDArray toFlattened(char order, INDArray... matrices) { return INSTANCE.toFlattened(order, matrices); } /** * Create the identity ndarray * * @param n the number for the identity * @return */ public static INDArray eye(long n) { INDArray ret = INSTANCE.eye(n); logCreationIfNecessary(ret); return ret; } /** * Rotate a matrix 90 degrees * * @param toRotate the matrix to rotate * @return the rotated matrix */ public static void rot90(INDArray toRotate) { INSTANCE.rot90(toRotate); } /** * Write NDArray to a text file * * @param filePath * @param split the split separator, defaults to "," * @deprecated custom col separators are no longer supported; uses "," * @param precision digits after the decimal point * @deprecated Precision is no longer used. * Defaults to scientific notation with 18 digits after the decimal * Use {@link #writeTxt(INDArray, String)} */ public static void writeTxt(INDArray write, String filePath, String split, int precision) { writeTxt(write,filePath); } /** * Write NDArray to a text file * * @param write * @param filePath * @param precision * @deprecated Precision is no longer used. * Defaults to scientific notation with 18 digits after the decimal * Use {@link #writeTxt(INDArray, String)} */ public static void writeTxt(INDArray write, String filePath, int precision) { writeTxt(write, filePath); } /** * Write NDArray to a text file * * @param write * @param filePath * @param split * @deprecated custom col and higher dimension separators are no longer supported; uses "," * Use {@link #writeTxt(INDArray, String)} */ public static void writeTxt(INDArray write, String filePath, String split) { writeTxt(write,filePath); } /** * Write NDArray to a text file * * @param write Array to write * @param filePath */ public static void writeTxt(INDArray write, String filePath) { try { String toWrite = writeStringForArray(write, "0.000000000000000000E0"); FileUtils.writeStringToFile(new File(filePath), toWrite); } catch (IOException e) { throw new RuntimeException("Error writing output", e); } } /** * Array written to outputstream * * @param os the outputstream stream ndarray * @param split * @deprecated custom col separators are no longer supported; uses "," * @param precision * @deprecated precision can no longer be specified. The array is written in scientific notation. * Use {@link #writeTxtString(INDArray, OutputStream)} */ public static void writeTxtString(INDArray write, OutputStream os, String split, int precision) { writeTxtString(write,os); } /** * * @param write * @param os * @param precision * @deprecated precision can no longer be specified. The array is written in scientific notation. * Use {@link #writeTxtString(INDArray, OutputStream)} */ @Deprecated public static void writeTxtString(INDArray write, OutputStream os, int precision) { writeTxtString(write,os); } /** * @param write * @param os * @param split * @deprecated column separator can longer be specified; Uses "," * Use {@link #writeTxtString(INDArray, OutputStream)} instead */ @Deprecated public static void writeTxtString(INDArray write, OutputStream os, String split) { writeTxtString(write, os); } /** * Write ndarray as text to output stream * @param write * @param os */ public static void writeTxtString(INDArray write, OutputStream os) { try { // default format is "0.000000000000000000E0" String toWrite = writeStringForArray(write, "0.000000000000000000E0"); os.write(toWrite.getBytes()); } catch (IOException e) { throw new RuntimeException("Error writing output", e); } } private static String writeStringForArray(INDArray write, String format) { if(write.isView() || !Shape.hasDefaultStridesForShape(write)) write = write.dup(); if (format.isEmpty()) format = "0.000000000000000000E0"; String lineOne = "{\n"; String lineTwo = "\"filefrom\": \"dl4j\",\n"; String lineThree = "\"ordering\": \"" + write.ordering() + "\",\n"; String lineFour = "\"shape\":\t" + java.util.Arrays.toString(write.shape()) + ",\n"; String lineFive = "\"data\":\n"; String fileData = new NDArrayStrings(",", format).format(write, false); String fileEnd = "\n}\n"; String fileBegin = lineOne + lineTwo + lineThree + lineFour + lineFive; String fileContents = fileBegin + fileData + fileEnd; return fileContents; } /**Y * Write an ndarray to a writer * @param writer the writer to write to * @param write the ndarray to write * @throws IOException */ public static void write(OutputStream writer, INDArray write) throws IOException { DataOutputStream stream = new DataOutputStream(writer); write(write, stream); stream.close(); } /** * Convert an ndarray to a byte array * @param arr the array to convert * @return the converted byte array * @throws IOException */ public static byte[] toByteArray(INDArray arr) throws IOException { if (arr.length() * arr.data().getElementSize() > Integer.MAX_VALUE) throw new ND4JIllegalStateException(""); ByteArrayOutputStream bos = new ByteArrayOutputStream((int) (arr.length() * arr.data().getElementSize())); DataOutputStream dos = new DataOutputStream(bos); write(arr, dos); byte[] ret = bos.toByteArray(); return ret; } /** * Read an ndarray from a byte array * @param arr the array to read from * @return the deserialized ndarray * @throws IOException */ public static INDArray fromByteArray(byte[] arr) throws IOException { ByteArrayInputStream bis = new ByteArrayInputStream(arr); INDArray ret = read(bis); return ret; } /** * Read line via input streams * * @param filePath the input stream ndarray * @param split the split separator * @return the read txt method */ public static INDArray readNumpy(InputStream filePath, String split) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(filePath)); String line; List<float[]> data2 = new ArrayList<>(); int numColumns = -1; INDArray ret; while ((line = reader.readLine()) != null) { String[] data = line.trim().split(split); if (numColumns < 0) { numColumns = data.length; } else Preconditions.checkState(data.length == numColumns, "Data has inconsistent number of columns: data length %s, numColumns %s", data.length, numColumns); data2.add(readSplit(data)); } ret = Nd4j.create(Nd4j.defaultFloatingPointType(), data2.size(), numColumns); for (int i = 0; i < data2.size(); i++) { float[] row = data2.get(i); INDArray arr = Nd4j.create(row, new long[]{1, row.length}, Nd4j.defaultFloatingPointType()); ret.putRow(i, arr); } return ret; } private static float[] readSplit(String[] split) { float[] ret = new float[split.length]; for (int i = 0; i < split.length; i++) { try { ret[i] = Float.parseFloat(split[i]); } catch (NumberFormatException e) { if (split[i].equalsIgnoreCase("inf")) { ret[i] = Float.POSITIVE_INFINITY; } else if (split[i].equalsIgnoreCase("-inf")) { ret[i] = Float.NEGATIVE_INFINITY; } else if (split[i].equalsIgnoreCase("nan")) { ret[i] = Float.NaN; } else throw new RuntimeException(e); } } return ret; } /** * Read line via input streams * * @param filePath the input stream ndarray * @param split the split separator * @return the read txt method */ public static INDArray readNumpy(String filePath, String split) throws IOException { try(InputStream is = new FileInputStream(filePath)) { return readNumpy(is, split); } } /** * Read line via input streams * * @param filePath the input stream ndarray * @return the read txt method */ public static INDArray readNumpy(String filePath) throws IOException { return readNumpy(filePath, "\t"); } /** * Raad an ndarray from an input stream * @param reader the input stream to use * @return the given ndarray * @throws IOException */ public static INDArray read(InputStream reader) throws IOException { return read(new DataInputStream(reader)); } /** * Read line via input streams * * @param ndarray the input stream ndarray * @return NDArray */ public static INDArray readTxtString(InputStream ndarray) { String sep = ","; /* We could dump an ndarray to a file with the tostring (since that is valid json) and use put/get to parse it as json But here we leverage our information of the tostring method to be more efficient With our current toString format we use tads along dimension (rank-1,rank-2) to write to the array in two dimensional chunks at a time. This is more efficient than setting each value at a time with putScalar. This also means we can read the file one line at a time instead of loading the whole thing into memory */ INDArray newArr = null; BufferedReader reader = new BufferedReader(new InputStreamReader(ndarray)); LineIterator it = IOUtils.lineIterator(reader); DecimalFormat format = (DecimalFormat) NumberFormat.getInstance(Locale.US); format.setParseBigDecimal(true); try { int lineNum = 0; int tensorNum = 0; char theOrder = 'c'; int rank = 0; long[] theShape = null; double[] subsetArr = null; while (it.hasNext()) { String line = it.nextLine(); lineNum++; line = line.replaceAll("\\s", ""); if (line.equals("") || line.equals("}")) continue; // is it from dl4j? if (lineNum == 2) { String[] lineArr = line.split(":"); String fileSource = lineArr[1].replaceAll("\\W", ""); if (!fileSource.equals("dl4j")) throw new IllegalArgumentException("Only files written out from Nd4j.writeTxT/writeTxtString can be read with the readTxt/readTxtString methods"); } // parse ordering if (lineNum == 3) { String[] lineArr = line.split(":"); theOrder = lineArr[1].replaceAll("\\W", "").charAt(0); continue; } // parse shape if (lineNum == 4) { String shapeString = line.split(":")[1].replace("[", "").replace("],", ""); if (shapeString.isEmpty()) { newArr = Nd4j.scalar(Nd4j.defaultFloatingPointType(), 0); } else { String[] shapeArr = shapeString.split(","); rank = shapeArr.length; theShape = new long[rank]; for (int i = 0; i < rank; i++) { theShape[i] = Integer.parseInt(shapeArr[i]); } if (theOrder == 'f' && theShape[rank-1] == 1) { //Hack fix for tad issue with 'f' order and rank-1 dim shape == 1 newArr = Nd4j.create(Nd4j.defaultFloatingPointType(), theShape, 'c'); } else { newArr = Nd4j.create(Nd4j.defaultFloatingPointType(), theShape, theOrder); } subsetArr = new double[(int) theShape[rank - 1]]; } continue; } //parse data if (lineNum > 5) { String[] entries = line.replace("\\],", "").replaceAll("\\]", "").replaceAll("\\[", "").split(sep); if (rank == 0) { try { newArr.addi((format.parse(entries[0])).doubleValue()); } catch (ParseException e) { e.printStackTrace(); } } else { Preconditions.checkState(entries.length == theShape[rank-1], "Invalid number of entries - format does not match expected shape." + "Expected %s values per line, got %s at line %s", theShape[rank-1], entries.length, lineNum ); for (int i = 0; i < theShape[rank - 1]; i++) { try { BigDecimal number = (BigDecimal) format.parse(entries[i]); subsetArr[i] = number.doubleValue(); } catch (ParseException e) { e.printStackTrace(); } } INDArray subTensor = Nd4j.create(subsetArr, new long[]{subsetArr.length}, Nd4j.defaultFloatingPointType()); newArr.tensorAlongDimension(tensorNum, rank - 1).addi(subTensor); tensorNum++; } } } //Hack fix for tad issue with 'f' order and rank-1 dim shape == 1 if (theOrder == 'f' && rank > 1 && theShape[rank-1] == 1) { newArr = newArr.dup('f'); } } finally { LineIterator.closeQuietly(it); } return newArr; } /** * Read line via input streams * * @param filePath the input stream ndarray * @return NDArray */ public static INDArray readTxt(String filePath) { String sep = ","; File file = new File(filePath); InputStream is = null; try { is = new FileInputStream(file); return readTxtString(is); } catch (FileNotFoundException e) { throw new RuntimeException(e); } finally { if (is != null) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } } private static int[] toIntArray(int length, DataBuffer buffer) { int[] ret = new int[length]; for (int i = 0; i < length; i++) { ret[i] = buffer.getInt(i); } return ret; } /** * * @param data * @param shapeInfo * @return */ public static INDArray createArrayFromShapeBuffer(DataBuffer data, DataBuffer shapeInfo) { val jvmShapeInfo = shapeInfo.asLong(); val rank = Shape.rank(jvmShapeInfo); val dataType = ArrayOptionsHelper.dataType(jvmShapeInfo); val shape = Shape.shape(jvmShapeInfo); val strides = Shape.stridesOf(jvmShapeInfo); val order = Shape.order(jvmShapeInfo); long offset = 0; INDArray result = Nd4j.create(data, shape, strides, 0, order, dataType); if (data instanceof CompressedDataBuffer) result.markAsCompressed(true); return result; } /** * * @param data * @param shapeInfo * @return */ public static INDArray createArrayFromShapeBuffer(DataBuffer data, Pair<DataBuffer, long[]> shapeInfo) { int rank = Shape.rank(shapeInfo.getFirst()); long offset = Shape.offset(shapeInfo.getFirst()); INDArray result = Nd4j.create(data, toIntArray(rank, Shape.shapeOf(shapeInfo.getFirst())), toIntArray(rank, Shape.stride(shapeInfo.getFirst())), offset, Shape.order(shapeInfo.getFirst())); if (data instanceof CompressedDataBuffer) result.markAsCompressed(true); return result; } /** * Read in an ndarray from a data input stream * * @param dis the data input stream to read from * @return the ndarray * @throws IOException */ public static INDArray read(DataInputStream dis) throws IOException { val headerShape = BaseDataBuffer.readHeader(dis); var shapeInformation = Nd4j.createBufferDetached(new long[]{headerShape.getMiddle().longValue()}, headerShape.getRight()); shapeInformation.read(dis, headerShape.getLeft(), headerShape.getMiddle(), headerShape.getThird()); val length = Shape.length(shapeInformation); DataType type = null; DataBuffer data = null; val headerData = BaseDataBuffer.readHeader(dis); try { // current version contains dtype in extras data = CompressedDataBuffer.readUnknown(dis, headerData.getFirst(), headerData.getMiddle(), headerData.getRight()); type = ArrayOptionsHelper.dataType(shapeInformation.asLong()); } catch (ND4JUnknownDataTypeException e) { // manually setting data type type = headerData.getRight(); long extras = ArrayOptionsHelper.setOptionBit(0L, type); shapeInformation.put(shapeInformation.length() - 3, extras); } return createArrayFromShapeBuffer(data, shapeInformation); } /** * Write an ndarray to the specified outputstream * * @param arr the array to write * @param dataOutputStream the data output stream to write to * @throws IOException */ public static void write(INDArray arr, DataOutputStream dataOutputStream) throws IOException { //BaseDataBuffer.write(...) doesn't know about strides etc, so dup (or equiv. strategy) is necessary here //Furthermore, because we only want to save the *actual* data for a view (not the full data), the shape info // (mainly strides, offset, element-wise stride) may be different in the duped array vs. the view array if (arr.isView()) arr = arr.dup(); arr.shapeInfoDataBuffer().write(dataOutputStream); arr.data().write(dataOutputStream); } /** * Save an ndarray to the given file * @param arr the array to save * @param saveTo the file to save to * @throws IOException */ public static void saveBinary(INDArray arr, File saveTo) throws IOException { BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(saveTo)); DataOutputStream dos = new DataOutputStream(bos); Nd4j.write(arr, dos); dos.flush(); dos.close(); bos.close(); } /** * Read a binary ndarray from the given file * @param read the nd array to read * @return the loaded ndarray * @throws IOException */ public static INDArray readBinary(File read) throws IOException { BufferedInputStream bis = new BufferedInputStream(new FileInputStream(read)); DataInputStream dis = new DataInputStream(bis); INDArray ret = Nd4j.read(dis); dis.close(); return ret; } /** * Clear nans from an ndarray * * @param arr the array to clear */ public static void clearNans(INDArray arr) { //BooleanIndexing.applyWhere(arr, Conditions.isNan(), new Value(Nd4j.EPS_THRESHOLD)); getExecutioner().exec(new ReplaceNans(arr, Nd4j.EPS_THRESHOLD)); } /** * Reverses the passed in matrix such that m[0] becomes m[m.length - 1] etc * * @param reverse the matrix to reverse * @return the reversed matrix */ public static INDArray rot(INDArray reverse) { INDArray ret = INSTANCE.rot(reverse); logCreationIfNecessary(ret); return ret; } /** * Reverses the passed in matrix such that m[0] becomes m[m.length - 1] etc * * @param reverse the matrix to reverse * @return the reversed matrix */ public static INDArray reverse(INDArray reverse) { //INDArray ret = INSTANCE.reverse(reverse); //logCreationIfNecessary(ret); return Nd4j.getExecutioner().exec(new OldReverse(reverse)); } /** * Create a 1D array of evenly spaced values between {@code begin} (inclusive) and {@code end} (exclusive) * with a step size of 1 * * @param begin the begin of the range (inclusive) * @param end the end of the range (exclusive) * @param step spacing between values. Default value is 1. * @return the 1D range vector */ public static INDArray arange(double begin, double end, double step) { INDArray ret = INSTANCE.arange(begin, end, step); logCreationIfNecessary(ret); return ret; } public static INDArray arange(double begin, double end) { INDArray ret = INSTANCE.arange(begin, end, 1); logCreationIfNecessary(ret); return ret; } /** * Create a 1D array of evenly spaced values between 0 (inclusive) and {@code end} (exclusive) * with a step size of 1 * * @param end the end of the range (exclusive) * @return the 1D range vector */ public static INDArray arange(double end) { return arange(0, end); } /** * Copy a to b * * @param a the origin matrix * @param b the destination matrix */ public static void copy(INDArray a, INDArray b) { INSTANCE.copy(a, b); } /** * Creates a new matrix where the values of the given vector are the diagonal values of * the matrix if a vector is passed in, if a matrix is returns the kth diagonal * in the matrix * * @param x the diagonal values * @param k the kth diagonal to get * @return new matrix */ public static INDArray diag(INDArray x, int k) { INDArray ret; if(x.isMatrix()) { ret = Nd4j.createUninitialized(new long[]{Math.min(x.size(0), x.size(1))}); Nd4j.getExecutioner().execAndReturn(new DiagPart(x,ret)); } else { ret = Nd4j.create(new long[]{x.length(), x.length()}); Nd4j.getExecutioner().execAndReturn(new Diag(new INDArray[]{x},new INDArray[]{ret})); } return ret; } /** * Creates a new matrix where the values of the given vector are the diagonal values of * the matrix if a vector is passed in, if a matrix is returns the kth diagonal * in the matrix * * @param x the diagonal values * @return new matrix */ public static INDArray diag(INDArray x) { return diag(x, 0); } /** * This method samples value from Source array to Target, with probabilites provided in Probs argument * * @param source * @param probs * @param target * @return */ public static INDArray choice(@NonNull INDArray source, @NonNull INDArray probs, @NonNull INDArray target, @NonNull org.nd4j.linalg.api.rng.Random rng) { if (source.length() != probs.length()) throw new ND4JIllegalStateException("Nd4j.choice() requires lengths of Source and Probs to be equal"); return Nd4j.getExecutioner().exec(new Choice(source, probs, target), rng); } /** * This method samples value from Source array to Target, with probabilites provided in Probs argument * * @param source * @param probs * @param target * @return */ public static INDArray choice(INDArray source, INDArray probs, INDArray target) { return choice(source, probs, target, Nd4j.getRandom()); } /** * This method returns new INDArray instance, sampled from Source array with probabilities given in Probs * * @param source * @param probs * @param numSamples * @return */ public static INDArray choice(INDArray source, INDArray probs, int numSamples, @NonNull org.nd4j.linalg.api.rng.Random rng) { if (numSamples < 1) throw new ND4JIllegalStateException("Nd4j.choice() numSamples must be positive value"); return choice(source, probs, createUninitialized(numSamples), rng); } /** * This method returns new INDArray instance, sampled from Source array with probabilities given in Probs * * @param source * @param probs * @param numSamples * @return */ public static INDArray choice(INDArray source, INDArray probs, int numSamples) { return choice(source, probs, numSamples, Nd4j.getRandom()); } public static INDArray appendBias(INDArray... vectors) { INDArray ret = INSTANCE.appendBias(vectors); logCreationIfNecessary(ret); return ret; } /** * Perform an operation along a diagonal * * @param x the ndarray to perform the operation on * @param func the operation to perform */ public static void doAlongDiagonal(INDArray x, Function<Number, Number> func) { if (x.isMatrix()) for (int i = 0; i < x.rows(); i++) x.put(i, i, func.apply(x.getDouble(i, i))); } ////////////////////// RANDOM /////////////////////////////// /** * Create a random ndarray with the given shape using * the current time as the seed * * @param shape the shape of the ndarray * @return the random ndarray with the specified shape */ public static INDArray rand(int[] shape) { INDArray ret = createUninitialized(shape, order()); //INSTANCE.rand(shape, Nd4j.getRandom()); logCreationIfNecessary(ret); return rand(ret); } public static INDArray rand(long[] shape) { INDArray ret = createUninitialized(shape, order()); //INSTANCE.rand(shape, Nd4j.getRandom()); logCreationIfNecessary(ret); return rand(ret); } public static INDArray rand(DataType dataType, long... shape) { INDArray ret = createUninitialized(dataType, shape, order()); //INSTANCE.rand(shape, Nd4j.getRandom()); logCreationIfNecessary(ret); return rand(ret); } /** * Create a random ndarray with the given shape and array order * * @param order the order of the ndarray to return * @param shape the shape of the ndarray * @return the random ndarray with the specified shape */ public static INDArray rand(char order, int[] shape) { INDArray ret = Nd4j.createUninitialized(shape, order); //INSTANCE.rand(order, shape); logCreationIfNecessary(ret); return rand(ret); } public static INDArray rand(DataType dataType, char order, int[] shape) { INDArray ret = Nd4j.createUninitialized(dataType, ArrayUtil.toLongArray(shape), order); //INSTANCE.rand(order, shape); logCreationIfNecessary(ret); return rand(ret); } public static INDArray rand(DataType dataType, int[] shape, char order) { INDArray ret = Nd4j.createUninitialized(dataType, ArrayUtil.toLongArray(shape), order); //INSTANCE.rand(order, shape); logCreationIfNecessary(ret); return rand(ret); } public static INDArray rand(DataType dataType, int[] shape) { INDArray ret = Nd4j.createUninitialized(dataType, ArrayUtil.toLongArray(shape), Nd4j.order()); //INSTANCE.rand(order, shape); logCreationIfNecessary(ret); return rand(ret); } /** * Create a random ndarray with the given shape using * the current time as the seed * * @param rows the number of rows in the matrix * @param columns the number of columns in the matrix * @return the random ndarray with the specified shape */ public static INDArray rand(int rows, int columns) { if (rows < 1 || columns < 1) throw new ND4JIllegalStateException("Number of rows and columns should be positive for new INDArray"); INDArray ret = createUninitialized(new int[] {rows, columns}, Nd4j.order());//INSTANCE.rand(rows, columns, Nd4j.getRandom()); logCreationIfNecessary(ret); return rand(ret); } /** * Create a random ndarray with the given shape and output order * * @param rows the number of rows in the matrix * @param columns the number of columns in the matrix * @return the random ndarray with the specified shape */ public static INDArray rand(char order, int rows, int columns) { if (rows < 1 || columns < 1) throw new ND4JIllegalStateException("Number of rows and columns should be positive for new INDArray"); INDArray ret = createUninitialized(new int[] {rows, columns}, order);//INSTANCE.rand(order, rows, columns); logCreationIfNecessary(ret); return rand(ret); } /** * Create a random ndarray with the given shape using given seed * * @param shape the shape of the ndarray * @param seed the seed to use * @return the random ndarray with the specified shape */ public static INDArray rand(int[] shape, long seed) { INDArray ret = createUninitialized(shape, Nd4j.order());//;INSTANCE.rand(shape, seed); logCreationIfNecessary(ret); return rand(ret, seed); } /** * Create a random ndarray with the given shape using the given seed * * @param rows the number of rows in the matrix * @param columns the columns of the ndarray * @param seed the seed to use * @return the random ndarray with the specified shape */ public static INDArray rand(int rows, int columns, long seed) { INDArray ret = createUninitialized(new int[] {rows, columns}, Nd4j.order()); logCreationIfNecessary(ret); return rand(ret, seed); } /** * Create a random ndarray with the given shape using the given RandomGenerator * * @param shape the shape of the ndarray * @param rng the random generator to use * @return the random ndarray with the specified shape */ public static INDArray rand(int[] shape, org.nd4j.linalg.api.rng.Random rng) { INDArray ret = createUninitialized(shape, Nd4j.order()); //INSTANCE.rand(shape, rng); logCreationIfNecessary(ret); return rand(ret, rng); } /** * Create a random ndarray with the given shape using the given rng * * @param shape the shape of the ndarray * @param dist distribution to use * @return the random ndarray with the specified shape */ public static INDArray rand(int[] shape, Distribution dist) { //INDArray ret = INSTANCE.rand(shape, dist); //logCreationIfNecessary(ret); return dist.sample(shape); } /** * Create a random ndarray with the given shape using the given rng * * @param shape the shape of the ndarray * @param dist distribution to use * @return the random ndarray with the specified shape */ public static INDArray rand(long[] shape, Distribution dist) { //INDArray ret = INSTANCE.rand(shape, dist); //logCreationIfNecessary(ret); return dist.sample(shape); } /** * Create a random ndarray with the given shape using the given rng * * @param rows the number of rows in the matrix * @param columns the number of columns in the matrix * @param rng the random generator to use * @return the random ndarray with the specified shape */ public static INDArray rand(int rows, int columns, org.nd4j.linalg.api.rng.Random rng) { INDArray ret = createUninitialized(new int[] {rows, columns}, order());//INSTANCE.rand(rows, columns, rng); logCreationIfNecessary(ret); return rand(ret, rng); } /** * Generates a random matrix between min and max * * @param shape the number of rows of the matrix * @param min the minimum number * @param max the maximum number * @param rng the rng to use * @return a random matrix of the specified shape and range */ public static INDArray rand(int[] shape, double min, double max, org.nd4j.linalg.api.rng.Random rng) { INDArray ret = createUninitialized(shape, order()); //INSTANCE.rand(shape, min, max, rng); logCreationIfNecessary(ret); return rand(ret, min, max, rng); } /** * Generates a random matrix between min and max * * @param shape the number of rows of the matrix * @param min the minimum number * @param max the maximum number * @param rng the rng to use * @return a random matrix of the specified shape and range */ public static INDArray rand(long[] shape, double min, double max, org.nd4j.linalg.api.rng.Random rng) { INDArray ret = createUninitialized(shape, order()); //INSTANCE.rand(shape, min, max, rng); logCreationIfNecessary(ret); return rand(ret, min, max, rng); } /** * Generates a random matrix between min and max * * @param rows the number of rows of the matrix * @param columns the number of columns in the matrix * @param min the minimum number * @param max the maximum number * @param rng the rng to use * @return a drandom matrix of the specified shape and range */ public static INDArray rand(int rows, int columns, double min, double max, org.nd4j.linalg.api.rng.Random rng) { INDArray ret = createUninitialized(rows, columns);//INSTANCE.rand(rows, columns, min, max, rng); logCreationIfNecessary(ret); return rand(ret, min, max, rng); } /** * Fill the given ndarray with random numbers drawn from a normal distribution * * @param target target array * @return the given target array */ public static INDArray randn(INDArray target) { return getExecutioner().exec(new GaussianDistribution(target), Nd4j.getRandom()); } /** * Random normal using the current time stamp * as the seed * * @param shape the shape of the ndarray * @return */ public static INDArray randn(int[] shape) { INDArray ret = Nd4j.createUninitialized(shape, order()); logCreationIfNecessary(ret); return randn(ret); } public static INDArray randn(DataType dataType, long... shape) { INDArray ret = Nd4j.createUninitialized(dataType, shape, order()); logCreationIfNecessary(ret); return randn(ret); } public static INDArray randn(long... shape) { INDArray ret = Nd4j.createUninitialized(shape, order()); logCreationIfNecessary(ret); return randn(ret); } /** * Random normal N(0,1) with the specified shape and array order * * @param order order of the output ndarray * @param shape the shape of the ndarray */ public static INDArray randn(char order, int[] shape) { INDArray ret = Nd4j.createUninitialized(shape, order); logCreationIfNecessary(ret); return randn(ret); } /** * Random normal N(0,1) with the specified shape and array order * * @param order order of the output ndarray * @param shape the shape of the ndarray */ public static INDArray randn(char order, long[] shape) { INDArray ret = Nd4j.createUninitialized(shape, order); logCreationIfNecessary(ret); return randn(ret); } public static INDArray randn(DataType dataType, char order, long[] shape) { INDArray ret = Nd4j.createUninitialized(dataType, shape, order); logCreationIfNecessary(ret); return randn(ret); } /** * Random normal using the specified seed * * @param shape the shape of the ndarray * @return */ public static INDArray randn(int[] shape, long seed) { INDArray ret = Nd4j.createUninitialized(shape, order()); logCreationIfNecessary(ret); return randn(ret, seed); } /** * Random normal using the current time stamp * as the seed * * @param rows the number of rows in the matrix * @param columns the number of columns in the matrix * @return */ public static INDArray randn(long rows, long columns) { INDArray ret = Nd4j.createUninitialized(new long[]{rows, columns}, order()); logCreationIfNecessary(ret); return randn(ret); } /** * Random normal N(0,1) with the specified shape and array order * * @param order the order of the output array * @param rows the number of rows in the matrix * @param columns the number of columns in the matrix */ public static INDArray randn(char order, long rows, long columns) { INDArray ret = Nd4j.createUninitialized(new long[]{rows, columns}, order); logCreationIfNecessary(ret); return randn(ret); } /** * Random normal using the specified seed * * @param rows the number of rows in the matrix * @param columns the number of columns in the matrix * @return */ public static INDArray randn(long rows, long columns, long seed) { INDArray ret = Nd4j.createUninitialized(new long[]{rows, columns}, order()); logCreationIfNecessary(ret); return randn(ret, seed); } /** * Random normal using the given rng * * @param rows the number of rows in the matrix * @param columns the number of columns in the matrix * @param r the random generator to use * @return */ public static INDArray randn(long rows, long columns, org.nd4j.linalg.api.rng.Random r) { INDArray ret = Nd4j.createUninitialized(new long[]{rows, columns}, order()); logCreationIfNecessary(ret); return randn(ret, r); } /** * Random normal using the given rng * * @param shape the shape of the ndarray * @param r the random generator to use * @return */ public static INDArray randn(int[] shape, org.nd4j.linalg.api.rng.Random r) { final INDArray ret = Nd4j.createUninitialized(shape, order()); logCreationIfNecessary(ret); return randn(ret, r); } /** * Random normal using the given rng * * @param shape the shape of the ndarray * @param r the random generator to use * @return */ public static INDArray randn(long[] shape, org.nd4j.linalg.api.rng.Random r) { final INDArray ret = Nd4j.createUninitialized(shape, order()); logCreationIfNecessary(ret); return randn(ret, r); } /** * Fill the given ndarray with random numbers drawn from a uniform distribution * * @param target target array * @return the given target array */ public static INDArray rand(INDArray target) { return getExecutioner().exec(new UniformDistribution(target), Nd4j.getRandom()); } /** * Fill the given ndarray with random numbers drawn from a uniform distribution * * @param target target array * @param seed the seed to use * @return the given target array */ public static INDArray rand(INDArray target, long seed) { Nd4j.getRandom().setSeed(seed); return getExecutioner().exec(new UniformDistribution(target), Nd4j.getRandom()); } /** * Fill the given ndarray with random numbers drawn from a uniform distribution using the given RandomGenerator * * @param target target array * @param rng the random generator to use * @return the given target array */ public static INDArray rand(INDArray target, org.nd4j.linalg.api.rng.Random rng) { return getExecutioner().exec(new UniformDistribution(target), rng); } /** * Fill the given ndarray with random numbers drawn from the given distribution * * @param target target array * @param dist distribution to use * @return the random ndarray with the specified shape */ public static INDArray rand(INDArray target, Distribution dist) { return dist.sample(target); } /** * Fill the given ndarray with random numbers drawn from a uniform distribution using the given RandomGenerator * * @param target target array * @param min the minimum number * @param max the maximum number * @param rng the random generator to use * @return the given target array */ public static INDArray rand(INDArray target, double min, double max, org.nd4j.linalg.api.rng.Random rng) { if (min > max) throw new IllegalArgumentException("the maximum value supplied is smaller than the minimum"); return getExecutioner().exec(new UniformDistribution(target, min, max), rng); } /** * Fill the given ndarray with random numbers drawn from a normal distribution * * @param target target array * @return the given target array */ public static INDArray randn(INDArray target, long seed) { Nd4j.getRandom().setSeed(seed); return getExecutioner().exec(new GaussianDistribution(target), Nd4j.getRandom()); } /** * Fill the given ndarray with random numbers drawn from a normal distribution utilizing the given random generator * * @param target target array * @param rng the random generator to use * @return the given target array */ public static INDArray randn(INDArray target, org.nd4j.linalg.api.rng.Random rng) { return getExecutioner().exec(new GaussianDistribution(target), rng); } /** * Generate a random array according to a binomial distribution with probability p: i.e., values 0 with probability * (1-p) or value 1 with probability p * * @param p Probability. Must be in range 0 to 1 * @param shape Shape of the result array * @return Result array */ public static INDArray randomBernoulli(double p, long... shape) { return randomBernoulli(p, Nd4j.createUninitialized(shape)); } /** * Fill the specified array with values generated according to a binomial distribution with probability p: i.e., * values 0 with probability (1-p) or value 1 with probability p * * @param p Probability. Must be in range 0 to 1 * @param target Result array to place generated values in * @return Result array */ public static INDArray randomBernoulli(double p, @NonNull INDArray target) { Preconditions.checkArgument(p >= 0 && p <= 1.0, "Invalid probability: must be in range 0 to 1, got %s", p); return Nd4j.getExecutioner().exec(new BernoulliDistribution(target, p)); } /** * Generate an array with random values generated according to a binomial distribution with the specified * number of trials and probability * * @param nTrials Number of trials. Must be >= 0 * @param p Probability. Must be in range 0 to 1 * @param shape Shape of the result array * @return Result array */ public static INDArray randomBinomial(int nTrials, double p, long... shape) { return randomBinomial(nTrials, p, Nd4j.createUninitialized(shape)); } /** * Fill the target array with random values generated according to a binomial distribution with the specified * number of trials and probability * * @param nTrials Number of trials. Must be >= 0 * @param p Probability. Must be in range 0 to 1 * @param target Result array * @return Result array */ public static INDArray randomBinomial(int nTrials, double p, INDArray target) { Preconditions.checkArgument(p >= 0 && p <= 1.0, "Invalid probability: must be in range 0 to 1, got %s", p); Preconditions.checkArgument(nTrials >= 0, "Number of trials must be positive: got %s", nTrials); return Nd4j.getExecutioner().exec(new BinomialDistribution(target, nTrials, p)); } /** * Exponential distribution: P(x) = lambda * exp(-lambda * x) * * @param lambda Must be > 0 * @param shape Shape of the array to generate */ public static INDArray randomExponential(double lambda, long... shape) { return randomExponential(lambda, Nd4j.createUninitialized(shape)); } /** * Exponential distribution: P(x) = lambda * exp(-lambda * x) * * @param lambda Must be > 0 * @param target Array to hold the result */ public static INDArray randomExponential(double lambda, INDArray target) { Preconditions.checkArgument(lambda > 0, "Lambda argument must be >= 0 - got %s", lambda); INDArray shapeArr = Nd4j.create(ArrayUtil.toDouble(target.shape())); Nd4j.getExecutioner().execAndReturn(new RandomExponential(shapeArr, target, lambda)); return target; } ////////////////////// CREATE /////////////////////////////// /** * This method returns uninitialized 2D array of rows x columns * * PLEASE NOTE: memory of underlying array will be NOT initialized, and won't be set to 0.0 * * @param rows * @param columns * @return */ public static INDArray createUninitialized(long rows, long columns) { return createUninitialized(new long[] {rows, columns}); } /** * Creates a row vector with the data * * @param data the columns of the ndarray * @return the created ndarray */ public static INDArray create(float[] data) { return create(data, order()); } public static INDArray create(boolean[] data) { return INSTANCE.create(data, new long[]{data.length}, new long[]{1}, DataType.BOOL, Nd4j.getMemoryManager().getCurrentWorkspace()); } /** * Creates a row vector with the data * * @param list the columns of the ndarray * @return the created ndarray */ public static INDArray create(List<? extends Number> list) { INDArray array = create(list.size()); int cnt = 0; if (dataType() == DataType.DOUBLE) { for (Number element: list) { array.putScalar(cnt++,element.doubleValue()); } } else { for (Number element : list) { array.putScalar(cnt++,element.floatValue()); } } return array; } /** * Creates a row vector with the data * * @param data the columns of the ndarray * @return the created ndarray */ public static INDArray create(double[] data) { return create(data, order()); } /** * * @param data * @return */ public static INDArray create(float[][] data) { return INSTANCE.create(data); } /** * * @param data * @param ordering * @return */ public static INDArray create(float[][] data, char ordering) { return INSTANCE.create(data, ordering); } /** * Create an ndarray based on the given data layout * * @param data the data to use * @return an ndarray with the given data layout */ public static INDArray create(double[][] data) { return INSTANCE.create(data); } public static INDArray create(long[][] data) { val shape = new long[]{data.length, data[0].length}; return INSTANCE.create(ArrayUtil.flatten(data), shape, getStrides(shape), DataType.LONG, Nd4j.getMemoryManager().getCurrentWorkspace()); } public static INDArray create(boolean[][] data) { val shape = new long[]{data.length, data[0].length}; return INSTANCE.create(ArrayUtil.flatten(data), shape, getStrides(shape), DataType.BOOL, Nd4j.getMemoryManager().getCurrentWorkspace()); } public static INDArray create(boolean[][] data, long[] shape) { return INSTANCE.create(ArrayUtil.flatten(data), shape, getStrides(shape), DataType.BOOL, Nd4j.getMemoryManager().getCurrentWorkspace()); } public static INDArray create(double[][][] data) { return create(ArrayUtil.flatten(data), new int[] {data.length, data[0].length, data[0][0].length}); } public static INDArray create(float[][][] data) { return create(ArrayUtil.flatten(data), new int[] {data.length, data[0].length, data[0][0].length}); } public static INDArray create(int[][][] data) { return create(ArrayUtil.flatten(data), new int[] {data.length, data[0].length, data[0][0].length}); } public static INDArray create(double[][][][] data) { return create(ArrayUtil.flatten(data), new int[] {data.length, data[0].length, data[0][0].length, data[0][0][0].length}); } public static INDArray create(float[][][][] data) { return create(ArrayUtil.flatten(data), new int[] {data.length, data[0].length, data[0][0].length, data[0][0][0].length}); } public static INDArray create(int[][][][] data) { return create(ArrayUtil.flatten(data), new int[] {data.length, data[0].length, data[0][0].length, data[0][0][0].length}); } /** * * @param data * @param ordering * @return */ public static INDArray create(double[][] data, char ordering) { return INSTANCE.create(data, ordering); } /** * Creates a row vector with the specified number of columns * * @param columns the columns of the ndarray * @return the created ndarray */ public static INDArray create(int columns) { return create(columns, order()); } /** * Creates a row vector with the data * * @param data the columns of the ndarray * @return the created ndarray */ public static INDArray create(float[] data, char order) { INDArray ret = INSTANCE.create(data, order); logCreationIfNecessary(ret); return ret; } /** * Creates a row vector with the data * * @param data the columns of the ndarray * @return the created ndarray */ public static INDArray create(double[] data, char order) { INDArray ret = INSTANCE.create(data, order); logCreationIfNecessary(ret); return ret; } /** * Creates a row vector with the specified number of columns * * @param columns the columns of the ndarray * @return the created ndarray */ public static INDArray create(int columns, char order) { if (columns < 1) throw new ND4JIllegalStateException("Number of columns should be positive for new INDArray"); INDArray ret = INSTANCE.create(new long[] {columns}, Nd4j.getStrides(new long[] {columns}, order), 0, order); logCreationIfNecessary(ret); return ret; } public static INDArray zeros(int columns, char order) { return Nd4j.create(columns, order); } public static INDArray create(int[] data, long[] shape, DataType type) { val ret = INSTANCE.create(data, shape, Nd4j.getStrides(shape), type, Nd4j.getMemoryManager().getCurrentWorkspace()); logCreationIfNecessary(ret); return ret; } public static INDArray create(long[] data, long[] shape, DataType type) { val ret = INSTANCE.create(data, shape, Nd4j.getStrides(shape), type, Nd4j.getMemoryManager().getCurrentWorkspace()); logCreationIfNecessary(ret); return ret; } public static INDArray create(double[] data, long[] shape, DataType type) { val ret = INSTANCE.create(data, shape, Nd4j.getStrides(shape), type, Nd4j.getMemoryManager().getCurrentWorkspace()); logCreationIfNecessary(ret); return ret; } public static INDArray create(float[] data, long[] shape, DataType type) { val ret = INSTANCE.create(data, shape, Nd4j.getStrides(shape), type, Nd4j.getMemoryManager().getCurrentWorkspace()); logCreationIfNecessary(ret); return ret; } public static INDArray create(short[] data, long[] shape, DataType type) { val ret = INSTANCE.create(data, shape, Nd4j.getStrides(shape), type, Nd4j.getMemoryManager().getCurrentWorkspace()); logCreationIfNecessary(ret); return ret; } public static INDArray create(byte[] data, long[] shape, DataType type) { val ret = INSTANCE.create(data, shape, Nd4j.getStrides(shape), type, Nd4j.getMemoryManager().getCurrentWorkspace()); logCreationIfNecessary(ret); return ret; } public static INDArray create(boolean[] data, long[] shape, DataType type) { val ret = INSTANCE.create(data, shape, Nd4j.getStrides(shape), type, Nd4j.getMemoryManager().getCurrentWorkspace()); logCreationIfNecessary(ret); return ret; } //////////////////////////////////////////////// public static INDArray create(int[] data, long[] shape, long[]strides, char order, DataType type) { val ret = INSTANCE.create(data, shape, strides, order, type, Nd4j.getMemoryManager().getCurrentWorkspace()); logCreationIfNecessary(ret); return ret; } public static INDArray create(long[] data, long[] shape, long[]strides, char order, DataType type) { val ret = INSTANCE.create(data, shape, strides, order, type, Nd4j.getMemoryManager().getCurrentWorkspace()); logCreationIfNecessary(ret); return ret; } public static INDArray create(double[] data, long[] shape, long[]strides, char order, DataType type) { val ret = INSTANCE.create(data, shape, strides, order, type, Nd4j.getMemoryManager().getCurrentWorkspace()); logCreationIfNecessary(ret); return ret; } public static INDArray create(float[] data, long[] shape, long[]strides, char order, DataType type) { val ret = INSTANCE.create(data, shape, strides, order, type, Nd4j.getMemoryManager().getCurrentWorkspace()); logCreationIfNecessary(ret); return ret; } public static INDArray create(short[] data, long[] shape, long[]strides, char order, DataType type) { val ret = INSTANCE.create(data, shape, strides, order, type, Nd4j.getMemoryManager().getCurrentWorkspace()); logCreationIfNecessary(ret); return ret; } public static INDArray create(byte[] data, long[] shape, long[]strides, char order, DataType type) { val ret = INSTANCE.create(data, shape, strides, order, type, Nd4j.getMemoryManager().getCurrentWorkspace()); logCreationIfNecessary(ret); return ret; } public static INDArray create(boolean[] data, long[] shape, long[]strides, char order, DataType type) { val ret = INSTANCE.create(data, shape, strides, order, type, Nd4j.getMemoryManager().getCurrentWorkspace()); logCreationIfNecessary(ret); return ret; } /** * This method creates new 0D INDArray, aka scalar. * * PLEASE NOTE: Temporary method, added to ensure backward compatibility * @param scalar * @return * @deprecated Use Nd4j.scalar methods, such as {@link #scalar(double)} or {@link #scalar(DataType, Number)} */ @Deprecated public static INDArray trueScalar(Number scalar) { val ret = INSTANCE.trueScalar(scalar); logCreationIfNecessary(ret); return ret; } /** * @deprecated Use {@link #createFromArray(boolean...)} */ @Deprecated public static INDArray trueVector(boolean[] data) { val ret = INSTANCE.trueVector(data); logCreationIfNecessary(ret); return ret; } /** * @deprecated Use {@link #createFromArray(long...)} */ @Deprecated public static INDArray trueVector(long[] data) { val ret = INSTANCE.trueVector(data); logCreationIfNecessary(ret); return ret; } /** * @deprecated Use {@link #createFromArray(int...)} */ @Deprecated public static INDArray trueVector(int[] data) { val ret = INSTANCE.trueVector(data); logCreationIfNecessary(ret); return ret; } /** * @deprecated Use {@link #createFromArray(float...)} */ @Deprecated public static INDArray trueVector(float[] data) { val ret = INSTANCE.trueVector(data); logCreationIfNecessary(ret); return ret; } /** * @deprecated Use {@link #createFromArray(double...)} */ @Deprecated public static INDArray trueVector(double[] data) { val ret = INSTANCE.trueVector(data); logCreationIfNecessary(ret); return ret; } /** * This method creates "empty" INDArray with datatype determined by {@link #dataType()} * * @return Empty INDArray */ public static INDArray empty() { return empty(Nd4j.dataType()); } /** * This method creates "empty" INDArray of the specified datatype * * @return Empty INDArray */ public static INDArray empty(DataType type) { if(EMPTY_ARRAYS[type.ordinal()] == null){ try(MemoryWorkspace ws = Nd4j.getMemoryManager().scopeOutOfWorkspaces()){ val ret = INSTANCE.empty(type); EMPTY_ARRAYS[type.ordinal()] = ret; logCreationIfNecessary(ret); } } return EMPTY_ARRAYS[type.ordinal()]; } /** * Create an ndrray with the specified shape * * @param data the data to use with tne ndarray * @param shape the shape of the ndarray * @return the created ndarray */ public static INDArray create(float[] data, int[] shape) { if (shape.length == 0 && data.length == 1) { return scalar(data[0]); } if (shape.length == 1) { if (shape[0] != data.length) throw new ND4JIllegalStateException("Shape of the new array doesn't match data length"); } checkShapeValues(data.length, shape); INDArray ret = INSTANCE.create(data, shape); logCreationIfNecessary(ret); return ret; } public static INDArray create(float[] data, long[] shape) { if (shape.length == 0 && data.length == 1) { return scalar(data[0]); } if (shape.length == 1) { if (shape[0] != data.length) throw new ND4JIllegalStateException("Shape of the new array doesn't match data length"); } checkShapeValues(data.length, shape); INDArray ret = INSTANCE.create(data, shape, Nd4j.getStrides(shape, Nd4j.order()), DataType.FLOAT, Nd4j.getMemoryManager().getCurrentWorkspace()); logCreationIfNecessary(ret); return ret; } public static INDArray create(double[] data, long[] shape) { if (shape.length == 0 && data.length == 1) { return scalar(data[0]); } if (shape.length == 1) { if (shape[0] != data.length) throw new ND4JIllegalStateException("Shape of the new array doesn't match data length"); } checkShapeValues(data.length, shape); INDArray ret = INSTANCE.create(data, shape, Nd4j.getStrides(shape, Nd4j.order()), DataType.DOUBLE, Nd4j.getMemoryManager().getCurrentWorkspace()); logCreationIfNecessary(ret); return ret; } /** * Create an ndrray with the specified shape * * @param data the data to use with tne ndarray * @param shape the shape of the ndarray * @return the created ndarray */ public static INDArray create(double[] data, int[] shape) { if (shape.length == 1) { if (shape[0] != data.length) throw new ND4JIllegalStateException("Shape of the new array " + Arrays.toString(shape) + " doesn't match data length: " + data.length); } checkShapeValues(data.length, shape); val lshape = ArrayUtil.toLongArray(shape); INDArray ret = INSTANCE.create(data, lshape, Nd4j.getStrides(lshape, Nd4j.order()), DataType.DOUBLE, Nd4j.getMemoryManager().getCurrentWorkspace()); logCreationIfNecessary(ret); return ret; } /** * Creates an ndarray with the specified shape * * @param shape the shape of the ndarray * @param stride the stride for the ndarray * @param offset the offset of the ndarray * @return the instance */ public static INDArray create(double[] data, int[] shape, int[] stride, long offset) { if (shape.length == 1) { if (shape[0] != data.length) throw new ND4JIllegalStateException("Shape of the new array " + Arrays.toString(shape) + " doesn't match data length: " + data.length); } checkShapeValues(data.length, shape); INDArray ret = INSTANCE.create(data, ArrayUtil.toLongArray(shape), ArrayUtil.toLongArray(stride), DataType.DOUBLE, Nd4j.getMemoryManager().getCurrentWorkspace()); logCreationIfNecessary(ret); return ret; } public static INDArray create(double[] data, long[] shape, long[] stride, long offset, char order) { checkShapeValues(data.length, shape); INDArray ret = INSTANCE.create(data, shape, stride, order, DataType.DOUBLE, Nd4j.getMemoryManager().getCurrentWorkspace()); logCreationIfNecessary(ret); return ret; } /** * Creates an ndarray with the specified shape * * @param data the data to use with the ndarray * @param rows the rows of the ndarray * @param columns the columns of the ndarray * @param stride the stride for the ndarray * @param offset the offset of the ndarray * @return the instance */ public static INDArray create(float[] data, int rows, int columns, int[] stride, long offset) { if (rows < 1 || columns < 1) throw new ND4JIllegalStateException("Number of rows and columns should be positive for new INDArray"); INDArray ret = INSTANCE.create(data, rows, columns, stride, offset); logCreationIfNecessary(ret); return ret; } /** * Creates an ndarray with the specified shape * * @param data the data to use with tne ndarray * @param rows the rows of the ndarray * @param columns the columns of the ndarray * @param stride the stride for the ndarray * @param offset the offset of the ndarray * @return the instance */ public static INDArray create(double[] data, int rows, int columns, int[] stride, long offset) { if (rows < 1 || columns < 1) throw new ND4JIllegalStateException("Number of rows and columns should be positive for new INDArray"); INDArray ret = INSTANCE.create(data, rows, columns, stride, offset); logCreationIfNecessary(ret); return ret; } /** * Creates an ndarray with the specified shape * * @param shape the shape of the ndarray * @param offset the offset of the ndarray * @return the instance */ public static INDArray create(float[] data, int[] shape, long offset) { if (shape.length == 1) { if (shape[0] != data.length) throw new ND4JIllegalStateException("Shape of the new array " + Arrays.toString(shape) + " doesn't match data length: " + data.length); } checkShapeValues(data.length, shape); INDArray ret = INSTANCE.create(data, shape, offset, Nd4j.order()); logCreationIfNecessary(ret); return ret; } public static INDArray create(float[] data, long[] shape, long offset) { if (shape.length == 1) { if (shape[0] != data.length) throw new ND4JIllegalStateException("Shape of the new array " + Arrays.toString(shape) + " doesn't match data length: " + data.length); } checkShapeValues(data.length, shape); INDArray ret = INSTANCE.create(data, shape, offset, Nd4j.order()); logCreationIfNecessary(ret); return ret; } /** * Creates an ndarray with the specified shape * * @param shape the shape of the ndarray * @param offset the offset of the ndarray * @return the instance */ public static INDArray create(double[] data, int[] shape, long offset, char ordering) { if (shape.length == 1) { if (shape[0] != data.length) throw new ND4JIllegalStateException("Shape of the new array " + Arrays.toString(shape) + " doesn't match data length: " + data.length); } checkShapeValues(data.length, shape); INDArray ret = INSTANCE.create(data, shape, Nd4j.getStrides(shape, ordering), offset, ordering); logCreationIfNecessary(ret); return ret; } public static INDArray create(double[] data, long[] shape, long offset, char ordering) { if (shape.length == 1) { if (shape[0] != data.length) throw new ND4JIllegalStateException("Shape of the new array " + Arrays.toString(shape) + " doesn't match data length: " + data.length); } checkShapeValues(data.length, shape); INDArray ret = INSTANCE.create(data, shape, Nd4j.getStrides(shape, ordering), offset, ordering); logCreationIfNecessary(ret); return ret; } /** * Creates an ndarray with the specified shape * * @param shape the shape of the ndarray * @param stride the stride for the ndarray * @param offset the offset of the ndarray * @return the instance */ public static INDArray create(float[] data, int[] shape, int[] stride, long offset) { if (shape.length == 1) { if (shape[0] != data.length) throw new ND4JIllegalStateException("Shape of the new array " + Arrays.toString(shape) + " doesn't match data length: " + data.length); } checkShapeValues(data.length, shape); INDArray ret = INSTANCE.create(data, shape, stride, offset); logCreationIfNecessary(ret); return ret; } /** * Creates an ndarray with the specified shape * * @param shape the shape of the ndarray * @return the instance */ public static INDArray create(List<INDArray> list, int[] shape) { checkShapeValues(shape); INDArray ret = INSTANCE.create(list, shape); logCreationIfNecessary(ret); return ret; } public static INDArray create(List<INDArray> list, long[] shape) { checkShapeValues(shape); INDArray ret = INSTANCE.create(list, shape); logCreationIfNecessary(ret); return ret; } /** * Creates an ndarray with the specified shape * * @param rows the rows of the ndarray * @param columns the columns of the ndarray * @param stride the stride for the ndarray * @param offset the offset of the ndarray * @return the instance */ public static INDArray create(int rows, int columns, int[] stride, long offset) { if (rows < 1 || columns < 1) throw new ND4JIllegalStateException("Number of rows and columns should be positive for new INDArray"); INDArray ret = INSTANCE.create(rows, columns, stride, offset); logCreationIfNecessary(ret); return ret; } public static INDArray zeros(int rows, int columns, int[] stride, long offset) { return create(rows, columns, stride, offset); } /** * Creates an ndarray with the specified shape * * @param shape the shape of the ndarray * @param stride the stride for the ndarray * @param offset the offset of the ndarray * @return the instance */ public static INDArray create(int[] shape, int[] stride, long offset) { checkShapeValues(shape); INDArray ret = INSTANCE.create(shape, stride, offset); logCreationIfNecessary(ret); return ret; } public static INDArray zeros(int[] shape, int[] stride, long offset) { return create(shape, stride, offset); } /** * Creates an ndarray with the specified shape * * @param rows the rows of the ndarray * @param columns the columns of the ndarray * @param stride the stride for the ndarray * @return the instance */ public static INDArray create(int rows, int columns, int[] stride) { return create(rows, columns, stride, order()); } public static INDArray zeros(int rows, int columns, int[] stride) { return create(rows, columns, stride, order()); } /** * Creates an ndarray with the specified shape * * @param shape the shape of the ndarray * @param stride the stride for the ndarray * @return the instance */ public static INDArray create(int[] shape, int[] stride) { return create(shape, stride, order()); } /** * * @param shape * @param stride * @return */ public static INDArray create(long[] shape, long[] stride) { return create(shape, stride, order()); } /** * * @param shape * @param stride * @return */ public static INDArray zeros(int[] shape, int[] stride) { return create(shape, stride); } /** * Creates an ndarray with the specified shape * * @param rows the rows of the ndarray * @param columns the columns of the ndarray * @return the instance */ public static INDArray create(int rows, int columns) { return create(rows, columns, order()); } /** * Creates an ndarray with the specified shape * * @param shape the shape of the ndarray * @return the instance */ public static INDArray create(int... shape) { return create(shape, order()); } /** * Creates an ndarray with the specified shape * * @param shape the shape of the ndarray * @return the instance */ public static INDArray create(long... shape) { return create(shape, order()); } public static INDArray create(DataType type, long... shape) { return create(type, shape, order()); } /** * * @param data * @param shape * @param stride * @param ordering * @param offset * @return */ public static INDArray create(float[] data, int[] shape, int[] stride, char ordering, long offset) { if (shape.length == 1) { if (shape[0] != data.length) throw new ND4JIllegalStateException("Shape of the new array " + Arrays.toString(shape) + " doesn't match data length: " + data.length); } checkShapeValues(data.length, shape); INDArray ret = INSTANCE.create(data, shape, stride, offset, ordering); logCreationIfNecessary(ret); return ret; } /** * * @param data * @param shape * @param ordering * @param offset * @return */ public static INDArray create(float[] data, int[] shape, char ordering, long offset) { if (shape.length == 1) { if (shape[0] != data.length) throw new ND4JIllegalStateException("Shape of the new array " + Arrays.toString(shape) + " doesn't match data length: " + data.length); } checkShapeValues(data.length, shape); INDArray ret = INSTANCE.create(data, shape, getStrides(shape, ordering), offset, ordering); logCreationIfNecessary(ret); return ret; } public static INDArray create(double[] data, int[] shape, char ordering, long offset) { if (shape.length == 1) { if (shape[0] != data.length) throw new ND4JIllegalStateException("Shape of the new array " + Arrays.toString(shape) + " doesn't match data length: " + data.length); } checkShapeValues(data.length, shape); INDArray ret = INSTANCE.create(data, shape, getStrides(shape, ordering), offset, ordering); logCreationIfNecessary(ret); return ret; } /** * * @param data * @param shape * @param strides * @param offset * @return */ public static INDArray create(DataBuffer data, int[] shape, int[] strides, long offset) { checkShapeValues(shape); INDArray ret = INSTANCE.create(data, shape, strides, offset); logCreationIfNecessary(ret); return ret; } public static INDArray create(DataBuffer data, long[] shape, long[] strides, long offset) { checkShapeValues(shape); INDArray ret = INSTANCE.create(data, shape, strides, offset); logCreationIfNecessary(ret); return ret; } /** * * @param data * @param shape * @param offset * @return */ public static INDArray create(DataBuffer data, int[] shape, long offset) { checkShapeValues(shape); INDArray ret = INSTANCE.create(data, shape, getStrides(shape), offset); logCreationIfNecessary(ret); return ret; } /** * * @param data * @param newShape * @param newStride * @param offset * @param ordering * @return */ public static INDArray create(DataBuffer data, int[] newShape, int[] newStride, long offset, char ordering) { checkShapeValues(newShape); INDArray ret = INSTANCE.create(data, newShape, newStride, offset, ordering); logCreationIfNecessary(ret); return ret; } public static INDArray create(DataBuffer data, long[] newShape, long[] newStride, long offset, char ordering) { checkShapeValues(newShape); INDArray ret = INSTANCE.create(data, newShape, newStride, offset, ordering); logCreationIfNecessary(ret); return ret; } public static INDArray create(DataBuffer data, long[] newShape, long[] newStride, long offset, long ews, char ordering) { checkShapeValues(newShape); INDArray ret = INSTANCE.create(data, newShape, newStride, offset, ews, ordering); logCreationIfNecessary(ret); return ret; } public static INDArray create(DataBuffer data, long[] newShape, long[] newStride, long offset, char ordering, DataType dataType) { checkShapeValues(newShape); INDArray ret = INSTANCE.create(data, newShape, newStride, offset, ordering, dataType); logCreationIfNecessary(ret); return ret; } /** * * @param data * @param shape * @return */ public static INDArray create(DataBuffer data, int[] shape) { checkShapeValues(shape); INDArray ret = INSTANCE.create(data, shape); logCreationIfNecessary(ret); return ret; } public static INDArray create(DataBuffer data, long[] shape) { checkShapeValues(shape); INDArray ret = INSTANCE.create(data, shape); logCreationIfNecessary(ret); return ret; } /** * * @param buffer * @return */ public static INDArray create(DataBuffer buffer) { INDArray ret = INSTANCE.create(buffer); logCreationIfNecessary(ret); return ret; } /** * Creates an ndarray with the specified shape * * @param data the data to use with the ndarray * @param rows the rows of the ndarray * @param columns the columns of the ndarray * @param stride the stride for the ndarray * @param offset the offset of the ndarray * @return the instance */ public static INDArray create(float[] data, int rows, int columns, int[] stride, long offset, char ordering) { int[] shape = new int[] {rows, columns}; checkShapeValues(data.length, shape); INDArray ret = INSTANCE.create(data, shape, stride, offset, ordering); logCreationIfNecessary(ret); return ret; } /** * * @param shape * @param dataType * @return */ public static INDArray create(int[] shape, DataType dataType) { checkShapeValues(shape); INDArray ret = INSTANCE.create(shape, dataType, Nd4j.getMemoryManager().getCurrentWorkspace()); logCreationIfNecessary(ret); return ret; } public static INDArray zeros(int[] shape, DataType dataType) { return create(shape, dataType); } /** * Creates an ndarray with the specified shape * * @param shape the shape of the ndarray * @param stride the stride for the ndarray * @param offset the offset of the ndarray * @return the instance */ public static INDArray create(double[] data, int[] shape, int[] stride, long offset, char ordering) { if (data.length == 1 && shape.length == 0) return scalar(data[0]); if (shape.length == 1) { if (shape[0] != data.length) throw new ND4JIllegalStateException("Shape of the new array " + Arrays.toString(shape) + " doesn't match data length: " + data.length); } checkShapeValues(data.length, shape); INDArray ret = INSTANCE.create(data, shape, stride, offset, ordering); logCreationIfNecessary(ret); return ret; } /** * Create an ndrray with the specified shape * * @param data the data to use with tne ndarray * @param shape the shape of the ndarray * @return the created ndarray */ public static INDArray create(double[] data, int[] shape, char ordering) { if (shape.length == 1) { if (shape[0] != data.length) throw new ND4JIllegalStateException("Shape of the new array " + Arrays.toString(shape) + " doesn't match data length: " + data.length); } checkShapeValues(data.length, shape); val lshape = ArrayUtil.toLongArray(shape); INDArray ret = INSTANCE.create(data, lshape, Nd4j.getStrides(lshape, ordering), ordering, DataType.DOUBLE, Nd4j.getMemoryManager().getCurrentWorkspace()); logCreationIfNecessary(ret); return ret; } /** * Create an ndrray with the specified shape * * @param data the data to use with tne ndarray * @param shape the shape of the ndarray * @return the created ndarray */ public static INDArray create(float[] data, int[] shape, char ordering) { if (shape.length == 1) { if (shape[0] != data.length) throw new ND4JIllegalStateException("Shape of the new array " + Arrays.toString(shape) + " doesn't match data length: " + data.length); } checkShapeValues(data.length, shape); INDArray ret = INSTANCE.create(data, shape, ordering); logCreationIfNecessary(ret); return ret; } public static INDArray create(float[] data, long[] shape, char ordering) { checkShapeValues(data.length, shape); INDArray ret = INSTANCE.create(data, shape, Nd4j.getStrides(shape, ordering), ordering, DataType.FLOAT); logCreationIfNecessary(ret); return ret; } public static INDArray create(double[] data, long[] shape, char ordering) { checkShapeValues(data.length, shape); INDArray ret = INSTANCE.create(data, shape, Nd4j.getStrides(shape, ordering), ordering, DataType.DOUBLE, Nd4j.getMemoryManager().getCurrentWorkspace()); logCreationIfNecessary(ret); return ret; } /** * Creates an ndarray with the specified shape * * @param data the data to use with tne ndarray * @param rows the rows of the ndarray * @param columns the columns of the ndarray * @param stride the stride for the ndarray * @param offset the offset of the ndarray * @return the instance */ public static INDArray create(double[] data, int rows, int columns, int[] stride, long offset, char ordering) { int[] shape = new int[]{rows,columns}; checkShapeValues(data.length, shape); INDArray ret = INSTANCE.create(Nd4j.createBuffer(data), shape, stride, offset, ordering); logCreationIfNecessary(ret); return ret; } /** * Creates an ndarray with the specified shape * * @param shape the shape of the ndarray * @param stride the stride for the ndarray * @param offset the offset of the ndarray * @return the instance */ public static INDArray create(float[] data, int[] shape, int[] stride, long offset, char ordering) { if (shape.length == 1) { if (shape[0] != data.length) throw new ND4JIllegalStateException("Shape of the new array " + Arrays.toString(shape) + " doesn't match data length: " + data.length); } checkShapeValues(data.length, shape); INDArray ret = INSTANCE.create(data, shape, stride, offset, ordering); logCreationIfNecessary(ret); return ret; } /** * Creates an ndarray with the specified shape * * @param shape the shape of the ndarray * @return the instance */ public static INDArray create(List<INDArray> list, int[] shape, char ordering) { checkShapeValues(shape); INDArray ret = INSTANCE.create(list, shape, ordering); logCreationIfNecessary(ret); return ret; } /** * Creates an ndarray with the specified shape * * @param rows the rows of the ndarray * @param columns the columns of the ndarray * @param stride the stride for the ndarray * @param offset the offset of the ndarray * @return the instance */ public static INDArray create(int rows, int columns, int[] stride, long offset, char ordering) { int[] shape = new int[]{rows, columns}; checkShapeValues(shape); INDArray ret = INSTANCE.create(shape, stride, offset, ordering); logCreationIfNecessary(ret); return ret; } public static INDArray zeros(int rows, int columns, int[] stride, long offset, char ordering) { return create(rows, columns, stride, offset, ordering); } /** * Creates an ndarray with the specified shape * * @param shape the shape of the ndarray * @param stride the stride for the ndarray * @param offset the offset of the ndarray * @return the instance */ public static INDArray create(int[] shape, int[] stride, long offset, char ordering) { if(shape.length == 0) return Nd4j.scalar(0.0); checkShapeValues(shape); INDArray ret = INSTANCE.create(shape, stride, offset, ordering); logCreationIfNecessary(ret); return ret; } /** * Creates an ndarray with the specified shape * * @param shape the shape of the ndarray * @param stride the stride for the ndarray * @param offset the offset of the ndarray * @return the instance */ public static INDArray create(long[] shape, long[] stride, long offset, char ordering) { if(shape.length == 0) return Nd4j.scalar(0.0); checkShapeValues(shape); INDArray ret = INSTANCE.create(shape, stride, offset, ordering); logCreationIfNecessary(ret); return ret; } public static INDArray zeros(int[] shape, int[] stride, long offset, char ordering) { return create(shape, stride, offset, ordering); } /** * Creates an ndarray with the specified shape * * @param rows the rows of the ndarray * @param columns the columns of the ndarray * @param stride the stride for the ndarray * @return the instance */ public static INDArray create(int rows, int columns, int[] stride, char ordering) { int[] shape = new int[]{rows, columns}; checkShapeValues(shape); INDArray ret = INSTANCE.create(shape, stride, 0, ordering); logCreationIfNecessary(ret); return ret; } public static INDArray zeros(int rows, int columns, int[] stride, char ordering) { return create(rows, columns, stride, ordering); } /** * Creates an ndarray with the specified shape * * @param shape the shape of the ndarray * @param stride the stride for the ndarray * @return the instance */ public static INDArray create(int[] shape, int[] stride, char ordering) { if(shape.length == 0) return Nd4j.scalar(Nd4j.dataType(), 0.0); checkShapeValues(shape); INDArray ret = INSTANCE.create(shape, stride, 0, ordering); logCreationIfNecessary(ret); return ret; } public static INDArray create(long[] shape, long[] stride, char ordering) { if(shape.length == 0) return Nd4j.scalar(Nd4j.dataType(), 0.0); checkShapeValues(shape); INDArray ret = INSTANCE.create(shape, stride, 0, ordering); logCreationIfNecessary(ret); return ret; } /** * * @param shape * @param stride * @param ordering * @return */ public static INDArray zeros(int[] shape, int[] stride, char ordering) { return create(shape, stride, ordering); } /** * Creates an ndarray with the specified shape * * @param rows the rows of the ndarray * @param columns the columns of the ndarray * @return the instance */ public static INDArray create(long rows, long columns, char ordering) { return create(new long[] {rows, columns}, ordering); } /** * * @param rows * @param columns * @param ordering * @return */ public static INDArray zeros(int rows, int columns, char ordering) { return create(new int[] {rows, columns}, ordering); } /** * Creates an ndarray with the specified shape * * @param shape the shape of the ndarray * @return the instance */ public static INDArray create(@NonNull int[] shape, char ordering) { if(shape.length == 0) return Nd4j.scalar(dataType(), 0.0); checkShapeValues(shape); INDArray ret = INSTANCE.create(shape, ordering); logCreationIfNecessary(ret); return ret; } /** * * @param shape * @param ordering * @return */ public static INDArray create(@NonNull long[] shape, char ordering) { if(shape.length == 0) return Nd4j.scalar(dataType(), 0.0); //ensure shapes that wind up being scalar end up with the write shape checkShapeValues(shape); INDArray ret = INSTANCE.create(shape, ordering); logCreationIfNecessary(ret); return ret; } public static INDArray create(DataType dataType, @NonNull long[] shape, long[] strides, char ordering) { if(shape.length == 0) return Nd4j.scalar(dataType, 0.0); checkShapeValues(shape); INDArray ret = INSTANCE.create(dataType, shape, strides, ordering, Nd4j.getMemoryManager().getCurrentWorkspace()); logCreationIfNecessary(ret); return ret; } public static INDArray create(@NonNull DataType dataType, @NonNull long[] shape, char ordering) { if(shape.length == 0) return Nd4j.scalar(dataType, 0.0); //ensure shapes that wind up being scalar end up with the write shape checkShapeValues(shape); INDArray ret = INSTANCE.create(dataType, shape, ordering, Nd4j.getMemoryManager().getCurrentWorkspace()); logCreationIfNecessary(ret); return ret; } /** * * @param shape */ public static void checkShapeValues(long[] shape) { for (long e: shape) { if (e < 1) throw new ND4JIllegalStateException("Invalid shape: Requested INDArray shape " + Arrays.toString(shape) + " contains dimension size values < 1 (all dimensions must be 1 or more)"); } } /** * * @param shape */ public static void checkShapeValues(int[] shape) { for (int e: shape) { if (e < 1) throw new ND4JIllegalStateException("Invalid shape: Requested INDArray shape " + Arrays.toString(shape) + " contains dimension size values < 1 (all dimensions must be 1 or more)"); } } protected static void checkShapeValues(int length, int[] shape) { checkShapeValues(shape); if (ArrayUtil.prodLong(shape) > length) throw new ND4JIllegalStateException("Shape of the new array " + Arrays.toString(shape) + " doesn't match data length: " + length); } protected static void checkShapeValues(int length, long[] shape) { checkShapeValues(shape); if (ArrayUtil.prodLong(shape) > length) throw new ND4JIllegalStateException("Shape of the new array " + Arrays.toString(shape) + " doesn't match data length: " + length); } /** * Creates an *uninitialized* ndarray with the specified shape and ordering.<br> * <b>NOTE</b>: The underlying memory (DataBuffer) will not be initialized. Don't use this unless you know what you are doing. * * @param shape the shape of the ndarray * @param ordering the order of the ndarray * @return the instance */ public static INDArray createUninitialized(int[] shape, char ordering) { if (shape.length == 0) return scalar(dataType(), 0.0); checkShapeValues(shape); INDArray ret = INSTANCE.createUninitialized(shape, ordering); logCreationIfNecessary(ret); return ret; } public static INDArray createUninitialized(DataType type, long... shape) { return createUninitialized(type, shape, Nd4j.order()); } public static INDArray createUninitialized(DataType type, long[] shape, char ordering) { if (shape.length == 0) { if(type == DataType.UTF8){ return scalar(""); } return scalar(type, 0); } checkShapeValues(shape); INDArray ret = INSTANCE.createUninitialized(type, shape, ordering, Nd4j.getMemoryManager().getCurrentWorkspace()); logCreationIfNecessary(ret); return ret; } public static INDArray createUninitialized(long[] shape, char ordering) { if (shape.length == 0) return scalar(dataType(), 0.0); checkShapeValues(shape); INDArray ret = INSTANCE.createUninitialized(shape, ordering); logCreationIfNecessary(ret); return ret; } /** * Cretes uninitialized INDArray detached from any (if any) workspace * * @param shape * @param ordering * @return */ public static INDArray createUninitializedDetached(int[] shape, char ordering) { if (shape.length == 0) return scalar(dataType(), 0.0); checkShapeValues(shape); INDArray ret = INSTANCE.createUninitializedDetached(shape, ordering); logCreationIfNecessary(ret); return ret; } /** * * @param shape * @param ordering * @return */ public static INDArray createUninitializedDetached(long[] shape, char ordering) { if (shape.length == 0) return scalar(dataType(), 0.0); checkShapeValues(shape); INDArray ret = INSTANCE.createUninitializedDetached(shape, ordering); logCreationIfNecessary(ret); return ret; } /** * Creates an *uninitialized* ndarray with the specified shape and default ordering.<br> * <b>NOTE</b>: The underlying memory (DataBuffer) will not be initialized. Don't use this unless you know what you are doing. * * @param shape the shape of the ndarray * @return the instance */ public static INDArray createUninitialized(int[] shape) { if(shape.length == 0) return Nd4j.scalar(dataType(), 0.0); checkShapeValues(shape); //ensure shapes that wind up being scalar end up with the write shape return createUninitialized(shape, Nd4j.order()); } public static INDArray createUninitialized(long[] shape) { checkShapeValues(shape); //ensure shapes that wind up being scalar end up with the write shape return createUninitialized(shape, Nd4j.order()); } /** * Cretes uninitialized INDArray detached from any (if any) workspace * * @param shape * @return */ public static INDArray createUninitializedDetached(int[] shape) { return createUninitializedDetached(shape, Nd4j.order()); } /** * Cretes uninitialized INDArray detached from any (if any) workspace * * @param shape * @return */ public static INDArray createUninitializedDetached(long[] shape) { return createUninitializedDetached(shape, Nd4j.order()); } /** * This method creates an *uninitialized* ndarray of specified length and default ordering. * * PLEASE NOTE: Do not use this method unless you're 100% sure why you use it. * * @param length * @return */ public static INDArray createUninitialized(int length) { return createUninitialized((long)length); } public static INDArray createUninitialized(long length) { if (length < 1) throw new IllegalStateException("INDArray length should be positive value"); long[] shape = new long[] {length}; INDArray ret = INSTANCE.createUninitialized(shape, order()); logCreationIfNecessary(ret); return ret; } /** * Cretes uninitialized INDArray detached from any (if any) workspace * * @param length * @return */ public static INDArray createUninitializedDetached(int length) { if (length < 1) throw new IllegalStateException("INDArray length should be positive value"); long[] shape = new long[] {length}; INDArray ret = INSTANCE.createUninitializedDetached(shape, order()); logCreationIfNecessary(ret); return ret; } /** * * @param data * @param shape * @param offset * @return */ public static INDArray create(double[] data, int[] shape, long offset) { if (shape.length == 1) { if (shape[0] != data.length) throw new ND4JIllegalStateException("Shape of the new array " + Arrays.toString(shape) + " doesn't match data length: " + data.length); } checkShapeValues(data.length, shape); INDArray ret = INSTANCE.create(data, shape, offset); logCreationIfNecessary(ret); return ret; } /** * @param data * @param columns * @param pointerB * @param pointerE * @param shape * @return a INDArray * */ public static INDArray createSparseCSR(double[] data, int[] columns, int[] pointerB, int[] pointerE, long[] shape) { INDArray matrix = SPARSE_INSTANCE.createSparseCSR(data, columns, pointerB, pointerE, shape); return matrix; } /** * @param data * @param columns * @param pointerB * @param pointerE * @param shape * @return a INDArray * */ public static INDArray createSparseCSR(float[] data, int[] columns, int[] pointerB, int[] pointerE, long[] shape) { INDArray matrix = SPARSE_INSTANCE.createSparseCSR(data, columns, pointerB, pointerE, shape); return matrix; } /** * @param data * @param columns * @param pointerB * @param pointerE * @param shape * @return a INDArray * */ public static INDArray createSparseCSR(DataBuffer data, int[] columns, int[] pointerB, int[] pointerE, long[] shape) { INDArray matrix = SPARSE_INSTANCE.createSparseCSR(data, columns, pointerB, pointerE, shape); return matrix; } /** * @param data * @param indices * @param shape * @return a INDArray * */ public static INDArray createSparseCOO(double[] data, int[][] indices, long[] shape) { INDArray matrix = SPARSE_INSTANCE.createSparseCOO(data, indices, shape); return matrix; } /** * @param data * @param indices * @param shape * @return a INDArray * */ public static INDArray createSparseCOO(float[] data, int[][] indices, long[] shape) { INDArray matrix = SPARSE_INSTANCE.createSparseCOO(data, indices, shape); return matrix; } /** * @param data * @param indices * @param shape * @return a INDArray * */ public static INDArray createSparseCOO(double[] data, long[][] indices, long[] shape) { INDArray matrix = SPARSE_INSTANCE.createSparseCOO(data, indices, shape); return matrix; } /** * @param data * @param indices * @param shape * @return a INDArray * */ public static INDArray createSparseCOO(float[] data, long[][] indices, long[] shape) { INDArray matrix = SPARSE_INSTANCE.createSparseCOO(data, indices, shape); return matrix; } /** * @param data * @param indices * @param shape * @return a INDArray * */ public static INDArray createSparseCOO(DataBuffer data, DataBuffer indices, long[] shape) { INDArray matrix = SPARSE_INSTANCE.createSparseCOO(data, indices, shape); return matrix; } /** * @param values a DataBuffer with the sparse non-null values * @param indices a DataBuffer with the indexes of the values * @param sparseInformation a DataBuffer containing the sparse information (flags, offsets and hidden dimensions) * @param shape * @return a INDArray * */ public static INDArray createSparseCOO(DataBuffer values, DataBuffer indices, DataBuffer sparseInformation, long[] shape) { INDArray matrix = SPARSE_INSTANCE.createSparseCOO(values, indices, sparseInformation, shape); return matrix; } /** * @param values a DataBuffer with the sparse non-null values * @param indices a DataBuffer with the indexes of the values * @param sparseOffsets the sparse * @param flags an array that define the inactive dimension * @param shape * @param hiddenDimensions an array containing the position of the hidden dimensions * @param underlyingRank the rank of the original ndarray * @return a INDArray * */ public static INDArray createSparseCOO(DataBuffer values, DataBuffer indices, long[] sparseOffsets, int[] flags, long[] shape, int[] hiddenDimensions, int underlyingRank) { INDArray matrix = SPARSE_INSTANCE.createSparseCOO(values, indices, sparseOffsets, flags, hiddenDimensions, underlyingRank, shape); return matrix; } ////////////////////// OTHER /////////////////////////////// /** * Creates a row vector with the specified number of columns * * @param rows the rows of the sndarray * @param columns the columns of the ndarray * @return the created ndarray */ public static INDArray zeros(long rows, long columns) { INDArray ret = INSTANCE.zeros(rows, columns); logCreationIfNecessary(ret); return ret; } /** * Creates a row vector with the specified number of columns * * @param columns the columns of the ndarray * @return the created ndarray */ public static INDArray zeros(int columns) { return INSTANCE.zeros(columns); } public static INDArray zeros(DataType dataType, int columns) { return INSTANCE.create(dataType, new long[]{columns}, 'c', Nd4j.getMemoryManager().getCurrentWorkspace()); } public static INDArray zeros(DataType dataType, long... shape) { return INSTANCE.create(dataType, shape, 'c', Nd4j.getMemoryManager().getCurrentWorkspace()); } /** * Creates an ndarray with the specified value * as the only value in the ndarray. * Some people may know this as np.full * * @param shape the shape of the ndarray * @param value the value to assign * @return the created ndarray */ public static INDArray valueArrayOf(int[] shape, double value) { if (shape.length == 0) return scalar(value); checkShapeValues(shape); INDArray ret = INSTANCE.valueArrayOf(shape, value); logCreationIfNecessary(ret); return ret; } /** * Creates an ndarray with the specified value as the only value in the FLOAT32 datatype NDArray. * Equivalent to Numpy's np.full * * @param shape the shape of the ndarray * @param value the value to assign * @return the created ndarray */ public static INDArray valueArrayOf(long[] shape, float value) { return valueArrayOf(shape, (double)value, DataType.FLOAT); } /** * Creates an ndarray with the specified value as the only value in the INTEGER datatype NDArray. * Equivalent to Numpy's np.full * * @param shape the shape of the ndarray * @param value the value to assign * @return the created ndarray */ public static INDArray valueArrayOf(long[] shape, int value) { return valueArrayOf(shape, (double)value, DataType.INT); } /** * Creates an ndarray with the specified value * as the only value in the ndarray. * Some people may know this as np.full * * @param shape the shape of the ndarray * @param value the value to assign * @return the created ndarray */ public static INDArray valueArrayOf(long[] shape, double value) { if (shape.length == 0) return scalar(value); checkShapeValues(shape); INDArray ret = INSTANCE.valueArrayOf(shape, value); logCreationIfNecessary(ret); return ret; } public static INDArray valueArrayOf(long[] shape, double value, DataType type) { if (shape.length == 0) return scalar(type, value); checkShapeValues(shape); INDArray ret = createUninitialized(type, shape); logCreationIfNecessary(ret); ret.assign(value); return ret; } public static INDArray valueArrayOf(long[] shape, long value, DataType type) { if (shape.length == 0) return scalar(type, value); checkShapeValues(shape); INDArray ret = createUninitialized(type, shape); logCreationIfNecessary(ret); ret.assign(value); return ret; } /** * Creates a row vector ndarray with the specified value * as the only value in the ndarray * * Some people may know this as np.full * * @param num number of columns * @param value the value to assign * @return the created ndarray */ public static INDArray valueArrayOf(long num, double value) { INDArray ret = INSTANCE.valueArrayOf(new long[] {num}, value); logCreationIfNecessary(ret); return ret; } /** * Creates a row vector with the specified number of columns * * Some people may know this as np.full * * @param rows the number of rows in the matrix * @param columns the columns of the ndarray * @param value the value to assign * @return the created ndarray */ public static INDArray valueArrayOf(long rows, long columns, double value) { if (rows < 1 || columns < 1) throw new ND4JIllegalStateException("Number of rows and columns should be positive for new INDArray"); INDArray ret = INSTANCE.valueArrayOf(rows, columns, value); logCreationIfNecessary(ret); return ret; } /** * Creates a row vector with the specified number of columns * * @param rows the number of rows in the matrix * @param columns the columns of the ndarray * @return the created ndarray */ public static INDArray ones(int rows, int columns) { INDArray ret = INSTANCE.ones(rows, columns); logCreationIfNecessary(ret); return ret; } public static INDArray ones(DataType dataType, int rows, int columns) { INDArray ret = INSTANCE.createUninitialized(dataType, new long[]{rows, columns}, Nd4j.order(), Nd4j.getMemoryManager().getCurrentWorkspace()); logCreationIfNecessary(ret); ret.assign(1); return ret; } /** * Empty like * * @param arr the array to create the ones like * @return ones in the shape of the given array */ public static INDArray zerosLike(INDArray arr) { return zeros(arr.dataType(), arr.shape()); } /** * Ones like * * @param arr the array to create the ones like * @return ones in the shape of the given array */ public static INDArray onesLike(INDArray arr) { return ones(arr.dataType(), arr.shape()); } /** * Creates a row vector with the specified number of columns * * @param columns the columns of the ndarray * @return the created ndarray */ public static INDArray ones(DataType dataType, long... columns) { INDArray ret = INSTANCE.createUninitialized(dataType, columns, Nd4j.order(), Nd4j.getMemoryManager().getCurrentWorkspace()); ret.assign(1); logCreationIfNecessary(ret); return ret; } /** * Concatenates two matrices horizontally. Matrices must have identical * numbers of rows. * * @param arrs the first matrix to concat */ public static INDArray hstack(INDArray... arrs) { INDArray ret = INSTANCE.hstack(arrs); logCreationIfNecessary(ret); return ret; } /** * Concatenates two matrices horizontally. Matrices must have identical * numbers of rows. * * @param arrs the first matrix to concat */ public static INDArray hstack(Collection<INDArray> arrs) { INDArray[] arrays = arrs.toArray(new INDArray[0]); INDArray ret = INSTANCE.hstack(arrays); logCreationIfNecessary(ret); return ret; } /** * Concatenates two matrices vertically. Matrices must have identical numbers of columns.<br> * Note that for vstack on rank 1 arrays, this is equivalent to {@link Nd4j#pile(INDArray...)}. Example: vstack([3],[3]) -> [2,3] * * @param arrs Arrays to vstack */ public static INDArray vstack(INDArray... arrs) { Preconditions.checkState(arrs != null && arrs.length > 0, "No input specified to vstack (null or length 0)"); if(arrs[0].rank() == 1){ //Edge case: vstack rank 1 arrays - gives rank 2... vstack([3],[3]) -> [2,3] return pile(arrs); } INDArray ret = INSTANCE.vstack(arrs); logCreationIfNecessary(ret); return ret; } /** * Concatenates two matrices vertically. Matrices must have identical numbers of columns.<br> * Note that for vstack on rank 1 arrays, this is equivalent to {@link Nd4j#pile(INDArray...)}. Example: vstack([3],[3]) -> [2,3] * * @param arrs Arrays to vstack */ public static INDArray vstack(Collection<INDArray> arrs) { INDArray[] arrays = arrs.toArray(new INDArray[0]); return vstack(arrays); } /** * This method averages input arrays, and returns averaged array. * On top of that, averaged array is propagated to all input arrays * * @param arrays * @return */ public static INDArray averageAndPropagate(INDArray target, INDArray[] arrays) { INDArray ret = INSTANCE.average(target, arrays); logCreationIfNecessary(ret); return ret; } /** * This method averages input arrays, and returns averaged array. * On top of that, averaged array is propagated to all input arrays * * @param arrays * @return */ public static INDArray averageAndPropagate(INDArray[] arrays) { INDArray ret = INSTANCE.average(arrays); logCreationIfNecessary(ret); return ret; } /** * This method averages input arrays, and returns averaged array. * On top of that, averaged array is propagated to all input arrays * * @param arrays * @return */ public static INDArray averageAndPropagate(Collection<INDArray> arrays) { INDArray ret = INSTANCE.average(arrays); logCreationIfNecessary(ret); return ret; } /** * This method averages input arrays, and returns averaged array. * On top of that, averaged array is propagated to all input arrays * * @param arrays * @return */ public static INDArray averageAndPropagate(INDArray target, Collection<INDArray> arrays) { INDArray ret = INSTANCE.average(target, arrays); logCreationIfNecessary(ret); return ret; } /** * Reshapes an ndarray to remove leading 1s * @param toStrip the ndarray to newShapeNoCopy * @return the reshaped ndarray */ public static INDArray stripOnes(INDArray toStrip) { if (toStrip.isVector()) return toStrip; else { long[] shape = Shape.squeeze(toStrip.shape()); return toStrip.reshape(shape); } } /** * This method sums given arrays and stores them to a new target array * * @param arrays * @return */ public static INDArray accumulate(Collection<INDArray> arrays) { if (arrays == null|| arrays.size() == 0) throw new ND4JIllegalStateException("Input for accumulation is null or empty"); return accumulate(arrays.toArray(new INDArray[0])); } /** * This method sums given arrays and stores them to a new array * * @param arrays * @return */ public static INDArray accumulate(INDArray... arrays) { if (arrays == null|| arrays.length == 0) throw new ND4JIllegalStateException("Input for accumulation is null or empty"); return accumulate(Nd4j.create(arrays[0].shape(), arrays[0].ordering()), arrays); } /** * This method sums given arrays and stores them to a given target array * * @param target * @param arrays * @return */ public static INDArray accumulate(INDArray target, Collection<INDArray> arrays) { return accumulate(target, arrays.toArray(new INDArray[0])); } /** * This method sums given arrays and stores them to a given target array * * @param target * @param arrays * @return */ public static INDArray accumulate(INDArray target, INDArray[] arrays) { if (arrays == null|| arrays.length == 0) return target; return factory().accumulate(target, arrays); } /** * This method produces concatenated array, that consist from tensors, fetched from source array, against some dimension and specified indexes * * @param source source tensor * @param sourceDimension dimension of source tensor * @param indexes indexes from source array * @return */ public static INDArray pullRows(INDArray source, int sourceDimension, int[] indexes) { return pullRows(source, sourceDimension, indexes, Nd4j.order()); } /** * This method produces concatenated array, * that consist from tensors, * fetched from source array, * against some dimension and specified indexes * * @param source source tensor * @param sourceDimension dimension of source tensor * @param indexes indexes from source array * @return */ public static INDArray pullRows(INDArray source, int sourceDimension, int[] indexes, char order) { if (sourceDimension >= source.rank()) throw new IllegalStateException("Source dimension can't be higher the rank of source tensor"); if (indexes == null || indexes.length == 0) throw new IllegalStateException("Indexes shouldn't be empty"); if (order != 'c' && order != 'f' && order != 'a') throw new IllegalStateException("Unknown order being passed in [" + order + "]"); for (int idx : indexes) { if (idx < 0 || idx >= source.shape()[source.rank() - sourceDimension - 1]) { throw new IllegalStateException( "Index can't be < 0 and >= " + source.shape()[source.rank() - sourceDimension - 1]); } } INDArray ret = INSTANCE.pullRows(source, sourceDimension, indexes, order); logCreationIfNecessary(ret); return ret; } /** * This method produces concatenated array, that consist from tensors, fetched from source array, against some * dimension and specified indexes. * The concatenated arrays are placed in the specified array. * * @param source source tensor * @param destination Destination tensor (result will be placed here) * @param sourceDimension dimension of source tensor * @param indexes indexes from source array * @return Destination array with specified tensors */ public static INDArray pullRows(INDArray source, INDArray destination, int sourceDimension, int[] indexes){ if (sourceDimension >= source.rank()) throw new IllegalStateException("Source dimension can't be higher the rank of source tensor"); if (indexes == null || indexes.length == 0) throw new IllegalStateException("Indexes shouldn't be empty"); for (int idx : indexes) { if (idx < 0 || idx >= source.shape()[source.rank() - sourceDimension - 1]) { throw new IllegalStateException( "Index can't be < 0 and >= " + source.shape()[source.rank() - sourceDimension - 1]); } } INDArray ret = INSTANCE.pullRows(source, destination, sourceDimension, indexes); logCreationIfNecessary(ret); return ret; } /** * Stack a set of N SDVariables of rank X into one rank X+1 variable. * If inputs have shape [a,b,c] then output has shape:<br> * axis = 0: [N,a,b,c]<br> * axis = 1: [a,N,b,c]<br> * axis = 2: [a,b,N,c]<br> * axis = 3: [a,b,c,N]<br> * * @param axis Axis to stack on * @param values Input variables to stack. Must have the same shape for all inputs * @return Output array * @see #concat(int, INDArray...) */ public static INDArray stack(int axis, INDArray... values){ Preconditions.checkArgument(values != null && values.length > 0, "No inputs: %s", values); Preconditions.checkState(axis >= -(values[0].rank()+1) && axis < values[0].rank()+1, "Invalid axis: must be between " + "%s (inclusive) and %s (exclusive) for rank %s input, got %s", -(values[0].rank()+1), values[0].rank()+1, values[0].rank(), axis); Stack stack = new Stack(values, null, axis); INDArray[] outputArrays = Nd4j.getExecutioner().allocateOutputArrays(stack); stack.addOutputArgument(outputArrays); Nd4j.getExecutioner().execAndReturn(stack); return outputArrays[0]; } /** * Concatneate ndarrays along a dimension * * @param dimension the dimension to concatneate along * @param toConcat the ndarrays to concat * @return the merged ndarrays with an output shape of * the ndarray shapes save the dimension shape specified * which is then the sum of the sizes along that dimension */ public static INDArray concat(int dimension, INDArray... toConcat) { if(dimension < 0) { dimension += toConcat[0].rank(); } INDArray ret = INSTANCE.concat(dimension, toConcat); logCreationIfNecessary(ret); return ret; } /** * Concatneate ndarrays along a dimension * * PLEASE NOTE: This method is special for GPU backend, it works on HOST side only. * * @param dimension * @param toConcat * @return */ public static INDArray specialConcat(int dimension, INDArray... toConcat) { INDArray ret = INSTANCE.specialConcat(dimension, toConcat); logCreationIfNecessary(ret); return ret; } /** * Create an ndarray of zeros * * @param shape the shape of the ndarray * @return an ndarray with ones filled in */ public static INDArray zeros(int[] shape, char order) { checkShapeValues(shape); INDArray ret = INSTANCE.create(shape, order); logCreationIfNecessary(ret); return ret; } public static INDArray zeros(long[] shape, char order) { checkShapeValues(shape); INDArray ret = INSTANCE.create(shape, order); logCreationIfNecessary(ret); return ret; } /** * Create an ndarray of zeros * * @param shape the shape of the ndarray * @return an ndarray with ones filled in */ public static INDArray zeros(int... shape) { return Nd4j.create(shape); } /** * Create an ndarray of zeros * * @param shape the shape of the ndarray * @return an ndarray with ones filled in */ public static INDArray zeros(long... shape) { return Nd4j.create(shape); } /** * Create an ndarray of ones * * @param shape the shape of the ndarray * @return an ndarray with ones filled in */ public static INDArray ones(@NonNull int... shape) { if(shape.length == 0) return Nd4j.scalar(dataType(), 1.0); checkShapeValues(shape); INDArray ret = INSTANCE.ones(shape); logCreationIfNecessary(ret); return ret; } public static INDArray ones(@NonNull long... shape) { if(shape.length == 0) return Nd4j.scalar(dataType(), 1.0); checkShapeValues(shape); INDArray ret = INSTANCE.ones(shape); logCreationIfNecessary(ret); return ret; } /** * Create a scalar ndarray with the specified value * * @param value the value to initialize the scalar with * @return the created ndarray */ public static INDArray scalar(Number value) { INDArray ret = INSTANCE.scalar(value); logCreationIfNecessary(ret); return ret; } /** * Create a scalar ndarray with the specified value and datatype * * @param value the value to initialize the scalar with * @return the created ndarray */ public static INDArray scalar(DataType dataType, Number value) { INDArray ret = INSTANCE.trueScalar(dataType, value); logCreationIfNecessary(ret); return ret; } /** * Create a scalar nd array with the specified value * * @param value the value of the scalar * @return the scalar nd array */ public static INDArray scalar(double value) { return scalar(DataType.DOUBLE, value); } /** * Create a scalar NDArray with the specified value and FLOAT datatype * * @param value the value of the scalar * @return the scalar nd array */ public static INDArray scalar(float value) { return scalar(DataType.FLOAT, value); } /** * Create a scalar NDArray with the specified value and BOOLEAN datatype * * @param value the value of the scalar * @return the scalar nd array */ public static INDArray scalar(boolean value) { return INSTANCE.trueScalar(DataType.BOOL, value ? 1 : 0); } /** * Create a scalar NDArray with the specified value and INT datatype * * @param value the value of the scalar * @return the scalar nd array */ public static INDArray scalar(int value) { return scalar(DataType.INT, value); } /** * Create a scalar NDArray with the specified value and LONG datatype * * @param value the value of the scalar * @return the scalar nd array */ public static INDArray scalar(long value) { return scalar(DataType.LONG, value); } /** * Get the strides for the given order and shape * * @param shape the shape of the ndarray * @param order the order to getScalar the strides for * @return the strides for the given shape and order */ public static int[] getStrides(int[] shape, char order) { if (order == NDArrayFactory.FORTRAN) return ArrayUtil.calcStridesFortran(shape); return ArrayUtil.calcStrides(shape); } public static long[] getStrides(long[] shape, char order) { if (order == NDArrayFactory.FORTRAN) return ArrayUtil.calcStridesFortran(shape); return ArrayUtil.calcStrides(shape); } /** * Get the strides based on the shape * and NDArrays.order() * * @param shape the shape of the ndarray * @return the strides for the given shape * and order specified by NDArrays.order() */ public static int[] getStrides(int[] shape) { return getStrides(shape, Nd4j.order()); } /** * Get the strides based on the shape * and NDArrays.order() * * @param shape the shape of the ndarray * @return the strides for the given shape * and order specified by NDArrays.order() */ public static long[] getStrides(long[] shape) { return getStrides(shape, Nd4j.order()); } /** * An alias for repmat * * @param tile the ndarray to tile * @param repeat the shape to repeat * @return the tiled ndarray */ public static INDArray tile(INDArray tile, int... repeat) { int d = repeat.length; long[] shape = ArrayUtil.copy(tile.shape()); long n = Math.max(tile.length(), 1); if (d < tile.rank()) { repeat = Ints.concat(ArrayUtil.nTimes(tile.rank() - d, 1), repeat); } for (int i = 0; i < shape.length; i++) { if (repeat[i] != 1) { tile = tile.reshape(-1, n).repeat(0, repeat[i]); } long in = shape[i]; long nOut = in * repeat[i]; shape[i] = nOut; n /= Math.max(in, 1); } return tile.reshape(shape); } /** * Get the strides for the given order and shape * * @param shape the shape of the ndarray * @param order the order to getScalar the strides for * @return the strides for the given shape and order */ public static int[] getComplexStrides(int[] shape, char order) { if (order == NDArrayFactory.FORTRAN) return ArrayUtil.calcStridesFortran(shape, 2); return ArrayUtil.calcStrides(shape, 2); } public static long[] getComplexStrides(long[] shape, char order) { if (order == NDArrayFactory.FORTRAN) return ArrayUtil.calcStridesFortran(shape, 2); return ArrayUtil.calcStrides(shape, 2); } /** * Get the strides based on the shape * and NDArrays.order() * * @param shape the shape of the ndarray * @return the strides for the given shape * and order specified by NDArrays.order() */ public static int[] getComplexStrides(int[] shape) { return getComplexStrides(shape, Nd4j.order()); } public static long[] getComplexStrides(long[] shape) { return getComplexStrides(shape, Nd4j.order()); } /** * Initializes nd4j */ public synchronized void initContext() { try { defaultFloatingPointDataType = new AtomicReference<>(); defaultFloatingPointDataType.set(DataType.FLOAT); Nd4jBackend backend = Nd4jBackend.load(); initWithBackend(backend); } catch (NoAvailableBackendException e) { throw new RuntimeException(e); } } /** * Initialize with the specific backend * @param backend the backend to initialize with */ public void initWithBackend(Nd4jBackend backend) { VersionCheck.checkVersions(); try { if (System.getProperties().getProperty("backends") != null && !System.getProperties().getProperty("backends").contains(backend.getClass().getName())) { return; } if (!isSupportedPlatform()) { showAttractiveMessage(getMessageForUnsupportedPlatform()); return; } Nd4j.backend = backend; updateNd4jContext(); props = Nd4jContext.getInstance().getConf(); PropertyParser pp = new PropertyParser(props); String otherDtype = pp.toString(ND4JSystemProperties.DTYPE); dtype = otherDtype.equalsIgnoreCase("float") ? DataType.FLOAT : otherDtype.equalsIgnoreCase("half") ? DataType.HALF : DataType.DOUBLE; if (dtype == DataType.HALF && backend.getClass().getName().equals("CpuBackend")) { showAttractiveMessage(getMessageForNativeHalfPrecision()); } if (Nd4j.dataType() != dtype){ DataTypeUtil.setDTypeForContext(dtype); } compressDebug = pp.toBoolean(COMPRESSION_DEBUG); shouldInstrument = pp.toBoolean(INSTRUMENTATION); ORDER = pp.toChar(ORDER_KEY, NDArrayFactory.C); affinityManagerClazz = (Class<? extends BasicAffinityManager>) Class .forName(pp.toString(AFFINITY_MANAGER)); affinityManager = affinityManagerClazz.newInstance(); ndArrayFactoryClazz = (Class<? extends NDArrayFactory>) Class.forName( pp.toString(NDARRAY_FACTORY_CLASS)); sparseNDArrayClazz = (Class<? extends NDArrayFactory>) Class.forName( pp.toString(SPARSE_NDARRAY_FACTORY_CLASS)); convolutionInstanceClazz = (Class<? extends ConvolutionInstance>) Class .forName(pp.toString(CONVOLUTION_OPS, DefaultConvolutionInstance.class.getName())); String defaultName = pp.toString(DATA_BUFFER_OPS, DefaultDataBufferFactory.class.getName()); dataBufferFactoryClazz = (Class<? extends DataBufferFactory>) Class .forName(pp.toString(DATA_BUFFER_OPS, defaultName)); shapeInfoProviderClazz = (Class<? extends BaseShapeInfoProvider>) Class .forName(pp.toString(SHAPEINFO_PROVIDER)); sparseInfoProviderClazz = (Class<? extends BaseSparseInfoProvider>) Class.forName( pp.toString(SPARSEINFO_PROVIDER)); constantProviderClazz = (Class<? extends BasicConstantHandler>) Class .forName(pp.toString(CONSTANT_PROVIDER)); memoryManagerClazz = (Class<? extends BasicMemoryManager>) Class .forName(pp.toString(MEMORY_MANAGER)); allowsOrder = backend.allowsOrder(); String rand = pp.toString(RANDOM_PROVIDER, DefaultRandom.class.getName()); randomClazz = (Class<? extends org.nd4j.linalg.api.rng.Random>) Class.forName(rand); randomFactory = new RandomFactory(randomClazz); workspaceManagerClazz = (Class<? extends MemoryWorkspaceManager>) Class .forName(pp.toString(WORKSPACE_MANAGER)); instrumentationClazz = (Class<? extends Instrumentation>) Class .forName(pp.toString(INSTRUMENTATION_CLASS, InMemoryInstrumentation.class.getName())); blasWrapperClazz = (Class<? extends BlasWrapper>) Class .forName(pp.toString(BLAS_OPS)); sparseBlasWrapperClazz = (Class<? extends BlasWrapper>) Class .forName(pp.toString(SPARSE_BLAS_OPS)); String clazzName = pp.toString(DISTRIBUTION, DefaultDistributionFactory.class.getName()); distributionFactoryClazz = (Class<? extends DistributionFactory>) Class.forName(clazzName); memoryManager = memoryManagerClazz.newInstance(); constantHandler = constantProviderClazz.newInstance(); shapeInfoProvider = shapeInfoProviderClazz.newInstance(); sparseInfoProvider = sparseInfoProviderClazz.newInstance(); workspaceManager = workspaceManagerClazz.newInstance(); opExecutionerClazz = (Class<? extends OpExecutioner>) Class .forName(pp.toString(OP_EXECUTIONER, DefaultOpExecutioner.class.getName())); instrumentation = instrumentationClazz.newInstance(); OP_EXECUTIONER_INSTANCE = opExecutionerClazz.newInstance(); Constructor c2 = ndArrayFactoryClazz.getConstructor(DataType.class, char.class); INSTANCE = (NDArrayFactory) c2.newInstance(dtype, ORDER); SPARSE_INSTANCE = sparseNDArrayClazz.newInstance(); CONVOLUTION_INSTANCE = convolutionInstanceClazz.newInstance(); BLAS_WRAPPER_INSTANCE = blasWrapperClazz.newInstance(); SPARSE_BLAS_WRAPPER_INSTANCE = sparseBlasWrapperClazz.newInstance(); DATA_BUFFER_FACTORY_INSTANCE = dataBufferFactoryClazz.newInstance(); DISTRIBUTION_FACTORY = distributionFactoryClazz.newInstance(); if (isFallback()) { fallbackMode.set(true); showAttractiveMessage(getMessageForFallback()); } else { fallbackMode.set(false); } String logInitProperty = System.getProperty(ND4JSystemProperties.LOG_INITIALIZATION, "true"); if(Boolean.parseBoolean(logInitProperty)) { OP_EXECUTIONER_INSTANCE.printEnvironmentInformation(); } val actions = ServiceLoader.load(EnvironmentalAction.class); val mappedActions = new HashMap<String, EnvironmentalAction>(); for (val a: actions) { if (!mappedActions.containsKey(a.targetVariable())) mappedActions.put(a.targetVariable(), a); } for (val e: mappedActions.keySet()) { val action = mappedActions.get(e); val value = System.getenv(e); if (value != null) { try { action.process(value); } catch (Exception e2) { logger.info("Failed to process env variable [" + e + "], got exception: " + e2.toString()); } } } } catch (Exception e) { throw new RuntimeException(e); } } private static boolean isSupportedPlatform() { return (System.getProperty("java.vm.name").equalsIgnoreCase("Dalvik") || System.getProperty("os.arch").toLowerCase().startsWith("arm") || System.getProperty("sun.arch.data.model").equals("64")); } private static void showAttractiveMessage(String... strings) { System.out.println(attract(strings)); } private static String attract(String... strings) { String delimiter = "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"; String shift = " "; StringBuilder sb = new StringBuilder().append(delimiter).append("\n").append("\n"); for (String s : strings) { sb.append(shift).append(s).append("\n"); } sb.append("\n").append(delimiter).append("\n"); return sb.toString(); } private static String[] getMessageForUnsupportedPlatform() { return new String[] {"Unfortunately you can't use DL4j/ND4j on 32-bit x86 JVM", "Please, consider running this on 64-bit JVM instead"}; } private static String[] getMessageForFallback() { return new String[] {"ND4J_FALLBACK environment variable is detected!", "Performance will be slightly reduced"}; } private String[] getMessageForNativeHalfPrecision() { return new String[] {"Half-precision data opType isn't support for nd4j-native", "Please, consider using FLOAT or DOUBLE data opType instead"}; } private void updateNd4jContext() throws IOException { try (InputStream is = backend.getConfigurationResource().getInputStream()) { Nd4jContext.getInstance().updateProperties(is); } } private boolean isFallback() { String fallback = System.getenv(ND4JEnvironmentVars.ND4J_FALLBACK); if (fallback == null) { return false; } return (fallback.equalsIgnoreCase("true") || fallback.equalsIgnoreCase("1")); } /** * * @return */ public static ShapeInfoProvider getShapeInfoProvider() { return shapeInfoProvider; } /** * * @return */ public static SparseInfoProvider getSparseInfoProvider() { return sparseInfoProvider; } /** * * @return */ public static ConstantHandler getConstantHandler() { return constantHandler; } /** * * @return */ public static AffinityManager getAffinityManager() { return affinityManager; } /** * * @return */ public static NDArrayFactory getNDArrayFactory() { return INSTANCE; } /** * This method returns BasicNDArrayCompressor instance, * suitable for NDArray compression/decompression * at runtime * * @return */ public static BasicNDArrayCompressor getCompressor() { return BasicNDArrayCompressor.getInstance(); } /** * This method returns backend-specific MemoryManager implementation, for low-level memory management * @return */ public static MemoryManager getMemoryManager() { return memoryManager; } public static INDArray typeConversion(INDArray array, DataTypeEx targetType) { return null; } /** * This method returns sizeOf(currentDataType), in bytes * * @return number of bytes per element */ public static int sizeOfDataType() { return sizeOfDataType(Nd4j.dataType()); } /** * This method returns size of element for specified dataType, in bytes * * @param dtype number of bytes per element * @return */ public static int sizeOfDataType(DataType dtype) { switch (dtype) { case BYTE: case BOOL: case UBYTE: return 1; case SHORT: case HALF: return 2; case FLOAT: case INT: return 4; case LONG: case DOUBLE: return 8; default: throw new ND4JIllegalStateException("Unsupported data type: [" + dtype +"]" ); } } /** * This method enables fallback to safe-mode for specific operations. Use of this method will reduce performance. * Currently supported operations are: * 1) CPU GEMM * * PLEASE NOTE: Do not use this method, unless you have too. * * @param reallyEnable */ public static void enableFallbackMode(boolean reallyEnable) { fallbackMode.set(reallyEnable); } /** * This method checks, if fallback mode was enabled. * * @return */ public static boolean isFallbackModeEnabled() { return fallbackMode.get(); } /** * This method returns WorkspaceManager implementation to be used within this JVM process * * @return */ public static MemoryWorkspaceManager getWorkspaceManager() { return workspaceManager; } /** * This method stacks vertically examples with the same shape, increasing result dimensionality. I.e. if you provide bunch of 3D tensors, output will be 4D tensor. Alignment is always applied to axis 0. * * @return */ public static INDArray pile(INDArray... arrays) { // if we have vectors as input, it's just vstack use case long[] shape = arrays[0].shape(); long[] newShape = ArrayUtils.add(shape, 0, 1); boolean shouldReshape = true; List<INDArray> reshaped = new ArrayList<>(); for(INDArray array: arrays) { if (!shouldReshape) reshaped.add(array); else reshaped.add(array.reshape(array.ordering(), newShape)); } return Nd4j.vstack(reshaped); } /** * This method stacks vertically examples with the same shape, increasing result dimensionality. I.e. if you provide bunch of 3D tensors, output will be 4D tensor. Alignment is always applied to axis 0. * * @return */ public static INDArray pile(@NonNull Collection<INDArray> arrays) { return pile(arrays.toArray(new INDArray[0])); } /** * This method does the opposite to pile/vstack/hstack - it returns independent TAD copies along given dimensions * * @param tensor * @param dimensions * @return */ public static INDArray[] tear(INDArray tensor, int... dimensions) { if (dimensions.length >= tensor.rank()) throw new ND4JIllegalStateException("Target dimensions number should be less tensor rank"); for (int e = 0; e < dimensions.length; e++) if (dimensions[e] < 0) throw new ND4JIllegalStateException("Target dimensions can't have negative values"); return factory().tear(tensor, dimensions); } /** * Upper triangle of an array. Return a copy of a matrix with the elements below the `k`-th diagonal zeroed. Please refer to the documentation for `tril` for further details. * @param m * @param k * @return */ public static INDArray triu(INDArray m,int k) { /** * """ Upper triangle of an array. Return a copy of a matrix with the elements below the `k`-th diagonal zeroed. Please refer to the documentation for `tril` for further details. See Also -------- tril : lower triangle of an array Examples -------- >>> np.triu([[1,2,3],[4,5,6],[7,8,9],[10,11,12]], -1) array([[ 1, 2, 3], [ 4, 5, 6], [ 0, 8, 9], [ 0, 0, 12]]) """ m = asanyarray(m) mask = tri(*m.shape[-2:], k=k-1, dtype=bool) return where(mask, zeros(1, m.dtype), m) */ //INDArray mask = tri(m.size(-2),1); /** * Find a way to apply choose with an existing condition array. * (This appears to be the select op in libnd4j) */ /* Select select = new Select(new INDArray[]{mask,Nd4j.zeros(1),m},new INDArray[]{Nd4j.zerosLike(m)}); Nd4j.getExecutioner().exec(select); return select.getOutputArgument(0); */ INDArray result = Nd4j.createUninitialized(m.shape()); val op = DynamicCustomOp.builder("triu") .addInputs(m) .addOutputs(result) .addIntegerArguments(k) .build(); Nd4j.getExecutioner().execAndReturn(op); return result; } /** * * @param n * @return */ public static INDArray tri(int n) { return tri(n,n,0); } /** * * @param n * @param k * @return */ public static INDArray tri(int n,int k) { return tri(n,n,k); } /** * Like the scipy function tri. * From the scipy documentation: * An array with ones at and below the given diagonal and zeros elsewhere. * @param n number of rows in the array * @param m number of columns in the array ( can be just equal to n) * @param k The sub-diagonal at and below which the array is filled. `k` = 0 is the main diagonal, while `k` < 0 is below it, and `k` > 0 is above. The default is 0. * @return */ public static INDArray tri(int n,int m,int k) { /* INDArray mRet = Transforms.greaterThanOrEqual(arange(n),arange(-k,m - k)); return mRet; */ INDArray ret = Nd4j.createUninitialized(n, m); val op = DynamicCustomOp.builder("tri") .addIntegerArguments(n, m, k) .addOutputs(ret) .build(); Nd4j.getExecutioner().execAndReturn(op); return ret; } /** * Similar to numpy.where operation. * Supports two modes of operation:<br> * (a) condition array only is provided: returns N 1d arrays of the indices where "condition" values are non-zero. * Specifically, each output out has shape [numNonZero(condition)], such that in[out[0], ..., out[n-1]] is non-zero<br> * (b) all 3 arrays are provided: returns {@code out[i] = (condition[i] != 0 ? x[i] : y[i])}<br> * @param condition Condition array * @param x X array. If null, y must be null also. * @param y Y array. If null, x must be null also * @return Either the indices where condition is non-zero (if x and y are null), or values from x/y depending on * value of condition */ public static INDArray[] where(INDArray condition, INDArray x, INDArray y){ Preconditions.checkState((x == null && y == null) || (x != null && y != null), "Both X and Y must be" + "null, or neither must be null"); INDArray out; DynamicCustomOp.DynamicCustomOpsBuilder op = DynamicCustomOp.builder("where_np"); List<LongShapeDescriptor> outShapes; if(x == null){ //First case: condition only... op.addInputs(condition); } else { if(!x.equalShapes(y) || !x.equalShapes(condition)){ Preconditions.throwStateEx("Shapes must be equal: condition=%s, x=%s, y=%s", condition.shape(), x.shape(), y.shape()); } op.addInputs(condition, x, y); } DynamicCustomOp o = op.build(); outShapes = Nd4j.getExecutioner().calculateOutputShape(o); INDArray[] outputs = new INDArray[outShapes.size()]; if(x == null && (outShapes.get(0) == null || outShapes.get(0).getShape().length == 0 || outShapes.get(0).getShape()[0] == 0)){ //Empty: no conditions match for( int i=0; i<outputs.length; i++ ){ outputs[i] = Nd4j.empty(); } return outputs; } for(int i=0; i<outputs.length; i++){ outputs[i] = Nd4j.create(outShapes.get(i), false); } op.addOutputs(outputs); Nd4j.getExecutioner().execAndReturn(op.build()); return outputs; } /** * Write an {@link INDArray} to a {@link File} in Numpy .npy format, which can then be loaded with numpy.load * @param arr the array to write in Numpy .npy format * @param file the file to write to * @throws IOException if an error occurs when writing the file */ public static void writeAsNumpy(INDArray arr, File file) throws IOException { writeAsNumpy(arr, new FileOutputStream(file)); } /** * Converts an {@link INDArray} to a numpy struct. * @param arr the array to convert * @return a pointer to the numpy struct */ public static Pointer convertToNumpy(INDArray arr) { return INSTANCE.convertToNumpy(arr); } /** * Writes an array to an output stream * @param arr the array to write * @param writeTo the output stream to write to * @throws IOException */ public static void writeAsNumpy(INDArray arr, OutputStream writeTo) throws IOException { try(BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(writeTo)) { Pointer asNumpy = convertToNumpy(arr); WritableByteChannel channel = Channels.newChannel(bufferedOutputStream); int written = channel.write(asNumpy.asByteBuffer()); if(written != asNumpy.capacity()) { throw new IllegalStateException("Not all bytes were written! Original capacity " + asNumpy.capacity() + " but wrote " + written); } bufferedOutputStream.flush(); } } /** * Create from an in memory numpy pointer * * @param pointer the pointer to the * numpy array * @return an ndarray created from the in memory * numpy pointer */ public static INDArray createFromNpyPointer(Pointer pointer) { return INSTANCE.createFromNpyPointer(pointer); } /** * Create from a given Numpy .npy file. * * @param file the file to create the ndarray from * @return the created ndarray */ public static INDArray createFromNpyFile(File file) { return INSTANCE.createFromNpyFile(file); } public static Map<String, INDArray> createFromNpzFile(File file) throws Exception{ return INSTANCE.createFromNpzFile(file); } /** * Create a numpy array based on the passed in input stream * @param is the input stream to read * @return the loaded ndarray * @throws IOException */ public static INDArray createNpyFromInputStream(InputStream is) throws IOException { byte[] content = IOUtils.toByteArray(is); return createNpyFromByteArray(content); } /** * Create an {@link INDArray} from the given numpy input.<br> * The numpy input follows the format: * https://docs.scipy.org/doc/numpy-1.14.0/neps/npy-format.html * * @param input the input byte array with the npy format * @return the equivalent {@link INDArray} */ public static INDArray createNpyFromByteArray(byte[] input) { ByteBuffer byteBuffer = ByteBuffer.allocateDirect(input.length); byteBuffer.put(input); byteBuffer.rewind(); Pointer pointer = new Pointer(byteBuffer); return createFromNpyPointer(pointer); } /** * Converts an {@link INDArray} to a byte array * @param input the input array * @return the {@link INDArray} as a byte array * with the numpy format. * For more on the format, see: https://docs.scipy.org/doc/numpy-1.14.0/neps/npy-format.html * @throws IOException */ public static byte[] toNpyByteArray(INDArray input) throws IOException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); writeAsNumpy(input,byteArrayOutputStream); return byteArrayOutputStream.toByteArray(); } /** * Create an {@link INDArray} from a flatbuffers {@link FlatArray} * @param array the array to create the {@link INDArray} from * @return the created {@link INDArray} */ public static INDArray createFromFlatArray(FlatArray array) { val dtype = array.dtype(); val order = array.byteOrder(); val rank = (int) array.shape(0); val shapeInfo = new long[Shape.shapeInfoLength(rank)]; for (int e = 0; e < shapeInfo.length; e++) shapeInfo[e] = array.shape(e); if (Shape.isEmpty(shapeInfo)) return Nd4j.empty(); char ordering = shapeInfo[shapeInfo.length - 1] == 99 ? 'c' : 'f'; val shapeOf = Shape.shapeOf(shapeInfo); val stridesOf = Shape.stridesOf(shapeInfo); val _dtype = FlatBuffersMapper.getDataTypeFromByte(dtype); val _order = FlatBuffersMapper.getOrderFromByte(order); val prod = rank > 0 ? ArrayUtil.prod(shapeOf) : 1; val bb = array.bufferAsByteBuffer(); switch (_dtype) { case DOUBLE: { val doubles = new double[prod]; val db = bb.order(_order).asDoubleBuffer(); for (int e = 0; e < prod; e++) doubles[e] = db.get(e); return Nd4j.create(doubles, shapeOf, stridesOf, ordering, DataType.DOUBLE); } case FLOAT: { val doubles = new float[prod]; val fb = bb.order(_order).asFloatBuffer(); for (int e = 0; e < prod; e++) doubles[e] = fb.get(e); return Nd4j.create(doubles, shapeOf, stridesOf, ordering, DataType.FLOAT); } case HALF: { val doubles = new float[prod]; val sb = bb.order(_order).asShortBuffer(); for (int e = 0; e < prod; e++) doubles[e] = HalfIndexer.toFloat((int) sb.get(e)); return Nd4j.create(doubles, shapeOf, stridesOf, ordering, DataType.HALF); } case INT: { val doubles = new int[prod]; val sb = bb.order(_order).asIntBuffer(); for (int e = 0; e < prod; e++) doubles[e] = sb.get(e); return Nd4j.create(doubles, shapeOf, stridesOf, ordering, DataType.INT); } case LONG: { val doubles = new long[prod]; val sb = bb.order(_order).asLongBuffer(); for (int e = 0; e < prod; e++) doubles[e] = sb.get(e); return Nd4j.create(doubles, shapeOf, stridesOf, ordering, DataType.LONG); } case SHORT: { val doubles = new short[prod]; val sb = bb.order(_order).asShortBuffer(); for (int e = 0; e < prod; e++) doubles[e] = sb.get(e); return Nd4j.create(doubles, shapeOf, stridesOf, ordering, DataType.SHORT); } case BYTE: { val doubles = new byte[prod]; val sb = bb.order(_order).asReadOnlyBuffer(); for (int e = 0; e < prod; e++) doubles[e] = (byte) sb.get(e + sb.position()); return Nd4j.create(doubles, shapeOf, stridesOf, ordering, DataType.BYTE); } case BOOL: { val doubles = new boolean[prod]; val sb = bb.order(_order).asReadOnlyBuffer(); for (int e = 0; e < prod; e++) doubles[e] = sb.get(e + sb.position()) == 1; return Nd4j.create(doubles, shapeOf, stridesOf, ordering, DataType.BOOL); } case UTF8: { try { val list = new ArrayList<String>(prod); val sb = bb.order(_order); val pos = bb.position(); val arr = new byte[sb.limit()]; for (int e = 0; e < arr.length; e++) { arr[e] = sb.get(e); } val bytes = Arrays.copyOfRange(arr, pos, arr.length); val bis = new ByteArrayInputStream(bytes); val dis = new DataInputStream(bis); val length = (int) dis.readLong(); val offsets = new long[length+1]; for (int e = 0; e <= length; e++) offsets[e] = dis.readLong(); for (int e = 0; e < length; e++) { val start = offsets[e]; val end = offsets[e+1]; val len = end - start; val builder = new StringBuilder(); for (int c = 0; c < len; c++) { builder.append((char) dis.readByte()); } list.add(builder.toString()); } return Nd4j.create(list, shapeOf); } catch (IOException e) { throw new RuntimeException(e); } } default: throw new UnsupportedOperationException("Unknown datatype: [" + _dtype + "]"); } } /** * This method returns maximal allowed number of threads for Nd4j. * If value wasn't set in advance, max(1, availableProcessor) will be returned * @return */ public static int numThreads() { val v = numThreads.get(); if (v <= 0) return Math.max(1, Runtime.getRuntime().availableProcessors() / 2); else return v; } /** * This method sets maximal allowed number of threads for Nd4j * @param numthreads */ public static void setNumThreads(int numthreads) { numThreads.set(numthreads); } public static DataType defaultFloatingPointType() { return defaultFloatingPointDataType.get(); } public static boolean isPrecisionBoostAllowed() { return false; } public static INDArray scalar(@NonNull String string) { return create(Collections.singletonList(string), new long[0]); } public static INDArray create(@NonNull String... strings) { return create(Arrays.asList(strings), new long[]{strings.length}); } public static INDArray create(@NonNull Collection<String> strings, long... shape) { return create(strings, shape, Nd4j.order()); } public static INDArray create(@NonNull Collection<String> strings, long[] shape, char order) { return INSTANCE.create(strings, shape, order); } /////////////////// /** * This method creates INDArray from provided jvm array * @param array * @return 1D INDArray with DOUBLE data type */ public static INDArray createFromArray(double... array) { Preconditions.checkNotNull(array, "Cannot create INDArray from null Java array"); if(array.length == 0) return Nd4j.empty(DataType.DOUBLE); long[] shape = new long[]{array.length}; return create(array, shape, ArrayUtil.calcStrides(shape), 'c', DataType.DOUBLE); } /** * This method creates INDArray from provided jvm array * @param array * @return 1D INDArray with FLOAT data type */ public static INDArray createFromArray(float... array) { Preconditions.checkNotNull(array, "Cannot create INDArray from null Java array"); if(array.length == 0) return Nd4j.empty(DataType.FLOAT); long[] shape = new long[]{array.length}; return create(array, shape, ArrayUtil.calcStrides(shape), 'c', DataType.FLOAT); } /** * This method creates INDArray from provided jvm array * @param array * @return 1D INDArray with INT32 data type */ public static INDArray createFromArray(int... array) { Preconditions.checkNotNull(array, "Cannot create INDArray from null Java array"); if(array.length == 0) return Nd4j.empty(DataType.INT); long[] shape = new long[]{array.length}; return create(array, shape, ArrayUtil.calcStrides(shape), 'c', DataType.INT); } /** * This method creates INDArray from provided jvm array * @param array * @return 1D INDArray with INT16 data type */ public static INDArray createFromArray(short... array) { Preconditions.checkNotNull(array, "Cannot create INDArray from null Java array"); if(array.length == 0) return Nd4j.empty(DataType.SHORT); long[] shape = new long[]{array.length}; return create(array, shape, ArrayUtil.calcStrides(shape), 'c', DataType.SHORT); } /** * This method creates INDArray from provided jvm array * @param array * @return 1D INDArray with INT8 data type */ public static INDArray createFromArray(byte... array) { Preconditions.checkNotNull(array, "Cannot create INDArray from null Java array"); if(array.length == 0) return Nd4j.empty(DataType.BYTE); long[] shape = new long[]{array.length}; return create(array, shape, ArrayUtil.calcStrides(shape), 'c', DataType.BYTE); } /** * This method creates INDArray from provided jvm array * @param array * @return 1D INDArray with INT64 data type */ public static INDArray createFromArray(long... array) { Preconditions.checkNotNull(array, "Cannot create INDArray from null Java array"); if(array.length == 0) return Nd4j.empty(DataType.LONG); long[] shape = new long[]{array.length}; return create(array, shape, ArrayUtil.calcStrides(shape), 'c', DataType.LONG); } /** * This method creates INDArray from provided jvm array * @param array * @return 1D INDArray with BOOL data type */ public static INDArray createFromArray(boolean... array) { Preconditions.checkNotNull(array, "Cannot create INDArray from null Java array"); if(array.length == 0) return Nd4j.empty(DataType.BOOL); long[] shape = new long[]{array.length}; return create(array, shape, ArrayUtil.calcStrides(shape), 'c', DataType.BOOL); } /////////////////// /** * This method creates INDArray from provided jvm array * @param array * @return 2D INDArray with DOUBLE data type */ public static INDArray createFromArray(double[][] array) { Preconditions.checkNotNull(array, "Cannot create INDArray from null Java array"); ArrayUtil.assertNotRagged(array); if(array.length == 0 || array[0].length == 0) return Nd4j.empty(DataType.DOUBLE); long[] shape = new long[]{array.length, array[0].length}; return create(ArrayUtil.flatten(array), shape, ArrayUtil.calcStrides(shape), 'c', DataType.DOUBLE); } /** * This method creates INDArray from provided jvm array * @param array * @return 2D INDArray with FLOAT data type */ public static INDArray createFromArray(float[][] array) { Preconditions.checkNotNull(array, "Cannot create INDArray from null Java array"); ArrayUtil.assertNotRagged(array); if(array.length == 0 || array[0].length == 0) return Nd4j.empty(DataType.FLOAT); long[] shape = new long[]{array.length, array[0].length}; return create(ArrayUtil.flatten(array), shape, ArrayUtil.calcStrides(shape), 'c', DataType.FLOAT); } /** * This method creates INDArray from provided jvm array * @param array * @return 2D INDArray with INT64 data type */ public static INDArray createFromArray(long[][] array) { Preconditions.checkNotNull(array, "Cannot create INDArray from null Java array"); ArrayUtil.assertNotRagged(array); if(array.length == 0 || array[0].length == 0) return Nd4j.empty(DataType.LONG); long[] shape = new long[]{array.length, array[0].length}; return create(ArrayUtil.flatten(array), shape, ArrayUtil.calcStrides(shape), 'c', DataType.LONG); } /** * This method creates INDArray from provided jvm array * @param array * @return 2D INDArray with INT32 data type */ public static INDArray createFromArray(int[][] array) { Preconditions.checkNotNull(array, "Cannot create INDArray from null Java array"); ArrayUtil.assertNotRagged(array); if(array.length == 0 || array[0].length == 0) return Nd4j.empty(DataType.INT); long[] shape = new long[]{array.length, array[0].length}; return create(ArrayUtil.flatten(array), shape, ArrayUtil.calcStrides(shape), 'c', DataType.INT); } /** * This method creates INDArray from provided jvm array * @param array * @return 2D INDArray with INT16 data type */ public static INDArray createFromArray(short[][] array) { Preconditions.checkNotNull(array, "Cannot create INDArray from null Java array"); ArrayUtil.assertNotRagged(array); if(array.length == 0 || array[0].length == 0) return Nd4j.empty(DataType.SHORT); long[] shape = new long[]{array.length, array[0].length}; return create(ArrayUtil.flatten(array), shape, ArrayUtil.calcStrides(shape), 'c', DataType.SHORT); } /** * This method creates INDArray from provided jvm array * @param array * @return 2D INDArray with INT8 data type */ public static INDArray createFromArray(byte[][] array) { Preconditions.checkNotNull(array, "Cannot create INDArray from null Java array"); ArrayUtil.assertNotRagged(array); if(array.length == 0 || array[0].length == 0) return Nd4j.empty(DataType.BYTE); long[] shape = new long[]{array.length, array[0].length}; return create(ArrayUtil.flatten(array), shape, ArrayUtil.calcStrides(shape), 'c', DataType.BYTE); } /** * This method creates INDArray from provided jvm array * @param array * @return 2D INDArray with BOOL data type */ public static INDArray createFromArray(boolean[][] array) { Preconditions.checkNotNull(array, "Cannot create INDArray from null Java array"); ArrayUtil.assertNotRagged(array); if(array.length == 0 || array[0].length == 0) return Nd4j.empty(DataType.BOOL); long[] shape = new long[]{array.length, array[0].length}; return create(ArrayUtil.flatten(array), shape, ArrayUtil.calcStrides(shape), 'c', DataType.BOOL); } /////////////////// /** * This method creates INDArray from provided jvm array * @param array * @return 3D INDArray with DOUBLE data type */ public static INDArray createFromArray(double[][][] array) { Preconditions.checkNotNull(array, "Cannot create INDArray from null Java array"); ArrayUtil.assertNotRagged(array); if(array.length == 0 || array[0].length == 0 || array[0][0].length == 0) return Nd4j.empty(DataType.DOUBLE); long[] shape = new long[]{array.length, array[0].length, array[0][0].length}; return create(ArrayUtil.flatten(array), shape, ArrayUtil.calcStrides(shape), 'c', DataType.DOUBLE); } /** * This method creates INDArray from provided jvm array * @param array * @return 3D INDArray with FLOAT data type */ public static INDArray createFromArray(float[][][] array) { Preconditions.checkNotNull(array, "Cannot create INDArray from null Java array"); ArrayUtil.assertNotRagged(array); if(array.length == 0 || array[0].length == 0 || array[0][0].length == 0) return Nd4j.empty(DataType.FLOAT); long[] shape = new long[]{array.length, array[0].length, array[0][0].length}; return create(ArrayUtil.flatten(array), shape, ArrayUtil.calcStrides(shape), 'c', DataType.FLOAT); } /** * This method creates INDArray from provided jvm array * @param array * @return 3D INDArray with INT64 data type */ public static INDArray createFromArray(long[][][] array) { Preconditions.checkNotNull(array, "Cannot create INDArray from null Java array"); ArrayUtil.assertNotRagged(array); if(array.length == 0 || array[0].length == 0 || array[0][0].length == 0) return Nd4j.empty(DataType.LONG); long[] shape = new long[]{array.length, array[0].length, array[0][0].length}; return create(ArrayUtil.flatten(array), shape, ArrayUtil.calcStrides(shape), 'c', DataType.LONG); } /** * This method creates INDArray from provided jvm array * @param array * @return 3D INDArray with INT32 data type */ public static INDArray createFromArray(int[][][] array) { Preconditions.checkNotNull(array, "Cannot create INDArray from null Java array"); ArrayUtil.assertNotRagged(array); if(array.length == 0 || array[0].length == 0 || array[0][0].length == 0) return Nd4j.empty(DataType.INT); long[] shape = new long[]{array.length, array[0].length, array[0][0].length}; return create(ArrayUtil.flatten(array), shape, ArrayUtil.calcStrides(shape), 'c', DataType.INT); } /** * This method creates INDArray from provided jvm array * @param array * @return 3D INDArray with INT16 data type */ public static INDArray createFromArray(short[][][] array) { Preconditions.checkNotNull(array, "Cannot create INDArray from null Java array"); ArrayUtil.assertNotRagged(array); if(array.length == 0 || array[0].length == 0 || array[0][0].length == 0) return Nd4j.empty(DataType.SHORT); long[] shape = new long[]{array.length, array[0].length, array[0][0].length}; return create(ArrayUtil.flatten(array), shape, ArrayUtil.calcStrides(shape), 'c', DataType.SHORT); } /** * This method creates INDArray from provided jvm array * @param array * @return 3D INDArray with INT8 data type */ public static INDArray createFromArray(byte[][][] array) { Preconditions.checkNotNull(array, "Cannot create INDArray from null Java array"); ArrayUtil.assertNotRagged(array); if(array.length == 0 || array[0].length == 0 || array[0][0].length == 0) return Nd4j.empty(DataType.BYTE); long[] shape = new long[]{array.length, array[0].length, array[0][0].length}; return create(ArrayUtil.flatten(array), shape, ArrayUtil.calcStrides(shape), 'c', DataType.BYTE); } /** * This method creates INDArray from provided jvm array * @param array * @return 3D INDArray with BOOL data type */ public static INDArray createFromArray(boolean[][][] array) { Preconditions.checkNotNull(array, "Cannot create INDArray from null Java array"); ArrayUtil.assertNotRagged(array); if(array.length == 0 || array[0].length == 0 || array[0][0].length == 0) return Nd4j.empty(DataType.BOOL); long[] shape = new long[]{array.length, array[0].length, array[0][0].length}; return create(ArrayUtil.flatten(array), shape, ArrayUtil.calcStrides(shape), 'c', DataType.BOOL); } /////////////////// /** * This method creates INDArray from provided jvm array * @param array * @return 4D INDArray with DOUBLE data type */ public static INDArray createFromArray(double[][][][] array) { Preconditions.checkNotNull(array, "Cannot create INDArray from null Java array"); ArrayUtil.assertNotRagged(array); if(array.length == 0 || array[0].length == 0 || array[0][0].length == 0 || array[0][0][0].length == 0) return Nd4j.empty(DataType.DOUBLE); long[] shape = new long[]{array.length, array[0].length, array[0][0].length, array[0][0][0].length}; return create(ArrayUtil.flatten(array), shape, ArrayUtil.calcStrides(shape), 'c', DataType.DOUBLE); } /** * This method creates INDArray from provided jvm array * @param array * @return 4D INDArray with FLOAT data type */ public static INDArray createFromArray(float[][][][] array) { Preconditions.checkNotNull(array, "Cannot create INDArray from null Java array"); ArrayUtil.assertNotRagged(array); if(array.length == 0 || array[0].length == 0 || array[0][0].length == 0 || array[0][0][0].length == 0) return Nd4j.empty(DataType.FLOAT); long[] shape = new long[]{array.length, array[0].length, array[0][0].length, array[0][0][0].length}; return create(ArrayUtil.flatten(array), shape, ArrayUtil.calcStrides(shape), 'c', DataType.FLOAT); } /** * This method creates INDArray from provided jvm array * @param array * @return 4D INDArray with INT64 data type */ public static INDArray createFromArray(long[][][][] array) { Preconditions.checkNotNull(array, "Cannot create INDArray from null Java array"); ArrayUtil.assertNotRagged(array); if(array.length == 0 || array[0].length == 0 || array[0][0].length == 0 || array[0][0][0].length == 0) return Nd4j.empty(DataType.LONG); long[] shape = new long[]{array.length, array[0].length, array[0][0].length, array[0][0][0].length}; return create(ArrayUtil.flatten(array), shape, ArrayUtil.calcStrides(shape), 'c', DataType.LONG); } /** * This method creates INDArray from provided jvm array * @param array * @return 4D INDArray with INT32 data type */ public static INDArray createFromArray(int[][][][] array) { Preconditions.checkNotNull(array, "Cannot create INDArray from null Java array"); ArrayUtil.assertNotRagged(array); if(array.length == 0 || array[0].length == 0 || array[0][0].length == 0 || array[0][0][0].length == 0) return Nd4j.empty(DataType.INT); long[] shape = new long[]{array.length, array[0].length, array[0][0].length, array[0][0][0].length}; return create(ArrayUtil.flatten(array), shape, ArrayUtil.calcStrides(shape), 'c', DataType.INT); } /** * This method creates INDArray from provided jvm array * @param array * @return 4D INDArray with INT16 data type */ public static INDArray createFromArray(short[][][][] array) { Preconditions.checkNotNull(array, "Cannot create INDArray from null Java array"); ArrayUtil.assertNotRagged(array); if(array.length == 0 || array[0].length == 0 || array[0][0].length == 0 || array[0][0][0].length == 0) return Nd4j.empty(DataType.SHORT); long[] shape = new long[]{array.length, array[0].length, array[0][0].length, array[0][0][0].length}; return create(ArrayUtil.flatten(array), shape, ArrayUtil.calcStrides(shape), 'c', DataType.SHORT); } /** * This method creates INDArray from provided jvm array * @param array * @return 4D INDArray with INT8 data type */ public static INDArray createFromArray(byte[][][][] array) { Preconditions.checkNotNull(array, "Cannot create INDArray from null Java array"); ArrayUtil.assertNotRagged(array); if(array.length == 0 || array[0].length == 0 || array[0][0].length == 0 || array[0][0][0].length == 0) return Nd4j.empty(DataType.BYTE); long[] shape = new long[]{array.length, array[0].length, array[0][0].length, array[0][0][0].length}; return create(ArrayUtil.flatten(array), shape, ArrayUtil.calcStrides(shape), 'c', DataType.BYTE); } /** * This method creates INDArray from provided jvm array * @param array * @return 4D INDArray with BOOL data type */ public static INDArray createFromArray(boolean[][][][] array) { Preconditions.checkNotNull(array, "Cannot create INDArray from null Java array"); ArrayUtil.assertNotRagged(array); if(array.length == 0 || array[0].length == 0 || array[0][0].length == 0 || array[0][0][0].length == 0) return Nd4j.empty(DataType.BOOL); long[] shape = new long[]{array.length, array[0].length, array[0][0].length, array[0][0][0].length}; return create(ArrayUtil.flatten(array), shape, ArrayUtil.calcStrides(shape), 'c', DataType.BOOL); } public static synchronized DeallocatorService getDeallocatorService() { if (deallocatorService == null) deallocatorService = new DeallocatorService(); return deallocatorService; } /////////////////// /** * This method creates INDArray from provided jvm array * @param array * @return 1D INDArray with DOUBLE data type */ public static INDArray createFromArray(Double[] array) { return createFromArray(ArrayUtil.toPrimitives(array)); } /** * This method creates INDArray from provided jvm array * @param array * @return 1D INDArray with FLOAT data type */ public static INDArray createFromArray(Float[] array) { return createFromArray(ArrayUtil.toPrimitives(array)); } /** * This method creates INDArray from provided jvm array * @param array * @return 1D INDArray with INT32 data type */ public static INDArray createFromArray(Integer[] array) { return createFromArray(ArrayUtil.toPrimitives(array)); } /** * This method creates INDArray from provided jvm array * @param array * @return 1D INDArray with INT16 data type */ public static INDArray createFromArray(Short[] array) { return createFromArray(ArrayUtil.toPrimitives(array)); } /** * This method creates INDArray from provided jvm array * @param array * @return 1D INDArray with INT8 data type */ public static INDArray createFromArray(Byte[] array) { return createFromArray(ArrayUtil.toPrimitives(array)); } /** * This method creates INDArray from provided jvm array * @param array * @return 1D INDArray with INT64 data type */ public static INDArray createFromArray(Long[] array) { return createFromArray(ArrayUtil.toPrimitives(array)); } /** * This method creates INDArray from provided jvm array * @param array * @return 1D INDArray with BOOL data type */ public static INDArray createFromArray(Boolean[] array) { return createFromArray(ArrayUtil.toPrimitives(array)); } /////////////////// /** * This method creates INDArray from provided jvm array * @param array * @return 2D INDArray with DOUBLE data type */ public static INDArray createFromArray(Double[][] array) { return createFromArray(ArrayUtil.toPrimitives(array)); } /** * This method creates INDArray from provided jvm array * @param array * @return 2D INDArray with FLOAT data type */ public static INDArray createFromArray(Float[][] array) { return createFromArray(ArrayUtil.toPrimitives(array)); } /** * This method creates INDArray from provided jvm array * @param array * @return 2D INDArray with INT32 data type */ public static INDArray createFromArray(Integer[][] array) { return createFromArray(ArrayUtil.toPrimitives(array)); } /** * This method creates INDArray from provided jvm array * @param array * @return 2D INDArray with INT16 data type */ public static INDArray createFromArray(Short[][] array) { return createFromArray(ArrayUtil.toPrimitives(array)); } /** * This method creates INDArray from provided jvm array * @param array * @return 2D INDArray with INT8 data type */ public static INDArray createFromArray(Byte[][] array) { return createFromArray(ArrayUtil.toPrimitives(array)); } /** * This method creates INDArray from provided jvm array * @param array * @return 2D INDArray with INT64 data type */ public static INDArray createFromArray(Long[][] array) { return createFromArray(ArrayUtil.toPrimitives(array)); } /** * This method creates INDArray from provided jvm array * @param array * @return 2D INDArray with BOOL data type */ public static INDArray createFromArray(Boolean[][] array) { return createFromArray(ArrayUtil.toPrimitives(array)); } /////////////////// /** * This method creates INDArray from provided jvm array * @param array * @return 3D INDArray with DOUBLE data type */ public static INDArray createFromArray(Double[][][] array) { return createFromArray(ArrayUtil.toPrimitives(array)); } /** * This method creates INDArray from provided jvm array * @param array * @return 3D INDArray with FLOAT data type */ public static INDArray createFromArray(Float[][][] array) { return createFromArray(ArrayUtil.toPrimitives(array)); } /** * This method creates INDArray from provided jvm array * @param array * @return 3D INDArray with INT32 data type */ public static INDArray createFromArray(Integer[][][] array) { return createFromArray(ArrayUtil.toPrimitives(array)); } /** * This method creates INDArray from provided jvm array * @param array * @return 3D INDArray with INT16 data type */ public static INDArray createFromArray(Short[][][] array) { return createFromArray(ArrayUtil.toPrimitives(array)); } /** * This method creates INDArray from provided jvm array * @param array * @return 3D INDArray with INT8 data type */ public static INDArray createFromArray(Byte[][][] array) { return createFromArray(ArrayUtil.toPrimitives(array)); } /** * This method creates INDArray from provided jvm array * @param array * @return 3D INDArray with INT64 data type */ public static INDArray createFromArray(Long[][][] array) { return createFromArray(ArrayUtil.toPrimitives(array)); } /** * This method creates INDArray from provided jvm array * @param array * @return 3D INDArray with BOOL data type */ public static INDArray createFromArray(Boolean[][][] array) { return createFromArray(ArrayUtil.toPrimitives(array)); } /////////////////// /** * This method creates INDArray from provided jvm array * @param array * @return 4D INDArray with DOUBLE data type */ public static INDArray createFromArray(Double[][][][] array) { return createFromArray(ArrayUtil.toPrimitives(array)); } /** * This method creates INDArray from provided jvm array * @param array * @return 4D INDArray with FLOAT data type */ public static INDArray createFromArray(Float[][][][] array) { return createFromArray(ArrayUtil.toPrimitives(array)); } /** * This method creates INDArray from provided jvm array * @param array * @return 4D INDArray with INT32 data type */ public static INDArray createFromArray(Integer[][][][] array) { return createFromArray(ArrayUtil.toPrimitives(array)); } /** * This method creates INDArray from provided jvm array * @param array * @return 4D INDArray with INT16 data type */ public static INDArray createFromArray(Short[][][][] array) { return createFromArray(ArrayUtil.toPrimitives(array)); } /** * This method creates INDArray from provided jvm array * @param array * @return 4D INDArray with INT8 data type */ public static INDArray createFromArray(Byte[][][][] array) { return createFromArray(ArrayUtil.toPrimitives(array)); } /** * This method creates INDArray from provided jvm array * @param array * @return 4D INDArray with INT64 data type */ public static INDArray createFromArray(Long[][][][] array) { return createFromArray(ArrayUtil.toPrimitives(array)); } /** * This method creates INDArray from provided jvm array * @param array * @return 4D INDArray with BOOL data type */ public static INDArray createFromArray(Boolean[][][][] array) { return createFromArray(ArrayUtil.toPrimitives(array)); } public static boolean isExperimentalMode() { return getExecutioner().isExperimentalMode(); } /** * Execute the operation and return the result * * @param op the operation to execute */ public static INDArray exec(Op op){ return getExecutioner().exec(op); } /** * Execute the operation and return the result * * @param op the operation to execute */ public static INDArray[] exec(CustomOp op){ return getExecutioner().exec(op); } /** * Execute the operation and return the result * * @param op the operation to execute */ public static INDArray[] exec(CustomOp op, OpContext context){ return getExecutioner().exec(op, context); } /** * This method applies ScatterUpdate op * * @param op * @param array * @param indices * @param updates * @param axis */ @Deprecated public static void scatterUpdate(ScatterUpdate.UpdateOp op, @NonNull INDArray array, @NonNull INDArray indices, @NonNull INDArray updates, int... axis) { Preconditions.checkArgument(indices.dataType() == DataType.INT, "Indices should have INT data type"); Preconditions.checkArgument(array.dataType() == updates.dataType(), "Array and updates should have the same data type"); getExecutioner().scatterUpdate(op, array, indices, updates, axis); } }
package com.scwang.smartrefresh.header; import android.support.annotation.RequiresApi; import android.content.Context; import android.graphics.Canvas; import android.graphics.Point; import android.graphics.RectF; import android.os.Build; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.util.SparseArray; import com.scwang.smartrefresh.header.fungame.FunGameView; import com.scwang.smartrefresh.layout.util.DensityUtil; import java.util.LinkedList; import java.util.Queue; import java.util.Random; /** * Created by Hitomis on 2016/3/09. * email:196425254@qq.com * from https://github.com/Hitomis/FunGameRefresh */ public class FunGameBattleCityHeader extends FunGameView { /** * 轨道数量 */ private static int TANK_ROW_NUM = 3; /** * 炮管尺寸所在tank尺寸的比率 */ private static final float TANK_BARREL_RATIO = 1/3.f; /** * 默认子弹之间空隙间距 */ private static final int DEFAULT_BULLET_NUM_SPACING = 360; /** * 默认敌方坦克之间间距 */ private static final int DEFAULT_ENEMY_TANK_NUM_SPACING = 60; /** * 表示运行漏掉的敌方坦克总数量 和 升级后消灭坦克总数量的增量 */ private static final int DEFAULT_TANK_MAGIC_TOTAL_NUM = 8; /** * 所有轨道上敌方坦克矩阵集合 */ private SparseArray<Queue<RectF>> eTankSparseArray; /** * 屏幕上所有子弹坐标点集合 */ private Queue<Point> mBulletList; /** * 击中敌方坦克的子弹坐标点 */ private Point usedBullet; /** * 用于随机定位一个轨道下标值 */ private Random random; /** * 子弹半径 */ private float bulletRadius; /** * 敌方坦克间距、子弹间距 */ private int enemyTankSpace, bulletSpace; /** * 炮筒尺寸 */ private int barrelSize; /** * 敌方坦克速度、子弹速度 */ private int enemySpeed = 1, bulletSpeed = 4; /** * 当前前一辆敌方坦克和后一辆已经存在的间距值 * 用于确定是否要派出新的一辆敌方坦克 */ private int offsetETankX; /** * 当前前一颗子弹和后一颗子弹的间距值 * 用于确定是否要发射新的一颗子弹 */ private int offsetMBulletX; /** * 当前漏掉的坦克数量 */ private int overstepNum; /** * 当前难度等级需要消灭坦克数量 */ private int levelNum; /** * 当前难度等级内消灭的敌方坦克数量 */ private int wipeOutNum; /** * 表示第一次标示值,用于添加第一辆敌方坦克逻辑 */ private boolean once = true; public FunGameBattleCityHeader(Context context) { super(context); } public FunGameBattleCityHeader(Context context, AttributeSet attrs) { super(context, attrs); } public FunGameBattleCityHeader(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @RequiresApi(Build.VERSION_CODES.LOLLIPOP) public FunGameBattleCityHeader(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); } @Override protected void initConcreteView() { random = new Random(); controllerSize = mHeaderHeight/TANK_ROW_NUM; barrelSize = (int) Math.floor(controllerSize * TANK_BARREL_RATIO + .5f); bulletRadius = (barrelSize - 2 * DIVIDING_LINE_SIZE) * .5f; resetConfigParams(); } @Override protected void drawGame(Canvas canvas, int width, int height) { drawSelfTank(canvas,width); if (status == STATUS_GAME_PLAY || status == STATUS_GAME_FINISHED || status == STATUS_GAME_FAIL) { drawEnemyTank(canvas,width); makeBulletPath(canvas,width); } if (isInEditMode()) { drawTank(canvas, new RectF(controllerSize, 0, controllerSize * 2, controllerSize)); drawTank(canvas, new RectF(0, controllerSize, controllerSize, controllerSize*2)); drawTank(canvas, new RectF(controllerSize * 3, controllerSize * 2, controllerSize * 4, controllerSize*3)); } } @Override protected void resetConfigParams() { status = FunGameView.STATUS_GAME_PREPAR; controllerPosition = DIVIDING_LINE_SIZE; enemySpeed = DensityUtil.dp2px(1); bulletSpeed = DensityUtil.dp2px(4); levelNum = DEFAULT_TANK_MAGIC_TOTAL_NUM; wipeOutNum = 0; once = true; enemyTankSpace = controllerSize + barrelSize + DEFAULT_ENEMY_TANK_NUM_SPACING; bulletSpace = DEFAULT_BULLET_NUM_SPACING; eTankSparseArray = new SparseArray<>(); for (int i = 0; i < TANK_ROW_NUM; i++) { Queue<RectF> rectFQueue = new LinkedList<>(); eTankSparseArray.put(i, rectFQueue); } mBulletList = new LinkedList<>(); } /** * 由index轨道下标从左边起始位置生成一个用于绘制敌方坦克的Rect * @param index 轨道下标 * @return 敌方坦克矩阵 */ private RectF generateEnemyTank(int index) { float left = - (controllerSize + barrelSize); float top = index * (controllerSize) + DIVIDING_LINE_SIZE; return new RectF(left, top, left + barrelSize * 2.5f, top + controllerSize); } /** * 绘制子弹路径 * @param canvas 默认画布 */ private void makeBulletPath(Canvas canvas, int width) { mPaint.setColor(mModelColor); offsetMBulletX += bulletSpeed; if (offsetMBulletX / bulletSpace == 1) { offsetMBulletX = 0; } if (offsetMBulletX == 0) { Point bulletPoint = new Point(); bulletPoint.x = width - controllerSize - barrelSize; bulletPoint.y = (int) (controllerPosition + controllerSize * .5f); mBulletList.offer(bulletPoint); } boolean isOversetp = false; for (Point point : mBulletList) { if (checkWipeOutETank(point)) { usedBullet = point; continue; } if (point.x + bulletRadius <= 0) { isOversetp = true; } drawBullet(canvas, point); } if (isOversetp) { mBulletList.poll(); } mBulletList.remove(usedBullet); usedBullet = null; } /** * 由Y坐标获取该坐标所在轨道的下标 * @param y 坐标Y值 * @return 轨道下标 */ private int getTrackIndex(int y) { int index = y / (mHeaderHeight / TANK_ROW_NUM); index = index >= TANK_ROW_NUM ? TANK_ROW_NUM - 1 : index; index = index < 0 ? 0 : index; return index; } /** * 判断是否消灭敌方坦克 * @param point 单签子弹坐标点 * @return 消灭:true, 反之:false */ private boolean checkWipeOutETank(Point point) { boolean beHit = false; int trackIndex = getTrackIndex(point.y); RectF rectF = eTankSparseArray.get(trackIndex).peek(); if (rectF != null && rectF.contains(point.x, point.y)) { // 击中 if (++wipeOutNum == levelNum) { upLevel(); } eTankSparseArray.get(trackIndex).poll(); beHit = true; } return beHit; } /** * 难度升级 */ private void upLevel() { levelNum += DEFAULT_TANK_MAGIC_TOTAL_NUM; enemySpeed += DensityUtil.dp2px(1); bulletSpeed += DensityUtil.dp2px(1); wipeOutNum = 0; if (enemyTankSpace > 12) enemyTankSpace -= 12; if (bulletSpace > 30) bulletSpace -= 30; } /** * 绘制子弹 * @param canvas 默认画布 * @param point 子弹圆心坐标点 */ private void drawBullet(Canvas canvas, Point point) { point.x -= bulletSpeed; canvas.drawCircle(point.x, point.y, bulletRadius, mPaint); } /** * 判断我方坦克是否与敌方坦克相撞 * @param index 轨道下标 * @param selfX 我方坦克所在坐标X值 * @param selfY 我方坦克矩阵的top 或者 bottom 值 * @return true:相撞,反之:false */ private boolean checkTankCrash(int index, float selfX, float selfY) { boolean isCrash = false; RectF rectF = eTankSparseArray.get(index).peek(); if (rectF != null && rectF.contains(selfX, selfY)) { isCrash = true; } return isCrash; } /** * 绘制我方坦克 * @param canvas 默认画布 */ private void drawSelfTank(Canvas canvas, int width) { mPaint.setColor(rModelColor); boolean isAboveCrash = checkTankCrash(getTrackIndex((int) controllerPosition), width - controllerSize, controllerPosition); boolean isBelowCrash = checkTankCrash(getTrackIndex((int) (controllerPosition + controllerSize)), width - controllerSize, controllerPosition + controllerSize); if (isAboveCrash || isBelowCrash) { status = STATUS_GAME_OVER; } canvas.drawRect(width - controllerSize, controllerPosition + DIVIDING_LINE_SIZE, width, controllerPosition + controllerSize + DIVIDING_LINE_SIZE, mPaint); canvas.drawRect(width - controllerSize - barrelSize, controllerPosition + (controllerSize - barrelSize) * .5f, width - controllerSize, controllerPosition + (controllerSize - barrelSize) * .5f + barrelSize, mPaint); } /** * 绘制三条轨道上的敌方坦克 * @param canvas 默认画布 */ private void drawEnemyTank(Canvas canvas, int width) { mPaint.setColor(lModelColor); offsetETankX += enemySpeed; if (offsetETankX / enemyTankSpace == 1 || once) { offsetETankX = 0; once = false; } boolean isOverstep = false; int option = apperanceOption(); for (int i = 0; i < TANK_ROW_NUM; i++) { Queue<RectF> rectFQueue = eTankSparseArray.get(i); if (offsetETankX == 0 && i == option) { rectFQueue.offer(generateEnemyTank(i)); } for (RectF rectF : rectFQueue) { if (rectF.left >= width) { isOverstep = true; if (++overstepNum >= DEFAULT_TANK_MAGIC_TOTAL_NUM) { status = STATUS_GAME_OVER; break; } continue; } drawTank(canvas, rectF); } if (status == STATUS_GAME_OVER) break; if (isOverstep) { rectFQueue.poll(); isOverstep = false; } } invalidate(); } /** * 绘制一辆敌方坦克 * @param canvas 默认画布 * @param rectF 坦克矩阵 */ private void drawTank(Canvas canvas, RectF rectF) { rectF.set(rectF.left + enemySpeed, rectF.top, rectF.right + enemySpeed, rectF.bottom); canvas.drawRect(rectF, mPaint); float barrelTop = rectF.top + (controllerSize - barrelSize) * .5f; canvas.drawRect(rectF.right, barrelTop, rectF.right + barrelSize, barrelTop + barrelSize, mPaint); } /** * 随机定位一个轨道下标值 * @return 轨道下标 */ private int apperanceOption() { return random.nextInt(TANK_ROW_NUM); } }
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.testFramework.fixtures.impl; import com.intellij.ide.IdeView; import com.intellij.ide.highlighter.ProjectFileType; import com.intellij.idea.IdeaTestApplication; import com.intellij.openapi.actionSystem.CommonDataKeys; import com.intellij.openapi.actionSystem.DataProvider; import com.intellij.openapi.actionSystem.LangDataKeys; import com.intellij.openapi.application.ReadAction; import com.intellij.openapi.command.WriteCommandAction; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.fileEditor.OpenFileDescriptor; import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx; import com.intellij.openapi.fileTypes.FileTypeManager; import com.intellij.openapi.fileTypes.impl.FileTypeManagerImpl; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ex.ProjectManagerEx; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VfsUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.vfs.encoding.EncodingManager; import com.intellij.openapi.vfs.impl.jar.JarFileSystemImpl; import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiManager; import com.intellij.psi.impl.source.tree.injected.InjectedLanguageManagerImpl; import com.intellij.testFramework.*; import com.intellij.testFramework.builders.ModuleFixtureBuilder; import com.intellij.testFramework.fixtures.HeavyIdeaTestFixture; import com.intellij.util.PathUtil; import com.intellij.util.lang.CompoundRuntimeException; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.junit.Assert; import java.io.IOException; import java.nio.file.Files; import java.nio.file.NoSuchFileException; import java.nio.file.Path; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; /** * Creates new project for each test. * @author mike */ @SuppressWarnings("TestOnlyProblems") final class HeavyIdeaTestFixtureImpl extends BaseFixture implements HeavyIdeaTestFixture { private Project myProject; private final Set<Path> myFilesToDelete = new HashSet<>(); private IdeaTestApplication myApplication; private final Set<ModuleFixtureBuilder> myModuleFixtureBuilders = new LinkedHashSet<>(); private EditorListenerTracker myEditorListenerTracker; private ThreadTracker myThreadTracker; private final String myName; private final boolean myIsDirectoryBasedProject; private SdkLeakTracker myOldSdks; HeavyIdeaTestFixtureImpl(@NotNull String name, boolean isDirectoryBasedProject) { myName = name; myIsDirectoryBasedProject = isDirectoryBasedProject; } void addModuleFixtureBuilder(ModuleFixtureBuilder builder) { myModuleFixtureBuilders.add(builder); } @Override public void setUp() throws Exception { super.setUp(); initApplication(); setUpProject(); EncodingManager.getInstance(); // adds listeners myEditorListenerTracker = new EditorListenerTracker(); myThreadTracker = new ThreadTracker(); InjectedLanguageManagerImpl.pushInjectors(getProject()); myOldSdks = new SdkLeakTracker(); } @Override public void tearDown() throws Exception { RunAll runAll = new RunAll(); if (myProject != null) { runAll = runAll .append(() -> LightPlatformTestCase.doTearDown(getProject(), myApplication)) .append(() -> { for (ModuleFixtureBuilder moduleFixtureBuilder : myModuleFixtureBuilders) { moduleFixtureBuilder.getFixture().tearDown(); } }) .append(() -> EdtTestUtil.runInEdtAndWait(() -> PlatformTestCase.closeAndDisposeProjectAndCheckThatNoOpenProjects(getProject()))) .append(() -> InjectedLanguageManagerImpl.checkInjectorsAreDisposed(getProject())) .append(() -> myProject = null); } JarFileSystemImpl.cleanupForNextTest(); for (Path fileToDelete : myFilesToDelete) { runAll = runAll.append(() -> { List<IOException> errors; try (Stream<Path> stream = Files.walk(fileToDelete)) { errors = stream .sorted(Comparator.reverseOrder()) .map(x -> { try { Files.delete(x); return null; } catch (IOException e) { return e; } }) .filter(Objects::nonNull) .collect(Collectors.toList()); } catch (NoSuchFileException ignore) { errors = Collections.emptyList(); } CompoundRuntimeException.throwIfNotEmpty(errors); }); } runAll .append(super::tearDown) .append(() -> { if (myEditorListenerTracker != null) { myEditorListenerTracker.checkListenersLeak(); } }) .append(() -> { if (myThreadTracker != null) { myThreadTracker.checkLeak(); } }) .append(LightPlatformTestCase::checkEditorsReleased) .append(() -> { if (myOldSdks != null) { myOldSdks.checkForJdkTableLeaks(); } }) .append(() -> PlatformTestCase.cleanupApplicationCaches(null)) // project is disposed by now, no point in passing it .run(); } private void setUpProject() { Path tempDirectory = TemporaryDirectory.generateTemporaryPath(myName); PlatformTestCase.synchronizeTempDirVfs(tempDirectory); myFilesToDelete.add(tempDirectory); myProject = PlatformTestCase.createProject(generateProjectPath(tempDirectory)); EdtTestUtil.runInEdtAndWait(() -> { ProjectManagerEx.getInstanceEx().openTestProject(myProject); for (ModuleFixtureBuilder moduleFixtureBuilder : myModuleFixtureBuilders) { moduleFixtureBuilder.getFixture().setUp(); } LightPlatformTestCase.clearUncommittedDocuments(myProject); ((FileTypeManagerImpl)FileTypeManager.getInstance()).drainReDetectQueue(); }); } @NotNull protected Path generateProjectPath(@NotNull Path tempDirectory) { String suffix = myIsDirectoryBasedProject ? "" : ProjectFileType.DOT_DEFAULT_EXTENSION; return tempDirectory.resolve(myName + suffix); } private void initApplication() { myApplication = IdeaTestApplication.getInstance(); myApplication.setDataProvider(new MyDataProvider()); } @Override public Project getProject() { Assert.assertNotNull("setUp() should be called first", myProject); return myProject; } @Override public Module getModule() { Module[] modules = ModuleManager.getInstance(getProject()).getModules(); return modules.length == 0 ? null : modules[0]; } private class MyDataProvider implements DataProvider { @Override @Nullable public Object getData(@NotNull @NonNls String dataId) { if (CommonDataKeys.PROJECT.is(dataId)) { return myProject; } else if (CommonDataKeys.EDITOR.is(dataId) || OpenFileDescriptor.NAVIGATE_IN_EDITOR.is(dataId)) { if (myProject == null) return null; return FileEditorManager.getInstance(myProject).getSelectedTextEditor(); } else { Editor editor = (Editor)getData(CommonDataKeys.EDITOR.getName()); if (editor != null) { FileEditorManagerEx manager = FileEditorManagerEx.getInstanceEx(myProject); return manager.getData(dataId, editor, editor.getCaretModel().getCurrentCaret()); } if (LangDataKeys.IDE_VIEW.is(dataId)) { VirtualFile[] contentRoots = ProjectRootManager.getInstance(myProject).getContentRoots(); if (contentRoots.length > 0) { final PsiDirectory psiDirectory = PsiManager.getInstance(myProject).findDirectory(contentRoots[0]); return new IdeView() { @NotNull @Override public PsiDirectory[] getDirectories() { return new PsiDirectory[] {psiDirectory}; } @Override public PsiDirectory getOrChooseDirectory() { return psiDirectory; } }; } } return null; } } } @Override public PsiFile addFileToProject(@NotNull @NonNls String rootPath, @NotNull @NonNls final String relativePath, @NotNull @NonNls final String fileText) throws IOException { final VirtualFile dir = VfsUtil.createDirectories(rootPath + "/" + PathUtil.getParentPath(relativePath)); final VirtualFile[] virtualFile = new VirtualFile[1]; WriteCommandAction.writeCommandAction(getProject()).run(() -> { virtualFile[0] = dir.createChildData(this, StringUtil.getShortName(relativePath, '/')); VfsUtil.saveText(virtualFile[0], fileText); PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); }); return ReadAction.compute(() -> PsiManager.getInstance(getProject()).findFile(virtualFile[0])); } }
package model.gameObjects; /** * basic entity, needs coordinates * * @author Tim * */ public abstract class Entity { /** * x coordinate on the field */ private int xPos; /** * y coordinate on the field */ private int yPos; /** * string to draw */ private char entityChar; /** * empty constructor */ public Entity() { } /** * set the position of the entity * * @param x * xpos * @param y * ypos */ public void setPosition(int x, int y) { if ((x >= 0) && (y >= 0)) { setxPos(x); setyPos(y); } else { System.err.println("setPostion(): invalid position"); } } /** * get the entityChar * * @return the entityChar */ public char getEntityChar() { return entityChar; } /** * get the x coordinate of the entity * * @return int x position */ public int getxPos() { return xPos; } /** * get the y coordinate of the entity * * @return int y position */ public int getyPos() { return yPos; } /** * set the entityChar * * @param entityChar * the entityChar to set */ public void setEntityChar(char entityChar) { this.entityChar = entityChar; } /** * set the x coordinate of the entity * * @param xPos * integer of x coordinate of the entity */ public void setxPos(int xPos) { this.xPos = xPos; } /** * set the y coordinate of the entity * * @param yPos * integer of y coordinate of the entity */ public void setyPos(int yPos) { this.yPos = yPos; } }
/** * 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.fs; import static org.junit.Assert.fail; import java.io.IOException; import org.junit.BeforeClass; import org.junit.Test; public class TestSymlinkHdfsFileContext extends TestSymlinkHdfs { private static FileContext fc; @BeforeClass public static void testSetup() throws Exception { fc = FileContext.getFileContext(cluster.getURI(0)); wrapper = new FileContextTestWrapper(fc, "/tmp/TestSymlinkHdfsFileContext"); } @Test(timeout=1000) /** Test access a symlink using AbstractFileSystem */ public void testAccessLinkFromAbstractFileSystem() throws IOException { Path file = new Path(testBaseDir1(), "file"); Path link = new Path(testBaseDir1(), "linkToFile"); createAndWriteFile(file); wrapper.createSymlink(file, link, false); try { AbstractFileSystem afs = fc.getDefaultFileSystem(); afs.open(link); fail("Opened a link using AFS"); } catch (UnresolvedLinkException x) { // Expected } } }
package ganyi.hadoop.replayer.simulator; import ganyi.hadoop.replayer.GlobalConfigure; import ganyi.hadoop.replayer.MetricsCollector; import ganyi.hadoop.replayer.message.Message; import ganyi.hadoop.replayer.message.MessageQueue; import ganyi.hadoop.replayer.rpc.RPCExecutor; import ganyi.hadoop.replayer.rpc.RpcInterpreter; import ganyi.hadoop.replayer.rpc.RpcRecorder; import ganyi.hadoop.replayer.rpc.RpcScript; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.yarn.exceptions.YarnException; import org.json.JSONObject; import java.io.IOException; import java.util.HashMap; import java.util.TimerTask; import java.util.concurrent.*; /** * Created by ganyi on 3/28/2017. */ public abstract class Simulator implements Runnable, SimulatorExecutor, RPCExecutor { public Log LOG = LogFactory.getLog(getClass()); protected String[] envs; protected String identifier; protected MessageQueue<Message> inboundQueue; /*RPCManager rpcMgr;*/ protected GlobalConfigure configure; protected RpcInterpreter interpreter; protected RpcRecorder recorder; protected RpcScript script; protected MetricsCollector metrics; MessageQueue<Message> outBoundQueue; protected boolean isConnected = false; private long jobID = -1; private long rand; boolean startHBCounter = false; /*protected HashMap<String, ScheduledFuture> timerMap; protected ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();*/ SimTimer simTimer; protected Simulator(String[] args) { this.setupEnvs(args); } protected Simulator(String[] args, GlobalConfigure configuration, MessageQueue<Message> inboundQueue, MessageQueue<Message> outBoundQueue) { this(args); this.configure = configuration; this.inboundQueue = inboundQueue; this.outBoundQueue = outBoundQueue; } public long getRand() { return rand; } public void setRand(long rand) { this.rand = rand; } public long getJobID() { return jobID; } public void setJobID(long jobID) { this.jobID = jobID; } /*public RPCManager getRpcMgr() { return rpcMgr; }*/ public GlobalConfigure getConfigure() { return configure; } public String getIdentifier() { return identifier; } public void setIdentifier(String identifier) { this.identifier = identifier; } public String getHostName() { return configure.getLocalInetAddress().getHostName(); } public String getIPaddr() { return configure.getLocalInetAddress().getHostAddress(); } /*public void showInfo(){ System.out.printf("Identifier: %s, localAddress: %s, port %d\n",identifier,localAddress,port); }*/ public MessageQueue<Message> getInboundQueue() { return inboundQueue; } public void scheduleTimerTask(long period, TimerTaskType type, String[] cmd) { Runnable task = ()-> periodicalJob(type,cmd); simTimer = new SimTimer(); simTimer.schedule(period,task); } public void scheduleAggresiveTimer(long initial, long maxInterval, TimerTaskType type, String[] cmd){ Runnable task = ()->periodicalJob(type,cmd); simTimer = new SimTimer(); simTimer.aggresiveSchedule(initial,maxInterval,task); } public void scheduleOnce(long period, TimerTaskType type, String[] cmd){ Runnable task = ()-> periodicalJob(type,cmd); SimTimer simTimer = new SimTimer(); simTimer.scheduleOnce(period,task); } /*public void scheduleTimerTask(long delay, TimerTaskType type, String[] cmd) { Runnable task = ()-> periodicalJob(type,cmd); ScheduledFuture<?> future = executorService.schedule(task,delay,TimeUnit.MILLISECONDS); timerMap.put(taskName+"|"+getIdentifier(),future); }*/ protected void stopTimers() { if(simTimer!=null&&simTimer.isRunning){ simTimer.cancel(); } } public void sendMessage(Message.MSG_TYPE type, String cmd, String src, String dest) { Message message = new Message(type, cmd, src, dest, jobID); outBoundQueue.put(message); } public void sendMessage(Message msg) { outBoundQueue.put(msg); } protected final void validateEmulator(String scriptFile) { if (!isConnected) { startRPCService(); SetupRpcManager(); loadScript(scriptFile); } } public void SetupRpcManager() { recorder = new RpcRecorder(); interpreter = new RpcInterpreter(this); script = new RpcScript(); metrics = new MetricsCollector(configure); } protected final void stopRPCService() { isConnected = false; stopSimulatorRPCConnection(); } public void setupEnvs(String[] args) { envs = args; } public abstract void init(); @Override public abstract void run(); public void testRPC(String[] cmds) { String[] param = interpreter.interpret(cmds, recorder); try { //System.out.println(param[3]); ActionStation(param[0], param[1], param[2], param[3]); } catch (IOException e) { e.printStackTrace(); } } public void playOnce(String pos) throws IOException { //special for datanode heartbeat String[] cmds = script.getNextByPos(pos); String[] param = interpreter.interpret(cmds, recorder); ActionStation(param[0], param[1], param[2], param[3]); } public void play(String range) throws IOException { if (range.equalsIgnoreCase("")) { script.setCursorRange("", ""); } else if (range.contains("@")) { //split String[] pos = range.split("@"); script.setCursorRange(pos[0], pos[1]); // LOG.info("setTerminate: "+script.getTerminatingPoint()+ // " Cursor pos: "+script.getPos(script.getCursor())); } long t1 = System.currentTimeMillis(); playbook(); long t2 = System.currentTimeMillis(); metrics.updateInterval(t1, t2); } public void respondWithFinish(String content) { //tell CC that simulator finish. sendMessage(Message.MSG_TYPE.finish_response, content, getIdentifier(), "CC.1"); } public void updateLatency(long t1, long t2, String pos, String cmd) { if(startHBCounter) { metrics.updateRpc(cmd, pos, t2 - t1); } } public void setStartHBCounter(boolean startHBCounter) { this.startHBCounter = startHBCounter; } public boolean isStartHBCounter() { return startHBCounter; } protected void doSleep(String timediff) { try { int sleepTime = Integer.valueOf(!timediff.equals("") ? timediff : "0"); String throttle = getConfigure().getSetting("throttle"); if (throttle != null && !throttle.equalsIgnoreCase("n")) { int i = Integer.valueOf(throttle); sleepTime = sleepTime > i ? i : sleepTime; } //sleepTime = sleepTime<1000?1000:sleepTime; Thread.sleep(sleepTime); //Thread.sleep(2000); } catch (InterruptedException e) { LOG.info("sleep is interrupted."); } } protected JSONObject toJSON(String jsonString) { JSONObject object = new JSONObject(); if (!jsonString.equals("")) { object = new JSONObject(jsonString); } return object; } public void metricsReport() { metrics.report(this); } public void loadScript(String file) { script.loadScript(file); } public void ActionStation(String pos, String rpc, String timediff, String jsonString) throws IOException { doSleep(timediff); try { ExecuteRPC(pos, rpc.split("\\.")[1], toJSON(jsonString)); } catch (YarnException e) { e.printStackTrace(); } } public enum TimerTaskType { None, DataNode_HeartBeat, APPMaster_RenewLease, NodeManager_HeartBeat, AppMaster_allocate, Container_job_finish, } }
/** * This code was generated by * \ / _ _ _| _ _ * | (_)\/(_)(_|\/| |(/_ v1.0.0 * / / */ package com.twilio.rest.authy.v1.service.entity.factor; import com.twilio.base.Creator; import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; import com.twilio.http.HttpMethod; import com.twilio.http.Request; import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; import org.joda.time.DateTime; /** * PLEASE NOTE that this class contains preview products that are subject to * change. Use them with caution. If you currently do not have developer preview * access, please contact help@twilio.com. */ public class ChallengeCreator extends Creator<Challenge> { private final String pathServiceSid; private final String pathIdentity; private final String pathFactorSid; private DateTime expirationDate; private String details; private String hiddenDetails; /** * Construct a new ChallengeCreator. * * @param pathServiceSid Service Sid. * @param pathIdentity Unique identity of the Entity * @param pathFactorSid Factor Sid. */ public ChallengeCreator(final String pathServiceSid, final String pathIdentity, final String pathFactorSid) { this.pathServiceSid = pathServiceSid; this.pathIdentity = pathIdentity; this.pathFactorSid = pathFactorSid; } /** * The future date in which this Challenge will expire, given in [ISO * 8601](https://en.wikipedia.org/wiki/ISO_8601) format.. * * @param expirationDate The future date in which this Challenge will expire * @return this */ public ChallengeCreator setExpirationDate(final DateTime expirationDate) { this.expirationDate = expirationDate; return this; } /** * Details provided to give context about the Challenge. Shown to the end user.. * * @param details Public details provided to contextualize the Challenge * @return this */ public ChallengeCreator setDetails(final String details) { this.details = details; return this; } /** * Details provided to give context about the Challenge. Not shown to the end * user.. * * @param hiddenDetails Hidden details provided to contextualize the Challenge * @return this */ public ChallengeCreator setHiddenDetails(final String hiddenDetails) { this.hiddenDetails = hiddenDetails; return this; } /** * Make the request to the Twilio API to perform the create. * * @param client TwilioRestClient with which to make the request * @return Created Challenge */ @Override @SuppressWarnings("checkstyle:linelength") public Challenge create(final TwilioRestClient client) { Request request = new Request( HttpMethod.POST, Domains.AUTHY.toString(), "/v1/Services/" + this.pathServiceSid + "/Entities/" + this.pathIdentity + "/Factors/" + this.pathFactorSid + "/Challenges", client.getRegion() ); addPostParams(request); Response response = client.request(request); if (response == null) { throw new ApiConnectionException("Challenge creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.apply(response.getStatusCode())) { RestException restException = RestException.fromJson(response.getStream(), client.getObjectMapper()); if (restException == null) { throw new ApiException("Server Error, no content"); } throw new ApiException( restException.getMessage(), restException.getCode(), restException.getMoreInfo(), restException.getStatus(), null ); } return Challenge.fromJson(response.getStream(), client.getObjectMapper()); } /** * Add the requested post parameters to the Request. * * @param request Request to add post params to */ private void addPostParams(final Request request) { if (expirationDate != null) { request.addPostParam("ExpirationDate", expirationDate.toString()); } if (details != null) { request.addPostParam("Details", details); } if (hiddenDetails != null) { request.addPostParam("HiddenDetails", hiddenDetails); } } }
package ru.systemoteh.web.students.dao.impl; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Repository; import org.springframework.web.client.RestTemplate; import ru.systemoteh.web.students.bean.SessionToken; import ru.systemoteh.web.students.dao.UserDao; import ru.systemoteh.web.students.domain.User; import javax.annotation.Resource; @Repository public class UserDaoImpl implements UserDao { @Value("${rest.host}") private String restHost; @Value("${rest.login}") private String restLogin; @Resource(name = "sessionToken") SessionToken sessionToken; @Override public User findByUsername(String username) { RestTemplate restTemplate = new RestTemplate(); HttpEntity<User> request = new HttpEntity<>(new User(username)); ResponseEntity<User> response = restTemplate .exchange(restHost + restLogin, HttpMethod.POST, request, User.class); User user = response.getBody(); sessionToken.setToken(user.getToken()); return user; } }
/* * 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.camel.spring.issues.packagescan; import org.apache.camel.builder.RouteBuilder; /** * */ public class MyCoolRoute extends RouteBuilder { @Override public void configure() throws Exception { from("direct:cool").routeId("cool").to("mock:cool"); } }
/* * 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.resourcemanager; import org.apache.flink.annotation.VisibleForTesting; import org.apache.flink.api.common.JobID; import org.apache.flink.api.common.time.Time; import org.apache.flink.api.java.tuple.Tuple2; import org.apache.flink.runtime.blob.TransientBlobKey; import org.apache.flink.runtime.clusterframework.ApplicationStatus; import org.apache.flink.runtime.clusterframework.messages.InfoMessage; import org.apache.flink.runtime.clusterframework.types.AllocationID; import org.apache.flink.runtime.clusterframework.types.ResourceID; import org.apache.flink.runtime.clusterframework.types.ResourceIDRetrievable; import org.apache.flink.runtime.clusterframework.types.ResourceProfile; import org.apache.flink.runtime.clusterframework.types.SlotID; import org.apache.flink.runtime.concurrent.FutureUtils; import org.apache.flink.runtime.entrypoint.ClusterInformation; import org.apache.flink.runtime.heartbeat.HeartbeatListener; import org.apache.flink.runtime.heartbeat.HeartbeatManager; import org.apache.flink.runtime.heartbeat.HeartbeatServices; import org.apache.flink.runtime.heartbeat.HeartbeatTarget; import org.apache.flink.runtime.highavailability.HighAvailabilityServices; import org.apache.flink.runtime.instance.HardwareDescription; import org.apache.flink.runtime.instance.InstanceID; import org.apache.flink.runtime.jobmaster.JobMaster; import org.apache.flink.runtime.jobmaster.JobMasterGateway; import org.apache.flink.runtime.jobmaster.JobMasterId; import org.apache.flink.runtime.jobmaster.JobMasterRegistrationSuccess; import org.apache.flink.runtime.leaderelection.LeaderContender; import org.apache.flink.runtime.leaderelection.LeaderElectionService; import org.apache.flink.runtime.messages.Acknowledge; import org.apache.flink.runtime.metrics.MetricRegistry; import org.apache.flink.runtime.metrics.dump.MetricQueryService; import org.apache.flink.runtime.registration.RegistrationResponse; import org.apache.flink.runtime.resourcemanager.exceptions.ResourceManagerException; import org.apache.flink.runtime.resourcemanager.exceptions.UnknownTaskExecutorException; import org.apache.flink.runtime.resourcemanager.registration.JobManagerRegistration; import org.apache.flink.runtime.resourcemanager.registration.WorkerRegistration; import org.apache.flink.runtime.resourcemanager.slotmanager.ResourceActions; import org.apache.flink.runtime.resourcemanager.slotmanager.SlotManager; import org.apache.flink.runtime.resourcemanager.slotmanager.SlotManagerException; import org.apache.flink.runtime.rest.messages.taskmanager.TaskManagerInfo; import org.apache.flink.runtime.rpc.FatalErrorHandler; import org.apache.flink.runtime.rpc.FencedRpcEndpoint; import org.apache.flink.runtime.rpc.RpcService; import org.apache.flink.runtime.taskexecutor.FileType; import org.apache.flink.runtime.taskexecutor.SlotReport; import org.apache.flink.runtime.taskexecutor.TaskExecutorGateway; import org.apache.flink.runtime.taskexecutor.TaskExecutorRegistrationSuccess; import org.apache.flink.util.ExceptionUtils; import org.apache.flink.util.FlinkException; import javax.annotation.Nullable; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeoutException; import static org.apache.flink.util.Preconditions.checkNotNull; /** * ResourceManager implementation. The resource manager is responsible for resource de-/allocation * and bookkeeping. * * <p>It offers the following methods as part of its rpc interface to interact with him remotely: * <ul> * <li>{@link #registerJobManager(JobMasterId, ResourceID, String, JobID, Time)} registers a {@link JobMaster} at the resource manager</li> * <li>{@link #requestSlot(JobMasterId, SlotRequest, Time)} requests a slot from the resource manager</li> * </ul> */ public abstract class ResourceManager<WorkerType extends ResourceIDRetrievable> extends FencedRpcEndpoint<ResourceManagerId> implements ResourceManagerGateway, LeaderContender { public static final String RESOURCE_MANAGER_NAME = "resourcemanager"; /** Unique id of the resource manager. */ private final ResourceID resourceId; /** All currently registered JobMasterGateways scoped by JobID. */ private final Map<JobID, JobManagerRegistration> jobManagerRegistrations; /** All currently registered JobMasterGateways scoped by ResourceID. */ private final Map<ResourceID, JobManagerRegistration> jmResourceIdRegistrations; /** Service to retrieve the job leader ids. */ private final JobLeaderIdService jobLeaderIdService; /** All currently registered TaskExecutors with there framework specific worker information. */ private final Map<ResourceID, WorkerRegistration<WorkerType>> taskExecutors; /** High availability services for leader retrieval and election. */ private final HighAvailabilityServices highAvailabilityServices; /** The heartbeat manager with task managers. */ private final HeartbeatManager<SlotReport, Void> taskManagerHeartbeatManager; /** The heartbeat manager with job managers. */ private final HeartbeatManager<Void, Void> jobManagerHeartbeatManager; /** Registry to use for metrics. */ private final MetricRegistry metricRegistry; /** Fatal error handler. */ private final FatalErrorHandler fatalErrorHandler; /** The slot manager maintains the available slots. */ private final SlotManager slotManager; private final ClusterInformation clusterInformation; /** The service to elect a ResourceManager leader. */ private LeaderElectionService leaderElectionService; /** All registered listeners for status updates of the ResourceManager. */ private ConcurrentMap<String, InfoMessageListenerRpcGateway> infoMessageListeners; /** * Represents asynchronous state clearing work. * * @see #clearStateAsync() * @see #clearStateInternal() */ private CompletableFuture<Void> clearStateFuture = CompletableFuture.completedFuture(null); public ResourceManager( RpcService rpcService, String resourceManagerEndpointId, ResourceID resourceId, HighAvailabilityServices highAvailabilityServices, HeartbeatServices heartbeatServices, SlotManager slotManager, MetricRegistry metricRegistry, JobLeaderIdService jobLeaderIdService, ClusterInformation clusterInformation, FatalErrorHandler fatalErrorHandler) { super(rpcService, resourceManagerEndpointId); this.resourceId = checkNotNull(resourceId); this.highAvailabilityServices = checkNotNull(highAvailabilityServices); this.slotManager = checkNotNull(slotManager); this.metricRegistry = checkNotNull(metricRegistry); this.jobLeaderIdService = checkNotNull(jobLeaderIdService); this.clusterInformation = checkNotNull(clusterInformation); this.fatalErrorHandler = checkNotNull(fatalErrorHandler); this.taskManagerHeartbeatManager = heartbeatServices.createHeartbeatManagerSender( resourceId, new TaskManagerHeartbeatListener(), rpcService.getScheduledExecutor(), log); this.jobManagerHeartbeatManager = heartbeatServices.createHeartbeatManagerSender( resourceId, new JobManagerHeartbeatListener(), rpcService.getScheduledExecutor(), log); this.jobManagerRegistrations = new HashMap<>(4); this.jmResourceIdRegistrations = new HashMap<>(4); this.taskExecutors = new HashMap<>(8); infoMessageListeners = new ConcurrentHashMap<>(8); } // ------------------------------------------------------------------------ // RPC lifecycle methods // ------------------------------------------------------------------------ @Override public void start() throws Exception { // start a leader super.start(); leaderElectionService = highAvailabilityServices.getResourceManagerLeaderElectionService(); initialize(); try { leaderElectionService.start(this); } catch (Exception e) { throw new ResourceManagerException("Could not start the leader election service.", e); } try { jobLeaderIdService.start(new JobLeaderIdActionsImpl()); } catch (Exception e) { throw new ResourceManagerException("Could not start the job leader id service.", e); } } @Override public CompletableFuture<Void> postStop() { Exception exception = null; taskManagerHeartbeatManager.stop(); jobManagerHeartbeatManager.stop(); try { slotManager.close(); } catch (Exception e) { exception = ExceptionUtils.firstOrSuppressed(e, exception); } try { leaderElectionService.stop(); } catch (Exception e) { exception = ExceptionUtils.firstOrSuppressed(e, exception); } try { jobLeaderIdService.stop(); } catch (Exception e) { exception = ExceptionUtils.firstOrSuppressed(e, exception); } clearStateInternal(); if (exception != null) { return FutureUtils.completedExceptionally( new FlinkException("Could not properly shut down the ResourceManager.", exception)); } else { return CompletableFuture.completedFuture(null); } } // ------------------------------------------------------------------------ // RPC methods // ------------------------------------------------------------------------ @Override public CompletableFuture<RegistrationResponse> registerJobManager( final JobMasterId jobMasterId, final ResourceID jobManagerResourceId, final String jobManagerAddress, final JobID jobId, final Time timeout) { checkNotNull(jobMasterId); checkNotNull(jobManagerResourceId); checkNotNull(jobManagerAddress); checkNotNull(jobId); if (!jobLeaderIdService.containsJob(jobId)) { try { jobLeaderIdService.addJob(jobId); } catch (Exception e) { ResourceManagerException exception = new ResourceManagerException("Could not add the job " + jobId + " to the job id leader service.", e); onFatalError(exception); log.error("Could not add job {} to job leader id service.", jobId, e); return FutureUtils.completedExceptionally(exception); } } log.info("Registering job manager {}@{} for job {}.", jobMasterId, jobManagerAddress, jobId); CompletableFuture<JobMasterId> jobMasterIdFuture; try { jobMasterIdFuture = jobLeaderIdService.getLeaderId(jobId); } catch (Exception e) { // we cannot check the job leader id so let's fail // TODO: Maybe it's also ok to skip this check in case that we cannot check the leader id ResourceManagerException exception = new ResourceManagerException("Cannot obtain the " + "job leader id future to verify the correct job leader.", e); onFatalError(exception); log.debug("Could not obtain the job leader id future to verify the correct job leader."); return FutureUtils.completedExceptionally(exception); } CompletableFuture<JobMasterGateway> jobMasterGatewayFuture = getRpcService().connect(jobManagerAddress, jobMasterId, JobMasterGateway.class); CompletableFuture<RegistrationResponse> registrationResponseFuture = jobMasterGatewayFuture.thenCombineAsync( jobMasterIdFuture, (JobMasterGateway jobMasterGateway, JobMasterId currentJobMasterId) -> { if (Objects.equals(currentJobMasterId, jobMasterId)) { return registerJobMasterInternal( jobMasterGateway, jobId, jobManagerAddress, jobManagerResourceId); } else { log.debug("The current JobMaster leader id {} did not match the received " + "JobMaster id {}.", jobMasterId, currentJobMasterId); return new RegistrationResponse.Decline("Job manager leader id did not match."); } }, getMainThreadExecutor()); // handle exceptions which might have occurred in one of the futures inputs of combine return registrationResponseFuture.handleAsync( (RegistrationResponse registrationResponse, Throwable throwable) -> { if (throwable != null) { if (log.isDebugEnabled()) { log.debug("Registration of job manager {}@{} failed.", jobMasterId, jobManagerAddress, throwable); } else { log.info("Registration of job manager {}@{} failed.", jobMasterId, jobManagerAddress); } return new RegistrationResponse.Decline(throwable.getMessage()); } else { return registrationResponse; } }, getRpcService().getExecutor()); } @Override public CompletableFuture<RegistrationResponse> registerTaskExecutor( final String taskExecutorAddress, final ResourceID taskExecutorResourceId, final int dataPort, final HardwareDescription hardwareDescription, final Time timeout) { CompletableFuture<TaskExecutorGateway> taskExecutorGatewayFuture = getRpcService().connect(taskExecutorAddress, TaskExecutorGateway.class); return taskExecutorGatewayFuture.handleAsync( (TaskExecutorGateway taskExecutorGateway, Throwable throwable) -> { if (throwable != null) { return new RegistrationResponse.Decline(throwable.getMessage()); } else { return registerTaskExecutorInternal( taskExecutorGateway, taskExecutorAddress, taskExecutorResourceId, dataPort, hardwareDescription); } }, getMainThreadExecutor()); } @Override public CompletableFuture<Acknowledge> sendSlotReport(ResourceID taskManagerResourceId, InstanceID taskManagerRegistrationId, SlotReport slotReport, Time timeout) { final WorkerRegistration<WorkerType> workerTypeWorkerRegistration = taskExecutors.get(taskManagerResourceId); if (workerTypeWorkerRegistration.getInstanceID().equals(taskManagerRegistrationId)) { slotManager.registerTaskManager(workerTypeWorkerRegistration, slotReport); return CompletableFuture.completedFuture(Acknowledge.get()); } else { return FutureUtils.completedExceptionally(new ResourceManagerException(String.format("Unknown TaskManager registration id %s.", taskManagerRegistrationId))); } } @Override public void heartbeatFromTaskManager(final ResourceID resourceID, final SlotReport slotReport) { taskManagerHeartbeatManager.receiveHeartbeat(resourceID, slotReport); } @Override public void heartbeatFromJobManager(final ResourceID resourceID) { jobManagerHeartbeatManager.receiveHeartbeat(resourceID, null); } @Override public void disconnectTaskManager(final ResourceID resourceId, final Exception cause) { closeTaskManagerConnection(resourceId, cause); } @Override public void disconnectJobManager(final JobID jobId, final Exception cause) { closeJobManagerConnection(jobId, cause); } @Override public CompletableFuture<Acknowledge> requestSlot( JobMasterId jobMasterId, SlotRequest slotRequest, final Time timeout) { JobID jobId = slotRequest.getJobId(); JobManagerRegistration jobManagerRegistration = jobManagerRegistrations.get(jobId); if (null != jobManagerRegistration) { if (Objects.equals(jobMasterId, jobManagerRegistration.getJobMasterId())) { log.info("Request slot with profile {} for job {} with allocation id {}.", slotRequest.getResourceProfile(), slotRequest.getJobId(), slotRequest.getAllocationId()); try { slotManager.registerSlotRequest(slotRequest); } catch (SlotManagerException e) { return FutureUtils.completedExceptionally(e); } return CompletableFuture.completedFuture(Acknowledge.get()); } else { return FutureUtils.completedExceptionally(new ResourceManagerException("The job leader's id " + jobManagerRegistration.getJobMasterId() + " does not match the received id " + jobMasterId + '.')); } } else { return FutureUtils.completedExceptionally(new ResourceManagerException("Could not find registered job manager for job " + jobId + '.')); } } @Override public void cancelSlotRequest(AllocationID allocationID) { // As the slot allocations are async, it can not avoid all redundant slots, but should best effort. slotManager.unregisterSlotRequest(allocationID); } @Override public void notifySlotAvailable( final InstanceID instanceID, final SlotID slotId, final AllocationID allocationId) { final ResourceID resourceId = slotId.getResourceID(); WorkerRegistration<WorkerType> registration = taskExecutors.get(resourceId); if (registration != null) { InstanceID registrationId = registration.getInstanceID(); if (Objects.equals(registrationId, instanceID)) { slotManager.freeSlot(slotId, allocationId); } else { log.debug("Invalid registration id for slot available message. This indicates an" + " outdated request."); } } else { log.debug("Could not find registration for resource id {}. Discarding the slot available" + "message {}.", resourceId, slotId); } } /** * Registers an info message listener. * * @param address address of infoMessage listener to register to this resource manager */ @Override public void registerInfoMessageListener(final String address) { if (infoMessageListeners.containsKey(address)) { log.warn("Receive a duplicate registration from info message listener on ({})", address); } else { CompletableFuture<InfoMessageListenerRpcGateway> infoMessageListenerRpcGatewayFuture = getRpcService() .connect(address, InfoMessageListenerRpcGateway.class); infoMessageListenerRpcGatewayFuture.whenCompleteAsync( (InfoMessageListenerRpcGateway gateway, Throwable failure) -> { if (failure != null) { log.warn("Receive a registration from unreachable info message listener on ({})", address); } else { log.info("Receive a registration from info message listener on ({})", address); infoMessageListeners.put(address, gateway); } }, getMainThreadExecutor()); } } /** * Unregisters an info message listener. * * @param address of the info message listener to unregister from this resource manager * */ @Override public void unRegisterInfoMessageListener(final String address) { infoMessageListeners.remove(address); } /** * Cleanup application and shut down cluster. * * @param finalStatus of the Flink application * @param diagnostics diagnostics message for the Flink application or {@code null} */ @Override public CompletableFuture<Acknowledge> deregisterApplication( final ApplicationStatus finalStatus, @Nullable final String diagnostics) { log.info("Shut down cluster because application is in {}, diagnostics {}.", finalStatus, diagnostics); try { internalDeregisterApplication(finalStatus, diagnostics); } catch (ResourceManagerException e) { log.warn("Could not properly shutdown the application.", e); } return CompletableFuture.completedFuture(Acknowledge.get()); } @Override public CompletableFuture<Integer> getNumberOfRegisteredTaskManagers() { return CompletableFuture.completedFuture(taskExecutors.size()); } @Override public CompletableFuture<Collection<TaskManagerInfo>> requestTaskManagerInfo(Time timeout) { final ArrayList<TaskManagerInfo> taskManagerInfos = new ArrayList<>(taskExecutors.size()); for (Map.Entry<ResourceID, WorkerRegistration<WorkerType>> taskExecutorEntry : taskExecutors.entrySet()) { final ResourceID resourceId = taskExecutorEntry.getKey(); final WorkerRegistration<WorkerType> taskExecutor = taskExecutorEntry.getValue(); taskManagerInfos.add( new TaskManagerInfo( resourceId, taskExecutor.getTaskExecutorGateway().getAddress(), taskExecutor.getDataPort(), taskManagerHeartbeatManager.getLastHeartbeatFrom(resourceId), slotManager.getNumberRegisteredSlotsOf(taskExecutor.getInstanceID()), slotManager.getNumberFreeSlotsOf(taskExecutor.getInstanceID()), taskExecutor.getHardwareDescription())); } return CompletableFuture.completedFuture(taskManagerInfos); } @Override public CompletableFuture<TaskManagerInfo> requestTaskManagerInfo(ResourceID resourceId, Time timeout) { final WorkerRegistration<WorkerType> taskExecutor = taskExecutors.get(resourceId); if (taskExecutor == null) { return FutureUtils.completedExceptionally(new UnknownTaskExecutorException(resourceId)); } else { final InstanceID instanceId = taskExecutor.getInstanceID(); final TaskManagerInfo taskManagerInfo = new TaskManagerInfo( resourceId, taskExecutor.getTaskExecutorGateway().getAddress(), taskExecutor.getDataPort(), taskManagerHeartbeatManager.getLastHeartbeatFrom(resourceId), slotManager.getNumberRegisteredSlotsOf(instanceId), slotManager.getNumberFreeSlotsOf(instanceId), taskExecutor.getHardwareDescription()); return CompletableFuture.completedFuture(taskManagerInfo); } } @Override public CompletableFuture<ResourceOverview> requestResourceOverview(Time timeout) { final int numberSlots = slotManager.getNumberRegisteredSlots(); final int numberFreeSlots = slotManager.getNumberFreeSlots(); return CompletableFuture.completedFuture( new ResourceOverview( taskExecutors.size(), numberSlots, numberFreeSlots)); } @Override public CompletableFuture<Collection<Tuple2<ResourceID, String>>> requestTaskManagerMetricQueryServicePaths(Time timeout) { final ArrayList<Tuple2<ResourceID, String>> metricQueryServicePaths = new ArrayList<>(taskExecutors.size()); for (Map.Entry<ResourceID, WorkerRegistration<WorkerType>> workerRegistrationEntry : taskExecutors.entrySet()) { final ResourceID tmResourceId = workerRegistrationEntry.getKey(); final WorkerRegistration<WorkerType> workerRegistration = workerRegistrationEntry.getValue(); final String taskManagerAddress = workerRegistration.getTaskExecutorGateway().getAddress(); final String tmMetricQueryServicePath = taskManagerAddress.substring(0, taskManagerAddress.lastIndexOf('/') + 1) + MetricQueryService.METRIC_QUERY_SERVICE_NAME + '_' + tmResourceId.getResourceIdString(); metricQueryServicePaths.add(Tuple2.of(tmResourceId, tmMetricQueryServicePath)); } return CompletableFuture.completedFuture(metricQueryServicePaths); } @Override public CompletableFuture<TransientBlobKey> requestTaskManagerFileUpload(ResourceID taskManagerId, FileType fileType, Time timeout) { log.debug("Request file {} upload from TaskExecutor {}.", fileType, taskManagerId); final WorkerRegistration<WorkerType> taskExecutor = taskExecutors.get(taskManagerId); if (taskExecutor == null) { log.debug("Requested file {} upload from unregistered TaskExecutor {}.", fileType, taskManagerId); return FutureUtils.completedExceptionally(new UnknownTaskExecutorException(taskManagerId)); } else { return taskExecutor.getTaskExecutorGateway().requestFileUpload(fileType, timeout); } } // ------------------------------------------------------------------------ // Internal methods // ------------------------------------------------------------------------ /** * Registers a new JobMaster. * * @param jobMasterGateway to communicate with the registering JobMaster * @param jobId of the job for which the JobMaster is responsible * @param jobManagerAddress address of the JobMaster * @param jobManagerResourceId ResourceID of the JobMaster * @return RegistrationResponse */ private RegistrationResponse registerJobMasterInternal( final JobMasterGateway jobMasterGateway, JobID jobId, String jobManagerAddress, ResourceID jobManagerResourceId) { if (jobManagerRegistrations.containsKey(jobId)) { JobManagerRegistration oldJobManagerRegistration = jobManagerRegistrations.get(jobId); if (Objects.equals(oldJobManagerRegistration.getJobMasterId(), jobMasterGateway.getFencingToken())) { // same registration log.debug("Job manager {}@{} was already registered.", jobMasterGateway.getFencingToken(), jobManagerAddress); } else { // tell old job manager that he is no longer the job leader disconnectJobManager( oldJobManagerRegistration.getJobID(), new Exception("New job leader for job " + jobId + " found.")); JobManagerRegistration jobManagerRegistration = new JobManagerRegistration( jobId, jobManagerResourceId, jobMasterGateway); jobManagerRegistrations.put(jobId, jobManagerRegistration); jmResourceIdRegistrations.put(jobManagerResourceId, jobManagerRegistration); } } else { // new registration for the job JobManagerRegistration jobManagerRegistration = new JobManagerRegistration( jobId, jobManagerResourceId, jobMasterGateway); jobManagerRegistrations.put(jobId, jobManagerRegistration); jmResourceIdRegistrations.put(jobManagerResourceId, jobManagerRegistration); } log.info("Registered job manager {}@{} for job {}.", jobMasterGateway.getFencingToken(), jobManagerAddress, jobId); jobManagerHeartbeatManager.monitorTarget(jobManagerResourceId, new HeartbeatTarget<Void>() { @Override public void receiveHeartbeat(ResourceID resourceID, Void payload) { // the ResourceManager will always send heartbeat requests to the JobManager } @Override public void requestHeartbeat(ResourceID resourceID, Void payload) { jobMasterGateway.heartbeatFromResourceManager(resourceID); } }); return new JobMasterRegistrationSuccess( getFencingToken(), resourceId); } /** * Registers a new TaskExecutor. * * @param taskExecutorGateway to communicate with the registering TaskExecutor * @param taskExecutorAddress address of the TaskExecutor * @param taskExecutorResourceId ResourceID of the TaskExecutor * @param dataPort port used for data transfer * @param hardwareDescription of the registering TaskExecutor * @return RegistrationResponse */ private RegistrationResponse registerTaskExecutorInternal( TaskExecutorGateway taskExecutorGateway, String taskExecutorAddress, ResourceID taskExecutorResourceId, int dataPort, HardwareDescription hardwareDescription) { WorkerRegistration<WorkerType> oldRegistration = taskExecutors.remove(taskExecutorResourceId); if (oldRegistration != null) { // TODO :: suggest old taskExecutor to stop itself log.debug("Replacing old registration of TaskExecutor {}.", taskExecutorResourceId); // remove old task manager registration from slot manager slotManager.unregisterTaskManager(oldRegistration.getInstanceID()); } final WorkerType newWorker = workerStarted(taskExecutorResourceId); if (newWorker == null) { log.warn("Discard registration from TaskExecutor {} at ({}) because the framework did " + "not recognize it", taskExecutorResourceId, taskExecutorAddress); return new RegistrationResponse.Decline("unrecognized TaskExecutor"); } else { WorkerRegistration<WorkerType> registration = new WorkerRegistration<>(taskExecutorGateway, newWorker, dataPort, hardwareDescription); log.info("Registering TaskManager with ResourceID {} ({}) at ResourceManager", taskExecutorResourceId, taskExecutorAddress); taskExecutors.put(taskExecutorResourceId, registration); taskManagerHeartbeatManager.monitorTarget(taskExecutorResourceId, new HeartbeatTarget<Void>() { @Override public void receiveHeartbeat(ResourceID resourceID, Void payload) { // the ResourceManager will always send heartbeat requests to the // TaskManager } @Override public void requestHeartbeat(ResourceID resourceID, Void payload) { taskExecutorGateway.heartbeatFromResourceManager(resourceID); } }); return new TaskExecutorRegistrationSuccess( registration.getInstanceID(), resourceId, clusterInformation); } } private void clearStateInternal() { jobManagerRegistrations.clear(); jmResourceIdRegistrations.clear(); taskExecutors.clear(); try { jobLeaderIdService.clear(); } catch (Exception e) { onFatalError(new ResourceManagerException("Could not properly clear the job leader id service.", e)); } clearStateFuture = clearStateAsync(); } /** * This method should be called by the framework once it detects that a currently registered * job manager has failed. * * @param jobId identifying the job whose leader shall be disconnected. * @param cause The exception which cause the JobManager failed. */ protected void closeJobManagerConnection(JobID jobId, Exception cause) { JobManagerRegistration jobManagerRegistration = jobManagerRegistrations.remove(jobId); if (jobManagerRegistration != null) { final ResourceID jobManagerResourceId = jobManagerRegistration.getJobManagerResourceID(); final JobMasterGateway jobMasterGateway = jobManagerRegistration.getJobManagerGateway(); final JobMasterId jobMasterId = jobManagerRegistration.getJobMasterId(); log.info("Disconnect job manager {}@{} for job {} from the resource manager.", jobMasterId, jobMasterGateway.getAddress(), jobId); jobManagerHeartbeatManager.unmonitorTarget(jobManagerResourceId); jmResourceIdRegistrations.remove(jobManagerResourceId); // tell the job manager about the disconnect jobMasterGateway.disconnectResourceManager(getFencingToken(), cause); } else { log.debug("There was no registered job manager for job {}.", jobId); } } /** * This method should be called by the framework once it detects that a currently registered * task executor has failed. * * @param resourceID Id of the TaskManager that has failed. * @param cause The exception which cause the TaskManager failed. */ protected void closeTaskManagerConnection(final ResourceID resourceID, final Exception cause) { taskManagerHeartbeatManager.unmonitorTarget(resourceID); WorkerRegistration<WorkerType> workerRegistration = taskExecutors.remove(resourceID); if (workerRegistration != null) { log.info("Closing TaskExecutor connection {} because: {}", resourceID, cause.getMessage()); // TODO :: suggest failed task executor to stop itself slotManager.unregisterTaskManager(workerRegistration.getInstanceID()); workerRegistration.getTaskExecutorGateway().disconnectResourceManager(cause); } else { log.debug( "No open TaskExecutor connection {}. Ignoring close TaskExecutor connection. Closing reason was: {}", resourceID, cause.getMessage()); } } protected void removeJob(JobID jobId) { try { jobLeaderIdService.removeJob(jobId); } catch (Exception e) { log.warn("Could not properly remove the job {} from the job leader id service.", jobId, e); } if (jobManagerRegistrations.containsKey(jobId)) { disconnectJobManager(jobId, new Exception("Job " + jobId + "was removed")); } } protected void jobLeaderLostLeadership(JobID jobId, JobMasterId oldJobMasterId) { if (jobManagerRegistrations.containsKey(jobId)) { JobManagerRegistration jobManagerRegistration = jobManagerRegistrations.get(jobId); if (Objects.equals(jobManagerRegistration.getJobMasterId(), oldJobMasterId)) { disconnectJobManager(jobId, new Exception("Job leader lost leadership.")); } else { log.debug("Discarding job leader lost leadership, because a new job leader was found for job {}. ", jobId); } } else { log.debug("Discard job leader lost leadership for outdated leader {} for job {}.", oldJobMasterId, jobId); } } protected void releaseResource(InstanceID instanceId, Exception cause) { WorkerType worker = null; // TODO: Improve performance by having an index on the instanceId for (Map.Entry<ResourceID, WorkerRegistration<WorkerType>> entry : taskExecutors.entrySet()) { if (entry.getValue().getInstanceID().equals(instanceId)) { worker = entry.getValue().getWorker(); break; } } if (worker != null) { if (stopWorker(worker)) { closeTaskManagerConnection(worker.getResourceID(), cause); } else { log.debug("Worker {} could not be stopped.", worker.getResourceID()); } } else { // unregister in order to clean up potential left over state slotManager.unregisterTaskManager(instanceId); } } // ------------------------------------------------------------------------ // Info messaging // ------------------------------------------------------------------------ public void sendInfoMessage(final String message) { getRpcService().execute(new Runnable() { @Override public void run() { InfoMessage infoMessage = new InfoMessage(message); for (InfoMessageListenerRpcGateway listenerRpcGateway : infoMessageListeners.values()) { listenerRpcGateway .notifyInfoMessage(infoMessage); } } }); } // ------------------------------------------------------------------------ // Error Handling // ------------------------------------------------------------------------ /** * Notifies the ResourceManager that a fatal error has occurred and it cannot proceed. * * @param t The exception describing the fatal error */ protected void onFatalError(Throwable t) { try { log.error("Fatal error occurred in ResourceManager.", t); } catch (Throwable ignored) {} // The fatal error handler implementation should make sure that this call is non-blocking fatalErrorHandler.onFatalError(t); } // ------------------------------------------------------------------------ // Leader Contender // ------------------------------------------------------------------------ /** * Callback method when current resourceManager is granted leadership. * * @param newLeaderSessionID unique leadershipID */ @Override public void grantLeadership(final UUID newLeaderSessionID) { final CompletableFuture<Boolean> acceptLeadershipFuture = clearStateFuture .thenComposeAsync((ignored) -> tryAcceptLeadership(newLeaderSessionID), getUnfencedMainThreadExecutor()); final CompletableFuture<Void> confirmationFuture = acceptLeadershipFuture.thenAcceptAsync( (acceptLeadership) -> { if (acceptLeadership) { // confirming the leader session ID might be blocking, leaderElectionService.confirmLeaderSessionID(newLeaderSessionID); } }, getRpcService().getExecutor()); confirmationFuture.whenComplete( (Void ignored, Throwable throwable) -> { if (throwable != null) { onFatalError(ExceptionUtils.stripCompletionException(throwable)); } }); } private CompletableFuture<Boolean> tryAcceptLeadership(final UUID newLeaderSessionID) { if (leaderElectionService.hasLeadership(newLeaderSessionID)) { final ResourceManagerId newResourceManagerId = ResourceManagerId.fromUuid(newLeaderSessionID); log.info("ResourceManager {} was granted leadership with fencing token {}", getAddress(), newResourceManagerId); // clear the state if we've been the leader before if (getFencingToken() != null) { clearStateInternal(); } setFencingToken(newResourceManagerId); slotManager.start(getFencingToken(), getMainThreadExecutor(), new ResourceActionsImpl()); return prepareLeadershipAsync().thenApply(ignored -> true); } else { return CompletableFuture.completedFuture(false); } } /** * Callback method when current resourceManager loses leadership. */ @Override public void revokeLeadership() { runAsyncWithoutFencing( () -> { log.info("ResourceManager {} was revoked leadership. Clearing fencing token.", getAddress()); clearStateInternal(); setFencingToken(null); slotManager.suspend(); }); } /** * Handles error occurring in the leader election service. * * @param exception Exception being thrown in the leader election service */ @Override public void handleError(final Exception exception) { onFatalError(new ResourceManagerException("Received an error from the LeaderElectionService.", exception)); } // ------------------------------------------------------------------------ // Framework specific behavior // ------------------------------------------------------------------------ /** * Initializes the framework specific components. * * @throws ResourceManagerException which occurs during initialization and causes the resource manager to fail. */ protected abstract void initialize() throws ResourceManagerException; /** * This method can be overridden to add a (non-blocking) initialization routine to the * ResourceManager that will be called when leadership is granted but before leadership is * confirmed. * * @return Returns a {@code CompletableFuture} that completes when the computation is finished. */ protected CompletableFuture<Void> prepareLeadershipAsync() { return CompletableFuture.completedFuture(null); } /** * This method can be overridden to add a (non-blocking) state clearing routine to the * ResourceManager that will be called when leadership is revoked. * * @return Returns a {@code CompletableFuture} that completes when the state clearing routine * is finished. */ protected CompletableFuture<Void> clearStateAsync() { return CompletableFuture.completedFuture(null); } /** * The framework specific code to deregister the application. This should report the * application's final status and shut down the resource manager cleanly. * * <p>This method also needs to make sure all pending containers that are not registered * yet are returned. * * @param finalStatus The application status to report. * @param optionalDiagnostics A diagnostics message or {@code null}. * @throws ResourceManagerException if the application could not be shut down. */ protected abstract void internalDeregisterApplication( ApplicationStatus finalStatus, @Nullable String optionalDiagnostics) throws ResourceManagerException; /** * Allocates a resource using the resource profile. * * @param resourceProfile The resource description * @return Collection of {@link ResourceProfile} describing the launched slots */ @VisibleForTesting public abstract Collection<ResourceProfile> startNewWorker(ResourceProfile resourceProfile); /** * Callback when a worker was started. * @param resourceID The worker resource id */ protected abstract WorkerType workerStarted(ResourceID resourceID); /** * Stops the given worker. * * @param worker The worker. * @return True if the worker was stopped, otherwise false */ public abstract boolean stopWorker(WorkerType worker); // ------------------------------------------------------------------------ // Static utility classes // ------------------------------------------------------------------------ private class ResourceActionsImpl implements ResourceActions { @Override public void releaseResource(InstanceID instanceId, Exception cause) { validateRunsInMainThread(); ResourceManager.this.releaseResource(instanceId, cause); } @Override public Collection<ResourceProfile> allocateResource(ResourceProfile resourceProfile) { validateRunsInMainThread(); return startNewWorker(resourceProfile); } @Override public void notifyAllocationFailure(JobID jobId, AllocationID allocationId, Exception cause) { validateRunsInMainThread(); JobManagerRegistration jobManagerRegistration = jobManagerRegistrations.get(jobId); if (jobManagerRegistration != null) { jobManagerRegistration.getJobManagerGateway().notifyAllocationFailure(allocationId, cause); } } } private class JobLeaderIdActionsImpl implements JobLeaderIdActions { @Override public void jobLeaderLostLeadership(final JobID jobId, final JobMasterId oldJobMasterId) { runAsync(new Runnable() { @Override public void run() { ResourceManager.this.jobLeaderLostLeadership(jobId, oldJobMasterId); } }); } @Override public void notifyJobTimeout(final JobID jobId, final UUID timeoutId) { runAsync(new Runnable() { @Override public void run() { if (jobLeaderIdService.isValidTimeout(jobId, timeoutId)) { removeJob(jobId); } } }); } @Override public void handleError(Throwable error) { onFatalError(error); } } private class TaskManagerHeartbeatListener implements HeartbeatListener<SlotReport, Void> { @Override public void notifyHeartbeatTimeout(final ResourceID resourceID) { runAsync(new Runnable() { @Override public void run() { log.info("The heartbeat of TaskManager with id {} timed out.", resourceID); closeTaskManagerConnection( resourceID, new TimeoutException("The heartbeat of TaskManager with id " + resourceID + " timed out.")); } }); } @Override public void reportPayload(final ResourceID resourceID, final SlotReport slotReport) { runAsync(new Runnable() { @Override public void run() { log.debug("Received new slot report from TaskManager {}.", resourceID); final WorkerRegistration<WorkerType> workerRegistration = taskExecutors.get(resourceID); if (workerRegistration == null) { log.debug("Received slot report from TaskManager {} which is no longer registered.", resourceID); } else { InstanceID instanceId = workerRegistration.getInstanceID(); slotManager.reportSlotStatus(instanceId, slotReport); } } }); } @Override public CompletableFuture<Void> retrievePayload(ResourceID resourceID) { return CompletableFuture.completedFuture(null); } } private class JobManagerHeartbeatListener implements HeartbeatListener<Void, Void> { @Override public void notifyHeartbeatTimeout(final ResourceID resourceID) { runAsync(new Runnable() { @Override public void run() { log.info("The heartbeat of JobManager with id {} timed out.", resourceID); if (jmResourceIdRegistrations.containsKey(resourceID)) { JobManagerRegistration jobManagerRegistration = jmResourceIdRegistrations.get(resourceID); if (jobManagerRegistration != null) { closeJobManagerConnection( jobManagerRegistration.getJobID(), new TimeoutException("The heartbeat of JobManager with id " + resourceID + " timed out.")); } } } }); } @Override public void reportPayload(ResourceID resourceID, Void payload) { // nothing to do since there is no payload } @Override public CompletableFuture<Void> retrievePayload(ResourceID resourceID) { return CompletableFuture.completedFuture(null); } } // ------------------------------------------------------------------------ // Resource Management // ------------------------------------------------------------------------ protected int getNumberRequiredTaskManagerSlots() { return slotManager.getNumberPendingTaskManagerSlots(); } // ------------------------------------------------------------------------ // Helper methods // ------------------------------------------------------------------------ protected static Collection<ResourceProfile> createSlotsPerWorker(int numSlots) { return Collections.nCopies(numSlots, ResourceProfile.ANY); } }
/* * Copyright (c) 2011 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. */ package com.google.devtools.moe.client.svn; import static com.google.common.base.Strings.isNullOrEmpty; import com.google.devtools.moe.client.FileSystem; import com.google.devtools.moe.client.Ui; import com.google.devtools.moe.client.InvalidProject; import com.google.devtools.moe.client.config.RepositoryConfig; import com.google.devtools.moe.client.repositories.RepositoryType; import javax.inject.Inject; /** * Creates a Subversion implementation of {@link RepositoryType}. */ public class SvnRepositoryFactory implements RepositoryType.Factory { private final FileSystem filesystem; private final SvnUtil util; private final Ui ui; @Inject public SvnRepositoryFactory(FileSystem filesystem, SvnUtil util, Ui ui) { this.filesystem = filesystem; this.util = util; this.ui = ui; } @Override public String type() { return "svn"; } @Override public RepositoryType create(String name, RepositoryConfig config) throws InvalidProject { checkType(config); String url = config.getUrl(); if (isNullOrEmpty(url)) { throw new InvalidProject("Svn repository config missing \"url\"."); } SvnRevisionHistory rh = new SvnRevisionHistory(name, url, util, config); return RepositoryType.create( name, rh, new SvnCodebaseCreator(filesystem, name, config, rh, util), new SvnWriterCreator(config, rh, util, filesystem, ui)); } }
package com.ss.gulimall.member.dao; import com.ss.gulimall.member.entity.IntegrationChangeHistoryEntity; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; /** * 积分变化历史记录 * * @author fangsheng * @email 445317262@qq.com * @date 2021-10-17 15:28:51 */ @Mapper public interface IntegrationChangeHistoryDao extends BaseMapper<IntegrationChangeHistoryEntity> { }
package edu.stanford.math.plex4.streams.storage_structures; import java.util.Iterator; import edu.stanford.math.primitivelib.autogen.pair.IntObjectPair; /** * This class provides iteration over the second component of each element * in an Iterable collection of type IntObjectPair<E>. It essentially * ignores the first component, and only returns the second. * * @author Andrew Tausz * * @param <E> */ public class IntOrderedIterator<E> implements Iterator<E> { /** * The iterator over the pair collection. */ private final Iterator<IntObjectPair<E>> internalIterator; /** * This constructor initializes the iterator with an iterable collection * over the type IntObjectPair<E>. * * @param collection the Iterable collection to initialize with */ public IntOrderedIterator(Iterable<IntObjectPair<E>> collection) { this.internalIterator = collection.iterator(); } /* (non-Javadoc) * @see java.util.Iterator#hasNext() */ public boolean hasNext() { return this.internalIterator.hasNext(); } /* (non-Javadoc) * @see java.util.Iterator#next() */ public E next() { return this.internalIterator.next().getSecond(); } /* (non-Javadoc) * @see java.util.Iterator#remove() */ public void remove() { throw new UnsupportedOperationException(); } }
/* * Copyright 2013-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.kinesisanalyticsv2.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.kinesisanalyticsv2.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * DeleteApplicationOutputResult JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DeleteApplicationOutputResultJsonUnmarshaller implements Unmarshaller<DeleteApplicationOutputResult, JsonUnmarshallerContext> { public DeleteApplicationOutputResult unmarshall(JsonUnmarshallerContext context) throws Exception { DeleteApplicationOutputResult deleteApplicationOutputResult = new DeleteApplicationOutputResult(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return deleteApplicationOutputResult; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("ApplicationARN", targetDepth)) { context.nextToken(); deleteApplicationOutputResult.setApplicationARN(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("ApplicationVersionId", targetDepth)) { context.nextToken(); deleteApplicationOutputResult.setApplicationVersionId(context.getUnmarshaller(Long.class).unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return deleteApplicationOutputResult; } private static DeleteApplicationOutputResultJsonUnmarshaller instance; public static DeleteApplicationOutputResultJsonUnmarshaller getInstance() { if (instance == null) instance = new DeleteApplicationOutputResultJsonUnmarshaller(); return instance; } }
package Thread; /** * @program: JavaSenior * @description: 生产者/消费者问题 * @author: Zhang.Qi * @create: 2021-03-31 10:53 **/ public class ProducerConsumerTest { }
/** * This code is released under the * Apache License Version 2.0 http://www.apache.org/licenses/. * * (c) Daniel Lemire, http://lemire.me/en/ */ package me.lemire.integercompression; /** * Interface describing a standard CODEC to compress integers. * * @author Daniel Lemire * */ public interface IntegerCODEC { /** * Compress data from an array to another array. * * Both inpos and outpos are modified to represent how much data was * read and written to if 12 ints (inlength = 12) are compressed to 3 * ints, then inpos will be incremented by 12 while outpos will be * incremented by 3 we use IntWrapper to pass the values by reference. * * @param in * input array * @param inpos * location in the input array * @param inlength * how many integers to compress * @param out * output array * @param outpos * where to write in the output array */ public void compress(int[] in, IntWrapper inpos, int inlength, int[] out, IntWrapper outpos); /** * Uncompress data from an array to another array. * * Both inpos and outpos parameters are modified to indicate new * positions after read/write. * * @param in * array containing data in compressed form * @param inpos * where to start reading in the array * @param inlength * length of the compressed data (ignored by some * schemes) * @param out * array where to write the compressed output * @param outpos * where to write the compressed output in out */ public void uncompress(int[] in, IntWrapper inpos, int inlength, int[] out, IntWrapper outpos); }
package io.github.scrumboot.langs.exception; import io.github.scrumboot.langs.model.status.StatusCode; /** * @author bingdyee * @since 2022/03/24 */ public class AuthenticationFailedException extends AbstractWebException { public AuthenticationFailedException() { super(StatusCode.LOGIN_FAILED.getCode(), "登录失败"); } public AuthenticationFailedException(String message) { super(StatusCode.LOGIN_FAILED.getCode(), message); } }
/* * Copyright 2002-2018 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.validation.beanvalidation; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Properties; import javax.validation.Configuration; import javax.validation.ConstraintValidatorFactory; import javax.validation.MessageInterpolator; import javax.validation.TraversableResolver; import javax.validation.Validation; import javax.validation.ValidationException; import javax.validation.ValidationProviderResolver; import javax.validation.Validator; import javax.validation.ValidatorContext; import javax.validation.ValidatorFactory; import javax.validation.bootstrap.GenericBootstrap; import javax.validation.bootstrap.ProviderSpecificBootstrap; import org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.MessageSource; import org.springframework.core.DefaultParameterNameDiscoverer; import org.springframework.core.ParameterNameDiscoverer; import org.springframework.core.io.Resource; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; import org.springframework.util.CollectionUtils; import org.springframework.util.ReflectionUtils; /** * This is the central class for {@code javax.validation} (JSR-303) setup in a Spring * application context: It bootstraps a {@code javax.validation.ValidationFactory} and * exposes it through the Spring {@link org.springframework.validation.Validator} interface * as well as through the JSR-303 {@link javax.validation.Validator} interface and the * {@link javax.validation.ValidatorFactory} interface itself. * * <p>When talking to an instance of this bean through the Spring or JSR-303 Validator interfaces, * you'll be talking to the default Validator of the underlying ValidatorFactory. This is very * convenient in that you don't have to perform yet another call on the factory, assuming that * you will almost always use the default Validator anyway. This can also be injected directly * into any target dependency of type {@link org.springframework.validation.Validator}! * * <p><b>As of Spring 4.0, this class supports Bean Validation 1.0 and 1.1, with special support * for Hibernate Validator 4.3 and 5.x</b> (see {@link #setValidationMessageSource}). * * <p>Note that Bean Validation 1.1's {@code #forExecutables} method isn't supported: We do not * expect that method to be called by application code; consider {@link MethodValidationInterceptor} * instead. If you really need programmatic {@code #forExecutables} access, inject this class as * a {@link ValidatorFactory} and call {@link #getValidator()} on it, then {@code #forExecutables} * on the returned native {@link Validator} reference instead of directly on this class. * Alternatively, call {@code #unwrap(Validator.class)} which will also provide the native object. * * <p>This class is also being used by Spring's MVC configuration namespace, in case of the * {@code javax.validation} API being present but no explicit Validator having been configured. * * @author Juergen Hoeller * @since 3.0 * @see javax.validation.ValidatorFactory * @see javax.validation.Validator * @see javax.validation.Validation#buildDefaultValidatorFactory() * @see javax.validation.ValidatorFactory#getValidator() */ public class LocalValidatorFactoryBean extends SpringValidatorAdapter implements ValidatorFactory, ApplicationContextAware, InitializingBean, DisposableBean { // Bean Validation 1.1 close() method available? private static final Method closeMethod = ClassUtils.getMethodIfAvailable(ValidatorFactory.class, "close"); @SuppressWarnings("rawtypes") private Class providerClass; private ValidationProviderResolver validationProviderResolver; private MessageInterpolator messageInterpolator; private TraversableResolver traversableResolver; private ConstraintValidatorFactory constraintValidatorFactory; private ParameterNameDiscoverer parameterNameDiscoverer = new DefaultParameterNameDiscoverer(); private Resource[] mappingLocations; private final Map<String, String> validationPropertyMap = new HashMap<String, String>(); private ApplicationContext applicationContext; private ValidatorFactory validatorFactory; /** * Specify the desired provider class, if any. * <p>If not specified, JSR-303's default search mechanism will be used. * @see javax.validation.Validation#byProvider(Class) * @see javax.validation.Validation#byDefaultProvider() */ @SuppressWarnings("rawtypes") public void setProviderClass(Class providerClass) { this.providerClass = providerClass; } /** * Specify a JSR-303 {@link ValidationProviderResolver} for bootstrapping the * provider of choice, as an alternative to {@code META-INF} driven resolution. * @since 4.3 */ public void setValidationProviderResolver(ValidationProviderResolver validationProviderResolver) { this.validationProviderResolver = validationProviderResolver; } /** * Specify a custom MessageInterpolator to use for this ValidatorFactory * and its exposed default Validator. */ public void setMessageInterpolator(MessageInterpolator messageInterpolator) { this.messageInterpolator = messageInterpolator; } /** * Specify a custom Spring MessageSource for resolving validation messages, * instead of relying on JSR-303's default "ValidationMessages.properties" bundle * in the classpath. This may refer to a Spring context's shared "messageSource" bean, * or to some special MessageSource setup for validation purposes only. * <p><b>NOTE:</b> This feature requires Hibernate Validator 4.3 or higher on the classpath. * You may nevertheless use a different validation provider but Hibernate Validator's * {@link ResourceBundleMessageInterpolator} class must be accessible during configuration. * <p>Specify either this property or {@link #setMessageInterpolator "messageInterpolator"}, * not both. If you would like to build a custom MessageInterpolator, consider deriving from * Hibernate Validator's {@link ResourceBundleMessageInterpolator} and passing in a * Spring-based {@code ResourceBundleLocator} when constructing your interpolator. * <p>In order for Hibernate's default validation messages to be resolved still, your * {@link MessageSource} must be configured for optional resolution (usually the default). * In particular, the {@code MessageSource} instance specified here should not apply * {@link org.springframework.context.support.AbstractMessageSource#setUseCodeAsDefaultMessage * "useCodeAsDefaultMessage"} behavior. Please double-check your setup accordingly. * @see ResourceBundleMessageInterpolator */ public void setValidationMessageSource(MessageSource messageSource) { this.messageInterpolator = HibernateValidatorDelegate.buildMessageInterpolator(messageSource); } /** * Specify a custom TraversableResolver to use for this ValidatorFactory * and its exposed default Validator. */ public void setTraversableResolver(TraversableResolver traversableResolver) { this.traversableResolver = traversableResolver; } /** * Specify a custom ConstraintValidatorFactory to use for this ValidatorFactory. * <p>Default is a {@link SpringConstraintValidatorFactory}, delegating to the * containing ApplicationContext for creating autowired ConstraintValidator instances. */ public void setConstraintValidatorFactory(ConstraintValidatorFactory constraintValidatorFactory) { this.constraintValidatorFactory = constraintValidatorFactory; } /** * Set the ParameterNameDiscoverer to use for resolving method and constructor * parameter names if needed for message interpolation. * <p>Default is a {@link org.springframework.core.DefaultParameterNameDiscoverer}. */ public void setParameterNameDiscoverer(ParameterNameDiscoverer parameterNameDiscoverer) { this.parameterNameDiscoverer = parameterNameDiscoverer; } /** * Specify resource locations to load XML constraint mapping files from, if any. */ public void setMappingLocations(Resource... mappingLocations) { this.mappingLocations = mappingLocations; } /** * Specify bean validation properties to be passed to the validation provider. * <p>Can be populated with a String "value" (parsed via PropertiesEditor) * or a "props" element in XML bean definitions. * @see javax.validation.Configuration#addProperty(String, String) */ public void setValidationProperties(Properties jpaProperties) { CollectionUtils.mergePropertiesIntoMap(jpaProperties, this.validationPropertyMap); } /** * Specify bean validation properties to be passed to the validation provider as a Map. * <p>Can be populated with a "map" or "props" element in XML bean definitions. * @see javax.validation.Configuration#addProperty(String, String) */ public void setValidationPropertyMap(Map<String, String> validationProperties) { if (validationProperties != null) { this.validationPropertyMap.putAll(validationProperties); } } /** * Allow Map access to the bean validation properties to be passed to the validation provider, * with the option to add or override specific entries. * <p>Useful for specifying entries directly, for example via "validationPropertyMap[myKey]". */ public Map<String, String> getValidationPropertyMap() { return this.validationPropertyMap; } @Override public void setApplicationContext(ApplicationContext applicationContext) { this.applicationContext = applicationContext; } @Override @SuppressWarnings({"rawtypes", "unchecked"}) public void afterPropertiesSet() { Configuration<?> configuration; if (this.providerClass != null) { ProviderSpecificBootstrap bootstrap = Validation.byProvider(this.providerClass); if (this.validationProviderResolver != null) { bootstrap = bootstrap.providerResolver(this.validationProviderResolver); } configuration = bootstrap.configure(); } else { GenericBootstrap bootstrap = Validation.byDefaultProvider(); if (this.validationProviderResolver != null) { bootstrap = bootstrap.providerResolver(this.validationProviderResolver); } configuration = bootstrap.configure(); } // Try Hibernate Validator 5.2's externalClassLoader(ClassLoader) method if (this.applicationContext != null) { try { Method eclMethod = configuration.getClass().getMethod("externalClassLoader", ClassLoader.class); ReflectionUtils.invokeMethod(eclMethod, configuration, this.applicationContext.getClassLoader()); } catch (NoSuchMethodException ex) { // Ignore - no Hibernate Validator 5.2+ or similar provider } } MessageInterpolator targetInterpolator = this.messageInterpolator; if (targetInterpolator == null) { targetInterpolator = configuration.getDefaultMessageInterpolator(); } configuration.messageInterpolator(new LocaleContextMessageInterpolator(targetInterpolator)); if (this.traversableResolver != null) { configuration.traversableResolver(this.traversableResolver); } ConstraintValidatorFactory targetConstraintValidatorFactory = this.constraintValidatorFactory; if (targetConstraintValidatorFactory == null && this.applicationContext != null) { targetConstraintValidatorFactory = new SpringConstraintValidatorFactory(this.applicationContext.getAutowireCapableBeanFactory()); } if (targetConstraintValidatorFactory != null) { configuration.constraintValidatorFactory(targetConstraintValidatorFactory); } if (this.parameterNameDiscoverer != null) { configureParameterNameProviderIfPossible(configuration); } if (this.mappingLocations != null) { for (Resource location : this.mappingLocations) { try { configuration.addMapping(location.getInputStream()); } catch (IOException ex) { throw new IllegalStateException("Cannot read mapping resource: " + location); } } } for (Map.Entry<String, String> entry : this.validationPropertyMap.entrySet()) { configuration.addProperty(entry.getKey(), entry.getValue()); } // Allow for custom post-processing before we actually build the ValidatorFactory. postProcessConfiguration(configuration); this.validatorFactory = configuration.buildValidatorFactory(); setTargetValidator(this.validatorFactory.getValidator()); } private void configureParameterNameProviderIfPossible(Configuration<?> configuration) { try { Class<?> parameterNameProviderClass = ClassUtils.forName("javax.validation.ParameterNameProvider", getClass().getClassLoader()); Method parameterNameProviderMethod = Configuration.class.getMethod("parameterNameProvider", parameterNameProviderClass); final Object defaultProvider = ReflectionUtils.invokeMethod( Configuration.class.getMethod("getDefaultParameterNameProvider"), configuration); final ParameterNameDiscoverer discoverer = this.parameterNameDiscoverer; Object parameterNameProvider = Proxy.newProxyInstance(getClass().getClassLoader(), new Class<?>[] {parameterNameProviderClass}, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getName().equals("getParameterNames")) { String[] result = null; if (args[0] instanceof Constructor) { result = discoverer.getParameterNames((Constructor<?>) args[0]); } else if (args[0] instanceof Method) { result = discoverer.getParameterNames((Method) args[0]); } if (result != null) { return Arrays.asList(result); } else { try { return method.invoke(defaultProvider, args); } catch (InvocationTargetException ex) { throw ex.getTargetException(); } } } else { // toString, equals, hashCode try { return method.invoke(this, args); } catch (InvocationTargetException ex) { throw ex.getTargetException(); } } } }); ReflectionUtils.invokeMethod(parameterNameProviderMethod, configuration, parameterNameProvider); } catch (Throwable ex) { // Bean Validation 1.1 API not available - simply not applying the ParameterNameDiscoverer } } /** * Post-process the given Bean Validation configuration, * adding to or overriding any of its settings. * <p>Invoked right before building the {@link ValidatorFactory}. * @param configuration the Configuration object, pre-populated with * settings driven by LocalValidatorFactoryBean's properties */ protected void postProcessConfiguration(Configuration<?> configuration) { } @Override public Validator getValidator() { Assert.notNull(this.validatorFactory, "No target ValidatorFactory set"); return this.validatorFactory.getValidator(); } @Override public ValidatorContext usingContext() { Assert.notNull(this.validatorFactory, "No target ValidatorFactory set"); return this.validatorFactory.usingContext(); } @Override public MessageInterpolator getMessageInterpolator() { Assert.notNull(this.validatorFactory, "No target ValidatorFactory set"); return this.validatorFactory.getMessageInterpolator(); } @Override public TraversableResolver getTraversableResolver() { Assert.notNull(this.validatorFactory, "No target ValidatorFactory set"); return this.validatorFactory.getTraversableResolver(); } @Override public ConstraintValidatorFactory getConstraintValidatorFactory() { Assert.notNull(this.validatorFactory, "No target ValidatorFactory set"); return this.validatorFactory.getConstraintValidatorFactory(); } @Override @SuppressWarnings("unchecked") public <T> T unwrap(Class<T> type) { if (type == null || !ValidatorFactory.class.isAssignableFrom(type)) { try { return super.unwrap(type); } catch (ValidationException ex) { // ignore - we'll try ValidatorFactory unwrapping next } } try { return this.validatorFactory.unwrap(type); } catch (ValidationException ex) { // ignore if just being asked for ValidatorFactory if (ValidatorFactory.class == type) { return (T) this.validatorFactory; } throw ex; } } public void close() { if (closeMethod != null && this.validatorFactory != null) { ReflectionUtils.invokeMethod(closeMethod, this.validatorFactory); } } @Override public void destroy() { close(); } /** * Inner class to avoid a hard-coded Hibernate Validator dependency. */ private static class HibernateValidatorDelegate { public static MessageInterpolator buildMessageInterpolator(MessageSource messageSource) { return new ResourceBundleMessageInterpolator(new MessageSourceResourceBundleLocator(messageSource)); } } }
package pf2ecs.model; public enum Size{ TINY, SMALL, MEDIUM, LARGE, HUGE, GARGANTUAN }
/*********************************************************************************************************************** * Copyright (C) 2010-2013 by the Stratosphere project (http://stratosphere.eu) * * 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. **********************************************************************************************************************/ /** * This file is based on source code from the Hadoop Project (http://hadoop.apache.org/), licensed by the Apache * Software Foundation (ASF) under the Apache License, Version 2.0. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. */ package eu.stratosphere.nephele.ipc; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.lang.reflect.Constructor; import java.net.BindException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.net.UnknownHostException; import java.nio.ByteBuffer; import java.nio.channels.CancelledKeyException; import java.nio.channels.ClosedChannelException; import java.nio.channels.ReadableByteChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.nio.channels.WritableByteChannel; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Random; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.LinkedBlockingQueue; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import eu.stratosphere.core.io.IOReadableWritable; import eu.stratosphere.core.io.StringRecord; import eu.stratosphere.core.protocols.VersionedProtocol; import eu.stratosphere.util.ClassUtils; /** * An abstract IPC service. IPC calls take a single {@link Writable} as a * parameter, and return a {@link Writable} as their value. A service runs on * a port and is defined by a parameter class and a value class. * * @see Client */ public abstract class Server { public static final Log LOG = LogFactory.getLog(Server.class); private static final Class<?>[] EMPTY_ARRAY = new Class[] {}; public static final ByteBuffer HEADER = ByteBuffer.wrap("crpc".getBytes()); /** * How many calls/handler are allowed in the queue. */ private static final int MAX_QUEUE_SIZE_PER_HANDLER = 100; private static final ThreadLocal<Server> SERVER = new ThreadLocal<Server>(); private static final Map<String, Class<? extends VersionedProtocol>> PROTOCOL_CACHE = new ConcurrentHashMap<String, Class<? extends VersionedProtocol>>(); static Class<? extends VersionedProtocol> getProtocolClass(String protocolName) throws ClassNotFoundException { Class<? extends VersionedProtocol> protocol = PROTOCOL_CACHE.get(protocolName); if (protocol == null) { protocol = (Class<? extends VersionedProtocol>) ClassUtils.getProtocolByName(protocolName); PROTOCOL_CACHE.put(protocolName, protocol); } return protocol; } /** * Returns the server instance called under or null. May be called under {@link #call(Writable, long)} * implementations, and under {@link Writable} methods of paramters and return values. Permits applications to * access * the server context. */ public static Server get() { return SERVER.get(); } /** * This is set to Call object before Handler invokes an RPC and reset * after the call returns. */ private static final ThreadLocal<Call> CurCall = new ThreadLocal<Call>(); /** * Returns the remote side ip address when invoked inside an RPC * Returns null incase of an error. */ public static InetAddress getRemoteIp() { Call call = CurCall.get(); if (call != null) { return call.connection.socket.getInetAddress(); } return null; } /** * Returns remote address as a string when invoked inside an RPC. * Returns null in case of an error. */ public static String getRemoteAddress() { InetAddress addr = getRemoteIp(); return (addr == null) ? null : addr.getHostAddress(); } private String bindAddress; private int port; // port we listen on private int handlerCount; // number of handler threads private Class<? extends IOReadableWritable> invocationClass; // invocation class to call private int maxIdleTime; // the maximum idle time after // which a client may be disconnected private int thresholdIdleConnections; // the number of idle connections // after which we will start // cleaning up idle // connections int maxConnectionsToNuke; // the max number of // connections to nuke // during a cleanup private int maxQueueSize; private int socketSendBufferSize; private final boolean tcpNoDelay; // if T then disable Nagle's Algorithm volatile private boolean running = true; // true while server runs private BlockingQueue<Call> callQueue; // queued calls private List<Connection> connectionList = Collections.synchronizedList(new LinkedList<Connection>()); // maintain a list // of client connections private Listener listener = null; private Responder responder = null; private int numConnections = 0; private Handler[] handlers = null; /** * A convenience method to bind to a given address and report * better exceptions if the address is not a valid host. * * @param socket * the socket to bind * @param address * the address to bind to * @param backlog * the number of connections allowed in the queue * @throws BindException * if the address can't be bound * @throws UnknownHostException * if the address isn't a valid host name * @throws IOException * other random errors from bind */ public static void bind(ServerSocket socket, InetSocketAddress address, int backlog) throws IOException { try { socket.bind(address, backlog); } catch (BindException e) { BindException bindException = new BindException("Problem binding to " + address + " : " + e.getMessage()); bindException.initCause(e); throw bindException; } catch (SocketException e) { // If they try to bind to a different host's address, give a better // error message. if ("Unresolved address".equals(e.getMessage())) { throw new UnknownHostException("Invalid hostname for server: " + address.getHostName()); } else { throw e; } } } /** A call queued for handling. */ private static class Call { private int id; // the client's call id private IOReadableWritable param; // the parameter passed private Connection connection; // connection to client private long timestamp; // the time received when response is null // the time served when response is not null private ByteBuffer response; // the response for this call public Call(int id, IOReadableWritable param, Connection connection) { this.id = id; this.param = param; this.connection = connection; this.timestamp = System.currentTimeMillis(); this.response = null; } @Override public String toString() { return param.toString() + " from " + connection.toString(); } public void setResponse(ByteBuffer response) { this.response = response; } } /** Listens on the socket. Creates jobs for the handler threads */ private class Listener extends Thread { private ServerSocketChannel acceptChannel = null; // the accept channel private Selector selector = null; // the selector that we use for the server private InetSocketAddress address; // the address we bind at private Random rand = new Random(); private long lastCleanupRunTime = 0; // the last time when a cleanup connec- // -tion (for idle connections) ran private long cleanupInterval = 10000; // the minimum interval between // two cleanup runs private int backlogLength = 128; private volatile boolean shutDown = false; public Listener() throws IOException { address = new InetSocketAddress(bindAddress, port); // Create a new server socket and set to non blocking mode acceptChannel = ServerSocketChannel.open(); acceptChannel.configureBlocking(false); // Bind the server socket to the local host and port bind(acceptChannel.socket(), address, backlogLength); port = acceptChannel.socket().getLocalPort(); // Could be an ephemeral port // create a selector; selector = Selector.open(); // Register accepts on the server socket with the selector. acceptChannel.register(selector, SelectionKey.OP_ACCEPT); this.setName("IPC Server listener on " + port); this.setDaemon(true); } /** * cleanup connections from connectionList. Choose a random range * to scan and also have a limit on the number of the connections * that will be cleanedup per run. The criteria for cleanup is the time * for which the connection was idle. If 'force' is true then all * connections will be looked at for the cleanup. */ private void cleanupConnections(boolean force) { if (force || numConnections > thresholdIdleConnections) { long currentTime = System.currentTimeMillis(); if (!force && (currentTime - lastCleanupRunTime) < cleanupInterval) { return; } int start = 0; int end = numConnections - 1; if (!force) { start = rand.nextInt() % numConnections; end = rand.nextInt() % numConnections; int temp; if (end < start) { temp = start; start = end; end = temp; } } int i = start; int numNuked = 0; while (i <= end) { Connection c; synchronized (connectionList) { try { c = connectionList.get(i); } catch (Exception e) { return; } } if (c.timedOut(currentTime)) { closeConnection(c); numNuked++; end--; c = null; if (!force && numNuked == maxConnectionsToNuke) { break; } } else { i++; } } lastCleanupRunTime = System.currentTimeMillis(); } } @Override public void run() { LOG.debug(getName() + ": starting"); SERVER.set(Server.this); while (running) { SelectionKey key = null; try { selector.select(); Iterator<SelectionKey> iter = selector.selectedKeys().iterator(); while (iter.hasNext()) { key = iter.next(); iter.remove(); try { if (key.isValid()) { if (key.isAcceptable()) { doAccept(key); } else if (key.isReadable()) { doRead(key); } } } catch (IOException e) { } key = null; } } catch (OutOfMemoryError e) { // we can run out of memory if we have too many threads // log the event and sleep for a minute and give // some thread(s) a chance to finish LOG.warn("Out of Memory in server select", e); closeCurrentConnection(key, e); cleanupConnections(true); try { Thread.sleep(60000); } catch (Exception ie) { } } catch (InterruptedException e) { if (running) { // unexpected -- log it LOG.info(getName() + " caught: " + e.toString()); } } catch (Exception e) { closeCurrentConnection(key, e); } cleanupConnections(false); } LOG.debug("Stopping " + this.getName()); synchronized (this) { try { acceptChannel.close(); selector.close(); } catch (IOException e) { } selector = null; acceptChannel = null; // clean up all connections while (!connectionList.isEmpty()) { closeConnection(connectionList.remove(0)); } } this.shutDown = true; } public boolean isShutDown() { return this.shutDown; } private void closeCurrentConnection(SelectionKey key, Throwable e) { if (key != null) { Connection c = (Connection) key.attachment(); if (c != null) { closeConnection(c); c = null; } } } InetSocketAddress getAddress() { return (InetSocketAddress) acceptChannel.socket().getLocalSocketAddress(); } void doAccept(SelectionKey key) throws IOException, OutOfMemoryError { Connection c = null; ServerSocketChannel server = (ServerSocketChannel) key.channel(); // accept up to 10 connections for (int i = 0; i < 10; i++) { SocketChannel channel = server.accept(); if (channel == null) { return; } channel.configureBlocking(false); channel.socket().setTcpNoDelay(tcpNoDelay); SelectionKey readKey = channel.register(selector, SelectionKey.OP_READ); c = new Connection(readKey, channel, System.currentTimeMillis()); readKey.attach(c); synchronized (connectionList) { connectionList.add(numConnections, c); numConnections++; } } } void doRead(SelectionKey key) throws InterruptedException { int count = 0; Connection c = (Connection) key.attachment(); if (c == null) { return; } c.setLastContact(System.currentTimeMillis()); try { count = c.readAndProcess(); } catch (InterruptedException ieo) { LOG.info(getName() + ": readAndProcess caught InterruptedException", ieo); throw ieo; } catch (Exception e) { LOG.info(getName() + ": readAndProcess threw exception " + e + ". Count of bytes read: " + count, e); count = -1; // so that the (count < 0) block is executed } if (count < 0) { closeConnection(c); c = null; } else { c.setLastContact(System.currentTimeMillis()); } } synchronized void doStop() { if (selector != null) { selector.wakeup(); Thread.yield(); } if (acceptChannel != null) { try { acceptChannel.socket().close(); } catch (IOException e) { LOG.info(getName() + ":Exception in closing listener socket. " + e); } } } } // Sends responses of RPC back to clients. private class Responder extends Thread { private Selector writeSelector; private int pending; // connections waiting to register final static int PURGE_INTERVAL = 900000; // 15mins private volatile boolean shutDown = false; Responder() throws IOException { this.setName("IPC Server Responder"); this.setDaemon(true); writeSelector = Selector.open(); // create a selector pending = 0; } @Override public void run() { LOG.debug(getName() + ": starting"); SERVER.set(Server.this); long lastPurgeTime = 0; // last check for old calls. while (running) { try { waitPending(); // If a channel is being registered, wait. writeSelector.select(PURGE_INTERVAL); Iterator<SelectionKey> iter = writeSelector.selectedKeys().iterator(); while (iter.hasNext()) { SelectionKey key = iter.next(); iter.remove(); try { if (key.isValid() && key.isWritable()) { doAsyncWrite(key); } } catch (IOException e) { LOG.info(getName() + ": doAsyncWrite threw exception " + e); } } long now = System.currentTimeMillis(); if (now < lastPurgeTime + PURGE_INTERVAL) { continue; } lastPurgeTime = now; // // If there were some calls that have not been sent out for a // long time, discard them. // ArrayList<Call> calls; // get the list of channels from list of keys. synchronized (writeSelector.keys()) { calls = new ArrayList<Call>(writeSelector.keys().size()); iter = writeSelector.keys().iterator(); while (iter.hasNext()) { SelectionKey key = iter.next(); Call call = (Call) key.attachment(); if (call != null && key.channel() == call.connection.channel) { calls.add(call); } } } for (Call call : calls) { try { doPurge(call, now); } catch (IOException e) { LOG.warn("Error in purging old calls " + e); } } } catch (OutOfMemoryError e) { // // we can run out of memory if we have too many threads // log the event and sleep for a minute and give // some thread(s) a chance to finish // LOG.warn("Out of Memory in server select", e); try { Thread.sleep(60000); } catch (Exception ie) { } } catch (Exception e) { LOG.warn("Exception in Responder " + e.toString()); } } LOG.debug("Stopping " + this.getName()); this.shutDown = true; } public boolean isShutDown() { return this.shutDown; } private void doAsyncWrite(SelectionKey key) throws IOException { Call call = (Call) key.attachment(); if (call == null) { return; } if (key.channel() != call.connection.channel) { throw new IOException("doAsyncWrite: bad channel"); } synchronized (call.connection.responseQueue) { if (processResponse(call.connection.responseQueue, false)) { try { key.interestOps(0); } catch (CancelledKeyException e) { /* * The Listener/reader might have closed the socket. * We don't explicitly cancel the key, so not sure if this will * ever fire. * This warning could be removed. */ LOG.warn("Exception while changing ops : " + e); } } } } // // Remove calls that have been pending in the responseQueue // for a long time. // private void doPurge(Call call, long now) throws IOException { LinkedList<Call> responseQueue = call.connection.responseQueue; synchronized (responseQueue) { Iterator<Call> iter = responseQueue.listIterator(0); while (iter.hasNext()) { call = iter.next(); if (now > call.timestamp + PURGE_INTERVAL) { closeConnection(call.connection); break; } } } } // Processes one response. Returns true if there are no more pending // data for this channel. // private boolean processResponse(LinkedList<Call> responseQueue, boolean inHandler) throws IOException { boolean error = true; boolean done = false; // there is more data for this channel. int numElements = 0; Call call = null; try { synchronized (responseQueue) { // // If there are no items for this channel, then we are done // numElements = responseQueue.size(); if (numElements == 0) { error = false; return true; // no more data for this channel. } // // Extract the first call // call = responseQueue.removeFirst(); SocketChannel channel = call.connection.channel; // // Send as much data as we can in the non-blocking fashion // int numBytes = channelWrite(channel, call.response); if (numBytes < 0) { return true; } if (!call.response.hasRemaining()) { call.connection.decRpcCount(); if (numElements == 1) { // last call fully processes. done = true; // no more data for this channel. } else { done = false; // more calls pending to be sent. } } else { // // If we were unable to write the entire response out, then // insert in Selector queue. // call.connection.responseQueue.addFirst(call); if (inHandler) { // set the serve time when the response has to be sent later call.timestamp = System.currentTimeMillis(); incPending(); try { // Wakeup the thread blocked on select, only then can the call // to channel.register() complete. writeSelector.wakeup(); channel.register(writeSelector, SelectionKey.OP_WRITE, call); } catch (ClosedChannelException e) { // Its ok. channel might be closed else where. done = true; } finally { decPending(); } } } error = false; // everything went off well } } finally { if (error && call != null) { LOG.warn(getName() + ", call " + call + ": output error"); done = true; // error. no more data for this channel. closeConnection(call.connection); } } return done; } // // Enqueue a response from the application. // void doRespond(Call call) throws IOException { synchronized (call.connection.responseQueue) { call.connection.responseQueue.addLast(call); if (call.connection.responseQueue.size() == 1) { processResponse(call.connection.responseQueue, true); } } } private synchronized void incPending() { // call waiting to be enqueued. pending++; } private synchronized void decPending() { // call done enqueueing. pending--; notify(); } private synchronized void waitPending() throws InterruptedException { while (pending > 0) { wait(); } } } /** Reads calls from a connection and queues them for handling. */ private class Connection { private boolean headerRead = false; // if the connection header that // follows version is read. private boolean protocolRead = false; private SocketChannel channel; private ByteBuffer data; private ByteBuffer dataLengthBuffer; private LinkedList<Call> responseQueue; private volatile int rpcCount = 0; // number of outstanding rpcs private long lastContact; private int dataLength; private Socket socket; // Cache the remote host & port info so that even if the socket is // disconnected, we can say where it used to connect to. private String hostAddress; private int remotePort; ConnectionHeader header = new ConnectionHeader(); Class<? extends VersionedProtocol> protocol; public Connection(SelectionKey key, SocketChannel channel, long lastContact) { this.channel = channel; this.lastContact = lastContact; this.data = null; this.dataLengthBuffer = ByteBuffer.allocate(4); this.socket = channel.socket(); InetAddress addr = socket.getInetAddress(); if (addr == null) { this.hostAddress = "*Unknown*"; } else { this.hostAddress = addr.getHostAddress(); } this.remotePort = socket.getPort(); this.responseQueue = new LinkedList<Call>(); if (socketSendBufferSize != 0) { try { socket.setSendBufferSize(socketSendBufferSize); } catch (IOException e) { LOG.warn("Connection: unable to set socket send buffer size to " + socketSendBufferSize); } } } @Override public String toString() { return getHostAddress() + ":" + remotePort; } public String getHostAddress() { return hostAddress; } public void setLastContact(long lastContact) { this.lastContact = lastContact; } /* Return true if the connection has no outstanding rpc */ private boolean isIdle() { return rpcCount == 0; } /* Decrement the outstanding RPC count */ private void decRpcCount() { rpcCount--; } /* Increment the outstanding RPC count */ private void incRpcCount() { rpcCount++; } private boolean timedOut(long currentTime) { if (isIdle() && currentTime - lastContact > maxIdleTime) { return true; } return false; } public int readAndProcess() throws IOException, InterruptedException { while (true) { /* * Read at most one RPC. If the header is not read completely yet * then iterate until we read first RPC or until there is no data left. */ int count = -1; if (dataLengthBuffer.remaining() > 0) { count = channelRead(channel, dataLengthBuffer); if (count < 0 || dataLengthBuffer.remaining() > 0) { return count; } } if (!headerRead) { dataLengthBuffer.flip(); if (!HEADER.equals(dataLengthBuffer)) { // Warning is ok since this is not supposed to happen. LOG.warn("Incorrect header from " + hostAddress + ":" + remotePort); return -1; } dataLengthBuffer.clear(); headerRead = true; continue; } if (data == null) { dataLengthBuffer.flip(); dataLength = dataLengthBuffer.getInt(); if (dataLength == Client.PING_CALL_ID) { dataLengthBuffer.clear(); return 0; // ping message } data = ByteBuffer.allocate(dataLength); incRpcCount(); // Increment the rpc count } count = channelRead(channel, data); if (data.remaining() == 0) { dataLengthBuffer.clear(); data.flip(); if (protocolRead) { processData(); data = null; return count; } else { processProtocol(); protocolRead = true; data = null; // Authorizitation is intenionally left out continue; } } return count; } } // / Reads the connection header following version private void processProtocol() throws IOException { DataInputStream in = new DataInputStream(new ByteArrayInputStream(data.array())); header.read(in); try { String protocolClassName = header.getProtocol(); if (protocolClassName != null) { protocol = getProtocolClass(header.getProtocol()); } } catch (ClassNotFoundException cnfe) { LOG.error(cnfe); throw new IOException("Unknown protocol: " + header.getProtocol()); } } private void processData() throws IOException, InterruptedException { DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data.array())); int id = dis.readInt(); // try to read an id IOReadableWritable invocation = newInstance(invocationClass); // read param invocation.read(dis); Call call = new Call(id, invocation, this); callQueue.put(call); // queue the call; maybe blocked here } private synchronized void close() throws IOException { data = null; dataLengthBuffer = null; if (!channel.isOpen()) { return; } try { socket.shutdownOutput(); } catch (Exception e) { } if (channel.isOpen()) { try { channel.close(); } catch (Exception e) { } } try { socket.close(); } catch (Exception e) { } } } /** Handles queued calls . */ private class Handler extends Thread { private volatile boolean shutDown = false; public Handler(int instanceNumber) { this.setDaemon(true); this.setName("IPC Server handler " + instanceNumber + " on " + port); } @Override public void run() { LOG.debug(getName() + ": starting"); SERVER.set(Server.this); ByteArrayOutputStream buf = new ByteArrayOutputStream(10240); while (running) { try { final Call call = callQueue.take(); // pop the queue; maybe blocked here String errorClass = null; String error = null; IOReadableWritable value = null; CurCall.set(call); value = call(call.connection.protocol, call.param, call.timestamp); CurCall.set(null); setupResponse(buf, call, (error == null) ? Status.SUCCESS : Status.ERROR, value, errorClass, error); responder.doRespond(call); } catch (InterruptedException e) { if (running) { // unexpected -- log it LOG.error(getName() + " caught: ", e); } } catch (Exception e) { LOG.error(getName() + " caught: ", e); } } LOG.debug(getName() + ": exiting"); this.shutDown = true; } public boolean isShutDown() { return this.shutDown; } } protected Server(String bindAddress, int port, Class<? extends IOReadableWritable> paramClass, int handlerCount) throws IOException { this(bindAddress, port, paramClass, handlerCount, Integer.toString(port)); } /** * Constructs a server listening on the named port and address. Parameters passed must * be of the named class. The <code>handlerCount</handlerCount> determines * the number of handler threads that will be used to process calls. */ protected Server(String bindAddress, int port, Class<? extends IOReadableWritable> invocationClass, int handlerCount, String serverName) throws IOException { this.bindAddress = bindAddress; this.port = port; this.invocationClass = invocationClass; this.handlerCount = handlerCount; this.socketSendBufferSize = 0; this.maxQueueSize = handlerCount * MAX_QUEUE_SIZE_PER_HANDLER; this.callQueue = new LinkedBlockingQueue<Call>(maxQueueSize); this.maxIdleTime = 2 * 1000; this.maxConnectionsToNuke = 10; this.thresholdIdleConnections = 4000; // Start the listener here and let it bind to the port listener = new Listener(); this.port = listener.getAddress().getPort(); this.tcpNoDelay = false; // Create the responder here responder = new Responder(); } private void closeConnection(Connection connection) { synchronized (connectionList) { if (connectionList.remove(connection)) { numConnections--; } } try { connection.close(); } catch (IOException e) { } } /** * Setup response for the IPC Call. * * @param response * buffer to serialize the response into * @param call * {@link Call} to which we are setting up the response * @param status * {@link Status} of the IPC call * @param rv * return value for the IPC Call, if the call was successful * @param errorClass * error class, if the the call failed * @param error * error message, if the call failed * @throws IOException */ private void setupResponse(ByteArrayOutputStream response, Call call, Status status, IOReadableWritable rv, String errorClass, String error) throws IOException { response.reset(); DataOutputStream out = new DataOutputStream(response); out.writeInt(call.id); // write call id out.writeInt(status.state); // write status if (status == Status.SUCCESS) { if (rv == null) { out.writeBoolean(false); } else { out.writeBoolean(true); StringRecord.writeString(out, rv.getClass().getName()); rv.write(out); } } else { StringRecord.writeString(out, errorClass); StringRecord.writeString(out, error); } call.setResponse(ByteBuffer.wrap(response.toByteArray())); } /** Sets the socket buffer size used for responding to RPCs */ public void setSocketSendBufSize(int size) { this.socketSendBufferSize = size; } /** Starts the service. Must be called before any calls will be handled. */ public synchronized void start() throws IOException { responder.start(); listener.start(); handlers = new Handler[handlerCount]; for (int i = 0; i < handlerCount; i++) { handlers[i] = new Handler(i); handlers[i].start(); } } /** Stops the service. No new calls will be handled after this is called. */ public synchronized void stop() { LOG.debug("Stopping server on " + port); running = false; if (handlers != null) { for (int i = 0; i < handlerCount; i++) { if (handlers[i] != null) { handlers[i].interrupt(); } } } listener.interrupt(); listener.doStop(); responder.interrupt(); notifyAll(); // Wait until shut down of handlers is complete if (this.handlers != null) { while (true) { int i = 0; for (; i < this.handlerCount; i++) { if (this.handlers[i] != null) { if (!this.handlers[i].isShutDown()) { break; } } } if (i < this.handlerCount) { try { wait(100); } catch (InterruptedException e) { break; } } else { // exit while loop break; } } } // Wait until shut down of responder is complete while (!this.responder.isShutDown()) { try { wait(100); } catch (InterruptedException e) { break; } } // Wait until shut down of listener is complete while (!this.listener.isShutDown()) { try { wait(100); } catch (InterruptedException e) { break; } } } /** * Wait for the server to be stopped. * Does not wait for all subthreads to finish. * See {@link #stop()}. */ public synchronized void join() throws InterruptedException { while (running) { wait(); } } /** * Return the socket (ip+port) on which the RPC server is listening to. * * @return the socket (ip+port) on which the RPC server is listening to. */ public synchronized InetSocketAddress getListenerAddress() { return listener.getAddress(); } /** Called for each call. */ public abstract IOReadableWritable call(Class<?> protocol, IOReadableWritable param, long receiveTime) throws IOException; /** * The number of open RPC conections * * @return the number of open rpc connections */ public int getNumOpenConnections() { return numConnections; } /** * The number of rpc calls in the queue. * * @return The number of rpc calls in the queue. */ public int getCallQueueLen() { return callQueue.size(); } /** * When the read or write buffer size is larger than this limit, i/o will be * done in chunks of this size. Most RPC requests and responses would be * be smaller. */ private static int NIO_BUFFER_LIMIT = 8 * 1024; // should not be more than 64KB. /** * This is a wrapper around {@link WritableByteChannel#write(ByteBuffer)}. * If the amount of data is large, it writes to channel in smaller chunks. * This is to avoid jdk from creating many direct buffers as the size of * buffer increases. This also minimizes extra copies in NIO layer * as a result of multiple write operations required to write a large * buffer. * * @see WritableByteChannel#write(ByteBuffer) */ private static int channelWrite(WritableByteChannel channel, ByteBuffer buffer) throws IOException { return (buffer.remaining() <= NIO_BUFFER_LIMIT) ? channel.write(buffer) : channelIO(null, channel, buffer); } /** * This is a wrapper around {@link ReadableByteChannel#read(ByteBuffer)}. * If the amount of data is large, it writes to channel in smaller chunks. * This is to avoid jdk from creating many direct buffers as the size of * ByteBuffer increases. There should not be any performance degredation. * * @see ReadableByteChannel#read(ByteBuffer) */ private static int channelRead(ReadableByteChannel channel, ByteBuffer buffer) throws IOException { return (buffer.remaining() <= NIO_BUFFER_LIMIT) ? channel.read(buffer) : channelIO(channel, null, buffer); } /** * Helper for {@link #channelRead(ReadableByteChannel, ByteBuffer)} and * {@link #channelWrite(WritableByteChannel, ByteBuffer)}. Only * one of readCh or writeCh should be non-null. * * @see #channelRead(ReadableByteChannel, ByteBuffer) * @see #channelWrite(WritableByteChannel, ByteBuffer) */ private static int channelIO(ReadableByteChannel readCh, WritableByteChannel writeCh, ByteBuffer buf) throws IOException { int originalLimit = buf.limit(); int initialRemaining = buf.remaining(); int ret = 0; while (buf.remaining() > 0) { try { int ioSize = Math.min(buf.remaining(), NIO_BUFFER_LIMIT); buf.limit(buf.position() + ioSize); ret = (readCh == null) ? writeCh.write(buf) : readCh.read(buf); if (ret < ioSize) { break; } } finally { buf.limit(originalLimit); } } int nBytes = initialRemaining - buf.remaining(); return (nBytes > 0) ? nBytes : ret; } public static <T> T newInstance(Class<T> theClass) { T result; Constructor<T> meth = null; try { meth = theClass.getDeclaredConstructor(EMPTY_ARRAY); meth.setAccessible(true); result = meth.newInstance(); } catch (Exception e) { throw new RuntimeException(e); } 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 com.bluenimble.platform.apis.mgm.utils; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import com.bluenimble.platform.Lang; import com.bluenimble.platform.api.Api; import com.bluenimble.platform.api.ApiAccessDeniedException; import com.bluenimble.platform.api.ApiService; import com.bluenimble.platform.api.ApiSpace; import com.bluenimble.platform.api.DescribeOption; import com.bluenimble.platform.api.security.ApiConsumer; import com.bluenimble.platform.json.JsonObject; public class MgmUtils { public static final String TemplatesFolder = "api-templates"; public static final String TemplatesFile = "templates.json"; private static final String VerbosePostfix = "-v"; private static final Map<String, DescribeOption.Option> DescribeOptions = new HashMap<String, DescribeOption.Option> (); static { for (DescribeOption.Option o : DescribeOption.Option.values ()) { DescribeOptions.put (o.name ().toLowerCase (), o); } } public static ApiSpace space (ApiConsumer consumer, Api api) throws ApiAccessDeniedException { String spaceNs = (String)consumer.get (ApiConsumer.Fields.Space); if (Lang.isNullOrEmpty (spaceNs)) { throw new ApiAccessDeniedException ("space not found in key pair"); } return api.space ().space (spaceNs); } public static Api api (ApiConsumer consumer, Api api, String apiNs) throws ApiAccessDeniedException { return space (consumer, api).api (apiNs); } public static DescribeOption [] options (String spec, DescribeOption _default) { if (Lang.isNullOrEmpty (spec)) { if (_default == null) { return null; } return new DescribeOption [] { _default}; } Set<DescribeOption> options = new HashSet<DescribeOption> (); String [] aOptions = Lang.split (spec, Lang.COMMA, true); for (String o : aOptions) { boolean verbose = false; o = o.toLowerCase (); if (o.endsWith (VerbosePostfix)) { o = o.substring (0, o.length () - VerbosePostfix.length ()); verbose = true; } String optName = o; String offsetAndLength = null; int indexOfColon = o.indexOf (Lang.COLON); if (indexOfColon > 0) { optName = o.substring (0, indexOfColon).trim (); offsetAndLength = o.substring (indexOfColon + 1).trim (); } DescribeOption.Option option = DescribeOptions.get (optName); if (option == null) { continue; } int offset = 0; int length = -1; if (!Lang.isNullOrEmpty (offsetAndLength)) { int indexOfDash = o.indexOf (Lang.DASH); if (indexOfDash > 0) { try { offset = Integer.valueOf (offsetAndLength.substring (0, indexOfDash).trim ()); } catch (NumberFormatException nfex) { // IGNORE, default to 0 } try { length = Integer.valueOf (offsetAndLength.substring (indexOfDash + 1).trim ()); } catch (NumberFormatException nfex) { // IGNORE, default to -1 } } else { try { length = Integer.valueOf (offsetAndLength); } catch (NumberFormatException nfex) { // IGNORE, default to -1 } } } options.add (new DescribeOption (option, verbose, offset, length)); } DescribeOption [] array = new DescribeOption [options.size ()]; options.toArray (array); return array; } public static boolean isSecure (ApiService service) { JsonObject security = service.getSecurity (); return security == null || !security.containsKey (ApiService.Spec.Security.Enabled) || security.get (ApiService.Spec.Security.Enabled) == "true"; } }
package com.bjsxt.domain; import com.baomidou.mybatisplus.annotation.*; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.Date; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * @author PengChenyu * @since 2021-06-10 16:59:16 */ /** * 平台用户 */ @ApiModel(value = "com-bjsxt-domain-SysUser") @Data @AllArgsConstructor @NoArgsConstructor @TableName(value = "sys_user") public class SysUser { /** * 主键 */ @TableId(value = "id", type = IdType.INPUT) @ApiModelProperty(value = "主键") private Long id; /** * 账号 */ @TableField(value = "username") @ApiModelProperty(value = "账号") private String username; /** * 密码 */ @TableField(value = "`password`") @ApiModelProperty(value = "密码") private String password; /** * 姓名 */ @TableField(value = "fullname") @ApiModelProperty(value = "姓名") private String fullname; /** * 手机号 */ @TableField(value = "mobile") @ApiModelProperty(value = "手机号") private String mobile; /** * 邮箱 */ @TableField(value = "email") @ApiModelProperty(value = "邮箱") private String email; /** * 状态 0-无效; 1-有效; */ @TableField(value = "`status`") @ApiModelProperty(value = "状态 0-无效; 1-有效;") private Byte status; /** * 创建人 */ @TableField(value = "create_by") @ApiModelProperty(value = "创建人") private Long createBy; /** * 修改人 */ @TableField(value = "modify_by", fill = FieldFill.UPDATE) @ApiModelProperty(value = "修改人") private Long modifyBy; /** * 创建时间 */ @TableField(value = "created", fill = FieldFill.INSERT) @ApiModelProperty(value = "创建时间") private Date created; /** * 修改时间 */ @TableField(value = "last_update_time", fill = FieldFill.UPDATE) @ApiModelProperty(value = "修改时间") private Date lastUpdateTime; /** * 角色的IDS */ @ApiModelProperty(value = "角色的IDS") @TableField(exist = false) private String role_strings; }
package jkind.api.ui.counterexample; import org.eclipse.jface.viewers.ColumnLabelProvider; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.widgets.Display; public class CounterexampleNameLabelProvider extends ColumnLabelProvider { @Override public String getText(Object element) { if (element instanceof SignalGroup) { SignalGroup group = (SignalGroup) element; return group.getName(); } else if (element instanceof CategoryHeader) { CategoryHeader header = (CategoryHeader) element; return header.getCategory(); } return ""; } @Override public Color getForeground(Object element) { if (element instanceof CategoryHeader) { return Display.getCurrent().getSystemColor(CategoryHeader.FOREGROUND_COLOR); } return null; } @Override public Color getBackground(Object element) { if (element instanceof CategoryHeader) { return Display.getCurrent().getSystemColor(CategoryHeader.BACKGROUND_COLOR); } return null; } }
package com.banking.core.dto.customer; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonValue; public enum CustType { INDIVIDUAL("Individual"), CORPORATE("Corporate"), ASSOCIATION("Association"); private String value; CustType(String value) { this.value = value; } @JsonValue public String getValue() { return value; } public void setValue(String value) { this.value = value; } @Override public String toString() { return value; } }
package win.himike.regionselector; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("win.himike.regionselector", appContext.getPackageName()); } }
package org.jmisb.api.klv.st1108.st1108_2; import org.jmisb.api.klv.ArrayBuilder; import org.jmisb.api.klv.st1108.IInterpretabilityQualityMetadataValue; import org.jmisb.core.klv.PrimitiveConverter; /** * Chip Edge Intensity (ST 1108.2 Tag 12). * * <p>Edge intensity (EI) is calculated from the Sobel horizontal and vertical filtered versions of * the input sub-image (chip) rows and columns. * * <p>See ST 1108.2 Section 7.12. */ public class ChipEdgeIntensity implements IInterpretabilityQualityMetadataValue { private int intensity; private static final int MIN_VALUE = 0; private static final int MAX_VALUE = 1000; private static final int REQUIRED_BYTES = 2; /** * Create from value. * * @param intensity The edge intensity. */ public ChipEdgeIntensity(int intensity) { if (intensity < MIN_VALUE || intensity > MAX_VALUE) { throw new IllegalArgumentException( this.getDisplayName() + " value must be in range [0,1000]"); } this.intensity = intensity; } /** * Create from encoded bytes. * * @param bytes Byte array of length 2 bytes. */ public ChipEdgeIntensity(byte[] bytes) { if (bytes.length != REQUIRED_BYTES) { throw new IllegalArgumentException( this.getDisplayName() + " encoding is two byte unsigned integer"); } intensity = PrimitiveConverter.toUint16(bytes); } /** * Get the intensity. * * @return The intensity. */ public int getIntensity() { return intensity; } @Override public String getDisplayableValue() { return String.format("%d", intensity); } @Override public final String getDisplayName() { return "Chip Edge Intensity"; } @Override public void appendBytesToBuilder(ArrayBuilder arrayBuilder) { arrayBuilder.appendAsOID(LegacyIQMetadataKey.ChipEdgeIntensity.getIdentifier()); byte[] valueBytes = PrimitiveConverter.uint16ToBytes(intensity); arrayBuilder.appendAsBerLength(valueBytes.length); arrayBuilder.append(valueBytes); } }
package org.apereo.cas.interrupt; import org.apereo.cas.authentication.Authentication; import org.apereo.cas.authentication.Credential; import org.apereo.cas.authentication.principal.Service; import org.apereo.cas.services.RegisteredService; /** * This is {@link InterruptInquirer}. * * @author Misagh Moayyed * @since 5.2.0 */ @FunctionalInterface public interface InterruptInquirer { /** * Inquire interrupt response. * * @param authentication the authentication * @param registeredService the registered service * @param service the service * @param credential the credential * @return the interrupt response */ InterruptResponse inquire(Authentication authentication, RegisteredService registeredService, Service service, Credential credential); }
package com.aquaman.security.admin.service; import com.aquaman.security.admin.entity.domain.RoleMenu; import com.baomidou.mybatisplus.extension.service.IService; import java.util.List; /** * <p> * 服务类 * </p> * * @author wei wang * @since 2019-03-05 */ public interface IRoleMenuService extends IService<RoleMenu> { /** * 通过roleId集合查询菜单集合 * @param roleIds */ List<String> findMenuIdsByRoleIds(List<Long> roleIds); /** * 通过roleId查询菜单 * @param roleId */ RoleMenu findMenuIdsByRoleId(Long roleId); }
/* * Copyright © 2014 - 2020 Leipzig University (Database Research 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 org.gradoop.storage.impl.hbase; import com.google.common.collect.Lists; import org.gradoop.common.exceptions.UnsupportedTypeException; import org.gradoop.common.model.api.entities.Edge; import org.gradoop.common.model.api.entities.GraphHead; import org.gradoop.common.model.api.entities.Vertex; import org.gradoop.common.model.api.entities.VertexFactory; import org.gradoop.common.model.impl.id.GradoopId; import org.gradoop.common.model.impl.id.GradoopIdSet; import org.gradoop.common.model.impl.pojo.EPGMEdge; import org.gradoop.common.model.impl.pojo.EPGMGraphHead; import org.gradoop.common.model.impl.pojo.EPGMVertex; import org.gradoop.common.model.impl.pojo.EPGMVertexFactory; import org.gradoop.common.model.impl.properties.Properties; import org.gradoop.common.util.AsciiGraphLoader; import org.gradoop.storage.common.iterator.ClosableIterator; import org.gradoop.storage.hbase.impl.HBaseEPGMStore; import org.testng.annotations.Test; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.PriorityQueue; import java.util.Queue; import static org.gradoop.common.GradoopTestUtils.*; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; /** * Test class of {@link HBaseEPGMStore} with main I/O functionality. */ public class HBaseEPGMStoreTest extends GradoopHBaseTestBase { /** * Creates persistent graph, vertex and edge data. Writes data to HBase, * closes the store, opens it and reads/validates the data again. * * @throws IOException on failure */ @Test public void writeCloseOpenReadTest() throws IOException { HBaseEPGMStore graphStore = createEmptyEPGMStore(); AsciiGraphLoader<EPGMGraphHead, EPGMVertex, EPGMEdge> loader = getMinimalFullFeaturedGraphLoader(); EPGMGraphHead graphHead = loader.getGraphHeads().iterator().next(); EPGMVertex vertex = loader.getVertices().iterator().next(); EPGMEdge edge = loader.getEdges().iterator().next(); graphStore.writeGraphHead(graphHead); graphStore.writeVertex(vertex); graphStore.writeEdge(edge); // re-open graphStore.close(); graphStore = openEPGMStore(); // validate validateGraphHead(graphStore, graphHead); validateVertex(graphStore, vertex); validateEdge(graphStore, edge); graphStore.close(); } /** * Creates persistent graph, vertex and edge data. Writes data to HBase, * closes the store, opens it and reads/validates the data again. * * @throws IOException on failure */ @Test public void writeCloseOpenReadTestWithPrefix() throws IOException { String prefix = "test."; HBaseEPGMStore graphStore = createEmptyEPGMStore(prefix); AsciiGraphLoader<EPGMGraphHead, EPGMVertex, EPGMEdge> loader = getMinimalFullFeaturedGraphLoader(); EPGMGraphHead graphHead = loader.getGraphHeads().iterator().next(); EPGMVertex vertex = loader.getVertices().iterator().next(); EPGMEdge edge = loader.getEdges().iterator().next(); graphStore.writeGraphHead(graphHead); graphStore.writeVertex(vertex); graphStore.writeEdge(edge); // re-open graphStore.close(); graphStore = openEPGMStore(prefix); // validate validateGraphHead(graphStore, graphHead); validateVertex(graphStore, vertex); validateEdge(graphStore, edge); graphStore.close(); } /** * Creates persistent graph, vertex and edge data. Writes data to HBase, * flushes the tables and reads/validates the data. * * @throws IOException on failure */ @Test public void writeFlushReadTest() throws IOException { HBaseEPGMStore graphStore = createEmptyEPGMStore(); graphStore.setAutoFlush(false); AsciiGraphLoader<EPGMGraphHead, EPGMVertex, EPGMEdge> loader = getMinimalFullFeaturedGraphLoader(); EPGMGraphHead graphHead = loader.getGraphHeads().iterator().next(); EPGMVertex vertex = loader.getVertices().iterator().next(); EPGMEdge edge = loader.getEdges().iterator().next(); graphStore.writeGraphHead(graphHead); graphStore.writeVertex(vertex); graphStore.writeEdge(edge); // flush changes graphStore.flush(); // validate validateGraphHead(graphStore, graphHead); validateVertex(graphStore, vertex); validateEdge(graphStore, edge); graphStore.close(); } /** * Stores social network data, loads it again and checks for element data * equality. * * @throws IOException if read to or write from store fails */ @Test public void iteratorTest() throws IOException { HBaseEPGMStore graphStore = createEmptyEPGMStore(); List<EPGMVertex> vertices = Lists.newArrayList(getSocialVertices()); List<EPGMEdge> edges = Lists.newArrayList(getSocialEdges()); List<EPGMGraphHead> graphHeads = Lists.newArrayList(getSocialGraphHeads()); // write social graph to HBase for (EPGMGraphHead g : graphHeads) { graphStore.writeGraphHead(g); } for (EPGMVertex v : vertices) { graphStore.writeVertex(v); } for (EPGMEdge e : edges) { graphStore.writeEdge(e); } graphStore.flush(); // graph heads validateElementCollections( graphHeads, graphStore.getGraphSpace().readRemainsAndClose() ); // vertices validateElementCollections( vertices, graphStore.getVertexSpace().readRemainsAndClose() ); validateGraphElementCollections( vertices, graphStore.getVertexSpace().readRemainsAndClose() ); // edges validateElementCollections( edges, graphStore.getEdgeSpace().readRemainsAndClose() ); validateGraphElementCollections( edges, graphStore.getEdgeSpace().readRemainsAndClose() ); graphStore.close(); } /** * Tries to add an unsupported property type {@link Queue} as property value. * * @throws IOException on failure */ @Test(expectedExceptions = UnsupportedTypeException.class) public void wrongPropertyTypeTest() throws IOException { HBaseEPGMStore graphStore = createEmptyEPGMStore(); VertexFactory<EPGMVertex> vertexFactory = new EPGMVertexFactory(); // Queue is not supported by final Queue<String> value = new PriorityQueue<>(); GradoopId vertexID = GradoopId.get(); final String label = "A"; Properties props = Properties.create(); props.set("k1", value); final GradoopIdSet graphs = new GradoopIdSet(); EPGMVertex vertex = vertexFactory.initVertex(vertexID, label, props, graphs); graphStore.writeVertex(vertex); } /** * Checks if property values are read correctly. * * @throws IOException on failure */ @Test public void propertyTypeTest() throws IOException { HBaseEPGMStore graphStore = createEmptyEPGMStore(); VertexFactory<EPGMVertex> vertexFactory = new EPGMVertexFactory(); final GradoopId vertexID = GradoopId.get(); final String label = "A"; Properties properties = Properties.createFromMap(SUPPORTED_PROPERTIES); final GradoopIdSet graphs = new GradoopIdSet(); // write to store graphStore.writeVertex(vertexFactory.initVertex(vertexID, label, properties, graphs)); graphStore.flush(); // read from store EPGMVertex v = graphStore.readVertex(vertexID); assert v != null; List<String> propertyKeys = Lists.newArrayList(v.getPropertyKeys()); assertEquals(propertyKeys.size(), properties.size()); for (String propertyKey : propertyKeys) { switch (propertyKey) { case KEY_0: assertTrue(v.getPropertyValue(propertyKey).isNull()); assertEquals(v.getPropertyValue(propertyKey).getObject(), NULL_VAL_0); break; case KEY_1: assertTrue(v.getPropertyValue(propertyKey).isBoolean()); assertEquals(v.getPropertyValue(propertyKey).getBoolean(), BOOL_VAL_1); break; case KEY_2: assertTrue(v.getPropertyValue(propertyKey).isInt()); assertEquals(v.getPropertyValue(propertyKey).getInt(), INT_VAL_2); break; case KEY_3: assertTrue(v.getPropertyValue(propertyKey).isLong()); assertEquals(v.getPropertyValue(propertyKey).getLong(), LONG_VAL_3); break; case KEY_4: assertTrue(v.getPropertyValue(propertyKey).isFloat()); assertEquals(v.getPropertyValue(propertyKey).getFloat(), FLOAT_VAL_4, 0); break; case KEY_5: assertTrue(v.getPropertyValue(propertyKey).isDouble()); assertEquals(v.getPropertyValue(propertyKey).getDouble(), DOUBLE_VAL_5, 0); break; case KEY_6: assertTrue(v.getPropertyValue(propertyKey).isString()); assertEquals(v.getPropertyValue(propertyKey).getString(), STRING_VAL_6); break; case KEY_7: assertTrue(v.getPropertyValue(propertyKey).isBigDecimal()); assertEquals(v.getPropertyValue(propertyKey).getBigDecimal(), BIG_DECIMAL_VAL_7); break; case KEY_8: assertTrue(v.getPropertyValue(propertyKey).isGradoopId()); assertEquals(v.getPropertyValue(propertyKey).getGradoopId(), GRADOOP_ID_VAL_8); break; case KEY_9: assertTrue(v.getPropertyValue(propertyKey).isMap()); assertEquals(v.getPropertyValue(propertyKey).getMap(), MAP_VAL_9); break; case KEY_a: assertTrue(v.getPropertyValue(propertyKey).isList()); assertEquals(v.getPropertyValue(propertyKey).getList(), LIST_VAL_a); break; case KEY_b: assertTrue(v.getPropertyValue(propertyKey).isDate()); assertEquals(v.getPropertyValue(propertyKey).getDate(), DATE_VAL_b); break; case KEY_c: assertTrue(v.getPropertyValue(propertyKey).isTime()); assertEquals(v.getPropertyValue(propertyKey).getTime(), TIME_VAL_c); break; case KEY_d: assertTrue(v.getPropertyValue(propertyKey).isDateTime()); assertEquals(v.getPropertyValue(propertyKey).getDateTime(), DATETIME_VAL_d); break; case KEY_e: assertTrue(v.getPropertyValue(propertyKey).isShort()); assertEquals(v.getPropertyValue(propertyKey).getShort(), SHORT_VAL_e); break; case KEY_f: assertTrue(v.getPropertyValue(propertyKey).isSet()); assertEquals(v.getPropertyValue(propertyKey).getSet(), SET_VAL_f); break; default: break; } } graphStore.close(); } /** * Test the truncate tables functionality. */ @Test public void truncateTablesTest() throws IOException { HBaseEPGMStore store = createEmptyEPGMStore("truncateTest"); AsciiGraphLoader<EPGMGraphHead, EPGMVertex, EPGMEdge> loader = getMinimalFullFeaturedGraphLoader(); checkIfStoreIsEmpty("Store was not empty before writing anything.", store); // Now write something to the store, check if it was written (i.e. the store is not empty). EPGMGraphHead graphHead = loader.getGraphHeads().iterator().next(); EPGMVertex vertex = loader.getVertices().iterator().next(); EPGMEdge edge = loader.getEdges().iterator().next(); store.writeGraphHead(graphHead); store.writeVertex(vertex); store.writeEdge(edge); store.flush(); validateGraphHead(store, graphHead); validateVertex(store, vertex); validateEdge(store, edge); // Now truncate and check if the store if empty afterwards. store.truncateTables(); checkIfStoreIsEmpty("Store was not empty after truncating.", store); // Finally check if we can write elements. store.writeGraphHead(graphHead); store.writeVertex(vertex); store.writeEdge(edge); store.close(); } /** * Check if all tables of are store are empty. * * @param message The messenge used in the assertion. * @param store The HBase store to check. * @throws IOException when accessing the store fails. */ private void checkIfStoreIsEmpty(String message, HBaseEPGMStore store) throws IOException { for (ClosableIterator<?> space : Arrays.asList(store.getGraphSpace(), store.getVertexSpace(), store.getEdgeSpace())) { boolean hasNext = space.hasNext(); // Make sure to close the iterator before the assertion. space.close(); assertFalse(hasNext, message); } } private AsciiGraphLoader<EPGMGraphHead, EPGMVertex, EPGMEdge> getMinimalFullFeaturedGraphLoader() { String asciiGraph = ":G{k:\"v\"}[(v:V{k:\"v\"}),(v)-[:e{k:\"v\"}]->(v)]"; return AsciiGraphLoader.fromString(asciiGraph, getEPGMElementFactoryProvider()); } private void validateGraphHead(HBaseEPGMStore graphStore, EPGMGraphHead originalGraphHead) throws IOException { GraphHead loadedGraphHead = graphStore.readGraph(originalGraphHead.getId()); validateElements(originalGraphHead, loadedGraphHead); } private void validateVertex(HBaseEPGMStore graphStore, EPGMVertex originalVertex) throws IOException { Vertex loadedVertex = graphStore.readVertex(originalVertex.getId()); validateElements(originalVertex, loadedVertex); validateGraphElements(originalVertex, loadedVertex); } private void validateEdge(HBaseEPGMStore graphStore, EPGMEdge originalEdge) throws IOException { Edge loadedEdge = graphStore.readEdge(originalEdge.getId()); validateElements(originalEdge, loadedEdge); validateGraphElements(originalEdge, loadedEdge); assert loadedEdge != null; assertEquals(loadedEdge.getSourceId(), originalEdge.getSourceId(), "source vertex mismatch"); assertEquals(loadedEdge.getTargetId(), originalEdge.getTargetId(), "target vertex mismatch"); } }
package com.smartdevicelink.proxy.interfaces; import com.smartdevicelink.proxy.rpc.PutFileResponse; public interface IPutFileResponseListener { public void onPutFileResponse(PutFileResponse response); public void onPutFileStreamError(Exception e, String info); }
// // ======================================================================== // Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd. // ------------------------------------------------------------------------ // All rights reserved. This program and the accompanying materials // are made available under the terms of the Eclipse Public License v1.0 // and Apache License v2.0 which accompanies this distribution. // // The Eclipse Public License is available at // http://www.eclipse.org/legal/epl-v10.html // // The Apache License v2.0 is available at // http://www.opensource.org/licenses/apache2.0.php // // You may elect to redistribute this code under either of these licenses. // ======================================================================== // package org.eclipse.jetty.jaas.callback; import java.io.IOException; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.callback.UnsupportedCallbackException; public abstract class AbstractCallbackHandler implements CallbackHandler { protected String _userName; protected Object _credential; public void setUserName (String userName) { _userName = userName; } public String getUserName () { return _userName; } public void setCredential (Object credential) { _credential = credential; } public Object getCredential () { return _credential; } public void handle (Callback[] callbacks) throws IOException, UnsupportedCallbackException { } }
// Copyright 2019 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 // // 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. /** * SamSessionErrorReason.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter. */ package com.google.api.ads.admanager.axis.v201911; public class SamSessionErrorReason implements java.io.Serializable { private java.lang.String _value_; private static java.util.HashMap _table_ = new java.util.HashMap(); // Constructor protected SamSessionErrorReason(java.lang.String value) { _value_ = value; _table_.put(_value_,this); } public static final java.lang.String _COULD_NOT_REGISTER_SESSION = "COULD_NOT_REGISTER_SESSION"; public static final java.lang.String _MALFORMED_SESSION_ID = "MALFORMED_SESSION_ID"; public static final java.lang.String _UNKNOWN = "UNKNOWN"; public static final SamSessionErrorReason COULD_NOT_REGISTER_SESSION = new SamSessionErrorReason(_COULD_NOT_REGISTER_SESSION); public static final SamSessionErrorReason MALFORMED_SESSION_ID = new SamSessionErrorReason(_MALFORMED_SESSION_ID); public static final SamSessionErrorReason UNKNOWN = new SamSessionErrorReason(_UNKNOWN); public java.lang.String getValue() { return _value_;} public static SamSessionErrorReason fromValue(java.lang.String value) throws java.lang.IllegalArgumentException { SamSessionErrorReason enumeration = (SamSessionErrorReason) _table_.get(value); if (enumeration==null) throw new java.lang.IllegalArgumentException(); return enumeration; } public static SamSessionErrorReason fromString(java.lang.String value) throws java.lang.IllegalArgumentException { return fromValue(value); } public boolean equals(java.lang.Object obj) {return (obj == this);} public int hashCode() { return toString().hashCode();} public java.lang.String toString() { return _value_;} public java.lang.Object readResolve() throws java.io.ObjectStreamException { return fromValue(_value_);} public static org.apache.axis.encoding.Serializer getSerializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.EnumSerializer( _javaType, _xmlType); } public static org.apache.axis.encoding.Deserializer getDeserializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.EnumDeserializer( _javaType, _xmlType); } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(SamSessionErrorReason.class); static { typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201911", "SamSessionError.Reason")); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } }
package hah.htetaunghlaing.popular_movies; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("hah.htetaunghlaing.popular_movies", appContext.getPackageName()); } }
package com.wangcaitao.admin.system.entity; import com.wangcaitao.common.entity.BaseQuery; import lombok.Data; import lombok.EqualsAndHashCode; /** * @author wangcaitao */ @EqualsAndHashCode(callSuper = true) @Data public class DictQuery extends BaseQuery { private static final long serialVersionUID = 5164054702799460823L; /** * 父级编码 */ private String parentCode; /** * 编码 */ private String code; /** * 名称 */ private String name; }
package com.alipay.api.domain; import com.alipay.api.AlipayObject; import com.alipay.api.internal.mapping.ApiField; /** * 服务地址 * * @author auto create * @since 1.0, 2019-12-04 19:59:24 */ public class ServiceAddressSimpleVO extends AlipayObject { private static final long serialVersionUID = 6197883255955771264L; /** * 维度 */ @ApiField("latitude") private String latitude; /** * 经度 */ @ApiField("longitude") private String longitude; /** * poi详细地址 */ @ApiField("poi_address") private String poiAddress; /** * 高德的poi code */ @ApiField("poi_code") private String poiCode; /** * poi的名称 */ @ApiField("poi_name") private String poiName; public String getLatitude() { return this.latitude; } public void setLatitude(String latitude) { this.latitude = latitude; } public String getLongitude() { return this.longitude; } public void setLongitude(String longitude) { this.longitude = longitude; } public String getPoiAddress() { return this.poiAddress; } public void setPoiAddress(String poiAddress) { this.poiAddress = poiAddress; } public String getPoiCode() { return this.poiCode; } public void setPoiCode(String poiCode) { this.poiCode = poiCode; } public String getPoiName() { return this.poiName; } public void setPoiName(String poiName) { this.poiName = poiName; } }
package sql; import java.sql.*; import java.util.ArrayList; public class ReadJdbc { private ArrayList<String> username = new ArrayList<String>(10); private ArrayList<Integer> score = new ArrayList<Integer>(10); public ReadJdbc(String mapName) { try { Class.forName("com.mysql.cj.jdbc.Driver").newInstance(); } catch (Exception ex) { } Connection conn = null; Statement stmt = null; try { conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/TD", "root", ""); stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("select map.username, map.score from " + mapName + " map" + " ORDER BY score DESC"); while (rs.next() || username.size() > 10) { username.add(rs.getString(1)); score.add(rs.getInt(2)); } } catch (SQLException ex) { // handle any errors System.out.println("SQLException: " + ex.getMessage()); System.out.println("SQLState: " + ex.getSQLState()); System.out.println("VendorError: " + ex.getErrorCode()); } finally { try { if (stmt != null) stmt.close(); } catch (SQLException se2) { } try { if (conn != null) conn.close(); } catch (SQLException se) { } } } public ArrayList<String> getUsername() { return username; } public void setUsername(ArrayList<String> username) { this.username = username; } public ArrayList<Integer> getScore() { return score; } public void setScore(ArrayList<Integer> score) { this.score = score; } }
/* * Copyright 2017 Red Hat, 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.wildfly.test.security.common.elytron; import static org.wildfly.common.Assert.checkNotNullParamWithNullPointerException; import static org.wildfly.test.security.common.ModelNodeUtil.setIfNotNull; import java.util.HashMap; import java.util.Map; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.client.ModelControllerClient; import org.jboss.as.controller.operations.common.Util; import org.jboss.as.test.integration.management.util.CLIWrapper; import org.jboss.as.test.integration.security.common.CoreUtils; import org.jboss.dmr.ModelNode; /** * Elytron 'dir-context' configuration. * * @author Josef Cacek */ public class DirContext extends AbstractConfigurableElement { private final String url; private final String authenticationContext; private final String authenticationLevel; private final Long connectionTimeout; private final CredentialReference credentialReference; private final Boolean enableConnectionPooling; private final String module; private final String principal; private final Map<String, String> properties; private final Long readTimeout; private final String referralMode; private final String sslContext; private DirContext(Builder builder) { super(builder); this.url = checkNotNullParamWithNullPointerException("builder.url", builder.url); this.authenticationContext = builder.authenticationContext; this.authenticationLevel = builder.authenticationLevel; this.connectionTimeout = builder.connectionTimeout; this.credentialReference = builder.credentialReference; this.enableConnectionPooling = builder.enableConnectionPooling; this.module = builder.module; this.principal = builder.principal; this.properties = new HashMap<>(builder.properties); this.readTimeout = builder.readTimeout; this.referralMode = builder.referralMode; this.sslContext = builder.sslContext; } @Override public void create(ModelControllerClient client, CLIWrapper cli) throws Exception { ModelNode op = Util .createAddOperation(PathAddress.pathAddress().append("subsystem", "elytron").append("dir-context", name)); op.get("url").set(url); setIfNotNull(op, "authentication-context", authenticationContext); setIfNotNull(op, "authentication-level", authenticationLevel); setIfNotNull(op, "connection-timeout", connectionTimeout); setIfNotNull(op, "credential-reference", credentialReference); setIfNotNull(op, "enable-connection-pooling", enableConnectionPooling); setIfNotNull(op, "module", module); setIfNotNull(op, "principal", principal); setIfNotNull(op, "properties", properties); setIfNotNull(op, "read-timeout", readTimeout); setIfNotNull(op, "referral-mode", referralMode); setIfNotNull(op, "ssl-context", sslContext); CoreUtils.applyUpdate(op, client); } @Override public void remove(ModelControllerClient client, CLIWrapper cli) throws Exception { CoreUtils.applyUpdate(Util.createRemoveOperation( PathAddress.pathAddress().append("subsystem", "elytron").append("dir-context", name)), client); } /** * Creates builder to build {@link DirContext}. * * @return created builder */ public static Builder builder() { return new Builder(); } /** * Builder to build {@link DirContext}. */ public static final class Builder extends AbstractConfigurableElement.Builder<Builder> { private String authenticationContext; private String authenticationLevel; private Long connectionTimeout; private CredentialReference credentialReference; private Boolean enableConnectionPooling; private String module; private String principal; private Map<String, String> properties = new HashMap<String, String>(); private Long readTimeout; private String referralMode; private String sslContext; private String url; private Builder() { } public Builder withAuthenticationContext(String authenticationContext) { this.authenticationContext = authenticationContext; return self(); } public Builder withAuthenticationLevel(String authenticationLevel) { this.authenticationLevel = authenticationLevel; return self(); } public Builder withConnectionTimeout(Long connectionTimeout) { this.connectionTimeout = connectionTimeout; return self(); } public Builder withCredentialReference(CredentialReference credentialReference) { this.credentialReference = credentialReference; return self(); } public Builder withEnableConnectionPooling(Boolean enableConnectionPooling) { this.enableConnectionPooling = enableConnectionPooling; return self(); } public Builder withModule(String module) { this.module = module; return self(); } public Builder withPrincipal(String principal) { this.principal = principal; return self(); } public Builder addProperty(String key, String value) { this.properties.put(key, value); return self(); } public Builder withReadTimeout(Long readTimeout) { this.readTimeout = readTimeout; return self(); } public Builder withReferralMode(String referralMode) { this.referralMode = referralMode; return self(); } public Builder withSslContext(String sslContext) { this.sslContext = sslContext; return self(); } public Builder withUrl(String url) { this.url = url; return self(); } public DirContext build() { return new DirContext(this); } @Override protected Builder self() { return this; } } }
package com.dongdongxia.my.jdk8.applet; import java.applet.Applet; import java.awt.Color; import java.awt.Graphics; /** * * <P>Description: 向窗口中输出 状态信息</P> * @ClassName: StatusWindow * @author java_liudong@163.com 2017年12月6日 下午4:19:25 */ /* * <applet width=500 height=900></applet> */ public class StatusWindow extends Applet { /** * @Fields serialVersionUID : TODO */ private static final long serialVersionUID = 1L; @Override public void init() { setBackground(Color.cyan); } @Override public void paint(Graphics g) { g.drawString("我是向窗口中输出的信息", 10, 20); showStatus("我是状态栏中输出的新"); // 这个会输出在窗口的下边框上面 } }
/* * Copyright (c) 2016-present, RxJava 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 io.reactivex.rxjava3.internal.util; import static org.junit.Assert.*; import java.io.IOException; import java.util.*; import java.util.concurrent.atomic.AtomicLong; import org.junit.Test; import org.reactivestreams.*; import io.reactivex.rxjava3.core.Observer; import io.reactivex.rxjava3.core.RxJavaTest; import io.reactivex.rxjava3.disposables.*; import io.reactivex.rxjava3.exceptions.*; import io.reactivex.rxjava3.functions.BooleanSupplier; import io.reactivex.rxjava3.internal.subscriptions.BooleanSubscription; import io.reactivex.rxjava3.observers.TestObserver; import io.reactivex.rxjava3.operators.SpscArrayQueue; import io.reactivex.rxjava3.subscribers.TestSubscriber; import io.reactivex.rxjava3.testsupport.TestHelper; public class QueueDrainHelperTest extends RxJavaTest { @Test public void isCancelled() { assertTrue(QueueDrainHelper.isCancelled(new BooleanSupplier() { @Override public boolean getAsBoolean() throws Exception { throw new IOException(); } })); } @Test public void requestMaxInt() { QueueDrainHelper.request(new Subscription() { @Override public void request(long n) { assertEquals(Integer.MAX_VALUE, n); } @Override public void cancel() { } }, Integer.MAX_VALUE); } @Test public void requestMinInt() { QueueDrainHelper.request(new Subscription() { @Override public void request(long n) { assertEquals(Long.MAX_VALUE, n); } @Override public void cancel() { } }, Integer.MIN_VALUE); } @Test public void requestAlmostMaxInt() { QueueDrainHelper.request(new Subscription() { @Override public void request(long n) { assertEquals(Integer.MAX_VALUE - 1, n); } @Override public void cancel() { } }, Integer.MAX_VALUE - 1); } @Test public void postCompleteEmpty() { TestSubscriber<Integer> ts = new TestSubscriber<>(); ArrayDeque<Integer> queue = new ArrayDeque<>(); AtomicLong state = new AtomicLong(); BooleanSupplier isCancelled = new BooleanSupplier() { @Override public boolean getAsBoolean() throws Exception { return false; } }; ts.onSubscribe(new BooleanSubscription()); QueueDrainHelper.postComplete(ts, queue, state, isCancelled); ts.assertResult(); } @Test public void postCompleteWithRequest() { TestSubscriber<Integer> ts = new TestSubscriber<>(); ArrayDeque<Integer> queue = new ArrayDeque<>(); AtomicLong state = new AtomicLong(); BooleanSupplier isCancelled = new BooleanSupplier() { @Override public boolean getAsBoolean() throws Exception { return false; } }; ts.onSubscribe(new BooleanSubscription()); queue.offer(1); state.getAndIncrement(); QueueDrainHelper.postComplete(ts, queue, state, isCancelled); ts.assertResult(1); } @Test public void completeRequestRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final TestSubscriber<Integer> ts = new TestSubscriber<>(); final ArrayDeque<Integer> queue = new ArrayDeque<>(); final AtomicLong state = new AtomicLong(); final BooleanSupplier isCancelled = new BooleanSupplier() { @Override public boolean getAsBoolean() throws Exception { return false; } }; ts.onSubscribe(new BooleanSubscription()); queue.offer(1); Runnable r1 = new Runnable() { @Override public void run() { QueueDrainHelper.postCompleteRequest(1, ts, queue, state, isCancelled); } }; Runnable r2 = new Runnable() { @Override public void run() { QueueDrainHelper.postComplete(ts, queue, state, isCancelled); } }; TestHelper.race(r1, r2); ts.assertResult(1); } } @Test public void postCompleteCancelled() { final TestSubscriber<Integer> ts = new TestSubscriber<>(); ArrayDeque<Integer> queue = new ArrayDeque<>(); AtomicLong state = new AtomicLong(); BooleanSupplier isCancelled = new BooleanSupplier() { @Override public boolean getAsBoolean() throws Exception { return ts.isCancelled(); } }; ts.onSubscribe(new BooleanSubscription()); queue.offer(1); state.getAndIncrement(); ts.cancel(); QueueDrainHelper.postComplete(ts, queue, state, isCancelled); ts.assertEmpty(); } @Test public void postCompleteCancelledAfterOne() { final TestSubscriber<Integer> ts = new TestSubscriber<Integer>() { @Override public void onNext(Integer t) { super.onNext(t); cancel(); } }; ArrayDeque<Integer> queue = new ArrayDeque<>(); AtomicLong state = new AtomicLong(); BooleanSupplier isCancelled = new BooleanSupplier() { @Override public boolean getAsBoolean() throws Exception { return ts.isCancelled(); } }; ts.onSubscribe(new BooleanSubscription()); queue.offer(1); state.getAndIncrement(); QueueDrainHelper.postComplete(ts, queue, state, isCancelled); ts.assertValue(1).assertNoErrors().assertNotComplete(); } @Test public void drainMaxLoopMissingBackpressure() { TestSubscriber<Integer> ts = new TestSubscriber<>(); ts.onSubscribe(new BooleanSubscription()); QueueDrain<Integer, Integer> qd = new QueueDrain<Integer, Integer>() { @Override public boolean cancelled() { return false; } @Override public boolean done() { return false; } @Override public Throwable error() { return null; } @Override public boolean enter() { return true; } @Override public long requested() { return 0; } @Override public long produced(long n) { return 0; } @Override public int leave(int m) { return 0; } @Override public boolean accept(Subscriber<? super Integer> a, Integer v) { return false; } }; SpscArrayQueue<Integer> q = new SpscArrayQueue<>(32); q.offer(1); QueueDrainHelper.drainMaxLoop(q, ts, false, null, qd); ts.assertFailure(MissingBackpressureException.class); } @Test public void drainMaxLoopMissingBackpressureWithResource() { TestSubscriber<Integer> ts = new TestSubscriber<>(); ts.onSubscribe(new BooleanSubscription()); QueueDrain<Integer, Integer> qd = new QueueDrain<Integer, Integer>() { @Override public boolean cancelled() { return false; } @Override public boolean done() { return false; } @Override public Throwable error() { return null; } @Override public boolean enter() { return true; } @Override public long requested() { return 0; } @Override public long produced(long n) { return 0; } @Override public int leave(int m) { return 0; } @Override public boolean accept(Subscriber<? super Integer> a, Integer v) { return false; } }; SpscArrayQueue<Integer> q = new SpscArrayQueue<>(32); q.offer(1); Disposable d = Disposable.empty(); QueueDrainHelper.drainMaxLoop(q, ts, false, d, qd); ts.assertFailure(MissingBackpressureException.class); assertTrue(d.isDisposed()); } @Test public void drainMaxLoopDontAccept() { TestSubscriber<Integer> ts = new TestSubscriber<>(); ts.onSubscribe(new BooleanSubscription()); QueueDrain<Integer, Integer> qd = new QueueDrain<Integer, Integer>() { @Override public boolean cancelled() { return false; } @Override public boolean done() { return false; } @Override public Throwable error() { return null; } @Override public boolean enter() { return true; } @Override public long requested() { return 1; } @Override public long produced(long n) { return 0; } @Override public int leave(int m) { return 0; } @Override public boolean accept(Subscriber<? super Integer> a, Integer v) { return false; } }; SpscArrayQueue<Integer> q = new SpscArrayQueue<>(32); q.offer(1); QueueDrainHelper.drainMaxLoop(q, ts, false, null, qd); ts.assertEmpty(); } @Test public void checkTerminatedDelayErrorEmpty() { TestSubscriber<Integer> ts = new TestSubscriber<>(); ts.onSubscribe(new BooleanSubscription()); QueueDrain<Integer, Integer> qd = new QueueDrain<Integer, Integer>() { @Override public boolean cancelled() { return false; } @Override public boolean done() { return false; } @Override public Throwable error() { return null; } @Override public boolean enter() { return true; } @Override public long requested() { return 0; } @Override public long produced(long n) { return 0; } @Override public int leave(int m) { return 0; } @Override public boolean accept(Subscriber<? super Integer> a, Integer v) { return false; } }; SpscArrayQueue<Integer> q = new SpscArrayQueue<>(32); QueueDrainHelper.checkTerminated(true, true, ts, true, q, qd); ts.assertResult(); } @Test public void checkTerminatedDelayErrorNonEmpty() { TestSubscriber<Integer> ts = new TestSubscriber<>(); ts.onSubscribe(new BooleanSubscription()); QueueDrain<Integer, Integer> qd = new QueueDrain<Integer, Integer>() { @Override public boolean cancelled() { return false; } @Override public boolean done() { return false; } @Override public Throwable error() { return null; } @Override public boolean enter() { return true; } @Override public long requested() { return 0; } @Override public long produced(long n) { return 0; } @Override public int leave(int m) { return 0; } @Override public boolean accept(Subscriber<? super Integer> a, Integer v) { return false; } }; SpscArrayQueue<Integer> q = new SpscArrayQueue<>(32); QueueDrainHelper.checkTerminated(true, false, ts, true, q, qd); ts.assertEmpty(); } @Test public void checkTerminatedDelayErrorEmptyError() { TestSubscriber<Integer> ts = new TestSubscriber<>(); ts.onSubscribe(new BooleanSubscription()); QueueDrain<Integer, Integer> qd = new QueueDrain<Integer, Integer>() { @Override public boolean cancelled() { return false; } @Override public boolean done() { return false; } @Override public Throwable error() { return new TestException(); } @Override public boolean enter() { return true; } @Override public long requested() { return 0; } @Override public long produced(long n) { return 0; } @Override public int leave(int m) { return 0; } @Override public boolean accept(Subscriber<? super Integer> a, Integer v) { return false; } }; SpscArrayQueue<Integer> q = new SpscArrayQueue<>(32); QueueDrainHelper.checkTerminated(true, true, ts, true, q, qd); ts.assertFailure(TestException.class); } @Test public void checkTerminatedNonDelayErrorError() { TestSubscriber<Integer> ts = new TestSubscriber<>(); ts.onSubscribe(new BooleanSubscription()); QueueDrain<Integer, Integer> qd = new QueueDrain<Integer, Integer>() { @Override public boolean cancelled() { return false; } @Override public boolean done() { return false; } @Override public Throwable error() { return new TestException(); } @Override public boolean enter() { return true; } @Override public long requested() { return 0; } @Override public long produced(long n) { return 0; } @Override public int leave(int m) { return 0; } @Override public boolean accept(Subscriber<? super Integer> a, Integer v) { return false; } }; SpscArrayQueue<Integer> q = new SpscArrayQueue<>(32); QueueDrainHelper.checkTerminated(true, false, ts, false, q, qd); ts.assertFailure(TestException.class); } @Test public void observerCheckTerminatedDelayErrorEmpty() { TestObserver<Integer> to = new TestObserver<>(); to.onSubscribe(Disposable.empty()); ObservableQueueDrain<Integer, Integer> qd = new ObservableQueueDrain<Integer, Integer>() { @Override public boolean cancelled() { return false; } @Override public boolean done() { return false; } @Override public Throwable error() { return null; } @Override public boolean enter() { return true; } @Override public int leave(int m) { return 0; } @Override public void accept(Observer<? super Integer> a, Integer v) { } }; SpscArrayQueue<Integer> q = new SpscArrayQueue<>(32); QueueDrainHelper.checkTerminated(true, true, to, true, q, null, qd); to.assertResult(); } @Test public void observerCheckTerminatedDelayErrorEmptyResource() { TestObserver<Integer> to = new TestObserver<>(); to.onSubscribe(Disposable.empty()); ObservableQueueDrain<Integer, Integer> qd = new ObservableQueueDrain<Integer, Integer>() { @Override public boolean cancelled() { return false; } @Override public boolean done() { return false; } @Override public Throwable error() { return null; } @Override public boolean enter() { return true; } @Override public int leave(int m) { return 0; } @Override public void accept(Observer<? super Integer> a, Integer v) { } }; SpscArrayQueue<Integer> q = new SpscArrayQueue<>(32); Disposable d = Disposable.empty(); QueueDrainHelper.checkTerminated(true, true, to, true, q, d, qd); to.assertResult(); assertTrue(d.isDisposed()); } @Test public void observerCheckTerminatedDelayErrorNonEmpty() { TestObserver<Integer> to = new TestObserver<>(); to.onSubscribe(Disposable.empty()); ObservableQueueDrain<Integer, Integer> qd = new ObservableQueueDrain<Integer, Integer>() { @Override public boolean cancelled() { return false; } @Override public boolean done() { return false; } @Override public Throwable error() { return null; } @Override public boolean enter() { return true; } @Override public int leave(int m) { return 0; } @Override public void accept(Observer<? super Integer> a, Integer v) { } }; SpscArrayQueue<Integer> q = new SpscArrayQueue<>(32); QueueDrainHelper.checkTerminated(true, false, to, true, q, null, qd); to.assertEmpty(); } @Test public void observerCheckTerminatedDelayErrorEmptyError() { TestObserver<Integer> to = new TestObserver<>(); to.onSubscribe(Disposable.empty()); ObservableQueueDrain<Integer, Integer> qd = new ObservableQueueDrain<Integer, Integer>() { @Override public boolean cancelled() { return false; } @Override public boolean done() { return false; } @Override public Throwable error() { return new TestException(); } @Override public boolean enter() { return true; } @Override public int leave(int m) { return 0; } @Override public void accept(Observer<? super Integer> a, Integer v) { } }; SpscArrayQueue<Integer> q = new SpscArrayQueue<>(32); QueueDrainHelper.checkTerminated(true, true, to, true, q, null, qd); to.assertFailure(TestException.class); } @Test public void observerCheckTerminatedNonDelayErrorError() { TestObserver<Integer> to = new TestObserver<>(); to.onSubscribe(Disposable.empty()); ObservableQueueDrain<Integer, Integer> qd = new ObservableQueueDrain<Integer, Integer>() { @Override public boolean cancelled() { return false; } @Override public boolean done() { return false; } @Override public Throwable error() { return new TestException(); } @Override public boolean enter() { return true; } @Override public int leave(int m) { return 0; } @Override public void accept(Observer<? super Integer> a, Integer v) { } }; SpscArrayQueue<Integer> q = new SpscArrayQueue<>(32); QueueDrainHelper.checkTerminated(true, false, to, false, q, null, qd); to.assertFailure(TestException.class); } @Test public void observerCheckTerminatedNonDelayErrorErrorResource() { TestObserver<Integer> to = new TestObserver<>(); to.onSubscribe(Disposable.empty()); ObservableQueueDrain<Integer, Integer> qd = new ObservableQueueDrain<Integer, Integer>() { @Override public boolean cancelled() { return false; } @Override public boolean done() { return false; } @Override public Throwable error() { return new TestException(); } @Override public boolean enter() { return true; } @Override public int leave(int m) { return 0; } @Override public void accept(Observer<? super Integer> a, Integer v) { } }; SpscArrayQueue<Integer> q = new SpscArrayQueue<>(32); Disposable d = Disposable.empty(); QueueDrainHelper.checkTerminated(true, false, to, false, q, d, qd); to.assertFailure(TestException.class); assertTrue(d.isDisposed()); } @Test public void postCompleteAlreadyComplete() { TestSubscriber<Integer> ts = new TestSubscriber<>(); Queue<Integer> q = new ArrayDeque<>(); q.offer(1); AtomicLong state = new AtomicLong(QueueDrainHelper.COMPLETED_MASK); QueueDrainHelper.postComplete(ts, q, state, new BooleanSupplier() { @Override public boolean getAsBoolean() throws Exception { return false; } }); } }
/* * Copyright (c) 2009-2018 jMonkeyEngine * 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 'jMonkeyEngine' 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 OWNER 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.jme3.gde.materialdefinition.dialog; import com.jme3.asset.ShaderNodeDefinitionKey; import com.jme3.gde.core.assets.ProjectAssetManager; import com.jme3.gde.core.util.TreeUtil; import com.jme3.gde.materialdefinition.editor.ShaderNodeDiagram; import com.jme3.gde.core.editor.icons.Icons; import com.jme3.gde.materialdefinition.utils.DocFormatter; import com.jme3.shader.Shader; import com.jme3.shader.ShaderNodeDefinition; import java.awt.Point; import java.awt.event.KeyEvent; import java.util.ArrayList; import java.util.List; import javax.swing.JScrollPane; import javax.swing.JTextPane; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreeNode; import javax.swing.tree.TreeSelectionModel; /** * * @author Nehon */ public class AddNodeDialog extends javax.swing.JDialog { private List<ShaderNodeDefinition> defList = new ArrayList<ShaderNodeDefinition>(); private final ShaderNodeDiagram diagram; private final Point clickPosition; private String path; /** * Creates new form NewJDialog */ public AddNodeDialog(java.awt.Frame parent, boolean modal, ProjectAssetManager mgr, ShaderNodeDiagram diagram, Point clickPosition) { super(parent, modal); this.diagram = diagram; initComponents(); loadDefs(mgr); fillList(mgr); this.clickPosition = clickPosition; } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel2 = new javax.swing.JPanel(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jSplitPane1 = new javax.swing.JSplitPane(); jPanel1 = new javax.swing.JPanel(); jScrollPane3 = new javax.swing.JScrollPane(); jTree1 = new javax.swing.JTree(); shaderNodesList = new javax.swing.JPanel(); jTabbedPane1 = new javax.swing.JTabbedPane(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Add a Shader Node"); setModal(true); jButton1.setText("ok"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jButton2.setMnemonic(KeyEvent.VK_ESCAPE); jButton2.setText("cancel"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(jButton2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton1) .addContainerGap()) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton1) .addComponent(jButton2)) ); jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Shader node definitions")); jScrollPane3.setViewportView(jTree1); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 236, Short.MAX_VALUE) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 468, Short.MAX_VALUE) ); jSplitPane1.setLeftComponent(jPanel1); shaderNodesList.setBorder(javax.swing.BorderFactory.createTitledBorder("Shader node definition")); javax.swing.GroupLayout shaderNodesListLayout = new javax.swing.GroupLayout(shaderNodesList); shaderNodesList.setLayout(shaderNodesListLayout); shaderNodesListLayout.setHorizontalGroup( shaderNodesListLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTabbedPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 339, Short.MAX_VALUE) ); shaderNodesListLayout.setVerticalGroup( shaderNodesListLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTabbedPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 468, Short.MAX_VALUE) ); jSplitPane1.setRightComponent(shaderNodesList); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jSplitPane1, javax.swing.GroupLayout.Alignment.LEADING) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jSplitPane1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed setVisible(false); }//GEN-LAST:event_jButton2ActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed setVisible(false); diagram.addNodesFromDefs(defList, path, clickPosition); }//GEN-LAST:event_jButton1ActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JSplitPane jSplitPane1; private javax.swing.JTabbedPane jTabbedPane1; private javax.swing.JTree jTree1; private javax.swing.JPanel shaderNodesList; // End of variables declaration//GEN-END:variables private void loadDefs(ProjectAssetManager mgr) { // defList.addAll(); // defList.addAll(mgr.getDependenciesShaderNodeDefs()); // List<ShaderNodeVariable> inputs = new ArrayList<ShaderNodeVariable>(); // inputs.add(new ShaderNodeVariable("vec2", "texCoord1")); // inputs.add(new ShaderNodeVariable("vec2", "texCoord2")); // List<ShaderNodeVariable> outputs = new ArrayList<ShaderNodeVariable>(); // outputs.add(new ShaderNodeVariable("vec2", "texCoord1")); // outputs.add(new ShaderNodeVariable("vec2", "texCoord2")); // ShaderNodeDefinition fogdef = new ShaderNodeDefinition("FogFactor", Shader.ShaderType.Vertex, "", ""); // fogdef.setInputs(inputs); // fogdef.setOutputs(outputs); // fogdef.setDocumentation( // " This Node is responsible for adding a fog contribution to a color according to a fogColor and a fogFactor.\n" // + " This node should be used with a FogFactor node that will be responsible to compute the fogFactor in the vertex shader.\n" // + " Inputs : \n" // + " color : the color on which the fog contribution will be added.\n" // + " fogFactor : the previously computed fog factor \n" // + " fogColor : the fog color\n" // + " Outputs : \n" // + " outColor : the color with fog contribution (usually assigned to Global.color) "); // // defList.add(fogdef); } private void createDoc(ShaderNodeDefinition def) { JTextPane doc = new JTextPane(); doc.setEditable(false); //doc.setBackground(new java.awt.Color(240, 240, 240)); doc.setMaximumSize(new java.awt.Dimension(300, 300)); doc.setMinimumSize(new java.awt.Dimension(300, 300)); doc.setPreferredSize(new java.awt.Dimension(300, 300)); JScrollPane defPanel = new JScrollPane(); defPanel.setViewportView(doc); jTabbedPane1.addTab(def.getName(), def.getType() == Shader.ShaderType.Vertex ? Icons.vert : Icons.frag, defPanel); doc.setText(""); DocFormatter.addDoc(def, doc.getStyledDocument()); doc.setCaretPosition(0); } private void fillList(final ProjectAssetManager mgr) { List<String> l = new ArrayList<String>(); l.addAll(mgr.getProjectShaderNodeDefs()); l.addAll(mgr.getDependenciesShaderNodeDefs()); String[] leaves = l.toArray(new String[l.size()]); TreeUtil.createTree(jTree1, leaves); TreeUtil.expandTree(jTree1, (TreeNode) jTree1.getModel().getRoot(), 10); jTree1.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); jTree1.addTreeSelectionListener(new TreeSelectionListener() { @Override public void valueChanged(TreeSelectionEvent e) { DefaultMutableTreeNode node = (DefaultMutableTreeNode) jTree1.getLastSelectedPathComponent(); if (node == null) { return; } if (node.isLeaf()) { jTabbedPane1.removeAll(); path = TreeUtil.getPath(node.getUserObjectPath()); path = path.substring(0, path.lastIndexOf("/")); ShaderNodeDefinitionKey k = new ShaderNodeDefinitionKey(path); k.setLoadDocumentation(true); defList = mgr.loadAsset(k); for (ShaderNodeDefinition def : defList) { createDoc(def); } } } }); } }
/* * Copyright 2002-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * $Id: ExtensionEvent.java,v 1.2 2004/02/16 23:00:27 minchau Exp $ */ package org.apache.xalan.trace; import java.lang.reflect.Constructor; import java.lang.reflect.Method; import org.apache.xalan.transformer.TransformerImpl; /** * An event representing an extension call. */ public class ExtensionEvent { public static final int DEFAULT_CONSTRUCTOR = 0; public static final int METHOD = 1; public static final int CONSTRUCTOR = 2; public final int m_callType; public final TransformerImpl m_transformer; public final Object m_method; public final Object m_instance; public final Object[] m_arguments; public ExtensionEvent(TransformerImpl transformer, Method method, Object instance, Object[] arguments) { m_transformer = transformer; m_method = method; m_instance = instance; m_arguments = arguments; m_callType = METHOD; } public ExtensionEvent(TransformerImpl transformer, Constructor constructor, Object[] arguments) { m_transformer = transformer; m_instance = null; m_arguments = arguments; m_method = constructor; m_callType = CONSTRUCTOR; } public ExtensionEvent(TransformerImpl transformer, Class clazz) { m_transformer = transformer; m_instance = null; m_arguments = null; m_method = clazz; m_callType = DEFAULT_CONSTRUCTOR; } }
/* * 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.as.v20180419.models; import com.tencentcloudapi.common.AbstractModel; import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.Expose; import java.util.HashMap; public class DeleteScheduledActionResponse extends AbstractModel{ /** * The unique request ID, which is returned for each request. RequestId is required for locating a problem. */ @SerializedName("RequestId") @Expose private String RequestId; /** * Get The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @return RequestId The unique request ID, which is returned for each request. RequestId is required for locating a problem. */ public String getRequestId() { return this.RequestId; } /** * Set The unique request ID, which is returned for each request. RequestId is required for locating a problem. * @param RequestId The unique request ID, which is returned for each request. RequestId is required for locating a problem. */ public void setRequestId(String RequestId) { this.RequestId = RequestId; } public DeleteScheduledActionResponse() { } /** * 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 DeleteScheduledActionResponse(DeleteScheduledActionResponse source) { if (source.RequestId != null) { this.RequestId = new String(source.RequestId); } } /** * Internal implementation, normal users should not use it. */ public void toMap(HashMap<String, String> map, String prefix) { this.setParamSimple(map, prefix + "RequestId", this.RequestId); } }
/** * Copyright 2011-2019 Asakusa Framework Team. * * 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.asakusafw.dag.compiler.codegen; import java.util.Optional; import java.util.function.Supplier; import com.asakusafw.dag.compiler.model.ClassData; import com.asakusafw.lang.compiler.api.DataModelLoader; import com.asakusafw.lang.compiler.common.DiagnosticException; import com.asakusafw.lang.compiler.model.description.ClassDescription; /** * An abstract super interface of class generator contexts. * @since 0.4.0 */ public interface ClassGeneratorContext { /** * Returns the current class loader. * @return the current class loader */ ClassLoader getClassLoader(); /** * Returns the current data model loader. * @return the current data model loader */ DataModelLoader getDataModelLoader(); /** * Returns a unique class name for the target category. * @param category the category name (must be a sub-package name) * @return the unique class name */ default ClassDescription getClassName(String category) { return getClassName(category, null); } /** * Returns a unique class name for the target category. * @param category the category name (must be a sub-package name) * @param hint the simple class name hint (nullable) * @return the unique class name */ ClassDescription getClassName(String category, String hint); /** * Adds a new Java class file. * @param data the class file contents * @return the target class description * @throws DiagnosticException if an error was occurred while adding the class file */ ClassDescription addClassFile(ClassData data); /** * Returns a cached class for the specified key. * @param key the cache key * @return the corresponded cache, or empty if there is no such a cached class * @see #addCache(Object, ClassDescription) */ Optional<ClassDescription> findCache(Object key); /** * Adds a class cache for the specified key only if cache is enabled. * @param key the cache key * @param target the target class * @see #findCache(Object) */ void addCache(Object key, ClassDescription target); /** * Returns a cached class or add a new class data if it has not been cached. * @param key the cache key * @param defaultValue the default class data if missing cached class * @return the added class data * @see #addCache(Object, ClassDescription) */ default ClassData cache(Object key, Supplier<? extends ClassData> defaultValue) { return findCache(key) .map(ClassData::new) .orElseGet(() -> { ClassData data = defaultValue.get(); addCache(key, data.getDescription()); return data; }); } /** * Forwarding for {@link ClassGeneratorContext}. */ public interface Forward extends ClassGeneratorContext { /** * Returns the forwarding target. * @return the forwarding target */ ClassGeneratorContext getForward(); @Override default ClassLoader getClassLoader() { return getForward().getClassLoader(); } @Override default DataModelLoader getDataModelLoader() { return getForward().getDataModelLoader(); } @Override default ClassDescription getClassName(String category) { return ClassGeneratorContext.super.getClassName(category); } @Override default ClassDescription getClassName(String category, String hint) { return getForward().getClassName(category, hint); } @Override default ClassDescription addClassFile(ClassData data) { return getForward().addClassFile(data); } @Override default void addCache(Object key, ClassDescription target) { getForward().addCache(key, target); } @Override default Optional<ClassDescription> findCache(Object key) { return getForward().findCache(key); } @Override default ClassData cache(Object key, Supplier<? extends ClassData> defaultValue) { return ClassGeneratorContext.super.cache(key, defaultValue); } } }
/* * ======================================================================== * * 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.manning.junitbook.ch19.util; import java.lang.reflect.Field; public class TestingHelper { private TestingHelper() { throw new UnsupportedOperationException("this class only provides static methods"); } private static Field getField(final Class<?> clazz, String fieldName) { Class<?> tmpClass = clazz; do { for ( Field field : tmpClass.getDeclaredFields() ) { String candidateName = field.getName(); if ( ! candidateName.equals(fieldName) ) { continue; } field.setAccessible(true); return field; } tmpClass = tmpClass.getSuperclass(); } while ( tmpClass != null ); throw new RuntimeException("Field '" + fieldName + "' not found on class " + clazz); } /** * Sets an object's field, using reflection. * @param object object to set the field * @param fieldName name of the field * @param newValue new value of the field */ public static void set( Object object, String fieldName, Object newValue ) { Field field = getField(object.getClass(), fieldName); try { field.set(object, newValue); } catch (IllegalAccessException e) { throw new RuntimeException( "Could not set value of field '" + fieldName + "' on object " + object + " to " + newValue, e ); } } /** * Gets the value of object's field, using reflection. * @param <T> type returned * @param object object to get the field from * @param fieldName name of the field * @return value of the field */ public static <T> T get(Object object, String fieldName) { Field field = getField(object.getClass(), fieldName); Object value; try { value = field.get(object); } catch (IllegalAccessException e) { throw new RuntimeException( "Could not get value of field '" + fieldName + "' from object " + object, e ); } @SuppressWarnings("unchecked") T castValue = (T) value; return castValue; } }
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2007, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library 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 Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * -------------------- * RectangleInsets.java * -------------------- * (C) Copyright 2004, 2005, 2007, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes: * -------- * 11-Feb-2004 : Version 1 (DG); * 14-Jun-2004 : Implemented Serializable (DG); * 02-Feb-2005 : Added new methods and renamed some existing methods (DG); * 22-Feb-2005 : Added a new constructor for convenience (DG); * 19-Apr-2005 : Changed order of parameters in constructors to match * java.awt.Insets (DG); * 16-Mar-2007 : Added default constructor (DG); * 21-Jun-2007 : Copied from JCommon (DG); * */ package org.jfree.chart.util; import java.awt.geom.Rectangle2D; import java.io.Serializable; /** * Represents the insets for a rectangle, specified in absolute or relative * terms. This class is immutable. */ public class RectangleInsets implements Serializable { /** For serialization. */ private static final long serialVersionUID = 1902273207559319996L; /** * A useful constant representing zero insets. */ public static final RectangleInsets ZERO_INSETS = new RectangleInsets( UnitType.ABSOLUTE, 0.0, 0.0, 0.0, 0.0); /** Absolute or relative units. */ private UnitType unitType; /** The top insets. */ private double top; /** The left insets. */ private double left; /** The bottom insets. */ private double bottom; /** The right insets. */ private double right; /** * Creates a new instance with all insets initialised to <code>1.0</code>. * * @since 1.0.9 */ public RectangleInsets() { this(1.0, 1.0, 1.0, 1.0); } /** * Creates a new instance with the specified insets (as 'absolute' units). * * @param top the top insets. * @param left the left insets. * @param bottom the bottom insets. * @param right the right insets. */ public RectangleInsets(double top, double left, double bottom, double right) { this(UnitType.ABSOLUTE, top, left, bottom, right); } /** * Creates a new instance. * * @param unitType absolute or relative units (<code>null</code> not * permitted). * @param top the top insets. * @param left the left insets. * @param bottom the bottom insets. * @param right the right insets. */ public RectangleInsets(UnitType unitType, double top, double left, double bottom, double right) { if (unitType == null) { throw new IllegalArgumentException("Null 'unitType' argument."); } this.unitType = unitType; this.top = top; this.bottom = bottom; this.left = left; this.right = right; } /** * Returns the unit type (absolute or relative). This specifies whether * the insets are measured as Java2D units or percentages. * * @return The unit type (never <code>null</code>). */ public UnitType getUnitType() { return this.unitType; } /** * Returns the top insets. * * @return The top insets. */ public double getTop() { return this.top; } /** * Returns the bottom insets. * * @return The bottom insets. */ public double getBottom() { return this.bottom; } /** * Returns the left insets. * * @return The left insets. */ public double getLeft() { return this.left; } /** * Returns the right insets. * * @return The right insets. */ public double getRight() { return this.right; } /** * Tests this instance for equality with an arbitrary object. * * @param obj the object (<code>null</code> permitted). * * @return A boolean. */ public boolean equals(Object obj) { if (obj == this) { return true; } if (!(obj instanceof RectangleInsets)) { return false; } final RectangleInsets that = (RectangleInsets) obj; if (that.unitType != this.unitType) { return false; } if (this.left != that.left) { return false; } if (this.right != that.right) { return false; } if (this.top != that.top) { return false; } if (this.bottom != that.bottom) { return false; } return true; } /** * Returns a hash code for the object. * * @return A hash code. */ public int hashCode() { int result; long temp; result = (this.unitType != null ? this.unitType.hashCode() : 0); temp = this.top != +0.0d ? Double.doubleToLongBits(this.top) : 0L; result = 29 * result + (int) (temp ^ (temp >>> 32)); temp = this.bottom != +0.0d ? Double.doubleToLongBits(this.bottom) : 0L; result = 29 * result + (int) (temp ^ (temp >>> 32)); temp = this.left != +0.0d ? Double.doubleToLongBits(this.left) : 0L; result = 29 * result + (int) (temp ^ (temp >>> 32)); temp = this.right != +0.0d ? Double.doubleToLongBits(this.right) : 0L; result = 29 * result + (int) (temp ^ (temp >>> 32)); return result; } /** * Returns a textual representation of this instance, useful for debugging * purposes. * * @return A string representing this instance. */ public String toString() { return "RectangleInsets[t=" + this.top + ",l=" + this.left + ",b=" + this.bottom + ",r=" + this.right + "]"; } /** * Creates an adjusted rectangle using the supplied rectangle, the insets * specified by this instance, and the horizontal and vertical * adjustment types. * * @param base the base rectangle (<code>null</code> not permitted). * @param horizontal the horizontal adjustment type (<code>null</code> not * permitted). * @param vertical the vertical adjustment type (<code>null</code> not * permitted). * * @return The inset rectangle. */ public Rectangle2D createAdjustedRectangle(Rectangle2D base, LengthAdjustmentType horizontal, LengthAdjustmentType vertical) { if (base == null) { throw new IllegalArgumentException("Null 'base' argument."); } double x = base.getX(); double y = base.getY(); double w = base.getWidth(); double h = base.getHeight(); if (horizontal == LengthAdjustmentType.EXPAND) { double leftOutset = calculateLeftOutset(w); x = x - leftOutset; w = w + leftOutset + calculateRightOutset(w); } else if (horizontal == LengthAdjustmentType.CONTRACT) { double leftMargin = calculateLeftInset(w); x = x + leftMargin; w = w - leftMargin - calculateRightInset(w); } if (vertical == LengthAdjustmentType.EXPAND) { double topMargin = calculateTopOutset(h); y = y - topMargin; h = h + topMargin + calculateBottomOutset(h); } else if (vertical == LengthAdjustmentType.CONTRACT) { double topMargin = calculateTopInset(h); y = y + topMargin; h = h - topMargin - calculateBottomInset(h); } return new Rectangle2D.Double(x, y, w, h); } /** * Creates an 'inset' rectangle. * * @param base the base rectangle (<code>null</code> not permitted). * * @return The inset rectangle. */ public Rectangle2D createInsetRectangle(Rectangle2D base) { return createInsetRectangle(base, true, true); } /** * Creates an 'inset' rectangle. * * @param base the base rectangle (<code>null</code> not permitted). * @param horizontal apply horizontal insets? * @param vertical apply vertical insets? * * @return The inset rectangle. */ public Rectangle2D createInsetRectangle(Rectangle2D base, boolean horizontal, boolean vertical) { if (base == null) { throw new IllegalArgumentException("Null 'base' argument."); } double topMargin = 0.0; double bottomMargin = 0.0; if (vertical) { topMargin = calculateTopInset(base.getHeight()); bottomMargin = calculateBottomInset(base.getHeight()); } double leftMargin = 0.0; double rightMargin = 0.0; if (horizontal) { leftMargin = calculateLeftInset(base.getWidth()); rightMargin = calculateRightInset(base.getWidth()); } return new Rectangle2D.Double( base.getX() + leftMargin, base.getY() + topMargin, base.getWidth() - leftMargin - rightMargin, base.getHeight() - topMargin - bottomMargin ); } /** * Creates an outset rectangle. * * @param base the base rectangle (<code>null</code> not permitted). * * @return An outset rectangle. */ public Rectangle2D createOutsetRectangle(Rectangle2D base) { return createOutsetRectangle(base, true, true); } /** * Creates an outset rectangle. * * @param base the base rectangle (<code>null</code> not permitted). * @param horizontal apply horizontal insets? * @param vertical apply vertical insets? * * @return An outset rectangle. */ public Rectangle2D createOutsetRectangle(Rectangle2D base, boolean horizontal, boolean vertical) { if (base == null) { throw new IllegalArgumentException("Null 'base' argument."); } double topMargin = 0.0; double bottomMargin = 0.0; if (vertical) { topMargin = calculateTopOutset(base.getHeight()); bottomMargin = calculateBottomOutset(base.getHeight()); } double leftMargin = 0.0; double rightMargin = 0.0; if (horizontal) { leftMargin = calculateLeftOutset(base.getWidth()); rightMargin = calculateRightOutset(base.getWidth()); } return new Rectangle2D.Double( base.getX() - leftMargin, base.getY() - topMargin, base.getWidth() + leftMargin + rightMargin, base.getHeight() + topMargin + bottomMargin ); } /** * Returns the top margin. * * @param height the height of the base rectangle. * * @return The top margin (in Java2D units). */ public double calculateTopInset(double height) { double result = this.top; if (this.unitType == UnitType.RELATIVE) { result = (this.top * height); } return result; } /** * Returns the top margin. * * @param height the height of the base rectangle. * * @return The top margin (in Java2D units). */ public double calculateTopOutset(double height) { double result = this.top; if (this.unitType == UnitType.RELATIVE) { result = (height / (1 - this.top - this.bottom)) * this.top; } return result; } /** * Returns the bottom margin. * * @param height the height of the base rectangle. * * @return The bottom margin (in Java2D units). */ public double calculateBottomInset(double height) { double result = this.bottom; if (this.unitType == UnitType.RELATIVE) { result = (this.bottom * height); } return result; } /** * Returns the bottom margin. * * @param height the height of the base rectangle. * * @return The bottom margin (in Java2D units). */ public double calculateBottomOutset(double height) { double result = this.bottom; if (this.unitType == UnitType.RELATIVE) { result = (height / (1 - this.top - this.bottom)) * this.bottom; } return result; } /** * Returns the left margin. * * @param width the width of the base rectangle. * * @return The left margin (in Java2D units). */ public double calculateLeftInset(double width) { double result = this.left; if (this.unitType == UnitType.RELATIVE) { result = (this.left * width); } return result; } /** * Returns the left margin. * * @param width the width of the base rectangle. * * @return The left margin (in Java2D units). */ public double calculateLeftOutset(double width) { double result = this.left; if (this.unitType == UnitType.RELATIVE) { result = (width / (1 - this.left - this.right)) * this.left; } return result; } /** * Returns the right margin. * * @param width the width of the base rectangle. * * @return The right margin (in Java2D units). */ public double calculateRightInset(double width) { double result = this.right; if (this.unitType == UnitType.RELATIVE) { result = (this.right * width); } return result; } /** * Returns the right margin. * * @param width the width of the base rectangle. * * @return The right margin (in Java2D units). */ public double calculateRightOutset(double width) { double result = this.right; if (this.unitType == UnitType.RELATIVE) { result = (width / (1 - this.left - this.right)) * this.right; } return result; } /** * Trims the given width to allow for the insets. * * @param width the width. * * @return The trimmed width. */ public double trimWidth(double width) { return width - calculateLeftInset(width) - calculateRightInset(width); } /** * Extends the given width to allow for the insets. * * @param width the width. * * @return The extended width. */ public double extendWidth(double width) { return width + calculateLeftOutset(width) + calculateRightOutset(width); } /** * Trims the given height to allow for the insets. * * @param height the height. * * @return The trimmed height. */ public double trimHeight(double height) { return height - calculateTopInset(height) - calculateBottomInset(height); } /** * Extends the given height to allow for the insets. * * @param height the height. * * @return The extended height. */ public double extendHeight(double height) { return height + calculateTopOutset(height) + calculateBottomOutset(height); } /** * Shrinks the given rectangle by the amount of these insets. * * @param area the area (<code>null</code> not permitted). */ public void trim(Rectangle2D area) { double w = area.getWidth(); double h = area.getHeight(); double l = calculateLeftInset(w); double r = calculateRightInset(w); double t = calculateTopInset(h); double b = calculateBottomInset(h); area.setRect(area.getX() + l, area.getY() + t, w - l - r, h - t - b); } }
package io.trivial.repositories; import io.trivial.models.entites.Role; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Deprecated @Repository public interface RoleRepository extends JpaRepository<Role, String> { }
/* * 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.facebook.presto.sql.analyzer; public enum SemanticErrorCode { MUST_BE_AGGREGATE_OR_GROUP_BY, NESTED_AGGREGATION, NESTED_WINDOW, MUST_BE_WINDOW_FUNCTION, MISSING_CATALOG, MISSING_SCHEMA, MISSING_TABLE, MISMATCHED_COLUMN_ALIASES, NOT_SUPPORTED, INVALID_SCHEMA_NAME, TABLE_ALREADY_EXISTS, DUPLICATE_RELATION, TYPE_MISMATCH, AMBIGUOUS_ATTRIBUTE, MISSING_ATTRIBUTE, INVALID_ORDINAL, ORDER_BY_MUST_BE_IN_SELECT, CANNOT_HAVE_AGGREGATIONS_OR_WINDOWS, WILDCARD_WITHOUT_FROM, MISMATCHED_SET_COLUMN_TYPES, MULTIPLE_FIELDS_FROM_SCALAR_SUBQUERY, DUPLICATE_COLUMN_NAME, COLUMN_NAME_NOT_SPECIFIED, EXPRESSION_NOT_CONSTANT, NON_NUMERIC_SAMPLE_PERCENTAGE, SAMPLE_PERCENTAGE_OUT_OF_RANGE }
package com.gentics.mesh.search.index.group; import static com.gentics.mesh.search.index.MappingHelper.NAME_KEY; import javax.inject.Inject; import javax.inject.Singleton; import com.gentics.mesh.core.data.Group; import com.gentics.mesh.search.index.AbstractTransformer; import io.vertx.core.json.JsonObject; /** * Transformer for group search index documents. */ @Singleton public class GroupTransformer extends AbstractTransformer<Group> { @Inject public GroupTransformer() { } @Override public JsonObject toDocument(Group group) { JsonObject document = new JsonObject(); document.put(NAME_KEY, group.getName()); addBasicReferences(document, group); addPermissionInfo(document, group); return document; } }
/* * 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.solr.cloud; import java.nio.charset.Charset; import java.util.NoSuchElementException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.function.Predicate; import org.apache.solr.SolrTestCaseJ4; import org.apache.solr.client.solrj.cloud.DistributedQueue; import org.apache.solr.common.cloud.SolrZkClient; import org.apache.solr.common.util.ExecutorUtil; import org.apache.solr.common.util.SolrNamedThreadFactory; import org.apache.solr.common.util.TimeSource; import org.apache.solr.util.TimeOut; import org.junit.After; import org.junit.Before; import org.junit.Test; public class DistributedQueueTest extends SolrTestCaseJ4 { private static final Charset UTF8 = Charset.forName("UTF-8"); protected ZkTestServer zkServer; protected SolrZkClient zkClient; protected ExecutorService executor = ExecutorUtil.newMDCAwareSingleThreadExecutor(new SolrNamedThreadFactory("dqtest-")); @Before @Override public void setUp() throws Exception { super.setUp(); setupZk(); } @Test public void testDistributedQueue() throws Exception { String dqZNode = "/distqueue/test"; byte[] data = "hello world".getBytes(UTF8); DistributedQueue dq = makeDistributedQueue(dqZNode); // basic ops assertNull(dq.poll()); try { dq.remove(); fail("NoSuchElementException expected"); } catch (NoSuchElementException expected) { // expected } dq.offer(data); assertArrayEquals(dq.peek(500), data); assertArrayEquals(dq.remove(), data); assertNull(dq.poll()); dq.offer(data); assertArrayEquals(dq.take(), data); // waits for data assertNull(dq.poll()); dq.offer(data); dq.peek(true); // wait until data is definitely there before calling remove assertArrayEquals(dq.remove(), data); assertNull(dq.poll()); // should block until the background thread makes the offer (new QueueChangerThread(dq, 1000)).start(); assertNotNull(dq.peek(true)); assertNotNull(dq.remove()); assertNull(dq.poll()); // timeout scenario ... background thread won't offer until long after the peek times out QueueChangerThread qct = new QueueChangerThread(dq, 1000); qct.start(); assertNull(dq.peek(500)); qct.join(); } @Test public void testDistributedQueueCache() throws Exception { String dqZNode = "/distqueue/test"; byte[] data = "hello world".getBytes(UTF8); ZkDistributedQueue consumer = makeDistributedQueue(dqZNode); DistributedQueue producer = makeDistributedQueue(dqZNode); DistributedQueue producer2 = makeDistributedQueue(dqZNode); producer2.offer(data); producer.offer(data); producer.offer(data); consumer.poll(); assertEquals(2, consumer.getZkStats().getQueueLength()); producer.offer(data); producer2.offer(data); consumer.poll(); // Wait for watcher being kicked off while (!consumer.isDirty()) { Thread.sleep(20); } // DQ still have elements in their queue, so we should not fetch elements path from Zk assertEquals(1, consumer.getZkStats().getQueueLength()); consumer.poll(); consumer.peek(); assertEquals(2, consumer.getZkStats().getQueueLength()); } @Test public void testDistributedQueueBlocking() throws Exception { String dqZNode = "/distqueue/test"; String testData = "hello world"; ZkDistributedQueue dq = makeDistributedQueue(dqZNode); assertNull(dq.peek()); Future<String> future = executor.submit(() -> new String(dq.peek(true), UTF8)); try { future.get(1000, TimeUnit.MILLISECONDS); fail("TimeoutException expected"); } catch (TimeoutException expected) { assertFalse(future.isDone()); } // Ultimately trips the watcher, triggering child refresh dq.offer(testData.getBytes(UTF8)); assertEquals(testData, future.get(1000, TimeUnit.MILLISECONDS)); assertNotNull(dq.poll()); // After draining the queue, a watcher should be set. assertNull(dq.peek(100)); TimeOut timeout = new TimeOut(30, TimeUnit.SECONDS, TimeSource.NANO_TIME); timeout.waitFor("Timeout waiting to see dirty=false", () -> { try { return !dq.isDirty(); } catch (InterruptedException e) { throw new RuntimeException(e); } }); assertFalse(dq.isDirty()); assertEquals(1, dq.watcherCount()); forceSessionExpire(); // Session expiry should have fired the watcher. Thread.sleep(100); assertTrue(dq.isDirty()); assertEquals(0, dq.watcherCount()); // Rerun the earlier test make sure updates are still seen, post reconnection. future = executor.submit(() -> new String(dq.peek(true), UTF8)); try { future.get(1000, TimeUnit.MILLISECONDS); fail("TimeoutException expected"); } catch (TimeoutException expected) { assertFalse(future.isDone()); } // Ultimately trips the watcher, triggering child refresh dq.offer(testData.getBytes(UTF8)); assertEquals(testData, future.get(1000, TimeUnit.MILLISECONDS)); assertNotNull(dq.poll()); assertNull(dq.poll()); } @Test public void testLeakChildWatcher() throws Exception { String dqZNode = "/distqueue/test"; ZkDistributedQueue dq = makeDistributedQueue(dqZNode); assertTrue(dq.peekElements(1, 1, s1 -> true).isEmpty()); assertEquals(1, dq.watcherCount()); assertFalse(dq.isDirty()); assertTrue(dq.peekElements(1, 1, s1 -> true).isEmpty()); assertEquals(1, dq.watcherCount()); assertFalse(dq.isDirty()); assertNull(dq.peek()); assertEquals(1, dq.watcherCount()); assertFalse(dq.isDirty()); assertNull(dq.peek(10)); assertEquals(1, dq.watcherCount()); assertFalse(dq.isDirty()); dq.offer("hello world".getBytes(UTF8)); assertNotNull(dq.peek()); // synchronously available // dirty and watcher state indeterminate here, race with watcher Thread.sleep(100); // watcher should have fired now assertNotNull(dq.peek()); // in case of race condition, childWatcher is kicked off after peek() if (dq.watcherCount() == 0) { assertTrue(dq.isDirty()); dq.poll(); dq.offer("hello world".getBytes(UTF8)); dq.peek(); } assertEquals(1, dq.watcherCount()); assertFalse(dq.isDirty()); assertFalse(dq.peekElements(1, 1, s -> true).isEmpty()); assertEquals(1, dq.watcherCount()); assertFalse(dq.isDirty()); } @Test public void testLocallyOffer() throws Exception { String dqZNode = "/distqueue/test"; ZkDistributedQueue dq = makeDistributedQueue(dqZNode); dq.peekElements(1, 1, s -> true); for (int i = 0; i < 100; i++) { byte[] data = String.valueOf(i).getBytes(UTF8); dq.offer(data); assertNotNull(dq.peek()); dq.poll(); dq.peekElements(1, 1, s -> true); } } @Test public void testPeekElements() throws Exception { String dqZNode = "/distqueue/test"; byte[] data = "hello world".getBytes(UTF8); ZkDistributedQueue dq = makeDistributedQueue(dqZNode); // Populate with data. dq.offer(data); dq.offer(data); dq.offer(data); Predicate<String> alwaysTrue = s -> true; Predicate<String> alwaysFalse = s -> false; // Should be able to get 0, 1, 2, or 3 instantly for (int i = 0; i <= 3; ++i) { assertEquals(i, dq.peekElements(i, 0, alwaysTrue).size()); } // Asking for more should return only 3. assertEquals(3, dq.peekElements(4, 0, alwaysTrue).size()); // If we filter everything out, we should block for the full time. long start = System.nanoTime(); assertEquals(0, dq.peekElements(4, 1000, alwaysFalse).size()); assertTrue(System.nanoTime() - start >= TimeUnit.MILLISECONDS.toNanos(500)); // If someone adds a new matching element while we're waiting, we should return immediately. executor.submit(() -> { try { Thread.sleep(500); dq.offer(data); } catch (Exception e) { // ignore } }); start = System.nanoTime(); assertEquals(1, dq.peekElements(4, 2000, child -> { // The 4th element in the queue will end with a "3". return child.endsWith("3"); }).size()); long timeTaken = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start); assertTrue("Time was " + timeTaken + "ms, expected 250-1500ms", timeTaken > 250 && timeTaken < 1500); } private void forceSessionExpire() throws InterruptedException, TimeoutException { long sessionId = zkClient.getSolrZooKeeper().getSessionId(); zkServer.expire(sessionId); zkClient.getConnectionManager().waitForDisconnected(10000); zkClient.getConnectionManager().waitForConnected(10000); for (int i = 0; i < 100; ++i) { if (zkClient.isConnected()) { break; } Thread.sleep(50); } assertTrue(zkClient.isConnected()); assertFalse(sessionId == zkClient.getSolrZooKeeper().getSessionId()); } protected ZkDistributedQueue makeDistributedQueue(String dqZNode) throws Exception { return new ZkDistributedQueue(zkClient, setupNewDistributedQueueZNode(dqZNode)); } private static class QueueChangerThread extends Thread { DistributedQueue dq; long waitBeforeOfferMs; QueueChangerThread(DistributedQueue dq, long waitBeforeOfferMs) { this.dq = dq; this.waitBeforeOfferMs = waitBeforeOfferMs; } public void run() { try { Thread.sleep(waitBeforeOfferMs); dq.offer(getName().getBytes(UTF8)); } catch (InterruptedException ie) { // do nothing } catch (Exception exc) { throw new RuntimeException(exc); } } } protected String setupNewDistributedQueueZNode(String znodePath) throws Exception { if (!zkClient.exists("/", true)) zkClient.makePath("/", false, true); if (zkClient.exists(znodePath, true)) zkClient.clean(znodePath); zkClient.makePath(znodePath, false, true); return znodePath; } @Override @After public void tearDown() throws Exception { try { super.tearDown(); } catch (Exception exc) { } closeZk(); executor.shutdown(); } protected void setupZk() throws Exception { System.setProperty("zkClientTimeout", "8000"); zkServer = new ZkTestServer(createTempDir("zkData")); zkServer.run(); System.setProperty("zkHost", zkServer.getZkAddress()); zkClient = new SolrZkClient(zkServer.getZkAddress(), AbstractZkTestCase.TIMEOUT); assertTrue(zkClient.isConnected()); } protected void closeZk() throws Exception { if (null != zkClient) { zkClient.close(); zkClient = null; } if (null != zkServer) { zkServer.shutdown(); zkServer = null; } } }
/* * Copyright (c) 2008-2015, Hazelcast, Inc. 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.hazelcast.client.impl.protocol.task; import com.hazelcast.client.impl.client.ClientPrincipal; import com.hazelcast.client.impl.protocol.ClientMessage; import com.hazelcast.client.impl.protocol.codec.ClientAuthenticationCustomCodec; import com.hazelcast.instance.Node; import com.hazelcast.nio.Address; import com.hazelcast.nio.Connection; import java.security.Permission; /** * Custom Authentication with custom credential impl */ public class AuthenticationCustomCredentialsMessageTask extends AuthenticationBaseMessageTask<ClientAuthenticationCustomCodec.RequestParameters> { public AuthenticationCustomCredentialsMessageTask(ClientMessage clientMessage, Node node, Connection connection) { super(clientMessage, node, connection); } @Override protected boolean isOwnerConnection() { return parameters.isOwnerConnection; } @Override protected String getClientType() { return parameters.clientType; } @Override protected ClientAuthenticationCustomCodec.RequestParameters decodeClientMessage(ClientMessage clientMessage) { ClientAuthenticationCustomCodec.RequestParameters parameters = ClientAuthenticationCustomCodec .decodeRequest(clientMessage); String uuid = parameters.uuid; String ownerUuid = parameters.ownerUuid; if (uuid != null && uuid.length() > 0) { principal = new ClientPrincipal(uuid, ownerUuid); } credentials = serializationService.toObject(parameters.credentials); clientSerializationVersion = parameters.serializationVersion; return parameters; } @Override protected ClientMessage encodeResponse(Object response) { return (ClientMessage) response; } @Override protected ClientMessage encodeAuth(byte status, Address thisAddress, String uuid, String ownerUuid, byte version) { return ClientAuthenticationCustomCodec.encodeResponse(status, thisAddress, uuid, ownerUuid, version); } @Override public String getServiceName() { return null; } @Override public String getDistributedObjectName() { return null; } @Override public String getMethodName() { return null; } @Override public Object[] getParameters() { return null; } @Override public Permission getRequiredPermission() { return null; } }
package com.sengami.keystoresharedpreferences; import android.content.Context; import android.content.SharedPreferences; import java.util.HashSet; import java.util.Set; public final class KeystoreSharedPreferencesEditor implements SharedPreferences.Editor { private final Context context; private final SharedPreferences.Editor editor; public KeystoreSharedPreferencesEditor(final Context context, final SharedPreferences.Editor editor) { this.context = context; this.editor = editor; } @Override public SharedPreferences.Editor putString(final String key, final String value) { return encryptAndPutString(key, value); } @Override public SharedPreferences.Editor putStringSet(final String key, final Set<String> values) { final Set<String> encryptedValues = new HashSet<>(); for (final String value : values) { encryptedValues.add(KeyStoreProxy.encryptString(context, value)); } editor.putStringSet(key, encryptedValues); return this; } @Override public SharedPreferences.Editor putInt(final String key, final int value) { final String valueAsString = Integer.valueOf(value).toString(); return encryptAndPutString(key, valueAsString); } @Override public SharedPreferences.Editor putLong(final String key, final long value) { final String valueAsString = Long.valueOf(value).toString(); return encryptAndPutString(key, valueAsString); } @Override public SharedPreferences.Editor putFloat(final String key, final float value) { final String valueAsString = Float.valueOf(value).toString(); return encryptAndPutString(key, valueAsString); } @Override public SharedPreferences.Editor putBoolean(final String key, final boolean value) { final String valueAsString = Boolean.valueOf(value).toString(); return encryptAndPutString(key, valueAsString); } @Override public SharedPreferences.Editor remove(final String key) { editor.remove(key); return this; } @Override public SharedPreferences.Editor clear() { editor.clear(); return this; } @Override public boolean commit() { editor.commit(); return true; } @Override public void apply() { editor.apply(); } private SharedPreferences.Editor encryptAndPutString(final String key, final String value) { final String encryptedValue = KeyStoreProxy.encryptString(context, value); editor.putString(key, encryptedValue); return this; } }
/** * Models */ package uk.ac.ox.ndph.mts.practitionerserviceclient.model;
/* * Copyright 2013 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. */ package org.versacoinj.jni; import org.versacoinj.wallet.Wallet; import org.versacoinj.wallet.listeners.WalletReorganizeEventListener; /** * An event listener that relays events to a native C++ object. A pointer to that object is stored in * this class using JNI on the native side, thus several instances of this can point to different actual * native implementations. */ public class NativeWalletReorganizeEventListener implements WalletReorganizeEventListener { public long ptr; @Override public native void onReorganize(Wallet wallet); }
package co.yixiang.modules.yaolian.service.dto; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; @Data @ApiModel(value="药联退单传输对象", description="药联退单传输对象") public class YaolianOrderRefundDto { @ApiModelProperty(value = "请求头") private ReqHead requestHead; @ApiModelProperty(value = "退单对象") private YaolianOrderRefund orderRefund; }
package it.fds.taskmanager.scheduler; import static java.util.concurrent.TimeUnit.SECONDS; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpEntity; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; import org.springframework.core.env.Environment; import it.fds.taskmanager.TaskService; import it.fds.taskmanager.dto.TaskDTO; import it.fds.taskmanager.tasksgenerator.TasksGenerator; /** * Create and schedule new Tasks * * @author fds * */ @Component public class SchedulerNewTasks { @Autowired TaskService taskService; private final Logger LOGGER = Logger.getLogger(SchedulerNewTasks.class); private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); @Autowired private TasksGenerator basicTaskGenerator; private Environment env; public SchedulerNewTasks(){} public void generateTask() { final Runnable newTaskGenerator = new Runnable() { public void run() { TaskDTO task = basicTaskGenerator.generateTask(); TaskDTO newt = taskService.saveTask(task); RestTemplate rt = new RestTemplate(); ResponseEntity<String> result = null; try { result = rt.postForEntity(new URI("http://"+ env.getProperty("rest.host")+":8080/task/notify"), newt.getUuid(), String.class); LOGGER.info("Result of the notify call: '" + result + "'"); LOGGER.info("New Task SAVED!"); } catch (RestClientException | URISyntaxException e) { e.printStackTrace(); } } }; final ScheduledFuture<?> fut1 = scheduler.scheduleAtFixedRate(newTaskGenerator, 5, 5, SECONDS); scheduler.schedule(new Runnable() { public void run() { fut1.cancel(true); } }, 60*60, SECONDS); } }
package br.com.agenda.api; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class AgendaApiApplication { public static void main(String[] args) { SpringApplication.run(AgendaApiApplication.class, args); } }
package com.telecominfraproject.wlan.hierarchical.datastore.writer; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.telecominfraproject.wlan.core.model.json.BaseJsonModel; import com.telecominfraproject.wlan.hierarchical.datastore.HierarchicalDatastore; import com.telecominfraproject.wlan.server.exceptions.GenericErrorException; /** * QueueReader picks up objects from the queue and writes them into zip streams in memory - one stream per N minutes, according to HierarchicalDatastore settings.<br> * Zip streams will be flushed into files after they have been idle for X minutes, according to HierarchicalDatastore settings.<br> * * @author dtop * */ public class QueueReader { private static final Logger LOG = LoggerFactory.getLogger(QueueReader.class); @SuppressWarnings("serial") static final BaseJsonModel poisonPill = new BaseJsonModel(){}; private final int customerId; private final long equipmentId; private final String fileNamePrefix; private final BlockingQueue<BaseJsonModel> queue = new ArrayBlockingQueue<>(5000); private final Thread queueReaderThread; private boolean shutdownRequested; public QueueReader(HierarchicalDatastore hierarchicalDatastore, int customerId, long equipmentId, long idleTimeoutBeforeFlushingMs) { this.customerId = customerId; this.equipmentId = equipmentId; this.fileNamePrefix = hierarchicalDatastore.getFileNamePrefix(); queueReaderThread = new Thread(new QueueReaderRunnable(queue, hierarchicalDatastore, customerId, equipmentId, idleTimeoutBeforeFlushingMs), "queueReader_"+fileNamePrefix+"_"+customerId+"_"+equipmentId+"_"+System.currentTimeMillis()); //This thread has to be non-daemon because we need it alive when shutdown hook // runs - to process poison pills and perform flush to files queueReaderThread.setDaemon(false); } /** * Start reading messages from the queue */ public void start(){ queueReaderThread.start(); } public int getQueueSize(){ return queue.size(); } public boolean isAlive(){ return queueReaderThread.isAlive(); } /** * Shutdown and flush to files all existing streams. * Actual shutdown and flush is performed when poison pill is read by the queueReaderThread. */ public void shutdown(){ if(!shutdownRequested){ shutdownRequested = true; LOG.info("Shutting down queue {}_{}_{}", fileNamePrefix, customerId, equipmentId); addToQueue(poisonPill); } } public void addToQueue(BaseJsonModel model){ LOG.trace("Adding model to queue({}_{}_{}) {}", fileNamePrefix, customerId, equipmentId, model); try { queue.put(model); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new GenericErrorException("Interrupted while trying to insert model into a queue " + fileNamePrefix + " for customer "+customerId+" equipment "+equipmentId, e); } } /** * @return true if shutdown was requested and queue reader thread have flushed all streams to S3 and exited */ public boolean isShutdownCompleted() { return shutdownRequested && !queueReaderThread.isAlive(); } }
package org.nwnx.nwnx2.jvm.constants; /** * This class contains all unique constants beginning with "VFX_EYES_YEL". * Non-distinct keys are filtered; only the LAST appearing was * kept. */ public final class VfxEyesYel { private VfxEyesYel() {} public final static int DWARF_FEMALE = 376; public final static int DWARF_MALE = 375; public final static int ELF_FEMALE = 378; public final static int ELF_MALE = 377; public final static int GNOME_FEMALE = 380; public final static int GNOME_MALE = 379; public final static int HALFLING_FEMALE = 382; public final static int HALFLING_MALE = 381; public final static int HALFORC_FEMALE = 384; public final static int HALFORC_MALE = 383; public final static int HUMAN_FEMALE = 374; public final static int HUMAN_MALE = 373; public final static int TROGLODYTE = 385; public static String nameOf(int value) { if (value == 376) return "VfxEyesYel.DWARF_FEMALE"; if (value == 375) return "VfxEyesYel.DWARF_MALE"; if (value == 378) return "VfxEyesYel.ELF_FEMALE"; if (value == 377) return "VfxEyesYel.ELF_MALE"; if (value == 380) return "VfxEyesYel.GNOME_FEMALE"; if (value == 379) return "VfxEyesYel.GNOME_MALE"; if (value == 382) return "VfxEyesYel.HALFLING_FEMALE"; if (value == 381) return "VfxEyesYel.HALFLING_MALE"; if (value == 384) return "VfxEyesYel.HALFORC_FEMALE"; if (value == 383) return "VfxEyesYel.HALFORC_MALE"; if (value == 374) return "VfxEyesYel.HUMAN_FEMALE"; if (value == 373) return "VfxEyesYel.HUMAN_MALE"; if (value == 385) return "VfxEyesYel.TROGLODYTE"; return "VfxEyesYel.(not found: " + value + ")"; } public static String nameOf(float value) { return "VfxEyesYel.(not found: " + value + ")"; } public static String nameOf(String value) { return "VfxEyesYel.(not found: " + value + ")"; } }
/** * 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.atlas.kafka; import org.apache.atlas.notification.NotificationConsumer; import org.apache.atlas.notification.NotificationException; import org.apache.atlas.notification.NotificationInterface; import org.apache.kafka.clients.producer.Producer; import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.clients.producer.RecordMetadata; import org.apache.kafka.common.TopicPartition; import org.testng.annotations.Test; import java.util.Arrays; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; public class KafkaNotificationMockTest { @Test @SuppressWarnings("unchecked") public void testCreateConsumers() throws Exception { Properties properties = mock(Properties.class); when(properties.getProperty("entities.group.id")).thenReturn("atlas"); Map<String, Integer> topicCountMap = new HashMap<>(); topicCountMap.put(KafkaNotification.ATLAS_ENTITIES_TOPIC, 1); final AtlasKafkaConsumer consumer1 = mock(AtlasKafkaConsumer.class); final AtlasKafkaConsumer consumer2 = mock(AtlasKafkaConsumer.class); KafkaNotification kafkaNotification = new TestKafkaNotification(properties, consumer1, consumer2); List<NotificationConsumer<AtlasKafkaConsumer>> consumers = kafkaNotification.createConsumers(NotificationInterface.NotificationType.ENTITIES, 2); assertEquals(consumers.size(), 2); assertTrue(consumers.contains(consumer1)); assertTrue(consumers.contains(consumer2)); } @Test @SuppressWarnings("unchecked") public void shouldSendMessagesSuccessfully() throws NotificationException, ExecutionException, InterruptedException { Properties configProperties = mock(Properties.class); KafkaNotification kafkaNotification = new KafkaNotification(configProperties); Producer producer = mock(Producer.class); String topicName = kafkaNotification.getTopicName(NotificationInterface.NotificationType.HOOK); String message = "This is a test message"; Future returnValue = mock(Future.class); TopicPartition topicPartition = new TopicPartition(topicName, 0); when(returnValue.get()).thenReturn(new RecordMetadata(topicPartition, 0, 0, 0, Long.valueOf(0), 0, 0)); ProducerRecord expectedRecord = new ProducerRecord(topicName, message); when(producer.send(expectedRecord)).thenReturn(returnValue); kafkaNotification.sendInternalToProducer(producer, NotificationInterface.NotificationType.HOOK, Arrays.asList(new String[]{message})); verify(producer).send(expectedRecord); } @Test @SuppressWarnings("unchecked") public void shouldThrowExceptionIfProducerFails() throws NotificationException, ExecutionException, InterruptedException { Properties configProperties = mock(Properties.class); KafkaNotification kafkaNotification = new KafkaNotification(configProperties); Producer producer = mock(Producer.class); String topicName = kafkaNotification.getTopicName(NotificationInterface.NotificationType.HOOK); String message = "This is a test message"; Future returnValue = mock(Future.class); when(returnValue.get()).thenThrow(new RuntimeException("Simulating exception")); ProducerRecord expectedRecord = new ProducerRecord(topicName, message); when(producer.send(expectedRecord)).thenReturn(returnValue); try { kafkaNotification.sendInternalToProducer(producer, NotificationInterface.NotificationType.HOOK, Arrays.asList(new String[]{message})); fail("Should have thrown NotificationException"); } catch (NotificationException e) { assertEquals(e.getFailedMessages().size(), 1); assertEquals(e.getFailedMessages().get(0), "This is a test message"); } } @Test @SuppressWarnings("unchecked") public void shouldCollectAllFailedMessagesIfProducerFails() throws NotificationException, ExecutionException, InterruptedException { Properties configProperties = mock(Properties.class); KafkaNotification kafkaNotification = new KafkaNotification(configProperties); Producer producer = mock(Producer.class); String topicName = kafkaNotification.getTopicName(NotificationInterface.NotificationType.HOOK); String message1 = "This is a test message1"; String message2 = "This is a test message2"; Future returnValue1 = mock(Future.class); when(returnValue1.get()).thenThrow(new RuntimeException("Simulating exception")); Future returnValue2 = mock(Future.class); when(returnValue2.get()).thenThrow(new RuntimeException("Simulating exception")); ProducerRecord expectedRecord1 = new ProducerRecord(topicName, message1); when(producer.send(expectedRecord1)).thenReturn(returnValue1); ProducerRecord expectedRecord2 = new ProducerRecord(topicName, message2); when(producer.send(expectedRecord2)).thenReturn(returnValue1); try { kafkaNotification.sendInternalToProducer(producer, NotificationInterface.NotificationType.HOOK, Arrays.asList(new String[]{message1, message2})); fail("Should have thrown NotificationException"); } catch (NotificationException e) { assertEquals(e.getFailedMessages().size(), 2); assertEquals(e.getFailedMessages().get(0), "This is a test message1"); assertEquals(e.getFailedMessages().get(1), "This is a test message2"); } } class TestKafkaNotification extends KafkaNotification { private final AtlasKafkaConsumer consumer1; private final AtlasKafkaConsumer consumer2; TestKafkaNotification(Properties properties, AtlasKafkaConsumer consumer1, AtlasKafkaConsumer consumer2) { super(properties); this.consumer1 = consumer1; this.consumer2 = consumer2; } @Override public <T> List<NotificationConsumer<T>> createConsumers(NotificationType notificationType, int numConsumers) { List consumerList = new ArrayList<NotificationConsumer>(); consumerList.add(consumer1); consumerList.add(consumer2); return consumerList; } protected <T> AtlasKafkaConsumer<T> createConsumers(Class<T> type, int consumerId, boolean autoCommitEnabled) { if (consumerId == 0) { return consumer1; } else if (consumerId == 1) { return consumer2; } return null; } } @Test public void justForSendSuccess() throws ExecutionException, InterruptedException, NotificationException { Properties configProperties = mock(Properties.class); configProperties.setProperty("atlas.notification.embedded", "false"); configProperties.setProperty("atlas.kafka.zookeeper.connect", "localhost:2181"); configProperties.setProperty("atlas.kafka.bootstrap.servers", "localhost:9027,localhost:9028,localhost:9029"); configProperties.setProperty("atlas.kafka.hook.group.id", "atlas"); // atlas.kafka.bootstrap.servers=localhost:9027,localhost:9028,localhost:9029 //#atlas.kafka.zookeeper.session.timeout.ms=400 // atlas.kafka.zookeeper.session.timeout.ms=60000 //#atlas.kafka.zookeeper.connection.timeout.ms=200 // atlas.kafka.zookeeper.connection.timeout.ms=30000 // atlas.kafka.zookeeper.sync.time.ms=20 // atlas.kafka.auto.commit.interval.ms=1000 // atlas.kafka.hook.group.id=atlas // // atlas.kafka.enable.auto.commit=false // atlas.kafka.auto.offset.reset=earliest // atlas.kafka.session.timeout.ms=30000 // atlas.kafka.offsets.topic.replication.factor=1 // atlas.kafka.poll.timeout.ms=1000 // // atlas.notification.create.topics=true // atlas.notification.replicas=1 // atlas.notification.topics=ATLAS_HOOK,ATLAS_ENTITIES // atlas.notification.log.failed.messages=true // atlas.notification.consumer.retry.interval=500 // atlas.notification.hook.retry.interval=1000 configProperties.setProperty("atlas.notification.replicas", "3"); configProperties.setProperty("atlas.notification.topics", "ATLAS_HOOK,ATLAS_ENTITIES"); KafkaNotification kafkaNotification = new KafkaNotification(configProperties); String message1 = "This is a test message3"; String topicName = kafkaNotification.getTopicName(NotificationInterface.NotificationType.HOOK); // ProducerRecord producerRecord = new ProducerRecord(topicName, message1); // Producer producer = mock(Producer.class); // Object o = producer.send(producerRecord).get(); kafkaNotification.sendInternal(NotificationInterface.NotificationType.HOOK, Arrays.asList(message1)); System.out.println(0); } }
package com.funalex.silvereggs.item; import com.funalex.silvereggs.entity.NetheriteEggEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.item.EggItem; import net.minecraft.item.ItemStack; import net.minecraft.sound.SoundCategory; import net.minecraft.sound.SoundEvents; import net.minecraft.stat.Stats; import net.minecraft.util.Hand; import net.minecraft.util.TypedActionResult; import net.minecraft.world.World; public class NetheriteEggItem extends EggItem { public NetheriteEggItem(Settings settings) { super(settings); } @Override public TypedActionResult<ItemStack> use(World world, PlayerEntity user, Hand hand) { ItemStack itemStack = user.getStackInHand(hand); world.playSound(null, user.getX(), user.getY(), user.getZ(), SoundEvents.ENTITY_EGG_THROW, SoundCategory.PLAYERS, 0.5F, 0.4F / (RANDOM.nextFloat() * 0.4F + 0.8F)); if (!world.isClient) { NetheriteEggEntity netheriteEggEntity = new NetheriteEggEntity(world, user); netheriteEggEntity.setItem(itemStack); netheriteEggEntity.setProperties(user, user.pitch, user.yaw, 0.0F, 1.5F, 1.0F); world.spawnEntity(netheriteEggEntity); } user.incrementStat(Stats.USED.getOrCreateStat(this)); if (!user.abilities.creativeMode) { itemStack.decrement(1); } return TypedActionResult.success(itemStack, world.isClient()); } }
package com.example.riven_chris; import java.io.*; /** * Created by riven_chris on 15/8/4. */ public class BasicFileOutPut { static String file = "test_files/BasicFileOutPut.out"; public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new StringReader( BufferedInputFile.read("Java_IO/src/com/example/riven_chris/BasicFileOutPut.java"))); // PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file)));//执行装饰工作 PrintWriter pw = new PrintWriter(file);//使用快捷方式 // BufferedWriter pw = new BufferedWriter(new FileWriter(file)); int lineCount = 1; String s; while ((s = br.readLine()) != null) { pw.println(lineCount++ + ": " + s); // pw.write(lineCount++ + ": " + s + "\n"); } pw.close(); System.out.println(BufferedInputFile.read(file)); } }
// SPDX-License-Identifier: Apache-2.0 // YAPION // Copyright (C) 2019,2020 yoyosource package yapion.packet; import lombok.extern.slf4j.Slf4j; import yapion.annotations.deserialize.YAPIONLoadExclude; import yapion.annotations.serialize.YAPIONSaveExclude; import yapion.hierarchy.typegroups.YAPIONAnyType; import yapion.hierarchy.types.YAPIONObject; import yapion.hierarchy.types.YAPIONValue; import yapion.hierarchy.types.YAPIONVariable; import yapion.parser.YAPIONParser; import yapion.serializing.YAPIONDeserializer; import java.io.IOException; import java.io.InputStream; @YAPIONSaveExclude(context = "*") @YAPIONLoadExclude(context = "*") @Slf4j public final class YAPIONInputStream { public static final int DEFAULT_WAIT = 10; public static final int LOW_WAIT = 1; public static final int HIGH_WAIT = 1000; private final InputStream inputStream; private YAPIONPacketReceiver yapionPacketReceiver = null; private YAPIONPacketIdentifier<?> staticIdentifier = null; private YAPIONPacketIdentifierCreator<?> dynamicIdentifier = null; private Thread yapionInputStreamHandler = null; private boolean running = true; /** * Creates a YAPIONInputStream from an InputStream. * * @param inputStream the InputStream */ public YAPIONInputStream(InputStream inputStream) { this.inputStream = inputStream; } /** * Set a direct receiver for data from this InputStream. * If an exception was thrown while reading, parsing, or * handling the received Packet an Exception packet will * be raised and handled by the same YAPIONPacketReceiver. * * @param yapionPacketReceiver the receiver */ public void setYAPIONPacketReceiver(YAPIONPacketReceiver yapionPacketReceiver) { this.yapionPacketReceiver = yapionPacketReceiver; thread(DEFAULT_WAIT); } /** * Set a direct receiver for data from this InputStream. * If an exception was thrown while reading, parsing, or * handling the received Packet an Exception packet will * be raised and handled by the same YAPIONPacketReceiver. * * @param yapionPacketReceiver the receiver * @param time the wait time of the internal receiver loop * this time should be between 1 and 1000 ms * and will be bounded to a value between it * when outside values are given if -1 is * given the default will be selected */ public void setYAPIONPacketReceiver(YAPIONPacketReceiver yapionPacketReceiver, int time) { if (time == -1) time = DEFAULT_WAIT; if (time < LOW_WAIT) time = LOW_WAIT; if (time > HIGH_WAIT) time = HIGH_WAIT; this.yapionPacketReceiver = yapionPacketReceiver; thread(time); } private void thread(int time) { if (yapionInputStreamHandler != null) return; yapionInputStreamHandler = new Thread(() -> { while (running) { try { Thread.sleep(time); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } if (handleAvailable() == 0) continue; try { handle(); } catch (Exception e) { drop(); if (yapionPacketReceiver != null) { YAPIONPacket yapionPacket = new YAPIONPacket(""); addIdentifier(yapionPacket); yapionPacketReceiver.handleException(yapionPacket, e); } log.warn("Something went wrong while handling the read object.", e.getCause()); } } }); yapionInputStreamHandler.setDaemon(true); yapionInputStreamHandler.start(); } private void drop() { try { while (inputStream.available() > 0) inputStream.read(); } catch (IOException e) { } } /** * Returns an estimate of bytes to be able to read. * * @return the estimated byte count * @throws IOException {@link YAPIONPacketReceiver} not null or {@link InputStream#available()} */ public synchronized int available() throws IOException { if (yapionPacketReceiver != null) throw new IOException(); return inputStream.available(); } /** * Read and parses the next YAPIONObject. * * @return the next YAPIONObject * @throws IOException {@link YAPIONPacketReceiver} not null */ public synchronized YAPIONObject read() throws IOException { if (yapionPacketReceiver != null) throw new IOException(); return YAPIONParser.parse(inputStream); } /** * Read, parses and deserialized the next YAPIONObject. * * @return the next Object * @throws IOException {@link YAPIONPacketReceiver} not null */ public synchronized Object readObject() throws IOException { if (yapionPacketReceiver != null) throw new IOException(); return YAPIONDeserializer.deserialize(read()); } /** * Closes this InputStream and tries to close the handler Thread * * @throws IOException {@link InputStream#close()} */ public synchronized void close() throws IOException { running = false; inputStream.close(); } public synchronized void identifier(YAPIONPacketIdentifier<?> yapionPacketIdentifier) { this.dynamicIdentifier = null; this.staticIdentifier = yapionPacketIdentifier; } public synchronized void identifier(YAPIONPacketIdentifierCreator<?> yapionPacketIdentifierCreator) { this.staticIdentifier = null; this.dynamicIdentifier = yapionPacketIdentifierCreator; } private synchronized int handleAvailable() { if (yapionPacketReceiver == null) return 0; try { return inputStream.available(); } catch (IOException e) { return 0; } } private synchronized void handle() { if (yapionPacketReceiver == null) return; YAPIONObject yapionObject = YAPIONParser.parse(inputStream); YAPIONVariable variable = yapionObject.getVariable("@type"); if (variable == null) return; YAPIONAnyType yapionAnyType = variable.getValue(); if (!(yapionAnyType instanceof YAPIONValue)) return; Object object = ((YAPIONValue) yapionAnyType).get(); if (!(object instanceof String)) return; if (!object.equals(YAPIONPacket.class.getTypeName())) return; YAPIONPacket yapionPacket = (YAPIONPacket) YAPIONDeserializer.deserialize(yapionObject); addIdentifier(yapionPacket); yapionPacketReceiver.handle(yapionPacket); } private void addIdentifier(YAPIONPacket yapionPacket) { if (staticIdentifier != null) yapionPacket.setYapionPacketIdentifier(staticIdentifier); if (dynamicIdentifier != null) yapionPacket.setYapionPacketIdentifier(dynamicIdentifier.identifier()); } }
package tc.wata.data; public class FastMap { int[] used; int[] value; int uid = 1; public FastMap(int n){ used = new int[n]; value = new int[n]; } public int getValue(int key){ if(used[key] != uid) return -1; return value[key]; } public void setValue(int key, int value){ if(add(key)) this.value[key] = value; } public void clear() { uid++; if (uid < 0) { for (int i = 0; i < used.length; i++) used[i] = 0; uid = 1; } } public boolean add(int i) { boolean res = used[i] != uid; used[i] = uid; return res; } public void remove(int i) { used[i] = uid - 1; } public boolean exist(int i) { return used[i] == uid; } }
package sqlancer.cockroachdb; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import sqlancer.Randomly; import sqlancer.cockroachdb.CockroachDBSchema.CockroachDBTable; import sqlancer.schema.AbstractSchema; import sqlancer.schema.AbstractTable; import sqlancer.schema.AbstractTableColumn; import sqlancer.schema.AbstractTables; import sqlancer.schema.TableIndex; public class CockroachDBSchema extends AbstractSchema<CockroachDBTable> { public enum CockroachDBDataType { INT, BOOL, STRING, FLOAT, BYTES, BIT, VARBIT, SERIAL, INTERVAL, TIMESTAMP, TIMESTAMPTZ, DECIMAL, JSONB, TIME, TIMETZ, ARRAY; private final boolean isPrimitive; CockroachDBDataType() { isPrimitive = true; } CockroachDBDataType(boolean isPrimitive) { this.isPrimitive = isPrimitive; } public static CockroachDBDataType getRandom() { return Randomly.fromOptions(values()); } public CockroachDBCompositeDataType get() { return CockroachDBCompositeDataType.getRandomForType(this); } public boolean isPrimitive() { return isPrimitive; } } public static class CockroachDBCompositeDataType { private final CockroachDBDataType dataType; private final int size; private CockroachDBCompositeDataType elementType; public CockroachDBCompositeDataType(CockroachDBDataType dataType) { this.dataType = dataType; this.size = -1; } public CockroachDBCompositeDataType(CockroachDBDataType dataType, int size) { this.dataType = dataType; this.size = size; } public CockroachDBCompositeDataType(CockroachDBDataType dataType, CockroachDBCompositeDataType elementType) { if (dataType != CockroachDBDataType.ARRAY) { throw new IllegalArgumentException(); } this.dataType = dataType; this.size = -1; this.elementType = elementType; } public CockroachDBDataType getPrimitiveDataType() { return dataType; } public int getSize() { if (size == -1) { throw new AssertionError(this); } return size; } public boolean isString() { return dataType == CockroachDBDataType.STRING; } public static CockroachDBCompositeDataType getInt(int size) { return new CockroachDBCompositeDataType(CockroachDBDataType.INT, size); } public static CockroachDBCompositeDataType getBit(int size) { return new CockroachDBCompositeDataType(CockroachDBDataType.BIT, size); } @Override public String toString() { switch (dataType) { case INT: switch (size) { case 2: return Randomly.fromOptions("INT2", "SMALLINT"); case 4: return "INT4"; case 8: // "INTEGER": can be affected by a session variable return Randomly.fromOptions("INT8", "INT64", "BIGINT"); default: return "INT"; } case SERIAL: switch (size) { case 2: return Randomly.fromOptions("SERIAL2", "SMALLSERIAL"); case 4: return "SERIAL4"; case 8: return Randomly.fromOptions("SERIAL8", "BIGSERIAL"); default: throw new AssertionError(); } case BIT: if (size == 1 && Randomly.getBoolean()) { return "BIT"; } else { return String.format("BIT(%d)", size); } case VARBIT: if (size == -1) { return String.format("VARBIT"); } else { return String.format("VARBIT(%d)", size); } case ARRAY: return String.format("%s[]", elementType.toString()); default: return dataType.toString(); } } public static CockroachDBCompositeDataType getRandom() { CockroachDBDataType randomDataType = CockroachDBDataType.getRandom(); return getRandomForType(randomDataType); } private static CockroachDBCompositeDataType getRandomForType(CockroachDBDataType randomDataType) { if (randomDataType == CockroachDBDataType.INT || randomDataType == CockroachDBDataType.SERIAL) { return new CockroachDBCompositeDataType(randomDataType, Randomly.fromOptions(2, 4, 8)); } else if (randomDataType == CockroachDBDataType.BIT) { return new CockroachDBCompositeDataType(randomDataType, (int) Randomly.getNotCachedInteger(1, 200)); } else if (randomDataType == CockroachDBDataType.VARBIT) { return new CockroachDBCompositeDataType(randomDataType, (int) Randomly.getNotCachedInteger(1, 200)); } else if (randomDataType == CockroachDBDataType.ARRAY) { return new CockroachDBCompositeDataType(randomDataType, getRandomForType(getArrayElementType())); } else { return new CockroachDBCompositeDataType(randomDataType); } } private static CockroachDBDataType getArrayElementType() { while (true) { CockroachDBDataType type = CockroachDBDataType.getRandom(); if (type != CockroachDBDataType.ARRAY && type != CockroachDBDataType.JSONB) { // nested arrays are not supported: // https://github.com/cockroachdb/cockroach/issues/32552 // JSONB arrays are not supported as well: // https://github.com/cockroachdb/cockroach/issues/23468 return type; } } } public static CockroachDBCompositeDataType getVarBit(int maxSize) { return new CockroachDBCompositeDataType(CockroachDBDataType.VARBIT, maxSize); } public CockroachDBCompositeDataType getElementType() { return elementType; } } public static class CockroachDBColumn extends AbstractTableColumn<CockroachDBTable, CockroachDBCompositeDataType> { private final boolean isPrimaryKey; private boolean isNullable; public CockroachDBColumn(String name, CockroachDBCompositeDataType columnType, boolean isPrimaryKey, boolean isNullable) { super(name, null, columnType); this.isPrimaryKey = isPrimaryKey; this.isNullable = isNullable; } public boolean isPrimaryKey() { return isPrimaryKey; } public boolean isNullable() { return isNullable; } } public static class CockroachDBTables extends AbstractTables<CockroachDBTable, CockroachDBColumn> { public CockroachDBTables(List<CockroachDBTable> tables) { super(tables); } } public CockroachDBSchema(List<CockroachDBTable> databaseTables) { super(databaseTables); } public CockroachDBTables getRandomTableNonEmptyTables() { return new CockroachDBTables(Randomly.nonEmptySubset(getDatabaseTables())); } private static CockroachDBCompositeDataType getColumnType(String typeString) { if (typeString.endsWith("[]")) { String substring = typeString.substring(0, typeString.length() - 2); CockroachDBCompositeDataType elementType = getColumnType(substring); return new CockroachDBCompositeDataType(CockroachDBDataType.ARRAY, elementType); } if (typeString.startsWith("STRING COLLATE")) { return new CockroachDBCompositeDataType(CockroachDBDataType.STRING); } if (typeString.startsWith("BIT(")) { int val = Integer.parseInt(typeString.substring(4, typeString.length() - 1)); return CockroachDBCompositeDataType.getBit(val); } if (typeString.startsWith("VARBIT(")) { int val = Integer.parseInt(typeString.substring(7, typeString.length() - 1)); return CockroachDBCompositeDataType.getBit(val); } switch (typeString) { case "VARBIT": return CockroachDBCompositeDataType.getVarBit(-1); case "BIT": return CockroachDBCompositeDataType.getBit(1); case "INT8": return CockroachDBCompositeDataType.getInt(8); case "INT4": return CockroachDBCompositeDataType.getInt(4); case "INT2": return CockroachDBCompositeDataType.getInt(2); case "BOOL": return new CockroachDBCompositeDataType(CockroachDBDataType.BOOL); case "STRING": return new CockroachDBCompositeDataType(CockroachDBDataType.STRING); case "FLOAT8": return new CockroachDBCompositeDataType(CockroachDBDataType.FLOAT); case "BYTES": return new CockroachDBCompositeDataType(CockroachDBDataType.BYTES); case "INTERVAL": return new CockroachDBCompositeDataType(CockroachDBDataType.INTERVAL); case "DECIMAL": return new CockroachDBCompositeDataType(CockroachDBDataType.DECIMAL); case "TIMESTAMP": return new CockroachDBCompositeDataType(CockroachDBDataType.TIMESTAMP); case "TIMESTAMPTZ": return new CockroachDBCompositeDataType(CockroachDBDataType.TIMESTAMPTZ); case "JSONB": return new CockroachDBCompositeDataType(CockroachDBDataType.JSONB); case "TIME": return new CockroachDBCompositeDataType(CockroachDBDataType.TIME); case "TIMETZ": return new CockroachDBCompositeDataType(CockroachDBDataType.TIMETZ); default: throw new AssertionError(typeString); } } public static class CockroachDBTable extends AbstractTable<CockroachDBColumn, TableIndex> { public CockroachDBTable(String tableName, List<CockroachDBColumn> columns, List<TableIndex> indexes, boolean isView) { super(tableName, columns, indexes, isView); } public boolean hasPrimaryKey() { return getColumns().stream().anyMatch(c -> c.isPrimaryKey()); } } public static CockroachDBSchema fromConnection(Connection con, String databaseName) throws SQLException { List<CockroachDBTable> databaseTables = new ArrayList<>(); List<String> tableNames = getTableNames(con); for (String tableName : tableNames) { List<CockroachDBColumn> databaseColumns = getTableColumns(con, tableName); List<TableIndex> indexes = getIndexes(con, tableName); boolean isView = tableName.startsWith("v"); CockroachDBTable t = new CockroachDBTable(tableName, databaseColumns, indexes, isView); for (CockroachDBColumn c : databaseColumns) { c.setTable(t); } databaseTables.add(t); } return new CockroachDBSchema(databaseTables); } private static List<String> getTableNames(Connection con) throws SQLException { List<String> tableNames = new ArrayList<>(); try (Statement s = con.createStatement()) { ResultSet tableRs = s.executeQuery( "SELECT table_name FROM information_schema.tables WHERE TABLE_TYPE IN ('BASE TABLE', 'LOCAL TEMPORARY');"); while (tableRs.next()) { String tableName = tableRs.getString(1); tableNames.add(tableName); } } return tableNames; } private static List<TableIndex> getIndexes(Connection con, String tableName) throws SQLException { List<TableIndex> indexes = new ArrayList<>(); try (Statement s = con.createStatement()) { try (ResultSet rs = s.executeQuery(String.format("SHOW INDEX FROM %s", tableName))) { while (rs.next()) { String indexName = rs.getString("index_name"); indexes.add(TableIndex.create(indexName)); } } } return indexes; } private static List<CockroachDBColumn> getTableColumns(Connection con, String tableName) throws SQLException { List<CockroachDBColumn> columns = new ArrayList<>(); try (Statement s = con.createStatement()) { try (ResultSet rs = s.executeQuery("SHOW COLUMNS FROM " + tableName)) { while (rs.next()) { String columnName = rs.getString("column_name"); if (columnName.contains("crdb_internal")) { continue; // created for CREATE INDEX ON t0(c0) USING HASH WITH BUCKET_COUNT = 1; } String dataType = rs.getString("data_type"); boolean isNullable = rs.getBoolean("is_nullable"); String indices = rs.getString("indices"); boolean isPrimaryKey = indices.contains("primary"); CockroachDBColumn c = new CockroachDBColumn(columnName, getColumnType(dataType), isPrimaryKey, isNullable); columns.add(c); } } } return columns; } }
/* * Copyright 1999-2018 Alibaba Group Holding Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.alibaba.nacos.api.naming; import com.alibaba.nacos.api.exception.NacosException; import java.lang.reflect.Constructor; import java.util.Properties; /** * Naming Factory. * * @author nkorange */ public class NamingFactory { /** * Create a new naming service. * * @param serverList server list * @return new naming service * @throws NacosException nacos exception */ public static NamingService createNamingService(String serverList) throws NacosException { try { Class<?> driverImplClass = Class.forName("com.alibaba.nacos.client.naming.NacosNamingService"); Constructor constructor = driverImplClass.getConstructor(String.class); NamingService vendorImpl = (NamingService) constructor.newInstance(serverList); return vendorImpl; } catch (Throwable e) { throw new NacosException(NacosException.CLIENT_INVALID_PARAM, e); } } /** * Create a new naming service. * * @param properties naming service properties * @return new naming service * @throws NacosException nacos exception */ public static NamingService createNamingService(Properties properties) throws NacosException { try { //其实就是通过反射来实例化,我们看下NamingService的构造方法中有没有进行特殊的初始化逻辑 Class<?> driverImplClass = Class.forName("com.alibaba.nacos.client.naming.NacosNamingService"); Constructor constructor = driverImplClass.getConstructor(Properties.class); NamingService vendorImpl = (NamingService) constructor.newInstance(properties); return vendorImpl; } catch (Throwable e) { throw new NacosException(NacosException.CLIENT_INVALID_PARAM, e); } } }
package com.google.api.services.sheets.v4.model; import com.google.api.client.util.Data; import com.google.api.client.util.GenericData; import com.google.api.client.util.Key; import java.util.List; import com.google.api.client.json.GenericJson; public final class Sheet extends GenericJson { @Key private List<BandedRange> bandedRanges; @Key private BasicFilter basicFilter; @Key private List<EmbeddedChart> charts; @Key private List<DimensionGroup> columnGroups; @Key private List<ConditionalFormatRule> conditionalFormats; @Key private List<GridData> data; @Key private List<DeveloperMetadata> developerMetadata; @Key private List<FilterView> filterViews; @Key private List<GridRange> merges; @Key private SheetProperties properties; @Key private List<ProtectedRange> protectedRanges; @Key private List<DimensionGroup> rowGroups; public List<BandedRange> getBandedRanges() { /*SL:141*/return this.bandedRanges; } public Sheet setBandedRanges(final List<BandedRange> bandedRanges) { /*SL:149*/this.bandedRanges = bandedRanges; /*SL:150*/return this; } public BasicFilter getBasicFilter() { /*SL:158*/return this.basicFilter; } public Sheet setBasicFilter(final BasicFilter basicFilter) { /*SL:166*/this.basicFilter = basicFilter; /*SL:167*/return this; } public List<EmbeddedChart> getCharts() { /*SL:175*/return this.charts; } public Sheet setCharts(final List<EmbeddedChart> charts) { /*SL:183*/this.charts = charts; /*SL:184*/return this; } public List<DimensionGroup> getColumnGroups() { /*SL:192*/return this.columnGroups; } public Sheet setColumnGroups(final List<DimensionGroup> columnGroups) { /*SL:200*/this.columnGroups = columnGroups; /*SL:201*/return this; } public List<ConditionalFormatRule> getConditionalFormats() { /*SL:209*/return this.conditionalFormats; } public Sheet setConditionalFormats(final List<ConditionalFormatRule> conditionalFormats) { /*SL:217*/this.conditionalFormats = conditionalFormats; /*SL:218*/return this; } public List<GridData> getData() { /*SL:230*/return this.data; } public Sheet setData(final List<GridData> data) { /*SL:242*/this.data = data; /*SL:243*/return this; } public List<DeveloperMetadata> getDeveloperMetadata() { /*SL:251*/return this.developerMetadata; } public Sheet setDeveloperMetadata(final List<DeveloperMetadata> developerMetadata) { /*SL:259*/this.developerMetadata = developerMetadata; /*SL:260*/return this; } public List<FilterView> getFilterViews() { /*SL:268*/return this.filterViews; } public Sheet setFilterViews(final List<FilterView> filterViews) { /*SL:276*/this.filterViews = filterViews; /*SL:277*/return this; } public List<GridRange> getMerges() { /*SL:285*/return this.merges; } public Sheet setMerges(final List<GridRange> merges) { /*SL:293*/this.merges = merges; /*SL:294*/return this; } public SheetProperties getProperties() { /*SL:302*/return this.properties; } public Sheet setProperties(final SheetProperties properties) { /*SL:310*/this.properties = properties; /*SL:311*/return this; } public List<ProtectedRange> getProtectedRanges() { /*SL:319*/return this.protectedRanges; } public Sheet setProtectedRanges(final List<ProtectedRange> protectedRanges) { /*SL:327*/this.protectedRanges = protectedRanges; /*SL:328*/return this; } public List<DimensionGroup> getRowGroups() { /*SL:336*/return this.rowGroups; } public Sheet setRowGroups(final List<DimensionGroup> rowGroups) { /*SL:344*/this.rowGroups = rowGroups; /*SL:345*/return this; } public Sheet set(final String a1, final Object a2) { /*SL:350*/return (Sheet)super.set(a1, a2); } public Sheet clone() { /*SL:355*/return (Sheet)super.clone(); } static { Data.<Object>nullOf(EmbeddedChart.class); Data.<Object>nullOf(GridData.class); } }
package guru.springframework.sfgpetclinic.fauxspring; import java.util.HashMap; import java.util.Map; public class ModelMapImpl implements Model{ Map<String,Object> map = new HashMap<>(); @Override public void addAttribute(String key, Object o) { map.put(key,o); } @Override public void addAttribute(Object o) { //do nothing } public Map<String, Object> getMap() { return map; } }
/* * 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 * * 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.apache.directory.api.ldap.extras.controls.vlv_impl; import org.apache.directory.api.asn1.actions.AbstractReadInteger; /** * The action used to store the contentCount value in VLV response * * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> */ public class StoreContentCountResponse extends AbstractReadInteger<VirtualListViewResponseContainer> { /** * Instantiates a new ContentCount action. */ public StoreContentCountResponse() { super( "VirtualListViewResponse contentCount" ); } /** * {@inheritDoc} */ @Override protected void setIntegerValue( int value, VirtualListViewResponseContainer vlvContainer ) { vlvContainer.getVirtualListViewResponse().setContentCount( value ); } }
/* * Copyright 2020 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.drools.traits.core.factmodel; import java.io.Serializable; import java.util.Collection; import java.util.Map; import java.util.Set; import org.drools.core.factmodel.BuildUtils; import org.drools.core.factmodel.ClassDefinition; import org.drools.core.factmodel.FieldDefinition; import org.drools.core.factmodel.traits.TraitFieldTMS; import org.drools.core.factmodel.traits.TraitableBean; import org.drools.mvel.asm.AsmUtil; import org.mvel2.asm.Label; import org.mvel2.asm.MethodVisitor; import org.mvel2.asm.Type; public abstract class AbstractPropertyWrapperClassBuilderImpl implements TraitPropertyWrapperClassBuilder, Serializable { protected transient ClassDefinition trait; protected transient TraitRegistryImpl traitRegistryImpl; protected ClassDefinition getTrait() { return trait; } public void init(ClassDefinition trait, TraitRegistryImpl traitRegistryImpl) { this.trait = trait; this.traitRegistryImpl = traitRegistryImpl; } protected void invokePut(MethodVisitor mv, String wrapperName, ClassDefinition core, String fieldName, FieldDefinition field) { mv.visitLdcInsn(fieldName); mv.visitVarInsn(ALOAD, 1); mv.visitMethodInsn(INVOKEVIRTUAL, Type.getInternalName(String.class), "equals", "(" + Type.getDescriptor(Object.class) + ")Z", false); Label l1 = new Label(); mv.visitJumpInsn(IFEQ, l1); mv.visitVarInsn(ALOAD, 2); if (BuildUtils.isPrimitive(field.getTypeName())) { TraitFactoryImpl.primitiveValue(mv, field.getTypeName()); mv.visitVarInsn( AsmUtil.storeType(field.getTypeName()), 3); TraitFactoryImpl.invokeInjector(mv, wrapperName, core, field, false, 3); } else { TraitFactoryImpl.invokeInjector(mv, wrapperName, core, field, false, 2); } mv.visitVarInsn(ALOAD, 2); mv.visitInsn(ARETURN); mv.visitLabel(l1); } protected void invokeRemove(MethodVisitor mv, String wrapperName, ClassDefinition core, String fieldName, FieldDefinition field) { mv.visitLdcInsn(fieldName); mv.visitVarInsn(ALOAD, 1); mv.visitMethodInsn(INVOKEVIRTUAL, Type.getInternalName(String.class), "equals", "(" + Type.getDescriptor(Object.class) + ")Z", false); Label l1 = new Label(); mv.visitJumpInsn(IFEQ, l1); TraitFactoryImpl.invokeExtractor(mv, wrapperName, core, field); if (BuildUtils.isPrimitive(field.getTypeName())) { TraitFactoryImpl.valueOf(mv, field.getTypeName()); } mv.visitVarInsn(ASTORE, 2); TraitFactoryImpl.invokeInjector(mv, wrapperName, core, field, true, 1); mv.visitVarInsn(ALOAD, 2); mv.visitInsn(ARETURN); mv.visitLabel(l1); } protected void registerLogicalField(MethodVisitor mv, String internalWrapper, FieldDefinition field, ClassDefinition core) { mv.visitVarInsn(ALOAD, 0); mv.visitFieldInsn(GETFIELD, internalWrapper, "object", Type.getDescriptor(core.getDefinedClass())); mv.visitTypeInsn(CHECKCAST, Type.getInternalName(TraitableBean.class)); mv.visitMethodInsn(INVOKEINTERFACE, Type.getInternalName(TraitableBean.class), "_getFieldTMS", Type.getMethodDescriptor(Type.getType(TraitFieldTMS.class)), true); mv.visitVarInsn(ASTORE, 1); mv.visitVarInsn(ALOAD, 1); mv.visitLdcInsn(field.resolveAlias()); mv.visitMethodInsn(INVOKEINTERFACE, Type.getInternalName(TraitFieldTMS.class), "isManagingField", Type.getMethodDescriptor(Type.BOOLEAN_TYPE, Type.getType(String.class)), true); Label l1 = new Label(); mv.visitJumpInsn(IFNE, l1); mv.visitVarInsn(ALOAD, 1); mv.visitLdcInsn(Type.getType(BuildUtils.getTypeDescriptor(core.getClassName()))); mv.visitLdcInsn(field.resolveAlias()); mv.visitMethodInsn(INVOKEINTERFACE, Type.getInternalName(TraitFieldTMS.class), "registerField", Type.getMethodDescriptor(Type.VOID_TYPE, Type.getType(Class.class), Type.getType(String.class)), true); mv.visitLabel(l1); } protected void invokeContainsKey(MethodVisitor mv, String fieldName) { mv.visitLdcInsn(fieldName); mv.visitVarInsn(ALOAD, 1); mv.visitMethodInsn(INVOKEVIRTUAL, Type.getInternalName(String.class), "equals", "(" + Type.getDescriptor(Object.class) + ")Z", false); Label l0 = new Label(); mv.visitJumpInsn(IFEQ, l0); mv.visitInsn(ICONST_1); mv.visitInsn(IRETURN); mv.visitLabel(l0); } protected void buildEntry(MethodVisitor mv, FieldDefinition field, String wrapperName, ClassDefinition core) { mv.visitVarInsn(ALOAD, 1); mv.visitLdcInsn(field.getName()); TraitFactoryImpl.invokeExtractor(mv, wrapperName, core, field); if (BuildUtils.isPrimitive(field.getTypeName())) { TraitFactoryImpl.valueOf(mv, field.getTypeName()); } mv.visitMethodInsn(INVOKESTATIC, Type.getInternalName(TraitProxyImpl.class), "buildEntry", "(" + Type.getDescriptor(String.class) + Type.getDescriptor(Object.class) + ")" + Type.getDescriptor(Map.Entry.class), false); mv.visitMethodInsn(INVOKEINTERFACE, Type.getInternalName(Set.class), "add", "(" + Type.getDescriptor(Object.class) + ")Z", true); mv.visitInsn(POP); } protected void extractAndCollect(MethodVisitor mv, String wrapperName, FieldDefinition field, ClassDefinition core) { mv.visitVarInsn(ALOAD, 1); TraitFactoryImpl.invokeExtractor(mv, wrapperName, core, field); if (BuildUtils.isPrimitive(field.getTypeName())) { TraitFactoryImpl.valueOf(mv, field.getTypeName()); } mv.visitMethodInsn(INVOKEINTERFACE, Type.getInternalName(Collection.class), "add", "(" + Type.getDescriptor(Object.class) + ")Z", true); mv.visitInsn(POP); } protected void extractAndTestNotNull(MethodVisitor mv, String wrapperName, ClassDefinition core, FieldDefinition field) { TraitFactoryImpl.invokeExtractor(mv, wrapperName, core, field); Label l1 = new Label(); mv.visitJumpInsn(IFNONNULL, l1); mv.visitInsn(ICONST_1); mv.visitInsn(IRETURN); mv.visitLabel(l1); } protected void collectFieldName(MethodVisitor mv, FieldDefinition field) { mv.visitVarInsn(ALOAD, 1); mv.visitLdcInsn(field.getName()); mv.visitMethodInsn(INVOKEINTERFACE, Type.getInternalName(Set.class), "add", "(" + Type.getDescriptor(Object.class) + ")Z", true); mv.visitInsn(POP); } }
package com.conveyal.r5.analyst.cluster; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; /** * Keep track of tasks throughput on worker, grouped by job. * All public methods should be synchronized since they will be called by several different threads at once. */ public class ThroughputTracker { /** * A list of times at which tasks have been completed. Regularly truncated to only times in the last minute. * This allows reporting average throughput over different timescales up to one minute. * TODO replace Long times with TaskStats containing more info about compute time breakdown */ private Map<String, List<Long>> recentTaskCompletionTimesByJob = new HashMap<>(); /** * Indicate to the tracker that a task has just been completed for the specified job. */ public synchronized void recordTaskCompletion(String jobId) { List<Long> times = recentTaskCompletionTimesByJob.get(jobId); if (times == null) { // Use a linked list so that elsewhere we can efficiently repeatedly remove the zeroth element. times = new LinkedList<>(); recentTaskCompletionTimesByJob.put(jobId, times); } times.add(System.currentTimeMillis()); } /** * @return the number of tasks completed in the last minute, broken down by job. Intended to be serialized as JSON. */ public synchronized Map<String, Integer> getTasksPerMinuteByJobId () { // First clear out all tasks more than one minute old for every job. removeOldTasks(); // Then summarize how many tasks were recorded in the last minute for each job. Map<String, Integer> tasksPerMinuteByJobId = new HashMap<>(); recentTaskCompletionTimesByJob.forEach((jobId, times) -> tasksPerMinuteByJobId.put(jobId, times.size())); return tasksPerMinuteByJobId; } /** * Remove all tasks from the per-job lists that are more than 1 minute old. * Any jobs for which no tasks have been finished in the last minute will be removed from the map. */ private synchronized void removeOldTasks () { long oneMinuteAgo = System.currentTimeMillis() - 1000 * 60; Iterator<Map.Entry<String, List<Long>>> iterator = recentTaskCompletionTimesByJob.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<String, List<Long>> entry = iterator.next(); List<Long> times = entry.getValue(); while (!times.isEmpty() && times.get(0) < oneMinuteAgo) { // For efficiency this should be operating on a linked list rather than an array. times.remove(0); } if (times.isEmpty()) iterator.remove(); } } }
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.compositor.bottombar.contextualsearch; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.content.Context; import android.view.ViewGroup; import androidx.annotation.VisibleForTesting; import org.chromium.base.ApiCompatibilityUtils; import org.chromium.chrome.R; import org.chromium.chrome.browser.compositor.animation.CompositorAnimator; import org.chromium.chrome.browser.compositor.bottombar.OverlayPanelAnimation; import org.chromium.chrome.browser.contextualsearch.QuickActionCategory; import org.chromium.chrome.browser.flags.ChromeFeatureList; import org.chromium.ui.base.LocalizationUtils; import org.chromium.ui.resources.dynamics.DynamicResourceLoader; /** * Controls the Search Bar in the Contextual Search Panel. */ public class ContextualSearchBarControl { /** Full opacity -- fully visible. */ private static final float FULL_OPACITY = 1.0f; /** Transparent opacity -- completely transparent (not visible). */ private static final float TRANSPARENT_OPACITY = 0.0f; /** * The panel used to get information about the panel layout. */ protected ContextualSearchPanel mContextualSearchPanel; /** * The {@link ContextualSearchContextControl} used to control the Search Context View. */ private final ContextualSearchContextControl mContextControl; /** * The {@link ContextualSearchTermControl} used to control the Search Term View. */ private final ContextualSearchTermControl mSearchTermControl; /** * The {@link ContextualSearchCaptionControl} used to control the Caption View. */ private final ContextualSearchCaptionControl mCaptionControl; /** * The {@link ContextualSearchQuickActionControl} used to control quick action behavior. */ private final ContextualSearchQuickActionControl mQuickActionControl; /** * The {@link ContextualSearchCardIconControl} used to control icons for non-action Cards * returned by the server. */ private final ContextualSearchCardIconControl mCardIconControl; /** The width of our icon, including padding, in pixels. */ private final float mPaddedIconWidthPx; /** * The {@link ContextualSearchImageControl} for the panel. */ private ContextualSearchImageControl mImageControl; /** * The opacity of the Bar's Search Context. * This text control may not be initialized until the opacity is set beyond 0. */ private float mSearchBarContextOpacity; /** * The opacity of the Bar's Search Term. * This text control may not be initialized until the opacity is set beyond 0. */ private float mSearchBarTermOpacity; // Dimensions used for laying out the search bar. private final float mTextLayerMinHeight; private final float mTermCaptionSpacing; /** * The visibility percentage for the divider line ranging from 0.f to 1.f. */ private float mDividerLineVisibilityPercentage; /** * The width of the divider line in px. */ private final float mDividerLineWidth; /** * The height of the divider line in px. */ private final float mDividerLineHeight; /** * The divider line color. */ private final int mDividerLineColor; /** * The width of the end button in px. */ private final float mEndButtonWidth; /** * The percentage the panel is expanded. 1.f is fully expanded and 0.f is peeked. */ private float mExpandedPercent; /** * Converts dp dimensions to pixels. */ private final float mDpToPx; /** * Whether the panel contents can be promoted to a new tab. */ private final boolean mCanPromoteToNewTab; /** The animator that controls the text opacity. */ private CompositorAnimator mTextOpacityAnimation; /** The animator that controls the divider line visibility. */ private CompositorAnimator mDividerLineVisibilityAnimation; /** The animator that controls touch highlighting. */ private CompositorAnimator mTouchHighlightAnimation; /** * Constructs a new bottom bar control container by inflating views from XML. * * @param panel The panel. * @param container The parent view for the bottom bar views. * @param loader The resource loader that will handle the snapshot capturing. */ public ContextualSearchBarControl(ContextualSearchPanel panel, Context context, ViewGroup container, DynamicResourceLoader loader) { mContextualSearchPanel = panel; mCanPromoteToNewTab = panel.canPromoteToNewTab(); mImageControl = new ContextualSearchImageControl(panel); mContextControl = new ContextualSearchContextControl(panel, context, container, loader); mSearchTermControl = new ContextualSearchTermControl(panel, context, container, loader); mCaptionControl = new ContextualSearchCaptionControl( panel, context, container, loader, mCanPromoteToNewTab); mQuickActionControl = new ContextualSearchQuickActionControl(context, loader); mCardIconControl = new ContextualSearchCardIconControl(context, loader); mTextLayerMinHeight = context.getResources().getDimension( R.dimen.contextual_search_text_layer_min_height); mTermCaptionSpacing = context.getResources().getDimension( R.dimen.contextual_search_term_caption_spacing); // Divider line values. mDividerLineWidth = context.getResources().getDimension( R.dimen.contextual_search_divider_line_width); mDividerLineHeight = context.getResources().getDimension( R.dimen.contextual_search_divider_line_height); mDividerLineColor = ApiCompatibilityUtils.getColor( context.getResources(), R.color.contextual_search_divider_line_color); // Icon attributes. mPaddedIconWidthPx = context.getResources().getDimension(R.dimen.contextual_search_padded_button_width); mEndButtonWidth = mPaddedIconWidthPx + context.getResources().getDimension(R.dimen.overlay_panel_button_padding); mDpToPx = context.getResources().getDisplayMetrics().density; } /** * @return The {@link ContextualSearchImageControl} for the panel. */ public ContextualSearchImageControl getImageControl() { return mImageControl; } /** * Returns the minimum height that the text layer (containing the Search Context, Term and * Caption) should be. */ public float getTextLayerMinHeight() { return mTextLayerMinHeight; } /** * Returns the spacing that should be placed between the Search Term and Caption. */ public float getSearchTermCaptionSpacing() { return mTermCaptionSpacing; } /** * Removes the bottom bar views from the parent container. */ public void destroy() { mContextControl.destroy(); mSearchTermControl.destroy(); mCaptionControl.destroy(); mQuickActionControl.destroy(); mCardIconControl.destroy(); } /** * Updates this bar when in transition between closed to peeked states. * @param percentage The percentage to the more opened state. */ public void onUpdateFromCloseToPeek(float percentage) { // #onUpdateFromPeekToExpanded() never reaches the 0.f value because this method is called // instead. If the panel is fully peeked, call #onUpdateFromPeekToExpanded(). if (percentage == FULL_OPACITY) onUpdateFromPeekToExpand(TRANSPARENT_OPACITY); // When the panel is completely closed the caption and custom image should be hidden. if (percentage == TRANSPARENT_OPACITY) { mQuickActionControl.reset(); mCaptionControl.hide(); getImageControl().hideCustomImage(false); } } /** * Updates this bar when in transition between peeked to expanded states. * @param percentage The percentage to the more opened state. */ public void onUpdateFromPeekToExpand(float percentage) { mExpandedPercent = percentage; // If there is a quick action, the divider line's appearance was animated when the quick // action was set. if (!getQuickActionControl().hasQuickAction() && !ChromeFeatureList.isEnabled(ChromeFeatureList.OVERLAY_NEW_LAYOUT)) { mDividerLineVisibilityPercentage = percentage; } getImageControl().onUpdateFromPeekToExpand(percentage); mCaptionControl.onUpdateFromPeekToExpand(percentage); mSearchTermControl.onUpdateFromPeekToExpand(percentage); mContextControl.onUpdateFromPeekToExpand(percentage); } /** * Sets the details of the context to display in the control. * @param selection The portion of the context that represents the user's selection. * @param end The portion of the context after the selection. */ public void setContextDetails(String selection, String end) { cancelSearchTermResolutionAnimation(); hideCaption(); mQuickActionControl.reset(); mContextControl.setContextDetails(selection, end); resetSearchBarContextOpacity(); animateDividerLine(false); } /** * Updates the Bar to display a dictionary definition card. * @param searchTerm The string that represents the search term to display. */ public void updateForDictionaryDefinition(String searchTerm) { if (!mCardIconControl.didUpdateControlsForDefinition( mContextControl, mImageControl, searchTerm)) { // Can't style, just update with the text to display. setSearchTerm(searchTerm); animateSearchTermResolution(); } } /** * Sets the search term to display in the control. * @param searchTerm The string that represents the search term. */ public void setSearchTerm(String searchTerm) { cancelSearchTermResolutionAnimation(); hideCaption(); mQuickActionControl.reset(); mSearchTermControl.setSearchTerm(searchTerm); resetSearchBarTermOpacity(); // If the panel is expanded, the divider line should not be hidden. This may happen if the // panel is opened before the search term is resolved. if (mExpandedPercent == TRANSPARENT_OPACITY) animateDividerLine(false); } /** * Sets the caption to display in the control and sets the caption visible. * @param caption The caption to display. */ public void setCaption(String caption) { mCaptionControl.setCaption(caption); } /** * Gets the current animation percentage for the Caption control, which guides the vertical * position and opacity of the caption. * @return The animation percentage ranging from 0.0 to 1.0. * */ public float getCaptionAnimationPercentage() { return mCaptionControl.getAnimationPercentage(); } /** * @return Whether the caption control is visible. */ public boolean getCaptionVisible() { return mCaptionControl.getIsVisible(); } /** * @return The Id of the Search Context View. */ public int getSearchContextViewId() { return mContextControl.getViewId(); } /** * @return The Id of the Search Term View. */ public int getSearchTermViewId() { return mSearchTermControl.getViewId(); } /** * @return The Id of the Search Caption View. */ public int getCaptionViewId() { return mCaptionControl.getViewId(); } /** * @return The text currently showing in the caption view. */ @VisibleForTesting public CharSequence getCaptionText() { return mCaptionControl.getCaptionText(); } /** * @return The opacity of the SearchBar's search context. */ public float getSearchBarContextOpacity() { return mSearchBarContextOpacity; } /** * @return The opacity of the SearchBar's search term. */ public float getSearchBarTermOpacity() { return mSearchBarTermOpacity; } /** * Sets the quick action if one is available. * @param quickActionUri The URI for the intent associated with the quick action. * @param quickActionCategory The {@link QuickActionCategory} for the quick action. * @param toolbarBackgroundColor The current toolbar background color. This may be used for * icon tinting. */ public void setQuickAction(String quickActionUri, @QuickActionCategory int quickActionCategory, int toolbarBackgroundColor) { mQuickActionControl.setQuickAction( quickActionUri, quickActionCategory, toolbarBackgroundColor); if (mQuickActionControl.hasQuickAction()) { // TODO(twellington): should the quick action caption be stored separately from the // regular caption? mCaptionControl.setCaption(mQuickActionControl.getCaption()); mImageControl.setCardIconResourceId(mQuickActionControl.getIconResId()); animateDividerLine(true); } } /** * @return The {@link ContextualSearchQuickActionControl} for the panel. */ public ContextualSearchQuickActionControl getQuickActionControl() { return mQuickActionControl; } /** * Resets the SearchBar text opacity when a new search context is set. The search * context is made visible and the search term invisible. */ private void resetSearchBarContextOpacity() { mSearchBarContextOpacity = FULL_OPACITY; mSearchBarTermOpacity = TRANSPARENT_OPACITY; } /** * Resets the SearchBar text opacity when a new search term is set. The search * term is made visible and the search context invisible. */ private void resetSearchBarTermOpacity() { mSearchBarContextOpacity = TRANSPARENT_OPACITY; mSearchBarTermOpacity = FULL_OPACITY; } /** * Hides the caption so it will not be displayed in the control. */ private void hideCaption() { mCaptionControl.hide(); } // ============================================================================================ // Divider Line // ============================================================================================ /** * @return The visibility percentage for the divider line ranging from 0.f to 1.f. */ public float getDividerLineVisibilityPercentage() { return mDividerLineVisibilityPercentage; } /** * @return The width of the divider line in px. */ public float getDividerLineWidth() { return mDividerLineWidth; } /** * @return The height of the divider line in px. */ public float getDividerLineHeight() { return mDividerLineHeight; } /** * @return The divider line color. */ public int getDividerLineColor() { return mDividerLineColor; } /** * @return The x-offset for the divider line relative to the x-position of the Bar in px. */ public float getDividerLineXOffset() { if (LocalizationUtils.isLayoutRtl()) { return mEndButtonWidth; } else { return mContextualSearchPanel.getContentViewWidthPx() - mEndButtonWidth - getDividerLineWidth(); } } /** * Animates the appearance or disappearance of the divider line. * @param visible Whether the divider line should be made visible. */ private void animateDividerLine(boolean visible) { if (ChromeFeatureList.isEnabled(ChromeFeatureList.OVERLAY_NEW_LAYOUT)) return; float endValue = visible ? FULL_OPACITY : TRANSPARENT_OPACITY; if (mDividerLineVisibilityPercentage == endValue) return; if (mDividerLineVisibilityAnimation != null) mDividerLineVisibilityAnimation.cancel(); mDividerLineVisibilityAnimation = CompositorAnimator.ofFloat( mContextualSearchPanel.getAnimationHandler(), mDividerLineVisibilityPercentage, endValue, OverlayPanelAnimation.BASE_ANIMATION_DURATION_MS, null); mDividerLineVisibilityAnimation.addUpdateListener( animator -> mDividerLineVisibilityPercentage = animator.getAnimatedValue()); mDividerLineVisibilityAnimation.start(); } // ============================================================================================ // Touch Highlight // ============================================================================================ /** * Whether the touch highlight is visible. */ private boolean mTouchHighlightVisible; /** * Whether the touch that triggered showing the touch highlight was on the end Bar button. */ private boolean mWasTouchOnEndButton; /** * Whether the divider line was visible when the touch highlight started showing. */ private boolean mWasDividerVisibleOnTouch; /** Where the touch highlight should start, in pixels. */ private float mTouchHighlightXOffsetPx; /** The width of the touch highlight, in pixels. */ private float mTouchHighlightWidthPx; /** * @return Whether the touch highlight is visible. */ public boolean getTouchHighlightVisible() { return mTouchHighlightVisible; } /** * @return The x-offset of the touch highlight in pixels. */ public float getTouchHighlightXOffsetPx() { if (ChromeFeatureList.isEnabled(ChromeFeatureList.OVERLAY_NEW_LAYOUT)) { return mTouchHighlightXOffsetPx; } if (mWasDividerVisibleOnTouch && ((mWasTouchOnEndButton && !LocalizationUtils.isLayoutRtl()) || (!mWasTouchOnEndButton && LocalizationUtils.isLayoutRtl()))) { // If the touch was on the end button in LTR, offset the touch highlight so that it // starts at the beginning of the end button. // If the touch was not on the end button in RTL, offset the touch highlight so that it // starts after the end button. return getDividerLineXOffset() + getDividerLineWidth(); } return 0; } /** * @return The width of the touch highlight in pixels. */ public float getTouchHighlightWidthPx() { if (ChromeFeatureList.isEnabled(ChromeFeatureList.OVERLAY_NEW_LAYOUT)) { return mTouchHighlightWidthPx; } if (mWasDividerVisibleOnTouch) { // The touch was on the end button so the touch highlight should cover the end button. if (mWasTouchOnEndButton) return mEndButtonWidth; // The touch was not on the end button so the touch highlight should cover everything // except the end button. return mContextualSearchPanel.getContentViewWidthPx() - mEndButtonWidth - getDividerLineWidth(); } // If the divider line wasn't visible when the Bar was touched, the touch highlight covers // the entire Bar. return mContextualSearchPanel.getContentViewWidthPx(); } /** * Should be called when the Bar is clicked. * @param xDps The x-position of the click in DPs. */ public void onSearchBarClick(float xDps) { showTouchHighlight(xDps * mDpToPx); } /** * Should be called when an onShowPress() event occurs on the Bar. * See {@code GestureDetector.SimpleOnGestureListener#onShowPress()}. * @param xDps The x-position of the touch in DPs. */ public void onShowPress(float xDps) { showTouchHighlight(xDps * mDpToPx); } /** * Classifies the give x position in pixels and computes the highlight offset and width. * @param xPx The x-coordinate of a touch location, in pixels. */ private void classifyTouchLocation(float xPx) { assert ChromeFeatureList.isEnabled(ChromeFeatureList.OVERLAY_NEW_LAYOUT); // There are 3 cases: // 1) The whole Bar (without any icons) // 2) The Bar minus icon (when the icon is present) // 3) The icon int panelWidth = mContextualSearchPanel.getContentViewWidthPx(); if (mContextualSearchPanel.isPeeking()) { // Case 1 - whole Bar. mTouchHighlightXOffsetPx = 0; mTouchHighlightWidthPx = panelWidth; } else { // The open-tab-icon is on the right (on the left in RTL). boolean isRtl = LocalizationUtils.isLayoutRtl(); float paddedIconWithMarginWidth = (mContextualSearchPanel.getBarMarginSide() + mContextualSearchPanel.getOpenTabIconDimension() + mContextualSearchPanel.getButtonPaddingDps()) * mDpToPx; float contentWidth = panelWidth - paddedIconWithMarginWidth; // Adjust the touch point to panel coordinates. xPx -= mContextualSearchPanel.getOffsetX() * mDpToPx; if (isRtl && xPx > paddedIconWithMarginWidth || !isRtl && xPx < contentWidth) { // Case 2 - Bar minus icon. mTouchHighlightXOffsetPx = isRtl ? paddedIconWithMarginWidth : 0; mTouchHighlightWidthPx = contentWidth; } else { // Case 3 - the icon. mTouchHighlightXOffsetPx = isRtl ? 0 : contentWidth; mTouchHighlightWidthPx = paddedIconWithMarginWidth; } } } /** * Shows the touch highlight if it is not already visible. * @param x The x-position of the touch in px. */ private void showTouchHighlight(float x) { if (mTouchHighlightVisible) return; mWasTouchOnEndButton = isTouchOnEndButton(x); // If the panel is expanded or maximized and the panel content cannot be promoted to a new // tab, then tapping anywhere besides the end buttons does nothing. In this case, the touch // highlight should not be shown. if (!mContextualSearchPanel.isPeeking() && !mCanPromoteToNewTab) return; if (ChromeFeatureList.isEnabled(ChromeFeatureList.OVERLAY_NEW_LAYOUT)) { classifyTouchLocation(x); } else { mWasDividerVisibleOnTouch = getDividerLineVisibilityPercentage() > TRANSPARENT_OPACITY; } mTouchHighlightVisible = true; // The touch highlight animation is used to ensure the touch highlight is visible for at // least OverlayPanelAnimation.BASE_ANIMATION_DURATION_MS. // TODO(donnd): Add a material ripple to this animation. if (mTouchHighlightAnimation == null) { mTouchHighlightAnimation = new CompositorAnimator(mContextualSearchPanel.getAnimationHandler()); mTouchHighlightAnimation.setDuration(OverlayPanelAnimation.BASE_ANIMATION_DURATION_MS); mTouchHighlightAnimation.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { mTouchHighlightVisible = false; } }); } mTouchHighlightAnimation.cancel(); mTouchHighlightAnimation.start(); } /** * @param xPx The x-position of the touch in px. * @return Whether the touch occurred on the search Bar's end button. */ private boolean isTouchOnEndButton(float xPx) { if (getDividerLineVisibilityPercentage() == TRANSPARENT_OPACITY) return false; // Adjust the touch position to compensate for the narrow panel. xPx -= mContextualSearchPanel.getOffsetX() * mDpToPx; if (LocalizationUtils.isLayoutRtl()) return xPx <= getDividerLineXOffset(); return xPx > getDividerLineXOffset(); } // ============================================================================================ // Search Bar Animation // ============================================================================================ /** * Animates the search term resolution. */ public void animateSearchTermResolution() { if (mTextOpacityAnimation == null) { mTextOpacityAnimation = CompositorAnimator.ofFloat( mContextualSearchPanel.getAnimationHandler(), TRANSPARENT_OPACITY, FULL_OPACITY, OverlayPanelAnimation.BASE_ANIMATION_DURATION_MS, null); mTextOpacityAnimation.addUpdateListener( animator -> updateSearchBarTextOpacity(animator.getAnimatedValue())); } mTextOpacityAnimation.cancel(); mTextOpacityAnimation.start(); } /** * Cancels the search term resolution animation if it is in progress. */ public void cancelSearchTermResolutionAnimation() { if (mTextOpacityAnimation != null) mTextOpacityAnimation.cancel(); } /** * Updates the UI state for the SearchBar text. The search context view will fade out * while the search term fades in. * * @param percentage The visibility percentage of the search term view. */ private void updateSearchBarTextOpacity(float percentage) { // The search context will start fading out before the search term starts fading in. // They will both be partially visible for overlapPercentage of the animation duration. float overlapPercentage = .75f; float fadingOutPercentage = Math.max(1 - (percentage / overlapPercentage), TRANSPARENT_OPACITY); float fadingInPercentage = Math.max(percentage - (1 - overlapPercentage), TRANSPARENT_OPACITY) / overlapPercentage; mSearchBarContextOpacity = fadingOutPercentage; mSearchBarTermOpacity = fadingInPercentage; } }
// tag::copyright[] /******************************************************************************* * Copyright (c) 2018 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - Initial implementation *******************************************************************************/ // end::copyright[] package it.io.openliberty.sample; import static org.junit.jupiter.api.Assertions.assertEquals; import javax.json.JsonObject; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.Response; import org.apache.cxf.jaxrs.provider.jsrjsonp.JsrJsonpProvider; import org.junit.jupiter.api.Test; public class PropertiesEndpointIT { @Test public void testGetProperties() { // system properties String port = System.getProperty("http.port"); String contextRoot = System.getProperty("context.root", "/"); String url = "http://localhost:" + port; // + contextRoot; // client setup Client client = ClientBuilder.newClient(); client.register(JsrJsonpProvider.class); // request WebTarget target = client.target(url + "/system/properties"); Response response = target.request().get(); // response assertEquals(200, response.getStatus(), "Incorrect response code from " + url); JsonObject obj = response.readEntity(JsonObject.class); response.close(); } }
// Copyright 2016 The Nomulus Authors. 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 google.registry.flows; import com.google.appengine.api.users.UserService; import google.registry.request.Action; import google.registry.request.Action.Method; import google.registry.request.Payload; import javax.inject.Inject; import javax.servlet.http.HttpSession; /** Runs EPP from the console and requires GAE user authentication. */ @Action( path = "/registrar-xhr", xsrfProtection = true, xsrfScope = EppConsoleAction.XSRF_SCOPE, method = Method.POST) public class EppConsoleAction implements Runnable { public static final String XSRF_SCOPE = "console"; @Inject @Payload byte[] inputXmlBytes; @Inject HttpSession session; @Inject EppRequestHandler eppRequestHandler; @Inject UserService userService; @Inject EppConsoleAction() {} @Override public void run() { eppRequestHandler.executeEpp( new HttpSessionMetadata(session), GaeUserCredentials.forCurrentUser(userService), EppRequestSource.CONSOLE, false, // This endpoint is never a dry run. false, // This endpoint is never a superuser. inputXmlBytes); } }
package bzh.tibus29.spring.metrik.services; import bzh.tibus29.spring.metrik.Metrik; import bzh.tibus29.spring.metrik.TraceMode; import org.springframework.stereotype.Service; @Service @Metrik(timeMode = Metrik.TimeMode.MILLIS, traceMode = TraceMode.AUTO) public class MetrikOnClassService extends MetrikTestBusiness { @Override public void doSomething() { super.doSomething(); } @Override @Metrik(enabled = false) public String sayHello(String to) { return super.sayHello(to); } @Override @Metrik(value = "TITI", timeMode = Metrik.TimeMode.NANO, traceMode = TraceMode.AUTO) public int add(int a, int b) { return super.add(a, b); } @Override @Metrik public void failingMethod() { super.failingMethod(); } }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.aliyuncs.scdn.model.v20171115; import com.aliyuncs.RpcAcsRequest; /** * @author auto create * @version */ public class DescribeScdnUserQuotaRequest extends RpcAcsRequest<DescribeScdnUserQuotaResponse> { public DescribeScdnUserQuotaRequest() { super("scdn", "2017-11-15", "DescribeScdnUserQuota"); } private String securityToken; private Long ownerId; public String getSecurityToken() { return this.securityToken; } public void setSecurityToken(String securityToken) { this.securityToken = securityToken; if(securityToken != null){ putQueryParameter("SecurityToken", securityToken); } } public Long getOwnerId() { return this.ownerId; } public void setOwnerId(Long ownerId) { this.ownerId = ownerId; if(ownerId != null){ putQueryParameter("OwnerId", ownerId.toString()); } } @Override public Class<DescribeScdnUserQuotaResponse> getResponseClass() { return DescribeScdnUserQuotaResponse.class; } }
package com.bdxh.onecard.service.impl; /** * @description: 虚拟卡管理service实现 * @author: xuyuan * @create: 2019-03-25 15:13 **/ public class VirtualCardServiceImpl { }
package contest.question1; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Created by wang on 2015/04/08. */ public class Answer2 { protected static Logger log = LoggerFactory.getLogger(Answer2.class); /** * |-----------------|-----------------|----------------------------------------------| * 出発点A B(中間点) C(中間点) D(終点) * * 1. 最適化のため、BとCを出発の時、満載(1000トン)がほしい * 2. 1kmは1トンの石炭を消費するので、最低3段(3000/1000)が方しい(4段なら、無駄な消費がある) * * そして、Bは2000トン、Cは1000トンの石炭を残りる * * 5*(AB) = 1000 (往復5回、1000トンの石炭を消費する) * 3*(BC) = 1000 (往復3回、1000トンの石炭を消費する) * AD = AB + BC + CD = 1000 * * CD = 467 * Dに最大運送石炭 = 1000 - 467 = 533 * * @param totalCoalWeight * @param distance * @param maxTransportWeight * @return 最大運送できる石炭量 */ public int resolve(int totalCoalWeight, int distance, int maxTransportWeight) { int n = totalCoalWeight / maxTransportWeight; int[] anMidPoint = new int[n]; int totalDistance = 0; for (int i = 0; i < (n - 1); i++) { anMidPoint[i] = maxTransportWeight / (2 * (n - i) - 1); totalDistance += anMidPoint[i]; log.debug("point {} distance {}", i, anMidPoint[i]); } anMidPoint[n - 1] = distance - totalDistance; log.debug("point {} distance {}", (n - 1), anMidPoint[n - 1]); return (maxTransportWeight - anMidPoint[n - 1]); } }
// Copyright 2015-2021 Nkisi 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 nkisi.db; import nkisi.concurrent.Cont; import nkisi.concurrent.Stage; import nkisi.concurrent.Sync; public abstract class Store { public abstract StoreContext storeContext(); public StoreSettings settings() { return this.storeContext().settings; } public abstract Database database(); public abstract Stage stage(); public abstract long size(); public abstract boolean isCommitting(); public abstract boolean isCompacting(); public abstract void openAsync(Cont<Store> cont); public abstract Store open() throws InterruptedException; public abstract void closeAsync(Cont<Store> cont); public abstract void close() throws InterruptedException; public abstract Zone zone(); public abstract Zone zone(int zoneId); public abstract void openZoneAsync(int zoneId, Cont<Zone> cont); public abstract Zone openZone(int zoneId) throws InterruptedException; public abstract void openDatabaseAsync(Cont<Database> cont); public Database openDatabase() throws InterruptedException { final Sync<Database> syncDatabase = new Sync<Database>(); this.openDatabaseAsync(syncDatabase); return syncDatabase.await(this.settings().databaseOpenTimeout); } public abstract PageLoader openPageLoader(TreeDelegate treeDelegate, boolean isResident); public abstract void commitAsync(Commit commit); public abstract void compactAsync(Compact compact); public abstract Zone shiftZone(); boolean pageShouldSplit(Database database, Page page) { return this.storeContext().pageShouldSplit(this, database, page); } boolean pageShouldMerge(Database database, Page page) { return this.storeContext().pageShouldMerge(this, database, page); } void hitPage(Database database, Page page) { this.storeContext().hitPage(this, database, page); } void treeDidOpen(Database database, Tree tree) { this.storeContext().treeDidOpen(this, database, tree); } void treeDidClose(Database database, Tree tree) { this.storeContext().treeDidClose(this, database, tree); } void treeDidChange(Database database, Tree newTree, Tree oldTree) { this.storeContext().treeDidChange(this, database, newTree, oldTree); } void databaseWillOpen(Database database) { this.storeContext().databaseWillOpen(this, database); } void databaseDidOpen(Database database) { this.storeContext().databaseDidOpen(this, database); } void databaseWillClose(Database database) { this.storeContext().databaseWillClose(this, database); } void databaseDidClose(Database database) { this.storeContext().databaseDidClose(this, database); } Commit databaseWillCommit(Database database, Commit commit) { return this.storeContext().databaseWillCommit(this, database, commit); } void databaseDidCommit(Database database, Chunk chunk) { this.storeContext().databaseDidCommit(this, database, chunk); } void databaseCommitDidFail(Database database, Throwable error) { this.storeContext().databaseCommitDidFail(this, database, error); } Compact databaseWillCompact(Database database, Compact compact) { return this.storeContext().databaseWillCompact(this, database, compact); } void databaseDidCompact(Database database, Compact compact) { this.storeContext().databaseDidCompact(this, database, compact); } void databaseCompactDidFail(Database database, Throwable error) { this.storeContext().databaseCompactDidFail(this, database, error); } }
/* * Copyright (c) 2004-2019, University of Oslo * 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 HISP project 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 OWNER 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 org.hisp.dhis.android.core; import android.content.Context; import androidx.test.platform.app.InstrumentationRegistry; import com.facebook.stetho.okhttp3.StethoInterceptor; import org.hisp.dhis.android.core.arch.storage.internal.AndroidInsecureStore; import org.hisp.dhis.android.core.arch.storage.internal.AndroidSecureStore; import org.hisp.dhis.android.core.arch.storage.internal.InMemorySecureStore; import org.hisp.dhis.android.core.arch.storage.internal.InMemoryUnsecureStore; import org.hisp.dhis.android.core.arch.storage.internal.InsecureStore; import org.hisp.dhis.android.core.arch.storage.internal.SecureStore; import org.hisp.dhis.android.core.maintenance.D2Error; import java.util.Collections; import okhttp3.logging.HttpLoggingInterceptor; public class D2Factory { public static D2 forNewDatabase() { return forNewDatabaseInternal(new InMemorySecureStore(), new InMemoryUnsecureStore()); } public static D2 forNewDatabaseWithAndroidSecureStore() throws D2Error { Context context = InstrumentationRegistry.getInstrumentation().getContext(); return forNewDatabaseInternal(new AndroidSecureStore(context), new AndroidInsecureStore(context)); } private static D2 forNewDatabaseInternal(SecureStore secureStore, InsecureStore insecureStore) { Context context = InstrumentationRegistry.getInstrumentation().getContext(); D2Configuration d2Configuration = d2Configuration(context); D2Manager.setTestMode(true); D2Manager.setTestingSecureStore(secureStore); D2Manager.setTestingInsecureStore(insecureStore); D2 d2 = D2Manager.blockingInstantiateD2(d2Configuration); D2Manager.clear(); return d2; } public static D2Configuration d2Configuration(Context context) { HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(); loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BASIC); return D2Configuration.builder() .appVersion("1.0.0") .readTimeoutInSeconds(30) .connectTimeoutInSeconds(30) .writeTimeoutInSeconds(30) .networkInterceptors(Collections.singletonList(new StethoInterceptor())) .interceptors(Collections.singletonList(loggingInterceptor)) .context(context) .build(); } }
/*- * #%L * ImgLib2: a general-purpose, multidimensional image processing library. * %% * Copyright (C) 2009 - 2021 Tobias Pietzsch, Stephan Preibisch, Stephan Saalfeld, * John Bogovic, Albert Cardona, Barry DeZonia, Christian Dietz, Jan Funke, * Aivar Grislis, Jonathan Hale, Grant Harris, Stefan Helfrich, Mark Hiner, * Martin Horn, Steffen Jaensch, Lee Kamentsky, Larry Lindsey, Melissa Linkert, * Mark Longair, Brian Northan, Nick Perry, Curtis Rueden, Johannes Schindelin, * Jean-Yves Tinevez and Michael Zinsmaier. * %% * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. 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. * * 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 HOLDERS 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. * #L% */ package net.imglib2.type; public final class Index { private int i = 0; /** * Get the index. * <p> * This is used by accessors (e.g., a {@code Cursor}) to position {@code * NativeType}s in the container, and by {@code NativeType}s to determine * the offset into the underlying primitive array, where the value of the * type is stored. */ public int get() { return i; } /** * Set the index to {@code index}. * <p> * This is used by accessors (e.g., a {@code Cursor}) to position {@code * NativeType}s in the container. */ public void set( final int index) { i = index; } /** * Increment the index. * <p> * This is used by accessors (e.g., a {@code Cursor}) to position {@code * NativeType}s in the container. */ public void inc() { ++i; } /** * Increase the index by {@code decrement} steps. * <p> * This is used by accessors (e.g., a {@code Cursor}) to position {@code * NativeType}s in the container. */ public void inc( final int increment ) { i += increment; } /** * Decrement the index. * <p> * This is used by accessors (e.g., a {@code Cursor}) to position {@code * NativeType}s in the container. */ public void dec() { --i; } /** * Decrease the index by {@code decrement} steps. * <p> * This is used by accessors (e.g., a {@code Cursor}) to position {@code * NativeType}s in the container. */ public void dec( final int decrement ) { i -= decrement; } }
// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) annotate safe package com.google.android.gms.internal.ads; final class zzavz { static final int zzakf[]; static { zzakf = new int[zzbbo.zze.values$50KLMJ33DTMIUPRFDTJMOP9FE1P6UT3FC9QMCBQ7CLN6ASJ1EHIM8JB5EDPM2PR59HKN8P949LIN8Q3FCHA6UIBEEPNMMP9R0().length]; // 0 0:invokestatic #16 <Method int[] zzbbo$zze.values$50KLMJ33DTMIUPRFDTJMOP9FE1P6UT3FC9QMCBQ7CLN6ASJ1EHIM8JB5EDPM2PR59HKN8P949LIN8Q3FCHA6UIBEEPNMMP9R0()> // 1 3:arraylength // 2 4:newarray int[] // 3 6:putstatic #18 <Field int[] zzakf> try { zzakf[zzbbo.zze.zzdud - 1] = 1; // 4 9:getstatic #18 <Field int[] zzakf> // 5 12:getstatic #22 <Field int zzbbo$zze.zzdud> // 6 15:iconst_1 // 7 16:isub // 8 17:iconst_1 // 9 18:iastore } //* 10 19:getstatic #18 <Field int[] zzakf> //* 11 22:getstatic #25 <Field int zzbbo$zze.zzdue> //* 12 25:iconst_1 //* 13 26:isub //* 14 27:iconst_2 //* 15 28:iastore //* 16 29:getstatic #18 <Field int[] zzakf> //* 17 32:getstatic #28 <Field int zzbbo$zze.zzduc> //* 18 35:iconst_1 //* 19 36:isub //* 20 37:iconst_3 //* 21 38:iastore //* 22 39:getstatic #18 <Field int[] zzakf> //* 23 42:getstatic #31 <Field int zzbbo$zze.zzduf> //* 24 45:iconst_1 //* 25 46:isub //* 26 47:iconst_4 //* 27 48:iastore //* 28 49:getstatic #18 <Field int[] zzakf> //* 29 52:getstatic #34 <Field int zzbbo$zze.zzdug> //* 30 55:iconst_1 //* 31 56:isub //* 32 57:iconst_5 //* 33 58:iastore //* 34 59:getstatic #18 <Field int[] zzakf> //* 35 62:getstatic #37 <Field int zzbbo$zze.zzdua> //* 36 65:iconst_1 //* 37 66:isub //* 38 67:bipush 6 //* 39 69:iastore //* 40 70:getstatic #18 <Field int[] zzakf> //* 41 73:getstatic #40 <Field int zzbbo$zze.zzdub> //* 42 76:iconst_1 //* 43 77:isub //* 44 78:bipush 7 //* 45 80:iastore //* 46 81:return catch(NoSuchFieldError nosuchfielderror) { } // 47 82:astore_0 try { zzakf[zzbbo.zze.zzdue - 1] = 2; } //* 48 83:goto 19 catch(NoSuchFieldError nosuchfielderror1) { } // 49 86:astore_0 try { zzakf[zzbbo.zze.zzduc - 1] = 3; } //* 50 87:goto 29 catch(NoSuchFieldError nosuchfielderror2) { } // 51 90:astore_0 try { zzakf[zzbbo.zze.zzduf - 1] = 4; } //* 52 91:goto 39 catch(NoSuchFieldError nosuchfielderror3) { } // 53 94:astore_0 try { zzakf[zzbbo.zze.zzdug - 1] = 5; } //* 54 95:goto 49 catch(NoSuchFieldError nosuchfielderror4) { } // 55 98:astore_0 try { zzakf[zzbbo.zze.zzdua - 1] = 6; } //* 56 99:goto 59 catch(NoSuchFieldError nosuchfielderror5) { } // 57 102:astore_0 try { zzakf[zzbbo.zze.zzdub - 1] = 7; } //* 58 103:goto 70 catch(NoSuchFieldError nosuchfielderror6) { } // 59 106:astore_0 //* 60 107:return } }
/* * Copyright 2014-2016 CyberVision, 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.kaaproject.kaa.client.channel; import org.kaaproject.kaa.client.event.EventManager; import org.kaaproject.kaa.common.endpoint.gen.EventSyncRequest; import org.kaaproject.kaa.common.endpoint.gen.EventSyncResponse; /** * {@link KaaTransport} for the Event service. * Updates the Event manager state. * * @author Yaroslav Zeygerman */ public interface EventTransport extends KaaTransport { /** * Creates the Event request. * * @param requestId new request id of the SyncRequest. * @return new Event request. * @see EventSyncRequest */ EventSyncRequest createEventRequest(Integer requestId); /** * Updates the state of the Event manager according to the given response. * * @param response the response from the server. * @see EventSyncResponse */ void onEventResponse(EventSyncResponse response); /** * Notifies event transport about response from server for specific request. * * @param requestId request id of the corresponding SyncRequest */ void onSyncResposeIdReceived(Integer requestId); /** * Sets the given Event manager. * * @param manager the Event manager which is going to be set. * @see EventManager */ void setEventManager(EventManager manager); /** * Block Event manager. */ void blockEventManager(); /** * Release Event manager. */ void releaseEventManager(); }
/** * This code was generated by * \ / _ _ _| _ _ * | (_)\/(_)(_|\/| |(/_ v1.0.0 * / / */ package com.twilio.rest.chat.v1.service.channel; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.base.MoreObjects; import com.twilio.base.Resource; import com.twilio.converter.DateConverter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; import com.twilio.http.HttpMethod; import com.twilio.http.Request; import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; import org.joda.time.DateTime; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Map; import java.util.Objects; @JsonIgnoreProperties(ignoreUnknown = true) public class Member extends Resource { private static final long serialVersionUID = 102574959310114L; /** * Create a MemberFetcher to execute fetch. * * @param pathServiceSid The SID of the Service to fetch the resource from * @param pathChannelSid The unique ID of the channel the member belongs to * @param pathSid The unique string that identifies the resource * @return MemberFetcher capable of executing the fetch */ public static MemberFetcher fetcher(final String pathServiceSid, final String pathChannelSid, final String pathSid) { return new MemberFetcher(pathServiceSid, pathChannelSid, pathSid); } /** * Create a MemberCreator to execute create. * * @param pathServiceSid The SID of the Service to create the resource under * @param pathChannelSid The unique ID of the channel the new member belongs to * @param identity The `identity` value that identifies the new resource's User * @return MemberCreator capable of executing the create */ public static MemberCreator creator(final String pathServiceSid, final String pathChannelSid, final String identity) { return new MemberCreator(pathServiceSid, pathChannelSid, identity); } /** * Create a MemberReader to execute read. * * @param pathServiceSid The SID of the Service to read the resources from * @param pathChannelSid The unique ID of the channel the member belongs to * @return MemberReader capable of executing the read */ public static MemberReader reader(final String pathServiceSid, final String pathChannelSid) { return new MemberReader(pathServiceSid, pathChannelSid); } /** * Create a MemberDeleter to execute delete. * * @param pathServiceSid The SID of the Service to delete the resource from * @param pathChannelSid The unique ID of the channel the message to delete * belongs to * @param pathSid The unique string that identifies the resource * @return MemberDeleter capable of executing the delete */ public static MemberDeleter deleter(final String pathServiceSid, final String pathChannelSid, final String pathSid) { return new MemberDeleter(pathServiceSid, pathChannelSid, pathSid); } /** * Create a MemberUpdater to execute update. * * @param pathServiceSid The SID of the Service to create the resource under * @param pathChannelSid The unique ID of the channel the member to update * belongs to * @param pathSid The unique string that identifies the resource * @return MemberUpdater capable of executing the update */ public static MemberUpdater updater(final String pathServiceSid, final String pathChannelSid, final String pathSid) { return new MemberUpdater(pathServiceSid, pathChannelSid, pathSid); } /** * Converts a JSON String into a Member object using the provided ObjectMapper. * * @param json Raw JSON String * @param objectMapper Jackson ObjectMapper * @return Member object represented by the provided JSON */ public static Member fromJson(final String json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Member.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { throw new ApiConnectionException(e.getMessage(), e); } } /** * Converts a JSON InputStream into a Member object using the provided * ObjectMapper. * * @param json Raw JSON InputStream * @param objectMapper Jackson ObjectMapper * @return Member object represented by the provided JSON */ public static Member fromJson(final InputStream json, final ObjectMapper objectMapper) { // Convert all checked exceptions to Runtime try { return objectMapper.readValue(json, Member.class); } catch (final JsonMappingException | JsonParseException e) { throw new ApiException(e.getMessage(), e); } catch (final IOException e) { throw new ApiConnectionException(e.getMessage(), e); } } private final String sid; private final String accountSid; private final String channelSid; private final String serviceSid; private final String identity; private final DateTime dateCreated; private final DateTime dateUpdated; private final String roleSid; private final Integer lastConsumedMessageIndex; private final DateTime lastConsumptionTimestamp; private final URI url; @JsonCreator private Member(@JsonProperty("sid") final String sid, @JsonProperty("account_sid") final String accountSid, @JsonProperty("channel_sid") final String channelSid, @JsonProperty("service_sid") final String serviceSid, @JsonProperty("identity") final String identity, @JsonProperty("date_created") final String dateCreated, @JsonProperty("date_updated") final String dateUpdated, @JsonProperty("role_sid") final String roleSid, @JsonProperty("last_consumed_message_index") final Integer lastConsumedMessageIndex, @JsonProperty("last_consumption_timestamp") final String lastConsumptionTimestamp, @JsonProperty("url") final URI url) { this.sid = sid; this.accountSid = accountSid; this.channelSid = channelSid; this.serviceSid = serviceSid; this.identity = identity; this.dateCreated = DateConverter.iso8601DateTimeFromString(dateCreated); this.dateUpdated = DateConverter.iso8601DateTimeFromString(dateUpdated); this.roleSid = roleSid; this.lastConsumedMessageIndex = lastConsumedMessageIndex; this.lastConsumptionTimestamp = DateConverter.iso8601DateTimeFromString(lastConsumptionTimestamp); this.url = url; } /** * Returns The The unique string that identifies the resource. * * @return The unique string that identifies the resource */ public final String getSid() { return this.sid; } /** * Returns The The SID of the Account that created the resource. * * @return The SID of the Account that created the resource */ public final String getAccountSid() { return this.accountSid; } /** * Returns The The unique ID of the Channel for the member. * * @return The unique ID of the Channel for the member */ public final String getChannelSid() { return this.channelSid; } /** * Returns The The SID of the Service that the resource is associated with. * * @return The SID of the Service that the resource is associated with */ public final String getServiceSid() { return this.serviceSid; } /** * Returns The The string that identifies the resource's User. * * @return The string that identifies the resource's User */ public final String getIdentity() { return this.identity; } /** * Returns The The RFC 2822 date and time in GMT when the resource was created. * * @return The RFC 2822 date and time in GMT when the resource was created */ public final DateTime getDateCreated() { return this.dateCreated; } /** * Returns The The RFC 2822 date and time in GMT when the resource was last * updated. * * @return The RFC 2822 date and time in GMT when the resource was last updated */ public final DateTime getDateUpdated() { return this.dateUpdated; } /** * Returns The The SID of the Role assigned to the member. * * @return The SID of the Role assigned to the member */ public final String getRoleSid() { return this.roleSid; } /** * Returns The The index of the last Message that the Member has read within the * Channel. * * @return The index of the last Message that the Member has read within the * Channel */ public final Integer getLastConsumedMessageIndex() { return this.lastConsumedMessageIndex; } /** * Returns The The ISO 8601 based timestamp string that represents the date-time * of the last Message read event for the Member within the Channel. * * @return The ISO 8601 based timestamp string that represents the date-time of * the last Message read event for the Member within the Channel */ public final DateTime getLastConsumptionTimestamp() { return this.lastConsumptionTimestamp; } /** * Returns The The absolute URL of the Member resource. * * @return The absolute URL of the Member resource */ public final URI getUrl() { return this.url; } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Member other = (Member) o; return Objects.equals(sid, other.sid) && Objects.equals(accountSid, other.accountSid) && Objects.equals(channelSid, other.channelSid) && Objects.equals(serviceSid, other.serviceSid) && Objects.equals(identity, other.identity) && Objects.equals(dateCreated, other.dateCreated) && Objects.equals(dateUpdated, other.dateUpdated) && Objects.equals(roleSid, other.roleSid) && Objects.equals(lastConsumedMessageIndex, other.lastConsumedMessageIndex) && Objects.equals(lastConsumptionTimestamp, other.lastConsumptionTimestamp) && Objects.equals(url, other.url); } @Override public int hashCode() { return Objects.hash(sid, accountSid, channelSid, serviceSid, identity, dateCreated, dateUpdated, roleSid, lastConsumedMessageIndex, lastConsumptionTimestamp, url); } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("sid", sid) .add("accountSid", accountSid) .add("channelSid", channelSid) .add("serviceSid", serviceSid) .add("identity", identity) .add("dateCreated", dateCreated) .add("dateUpdated", dateUpdated) .add("roleSid", roleSid) .add("lastConsumedMessageIndex", lastConsumedMessageIndex) .add("lastConsumptionTimestamp", lastConsumptionTimestamp) .add("url", url) .toString(); } }
package org.odk.collect.android.preferences; import android.content.Context; import android.content.SharedPreferences; import android.widget.EditText; import androidx.appcompat.app.AlertDialog; import androidx.fragment.app.testing.FragmentScenario; import androidx.test.ext.junit.runners.AndroidJUnit4; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.odk.collect.android.R; import org.odk.collect.android.injection.config.AppDependencyModule; import org.odk.collect.android.support.RobolectricHelpers; import static androidx.test.core.app.ApplicationProvider.getApplicationContext; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; @RunWith(AndroidJUnit4.class) public class ServerAuthDialogFragmentTest { private SharedPreferences generalPrefs; @Before public void setup() { generalPrefs = getApplicationContext().getSharedPreferences("test", Context.MODE_PRIVATE); generalPrefs.edit() .putString(GeneralKeys.KEY_USERNAME, "Alpen") .putString(GeneralKeys.KEY_PASSWORD, "swiss") .apply(); RobolectricHelpers.overrideAppDependencyModule(new AppDependencyModule() { @Override public PreferencesProvider providesPreferencesProvider(Context context) { return new PreferencesProvider(context) { @Override public SharedPreferences getGeneralSharedPreferences() { return generalPrefs; } }; } }); } @Test public void prefillsUsernameAndPassword() { generalPrefs.edit() .putString(GeneralKeys.KEY_USERNAME, "Alpen") .putString(GeneralKeys.KEY_PASSWORD, "swiss") .apply(); FragmentScenario<ServerAuthDialogFragment> scenario = FragmentScenario.launch( ServerAuthDialogFragment.class, null, R.style.Theme_AppCompat, null ); scenario.onFragment(fragment -> { EditText username = fragment.getDialogView().findViewById(R.id.username_edit); EditText password = fragment.getDialogView().findViewById(R.id.password_edit); assertThat(username.getText().toString(), is("Alpen")); assertThat(password.getText().toString(), is("swiss")); }); } @Test public void clickingOK_savesUsernameAndPasswordToGeneralPrefs() { FragmentScenario<ServerAuthDialogFragment> scenario = FragmentScenario.launch( ServerAuthDialogFragment.class, null, R.style.Theme_AppCompat, null ); scenario.onFragment(fragment -> { EditText username = fragment.getDialogView().findViewById(R.id.username_edit); EditText password = fragment.getDialogView().findViewById(R.id.password_edit); username.setText("Frederick Chilton"); password.setText("chesapeake"); ((AlertDialog) fragment.getDialog()).getButton(AlertDialog.BUTTON_POSITIVE).performClick(); }); assertThat(generalPrefs.getString(GeneralKeys.KEY_USERNAME, null), is("Frederick Chilton")); assertThat(generalPrefs.getString(GeneralKeys.KEY_PASSWORD, null), is("chesapeake")); } }
package org.jfree.chart.axis; import java.io.ObjectStreamException; import java.io.Serializable; import org.jfree.chart.util.ParamChecks; public final class AxisLocation implements Serializable { public static final AxisLocation BOTTOM_OR_LEFT; public static final AxisLocation BOTTOM_OR_RIGHT; public static final AxisLocation TOP_OR_LEFT; public static final AxisLocation TOP_OR_RIGHT; private static final long serialVersionUID = -3276922179323563410L; private String name; static { TOP_OR_LEFT = new AxisLocation("AxisLocation.TOP_OR_LEFT"); TOP_OR_RIGHT = new AxisLocation("AxisLocation.TOP_OR_RIGHT"); BOTTOM_OR_LEFT = new AxisLocation("AxisLocation.BOTTOM_OR_LEFT"); BOTTOM_OR_RIGHT = new AxisLocation("AxisLocation.BOTTOM_OR_RIGHT"); } private AxisLocation(String name) { this.name = name; } public AxisLocation getOpposite() { return getOpposite(this); } public String toString() { return this.name; } public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof AxisLocation)) { return false; } if (this.name.equals(((AxisLocation) obj).toString())) { return true; } return false; } public int hashCode() { return this.name.hashCode() + 415; } public static AxisLocation getOpposite(AxisLocation location) { ParamChecks.nullNotPermitted(location, "location"); if (location == TOP_OR_LEFT) { return BOTTOM_OR_RIGHT; } if (location == TOP_OR_RIGHT) { return BOTTOM_OR_LEFT; } if (location == BOTTOM_OR_LEFT) { return TOP_OR_RIGHT; } if (location == BOTTOM_OR_RIGHT) { return TOP_OR_LEFT; } throw new IllegalStateException("AxisLocation not recognised."); } private Object readResolve() throws ObjectStreamException { if (equals(TOP_OR_RIGHT)) { return TOP_OR_RIGHT; } if (equals(BOTTOM_OR_RIGHT)) { return BOTTOM_OR_RIGHT; } if (equals(TOP_OR_LEFT)) { return TOP_OR_LEFT; } if (equals(BOTTOM_OR_LEFT)) { return BOTTOM_OR_LEFT; } return null; } }
// Copyright 2016 Google Inc. 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.google.api.ads.adwords.awreporting.model.entities; import com.google.api.ads.adwords.awreporting.model.csv.annotation.CsvField; import com.google.api.ads.adwords.awreporting.model.csv.annotation.CsvReport; import com.google.api.ads.adwords.awreporting.model.csv.annotation.MoneyField; import com.google.api.ads.adwords.awreporting.model.util.BigDecimalUtil; import com.google.api.ads.adwords.lib.jaxb.v201806.ReportDefinitionReportType; import java.math.BigDecimal; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; /** * Specific report class for DisplayTopicsPerformanceReport. * */ @Entity @Table(name = "AW_DisplayTopicsPerformanceReport") @CsvReport(value = ReportDefinitionReportType.DISPLAY_TOPICS_PERFORMANCE_REPORT) public class DisplayTopicsPerformanceReport extends DateReport { @Column(name = "AccountCurrencyCode") @CsvField(value = "Currency", reportField = "AccountCurrencyCode") private String accountCurrencyCode; @Column(name = "AccountDescriptiveName") @CsvField(value = "Account", reportField = "AccountDescriptiveName") private String accountDescriptiveName; @Column(name = "AccountTimeZone") @CsvField(value = "Time zone", reportField = "AccountTimeZone") private String accountTimeZone; @Column(name = "ActiveViewCpm") @CsvField(value = "Active View avg. CPM", reportField = "ActiveViewCpm") @MoneyField private BigDecimal activeViewCpm; @Column(name = "ActiveViewCtr") @CsvField(value = "Active View viewable CTR", reportField = "ActiveViewCtr") private BigDecimal activeViewCtr; @Column(name = "ActiveViewImpressions") @CsvField(value = "Active View viewable impressions", reportField = "ActiveViewImpressions") private Long activeViewImpressions; @Column(name = "ActiveViewMeasurability") @CsvField(value = "Active View measurable impr. / impr.", reportField = "ActiveViewMeasurability") private BigDecimal activeViewMeasurability; @Column(name = "ActiveViewMeasurableCost") @CsvField(value = "Active View measurable cost", reportField = "ActiveViewMeasurableCost") @MoneyField private BigDecimal activeViewMeasurableCost; @Column(name = "ActiveViewMeasurableImpressions") @CsvField(value = "Active View measurable impr.", reportField = "ActiveViewMeasurableImpressions") private Long activeViewMeasurableImpressions; @Column(name = "ActiveViewViewability") @CsvField(value = "Active View viewable impr. / measurable impr.", reportField = "ActiveViewViewability") private BigDecimal activeViewViewability; @Column(name = "AdGroupId") @CsvField(value = "Ad group ID", reportField = "AdGroupId") private Long adGroupId; @Column(name = "AdGroupName") @CsvField(value = "Ad group", reportField = "AdGroupName") private String adGroupName; @Column(name = "AdGroupStatus") @CsvField(value = "Ad group state", reportField = "AdGroupStatus") private String adGroupStatus; @Column(name = "AdNetworkType1") @CsvField(value = "Network", reportField = "AdNetworkType1") private String adNetworkType1; @Column(name = "AdNetworkType2") @CsvField(value = "Network (with search partners)", reportField = "AdNetworkType2") private String adNetworkType2; @Column(name = "AllConversionRate") @CsvField(value = "All conv. rate", reportField = "AllConversionRate") private BigDecimal allConversionRate; @Column(name = "AllConversions") @CsvField(value = "All conv.", reportField = "AllConversions") private BigDecimal allConversions; @Column(name = "AllConversionValue") @CsvField(value = "All conv. value", reportField = "AllConversionValue") private BigDecimal allConversionValue; @Column(name = "AverageCost") @CsvField(value = "Avg. Cost", reportField = "AverageCost") @MoneyField private BigDecimal averageCost; @Column(name = "AverageCpc") @CsvField(value = "Avg. CPC", reportField = "AverageCpc") @MoneyField private BigDecimal averageCpc; @Column(name = "AverageCpe") @CsvField(value = "Avg. CPE", reportField = "AverageCpe") private BigDecimal averageCpe; @Column(name = "AverageCpm") @CsvField(value = "Avg. CPM", reportField = "AverageCpm") @MoneyField private BigDecimal averageCpm; @Column(name = "AverageCpv") @CsvField(value = "Avg. CPV", reportField = "AverageCpv") private BigDecimal averageCpv; @Column(name = "BaseAdGroupId") @CsvField(value = "Base Ad group ID", reportField = "BaseAdGroupId") private Long baseAdGroupId; @Column(name = "BaseCampaignId") @CsvField(value = "Base Campaign ID", reportField = "BaseCampaignId") private Long baseCampaignId; @Column(name = "BiddingStrategyId") @CsvField(value = "Bid Strategy ID", reportField = "BiddingStrategyId") private Long biddingStrategyId; @Column(name = "BiddingStrategyName") @CsvField(value = "Bid Strategy Name", reportField = "BiddingStrategyName") private String biddingStrategyName; @Column(name = "BiddingStrategyType") @CsvField(value = "Bid Strategy Type", reportField = "BiddingStrategyType") private String biddingStrategyType; @Column(name = "BidModifier") @CsvField(value = "Bid adj.", reportField = "BidModifier") private BigDecimal bidModifier; @Column(name = "CampaignId") @CsvField(value = "Campaign ID", reportField = "CampaignId") private Long campaignId; @Column(name = "CampaignName") @CsvField(value = "Campaign", reportField = "CampaignName") private String campaignName; @Column(name = "CampaignStatus") @CsvField(value = "Campaign state", reportField = "CampaignStatus") private String campaignStatus; @Column(name = "Clicks") @CsvField(value = "Clicks", reportField = "Clicks") private Long clicks; @Column(name = "ClickType") @CsvField(value = "Click type", reportField = "ClickType") private String clickType; @Column(name = "ConversionCategoryName") @CsvField(value = "Conversion category", reportField = "ConversionCategoryName") private String conversionCategoryName; @Column(name = "ConversionRate") @CsvField(value = "Conv. rate", reportField = "ConversionRate") private BigDecimal conversionRate; @Column(name = "Conversions") @CsvField(value = "Conversions", reportField = "Conversions") private BigDecimal conversions; @Column(name = "ConversionTrackerId") @CsvField(value = "Conversion Tracker Id", reportField = "ConversionTrackerId") private Long conversionTrackerId; @Column(name = "ConversionTypeName") @CsvField(value = "Conversion name", reportField = "ConversionTypeName") private String conversionTypeName; @Column(name = "ConversionValue") @CsvField(value = "Total conv. value", reportField = "ConversionValue") private BigDecimal conversionValue; @Column(name = "Cost") @CsvField(value = "Cost", reportField = "Cost") @MoneyField private BigDecimal cost; @Column(name = "CostPerAllConversion") @CsvField(value = "Cost / all conv.", reportField = "CostPerAllConversion") @MoneyField private BigDecimal costPerAllConversion; @Column(name = "CostPerConversion") @CsvField(value = "Cost / conv.", reportField = "CostPerConversion") @MoneyField private BigDecimal costPerConversion; @Column(name = "CpcBid") @CsvField(value = "Max. CPC", reportField = "CpcBid") @MoneyField private BigDecimal cpcBid; @Column(name = "CpcBidSource") @CsvField(value = "Max CPC source", reportField = "CpcBidSource") private String cpcBidSource; @Column(name = "CpmBid") @CsvField(value = "Max. CPM", reportField = "CpmBid") @MoneyField private BigDecimal cpmBid; @Column(name = "CpmBidSource") @CsvField(value = "Max CPM Source", reportField = "CpmBidSource") private String cpmBidSource; @Column(name = "Criteria") @CsvField(value = "Topic", reportField = "Criteria") private String criteria; @Column(name = "CriteriaDestinationUrl", length = 2048) @CsvField(value = "Destination URL", reportField = "CriteriaDestinationUrl") private String criteriaDestinationUrl; @Column(name = "CrossDeviceConversions") @CsvField(value = "Cross-device conv.", reportField = "CrossDeviceConversions") private BigDecimal crossDeviceConversions; @Column(name = "Ctr") @CsvField(value = "CTR", reportField = "Ctr") private BigDecimal ctr; @Column(name = "CustomerDescriptiveName") @CsvField(value = "Client name", reportField = "CustomerDescriptiveName") private String customerDescriptiveName; @Column(name = "Device") @CsvField(value = "Device", reportField = "Device") private String device; @Column(name = "EngagementRate") @CsvField(value = "Engagement rate", reportField = "EngagementRate") private BigDecimal engagementRate; @Column(name = "Engagements") @CsvField(value = "Engagements", reportField = "Engagements") private Long engagements; @Column(name = "ExternalConversionSource") @CsvField(value = "Conversion source", reportField = "ExternalConversionSource") private String externalConversionSource; @Column(name = "FinalAppUrls", length = 2048) @CsvField(value = "App final URL", reportField = "FinalAppUrls") private String finalAppUrls; @Column(name = "FinalMobileUrls", length = 2048) @CsvField(value = "Mobile final URL", reportField = "FinalMobileUrls") private String finalMobileUrls; @Column(name = "FinalUrls", length = 2048) @CsvField(value = "Final URL", reportField = "FinalUrls") private String finalUrls; @Column(name = "GmailForwards") @CsvField(value = "Gmail forwards", reportField = "GmailForwards") private Long gmailForwards; @Column(name = "GmailSaves") @CsvField(value = "Gmail saves", reportField = "GmailSaves") private Long gmailSaves; @Column(name = "GmailSecondaryClicks") @CsvField(value = "Gmail clicks to website", reportField = "GmailSecondaryClicks") private Long gmailSecondaryClicks; @Column(name = "Id") @CsvField(value = "Criterion ID", reportField = "Id") private Long id; @Column(name = "Impressions") @CsvField(value = "Impressions", reportField = "Impressions") private Long impressions; @Column(name = "InteractionRate") @CsvField(value = "Interaction Rate", reportField = "InteractionRate") private BigDecimal interactionRate; @Column(name = "Interactions") @CsvField(value = "Interactions", reportField = "Interactions") private Long interactions; @Column(name = "InteractionTypes") @CsvField(value = "Interaction Types", reportField = "InteractionTypes") private String interactionTypes; @Column(name = "IsNegative") @CsvField(value = "Is negative", reportField = "IsNegative") private String isNegative; @Column(name = "IsRestrict") @CsvField(value = "Is restricting", reportField = "IsRestrict") private String isRestrict; @Column(name = "Status") @CsvField(value = "Topic state", reportField = "Status") private String status; @Column(name = "TrackingUrlTemplate", length = 2048) @CsvField(value = "Tracking template", reportField = "TrackingUrlTemplate") private String trackingUrlTemplate; @Column(name = "UrlCustomParameters", length = 2048) @CsvField(value = "Custom parameter", reportField = "UrlCustomParameters") private String urlCustomParameters; @Column(name = "ValuePerAllConversion") @CsvField(value = "Value / all conv.", reportField = "ValuePerAllConversion") private BigDecimal valuePerAllConversion; @Column(name = "ValuePerConversion") @CsvField(value = "Value / conv.", reportField = "ValuePerConversion") private BigDecimal valuePerConversion; @Column(name = "VerticalId") @CsvField(value = "Vertical ID", reportField = "VerticalId") private Long verticalId; @Column(name = "VideoQuartile100Rate") @CsvField(value = "Video played to 100%", reportField = "VideoQuartile100Rate") private BigDecimal videoQuartile100Rate; @Column(name = "VideoQuartile25Rate") @CsvField(value = "Video played to 25%", reportField = "VideoQuartile25Rate") private BigDecimal videoQuartile25Rate; @Column(name = "VideoQuartile50Rate") @CsvField(value = "Video played to 50%", reportField = "VideoQuartile50Rate") private BigDecimal videoQuartile50Rate; @Column(name = "VideoQuartile75Rate") @CsvField(value = "Video played to 75%", reportField = "VideoQuartile75Rate") private BigDecimal videoQuartile75Rate; @Column(name = "VideoViewRate") @CsvField(value = "View rate", reportField = "VideoViewRate") private BigDecimal videoViewRate; @Column(name = "VideoViews") @CsvField(value = "Views", reportField = "VideoViews") private Long videoViews; @Column(name = "ViewThroughConversions") @CsvField(value = "View-through conv.", reportField = "ViewThroughConversions") private Long viewThroughConversions; /** * Hibernate needs an empty constructor */ public DisplayTopicsPerformanceReport() { } public DisplayTopicsPerformanceReport(Long topAccountId, Long accountId){ super(topAccountId, accountId); } public String getAccountCurrencyCode() { return accountCurrencyCode; } public void setAccountCurrencyCode(String accountCurrencyCode) { this.accountCurrencyCode = accountCurrencyCode; } public String getAccountDescriptiveName() { return accountDescriptiveName; } public void setAccountDescriptiveName(String accountDescriptiveName) { this.accountDescriptiveName = accountDescriptiveName; } public String getAccountTimeZone() { return accountTimeZone; } public void setAccountTimeZone(String accountTimeZone) { this.accountTimeZone = accountTimeZone; } public BigDecimal getActiveViewCpm() { return activeViewCpm; } public void setActiveViewCpm(BigDecimal activeViewCpm) { this.activeViewCpm = activeViewCpm; } public String getActiveViewCtr() { return BigDecimalUtil.formatAsReadable(activeViewCtr); } public BigDecimal getActiveViewCtrBigDecimal() { return activeViewCtr; } public void setActiveViewCtr(String activeViewCtr) { this.activeViewCtr = BigDecimalUtil.parseFromNumberString(activeViewCtr); } public Long getActiveViewImpressions() { return activeViewImpressions; } public void setActiveViewImpressions(Long activeViewImpressions) { this.activeViewImpressions = activeViewImpressions; } public String getActiveViewMeasurability() { return BigDecimalUtil.formatAsReadable(activeViewMeasurability); } public BigDecimal getActiveViewMeasurabilityBigDecimal() { return activeViewMeasurability; } public void setActiveViewMeasurability(String activeViewMeasurability) { this.activeViewMeasurability = BigDecimalUtil.parseFromNumberString(activeViewMeasurability); } public BigDecimal getActiveViewMeasurableCost() { return activeViewMeasurableCost; } public void setActiveViewMeasurableCost(BigDecimal activeViewMeasurableCost) { this.activeViewMeasurableCost = activeViewMeasurableCost; } public Long getActiveViewMeasurableImpressions() { return activeViewMeasurableImpressions; } public void setActiveViewMeasurableImpressions(Long activeViewMeasurableImpressions) { this.activeViewMeasurableImpressions = activeViewMeasurableImpressions; } public String getActiveViewViewability() { return BigDecimalUtil.formatAsReadable(activeViewViewability); } public BigDecimal getActiveViewViewabilityBigDecimal() { return activeViewViewability; } public void setActiveViewViewability(String activeViewViewability) { this.activeViewViewability = BigDecimalUtil.parseFromNumberString(activeViewViewability); } public Long getAdGroupId() { return adGroupId; } public void setAdGroupId(Long adGroupId) { this.adGroupId = adGroupId; } public String getAdGroupName() { return adGroupName; } public void setAdGroupName(String adGroupName) { this.adGroupName = adGroupName; } public String getAdGroupStatus() { return adGroupStatus; } public void setAdGroupStatus(String adGroupStatus) { this.adGroupStatus = adGroupStatus; } public String getAdNetworkType1() { return adNetworkType1; } public void setAdNetworkType1(String adNetworkType1) { this.adNetworkType1 = adNetworkType1; } public String getAdNetworkType2() { return adNetworkType2; } public void setAdNetworkType2(String adNetworkType2) { this.adNetworkType2 = adNetworkType2; } public String getAllConversionRate() { return BigDecimalUtil.formatAsReadable(allConversionRate); } public BigDecimal getAllConversionRateBigDecimal() { return allConversionRate; } public void setAllConversionRate(String allConversionRate) { this.allConversionRate = BigDecimalUtil.parseFromNumberString(allConversionRate); } public String getAllConversions() { return BigDecimalUtil.formatAsReadable(allConversions); } public BigDecimal getAllConversionsBigDecimal() { return allConversions; } public void setAllConversions(String allConversions) { this.allConversions = BigDecimalUtil.parseFromNumberString(allConversions); } public String getAllConversionValue() { return BigDecimalUtil.formatAsReadable(allConversionValue); } public BigDecimal getAllConversionValueBigDecimal() { return allConversionValue; } public void setAllConversionValue(String allConversionValue) { this.allConversionValue = BigDecimalUtil.parseFromNumberString(allConversionValue); } public BigDecimal getAverageCost() { return averageCost; } public void setAverageCost(BigDecimal averageCost) { this.averageCost = averageCost; } public BigDecimal getAverageCpc() { return averageCpc; } public void setAverageCpc(BigDecimal averageCpc) { this.averageCpc = averageCpc; } public String getAverageCpe() { return BigDecimalUtil.formatAsReadable(averageCpe); } public BigDecimal getAverageCpeBigDecimal() { return averageCpe; } public void setAverageCpe(String averageCpe) { this.averageCpe = BigDecimalUtil.parseFromNumberString(averageCpe); } public BigDecimal getAverageCpm() { return averageCpm; } public void setAverageCpm(BigDecimal averageCpm) { this.averageCpm = averageCpm; } public String getAverageCpv() { return BigDecimalUtil.formatAsReadable(averageCpv); } public BigDecimal getAverageCpvBigDecimal() { return averageCpv; } public void setAverageCpv(String averageCpv) { this.averageCpv = BigDecimalUtil.parseFromNumberString(averageCpv); } public Long getBaseAdGroupId() { return baseAdGroupId; } public void setBaseAdGroupId(Long baseAdGroupId) { this.baseAdGroupId = baseAdGroupId; } public Long getBaseCampaignId() { return baseCampaignId; } public void setBaseCampaignId(Long baseCampaignId) { this.baseCampaignId = baseCampaignId; } public Long getBiddingStrategyId() { return biddingStrategyId; } public void setBiddingStrategyId(Long biddingStrategyId) { this.biddingStrategyId = biddingStrategyId; } public String getBiddingStrategyName() { return biddingStrategyName; } public void setBiddingStrategyName(String biddingStrategyName) { this.biddingStrategyName = biddingStrategyName; } public String getBiddingStrategyType() { return biddingStrategyType; } public void setBiddingStrategyType(String biddingStrategyType) { this.biddingStrategyType = biddingStrategyType; } public String getBidModifier() { return BigDecimalUtil.formatAsReadable(bidModifier); } public BigDecimal getBidModifierBigDecimal() { return bidModifier; } public void setBidModifier(String bidModifier) { this.bidModifier = BigDecimalUtil.parseFromNumberString(bidModifier); } public Long getCampaignId() { return campaignId; } public void setCampaignId(Long campaignId) { this.campaignId = campaignId; } public String getCampaignName() { return campaignName; } public void setCampaignName(String campaignName) { this.campaignName = campaignName; } public String getCampaignStatus() { return campaignStatus; } public void setCampaignStatus(String campaignStatus) { this.campaignStatus = campaignStatus; } public Long getClicks() { return clicks; } public void setClicks(Long clicks) { this.clicks = clicks; } public String getClickType() { return clickType; } public void setClickType(String clickType) { this.clickType = clickType; } public String getConversionCategoryName() { return conversionCategoryName; } public void setConversionCategoryName(String conversionCategoryName) { this.conversionCategoryName = conversionCategoryName; } public String getConversionRate() { return BigDecimalUtil.formatAsReadable(conversionRate); } public BigDecimal getConversionRateBigDecimal() { return conversionRate; } public void setConversionRate(String conversionRate) { this.conversionRate = BigDecimalUtil.parseFromNumberString(conversionRate); } public String getConversions() { return BigDecimalUtil.formatAsReadable(conversions); } public BigDecimal getConversionsBigDecimal() { return conversions; } public void setConversions(String conversions) { this.conversions = BigDecimalUtil.parseFromNumberString(conversions); } public Long getConversionTrackerId() { return conversionTrackerId; } public void setConversionTrackerId(Long conversionTrackerId) { this.conversionTrackerId = conversionTrackerId; } public String getConversionTypeName() { return conversionTypeName; } public void setConversionTypeName(String conversionTypeName) { this.conversionTypeName = conversionTypeName; } public String getConversionValue() { return BigDecimalUtil.formatAsReadable(conversionValue); } public BigDecimal getConversionValueBigDecimal() { return conversionValue; } public void setConversionValue(String conversionValue) { this.conversionValue = BigDecimalUtil.parseFromNumberString(conversionValue); } public BigDecimal getCost() { return cost; } public void setCost(BigDecimal cost) { this.cost = cost; } public BigDecimal getCostPerAllConversion() { return costPerAllConversion; } public void setCostPerAllConversion(BigDecimal costPerAllConversion) { this.costPerAllConversion = costPerAllConversion; } public BigDecimal getCostPerConversion() { return costPerConversion; } public void setCostPerConversion(BigDecimal costPerConversion) { this.costPerConversion = costPerConversion; } public BigDecimal getCpcBid() { return cpcBid; } public void setCpcBid(BigDecimal cpcBid) { this.cpcBid = cpcBid; } public String getCpcBidSource() { return cpcBidSource; } public void setCpcBidSource(String cpcBidSource) { this.cpcBidSource = cpcBidSource; } public BigDecimal getCpmBid() { return cpmBid; } public void setCpmBid(BigDecimal cpmBid) { this.cpmBid = cpmBid; } public String getCpmBidSource() { return cpmBidSource; } public void setCpmBidSource(String cpmBidSource) { this.cpmBidSource = cpmBidSource; } public String getCriteria() { return criteria; } public void setCriteria(String criteria) { this.criteria = criteria; } public String getCriteriaDestinationUrl() { return criteriaDestinationUrl; } public void setCriteriaDestinationUrl(String criteriaDestinationUrl) { this.criteriaDestinationUrl = criteriaDestinationUrl; } public String getCrossDeviceConversions() { return BigDecimalUtil.formatAsReadable(crossDeviceConversions); } public BigDecimal getCrossDeviceConversionsBigDecimal() { return crossDeviceConversions; } public void setCrossDeviceConversions(String crossDeviceConversions) { this.crossDeviceConversions = BigDecimalUtil.parseFromNumberString(crossDeviceConversions); } public String getCtr() { return BigDecimalUtil.formatAsReadable(ctr); } public BigDecimal getCtrBigDecimal() { return ctr; } public void setCtr(String ctr) { this.ctr = (ctr == null ? null : BigDecimalUtil.parseFromNumberString(ctr.replace("%",""))); } public String getCustomerDescriptiveName() { return customerDescriptiveName; } public void setCustomerDescriptiveName(String customerDescriptiveName) { this.customerDescriptiveName = customerDescriptiveName; } public String getDevice() { return device; } public void setDevice(String device) { this.device = device; } public String getEngagementRate() { return BigDecimalUtil.formatAsReadable(engagementRate); } public BigDecimal getEngagementRateBigDecimal() { return engagementRate; } public void setEngagementRate(String engagementRate) { this.engagementRate = BigDecimalUtil.parseFromNumberString(engagementRate); } public Long getEngagements() { return engagements; } public void setEngagements(Long engagements) { this.engagements = engagements; } public String getExternalConversionSource() { return externalConversionSource; } public void setExternalConversionSource(String externalConversionSource) { this.externalConversionSource = externalConversionSource; } public String getFinalAppUrls() { return finalAppUrls; } public void setFinalAppUrls(String finalAppUrls) { this.finalAppUrls = finalAppUrls; } public String getFinalMobileUrls() { return finalMobileUrls; } public void setFinalMobileUrls(String finalMobileUrls) { this.finalMobileUrls = finalMobileUrls; } public String getFinalUrls() { return finalUrls; } public void setFinalUrls(String finalUrls) { this.finalUrls = finalUrls; } public Long getGmailForwards() { return gmailForwards; } public void setGmailForwards(Long gmailForwards) { this.gmailForwards = gmailForwards; } public Long getGmailSaves() { return gmailSaves; } public void setGmailSaves(Long gmailSaves) { this.gmailSaves = gmailSaves; } public Long getGmailSecondaryClicks() { return gmailSecondaryClicks; } public void setGmailSecondaryClicks(Long gmailSecondaryClicks) { this.gmailSecondaryClicks = gmailSecondaryClicks; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getImpressions() { return impressions; } public void setImpressions(Long impressions) { this.impressions = impressions; } public String getInteractionRate() { return BigDecimalUtil.formatAsReadable(interactionRate); } public BigDecimal getInteractionRateBigDecimal() { return interactionRate; } public void setInteractionRate(String interactionRate) { this.interactionRate = BigDecimalUtil.parseFromNumberString(interactionRate); } public Long getInteractions() { return interactions; } public void setInteractions(Long interactions) { this.interactions = interactions; } public String getInteractionTypes() { return interactionTypes; } public void setInteractionTypes(String interactionTypes) { this.interactionTypes = interactionTypes; } public String getIsNegative() { return isNegative; } public void setIsNegative(String isNegative) { this.isNegative = isNegative; } public String getIsRestrict() { return isRestrict; } public void setIsRestrict(String isRestrict) { this.isRestrict = isRestrict; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getTrackingUrlTemplate() { return trackingUrlTemplate; } public void setTrackingUrlTemplate(String trackingUrlTemplate) { this.trackingUrlTemplate = trackingUrlTemplate; } public String getUrlCustomParameters() { return urlCustomParameters; } public void setUrlCustomParameters(String urlCustomParameters) { this.urlCustomParameters = urlCustomParameters; } public String getValuePerAllConversion() { return BigDecimalUtil.formatAsReadable(valuePerAllConversion); } public BigDecimal getValuePerAllConversionBigDecimal() { return valuePerAllConversion; } public void setValuePerAllConversion(String valuePerAllConversion) { this.valuePerAllConversion = BigDecimalUtil.parseFromNumberString(valuePerAllConversion); } public String getValuePerConversion() { return BigDecimalUtil.formatAsReadable(valuePerConversion); } public BigDecimal getValuePerConversionBigDecimal() { return valuePerConversion; } public void setValuePerConversion(String valuePerConversion) { this.valuePerConversion = BigDecimalUtil.parseFromNumberString(valuePerConversion); } public Long getVerticalId() { return verticalId; } public void setVerticalId(Long verticalId) { this.verticalId = verticalId; } public String getVideoQuartile100Rate() { return BigDecimalUtil.formatAsReadable(videoQuartile100Rate); } public BigDecimal getVideoQuartile100RateBigDecimal() { return videoQuartile100Rate; } public void setVideoQuartile100Rate(String videoQuartile100Rate) { this.videoQuartile100Rate = BigDecimalUtil.parseFromNumberString(videoQuartile100Rate); } public String getVideoQuartile25Rate() { return BigDecimalUtil.formatAsReadable(videoQuartile25Rate); } public BigDecimal getVideoQuartile25RateBigDecimal() { return videoQuartile25Rate; } public void setVideoQuartile25Rate(String videoQuartile25Rate) { this.videoQuartile25Rate = BigDecimalUtil.parseFromNumberString(videoQuartile25Rate); } public String getVideoQuartile50Rate() { return BigDecimalUtil.formatAsReadable(videoQuartile50Rate); } public BigDecimal getVideoQuartile50RateBigDecimal() { return videoQuartile50Rate; } public void setVideoQuartile50Rate(String videoQuartile50Rate) { this.videoQuartile50Rate = BigDecimalUtil.parseFromNumberString(videoQuartile50Rate); } public String getVideoQuartile75Rate() { return BigDecimalUtil.formatAsReadable(videoQuartile75Rate); } public BigDecimal getVideoQuartile75RateBigDecimal() { return videoQuartile75Rate; } public void setVideoQuartile75Rate(String videoQuartile75Rate) { this.videoQuartile75Rate = BigDecimalUtil.parseFromNumberString(videoQuartile75Rate); } public String getVideoViewRate() { return BigDecimalUtil.formatAsReadable(videoViewRate); } public BigDecimal getVideoViewRateBigDecimal() { return videoViewRate; } public void setVideoViewRate(String videoViewRate) { this.videoViewRate = BigDecimalUtil.parseFromNumberString(videoViewRate); } public Long getVideoViews() { return videoViews; } public void setVideoViews(Long videoViews) { this.videoViews = videoViews; } public Long getViewThroughConversions() { return viewThroughConversions; } public void setViewThroughConversions(Long viewThroughConversions) { this.viewThroughConversions = viewThroughConversions; } @Override public void setRowId() { // General fields for generating unique id. StringBuilder idBuilder = new StringBuilder(getCustomerId().toString()); if (campaignId != null) { idBuilder.append("-").append(campaignId); } if (adGroupId != null) { idBuilder.append("-").append(adGroupId); } if (id != null) { idBuilder.append("-").append(id); } idBuilder.append("-").append(getDateLabel()); // Include all segmentation fields (if set). if (!StringUtils.isEmpty(adNetworkType1)) { idBuilder.append("-").append(adNetworkType1); } if (!StringUtils.isEmpty(adNetworkType2)) { idBuilder.append("-").append(adNetworkType2); } if (!StringUtils.isEmpty(clickType)) { idBuilder.append("-").append(clickType); } if (!StringUtils.isEmpty(conversionCategoryName)) { idBuilder.append("-").append(conversionCategoryName); } if (conversionTrackerId != null) { idBuilder.append("-").append(conversionTrackerId); } if (!StringUtils.isEmpty(conversionTypeName)) { idBuilder.append("-").append(conversionTypeName); } if (!StringUtils.isEmpty(device)) { idBuilder.append("-").append(device); } if (!StringUtils.isEmpty(externalConversionSource)) { idBuilder.append("-").append(externalConversionSource); } this.rowId = idBuilder.toString(); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (obj == this) { return true; } if (obj.getClass() != getClass()) { return false; } DisplayTopicsPerformanceReport other = (DisplayTopicsPerformanceReport) obj; return new EqualsBuilder() .appendSuper(super.equals(obj)) .append(accountCurrencyCode, other.accountCurrencyCode) .append(accountDescriptiveName, other.accountDescriptiveName) .append(accountTimeZone, other.accountTimeZone) .append(activeViewCpm, other.activeViewCpm) .append(activeViewCtr, other.activeViewCtr) .append(activeViewImpressions, other.activeViewImpressions) .append(activeViewMeasurability, other.activeViewMeasurability) .append(activeViewMeasurableCost, other.activeViewMeasurableCost) .append(activeViewMeasurableImpressions, other.activeViewMeasurableImpressions) .append(activeViewViewability, other.activeViewViewability) .append(adGroupId, other.adGroupId) .append(adGroupName, other.adGroupName) .append(adGroupStatus, other.adGroupStatus) .append(adNetworkType1, other.adNetworkType1) .append(adNetworkType2, other.adNetworkType2) .append(allConversionRate, other.allConversionRate) .append(allConversions, other.allConversions) .append(allConversionValue, other.allConversionValue) .append(averageCost, other.averageCost) .append(averageCpc, other.averageCpc) .append(averageCpe, other.averageCpe) .append(averageCpm, other.averageCpm) .append(averageCpv, other.averageCpv) .append(baseAdGroupId, other.baseAdGroupId) .append(baseCampaignId, other.baseCampaignId) .append(biddingStrategyId, other.biddingStrategyId) .append(biddingStrategyName, other.biddingStrategyName) .append(biddingStrategyType, other.biddingStrategyType) .append(bidModifier, other.bidModifier) .append(campaignId, other.campaignId) .append(campaignName, other.campaignName) .append(campaignStatus, other.campaignStatus) .append(clicks, other.clicks) .append(clickType, other.clickType) .append(conversionCategoryName, other.conversionCategoryName) .append(conversionRate, other.conversionRate) .append(conversions, other.conversions) .append(conversionTrackerId, other.conversionTrackerId) .append(conversionTypeName, other.conversionTypeName) .append(conversionValue, other.conversionValue) .append(cost, other.cost) .append(costPerAllConversion, other.costPerAllConversion) .append(costPerConversion, other.costPerConversion) .append(cpcBid, other.cpcBid) .append(cpcBidSource, other.cpcBidSource) .append(cpmBid, other.cpmBid) .append(cpmBidSource, other.cpmBidSource) .append(criteria, other.criteria) .append(criteriaDestinationUrl, other.criteriaDestinationUrl) .append(crossDeviceConversions, other.crossDeviceConversions) .append(ctr, other.ctr) .append(customerDescriptiveName, other.customerDescriptiveName) .append(device, other.device) .append(engagementRate, other.engagementRate) .append(engagements, other.engagements) .append(externalConversionSource, other.externalConversionSource) .append(finalAppUrls, other.finalAppUrls) .append(finalMobileUrls, other.finalMobileUrls) .append(finalUrls, other.finalUrls) .append(gmailForwards, other.gmailForwards) .append(gmailSaves, other.gmailSaves) .append(gmailSecondaryClicks, other.gmailSecondaryClicks) .append(id, other.id) .append(impressions, other.impressions) .append(interactionRate, other.interactionRate) .append(interactions, other.interactions) .append(interactionTypes, other.interactionTypes) .append(isNegative, other.isNegative) .append(isRestrict, other.isRestrict) .append(status, other.status) .append(trackingUrlTemplate, other.trackingUrlTemplate) .append(urlCustomParameters, other.urlCustomParameters) .append(valuePerAllConversion, other.valuePerAllConversion) .append(valuePerConversion, other.valuePerConversion) .append(verticalId, other.verticalId) .append(videoQuartile100Rate, other.videoQuartile100Rate) .append(videoQuartile25Rate, other.videoQuartile25Rate) .append(videoQuartile50Rate, other.videoQuartile50Rate) .append(videoQuartile75Rate, other.videoQuartile75Rate) .append(videoViewRate, other.videoViewRate) .append(videoViews, other.videoViews) .append(viewThroughConversions, other.viewThroughConversions) .isEquals(); } @Override public int hashCode() { return new HashCodeBuilder(17, 37) .appendSuper(super.hashCode()) .append(accountCurrencyCode) .append(accountDescriptiveName) .append(accountTimeZone) .append(activeViewCpm) .append(activeViewCtr) .append(activeViewImpressions) .append(activeViewMeasurability) .append(activeViewMeasurableCost) .append(activeViewMeasurableImpressions) .append(activeViewViewability) .append(adGroupId) .append(adGroupName) .append(adGroupStatus) .append(adNetworkType1) .append(adNetworkType2) .append(allConversionRate) .append(allConversions) .append(allConversionValue) .append(averageCost) .append(averageCpc) .append(averageCpe) .append(averageCpm) .append(averageCpv) .append(baseAdGroupId) .append(baseCampaignId) .append(biddingStrategyId) .append(biddingStrategyName) .append(biddingStrategyType) .append(bidModifier) .append(campaignId) .append(campaignName) .append(campaignStatus) .append(clicks) .append(clickType) .append(conversionCategoryName) .append(conversionRate) .append(conversions) .append(conversionTrackerId) .append(conversionTypeName) .append(conversionValue) .append(cost) .append(costPerAllConversion) .append(costPerConversion) .append(cpcBid) .append(cpcBidSource) .append(cpmBid) .append(cpmBidSource) .append(criteria) .append(criteriaDestinationUrl) .append(crossDeviceConversions) .append(ctr) .append(customerDescriptiveName) .append(device) .append(engagementRate) .append(engagements) .append(externalConversionSource) .append(finalAppUrls) .append(finalMobileUrls) .append(finalUrls) .append(gmailForwards) .append(gmailSaves) .append(gmailSecondaryClicks) .append(id) .append(impressions) .append(interactionRate) .append(interactions) .append(interactionTypes) .append(isNegative) .append(isRestrict) .append(status) .append(trackingUrlTemplate) .append(urlCustomParameters) .append(valuePerAllConversion) .append(valuePerConversion) .append(verticalId) .append(videoQuartile100Rate) .append(videoQuartile25Rate) .append(videoQuartile50Rate) .append(videoQuartile75Rate) .append(videoViewRate) .append(videoViews) .append(viewThroughConversions) .toHashCode(); } }
package eng.simpleImage; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; public abstract class Image { public static <T> T load(String fileName, Class<? extends T> imageType) { BufferedImage img = null; try { img = ImageIO.read(new File(fileName)); } catch (IOException e) { throw new ImageProcessingException("Failed to load image from file " + fileName + ".", e); } Method method; try { method = imageType.getMethod("fromBufferedImage", new Class[]{BufferedImage.class}); } catch (NoSuchMethodException e) { throw new ImageProcessingException("Failed to find method 'fromBufferedImage' in type '" + imageType.getName() + "'.", e); } T ret; try { ret = (T) method.invoke(null, new Object[]{img}); } catch (IllegalAccessException | InvocationTargetException e) { throw new ImageProcessingException("Failed to convert BufferedImage into '" + imageType + "'.", e); } return ret; } protected abstract int getWidth(); protected abstract int getHeight(); protected abstract BufferedImage toBufferedImage(); public void save(String fileName) { BufferedImage img = this.toBufferedImage(); try { // retrieve image File outputfile = new File(fileName); ImageIO.write(img, "png", outputfile); } catch (IOException ex) { throw new ImageProcessingException("Failed to save image to file " + fileName + ".", ex); } } protected int ensureValueInWidth(int x) { if (x < 0) x = 0; if (x >= this.getWidth()) x = this.getWidth() - 1; return x; } protected int ensureValueInHeight(int y) { if (y < 0) y = 0; if (y >= this.getHeight()) y = this.getHeight() - 1; return y; } protected int ensureValueInColorRange(int val) { if (val < 0) val = 0; if (val > 255) val = 255; return val; } protected int getIndex(int x, int y) { int ret = x * getHeight() + y; return ret; } }
// Copyright 2021 The Terasology Foundation // SPDX-License-Identifier: Apache-2.0 package org.terasology.engine.logic.debug; import org.terasology.engine.rendering.nui.layers.hud.CoreHudWidget; import org.terasology.nui.layouts.ColumnLayout; import org.terasology.nui.layouts.PropertyLayout; /** * Simple NUI HUD widget, that comes up when pressing F1 ingame. Shows a property layout panel with all registered * Objects. * * See DebugPropertySystem#addProperty * */ public class DebugProperties extends CoreHudWidget { private ColumnLayout container; private PropertyLayout propertyLayout; @Override public void initialise() { container = find("container", ColumnLayout.class); propertyLayout = find("properties", PropertyLayout.class); } public PropertyLayout getPropertyLayout() { return propertyLayout; } }
/*! ****************************************************************************** * * Hop : The Hop Orchestration Platform * * Copyright (C) 2015 - 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.ui.pipeline.transforms.sftpput; import org.apache.commons.lang.reflect.FieldUtils; import org.apache.hop.core.Props; import org.apache.hop.workflow.actions.sftp.SFTPClient; import org.apache.hop.junit.rules.RestoreHopEngineEnvironment; import org.apache.hop.pipeline.PipelineMeta; import org.apache.hop.pipeline.transforms.sftpput.SFTPPutMeta; import org.apache.hop.ui.core.PropsUI; import org.eclipse.swt.widgets.Shell; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.ClassRule; import org.junit.Test; import java.lang.reflect.Field; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; /** * Created by Yury_Ilyukevich on 7/1/2015. */ public class SFTPPutDialogTest { @ClassRule public static RestoreHopEngineEnvironment env = new RestoreHopEngineEnvironment(); private static boolean changedPropsUi; @BeforeClass public static void hackPropsUi() throws Exception { Field props = getPropsField(); if ( props == null ) { throw new IllegalStateException( "Cannot find 'props' field in " + Props.class.getName() ); } Object value = FieldUtils.readStaticField( props, true ); if ( value == null ) { PropsUI mock = mock( PropsUI.class ); FieldUtils.writeStaticField( props, mock, true ); changedPropsUi = true; } else { changedPropsUi = false; } } @AfterClass public static void restoreNullInPropsUi() throws Exception { if ( changedPropsUi ) { Field props = getPropsField(); FieldUtils.writeStaticField( props, null, true ); } } private static Field getPropsField() { return FieldUtils.getDeclaredField( Props.class, "props", true ); } @Test public void connectToSFTP_SeveralTimes_AlwaysReturnTrue() throws Exception { SFTPClient sftp = mock( SFTPClient.class ); SFTPPutDialog sod = new SFTPPutDialog( mock( Shell.class ), new SFTPPutMeta(), mock( PipelineMeta.class ), "SFTPPutDialogTest" ); SFTPPutDialog sodSpy = spy( sod ); doReturn( sftp ).when( sodSpy ).createSFTPClient(); assertTrue( sodSpy.connectToSFTP( false, null ) ); assertTrue( sodSpy.connectToSFTP( false, null ) ); } @Test public void connectToSFTP_CreateNewConnection_AfterChange() throws Exception { SFTPClient sftp = mock( SFTPClient.class ); SFTPPutMeta sodMeta = new SFTPPutMeta(); SFTPPutDialog sod = new SFTPPutDialog( mock( Shell.class ), sodMeta, mock( PipelineMeta.class ), "SFTPPutDialogTest" ); SFTPPutDialog sodSpy = spy( sod ); doReturn( sftp ).when( sodSpy ).createSFTPClient(); assertTrue( sodSpy.connectToSFTP( false, null ) ); sodMeta.setChanged( true ); assertTrue( sodSpy.connectToSFTP( false, null ) ); verify( sodSpy, times( 2 ) ).createSFTPClient(); } }
package chi.core; import base.BaseFileUtil; import chi.bean.CHITextBean; import chi.util.CHIFileUtil; import util.SegmentUtil; import util.bean.TermBean; import java.io.IOException; import java.util.*; /** * @author yiding */ public class CHICore { private HashSet<String> dicWordSet = new HashSet<>(); private int segType = 1; public HashMap<String, HashMap<String, Float>> calculateCateWordCHI(ArrayList<CHITextBean> textBeanList, HashSet<String> dicWordSet, String corpusPath) { long start = System.currentTimeMillis(); // 获得类别 Set<String> categorys = CHIFileUtil.getCategory(corpusPath); // 存放结果 HashMap<String, HashMap<String, Float>> categoryKeyWord = new HashMap<>(); for (String cate : categorys) { HashMap<String, Float> wordCHI = new HashMap<>(); for (String word : dicWordSet) { int[] resValues = calculateResValue(cate, word, textBeanList); float wordForCateCHI = calculateCHI(resValues[0], resValues[1], resValues[2], resValues[3]); wordCHI.put(word, wordForCateCHI); } System.out.println((System.currentTimeMillis() - start) / 1000 + "s"); System.out.println("================ " + cate + " is done ================"); categoryKeyWord.put(cate, wordCHI); } System.out.println((System.currentTimeMillis() - start) / 1000 + "s"); return categoryKeyWord; } public void saveCHIModel(String outPath, HashMap<String, HashMap<String, Float>> categoryKeyWord) { try { CHIFileUtil.writeFileByLine(outPath, categoryKeyWord); } catch (IOException e) { e.printStackTrace(); } } private int[] calculateResValue(String cate, String word, ArrayList<CHITextBean> textBeanList) { int[] resValues = new int[4]; for (CHITextBean chiTextBean : textBeanList) { Set<String> wordSet = chiTextBean.getWordset(); String textCate = chiTextBean.getCategory(); if (wordSet.contains(word) && cate.equals(textCate)) { resValues[0]++; } if (wordSet.contains(word) && (!cate.equals(textCate))) { resValues[1]++; } if ((!wordSet.contains(word)) && cate.equals(textCate)) { resValues[2]++; } if ((!wordSet.contains(word)) && (!cate.equals(textCate))) { resValues[3]++; } } return resValues; } public ArrayList<CHITextBean> getTextBean(ArrayList<String> fileList) throws IOException { ArrayList<CHITextBean> chiList = new ArrayList<>(); for (String path : fileList) { CHITextBean chiTextBean = new CHITextBean(); HashSet<String> wordSet = new HashSet<>(); String content = BaseFileUtil.readFileAllContent(path); // 这种分词方式,过滤了停止词,停止词可见:https://github.com/hankcs/HanLP/blob/master/data/dictionary/stopwords.txt List<TermBean> termList = SegmentUtil.segment(content, segType); for (TermBean term : termList) { wordSet.add(term.getWord()); dicWordSet.add(term.getWord()); } String[] paths = path.split("/"); String category = paths[paths.length - 2]; chiTextBean.setCategory(category); chiTextBean.setPath(path); chiTextBean.setWordset(wordSet); chiList.add(chiTextBean); } return chiList; } public HashSet<String> getDicWordSet() { return dicWordSet; } private float calculateCHI(long a, long b, long c, long d) { long n = a + b + c + d; return (float) (n * Math.pow(a * d - b * c, 2) / ((a + c) * (a + b) * (b + d) * (c + d))); } }
package iot.technology.token.dao.service.impl; import iot.technology.token.dao.model.CustomerEntity; import iot.technology.token.dao.service.CustomerService; import iot.technology.token.dao.sql.CustomerRepository; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service @Slf4j public class CustomerServiceImpl implements CustomerService { @Autowired private CustomerRepository customerRepository; @Override public CustomerEntity findCustomerById(long customerId) { log.trace("Executing findCustomerById [{}]", customerId); return customerRepository.findById(customerId).get(); } }
package io.adtrace.sample; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() { assertEquals(4, 2 + 2); } }
package com.liusp.roommv.controller; import java.io.IOException; import net.paoding.analysis.analyzer.PaodingAnalyzer; import org.apache.log4j.Logger; import org.apache.lucene.analysis.Analyzer; import org.springframework.beans.factory.config.ConfigurableBeanFactory; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.liusp.roommv.common.RoommvConstant; import com.liusp.roommv.index.HtmlIndexer; import com.liusp.roommv.vo.AjaxResult; @Controller(value = "indexController") @Scope(ConfigurableBeanFactory.SCOPE_SINGLETON) @RequestMapping("/indexControl") public class IndexController { public static final Logger logger = Logger.getLogger(IndexController.class); @RequestMapping("/deleteAllHtmlIndex") public @ResponseBody AjaxResult deleteAllHtmlIndex() { AjaxResult result = new AjaxResult(); try { HtmlIndexer indexer = new HtmlIndexer(); indexer.setIndexesPath(RoommvConstant.HTML_INDEXES_PATH); indexer.deleteAll(); result.setResultCode(AjaxResult.ResultCode.SUCCESS); } catch (Exception e) { // TODO Auto-generated catch block result.setResultCode(AjaxResult.ResultCode.FAILED); logger.error("系统错误", e); } return result; } @RequestMapping("/createHtmlIndex") public @ResponseBody AjaxResult createHtmlIndex() { AjaxResult result = new AjaxResult(); try { Analyzer analyzer = new PaodingAnalyzer(); HtmlIndexer indexer = new HtmlIndexer( RoommvConstant.HTML_INDEXES_PATH, RoommvConstant.HTML_FILES_PATH); indexer.setAnalyzer(analyzer); indexer.createSearchIndexes(); result.setResultCode(AjaxResult.ResultCode.SUCCESS); } catch (Exception e) { // TODO Auto-generated catch block result.setResultCode(AjaxResult.ResultCode.FAILED); logger.error("系统错误", e); } return result; } @RequestMapping("/optimizeHtmlIndex") public @ResponseBody AjaxResult optimizeHtmlIndex() { AjaxResult result = new AjaxResult(); try { HtmlIndexer indexer = new HtmlIndexer(); indexer.setIndexesPath(RoommvConstant.HTML_INDEXES_PATH); indexer.optimize(); result.setResultCode(AjaxResult.ResultCode.SUCCESS); } catch (Exception e) { // TODO Auto-generated catch block result.setResultCode(AjaxResult.ResultCode.FAILED); logger.error("系统错误", e); } return result; } @RequestMapping("") public String indexControl() throws IOException { return "indexControl"; } }
package com.yjcocoa.oom; import java.util.ArrayList; import java.util.List; /** * <p>Title: HeapOOM</p> * <p>Description: </p> * <p>Create Time: 2017/12/1 下午5:18</p> * <p>Copyright: © 2017年 java. All rights reserved.</p> * * @author 阳君 * @version 1.0 */ public class HeapOOM { public static void main(String[] args) { System.out.println("开始"); List list = new ArrayList(); while (true) { list.add(new HeapOOM()); } } } /* 堆溢出 java -Xms20m -Xmx20m -XX:+HeapDumpOnOutOfMemoryError com.yjcocoa.oom.HeapOOM 错误: java.lang.OutOfMemoryError: Java heap space Dumping heap to java_pid19833.hprof ... Heap dump file created [28780192 bytes in 0.134 secs] */
/* * Copyright (C) 2018 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. */ package com.google.cloud.teleport.spanner; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import com.google.cloud.spanner.ReadOnlyTransaction; import com.google.cloud.teleport.spanner.ddl.Ddl; import com.google.cloud.teleport.spanner.ddl.InformationSchemaScanner; import com.google.protobuf.util.JsonFormat; import java.io.File; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.Arrays; import java.util.Collections; import org.apache.avro.LogicalTypes; import org.apache.avro.Schema; import org.apache.avro.SchemaBuilder; import org.apache.avro.file.DataFileWriter; import org.apache.avro.generic.GenericDatumWriter; import org.apache.avro.generic.GenericRecord; import org.apache.avro.generic.GenericRecordBuilder; import org.apache.beam.sdk.PipelineResult; import org.apache.beam.sdk.options.ValueProvider; import org.apache.beam.sdk.testing.TestPipeline; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.rules.TemporaryFolder; /** * Tests import of Avro files. * This requires an active GCP project with a Spanner instance. * Hence this test can only be run locally with a project set up using 'gcloud config'. */ @Category(IntegrationTest.class) public class ImportFromAvroTest { @Rule public final TestPipeline importPipeline = TestPipeline.create(); @Rule public final TemporaryFolder tmpDir = new TemporaryFolder(); @Rule public final SpannerServerResource spannerServer = new SpannerServerResource(); private final String dbName = "importdbtest"; @Before public void setup() { // Just to make sure an old database is not left over. spannerServer.dropDatabase(dbName); } @After public void tearDown() { spannerServer.dropDatabase(dbName); } @Test public void booleans() throws Exception { SchemaBuilder.RecordBuilder<Schema> record = SchemaBuilder.record("booleans"); SchemaBuilder.FieldAssembler<Schema> fieldAssembler = record.fields(); fieldAssembler // Primary key. .requiredLong("id") // Boolean columns. .optionalBoolean("optional_boolean") .requiredBoolean("required_boolean") .optionalString("optional_string_boolean") .requiredString("required_string_boolean"); Schema schema = fieldAssembler.endRecord(); String spannerSchema = "CREATE TABLE `AvroTable` (" + "`id` INT64 NOT NULL," + "`optional_boolean` BOOL," + "`required_boolean` BOOL NOT NULL," + "`optional_string_boolean` BOOL," + "`required_string_boolean` BOOL NOT NULL," + ") PRIMARY KEY (`id`)"; runTest(schema, spannerSchema, Arrays.asList(new GenericRecordBuilder(schema) .set("id", 1L) .set("required_boolean", true) .set("optional_boolean", false) .set("required_string_boolean", "FALSE") .set("optional_string_boolean", "TRUE") .build(), new GenericRecordBuilder(schema) .set("id", 2L) .set("required_boolean", false) .set("optional_boolean", true) .set("required_string_boolean", "true") .set("optional_string_boolean", "f") .build())); } @Test public void integers() throws Exception { SchemaBuilder.RecordBuilder<Schema> record = SchemaBuilder.record("integers"); SchemaBuilder.FieldAssembler<Schema> fieldAssembler = record.fields(); fieldAssembler // Primary key. .requiredLong("id") // Integer columns. .optionalInt("optional_int") .requiredInt("required_int") .requiredLong("required_long") .optionalLong("optional_long") .optionalString("optional_string_long") .requiredString("required_string_long"); Schema schema = fieldAssembler.endRecord(); String spannerSchema = "CREATE TABLE `AvroTable` (" + "`id` INT64 NOT NULL," + "`optional_int` INT64," + "`required_int` INT64 NOT NULL," + "`optional_long` INT64," + "`required_long` INT64 NOT NULL," + "`optional_string_long` INT64," + "`required_string_long` INT64 NOT NULL," + ") PRIMARY KEY (`id`)"; runTest(schema, spannerSchema, Arrays.asList(new GenericRecordBuilder(schema) .set("id", 1L) .set("optional_int", 1) .set("optional_long", 2L) .set("required_long", 3L) .set("required_int", 4) .set("optional_string_long", "1000") .set("required_string_long", "5000") .build(), new GenericRecordBuilder(schema) .set("id", 2L) .set("optional_int", 10) .set("optional_long", 20L) .set("required_long", 30L) .set("required_int", 40) .set("optional_string_long", "10000") .set("required_string_long", "50000") .build())); } @Test public void floats() throws Exception { SchemaBuilder.RecordBuilder<Schema> record = SchemaBuilder.record("floats"); SchemaBuilder.FieldAssembler<Schema> fieldAssembler = record.fields(); fieldAssembler // Primary key. .requiredLong("id") // Integer columns. .optionalInt("optional_int") .requiredInt("required_int") .requiredLong("required_long") .optionalLong("optional_long") // Floating columns .optionalFloat("optional_float") .requiredFloat("required_float") .requiredDouble("required_double") .optionalDouble("optional_double") .optionalString("optional_string_double") .requiredString("required_string_double"); Schema schema = fieldAssembler.endRecord(); String spannerSchema = "CREATE TABLE `AvroTable` (" + "`id` INT64 NOT NULL," + "`optional_int` FLOAT64," + "`required_int` FLOAT64 NOT NULL," + "`optional_long` FLOAT64," + "`required_long` FLOAT64 NOT NULL," + "`optional_float` FLOAT64," + "`required_float` FLOAT64 NOT NULL," + "`optional_double` FLOAT64," + "`required_double` FLOAT64 NOT NULL," + "`optional_string_double` FLOAT64," + "`required_string_double` FLOAT64 NOT NULL," + ") PRIMARY KEY (`id`)"; runTest(schema, spannerSchema, Arrays.asList(new GenericRecordBuilder(schema) .set("id", 1L) .set("optional_int", 1) .set("required_int", 4) .set("optional_long", 2L) .set("required_long", 3L) .set("optional_float", 2.3f) .set("required_float", 3.4f) .set("optional_double", 2.5) .set("required_double", 3.6) .set("optional_string_double", "100.30") .set("required_string_double", "0.1e-3") .build(), new GenericRecordBuilder(schema) .set("id", 2L) .set("optional_int", 10) .set("required_int", 40) .set("optional_long", 20L) .set("required_long", 30L) .set("optional_float", 2.03f) .set("required_float", 3.14f) .set("optional_double", 2.05) .set("required_double", 3.16) .set("optional_string_double", "100.301") .set("required_string_double", "1.1e-3") .build())); } @Test public void strings() throws Exception { SchemaBuilder.RecordBuilder<Schema> record = SchemaBuilder.record("strings"); SchemaBuilder.FieldAssembler<Schema> fieldAssembler = record.fields(); fieldAssembler // Primary key. .requiredLong("id") // Integer columns. .optionalInt("optional_int") .requiredInt("required_int") .requiredLong("required_long") .optionalLong("optional_long") // Floating columns .optionalFloat("optional_float") .requiredFloat("required_float") .requiredDouble("required_double") .optionalDouble("optional_double") // String columns .optionalString("optional_string") .requiredString("required_string"); Schema schema = fieldAssembler.endRecord(); String spannerSchema = "CREATE TABLE `AvroTable` (" + "`id` INT64 NOT NULL," + "`optional_int` STRING(10)," + "`required_int` STRING(MAX) NOT NULL," + "`optional_long` STRING(MAX)," + "`required_long` STRING(MAX) NOT NULL," + "`optional_float` STRING(MAX)," + "`required_float` STRING(MAX) NOT NULL," + "`optional_double` STRING(MAX)," + "`required_double` STRING(MAX) NOT NULL," + "`optional_string` STRING(MAX)," + "`required_string` STRING(30) NOT NULL," + ") PRIMARY KEY (`id`)"; runTest(schema, spannerSchema, Arrays.asList(new GenericRecordBuilder(schema) .set("id", 1L) .set("optional_int", 1) .set("required_int", 4) .set("optional_long", 2L) .set("required_long", 3L) .set("optional_float", 2.3f) .set("required_float", 3.4f) .set("optional_double", 2.5) .set("required_double", 3.6) .set("optional_string", "ONE STRING") .set("required_string", "TWO STRING") .build(), new GenericRecordBuilder(schema) .set("id", 2L) .set("optional_int", 10) .set("required_int", 40) .set("optional_long", 20L) .set("required_long", 30L) .set("optional_float", 2.03f) .set("required_float", 3.14f) .set("optional_double", 2.05) .set("required_double", 3.16) .set("optional_string", null) .set("required_string", "THE STRING") .build())); } @Test public void timestamps() throws Exception { SchemaBuilder.RecordBuilder<Schema> record = SchemaBuilder.record("timestamps"); SchemaBuilder.FieldAssembler<Schema> fieldAssembler = record.fields(); fieldAssembler // Primary key. .requiredLong("id") // Long columns. .requiredLong("required_long") .optionalLong("optional_long") // String columns .optionalString("optional_string") .requiredString("required_string"); Schema schema = fieldAssembler.endRecord(); String spannerSchema = "CREATE TABLE `AvroTable` (" + "`id` INT64 NOT NULL," + "`optional_long` TIMESTAMP," + "`required_long` TIMESTAMP NOT NULL," + "`optional_string` TIMESTAMP," + "`required_string` TIMESTAMP NOT NULL," + ") PRIMARY KEY (`id`)"; runTest( schema, spannerSchema, Arrays.asList( new GenericRecordBuilder(schema) .set("id", 1L) .set("optional_long", 5000000L) .set("required_long", 6000000L) .set("optional_string", "2018-06-06T21:00:35.312000000Z") .set("required_string", "2018-06-06T21:00:35.312000000Z") .build(), new GenericRecordBuilder(schema) .set("id", 2L) .set("optional_long", 500000330L) .set("required_long", 6000020000L) .set("optional_string", "2017-06-06T21:00:35.312000000Z") .set("required_string", "2017-06-06T21:00:35.312000000Z") .build(), new GenericRecordBuilder(schema) .set("id", 3L) .set("optional_long", null) .set("required_long", 6000020000L) .set("optional_string", null) .set("required_string", "0001-01-01T00:00:00Z") .build())); } @Test public void dates() throws Exception { // Unfortunately Avro SchemaBuilder has a limitation of not allowing nullable LogicalTypes. Schema dateType = LogicalTypes.date().addToSchema(Schema.create(Schema.Type.INT)); Schema schema = SchemaBuilder.record("dates") .fields() // Primary key. .requiredLong("id") // String columns .optionalString("optional_string") .requiredString("required_string") .name("required_int").type(dateType).noDefault() .endRecord(); String spannerSchema = "CREATE TABLE `AvroTable` (" + "`id` INT64 NOT NULL," + "`optional_string` DATE," + "`required_string` DATE NOT NULL," + "`required_int` DATE NOT NULL," + ") PRIMARY KEY (`id`)"; runTest( schema, spannerSchema, Arrays.asList( new GenericRecordBuilder(schema) .set("id", 1L) .set("optional_string", "2018-03-04") .set("required_string", "2018-04-04") .set("required_int", 2) .build(), new GenericRecordBuilder(schema) .set("id", 2L) .set("optional_string", null) .set("required_string", "2018-01-02") .set("required_int", 3) .build())); } // TODO: enable this test once generated columns are supported. // @Test public void generatedColumns() throws Exception { SchemaBuilder.RecordBuilder<Schema> record = SchemaBuilder.record("generatedColumns"); SchemaBuilder.FieldAssembler<Schema> fieldAssembler = record.fields(); fieldAssembler // Primary key. .requiredLong("id") // Integer columns. .optionalLong("optional_generated") .requiredLong("required_generated"); Schema schema = fieldAssembler.endRecord(); String spannerSchema = "CREATE TABLE `AvroTable` (" + "`id` INT64 NOT NULL," + "`optional_generated` INT64 AS (`id`) STORED," + "`required_generated` INT64 NOT NULL AS (`id`) STORED," + ") PRIMARY KEY (`id`)"; runTest(schema, spannerSchema, Arrays.asList(new GenericRecordBuilder(schema) .set("id", 1L) .set("optional_generated", 1L) .set("required_generated", 1L) .build())); } private void runTest(Schema avroSchema, String spannerSchema, Iterable<GenericRecord> records) throws Exception { // Create the Avro file to be imported. String fileName = "avroFile.avro"; ExportProtos.Export exportProto = ExportProtos.Export.newBuilder() .addTables( ExportProtos.Export.Table.newBuilder() .setName("AvroTable") .addDataFiles(fileName) .build()) .addDatabaseOptions( ExportProtos.Export.DatabaseOption.newBuilder() .setOptionName("version_retention_period") .setOptionValue("\"4d\"") .build()) .build(); JsonFormat.printer().print(exportProto); File manifestFile = tmpDir.newFile("spanner-export.json"); String manifestFileLocation = manifestFile.getParent(); Files.write( manifestFile.toPath(), JsonFormat.printer().print(exportProto).getBytes(StandardCharsets.UTF_8)); File avroFile = tmpDir.newFile(fileName); try (DataFileWriter<GenericRecord> fileWriter = new DataFileWriter<>( new GenericDatumWriter<>(avroSchema))) { fileWriter.create(avroSchema, avroFile); for (GenericRecord r : records) { fileWriter.append(r); } fileWriter.flush(); } // Create the target database. spannerServer.createDatabase(dbName, Collections.singleton(spannerSchema)); // Run the import pipeline. importPipeline.apply( "Import", new ImportTransform( spannerServer.getSpannerConfig(dbName), ValueProvider.StaticValueProvider.of(manifestFileLocation), ValueProvider.StaticValueProvider.of(true), ValueProvider.StaticValueProvider.of(true), ValueProvider.StaticValueProvider.of(true))); PipelineResult importResult = importPipeline.run(); importResult.waitUntilFinish(); Ddl ddl; try (ReadOnlyTransaction ctx = spannerServer.getDbClient(dbName).readOnlyTransaction()) { ddl = new InformationSchemaScanner(ctx).scan(); } assertThat(ddl.databaseOptions().size(), is(1)); ExportProtos.Export.DatabaseOption dbOption = ddl.databaseOptions().get(0); assertThat(dbOption.getOptionName(), is("version_retention_period")); assertThat(dbOption.getOptionValue(), is("4d")); } }