text
stringlengths
7
1.01M
package com.qf.service; import com.qf.dto.ResultBean; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; @FeignClient("shop-search-service") public interface ISearchService { @RequestMapping("search") ResultBean searchByKeyword(@RequestParam("keyword") String keyword); @RequestMapping("addProduct") ResultBean addProduct(@RequestParam("pid") Long pid); }
/** * Copyright 2018 LinkedIn Corporation. All rights reserved. Licensed under the BSD-2 Clause license. * See LICENSE in the project root for license information. */ package com.linkedin.tony; import java.util.Arrays; import java.util.Collections; import java.util.List; import static com.linkedin.tony.Constants.SIDECAR_TB_ROLE_NAME; public class TonyConfigurationKeys { public enum FrameworkType { TENSORFLOW, PYTORCH, HOROVOD, MXNET, STANDALONE } public enum DistributedMode { GANG, FCFS } private TonyConfigurationKeys() { } public static final String TONY_PREFIX = "tony."; // Version info configuration public static final String TONY_VERSION_INFO_PREFIX = TONY_PREFIX + "version-info."; public static final String TONY_VERSION_INFO_VERSION = TONY_VERSION_INFO_PREFIX + "version"; public static final String TONY_VERSION_INFO_REVISION = TONY_VERSION_INFO_PREFIX + "revision"; public static final String TONY_VERSION_INFO_BRANCH = TONY_VERSION_INFO_PREFIX + "branch"; public static final String TONY_VERSION_INFO_USER = TONY_VERSION_INFO_PREFIX + "user"; public static final String TONY_VERSION_INFO_DATE = TONY_VERSION_INFO_PREFIX + "date"; public static final String TONY_VERSION_INFO_URL = TONY_VERSION_INFO_PREFIX + "url"; public static final String TONY_VERSION_INFO_CHECKSUM = TONY_VERSION_INFO_PREFIX + "checksum"; public static final String OTHER_NAMENODES_TO_ACCESS = TONY_PREFIX + "other.namenodes"; // History-related configuration public static final String TONY_HISTORY_PREFIX = TONY_PREFIX + "history."; public static final String TONY_HISTORY_LOCATION = TONY_HISTORY_PREFIX + "location"; public static final String DEFAULT_TONY_HISTORY_LOCATION = "/path/to/tony-history"; public static final String TONY_HISTORY_INTERMEDIATE = TONY_HISTORY_PREFIX + "intermediate"; public static final String DEFAULT_TONY_HISTORY_INTERMEDIATE = DEFAULT_TONY_HISTORY_LOCATION + "/intermediate"; public static final String TONY_HISTORY_FINISHED = TONY_HISTORY_PREFIX + "finished"; public static final String DEFAULT_TONY_HISTORY_FINISHED = DEFAULT_TONY_HISTORY_LOCATION + "/finished"; public static final String TONY_HISTORY_MOVER_INTERVAL_MS = TONY_HISTORY_PREFIX + "mover-interval-ms"; public static final int DEFAULT_TONY_HISTORY_MOVER_INTERVAL_MS = 5 * 60 * 1000; public static final String TONY_HISTORY_FINISHED_DIR_TIMEZONE = TONY_HISTORY_PREFIX + "finished-dir-timezone"; public static final String DEFAULT_TONY_HISTORY_FINISHED_DIR_TIMEZONE = "UTC"; // How many seconds to retain history files for public static final String TONY_HISTORY_RETENTION_SECONDS = TONY_HISTORY_PREFIX + "retention-sec"; public static final int DEFAULT_TONY_HISTORY_RETENTION_SECONDS = 30 * 24 * 60 * 60; // How frequently to run the purger thread public static final String TONY_HISTORY_PURGER_INTERVAL_MS = TONY_HISTORY_PREFIX + "purger-interval-ms"; public static final int DEFAULT_TONY_HISTORY_PURGER_INTERVAL_MS = 6 * 60 * 60 * 1000; public static final String TONY_PORTAL_CACHE_MAX_ENTRIES = TONY_PREFIX + "portal.cache.max-entries"; public static final String DEFAULT_TONY_PORTAL_CACHE_MAX_ENTRIES = "10000"; public static final String TONY_KEYTAB_USER = TONY_PREFIX + "keytab.user"; public static final String DEFAULT_TONY_KEYTAB_USER = "user"; public static final String TONY_KEYTAB_LOCATION = TONY_PREFIX + "keytab.location"; public static final String DEFAULT_TONY_KEYTAB_LOCATION = "/path/to/tony.keytab"; // All these variables are here to pass TestTonyConfigurationFields. // Do not remove unless it is also removed in tony-default.xml. public static final String TONY_HTTPS_PORT = TONY_PREFIX + "https.port"; public static final String DEFAULT_TONY_HTTPS_PORT = "19886"; public static final String TONY_HTTPS_KEYSTORE_PATH = TONY_PREFIX + "https.keystore.path"; public static final String DEFAULT_TONY_HTTPS_KEYSTORE_PATH = "/path/to/keystore.jks"; public static final String TONY_HTTPS_KEYSTORE_TYPE = TONY_PREFIX + "https.keystore.type"; public static final String DEFAULT_TONY_HTTPS_KEYSTORE_TYPE = "JKS"; public static final String TONY_HTTPS_KEYSTORE_PASSWORD = TONY_PREFIX + "https.keystore.password"; public static final String DEFAULT_TONY_HTTPS_KEYSTORE_PASSWORD = "password"; public static final String TONY_HTTPS_KEYSTORE_ALGORITHM = TONY_PREFIX + "https.keystore.algorithm"; public static final String DEFAULT_TONY_HTTPS_KEYSTORE_ALGORITHM = "SunX509"; public static final String TONY_HTTP_PORT = TONY_PREFIX + "http.port"; public static final String DEFAULT_TONY_HTTP_PORT = "disabled"; public static final String TONY_SECRET_KEY = TONY_PREFIX + "secret.key"; public static final String DEFAULT_TONY_SECRET_KEY = "changeme"; public static final String TONY_PORTAL_URL = TONY_PREFIX + "portal.url"; public static final String DEFAULT_TONY_PORTAL_URL = "https://localhost:" + DEFAULT_TONY_HTTPS_PORT; // Application configurations public static final String YARN_QUEUE_NAME = TONY_PREFIX + "yarn.queue"; public static final String DEFAULT_YARN_QUEUE_NAME = "default"; public static final String TONY_APPLICATION_PREFIX = TONY_PREFIX + "application."; public static final String APPLICATION_NAME = TONY_APPLICATION_PREFIX + "name"; public static final String DEFAULT_APPLICATION_NAME = "TonyApplication"; public static final String APPLICATION_TYPE = TONY_APPLICATION_PREFIX + "type"; public static final String DEFAULT_APPLICATION_TYPE = Constants.APP_TYPE; public static final String FRAMEWORK_NAME = TONY_APPLICATION_PREFIX + "framework"; public static final String DEFAULT_FRAMEWORK_NAME = "tensorflow"; public static final String APPLICATION_NODE_LABEL = TONY_APPLICATION_PREFIX + "node-label"; public static final String ENABLE_PREPROCESSING_JOB = TONY_APPLICATION_PREFIX + "enable-preprocess"; public static final boolean DEFAULT_ENABLE_PREPROCESSING_JOB = false; public static final String APPLICATION_TIMEOUT = TONY_APPLICATION_PREFIX + "timeout"; public static final int DEFAULT_APPLICATION_TIMEOUT = 0; public static final String RM_CLIENT_CONNECT_RETRY_MULTIPLIER = TONY_APPLICATION_PREFIX + "num-client-rm-connect-retries"; public static final int DEFAULT_RM_CLIENT_CONNECT_RETRY_MULTIPLIER = 3; public static final String APPLICATION_TAGS = TONY_APPLICATION_PREFIX + "tags"; public static final String APPLICATION_PREPARE_STAGE = TONY_APPLICATION_PREFIX + "prepare-stage"; public static final String APPLICATION_TRAINING_STAGE = TONY_APPLICATION_PREFIX + "training-stage"; public static final String APPLICATION_DISTRIBUTED_MODE = TONY_APPLICATION_PREFIX + "distributed-mode"; public static final String DEFAULT_APPLICATION_DISTRIBUTED_MODE = DistributedMode.GANG.name(); public static final String TONY_HADOOP_PREFIX = TONY_APPLICATION_PREFIX + "hadoop."; public static final String APPLICATION_HADOOP_LOCATION = TONY_HADOOP_PREFIX + "location"; public static final String APPLICATION_HADOOP_CLASSPATH = TONY_HADOOP_PREFIX + "classpath"; // Task configurations public static final String TONY_TASK_PREFIX = TONY_PREFIX + "task."; /** * Max total number of task instances that can be requested across all task types. */ public static final String MAX_TOTAL_INSTANCES = TONY_TASK_PREFIX + "max-total-instances"; public static final int DEFAULT_MAX_TOTAL_INSTANCES = -1; public static final String TASK_AM_JVM_OPTS = TONY_TASK_PREFIX + "am.jvm.opts"; public static final String TASK_EXECUTOR_JVM_OPTS = TONY_TASK_PREFIX + "executor.jvm.opts"; public static final String DEFAULT_TASK_EXECUTOR_JVM_OPTS = "-Xmx1536m"; public static final String TASK_JAVA_AGENT = TONY_TASK_PREFIX + "java.agent"; public static final String TASK_HEARTBEAT_INTERVAL_MS = TONY_TASK_PREFIX + "heartbeat-interval-ms"; public static final int DEFAULT_TASK_HEARTBEAT_INTERVAL_MS = 1000; public static final String TASK_MAX_MISSED_HEARTBEATS = TONY_TASK_PREFIX + "max-missed-heartbeats"; public static final int DEFAULT_TASK_MAX_MISSED_HEARTBEATS = 25; public static final String TASK_METRICS_UPDATE_INTERVAL_MS = TONY_TASK_PREFIX + "metrics-interval-ms"; public static final int DEFAULT_TASK_METRICS_UPDATE_INTERVAL_MS = 5000; public static final String TASK_GPU_METRICS_ENABLED = TONY_TASK_PREFIX + "gpu-metrics.enabled"; public static final boolean DEFAULT_TASK_GPU_METRICS_ENABLED = true; public static final String TASK_EXECUTION_TIMEOUT = TONY_TASK_PREFIX + "executor.execution-timeout-ms"; public static final int DEFAULT_TASK_EXECUTION_TIMEOUT = 0; // AM configurations public static final String AM_PREFIX = TONY_PREFIX + "am."; public static final String AM_RETRY_COUNT = AM_PREFIX + "retry-count"; public static final int DEFAULT_AM_RETRY_COUNT = 0; public static final String AM_MEMORY = AM_PREFIX + "memory"; public static final String DEFAULT_AM_MEMORY = "2g"; public static final String AM_VCORES = AM_PREFIX + "vcores"; public static final int DEFAULT_AM_VCORES = 1; public static final String AM_GPUS = AM_PREFIX + "gpus"; public static final int DEFAULT_AM_GPUS = 0; public static final String AM_WAIT_CLIENT_STOP_TIMEOUT = AM_PREFIX + "wait-client-signal-stop-timeout-sec"; public static final int DEFAULT_AM_WAIT_CLIENT_STOP_TIMEOUT = 15; // Keys/default values for configurable TensorFlow job names public static final String INSTANCES_REGEX = "tony\\.([a-z]+)\\.instances"; public static final String MAX_TOTAL_RESOURCES_REGEX = TONY_TASK_PREFIX + "max-total-([a-z]+)"; public static final String RESOURCES_REGEX = "tony\\.([a-z]+)\\.resources"; public static final String DEFAULT_MEMORY = "2g"; public static final int DEFAULT_VCORES = 1; public static final int DEFAULT_GPUS = 0; public static String getInstancesKey(String jobName) { return String.format(TONY_PREFIX + "%s.instances", jobName); } /** * Configuration key for property controlling how many {@code jobName} task instances a job can request. * @param jobName the task type for which to get the max instances config key * @return the max instances configuration key for the {@code jobName} */ public static String getMaxInstancesKey(String jobName) { return String.format(TONY_PREFIX + "%s.max-instances", jobName); } public static String getResourceKey(String jobName, String resource) { return String.format(TONY_PREFIX + "%s.%s", jobName, resource); } public static String getNodeLabelKey(String jobName) { return String.format(TONY_PREFIX + "%s.node-label", jobName); } public static String getDependsOnKey(String jobName) { return String.format(TONY_PREFIX + "%s.depends-on", jobName); } public static String getMaxTotalResourceKey(String resource) { return String.format(TONY_TASK_PREFIX + "max-total-%s", resource); } // Job specific resources public static String getResourcesKey(String jobName) { return String.format(TONY_PREFIX + "%s.resources", jobName); } // Resources for all containers public static String getContainerResourcesKey() { return TONY_PREFIX + "containers.resources"; } // Job specific execution command public static String getExecuteCommandKey(String jobName) { return String.format(TONY_PREFIX + "%s.command", jobName); } // Execution command for all containers public static String getContainerExecuteCommandKey() { return TONY_PREFIX + "containers.command"; } // Job specific docker image public static String getDockerImageKey(String jobName) { return String.format(DOCKER_PREFIX + "%s.image", jobName); } // Docker images for all containers public static String getContainerDockerKey() { return DOCKER_PREFIX + "containers.image"; } public static String getContainerDockerMountKey() { return DOCKER_PREFIX + "containers.mount"; } // Container configurations public static final String CONTAINER_PREFIX = TONY_PREFIX + "container."; public static final String CONTAINER_REGISTRATION_TIMEOUT = CONTAINER_PREFIX + "registration.timeout"; public static final int DEFAULT_CONTAINER_REGISTRATION_TIMEOUT = 15 * 60 * 1000; public static final String CONTAINER_ALLOCATION_TIMEOUT = CONTAINER_PREFIX + "allocation.timeout"; public static final int DEFAULT_CONTAINER_ALLOCATION_TIMEOUT = 0; // Job types that we don't wait to finish public static final String UNTRACKED_JOBTYPES = TONY_APPLICATION_PREFIX + "untracked.jobtypes"; public static final String UNTRACKED_JOBTYPES_DEFAULT = "ps"; // Job types that we don't wait to finish and ignore its failure. public static final String SIDECAR_JOBTYPES = TONY_APPLICATION_PREFIX + "sidecar.jobtypes"; public static final String DEFAULT_SIDECAR_JOBTYPES = SIDECAR_TB_ROLE_NAME; // Job types that we will short circuit when it failed public static final String STOP_ON_FAILURE_JOBTYPES = TONY_APPLICATION_PREFIX + "stop-on-failure-jobtypes"; // Tony configuration to return failure when a worker failed public static final String FAIL_ON_WORKER_FAILURE_ENABLED = TONY_APPLICATION_PREFIX + "fail-on-worker-failure-enabled"; public static final boolean DEFAULT_FAIL_ON_WORKER_FAILURE_ENABLED = false; // Tony with docker configuration public static final String DOCKER_PREFIX = TONY_PREFIX + "docker."; public static final String DOCKER_ENABLED = DOCKER_PREFIX + "enabled"; public static final boolean DEFAULT_DOCKER_ENABLED = false; // Environment public static final String CONTAINER_LAUNCH_ENV = TONY_PREFIX + "containers.envs"; public static final String EXECUTION_ENV = TONY_PREFIX + "execution.envs"; public static final String GPU_PATH_TO_EXEC = TONY_PREFIX + "gpu-exec-path"; public static final String DEFAULT_GPU_PATH_TO_EXEC = "nvidia-smi"; public static final String PYTHON_EXEC_PATH = TONY_PREFIX + "python-exec-path"; // Local testing configurations public static final String SECURITY_ENABLED = TONY_APPLICATION_PREFIX + "security.enabled"; public static final boolean DEFAULT_SECURITY_ENABLED = true; public static final String HDFS_CONF_LOCATION = TONY_APPLICATION_PREFIX + "hdfs-conf-path"; public static final String YARN_CONF_LOCATION = TONY_APPLICATION_PREFIX + "yarn-conf-path"; public static final String MAPRED_CONF_LOCATION = TONY_APPLICATION_PREFIX + "mapred-conf-path"; // Configurations that can take multiple values. public static final List<String> MULTI_VALUE_CONF = Collections.unmodifiableList( Arrays.asList(CONTAINER_LAUNCH_ENV, EXECUTION_ENV, getContainerResourcesKey())); // For Horovod public static final String TONY_HOROVOD_PREFIX = TONY_PREFIX + "horovod."; // Local testing horovod driver public static final String TEST_HOROVOD_FAIL_ENABLE_KEY = TONY_HOROVOD_PREFIX + "mode.test.fast.fail"; public static final boolean DEFAULT_TEST_HOROVOD_FAIL = false; public static final String IN_TEST_HOROVOD_MODE = TONY_HOROVOD_PREFIX + "mode.test"; public static final boolean DEFAULT_IN_TEST_HOROVOD_MODE = false; public static final String HOROVOD_DRIVER_DEBUG_MODE_ENABLE = TONY_HOROVOD_PREFIX + "driver.mode.debug"; public static final boolean DEFAULT_HOROVOD_DEBUG_MODE_ENABLE = false; // Set Tensorboard log dir to start it public static final String TENSORBOARD_LOG_DIR = TONY_APPLICATION_PREFIX + "tensorboard-log-dir"; public static final String TB_JOB_PREFIX = TONY_PREFIX + SIDECAR_TB_ROLE_NAME + "."; public static final String TB_VCORE = TB_JOB_PREFIX + "vcores"; public static final int DEFAULT_TB_VCORE = 2; public static final String TB_INSTANCES = TB_JOB_PREFIX + "instances"; public static final int DEFAULT_TB_INSTANCES = 1; public static final String TB_MEMORY = TB_JOB_PREFIX + "memory"; public static final String DEFAULT_TB_MEMORY = "2g"; public static final String TB_GPUS = TB_JOB_PREFIX + "gpus"; public static final int DEFAULT_TB_GPUS = 0; /** * Introduce the group dependency waiting time(sec), like as follows: * tony.application.group.A = worker,chief * * tony.application.dependency.evaluator.timeout.after.A = 3600 */ public static final String GROUP_REGEX = TONY_APPLICATION_PREFIX + "group\\.([A-Za-z]+)$"; public static final String GROUP_DEPEND_TIMEOUT_REGEX = TONY_APPLICATION_PREFIX + "dependency\\.([A-Za-z]+)\\.timeout\\.after\\.([A-Za-z]+)$"; public static String getGroupKey(String groupName) { return String.format(TONY_APPLICATION_PREFIX + "group.%s", groupName); } public static String getGroupDependentKey(String grp, String dependentGrp) { return String.format(TONY_APPLICATION_PREFIX + "dependency.%s.timeout.after.%s", grp, dependentGrp); } }
package com.fasterxml.jackson.dataformat.xml.ser; import java.io.IOException; import java.util.Set; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.ser.BeanPropertyWriter; import com.fasterxml.jackson.databind.ser.BeanSerializer; import com.fasterxml.jackson.databind.ser.impl.BeanAsArraySerializer; import com.fasterxml.jackson.databind.ser.impl.ObjectIdWriter; import com.fasterxml.jackson.databind.ser.std.BeanSerializerBase; import com.fasterxml.jackson.databind.util.NameTransformer; /** * Variant of {@link BeanSerializer} for XML handling. * * @author Pascal Gélinas */ public class XmlBeanSerializer extends XmlBeanSerializerBase { private static final long serialVersionUID = 1L; /* /********************************************************** /* Life-cycle: constructors /********************************************************** */ public XmlBeanSerializer(BeanSerializerBase src) { super(src); } public XmlBeanSerializer(XmlBeanSerializerBase src, ObjectIdWriter objectIdWriter, Object filterId) { super(src, objectIdWriter, filterId); } public XmlBeanSerializer(XmlBeanSerializerBase src, ObjectIdWriter objectIdWriter) { super(src, objectIdWriter); } public XmlBeanSerializer(XmlBeanSerializerBase src, Set<String> toIgnore) { super(src, toIgnore); } /* /********************************************************** /* Life-cycle: factory methods, fluent factories /********************************************************** */ @Override public JsonSerializer<Object> unwrappingSerializer(NameTransformer unwrapper) { return new UnwrappingXmlBeanSerializer(this, unwrapper); } @Override public BeanSerializerBase withObjectIdWriter(ObjectIdWriter objectIdWriter) { return new XmlBeanSerializer(this, objectIdWriter, _propertyFilterId); } @Override public BeanSerializerBase withFilterId(Object filterId) { return new XmlBeanSerializer(this, _objectIdWriter, filterId); } @Override protected BeanSerializerBase withIgnorals(Set<String> toIgnore) { return new XmlBeanSerializer(this, toIgnore); } /** * Implementation has to check whether as-array serialization * is possible reliably; if (and only if) so, will construct * a {@link BeanAsArraySerializer}, otherwise will return this * serializer as is. */ @Override protected BeanSerializerBase asArraySerializer() { /* Can not: * * - have Object Id (may be allowed in future) * - have any getter */ if ((_objectIdWriter == null) && (_anyGetterWriter == null) && (_propertyFilterId == null) ) { return new BeanAsArraySerializer(this); } // already is one, so: return this; } /* /********************************************************** /* JsonSerializer implementation that differs between impls /********************************************************** */ /** * Main serialization method that will delegate actual output to configured * {@link BeanPropertyWriter} instances. */ @Override public void serialize(Object bean, JsonGenerator g, SerializerProvider provider) throws IOException { if (_objectIdWriter != null) { _serializeWithObjectId(bean, g, provider, true); return; } g.writeStartObject(); if (_propertyFilterId != null) { serializeFieldsFiltered(bean, g, provider); } else { serializeFields(bean, g, provider); } g.writeEndObject(); } /* /********************************************************** /* Standard methods /********************************************************** */ @Override public String toString() { return "XmlBeanSerializer for " + handledType().getName(); } }
package com.itridtechnologies.resturantapp.model; public class OrderDetailModel { private String mQty; private String mOrderNamel; private String mPrice; public OrderDetailModel(String mQty, String mOrderNamel, String mPrice) { this.mQty = mQty; this.mOrderNamel = mOrderNamel; this.mPrice = mPrice; } public String getmQty() { return mQty; } public String getmOrderNamel() { return mOrderNamel; } public String getmPrice() { return mPrice; } }
/* * JAHM - Java Advanced Hierarchical Model * * ValidateAction.java * * Copyright 2009 Robert Arvin Dunnagan * * 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.xmodel.xaction; import java.util.ArrayList; import java.util.List; import org.xmodel.IModelObject; import org.xmodel.IModelObjectFactory; import org.xmodel.xpath.expression.IContext; import org.xmodel.xpath.expression.IExpression; import org.xmodel.xpath.variable.IVariableScope; import org.xmodel.xsd.Schema; import org.xmodel.xsd.check.SchemaError; /** * An action which validates an element against its simplified schema. */ public class ValidateAction extends GuardedAction { /* (non-Javadoc) * @see org.xmodel.ui.swt.form.actions.GuardedAction#configure(org.xmodel.ui.model.ViewModel) */ @Override public void configure( XActionDocument document) { super.configure( document); IModelObject config = document.getRoot(); factory = Conventions.getFactory( config); var = Conventions.getVarName( config, true, "assign"); sourceExpr = document.getExpression( "source", false); schemaRootExpr = document.getExpression( "schema", false); } /* (non-Javadoc) * @see org.xmodel.ui.swt.form.actions.GuardedAction#doAction(org.xmodel.xpath.expression.IContext) */ @Override protected Object[] doAction( IContext context) { IModelObject schemaRoot = schemaRootExpr.queryFirst( context); if ( schemaRoot == null) throw new IllegalArgumentException( "Schema root is null in ValidateAction: "+this); List<IModelObject> result = new ArrayList<IModelObject>(); for( IModelObject document: sourceExpr.query( context, null)) { List<SchemaError> errors = Schema.validate( schemaRoot, document, false); if ( errors != null) for( SchemaError error: errors) { IModelObject element = factory.createObject( null, "error"); element.setValue( error.toString()); } } IVariableScope scope = context.getScope(); if ( scope == null) throw new IllegalArgumentException( "Action executed in scope which does not support variable assignment: "+this); scope.set( var, result); return null; } private IModelObjectFactory factory; private String var; private IExpression sourceExpr; private IExpression schemaRootExpr; }
package org.intermine.api.query; /* * Copyright (C) 2002-2014 FlyMine * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. See the LICENSE file for more * information or http://www.gnu.org/copyleft/lesser.html. * */ import org.intermine.objectstore.query.Constraint; import org.intermine.objectstore.query.QueryNode; import org.intermine.objectstore.query.Queryable; import org.intermine.pathquery.PathConstraintRange; /** * * @author Alex * */ public interface RangeHelper { /** * * @param q field to constrain * @param node class to constrain * @param con constraint * @return range constraint */ Constraint createConstraint(Queryable q, QueryNode node, PathConstraintRange con); }
import java.awt.BorderLayout; import javax.swing.DefaultListSelectionModel; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.ListSelectionModel; import javax.swing.table.DefaultTableColumnModel; import javax.swing.table.TableColumn; import javax.swing.table.TableColumnModel; public class Main { public static void main(String args[]) { Object rows[][] = { { "one", "ichi" }, { "two", "ni" }, { "three", "san" }, { "four", "shi" }, { "five", "go" }, { "six", "roku" }, { "seven", "shichi" }, { "eight", "hachi" }, { "nine", "kyu" }, { "ten", "ju" } }; Object headers[] = { "English", "Japanese" }; String title = (args.length == 0 ? "JTable Sample" : args[0]); JFrame frame = new JFrame(title); TableColumnModel columnModel = new DefaultTableColumnModel(); TableColumn firstColumn = new TableColumn(1); firstColumn.setHeaderValue(headers[1]); columnModel.addColumn(firstColumn); TableColumn secondColumn = new TableColumn(0); secondColumn.setHeaderValue(headers[0]); columnModel.addColumn(secondColumn); ListSelectionModel selectionModel = new DefaultListSelectionModel(); selectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // JTable table = new JTable(model, columnModel, selectionModel); JTable table = new JTable(rows, headers); JScrollPane scrollPane = new JScrollPane(table); frame.getContentPane().add(scrollPane, BorderLayout.CENTER); frame.setSize(300, 150); frame.setVisible(true); } }
/* * The MIT License (MIT) * * Copyright (c) 2014 daimajia * Modifications Copyright(C) 2016 Fred Grott(GrottWorkShop) * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.github.shareme.greenandroid.viewanim.bouncing_entrances; import android.animation.ObjectAnimator; import android.view.View; import com.github.shareme.greenandroid.viewanim.BaseViewAnimator; @SuppressWarnings("unused") public class BounceInRightAnimator extends BaseViewAnimator { @Override public void prepare(View target) { getAnimatorAgent().playTogether( ObjectAnimator.ofFloat(target,"translationX",target.getMeasuredWidth()+target.getWidth(),-30,10,0), ObjectAnimator.ofFloat(target,"alpha",0,1,1,1) ); } }
package com.yunbao.video.interfaces; import com.yunbao.video.adapter.MusicAdapter; import com.yunbao.video.bean.MusicBean; /** * Created by cxf on 2018/12/7. */ public interface VideoMusicActionListener { void onPlayMusic(MusicAdapter adapter, MusicBean bean, int position); void onStopMusic(); void onUseClick(MusicBean bean); void onCollect(MusicAdapter adapter, int musicId, int isCollect); }
package com.xtoon.boot.infrastructure.persistence.mybatis.repository.impl; import com.xtoon.boot.domain.repository.UserRepository; import org.junit.jupiter.api.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; /** * 用户Repository测试类 * * @author haoxin * @date 2021-02-13 **/ @RunWith(SpringRunner.class) @SpringBootTest class UserRepositoryImplTest { private Logger logger = LoggerFactory.getLogger(getClass()); @Autowired private UserRepository userRepository; @Test void getUserPermissions() { } }
package invtweaks; import cpw.mods.fml.common.Loader; import invtweaks.api.IItemTree; import invtweaks.api.IItemTreeItem; import invtweaks.api.SortingMethod; import invtweaks.api.container.ContainerSection; import invtweaks.forge.InvTweaksMod; import net.minecraft.client.Minecraft; import net.minecraft.client.audio.PositionedSoundRecord; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.gui.inventory.GuiContainer; import net.minecraft.enchantment.EnchantmentHelper; import net.minecraft.init.Items; import net.minecraft.inventory.Container; import net.minecraft.inventory.Slot; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.util.ResourceLocation; import net.minecraft.util.StatCollector; import org.apache.commons.lang3.ObjectUtils; import org.apache.logging.log4j.Logger; import org.lwjgl.LWJGLException; import org.lwjgl.input.Keyboard; import org.lwjgl.input.Mouse; import org.lwjgl.opengl.Display; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.*; import java.util.concurrent.TimeoutException; import java.util.logging.Level; /** * Main class for Inventory Tweaks, which maintains various hooks and dispatches the events to the correct handlers. * * @author Jimeo Wan * <p/> * Contact: jimeo.wan (at) gmail (dot) com Website: <a href="https://inventory-tweaks.readthedocs.org/">https://inventory-tweaks.readthedocs.org/</a> * Source code: <a href="https://github.com/kobata/inventory-tweaks">GitHub</a> License: MIT */ public class InvTweaks extends InvTweaksObfuscation { public static Logger log; private static InvTweaks instance; /** * The configuration loader. */ private InvTweaksConfigManager cfgManager = null; /** * Attributes to remember the status of chest sorting while using middle clicks. */ private SortingMethod chestAlgorithm = SortingMethod.DEFAULT; private long chestAlgorithmClickTimestamp = 0; private boolean chestAlgorithmButtonDown = false; /** * Various information concerning the context, stored on each tick to allow for certain features (auto-refill, * sorting on pick up...) */ private String storedStackId = null; private int storedStackDamage = InvTweaksConst.DAMAGE_WILDCARD, storedFocusedSlot = -1; private ItemStack[] hotbarClone = new ItemStack[InvTweaksConst.INVENTORY_HOTBAR_SIZE]; private boolean hadFocus = true, mouseWasDown = false; private boolean wasInGUI = false; /** * Allows to trigger some logic only every Const.POLLING_DELAY. */ private int tickNumber = 0, lastPollingTickNumber = -InvTweaksConst.POLLING_DELAY; /** * Stores when the sorting key was last pressed (allows to detect long key holding) */ private long sortingKeyPressedDate = 0; private boolean sortKeyDown = false; private boolean sortKeyEnabled = true; private boolean textboxMode = false; private boolean itemPickupPending = false; private int itemPickupTimeout = 0; private boolean isNEILoaded; private PriorityQueue<TickScheduledTask> scheduledTasks = new PriorityQueue<TickScheduledTask>(16, new TickScheduledTask.TaskComparator()); /** * Creates an instance of the mod, and loads the configuration from the files, creating them if necessary. * * @param mc */ public InvTweaks(Minecraft mc) { super(mc); //log.setLevel(InvTweaksConst.DEFAULT_LOG_LEVEL); // Store instance instance = this; isNEILoaded = Loader.isModLoaded("NotEnoughItems"); // Load config files cfgManager = new InvTweaksConfigManager(mc); if(cfgManager.makeSureConfigurationIsLoaded()) { log.info("Mod initialized"); } else { log.error("Mod failed to initialize!"); } } public void addScheduledTask(TickScheduledTask task) { scheduledTasks.add(task); } public void addScheduledTask(long time, final Runnable task) { scheduledTasks.add(new TickScheduledTask(time) { @Override void run() { task.run(); } }); } /** * To be called on each tick during the game (except when in a menu). Handles the auto-refill. */ public void onTickInGame() { synchronized(this) { if(!onTick()) { return; } handleAutoRefill(); if(wasInGUI) { wasInGUI = false; textboxMode = false; } } } /** * To be called on each tick when a menu is open. Handles the GUI additions and the middle clicking. * * @param guiScreen */ public void onTickInGUI(GuiScreen guiScreen) { synchronized(this) { handleMiddleClick(guiScreen); // Called before the rest to be able to trigger config reload if(!onTick()) { return; } if(isTimeForPolling()) { unlockKeysIfNecessary(); } if(guiScreen instanceof GuiContainer) { handleGUILayout((GuiContainer) guiScreen); } if(!wasInGUI) { // Right-click is always true on initial open of GUI. // Ignore it to prevent erroneous trigger of shortcuts. mouseWasDown = true; log.info(guiScreen.getClass().getName()); if(guiScreen instanceof GuiContainer) { log.info(((GuiContainer) guiScreen).inventorySlots.getClass().getName()); } } if(guiScreen instanceof GuiContainer) { handleShortcuts((GuiContainer) guiScreen); } // Copy some info about current selected stack for auto-refill ItemStack currentStack = getFocusedStack(); storedStackId = (currentStack == null) ? null : Item.itemRegistry.getNameForObject(currentStack.getItem()); storedStackDamage = (currentStack == null) ? 0 : currentStack.getItemDamage(); if(!wasInGUI) { wasInGUI = true; } } } /** * To be called every time the sorting key is pressed. Sorts the inventory. */ public final void onSortingKeyPressed() { synchronized(this) { // Check config loading success if(!cfgManager.makeSureConfigurationIsLoaded()) { return; } // Check current GUI GuiScreen guiScreen = getCurrentScreen(); if(guiScreen == null || (guiScreen instanceof GuiContainer && (isValidChest( ((GuiContainer) guiScreen).inventorySlots) || isValidInventory( ((GuiContainer) guiScreen).inventorySlots)))) { // Sorting! handleSorting(guiScreen); } } } /** * To be called everytime a stack has been picked up. Moves the picked up item in another slot that matches best the * current configuration. */ public void onItemPickup() { if(!cfgManager.makeSureConfigurationIsLoaded()) { return; } InvTweaksConfig config = cfgManager.getConfig(); // Handle option to disable this feature if(cfgManager.getConfig().getProperty(InvTweaksConfig.PROP_ENABLE_SORTING_ON_PICKUP).equals("false")) { itemPickupPending = false; return; } try { InvTweaksContainerSectionManager containerMgr = new InvTweaksContainerSectionManager(mc, ContainerSection.INVENTORY); // Find stack slot (look in hotbar only). // We're looking for a brand new stack in the hotbar // (not an existing stack whose amount has been increased) int currentSlot = -1; for(int i = 0; i < InvTweaksConst.INVENTORY_HOTBAR_SIZE; i++) { ItemStack currentHotbarStack = containerMgr.getItemStack(i + 27); // Don't move already started stacks if(currentHotbarStack != null && currentHotbarStack.animationsToGo > 0 && hotbarClone[i] == null) { currentSlot = i + 27; } } if(currentSlot != -1) { itemPickupPending = false; // Find preffered slots List<Integer> prefferedPositions = new LinkedList<Integer>(); IItemTree tree = config.getTree(); ItemStack stack = containerMgr.getItemStack(currentSlot); List<IItemTreeItem> items = tree.getItems(Item.itemRegistry.getNameForObject(stack.getItem()), stack.getItemDamage()); for(InvTweaksConfigSortingRule rule : config.getRules()) { if(tree.matches(items, rule.getKeyword())) { for(int slot : rule.getPreferredSlots()) { prefferedPositions.add(slot); } } } // Find best slot for stack boolean hasToBeMoved = true; for(int newSlot : prefferedPositions) { // Already in the best slot! if(newSlot == currentSlot) { hasToBeMoved = false; break; } // Is the slot available? else if(containerMgr.getItemStack(newSlot) == null) { // TODO: Check rule level before to move if(containerMgr.move(currentSlot, newSlot)) { break; } } } // Else, put the slot anywhere if(hasToBeMoved) { for(int i = 0; i < containerMgr.getSize(); i++) { if(containerMgr.getItemStack(i) == null) { if(containerMgr.move(currentSlot, i)) { break; } } } } // Sync after pickup movements. InvTweaksMod.proxy.sortComplete(); } else { if(--itemPickupTimeout == 0) { itemPickupPending = false; } } } catch(Exception e) { logInGameError("Failed to move picked up stack", e); itemPickupPending = false; } } public int compareItems(ItemStack i, ItemStack j) { return compareItems(i, j, getItemOrder(i), getItemOrder(j)); } int compareItems(ItemStack i, ItemStack j, int orderI, int orderJ) { if(j == null) { return -1; } else if(i == null || orderI == -1) { return 1; } else { if(orderI == orderJ) { // Items of same keyword orders can have different IDs, // in the case of categories defined by a range of IDs if(i.getItem() == j.getItem()) { boolean iHasName = i.hasDisplayName(); boolean jHasName = j.hasDisplayName(); if(iHasName || jHasName) { if(!iHasName) { return -1; } else if(!jHasName) { return 1; } else { String iDisplayName = i.getDisplayName(); String jDisplayName = j.getDisplayName(); if(!iDisplayName.equals(jDisplayName)) { return iDisplayName.compareTo(jDisplayName); } } } @SuppressWarnings("unchecked") Map<Integer, Integer> iEnchs = EnchantmentHelper.getEnchantments(i); @SuppressWarnings("unchecked") Map<Integer, Integer> jEnchs = EnchantmentHelper.getEnchantments(j); if(iEnchs.size() == jEnchs.size()) { int iEnchMaxId = 0, iEnchMaxLvl = 0; int jEnchMaxId = 0, jEnchMaxLvl = 0; for(Map.Entry<Integer, Integer> ench : iEnchs.entrySet()) { if(ench.getValue() > iEnchMaxLvl) { iEnchMaxId = ench.getKey(); iEnchMaxLvl = ench.getValue(); } else if(ench.getValue() == iEnchMaxLvl && ench.getKey() > iEnchMaxId) { iEnchMaxId = ench.getKey(); } } for(Map.Entry<Integer, Integer> ench : jEnchs.entrySet()) { if(ench.getValue() > jEnchMaxLvl) { jEnchMaxId = ench.getKey(); jEnchMaxLvl = ench.getValue(); } else if(ench.getValue() == jEnchMaxLvl && ench.getKey() > jEnchMaxId) { jEnchMaxId = ench.getKey(); } } if(iEnchMaxId == jEnchMaxId) { if(iEnchMaxLvl == jEnchMaxLvl) { if(i.getItemDamage() != j.getItemDamage()) { if(i.isItemStackDamageable()) { return j.getItemDamage() - i.getItemDamage(); } else { return i.getItemDamage() - j.getItemDamage(); } } else { return j.stackSize - i.stackSize; } } else { return jEnchMaxLvl - iEnchMaxLvl; } } else { return jEnchMaxId - iEnchMaxId; } } else { return jEnchs.size() - iEnchs.size(); } } else { return ObjectUtils.compare(Item.itemRegistry.getNameForObject(i.getItem()), Item.itemRegistry.getNameForObject(j.getItem())); } } else { return orderI - orderJ; } } } public void setItemPickupPending(boolean itemPickupPending) { this.itemPickupPending = itemPickupPending; itemPickupTimeout = 5; } public void setSortKeyEnabled(boolean enabled) { sortKeyEnabled = enabled; } public void setTextboxMode(boolean enabled) { textboxMode = enabled; } public void logInGame(String message) { logInGame(message, false); } private List<String> queuedMessages = new ArrayList<String>(); public void printQueuedMessages() { if(mc.ingameGUI != null && !queuedMessages.isEmpty()) { for(String s : queuedMessages) { addChatMessage(s); } queuedMessages.clear(); } } public void logInGame(String message, boolean alreadyTranslated) { String formattedMsg = buildlogString(Level.INFO, (alreadyTranslated) ? message : StatCollector.translateToLocal(message)); if(mc.ingameGUI == null) { queuedMessages.add(formattedMsg); } else { addChatMessage(formattedMsg); } log.info(formattedMsg); } public void logInGameError(String message, Exception e) { e.printStackTrace(); String formattedMsg = buildlogString(Level.SEVERE, StatCollector.translateToLocal(message), e); if(mc.ingameGUI == null) { queuedMessages.add(formattedMsg); } else { addChatMessage(formattedMsg); } } public static void logInGameStatic(String message) { InvTweaks.getInstance().logInGame(message); } public static void logInGameErrorStatic(String message, Exception e) { InvTweaks.getInstance().logInGameError(message, e); } /** * @return InvTweaks instance */ public static InvTweaks getInstance() { return instance; } public static Minecraft getMinecraftInstance() { return instance.mc; } public static InvTweaksConfigManager getConfigManager() { return instance.cfgManager; } public static boolean classExists(String className) { try { return Class.forName(className) != null; } catch(ClassNotFoundException e) { return false; } } private boolean onTick() { printQueuedMessages(); tickNumber++; // Not calling "cfgManager.makeSureConfigurationIsLoaded()" for performance reasons InvTweaksConfig config = cfgManager.getConfig(); if(config == null) { return false; } while(!scheduledTasks.isEmpty() && (scheduledTasks.peek().getScheduledTickTime() <= mc.theWorld.getTotalWorldTime())) { scheduledTasks.poll().run(); } // Clone the hotbar to be able to monitor changes on it if(itemPickupPending) { onItemPickup(); } GuiScreen currentScreen = getCurrentScreen(); if(currentScreen == null || isGuiInventory(currentScreen)) { cloneHotbar(); } // Handle sort key if(isSortingShortcutDown()) { if(!sortKeyDown) { sortKeyDown = true; onSortingKeyPressed(); } } else { sortKeyDown = false; } // Handle config switch handleConfigSwitch(); return true; } private void handleConfigSwitch() { InvTweaksConfig config = cfgManager.getConfig(); GuiScreen currentScreen = getCurrentScreen(); // Switch between configurations (shortcut) cfgManager.getShortcutsHandler().updatePressedKeys(); InvTweaksShortcutMapping switchMapping = cfgManager.getShortcutsHandler().isShortcutDown( InvTweaksShortcutType.MOVE_TO_SPECIFIC_HOTBAR_SLOT); if(isSortingShortcutDown() && switchMapping != null) { String newRuleset = null; int pressedKey = switchMapping.getKeyCodes().get(0); if(pressedKey >= Keyboard.KEY_1 && pressedKey <= Keyboard.KEY_9) { newRuleset = config.switchConfig(pressedKey - Keyboard.KEY_1); } else { switch(pressedKey) { case Keyboard.KEY_NUMPAD1: newRuleset = config.switchConfig(0); break; case Keyboard.KEY_NUMPAD2: newRuleset = config.switchConfig(1); break; case Keyboard.KEY_NUMPAD3: newRuleset = config.switchConfig(2); break; case Keyboard.KEY_NUMPAD4: newRuleset = config.switchConfig(3); break; case Keyboard.KEY_NUMPAD5: newRuleset = config.switchConfig(4); break; case Keyboard.KEY_NUMPAD6: newRuleset = config.switchConfig(5); break; case Keyboard.KEY_NUMPAD7: newRuleset = config.switchConfig(6); break; case Keyboard.KEY_NUMPAD8: newRuleset = config.switchConfig(7); break; case Keyboard.KEY_NUMPAD9: newRuleset = config.switchConfig(8); break; } } if(newRuleset != null) { logInGame(String.format(StatCollector.translateToLocal("invtweaks.loadconfig.enabled"), newRuleset), true); // Hack to prevent 2nd way to switch configs from being enabled sortingKeyPressedDate = Integer.MAX_VALUE; } } // Switch between configurations (by holding the sorting key) if(isSortingShortcutDown()) { long currentTime = System.currentTimeMillis(); if(sortingKeyPressedDate == 0) { sortingKeyPressedDate = currentTime; } else if(currentTime - sortingKeyPressedDate > InvTweaksConst.RULESET_SWAP_DELAY && sortingKeyPressedDate != Integer.MAX_VALUE) { String previousRuleset = config.getCurrentRulesetName(); String newRuleset = config.switchConfig(); // Log only if there is more than 1 ruleset if(previousRuleset != null && newRuleset != null && !previousRuleset.equals(newRuleset)) { logInGame(String.format(StatCollector.translateToLocal("invtweaks.loadconfig.enabled"), newRuleset), true); handleSorting(currentScreen); } sortingKeyPressedDate = currentTime; } } else { sortingKeyPressedDate = 0; } } private void handleSorting(GuiScreen guiScreen) { ItemStack selectedItem = null; int focusedSlot = getFocusedSlot(); ItemStack[] mainInventory = getMainInventory(); if(focusedSlot < mainInventory.length && focusedSlot >= 0) { selectedItem = mainInventory[focusedSlot]; } // Sorting try { new InvTweaksHandlerSorting(mc, cfgManager.getConfig(), ContainerSection.INVENTORY, SortingMethod.INVENTORY, InvTweaksConst.INVENTORY_ROW_SIZE) .sort(); } catch(Exception e) { logInGameError("invtweaks.sort.inventory.error", e); e.printStackTrace(); } playClick(); // This needs to be remembered so that the // auto-refill feature doesn't trigger if(selectedItem != null && mainInventory[focusedSlot] == null) { storedStackId = null; } } private void handleAutoRefill() { ItemStack currentStack = getFocusedStack(); String currentStackId = (currentStack == null) ? null : Item.itemRegistry.getNameForObject( currentStack.getItem()); int currentStackDamage = (currentStack == null) ? 0 : currentStack.getItemDamage(); int focusedSlot = getFocusedSlot() + 27; // Convert to container slots index InvTweaksConfig config = cfgManager.getConfig(); if(!ObjectUtils.equals(currentStackId, storedStackId) || currentStackDamage != storedStackDamage) { if(storedFocusedSlot != focusedSlot) { // Filter selection change storedFocusedSlot = focusedSlot; } else if((currentStack == null || currentStack.getItem() == Items.bowl && ObjectUtils.equals(storedStackId, "mushroom_stew")) // Handle eaten mushroom soup && (getCurrentScreen() == null || // Filter open inventory or other window isGuiEditSign( getCurrentScreen()))) { // TODO: This should be more expandable on 'equivalent' items (API?) and allowed GUIs if(config.isAutoRefillEnabled(storedStackId, storedStackDamage)) { try { cfgManager.getAutoRefillHandler().autoRefillSlot(focusedSlot, storedStackId, storedStackDamage); } catch(Exception e) { logInGameError("invtweaks.sort.autorefill.error", e); } } } else { // Item int itemMaxDamage = currentStack.getMaxDamage(); int autoRefillThreshhold = config.getIntProperty(InvTweaksConfig.PROP_AUTO_REFILL_DAMAGE_THRESHHOLD); if(canToolBeReplaced(currentStackDamage, itemMaxDamage, autoRefillThreshhold) && config .getProperty(InvTweaksConfig.PROP_AUTO_REFILL_BEFORE_BREAK) .equals(InvTweaksConfig.VALUE_TRUE) && config .isAutoRefillEnabled(storedStackId, storedStackDamage)) { // Trigger auto-refill before the tool breaks try { cfgManager.getAutoRefillHandler().autoRefillSlot(focusedSlot, storedStackId, storedStackDamage); } catch(Exception e) { logInGameError("invtweaks.sort.autorefill.error", e); } } } } // Copy some info about current selected stack for auto-refill storedStackId = currentStackId; storedStackDamage = currentStackDamage; } private boolean canToolBeReplaced(int currentStackDamage, int itemMaxDamage, int autoRefillThreshhold) { return itemMaxDamage != 0 && itemMaxDamage - currentStackDamage < autoRefillThreshhold && itemMaxDamage - storedStackDamage >= autoRefillThreshhold; } private void handleMiddleClick(GuiScreen guiScreen) { if(Mouse.isButtonDown(2)) { if(!cfgManager.makeSureConfigurationIsLoaded()) { return; } InvTweaksConfig config = cfgManager.getConfig(); // Check that middle click sorting is allowed if(config.getProperty(InvTweaksConfig.PROP_ENABLE_MIDDLE_CLICK) .equals(InvTweaksConfig.VALUE_TRUE) && guiScreen instanceof GuiContainer) { GuiContainer guiContainer = (GuiContainer) guiScreen; Container container = guiContainer.inventorySlots; if(!chestAlgorithmButtonDown) { chestAlgorithmButtonDown = true; InvTweaksContainerManager containerMgr = new InvTweaksContainerManager(mc); Slot slotAtMousePosition = InvTweaksObfuscation .getSlotAtMousePosition((GuiContainer) getCurrentScreen()); ContainerSection target = null; if(slotAtMousePosition != null) { target = containerMgr.getSlotSection(getSlotNumber(slotAtMousePosition)); } if(isValidChest(container)) { // Check if the middle click target the chest or the inventory // (copied GuiContainer.getSlotAtPosition algorithm) if(ContainerSection.CHEST.equals(target)) { // Play click playClick(); long timestamp = System.currentTimeMillis(); if(timestamp - chestAlgorithmClickTimestamp > InvTweaksConst.CHEST_ALGORITHM_SWAP_MAX_INTERVAL) { chestAlgorithm = SortingMethod.DEFAULT; } try { new InvTweaksHandlerSorting(mc, cfgManager.getConfig(), ContainerSection.CHEST, chestAlgorithm, getContainerRowSize(guiContainer)).sort(); } catch(Exception e) { logInGameError("invtweaks.sort.chest.error", e); e.printStackTrace(); } // TODO: Better replacement for this. chestAlgorithm = SortingMethod.values()[(chestAlgorithm.ordinal() + 1) % 3]; chestAlgorithmClickTimestamp = timestamp; } else if(ContainerSection.CRAFTING_IN.equals(target) || ContainerSection.CRAFTING_IN_PERSISTENT .equals(target)) { try { new InvTweaksHandlerSorting(mc, cfgManager.getConfig(), target, SortingMethod.EVEN_STACKS, (containerMgr.getSize(target) == 9) ? 3 : 2).sort(); } catch(Exception e) { logInGameError("invtweaks.sort.crafting.error", e); e.printStackTrace(); } } else if(ContainerSection.INVENTORY_HOTBAR.equals(target) || (ContainerSection .INVENTORY_NOT_HOTBAR.equals(target))) { handleSorting(guiScreen); } } else if(isValidInventory(container)) { if(ContainerSection.CRAFTING_IN.equals(target) || ContainerSection.CRAFTING_IN_PERSISTENT .equals(target)) { // Crafting stacks evening try { new InvTweaksHandlerSorting(mc, cfgManager.getConfig(), target, SortingMethod.EVEN_STACKS, (containerMgr.getSize(target) == 9) ? 3 : 2).sort(); } catch(Exception e) { logInGameError("invtweaks.sort.crafting.error", e); e.printStackTrace(); } } else { // Sorting handleSorting(guiScreen); } } } } } else { chestAlgorithmButtonDown = false; } } private boolean wasNEIEnabled = false; private void handleGUILayout(GuiContainer guiContainer) { InvTweaksConfig config = cfgManager.getConfig(); Container container = guiContainer.inventorySlots; boolean isValidChest = isValidChest(container); if(showButtons(container) && !isGuiEnchantmentTable(guiContainer)) { int w = 10, h = 10; // Re-layout when NEI changes states. final boolean isNEIEnabled = isNotEnoughItemsEnabled(); boolean relayout = wasNEIEnabled != isNEIEnabled; wasNEIEnabled = isNEIEnabled; // Look for the mods buttons boolean customButtonsAdded = false; @SuppressWarnings("unchecked") List<Object> controlList = guiContainer.buttonList; @SuppressWarnings("unchecked") List<Object> toRemove = new ArrayList<Object>(); for(Object o : controlList) { if(isGuiButton(o)) { GuiButton button = (GuiButton) o; if(button.id>= InvTweaksConst.JIMEOWAN_ID && button.id < (InvTweaksConst.JIMEOWAN_ID + 4)) { if(relayout) { toRemove.add(button); } else { customButtonsAdded = true; break; } } } } controlList.removeAll(toRemove); guiContainer.buttonList = controlList; if(!customButtonsAdded) { // Check for custom button texture boolean customTextureAvailable = hasTexture( new ResourceLocation("inventorytweaks", "textures/gui/button10px.png")); // Inventory button if(!isValidChest) { controlList.add(new InvTweaksGuiSettingsButton(cfgManager, InvTweaksConst.JIMEOWAN_ID, guiContainer.guiLeft + guiContainer.xSize - 15, guiContainer.guiTop + 5, w, h, "...", StatCollector.translateToLocal( "invtweaks.button.settings.tooltip"), customTextureAvailable)); } // Chest buttons else { // Reset sorting algorithm selector chestAlgorithmClickTimestamp = 0; int id = InvTweaksConst.JIMEOWAN_ID, x = guiContainer.guiLeft + guiContainer.xSize - 16, y = guiContainer.guiTop + 5; boolean isChestWayTooBig = isLargeChest(guiContainer.inventorySlots); // NotEnoughItems compatibility if(isChestWayTooBig && isNEIEnabled) { x = guiContainer.guiLeft + guiContainer.xSize - 35; y += 50; } // Settings button controlList .add(new InvTweaksGuiSettingsButton(cfgManager, id++, (isChestWayTooBig) ? x + 22 : x - 1, (isChestWayTooBig) ? y - 3 : y, w, h, "...", StatCollector.translateToLocal( "invtweaks.button.settings.tooltip"), customTextureAvailable)); // Sorting buttons if(!config.getProperty(InvTweaksConfig.PROP_SHOW_CHEST_BUTTONS).equals("false")) { int rowSize = getContainerRowSize(guiContainer); GuiButton button = new InvTweaksGuiSortingButton(cfgManager, id++, (isChestWayTooBig) ? x + 22 : x - 13, (isChestWayTooBig) ? y + 12 : y, w, h, "h", StatCollector.translateToLocal( "invtweaks.button.chest3.tooltip"), SortingMethod.HORIZONTAL, rowSize, customTextureAvailable); controlList.add(button); button = new InvTweaksGuiSortingButton(cfgManager, id++, (isChestWayTooBig) ? x + 22 : x - 25, (isChestWayTooBig) ? y + 25 : y, w, h, "v", StatCollector .translateToLocal("invtweaks.button.chest2.tooltip"), SortingMethod.VERTICAL, rowSize, customTextureAvailable); controlList.add(button); button = new InvTweaksGuiSortingButton(cfgManager, id++, (isChestWayTooBig) ? x + 22 : x - 37, (isChestWayTooBig) ? y + 38 : y, w, h, "s", StatCollector .translateToLocal("invtweaks.button.chest1.tooltip"), SortingMethod.DEFAULT, rowSize, customTextureAvailable); controlList.add(button); } } } } else { // Remove "..." button from non-survival tabs of the creative screen if(isGuiInventoryCreative(guiContainer)) { @SuppressWarnings("unchecked") List<Object> controlList = guiContainer.buttonList; GuiButton buttonToRemove = null; for(Object o : controlList) { if(isGuiButton(o)) { // GuiButton if(((GuiButton) o).id == InvTweaksConst.JIMEOWAN_ID) { buttonToRemove = (GuiButton) o; break; } } } if(buttonToRemove != null) { controlList.remove(buttonToRemove); } } } } private Class neiClientConfig; private Method neiHidden; @SuppressWarnings("unchecked") private boolean isNotEnoughItemsEnabled() { if(isNEILoaded) { if(neiHidden == null) { try { neiClientConfig = Class.forName("codechicken.nei.NEIClientConfig"); neiHidden = neiClientConfig.getMethod("isHidden"); } catch(ClassNotFoundException e) { return false; } catch(NoSuchMethodException e) { return false; } } try { return !(Boolean) neiHidden.invoke(null); } catch(IllegalAccessException e) { return false; } catch(InvocationTargetException e) { return false; } } else { return false; } } private void handleShortcuts(GuiContainer guiScreen) { // Check open GUI if(!(isValidChest(guiScreen.inventorySlots) || isValidInventory(guiScreen.inventorySlots))) { return; } // Configurable shortcuts if(Mouse.isButtonDown(0) || Mouse.isButtonDown(1)) { if(!mouseWasDown) { mouseWasDown = true; // The mouse has just been clicked, // trigger a shortcut according to the pressed keys. if(cfgManager.getConfig().getProperty(InvTweaksConfig.PROP_ENABLE_SHORTCUTS).equals("true")) { cfgManager.getShortcutsHandler().handleShortcut(); } } } else { mouseWasDown = false; } } private int getItemOrder(ItemStack itemStack) { List<IItemTreeItem> items = cfgManager.getConfig().getTree().getItems(Item.itemRegistry.getNameForObject(itemStack.getItem()), itemStack.getItemDamage()); return (items != null && items.size() > 0) ? items.get(0).getOrder() : Integer.MAX_VALUE; } private int getContainerRowSize(GuiContainer guiContainer) { return getSpecialChestRowSize(guiContainer.inventorySlots); } private boolean isSortingShortcutDown() { if(sortKeyEnabled && !textboxMode) { int keyCode = cfgManager.getConfig().getSortKeyCode(); if(keyCode > 0) { return Keyboard.isKeyDown(keyCode); } else { return Mouse.isButtonDown(100 + keyCode); } } else { return false; } } private boolean isTimeForPolling() { if(tickNumber - lastPollingTickNumber >= InvTweaksConst.POLLING_DELAY) { lastPollingTickNumber = tickNumber; } return tickNumber - lastPollingTickNumber == 0; } /** * When Minecraft gains focus, reset all pressed keys to avoid the "stuck keys" bug. */ private void unlockKeysIfNecessary() { boolean hasFocus = Display.isActive(); if(!hadFocus && hasFocus) { Keyboard.destroy(); boolean firstTry = true; while(!Keyboard.isCreated()) { try { Keyboard.create(); } catch(LWJGLException e) { if(firstTry) { logInGameError("invtweaks.keyboardfix.error", e); firstTry = false; } } } if(!firstTry) { logInGame("invtweaks.keyboardfix.recover"); } } hadFocus = hasFocus; } /** * Allows to maintain a clone of the hotbar contents to track changes (especially needed by the "on pickup" * features). */ private void cloneHotbar() { ItemStack[] mainInventory = getMainInventory(); for(int i = 0; i < 9; i++) { if(mainInventory[i] != null) { hotbarClone[i] = mainInventory[i].copy(); } else { hotbarClone[i] = null; } } } private void playClick() { if(!cfgManager.getConfig().getProperty(InvTweaksConfig.PROP_ENABLE_SOUNDS) .equals(InvTweaksConfig.VALUE_FALSE)) { mc.getSoundHandler() .playSound(PositionedSoundRecord.func_147674_a(new ResourceLocation("gui.button.press"), 1.0F)); } } private String buildlogString(Level level, String message, Exception e) { if(e != null) { StackTraceElement exceptionLine = e.getStackTrace()[0]; if(exceptionLine != null && exceptionLine.getFileName() != null) { return buildlogString(level, message) + ": " + e.getMessage() + " (l" + exceptionLine.getLineNumber() + " in " + exceptionLine.getFileName().replace("InvTweaks", "") + ")"; } else { return buildlogString(level, message) + ": " + e.getMessage(); } } else { return buildlogString(level, message); } } private String buildlogString(Level level, String message) { return InvTweaksConst.INGAME_LOG_PREFIX + ((level.equals(Level.SEVERE)) ? "[ERROR] " : "") + message; } }
/* * @(#)file RmiConnectorServerObject.java * @(#)author Sun Microsystems, Inc. * @(#)version 1.18 * @(#)date 07/10/01 * * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright (c) 2007 Sun Microsystems, Inc. All Rights Reserved. * * The contents of this file are subject to the terms of either the GNU General * Public License Version 2 only ("GPL") or the Common Development and * Distribution License("CDDL")(collectively, the "License"). You may not use * this file except in compliance with the License. You can obtain a copy of the * License at http://opendmk.dev.java.net/legal_notices/licenses.txt or in the * LEGAL_NOTICES folder that accompanied this code. See the License for the * specific language governing permissions and limitations under the License. * * When distributing the software, include this License Header Notice in each * file and include the License file found at * http://opendmk.dev.java.net/legal_notices/licenses.txt * or in the LEGAL_NOTICES folder that accompanied this code. * Sun designates this particular file as subject to the "Classpath" exception * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. * * If applicable, add the following below the License Header, with the fields * enclosed by brackets [] replaced by your own identifying information: * * "Portions Copyrighted [year] [name of copyright owner]" * * Contributor(s): * * If you wish your version of this file to be governed by only the CDDL or * only the GPL Version 2, indicate your decision by adding * * "[Contributor] elects to include this software in this distribution * under the [CDDL or GPL Version 2] license." * * If you don't indicate a single choice of license, a recipient has the option * to distribute your version of this file under either the CDDL or the GPL * Version 2, or to extend the choice of license to its licensees as provided * above. However, if you add GPL Version 2 code and therefore, elected the * GPL Version 2 license, then the option applies only if the new code is made * subject to such option by the copyright holder. * * */ package com.sun.jdmk.comm; // java import // import java.rmi.Remote; import java.rmi.RemoteException; // jmx import // import javax.management.*; /** * The <CODE>RmiConnectorServerObject</CODE> interface defines the remote * method invocation (RMI) interface to be used by the RMI implementation of * {@link com.sun.jdmk.comm.RemoteMBeanServer} class. * */ interface RmiConnectorServerObject extends Remote { /** * --------------------------------------------------------- * MBean creation and registration operations * --------------------------------------------------------- */ /** * Creates an registers an instance of an MBean in the remote object server. When * calling the method, you have to provide the class name of the Java * implementation to be used for instantiating the new object. It * returns an ObjectInstance representing the remote MBean created. * * @param className The name of the Java class to be used by the MBeanServer for creating the MBean. * * @param name The name of the MBean to be created. * * @return An ObjectInstance representing the newly created MBean. * * @exception ReflectionException Wraps the java.lang.Exception that occurred trying to invoke the MBean's * constructor. * @exception RemoteException See java.rmi.RemoteException. * @exception InstanceAlreadyExistsException * @exception MBeanRegistrationException The preRegister (MBeanRegistration interface) method of the MBean * has thrown an exception. The MBean will not be registered. * @exception MBeanException Wraps an exception thrown by the MBean's constructor. * @exception NotCompliantMBeanException This class is not an JMX compliant MBean */ public ObjectInstance createMBean(String className, ObjectName name) throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException, RemoteException ; /** * Creates and registers an instance of an MBean in the remote object server. When * calling the method, you have to provide the class name of the Java * implementation to be used for instantiating the new object. You can * optionally provide the name of the class loader to be used. It * returns an ObjectInstance representing the remote MBean created. * * @param className The name of the Java class to be used by the MBeanServer for creating the MBean. * * @param name The name of the MBean to be created. * * @param loaderName The name of the class loader to be used by the MBeanServer. * * @return An ObjectInstance representing the newly created MBean. * * @exception ReflectionException Wraps the java.lang.Exception that occurred trying to invoke the MBean's * constructor. * @exception RemoteException See java.rmi.RemoteException. * @exception InstanceAlreadyExistsException * @exception MBeanRegistrationException The preRegister (MBeanRegistration interface) method of the MBean * has thrown an exception. The MBean will not be registered. * @exception MBeanException Wraps an exception thrown by the MBean's constructor. * @exception NotCompliantMBeanException This class is not an JMX compliant MBean * @exception InstanceNotFoundException The specified loader is not registered in the MBeanServer */ public ObjectInstance createMBean(String className, ObjectName name, ObjectName loaderName) throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException, InstanceNotFoundException, RemoteException ; /** * Creates and registers an instance of an MBean in the remote object server. When * calling the method, you have to provide the class name of the Java * implementation to be used for instantiating the new object. It * returns an ObjectInstance representing the remote MBean created. * * @param className The name of the Java class to be used by the MBeanServer for creating * the MBean. * * @param name The name of the MBean to be created. * * @param params An array containing the parameters of the constructor to be invoked. * * @param signature An array containing the signature of the constructor to be invoked. * * * @return An ObjectInstance representing the newly created MBean. * * @exception RemoteException See java.rmi.RemoteException. * @exception ReflectionException Wraps the java.lang.Exception that occurred trying to invoke the MBean's * constructor. * @exception InstanceAlreadyExistsException * @exception MBeanRegistrationException The preRegister (MBeanRegistration interface) method of the MBean * has thrown an exception. The MBean will not be registered. * @exception MBeanException Wraps an exception thrown by the MBean's constructor. * @exception NotCompliantMBeanException This class is not an JMX compliant MBean */ public ObjectInstance createMBean(String className, ObjectName name, Object params[], String signature[]) throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException, RemoteException ; /** * Creates and registers an instance of an MBean in the remote object server. When * calling the method, you have to provide the class name of the Java * implementation to be used for instantiating the new object. You can * optionally provide the name of the class loader to be used. It * returns an ObjectInstance representing the remote MBean created. * * @param className The name of the Java class to be used by the MBeanServer for creating * the MBean. * * @param name The name of the MBean to be created. * * @param loaderName The name of the class loader to be used by the MBeanServer. * * @param params An array containing the parameters of the constructor to be invoked. * * @param signature An array containing the signature of the constructor to be invoked. * * * @return An ObjectInstance representing the newly created MBean. * * @exception RemoteException See java.rmi.RemoteException. * @exception ReflectionException Wraps the java.lang.Exception that occurred trying to invoke the MBean's * constructor. * @exception InstanceAlreadyExistsException * @exception MBeanRegistrationException The preRegister (MBeanRegistration interface) method of the MBean * has thrown an exception. The MBean will not be registered. * @exception MBeanException Wraps an exception thrown by the MBean's constructor. * @exception NotCompliantMBeanException This class is not an JMX compliant MBean * @exception InstanceNotFoundException The specified loader is not registered in the MBeanServer */ public ObjectInstance createMBean(String className, ObjectName name, ObjectName loaderName, Object params[], String signature[]) throws ReflectionException, InstanceAlreadyExistsException, MBeanRegistrationException, MBeanException, NotCompliantMBeanException, InstanceNotFoundException, RemoteException ; /** * --------------------------------------------------------- * MBean unregistration operations * --------------------------------------------------------- */ /** * Deletes an instance of an MBean in the remote MBean server. * * @param name The name of the MBean to be deleted. * * @exception RemoteException See java.rmi.RemoteException. * @exception InstanceNotFoundException* * @exception MBeanRegistrationException The preDeregister (MBeanRegistration interface) method of the MBean * has thrown an exception. */ public void unregisterMBean(ObjectName name) throws InstanceNotFoundException, MBeanRegistrationException, RemoteException ; /** * --------------------------------------------------------- * ProxyMBean/GenericProxy creation operations * --------------------------------------------------------- */ /** * Gets the ObjectInstance for a given MBean registered with the MBeanServer. * * @param name The object name of the MBean. * * @return The ObjectInstance associated to the MBean specified by <VAR>name</VAR>. * * @exception RemoteException See java.rmi.RemoteException. * @exception InstanceNotFoundException The specified MBean is not registered in the MBeanServer. */ public ObjectInstance getObjectInstance(ObjectName name) throws InstanceNotFoundException, RemoteException ; /** * Gets MBeans controlled by the MBeanServer. This method allows any * of the following to be obtained: All MBeans, a set of MBeans specified * by pattern matching on the ObjectName and/or a Query expression, a * specific MBean. When the object name is null or empty, all objects are * to be selected (and filtered if a query is specified). It returns the * set of ObjectInstance objects (containing the ObjectName and the Java Class name) for * the selected MBeans. * * @param name The object name pattern identifying the MBeans to be retrieved. If * null or empty all the MBeans registered will be retrieved. * @param query The query expression to be applied for selecting MBeans. * * @return A set containing the ObjectInstance objects for the selected MBeans. * If no MBean satisfies the query an empty list is returned. * * @exception RemoteException See java.rmi.RemoteException. */ public java.util.Set queryMBeans(ObjectName name, QueryExp query) throws RemoteException ; /** * --------------------------------------------------------- * Miscelleneous operations * --------------------------------------------------------- */ /** * Checks whether an MBean, identified by its object name, is already registered * with the MBeanServer. * * @param name The object name of the MBean to be checked. * * @return True if the MBean is already registered in the MBeanServer, false otherwise. * * @exception RemoteException See java.rmi.RemoteException. */ public boolean isRegistered(ObjectName name) throws RemoteException ; /** * Gets the names of MBeans controlled by the MBeanServer. This method * allows any of the following to be obtained: The names of all MBeans, * the names of a set of MBeans specified by pattern matching on the * ObjectName and/or a Query expression, a specific MBean name (equivalent to * testing whether an MBean is registered). When the object name is * null or empty, all the objects are to be selected (and filtered if * a query is specified). It returns the set of ObjectNames for the * MBeans selected. * * @param name The object name pattern identifying the MBean names to be retrieved. If * null or empty, the names of all the registered MBeans will be retrieved. * * * @param query The query expression to be applied for selecting MBeans. * * @return A set containing the ObjectNames for the MBeans selected. * * @exception RemoteException See java.rmi.RemoteException. */ public java.util.Set queryNames(ObjectName name, QueryExp query) throws RemoteException ; /** * Returns the number of MBeans controlled by the MBeanServer. * * @exception RemoteException See java.rmi.RemoteException. */ public Integer getMBeanCount() throws RemoteException ; /** * Returns the default domain used for the MBean naming. * * @exception RemoteException See java.rmi.RemoteException. */ public String getDefaultDomain()throws RemoteException; /** * --------------------------------------------------------- * Management operations on MBean * --------------------------------------------------------- */ /** * Gets the value of a specific attribute of a named MBean. The MBean * is identified by its object name. * * @param name The object name of the MBean from which the attribute is to be retrieved. * @param attribute A String specifying the name of the attribute to be * retrieved. * * @return The value of the retrieved attribute. * * @exception RemoteException See java.rmi.RemoteException. * @exception AttributeNotFoundException The specified attribute is not accessible in the MBean. * @exception MBeanException Wraps an exception thrown by the MBean's getter. * @exception InstanceNotFoundException The specified MBean is not registered in the MBeanServer. * @exception ReflectionException Wraps an java.lang.Exception thrown while trying to invoke the setter. */ public Object getAttribute(ObjectName name, String attribute) throws MBeanException, AttributeNotFoundException, InstanceNotFoundException, ReflectionException, RemoteException ; /** * Allows to retrieve the values of several attributes of an MBean. * * @param name The object name of the MBean from within which the attributes are * to be retrieved. * * @param attributes A list of the attributes to be retrieved. * * @return The values of the attributes retrieved. * * @exception RemoteException See java.rmi.RemoteException. * @exception InstanceNotFoundException * @exception ReflectionException An exception occurred trying to invoke the getAttributes method of a Dynamic MBean. */ public AttributeList getAttributes(ObjectName name, String[] attributes) throws InstanceNotFoundException, ReflectionException, RemoteException ; /** * Sets the value of a specific attribute of a named MBean. The MBean * is identified by its object name. * * @param name The name of the MBean within which the attribute is to * be set. * * @param attribute The attribute to be set. * * @exception RemoteException See java.rmi.RemoteException. * @exception InstanceNotFoundException * @exception AttributeNotFoundException * @exception InvalidAttributeValueException * @exception MBeanException Wraps an exception thrown by the MBean's * setter. * * @exception ReflectionException Wraps an exception thrown while trying * to set the attribute. */ public void setAttribute(ObjectName name, Attribute attribute) throws InstanceNotFoundException, AttributeNotFoundException, InvalidAttributeValueException, MBeanException, ReflectionException, RemoteException ; /** * Allows to modify the values of several attributes of an MBean. * * @param name The object name of the MBean from within which the * attributes are to be set. * * @param attributes A list of the attributes to be set. * * @return The values of the attributes that were set. * * @exception RemoteException See java.rmi.RemoteException. * @exception InstanceNotFoundException * @exception ReflectionException An exception occurred trying to * invoke the setAttributes method of a Dynamic MBean. */ public AttributeList setAttributes(ObjectName name, AttributeList attributes) throws InstanceNotFoundException, ReflectionException, RemoteException ; /** * Invokes an action on an MBean. * * @param name The object name of the MBean on which the method is to be invoked. * @param actionName The name of the action to be invoked. * @param params An array containing the parameters to be set when the action is * invoked * @param signature An array containing the signature of the action. The class objects will * be loaded using the same class loader as the one used for loading the MBean on which the action was invoked. * * @return The object returned by the action, which represents the result of invoking the action on the * specified MBean. * * @exception RemoteException See java.rmi.RemoteException. * @exception InstanceNotFoundException The specified MBean is not registered in the MBeanServer. * @exception MBeanException Wraps an exception thrown by the MBean's invoked method. * @exception ReflectionException Wraps an java.lang.Exception thrown while trying to invoke the method. */ public Object invoke(ObjectName name, String actionName, Object params[], String signature[]) throws InstanceNotFoundException, MBeanException, ReflectionException, RemoteException ; /** * This method discovers the attributes and operations that an MBean exposes * for management. When flatten is false, inherited attributes are not returned. * * @param name The name of the MBean to analyze * * @return An instance of MBeanInfo allowing to retrieve all attributes and operations * of this MBean. * * @exception RemoteException See java.rmi.RemoteException. * @exception MBeanException * @exception IntrospectionException An exception occurs during introspection. * @exception InstanceNotFoundException The specified MBean is not found. * @exception ReflectionException An exception occurred trying to invoke the getMBeanInfo of a Dynamic MBean. */ public MBeanInfo getMBeanInfo(ObjectName name) throws InstanceNotFoundException, IntrospectionException, ReflectionException, RemoteException ; /** * Notifications */ public Object[] remoteRequest(int opType, Object[] params) throws Exception, RemoteException ; /** * HeartBeat */ public String pingHeartBeatServer(String sessionId, int period, int nretries, Long notifSessionId) throws RemoteException; }
package com.pengxl.petassistant; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.ComponentName; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Picture; import android.location.Location; import android.os.Binder; import android.os.Bundle; import android.os.IBinder; import android.support.annotation.Nullable; import android.support.v4.app.NotificationCompat; import android.util.Log; import android.widget.ImageView; import static com.pengxl.petassistant.StaticMember.*; public class AlertService extends Service { private final IBinder binder = new AlertService.LocalBinder(); private boolean flag = false; private Thread thread; public class LocalBinder extends Binder { AlertService getService() { return AlertService.this; } } public void work() { thread = new Thread(new Runnable() { @Override public void run() { int id = 1; final String CHANNEL_ID = "pengxl_id_1233"; final String CHANNEL_NAME = "pengxl_name_1233"; NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH); channel.setBypassDnd(true); channel.setShowBadge(true); channel.enableLights(true); channel.enableVibration(true); manager.createNotificationChannel(channel); //设置通知点击事件 Intent intent = new Intent(Intent.ACTION_MAIN); intent.setComponent(new ComponentName(AlertService.this, MainActivity.class)); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED); PendingIntent pendingIntent = PendingIntent.getActivity(AlertService.this, id, intent, PendingIntent.FLAG_UPDATE_CURRENT); NotificationCompat.Builder builder = new NotificationCompat.Builder(AlertService.this, CHANNEL_ID); builder.setSmallIcon(R.mipmap.ic_launcher).setContentTitle("宠物助手").setContentText("宠物离开围栏区域!").setAutoCancel(true) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC).setContentIntent(pendingIntent); while(!thread.isInterrupted()) { try { if(geoFence != null && petPosition != null && !geoFence.contains(petPosition)) { manager.notify(id, builder.build()); Log.i("pengxl1999", "alert!"); Thread.sleep(5000); } } catch (Exception e) { e.printStackTrace(); break; } } } }); thread.start(); } @Override public void onCreate() { super.onCreate(); } @Nullable @Override public IBinder onBind(Intent intent) { return binder; } }
package net.catchpole.web.servlet; // Copyright 2014 catchpole.net // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import junit.framework.TestCase; import net.catchpole.io.Arrays; import net.catchpole.io.Files; import net.catchpole.lang.Throw; import net.catchpole.sql.Database; import net.catchpole.sql.mapping.SchemaExport; import net.catchpole.sql.meta.Table; import net.catchpole.sql.query.Prospect; import net.catchpole.web.server.JettyServer; import org.junit.Test; import java.io.File; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.sql.DriverManager; public class WebServiceServletTest { private static final Database database = AirlineDatabase.create(); @Test public void testServer() throws Exception { Table table = database.getTable("reservation"); Prospect prospect = new Prospect(table); prospect.addSelectColumn(table.getColumn("booking")); prospect.addSelectColumn(table.getColumn("flight")); prospect.addSelectColumn(table.getColumn("passenger")); prospect.addOrderColumn(table.getColumn("booking")); prospect.addSelectColumn(database.getTable("airline").getColumn("code")); SchemaExport schemaExport = new SchemaExport(prospect); JettyServer jettyServer = new JettyServer(9999, new WebServiceServlet(schemaExport.getValueModel())); try { URLConnection urlConnection = new URL("http://localhost:9999/").openConnection(); TestCase.assertEquals(200, ((HttpURLConnection)urlConnection).getResponseCode()); Arrays.spool(urlConnection.getInputStream(), System.out); } finally { jettyServer.stop(); } } } class AirlineDatabase { private static int count = 0; public static Database create() { try { Class.forName("org.hsqldb.jdbcDriver"); Database database = new Database(DriverManager.getConnection("jdbc:hsqldb:mem:Airline-" + count++, "sa", ""), "%"); database.executeStatement(new String(Files.loadFile(new File("../atomicobjects-demo/src/main/resources/net/catchpole/sql/AirlinesTest.sql")))); database.reloadTables(); return database; } catch (Exception e) { throw Throw.unchecked(e); } } }
/* * */ package net.community.chest.dom.xpath.test; import java.io.PrintStream; import java.util.Collection; import net.community.chest.dom.DOMUtils; import net.community.chest.dom.xpath.manip.XPathManipulationData; import net.community.chest.dom.xpath.manip.XPathManipulationListener; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; public class XPathManipTestListener implements XPathManipulationListener { private final PrintStream _out; public final PrintStream getPrintStream () { return _out; } public XPathManipTestListener (final PrintStream out) { if (null == (_out=out)) throw new IllegalArgumentException("No print stream provided"); } public void printResult (final PrintStream out, final String indent, final Object result) { if ((null == out) || (null == result)) return; if (result instanceof Element) out.println(indent + "\t==> " + DOMUtils.toString((Element) result)); else if (result instanceof Attr) out.println(indent + "\t==> " + DOMUtils.toString((Attr) result)); else if (result instanceof Collection<?>) { final Collection<?> cl=(Collection<?>) result; if (cl.size() <= 0) return; out.println(indent + "\t==> " + Collection.class.getName()); final String newIndent=indent + "\t"; for (final Object o : cl) printResult(out, newIndent, o); } else out.println(indent + "\t==>(" + result.getClass().getName() + ") " + result); } /* * @see net.community.chest.dom.xpath.manip.XPathManipulationListener#handleManipulationExecutionResult(net.community.chest.dom.xpath.manip.XPathManipulationData, org.w3c.dom.Document, org.w3c.dom.Element, java.lang.Object) */ @Override public void handleManipulationExecutionResult (XPathManipulationData manip, Document doc, Element elem, Object result) { final PrintStream out=getPrintStream(); if (null == out) return; out.println("\tEXECUTE " + manip + " => " + DOMUtils.toString(elem)); printResult(out, "\t", result); } }
/* * Copyright 2017-2017 Spotify AB * Copyright 2017-2019 The Last Pickle 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 io.cassandrareaper.jmx; import io.cassandrareaper.AppContext; import io.cassandrareaper.ReaperApplicationConfiguration; import io.cassandrareaper.ReaperException; import io.cassandrareaper.core.Cluster; import io.cassandrareaper.core.Node; import io.cassandrareaper.crypto.Cryptograph; import io.cassandrareaper.storage.CassandraStorage; import java.net.UnknownHostException; import java.util.Collections; import java.util.concurrent.atomic.AtomicInteger; import com.google.common.collect.ImmutableSet; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public final class JmxCustomPortTest { /* * Test that the custom JMX port is correctly used by the connection factory * * @throws ReaperException */ @Test public void customJmxPortTest() throws ReaperException, InterruptedException, UnknownHostException { AppContext context = new AppContext(); final Cryptograph cryptographMock = mock(Cryptograph.class); final JmxProxy jmxProxyMock = JmxProxyTest.mockJmxProxyImpl(); final AtomicInteger port = new AtomicInteger(0); HostConnectionCounters hostConnectionCounters = mock(HostConnectionCounters.class); when(hostConnectionCounters.getSuccessfulConnections(any())).thenReturn(1); context.jmxConnectionFactory = new JmxConnectionFactory(context, cryptographMock) { @Override protected JmxProxy connectImpl(Node node) throws ReaperException { final JmxProxy jmx = jmxProxyMock; port.set(node.getJmxPort()); return jmx; } @Override public HostConnectionCounters getHostConnectionCounters() { return hostConnectionCounters; } }; context.config = new ReaperApplicationConfiguration(); context.storage = mock(CassandraStorage.class); Cluster cluster = Cluster.builder() .withName("test") .withPartitioner("murmur3partitioner") .withSeedHosts(ImmutableSet.of("127.0.0.1", "127.0.0.2")) .withJmxPort(7188) .build(); context.jmxConnectionFactory .connectAny(Collections.singleton(Node.builder().withCluster(cluster).withHostname("127.0.0.1").build())); assertEquals(7188, port.get()); Cluster cluster2 = Cluster.builder() .withName("test") .withPartitioner("murmur3partitioner") .withSeedHosts(ImmutableSet.of("127.0.0.1", "127.0.0.2")) .withJmxPort(7198) .build(); context.jmxConnectionFactory .connectAny(Collections.singleton(Node.builder().withCluster(cluster2).withHostname("127.0.0.3").build())); assertEquals(7198, port.get()); } }
package com.example.kuouweather.util; import android.text.TextUtils; import com.example.kuouweather.db.City; import com.example.kuouweather.db.County; import com.example.kuouweather.db.Province; import com.example.kuouweather.gson.Weather; import com.google.gson.Gson; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class Utility { /** * 解析和处理服务器返回的省级数据 * @param response response * @return 是否成功 */ public static boolean handleProvinceResponse(String response) { if (!TextUtils.isEmpty(response)) { try { JSONArray allProvinces = new JSONArray(response); for (int i = 0; i < allProvinces.length(); i++) { JSONObject provinceObject = allProvinces.getJSONObject(i); Province province = new Province(); province.setProvinceName(provinceObject.getString("name")); province.setProvinceCode(provinceObject.getInt("id")); province.save(); } return true; } catch (JSONException e) { e.printStackTrace(); } } return false; } /** * 解析和处理服务器返回的市级数据 * @param response response * @param provinceId provinceId * @return 是否成功 */ public static boolean handleCityResponse(String response, int provinceId) { if (!TextUtils.isEmpty(response)) { try { JSONArray allCities = new JSONArray(response); for (int i = 0; i < allCities.length(); i++) { JSONObject cityObject = allCities.getJSONObject(i); City city = new City(); city.setCityName(cityObject.getString("name")); city.setCityCode(cityObject.getInt("id")); city.setProvinceId(provinceId); city.save(); } return true; } catch (JSONException e) { e.printStackTrace(); } } return false; } /** * 解析和处理服务器返回的县级数据 * @param response response * @param cityId cityId * @return 是否成功 */ public static boolean handleCountyResponse(String response, int cityId) { if (!TextUtils.isEmpty(response)) { try { JSONArray allCounties = new JSONArray(response); for (int i = 0; i < allCounties.length(); i++) { JSONObject countyObject = allCounties.getJSONObject(i); County county = new County(); //注意这里 county.setCountyName(countyObject.getString("name")); county.setWeatherId(countyObject.getString("weather_id")); county.setCityId(cityId); county.save(); } return true; } catch (JSONException e) { e.printStackTrace(); } } return false; } /** * 将返回的JSON数据解析成Weather实体类 */ public static Weather handleWeatherResponse(final String response) { try { JSONObject jsonObject = new JSONObject(response); JSONArray jsonArray = jsonObject.getJSONArray("HeWeather"); String weatherContent = jsonArray.getJSONObject(0).toString(); return new Gson().fromJson(weatherContent, Weather.class); } catch (JSONException e) { e.printStackTrace(); } return null; } }
/* * Copyright 2012-2019 MarkLogic Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.marklogic.client.semantics; import java.util.Map; import java.util.Set; /** * <p>A Map of permissions for a graph, where the keys are roles and the values * are the Set of capabilities available to that role (one of READ, UPDATE, or * EXECUTE). See usage examples in javadocs for {@link GraphManager} and * {@link SPARQLQueryManager}.</p> * * <p>For details about RDF, SPARQL, and semantics in MarkLogic see * <a href="https://docs.marklogic.com/guide/semantics" target="_top">Semantics Developer's Guide</a> */ public interface GraphPermissions extends Map<String, Set<Capability>> { /** Add the specified role and capabilities to this GraphPermissions object. * * @param role the name of the role receiving these capabilities * @param capabilities the capabilities (READ, UPDATE, or EXECUTE) granted to this role * * @return the new GraphPermissions object with these permissions added */ GraphPermissions permission(String role, Capability... capabilities); }
package com.google.android.gms.internal.ads; final class zzbeq extends zzben { zzbeq() { } private static int zza(byte[] bArr, int i, long j, int i2) { if (i2 == 0) { return zzbem.zzda(i); } if (i2 == 1) { return zzbem.zzz(i, zzbek.zza(bArr, j)); } if (i2 == 2) { return zzbem.zzf(i, (int) zzbek.zza(bArr, j), (int) zzbek.zza(bArr, j + 1)); } throw new AssertionError(); } /* access modifiers changed from: package-private */ /* JADX WARNING: Code restructure failed: missing block: B:29:0x0061, code lost: return -1; */ /* JADX WARNING: Code restructure failed: missing block: B:57:0x00b6, code lost: return -1; */ /* Code decompiled incorrectly, please refer to instructions dump. */ public final int zzb(int r16, byte[] r17, int r18, int r19) { /* r15 = this; r0 = r17 r1 = r18 r2 = r19 r3 = r1 | r2 int r4 = r0.length int r4 = r4 - r2 r3 = r3 | r4 r4 = 2 r5 = 3 r6 = 0 if (r3 < 0) goto L_0x00b7 long r7 = (long) r1 long r1 = (long) r2 long r1 = r1 - r7 int r2 = (int) r1 r1 = 16 r9 = 1 if (r2 >= r1) goto L_0x001c r1 = 0 goto L_0x002e L_0x001c: r11 = r7 r1 = 0 L_0x001e: if (r1 >= r2) goto L_0x002d long r13 = r11 + r9 byte r3 = com.google.android.gms.internal.ads.zzbek.zza(r0, r11) if (r3 >= 0) goto L_0x0029 goto L_0x002e L_0x0029: int r1 = r1 + 1 r11 = r13 goto L_0x001e L_0x002d: r1 = r2 L_0x002e: int r2 = r2 - r1 long r11 = (long) r1 long r7 = r7 + r11 L_0x0031: r1 = 0 L_0x0032: if (r2 <= 0) goto L_0x0041 long r11 = r7 + r9 byte r1 = com.google.android.gms.internal.ads.zzbek.zza(r0, r7) if (r1 < 0) goto L_0x0040 int r2 = r2 + -1 r7 = r11 goto L_0x0032 L_0x0040: r7 = r11 L_0x0041: if (r2 != 0) goto L_0x0044 return r6 L_0x0044: int r2 = r2 + -1 r3 = -32 r11 = -65 r12 = -1 if (r1 >= r3) goto L_0x0062 if (r2 != 0) goto L_0x0050 return r1 L_0x0050: int r2 = r2 + -1 r3 = -62 if (r1 < r3) goto L_0x0061 long r13 = r7 + r9 byte r1 = com.google.android.gms.internal.ads.zzbek.zza(r0, r7) if (r1 <= r11) goto L_0x005f goto L_0x0061 L_0x005f: r7 = r13 goto L_0x0031 L_0x0061: return r12 L_0x0062: r13 = -16 if (r1 >= r13) goto L_0x008c if (r2 >= r4) goto L_0x006d int r0 = zza(r0, r1, r7, r2) return r0 L_0x006d: int r2 = r2 + -2 long r13 = r7 + r9 byte r7 = com.google.android.gms.internal.ads.zzbek.zza(r0, r7) if (r7 > r11) goto L_0x008b r8 = -96 if (r1 != r3) goto L_0x007d if (r7 < r8) goto L_0x008b L_0x007d: r3 = -19 if (r1 != r3) goto L_0x0083 if (r7 >= r8) goto L_0x008b L_0x0083: long r7 = r13 + r9 byte r1 = com.google.android.gms.internal.ads.zzbek.zza(r0, r13) if (r1 <= r11) goto L_0x0031 L_0x008b: return r12 L_0x008c: if (r2 >= r5) goto L_0x0093 int r0 = zza(r0, r1, r7, r2) return r0 L_0x0093: int r2 = r2 + -3 long r13 = r7 + r9 byte r3 = com.google.android.gms.internal.ads.zzbek.zza(r0, r7) if (r3 > r11) goto L_0x00b6 int r1 = r1 << 28 int r3 = r3 + 112 int r1 = r1 + r3 int r1 = r1 >> 30 if (r1 != 0) goto L_0x00b6 long r7 = r13 + r9 byte r1 = com.google.android.gms.internal.ads.zzbek.zza(r0, r13) if (r1 > r11) goto L_0x00b6 long r13 = r7 + r9 byte r1 = com.google.android.gms.internal.ads.zzbek.zza(r0, r7) if (r1 <= r11) goto L_0x005f L_0x00b6: return r12 L_0x00b7: java.lang.ArrayIndexOutOfBoundsException r3 = new java.lang.ArrayIndexOutOfBoundsException java.lang.Object[] r5 = new java.lang.Object[r5] int r0 = r0.length java.lang.Integer r0 = java.lang.Integer.valueOf(r0) r5[r6] = r0 java.lang.Integer r0 = java.lang.Integer.valueOf(r18) r1 = 1 r5[r1] = r0 java.lang.Integer r0 = java.lang.Integer.valueOf(r19) r5[r4] = r0 java.lang.String r0 = "Array length=%d, index=%d, limit=%d" java.lang.String r0 = java.lang.String.format(r0, r5) r3.<init>(r0) goto L_0x00da L_0x00d9: throw r3 L_0x00da: goto L_0x00d9 */ throw new UnsupportedOperationException("Method not decompiled: com.google.android.gms.internal.ads.zzbeq.zzb(int, byte[], int, int):int"); } /* access modifiers changed from: package-private */ /* JADX WARNING: Removed duplicated region for block: B:11:0x0031 */ /* JADX WARNING: Removed duplicated region for block: B:13:0x0033 A[LOOP:1: B:13:0x0033->B:38:0x00fb, LOOP_START, PHI: r2 r3 r4 r11 PHI: (r2v4 int) = (r2v3 int), (r2v6 int) binds: [B:10:0x002f, B:38:0x00fb] A[DONT_GENERATE, DONT_INLINE] PHI: (r3v3 char) = (r3v2 char), (r3v4 char) binds: [B:10:0x002f, B:38:0x00fb] A[DONT_GENERATE, DONT_INLINE] PHI: (r4v3 long) = (r4v2 long), (r4v5 long) binds: [B:10:0x002f, B:38:0x00fb] A[DONT_GENERATE, DONT_INLINE] PHI: (r11v3 long) = (r11v2 long), (r11v4 long) binds: [B:10:0x002f, B:38:0x00fb] A[DONT_GENERATE, DONT_INLINE]] */ /* Code decompiled incorrectly, please refer to instructions dump. */ public final int zzb(java.lang.CharSequence r23, byte[] r24, int r25, int r26) { /* r22 = this; r0 = r23 r1 = r24 r2 = r25 r3 = r26 long r4 = (long) r2 long r6 = (long) r3 long r6 = r6 + r4 int r8 = r23.length() java.lang.String r9 = " at index " java.lang.String r10 = "Failed writing " if (r8 > r3) goto L_0x0146 int r11 = r1.length int r11 = r11 - r3 if (r11 < r2) goto L_0x0146 r2 = 0 L_0x001a: r3 = 128(0x80, float:1.794E-43) r11 = 1 if (r2 >= r8) goto L_0x002f char r13 = r0.charAt(r2) if (r13 >= r3) goto L_0x002f long r11 = r11 + r4 byte r3 = (byte) r13 com.google.android.gms.internal.ads.zzbek.zza((byte[]) r1, (long) r4, (byte) r3) int r2 = r2 + 1 r4 = r11 goto L_0x001a L_0x002f: if (r2 != r8) goto L_0x0033 int r0 = (int) r4 return r0 L_0x0033: if (r2 >= r8) goto L_0x0144 char r13 = r0.charAt(r2) if (r13 >= r3) goto L_0x004b int r14 = (r4 > r6 ? 1 : (r4 == r6 ? 0 : -1)) if (r14 >= 0) goto L_0x004b long r14 = r4 + r11 byte r13 = (byte) r13 com.google.android.gms.internal.ads.zzbek.zza((byte[]) r1, (long) r4, (byte) r13) r4 = r11 r12 = r14 L_0x0047: r11 = 128(0x80, float:1.794E-43) goto L_0x00fb L_0x004b: r14 = 2048(0x800, float:2.87E-42) if (r13 >= r14) goto L_0x0075 r14 = 2 long r14 = r6 - r14 int r16 = (r4 > r14 ? 1 : (r4 == r14 ? 0 : -1)) if (r16 > 0) goto L_0x0075 long r14 = r4 + r11 int r3 = r13 >>> 6 r3 = r3 | 960(0x3c0, float:1.345E-42) byte r3 = (byte) r3 com.google.android.gms.internal.ads.zzbek.zza((byte[]) r1, (long) r4, (byte) r3) long r3 = r14 + r11 r5 = r13 & 63 r13 = 128(0x80, float:1.794E-43) r5 = r5 | r13 byte r5 = (byte) r5 com.google.android.gms.internal.ads.zzbek.zza((byte[]) r1, (long) r14, (byte) r5) r20 = r11 r11 = 128(0x80, float:1.794E-43) r12 = r3 r4 = r20 goto L_0x00fb L_0x0075: r3 = 57343(0xdfff, float:8.0355E-41) r14 = 55296(0xd800, float:7.7486E-41) if (r13 < r14) goto L_0x007f if (r3 >= r13) goto L_0x00ae L_0x007f: r15 = 3 long r15 = r6 - r15 int r17 = (r4 > r15 ? 1 : (r4 == r15 ? 0 : -1)) if (r17 > 0) goto L_0x00ae long r14 = r4 + r11 int r3 = r13 >>> 12 r3 = r3 | 480(0x1e0, float:6.73E-43) byte r3 = (byte) r3 com.google.android.gms.internal.ads.zzbek.zza((byte[]) r1, (long) r4, (byte) r3) long r3 = r14 + r11 int r5 = r13 >>> 6 r5 = r5 & 63 r11 = 128(0x80, float:1.794E-43) r5 = r5 | r11 byte r5 = (byte) r5 com.google.android.gms.internal.ads.zzbek.zza((byte[]) r1, (long) r14, (byte) r5) r14 = 1 long r18 = r3 + r14 r5 = r13 & 63 r5 = r5 | r11 byte r5 = (byte) r5 com.google.android.gms.internal.ads.zzbek.zza((byte[]) r1, (long) r3, (byte) r5) r12 = r18 r4 = 1 goto L_0x0047 L_0x00ae: r11 = 4 long r11 = r6 - r11 int r15 = (r4 > r11 ? 1 : (r4 == r11 ? 0 : -1)) if (r15 > 0) goto L_0x010f int r3 = r2 + 1 if (r3 == r8) goto L_0x0107 char r2 = r0.charAt(r3) boolean r11 = java.lang.Character.isSurrogatePair(r13, r2) if (r11 == 0) goto L_0x0106 int r2 = java.lang.Character.toCodePoint(r13, r2) r11 = 1 long r13 = r4 + r11 int r15 = r2 >>> 18 r15 = r15 | 240(0xf0, float:3.36E-43) byte r15 = (byte) r15 com.google.android.gms.internal.ads.zzbek.zza((byte[]) r1, (long) r4, (byte) r15) long r4 = r13 + r11 int r15 = r2 >>> 12 r15 = r15 & 63 r11 = 128(0x80, float:1.794E-43) r12 = r15 | 128(0x80, float:1.794E-43) byte r12 = (byte) r12 com.google.android.gms.internal.ads.zzbek.zza((byte[]) r1, (long) r13, (byte) r12) r12 = 1 long r14 = r4 + r12 int r16 = r2 >>> 6 r12 = r16 & 63 r12 = r12 | r11 byte r12 = (byte) r12 com.google.android.gms.internal.ads.zzbek.zza((byte[]) r1, (long) r4, (byte) r12) r4 = 1 long r12 = r14 + r4 r2 = r2 & 63 r2 = r2 | r11 byte r2 = (byte) r2 com.google.android.gms.internal.ads.zzbek.zza((byte[]) r1, (long) r14, (byte) r2) r2 = r3 L_0x00fb: int r2 = r2 + 1 r3 = 128(0x80, float:1.794E-43) r20 = r4 r4 = r12 r11 = r20 goto L_0x0033 L_0x0106: r2 = r3 L_0x0107: com.google.android.gms.internal.ads.zzbep r0 = new com.google.android.gms.internal.ads.zzbep int r2 = r2 + -1 r0.<init>(r2, r8) throw r0 L_0x010f: if (r14 > r13) goto L_0x0127 if (r13 > r3) goto L_0x0127 int r1 = r2 + 1 if (r1 == r8) goto L_0x0121 char r0 = r0.charAt(r1) boolean r0 = java.lang.Character.isSurrogatePair(r13, r0) if (r0 != 0) goto L_0x0127 L_0x0121: com.google.android.gms.internal.ads.zzbep r0 = new com.google.android.gms.internal.ads.zzbep r0.<init>(r2, r8) throw r0 L_0x0127: java.lang.ArrayIndexOutOfBoundsException r0 = new java.lang.ArrayIndexOutOfBoundsException r1 = 46 java.lang.StringBuilder r2 = new java.lang.StringBuilder r2.<init>(r1) r2.append(r10) r2.append(r13) r2.append(r9) r2.append(r4) java.lang.String r1 = r2.toString() r0.<init>(r1) throw r0 L_0x0144: int r0 = (int) r4 return r0 L_0x0146: java.lang.ArrayIndexOutOfBoundsException r1 = new java.lang.ArrayIndexOutOfBoundsException int r8 = r8 + -1 char r0 = r0.charAt(r8) int r2 = r2 + r3 r3 = 37 java.lang.StringBuilder r4 = new java.lang.StringBuilder r4.<init>(r3) r4.append(r10) r4.append(r0) r4.append(r9) r4.append(r2) java.lang.String r0 = r4.toString() r1.<init>(r0) goto L_0x016b L_0x016a: throw r1 L_0x016b: goto L_0x016a */ throw new UnsupportedOperationException("Method not decompiled: com.google.android.gms.internal.ads.zzbeq.zzb(java.lang.CharSequence, byte[], int, int):int"); } }
public class Foo { void m(int x) { x.sameKey<caret> } }
package ai.api.test; /** * ******************************************************************************************************************** * <p/> * API.AI Android SDK - client-side libraries for API.AI * ================================================= * <p/> * Copyright (C) 2014 by Speaktoit, Inc. (https://www.speaktoit.com) * https://www.api.ai * <p/> * ********************************************************************************************************************** * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * <p/> * ********************************************************************************************************************* */ import android.text.TextUtils; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.RobolectricTestRunner; import org.robolectric.RuntimeEnvironment; import org.robolectric.annotation.Config; import ai.api.AIConfiguration; import ai.api.AIDataService; import ai.api.AIServiceException; import ai.api.BuildConfig; import ai.api.model.AIRequest; import ai.api.model.AIResponse; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @Config(constants = BuildConfig.class, manifest = Config.NONE, sdk = BuildConfig.TESTS_SDK) @RunWith(RobolectricTestRunner.class) @Ignore("Tests for development purposes. Disabled by default.") public class ProtocolDevTest extends ProtocolTestBase { // Testing keys protected static final String ACCESS_TOKEN = "a410386b327946c6ac162aad10cf9788"; protected static final String SUBSCRIPTION_KEY = "no difference"; @Override protected String getAccessToken() { return ACCESS_TOKEN; } @Override protected String getSecondAccessToken() { return "212bf93686444afab30e20ed6f2dff1d"; } @Override protected String getSubscriptionKey() { return SUBSCRIPTION_KEY; } @Override protected String getRuAccessToken() { return "43a7541fb0a94fae8f1bef406a2d9ca8"; } @Override protected String getBrAccessToken() { return ""; } @Override protected String getPtBrAccessToken() { return "521282797a864a029e1f965fa973cf61"; } @Override protected String getJaAccessToken() { return "c82b0a650c9a4758984fb53411f271e4"; } protected String getDevUrl() { return "https://dev.api.ai/api/"; } @Test public void AIDataServiceDevRuTest() { final String devUrl = getDevUrl(); if (!TextUtils.isEmpty(devUrl)) { final AIConfiguration config = new AIConfiguration("43a7541fb0a94fae8f1bef406a2d9ca8", getSubscriptionKey(), AIConfiguration.SupportedLanguages.Russian, AIConfiguration.RecognitionEngine.System); config.setServiceUrl(devUrl); final AIDataService aiDataService = new AIDataService(RuntimeEnvironment.application, config); final AIRequest aiRequest = new AIRequest(); aiRequest.setQuery("привет"); try { final AIResponse aiResponse = makeRequest(aiDataService, aiRequest); assertFalse(TextUtils.isEmpty(aiResponse.getResult().getResolvedQuery())); assertEquals("helloAction", aiResponse.getResult().getAction()); assertEquals("Добрый день", aiResponse.getResult().getFulfillment().getSpeech()); } catch (final AIServiceException e) { e.printStackTrace(); assertTrue(e.getMessage(), false); } } else { assertTrue(true); } } @Test public void AIDataServiceDevTest() throws AIServiceException { final String devUrl = getDevUrl(); if (!TextUtils.isEmpty(devUrl)) { final AIConfiguration config = new AIConfiguration(getAccessToken(), getSubscriptionKey(), AIConfiguration.SupportedLanguages.English, AIConfiguration.RecognitionEngine.System); config.setServiceUrl(devUrl); final AIDataService aiDataService = new AIDataService(RuntimeEnvironment.application, config); final AIRequest aiRequest = new AIRequest(); aiRequest.setQuery("hello"); final AIResponse aiResponse = makeRequest(aiDataService, aiRequest); assertFalse(TextUtils.isEmpty(aiResponse.getResult().getResolvedQuery())); assertEquals("greeting", aiResponse.getResult().getAction()); assertEquals("Hi! How are you?", aiResponse.getResult().getFulfillment().getSpeech()); } else { assertTrue(true); } } @Override protected void updateConfig(final AIConfiguration config) { final String devUrl = getDevUrl(); if (!TextUtils.isEmpty(devUrl)) { config.setServiceUrl(devUrl); } } }
/* * Copyright 2015-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.networkfirewall.model; import java.io.Serializable; import javax.annotation.Generated; import com.amazonaws.protocol.StructuredPojo; import com.amazonaws.protocol.ProtocolMarshaller; /** * <p> * The ID for a subnet that you want to associate with the firewall. This is used with <a>CreateFirewall</a> and * <a>AssociateSubnets</a>. AWS Network Firewall creates an instance of the associated firewall in each subnet that you * specify, to filter traffic in the subnet's Availability Zone. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/network-firewall-2020-11-12/SubnetMapping" target="_top">AWS API * Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class SubnetMapping implements Serializable, Cloneable, StructuredPojo { /** * <p> * The unique identifier for the subnet. * </p> */ private String subnetId; /** * <p> * The unique identifier for the subnet. * </p> * * @param subnetId * The unique identifier for the subnet. */ public void setSubnetId(String subnetId) { this.subnetId = subnetId; } /** * <p> * The unique identifier for the subnet. * </p> * * @return The unique identifier for the subnet. */ public String getSubnetId() { return this.subnetId; } /** * <p> * The unique identifier for the subnet. * </p> * * @param subnetId * The unique identifier for the subnet. * @return Returns a reference to this object so that method calls can be chained together. */ public SubnetMapping withSubnetId(String subnetId) { setSubnetId(subnetId); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getSubnetId() != null) sb.append("SubnetId: ").append(getSubnetId()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof SubnetMapping == false) return false; SubnetMapping other = (SubnetMapping) obj; if (other.getSubnetId() == null ^ this.getSubnetId() == null) return false; if (other.getSubnetId() != null && other.getSubnetId().equals(this.getSubnetId()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getSubnetId() == null) ? 0 : getSubnetId().hashCode()); return hashCode; } @Override public SubnetMapping clone() { try { return (SubnetMapping) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } @com.amazonaws.annotation.SdkInternalApi @Override public void marshall(ProtocolMarshaller protocolMarshaller) { com.amazonaws.services.networkfirewall.model.transform.SubnetMappingMarshaller.getInstance().marshall(this, protocolMarshaller); } }
package csu.standard.simplePartition; public class StandardPoint<T extends Number> { private T x_; private T y_; public StandardPoint(T x, T y) { this.x_ = x; this.y_ = y; } public T getX() { return x_; } public void setX(T x) { this.x_ = x; } public T getY() { return y_; } public void setY(T y) { this.y_ = y; } public double distanceTo(StandardPoint<?> point) { double dx = Math.abs(getX().doubleValue() - point.getX().doubleValue()); double dy = Math.abs(getY().doubleValue() - point.getY().doubleValue()); double d = Math.sqrt(dx * dx + dy * dy); return d; } }
/** * Logback: the reliable, generic, fast and flexible logging framework. * Copyright (C) 1999-2015, QOS.ch. All rights reserved. * * This program and the accompanying materials are dual-licensed under * either the terms of the Eclipse Public License v1.0 as published by * the Eclipse Foundation * * or (per the licensee's choosing) * * under the terms of the GNU Lesser General Public License version 2.1 * as published by the Free Software Foundation. */ package ch.qos.logback.classic.spi; import java.io.Serializable; import java.util.Arrays; public class ThrowableProxyVO implements IThrowableProxy, Serializable { private static final long serialVersionUID = -773438177285807139L; private String className; private String message; private int commonFramesCount; private StackTraceElementProxy[] stackTraceElementProxyArray; private IThrowableProxy cause; private IThrowableProxy[] suppressed; public String getMessage() { return message; } public String getClassName() { return className; } public int getCommonFrames() { return commonFramesCount; } public IThrowableProxy getCause() { return cause; } public StackTraceElementProxy[] getStackTraceElementProxyArray() { return stackTraceElementProxyArray; } public IThrowableProxy[] getSuppressed() { return suppressed; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((className == null) ? 0 : className.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final ThrowableProxyVO other = (ThrowableProxyVO) obj; if (className == null) { if (other.className != null) return false; } else if (!className.equals(other.className)) return false; if (!Arrays.equals(stackTraceElementProxyArray, other.stackTraceElementProxyArray)) return false; if (!Arrays.equals(suppressed, other.suppressed)) return false; if (cause == null) { if (other.cause != null) return false; } else if (!cause.equals(other.cause)) return false; return true; } public static ThrowableProxyVO build(IThrowableProxy throwableProxy) { if (throwableProxy == null) { return null; } ThrowableProxyVO tpvo = new ThrowableProxyVO(); tpvo.className = throwableProxy.getClassName(); tpvo.message = throwableProxy.getMessage(); tpvo.commonFramesCount = throwableProxy.getCommonFrames(); tpvo.stackTraceElementProxyArray = throwableProxy.getStackTraceElementProxyArray(); IThrowableProxy cause = throwableProxy.getCause(); if (cause != null) { tpvo.cause = ThrowableProxyVO.build(cause); } IThrowableProxy[] suppressed = throwableProxy.getSuppressed(); if (suppressed != null) { tpvo.suppressed = new IThrowableProxy[suppressed.length]; for (int i = 0; i < suppressed.length; i++) { tpvo.suppressed[i] = ThrowableProxyVO.build(suppressed[i]); } } return tpvo; } }
package com.zhangxin.study.mvp.presenter.impl; import com.zhangxin.study.mvp.model.LoginModel; import com.zhangxin.study.mvp.model.entities.User; import com.zhangxin.study.mvp.model.impl.LoginModelImpl; import com.zhangxin.study.mvp.presenter.LoginPresenter; import com.zhangxin.study.mvp.presenter.OnLoginFinishedListener; import com.zhangxin.study.mvp.view.LoginView; /** * @author zhangxin * @date 2020/4/13 * @desc 由于presenter完成二者的交互,那么肯定需要二者的实现类(通过传入参数,或者new)。 * presenter里面有个OnLoginFinishedListener, 其在Presenter层实现,给Model层回调,更改View层的状态, 确保 Model层不直接操作View层。 **/ public class LoginPresenterImpl implements LoginPresenter, OnLoginFinishedListener { private LoginView loginView; private LoginModel loginModel; public LoginPresenterImpl(LoginView loginView) { this.loginView = loginView; loginModel = new LoginModelImpl(); } @Override public void validateCredentials(User user) { if (null != loginView) { loginView.showProgress(); } loginModel.login(user, this); } @Override public void onDestroy() { loginView = null; } @Override public void onUsernameError() { if (null != loginView) { loginView.setUsernameError(); loginView.hideProgress(); } } @Override public void onPasswordError() { if (null != loginView) { loginView.setPasswordError(); loginView.hideProgress(); } } @Override public void onSuccess() { if (null != loginView) { loginView.showSuccess(); } } }
package com.gc.nfc.component; import android.content.Context; import android.util.Log; import com.alibaba.sdk.android.push.AliyunMessageIntentService; import com.alibaba.sdk.android.push.notification.CPushMessage; import java.util.Map; import static com.gc.nfc.component.MyMessageReceiver.REC_TAG; /** * Created by liyazhou on 17/8/22. * 为避免推送广播被系统拦截的小概率事件,我们推荐用户通过IntentService处理消息互调,接入步骤: * 1. 创建IntentService并继承AliyunMessageIntentService * 2. 覆写相关方法,并在Manifest的注册该Service * 3. 调用接口CloudPushService.setPushIntentService * 详细用户可参考:https://help.aliyun.com/document_detail/30066.html#h2-2-messagereceiver-aliyunmessageintentservice */ public class MyMessageIntentService extends AliyunMessageIntentService { private static final String TAG = "MyMessageIntentService"; /** * 推送通知的回调方法 * @param context * @param title * @param summary * @param extraMap */ @Override protected void onNotification(Context context, String title, String summary, Map<String, String> extraMap) { // Log.i(REC_TAG,"收到一条推送通知 : " + title + ", summary:" + summary); // MainApplication.setConsoleText("收到一条推送通知 : " + title + ", summary:" + summary); System.out.print("收到一条推送通知 : " + title + ", summary:" + summary); } /** * 推送消息的回调方法 * @param context * @param cPushMessage */ @Override protected void onMessage(Context context, CPushMessage cPushMessage) { // Log.i(REC_TAG,"收到一条推送消息 : " + cPushMessage.getTitle() + ", content:" + cPushMessage.getContent()); // MainApplication.setConsoleText(cPushMessage.getTitle() + ", content:" + cPushMessage.getContent()); System.out.print("收到一条推送消息 : " + cPushMessage.getTitle() + ", content:" + cPushMessage.getContent()); } /** * 从通知栏打开通知的扩展处理 * @param context * @param title * @param summary * @param extraMap */ @Override protected void onNotificationOpened(Context context, String title, String summary, String extraMap) { System.out.print("onNotificationOpened : " + " : " + title + " : " + summary + " : " + extraMap); // Log.i(REC_TAG,"onNotificationOpened : " + " : " + title + " : " + summary + " : " + extraMap); // MainApplication.setConsoleText("onNotificationOpened : " + " : " + title + " : " + summary + " : " + extraMap); } /** * 无动作通知点击回调。当在后台或阿里云控制台指定的通知动作为无逻辑跳转时,通知点击回调为onNotificationClickedWithNoAction而不是onNotificationOpened * @param context * @param title * @param summary * @param extraMap */ @Override protected void onNotificationClickedWithNoAction(Context context, String title, String summary, String extraMap) { // Log.i(REC_TAG,"onNotificationClickedWithNoAction : " + " : " + title + " : " + summary + " : " + extraMap); // MainApplication.setConsoleText("onNotificationClickedWithNoAction : " + " : " + title + " : " + summary + " : " + extraMap); } /** * 通知删除回调 * @param context * @param messageId */ @Override protected void onNotificationRemoved(Context context, String messageId) { // Log.i(REC_TAG, "onNotificationRemoved : " + messageId); // MainApplication.setConsoleText("onNotificationRemoved : " + messageId); } /** * 应用处于前台时通知到达回调。注意:该方法仅对自定义样式通知有效,相关详情请参考https://help.aliyun.com/document_detail/30066.html#h3-3-4-basiccustompushnotification-api * @param context * @param title * @param summary * @param extraMap * @param openType * @param openActivity * @param openUrl */ @Override protected void onNotificationReceivedInApp(Context context, String title, String summary, Map<String, String> extraMap, int openType, String openActivity, String openUrl) { System.out.print("onNotificationReceivedInApp : " + " : " + title + " : " + summary + " : " + extraMap); // Log.i(REC_TAG,"onNotificationReceivedInApp : " + " : " + title + " : " + summary + " " + extraMap + " : " + openType + " : " + openActivity + " : " + openUrl); // MainApplication.setConsoleText("onNotificationReceivedInApp : " + " : " + title + " : " + summary); } }
package net.glowstone.scoreboard; import net.glowstone.util.nbt.CompoundTag; import net.glowstone.util.nbt.NbtOutputStream; import org.bukkit.scoreboard.DisplaySlot; import org.bukkit.scoreboard.Objective; import org.bukkit.scoreboard.Score; import org.bukkit.scoreboard.Team; import java.io.DataOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class NbtScoreboardIoWriter { /** * Saves a scoreboard to a compressed NBT file. * * @param path the file path to write to * @param scoreboard the scoreboard to save * @throws IOException if the file cannot be written */ public static void writeMainScoreboard(File path, GlowScoreboard scoreboard) throws IOException { CompoundTag root = new CompoundTag(); CompoundTag data = new CompoundTag(); root.putCompound("data", data); try (NbtOutputStream nbt = new NbtOutputStream(getDataOutputStream(path), true)) { writeObjectives(data, scoreboard); writeScores(data, scoreboard); writeTeams(data, scoreboard); writeDisplaySlots(data, scoreboard); nbt.writeTag(root); nbt.close(); } } private static DataOutputStream getDataOutputStream(File path) throws IOException { if (!path.exists()) { path.getParentFile().mkdirs(); path.createNewFile(); } return new DataOutputStream(new FileOutputStream(path)); } private static void writeObjectives(CompoundTag root, GlowScoreboard scoreboard) { List<CompoundTag> objectives = new ArrayList<>(); for (Objective objective : scoreboard.getObjectives()) { CompoundTag objectiveNbt = new CompoundTag(); objectiveNbt.putString("CriteriaName", objective.getCriteria()); objectiveNbt.putString("DisplayName", objective.getDisplayName()); objectiveNbt.putString("Name", objective.getName()); objectiveNbt.putString("RenderType", ((GlowObjective) objective).getType().name()); objectives.add(objectiveNbt); } root.putCompoundList("Objectives", objectives); } private static void writeScores(CompoundTag root, GlowScoreboard scoreboard) { List<CompoundTag> scores = new ArrayList<>(); for (String objective : scoreboard.getEntries()) { for (Score score : scoreboard.getScores(objective)) { CompoundTag scoreNbt = new CompoundTag(); scoreNbt.putInt("Score", score.getScore()); scoreNbt.putString("Name", score.getEntry()); scoreNbt.putString("Objective", score.getObjective().getName()); scoreNbt.putByte("Locked", ((GlowScore) score).getLocked() ? 1 : 0); scores.add(scoreNbt); } } root.putCompoundList("PlayerScores", scores); } private static void writeTeams(CompoundTag root, GlowScoreboard scoreboard) { List<CompoundTag> teams = new ArrayList<>(); for (Team team : scoreboard.getTeams()) { CompoundTag teamNbt = new CompoundTag(); teamNbt.putByte("AllowFriendlyFire", team.allowFriendlyFire() ? 1 : 0); teamNbt.putByte("SeeFriendlyInvisibles", team.canSeeFriendlyInvisibles() ? 1 : 0); teamNbt.putString("NameTagVisibility", team.getOption(Team.Option.NAME_TAG_VISIBILITY).name().toLowerCase()); switch (team.getOption(Team.Option.DEATH_MESSAGE_VISIBILITY)) { case NEVER: teamNbt.putString("DeathMessageVisibility", "never"); break; case FOR_OTHER_TEAMS: teamNbt.putString("DeathMessageVisibility", "hideForOtherTeams"); break; case FOR_OWN_TEAM: teamNbt.putString("DeathMessageVisibility", "hideForOwnTeam"); break; default: teamNbt.putString("DeathMessageVisibility", "always"); } switch (team.getOption(Team.Option.COLLISION_RULE)) { case NEVER: teamNbt.putString("CollisionRule", "never"); break; case FOR_OTHER_TEAMS: teamNbt.putString("CollisionRule", "pushOtherTeams"); break; case FOR_OWN_TEAM: teamNbt.putString("CollisionRule", "pushOwnTeam"); break; default: teamNbt.putString("CollisionRule", "always"); } teamNbt.putString("DisplayName", team.getDisplayName()); teamNbt.putString("Name", team.getName()); teamNbt.putString("Prefix", team.getPrefix()); teamNbt.putString("Suffix", team.getSuffix()); teamNbt.putString("TeamColor", ((GlowTeam) team).getColor().name().toLowerCase()); List<String> players = new ArrayList<>(team.getEntries()); teamNbt.putStringList("Players", players); teams.add(teamNbt); } root.putCompoundList("Teams", teams); } private static void writeDisplaySlots(CompoundTag root, GlowScoreboard scoreboard) { CompoundTag slots = new CompoundTag(); if (scoreboard.getObjective(DisplaySlot.PLAYER_LIST) != null) { slots.putString("slot_0", scoreboard.getObjective(DisplaySlot.PLAYER_LIST).getName()); } if (scoreboard.getObjective(DisplaySlot.SIDEBAR) != null) { slots.putString("slot_1", scoreboard.getObjective(DisplaySlot.SIDEBAR).getName()); } if (scoreboard.getObjective(DisplaySlot.BELOW_NAME) != null) { slots.putString("slot_2", scoreboard.getObjective(DisplaySlot.BELOW_NAME).getName()); } root.putCompound("DisplaySlots", slots); } }
package br.com.caelum.tubaina.parser.html; import br.com.caelum.tubaina.chunk.TodoChunk; import br.com.caelum.tubaina.parser.Tag; public class TodoTagTemplate implements Tag<TodoChunk> { private TodoTagTemplate template = new TodoTagTemplate(); @Override public String parse(TodoChunk chunk) { return template.parse(chunk); } }
/* * SPDX-License-Identifier: Apache-2.0 * * The OpenSearch Contributors require contributions made to * this file be licensed under the Apache-2.0 license or a * compatible open source license. */ package org.opensearch.indices.replication; import org.opensearch.OpenSearchException; import org.opensearch.action.ActionListener; import org.opensearch.common.bytes.BytesReference; import org.opensearch.common.util.CancellableThreads; import org.opensearch.index.shard.IndexShard; import org.opensearch.index.store.StoreFileMetadata; import org.opensearch.indices.replication.checkpoint.ReplicationCheckpoint; import org.opensearch.indices.replication.common.ReplicationLuceneIndex; import org.opensearch.indices.replication.common.ReplicationState; import org.opensearch.indices.replication.common.ReplicationTarget; import java.io.IOException; /** * Represents the target of a replication event. * * @opensearch.internal */ public class SegmentReplicationTarget extends ReplicationTarget { private final ReplicationCheckpoint checkpoint; private final SegmentReplicationSource source; private final SegmentReplicationState state; public SegmentReplicationTarget( ReplicationCheckpoint checkpoint, IndexShard indexShard, SegmentReplicationSource source, SegmentReplicationTargetService.SegmentReplicationListener listener ) { super("replication_target", indexShard, new ReplicationLuceneIndex(), listener); this.checkpoint = checkpoint; this.source = source; this.state = new SegmentReplicationState(); } @Override protected void closeInternal() { // TODO } @Override protected String getPrefix() { // TODO return null; } @Override protected void onDone() { this.state.setStage(SegmentReplicationState.Stage.DONE); } @Override protected void onCancel(String reason) { // TODO } @Override public ReplicationState state() { return state; } @Override public ReplicationTarget retryCopy() { // TODO return null; } @Override public String description() { // TODO return null; } @Override public void notifyListener(OpenSearchException e, boolean sendShardFailure) { listener.onFailure(state(), e, sendShardFailure); } @Override public boolean reset(CancellableThreads newTargetCancellableThreads) throws IOException { // TODO return false; } @Override public void writeFileChunk( StoreFileMetadata metadata, long position, BytesReference content, boolean lastChunk, int totalTranslogOps, ActionListener<Void> listener ) { // TODO } /** * Start the Replication event. * @param listener {@link ActionListener} listener. */ public void startReplication(ActionListener<Void> listener) { // TODO } }
package net.haesleinhuepf.clij2.converters.helptypes; public class Char1 { public char[] data; public Char1(char[] data) { this.data = data; } }
import java.util.*; import java.io.*; public class Main { public static void main(String[] arg) { new Main(); } public Main() { Scanner cin=new Scanner(new BufferedInputStream(System.in)); int m=cin.nextInt(),k=cin.nextInt(); int[] d=new int[m],s=new int[m]; for (int i=0;i<m;i++) { d[i]=cin.nextInt(); } for (int i=0;i<m;i++) { s[i]=cin.nextInt(); } int max=0,sum=0,ans=0; for (int i=0;i<m;i++) { if (max<s[i]) max=s[i]; sum+=s[i]; sum-=d[i]; while (sum<0) { sum+=max; ans+=k; } ans+=d[i]; } System.out.println(ans); cin.close(); } }
package org.zstack.sdk; import java.util.HashMap; import java.util.Map; import org.zstack.sdk.*; public class DeletePortForwardingRuleAction extends AbstractAction { private static final HashMap<String, Parameter> parameterMap = new HashMap<>(); private static final HashMap<String, Parameter> nonAPIParameterMap = new HashMap<>(); public static class Result { public ErrorCode error; public org.zstack.sdk.DeletePortForwardingRuleResult value; public Result throwExceptionIfError() { if (error != null) { throw new ApiException( String.format("error[code: %s, description: %s, details: %s]", error.code, error.description, error.details) ); } return this; } } @Param(required = true, nonempty = false, nullElements = false, emptyString = true, noTrim = false) public java.lang.String uuid; @Param(required = false) public java.lang.String deleteMode = "Permissive"; @Param(required = false) public java.util.List systemTags; @Param(required = false) public java.util.List userTags; @Param(required = true) public String sessionId; @NonAPIParam public long timeout = -1; @NonAPIParam public long pollingInterval = -1; private Result makeResult(ApiResult res) { Result ret = new Result(); if (res.error != null) { ret.error = res.error; return ret; } org.zstack.sdk.DeletePortForwardingRuleResult value = res.getResult(org.zstack.sdk.DeletePortForwardingRuleResult.class); ret.value = value == null ? new org.zstack.sdk.DeletePortForwardingRuleResult() : value; return ret; } public Result call() { ApiResult res = ZSClient.call(this); return makeResult(res); } public void call(final Completion<Result> completion) { ZSClient.call(this, new InternalCompletion() { @Override public void complete(ApiResult res) { completion.complete(makeResult(res)); } }); } protected Map<String, Parameter> getParameterMap() { return parameterMap; } protected Map<String, Parameter> getNonAPIParameterMap() { return nonAPIParameterMap; } protected RestInfo getRestInfo() { RestInfo info = new RestInfo(); info.httpMethod = "DELETE"; info.path = "/port-forwarding/{uuid}"; info.needSession = true; info.needPoll = true; info.parameterName = ""; return info; } }
package com.dream.work.entity; /** * Created by Dream on 2017/3/3. */ public class UserInfo { //用户id private int uid; //用户昵称 private String uname; // 用户手机 private long mobile; // 用户个性签名 private String uintro; // 用户头像地址 private String uavatar; // 用户年龄 private int age; // 用户性别 private String gender; // 用户学校 private String school; //用户的技能(标签) private String tag; //用户所在经度 private double longitude; //用户所在纬度 private double latitude; public double getLongitude() { return longitude; } public void setLongitude(double longitude) { this.longitude = longitude; } public double getLatitude() { return latitude; } public void setLatitude(double latitude) { this.latitude = latitude; } public UserInfo(String uname, Long mobile, String uintro, String uavatar, Integer age, String gender, String school, String tag, double longitude, double latitude) { this.uname = uname; this.mobile = mobile; this.uintro = uintro; this.uavatar = uavatar; this.age = age; this.gender = gender; this.school = school; this.tag = tag; this.latitude = latitude; this.longitude = longitude; } public UserInfo() { } public UserInfo(int uid, String uname, long mobile, String uintro, String uavatar, Integer age, String gender, String school, String tag, double longitude, double latitude) { this.uid = uid; this.uname = uname; this.mobile = mobile; this.uintro = uintro; this.uavatar = uavatar; this.age = age; this.gender = gender; this.school = school; this.tag = tag; this.longitude = longitude; this.latitude = latitude; } @Override public String toString() { return "UserInfo{" + "uid=" + uid + ", uname='" + uname + '\'' + ", mobile=" + mobile + ", uintro='" + uintro + '\'' + ", uavatar='" + uavatar + '\'' + ", age=" + age + ", gender='" + gender + '\'' + ", school='" + school + '\'' + ", tag='" + tag + '}'; } public String getTag() { return tag; } public void setTag(String tag) { this.tag = tag; } public int getUid() { return uid; } public void setUid(int uid) { this.uid = uid; } public String getUname() { return uname; } public void setUname(String uname) { this.uname = uname; } public long getMobile() { return mobile; } public void setMobile(long mobile) { this.mobile = mobile; } public String getUintro() { return uintro; } public void setUintro(String uintro) { this.uintro = uintro; } public String getUavatar() { return uavatar; } public void setUavatar(String uavatar) { this.uavatar = uavatar; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getSchool() { return school; } public void setSchool(String school) { this.school = school; } }
/* * 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.alibaba.dubbo.common.bytecode; import com.alibaba.dubbo.common.utils.ClassHelper; import com.alibaba.dubbo.common.utils.ReflectUtils; import java.lang.ref.Reference; import java.lang.ref.WeakReference; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.WeakHashMap; import java.util.concurrent.atomic.AtomicLong; /** * Proxy. */ public abstract class Proxy { public static final InvocationHandler RETURN_NULL_INVOKER = new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) { return null; } }; public static final InvocationHandler THROW_UNSUPPORTED_INVOKER = new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) { throw new UnsupportedOperationException("Method [" + ReflectUtils.getName(method) + "] unimplemented."); } }; /** * Proxy Class 计数,用于生成 Proxy 类名自增。 */ private static final AtomicLong PROXY_CLASS_COUNTER = new AtomicLong(0); /** * 包名 */ private static final String PACKAGE_NAME = Proxy.class.getPackage().getName(); /** * Proxy 对象缓存 * key :ClassLoader * value.key :Proxy 标识。使用 Proxy 实现接口名拼接 * value.value :Proxy 对象 */ private static final Map<ClassLoader, Map<String, Object>> ProxyCacheMap = new WeakHashMap<ClassLoader, Map<String, Object>>(); private static final Object PendingGenerationMarker = new Object(); protected Proxy() { } /** * Get proxy. * * @param ics interface class array. * @return Proxy instance. */ public static Proxy getProxy(Class<?>... ics) { return getProxy(ClassHelper.getClassLoader(Proxy.class), ics); } /** * Get proxy. * * @param cl class loader. * @param ics interface class array. * @return Proxy instance. */ public static Proxy getProxy(ClassLoader cl, Class<?>... ics) { // 校验接口超过上限 if (ics.length > 65535) throw new IllegalArgumentException("interface limit exceeded"); // use interface class name list as key. StringBuilder sb = new StringBuilder(); for (int i = 0; i < ics.length; i++) { String itf = ics[i].getName(); // 校验是否为接口 if (!ics[i].isInterface()) throw new RuntimeException(itf + " is not a interface."); // 加载接口类 Class<?> tmp = null; try { tmp = Class.forName(itf, false, cl); } catch (ClassNotFoundException e) { } if (tmp != ics[i]) // 加载接口类失败 throw new IllegalArgumentException(ics[i] + " is not visible from class loader"); sb.append(itf).append(';'); } // use interface class name list as key. String key = sb.toString(); // get cache by class loader. Map<String, Object> cache; synchronized (ProxyCacheMap) { cache = ProxyCacheMap.get(cl); if (cache == null) { cache = new HashMap<String, Object>(); ProxyCacheMap.put(cl, cache); } } // 获得 Proxy Proxy proxy = null; synchronized (cache) { do { // 从缓存中获取 Proxy Object value = cache.get(key); if (value instanceof Reference<?>) { proxy = (Proxy) ((Reference<?>) value).get(); if (proxy != null) return proxy; } // 缓存中不存在,设置生成 Proxy 代码标记。创建中时,其他创建请求等待,避免并发。 if (value == PendingGenerationMarker) { try { cache.wait(); } catch (InterruptedException e) { } } else { cache.put(key, PendingGenerationMarker); break; } } while (true); } long id = PROXY_CLASS_COUNTER.getAndIncrement(); String pkg = null; ClassGenerator ccp = null, // proxy class generator ccm = null; // Proxy class generator try { // 创建 proxy 代码生成器 ccp = ClassGenerator.newInstance(cl); Set<String> worked = new HashSet<String>(); // 已处理方法签名集合。key:方法签名 List<Method> methods = new ArrayList<Method>(); // 已处理方法集合。 // 处理接口 for (int i = 0; i < ics.length; i++) { // 非 public 接口,使用接口包名 if (!Modifier.isPublic(ics[i].getModifiers())) { String npkg = ics[i].getPackage().getName(); if (pkg == null) { pkg = npkg; } else { if (!pkg.equals(npkg)) // 实现了两个非 public 的接口, throw new IllegalArgumentException("non-public interfaces from different packages"); } } // 添加接口 ccp.addInterface(ics[i]); // 处理接口方法 for (Method method : ics[i].getMethods()) { // 添加方法签名到已处理方法签名集合 String desc = ReflectUtils.getDesc(method); if (worked.contains(desc)) continue; worked.add(desc); // 生成接口方法实现代码 int ix = methods.size(); Class<?> rt = method.getReturnType(); Class<?>[] pts = method.getParameterTypes(); StringBuilder code = new StringBuilder("Object[] args = new Object[").append(pts.length).append("];"); for (int j = 0; j < pts.length; j++) code.append(" args[").append(j).append("] = ($w)$").append(j + 1).append(";"); code.append(" Object ret = handler.invoke(this, methods[" + ix + "], args);"); if (!Void.TYPE.equals(rt)) code.append(" return ").append(asArgument(rt, "ret")).append(";"); methods.add(method); // 添加方法 ccp.addMethod(method.getName(), method.getModifiers(), rt, pts, method.getExceptionTypes(), code.toString()); } } // 设置包路径 if (pkg == null) pkg = PACKAGE_NAME; // ===== 设置 proxy 代码生成的属性 ===== // create ProxyInstance class. // 设置类名 String pcn = pkg + ".proxy" + id; ccp.setClassName(pcn); // 添加静态属性 methods ccp.addField("public static java.lang.reflect.Method[] methods;"); // 添加属性 handler ccp.addField("private " + InvocationHandler.class.getName() + " handler;"); // 添加构造方法,参数 handler ccp.addConstructor(Modifier.PUBLIC, new Class<?>[]{InvocationHandler.class}, new Class<?>[0], "handler=$1;"); // 添加构造方法,参数 空 ccp.addDefaultConstructor(); // 生成类 Class<?> clazz = ccp.toClass(); // 设置静态属性 methods clazz.getField("methods").set(null, methods.toArray(new Method[0])); // create Proxy class. // 创建 Proxy 代码生成器 String fcn = Proxy.class.getName() + id; ccm = ClassGenerator.newInstance(cl); // 设置类名 ccm.setClassName(fcn); // 添加构造方法,参数 空 ccm.addDefaultConstructor(); // 设置父类为 Proxy.class ccm.setSuperClass(Proxy.class); // 添加方法 #newInstance(handler) ccm.addMethod("public Object newInstance(" + InvocationHandler.class.getName() + " h){ return new " + pcn + "($1); }"); // 生成类 Class<?> pc = ccm.toClass(); // 创建 Proxy 对象 proxy = (Proxy) pc.newInstance(); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } finally { // release ClassGenerator if (ccp != null) ccp.release(); if (ccm != null) ccm.release(); // 唤醒缓存 wait synchronized (cache) { if (proxy == null) cache.remove(key); else cache.put(key, new WeakReference<Proxy>(proxy)); cache.notifyAll(); } } return proxy; } private static String asArgument(Class<?> cl, String name) { if (cl.isPrimitive()) { if (Boolean.TYPE == cl) return name + "==null?false:((Boolean)" + name + ").booleanValue()"; if (Byte.TYPE == cl) return name + "==null?(byte)0:((Byte)" + name + ").byteValue()"; if (Character.TYPE == cl) return name + "==null?(char)0:((Character)" + name + ").charValue()"; if (Double.TYPE == cl) return name + "==null?(double)0:((Double)" + name + ").doubleValue()"; if (Float.TYPE == cl) return name + "==null?(float)0:((Float)" + name + ").floatValue()"; if (Integer.TYPE == cl) return name + "==null?(int)0:((Integer)" + name + ").intValue()"; if (Long.TYPE == cl) return name + "==null?(long)0:((Long)" + name + ").longValue()"; if (Short.TYPE == cl) return name + "==null?(short)0:((Short)" + name + ").shortValue()"; throw new RuntimeException(name + " is unknown primitive type."); } return "(" + ReflectUtils.getName(cl) + ")" + name; } /** * get instance with default handler. * * @return instance. */ public Object newInstance() { return newInstance(THROW_UNSUPPORTED_INVOKER); } /** * get instance with special handler. * * @return instance. */ abstract public Object newInstance(InvocationHandler handler); }
/* * 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.plc4x.java.spi.codegen.fields; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.NotImplementedException; import org.apache.plc4x.java.spi.codegen.FieldCommons; import org.apache.plc4x.java.spi.codegen.io.DataReader; import org.apache.plc4x.java.spi.codegen.io.ParseSupplier; import org.apache.plc4x.java.spi.generation.ParseException; import org.apache.plc4x.java.spi.generation.ReadBuffer; import org.apache.plc4x.java.spi.generation.WithReaderArgs; import org.apache.plc4x.java.spi.generation.WithReaderWriterArgs; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; import java.util.function.Supplier; public class FieldReaderManualArray<T> implements FieldCommons { public byte[] readManualByteArrayField(String logicalName, ReadBuffer readBuffer, Supplier<Boolean> termination, ParseSupplier<T> parse, WithReaderArgs... readerArgs) throws ParseException { // Ensure we have the render as list argument present readerArgs = ArrayUtils.add(readerArgs, WithReaderWriterArgs.WithRenderAsList(true)); readBuffer.pullContext(logicalName, readerArgs); List<Byte> result = new ArrayList<>(); while (!termination.get()) { result.add((Byte) parse.get()); } readBuffer.closeContext(logicalName, readerArgs); return ArrayUtils.toPrimitive(result.toArray(new Byte[0])); } public List<T> readManualArrayField(String logicalName, ReadBuffer readBuffer, Supplier<Boolean> termination, ParseSupplier<T> parse, WithReaderArgs... readerArgs) throws ParseException { // Ensure we have the render as list argument present readerArgs = ArrayUtils.add(readerArgs, WithReaderWriterArgs.WithRenderAsList(true)); readBuffer.pullContext(logicalName, readerArgs); List<T> result = new ArrayList<>(); while (!termination.get()) { result.add(parse.get()); } readBuffer.closeContext(logicalName, readerArgs); return result; } }
package shittymcsuggestions.mixin.block; import net.minecraft.block.Block; import net.minecraft.block.Blocks; import net.minecraft.block.PistonBlock; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Redirect; import shittymcsuggestions.block.ICustomPiston; @Mixin(PistonBlock.class) public class MixinPistonBlock { @Redirect(method = "move", at = @At(value = "FIELD", target = "Lnet/minecraft/block/Blocks;PISTON_HEAD:Lnet/minecraft/block/Block;")) private Block getPistonHeadBlock() { return this instanceof ICustomPiston ? ((ICustomPiston) this).getCustomPistonHeadBlock() : Blocks.PISTON_HEAD; } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/speech/v1beta1/cloud_speech.proto package com.google.cloud.speech.v1beta1; public final class SpeechProto { private SpeechProto() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistryLite registry) { } public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { registerAllExtensions( (com.google.protobuf.ExtensionRegistryLite) registry); } static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_speech_v1beta1_SyncRecognizeRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_speech_v1beta1_SyncRecognizeRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_speech_v1beta1_AsyncRecognizeRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_speech_v1beta1_AsyncRecognizeRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_speech_v1beta1_StreamingRecognizeRequest_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_speech_v1beta1_StreamingRecognizeRequest_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_speech_v1beta1_StreamingRecognitionConfig_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_speech_v1beta1_StreamingRecognitionConfig_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_speech_v1beta1_RecognitionConfig_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_speech_v1beta1_RecognitionConfig_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_speech_v1beta1_SpeechContext_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_speech_v1beta1_SpeechContext_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_speech_v1beta1_RecognitionAudio_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_speech_v1beta1_RecognitionAudio_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_speech_v1beta1_SyncRecognizeResponse_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_speech_v1beta1_SyncRecognizeResponse_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_speech_v1beta1_AsyncRecognizeResponse_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_speech_v1beta1_AsyncRecognizeResponse_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_speech_v1beta1_AsyncRecognizeMetadata_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_speech_v1beta1_AsyncRecognizeMetadata_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_speech_v1beta1_StreamingRecognizeResponse_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_speech_v1beta1_StreamingRecognizeResponse_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_speech_v1beta1_StreamingRecognitionResult_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_speech_v1beta1_StreamingRecognitionResult_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_speech_v1beta1_SpeechRecognitionResult_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_speech_v1beta1_SpeechRecognitionResult_fieldAccessorTable; static final com.google.protobuf.Descriptors.Descriptor internal_static_google_cloud_speech_v1beta1_SpeechRecognitionAlternative_descriptor; static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_google_cloud_speech_v1beta1_SpeechRecognitionAlternative_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n.google/cloud/speech/v1beta1/cloud_spee" + "ch.proto\022\033google.cloud.speech.v1beta1\032\034g" + "oogle/api/annotations.proto\032#google/long" + "running/operations.proto\032\036google/protobu" + "f/duration.proto\032\037google/protobuf/timest" + "amp.proto\032\027google/rpc/status.proto\"\224\001\n\024S" + "yncRecognizeRequest\022>\n\006config\030\001 \001(\0132..go" + "ogle.cloud.speech.v1beta1.RecognitionCon" + "fig\022<\n\005audio\030\002 \001(\0132-.google.cloud.speech" + ".v1beta1.RecognitionAudio\"\225\001\n\025AsyncRecog", "nizeRequest\022>\n\006config\030\001 \001(\0132..google.clo" + "ud.speech.v1beta1.RecognitionConfig\022<\n\005a" + "udio\030\002 \001(\0132-.google.cloud.speech.v1beta1" + ".RecognitionAudio\"\236\001\n\031StreamingRecognize" + "Request\022S\n\020streaming_config\030\001 \001(\01327.goog" + "le.cloud.speech.v1beta1.StreamingRecogni" + "tionConfigH\000\022\027\n\raudio_content\030\002 \001(\014H\000B\023\n" + "\021streaming_request\"\217\001\n\032StreamingRecognit" + "ionConfig\022>\n\006config\030\001 \001(\0132..google.cloud" + ".speech.v1beta1.RecognitionConfig\022\030\n\020sin", "gle_utterance\030\002 \001(\010\022\027\n\017interim_results\030\003" + " \001(\010\"\352\002\n\021RecognitionConfig\022N\n\010encoding\030\001" + " \001(\0162<.google.cloud.speech.v1beta1.Recog" + "nitionConfig.AudioEncoding\022\023\n\013sample_rat" + "e\030\002 \001(\005\022\025\n\rlanguage_code\030\003 \001(\t\022\030\n\020max_al" + "ternatives\030\004 \001(\005\022\030\n\020profanity_filter\030\005 \001" + "(\010\022B\n\016speech_context\030\006 \001(\0132*.google.clou" + "d.speech.v1beta1.SpeechContext\"a\n\rAudioE" + "ncoding\022\030\n\024ENCODING_UNSPECIFIED\020\000\022\014\n\010LIN" + "EAR16\020\001\022\010\n\004FLAC\020\002\022\t\n\005MULAW\020\003\022\007\n\003AMR\020\004\022\n\n", "\006AMR_WB\020\005\" \n\rSpeechContext\022\017\n\007phrases\030\001 " + "\003(\t\"D\n\020RecognitionAudio\022\021\n\007content\030\001 \001(\014" + "H\000\022\r\n\003uri\030\002 \001(\tH\000B\016\n\014audio_source\"^\n\025Syn" + "cRecognizeResponse\022E\n\007results\030\002 \003(\01324.go" + "ogle.cloud.speech.v1beta1.SpeechRecognit" + "ionResult\"_\n\026AsyncRecognizeResponse\022E\n\007r" + "esults\030\002 \003(\01324.google.cloud.speech.v1bet" + "a1.SpeechRecognitionResult\"\230\001\n\026AsyncReco" + "gnizeMetadata\022\030\n\020progress_percent\030\001 \001(\005\022" + ".\n\nstart_time\030\002 \001(\0132\032.google.protobuf.Ti", "mestamp\0224\n\020last_update_time\030\003 \001(\0132\032.goog" + "le.protobuf.Timestamp\"\205\003\n\032StreamingRecog" + "nizeResponse\022!\n\005error\030\001 \001(\0132\022.google.rpc" + ".Status\022H\n\007results\030\002 \003(\01327.google.cloud." + "speech.v1beta1.StreamingRecognitionResul" + "t\022\024\n\014result_index\030\003 \001(\005\022_\n\017endpointer_ty" + "pe\030\004 \001(\0162F.google.cloud.speech.v1beta1.S" + "treamingRecognizeResponse.EndpointerType" + "\"\202\001\n\016EndpointerType\022 \n\034ENDPOINTER_EVENT_" + "UNSPECIFIED\020\000\022\023\n\017START_OF_SPEECH\020\001\022\021\n\rEN", "D_OF_SPEECH\020\002\022\020\n\014END_OF_AUDIO\020\003\022\024\n\020END_O" + "F_UTTERANCE\020\004\"\222\001\n\032StreamingRecognitionRe" + "sult\022O\n\014alternatives\030\001 \003(\01329.google.clou" + "d.speech.v1beta1.SpeechRecognitionAltern" + "ative\022\020\n\010is_final\030\002 \001(\010\022\021\n\tstability\030\003 \001" + "(\002\"j\n\027SpeechRecognitionResult\022O\n\014alterna" + "tives\030\001 \003(\01329.google.cloud.speech.v1beta" + "1.SpeechRecognitionAlternative\"F\n\034Speech" + "RecognitionAlternative\022\022\n\ntranscript\030\001 \001" + "(\t\022\022\n\nconfidence\030\002 \001(\0022\310\003\n\006Speech\022\240\001\n\rSy", "ncRecognize\0221.google.cloud.speech.v1beta" + "1.SyncRecognizeRequest\0322.google.cloud.sp" + "eech.v1beta1.SyncRecognizeResponse\"(\202\323\344\223" + "\002\"\"\035/v1beta1/speech:syncrecognize:\001*\022\216\001\n" + "\016AsyncRecognize\0222.google.cloud.speech.v1" + "beta1.AsyncRecognizeRequest\032\035.google.lon" + "grunning.Operation\")\202\323\344\223\002#\"\036/v1beta1/spe" + "ech:asyncrecognize:\001*\022\211\001\n\022StreamingRecog" + "nize\0226.google.cloud.speech.v1beta1.Strea" + "mingRecognizeRequest\0327.google.cloud.spee", "ch.v1beta1.StreamingRecognizeResponse(\0010" + "\001Bs\n\037com.google.cloud.speech.v1beta1B\013Sp" + "eechProtoP\001ZAgoogle.golang.org/genproto/" + "googleapis/cloud/speech/v1beta1;speechb\006" + "proto3" }; com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() { public com.google.protobuf.ExtensionRegistry assignDescriptors( com.google.protobuf.Descriptors.FileDescriptor root) { descriptor = root; return null; } }; com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { com.google.api.AnnotationsProto.getDescriptor(), com.google.longrunning.OperationsProto.getDescriptor(), com.google.protobuf.DurationProto.getDescriptor(), com.google.protobuf.TimestampProto.getDescriptor(), com.google.rpc.StatusProto.getDescriptor(), }, assigner); internal_static_google_cloud_speech_v1beta1_SyncRecognizeRequest_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_google_cloud_speech_v1beta1_SyncRecognizeRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_speech_v1beta1_SyncRecognizeRequest_descriptor, new java.lang.String[] { "Config", "Audio", }); internal_static_google_cloud_speech_v1beta1_AsyncRecognizeRequest_descriptor = getDescriptor().getMessageTypes().get(1); internal_static_google_cloud_speech_v1beta1_AsyncRecognizeRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_speech_v1beta1_AsyncRecognizeRequest_descriptor, new java.lang.String[] { "Config", "Audio", }); internal_static_google_cloud_speech_v1beta1_StreamingRecognizeRequest_descriptor = getDescriptor().getMessageTypes().get(2); internal_static_google_cloud_speech_v1beta1_StreamingRecognizeRequest_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_speech_v1beta1_StreamingRecognizeRequest_descriptor, new java.lang.String[] { "StreamingConfig", "AudioContent", "StreamingRequest", }); internal_static_google_cloud_speech_v1beta1_StreamingRecognitionConfig_descriptor = getDescriptor().getMessageTypes().get(3); internal_static_google_cloud_speech_v1beta1_StreamingRecognitionConfig_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_speech_v1beta1_StreamingRecognitionConfig_descriptor, new java.lang.String[] { "Config", "SingleUtterance", "InterimResults", }); internal_static_google_cloud_speech_v1beta1_RecognitionConfig_descriptor = getDescriptor().getMessageTypes().get(4); internal_static_google_cloud_speech_v1beta1_RecognitionConfig_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_speech_v1beta1_RecognitionConfig_descriptor, new java.lang.String[] { "Encoding", "SampleRate", "LanguageCode", "MaxAlternatives", "ProfanityFilter", "SpeechContext", }); internal_static_google_cloud_speech_v1beta1_SpeechContext_descriptor = getDescriptor().getMessageTypes().get(5); internal_static_google_cloud_speech_v1beta1_SpeechContext_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_speech_v1beta1_SpeechContext_descriptor, new java.lang.String[] { "Phrases", }); internal_static_google_cloud_speech_v1beta1_RecognitionAudio_descriptor = getDescriptor().getMessageTypes().get(6); internal_static_google_cloud_speech_v1beta1_RecognitionAudio_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_speech_v1beta1_RecognitionAudio_descriptor, new java.lang.String[] { "Content", "Uri", "AudioSource", }); internal_static_google_cloud_speech_v1beta1_SyncRecognizeResponse_descriptor = getDescriptor().getMessageTypes().get(7); internal_static_google_cloud_speech_v1beta1_SyncRecognizeResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_speech_v1beta1_SyncRecognizeResponse_descriptor, new java.lang.String[] { "Results", }); internal_static_google_cloud_speech_v1beta1_AsyncRecognizeResponse_descriptor = getDescriptor().getMessageTypes().get(8); internal_static_google_cloud_speech_v1beta1_AsyncRecognizeResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_speech_v1beta1_AsyncRecognizeResponse_descriptor, new java.lang.String[] { "Results", }); internal_static_google_cloud_speech_v1beta1_AsyncRecognizeMetadata_descriptor = getDescriptor().getMessageTypes().get(9); internal_static_google_cloud_speech_v1beta1_AsyncRecognizeMetadata_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_speech_v1beta1_AsyncRecognizeMetadata_descriptor, new java.lang.String[] { "ProgressPercent", "StartTime", "LastUpdateTime", }); internal_static_google_cloud_speech_v1beta1_StreamingRecognizeResponse_descriptor = getDescriptor().getMessageTypes().get(10); internal_static_google_cloud_speech_v1beta1_StreamingRecognizeResponse_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_speech_v1beta1_StreamingRecognizeResponse_descriptor, new java.lang.String[] { "Error", "Results", "ResultIndex", "EndpointerType", }); internal_static_google_cloud_speech_v1beta1_StreamingRecognitionResult_descriptor = getDescriptor().getMessageTypes().get(11); internal_static_google_cloud_speech_v1beta1_StreamingRecognitionResult_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_speech_v1beta1_StreamingRecognitionResult_descriptor, new java.lang.String[] { "Alternatives", "IsFinal", "Stability", }); internal_static_google_cloud_speech_v1beta1_SpeechRecognitionResult_descriptor = getDescriptor().getMessageTypes().get(12); internal_static_google_cloud_speech_v1beta1_SpeechRecognitionResult_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_speech_v1beta1_SpeechRecognitionResult_descriptor, new java.lang.String[] { "Alternatives", }); internal_static_google_cloud_speech_v1beta1_SpeechRecognitionAlternative_descriptor = getDescriptor().getMessageTypes().get(13); internal_static_google_cloud_speech_v1beta1_SpeechRecognitionAlternative_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable( internal_static_google_cloud_speech_v1beta1_SpeechRecognitionAlternative_descriptor, new java.lang.String[] { "Transcript", "Confidence", }); com.google.protobuf.ExtensionRegistry registry = com.google.protobuf.ExtensionRegistry.newInstance(); registry.add(com.google.api.AnnotationsProto.http); com.google.protobuf.Descriptors.FileDescriptor .internalUpdateFileDescriptor(descriptor, registry); com.google.api.AnnotationsProto.getDescriptor(); com.google.longrunning.OperationsProto.getDescriptor(); com.google.protobuf.DurationProto.getDescriptor(); com.google.protobuf.TimestampProto.getDescriptor(); com.google.rpc.StatusProto.getDescriptor(); } // @@protoc_insertion_point(outer_class_scope) }
/*- * ============LICENSE_START======================================================= * SDC * ================================================================================ * Copyright (C) 2017 AT&T Intellectual Property. 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. * ============LICENSE_END========================================================= */ package org.openecomp.sdc.be.dao.neo4j.filters; import java.util.HashMap; import java.util.Map; public class MatchFilter { private Map<String, Object> toMatchProperties; public MatchFilter() { toMatchProperties = new HashMap<>(); } public MatchFilter(Map<String, Object> toMatchProperties) { super(); this.toMatchProperties = toMatchProperties; } public Map<String, Object> getProperties() { return toMatchProperties; } public void setProperties(Map<String, Object> properties) { this.toMatchProperties = properties; } public MatchFilter addToMatch(String propName, Object value) { toMatchProperties.put(propName, value); return this; } }
/* * 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.directory.fortress.web.panel; import org.apache.commons.lang.StringUtils; import org.apache.directory.fortress.web.control.SecUtils; import org.apache.directory.fortress.web.event.SelectModelEvent; import org.apache.log4j.Logger; import org.apache.wicket.Component; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.event.IEvent; import org.apache.wicket.markup.html.basic.Label; import org.apache.wicket.markup.html.form.Form; import org.apache.wicket.markup.html.form.FormComponentPanel; import org.apache.wicket.model.CompoundPropertyModel; import org.apache.wicket.model.IModel; import org.apache.wicket.spring.injection.annot.SpringBean; import org.apache.directory.fortress.web.common.GlobalIds; import org.apache.directory.fortress.core.*; import org.apache.directory.fortress.core.model.Bind; import org.apache.directory.fortress.core.model.User; /** * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> * @version $Rev$ * Date: 8/11/13 */ public class AuditBindDetailPanel extends FormComponentPanel { /** Default serialVersionUID */ private static final long serialVersionUID = 1L; @SpringBean private AuditMgr auditMgr; @SpringBean private ReviewMgr reviewMgr; private static final Logger LOG = Logger.getLogger( AuditBindDetailPanel.class.getName() ); private Form detailForm; private Displayable display; private UserAuditDetailPanel userPanel; public Form getForm() { return this.detailForm; } public AuditBindDetailPanel( String id, Displayable display ) { super( id ); this.auditMgr.setAdmin( SecUtils.getSession( this ) ); this.reviewMgr.setAdmin( SecUtils.getSession( this ) ); this.detailForm = new AuditBindDetailForm( GlobalIds.DETAIL_FIELDS, new CompoundPropertyModel<>( new Bind() ) ); this.display = display; add( detailForm ); } public class AuditBindDetailForm extends Form { /** Default serialVersionUID */ private static final long serialVersionUID = 1L; private Component component; public AuditBindDetailForm( String id, final IModel<Bind> model ) { super( id, model ); add( new Label( GlobalIds.REQ_DN ) ); add( new Label( GlobalIds.REQ_RESULT ) ); add( new Label( GlobalIds.REQ_START ) ); userPanel = new UserAuditDetailPanel( GlobalIds.USERAUDITDETAILPANEL, new CompoundPropertyModel<>( new User() ) ); add( userPanel ); setOutputMarkupId( true ); } @Override public void onEvent( final IEvent<?> event ) { if ( event.getPayload() instanceof SelectModelEvent ) { SelectModelEvent modelEvent = ( SelectModelEvent ) event.getPayload(); Bind bind = ( Bind ) modelEvent.getEntity(); this.setModelObject( bind ); String msg = "Bind: " + bind.getReqDN() + " has been selected"; LOG.debug( ".onEvent SelectModelEvent: " + bind.getReqDN() ); display.setMessage( msg ); component = detailForm; } else if ( event.getPayload() instanceof AjaxRequestTarget ) { // only add the form to ajax target if something has changed... if ( component != null ) { AjaxRequestTarget target = ( ( AjaxRequestTarget ) event.getPayload() ); LOG.debug( ".onEvent AjaxRequestTarget: " + target.toString() ); target.add( component ); component = null; } display.display( ( AjaxRequestTarget ) event.getPayload() ); } } @Override protected void onBeforeRender() { if ( getModel() != null ) { User user = null; // necessary to push the 'changed' model down into the aggregated panel: Bind bind = ( Bind ) detailForm.getModelObject(); if ( StringUtils.isNotBlank( bind.getReqDN() ) ) { user = AuditUtils.getUser( reviewMgr, bind.getReqDN() ); } if ( user == null ) { user = new User(); } IModel<User> userModel = new CompoundPropertyModel<>( user ); userPanel.setDefaultModel( userModel ); } else { LOG.info( ".onBeforeRender null model object" ); } super.onBeforeRender(); } } }
/* * 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.asterix.geo.evaluators.functions; import com.esri.core.geometry.ogc.OGCGeometry; import org.apache.asterix.om.functions.BuiltinFunctions; import org.apache.asterix.om.functions.IFunctionDescriptor; import org.apache.asterix.om.functions.IFunctionDescriptorFactory; import org.apache.hyracks.algebricks.core.algebra.functions.FunctionIdentifier; import org.apache.hyracks.api.exceptions.HyracksDataException; public class STZMaxDescriptor extends AbstractSTSingleGeometryDescriptor { private static final long serialVersionUID = 1L; public static final IFunctionDescriptorFactory FACTORY = new IFunctionDescriptorFactory() { @Override public IFunctionDescriptor createFunctionDescriptor() { return new STZMaxDescriptor(); } }; @Override protected Object evaluateOGCGeometry(OGCGeometry geometry) throws HyracksDataException { return geometry.MaxZ(); } @Override public FunctionIdentifier getIdentifier() { return BuiltinFunctions.ST_Z_MAX; } }
// Tags: JDK1.4 // Copyright (C) 2004 David Gilbert (david.gilbert@object-refinery.com) // This file is part of Mauve. // Mauve is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2, or (at your option) // any later version. // Mauve is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Mauve; see the file COPYING. If not, write to // the Free Software Foundation, 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. */ package gnu.testlet.java.util.SimpleTimeZone; import gnu.testlet.TestHarness; import gnu.testlet.Testlet; import java.util.Calendar; import java.util.SimpleTimeZone; import java.util.TimeZone; /** * Some checks for the hasSameRules() method in the SimpleTimeZone class. */ public class hasSameRules implements Testlet { /** * Runs the tests. * * @param harness the test harness. */ public void test(TestHarness harness) { test1(harness); test2(harness); } private void test1(TestHarness harness) { SimpleTimeZone z1 = new SimpleTimeZone(5 * 60 * 60 * 1000, "Z1"); harness.check(!z1.hasSameRules(null)); SimpleTimeZone z2 = new SimpleTimeZone(5 * 60 * 60 * 1000, "Z1"); harness.check(z1.hasSameRules(z2)); // check 1 harness.check(z2.hasSameRules(z1)); // check 2 int rawOffset1 = 5 * 60 * 60 * 1000; int rawOffset2 = 6 * 60 * 60 * 1000; int time1 = 2 * 60 * 60 * 1000; int time2 = 3 * 60 * 60 * 1000; z1 = new SimpleTimeZone(rawOffset1, "Z1", Calendar.APRIL, 5, 0, time1, Calendar.SEPTEMBER, 15, 0, time2, 3600000); z2 = new SimpleTimeZone(rawOffset1, "Z2", Calendar.APRIL, 5, 0, time1, Calendar.SEPTEMBER, 15, 0, time2, 3600000); harness.check(z1.hasSameRules(z2)); // check 3 z1 = new SimpleTimeZone(rawOffset2, "Z1", Calendar.APRIL, 5, 0, time1, Calendar.SEPTEMBER, 15, 0, time2, 3600000); harness.check(!z1.hasSameRules(z2)); // check 4 z2 = new SimpleTimeZone(rawOffset2, "Z2", Calendar.APRIL, 5, 0, time1, Calendar.SEPTEMBER, 15, 0, time2, 3600000); harness.check(z1.hasSameRules(z2)); // check 5 z1 = new SimpleTimeZone(rawOffset2, "Z1", Calendar.MAY, 5, 0, time1, Calendar.SEPTEMBER, 15, 0, time2, 3600000); harness.check(!z1.hasSameRules(z2)); // check 6 z2 = new SimpleTimeZone(rawOffset2, "Z2", Calendar.MAY, 5, 0, time1, Calendar.SEPTEMBER, 15, 0, time2, 3600000); harness.check(z1.hasSameRules(z2)); // check 7 z1 = new SimpleTimeZone(rawOffset2, "Z1", Calendar.MAY, 6, 0, time1, Calendar.SEPTEMBER, 15, 0, time2, 3600000); harness.check(!z1.hasSameRules(z2)); // check 8 z2 = new SimpleTimeZone(rawOffset2, "Z2", Calendar.MAY, 6, 0, time1, Calendar.SEPTEMBER, 15, 0, time2, 3600000); harness.check(z1.hasSameRules(z2)); // check 9 z1 = new SimpleTimeZone(rawOffset2, "Z1", Calendar.MAY, 6, 0, time2, Calendar.SEPTEMBER, 15, 0, time2, 3600000); harness.check(!z1.hasSameRules(z2)); // check 10 z2 = new SimpleTimeZone(rawOffset2, "Z2", Calendar.MAY, 6, 0, time2, Calendar.SEPTEMBER, 15, 0, time2, 3600000); harness.check(z1.hasSameRules(z2)); // check 11 z1 = new SimpleTimeZone(rawOffset2, "Z1", Calendar.MAY, 6, 0, time2, Calendar.OCTOBER, 15, 0, time2, 3600000); harness.check(!z1.hasSameRules(z2)); // check 12 z2 = new SimpleTimeZone(rawOffset2, "Z2", Calendar.MAY, 6, 0, time2, Calendar.OCTOBER, 15, 0, time2, 3600000); harness.check(z1.hasSameRules(z2)); // check 13 z1 = new SimpleTimeZone(rawOffset2, "Z1", Calendar.MAY, 6, 0, time2, Calendar.OCTOBER, 16, 0, time2, 3600000); harness.check(!z1.hasSameRules(z2)); // check 14 z2 = new SimpleTimeZone(rawOffset2, "Z2", Calendar.MAY, 6, 0, time2, Calendar.OCTOBER, 16, 0, time2, 3600000); harness.check(z1.hasSameRules(z2)); // check 15 z1 = new SimpleTimeZone(rawOffset2, "Z1", Calendar.MAY, 6, 0, time2, Calendar.OCTOBER, 16, 0, time1, 3600000); harness.check(!z1.hasSameRules(z2)); // check 16 z2 = new SimpleTimeZone(rawOffset2, "Z1", Calendar.MAY, 6, 0, time2, Calendar.OCTOBER, 16, 0, time1, 3600000); harness.check(z1.hasSameRules(z2)); // check 17 z1 = new SimpleTimeZone(rawOffset2, "Z1", Calendar.MAY, 6, 0, time2, Calendar.OCTOBER, 16, 0, time1, 3600001); harness.check(!z1.hasSameRules(z2)); // check 18 z2 = new SimpleTimeZone(rawOffset2, "Z2", Calendar.MAY, 6, 0, time2, Calendar.OCTOBER, 16, 0, time1, 3600001); harness.check(z1.hasSameRules(z2)); // check 19 } // Tests converted from the SimpleTimeZoneTest.java attachment // of http://gcc.gnu.org/ml/java-patches/2007-q1/msg00587.html. private void test2(TestHarness harness) { TimeZone utc = (TimeZone) new SimpleTimeZone(0, "GMT"); TimeZone.setDefault(utc); Calendar cal = Calendar.getInstance(utc); TimeZone tz2 = new SimpleTimeZone( -12600000, "Test1", Calendar.MARCH, 8, -Calendar.SUNDAY, 60000, SimpleTimeZone.WALL_TIME, Calendar.NOVEMBER, 1, -Calendar.SUNDAY, 60000, SimpleTimeZone.STANDARD_TIME, 3600000); TimeZone tz3 = new SimpleTimeZone( -12600000, "Test2", Calendar.MARCH, 8, -Calendar.SUNDAY, 60000, Calendar.NOVEMBER, 1, -Calendar.SUNDAY, 3660000, 3600000); harness.check(!tz2.hasSameRules(tz3)); ((SimpleTimeZone) tz2).setEndRule( Calendar.NOVEMBER, 1, -Calendar.SUNDAY, 3660000); harness.check(tz2.hasSameRules(tz3)); } }
package io.gomint.server.world.block; import io.gomint.inventory.item.ItemStack; import io.gomint.math.BlockPosition; import io.gomint.math.Location; import io.gomint.math.MathUtils; import io.gomint.math.Vector; import io.gomint.server.entity.EntityLiving; import io.gomint.server.util.random.WeightedRandom; import io.gomint.server.world.UpdateReason; import io.gomint.server.world.block.state.ProgressBlockState; import io.gomint.world.block.BlockType; import io.gomint.world.block.data.Facing; import java.util.ArrayList; import java.util.concurrent.ThreadLocalRandom; /** * @author geNAZt * @version 1.0 * <p> * This is a generic class for anything that can grow with metadata like crops, beetroot etc. */ public abstract class Growable extends Block { /** * Randomizer for seed drop output */ protected static final WeightedRandom<Integer> SEED_RANDOMIZER = new WeightedRandom<>(ThreadLocalRandom.current()); static { SEED_RANDOMIZER.add(0.15, 0); SEED_RANDOMIZER.add(0.35, 1); SEED_RANDOMIZER.add(0.35, 2); SEED_RANDOMIZER.add(0.15, 3); } protected static final ProgressBlockState GROWTH = new ProgressBlockState(() -> new String[]{"growth"}, 7, aVoid -> { }); @Override public boolean beforePlacement(EntityLiving<?> entity, ItemStack<?> item, Facing face, Location location, Vector clickVector) { // Check if we place on farmland return location.world().blockAt(location.toBlockPosition().add(BlockPosition.DOWN)).blockType() == BlockType.FARMLAND; } @Override public long update(UpdateReason updateReason, long currentTimeMS, float dT) { if (updateReason == UpdateReason.NEIGHBOUR_UPDATE) { // Check if farmland is still under us if (this.world.blockAt(this.location.toBlockPosition().add(BlockPosition.DOWN)).blockType() != BlockType.FARMLAND) { this.world.breakBlock(this.location.toBlockPosition(), new ArrayList<>(), false); } } else if (updateReason == UpdateReason.RANDOM) { this.grow(); } return -1; } protected void grow() { // Check for growth state if (GROWTH.state(this) < 1f) { float growthDivider = getGrowthDivider(); int random = ThreadLocalRandom.current().nextInt((int) ((25f / growthDivider) + 1)); // Grow it if (random == 0) { // TODO: Some sort of growth event GROWTH.progress(this); } } } protected float getGrowthDivider() { float divider = 1f; BlockPosition underCrops = this.location.toBlockPosition().add(BlockPosition.DOWN); // Check for farmland blocks around (hydration states) for (int x = -1; x <= 1; ++x) { for (int z = -1; z <= 1; ++z) { float currentBlockDivider = 0f; Block block = this.world.blockAt(underCrops.add(new BlockPosition(x, 0, z))); if (block instanceof Farmland) { currentBlockDivider = 1f; if (((Farmland) block).moisture() > MathUtils.EPSILON) { currentBlockDivider = 3f; } } // Surrounding blocks affect only to 25% if (x != 0 || z != 0) { currentBlockDivider /= 4f; } divider += currentBlockDivider; } } // Check if there are similar crops around (slow down bigger farms) // We check in a pattern which goes up and clockwise around BlockPosition start = this.location.toBlockPosition().add(BlockPosition.NORTH); if (this.world.blockAt(start).blockType() == blockType() || this.world.blockAt(start.add(BlockPosition.EAST)).blockType() == blockType() || this.world.blockAt(start.add(BlockPosition.SOUTH)).blockType() == blockType() || this.world.blockAt(start.add(BlockPosition.SOUTH)).blockType() == blockType() || this.world.blockAt(start.add(BlockPosition.WEST)).blockType() == blockType() || this.world.blockAt(start.add(BlockPosition.WEST)).blockType() == blockType() || this.world.blockAt(start.add(BlockPosition.NORTH)).blockType() == blockType() || this.world.blockAt(start.add(BlockPosition.NORTH)).blockType() == blockType()) { divider /= 2f; } return divider; } }
/* * Copyright (c) 2020 GeekXYZ. * All rights reserved. */ package io.geekshop.mapper; import io.geekshop.entity.StockMovementEntity; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.apache.ibatis.annotations.Mapper; /** * Created on Nov, 2020 by @author bobo */ @Mapper public interface StockMovementEntityMapper extends BaseMapper<StockMovementEntity> { }
package frontend.user.features; import frontend.common.demographic_information.DemographicInformationView; import frontend.print.BloodBookPrinter; import frontend.user.features.all_blood_donor_request.AllActiveBloodDonorRequestView; import frontend.user.features.all_blood_receiver_request.AllActiveBloodReceiverRequestView; import frontend.user.features.blood_donation_request.BloodDonationRequestView; import frontend.user.features.blood_receiver_request.BloodReceiverRequestView; import frontend.user.features.export_user_data.ExportUserDataView; import frontend.user.features.rate_blood_bank.RateBloodBankView; import frontend.user.features.statistics.UserStatisticsView; import frontend.user.features.user_profile_management.UserProfileManagementView; import frontend.user.features.vaccination.VaccinationView; import java.util.Scanner; public final class UserFeaturesView { private final BloodBookPrinter printer; private final Scanner scanner; public UserFeaturesView(final BloodBookPrinter printer, final Scanner scanner) { this.printer = printer; this.scanner = scanner; } public final void showUserFeatures() { printer.printScreenTitle("All User Features"); while (true) { printer.printContent("1. Rate blood bank"); printer.printContent("2. Blood donation request"); printer.printContent("3. Blood receiver request"); printer.printContent("4. All Blood Donor Requests"); printer.printContent("5. All Blood Receiver Requests"); printer.printContent("6. User Statistics"); printer.printContent("7. User Profile Management"); printer.printContent("8. User Vaccination Registration/View"); printer.printContent("9. Export User Data"); printer.printContent("10. Demographic Information"); printer.printContent("11. Logout"); printer.printContent("Select an option:"); final String input = scanner.nextLine(); switch (input) { case "1": final RateBloodBankView rateBloodBankView = new RateBloodBankView(printer, scanner); rateBloodBankView.performRating(); break; case "2": final BloodDonationRequestView bloodDonationRequestView = new BloodDonationRequestView(printer, scanner); bloodDonationRequestView.performBloodDonationRequest(); break; case "3": final BloodReceiverRequestView bloodReceiverRequestView = new BloodReceiverRequestView(printer, scanner); bloodReceiverRequestView.performBloodReceiveRequest(); break; case "4": final AllActiveBloodDonorRequestView allActiveBloodDonorRequestView = new AllActiveBloodDonorRequestView(printer, scanner); allActiveBloodDonorRequestView.activeBloodDonorRequest(); break; case "5": final AllActiveBloodReceiverRequestView allActiveBloodReceiverRequestView = new AllActiveBloodReceiverRequestView(printer, scanner); allActiveBloodReceiverRequestView.activeBloodReceiverRequest(); break; case "6": final UserStatisticsView userStatisticsView = new UserStatisticsView(printer, scanner); userStatisticsView.fetchStatistics(); break; case "7": final UserProfileManagementView userProfileManagementView = new UserProfileManagementView(printer, scanner); userProfileManagementView.manageMyProfile(); break; case "8": final VaccinationView vaccinationView = new VaccinationView(printer, scanner); vaccinationView.scheduleVaccination(); break; case "9": final ExportUserDataView exportUserDataView = new ExportUserDataView(printer, scanner); exportUserDataView.exportData(); break; case "10": final DemographicInformationView demographicInformationView = new DemographicInformationView(printer, scanner); demographicInformationView.getDemographicInformation(); break; case "11": return; default: break; } } } }
package com.xxxifan.devbox.library.callbacks; import android.os.Handler; import android.os.Looper; import android.os.Message; import java.io.IOException; /** * Created by xifan on 15-7-25. */ public class HttpCallbackHandler extends Handler { private HttpCallback mHttpCallback; public HttpCallbackHandler(HttpCallback httpCallback) { super(Looper.getMainLooper()); mHttpCallback = httpCallback; } @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case 1: mHttpCallback.done(msg.obj, null); break; case -1: mHttpCallback.done(null, (IOException) msg.obj); break; } } }
package com.github.set.demo5; /** * @author 许大仙 * @version 1.0 * @since 2021-09-29 14:30 */ public class Person implements Comparable<Person> { private String name; private int age; public Person() {} public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public int getAge() { return this.age; } public void setAge(int age) { this.age = age; } @Override public int compareTo(Person o) { return Integer.compare(this.getAge(), o.getAge()); } @Override public String toString() { return "Person{" + "name='" + this.name + '\'' + ", age='" + this.age + '\'' + '}'; } }
package de.fau.clients.orchestrator.nodes; /** * Enum to internally distinguish between (un-)supported MIME types. */ public enum InternalContentType { /** * No support for the given content type. */ UNSUPPORTED, /** * Unknown content type. */ UNKNOWN, /** * Supported image type. */ IMAGE, /** * Supported text type. */ TEXT, TEXT_XML, }
package net.icelane.amplifire.database.sql; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import net.icelane.amplifire.player.AudioFile; import java.io.File; /** * amplifier - Audio-Player Project * * @author Oliver Daus / Luca Madonia * */ public class LoLPlayerDB extends DataBase { public HashMap<Integer, AudioFile> getPlaylistItems() throws SQLException { ResultSet rs = getConnection().getValues("playlistview"); HashMap<Integer, AudioFile> playlist = new HashMap<Integer, AudioFile>(); while (rs.next()) { int no = rs.getInt("no"); AudioFile af = new AudioFile(new File(rs.getString("path")), rs.getString("title"), rs.getString("author")); playlist.put(no, af); } return playlist; } public void clearPlaylist(){ String sql = String.format("DELETE FROM playlist;"); try { getConnection().sendSQLUpdate(sql); } catch (SQLException ex) {} } public void addPlaylistItem(AudioFile af) throws SQLException{ int songid = addAudioFile(af); String sql = String.format("INSERT INTO playlist(songid) VALUES(%s);", songid); getConnection().sendSQLUpdate(sql); } public int addAudioFile(AudioFile af) throws SQLException { AudioFile naf = getAudioFilebyFilepath(af.getFile().toString()); if (naf != null) return naf.getId(); int fileid = addFile(af.getFile().toString()); int titleid = addTitle(af.getTitle()); int authorid = addAuthor(af.getAuthor()); int albumid = addAlbum(af.getAlbum()); int genreid = addGenre(af.getGenre()); return addMedia(fileid, titleid, authorid, albumid, genreid); } public int addMedia(int fileid, int titleid, int authorid, int albumid, int genreid) throws SQLException { String sql = String .format("INSERT INTO media(fileid,titleid,authorid,albumid,genreid) VALUES(%s,%s,%s,%s,%s);", fileid, titleid, authorid, albumid, genreid); if (getAudioFilebyFilepath(getFile(fileid)) == null) getConnection().sendSQLUpdate(sql); int songid = getSongID(fileid); setStatistic(songid, 0); setRating(songid, 0); try{ return getAudioFilebyFilepath(getFile(fileid)).getId(); }catch(Exception e){ return -1; } } public void setStatistic(int songid, int frequency) throws SQLException { String sql = String.format( "INSERT INTO statistic(songid, frequency) VALUES(%s,%s);", songid, frequency); if (getStatistic(songid) < 0) getConnection().sendSQLUpdate(sql); } public int getStatistic(int songid) { String sql = String.format( "SELECT * FROM statistic WHERE statistic.songid = %s;", songid); try { ResultSet rs = getConnection().sendSQLQuery(sql); rs.next(); return rs.getInt("frequency"); } catch (SQLException ex) { } return -1; } public void setRating(int songid, int rate) throws SQLException { String sql = String .format("INSERT INTO rating(songid, rate) VALUES(%s,%s);", songid, rate); if (getRating(songid) < 0) getConnection().sendSQLUpdate(sql); } public int getRating(int songid) { String sql = String.format( "SELECT * FROM rating WHERE rating.songid = %s;", songid); try { ResultSet rs = getConnection().sendSQLQuery(sql); rs.next(); return rs.getInt("rate"); } catch (SQLException ex) { } return -1; } public int addFile(String s) { String sql = String.format("INSERT INTO file(path) VALUES('%s');", s); if (getFileID(s) == -1) try { getConnection().sendSQLUpdate(sql); } catch (SQLException ex) { } return getFileID(s); } public int addTitle(String s) { String sql = String.format("INSERT INTO title(title) VALUES('%s');", s); if (getTitleID(s) == -1) try { getConnection().sendSQLUpdate(sql); } catch (SQLException ex) { } return getTitleID(s); } public int addAuthor(String s) { String sql = String.format("INSERT INTO author(author) VALUES('%s');", s); if (getAuthorID(s) == -1) try { getConnection().sendSQLUpdate(sql); } catch (SQLException ex) { } return getAuthorID(s); } public int addAlbum(String s) { String sql = String.format("INSERT INTO album(album) VALUES('%s');", s); if (getAlbumID(s) == -1) try { getConnection().sendSQLUpdate(sql); } catch (SQLException ex) { } return getAlbumID(s); } public int addGenre(String s) { String sql = String.format("INSERT INTO genre(genre) VALUES('%s');", s); if (getGenreID(s) == -1) try { getConnection().sendSQLUpdate(sql); } catch (SQLException ex) { } return getGenreID(s); } public AudioFile getAudioFilebyFilepath(String filepath) { String sql = "SELECT mediafile.*" + "FROM mediafile " + "WHERE mediafile.path = '%s';"; try { ResultSet rs = getConnection().sendSQLQuery( String.format(sql, new File(filepath).toString())); AudioFile af = getAudioFile(rs); if (af == null) { rs = getConnection() .sendSQLQuery( String.format(sql, new File(filepath).getAbsolutePath())); af = getAudioFile(rs); } return af; } catch (Exception ex) { return null; } } private AudioFile getAudioFile(ResultSet rs) { try { rs.next(); AudioFile af = new AudioFile(new File(rs.getString("path"))); af.setTitle(rs.getString("title")); af.setAuthor(rs.getString("author")); af.setAlbum(rs.getString("album")); af.setGenre(rs.getString("genre")); af.setRating(rs.getInt("rate")); af.setFrequency(rs.getInt("frequency")); af.setId(rs.getInt("id")); return af; } catch (SQLException ex) { return null; } } public int getSongID(int fileid) { String sql = String.format( "SELECT media.* FROM media WHERE media.fileid = '%s'", fileid); try { ResultSet rs = getConnection().sendSQLQuery(sql); rs.next(); return rs.getInt("id"); } catch (SQLException ex) { } return -1; } public int getFileID(String filepath) { String sql = "SELECT *" + "FROM file " + "WHERE file.path = '%s';"; try { ResultSet rs = getConnection().sendSQLQuery( String.format(sql, filepath)); rs.next(); return rs.getInt("id"); } catch (SQLException ex) { return -1; } } public int getTitleID(String title) { String sql = "SELECT *" + "FROM title " + "WHERE title.title = '%s';"; try { ResultSet rs = getConnection().sendSQLQuery(String.format(sql, title)); rs.next(); return rs.getInt("id"); } catch (SQLException ex) { return -1; } } public int getAuthorID(String author) { String sql = "SELECT *" + "FROM author " + "WHERE author.author = '%s';"; try { ResultSet rs = getConnection() .sendSQLQuery(String.format(sql, author)); rs.next(); return rs.getInt("id"); } catch (SQLException ex) { return -1; } } public int getAlbumID(String album) { String sql = "SELECT *" + "FROM album " + "WHERE album.album = '%s';"; try { ResultSet rs = getConnection().sendSQLQuery(String.format(sql, album)); rs.next(); return rs.getInt("id"); } catch (SQLException ex) { return -1; } } public int getGenreID(String genre) { String sql = "SELECT *" + "FROM genre " + "WHERE genre.genre = '%s';"; try { ResultSet rs = getConnection().sendSQLQuery(String.format(sql, genre)); rs.next(); return rs.getInt("id"); } catch (SQLException ex) { return -1; } } public String getFile(int id) { String sql = "SELECT *" + "FROM file " + "WHERE file.id = '%s';"; try { ResultSet rs = getConnection().sendSQLQuery(String.format(sql, id)); rs.next(); return rs.getString("path"); } catch (SQLException ex) { return null; } } public String getTitle(int id) { String sql = "SELECT *" + "FROM title " + "WHERE title.id = '%s';"; try { ResultSet rs = getConnection().sendSQLQuery(String.format(sql, id)); rs.next(); return rs.getString("title"); } catch (SQLException ex) { return null; } } public String getAuthor(int id) { String sql = "SELECT *" + "FROM author " + "WHERE author.id = '%s';"; try { ResultSet rs = getConnection().sendSQLQuery(String.format(sql, id)); rs.next(); return rs.getString("author"); } catch (SQLException ex) { return null; } } public String getAlbum(int id) { String sql = "SELECT *" + "FROM album " + "WHERE album.id = '%s';"; try { ResultSet rs = getConnection().sendSQLQuery(String.format(sql, id)); rs.next(); return rs.getString("album"); } catch (SQLException ex) { return null; } } public String getGenre(int id) { String sql = "SELECT *" + "FROM genre " + "WHERE genre.id = '%s';"; try { ResultSet rs = getConnection().sendSQLQuery(String.format(sql, id)); rs.next(); return rs.getString("genre"); } catch (SQLException ex) { return null; } } public void updateFrequency(int id) throws SQLException { getConnection().sendSQLUpdate("UPDATE statistic SET frequency = frequency + 1 WHERE songid = " + id); } public class PlaylistItem { private int songid; private int no; private String filepath; private String title; private String author; public PlaylistItem(int songid, int no, String filepath, String title, String author) { super(); this.songid = songid; this.no = no; this.filepath = filepath; this.title = title; this.author = author; } public int getSongid() { return songid; } public int getNo() { return no; } public String getFilepath() { return filepath; } public String getTitle() { return title; } public String getAuthor() { return author; } } }
package com.alipay.api.response; import java.util.List; import com.alipay.api.internal.mapping.ApiField; import com.alipay.api.internal.mapping.ApiListField; import com.alipay.api.domain.AuthApiDTO; import com.alipay.api.AlipayResponse; /** * ALIPAY API: alipay.open.app.api.query response. * * @author auto create * @since 1.0, 2020-10-27 11:10:14 */ public class AlipayOpenAppApiQueryResponse extends AlipayResponse { private static final long serialVersionUID = 2142114118473649797L; /** * 应用可申请的接口出参敏感字段列表 */ @ApiListField("apis") @ApiField("auth_api_d_t_o") private List<AuthApiDTO> apis; public void setApis(List<AuthApiDTO> apis) { this.apis = apis; } public List<AuthApiDTO> getApis( ) { return this.apis; } }
package com.mmzsblog.springboot.controller; import com.mmzsblog.springboot.service.SendMail; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.Resource; @RestController public class SendMailController { @Resource private SendMail sendMail; @GetMapping("/sendSimpleMail") public void sendSimpleMail() { sendMail.sendSimpleMail(); } @GetMapping("/sendMimeMail") public void sendMimeMail() { sendMail.sendMimeMail(); } }
/* // Licensed to Julian Hyde under one or more contributor license // agreements. See the NOTICE file distributed with this work for // additional information regarding copyright ownership. // // Julian Hyde 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.eigenbase.sql.test; import org.eigenbase.reltype.RelDataTypeFactory; import org.eigenbase.sql.SqlOperatorTable; import org.eigenbase.sql.advise.SqlAdvisor; import org.eigenbase.sql.fun.SqlStdOperatorTable; import org.eigenbase.sql.parser.SqlParser; import org.eigenbase.sql.parser.impl.SqlParserImpl; import org.eigenbase.sql.type.SqlTypeFactoryImpl; import org.eigenbase.sql.validate.*; import org.eigenbase.test.MockCatalogReader; import org.eigenbase.test.MockSqlOperatorTable; import net.hydromatic.avatica.Casing; import net.hydromatic.avatica.Quoting; import com.google.common.collect.ImmutableMap; /** * Default implementation of {@link SqlTestFactory}. * * <p>Suitable for most tests. If you want different behavior, you can extend; * if you want a factory with different properties (e.g. SQL conformance level * or identifier quoting), wrap in a * {@link DelegatingSqlTestFactory} and * override {@link #get}.</p> */ public class DefaultSqlTestFactory implements SqlTestFactory { public static final ImmutableMap<String, Object> DEFAULT_OPTIONS = ImmutableMap.of( "quoting", (Object) Quoting.DOUBLE_QUOTE, "quotedCasing", Casing.UNCHANGED, "unquotedCasing", Casing.TO_UPPER, "caseSensitive", true, "conformance", SqlConformance.DEFAULT); public static final DefaultSqlTestFactory INSTANCE = new DefaultSqlTestFactory(); private DefaultSqlTestFactory() { } public SqlOperatorTable createOperatorTable() { MockSqlOperatorTable opTab = new MockSqlOperatorTable(SqlStdOperatorTable.instance()); MockSqlOperatorTable.addRamp(opTab); return opTab; } public SqlParser createParser(SqlTestFactory factory, String sql) { Quoting quoting = (Quoting) factory.get("quoting"); Casing quotedCasing = (Casing) factory.get("quotedCasing"); Casing unquotedCasing = (Casing) factory.get("unquotedCasing"); return SqlParser.create(SqlParserImpl.FACTORY, sql, quoting, unquotedCasing, quotedCasing); } public SqlValidator getValidator(SqlTestFactory factory) { final SqlOperatorTable operatorTable = factory.createOperatorTable(); final boolean caseSensitive = (Boolean) factory.get("caseSensitive"); final RelDataTypeFactory typeFactory = new SqlTypeFactoryImpl(); return SqlValidatorUtil.newValidator(operatorTable, new MockCatalogReader(typeFactory, caseSensitive), typeFactory); } public SqlAdvisor createAdvisor(SqlValidatorWithHints validator) { throw new UnsupportedOperationException(); } public Object get(String name) { return DEFAULT_OPTIONS.get(name); } } // End DefaultSqlTestFactory.java
package okhttp3.spring.boot; import java.net.ProxySelector; import java.net.Socket; import java.time.Duration; import java.util.List; import java.util.concurrent.TimeUnit; import org.springframework.boot.context.properties.ConfigurationProperties; import lombok.Data; import okhttp3.ConnectionPool; import okhttp3.Protocol; import okhttp3.Response; import okhttp3.WebSocketListener; import okhttp3.internal.Util; import okhttp3.logging.HttpLoggingInterceptor.Level; import okio.Source; @ConfigurationProperties(OkHttp3Properties.PREFIX) @Data public class OkHttp3Properties { public static final String PREFIX = "okhttp3"; /** * Default value for disabling SSL validation. */ public static final boolean DEFAULT_DISABLE_SSL_VALIDATION = false; /** * Default value for following redirects. */ public static final boolean DEFAULT_FOLLOW_REDIRECTS = true; /** * Configure this client to follow redirects from HTTPS to HTTP and from HTTP to HTTPS. * * <p>If unset, protocol redirects will be followed. This is different than the built-in {@code * HttpURLConnection}'s default. */ private boolean followSslRedirects = DEFAULT_FOLLOW_REDIRECTS; /** * Configure this client to follow redirects. If unset, redirects will be followed. */ private boolean followRedirects = true; /** * Configure this client to retry or not when a connectivity problem is encountered. By default, * this client silently recovers from the following problems: * * <ul> * <li><strong>Unreachable IP addresses.</strong> If the URL's host has multiple IP addresses, * failure to reach any individual IP address doesn't fail the overall request. This can * increase availability of multi-homed services. * <li><strong>Stale pooled connections.</strong> The {@link ConnectionPool} reuses sockets * to decrease request latency, but these connections will occasionally time out. * <li><strong>Unreachable proxy servers.</strong> A {@link ProxySelector} can be used to * attempt multiple proxy servers in sequence, eventually falling back to a direct * connection. * </ul> * * Set this to false to avoid retrying requests when doing so is destructive. In this case the * calling application should do its own recovery of connectivity failures. */ private boolean retryOnConnectionFailure = true; private int maxRetry; // 最大重试次数 private long retryInterval;// 重试的间隔 /** * Sets the default timeout for complete calls. A value of 0 means no timeout, otherwise values * must be between 1 and {@link Integer#MAX_VALUE} when converted to milliseconds. * * The call timeout spans the entire call: resolving DNS, connecting, writing the request * body, server processing, and reading the response body. If the call requires redirects or * retries all must complete within one timeout period. * * The default value is 0 which imposes no timeout. */ private Duration callTimeout = Duration.ofSeconds(0); /** * Sets the default connect timeout for new connections. A value of 0 means no timeout, * otherwise values must be between 1 and {@link Integer#MAX_VALUE} when converted to * milliseconds. * * <p>The connectTimeout is applied when connecting a TCP socket to the target host. * The default value is 10 seconds. */ private Duration connectTimeout = Duration.ofSeconds(10); /** * Sets the default read timeout for new connections. A value of 0 means no timeout, otherwise * values must be between 1 and {@link Integer#MAX_VALUE} when converted to milliseconds. * * The read timeout is applied to both the TCP socket and for individual read IO operations * including on {@link Source} of the {@link Response}. The default value is 10 seconds. * * @see Socket#setSoTimeout(int) * @see Source#timeout() */ private Duration readTimeout = Duration.ofSeconds(10); /** * Sets the default write timeout for new connections. A value of 0 means no timeout, otherwise * values must be between 1 and {@link Integer#MAX_VALUE} when converted to milliseconds. * * <p>The write timeout is applied for individual write IO operations. * The default value is 10 seconds. * */ private Duration writeTimeout = Duration.ofSeconds(10); /** * Sets the interval between HTTP/2 and web socket pings initiated by this client. Use this to * automatically send ping frames until either the connection fails or it is closed. This keeps * the connection alive and may detect connectivity failures. * * <p>If the server does not respond to each ping with a pong within {@code interval}, this * client will assume that connectivity has been lost. When this happens on a web socket the * connection is canceled and its listener is {@linkplain WebSocketListener#onFailure notified * of the failure}. When it happens on an HTTP/2 connection the connection is closed and any * calls it is carrying {@linkplain java.io.IOException will fail with an IOException}. * * <p>The default value of 0 disables client-initiated pings. */ private Duration pingInterval = Duration.ofSeconds(0); /** * the protocols to use, in order of preference. If the list contains {@link * Protocol#H2_PRIOR_KNOWLEDGE} then that must be the only protocol and HTTPS URLs will not * be supported. Otherwise the list must contain {@link Protocol#HTTP_1_1}. The list must * not contain null or {@link Protocol#HTTP_1_0}. */ List<Protocol> protocols = Util.immutableList(Protocol.HTTP_2, Protocol.HTTP_1_1); private Level logLevel = Level.NONE; }
package com.digitalchannelforum.drupalcon.model; import com.digitalchannelforum.drupalcon.model.data.Event; import com.digitalchannelforum.drupalcon.model.data.Speaker; import com.digitalchannelforum.drupalcon.model.data.TimeRange; import com.digitalchannelforum.drupalcon.model.data.Track; import com.digitalchannelforum.drupalcon.model.managers.BofsManager; import com.digitalchannelforum.drupalcon.model.managers.EventManager; import com.digitalchannelforum.drupalcon.model.managers.ProgramManager; import com.digitalchannelforum.drupalcon.model.managers.SocialManager; import com.digitalchannelforum.drupalcon.model.managers.SpeakerManager; import com.digitalchannelforum.drupalcon.model.managers.TracksManager; import com.digitalchannelforum.ui.adapter.item.EventItemCreator; import com.digitalchannelforum.ui.adapter.item.EventListItem; import com.digitalchannelforum.ui.adapter.item.ProgramItem; import com.digitalchannelforum.ui.adapter.item.TimeRangeItem; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.List; public class EventGenerator { private EventManager mEventManager; private BofsManager mBofsManager; private SocialManager mSocialManager; private ProgramManager mProgramManager; private boolean mShouldBreak; public EventGenerator() { mEventManager = Model.instance().getEventManager(); mBofsManager = Model.instance().getBofsManager(); mSocialManager = Model.instance().getSocialManager(); mProgramManager = Model.instance().createProgramManager(); } public List<EventListItem> generate(long day, int eventClass, @NotNull EventItemCreator eventItemCreator) { List<EventListItem> eventListItems; if (eventClass == Event.SOCIALS_CLASS) { eventListItems = mSocialManager.getSocialItemsSafe(day); } else { eventListItems = mBofsManager.getBofsItemsSafe(day); } if (mShouldBreak) { return new ArrayList<>(); } List<TimeRange> ranges = mEventManager.getDistrictTimeRangeSafe(eventClass, day); if (mShouldBreak) { return new ArrayList<>(); } return getEventItems(eventItemCreator, eventListItems, ranges); } public List<EventListItem> generate(long day, int eventClass, List<Long> levelIds, List<Long> trackIds, @NotNull EventItemCreator eventItemCreator) { List<EventListItem> eventListItems = mProgramManager.getProgramItemsSafe(eventClass, day, levelIds, trackIds); if (mShouldBreak) { return new ArrayList<>(); } List<TimeRange> ranges = mEventManager.getDistrictTimeRangeSafe(eventClass, day, levelIds, trackIds); if (mShouldBreak) { return new ArrayList<>(); } Collections.sort(eventListItems, new Comparator<EventListItem>() { @Override public int compare(EventListItem first, EventListItem second) { double order1 = first.getEvent().getOrder(); double order2 = second.getEvent().getOrder(); if (order1 > order2) { return 1; } else if (order1 < order2) { return -1; } else { return 0; } } }); return getEventItems(eventItemCreator, eventListItems, ranges); } public List<EventListItem> generateForFavorites(long day, @NotNull EventItemCreator eventItemCreator) { List<Long> favoriteEventIds = Model.instance().getSharedScheduleManager().getMyFavoriteEventIds(); List<EventListItem> eventListItems = mProgramManager.getFavoriteProgramItemsSafe(favoriteEventIds, day); if (mShouldBreak) { return new ArrayList<>(); } return sortFavorites(favoriteEventIds, eventListItems, day, eventItemCreator); } public List<EventListItem> generateForFriendsFavorites(long day, @NotNull EventItemCreator eventItemCreator) { List<Long> favoriteEventIds = Model.instance().getSharedScheduleManager().getFriendsFavoriteEventIds(); List<EventListItem> eventListItems = mProgramManager.getFavoriteProgramItemsSafe(favoriteEventIds, day); if (mShouldBreak) { return new ArrayList<>(); } return sortFavorites(favoriteEventIds, eventListItems, day, eventItemCreator); } private List<EventListItem> sortFavorites(List<Long> favoriteEventIds, List<EventListItem> eventListItems, long day, @NotNull EventItemCreator eventItemCreator) { List<EventListItem> result = new ArrayList<>(); if (eventListItems.isEmpty()) { return result; } List<EventListItem> schedules = new ArrayList<>(); List<EventListItem> bofs = new ArrayList<>(); List<EventListItem> socials = new ArrayList<>(); for (EventListItem eventListItem : eventListItems) { Event event = eventListItem.getEvent(); if (Event.PROGRAM_CLASS == event.getEventClass()) { schedules.add(eventListItem); } else if (Event.BOFS_CLASS == event.getEventClass()) { bofs.add(eventListItem); } else if (Event.SOCIALS_CLASS == event.getEventClass()) { socials.add(eventListItem); } } if (!schedules.isEmpty()) { List<TimeRange> ranges = mEventManager.getDistrictFavoriteTimeRangeSafe(Event.PROGRAM_CLASS, favoriteEventIds, day); schedules = getEventItems(eventItemCreator, schedules, ranges); } if (!bofs.isEmpty()) { List<TimeRange> ranges = mEventManager.getDistrictFavoriteTimeRangeSafe(Event.BOFS_CLASS, favoriteEventIds, day); bofs = getEventItems(eventItemCreator, bofs, ranges); } if (!socials.isEmpty()) { List<TimeRange> ranges = mEventManager.getDistrictFavoriteTimeRangeSafe(Event.SOCIALS_CLASS, favoriteEventIds, day); socials = getEventItems(eventItemCreator, socials, ranges); } result.addAll(schedules); result.addAll(bofs); result.addAll(socials); Collections.sort(result, new Comparator<EventListItem>() { @Override public int compare(EventListItem first, EventListItem second) { long order1 = first.getEvent().getFromMillis(); long order2 = second.getEvent().getFromMillis(); if (order1 > order2) { return 1; } else if (order1 < order2) { return -1; } else { return 0; } } }); return result; } private List<EventListItem> getEventItems(EventItemCreator eventItemCreator, List<EventListItem> events, List<TimeRange> ranges) { List<EventListItem> result = new ArrayList<>(); for (TimeRange timeRange : ranges) { if (mShouldBreak) { return result; } List<EventListItem> timeRangeEvents = new ArrayList<>(); for (EventListItem eventListItem : events) { Event event = eventListItem.getEvent(); if (event == null) { continue; } if (timeRange.equals(event.getTimeRange())) { timeRangeEvents.add(eventListItem); } } result.addAll(generateEventItems(timeRangeEvents, eventItemCreator)); } return result; } private List<EventListItem> fetchEventItems(List<Event> events) { SpeakerManager speakerManager = Model.instance().getSpeakerManager(); TracksManager tracksManager = Model.instance().getTracksManager(); List<EventListItem> result = new ArrayList<>(); for (Event event : events) { List<Long> speakersIds = mEventManager.getEventSpeakerSafe(event.getId()); List<Speaker> speakers = new ArrayList<Speaker>(); List<String> speakersNames = new ArrayList<>(); for (Long id : speakersIds) { speakers.addAll(speakerManager.getSpeakers(id)); } Track track = tracksManager.getTrack(event.getTrack()); TimeRangeItem item = new TimeRangeItem(); item.setEvent(event); item.setTrack(track != null ? track.getName() : null); for (Speaker speaker : speakers) { speakersNames.add(speaker.getFirstName() + " " + speaker.getLastName()); } item.setSpeakers(speakersNames); result.add(item); } return result; } private List<EventListItem> generateEventItems(List<EventListItem> eventListItems, EventItemCreator eventItemCreator) { TracksManager tracksManager = Model.instance().getTracksManager(); List<EventListItem> result = new ArrayList<>(); if (eventListItems.size() > 0) { EventListItem item = eventListItems.get(0); Event event = item.getEvent(); if (event == null) { return result; } TimeRangeItem timeRangeItem = (TimeRangeItem) eventItemCreator.getItem(event); if (event.getTimeRange().getFromTime() != null) { Calendar eventFromTime = event.getTimeRange().getFromTime(); long eventDate = event.getTimeRange().getDate(); Date date = parseEventDate(eventFromTime, eventDate); timeRangeItem.setDate(date); } timeRangeItem.setSpeakers(item.getSpeakers()); Track track = tracksManager.getTrack(event.getTrack()); timeRangeItem.setTrack(track != null ? track.getName() : null); if (eventListItems.get(0) instanceof ProgramItem) { ProgramItem firstItem = (ProgramItem) eventListItems.get(0); timeRangeItem.setSpeakers(firstItem.getSpeakers()); timeRangeItem.setTrack(firstItem.getTrack()); } if (eventListItems.size() > 1) { timeRangeItem.setFirst(true); eventListItems.remove(0); eventListItems.get(eventListItems.size() - 1).setLast(true); result.add(timeRangeItem); result.addAll(eventListItems); } else { result.add(timeRangeItem); } } return result; } private Date parseEventDate(Calendar fromTime, long dateTime) { Calendar monthYear = Calendar.getInstance(); monthYear.setTimeInMillis(dateTime); Calendar time = Calendar.getInstance(); time.set(monthYear.get(Calendar.YEAR), monthYear.get(Calendar.MONTH), monthYear.get(Calendar.DAY_OF_MONTH)); time.set(Calendar.HOUR_OF_DAY, fromTime.get(Calendar.HOUR_OF_DAY)); time.set(Calendar.MINUTE, fromTime.get(Calendar.MINUTE)); return time.getTime(); } public void setShouldBreak(boolean shouldBreak) { mShouldBreak = shouldBreak; mProgramManager.getEventDao().setShouldBreak(shouldBreak); } private void addRange(List<TimeRange> ranges, List<Long> favoriteEventIds, long day) { for (TimeRange item : mEventManager.getDistrictFavoriteTimeRangeSafe(Event.SOCIALS_CLASS, favoriteEventIds, day)) { if (!ranges.contains(item)) { ranges.add(item); } } } }
/** * Copyright 2017 LinkedIn Corp. 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. */ package com.github.ambry.messageformat; import com.github.ambry.utils.Utils; import io.netty.buffer.ByteBuf; import java.io.DataInputStream; import java.io.IOException; import java.nio.ByteBuffer; /** * MessageFormat metadata associated with messages sent out. */ public class MessageMetadata { private static final short MESSAGE_METADATA_VERSION_V1 = 1; private final ByteBuffer encryptionKey; private final short version; MessageMetadata(short version, ByteBuffer encryptionKey) { this.version = version; this.encryptionKey = encryptionKey; } public MessageMetadata(ByteBuffer encryptionKey) { this(MESSAGE_METADATA_VERSION_V1, encryptionKey); } public ByteBuffer getEncryptionKey() { return encryptionKey; } public short getVersion() { return version; } /** * @return The number of bytes in the serialized form of this instance of MessageMetadata. */ public int sizeInBytes() { return Short.BYTES + Integer.BYTES + (encryptionKey == null ? 0 : encryptionKey.remaining()); } /** * Serialize the MessageMetadata into the given {@link ByteBuf} * @param outputBuf the {@link ByteBuf} to which to write the serialized bytes into. */ public void serializeMessageMetadata(ByteBuf outputBuf) { switch (version) { case MESSAGE_METADATA_VERSION_V1: outputBuf.writeShort(version); if (encryptionKey != null) { outputBuf.writeInt(encryptionKey.remaining()); outputBuf.writeBytes(encryptionKey); } else { outputBuf.writeInt(0); } break; default: throw new IllegalStateException("Unknown MessageMetadata version"); } } /** * Deserialize MessageMetadata from the given {@link DataInputStream} * @param stream the stream to read bytes from. * @return the deserialized MessageMetadata. * @throws IOException if an error occurs reading from the stream. */ public static MessageMetadata deserializeMessageMetadata(DataInputStream stream) throws IOException { MessageMetadata messageMetadata; short version = stream.readShort(); switch (version) { case MESSAGE_METADATA_VERSION_V1: ByteBuffer encryptionKey = Utils.readIntBuffer(stream); // An empty encryption key could mean that the original before serialization was null or empty. Either way // denotes the absence of a key. messageMetadata = new MessageMetadata(version, encryptionKey); break; default: throw new IllegalStateException("Unknown MessageMetadata version"); } return messageMetadata; } }
package io.deephaven.db.v2; import io.deephaven.base.FileUtils; import io.deephaven.datastructures.util.CollectionUtil; import io.deephaven.datastructures.util.SmartKey; import io.deephaven.io.logger.Logger; import io.deephaven.io.logger.StreamLoggerImpl; import io.deephaven.db.tables.ColumnDefinition; import io.deephaven.db.tables.Table; import io.deephaven.db.tables.TableDefinition; import io.deephaven.db.tables.live.LiveTableMonitor; import io.deephaven.db.tables.select.MatchPairFactory; import io.deephaven.db.tables.utils.*; import io.deephaven.db.v2.sources.AbstractColumnSource; import io.deephaven.db.v2.sources.ColumnSource; import io.deephaven.db.v2.utils.ColumnHolder; import io.deephaven.db.v2.utils.Index; import io.deephaven.test.types.OutOfBandTest; import io.deephaven.util.QueryConstants; import junit.framework.TestCase; import org.apache.commons.lang3.mutable.MutableInt; import org.jetbrains.annotations.NotNull; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.util.*; import java.util.function.BiConsumer; import org.junit.experimental.categories.Category; import static io.deephaven.db.tables.utils.TableTools.*; import static io.deephaven.db.v2.TstUtils.*; import static io.deephaven.util.QueryConstants.NULL_INT; import static java.util.Arrays.asList; @Category(OutOfBandTest.class) public class QueryTableNaturalJoinTest extends QueryTableTestBase { public void testNaturalJoinRehash() { setExpectError(false); final Random random = new Random(0); final String[] leftJoinKey = new String[1024]; final int[] leftSentinel = new int[1024]; final String[] rightJoinKey = new String[1024]; final int[] rightSentinel = new int[1024]; int offset = 0; fillRehashKeys(offset, leftJoinKey, leftSentinel, rightJoinKey, rightSentinel); final QueryTable leftTable = TstUtils.testRefreshingTable(stringCol("JoinKey", leftJoinKey), intCol("LeftSentinel", leftSentinel)); final QueryTable rightTable = TstUtils.testRefreshingTable(stringCol("JoinKey", rightJoinKey), intCol("RightSentinel", rightSentinel)); final EvalNugget[] en = new EvalNugget[] { new EvalNugget() { public Table e() { return leftTable.naturalJoin(rightTable, "JoinKey", "RJK=JoinKey,RightSentinel"); } }, }; if (printTableUpdates) { for (int ii = 0; ii < en.length; ++ii) { en[ii].showResult("Original " + ii, en[ii].originalValue); } } for (int step = 0; step < 40; step++) { System.out .println("Step = " + step + ", leftSize=" + leftTable.size() + ", rightSize=" + rightTable.size()); offset += leftJoinKey.length; fillRehashKeys(offset, leftJoinKey, leftSentinel, rightJoinKey, rightSentinel); final int foffset = offset; LiveTableMonitor.DEFAULT.runWithinUnitTestCycle(() -> { final Index addIndex = Index.FACTORY.getIndexByRange(foffset, foffset + leftJoinKey.length - 1); addToTable(leftTable, addIndex, stringCol("JoinKey", leftJoinKey), intCol("LeftSentinel", leftSentinel)); leftTable.notifyListeners(addIndex, i(), i()); final Index.SequentialBuilder modIndexBuilder = Index.FACTORY.getSequentialBuilder(); int slot = random.nextInt(foffset / 100); for (int ii = 0; ii < 100; ++ii) { modIndexBuilder.appendKey(slot); slot += 1 + random.nextInt(foffset / 100); if (slot >= foffset) { break; } } final Index modIndex = modIndexBuilder.getIndex(); final String[] rightModifications = new String[modIndex.intSize()]; final int[] rightModifySentinel = new int[modIndex.intSize()]; final MutableInt position = new MutableInt(); modIndex.forAllLongs((long ll) -> { final int ii = (int) ll; if (ii % 2 == 0) { // make something that exists go away rightModifications[position.intValue()] = Integer.toString(ii * 10 + 2); } else { // make something that did not exist come back rightModifications[position.intValue()] = Integer.toString(ii * 10); } rightModifySentinel[position.intValue()] = ii * 100 + 25; position.increment(); }); addToTable(rightTable, addIndex, stringCol("JoinKey", rightJoinKey), intCol("RightSentinel", rightSentinel)); addToTable(rightTable, modIndex, stringCol("JoinKey", rightModifications), intCol("RightSentinel", rightModifySentinel)); rightTable.notifyListeners(addIndex, i(), modIndex); }); TstUtils.validate(en); } } private void fillRehashKeys(int offset, String[] leftJoinKey, int[] leftSentinel, String[] rightJoinKey, int[] rightSentinel) { for (int ii = 0; ii < leftJoinKey.length; ii++) { final int iio = ii + offset; leftJoinKey[ii] = Integer.toString(iio * 10); leftSentinel[ii] = iio * 100; if (iio % 2 == 0) { rightJoinKey[ii] = Integer.toString(iio * 10); } else { rightJoinKey[ii] = Integer.toString((iio / 4 * 10) + 1); } rightSentinel[ii] = iio * 100 + 25; } } public void testNaturalJoinIncremental() { setExpectError(false); final int sz = 5; final int maxSteps = 10; for (JoinIncrement joinIncrement : joinIncrementorsShift) { testNaturalJoinIncremental(false, false, sz, sz, joinIncrement, 0, maxSteps); } final int[] leftSizes = new int[] {10, 50, 100}; final int[] rightSizes = new int[] {10, 50, 100}; for (long seed = 0; seed < 5; seed++) { for (int leftSize : leftSizes) { for (int rightSize : rightSizes) { for (JoinIncrement joinIncrement : joinIncrementorsShift) { testNaturalJoinIncremental(false, false, leftSize, rightSize, joinIncrement, seed, maxSteps); } } } } } public void testNaturalJoinIncrementalOverflow() { setExpectError(false); final int maxSteps = 5; final int[] leftSizes = new int[] {10000}; final int[] rightSizes = new int[] {10000}; for (long seed = 0; seed < 5; seed++) { for (int leftSize : leftSizes) { for (int rightSize : rightSizes) { for (JoinIncrement joinIncrement : new JoinIncrement[] {leftRightConcurrentStepShift}) { testNaturalJoinIncremental(false, false, leftSize, rightSize, joinIncrement, seed, maxSteps, QueryTableJoinTest.HIGH_LOAD_FACTOR_CONTROL); } } } } } public void testNaturalJoinLeftIncrementalRightStatic() { for (JoinIncrement joinIncrement : new JoinIncrement[] {leftStepShift, leftStep}) { final int sz = 5; final int maxSteps = 20; testNaturalJoinIncremental(false, true, sz, sz, joinIncrement, 0, maxSteps); final int[] leftSizes = new int[] {50, 100}; final int[] rightSizes = new int[] {50, 100}; for (long seed = 0; seed < 1; seed++) { for (int leftSize : leftSizes) { for (int rightSize : rightSizes) { testNaturalJoinIncremental(false, true, leftSize, rightSize, joinIncrement, seed, maxSteps); } } } } } public void testNaturalJoinLeftStaticRightIncremental() { for (JoinIncrement joinIncrement : new JoinIncrement[] {rightStepShift, rightStep}) { final int sz = 5; final int maxSteps = 20; testNaturalJoinIncremental(true, false, sz, sz, joinIncrement, 0, maxSteps); final int[] leftSizes = new int[] {50, 100}; final int[] rightSizes = new int[] {50, 100}; for (long seed = 0; seed < 5; seed++) { for (int leftSize : leftSizes) { for (int rightSize : rightSizes) { testNaturalJoinIncremental(true, false, leftSize, rightSize, joinIncrement, seed, maxSteps); } } } } } private void testNaturalJoinIncremental(boolean leftStatic, boolean rightStatic, int leftSize, int rightSize, JoinIncrement joinIncrement, long seed, long maxSteps) { testNaturalJoinIncremental(leftStatic, rightStatic, leftSize, rightSize, joinIncrement, seed, new MutableInt((int) maxSteps)); } private void testNaturalJoinIncremental(boolean leftStatic, boolean rightStatic, int leftSize, int rightSize, JoinIncrement joinIncrement, long seed, MutableInt numSteps) { testNaturalJoinIncremental(leftStatic, rightStatic, leftSize, rightSize, joinIncrement, seed, numSteps, new JoinControl()); } private static void testNaturalJoinIncremental(boolean leftStatic, boolean rightStatic, int leftSize, int rightSize, JoinIncrement joinIncrement, long seed, long maxSteps, JoinControl control) { testNaturalJoinIncremental(leftStatic, rightStatic, leftSize, rightSize, joinIncrement, seed, new MutableInt((int) maxSteps), control); } private static void testNaturalJoinIncremental(boolean leftStatic, boolean rightStatic, int leftSize, int rightSize, JoinIncrement joinIncrement, long seed, MutableInt numSteps, JoinControl control) { final Random random = new Random(seed); final int maxSteps = numSteps.intValue(); final Logger log = new StreamLoggerImpl(); final TstUtils.ColumnInfo[] rightColumnInfo; final TstUtils.UniqueIntGenerator rightIntGenerator = new TstUtils.UniqueIntGenerator(1, rightSize * (rightStatic ? 2 : 4)); final TstUtils.UniqueIntGenerator rightInt2Generator = new TstUtils.UniqueIntGenerator(1, rightSize * (rightStatic ? 2 : 4)); final TstUtils.IntGenerator duplicateGenerator = new TstUtils.IntGenerator(100000, 100010); final List<TstUtils.Generator<Integer, Integer>> generatorList = Arrays.asList(rightIntGenerator, duplicateGenerator); final TstUtils.Generator<Integer, Integer> compositeGenerator = new TstUtils.CompositeGenerator<>(generatorList, 0.9); final QueryTable rightTable = getTable(!rightStatic, rightSize, random, rightColumnInfo = initColumnInfos(new String[] {"I1", "C1", "C2"}, compositeGenerator, new SetGenerator<>("a", "b"), rightInt2Generator)); final ColumnInfo[] leftColumnInfo; final QueryTable leftTable = getTable(!leftStatic, leftSize, random, leftColumnInfo = initColumnInfos(new String[] {"I1", "C1", "C2"}, new FromUniqueIntGenerator(rightIntGenerator, new IntGenerator(20, 10000), 0.75), new SetGenerator<>("a", "b", "c"), new FromUniqueIntGenerator(rightInt2Generator, new IntGenerator(20, 10000), 0.75))); final EvalNugget[] en = new EvalNugget[] { new EvalNugget() { public Table e() { return NaturalJoinHelper.naturalJoin(leftTable, rightTable, MatchPairFactory.getExpressions("I1"), MatchPairFactory.getExpressions("LI1=I1", "LC1=C1", "LC2=C2"), false, control); } }, new EvalNugget() { public Table e() { return NaturalJoinHelper.naturalJoin(leftTable, rightTable, MatchPairFactory.getExpressions("C1", "I1"), MatchPairFactory.getExpressions("LC2=C2"), false, control); } }, new EvalNugget() { public Table e() { return NaturalJoinHelper.naturalJoin(leftTable, (QueryTable) rightTable.update("Exists=true"), MatchPairFactory.getExpressions("C1", "C2", "I1"), MatchPairFactory.getExpressions("Exists"), false, control); } }, }; if (printTableUpdates) { for (int ii = 0; ii < en.length; ++ii) { en[ii].showResult("Original " + ii, en[ii].originalValue); } } final int leftStepSize = (int) Math.ceil(Math.sqrt(leftSize)); final int rightStepSize = (int) Math.ceil(Math.sqrt(rightSize)); for (numSteps.setValue(0); numSteps.intValue() < maxSteps; numSteps.increment()) { if (printTableUpdates) { System.out.println("Step = " + numSteps.intValue() + ", leftSize=" + leftSize + ", rightSize=" + rightSize + ", seed = " + seed + ", joinIncrement=" + joinIncrement); System.out.println("Left Table:" + leftTable.size()); showWithIndex(leftTable, 100); System.out.println("Right Table:" + rightTable.size()); showWithIndex(rightTable, 100); } joinIncrement.step(leftStepSize, rightStepSize, leftTable, rightTable, leftColumnInfo, rightColumnInfo, en, random); } } public void testNaturalJoinMixedGrouping() { testNaturalJoinMixedGroupingLeftStatic(10, 10, 0, 20); testNaturalJoinMixedGroupingLeftStatic(1000, 1000, 1, 10); testNaturalJoinMixedGroupingLeftStatic(10000, 10000, 1, 10); } private void testNaturalJoinMixedGroupingLeftStatic(int leftSize, int rightSize, long seed, int steps) { final Random random = new Random(seed); final QueryTable leftTable = getTable(false, leftSize, random, initColumnInfos(new String[] {"I1", "C1", "C2"}, new ColumnInfo.ColAttributes[] {ColumnInfo.ColAttributes.Grouped}, new IntGenerator(1, rightSize * 10), new SetGenerator<>("a", "b", "c", "d", "e", "f"), new IntGenerator(1, 10))); final ColumnInfo[] rightColumnInfos = initColumnInfos(new String[] {"I1", "C1", "C2"}, new ColumnInfo.ColAttributes[] {}, new UniqueIntGenerator(1, rightSize * 10), new SetGenerator<>("a", "b", "c", "d", "e"), new IntGenerator(1, 10)); final QueryTable rightTable = getTable(true, rightSize, random, rightColumnInfos); System.out.println("Left:"); TableTools.showWithIndex(leftTable); System.out.println("Right:"); TableTools.showWithIndex(rightTable); final Table result = leftTable.naturalJoin(rightTable, "I1", "LC1=C1,LC2=C2"); System.out.println("Result:"); TableTools.showWithIndex(result); final Table ungroupedResult = leftTable.update("I1=I1*10") .naturalJoin(rightTable.update("I1=I1*10"), "I1", "LC1=C1,LC2=C2").update("I1=(int)(I1/10)"); System.out.println("Ungrouped Result:"); TableTools.showWithIndex(ungroupedResult); assertTableEquals(ungroupedResult, result); final Table leftFlat = leftTable.flatten(); final ColumnSource flatGrouped = leftFlat.getColumnSource("I1"); final Index flatIndex = leftFlat.getIndex(); final Map<Object, Index> grouping = flatIndex.getGrouping(flatGrouped); // noinspection unchecked ((AbstractColumnSource) flatGrouped).setGroupToRange(grouping); final Table resultFlat = leftFlat.naturalJoin(rightTable, "I1", "LC1=C1,LC2=C2"); assertTableEquals(ungroupedResult, resultFlat); for (int step = 0; step < steps; ++step) { if (LiveTableTestCase.printTableUpdates) { System.out.println("Step = " + step); } LiveTableMonitor.DEFAULT.runWithinUnitTestCycle(() -> { GenerateTableUpdates.generateShiftAwareTableUpdates(GenerateTableUpdates.DEFAULT_PROFILE, rightSize, random, rightTable, rightColumnInfos); }); if (LiveTableTestCase.printTableUpdates) { System.out.println("Expected"); TableTools.showWithIndex(result); System.out.println("Result"); TableTools.showWithIndex(result); } assertTableEquals(ungroupedResult, result); assertTableEquals(ungroupedResult, resultFlat); } } public void testNaturalJoinSimpleStatic() { // noinspection unchecked testNaturalJoinSimpleStatic(TstUtils::c); } public void testNaturalJoinGroupedStatic() { // noinspection unchecked testNaturalJoinSimpleStatic(TstUtils::cG); } private interface MakeLeftColumn { @SuppressWarnings("unchecked") <T> ColumnHolder make(String name, T... data); } private void testNaturalJoinSimpleStatic(MakeLeftColumn lC) { final Table left = testTable(lC.make("Symbol", "A", "B", "C"), c("LeftSentinel", 1, 2, 3)); final Table right = newTable(c("Symbol", "A", "B", "D", "E", "F"), c("RightSentinel", 10, 11, 12, 13, 14), c("RightObjectSentinel", 10, 11L, "12", "13", "14")); final Table cj = left.naturalJoin(right, "Symbol"); TableTools.showWithIndex(cj); assertEquals(new int[] {10, 11, NULL_INT}, intColumn(cj, "RightSentinel")); // the two wheres check for filling null keys final Table cjw = cj.where("RightObjectSentinel = null"); final Table cjw2 = left.naturalJoin(SparseSelect.sparseSelect(right), "Symbol").where("RightObjectSentinel = null"); TableTools.showWithIndex(cjw); TableTools.showWithIndex(cjw2); final Table left2 = newTable(lC.make("Symbol", "A", "B", "C", "A"), c("LeftSentinel", 1, 2, 3, 4)); final Table right2 = newTable(c("Symbol", "A", "B", "D"), c("RightSentinel", 10, 11, 12)); final Table cj2 = left2.naturalJoin(right2, "Symbol"); TableTools.showWithIndex(cj2); assertEquals(new int[] {10, 11, NULL_INT, 10}, intColumn(cj2, "RightSentinel")); final int collision = 16384; final Table left3 = newTable(lC.make("Int", 10, collision + 10, collision * 2 + 10, collision * 3 + 10), c("LeftSentinel", 1, 3, 3, 4)); final Table right3 = newTable(c("Int", 10, collision + 10, collision * 4 + 10), c("RightSentinel", 10, 11, 13)); TableTools.show(left3); TableTools.show(right3); final Table cj3 = left3.naturalJoin(right3, "Int"); TableTools.showWithIndex(cj3); assertEquals(new int[] {10, 11, NULL_INT, NULL_INT}, intColumn(cj3, "RightSentinel")); final Table left4 = newTable( lC.make("String", "c", "e", "g"), c("LeftSentinel", 1, 2, 3)); final Table right4 = newTable(c("String", "c", "e"), c("RightSentinel", 10, 11)); final Table cj4 = left4.naturalJoin(right4, "String"); TableTools.showWithIndex(cj4); assertEquals(new int[] {10, 11, NULL_INT}, intColumn(cj4, "RightSentinel")); final Table left5 = newTable( lC.make("String", "c", "e", "g"), c("LeftSentinel", 1, 2, 3)); final Table right5 = newTable(c("RightSentinel", 10)); final Table cj5 = left5.naturalJoin(right5, ""); TableTools.showWithIndex(cj5); assertEquals(new int[] {10, 10, 10}, intColumn(cj5, "RightSentinel")); final Table left6 = newTable( lC.make("String", "c", "e", "g"), c("LeftSentinel", 1, 2, 3)); final Table right6 = newTable(intCol("RightSentinel")); final Table cj6 = left6.naturalJoin(right6, ""); TableTools.showWithIndex(cj6); assertEquals(new int[] {NULL_INT, NULL_INT, NULL_INT}, intColumn(cj6, "RightSentinel")); final Table left7 = newTable( lC.make("String", CollectionUtil.ZERO_LENGTH_STRING_ARRAY), intCol("LeftSentinel")); final Table right7 = newTable(intCol("RightSentinel", 10, 11)); final Table cj7 = left7.naturalJoin(right7, ""); TableTools.showWithIndex(cj7); assertEquals(0, cj7.size()); // inactive right hand side state, build using the left final Table left8 = newTable(lC.make("Symbol", "A", "B", "C"), c("LeftSentinel", 1, 2, 3)); final Table right8 = newTable(c("Symbol", "A", "B", "D", "D", "E", "E", "D"), c("RightSentinel", 10, 11, 12, 13, 14, 15, 16)); final Table cj8 = left8.naturalJoin(right8, "Symbol"); TableTools.showWithIndex(cj8); assertEquals(new int[] {10, 11, NULL_INT}, intColumn(cj8, "RightSentinel")); // inactive right hand side state, build using the right final Table left9 = newTable(lC.make("Symbol", "A", "B", "C", "A", "B", "C"), c("LeftSentinel", 1, 2, 3, 4, 5, 6)); final Table right9 = newTable(c("Symbol", "A", "D", "D"), c("RightSentinel", 10, 11, 12)); final Table cj9 = left9.naturalJoin(right9, "Symbol"); TableTools.showWithIndex(cj9); assertEquals(new int[] {10, NULL_INT, NULL_INT, 10, NULL_INT, NULL_INT}, intColumn(cj9, "RightSentinel")); } public void testNaturalJoinDuplicateRights() { // build from right final Table left = testTable(c("Symbol", "A", "B", "C", "D"), c("LeftSentinel", 1, 2, 3, 4)); final Table right = newTable(c("Symbol", "A", "A"), c("RightSentinel", 10, 11)); try { final Table cj = left.naturalJoin(right, "Symbol"); TableTools.showWithIndex(cj); fail("Expected exception."); } catch (IllegalStateException e) { assertEquals("More than one right side mapping for A", e.getMessage()); } // build from left final Table left2 = testTable(c("Symbol", "A", "B"), c("LeftSentinel", 1, 2)); final Table right2 = newTable(c("Symbol", "A", "A", "B", "C", "D"), c("RightSentinel", 10, 11, 12, 13, 14)); try { final Table cj2 = left2.naturalJoin(right2, "Symbol"); TableTools.showWithIndex(cj2); fail("Expected exception"); } catch (IllegalStateException e) { assertEquals("More than one right side mapping for A", e.getMessage()); } } public void testNaturalJoinDuplicateRightsRefreshingRight() { // initial case final Table left = testTable(c("Symbol", "A", "B"), c("LeftSentinel", 1, 2)); final Table right = testRefreshingTable(c("Symbol", "A", "A"), c("RightSentinel", 10, 11)); try { final Table cj = left.naturalJoin(right, "Symbol"); TableTools.showWithIndex(cj); fail("Expected exception."); } catch (IllegalStateException rte) { assertEquals("Duplicate right key for A", rte.getMessage()); } // bad right key added final QueryTable right2 = testRefreshingTable(c("Symbol", "A"), c("RightSentinel", 10)); final Table cj2 = left.naturalJoin(right2, "Symbol"); assertTableEquals( newTable(col("Symbol", "A", "B"), intCol("LeftSentinel", 1, 2), intCol("RightSentinel", 10, NULL_INT)), cj2); final ErrorListener listener = new ErrorListener((DynamicTable) cj2); ((DynamicTable) cj2).listenForUpdates(listener); try (final ErrorExpectation ignored = new ErrorExpectation()) { LiveTableMonitor.DEFAULT.runWithinUnitTestCycle(() -> { TstUtils.addToTable(right2, i(3), c("Symbol", "A"), intCol("RightSentinel", 10)); right2.notifyListeners(i(3), i(), i()); }); } assertNotNull(listener.originalException); assertEquals("Duplicate right key for A", listener.originalException.getMessage()); } public void testNaturalJoinDuplicateRightsRefreshingBoth() { // build from right final Table left = testRefreshingTable(c("Symbol", "A", "B"), c("LeftSentinel", 1, 2)); final Table right = testRefreshingTable(c("Symbol", "A", "A"), c("RightSentinel", 10, 11)); try { final Table cj = left.naturalJoin(right, "Symbol"); TableTools.showWithIndex(cj); fail("Expected exception."); } catch (IllegalStateException rte) { assertEquals("Duplicate right key for A", rte.getMessage()); } // bad right key added final QueryTable right2 = testRefreshingTable(c("Symbol", "A"), c("RightSentinel", 10)); final Table cj2 = left.naturalJoin(right2, "Symbol"); assertTableEquals( newTable(col("Symbol", "A", "B"), intCol("LeftSentinel", 1, 2), intCol("RightSentinel", 10, NULL_INT)), cj2); final ErrorListener listener = new ErrorListener((DynamicTable) cj2); ((DynamicTable) cj2).listenForUpdates(listener); try (final ErrorExpectation ignored = new ErrorExpectation()) { LiveTableMonitor.DEFAULT.runWithinUnitTestCycle(() -> { TstUtils.addToTable(right2, i(3), c("Symbol", "A"), intCol("RightSentinel", 10)); right2.notifyListeners(i(3), i(), i()); }); } assertNotNull(listener.originalException); assertEquals("Duplicate right key for A", listener.originalException.getMessage()); } public void testNaturalJoinReinterprets() { final Table left = testTable(c("JBool", true, false, null, true), c("LeftSentinel", 1, 2, 3, 4)); final Table right = newTable(c("JBool", true, false, null), c("RightSentinel", 10, 11, 12)); final Table cj = left.naturalJoin(right, "JBool"); TableTools.showWithIndex(cj); assertEquals(new int[] {10, 11, 12, 10}, intColumn(cj, "RightSentinel")); final DBDateTime time1 = DBTimeUtils.convertDateTime("2019-05-10T09:45:00 NY"); final DBDateTime time2 = DBTimeUtils.convertDateTime("2019-05-10T21:45:00 NY"); final Table left2 = testTable(c("JDate", time1, time2, null, time2), c("LeftSentinel", 1, 2, 3, 4)); final Table right2 = newTable(c("JDate", time2, time1, null), c("RightSentinel", 10, 11, 12)); final Table cj2 = left2.naturalJoin(right2, "JDate"); TableTools.showWithIndex(cj2); assertEquals(new int[] {11, 10, 12, 10}, intColumn(cj2, "RightSentinel")); } public void testNaturalJoinFloats() { final Table left = testTable(floatCol("JF", 1.0f, 2.0f, Float.NaN, 3.0f), c("LeftSentinel", 1, 2, 3, 4)); final Table right = newTable(floatCol("JF", Float.NaN, 1.0f, 2.0f), c("RightSentinel", 10, 11, 12)); final Table cj = left.naturalJoin(right, "JF"); TableTools.showWithIndex(cj); assertEquals(new int[] {11, 12, 10, NULL_INT}, intColumn(cj, "RightSentinel")); final Table left2 = testTable(doubleCol("JD", 10.0, 20.0, Double.NaN, io.deephaven.util.QueryConstants.NULL_DOUBLE), c("LeftSentinel", 1, 2, 3, 4)); final Table right2 = newTable(doubleCol("JD", QueryConstants.NULL_DOUBLE, Double.NaN, 10.0), c("RightSentinel", 10, 11, 12)); final Table cj2 = left2.naturalJoin(right2, "JD"); TableTools.showWithIndex(cj2); assertEquals(new int[] {12, NULL_INT, 11, 10}, intColumn(cj2, "RightSentinel")); } public void testNaturalJoinZeroKeys() { setExpectError(false); final QueryTable c0 = TstUtils.testRefreshingTable(intCol("Left", 1, 2, 3)); final QueryTable c1 = TstUtils.testRefreshingTable(intCol("Right")); final Table cj = c0.naturalJoin(c1, ""); final DynamicTable emptyRightResult = newTable(intCol("Left", 1, 2, 3), intCol("Right", NULL_INT, NULL_INT, NULL_INT)); assertTableEquals(emptyRightResult, cj); TableTools.showWithIndex(cj); LiveTableMonitor.DEFAULT.runWithinUnitTestCycle(() -> { addToTable(c1, i(1), intCol("Right", 4)); c1.notifyListeners(i(1), i(), i()); }); TableTools.showWithIndex(cj); final DynamicTable fourRightResult = newTable(intCol("Left", 1, 2, 3), intCol("Right", 4, 4, 4)); assertTableEquals(fourRightResult, cj); LiveTableMonitor.DEFAULT.runWithinUnitTestCycle(() -> { removeRows(c1, i(1)); c1.notifyListeners(i(), i(1), i()); }); TableTools.showWithIndex(cj); assertTableEquals(emptyRightResult, cj); LiveTableMonitor.DEFAULT.runWithinUnitTestCycle(() -> { addToTable(c0, i(6), intCol("Left", 6)); addToTable(c1, i(2), intCol("Right", 5)); c0.notifyListeners(i(6), i(), i()); c1.notifyListeners(i(2), i(), i()); }); TableTools.showWithIndex(cj); final DynamicTable fiveResult = newTable(intCol("Left", 1, 2, 3, 6), intCol("Right", 5, 5, 5, 5)); assertTableEquals(fiveResult, cj); } public void testNaturalJoinZeroKeysStaticRight() { setExpectError(false); final QueryTable c0 = TstUtils.testRefreshingTable(intCol("Left", 1, 2, 3)); final Table c1 = newTable(intCol("Right")); final Table c2 = newTable(intCol("Right", 4)); final Table cj1 = c0.naturalJoin(c1, ""); assertTableEquals(newTable(intCol("Left", 1, 2, 3), intCol("Right", NULL_INT, NULL_INT, NULL_INT)), cj1); LiveTableMonitor.DEFAULT.runWithinUnitTestCycle(() -> { addToTable(c0, i(6), intCol("Left", 6)); c0.notifyListeners(i(6), i(), i()); }); TableTools.showWithIndex(cj1); assertTableEquals(newTable(intCol("Left", 1, 2, 3, 6), intCol("Right", NULL_INT, NULL_INT, NULL_INT, NULL_INT)), cj1); final Table cj2 = c0.naturalJoin(c2, ""); assertTableEquals(newTable(intCol("Left", 1, 2, 3, 6), intCol("Right", 4, 4, 4, 4)), cj2); LiveTableMonitor.DEFAULT.runWithinUnitTestCycle(() -> { addToTable(c0, i(7), intCol("Left", 7)); c0.notifyListeners(i(7), i(), i()); }); TableTools.showWithIndex(cj1); assertTableEquals(newTable(intCol("Left", 1, 2, 3, 6, 7), intCol("Right", 4, 4, 4, 4, 4)), cj2); } public void testNaturalJoinZeroKeysStaticLeft() { setExpectError(false); final Table c0 = newTable(intCol("Left", 1, 2, 3)); final QueryTable c1 = TstUtils.testRefreshingTable(intCol("Right")); final Table cj = c0.naturalJoin(c1, ""); final DynamicTable emptyRightResult = newTable(intCol("Left", 1, 2, 3), intCol("Right", NULL_INT, NULL_INT, NULL_INT)); assertTableEquals(emptyRightResult, cj); TableTools.showWithIndex(cj); LiveTableMonitor.DEFAULT.runWithinUnitTestCycle(() -> { addToTable(c1, i(1), intCol("Right", 4)); c1.notifyListeners(i(1), i(), i()); }); TableTools.showWithIndex(cj); final DynamicTable fourRightResult = newTable(intCol("Left", 1, 2, 3), intCol("Right", 4, 4, 4)); assertTableEquals(fourRightResult, cj); LiveTableMonitor.DEFAULT.runWithinUnitTestCycle(() -> { removeRows(c1, i(1)); c1.notifyListeners(i(), i(1), i()); }); TableTools.showWithIndex(cj); assertTableEquals(emptyRightResult, cj); TableTools.showWithIndex(cj); assertTableEquals(emptyRightResult, cj); } public void testNaturalJoin() { final Table c0 = TstUtils.testRefreshingTable(c("USym0", "A", "B"), intCol("X", 1, 2)); final Table c1 = TstUtils.testRefreshingTable(c("USym1", "A", "D"), intCol("Y", 1, 2)); Table cj = c0.naturalJoin(c1, "USym0=USym1", "Y"); cj.select(); cj = c0.naturalJoin(c1, "USym0=USym1", "USym1,Y"); cj.select(); final Table lTable = TstUtils.testRefreshingTable( c("String", "a", "b", "c"), intCol("Int", 1, 2, 3)); final Table rTable = TstUtils.testRefreshingTable( c("String", "a", "b", "c"), intCol("Int", 10, 20, 30)); final Table result = lTable.naturalJoin(rTable, "String", "Int2=Int"); assertEquals(3, result.size()); assertEquals(3, result.getColumns().length); assertEquals("String", result.getColumns()[0].getName()); assertEquals("Int", result.getColumns()[1].getName()); assertEquals("Int2", result.getColumns()[2].getName()); assertEquals(Arrays.asList("a", "b", "c"), Arrays.asList(result.getColumn("String").get(0, 3))); assertEquals(Arrays.asList(1, 2, 3), Arrays.asList(result.getColumn("Int").get(0, 3))); assertEquals(Arrays.asList(10, 20, 30), Arrays.asList(result.getColumn("Int2").get(0, 3))); Table table1 = TstUtils.testRefreshingTable( c("String", "c", "e", "g")); Table table2 = TstUtils.testRefreshingTable(c("String", "c", "e"), c("v", 1, 2)); Table pairMatch = table1.naturalJoin(table2, "String", "v"); assertEquals(3, pairMatch.size()); assertEquals(2, pairMatch.getColumns().length); assertEquals("String", pairMatch.getColumns()[0].getName()); assertEquals("v", pairMatch.getColumns()[1].getName()); assertEquals(String.class, pairMatch.getColumns()[0].getType()); assertEquals(int.class, pairMatch.getColumns()[1].getType()); assertEquals(asList("c", "e", "g"), asList((Object[]) pairMatch.getColumns()[0].getDirect())); assertEquals(asList(1, 2, null), asList(pairMatch.getColumn("v").get(0, 3))); table2 = TstUtils.testRefreshingTable( c("String", "c", "e", "g"), c("v", 1, 2, 3)); pairMatch = table1.naturalJoin(table2, "String", "v"); assertEquals(3, pairMatch.size()); assertEquals(2, pairMatch.getColumns().length); assertEquals("String", pairMatch.getColumns()[0].getName()); assertEquals("v", pairMatch.getColumns()[1].getName()); assertEquals(String.class, pairMatch.getColumns()[0].getType()); assertEquals(int.class, pairMatch.getColumns()[1].getType()); assertEquals(asList("c", "e", "g"), asList((Object[]) pairMatch.getColumns()[0].getDirect())); assertEquals(asList(1, 2, 3), asList(pairMatch.getColumn("v").get(0, 3))); pairMatch = table2.naturalJoin(table1, "String", ""); assertEquals(3, pairMatch.size()); assertEquals(2, pairMatch.getColumns().length); assertEquals("String", pairMatch.getColumns()[0].getName()); assertEquals("v", pairMatch.getColumns()[1].getName()); assertEquals(String.class, pairMatch.getColumns()[0].getType()); assertEquals(int.class, pairMatch.getColumns()[1].getType()); assertEquals(asList("c", "e", "g"), asList((Object[]) pairMatch.getColumns()[0].getDirect())); assertEquals(asList(1, 2, 3), asList(pairMatch.getColumn("v").get(0, 3))); pairMatch = table1.naturalJoin(table2, "String=String", "v"); assertEquals(3, pairMatch.size()); assertEquals(2, pairMatch.getColumns().length); assertEquals("String", pairMatch.getColumns()[0].getName()); assertEquals("v", pairMatch.getColumns()[1].getName()); assertEquals(String.class, pairMatch.getColumns()[0].getType()); assertEquals(int.class, pairMatch.getColumns()[1].getType()); assertEquals(asList("c", "e", "g"), asList((Object[]) pairMatch.getColumns()[0].getDirect())); assertEquals(asList(1, 2, 3), asList(pairMatch.getColumn("v").get(0, 3))); pairMatch = table2.naturalJoin(table1, "String=String", ""); assertEquals(3, pairMatch.size()); assertEquals(2, pairMatch.getColumns().length); assertEquals("String", pairMatch.getColumns()[0].getName()); assertEquals("v", pairMatch.getColumns()[1].getName()); assertEquals(String.class, pairMatch.getColumns()[0].getType()); assertEquals(int.class, pairMatch.getColumns()[1].getType()); assertEquals(asList("c", "e", "g"), asList((Object[]) pairMatch.getColumns()[0].getDirect())); assertEquals(1, pairMatch.getColumn("v").getInt(0)); assertEquals(2, pairMatch.getColumn("v").getInt(1)); assertEquals(3, pairMatch.getColumn("v").getInt(2)); table1 = TstUtils.testRefreshingTable( c("String1", "c", "e", "g")); table2 = TstUtils.testRefreshingTable( c("String2", "c", "e", "g"), c("v", 1, 2, 3)); pairMatch = table1.naturalJoin(table2, "String1=String2", "String2,v"); assertEquals(3, pairMatch.size()); assertEquals(3, pairMatch.getColumns().length); assertEquals("String1", pairMatch.getColumns()[0].getName()); assertEquals("String2", pairMatch.getColumns()[1].getName()); assertEquals("v", pairMatch.getColumns()[2].getName()); assertEquals(String.class, pairMatch.getColumns()[0].getType()); assertEquals(String.class, pairMatch.getColumns()[1].getType()); assertEquals(int.class, pairMatch.getColumns()[2].getType()); assertEquals(asList("c", "e", "g"), asList((Object[]) pairMatch.getColumns()[0].getDirect())); assertEquals(asList("c", "e", "g"), asList((Object[]) pairMatch.getColumns()[1].getDirect())); assertEquals(asList(1, 2, 3), asList(pairMatch.getColumns()[2].get(0, 3))); pairMatch = table2.naturalJoin(table1, "String2=String1", "String1"); assertEquals(3, pairMatch.size()); assertEquals(3, pairMatch.getColumns().length); assertEquals("String2", pairMatch.getColumns()[0].getName()); assertEquals("v", pairMatch.getColumns()[1].getName()); assertEquals("String1", pairMatch.getColumns()[2].getName()); assertEquals(String.class, pairMatch.getColumn("String1").getType()); assertEquals(String.class, pairMatch.getColumn("String2").getType()); assertEquals(int.class, pairMatch.getColumn("v").getType()); assertEquals(asList("c", "e", "g"), asList((Object[]) pairMatch.getColumn("String1").getDirect())); assertEquals(asList("c", "e", "g"), asList((Object[]) pairMatch.getColumn("String2").getDirect())); assertEquals(asList(1, 2, 3), asList(pairMatch.getColumn("v").get(0, 3))); } public void testNaturalJoinNull() { final Table c0 = TstUtils.testRefreshingTable(c("USym0", "A", null), c("X", 1, 2)); final Table c1 = TstUtils.testRefreshingTable(c("USym1", "A", null), c("Y", 3, 4)); final Table cj = c0.naturalJoin(c1, "USym0=USym1", "Y"); TableTools.show(cj); assertEquals(1, cj.getColumn("X").get(0)); assertEquals(2, cj.getColumn("X").get(1)); assertEquals(3, cj.getColumn("Y").get(0)); assertEquals(4, cj.getColumn("Y").get(1)); } public void testNaturalJoinInactive() { setExpectError(false); final QueryTable c0 = TstUtils.testRefreshingTable(c("USym0", "A", "C"), c("X", 1, 2)); final QueryTable c1 = TstUtils.testRefreshingTable(c("USym1", "A", "B", "B"), c("Y", 3, 4, 5)); final Table cj = c0.naturalJoin(c1, "USym0=USym1", "Y"); System.out.println("Result:"); TableTools.showWithIndex(cj); assertEquals(1, cj.getColumn("X").get(0)); assertEquals(2, cj.getColumn("X").get(1)); assertEquals(3, cj.getColumn("Y").get(0)); assertNull(cj.getColumn("Y").get(1)); LiveTableMonitor.DEFAULT.runWithinUnitTestCycle(() -> { removeRows(c1, i(2)); c1.notifyListeners(i(), i(2), i()); }); System.out.println("Right:"); TableTools.showWithIndex(c1); assertEquals(1, cj.getColumn("X").get(0)); assertEquals(2, cj.getColumn("X").get(1)); assertEquals(3, cj.getColumn("Y").get(0)); assertNull(cj.getColumn("Y").get(1)); LiveTableMonitor.DEFAULT.runWithinUnitTestCycle(() -> { addToTable(c0, i(2), col("USym0", "B"), col("X", 6)); c0.notifyListeners(i(2), i(), i()); }); System.out.println("Left:"); TableTools.showWithIndex(c0); System.out.println("Result:"); TableTools.showWithIndex(cj); assertEquals(1, cj.getColumn("X").get(0)); assertEquals(2, cj.getColumn("X").get(1)); assertEquals(6, cj.getColumn("X").get(2)); assertEquals(3, cj.getColumn("Y").get(0)); assertNull(cj.getColumn("Y").get(1)); assertEquals(4, cj.getColumn("Y").get(2)); } public void testNaturalJoinLeftIncrementalRightStaticSimple() { final QueryTable leftQueryTable = TstUtils.testRefreshingTable(i(1, 2, 4, 6), c("Sym", "aa", "bc", "aa", "aa"), c("ByteCol", (byte) 10, (byte) 20, (byte) 30, (byte) 50), c("DoubleCol", 0.1, 0.2, 0.3, 0.5)); final QueryTable rightQueryTable = TstUtils.testTable(i(3, 6), c("RSym", "aa", "bc"), c("ByteCol", (byte) 10, (byte) 20), c("RDoubleCol", 1.1, 2.2)); final EvalNugget[] en = new EvalNugget[] { new EvalNugget() { public Table e() { return leftQueryTable.naturalJoin(rightQueryTable, "ByteCol", "RSym,RDoubleCol"); } } }; LiveTableMonitor.DEFAULT.runWithinUnitTestCycle(() -> { addToTable(leftQueryTable, i(3, 9), c("Sym", "aa", "aa"), c("ByteCol", (byte) 20, (byte) 10), c("DoubleCol", 2.1, 2.2)); System.out.println("Left Table Updated:"); showWithIndex(leftQueryTable); leftQueryTable.notifyListeners(i(3, 9), i(), i()); }); TstUtils.validate(en); LiveTableMonitor.DEFAULT.runWithinUnitTestCycle(() -> leftQueryTable.notifyListeners(i(), i(), i(1, 2, 4, 6))); TstUtils.validate(en); } public void testNaturalJoinIterative() { final QueryTable leftQueryTable = TstUtils.testRefreshingTable(i(1, 2, 4, 6), c("Sym", "aa", "bc", "aa", "aa"), c("intCol", 10, 20, 30, 50), c("doubleCol", 0.1, 0.2, 0.3, 0.5)); final QueryTable rightQueryTable1 = TstUtils.testRefreshingTable(i(3, 6), c("Sym", "aa", "bc"), c("xCol", 11, 22), c("yCol", 1.1, 2.2)); final QueryTable rightQueryTable2 = TstUtils.testRefreshingTable(i(10, 20, 30), c("Sym", "aa", "bc", "aa"), c("xCol", 11, 20, 20), c("yCol", 1.1, 2.2, 5.5)); final EvalNugget[] en = new EvalNugget[] { new EvalNugget() { public Table e() { return leftQueryTable.naturalJoin(rightQueryTable1, "Sym", "xCol,yCol"); } }, new EvalNugget() { public Table e() { return leftQueryTable.naturalJoin(rightQueryTable2, "Sym,intCol=xCol", "xCol,yCol"); } }, new EvalNugget() { public Table e() { return leftQueryTable.naturalJoin(rightQueryTable1, "Sym", "xCol,yCol").select(); } }, new EvalNugget() { public Table e() { return leftQueryTable.naturalJoin(rightQueryTable2, "Sym,intCol=xCol", "xCol,yCol").select(); } }, new EvalNugget() { public Table e() { return leftQueryTable.naturalJoin(rightQueryTable1, "Sym", "xCol,yCol").update("q=xCol+yCol"); } }, new EvalNugget() { public Table e() { return leftQueryTable.naturalJoin(rightQueryTable2, "Sym,intCol=xCol", "xCol,yCol") .update("q=xCol+yCol"); } }, new EvalNugget() { public Table e() { return leftQueryTable.select().naturalJoin(rightQueryTable1, "Sym", "xCol,yCol"); } }, new EvalNugget() { public Table e() { return leftQueryTable.select().naturalJoin(rightQueryTable2, "Sym,intCol=xCol", "xCol,yCol"); } }, new EvalNugget() { public Table e() { return leftQueryTable.select().naturalJoin(rightQueryTable1, "Sym", "xCol,yCol") .update("q=xCol+yCol"); } }, new EvalNugget() { public Table e() { return leftQueryTable.select().naturalJoin(rightQueryTable2, "Sym,intCol=xCol", "xCol,yCol") .select(); } }, new EvalNugget() { public Table e() { return leftQueryTable.select().naturalJoin(rightQueryTable1, "Sym", "xCol,yCol").select(); } }, new EvalNugget() { public Table e() { return leftQueryTable.select().naturalJoin(rightQueryTable2, "Sym,intCol=xCol", "xCol,yCol") .select(); } }, }; System.out.println("Left Table:"); TableTools.showWithIndex(leftQueryTable); System.out.println("Right Table 1:"); TableTools.showWithIndex(rightQueryTable1); LiveTableMonitor.DEFAULT.runWithinUnitTestCycle(() -> { addToTable(leftQueryTable, i(3, 9), c("Sym", "aa", "aa"), c("intCol", 20, 10), c("doubleCol", 2.1, 2.2)); System.out.println("Left Table Updated:"); showWithIndex(leftQueryTable); leftQueryTable.notifyListeners(i(3, 9), i(), i()); }); TstUtils.validate(en); LiveTableMonitor.DEFAULT.runWithinUnitTestCycle(() -> { addToTable(leftQueryTable, i(1, 9), c("Sym", "bc", "aa"), c("intCol", 30, 11), c("doubleCol", 2.1, 2.2)); leftQueryTable.notifyListeners(i(), i(), i(1, 9)); }); TstUtils.validate(en); LiveTableMonitor.DEFAULT.runWithinUnitTestCycle(() -> { addToTable(rightQueryTable1, i(3, 4), c("Sym", "ab", "ac"), c("xCol", 55, 33), c("yCol", 6.6, 7.7)); rightQueryTable1.notifyListeners(i(4), i(), i(3)); }); TstUtils.validate(en); LiveTableMonitor.DEFAULT.runWithinUnitTestCycle(() -> { show(rightQueryTable2); addToTable(rightQueryTable2, i(20, 40), c("Sym", "aa", "bc"), c("xCol", 30, 50), c("yCol", 1.3, 1.5)); show(rightQueryTable2); rightQueryTable2.notifyListeners(i(40), i(), i(20)); }); TstUtils.validate(en); LiveTableMonitor.DEFAULT.runWithinUnitTestCycle(() -> { addToTable(rightQueryTable1, i(4, 6), c("Sym", "bc", "aa"), c("xCol", 66, 44), c("yCol", 7.6, 6.7)); rightQueryTable1.notifyListeners(i(), i(), i(4, 6)); }); TstUtils.validate(en); LiveTableMonitor.DEFAULT.runWithinUnitTestCycle(() -> { addToTable(rightQueryTable1, i(4, 6), c("Sym", "bc", "aa"), c("xCol", 66, 44), c("yCol", 7.7, 6.8)); rightQueryTable1.notifyListeners(i(), i(), i(4, 6)); }); TstUtils.validate(en); LiveTableMonitor.DEFAULT.runWithinUnitTestCycle(() -> { addToTable(rightQueryTable1, i(4, 31), c("Sym", "aq", "bc"), c("xCol", 66, 44), c("yCol", 7.5, 6.9)); rightQueryTable1.notifyListeners(i(31), i(), i(4)); }); TstUtils.validate(en); LiveTableMonitor.DEFAULT.runWithinUnitTestCycle(() -> { addToTable(rightQueryTable2, i(20, 30), c("Sym", "aa", "aa"), c("xCol", 20, 30), c("yCol", 3.1, 5.1)); rightQueryTable2.notifyListeners(i(), i(), i(20, 30)); }); TstUtils.validate(en); LiveTableMonitor.DEFAULT.runWithinUnitTestCycle(() -> { TstUtils.removeRows(rightQueryTable1, i(4)); rightQueryTable1.notifyListeners(i(), i(4), i()); }); TstUtils.validate(en); LiveTableMonitor.DEFAULT.runWithinUnitTestCycle(() -> { addToTable(rightQueryTable2, i(40), c("Sym", "bc"), c("xCol", 20), c("yCol", 3.2)); TstUtils.removeRows(rightQueryTable2, i(20, 30)); rightQueryTable2.notifyListeners(i(), i(20, 30), i(40)); }); TstUtils.validate(en); LiveTableMonitor.DEFAULT.runWithinUnitTestCycle(() -> { TstUtils.removeRows(leftQueryTable, i(9)); dumpComplete(leftQueryTable, "Sym", "intCol"); leftQueryTable.notifyListeners(i(), i(9), i()); }); TstUtils.validate(en); } private void dumpComplete(QueryTable queryTable, String... columns) { final Index index = queryTable.getIndex(); final ColumnSource[] columnSources = new ColumnSource[columns.length]; for (int ii = 0; ii < columns.length; ++ii) { columnSources[ii] = queryTable.getColumnSourceMap().get(columns[ii]); } final StringBuilder sb = new StringBuilder(); sb.append("Complete Table has ").append(index.size()).append(" rows:\n"); sb.append("Index=").append(index).append("\n"); for (final Index.Iterator it = index.iterator(); it.hasNext();) { final long value = it.nextLong(); final Object[] keyValues = new Object[columns.length]; for (int ii = 0; ii < columns.length; ++ii) { keyValues[ii] = columnSources[ii].get(value); } sb.append(value).append("=").append(new SmartKey(keyValues)).append("\n"); } final Index prevIndex = index.getPrevIndex(); sb.append("Complete Previous Table has ").append(prevIndex.size()).append(" rows:\n"); sb.append("Index=").append(index).append("\n"); for (final Index.Iterator it = prevIndex.iterator(); it.hasNext();) { final long value = it.nextLong(); final Object[] keyValues = new Object[columns.length]; for (int ii = 0; ii < columns.length; ++ii) { keyValues[ii] = columnSources[ii].getPrev(value); } sb.append(value).append("=").append(new SmartKey(keyValues)).append("\n"); } System.out.println(sb); } public void testNaturalJoinIterative2() { final QueryTable leftQueryTable = TstUtils.testRefreshingTable(i(1, 2, 4, 6), c("Sym", "aa", "bc", "aa", "aa"), c("intCol", 10, 20, 30, 50), c("doubleCol", 0.1, 0.2, 0.3, 0.5)); final QueryTable rightQueryTable2 = TstUtils.testRefreshingTable(i(10, 20, 30), c("Sym", "aa", "bc", "aa"), c("xCol", 11, 20, 20), c("yCol", 1.1, 2.2, 5.5)); final EvalNugget[] en = new EvalNugget[] { new EvalNugget() { public Table e() { return leftQueryTable.naturalJoin(rightQueryTable2.lastBy("Sym"), "Sym", "xCol,yCol"); } }, new EvalNugget() { public Table e() { return leftQueryTable.naturalJoin(rightQueryTable2.lastBy("Sym"), "Sym", "xCol,yCol").select(); } } }; LiveTableMonitor.DEFAULT.runWithinUnitTestCycle(() -> { addToTable(leftQueryTable, i(3, 9), c("Sym", "aa", "aa"), c("intCol", 20, 10), c("doubleCol", 2.1, 2.2)); leftQueryTable.notifyListeners(i(3, 9), i(), i()); }); TstUtils.validate(en); LiveTableMonitor.DEFAULT.runWithinUnitTestCycle(() -> { addToTable(leftQueryTable, i(1, 9), c("Sym", "bc", "aa"), c("intCol", 30, 11), c("doubleCol", 2.1, 2.2)); leftQueryTable.notifyListeners(i(), i(), i(1, 9)); }); TstUtils.validate(en); LiveTableMonitor.DEFAULT.runWithinUnitTestCycle(() -> { show(rightQueryTable2); addToTable(rightQueryTable2, i(20, 40), c("Sym", "aa", "bc"), c("xCol", 30, 50), c("yCol", 1.3, 1.5)); show(rightQueryTable2); rightQueryTable2.notifyListeners(i(40), i(), i(20)); }); TstUtils.validate(en); LiveTableMonitor.DEFAULT.runWithinUnitTestCycle(() -> { addToTable(rightQueryTable2, i(20, 30), c("Sym", "aa", "aa"), c("xCol", 20, 30), c("yCol", 3.1, 5.1)); rightQueryTable2.notifyListeners(i(), i(), i(20, 30)); }); TstUtils.validate(en); LiveTableMonitor.DEFAULT.runWithinUnitTestCycle(() -> { addToTable(rightQueryTable2, i(40), c("Sym", "bc"), c("xCol", 20), c("yCol", 3.2)); TstUtils.removeRows(rightQueryTable2, i(20)); rightQueryTable2.notifyListeners(i(), i(20), i(40)); }); TstUtils.validate(en); LiveTableMonitor.DEFAULT.runWithinUnitTestCycle(() -> { TstUtils.removeRows(leftQueryTable, i(9)); leftQueryTable.notifyListeners(i(), i(9), i()); }); TstUtils.validate(en); } public void testNaturalJoinSortedData() { final QueryTable leftTable = TstUtils.testRefreshingTable( c("Sym", "a", "b", "c"), c("Size", 1, 2, 3)); final QueryTable rightTable = TstUtils.testRefreshingTable( c("Sym", "a", "b", "c"), c("Qty", 10, 20, 30)); final EvalNugget[] en = new EvalNugget[] { new EvalNugget() { public Table e() { return leftTable.naturalJoin(rightTable, "Sym", "Qty"); } }, new EvalNugget() { public Table e() { return leftTable.sortDescending("Size").naturalJoin(rightTable, "Sym", "Qty"); } }, new EvalNugget() { public Table e() { return leftTable.sortDescending("Size").naturalJoin(rightTable.sortDescending("Qty"), "Sym", "Qty"); } }, new EvalNugget() { public Table e() { return leftTable.naturalJoin(rightTable.sortDescending("Qty"), "Sym", "Qty"); } }, new EvalNugget() { public Table e() { return leftTable.sortDescending("Size") .naturalJoin(rightTable.sortDescending("Qty"), "Sym", "Qty").update("x = Qty*Size"); } }, new EvalNugget() { public Table e() { return leftTable.sortDescending("Size") .naturalJoin(rightTable.sortDescending("Qty"), "Sym", "Qty").updateView("x = Qty*Size"); } }, new EvalNugget() { public Table e() { return leftTable.sortDescending("Size") .naturalJoin(rightTable.sortDescending("Qty"), "Sym", "Qty") .view("Sym", "x = Qty*Size"); } }, new EvalNugget() { public Table e() { return leftTable.sortDescending("Size") .naturalJoin(rightTable.sortDescending("Qty"), "Sym", "Qty") .select("Sym", "x = Qty*Size"); } }, }; TstUtils.validate(en); LiveTableMonitor.DEFAULT.runWithinUnitTestCycle(() -> { addToTable(leftTable, i(0, 1, 2), c("Sym", "c", "a", "b"), c("Size", 1, 2, 3)); leftTable.notifyListeners(i(), i(), i(0, 1, 2)); }); TstUtils.validate(en); LiveTableMonitor.DEFAULT.runWithinUnitTestCycle(() -> { addToTable(rightTable, i(0, 1, 2), c("Sym", "b", "c", "a"), c("Qty", 10, 20, 30)); rightTable.notifyListeners(i(), i(), i(0, 1, 2)); }); TstUtils.validate(en); LiveTableMonitor.DEFAULT.runWithinUnitTestCycle(() -> { addToTable(leftTable, i(0, 1, 2), c("Sym", "a", "b", "c"), c("Size", 3, 1, 2)); leftTable.notifyListeners(i(), i(), i(0, 1, 2)); }); TstUtils.validate(en); LiveTableMonitor.DEFAULT.runWithinUnitTestCycle(() -> { addToTable(rightTable, i(0, 1, 2), c("Sym", "a", "b", "c"), c("Qty", 30, 10, 20)); rightTable.notifyListeners(i(), i(), i(0, 1, 2)); }); TstUtils.validate(en); LiveTableMonitor.DEFAULT.runWithinUnitTestCycle(() -> { addToTable(leftTable, i(3, 4), c("Sym", "d", "e"), c("Size", -1, 100)); leftTable.notifyListeners(i(3, 4), i(), i()); }); TstUtils.validate(en); LiveTableMonitor.DEFAULT.runWithinUnitTestCycle(() -> { addToTable(rightTable, i(3, 4), c("Sym", "e", "d"), c("Qty", -10, 50)); rightTable.notifyListeners(i(3, 4), i(), i()); }); TstUtils.validate(en); } public void testExactJoin() { Table table1 = testRefreshingTable( c("String", "c", "e", "g")); try { table1.exactJoin(testRefreshingTable(c("String", "c", "e"), c("v", 1, 2)), "String"); TestCase.fail("Previous statement should have thrown an exception"); } catch (Exception e) { assertEquals("Tables don't have one-to-one mapping - no mappings for key g.", e.getMessage()); } Table table2 = testRefreshingTable(c("String", "c", "e", "g"), c("v", 1, 2, 3)); Table pairMatch = table1.exactJoin(table2, "String"); assertEquals(3, pairMatch.size()); assertEquals(2, pairMatch.getColumns().length); assertEquals("String", pairMatch.getColumns()[0].getName()); assertEquals("v", pairMatch.getColumns()[1].getName()); assertEquals(String.class, pairMatch.getColumns()[0].getType()); assertEquals(int.class, pairMatch.getColumns()[1].getType()); assertEquals(asList("c", "e", "g"), asList((Object[]) pairMatch.getColumns()[0].getDirect())); assertEquals(asList(1, 2, 3), asList(pairMatch.getColumn("v").get(0, 3))); pairMatch = table2.exactJoin(table1, "String"); assertEquals(3, pairMatch.size()); assertEquals(2, pairMatch.getColumns().length); assertEquals("String", pairMatch.getColumns()[0].getName()); assertEquals("v", pairMatch.getColumns()[1].getName()); assertEquals(String.class, pairMatch.getColumns()[0].getType()); assertEquals(int.class, pairMatch.getColumns()[1].getType()); assertEquals(asList("c", "e", "g"), asList((Object[]) pairMatch.getColumns()[0].getDirect())); assertEquals(asList(1, 2, 3), asList(pairMatch.getColumn("v").get(0, 3))); pairMatch = table1.exactJoin(table2, "String=String"); assertEquals(3, pairMatch.size()); assertEquals(2, pairMatch.getColumns().length); assertEquals("String", pairMatch.getColumns()[0].getName()); assertEquals("v", pairMatch.getColumns()[1].getName()); assertEquals(String.class, pairMatch.getColumns()[0].getType()); assertEquals(int.class, pairMatch.getColumns()[1].getType()); assertEquals(asList("c", "e", "g"), asList((Object[]) pairMatch.getColumns()[0].getDirect())); assertEquals(asList(1, 2, 3), asList(pairMatch.getColumn("v").get(0, 3))); pairMatch = table2.exactJoin(table1, "String=String"); assertEquals(3, pairMatch.size()); assertEquals(2, pairMatch.getColumns().length); assertEquals("String", pairMatch.getColumns()[0].getName()); assertEquals("v", pairMatch.getColumns()[1].getName()); assertEquals(String.class, pairMatch.getColumns()[0].getType()); assertEquals(int.class, pairMatch.getColumns()[1].getType()); assertEquals(asList("c", "e", "g"), asList((Object[]) pairMatch.getColumns()[0].getDirect())); assertEquals(1, pairMatch.getColumn("v").getInt(0)); assertEquals(2, pairMatch.getColumn("v").getInt(1)); assertEquals(3, pairMatch.getColumn("v").getInt(2)); table1 = testRefreshingTable(c("String1", "c", "e", "g")); table2 = testRefreshingTable(c("String2", "c", "e", "g"), c("v", 1, 2, 3)); pairMatch = table1.exactJoin(table2, "String1=String2"); assertEquals(3, pairMatch.size()); assertEquals(3, pairMatch.getColumns().length); assertEquals("String1", pairMatch.getColumns()[0].getName()); assertEquals("String2", pairMatch.getColumns()[1].getName()); assertEquals("v", pairMatch.getColumns()[2].getName()); assertEquals(String.class, pairMatch.getColumns()[0].getType()); assertEquals(String.class, pairMatch.getColumns()[1].getType()); assertEquals(int.class, pairMatch.getColumns()[2].getType()); assertEquals(asList("c", "e", "g"), asList((Object[]) pairMatch.getColumns()[0].getDirect())); assertEquals(asList("c", "e", "g"), asList((Object[]) pairMatch.getColumns()[1].getDirect())); assertEquals(asList(1, 2, 3), asList(pairMatch.getColumns()[2].get(0, 3))); pairMatch = table2.exactJoin(table1, "String2=String1"); assertEquals(3, pairMatch.size()); assertEquals(3, pairMatch.getColumns().length); assertEquals("String2", pairMatch.getColumns()[0].getName()); assertEquals("v", pairMatch.getColumns()[1].getName()); assertEquals("String1", pairMatch.getColumns()[2].getName()); assertEquals(String.class, pairMatch.getColumn("String1").getType()); assertEquals(String.class, pairMatch.getColumn("String2").getType()); assertEquals(int.class, pairMatch.getColumn("v").getType()); assertEquals(asList("c", "e", "g"), asList((Object[]) pairMatch.getColumn("String1").getDirect())); assertEquals(asList("c", "e", "g"), asList((Object[]) pairMatch.getColumn("String2").getDirect())); assertEquals(asList(1, 2, 3), asList(pairMatch.getColumn("v").get(0, 3))); } public void testSymbolTableJoin() throws IOException { diskBackedTestHarness((left, right) -> { final Table result = left.naturalJoin(right, "Symbol"); TableTools.showWithIndex(result); final int[] rightSide = intColumn(result, "RightSentinel"); assertEquals(new int[] {101, 102, 103, NULL_INT, 101, 103, 102, 102, 103}, rightSide); }); } private void diskBackedTestHarness(BiConsumer<Table, Table> testFunction) throws IOException { final File leftDirectory = Files.createTempDirectory("QueryTableJoinTest-Left").toFile(); final File rightDirectory = Files.createTempDirectory("QueryTableJoinTest-Right").toFile(); try { final Table leftTable = makeLeftDiskTable(new File(leftDirectory, "Left.parquet")); final Table rightTable = makeRightDiskTable(new File(rightDirectory, "Right.parquet")); testFunction.accept(leftTable, rightTable); leftTable.close(); rightTable.close(); } finally { FileUtils.deleteRecursively(leftDirectory); FileUtils.deleteRecursively(rightDirectory); } } @NotNull private Table makeLeftDiskTable(File leftLocation) throws IOException { final TableDefinition leftDefinition = TableDefinition.of( ColumnDefinition.ofString("Symbol"), ColumnDefinition.ofInt("LeftSentinel")); final String[] leftSyms = new String[] {"Apple", "Banana", "Cantaloupe", "DragonFruit", "Apple", "Cantaloupe", "Banana", "Banana", "Cantaloupe"}; final Table leftTable = newTable(stringCol("Symbol", leftSyms)).update("LeftSentinel=i"); ParquetTools.writeTable(leftTable, leftLocation, leftDefinition); return ParquetTools.readTable(leftLocation); } @NotNull private Table makeRightDiskTable(File rightLocation) throws IOException { final TableDefinition rightDefinition = TableDefinition.of( ColumnDefinition.ofString("Symbol"), ColumnDefinition.ofInt("RightSentinel")); final String[] rightSyms = new String[] {"Elderberry", "Apple", "Banana", "Cantaloupe"}; final Table rightTable = newTable(stringCol("Symbol", rightSyms)).update("RightSentinel=100+i"); ParquetTools.writeTable(rightTable, rightLocation, rightDefinition); return ParquetTools.readTable(rightLocation); } }
/* * Copyright 2011 castLabs, Berlin * * 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.googlecode.mp4parser.boxes.mp4.objectdescriptors; import com.coremedia.iso.Hex; import java.io.IOException; import java.nio.ByteBuffer; import java.util.logging.Logger; /** * abstract class ExtensionDescriptor extends BaseDescriptor * : bit(8) tag = ExtensionProfileLevelDescrTag, ExtDescrTagStartRange .. * ExtDescrTagEndRange { * // empty. To be filled by classes extending this class. * } */ @Descriptor(tags = {0x13, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253}) public class ExtensionDescriptor extends BaseDescriptor { private static Logger log = Logger.getLogger(ExtensionDescriptor.class.getName()); byte[] bytes; //todo: add this better to the tags list? //14496-1:2010 p.20: //0x6A-0xBF Reserved for ISO use //0xC0-0xFE User private // //ExtDescrTagStartRange = 0x6A //ExtDescrTagEndRange = 0xFE static int[] allTags() { int[] ints = new int[0xFE - 0x6A]; for (int i = 0x6A; i < 0xFE; i++) { final int pos = i - 0x6A; log.finest("pos:" + pos); ints[pos] = i; } return ints; } @Override public void parseDetail(ByteBuffer bb) throws IOException { if (getSize() > 0) { bytes = new byte[sizeOfInstance]; bb.get(bytes); } } @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append("ExtensionDescriptor"); sb.append("{bytes=").append(bytes == null ? "null" : Hex.encodeHex(bytes)); sb.append('}'); return sb.toString(); } }
/** * TLS-Attacker - A Modular Penetration Testing Framework for TLS * * Copyright 2014-2017 Ruhr University Bochum / Hackmanit GmbH * * Licensed under Apache License 2.0 * http://www.apache.org/licenses/LICENSE-2.0 */ package de.rub.nds.tlsattacker.core.https; import de.rub.nds.tlsattacker.core.constants.ProtocolVersion; import de.rub.nds.tlsattacker.core.state.TlsContext; import org.junit.Before; import org.junit.Test; import java.nio.charset.Charset; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class HttpsRequestHandlerTest { private TlsContext context; private HttpsRequestMessage message; private HttpsRequestHandler handler; @Before public void setUp() { context = new TlsContext(); String rawMessage = "GET /index.html HTTP/1.1\r\nUser-Agent: Test\r\nHost: www.rub.de\r\n\r\n"; HttpsRequestParser parser = new HttpsRequestParser(0, rawMessage.getBytes(Charset.forName("UTF-8")), ProtocolVersion.TLS12); message = parser.parse(); handler = new HttpsRequestHandler(context); } @Test public void testGetParser() { assertTrue(handler.getParser(new byte[1], 0) instanceof HttpsRequestParser); } @Test public void testGetPreparator() { assertTrue(handler.getPreparator(new HttpsRequestMessage()) instanceof HttpsRequestPreparator); } @Test public void testGetSerializer() { assertTrue(handler.getSerializer(new HttpsRequestMessage()) instanceof HttpsRequestSerializer); } @Test public void testAdjustTLSContext() { handler.adjustTLSContext(message); assertEquals(context.getHttpContext().getLastRequestPath(), message.getRequestPath().getValue()); } }
// Targeted by JavaCPP version 1.5.6: DO NOT EDIT THIS FILE package org.bytedeco.ale; import java.nio.*; import org.bytedeco.javacpp.*; import org.bytedeco.javacpp.annotation.*; import static org.bytedeco.javacpp.presets.javacpp.*; import static org.bytedeco.ale.global.ale.*; @Opaque @Properties(inherit = org.bytedeco.ale.presets.ale.class) public class RomSettings extends Pointer { /** Empty constructor. Calls {@code super((Pointer)null)}. */ public RomSettings() { super((Pointer)null); } /** Pointer cast constructor. Invokes {@link Pointer#Pointer(Pointer)}. */ public RomSettings(Pointer p) { super(p); } }
package com.iqarr.maven.plugin.utils; import java.io.File; import java.util.List; import com.iqarr.maven.plugin.constant.JCVConstant; import com.iqarr.maven.plugin.domain.JCVConfig; import com.iqarr.maven.plugin.domain.JCVFileInfo; import com.iqarr.maven.plugin.domain.JCVMethodEnum; /** * @author * zhangyong */ public class BaseUtils { /** * * 比较数组是否相等 * * @param source * @param startIndex * @param comparisonSource * @return */ public static boolean comparisonCharArray(final char[] source, final int startIndex, final char[] comparisonSource) { int sourceLenth = source.length; int comLenth = comparisonSource.length; for (int i = 0; i < comLenth; i++) { if (sourceLenth <= (i + startIndex)) { return false; } else { if (source[startIndex + i] == comparisonSource[i]) { if (i == (comLenth - 1)) { return true; } else { continue; } } else { return false; } } } return false; } /** * * 比较数组是否相等(向上比较) * * @param source * @param startIndex * @param comparisonSource * @return */ public static boolean comparisonUpCharArray(final char[] source, final int startIndex, final char[] comparisonSource) { int sourceLenth = source.length; int comLenth = comparisonSource.length; for (int i = 0,j=comLenth-1;(i<sourceLenth-startIndex && j>=0); i++,j--) { if (source[startIndex - i] == comparisonSource[j]) { if (j==0) { return true; } else { continue; } } else { return false; } } return false; } /** * * 检查下一个字符串位置 * * @param cas * @param index * @param chars * @return */ public static int checkNextStrIndex(final char[] cas, final int index, final String chars) { char[] sub = chars.toCharArray(); if (sub.length < 0) { return -1; } for (int i = index; i < cas.length; i++) { if (cas[i] == sub[0]) { for (int subI = 0; subI < sub.length; subI++) { if (cas[i + subI] != sub[subI]) { break; } else { if (subI == sub.length - 1) { return i; } } } } } return -1; } /** * * 检查上一个字符的位置 * * @param cas * @param index * @param chars * @return */ public static int checkUpStrIndex(final char[] cas, final int index, final String chars) { char[] sub = chars.toCharArray(); if (sub.length < 0) { return -1; } for (int i = index; i >= 0; i--) { if (cas[i] == sub[0]) { for (int subI = 0; subI < sub.length; subI++) { if (cas[i + subI] != sub[subI]) { break; } else { if (subI == sub.length - 1) { return i; } } } } } return -1; } public static int checkNextCharIndex(final char[] cas, final int index, final char[] sub) { for (int i = index; i < cas.length; i++) { if (cas[i] == sub[0]) { for (int subI = 0; subI < sub.length; subI++) { if (cas[i + subI] != sub[subI]) { break; } else { if (subI == sub.length - 1) { return i; } } } } } return -1; } /** * * 检查下一个字符位置 * @param cas * @param index * @param cr * @return */ public static int checkNextCharIndex(final char[] cas, final int index, final char cr) { char[] sub = new char[1]; sub[0] = cr; return checkNextCharIndex(cas, index, sub); } /** * * 检查str是否在list中 * @param checkStr * @param list * @param isLike 是否模糊匹配(暂时未实现) * @return true 在 */ public static boolean checkStrIsInList(final String checkStr,final List<String> list,final boolean isLike){ if(null==checkStr || "".equals(checkStr) ){ return false; } if(list ==null){ return false; } if(isLike){ //模糊 return list.contains(checkStr); }else { return list.contains(checkStr); } } /** * * 替换字符串中的所有单个字符 * @param str * @param hisStr * @param replacement * @return */ public static String replaceAll(final String str,final char hisStr,final char replacement){ char[] sub = str.toCharArray(); StringBuilder sb=new StringBuilder(); int size=sub.length; for(int i=0;i<size;i++){ if(sub[i]==hisStr){ sb.append(replacement); }else { sb.append(sub[i]); } } return sb.toString(); } /** * * <p>替换文件路径为linux 路径</p> * @param path * @return */ public static String replaceLinuxSystemLine(final String path){ if(FileUtils.getSystemFileSeparatorIslinux()){ //linux return path; }else { if(path==null || "".equals(path)){ return path; } //windows return replaceAll(path,'\\','/'); } } /** * * 转换为当前系统路径 * @param path * @return */ public static String replacecurrentSystemLine(final String path){ if(FileUtils.getSystemFileSeparatorIslinux()){ //linux return replaceAll(path,'\\','/'); }else { //windows return replaceAll(path,'/','\\'); } } /** * * 获取文件输出路径 * @param jcv * @param isCompression 是否压缩 * @param meth 处理方法 * @return */ public static String getJSSCSSOutPath(final JCVFileInfo jcv,final boolean isCompression, final JCVMethodEnum meth,final String outDir ,final JCVConfig jCVConfig,final String ... userCompressionSuffix ) { StringBuilder tempPath=new StringBuilder(); if(outDir!=null ){ tempPath.append(outDir); } if (!outDir.endsWith(FileUtils.getSystemFileSeparator())) { tempPath.append(FileUtils.getSystemFileSeparator()); } //添加alise if(JCVFileInfo.CSS.equals(jcv.getFileType()) && (null!=jCVConfig.getCssConstantName ()&& !"".equals (jCVConfig.getCssConstantName ()) )){ if(null!=jCVConfig.getCssConstantAliasPath () && !"".equals (jCVConfig.getCssConstantAliasPath ())){ if(jCVConfig.getCssConstantAliasPath ().startsWith ("/")){ tempPath.append(jCVConfig.getCssConstantAliasPath ().substring (1,jCVConfig.getCssConstantAliasPath ().length ())); }else { tempPath.append(jCVConfig.getCssConstantAliasPath ()); } if(!jCVConfig.getCssConstantAliasPath ().endsWith ("/")){ tempPath.append(FileUtils.getSystemFileSeparator()); } } }else if(JCVFileInfo.JS.equals(jcv.getFileType()) && (null!=jCVConfig.getCssConstantName () && !"".equals (jCVConfig.getCssConstantName ()))) { if(null!=jCVConfig.getJsConstantAliasPath () && !"".equals (jCVConfig.getJsConstantAliasPath ())){ if(jCVConfig.getJsConstantAliasPath ().startsWith ("/")){ tempPath.append(jCVConfig.getJsConstantAliasPath ().substring (1,jCVConfig.getJsConstantAliasPath ().length())); }else { tempPath.append(jCVConfig.getJsConstantAliasPath ()); } if(!jCVConfig.getJsConstantAliasPath ().endsWith ("/")){ tempPath.append(FileUtils.getSystemFileSeparator()); } } } if (meth == JCVMethodEnum.DEFAULTS_UNUSED) { if (outDir.endsWith(FileUtils.getSystemFileSeparator())) { tempPath.append(replacecurrentSystemLine(jcv.getRelativelyFilePath())); } else { tempPath.append(FileUtils.getSystemFileSeparator() + replacecurrentSystemLine(jcv.getRelativelyFilePath())); } return tempPath.toString(); } if (JCVFileInfo.CSS.equals(jcv.getFileType()) || JCVFileInfo.JS.equals(jcv.getFileType())) { if (meth == JCVMethodEnum.MD5FileName_METHOD || isCompression) { tempPath .append(replacecurrentSystemLine(jcv.getRelativelyFilePath())); int lastIndexOf = tempPath.lastIndexOf(FileUtils.getSystemFileSeparator()); tempPath = tempPath.delete(lastIndexOf, tempPath.length()); //substring(0, lastIndexOf); tempPath.append(FileUtils.getSystemFileSeparator() +jcv.getFinalFileName()); //jcv.getFileVersion() + "." + userCompressionSuffix + "." + jcv.getFileType(); } else { String fileName=""; int indexSp = jcv.getFileName().lastIndexOf("."); if (indexSp > 0) { fileName = jcv.getFileName().substring(0, indexSp); } else { fileName = jcv.getFileName(); } if(isCompression){ tempPath.append(fileName + "." +userCompressionSuffix[0]+"."+ jcv.getFileType() ); }else { tempPath.append(fileName + "." + jcv.getFileType() );// fielName + "." + userCompressionSuffix + "." + jcv.getFileType(); } } } return tempPath.toString(); } /** * * 获取文件的目录地址 * @param path * @return */ public static String getFilePathDir(String path){ int lastIndexOf = path.lastIndexOf(FileUtils.getSystemFileSeparator()); path = path.substring(0, lastIndexOf); return path; } /** * * 获取文件hash * @param f * @param meth * @return * @throws Exception */ public static String getFileHashKey(final File f,final String meth) throws Exception{ if(JCVConstant.FILE_HASH_MD5.equals (meth)){ return Md5Utils.getFileMD5(f); }else { throw new Exception ("error meth"); } } }
package com.example.projectsix; public class NewsData { private String mTitle; private String mSectionName; private String mWebURL; private String mDate; private String mTime; private String mAuthor; public NewsData(String title, String webUrl, String sectionName, String date, String time, String author) { mWebURL = webUrl; mTitle = title; mSectionName = sectionName; mDate = date; mTime = time; mAuthor = author; } public String getTitle() { return mTitle; } public String getSectionName() { return mSectionName; } public String getWebURL() { return mWebURL; } public String getDate() { return mDate; } public String getTime() { return mTime; } public String getAuthor() { return mAuthor; } }
package seedu.address.storage; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import seedu.address.commons.exceptions.IllegalValueException; import seedu.address.model.classid.ClassId; import seedu.address.model.note.ClassType; import seedu.address.model.note.Content; import seedu.address.model.note.Notes; /** * Jackson-friendly version of {@link Notes}. */ public class JsonAdaptedNote { public static final String MISSING_FIELD_MESSAGE_FORMAT = "Note's %s field is missing!"; private final String classId; private final String type; private final String content; /** * Constructs a {@code JsonAdaptedPerson} with the given person details. */ @JsonCreator public JsonAdaptedNote(@JsonProperty("classId") String classId, @JsonProperty("type") String type, @JsonProperty("content") String content) { this.classId = classId; this.type = type; this.content = content; } /** * Converts a given {@code Person} into this class for Jackson use. */ public JsonAdaptedNote(Notes source) { classId = source.getCode().value; type = source.getType().type; content = source.getContent().content; } /** * Converts this Jackson-friendly adapted person object into the model's {@code Person} object. * * @throws IllegalValueException if there were any data constraints violated in the adapted person. */ public Notes toModelType() throws IllegalValueException { if (classId == null) { throw new IllegalValueException(String.format(MISSING_FIELD_MESSAGE_FORMAT, ClassId.class.getSimpleName())); } if (!ClassId.isValidClassId(classId)) { throw new IllegalValueException(ClassId.MESSAGE_CONSTRAINTS); } final ClassId modelCode = new ClassId(classId); if (type == null) { throw new IllegalValueException(String.format(MISSING_FIELD_MESSAGE_FORMAT, ClassType.class.getSimpleName())); } if (!ClassType.isValidClassType(type)) { throw new IllegalValueException(ClassType.MESSAGE_CONSTRAINTS); } final ClassType modelType = new ClassType(type); if (content == null) { throw new IllegalValueException(String.format(MISSING_FIELD_MESSAGE_FORMAT, Content.class.getSimpleName())); } if (!Content.isValidContent(content)) { throw new IllegalValueException(Content.MESSAGE_CONSTRAINTS); } final Content modelContent = new Content(content); Notes modelNote = new Notes(modelCode, modelType, modelContent); return modelNote; } }
package edu.iastate.metnet.metaomgraph.ui; import java.awt.EventQueue; import java.awt.Font; import javax.swing.JInternalFrame; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Component; import javax.swing.JPanel; import javax.swing.JSplitPane; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.DefaultComboBoxModel; import javax.swing.JComboBox; import javax.swing.JTextField; import javax.swing.SortOrder; import javax.swing.RowSorter.SortKey; import javax.swing.plaf.ColorUIResource; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableCellRenderer; import javax.swing.table.TableRowSorter; //import com.itextpdf.xmp.impl.Utils; import edu.iastate.metnet.metaomgraph.AnimatedSwingWorker; import edu.iastate.metnet.metaomgraph.MetaOmProject; import javax.swing.JScrollPane; import javax.swing.JTable; import java.awt.event.ActionListener; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.Vector; import java.awt.event.ActionEvent; import javax.swing.JButton; import javax.swing.JMenuBar; import javax.swing.JMenu; import javax.swing.JMenuItem; public class SearchByExpressionFrame extends JInternalFrame { private JTextField textField; private JTextField textField_1; private JComboBox comboBox; private JPanel panel; private JPanel panel_1; private JSplitPane splitPane; private MetaOmProject myProject; private JScrollPane scrollPane; private JScrollPane scrollPane_1; private JTable table; private JTable table_1; private boolean searchDC = true; /** * Default Properties */ private Color SELECTIONBCKGRND = Color.black; private Color BCKGRNDCOLOR1 = Color.white; private Color BCKGRNDCOLOR2 = new ColorUIResource(216, 236, 213); private JButton btnGo; private JMenuBar menuBar; private JMenu mnFile; private JMenuItem mntmExportResults; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { SearchByExpressionFrame frame = new SearchByExpressionFrame(null); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public SearchByExpressionFrame(MetaOmProject project) { setBounds(100, 100, 450, 300); setDefaultCloseOperation(DISPOSE_ON_CLOSE); setSize(600, 400); myProject = project; getContentPane().setLayout(new BorderLayout(0, 0)); panel = new JPanel(); getContentPane().add(panel, BorderLayout.NORTH); JLabel lblSearchFor = new JLabel("Search for"); JLabel lblWithExpressionLevel = new JLabel("with expression level between"); textField = new JTextField(); textField.setColumns(7); JLabel lblAnd = new JLabel("and"); textField_1 = new JTextField(); textField_1.setColumns(7); panel_1 = new JPanel(); getContentPane().add(panel_1, BorderLayout.SOUTH); splitPane = new JSplitPane(); splitPane.setDividerSize(2); splitPane.setResizeWeight(.71d); getContentPane().add(splitPane, BorderLayout.CENTER); scrollPane = new JScrollPane(); scrollPane.setToolTipText("Select rows and click Go. Results will be displayed in the table to the right."); splitPane.setLeftComponent(scrollPane); table = new JTable(); scrollPane.setViewportView(table); scrollPane_1 = new JScrollPane(); splitPane.setRightComponent(scrollPane_1); table_1 = new JTable(); scrollPane_1.setViewportView(table_1); comboBox = new JComboBox(); /* * String[] cboxOpts = new String[2]; cboxOpts[0] = * myProject.getInfoColumnNames()[myProject.getDefaultColumn()]; cboxOpts[1] = * myProject.getMetadataHybrid().getDataColName(); comboBox = new JComboBox(); */ initFrame(); comboBox.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { int selected = comboBox.getSelectedIndex(); if (selected == 0) { searchDC = true; } else { searchDC = false; } initLeftTable(); } }); // add to panel panel.add(lblSearchFor); panel.add(comboBox); panel.add(lblWithExpressionLevel); panel.add(textField); panel.add(lblAnd); panel.add(textField_1); btnGo = new JButton("Go"); btnGo.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { new AnimatedSwingWorker("Working...", true) { @Override public Object construct() { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { startSearch(); } catch (Exception e) { e.printStackTrace(); } } }); return null; } }.start(); } }); panel.add(btnGo); // frame properties this.setClosable(true); putClientProperty("JInternalFrame.frameType", "normal"); setResizable(true); setMaximizable(true); setIconifiable(true); setClosable(true); menuBar = new JMenuBar(); setJMenuBar(menuBar); mnFile = new JMenu("File"); menuBar.add(mnFile); mntmExportResults = new JMenuItem("Export results"); mntmExportResults.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { edu.iastate.metnet.metaomgraph.utils.Utils.saveJTabletofile(table_1); } }); mnFile.add(mntmExportResults); } public void initFrame() { // init conbo box String[] cboxOpts = null; if (myProject.getMetadataHybrid() != null) { cboxOpts = new String[2]; cboxOpts[0] = myProject.getInfoColumnNames()[myProject.getDefaultColumn()]; cboxOpts[1] = myProject.getMetadataHybrid().getDataColName(); } else { cboxOpts = new String[1]; cboxOpts[0] = myProject.getInfoColumnNames()[myProject.getDefaultColumn()]; } comboBox = new JComboBox(); comboBox.setModel(new DefaultComboBoxModel(cboxOpts)); textField = new JTextField("0"); textField.setColumns(7); textField_1 = new JTextField("100"); textField_1.setColumns(7); initLeftTable(); } public void initLeftTable() { table = new JTable() { @Override public boolean getScrollableTracksViewportWidth() { return getPreferredSize().width < getParent().getWidth(); } @Override public Component prepareRenderer(TableCellRenderer renderer, int row, int column) { Component c = super.prepareRenderer(renderer, row, column); if (!isRowSelected(row)) { c.setBackground(getBackground()); int modelRow = convertRowIndexToModel(row); if (row % 2 == 0) { c.setBackground(BCKGRNDCOLOR1); } else { c.setBackground(BCKGRNDCOLOR2); } } else { c.setBackground(SELECTIONBCKGRND); } return c; } }; table.setModel(new DefaultTableModel() { @Override public boolean isCellEditable(int row, int column) { return false; } @Override public Class<?> getColumnClass(int col) { Class<?> returnValue; returnValue = Object.class; return returnValue; } }); DefaultTableModel tablemodel = (DefaultTableModel) table.getModel(); // add data if (searchDC) { // get all rows String[] rowNames = myProject.getAllDefaultRowNames(); tablemodel.addColumn(comboBox.getItemAt(0).toString()); for (int i = 0; i < rowNames.length; i++) { String[] temp = new String[1]; temp[0] = rowNames[i]; tablemodel.addRow(temp); } } else { // get all rows String[] rowNames = myProject.getDataColumnHeaders(); tablemodel.addColumn(comboBox.getItemAt(1).toString()); for (int i = 0; i < rowNames.length; i++) { String[] temp = new String[1]; temp[0] = rowNames[i]; tablemodel.addRow(temp); } } TableRowSorter sorter = new TableRowSorter(tablemodel) { @Override public void toggleSortOrder(int column) { List<? extends SortKey> sortKeys = getSortKeys(); if (sortKeys.size() > 0) { if (sortKeys.get(0).getSortOrder() == SortOrder.DESCENDING) { setSortKeys(null); return; } } super.toggleSortOrder(column); } }; // sorter.setComparator(0, new // MetadataTableDisplayPanel.AlphanumericComparator()); table.setRowSorter(sorter); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); table.setPreferredScrollableViewportSize(table.getPreferredSize()); table.setFillsViewportHeight(true); table.getTableHeader().setFont(new Font("Garamond", Font.BOLD, 14)); scrollPane.setViewportView(table); } public void initRightTable(List<String> colNames, List<List<String>> data) { table_1 = new JTable() { @Override public boolean getScrollableTracksViewportWidth() { return getPreferredSize().width < getParent().getWidth(); } @Override public Component prepareRenderer(TableCellRenderer renderer, int row, int column) { Component c = super.prepareRenderer(renderer, row, column); if (!isRowSelected(row)) { c.setBackground(getBackground()); int modelRow = convertRowIndexToModel(row); if (row % 2 == 0) { c.setBackground(BCKGRNDCOLOR1); } else { c.setBackground(BCKGRNDCOLOR2); } } else { c.setBackground(SELECTIONBCKGRND); } return c; } }; table_1.setModel(new DefaultTableModel() { @Override public boolean isCellEditable(int row, int column) { return false; } @Override public Class<?> getColumnClass(int col) { Class<?> returnValue; returnValue = Object.class; return returnValue; } }); DefaultTableModel tablemodel = (DefaultTableModel) table_1.getModel(); // add data int maxRows = -1; int maxInd = -1; int minRows = 999999999; int minInd = 999999999; List<String> intersection = new ArrayList<>(); List<String> union = new ArrayList<>(); // add intersection and union colNames.add("Intersection"); colNames.add("Union"); for (int j = 0; j < colNames.size(); j++) { tablemodel.addColumn(colNames.get(j)); // last two colnames are intersect and union. there is no list in data foor // those right now if (j < colNames.size() - 2) { if (data.get(j).size() > maxRows) { maxRows = data.get(j).size(); maxInd = j; } if (data.get(j).size() < minRows) { minRows = data.get(j).size(); minInd = j; } } } List<String> maxList = data.get(maxInd); List<String> minList = data.get(minInd); // JOptionPane.showMessageDialog(null, "mI" + minInd + "ml:" + // minList.toString()); // get intersection for (int j = 0; j < minList.size(); j++) { String thisItem = minList.get(j); boolean breakflag = false; for (int i = 0; i < data.size(); i++) { if (!data.get(i).contains(thisItem)) { breakflag = true; break; } } if (!breakflag) { intersection.add(thisItem); } } // get union for (int i = 0; i < data.size(); i++) { union.addAll(data.get(i)); } Set<String> set = new HashSet<String>(union); union = new ArrayList<>(set); // JOptionPane.showMessageDialog(null, "alldataU" +union.toString()); // add row data data.add(intersection); data.add(union); if (union.size() > maxRows) { maxRows = union.size(); } for (int i = 0; i < maxRows; i++) { Vector temp = new Vector<>(); for (int j = 0; j < colNames.size(); j++) { if (i < data.get(j).size()) { temp.add(data.get(j).get(i)); } else { temp.add(""); } } tablemodel.addRow(temp); } TableRowSorter sorter = new TableRowSorter(tablemodel) { @Override public void toggleSortOrder(int column) { List<? extends SortKey> sortKeys = getSortKeys(); if (sortKeys.size() > 0) { if (sortKeys.get(0).getSortOrder() == SortOrder.DESCENDING) { setSortKeys(null); return; } } super.toggleSortOrder(column); } }; // sorter.setComparator(0, new // MetadataTableDisplayPanel.AlphanumericComparator()); table_1.setRowSorter(sorter); table_1.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); table_1.setPreferredScrollableViewportSize(table.getPreferredSize()); table_1.setFillsViewportHeight(true); table_1.getTableHeader().setFont(new Font("Garamond", Font.BOLD, 14)); scrollPane_1.setViewportView(table_1); } /** * function to perform search by expression values */ public void startSearch() { double minVal = 0; double maxVal = 0; List<String> colNames = new ArrayList<>(); try { minVal = Double.parseDouble(textField.getText()); maxVal = Double.parseDouble(textField_1.getText()); } catch (NumberFormatException nfe) { JOptionPane.showMessageDialog(null, "Please check min and max values", "Values error", JOptionPane.ERROR_MESSAGE); return; } // get results for selected rows int[] selected = table.getSelectedRows(); if (selected == null || selected.length < 1) { JOptionPane.showMessageDialog(null, "Please select rows to search.", "Please select rows", JOptionPane.ERROR_MESSAGE); return; } List<List<String>> res = new ArrayList<>(); // search datacolumns if (searchDC) { try { for (int s = 0; s < selected.length; s++) { int thisIndex = table.convertRowIndexToModel(selected[s]); List<String> temp = new ArrayList<>(); colNames.add(myProject.getDefaultRowNames(thisIndex)); double[] values = myProject.getAllData(thisIndex); for (int i = 0; i < values.length; i++) { try { if (values[i] >= minVal && values[i] <= maxVal) temp.add(myProject.getDataColumnHeader(i)); } catch (NumberFormatException nfe) { System.err.println("value at " + i + " is not a number"); } } res.add(temp); } } catch (IOException e) { e.printStackTrace(); } } else {// search features try { for (int s = 0; s < selected.length; s++) { int thisIndex = table.convertRowIndexToModel(selected[s]); List<String> temp = new ArrayList<>(); colNames.add(myProject.getDataColumnHeader(thisIndex)); double[] values = myProject.getDataForColumn(thisIndex); for (int i = 0; i < values.length; i++) { try { if (values[i] >= minVal && values[i] <= maxVal) temp.add(myProject.getDefaultRowNames(i)); } catch (NumberFormatException nfe) { System.err.println("value at " + i + " is not a number"); } } res.add(temp); } } catch (IOException e) { e.printStackTrace(); } } initRightTable(colNames, res); } }
package elucent.rootsclassic.item; import net.minecraft.entity.EntityLivingBase; import net.minecraft.init.Items; import net.minecraft.item.ItemFood; import net.minecraft.item.ItemStack; import net.minecraft.world.World; public class ItemBowlFood extends ItemFood { public ItemBowlFood(int amount, float saturation) { super(amount, saturation, false); this.setMaxStackSize(1); } @Override public ItemStack onItemUseFinish(ItemStack stack, World worldIn, EntityLivingBase entityLiving) { super.onItemUseFinish(stack, worldIn, entityLiving); stack = new ItemStack(Items.BOWL); stack.setCount(1); return stack; } }
package org.blackdev.bloodbank_college; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Adapter; import android.widget.AdapterView; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * Created by Balaji on 28-01-2018. */ public class Donordetails extends AppCompatActivity { ArrayList<User> users; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.donor_details); Bundle b = getIntent().getExtras(); users = (ArrayList<User>) b.getSerializable("user_list"); final ListView listView = (ListView) findViewById(R.id.listView); UserAdapter adapter = new UserAdapter(Donordetails.this, R.layout.listviewelements, users); listView.setAdapter(adapter); System.out.println(users); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // TODO Auto-generated method stub String pos = users.get(position).getphone_number(); Toast.makeText(Donordetails.this, pos, Toast.LENGTH_SHORT).show(); } }); } }
/* * The MIT License * * Copyright 2015 misakura. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package jp.gr.java_conf.kgd.library.water.java.core.value; /** * 値の型を{@link Long}に特化し、デフォルトの挙動を定めた{@link LongColor4}。 * * デフォルトの挙動を定めたものであり、原則としてインターフェース部分に使ってはいけません。 * * @author misakura */ public interface LongColor4Trait extends ObjectColor4<Long>, NumberColor4 { /** * この色の赤成分にあたる値を返す。 * * デフォルトの実装では、{@link #getRedAsLong()}に委譲し、得られた値を静的キャストして返します。 * * @return {@inheritDoc} */ @Override default int getRedAsInt() { return (int) getRedAsLong(); } /** * この色の緑成分にあたる値を返す。 * * デフォルトの実装では、{@link #getGreenAsLong()}に委譲し、得られた値を静的キャストして返します。 * * @return {@inheritDoc} */ @Override default int getGreenAsInt() { return (int) getGreenAsLong(); } /** * この色の青成分にあたる値を返す。 * * デフォルトの実装では、{@link #getBlueAsLong()}に委譲し、得られた値を静的キャストして返します。 * * @return {@inheritDoc} */ @Override default int getBlueAsInt() { return (int) getBlueAsLong(); } /** * この色の透明度にあたる値を返す。 * * デフォルトの実装では、{@link #getAlphaAsLong()}に委譲し、得られた値を静的キャストして返します。 * * @return {@inheritDoc} */ @Override default int getAlphaAsInt() { return (int) getAlphaAsLong(); } /** * この色の赤成分にあたる値を返す。 * * デフォルトの実装では、{@link #getRedAsLong()}に委譲し、得られた値を静的キャストして返します。 * * @return {@inheritDoc} */ @Override default double getRedAsDouble() { return (double) getRedAsLong(); } /** * この色の緑成分にあたる値を返す。 * * デフォルトの実装では、{@link #getGreenAsLong()}に委譲し、得られた値を静的キャストして返します。 * * @return {@inheritDoc} */ @Override default double getGreenAsDouble() { return (double) getGreenAsLong(); } /** * この色の青成分にあたる値を返す。 * * デフォルトの実装では、{@link #getBlueAsLong()}に委譲し、得られた値を静的キャストして返します。 * * @return {@inheritDoc} */ @Override default double getBlueAsDouble() { return (double) getBlueAsLong(); } /** * この色の透明度にあたる値を返す。 * * デフォルトの実装では、{@link #getAlphaAsLong()}に委譲し、得られた値を静的キャストして返します。 * * @return {@inheritDoc} */ @Override default double getAlphaAsDouble() { return (double) getAlphaAsLong(); } /** * この色の赤成分にあたる値を返す。 * * 得られる値が防御的にコピーされたものであるかどうかは実装依存です。<br> * デフォルトの実装では、{@link #getRedAsLong()}に委譲し、得られた値をボックス化して返します。(つまり、防御的コピーを行います。) * * @return {@inheritDoc} * @deprecated このインターフェースを直接操作する場合は{@link #getRedAsLong()}を使うべきです。 */ @Deprecated @Override default Long getRed() { return getRedAsLong(); } /** * この色の緑成分にあたる値を返す。 * * 得られる値が防御的にコピーされたものであるかどうかは実装依存です。<br> * デフォルトの実装では、{@link #getGreenAsLong()}に委譲し、得られた値をボックス化して返します。(つまり、防御的コピーを行います。) * * @return {@inheritDoc} * @deprecated このインターフェースを直接操作する場合は{@link #getGreenAsLong()}を使うべきです。 */ @Deprecated @Override default Long getGreen() { return getGreenAsLong(); } /** * この色の青成分にあたる値を返す。 * * 得られる値が防御的にコピーされたものであるかどうかは実装依存です。<br> * デフォルトの実装では、{@link #getBlueAsLong()}に委譲し、得られた値をボックス化して返します。(つまり、防御的コピーを行います。) * * @return {@inheritDoc} * @deprecated このインターフェースを直接操作する場合は{@link #getBlueAsLong()}を使うべきです。 */ @Deprecated @Override default Long getBlue() { return getBlueAsLong(); } /** * この色の透明度にあたる値を返す。 * * 得られる値が防御的にコピーされたものであるかどうかは実装依存です。<br> * デフォルトの実装では、{@link #getAlphaAsLong()}に委譲し、得られた値をボックス化して返します。(つまり、防御的コピーを行います。) * * @return {@inheritDoc} * @deprecated このインターフェースを直接操作する場合は{@link #getAlphaAsLong()}を使うべきです。 */ @Deprecated @Override default Long getAlpha() { return getAlphaAsLong(); } }
package com.example; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest public class SpringBootAngular2ApplicationTests { @Test public void contextLoads() { } }
/* * 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.shardingsphere.data.pipeline.core.constant; import lombok.AccessLevel; import lombok.NoArgsConstructor; /** * Data pipeline constants. */ @NoArgsConstructor(access = AccessLevel.PRIVATE) public final class DataPipelineConstants { /** * Data pipeline root path. */ // TODO change to /pipeline after job configuration structure completed public static final String DATA_PIPELINE_ROOT = "/scaling"; }
package net.bytebuddy.instrumentation.attribute; import net.bytebuddy.instrumentation.attribute.annotation.AnnotationAppender; import net.bytebuddy.instrumentation.field.FieldDescription; import net.bytebuddy.instrumentation.type.TypeDescription; import org.objectweb.asm.FieldVisitor; import java.lang.annotation.Annotation; import java.lang.reflect.Field; import java.util.Arrays; /** * An appender that writes attributes or annotations to a given ASM {@link org.objectweb.asm.FieldVisitor}. */ public interface FieldAttributeAppender { /** * Applies this attribute appender to a given field visitor. * * @param fieldVisitor The field visitor to which the attributes that are represented by this attribute appender * are written to. * @param fieldDescription The description of the field to which the field visitor belongs to. */ void apply(FieldVisitor fieldVisitor, FieldDescription fieldDescription); /** * A field attribute appender that does not append any attributes. */ static enum NoOp implements FieldAttributeAppender, Factory { /** * The singleton instance. */ INSTANCE; @Override public FieldAttributeAppender make(TypeDescription typeDescription) { return this; } @Override public void apply(FieldVisitor fieldVisitor, FieldDescription fieldDescription) { /* do nothing */ } } /** * A factory that creates field attribute appenders for a given type. */ static interface Factory { /** * Returns a field attribute appender that is applicable for a given type description. * * @param typeDescription The type for which a field attribute appender is to be applied for. * @return The field attribute appender which should be applied for the given type. */ FieldAttributeAppender make(TypeDescription typeDescription); /** * A field attribute appender factory that combines several field attribute appender factories to be * represented as a single factory. */ static class Compound implements Factory { /** * The factories that this compound factory represents in their application order. */ private final Factory[] factory; /** * Creates a new compound field attribute appender factory. * * @param factory The factories that are to be combined by this compound factory in the order of their * application. */ public Compound(Factory... factory) { this.factory = factory; } @Override public FieldAttributeAppender make(TypeDescription typeDescription) { FieldAttributeAppender[] fieldAttributeAppender = new FieldAttributeAppender[factory.length]; int index = 0; for (Factory factory : this.factory) { fieldAttributeAppender[index++] = factory.make(typeDescription); } return new FieldAttributeAppender.Compound(fieldAttributeAppender); } @Override public boolean equals(Object other) { return this == other || !(other == null || getClass() != other.getClass()) && Arrays.equals(factory, ((Compound) other).factory); } @Override public int hashCode() { return Arrays.hashCode(factory); } @Override public String toString() { return "FieldAttributeAppender.Factory.Compound{" + Arrays.toString(factory) + '}'; } } } /** * Appends an annotation to a field. The visibility of the annotation is determined by the annotation type's * {@link java.lang.annotation.RetentionPolicy} annotation. */ static class ForAnnotation implements FieldAttributeAppender, Factory { /** * The annotations that this appender appends. */ private final Annotation[] annotation; /** * Creates a new field annotation appender. * * @param annotation The annotations to be appended to the field. */ public ForAnnotation(Annotation... annotation) { this.annotation = annotation; } @Override public void apply(FieldVisitor fieldVisitor, FieldDescription fieldDescription) { AnnotationAppender annotationAppender = new AnnotationAppender.Default(new AnnotationAppender.Target.OnField(fieldVisitor)); for (Annotation annotation : this.annotation) { annotationAppender.append(annotation, AnnotationAppender.AnnotationVisibility.of(annotation)); } } @Override public FieldAttributeAppender make(TypeDescription typeDescription) { return this; } @Override public boolean equals(Object other) { return this == other || !(other == null || getClass() != other.getClass()) && Arrays.equals(annotation, ((ForAnnotation) other).annotation); } @Override public int hashCode() { return Arrays.hashCode(annotation); } @Override public String toString() { return "FieldAttributeAppender.ForAnnotation{annotation=" + Arrays.toString(annotation) + '}'; } } /** * Writes all annotations that are found on a field that belongs to a loaded type of the JVM as visible * annotations. */ static class ForLoadedField implements FieldAttributeAppender, Factory { /** * The field from which the annotations should be copied. */ private final Field field; /** * Creates a new field attribute appender that appends all annotations that are found on a loaded field. * * @param field The field from which the annotations to append are read. */ public ForLoadedField(Field field) { this.field = field; } @Override public void apply(FieldVisitor fieldVisitor, FieldDescription fieldDescription) { AnnotationAppender annotationAppender = new AnnotationAppender.Default(new AnnotationAppender.Target.OnField(fieldVisitor)); for (Annotation annotation : field.getAnnotations()) { annotationAppender.append(annotation, AnnotationAppender.AnnotationVisibility.RUNTIME); } } @Override public FieldAttributeAppender make(TypeDescription typeDescription) { return this; } @Override public boolean equals(Object other) { return this == other || !(other == null || getClass() != other.getClass()) && field.equals(((ForLoadedField) other).field); } @Override public int hashCode() { return field.hashCode(); } @Override public String toString() { return "FieldAttributeAppender.ForLoadedField{field=" + field + '}'; } } /** * A field attribute appender that combines several method attribute appenders to be represented as a single * field attribute appender. */ static class Compound implements FieldAttributeAppender { /** * The field attribute appenders this appender represents in their application order. */ private final FieldAttributeAppender[] fieldAttributeAppender; /** * Creates a new compound field attribute appender. * * @param fieldAttributeAppender The field attribute appenders that are to be combined by this compound appender * in the order of their application. */ public Compound(FieldAttributeAppender... fieldAttributeAppender) { this.fieldAttributeAppender = fieldAttributeAppender; } @Override public void apply(FieldVisitor fieldVisitor, FieldDescription fieldDescription) { for (FieldAttributeAppender fieldAttributeAppender : this.fieldAttributeAppender) { fieldAttributeAppender.apply(fieldVisitor, fieldDescription); } } @Override public boolean equals(Object other) { return this == other || !(other == null || getClass() != other.getClass()) && Arrays.equals(fieldAttributeAppender, ((Compound) other).fieldAttributeAppender); } @Override public int hashCode() { return Arrays.hashCode(fieldAttributeAppender); } @Override public String toString() { return "FieldAttributeAppenderCompound{" + Arrays.toString(fieldAttributeAppender) + '}'; } } }
package cn.wildfirechat.app.github.pojo; import com.google.gson.Gson; public class PullRequestEvent { public PullRequest pull_request; public Repository repository; public User sender; public static PullRequestEvent fromJson(String jsonStr) { return new Gson().fromJson(jsonStr, PullRequestEvent.class); } public static void main(String[] args) { String event1 = "{\"action\":\"opened\",\"number\":234,\"pull_request\":{\"url\":\"https://api.github.com/repos/wildfirechat/ios-chat/pulls/234\",\"id\":472308019,\"node_id\":\"MDExOlB1bGxSZXF1ZXN0NDcyMzA4MDE5\",\"html_url\":\"https://github.com/wildfirechat/ios-chat/pull/234\",\"diff_url\":\"https://github.com/wildfirechat/ios-chat/pull/234.diff\",\"patch_url\":\"https://github.com/wildfirechat/ios-chat/pull/234.patch\",\"issue_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/issues/234\",\"number\":234,\"state\":\"open\",\"locked\":false,\"title\":\"iCloud Driver 问题\",\"user\":{\"login\":\"ManBuTianYa\",\"id\":16189552,\"node_id\":\"MDQ6VXNlcjE2MTg5NTUy\",\"avatar_url\":\"https://avatars1.githubusercontent.com/u/16189552?v=4\",\"gravatar_id\":\"\",\"url\":\"https://api.github.com/users/ManBuTianYa\",\"html_url\":\"https://github.com/ManBuTianYa\",\"followers_url\":\"https://api.github.com/users/ManBuTianYa/followers\",\"following_url\":\"https://api.github.com/users/ManBuTianYa/following{/other_user}\",\"gists_url\":\"https://api.github.com/users/ManBuTianYa/gists{/gist_id}\",\"starred_url\":\"https://api.github.com/users/ManBuTianYa/starred{/owner}{/repo}\",\"subscriptions_url\":\"https://api.github.com/users/ManBuTianYa/subscriptions\",\"organizations_url\":\"https://api.github.com/users/ManBuTianYa/orgs\",\"repos_url\":\"https://api.github.com/users/ManBuTianYa/repos\",\"events_url\":\"https://api.github.com/users/ManBuTianYa/events{/privacy}\",\"received_events_url\":\"https://api.github.com/users/ManBuTianYa/received_events\",\"type\":\"User\",\"site_admin\":false},\"body\":\"模拟器发送文件正常, 真机下发送崩溃。\",\"created_at\":\"2020-08-24T06:59:34Z\",\"updated_at\":\"2020-08-24T06:59:34Z\",\"closed_at\":null,\"merged_at\":null,\"merge_commit_sha\":null,\"assignee\":null,\"assignees\":[],\"requested_reviewers\":[],\"requested_teams\":[],\"labels\":[],\"milestone\":null,\"draft\":false,\"commits_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/pulls/234/commits\",\"review_comments_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/pulls/234/comments\",\"review_comment_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/pulls/comments{/number}\",\"comments_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/issues/234/comments\",\"statuses_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/statuses/d09a7ca9d9b7c0deb1392650aa343339086ee997\",\"head\":{\"label\":\"ManBuTianYa:master\",\"ref\":\"master\",\"sha\":\"d09a7ca9d9b7c0deb1392650aa343339086ee997\",\"user\":{\"login\":\"ManBuTianYa\",\"id\":16189552,\"node_id\":\"MDQ6VXNlcjE2MTg5NTUy\",\"avatar_url\":\"https://avatars1.githubusercontent.com/u/16189552?v=4\",\"gravatar_id\":\"\",\"url\":\"https://api.github.com/users/ManBuTianYa\",\"html_url\":\"https://github.com/ManBuTianYa\",\"followers_url\":\"https://api.github.com/users/ManBuTianYa/followers\",\"following_url\":\"https://api.github.com/users/ManBuTianYa/following{/other_user}\",\"gists_url\":\"https://api.github.com/users/ManBuTianYa/gists{/gist_id}\",\"starred_url\":\"https://api.github.com/users/ManBuTianYa/starred{/owner}{/repo}\",\"subscriptions_url\":\"https://api.github.com/users/ManBuTianYa/subscriptions\",\"organizations_url\":\"https://api.github.com/users/ManBuTianYa/orgs\",\"repos_url\":\"https://api.github.com/users/ManBuTianYa/repos\",\"events_url\":\"https://api.github.com/users/ManBuTianYa/events{/privacy}\",\"received_events_url\":\"https://api.github.com/users/ManBuTianYa/received_events\",\"type\":\"User\",\"site_admin\":false},\"repo\":{\"id\":289814706,\"node_id\":\"MDEwOlJlcG9zaXRvcnkyODk4MTQ3MDY=\",\"name\":\"ios-chat\",\"full_name\":\"ManBuTianYa/ios-chat\",\"private\":false,\"owner\":{\"login\":\"ManBuTianYa\",\"id\":16189552,\"node_id\":\"MDQ6VXNlcjE2MTg5NTUy\",\"avatar_url\":\"https://avatars1.githubusercontent.com/u/16189552?v=4\",\"gravatar_id\":\"\",\"url\":\"https://api.github.com/users/ManBuTianYa\",\"html_url\":\"https://github.com/ManBuTianYa\",\"followers_url\":\"https://api.github.com/users/ManBuTianYa/followers\",\"following_url\":\"https://api.github.com/users/ManBuTianYa/following{/other_user}\",\"gists_url\":\"https://api.github.com/users/ManBuTianYa/gists{/gist_id}\",\"starred_url\":\"https://api.github.com/users/ManBuTianYa/starred{/owner}{/repo}\",\"subscriptions_url\":\"https://api.github.com/users/ManBuTianYa/subscriptions\",\"organizations_url\":\"https://api.github.com/users/ManBuTianYa/orgs\",\"repos_url\":\"https://api.github.com/users/ManBuTianYa/repos\",\"events_url\":\"https://api.github.com/users/ManBuTianYa/events{/privacy}\",\"received_events_url\":\"https://api.github.com/users/ManBuTianYa/received_events\",\"type\":\"User\",\"site_admin\":false},\"html_url\":\"https://github.com/ManBuTianYa/ios-chat\",\"description\":\"开源的即时通讯(野火IM)系统\",\"fork\":true,\"url\":\"https://api.github.com/repos/ManBuTianYa/ios-chat\",\"forks_url\":\"https://api.github.com/repos/ManBuTianYa/ios-chat/forks\",\"keys_url\":\"https://api.github.com/repos/ManBuTianYa/ios-chat/keys{/key_id}\",\"collaborators_url\":\"https://api.github.com/repos/ManBuTianYa/ios-chat/collaborators{/collaborator}\",\"teams_url\":\"https://api.github.com/repos/ManBuTianYa/ios-chat/teams\",\"hooks_url\":\"https://api.github.com/repos/ManBuTianYa/ios-chat/hooks\",\"issue_events_url\":\"https://api.github.com/repos/ManBuTianYa/ios-chat/issues/events{/number}\",\"events_url\":\"https://api.github.com/repos/ManBuTianYa/ios-chat/events\",\"assignees_url\":\"https://api.github.com/repos/ManBuTianYa/ios-chat/assignees{/user}\",\"branches_url\":\"https://api.github.com/repos/ManBuTianYa/ios-chat/branches{/branch}\",\"tags_url\":\"https://api.github.com/repos/ManBuTianYa/ios-chat/tags\",\"blobs_url\":\"https://api.github.com/repos/ManBuTianYa/ios-chat/git/blobs{/sha}\",\"git_tags_url\":\"https://api.github.com/repos/ManBuTianYa/ios-chat/git/tags{/sha}\",\"git_refs_url\":\"https://api.github.com/repos/ManBuTianYa/ios-chat/git/refs{/sha}\",\"trees_url\":\"https://api.github.com/repos/ManBuTianYa/ios-chat/git/trees{/sha}\",\"statuses_url\":\"https://api.github.com/repos/ManBuTianYa/ios-chat/statuses/{sha}\",\"languages_url\":\"https://api.github.com/repos/ManBuTianYa/ios-chat/languages\",\"stargazers_url\":\"https://api.github.com/repos/ManBuTianYa/ios-chat/stargazers\",\"contributors_url\":\"https://api.github.com/repos/ManBuTianYa/ios-chat/contributors\",\"subscribers_url\":\"https://api.github.com/repos/ManBuTianYa/ios-chat/subscribers\",\"subscription_url\":\"https://api.github.com/repos/ManBuTianYa/ios-chat/subscription\",\"commits_url\":\"https://api.github.com/repos/ManBuTianYa/ios-chat/commits{/sha}\",\"git_commits_url\":\"https://api.github.com/repos/ManBuTianYa/ios-chat/git/commits{/sha}\",\"comments_url\":\"https://api.github.com/repos/ManBuTianYa/ios-chat/comments{/number}\",\"issue_comment_url\":\"https://api.github.com/repos/ManBuTianYa/ios-chat/issues/comments{/number}\",\"contents_url\":\"https://api.github.com/repos/ManBuTianYa/ios-chat/contents/{+path}\",\"compare_url\":\"https://api.github.com/repos/ManBuTianYa/ios-chat/compare/{base}...{head}\",\"merges_url\":\"https://api.github.com/repos/ManBuTianYa/ios-chat/merges\",\"archive_url\":\"https://api.github.com/repos/ManBuTianYa/ios-chat/{archive_format}{/ref}\",\"downloads_url\":\"https://api.github.com/repos/ManBuTianYa/ios-chat/downloads\",\"issues_url\":\"https://api.github.com/repos/ManBuTianYa/ios-chat/issues{/number}\",\"pulls_url\":\"https://api.github.com/repos/ManBuTianYa/ios-chat/pulls{/number}\",\"milestones_url\":\"https://api.github.com/repos/ManBuTianYa/ios-chat/milestones{/number}\",\"notifications_url\":\"https://api.github.com/repos/ManBuTianYa/ios-chat/notifications{?since,all,participating}\",\"labels_url\":\"https://api.github.com/repos/ManBuTianYa/ios-chat/labels{/name}\",\"releases_url\":\"https://api.github.com/repos/ManBuTianYa/ios-chat/releases{/id}\",\"deployments_url\":\"https://api.github.com/repos/ManBuTianYa/ios-chat/deployments\",\"created_at\":\"2020-08-24T03:05:35Z\",\"updated_at\":\"2020-08-24T06:53:04Z\",\"pushed_at\":\"2020-08-24T06:52:59Z\",\"git_url\":\"git://github.com/ManBuTianYa/ios-chat.git\",\"ssh_url\":\"git@github.com:ManBuTianYa/ios-chat.git\",\"clone_url\":\"https://github.com/ManBuTianYa/ios-chat.git\",\"svn_url\":\"https://github.com/ManBuTianYa/ios-chat\",\"homepage\":\"http://docs.wildfirechat.cn\",\"size\":402374,\"stargazers_count\":0,\"watchers_count\":0,\"language\":\"Objective-C\",\"has_issues\":false,\"has_projects\":true,\"has_downloads\":true,\"has_wiki\":true,\"has_pages\":false,\"forks_count\":0,\"mirror_url\":null,\"archived\":false,\"disabled\":false,\"open_issues_count\":0,\"license\":{\"key\":\"other\",\"name\":\"Other\",\"spdx_id\":\"NOASSERTION\",\"url\":null,\"node_id\":\"MDc6TGljZW5zZTA=\"},\"forks\":0,\"open_issues\":0,\"watchers\":0,\"default_branch\":\"master\",\"allow_squash_merge\":true,\"allow_merge_commit\":true,\"allow_rebase_merge\":true,\"delete_branch_on_merge\":false}},\"base\":{\"label\":\"wildfirechat:master\",\"ref\":\"master\",\"sha\":\"7c49cb7785cf2cf70205d225f52ac6e6485e56a8\",\"user\":{\"login\":\"wildfirechat\",\"id\":33191460,\"node_id\":\"MDEyOk9yZ2FuaXphdGlvbjMzMTkxNDYw\",\"avatar_url\":\"https://avatars0.githubusercontent.com/u/33191460?v=4\",\"gravatar_id\":\"\",\"url\":\"https://api.github.com/users/wildfirechat\",\"html_url\":\"https://github.com/wildfirechat\",\"followers_url\":\"https://api.github.com/users/wildfirechat/followers\",\"following_url\":\"https://api.github.com/users/wildfirechat/following{/other_user}\",\"gists_url\":\"https://api.github.com/users/wildfirechat/gists{/gist_id}\",\"starred_url\":\"https://api.github.com/users/wildfirechat/starred{/owner}{/repo}\",\"subscriptions_url\":\"https://api.github.com/users/wildfirechat/subscriptions\",\"organizations_url\":\"https://api.github.com/users/wildfirechat/orgs\",\"repos_url\":\"https://api.github.com/users/wildfirechat/repos\",\"events_url\":\"https://api.github.com/users/wildfirechat/events{/privacy}\",\"received_events_url\":\"https://api.github.com/users/wildfirechat/received_events\",\"type\":\"Organization\",\"site_admin\":false},\"repo\":{\"id\":167198690,\"node_id\":\"MDEwOlJlcG9zaXRvcnkxNjcxOTg2OTA=\",\"name\":\"ios-chat\",\"full_name\":\"wildfirechat/ios-chat\",\"private\":false,\"owner\":{\"login\":\"wildfirechat\",\"id\":33191460,\"node_id\":\"MDEyOk9yZ2FuaXphdGlvbjMzMTkxNDYw\",\"avatar_url\":\"https://avatars0.githubusercontent.com/u/33191460?v=4\",\"gravatar_id\":\"\",\"url\":\"https://api.github.com/users/wildfirechat\",\"html_url\":\"https://github.com/wildfirechat\",\"followers_url\":\"https://api.github.com/users/wildfirechat/followers\",\"following_url\":\"https://api.github.com/users/wildfirechat/following{/other_user}\",\"gists_url\":\"https://api.github.com/users/wildfirechat/gists{/gist_id}\",\"starred_url\":\"https://api.github.com/users/wildfirechat/starred{/owner}{/repo}\",\"subscriptions_url\":\"https://api.github.com/users/wildfirechat/subscriptions\",\"organizations_url\":\"https://api.github.com/users/wildfirechat/orgs\",\"repos_url\":\"https://api.github.com/users/wildfirechat/repos\",\"events_url\":\"https://api.github.com/users/wildfirechat/events{/privacy}\",\"received_events_url\":\"https://api.github.com/users/wildfirechat/received_events\",\"type\":\"Organization\",\"site_admin\":false},\"html_url\":\"https://github.com/wildfirechat/ios-chat\",\"description\":\"开源的即时通讯(野火IM)系统\",\"fork\":false,\"url\":\"https://api.github.com/repos/wildfirechat/ios-chat\",\"forks_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/forks\",\"keys_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/keys{/key_id}\",\"collaborators_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/collaborators{/collaborator}\",\"teams_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/teams\",\"hooks_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/hooks\",\"issue_events_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/issues/events{/number}\",\"events_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/events\",\"assignees_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/assignees{/user}\",\"branches_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/branches{/branch}\",\"tags_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/tags\",\"blobs_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/git/blobs{/sha}\",\"git_tags_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/git/tags{/sha}\",\"git_refs_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/git/refs{/sha}\",\"trees_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/git/trees{/sha}\",\"statuses_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/statuses/{sha}\",\"languages_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/languages\",\"stargazers_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/stargazers\",\"contributors_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/contributors\",\"subscribers_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/subscribers\",\"subscription_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/subscription\",\"commits_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/commits{/sha}\",\"git_commits_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/git/commits{/sha}\",\"comments_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/comments{/number}\",\"issue_comment_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/issues/comments{/number}\",\"contents_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/contents/{+path}\",\"compare_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/compare/{base}...{head}\",\"merges_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/merges\",\"archive_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/{archive_format}{/ref}\",\"downloads_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/downloads\",\"issues_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/issues{/number}\",\"pulls_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/pulls{/number}\",\"milestones_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/milestones{/number}\",\"notifications_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/notifications{?since,all,participating}\",\"labels_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/labels{/name}\",\"releases_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/releases{/id}\",\"deployments_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/deployments\",\"created_at\":\"2019-01-23T14:41:53Z\",\"updated_at\":\"2020-08-23T08:41:29Z\",\"pushed_at\":\"2020-08-19T10:30:48Z\",\"git_url\":\"git://github.com/wildfirechat/ios-chat.git\",\"ssh_url\":\"git@github.com:wildfirechat/ios-chat.git\",\"clone_url\":\"https://github.com/wildfirechat/ios-chat.git\",\"svn_url\":\"https://github.com/wildfirechat/ios-chat\",\"homepage\":\"http://docs.wildfirechat.cn\",\"size\":402374,\"stargazers_count\":766,\"watchers_count\":766,\"language\":\"Objective-C\",\"has_issues\":true,\"has_projects\":true,\"has_downloads\":true,\"has_wiki\":true,\"has_pages\":false,\"forks_count\":356,\"mirror_url\":null,\"archived\":false,\"disabled\":false,\"open_issues_count\":20,\"license\":{\"key\":\"other\",\"name\":\"Other\",\"spdx_id\":\"NOASSERTION\",\"url\":null,\"node_id\":\"MDc6TGljZW5zZTA=\"},\"forks\":356,\"open_issues\":20,\"watchers\":766,\"default_branch\":\"master\",\"allow_squash_merge\":true,\"allow_merge_commit\":true,\"allow_rebase_merge\":true,\"delete_branch_on_merge\":false}},\"_links\":{\"self\":{\"href\":\"https://api.github.com/repos/wildfirechat/ios-chat/pulls/234\"},\"html\":{\"href\":\"https://github.com/wildfirechat/ios-chat/pull/234\"},\"issue\":{\"href\":\"https://api.github.com/repos/wildfirechat/ios-chat/issues/234\"},\"comments\":{\"href\":\"https://api.github.com/repos/wildfirechat/ios-chat/issues/234/comments\"},\"review_comments\":{\"href\":\"https://api.github.com/repos/wildfirechat/ios-chat/pulls/234/comments\"},\"review_comment\":{\"href\":\"https://api.github.com/repos/wildfirechat/ios-chat/pulls/comments{/number}\"},\"commits\":{\"href\":\"https://api.github.com/repos/wildfirechat/ios-chat/pulls/234/commits\"},\"statuses\":{\"href\":\"https://api.github.com/repos/wildfirechat/ios-chat/statuses/d09a7ca9d9b7c0deb1392650aa343339086ee997\"}},\"author_association\":\"NONE\",\"active_lock_reason\":null,\"merged\":false,\"mergeable\":null,\"rebaseable\":null,\"mergeable_state\":\"unknown\",\"merged_by\":null,\"comments\":0,\"review_comments\":0,\"maintainer_can_modify\":true,\"commits\":1,\"additions\":68,\"deletions\":7,\"changed_files\":1},\"repository\":{\"id\":167198690,\"node_id\":\"MDEwOlJlcG9zaXRvcnkxNjcxOTg2OTA=\",\"name\":\"ios-chat\",\"full_name\":\"wildfirechat/ios-chat\",\"private\":false,\"owner\":{\"login\":\"wildfirechat\",\"id\":33191460,\"node_id\":\"MDEyOk9yZ2FuaXphdGlvbjMzMTkxNDYw\",\"avatar_url\":\"https://avatars0.githubusercontent.com/u/33191460?v=4\",\"gravatar_id\":\"\",\"url\":\"https://api.github.com/users/wildfirechat\",\"html_url\":\"https://github.com/wildfirechat\",\"followers_url\":\"https://api.github.com/users/wildfirechat/followers\",\"following_url\":\"https://api.github.com/users/wildfirechat/following{/other_user}\",\"gists_url\":\"https://api.github.com/users/wildfirechat/gists{/gist_id}\",\"starred_url\":\"https://api.github.com/users/wildfirechat/starred{/owner}{/repo}\",\"subscriptions_url\":\"https://api.github.com/users/wildfirechat/subscriptions\",\"organizations_url\":\"https://api.github.com/users/wildfirechat/orgs\",\"repos_url\":\"https://api.github.com/users/wildfirechat/repos\",\"events_url\":\"https://api.github.com/users/wildfirechat/events{/privacy}\",\"received_events_url\":\"https://api.github.com/users/wildfirechat/received_events\",\"type\":\"Organization\",\"site_admin\":false},\"html_url\":\"https://github.com/wildfirechat/ios-chat\",\"description\":\"开源的即时通讯(野火IM)系统\",\"fork\":false,\"url\":\"https://api.github.com/repos/wildfirechat/ios-chat\",\"forks_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/forks\",\"keys_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/keys{/key_id}\",\"collaborators_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/collaborators{/collaborator}\",\"teams_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/teams\",\"hooks_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/hooks\",\"issue_events_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/issues/events{/number}\",\"events_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/events\",\"assignees_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/assignees{/user}\",\"branches_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/branches{/branch}\",\"tags_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/tags\",\"blobs_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/git/blobs{/sha}\",\"git_tags_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/git/tags{/sha}\",\"git_refs_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/git/refs{/sha}\",\"trees_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/git/trees{/sha}\",\"statuses_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/statuses/{sha}\",\"languages_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/languages\",\"stargazers_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/stargazers\",\"contributors_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/contributors\",\"subscribers_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/subscribers\",\"subscription_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/subscription\",\"commits_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/commits{/sha}\",\"git_commits_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/git/commits{/sha}\",\"comments_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/comments{/number}\",\"issue_comment_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/issues/comments{/number}\",\"contents_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/contents/{+path}\",\"compare_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/compare/{base}...{head}\",\"merges_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/merges\",\"archive_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/{archive_format}{/ref}\",\"downloads_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/downloads\",\"issues_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/issues{/number}\",\"pulls_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/pulls{/number}\",\"milestones_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/milestones{/number}\",\"notifications_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/notifications{?since,all,participating}\",\"labels_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/labels{/name}\",\"releases_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/releases{/id}\",\"deployments_url\":\"https://api.github.com/repos/wildfirechat/ios-chat/deployments\",\"created_at\":\"2019-01-23T14:41:53Z\",\"updated_at\":\"2020-08-23T08:41:29Z\",\"pushed_at\":\"2020-08-19T10:30:48Z\",\"git_url\":\"git://github.com/wildfirechat/ios-chat.git\",\"ssh_url\":\"git@github.com:wildfirechat/ios-chat.git\",\"clone_url\":\"https://github.com/wildfirechat/ios-chat.git\",\"svn_url\":\"https://github.com/wildfirechat/ios-chat\",\"homepage\":\"http://docs.wildfirechat.cn\",\"size\":402374,\"stargazers_count\":766,\"watchers_count\":766,\"language\":\"Objective-C\",\"has_issues\":true,\"has_projects\":true,\"has_downloads\":true,\"has_wiki\":true,\"has_pages\":false,\"forks_count\":356,\"mirror_url\":null,\"archived\":false,\"disabled\":false,\"open_issues_count\":20,\"license\":{\"key\":\"other\",\"name\":\"Other\",\"spdx_id\":\"NOASSERTION\",\"url\":null,\"node_id\":\"MDc6TGljZW5zZTA=\"},\"forks\":356,\"open_issues\":20,\"watchers\":766,\"default_branch\":\"master\"},\"organization\":{\"login\":\"wildfirechat\",\"id\":33191460,\"node_id\":\"MDEyOk9yZ2FuaXphdGlvbjMzMTkxNDYw\",\"url\":\"https://api.github.com/orgs/wildfirechat\",\"repos_url\":\"https://api.github.com/orgs/wildfirechat/repos\",\"events_url\":\"https://api.github.com/orgs/wildfirechat/events\",\"hooks_url\":\"https://api.github.com/orgs/wildfirechat/hooks\",\"issues_url\":\"https://api.github.com/orgs/wildfirechat/issues\",\"members_url\":\"https://api.github.com/orgs/wildfirechat/members{/member}\",\"public_members_url\":\"https://api.github.com/orgs/wildfirechat/public_members{/member}\",\"avatar_url\":\"https://avatars0.githubusercontent.com/u/33191460?v=4\",\"description\":\"北京野火无限网络科技有限公司--专注于即时通讯技术,提供优质可控的即时通讯能力\"},\"sender\":{\"login\":\"ManBuTianYa\",\"id\":16189552,\"node_id\":\"MDQ6VXNlcjE2MTg5NTUy\",\"avatar_url\":\"https://avatars1.githubusercontent.com/u/16189552?v=4\",\"gravatar_id\":\"\",\"url\":\"https://api.github.com/users/ManBuTianYa\",\"html_url\":\"https://github.com/ManBuTianYa\",\"followers_url\":\"https://api.github.com/users/ManBuTianYa/followers\",\"following_url\":\"https://api.github.com/users/ManBuTianYa/following{/other_user}\",\"gists_url\":\"https://api.github.com/users/ManBuTianYa/gists{/gist_id}\",\"starred_url\":\"https://api.github.com/users/ManBuTianYa/starred{/owner}{/repo}\",\"subscriptions_url\":\"https://api.github.com/users/ManBuTianYa/subscriptions\",\"organizations_url\":\"https://api.github.com/users/ManBuTianYa/orgs\",\"repos_url\":\"https://api.github.com/users/ManBuTianYa/repos\",\"events_url\":\"https://api.github.com/users/ManBuTianYa/events{/privacy}\",\"received_events_url\":\"https://api.github.com/users/ManBuTianYa/received_events\",\"type\":\"User\",\"site_admin\":false}}"; PullRequestEvent pullRequestEvent = fromJson(event1); System.out.println(pullRequestEvent.pull_request.title); } }
// // OpenForecast - open source, general-purpose forecasting package. // Copyright (C) 2002-2011 Steven R. Gould // // 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // Olympic scoring model considers the average of the last k weeks // (dropping the b highest and lowest values) as the current prediction. package com.yahoo.egads.models.tsmm; import com.yahoo.egads.data.*; import com.yahoo.egads.data.TimeSeries.Entry; import org.json.JSONObject; import org.json.JSONStringer; import java.util.Properties; import net.sourceforge.openforecast.DataSet; import net.sourceforge.openforecast.ForecastingModel; import net.sourceforge.openforecast.DataPoint; import net.sourceforge.openforecast.Observation; import java.util.*; // Double exponential smoothing - also known as Holt exponential smoothing - is a refinement of the popular simple // exponential smoothing model but adds another component which takes into account any trend in the data. public class DoubleExponentialSmoothingModel extends TimeSeriesAbstractModel { // methods //////////////////////////////////////////////// // The model that will be used for forecasting. private ForecastingModel forecaster; // Stores the historical values. private TimeSeries.DataSequence data; public DoubleExponentialSmoothingModel(Properties config) { super(config); modelName = "DoubleExponentialSmoothingModel"; } public void reset() { // At this point, reset does nothing. } public void train(TimeSeries.DataSequence data) { this.data = data; int n = data.size(); DataPoint dp = null; DataSet observedData = new DataSet(); for (int i = 0; i < n; i++) { dp = new Observation(data.get(i).value); dp.setIndependentValue("x", i); observedData.add(dp); } observedData.setTimeVariable("x"); // TODO: Make weights configurable. forecaster = new net.sourceforge.openforecast.models.DoubleExponentialSmoothingModel(0.75, 0.1); forecaster.init(observedData); initForecastErrors(forecaster, data); logger.debug(getBias() + "\t" + getMAD() + "\t" + getMAPE() + "\t" + getMSE() + "\t" + getSAE() + "\t" + 0 + "\t" + 0); } public void update(TimeSeries.DataSequence data) { } public String getModelName() { return modelName; } public void predict(TimeSeries.DataSequence sequence) throws Exception { int n = data.size(); DataSet requiredDataPoints = new DataSet(); DataPoint dp; for (int count = 0; count < n; count++) { dp = new Observation(0.0); dp.setIndependentValue("x", count); requiredDataPoints.add(dp); } forecaster.forecast(requiredDataPoints); // Output the results Iterator<DataPoint> it = requiredDataPoints.iterator(); int i = 0; while (it.hasNext()) { DataPoint pnt = ((DataPoint) it.next()); logger.info(data.get(i).time + "," + data.get(i).value + "," + pnt.getDependentValue()); sequence.set(i, (new Entry(data.get(i).time, (float) pnt.getDependentValue()))); i++; } } public void toJson(JSONStringer json_out) { } public void fromJson(JSONObject json_obj) { } }
package yang.weiwei.tools; import java.io.IOException; import yang.weiwei.preprocess.Tokenizer; public class ToolTokenizer extends ToolInterface { private String modelFileName=""; private String corpusFileName=""; private String outputFileName=""; public void parseCommand(String[] args) { help=findArg("--help", args, false); modelFileName=getArg("--model", args); corpusFileName=getArg("--corpus", args); outputFileName=getArg("--output", args); } protected boolean checkCommand() { if (help) return false; if (corpusFileName.length()==0) { println("Corpus file is not specified."); return false; } if (outputFileName.length()==0) { println("Output file is not specified."); return false; } return true; } public void execute() throws IOException { if (!checkCommand()) { printHelp(); return; } Tokenizer tokenizer=(modelFileName.length()>0? new Tokenizer(modelFileName) : new Tokenizer()); tokenizer.tokenizeFile(corpusFileName, outputFileName); } public void printHelp() { println("Arguments for Tokenizer:"); println("\t--help [optional]: Print help information."); println("\t--model [optional]: Use user's model to tokenize documents."); println("\t--corpus: Untokenized corpus file."); println("\t--output: Tokenized corpus file."); } }
package com.siriusxi.ms.store.ps; import com.siriusxi.ms.store.api.core.product.Product; import com.siriusxi.ms.store.ps.controller.ProductMapper; import com.siriusxi.ms.store.ps.persistence.ProductEntity; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; public class MapperTests { private final ProductMapper mapper = ProductMapper.INSTANCE; @Test public void mapperTests() { assertNotNull(mapper); Product api = new Product(1, "n", 1, "sa"); ProductEntity entity = mapper.apiToEntity(api); assertEquals(api.getProductId(), entity.getProductId()); assertEquals(api.getProductId(), entity.getProductId()); assertEquals(api.getName(), entity.getName()); assertEquals(api.getWeight(), entity.getWeight()); Product api2 = mapper.entityToApi(entity); assertEquals(api.getProductId(), api2.getProductId()); assertEquals(api.getProductId(), api2.getProductId()); assertEquals(api.getName(), api2.getName()); assertEquals(api.getWeight(), api2.getWeight()); assertNull(api2.getServiceAddress()); } }
package com.ws.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.ws.bean.Sys_record_commissioner; import org.springframework.stereotype.Repository; @Repository public interface CommissionerMapper extends BaseMapper<Sys_record_commissioner> { }
package eu.datlab.worker.parser; import eu.datlab.dataaccess.dao.DAOFactory; import eu.datlab.dataaccess.dto.parsed.ParsedBudgetItem; import eu.dl.dataaccess.dao.ParsedDAO; import eu.dl.dataaccess.dao.RawDAO; import eu.dl.dataaccess.dao.TransactionUtils; import eu.dl.dataaccess.dto.raw.RawData; import eu.dl.worker.parsed.BaseParser; /** * Base class for budget item parsers. */ public abstract class BaseDatlabBudgetItemParser extends BaseParser<RawData, ParsedBudgetItem> { @Override protected final RawDAO<RawData> getRawDAO() { return DAOFactory.getDAOFactory().getRawBudgetItemDAO(getName(), getVersion()); } @Override protected final ParsedDAO<ParsedBudgetItem> getParsedDAO() { return DAOFactory.getDAOFactory().getParsedBudgetItemDAO(getName(), getVersion()); } @Override protected final TransactionUtils getTransactionUtils() { return DAOFactory.getDAOFactory().getTransactionUtils(); } }
/** * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.gravitee.gateway.standalone.vertx; import io.gravitee.common.http.IdGenerator; import io.gravitee.gateway.api.Request; import io.gravitee.gateway.api.Response; import io.gravitee.gateway.api.handler.Handler; import io.gravitee.gateway.reactor.Reactor; import io.vertx.core.Vertx; /** * @author David BRASSELY (david.brassely at graviteesource.com) * @author GraviteeSource Team */ public class VertxReactorTimeoutHandler extends VertxReactorHandler { private final VertxReactorHandler handler; private final Vertx vertx; private final long timeout; VertxReactorTimeoutHandler( final Reactor reactor, final VertxReactorHandler handler, final Vertx vertx, final long timeout, IdGenerator idGenerator ) { super(reactor, idGenerator); this.handler = handler; this.vertx = vertx; this.timeout = timeout; } protected void route(final Request request, final Response response) { if (!request.isWebSocket()) { long timeoutId = vertx.setTimer( timeout, event -> { if (!response.ended()) { Handler<Long> handler = request.timeoutHandler(); handler.handle(event); } } ); // Release timeout when response ends handler.route(request, new TimeoutServerResponse(vertx, response, timeoutId)); } else { handler.route(request, response); } } }
/* * 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.accumulo.fate.util; import java.security.Security; import junit.framework.TestCase; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Test the AddressUtil class. * */ public class AddressUtilTest extends TestCase { private static final Logger log = LoggerFactory.getLogger(AddressUtilTest.class); public void testGetNegativeTtl() { log.info("Checking that we can get the ttl on dns failures."); int expectedTtl = 20; boolean expectException = false; /* TODO ACCUMULO-2242 replace all of this with Powermock on the Security class */ try { Security.setProperty("networkaddress.cache.negative.ttl", Integer.toString(expectedTtl)); } catch (SecurityException exception) { log.warn("We can't set the DNS cache period, so we're only testing fetching the system value."); expectedTtl = 10; } try { expectedTtl = Integer.parseInt(Security.getProperty("networkaddress.cache.negative.ttl")); } catch (SecurityException exception) { log.debug("Security manager won't let us fetch the property, testing default path."); expectedTtl = 10; } catch (NumberFormatException exception) { log.debug("property isn't a number, testing default path."); expectedTtl = 10; } if (-1 == expectedTtl) { log.debug("property is set to 'forever', testing exception path"); expectException = true; } if (0 > expectedTtl) { log.debug("property is a negative value other than 'forever', testing default path."); expectedTtl = 10; } try { if (expectException) { log.info("AddressUtil is (hopefully) going to spit out an error about DNS lookups. you can ignore it."); } int result = AddressUtil.getAddressCacheNegativeTtl(null); if (expectException) { fail("The JVM Security settings cache DNS failures forever. In this case we expect an exception but didn't get one."); } assertEquals("Didn't get the ttl we expected", expectedTtl, result); } catch (IllegalArgumentException exception) { if (!expectException) { log.error("Got an exception when we weren't expecting.", exception); fail("We only expect to throw an IllegalArgumentException when the JVM caches DNS failures forever."); } } } public void testGetNegativeTtlThrowsOnForever() { log.info("When DNS is cached forever, we should throw."); /* TODO ACCUMULO-2242 replace all of this with Powermock on the Security class */ try { Security.setProperty("networkaddress.cache.negative.ttl", "-1"); } catch (SecurityException exception) { log.error("We can't set the DNS cache period, so this test is effectively ignored."); return; } try { log.info("AddressUtil is (hopefully) going to spit out an error about DNS lookups. you can ignore it."); AddressUtil.getAddressCacheNegativeTtl(null); fail("The JVM Security settings cache DNS failures forever, this should cause an exception."); } catch (IllegalArgumentException exception) { assertTrue(true); } } }
/* Copyright 2018 The Trustees of University of Arizona 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 stargate.managers.transport.layout; import java.io.IOException; import java.util.Collection; import stargate.commons.cluster.Cluster; import stargate.commons.cluster.Node; import stargate.commons.datastore.AbstractBigKeyValueStore; import stargate.commons.recipe.Recipe; import stargate.commons.recipe.RecipeChunk; import stargate.commons.service.AbstractService; import stargate.commons.utils.StringUtils; import stargate.managers.transport.TransportManager; import stargate.service.StargateService; /** * * @author iychoi */ public class MasterCopyTransferLayoutAlgorithm extends AbstractTransferLayoutAlgorithm { public MasterCopyTransferLayoutAlgorithm(AbstractService service, TransportManager manager, AbstractBigKeyValueStore dataCacheStore, AbstractContactNodeSelectionAlgorithm contactNodeSelectionAlgorithm) { if(service == null) { throw new IllegalArgumentException("service is null"); } if(manager == null) { throw new IllegalArgumentException("manager is null"); } if(dataCacheStore == null) { throw new IllegalArgumentException("dataCacheStore is null"); } if(contactNodeSelectionAlgorithm == null) { throw new IllegalArgumentException("contactNodeSelectionAlgorithm is null"); } if(!(service instanceof StargateService)) { throw new IllegalArgumentException("service is not an instance of StargateService"); } if(!service.isStarted()) { throw new IllegalArgumentException("service is not started"); } if(!manager.isStarted()) { throw new IllegalArgumentException("manager is not started"); } this.service = (StargateService) service; this.manager = manager; this.dataCacheStore = dataCacheStore; this.contactNodeSelectionAlgorithm = contactNodeSelectionAlgorithm; } public MasterCopyTransferLayoutAlgorithm(StargateService service, TransportManager manager, AbstractBigKeyValueStore dataCacheStore, AbstractContactNodeSelectionAlgorithm contactNodeSelectionAlgorithm) { if(service == null) { throw new IllegalArgumentException("service is null"); } if(manager == null) { throw new IllegalArgumentException("manager is null"); } if(dataCacheStore == null) { throw new IllegalArgumentException("dataCacheStore is null"); } if(contactNodeSelectionAlgorithm == null) { throw new IllegalArgumentException("contactNodeSelectionAlgorithm is null"); } if(!service.isStarted()) { throw new IllegalArgumentException("service is not started"); } if(!manager.isStarted()) { throw new IllegalArgumentException("manager is not started"); } this.service = service; this.manager = manager; this.dataCacheStore = dataCacheStore; this.contactNodeSelectionAlgorithm = contactNodeSelectionAlgorithm; } @Override public void increaseNodeWorkload(Cluster cluster, Node node) throws IOException { // noop } @Override public void decreaseNodeWorkload(Cluster cluster, Node node) throws IOException { // noop } @Override public Node determineLocalNode(Cluster cluster, Recipe recipe, String hash) throws IOException { if(cluster == null) { throw new IllegalArgumentException("cluster is null"); } if(recipe == null) { throw new IllegalArgumentException("recipe is null"); } if(hash == null || hash.isEmpty()) { throw new IllegalArgumentException("hash is null"); } // use always the master String primaryNodeName = this.dataCacheStore.getPrimaryNodeForData(hash); Node node = cluster.getNode(primaryNodeName); return node; } @Override public Node determineRemoteNode(Cluster localCluster, Node localNode, Cluster remoteCluster, Recipe recipe, String hash) throws IOException { if(localCluster == null) { throw new IllegalArgumentException("localCluster is null"); } if(localNode == null) { throw new IllegalArgumentException("localNode is null"); } if(remoteCluster == null) { throw new IllegalArgumentException("remoteCluster is null"); } if(recipe == null) { throw new IllegalArgumentException("recipe is null"); } if(hash == null || hash.isEmpty()) { throw new IllegalArgumentException("hash is null or empty"); } RecipeChunk chunk = recipe.getChunk(hash); Collection<Integer> nodeIDs = chunk.getNodeIDs(); if(nodeIDs.isEmpty()) { throw new IOException(String.format("There is no node for hash %s", hash)); } Collection<String> nodeNames = recipe.getNodeNames(nodeIDs); if(nodeNames.isEmpty()) { throw new IOException(String.format("Cannot get node names for node IDs: %s", StringUtils.getCommaSeparatedString(nodeIDs))); } for(String nodeName : nodeNames) { Node remoteNode = remoteCluster.getNode(nodeName); // we return very first node who has the chunk return remoteNode; } // ERROR throw new IOException(String.format("Cannot determine remote node for hash %s, nodeNames %s", hash, StringUtils.getCommaSeparatedString(nodeNames))); } }
package com.ketai.gmall.pms.entity; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.io.Serializable; import java.util.Date; import lombok.Data; /** * 品牌 * * @author yuxingyou * @email qiyuanYXY@163.com * @date 2020-04-14 10:06:35 */ @ApiModel @Data @TableName("pms_brand") public class BrandEntity implements Serializable { private static final long serialVersionUID = 1L; /** * 品牌id */ @TableId @ApiModelProperty(name = "brandId",value = "品牌id") private Long brandId; /** * 品牌名 */ @ApiModelProperty(name = "name",value = "品牌名") private String name; /** * 品牌logo地址 */ @ApiModelProperty(name = "logo",value = "品牌logo地址") private String logo; /** * 介绍 */ @ApiModelProperty(name = "descript",value = "介绍") private String descript; /** * 显示状态[0-不显示;1-显示] */ @ApiModelProperty(name = "showStatus",value = "显示状态[0-不显示;1-显示]") private Integer showStatus; /** * 检索首字母 */ @ApiModelProperty(name = "firstLetter",value = "检索首字母") private String firstLetter; /** * 排序 */ @ApiModelProperty(name = "sort",value = "排序") private Integer sort; }
/* * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.location.provider; import android.annotation.IntDef; import android.annotation.NonNull; import android.os.Parcel; import android.os.Parcelable; import com.android.internal.util.Preconditions; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.util.Objects; /** * Location provider properties. */ public final class ProviderProperties implements Parcelable { /** * A constant indicating low power usage. */ public static final int POWER_USAGE_LOW = 1; /** * A constant indicating a medium power usage. */ public static final int POWER_USAGE_MEDIUM = 2; /** * A constant indicating high power usage. */ public static final int POWER_USAGE_HIGH = 3; /** @hide */ @Retention(RetentionPolicy.SOURCE) @IntDef(prefix = "POWER_USAGE_", value = {POWER_USAGE_LOW, POWER_USAGE_MEDIUM, POWER_USAGE_HIGH}) public @interface PowerUsage {} /** * A constant indicating a finer location accuracy. */ public static final int ACCURACY_FINE = 1; /** * A constant indicating a coarser location accuracy. */ public static final int ACCURACY_COARSE = 2; /** @hide */ @Retention(RetentionPolicy.SOURCE) @IntDef(prefix = "ACCURACY_", value = {ACCURACY_FINE, ACCURACY_COARSE}) public @interface Accuracy {} private final boolean mHasNetworkRequirement; private final boolean mHasSatelliteRequirement; private final boolean mHasCellRequirement; private final boolean mHasMonetaryCost; private final boolean mHasAltitudeSupport; private final boolean mHasSpeedSupport; private final boolean mHasBearingSupport; private final @PowerUsage int mPowerUsage; private final @Accuracy int mAccuracy; private ProviderProperties(boolean hasNetworkRequirement, boolean hasSatelliteRequirement, boolean hasCellRequirement, boolean hasMonetaryCost, boolean hasAltitudeSupport, boolean hasSpeedSupport, boolean hasBearingSupport, @PowerUsage int powerUsage, @Accuracy int accuracy) { mHasNetworkRequirement = hasNetworkRequirement; mHasSatelliteRequirement = hasSatelliteRequirement; mHasCellRequirement = hasCellRequirement; mHasMonetaryCost = hasMonetaryCost; mHasAltitudeSupport = hasAltitudeSupport; mHasSpeedSupport = hasSpeedSupport; mHasBearingSupport = hasBearingSupport; mPowerUsage = powerUsage; mAccuracy = accuracy; } /** * True if provider requires access to a data network (e.g., the Internet). */ public boolean hasNetworkRequirement() { return mHasNetworkRequirement; } /** * True if the provider requires access to a satellite-based positioning system (e.g., GPS). */ public boolean hasSatelliteRequirement() { return mHasSatelliteRequirement; } /** * True if the provider requires access to a cellular network (e.g., for cell tower IDs). */ public boolean hasCellRequirement() { return mHasCellRequirement; } /** * True if this provider may result in a monetary charge to the user. Network usage is not * considered a monetary cost. */ public boolean hasMonetaryCost() { return mHasMonetaryCost; } /** * True if the provider is able to provide altitude under at least some conditions. */ public boolean hasAltitudeSupport() { return mHasAltitudeSupport; } /** * True if the provider is able to provide speed under at least some conditions. */ public boolean hasSpeedSupport() { return mHasSpeedSupport; } /** * True if the provider is able to provide bearing under at least some conditions. */ public boolean hasBearingSupport() { return mHasBearingSupport; } /** * Power usage for this provider. */ public @PowerUsage int getPowerUsage() { return mPowerUsage; } /** * Rough location accuracy for this provider, primarily with respect to horizontal location * accuracy. */ public @Accuracy int getAccuracy() { return mAccuracy; } public static final @NonNull Creator<ProviderProperties> CREATOR = new Creator<ProviderProperties>() { @Override public ProviderProperties createFromParcel(Parcel in) { return new ProviderProperties( /* hasNetworkRequirement= */ in.readBoolean(), /* hasSatelliteRequirement= */ in.readBoolean(), /* hasCellRequirement= */ in.readBoolean(), /* hasMonetaryCost= */ in.readBoolean(), /* hasAltitudeSupport= */ in.readBoolean(), /* hasSpeedSupport= */ in.readBoolean(), /* hasBearingSupport= */ in.readBoolean(), /* powerUsage= */ in.readInt(), /* accuracy= */ in.readInt()); } @Override public ProviderProperties[] newArray(int size) { return new ProviderProperties[size]; } }; @Override public int describeContents() { return 0; } @Override public void writeToParcel(@NonNull Parcel parcel, int flags) { parcel.writeBoolean(mHasNetworkRequirement); parcel.writeBoolean(mHasSatelliteRequirement); parcel.writeBoolean(mHasCellRequirement); parcel.writeBoolean(mHasMonetaryCost); parcel.writeBoolean(mHasAltitudeSupport); parcel.writeBoolean(mHasSpeedSupport); parcel.writeBoolean(mHasBearingSupport); parcel.writeInt(mPowerUsage); parcel.writeInt(mAccuracy); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof ProviderProperties)) { return false; } ProviderProperties that = (ProviderProperties) o; return mHasNetworkRequirement == that.mHasNetworkRequirement && mHasSatelliteRequirement == that.mHasSatelliteRequirement && mHasCellRequirement == that.mHasCellRequirement && mHasMonetaryCost == that.mHasMonetaryCost && mHasAltitudeSupport == that.mHasAltitudeSupport && mHasSpeedSupport == that.mHasSpeedSupport && mHasBearingSupport == that.mHasBearingSupport && mPowerUsage == that.mPowerUsage && mAccuracy == that.mAccuracy; } @Override public int hashCode() { return Objects.hash(mHasNetworkRequirement, mHasSatelliteRequirement, mHasCellRequirement, mHasMonetaryCost, mHasAltitudeSupport, mHasSpeedSupport, mHasBearingSupport, mPowerUsage, mAccuracy); } @Override public String toString() { StringBuilder b = new StringBuilder("ProviderProperties["); b.append("powerUsage=").append(powerToString(mPowerUsage)).append(", "); b.append("accuracy=").append(accuracyToString(mAccuracy)); if (mHasNetworkRequirement || mHasSatelliteRequirement || mHasCellRequirement) { b.append(", requires="); if (mHasNetworkRequirement) { b.append("network,"); } if (mHasSatelliteRequirement) { b.append("satellite,"); } if (mHasCellRequirement) { b.append("cell,"); } b.setLength(b.length() - 1); } if (mHasMonetaryCost) { b.append(", hasMonetaryCost"); } if (mHasBearingSupport || mHasSpeedSupport || mHasAltitudeSupport) { b.append(", supports=["); if (mHasBearingSupport) { b.append("bearing,"); } if (mHasSpeedSupport) { b.append("speed,"); } if (mHasAltitudeSupport) { b.append("altitude,"); } b.setLength(b.length() - 1); b.append("]"); } b.append("]"); return b.toString(); } private static String powerToString(@PowerUsage int power) { switch (power) { case POWER_USAGE_LOW: return "Low"; case POWER_USAGE_MEDIUM: return "Medium"; case POWER_USAGE_HIGH: return "High"; default: throw new AssertionError(); } } private static String accuracyToString(@Accuracy int accuracy) { switch (accuracy) { case ACCURACY_COARSE: return "Coarse"; case ACCURACY_FINE: return "Fine"; default: throw new AssertionError(); } } /** * Builder for ProviderProperties. */ public static final class Builder { private boolean mHasNetworkRequirement; private boolean mHasSatelliteRequirement; private boolean mHasCellRequirement; private boolean mHasMonetaryCost; private boolean mHasAltitudeSupport; private boolean mHasSpeedSupport; private boolean mHasBearingSupport; private @PowerUsage int mPowerUsage; private @Accuracy int mAccuracy; public Builder() { mHasNetworkRequirement = false; mHasSatelliteRequirement = false; mHasCellRequirement = false; mHasMonetaryCost = false; mHasAltitudeSupport = false; mHasSpeedSupport = false; mHasBearingSupport = false; mPowerUsage = POWER_USAGE_HIGH; mAccuracy = ACCURACY_COARSE; } public Builder(@NonNull ProviderProperties providerProperties) { mHasNetworkRequirement = providerProperties.mHasNetworkRequirement; mHasSatelliteRequirement = providerProperties.mHasSatelliteRequirement; mHasCellRequirement = providerProperties.mHasCellRequirement; mHasMonetaryCost = providerProperties.mHasMonetaryCost; mHasAltitudeSupport = providerProperties.mHasAltitudeSupport; mHasSpeedSupport = providerProperties.mHasSpeedSupport; mHasBearingSupport = providerProperties.mHasBearingSupport; mPowerUsage = providerProperties.mPowerUsage; mAccuracy = providerProperties.mAccuracy; } /** * Sets whether a provider requires network access. False by default. */ public @NonNull Builder setHasNetworkRequirement(boolean requiresNetwork) { mHasNetworkRequirement = requiresNetwork; return this; } /** * Sets whether a provider requires satellite access. False by default. */ public @NonNull Builder setHasSatelliteRequirement(boolean requiresSatellite) { mHasSatelliteRequirement = requiresSatellite; return this; } /** * Sets whether a provider requires cell tower access. False by default. */ public @NonNull Builder setHasCellRequirement(boolean requiresCell) { mHasCellRequirement = requiresCell; return this; } /** * Sets whether a provider has a monetary cost. False by default. */ public @NonNull Builder setHasMonetaryCost(boolean monetaryCost) { mHasMonetaryCost = monetaryCost; return this; } /** * Sets whether a provider can provide altitude information. False by default. */ public @NonNull Builder setHasAltitudeSupport(boolean supportsAltitude) { mHasAltitudeSupport = supportsAltitude; return this; } /** * Sets whether a provider can provide speed information. False by default. */ public @NonNull Builder setHasSpeedSupport(boolean supportsSpeed) { mHasSpeedSupport = supportsSpeed; return this; } /** * Sets whether a provider can provide bearing information. False by default. */ public @NonNull Builder setHasBearingSupport(boolean supportsBearing) { mHasBearingSupport = supportsBearing; return this; } /** * Sets a very rough bucket of provider power usage. {@link #POWER_USAGE_HIGH} by default. */ public @NonNull Builder setPowerUsage(@PowerUsage int powerUsage) { mPowerUsage = Preconditions.checkArgumentInRange(powerUsage, POWER_USAGE_LOW, POWER_USAGE_HIGH, "powerUsage"); return this; } /** * Sets a very rough bucket of provider location accuracy. {@link #ACCURACY_COARSE} by * default. */ public @NonNull Builder setAccuracy(@Accuracy int accuracy) { mAccuracy = Preconditions.checkArgumentInRange(accuracy, ACCURACY_FINE, ACCURACY_COARSE, "accuracy"); return this; } /** * Builds a new ProviderProperties. */ public @NonNull ProviderProperties build() { return new ProviderProperties(mHasNetworkRequirement, mHasSatelliteRequirement, mHasCellRequirement, mHasMonetaryCost, mHasAltitudeSupport, mHasSpeedSupport, mHasBearingSupport, mPowerUsage, mAccuracy); } } }
/* * 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.mongodb.v20180408.models; import com.tencentcloudapi.common.AbstractModel; import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.Expose; import java.util.HashMap; public class TagInfo extends AbstractModel{ /** * 标签Key值 */ @SerializedName("TagKey") @Expose private String TagKey; /** * 标签值 */ @SerializedName("TagValue") @Expose private String TagValue; /** * Get 标签Key值 * @return TagKey 标签Key值 */ public String getTagKey() { return this.TagKey; } /** * Set 标签Key值 * @param TagKey 标签Key值 */ public void setTagKey(String TagKey) { this.TagKey = TagKey; } /** * Get 标签值 * @return TagValue 标签值 */ public String getTagValue() { return this.TagValue; } /** * Set 标签值 * @param TagValue 标签值 */ public void setTagValue(String TagValue) { this.TagValue = TagValue; } /** * Internal implementation, normal users should not use it. */ public void toMap(HashMap<String, String> map, String prefix) { this.setParamSimple(map, prefix + "TagKey", this.TagKey); this.setParamSimple(map, prefix + "TagValue", this.TagValue); } }
package com.zshuai.util; import com.zshuai.pojo.Comment; import org.springframework.beans.BeanUtils; import java.util.ArrayList; import java.util.List; /** * 评论格式化工具 */ public class CommentUtil { /** * 循环每个顶级的评论节点 * @param comments * @return */ public static List<Comment> eachComment(List<Comment> comments) { List<Comment> commentsView = new ArrayList<>(); for (Comment comment : comments) { Comment c = new Comment(); BeanUtils.copyProperties(comment,c); commentsView.add(c); } //合并评论的各层子代到第一级子代集合中 combineChildren(commentsView); return commentsView; } /** * * @param comments root根节点,blog不为空的对象集合 * @return */ public static void combineChildren(List<Comment> comments) { for (Comment comment : comments) { List<Comment> replys1 = comment.getReplyComments(); for(Comment reply1 : replys1) { //循环迭代,找出子代,存放在tempReplys中 recursively(reply1); } //修改顶级节点的reply集合为迭代处理后的集合 comment.setReplyComments(tempReplys); //清除临时存放区 tempReplys = new ArrayList<>(); } } //存放迭代找出的所有子代的集合 public static List<Comment> tempReplys = new ArrayList<>(); /** * 递归迭代,剥洋葱 * @param comment 被迭代的对象 * @return */ public static void recursively(Comment comment) { tempReplys.add(comment);//顶节点添加到临时存放集合 if (comment.getReplyComments().size()>0) { List<Comment> replys = comment.getReplyComments(); for (Comment reply : replys) { tempReplys.add(reply); if (reply.getReplyComments().size()>0) { recursively(reply); } } } } }
package cells; public class ForagingAntsCell extends CellWithPatch { private boolean myFoodItem; private int myNestPheromones; private int myFoodPheromones; private int myLives; private int[] myNeighborLocations; private int myNumberOfAnts; private boolean isNest; private boolean isFood; public ForagingAntsCell () { myOrientation = 0; myForwardLocations = new int[3]; myFoodItem = false; myNestPheromones = 0; myFoodPheromones = 0; myNumberOfAnts = 0; myLives = 0; isNest = false; isFood = false; } public void setIsNest (boolean isnest) { isNest = isnest; } public void setIsFood (boolean isfood) { isFood = isfood; } public boolean isNest () { return isNest; } public boolean isFood () { return isFood; } public int getMyLives () { return myLives; } public void incrementLives () { myLives++; } public void resetLives () { myLives = 0; } public void addToNumberOfAnts (int toAdd) { myNumberOfAnts += toAdd; } public void incrementMyNumberOfAnts () { myNumberOfAnts++; } public void decrementMyNumberOfAnts () { myNumberOfAnts--; } public void setMyNeighborLocations () { myNeighborLocations = new int[myNeighbors.length]; for (int i = 0; i < getMyNeighbors().length; i++) { myNeighborLocations[i] = i; } } public boolean hasFoodItem () { return myFoodItem; } public int getMyNestPheromones () { return myNestPheromones; } public int getMyFoodPheromones () { return myFoodPheromones; } public int[] getMyNeighborLocations () { return myNeighborLocations; } public int getMyNumberOfAnts () { return myNumberOfAnts; } public void setMyNestPheromones (int myNestPheromones) { this.myNestPheromones = myNestPheromones; } public void setMyFoodPheromones (int myFoodPheromones) { this.myFoodPheromones = myFoodPheromones; } public void setMyFoodItem (boolean myFoodItem) { this.myFoodItem = myFoodItem; } public int getTotalPheromones () { return myFoodPheromones + myNestPheromones; } @Override public void initializeWithState (int state) { myNextState = state; myFoodItem = false; myNestPheromones = 0; myFoodPheromones = 0; myLives = 0; } @Override public void evaporate (double evaporationRate) { myNestPheromones = (int) (myNestPheromones * evaporationRate); myFoodPheromones = (int) (myFoodPheromones * evaporationRate); } @Override public void diffuse (double diffusionRate) { for (Cell cell : myNeighbors) { ForagingAntsCell neighbor = (ForagingAntsCell) cell; if (neighbor != null) { int currentNeighborPatch = neighbor.getMyNestPheromones(); int patchToAdd = (int) (myNestPheromones * diffusionRate); neighbor.setMyNestPheromones(currentNeighborPatch + patchToAdd); currentNeighborPatch = neighbor.getMyFoodPheromones(); patchToAdd = (int) (myFoodPheromones * diffusionRate); neighbor.setMyFoodPheromones(currentNeighborPatch + patchToAdd); } } } }
/* * Copyright 2014-2017 See AUTHORS file. * * 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.kotcrab.vis.editor.serializer.cloner; import com.badlogic.gdx.utils.Array; import com.rits.cloning.IDeepCloner; import java.util.Map; /** @author Kotcrab */ public class ArrayCloner extends VisCloner<Array<?>> { @Override protected Array<?> cloneObject (Array<?> original, IDeepCloner cloner, Map<Object, Object> clones) { Array<Object> array = new Array<>(original.size); for (int i = 0; i < original.size; i++) array.add(cloner.deepClone(original.get(i), clones)); return array; } }
/* * Copyright 2017 Apereo * * 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.tle.web.language; import com.google.inject.name.Names; import com.tle.web.sections.equella.guice.SectionsModule; /** * @author larry */ public class LanguageModule extends SectionsModule { @Override protected void configure() { bind(Object.class).annotatedWith(Names.named("/access/language")).toProvider(node(RootLanguageSection.class)); } }
package com.bankass.bankass.model; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.Table; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; @Entity @Table(name = "phone") @Accessors( chain = true) @JsonInclude( value = JsonInclude.Include.NON_NULL) @JsonIgnoreProperties( ignoreUnknown = true) @NoArgsConstructor @AllArgsConstructor @Data public class Phone implements Serializable { /** * */ private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "fone_id") private long id; @Column(name = "code") private int code; @Column(name = "number") private long number; @ManyToOne private Employee employee; @ManyToOne private Client client; }
package cn.hutool.json; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Map; import org.junit.Assert; import org.junit.Test; import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.date.DateUtil; import cn.hutool.core.map.MapUtil; import cn.hutool.json.test.bean.Price; import cn.hutool.json.test.bean.UserA; import cn.hutool.json.test.bean.UserC; public class JSONUtilTest { @Test public void toDateTest() { String x = JSONUtil.parse(new Date()).toString(); Date date = JSONUtil.toBean(JSONUtil.parseObj(x), Date.class); Assert.assertNotNull(date); } @Test public void toJsonStrTest() { UserA a1 = new UserA(); a1.setA("aaaa"); a1.setDate(DateUtil.date()); a1.setName("AAAAName"); UserA a2 = new UserA(); a2.setA("aaaa222"); a2.setDate(DateUtil.date()); a2.setName("AAAA222Name"); ArrayList<UserA> list = CollectionUtil.newArrayList(a1, a2); HashMap<String, Object> map = CollectionUtil.newHashMap(); map.put("total", 13); map.put("rows", list); String str = JSONUtil.toJsonStr(map); Assert.assertNotNull(str); } @Test public void toJsonStrTest2() { Map<String, Object> model = new HashMap<String, Object>(); model.put("mobile", "17610836523"); model.put("type", 1); Map<String, Object> data = new HashMap<String, Object>(); data.put("model", model); JSONObject jsonObject = JSONUtil.parseObj(data); Assert.assertTrue(jsonObject.containsKey("model")); Assert.assertEquals(1, jsonObject.getJSONObject("model").getInt("type").intValue()); Assert.assertEquals("17610836523", jsonObject.getJSONObject("model").getStr("mobile")); // Assert.assertEquals("{\"model\":{\"type\":1,\"mobile\":\"17610836523\"}}", jsonObject.toString()); } @Test public void toJsonStrTest3() { // 验证某个字段为JSON字符串时转义是否规范 JSONObject object = new JSONObject(true); object.put("name", "123123"); object.put("value", "\\"); object.put("value2", "</"); HashMap<String, String> map = MapUtil.newHashMap(); map.put("user", object.toString()); JSONObject json = JSONUtil.parseObj(map); Assert.assertEquals("{\"name\":\"123123\",\"value\":\"\\\\\",\"value2\":\"<\\/\"}", json.get("user")); Assert.assertEquals("{\"user\":\"{\\\"name\\\":\\\"123123\\\",\\\"value\\\":\\\"\\\\\\\\\\\",\\\"value2\\\":\\\"<\\\\/\\\"}\"}", json.toString()); JSONObject json2 = JSONUtil.parseObj(json.toString()); Assert.assertEquals("{\"name\":\"123123\",\"value\":\"\\\\\",\"value2\":\"<\\/\"}", json2.get("user")); } @Test public void toBeanTest() { String json = "{\"ADT\":[[{\"BookingCode\":[\"N\",\"N\"]}]]}"; Price price = JSONUtil.toBean(json, Price.class); Assert.assertEquals("N", price.getADT().get(0).get(0).getBookingCode().get(0)); } @Test public void toBeanTest2() { // 测试JSONObject转为Bean中字符串字段的情况 String json = "{\"id\":123,\"name\":\"张三\",\"prop\":{\"gender\":\"男\", \"age\":18}}"; UserC user = JSONUtil.toBean(json, UserC.class); Assert.assertNotNull(user.getProp()); String prop = user.getProp(); JSONObject propJson = JSONUtil.parseObj(prop); Assert.assertEquals("男", propJson.getStr("gender")); Assert.assertEquals(18, propJson.getInt("age").intValue()); // Assert.assertEquals("{\"age\":18,\"gender\":\"男\"}", user.getProp()); } @Test public void putByPathTest() { JSONObject json = new JSONObject(); json.putByPath("aa.bb", "BB"); Assert.assertEquals("{\"aa\":{\"bb\":\"BB\"}}", json.toString()); } @Test public void getStrTest() { String html = "{\"name\":\"Something must have been changed since you leave\"}"; JSONObject jsonObject = JSONUtil.parseObj(html); Assert.assertEquals("Something must have been changed since you leave", jsonObject.getStr("name")); } @Test public void getStrTest2() { String html = "{\"name\":\"Something\\u00a0must have been changed since you leave\"}"; JSONObject jsonObject = JSONUtil.parseObj(html); Assert.assertEquals("Something\\u00a0must\\u00a0have\\u00a0been\\u00a0changed\\u00a0since\\u00a0you\\u00a0leave", jsonObject.getStr("name")); } @Test public void parseFromXmlTest() { String s = "<sfzh>640102197312070614</sfzh><sfz>640102197312070614X</sfz><name>aa</name><gender>1</gender>"; JSONObject json = JSONUtil.parseFromXml(s); Assert.assertEquals(640102197312070614L, json.get("sfzh")); Assert.assertEquals("640102197312070614X", json.get("sfz")); Assert.assertEquals("aa", json.get("name")); Assert.assertEquals(1, json.get("gender")); } }
package an.devhp.ui.fragment.select.android.db; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import an.devhp.R; import an.devhp.manager.FragmentIds; import an.devhp.model.entity.realm.User; import an.devhp.ui.adapter.SimpleStringListAdapter; import an.devhp.ui.fragment.SimpleListFragment; import an.devhp.ui.listener.ListItemClickListener; import an.devhp.util.LsUtil; import butterknife.BindView; import io.realm.Realm; import io.realm.RealmResults; import io.realm.Sort; /** * @description: * @author: Kenny * @date: 2017-09-03 13:37 * @version: 1.0 */ public class ShowRealmFragment extends SimpleListFragment { @BindView(R.id.show_list_rv) RecyclerView mRvShowList; private SimpleStringListAdapter mShowListAdapter; private List<String> mShowList = new ArrayList<>(); HashMap<String, Integer> map = new HashMap<>(); public static ShowRealmFragment newInstance() { return new ShowRealmFragment(); } @Override protected boolean addFragmentList() { return false; } @Override public String getTitle() { return "Realm Show"; } @Override public long getSimpleFragmentId() { return FragmentIds.SHOW_REALM_DB; } @Override protected View onCreateContentView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_show_db, container, false); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mRvShowList.setLayoutManager(new LinearLayoutManager(mActivity)); List<String> list = new ArrayList<>(); LsUtil.add(list, "增", "删全部", "删第一个", "删除第5个", "删位置为1的数据", "删最后一个", "改最后一个", "改全部", "查询全部", "查询降序", "查询升序", "异步操作"); final SimpleStringListAdapter adapter = new SimpleStringListAdapter(mActivity, list); adapter.setOnItemClickListener(new ListItemClickListener() { @Override public void onListItemClick(View view, int position) { Object t = LsUtil.getLsElement(adapter.getData(),position); if (t instanceof String) { String key = (String) t; final Realm realm = Realm.getDefaultInstance(); if ("增".equals(key)) { realm.beginTransaction(); User user = realm.createObject(User.class); Integer addCount = map.get(key); if (addCount == null) { addCount = 0; } user.name = key + " " + addCount; map.put(key, ++addCount); realm.commitTransaction(); } else if (key.startsWith("删")) { final RealmResults<User> result = realm.where(User.class).findAll(); if ("删全部".equals(key)) { realm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { result.deleteAllFromRealm(); } }); } else if ("删第一个".equals(key)) { realm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { result.deleteFirstFromRealm(); } }); } else if ("删除第5个".equals(key)) { realm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { User user = LsUtil.getLsElement(result, 5); if (user != null) { user.deleteFromRealm(); } } }); } else if ("删位置为1的数据".equals(key)) { realm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { if(result.size()>1){ result.deleteFromRealm(1); } } }); } else if ("删最后一个".equals(key)) { realm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { result.deleteLastFromRealm(); } }); } } else if ("改最后一个".equals(key)) { RealmResults<User> result = realm.where(User.class).findAll(); if(result.size()>0){ User user = result.get(result.size() - 1); realm.beginTransaction(); user.name = "改了最后一个"; realm.commitTransaction(); } } else if ("改全部".equals(key)) { RealmResults<User> result = realm.where(User.class).findAll(); realm.beginTransaction(); for (User u : result) { u.name += "改全部"; } realm.commitTransaction(); } else if (key.startsWith("查询")) { RealmResults<User> result = realm.where(User.class).findAll(); if ("查询降序".equals(key)) { result = result.sort("name", Sort.DESCENDING); } else if ("查询升序".equals(key)) { result = result.sort("name", Sort.ASCENDING); } else if ("查询全部".equals(key)) { queryAll(realm); return; } List<User> userNewList = realm.copyFromRealm(result); if (userNewList != null) { mShowList.clear(); for (User u : userNewList) { mShowList.add(u.name); } setShowListView(); } return; } else if ("异步操作".equals(key)) { realm.executeTransactionAsync(new Realm.Transaction() { @Override public void execute(Realm realm) { User user = realm.createObject(User.class); user.name = "异步创建的对象"; realm.copyToRealm(user); } }, new Realm.Transaction.OnSuccess() { @Override public void onSuccess() { Toast.makeText(mActivity, "异步操作成功了", Toast.LENGTH_LONG).show(); queryAll(realm); } }, new Realm.Transaction.OnError() { @Override public void onError(Throwable error) { Toast.makeText(mActivity, "异步操作失败了", Toast.LENGTH_LONG).show(); } }); return; } queryAll(realm); } } }); setAdapter(adapter); } private void queryAll(Realm realm) { RealmResults<User> users = realm.where(User.class).findAll(); List<User> userNewList = realm.copyFromRealm(users); if (userNewList != null) { mShowList.clear(); for (User u : userNewList) { mShowList.add(u.name); } setShowListView(); } } private void setShowListView() { if (mShowListAdapter == null) { mShowListAdapter = new SimpleStringListAdapter(mActivity, mShowList); mRvShowList.setAdapter(mShowListAdapter); } else { mShowListAdapter.notifyDataSetChanged(); } } }
/** * vertigo - application development platform * * Copyright (C) 2013-2020, Vertigo.io, team@vertigo.io * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.vertigo.ui.impl.thymeleaf.components; import java.util.Map; import org.thymeleaf.context.ITemplateContext; import org.thymeleaf.engine.TemplateData; import org.thymeleaf.engine.TemplateModel; import org.thymeleaf.exceptions.TemplateInputException; import org.thymeleaf.model.IModel; import org.thymeleaf.processor.element.IElementModelStructureHandler; import org.thymeleaf.standard.expression.Fragment; import org.thymeleaf.standard.expression.FragmentExpression; import org.thymeleaf.standard.expression.FragmentExpression.ExecutedFragmentExpression; import org.thymeleaf.standard.expression.IStandardExpressionParser; import org.thymeleaf.standard.expression.NoOpToken; import org.thymeleaf.standard.expression.StandardExpressions; public final class FragmentUtil { private FragmentUtil() { //private constructor for Helper } public static IModel getFragmentModel(final ITemplateContext context, final String attributeValue, final IElementModelStructureHandler structureHandler) { final Object fragmentObj = computeFragment(context, attributeValue); if (fragmentObj == null) { // If the Fragment result is null, this is an error. Note a NULL result is not the same as the result being the empty fragment // (~{}) throw new TemplateInputException("Error resolving fragment: \"" + attributeValue + "\": " + "template or fragment could not be resolved"); } final Fragment fragment = (Fragment) fragmentObj; final TemplateModel fragmentModel = fragment.getTemplateModel(); final Map<String, Object> fragmentParameters = fragment.getParameters(); /* * APPLY THE FRAGMENT'S TEMPLATE RESOLUTION so that all code inside the fragment is executed with its own template resolution info (working * as if it were a local variable) */ final TemplateData fragmentTemplateData = fragmentModel.getTemplateData(); structureHandler.setTemplateData(fragmentTemplateData); /* * APPLY THE FRAGMENT PARAMETERS AS LOCAL VARIABLES, perhaps after reshaping it according to the fragment signature */ if (fragmentParameters != null && fragmentParameters.size() > 0) { for (final Map.Entry<String, Object> fragmentParameterEntry : fragmentParameters.entrySet()) { structureHandler.setLocalVariable(fragmentParameterEntry.getKey(), fragmentParameterEntry.getValue()); } } return fragmentModel; } private static Object computeFragment(final ITemplateContext context, final String input) { final IStandardExpressionParser expressionParser = StandardExpressions.getExpressionParser(context.getConfiguration()); final FragmentExpression fragmentExpression = (FragmentExpression) expressionParser.parseExpression(context, input.trim()); final ExecutedFragmentExpression executedFragmentExpression = FragmentExpression.createExecutedFragmentExpression(context, fragmentExpression); if (executedFragmentExpression.getFragmentSelectorExpressionResult() == null && executedFragmentExpression.getFragmentParameters() == null) { // We might be in the scenario that what we thought was a template name in fact was instead an expression // returning a Fragment itself, so we should simply return it final Object templateNameExpressionResult = executedFragmentExpression.getTemplateNameExpressionResult(); if (templateNameExpressionResult != null) { if (templateNameExpressionResult instanceof Fragment) { return templateNameExpressionResult; } if (templateNameExpressionResult == NoOpToken.VALUE) { return NoOpToken.VALUE; } } } // Given this is a simple (originally unwrapped) fragment expression, we will consider the non-existence // of the fragment a failure. The reason we do this here instead of just waiting and seeing if we receive // a null and then failing is that, in order to receive such "null", the underlying resolution system would // have to execute a (potentially costly) resource.exists() call on the resolved resource. return FragmentExpression.resolveExecutedFragmentExpression(context, executedFragmentExpression, true); } }
/* * Copyright 2017-2022 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.amplifybackend.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.amplifybackend.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * GetBackendAPIResult JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class GetBackendAPIResultJsonUnmarshaller implements Unmarshaller<GetBackendAPIResult, JsonUnmarshallerContext> { public GetBackendAPIResult unmarshall(JsonUnmarshallerContext context) throws Exception { GetBackendAPIResult getBackendAPIResult = new GetBackendAPIResult(); 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 getBackendAPIResult; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("appId", targetDepth)) { context.nextToken(); getBackendAPIResult.setAppId(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("backendEnvironmentName", targetDepth)) { context.nextToken(); getBackendAPIResult.setBackendEnvironmentName(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("error", targetDepth)) { context.nextToken(); getBackendAPIResult.setError(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("resourceConfig", targetDepth)) { context.nextToken(); getBackendAPIResult.setResourceConfig(BackendAPIResourceConfigJsonUnmarshaller.getInstance().unmarshall(context)); } if (context.testExpression("resourceName", targetDepth)) { context.nextToken(); getBackendAPIResult.setResourceName(context.getUnmarshaller(String.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 getBackendAPIResult; } private static GetBackendAPIResultJsonUnmarshaller instance; public static GetBackendAPIResultJsonUnmarshaller getInstance() { if (instance == null) instance = new GetBackendAPIResultJsonUnmarshaller(); return instance; } }
package everyos.browser.spec.jcss.intf; public interface StyleSheet { String getType(); String getHref(); Object getOwnerNode(); CSSStyleSheet getParentStyleSheet(); String getTitle(); MediaList getMedia(); boolean getDisabled(); boolean setDisabled(boolean disabled); }
/*! ****************************************************************************** * * Hop : The Hop Orchestration Platform * * http://www.project-hop.org * ******************************************************************************* * * 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.pipeline.transforms.jsonoutput; /** * Describes a single field in an Json output file * * @author Samatar * @since 14-june-2010 * */ public class JsonOutputField implements Cloneable { private String fieldName; private String elementName; public JsonOutputField( String fieldName, String elementName, int type, String format, int length, int precision, String currencySymbol, String decimalSymbol, String groupSymbol, String nullString, boolean attribute, String attributeParentName ) { this.fieldName = fieldName; this.elementName = elementName; } public JsonOutputField() { } public int compare( Object obj ) { JsonOutputField field = (JsonOutputField) obj; return fieldName.compareTo( field.getFieldName() ); } public boolean equal( Object obj ) { JsonOutputField field = (JsonOutputField) obj; return fieldName.equals( field.getFieldName() ); } public Object clone() { try { Object retval = super.clone(); return retval; } catch ( CloneNotSupportedException e ) { return null; } } public String getFieldName() { return fieldName; } public void setFieldName( String fieldname ) { this.fieldName = fieldname; } /** * @return Returns the elementName. */ public String getElementName() { return elementName; } /** * @param elementName * The elementName to set. */ public void setElementName( String elementName ) { this.elementName = elementName; } }
package intensiveteamhslee; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.data.rest.core.annotation.RepositoryRestResource; import feign.Param; @RepositoryRestResource(collectionResourceRel="marketings", path="marketings") public interface MarketingRepository extends PagingAndSortingRepository<Marketing, Long>{ Marketing findByRoomId(@Param("roomId") Long roomId); }
package tools; import java.awt.Graphics; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseWheelEvent; import java.io.File; import java.util.ArrayList; import java.util.List; import backgroundThreads.Thumbnail_Reader; import main.Data_Access; import main.IMP; import file.Input; import gui.Design_Preferences; import gui.Image_Tile; import gui_system.GuiIntValue; import gui_system.GuiStringValue; import gui_system.PE_Button2; import gui_system.PE_File_Preview; import gui_system.PE_File_Preview_Element; import gui_system.PE_File_Preview_Folders; import gui_system.PE_Slider; import gui_system.PE_Textfield; import gui_system.Tile; public class Routine_Open_Image extends Routine implements Data_Access, Design_Preferences{ //gui Tile main_tile; PE_File_Preview image_preview; PE_File_Preview_Folders folder_preview; private List<PE_File_Preview_Element> file_tiles; PE_Textfield location_bar_textfield; GuiIntValue preview_size_value; GuiIntValue scroll_value; // previous gui state private boolean sidepanelWasVisible; //Threads Thumbnail_Reader thumbnail_reader; public Routine_Open_Image() { super(); //functionality directory=new File(System.getProperty("user.home")); //GUI set_name("Öffne ein Bild"); category = "Datei"; key_shortcut = 'o'; main_tile=new Tile(Tile.VERTICAL); Tile location_bar = new Tile(Tile.HORIZONTAL); location_bar.set_height(30); location_bar.height_is_fixed=true; search_bar_text=new GuiStringValue(directory.getAbsolutePath()); location_bar_textfield=new PE_Textfield(search_bar_text); location_bar.add(new PE_Button2("directory up", "directory_up", this)); location_bar.add(location_bar_textfield); // location_bar.add(open_button); main_tile.add(location_bar); preview_size_value=new GuiIntValue(0,1800,200); scroll_value=new GuiIntValue(0,4000,0); folder_preview = new PE_File_Preview_Folders(); image_preview = new PE_File_Preview(preview_size_value, scroll_value); file_tiles=new ArrayList<PE_File_Preview_Element>(); Tile horizontal_tile=new Tile(Tile.HORIZONTAL); horizontal_tile.add(folder_preview); horizontal_tile.add(image_preview); main_tile.add(horizontal_tile); PE_Slider zoom_slider = new PE_Slider("zoom",preview_size_value, this); main_tile.add(zoom_slider); main_tile.refresh_children(); //----- needs_open_image = false; } @Override public void activate(){ super.activate(); sidepanelWasVisible = IMP.mama.isComponentVisible(IMP.mama.SIDEPANEL); System.out.println(sidepanelWasVisible); IMP.mama.hideComponent(IMP.mama.SIDEPANEL); scan_directory(directory); } @Override public void apply(){ thumbnail_reader.interrupt(); Input.scan_document(selected_image); super.apply(); revertGuiChanges(); IMP.active_image_tile.view.filled_view(); } @Override public void abort(){ super.abort(); revertGuiChanges(); } @Override public void mouse_pressed(MouseEvent e){ main_tile.mouse_pressed(e); } @Override public void mouse_dragged(MouseEvent e){ main_tile.mouse_dragged(e); } @Override public void mouse_released(MouseEvent e){ main_tile.mouse_released(e); } public void mouse_released_anywhere(MouseEvent e){ main_tile.mouse_released_anywhere(e); } @Override public void mouse_clicked(MouseEvent e){ for(int i=0;i<file_tiles.size();i++){ file_tiles.get(i).selected=false; } main_tile.mouse_clicked(e); } @Override public void key_pressed(KeyEvent e){ main_tile.key_pressed(e); } @Override public void key_typed(KeyEvent e){ main_tile.key_typed(e); } @Override public void mouse_wheel(MouseWheelEvent e){ main_tile.mouse_wheel(e); } @Override public void take_action(String action) { if(action=="open"){ if (selected_image!=null) apply(); } else if(action=="selected"){ selected_image=null; for(int i=0;i<file_tiles.size();i++){ if(file_tiles.get(i).selected) selected_image=file_tiles.get(i).get_file(); } if(selected_image!=null) location_bar_textfield.set_text(selected_image.getAbsolutePath()); else location_bar_textfield.set_text(directory.getAbsolutePath()); } else if(action=="directory_up"){ this.directory=directory.getParentFile(); scan_directory(this.directory); } else{ File directory = new File(action); if(directory.isDirectory()){ this.directory=directory; scan_directory(this.directory); } } } @Override public void paint_on_screen(Graphics g, Image_Tile tile) { main_tile.set_position(IMP.active_image_tile.get_position()); main_tile.set_size(IMP.active_image_tile.get_size()); main_tile.refresh_children(); g.setClip(main_tile.get_position().x,main_tile.get_position().y,main_tile.getWidth(),main_tile.getHeight()); main_tile.paint(g); } //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ //------------------------------------------------------------------------------------------------------------------------------ //funcionality // Function parameters that the user can change in the dialogue. The calculated values are set to make the filter work in a default way. static int width=1000; //width of the new image static int height=1000; //height of the new image private File directory; private File selected_image; private List<File> files; private List<File> directories; private GuiStringValue search_bar_text; private void scan_directory(File directory){ //read all directory entries File[] elements=directory.listFiles(); //filter image files into a new list called files files=new ArrayList<File>(); directories=new ArrayList<File>(); for(int i=0;i<elements.length;i++){ if(elements[i].isFile() && file_contains_image_extension(elements[i])) files.add(elements[i]); else if(elements[i].isDirectory() && !elements[i].isHidden()) directories.add(elements[i]); } //empty old preview file objects and load the new ones file_tiles.clear(); image_preview.remove_all_children(); folder_preview.remove_all_children(); for(int i=0;i<files.size();i++){ PE_File_Preview_Element file_to_add=new PE_File_Preview_Element(files.get(i), "action", this); file_tiles.add(file_to_add); image_preview.add(file_to_add); } for(int i=0;i<directories.size();i++){ folder_preview.add(new PE_Button2(directories.get(i).getName(), directories.get(i).getAbsolutePath(), this)); } //Threads thumbnail_reader=new Thumbnail_Reader(file_tiles); thumbnail_reader.start(); } private boolean file_contains_image_extension(File file) { if(file.getName().endsWith(".jpg") || file.getName().endsWith(".png") || file.getName().endsWith(".bmp") || file.getName().endsWith(".gif") || file.getName().endsWith(".jpeg") || file.getName().endsWith(".JPG")) return true; else return false; } private void revertGuiChanges(){ if(sidepanelWasVisible) { IMP.mama.showComponent(IMP.mama.SIDEPANEL); } else{ IMP.mama.hideComponent(IMP.mama.SIDEPANEL); } } }
/* * Copyright 2016, gRPC 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 io.grpc.okhttp; import static com.google.common.truth.Truth.assertThat; import static io.grpc.internal.ClientStreamListener.RpcProgress.PROCESSED; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.eq; import static org.mockito.Matchers.isA; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import com.google.common.io.BaseEncoding; import io.grpc.Metadata; import io.grpc.MethodDescriptor; import io.grpc.MethodDescriptor.MethodType; import io.grpc.Status; import io.grpc.internal.GrpcUtil; import io.grpc.internal.NoopClientStreamListener; import io.grpc.internal.StatsTraceContext; import io.grpc.internal.TransportTracer; import io.grpc.okhttp.internal.framed.ErrorCode; import io.grpc.okhttp.internal.framed.Header; import java.io.ByteArrayInputStream; import java.nio.charset.Charset; import java.util.List; import java.util.concurrent.atomic.AtomicReference; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; @RunWith(JUnit4.class) public class OkHttpClientStreamTest { private static final int MAX_MESSAGE_SIZE = 100; @Mock private MethodDescriptor.Marshaller<Void> marshaller; @Mock private AsyncFrameWriter frameWriter; @Mock private OkHttpClientTransport transport; @Mock private OutboundFlowController flowController; @Captor private ArgumentCaptor<List<Header>> headersCaptor; private final Object lock = new Object(); private final TransportTracer transportTracer = new TransportTracer(); private MethodDescriptor<?, ?> methodDescriptor; private OkHttpClientStream stream; @Before public void setUp() { MockitoAnnotations.initMocks(this); methodDescriptor = MethodDescriptor.<Void, Void>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName("testService/test") .setRequestMarshaller(marshaller) .setResponseMarshaller(marshaller) .build(); stream = new OkHttpClientStream( methodDescriptor, new Metadata(), frameWriter, transport, flowController, lock, MAX_MESSAGE_SIZE, "localhost", "userAgent", StatsTraceContext.NOOP, transportTracer); } @Test public void getType() { assertEquals(MethodType.UNARY, stream.getType()); } @Test public void cancel_notStarted() { final AtomicReference<Status> statusRef = new AtomicReference<Status>(); stream.start(new BaseClientStreamListener() { @Override public void closed( Status status, RpcProgress rpcProgress, Metadata trailers) { statusRef.set(status); assertTrue(Thread.holdsLock(lock)); } }); stream.cancel(Status.CANCELLED); assertEquals(Status.Code.CANCELLED, statusRef.get().getCode()); } @Test public void cancel_started() { stream.start(new BaseClientStreamListener()); stream.transportState().start(1234); Mockito.doAnswer(new Answer<Void>() { @Override public Void answer(InvocationOnMock invocation) throws Throwable { assertTrue(Thread.holdsLock(lock)); return null; } }).when(transport).finishStream( 1234, Status.CANCELLED, PROCESSED, true, ErrorCode.CANCEL, null); stream.cancel(Status.CANCELLED); verify(transport).finishStream(1234, Status.CANCELLED, PROCESSED,true, ErrorCode.CANCEL, null); } @Test public void start_alreadyCancelled() { stream.start(new BaseClientStreamListener()); stream.cancel(Status.CANCELLED); stream.transportState().start(1234); verifyNoMoreInteractions(frameWriter); } @Test public void start_userAgentRemoved() { Metadata metaData = new Metadata(); metaData.put(GrpcUtil.USER_AGENT_KEY, "misbehaving-application"); stream = new OkHttpClientStream(methodDescriptor, metaData, frameWriter, transport, flowController, lock, MAX_MESSAGE_SIZE, "localhost", "good-application", StatsTraceContext.NOOP, transportTracer); stream.start(new BaseClientStreamListener()); stream.transportState().start(3); verify(frameWriter).synStream(eq(false), eq(false), eq(3), eq(0), headersCaptor.capture()); assertThat(headersCaptor.getValue()) .contains(new Header(GrpcUtil.USER_AGENT_KEY.name(), "good-application")); } @Test public void start_headerFieldOrder() { Metadata metaData = new Metadata(); metaData.put(GrpcUtil.USER_AGENT_KEY, "misbehaving-application"); stream = new OkHttpClientStream(methodDescriptor, metaData, frameWriter, transport, flowController, lock, MAX_MESSAGE_SIZE, "localhost", "good-application", StatsTraceContext.NOOP, transportTracer); stream.start(new BaseClientStreamListener()); stream.transportState().start(3); verify(frameWriter).synStream(eq(false), eq(false), eq(3), eq(0), headersCaptor.capture()); assertThat(headersCaptor.getValue()).containsExactly( Headers.SCHEME_HEADER, Headers.METHOD_HEADER, new Header(Header.TARGET_AUTHORITY, "localhost"), new Header(Header.TARGET_PATH, "/" + methodDescriptor.getFullMethodName()), new Header(GrpcUtil.USER_AGENT_KEY.name(), "good-application"), Headers.CONTENT_TYPE_HEADER, Headers.TE_HEADER) .inOrder(); } @Test public void getUnaryRequest() { MethodDescriptor<?, ?> getMethod = MethodDescriptor.<Void, Void>newBuilder() .setType(MethodDescriptor.MethodType.UNARY) .setFullMethodName("service/method") .setIdempotent(true) .setSafe(true) .setRequestMarshaller(marshaller) .setResponseMarshaller(marshaller) .build(); stream = new OkHttpClientStream(getMethod, new Metadata(), frameWriter, transport, flowController, lock, MAX_MESSAGE_SIZE, "localhost", "good-application", StatsTraceContext.NOOP, transportTracer); stream.start(new BaseClientStreamListener()); // GET streams send headers after halfClose is called. verify(frameWriter, times(0)).synStream( eq(false), eq(false), eq(3), eq(0), headersCaptor.capture()); verify(transport, times(0)).streamReadyToStart(isA(OkHttpClientStream.class)); byte[] msg = "request".getBytes(Charset.forName("UTF-8")); stream.writeMessage(new ByteArrayInputStream(msg)); stream.halfClose(); verify(transport).streamReadyToStart(eq(stream)); stream.transportState().start(3); verify(frameWriter) .synStream(eq(true), eq(false), eq(3), eq(0), headersCaptor.capture()); assertThat(headersCaptor.getValue()).contains(Headers.METHOD_GET_HEADER); assertThat(headersCaptor.getValue()).contains( new Header(Header.TARGET_PATH, "/" + getMethod.getFullMethodName() + "?" + BaseEncoding.base64().encode(msg))); } // TODO(carl-mastrangelo): extract this out into a testing/ directory and remove other definitions // of it. private static class BaseClientStreamListener extends NoopClientStreamListener { @Override public void messagesAvailable(MessageProducer producer) { while (producer.next() != null) {} } } }
/* * 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.inlong.manager.common.pojo.query.hive; import org.apache.inlong.manager.common.pojo.query.ColumnInfoBean; public class HiveColumnInfoBean extends ColumnInfoBean { }
package org.springframework.transaction.config; import java.io.Serializable; import org.springframework.transaction.annotation.Transactional; /** * @author Rob Harrop * @author Juergen Hoeller */ @SuppressWarnings("serial") public class TransactionalService implements Serializable { @Transactional("synch") public void setSomething(String name) { } @Transactional("noSynch") public void doSomething() { } }
package org.robolectric.fakes; import android.webkit.WebSettings; /** * Robolectric implementation of {@link android.webkit.WebSettings}. */ public class RoboWebSettings extends WebSettings { private boolean blockNetworkImage = false; private boolean javaScriptEnabled = false; private boolean javaScriptCanOpenWindowAutomatically = false; private boolean lightTouchEnabled = false; private boolean needInitialFocus = false; private RenderPriority renderPriority = RenderPriority.NORMAL; private boolean pluginsEnabled = false; private boolean saveFormData = false; private boolean supportMultipleWindows = false; private boolean supportZoom = true; private boolean useWideViewPort = false; private int cacheMode; private WebSettings.LayoutAlgorithm layoutAlgorithm = WebSettings.LayoutAlgorithm.NARROW_COLUMNS; private String defaultTextEncoding = "UTF-8"; private int defaultFontSize = 16; private boolean loadsImagesAutomatically; private int defaultFixedFontSize; private int minimumLogicalFontSize; private int minimumFontSize; private String fantasyFontFamily; private String cursiveFontFamily; private String serifFontFamily; private String sansSerifFontFamily; private String fixedFontFamily; private String standardFontFamily; private boolean savePassword; private int userAgent; private boolean navDump; private int forceDark; @Override public synchronized boolean getBlockNetworkImage() { return blockNetworkImage; } @Override public synchronized void setBlockNetworkImage(boolean flag) { blockNetworkImage = flag; } @Override public synchronized boolean getJavaScriptEnabled() { return javaScriptEnabled; } @Override public synchronized void setJavaScriptEnabled(boolean flag) { javaScriptEnabled = flag; } @Override public boolean getLightTouchEnabled() { return lightTouchEnabled; } @Override public void setLightTouchEnabled(boolean flag) { lightTouchEnabled = flag; } public boolean getNeedInitialFocus() { return needInitialFocus; } @Override public void setNeedInitialFocus(boolean flag) { needInitialFocus = flag; } @Override public synchronized void setRenderPriority(RenderPriority priority) { renderPriority = priority; } public RenderPriority getRenderPriority() { return renderPriority; } @Override public synchronized boolean getPluginsEnabled() { return pluginsEnabled; } @Override public synchronized void setPluginsEnabled(boolean flag) { pluginsEnabled = flag; } public boolean getSupportMultipleWindows() { return supportMultipleWindows; } @Override public synchronized void setSupportMultipleWindows(boolean support) { supportMultipleWindows = support; } public boolean getSupportZoom() { return supportZoom; } @Override public void setSupportZoom(boolean support) { supportZoom = support; } @Override public void setCacheMode(int mode) { this.cacheMode = mode; } @Override public int getCacheMode() { return cacheMode; } @Override public boolean getUseWideViewPort() { return useWideViewPort; } @Override public void setUseWideViewPort(boolean useWideViewPort) { this.useWideViewPort = useWideViewPort; } @Override public boolean getSaveFormData() { return saveFormData; } @Override public void setSaveFormData(boolean saveFormData) { this.saveFormData = saveFormData; } @Override public void setJavaScriptCanOpenWindowsAutomatically(boolean javaScriptCanOpenWindowAutomatically) { this.javaScriptCanOpenWindowAutomatically = javaScriptCanOpenWindowAutomatically; } @Override public boolean getJavaScriptCanOpenWindowsAutomatically() { return this.javaScriptCanOpenWindowAutomatically; } @Override public synchronized void setLayoutAlgorithm(WebSettings.LayoutAlgorithm algorithm) { this.layoutAlgorithm = algorithm; } @Override public String getDefaultTextEncodingName() { return this.defaultTextEncoding; } @Override public void setDefaultTextEncodingName(String defaultTextEncoding) { this.defaultTextEncoding = defaultTextEncoding; } @Override public int getDefaultFontSize() { return defaultFontSize; } @Override public void setDefaultFontSize(int defaultFontSize) { this.defaultFontSize = defaultFontSize; } @Override public boolean getLoadsImagesAutomatically() { return loadsImagesAutomatically; } @Override public void setLoadsImagesAutomatically(boolean loadsImagesAutomatically) { this.loadsImagesAutomatically = loadsImagesAutomatically; } @Override public int getDefaultFixedFontSize() { return defaultFixedFontSize; } @Override public void setDefaultFixedFontSize(int defaultFixedFontSize) { this.defaultFixedFontSize = defaultFixedFontSize; } @Override public int getMinimumLogicalFontSize() { return minimumLogicalFontSize; } @Override public void setMinimumLogicalFontSize(int minimumLogicalFontSize) { this.minimumLogicalFontSize = minimumLogicalFontSize; } @Override public int getMinimumFontSize() { return minimumFontSize; } @Override public void setMinimumFontSize(int minimumFontSize) { this.minimumFontSize = minimumFontSize; } @Override public String getFantasyFontFamily() { return fantasyFontFamily; } @Override public void setFantasyFontFamily(String fantasyFontFamily) { this.fantasyFontFamily = fantasyFontFamily; } @Override public String getCursiveFontFamily() { return cursiveFontFamily; } @Override public void setCursiveFontFamily(String cursiveFontFamily) { this.cursiveFontFamily = cursiveFontFamily; } @Override public String getSerifFontFamily() { return serifFontFamily; } @Override public void setSerifFontFamily(String serifFontFamily) { this.serifFontFamily = serifFontFamily; } @Override public String getSansSerifFontFamily() { return sansSerifFontFamily; } @Override public void setSansSerifFontFamily(String sansSerifFontFamily) { this.sansSerifFontFamily = sansSerifFontFamily; } @Override public String getFixedFontFamily() { return fixedFontFamily; } @Override public void setFixedFontFamily(String fixedFontFamily) { this.fixedFontFamily = fixedFontFamily; } @Override public String getStandardFontFamily() { return standardFontFamily; } @Override public void setStandardFontFamily(String standardFontFamily) { this.standardFontFamily = standardFontFamily; } @Override public LayoutAlgorithm getLayoutAlgorithm() { return layoutAlgorithm; } @Override public boolean supportMultipleWindows() { return supportMultipleWindows; } @Override public boolean getSavePassword() { return savePassword; } @Override public void setSavePassword(boolean savePassword) { this.savePassword = savePassword; } @Override public boolean supportZoom() { return supportZoom; } @Override public int getUserAgent() { return userAgent; } @Override public void setUserAgent(int userAgent) { this.userAgent = userAgent; } @Override public boolean getNavDump() { return navDump; } @Override public void setNavDump(boolean navDump) { this.navDump = navDump; } private boolean allowFileAccess = true; private boolean builtInZoomControls = true; private String userAgentString = "Mozilla/5.0 (Linux; U; Android 4.0.3; ko-kr; LG-L160L Build/IML74K) AppleWebkit/534.30" + " (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30"; @Override public boolean getAllowFileAccess() { return allowFileAccess; } @Override public void setAllowFileAccess(boolean allow) { allowFileAccess = allow; } @Override public boolean getBuiltInZoomControls() { return builtInZoomControls; } @Override public void setBuiltInZoomControls(boolean enabled) { builtInZoomControls = enabled; } @Override public synchronized void setUserAgentString(String ua) { userAgentString = ua; } @Override public synchronized String getUserAgentString() { return userAgentString; } // End API 3 private boolean databaseEnabled = false; private String databasePath = "database"; private String geolocationDatabasePath = "geolocation"; private boolean geolocationEnabled = false; @Override public synchronized boolean getDatabaseEnabled() { return databaseEnabled; } @Override public synchronized void setDatabaseEnabled(boolean flag) { databaseEnabled = flag; } @Override public synchronized void setDatabasePath(String path) { databasePath = path; } @Override public synchronized String getDatabasePath() { return databasePath; } public String getGeolocationDatabasePath() { return geolocationDatabasePath; } @Override public void setGeolocationDatabasePath(String geolocationDatabasePath) { this.geolocationDatabasePath = geolocationDatabasePath; } public boolean getGeolocationEnabled() { return geolocationEnabled; } @Override public void setGeolocationEnabled(boolean geolocationEnabled) { this.geolocationEnabled = geolocationEnabled; } // End API 5 private ZoomDensity defaultZoom; private boolean domStorageEnabled = false; private boolean loadWithOverviewMode = false; private boolean appCacheEnabled = false; private long appCacheMaxSize; private String appCachePath = "appcache"; @Override public void setDefaultZoom(ZoomDensity zoom) { this.defaultZoom = zoom; } @Override public ZoomDensity getDefaultZoom() { return defaultZoom; } @Override public synchronized boolean getDomStorageEnabled() { return domStorageEnabled; } @Override public synchronized void setDomStorageEnabled(boolean flag) { domStorageEnabled = flag; } @Override public boolean getLoadWithOverviewMode() { return loadWithOverviewMode; } @Override public void setLoadWithOverviewMode(boolean flag) { loadWithOverviewMode = flag; } public boolean getAppCacheEnabled() { return appCacheEnabled; } @Override public void setAppCacheEnabled(boolean appCacheEnabled) { this.appCacheEnabled = appCacheEnabled; } @Override public void setAppCacheMaxSize(long appCacheMaxSize) { this.appCacheMaxSize = appCacheMaxSize; } public long getAppCacheMaxSize() { return appCacheMaxSize; } public String getAppCachePath() { return appCachePath; } @Override public void setAppCachePath(String appCachePath) { this.appCachePath = appCachePath; } // End API 7 private boolean blockNetworkLoads = false; private WebSettings.PluginState pluginState = WebSettings.PluginState.OFF; @Override public synchronized boolean getBlockNetworkLoads() { return blockNetworkLoads; } @Override public synchronized void setBlockNetworkLoads(boolean flag) { blockNetworkLoads = flag; } @Override public synchronized WebSettings.PluginState getPluginState() { return pluginState; } @Override public synchronized void setPluginState(WebSettings.PluginState state) { pluginState = state; } // End API 8 private boolean useWebViewBackgroundForOverscrollBackground; @Override public boolean getUseWebViewBackgroundForOverscrollBackground() { return useWebViewBackgroundForOverscrollBackground; } @Override public void setUseWebViewBackgroundForOverscrollBackground(boolean useWebViewBackgroundForOverscrollBackground) { this.useWebViewBackgroundForOverscrollBackground = useWebViewBackgroundForOverscrollBackground; } // End API 9 private boolean enableSmoothTransition; private boolean allowContentAccess = true; private boolean displayZoomControls; @Override public boolean enableSmoothTransition() { return enableSmoothTransition; } @Override public void setEnableSmoothTransition(boolean enableSmoothTransition) { this.enableSmoothTransition = enableSmoothTransition; } @Override public void setAllowContentAccess(boolean allow) { allowContentAccess = allow; } @Override public boolean getAllowContentAccess() { return allowContentAccess; } @Override public void setDisplayZoomControls(boolean enabled) { displayZoomControls = enabled; } @Override public boolean getDisplayZoomControls() { return displayZoomControls; } // End API 11 private int textZoom = 100; @Override public int getTextZoom() { return textZoom; } @Override public void setTextZoom(int textZoom) { this.textZoom = textZoom; } // End API 14 private boolean allowFileAccessFromFile = true; private boolean allowUniversalAccessFromFile = true; @Override public boolean getAllowFileAccessFromFileURLs() { return allowFileAccessFromFile; } @Override public void setAllowFileAccessFromFileURLs(boolean allow) { allowFileAccessFromFile = allow; } @Override public boolean getAllowUniversalAccessFromFileURLs() { return allowUniversalAccessFromFile; } @Override public void setAllowUniversalAccessFromFileURLs(boolean allow) { allowUniversalAccessFromFile = allow; } //End API 16 private boolean mediaPlaybackRequiresUserGesture = true; @Override public boolean getMediaPlaybackRequiresUserGesture() { return mediaPlaybackRequiresUserGesture; } @Override public void setMediaPlaybackRequiresUserGesture(boolean require) { mediaPlaybackRequiresUserGesture = require; } //End API 17 private int mixedContentMode; private boolean acceptThirdPartyCookies; private boolean videoOverlayForEmbeddedEncryptedVideoEnabled; @Override public void setMixedContentMode(int mixedContentMode) { this.mixedContentMode = mixedContentMode; } @Override public int getMixedContentMode() { return mixedContentMode; } @Override public void setVideoOverlayForEmbeddedEncryptedVideoEnabled(boolean b) { videoOverlayForEmbeddedEncryptedVideoEnabled = b; } @Override public boolean getVideoOverlayForEmbeddedEncryptedVideoEnabled() { return videoOverlayForEmbeddedEncryptedVideoEnabled; } @Override public boolean getAcceptThirdPartyCookies() { return acceptThirdPartyCookies; } @Override public void setAcceptThirdPartyCookies(boolean acceptThirdPartyCookies) { this.acceptThirdPartyCookies = acceptThirdPartyCookies; } // End API 21 @Override public void setOffscreenPreRaster(boolean enabled) { } @Override public boolean getOffscreenPreRaster() { return false; } // End API 23 @Override public int getDisabledActionModeMenuItems() { return 0; } @Override public void setDisabledActionModeMenuItems(int menuItems) { } // End API 24. @Override public boolean getSafeBrowsingEnabled() { return false; } @Override public void setSafeBrowsingEnabled(boolean enabled) { } // End API 26 @Override public int getForceDark() { return forceDark; } @Override public void setForceDark(int forceDark) { this.forceDark = forceDark; } // End API 29 }
package spelling; import java.util.LinkedList; /** * A class that implements the Dictionary interface using a LinkedList * */ public class DictionaryLL implements Dictionary { private LinkedList<String> dict; private int size; // TODO: Add a constructor public DictionaryLL() { dict = new LinkedList<String>(); size = 0; } /** * Add this word to the dictionary. Convert it to lowercase first for the * assignment requirements. * * @param word * The word to add * @return true if the word was added to the dictionary (it wasn't already * there). */ public boolean addWord(String word) { word = word.toLowerCase(); if (dict.contains(word)) { return false; } else { dict.add(word); size++; return true; } } /** Return the number of words in the dictionary */ public int size() { return size; } /** Is this a word according to this dictionary? */ public boolean isWord(String s) { s = s.toLowerCase(); if (dict.contains(s)) { return true; } else { return false; } } }
package io.home.service; import io.home.model.LogFile; import io.home.model.Profile; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.function.Supplier; public class ProfileRunner implements Supplier<ProfileRunner> { private static final Logger LOG = LoggerFactory.getLogger(ProfileRunner.class); private final Profile profile; private final LogFile logFile; private Process process; public ProfileRunner(Profile profile, LogFile logFile) { this.profile = profile; this.logFile = logFile; } @Override public ProfileRunner get() { LOG.info("run {}", profile.getFile()); LOG.info("arguments: {}", profile.getArguments()); LOG.info("workingPath: {}", profile.getWorkingPath()); LOG.info("environment: {}", profile.getEnvironment()); ProcessBuilder processBuilder = new ProcessBuilder(); List<String> command = new ArrayList<>(); command.add(profile.getFile()); if (profile.getArguments() != null && !profile.getArguments().isEmpty()) { command.addAll(profile.getArguments()); } processBuilder.command(command); if (profile.getWorkingPath() != null) { processBuilder.directory(new File(profile.getWorkingPath())); } if (profile.getEnvironment() != null && !profile.getEnvironment().isEmpty()) { processBuilder.environment().putAll(profile.getEnvironment()); } processBuilder.redirectErrorStream(true); processBuilder.redirectOutput(logFile.getFile()); try { process = processBuilder.start(); process.waitFor(); LOG.info("finish"); } catch (IOException | InterruptedException e) { throw new RuntimeException(e); } return this; } public Profile getProfile() { return profile; } public LogFile getLogFile() { return logFile; } public Process getProcess() { return process; } }
package net.minecraft.client.model; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.passive.EntityOcelot; import net.minecraft.util.MathHelper; public class ModelOcelot extends ModelBase { /** The back left leg model for the Ocelot. */ ModelRenderer ocelotBackLeftLeg; /** The back right leg model for the Ocelot. */ ModelRenderer ocelotBackRightLeg; /** The front left leg model for the Ocelot. */ ModelRenderer ocelotFrontLeftLeg; /** The front right leg model for the Ocelot. */ ModelRenderer ocelotFrontRightLeg; /** The tail model for the Ocelot. */ ModelRenderer ocelotTail; /** The second part of tail model for the Ocelot. */ ModelRenderer ocelotTail2; /** The head model for the Ocelot. */ ModelRenderer ocelotHead; /** The body model for the Ocelot. */ ModelRenderer ocelotBody; int field_78163_i = 1; public ModelOcelot() { this.setTextureOffset("head.main", 0, 0); this.setTextureOffset("head.nose", 0, 24); this.setTextureOffset("head.ear1", 0, 10); this.setTextureOffset("head.ear2", 6, 10); this.ocelotHead = new ModelRenderer(this, "head"); this.ocelotHead.addBox("main", -2.5F, -2.0F, -3.0F, 5, 4, 5); this.ocelotHead.addBox("nose", -1.5F, 0.0F, -4.0F, 3, 2, 2); this.ocelotHead.addBox("ear1", -2.0F, -3.0F, 0.0F, 1, 1, 2); this.ocelotHead.addBox("ear2", 1.0F, -3.0F, 0.0F, 1, 1, 2); this.ocelotHead.setRotationPoint(0.0F, 15.0F, -9.0F); this.ocelotBody = new ModelRenderer(this, 20, 0); this.ocelotBody.addBox(-2.0F, 3.0F, -8.0F, 4, 16, 6, 0.0F); this.ocelotBody.setRotationPoint(0.0F, 12.0F, -10.0F); this.ocelotTail = new ModelRenderer(this, 0, 15); this.ocelotTail.addBox(-0.5F, 0.0F, 0.0F, 1, 8, 1); this.ocelotTail.rotateAngleX = 0.9F; this.ocelotTail.setRotationPoint(0.0F, 15.0F, 8.0F); this.ocelotTail2 = new ModelRenderer(this, 4, 15); this.ocelotTail2.addBox(-0.5F, 0.0F, 0.0F, 1, 8, 1); this.ocelotTail2.setRotationPoint(0.0F, 20.0F, 14.0F); this.ocelotBackLeftLeg = new ModelRenderer(this, 8, 13); this.ocelotBackLeftLeg.addBox(-1.0F, 0.0F, 1.0F, 2, 6, 2); this.ocelotBackLeftLeg.setRotationPoint(1.1F, 18.0F, 5.0F); this.ocelotBackRightLeg = new ModelRenderer(this, 8, 13); this.ocelotBackRightLeg.addBox(-1.0F, 0.0F, 1.0F, 2, 6, 2); this.ocelotBackRightLeg.setRotationPoint(-1.1F, 18.0F, 5.0F); this.ocelotFrontLeftLeg = new ModelRenderer(this, 40, 0); this.ocelotFrontLeftLeg.addBox(-1.0F, 0.0F, 0.0F, 2, 10, 2); this.ocelotFrontLeftLeg.setRotationPoint(1.2F, 13.8F, -5.0F); this.ocelotFrontRightLeg = new ModelRenderer(this, 40, 0); this.ocelotFrontRightLeg.addBox(-1.0F, 0.0F, 0.0F, 2, 10, 2); this.ocelotFrontRightLeg.setRotationPoint(-1.2F, 13.8F, -5.0F); } /** * Sets the models various rotation angles then renders the model. */ public void render(Entity entityIn, float p_78088_2_, float p_78088_3_, float p_78088_4_, float p_78088_5_, float p_78088_6_, float scale) { this.setRotationAngles(p_78088_2_, p_78088_3_, p_78088_4_, p_78088_5_, p_78088_6_, scale, entityIn); if (this.isChild) { float f = 2.0F; GlStateManager.pushMatrix(); GlStateManager.scale(1.5F / f, 1.5F / f, 1.5F / f); GlStateManager.translate(0.0F, 10.0F * scale, 4.0F * scale); this.ocelotHead.render(scale); GlStateManager.popMatrix(); GlStateManager.pushMatrix(); GlStateManager.scale(1.0F / f, 1.0F / f, 1.0F / f); GlStateManager.translate(0.0F, 24.0F * scale, 0.0F); this.ocelotBody.render(scale); this.ocelotBackLeftLeg.render(scale); this.ocelotBackRightLeg.render(scale); this.ocelotFrontLeftLeg.render(scale); this.ocelotFrontRightLeg.render(scale); this.ocelotTail.render(scale); this.ocelotTail2.render(scale); GlStateManager.popMatrix(); } else { this.ocelotHead.render(scale); this.ocelotBody.render(scale); this.ocelotTail.render(scale); this.ocelotTail2.render(scale); this.ocelotBackLeftLeg.render(scale); this.ocelotBackRightLeg.render(scale); this.ocelotFrontLeftLeg.render(scale); this.ocelotFrontRightLeg.render(scale); } } /** * Sets the model's various rotation angles. For bipeds, par1 and par2 are used * for animating the movement of arms and legs, where par1 represents the * time(so that arms and legs swing back and forth) and par2 represents how * "far" arms and legs can swing at most. */ public void setRotationAngles(float p_78087_1_, float p_78087_2_, float p_78087_3_, float p_78087_4_, float p_78087_5_, float p_78087_6_, Entity entityIn) { this.ocelotHead.rotateAngleX = p_78087_5_ / (180F / (float) Math.PI); this.ocelotHead.rotateAngleY = p_78087_4_ / (180F / (float) Math.PI); if (this.field_78163_i != 3) { this.ocelotBody.rotateAngleX = ((float) Math.PI / 2F); if (this.field_78163_i == 2) { this.ocelotBackLeftLeg.rotateAngleX = MathHelper.cos(p_78087_1_ * 0.6662F) * 1.0F * p_78087_2_; this.ocelotBackRightLeg.rotateAngleX = MathHelper.cos(p_78087_1_ * 0.6662F + 0.3F) * 1.0F * p_78087_2_; this.ocelotFrontLeftLeg.rotateAngleX = MathHelper.cos(p_78087_1_ * 0.6662F + (float) Math.PI + 0.3F) * 1.0F * p_78087_2_; this.ocelotFrontRightLeg.rotateAngleX = MathHelper.cos(p_78087_1_ * 0.6662F + (float) Math.PI) * 1.0F * p_78087_2_; this.ocelotTail2.rotateAngleX = 1.7278761F + ((float) Math.PI / 10F) * MathHelper.cos(p_78087_1_) * p_78087_2_; } else { this.ocelotBackLeftLeg.rotateAngleX = MathHelper.cos(p_78087_1_ * 0.6662F) * 1.0F * p_78087_2_; this.ocelotBackRightLeg.rotateAngleX = MathHelper.cos(p_78087_1_ * 0.6662F + (float) Math.PI) * 1.0F * p_78087_2_; this.ocelotFrontLeftLeg.rotateAngleX = MathHelper.cos(p_78087_1_ * 0.6662F + (float) Math.PI) * 1.0F * p_78087_2_; this.ocelotFrontRightLeg.rotateAngleX = MathHelper.cos(p_78087_1_ * 0.6662F) * 1.0F * p_78087_2_; if (this.field_78163_i == 1) { this.ocelotTail2.rotateAngleX = 1.7278761F + ((float) Math.PI / 4F) * MathHelper.cos(p_78087_1_) * p_78087_2_; } else { this.ocelotTail2.rotateAngleX = 1.7278761F + 0.47123894F * MathHelper.cos(p_78087_1_) * p_78087_2_; } } } } /** * Used for easily adding entity-dependent animations. The second and third * float params here are the same second and third as in the setRotationAngles * method. */ public void setLivingAnimations(EntityLivingBase entitylivingbaseIn, float p_78086_2_, float p_78086_3_, float partialTickTime) { EntityOcelot entityocelot = (EntityOcelot) entitylivingbaseIn; this.ocelotBody.rotationPointY = 12.0F; this.ocelotBody.rotationPointZ = -10.0F; this.ocelotHead.rotationPointY = 15.0F; this.ocelotHead.rotationPointZ = -9.0F; this.ocelotTail.rotationPointY = 15.0F; this.ocelotTail.rotationPointZ = 8.0F; this.ocelotTail2.rotationPointY = 20.0F; this.ocelotTail2.rotationPointZ = 14.0F; this.ocelotFrontLeftLeg.rotationPointY = this.ocelotFrontRightLeg.rotationPointY = 13.8F; this.ocelotFrontLeftLeg.rotationPointZ = this.ocelotFrontRightLeg.rotationPointZ = -5.0F; this.ocelotBackLeftLeg.rotationPointY = this.ocelotBackRightLeg.rotationPointY = 18.0F; this.ocelotBackLeftLeg.rotationPointZ = this.ocelotBackRightLeg.rotationPointZ = 5.0F; this.ocelotTail.rotateAngleX = 0.9F; if (entityocelot.isSneaking()) { ++this.ocelotBody.rotationPointY; this.ocelotHead.rotationPointY += 2.0F; ++this.ocelotTail.rotationPointY; this.ocelotTail2.rotationPointY += -4.0F; this.ocelotTail2.rotationPointZ += 2.0F; this.ocelotTail.rotateAngleX = ((float) Math.PI / 2F); this.ocelotTail2.rotateAngleX = ((float) Math.PI / 2F); this.field_78163_i = 0; } else if (entityocelot.isSprinting()) { this.ocelotTail2.rotationPointY = this.ocelotTail.rotationPointY; this.ocelotTail2.rotationPointZ += 2.0F; this.ocelotTail.rotateAngleX = ((float) Math.PI / 2F); this.ocelotTail2.rotateAngleX = ((float) Math.PI / 2F); this.field_78163_i = 2; } else if (entityocelot.isSitting()) { this.ocelotBody.rotateAngleX = ((float) Math.PI / 4F); this.ocelotBody.rotationPointY += -4.0F; this.ocelotBody.rotationPointZ += 5.0F; this.ocelotHead.rotationPointY += -3.3F; ++this.ocelotHead.rotationPointZ; this.ocelotTail.rotationPointY += 8.0F; this.ocelotTail.rotationPointZ += -2.0F; this.ocelotTail2.rotationPointY += 2.0F; this.ocelotTail2.rotationPointZ += -0.8F; this.ocelotTail.rotateAngleX = 1.7278761F; this.ocelotTail2.rotateAngleX = 2.670354F; this.ocelotFrontLeftLeg.rotateAngleX = this.ocelotFrontRightLeg.rotateAngleX = -0.15707964F; this.ocelotFrontLeftLeg.rotationPointY = this.ocelotFrontRightLeg.rotationPointY = 15.8F; this.ocelotFrontLeftLeg.rotationPointZ = this.ocelotFrontRightLeg.rotationPointZ = -7.0F; this.ocelotBackLeftLeg.rotateAngleX = this.ocelotBackRightLeg.rotateAngleX = -((float) Math.PI / 2F); this.ocelotBackLeftLeg.rotationPointY = this.ocelotBackRightLeg.rotationPointY = 21.0F; this.ocelotBackLeftLeg.rotationPointZ = this.ocelotBackRightLeg.rotationPointZ = 1.0F; this.field_78163_i = 3; } else { this.field_78163_i = 1; } } }