hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
10cc9f51e3913cf84a4e1c85c64b36cf2eea7c9d
3,012
/* Copyright (C) 2015-2021 Swift Navigation Inc. * Contact: https://support.swiftnav.com * * This source is subject to the license found in the file 'LICENSE' which must * be be distributed together with this source. All other rights reserved. * * THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, * EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. */ package com.swiftnav.sbp.linux; // This file was auto-generated from yaml/swiftnav/sbp/linux.yaml by generate.py. // Do not modify by hand! import com.swiftnav.sbp.SBPBinaryException; import com.swiftnav.sbp.SBPMessage; import org.json.JSONArray; import org.json.JSONObject; /** * SBP class for message MSG_LINUX_SOCKET_USAGE (0x7F05). * * <p>You can have MSG_LINUX_SOCKET_USAGE inherent its fields directly from an inherited SBP object, * or construct it inline using a dict of its fields. * * <p>Summaries the socket usage across the system. */ public class MsgLinuxSocketUsage extends SBPMessage { public static final int TYPE = 0x7F05; /** average socket queue depths across all sockets on the system */ public long avg_queue_depth; /** the max queue depth seen within the reporting period */ public long max_queue_depth; /** * A count for each socket type reported in the `socket_types_reported` field, the first entry * corresponds to the first enabled bit in `types_reported`. */ public int[] socket_state_counts; /** * A count for each socket type reported in the `socket_types_reported` field, the first entry * corresponds to the first enabled bit in `types_reported`. */ public int[] socket_type_counts; public MsgLinuxSocketUsage(int sender) { super(sender, TYPE); } public MsgLinuxSocketUsage() { super(TYPE); } public MsgLinuxSocketUsage(SBPMessage msg) throws SBPBinaryException { super(msg); assert msg.type == TYPE; } @Override protected void parse(Parser parser) throws SBPBinaryException { /* Parse fields from binary */ avg_queue_depth = parser.getU32(); max_queue_depth = parser.getU32(); socket_state_counts = parser.getArrayofU16(16); socket_type_counts = parser.getArrayofU16(16); } @Override protected void build(Builder builder) { builder.putU32(avg_queue_depth); builder.putU32(max_queue_depth); builder.putArrayofU16(socket_state_counts, 16); builder.putArrayofU16(socket_type_counts, 16); } @Override public JSONObject toJSON() { JSONObject obj = super.toJSON(); obj.put("avg_queue_depth", avg_queue_depth); obj.put("max_queue_depth", max_queue_depth); obj.put("socket_state_counts", new JSONArray(socket_state_counts)); obj.put("socket_type_counts", new JSONArray(socket_type_counts)); return obj; } }
33.098901
100
0.703851
e968f967d073b8c905e10a9b5590040615ad2ea6
1,184
package www.hughwang.me.tcp; import org.apache.mina.core.service.IoHandlerAdapter; import org.apache.mina.core.session.IdleStatus; import org.apache.mina.core.session.IoSession; import org.apache.mina.transport.socket.nio.NioSocketConnector; /** * Created by wanghuan on 2017/8/8. */ public class MinaClientHandler extends IoHandlerAdapter{ @Override public void sessionCreated(IoSession session) throws Exception { super.sessionCreated(session); } @Override public void sessionOpened(IoSession session) throws Exception { super.sessionOpened(session); } @Override public void sessionIdle(IoSession session, IdleStatus status) throws Exception { super.sessionIdle(session, status); } @Override public void sessionClosed(IoSession session) throws Exception { super.sessionClosed(session); } @Override public void messageReceived(IoSession session, Object message) throws Exception { super.messageReceived(session, message); } @Override public void messageSent(IoSession session, Object message) throws Exception { super.messageSent(session, message); } }
27.534884
85
0.727196
1fb3c14b65f4e313126caf5e869dd7ada5e38fc7
3,914
package net.minecraft.server; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import java.util.Map; import javax.annotation.Nullable; public class BlockCoralFanWallAbstract extends BlockCoralFanAbstract { public static final BlockStateDirection a = BlockFacingHorizontal.FACING; private static final Map<EnumDirection, VoxelShape> c = Maps.newEnumMap(ImmutableMap.of(EnumDirection.NORTH, Block.a(0.0D, 4.0D, 5.0D, 16.0D, 12.0D, 16.0D), EnumDirection.SOUTH, Block.a(0.0D, 4.0D, 0.0D, 16.0D, 12.0D, 11.0D), EnumDirection.WEST, Block.a(5.0D, 4.0D, 0.0D, 16.0D, 12.0D, 16.0D), EnumDirection.EAST, Block.a(0.0D, 4.0D, 0.0D, 11.0D, 12.0D, 16.0D))); protected BlockCoralFanWallAbstract(BlockBase.Info blockbase_info) { super(blockbase_info); this.j((IBlockData) ((IBlockData) ((IBlockData) this.blockStateList.getBlockData()).set(BlockCoralFanWallAbstract.a, EnumDirection.NORTH)).set(BlockCoralFanWallAbstract.b, true)); } @Override public VoxelShape b(IBlockData iblockdata, IBlockAccess iblockaccess, BlockPosition blockposition, VoxelShapeCollision voxelshapecollision) { return (VoxelShape) BlockCoralFanWallAbstract.c.get(iblockdata.get(BlockCoralFanWallAbstract.a)); } @Override public IBlockData a(IBlockData iblockdata, EnumBlockRotation enumblockrotation) { return (IBlockData) iblockdata.set(BlockCoralFanWallAbstract.a, enumblockrotation.a((EnumDirection) iblockdata.get(BlockCoralFanWallAbstract.a))); } @Override public IBlockData a(IBlockData iblockdata, EnumBlockMirror enumblockmirror) { return iblockdata.a(enumblockmirror.a((EnumDirection) iblockdata.get(BlockCoralFanWallAbstract.a))); } @Override protected void a(BlockStateList.a<Block, IBlockData> blockstatelist_a) { blockstatelist_a.a(BlockCoralFanWallAbstract.a, BlockCoralFanWallAbstract.b); } @Override public IBlockData updateState(IBlockData iblockdata, EnumDirection enumdirection, IBlockData iblockdata1, GeneratorAccess generatoraccess, BlockPosition blockposition, BlockPosition blockposition1) { if ((Boolean) iblockdata.get(BlockCoralFanWallAbstract.b)) { generatoraccess.getFluidTickList().a(blockposition, FluidTypes.WATER, FluidTypes.WATER.a((IWorldReader) generatoraccess)); } return enumdirection.opposite() == iblockdata.get(BlockCoralFanWallAbstract.a) && !iblockdata.canPlace(generatoraccess, blockposition) ? Blocks.AIR.getBlockData() : iblockdata; } @Override public boolean canPlace(IBlockData iblockdata, IWorldReader iworldreader, BlockPosition blockposition) { EnumDirection enumdirection = (EnumDirection) iblockdata.get(BlockCoralFanWallAbstract.a); BlockPosition blockposition1 = blockposition.shift(enumdirection.opposite()); IBlockData iblockdata1 = iworldreader.getType(blockposition1); return iblockdata1.d(iworldreader, blockposition1, enumdirection); } @Nullable @Override public IBlockData getPlacedState(BlockActionContext blockactioncontext) { IBlockData iblockdata = super.getPlacedState(blockactioncontext); World world = blockactioncontext.getWorld(); BlockPosition blockposition = blockactioncontext.getClickPosition(); EnumDirection[] aenumdirection = blockactioncontext.e(); EnumDirection[] aenumdirection1 = aenumdirection; int i = aenumdirection.length; for (int j = 0; j < i; ++j) { EnumDirection enumdirection = aenumdirection1[j]; if (enumdirection.n().d()) { iblockdata = (IBlockData) iblockdata.set(BlockCoralFanWallAbstract.a, enumdirection.opposite()); if (iblockdata.canPlace(world, blockposition)) { return iblockdata; } } } return null; } }
48.925
367
0.730455
2fbd1a3e7d911a7f1da49725851bc24f3cc5a229
9,249
package ca.corefacility.bioinformatics.irida.ria.unit.web.projects; import java.security.Principal; import java.util.*; import java.util.function.Function; import org.junit.Before; import org.junit.Test; import org.springframework.context.MessageSource; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.ui.ExtendedModelMap; import org.springframework.ui.Model; import ca.corefacility.bioinformatics.irida.model.enums.ProjectRole; import ca.corefacility.bioinformatics.irida.model.joins.Join; import ca.corefacility.bioinformatics.irida.model.joins.impl.ProjectUserJoin; import ca.corefacility.bioinformatics.irida.model.joins.impl.RelatedProjectJoin; import ca.corefacility.bioinformatics.irida.model.project.Project; import ca.corefacility.bioinformatics.irida.model.user.User; import ca.corefacility.bioinformatics.irida.ria.web.cart.CartController; import ca.corefacility.bioinformatics.irida.ria.web.projects.ProjectControllerUtils; import ca.corefacility.bioinformatics.irida.ria.web.projects.ProjectsController; import ca.corefacility.bioinformatics.irida.security.permissions.sample.UpdateSamplePermission; import ca.corefacility.bioinformatics.irida.service.ProjectService; import ca.corefacility.bioinformatics.irida.service.TaxonomyService; import ca.corefacility.bioinformatics.irida.service.sample.SampleService; import ca.corefacility.bioinformatics.irida.service.user.UserService; import ca.corefacility.bioinformatics.irida.util.TreeNode; import com.google.common.collect.Lists; import static org.junit.Assert.*; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.*; /** * Unit test for {@link } */ public class ProjectsControllerTest { public static final String PROJECT_ORGANISM = "E. coli"; private static final String USER_NAME = "testme"; private static final User user = new User(USER_NAME, null, null, null, null, null); private static final String PROJECT_NAME = "test_project"; private static final Long PROJECT_ID = 1L; private static final Long PROJECT_MODIFIED_DATE = 1403723706L; private static Project project = null; // Services private ProjectService projectService; private ProjectsController controller; private SampleService sampleService; private UserService userService; private ProjectControllerUtils projectUtils; private TaxonomyService taxonomyService; private CartController cartController; private UpdateSamplePermission updateSamplePermission; private MessageSource messageSource; @Before public void setUp() { projectService = mock(ProjectService.class); sampleService = mock(SampleService.class); userService = mock(UserService.class); cartController = mock(CartController.class); taxonomyService = mock(TaxonomyService.class); projectUtils = mock(ProjectControllerUtils.class); updateSamplePermission = mock(UpdateSamplePermission.class); messageSource = mock(MessageSource.class); controller = new ProjectsController(projectService, sampleService, userService, projectUtils, taxonomyService, cartController, updateSamplePermission, messageSource); user.setId(1L); mockSidebarInfo(); } @Test public void showAllProjects() { Model model = new ExtendedModelMap(); String page = controller.getProjectsPage(model); assertEquals(ProjectsController.LIST_PROJECTS_PAGE, page); } @Test public void testGetSpecificProjectPage() { Model model = new ExtendedModelMap(); Long projectId = 1L; Principal principal = () -> USER_NAME; List<Join<Project, User>> projects = getProjectsForUser(); when(userService.getUsersForProjectByRole(getProject(), ProjectRole.PROJECT_OWNER)).thenReturn( getUsersForProjectByRole()); when(projectService.getProjectsForUser(user)).thenReturn(projects); when(projectService.getRelatedProjects(getProject())).thenReturn(getRelatedProjectJoin(projects)); assertEquals("Returns the correct Project Page", ProjectsController.SPECIFIC_PROJECT_PAGE, controller.getProjectSpecificPage(projectId, model, principal)); } @Test public void testGetCreateProjectPage() { Model model = new ExtendedModelMap(); String page = controller.getCreateProjectPage(false, model, false); assertEquals("Reruns the correct New Project Page", "projects/project_new", page); assertTrue("Model now has and error attribute", model.containsAttribute("errors")); } @Test public void testCreateNewProject() { Model model = new ExtendedModelMap(); String projectName = "Test Project"; Long projectId = 1002L; Project project = new Project(projectName); project.setId(projectId); // Test creating project when(projectService.create(any(Project.class))).thenReturn(project); when(projectService.update(any(Project.class))).thenReturn(project); String page = controller.createNewProject(model, new Project(projectName), false, false); assertEquals("Returns the correct redirect to the collaborators page", "redirect:/projects/" + projectId + "/settings", page); } @Test public void testSearchTaxonomy() { String searchTerm = "bac"; TreeNode<String> root = new TreeNode<>("Bacteria"); TreeNode<String> child = new TreeNode<>("ChildBacteria"); child.setParent(root); root.addChild(child); List<TreeNode<String>> resultList = new ArrayList<>(); resultList.add(root); // the elements that should be at the root List<String> results = Lists.newArrayList(searchTerm, "Bacteria"); when(taxonomyService.search(searchTerm)).thenReturn(resultList); List<Map<String, Object>> searchTaxonomy = controller.searchTaxonomy(searchTerm); verify(taxonomyService).search(searchTerm); assertFalse(searchTaxonomy.isEmpty()); assertEquals(2, searchTaxonomy.size()); for (Map<String, Object> element : searchTaxonomy) { assertTrue(element.containsKey("text")); assertTrue(element.containsKey("id")); assertTrue(results.contains(element.get("text"))); } } /** * Mocks the information found within the project sidebar. */ private void mockSidebarInfo() { Project project = getProject(); Collection<Join<Project, User>> ownerList = new ArrayList<>(); ownerList.add(new ProjectUserJoin(project, user, ProjectRole.PROJECT_OWNER)); when(userService.getUsersForProjectByRole(any(Project.class), any(ProjectRole.class))).thenReturn(ownerList); when(projectService.read(PROJECT_ID)).thenReturn(project); when(userService.getUserByUsername(anyString())).thenReturn(user); } private List<Join<Project, User>> getProjectsForUser() { List<Join<Project, User>> projects = new ArrayList<>(); for (int i = 0; i < 10; i++) { Project p = new Project("project" + i); p.setId(1L + i); projects.add(new ProjectUserJoin(p, user, ProjectRole.PROJECT_USER)); } return projects; } private List<RelatedProjectJoin> getRelatedProjectJoin(List<Join<Project, User>> projects) { List<RelatedProjectJoin> join = new ArrayList<>(); Project objectProject = getProject(); for (Join<Project, User> j : projects) { Project p = j.getSubject(); join.add(new RelatedProjectJoin(objectProject, p)); } // Add a couple that do not have authorization for (int i = 10; i < 15; i++) { Project p = new Project("project" + i); p.setId(1L + i); join.add(new RelatedProjectJoin(objectProject, p)); } return join; } private Project getProject() { if (project == null) { project = new Project(PROJECT_NAME); project.setId(PROJECT_ID); project.setOrganism(PROJECT_ORGANISM); project.setModifiedDate(new Date(PROJECT_MODIFIED_DATE)); } return project; } private List<Join<Project, User>> getUsersForProjectByRole() { List<Join<Project, User>> list = new ArrayList<>(); list.add(new ProjectUserJoin(getProject(), user, ProjectRole.PROJECT_OWNER)); return list; } public Page<Project> getProjectPage() { return new Page<Project>() { @Override public int getTotalPages() { return 10; } @Override public long getTotalElements() { return 100; } @Override public <U> Page<U> map(Function<? super Project, ? extends U> function) { return null; } @Override public int getNumber() { return 10; } @Override public int getSize() { return 10; } @Override public int getNumberOfElements() { return 100; } @Override public List<Project> getContent() { List<Project> list = new ArrayList<>(); for (int i = 0; i < 10; i++) { list.add(new Project("project-" + i)); } return list; } @Override public boolean hasContent() { return true; } @Override public Sort getSort() { return null; } @Override public boolean isFirst() { return false; } @Override public boolean isLast() { return false; } @Override public boolean hasNext() { return false; } @Override public boolean hasPrevious() { return false; } @Override public Pageable nextPageable() { return null; } @Override public Pageable previousPageable() { return null; } @Override public Iterator<Project> iterator() { return null; } }; } }
31.246622
112
0.746459
0d8f451ff0735b2dce70be9995d13d306c9541dc
1,350
package Bank; import java.util.ArrayList; public class Card { private static ArrayList<Card> allCards = new ArrayList<Card>(); private String cardNo; private String password; private int balance; public Card(String cardNo, String password) { this.cardNo = cardNo; this.password = password; this.balance = 0; addCard(this); } public static synchronized void addCard(Card card) { allCards.add(card); } public static Card getCardByCardNo(String cardNo) { for (Card card : allCards) { if (card.cardNo.equals(cardNo)) return card; } return null; } public synchronized static ArrayList<Card> getAllCards() { return allCards; } public String getPassword() { return password; } public synchronized void decreaseBalance(int amount) { this.balance -= amount; } public synchronized void increaseBalance(int amount) { this.balance += amount; } public void setPassword(String password) { this.password = password; } public String getCardNo() { return cardNo; } public synchronized int getBalance() { return balance; } public static void eraseData() { Card.allCards = new ArrayList<>(); } }
21.774194
68
0.608148
61c921583eaa00a07ddb19138ab8daf16ef44595
5,363
/* * Licensed to David Pilato (the "Author") under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Author 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 fr.pilato.elasticsearch.crawler.fs.settings; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; public class Server { public static final class PROTOCOL { public static final String LOCAL = "local"; public static final String SSH = "ssh"; public static final int SSH_PORT = 22; } public Server() { } private Server(String hostname, int port, String username, String password, String protocol, String pemPath) { this.hostname = hostname; this.port = port; this.username = username; this.password = password; this.protocol = protocol; this.pemPath = pemPath; } private String hostname; private int port = PROTOCOL.SSH_PORT; private String username; @JsonIgnore private String password; private String protocol = PROTOCOL.LOCAL; private String pemPath; public String getHostname() { return hostname; } public void setHostname(String hostname) { this.hostname = hostname; } public int getPort() { return port; } public void setPort(int port) { this.port = port; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } @JsonIgnore public String getPassword() { return password; } @JsonProperty public void setPassword(String password) { this.password = password; } public String getProtocol() { return protocol; } public void setProtocol(String protocol) { this.protocol = protocol; } public String getPemPath() { return pemPath; } public void setPemPath(String pemPath) { this.pemPath = pemPath; } public static Builder builder() { return new Builder(); } public static class Builder { private String hostname = null; private int port = PROTOCOL.SSH_PORT; private String username = null; private String password = null; private String protocol = PROTOCOL.LOCAL; private String pemPath = null; public Builder setHostname(String hostname) { this.hostname = hostname; return this; } public Builder setPort(int port) { this.port = port; return this; } public Builder setUsername(String username) { this.username = username; return this; } public Builder setPassword(String password) { this.password = password; return this; } public Builder setProtocol(String protocol) { this.protocol = protocol; return this; } public Builder setPemPath(String pemPath) { this.pemPath = pemPath; return this; } public Server build() { return new Server(hostname, port, username, password, protocol, pemPath); } } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Server server = (Server) o; if (port != server.port) return false; if (hostname != null ? !hostname.equals(server.hostname) : server.hostname != null) return false; if (username != null ? !username.equals(server.username) : server.username != null) return false; // We can't really test the password as it may be obfuscated if (protocol != null ? !protocol.equals(server.protocol) : server.protocol != null) return false; return !(pemPath != null ? !pemPath.equals(server.pemPath) : server.pemPath != null); } @Override public int hashCode() { int result = hostname != null ? hostname.hashCode() : 0; result = 31 * result + port; result = 31 * result + (username != null ? username.hashCode() : 0); result = 31 * result + (protocol != null ? protocol.hashCode() : 0); result = 31 * result + (pemPath != null ? pemPath.hashCode() : 0); return result; } @Override public String toString() { return "Server{" + "hostname='" + hostname + '\'' + ", port=" + port + ", username='" + username + '\'' + ", protocol='" + protocol + '\'' + ", pemPath='" + pemPath + '\'' + '}'; } }
28.679144
114
0.605818
74b1c4727a3214928ffb668f4deed041d623909a
1,522
/* * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cloud.circuitbreaker.hystrix; import java.util.function.Function; import java.util.function.Supplier; import com.netflix.hystrix.HystrixCommand; import org.springframework.cloud.circuitbreaker.commons.CircuitBreaker; /** * Hystrix implementation of {@link CircuitBreaker}. * * @author Ryan Baxter */ public class HystrixCircuitBreaker implements CircuitBreaker { private HystrixCommand.Setter setter; public HystrixCircuitBreaker(HystrixCommand.Setter setter) { this.setter = setter; } @Override public <T> T run(Supplier<T> toRun, Function<Throwable, T> fallback) { HystrixCommand<T> command = new HystrixCommand<T>(setter) { @Override protected T run() throws Exception { return toRun.get(); } @Override protected T getFallback() { return fallback.apply(getExecutionException()); } }; return command.execute(); } }
26.701754
75
0.743101
2983489813dbf75f73a8b313852d19d788038fc4
12,266
/* * Copyright (c) 2008-2016 Haulmont. * * 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.haulmont.cuba.client.testsupport; import com.haulmont.chile.core.datatypes.DatatypeRegistry; import com.haulmont.chile.core.datatypes.FormatStringsRegistry; import com.haulmont.cuba.client.ClientConfig; import com.haulmont.cuba.core.app.PersistenceManagerService; import com.haulmont.cuba.core.global.*; import com.haulmont.cuba.core.sys.AppContext; import com.haulmont.cuba.core.sys.FormatStringsRegistryImpl; import mockit.Mocked; import mockit.Expectations; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.io.Resource; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.core.io.support.ResourcePatternResolver; import org.springframework.core.type.AnnotationMetadata; import org.springframework.core.type.ClassMetadata; import org.springframework.core.type.classreading.CachingMetadataReaderFactory; import org.springframework.core.type.classreading.MetadataReader; import org.springframework.core.type.classreading.MetadataReaderFactory; import javax.persistence.Entity; import javax.persistence.MappedSuperclass; import java.io.IOException; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * Base class for building client-side integration tests. * */ public class CubaClientTestCase { private Map<String, List<String>> entityPackages = new LinkedHashMap<>(); private String viewConfig; @Mocked protected AppContext appContext; @Mocked protected AppBeans appBeans; @Mocked protected Configuration configuration; @Mocked protected PersistenceManagerService persistenceManager; @Mocked protected GlobalConfig globalConfig; @Mocked protected ClientConfig clientConfig; protected TestMetadataClient metadata; protected TestViewRepositoryClient viewRepository; protected TestUserSessionSource userSessionSource; protected TestUuidSource uuidSource; protected TestSecurity security; protected TestExtendedEntities extendedEntities; protected FormatStringsRegistry formatStringsRegistry; protected TestMessages messages; protected TestMessageTools messageTools; protected TestBeanValidation beanValidation; protected TestEntityStates entityStates; protected ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(); protected MetadataReaderFactory metadataReaderFactory = new CachingMetadataReaderFactory(this.resourcePatternResolver); private Logger log = LoggerFactory.getLogger(CubaClientTestCase.class); static { String property = System.getProperty("logback.configurationFile"); if (StringUtils.isBlank(property)) { System.setProperty("logback.configurationFile", "test-logback.xml"); } } /** * Add entities package to build metadata from. Should be invoked by concrete test classes in their @Before method. * @param packageName package FQN, e.g. <code>com.haulmont.cuba.core.entity</code> */ protected void addEntityPackage(String packageName) { log.debug("Adding entity package: " + packageName); String packagePrefix = packageName.replace(".", "/") + "/**/*.class"; String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + packagePrefix; Resource[] resources; try { resources = resourcePatternResolver.getResources(packageSearchPath); } catch (IOException e) { throw new RuntimeException(e); } entityPackages.put(packageName, getClasses(resources)); } protected List<String> getClasses(Resource[] resources) { List<String> classNames = new ArrayList<>(); for (Resource resource : resources) { if (resource.isReadable()) { MetadataReader metadataReader; try { metadataReader = metadataReaderFactory.getMetadataReader(resource); } catch (IOException e) { throw new RuntimeException("Unable to read metadata resource", e); } AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata(); if (annotationMetadata.isAnnotated(com.haulmont.chile.core.annotations.MetaClass.class.getName()) || annotationMetadata.isAnnotated(MappedSuperclass.class.getName()) || annotationMetadata.isAnnotated(Entity.class.getName())) { ClassMetadata classMetadata = metadataReader.getClassMetadata(); classNames.add(classMetadata.getClassName()); } } } return classNames; } /** * Set path to Views configuration file to build ViewRepository from it. Should be invoked by concrete test classes * once in their @Before method. * @param viewConfigPath configuration resource FQN, e.g. <code>/com/haulmont/cuba/gui/data/impl/testmodel1/test-views.xml</code> */ protected void setViewConfig(String viewConfigPath) { viewConfig = viewConfigPath; } /** * Set up {@link Metadata} and other infrastructure objects before running test. Should be invoked by concrete test classes * once in their @Before method. */ protected void setupInfrastructure() { log.debug("Setting up infrastructure"); new Expectations() { { AppContext.getProperty("cuba.confDir"); result = System.getProperty("user.dir"); minTimes = 0; } }; viewRepository = new TestViewRepositoryClient(viewConfig); metadata = new TestMetadataClient(entityPackages, viewRepository, globalConfig); userSessionSource = new TestUserSessionSource(); uuidSource = new TestUuidSource(); extendedEntities = new TestExtendedEntities(metadata); security = new TestSecurity(userSessionSource, metadata, extendedEntities); formatStringsRegistry = new FormatStringsRegistryImpl(); new Expectations() { { configuration.getConfig(GlobalConfig.class); result = globalConfig; minTimes = 0; configuration.getConfig(ClientConfig.class); result = clientConfig; minTimes = 0; globalConfig.getConfDir(); result = System.getProperty("user.dir"); minTimes = 0; clientConfig.getRemoteMessagesSearchEnabled(); result = false; minTimes = 0; } }; messages = new TestMessages(userSessionSource, configuration, metadata, extendedEntities, formatStringsRegistry); messageTools = (TestMessageTools) messages.getTools(); beanValidation = new TestBeanValidation(); entityStates = new TestEntityStates(); ((TestMetadataTools) metadata.getTools()).setMessages(messages); ((TestMetadataTools) metadata.getTools()).setUserSessionSource(userSessionSource); messages.setConfiguration(configuration); new Expectations() { { AppBeans.get(Metadata.NAME); result = metadata; minTimes = 0; AppBeans.get(Metadata.class); result = metadata; minTimes = 0; AppBeans.get(Metadata.NAME, Metadata.class); result = metadata; minTimes = 0; AppBeans.get(ViewRepository.NAME); result = viewRepository; minTimes = 0; AppBeans.get(ViewRepository.class); result = viewRepository; minTimes = 0; AppBeans.get(ViewRepository.NAME, ViewRepository.class); result = viewRepository; minTimes = 0; AppBeans.get(MetadataTools.NAME); result = metadata.getTools(); minTimes = 0; AppBeans.get(MetadataTools.class); result = metadata.getTools(); minTimes = 0; AppBeans.get(MetadataTools.NAME, MetadataTools.class); result = metadata.getTools(); minTimes = 0; AppBeans.get(DatatypeRegistry.NAME); result = metadata.getDatatypes(); minTimes = 0; AppBeans.get(DatatypeRegistry.class); result = metadata.getDatatypes(); minTimes = 0; AppBeans.get(DatatypeRegistry.NAME, DatatypeRegistry.class); result = metadata.getDatatypes(); minTimes = 0; AppBeans.get(FormatStringsRegistry.NAME); result = formatStringsRegistry; minTimes = 0; AppBeans.get(FormatStringsRegistry.class); result = formatStringsRegistry; minTimes = 0; AppBeans.get(FormatStringsRegistry.NAME, FormatStringsRegistry.class); result = formatStringsRegistry; minTimes = 0; AppBeans.get(Configuration.NAME); result = configuration; minTimes = 0; AppBeans.get(Configuration.class); result = configuration; minTimes = 0; AppBeans.get(Configuration.NAME, Configuration.class); result = configuration; minTimes = 0; AppBeans.get(PersistenceManagerService.NAME); result = persistenceManager; minTimes = 0; AppBeans.get(PersistenceManagerService.class); result = persistenceManager; minTimes = 0; AppBeans.get(PersistenceManagerService.NAME, PersistenceManagerService.class); result = persistenceManager; minTimes = 0; AppBeans.get(UserSessionSource.NAME); result = userSessionSource; minTimes = 0; AppBeans.get(UserSessionSource.class); result = userSessionSource; minTimes = 0; AppBeans.get(UserSessionSource.NAME, UserSessionSource.class); result = userSessionSource; minTimes = 0; AppBeans.get(UuidSource.NAME); result = uuidSource; minTimes = 0; AppBeans.get(UuidSource.class); result = uuidSource; minTimes = 0; AppBeans.get(UuidSource.NAME, UuidSource.class); result = uuidSource; minTimes = 0; AppBeans.get(Security.NAME); result = security; minTimes = 0; AppBeans.get(Security.class); result= security; minTimes = 0; AppBeans.get(Security.NAME, Security.class); result = security; minTimes = 0; AppBeans.get(ExtendedEntities.NAME); result = extendedEntities; minTimes = 0; AppBeans.get(ExtendedEntities.class); result = extendedEntities; minTimes = 0; AppBeans.get(ExtendedEntities.NAME, ExtendedEntities.class); result = extendedEntities; minTimes = 0; AppBeans.get(Messages.NAME); result = messages; minTimes = 0; AppBeans.get(Messages.class); result = messages; minTimes = 0; AppBeans.get(Messages.NAME, Messages.class); result = messages; minTimes = 0; AppBeans.get(MessageTools.NAME); result = messageTools; minTimes = 0; AppBeans.get(MessageTools.class); result = messageTools; minTimes = 0; AppBeans.get(MessageTools.NAME, MessageTools.class); result = messageTools; minTimes = 0; AppBeans.get(BeanValidation.NAME); result = beanValidation; minTimes = 0; AppBeans.get(BeanValidation.class); result = beanValidation; minTimes = 0; AppBeans.get(BeanValidation.NAME, BeanValidation.class); result = beanValidation; minTimes = 0; AppBeans.get(EntityStates.NAME); result = entityStates; minTimes = 0; AppBeans.get(EntityStates.class); result = entityStates; minTimes = 0; AppBeans.get(EntityStates.NAME, BeanValidation.class); result = entityStates; minTimes = 0; } }; metadata.initMetadata(); } }
45.598513
137
0.689304
735e1201fdf08fb9d62503eca2a139534e694dae
1,593
/******************************************************************************* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ package net.adoptopenjdk.bumblebench.math; import java.lang.Math; import java.util.Random; import net.adoptopenjdk.bumblebench.core.MicroBench; public final class SIMDDoubleMaxMinBench extends MicroBench { protected long doBatch(long numIterations) throws InterruptedException { pauseTimer(); Double a, b; Double minRange = 0.0; Double maxRange = 100.0; Double rangeDiff = maxRange - minRange; Random randGen = new Random(); Double min = 0.0; Double max = 0.0; for (long i = 0; i < numIterations; i++) { a=randGen.nextDouble(); b=randGen.nextDouble(); a=(a*rangeDiff)+minRange; b=(b*rangeDiff)+minRange; startTimer(); max = Math.max(a+max,b+max); min = Math.min(a+max,b+max); pauseTimer(); } return numIterations; } }
37.046512
95
0.59887
7a627f91c2d3f16a029a2790a1db79c84dfc7cec
1,525
package com.gemalto.assignment; import android.app.Activity; import android.app.Application; import android.arch.persistence.room.Room; import com.gemalto.assignment.api.GemaltoApi; import com.gemalto.assignment.db.UserDb; import com.gemalto.assignment.di.component.DaggerAssignmentAppComponent; import net.danlew.android.joda.JodaTimeAndroid; import javax.inject.Inject; import dagger.android.AndroidInjector; import dagger.android.DispatchingAndroidInjector; import dagger.android.HasActivityInjector; import io.reactivex.disposables.Disposable; import timber.log.Timber; /** * Created by jacksondeng on 14/12/18. */ public class AssignmentApp extends Application implements HasActivityInjector{ @Inject DispatchingAndroidInjector<Activity> dispatchingAndroidInjector; @Inject GemaltoApi gemaltoApi; @Override public DispatchingAndroidInjector<Activity> activityInjector() { return dispatchingAndroidInjector; } @Override public void onCreate() { super.onCreate(); // Timber if (BuildConfig.DEBUG) { Timber.plant(new Timber.DebugTree()); } // Init JodaTime JodaTimeAndroid.init(this); initDagger(); } public void initDagger(){ // Init dagger DaggerAssignmentAppComponent .builder() .application(this) .build() .inject(this); } public GemaltoApi GegetGemaltoApi(){ return gemaltoApi; } }
23.828125
78
0.69377
657b74eb44919fc37f08f1fad65d82a8090eb622
2,537
package util; import java.sql.SQLException; import java.sql.Statement; import java.util.Enumeration; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import javax.faces.context.FacesContext; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; public class ManagerSession implements HttpSessionListener { @Override public void sessionCreated(HttpSessionEvent ev) { try { HttpSession sessao = ev.getSession(); sessao.setAttribute("cf", new ConnectFilemaker()); sessao.setAttribute("connectionBD", ((ConnectFilemaker) sessao.getAttribute("cf")).getCon().createStatement()); sessao.setAttribute("connectionBD2", ((ConnectFilemaker) sessao.getAttribute("cf")).getCon().createStatement()); } catch (SQLException e) { e.printStackTrace(); } } @Override public void sessionDestroyed(HttpSessionEvent ev) { try { HttpSession sessao = ev.getSession(); ((Statement) sessao.getAttribute("connectionBD")).close(); ((Statement) sessao.getAttribute("connectionBD2")).close(); ((ConnectFilemaker) sessao.getAttribute("cf")).getCon().close(); System.out.println("Sessão: " + sessao.getAttributeNames()); // stmt.close(); // cf.getCon().close(); // System.out.println("Id -> " + sessao.getId()); // Set<Thread> threadSet = Thread.getAllStackTraces().keySet(); // for(Thread t : threadSet) { // System.out.println("Nome Thread - > " + t.getName()); // } if (sessao.getAttribute("timerCloseConnection") != null) { System.out.println("Encerrando threads..."); ((ScheduledFuture<?>) sessao.getAttribute("timerCloseConnection")).cancel(true); ((ScheduledExecutorService) sessao.getAttribute("Executor")).shutdown(); } } catch (SQLException e) { e.printStackTrace(); } System.out.println("A SESSÃO FOI ENCERRADA"); } public void createConnection() { try { HttpSession sessao = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false); sessao.setAttribute("cf", new ConnectFilemaker()); sessao.setAttribute("connectionBD", ((ConnectFilemaker) sessao.getAttribute("cf")).getCon().createStatement()); sessao.setAttribute("connectionBD2", ((ConnectFilemaker) sessao.getAttribute("cf")).getCon().createStatement()); } catch (SQLException e) { e.printStackTrace(); } } }
32.948052
112
0.690579
295445cb48eae7aa4db663beb397e3113bfb73ca
30,444
/******************************************************************************* * 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.olingo.odata2.jpa.processor.core; import java.net.URI; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.olingo.odata2.api.ODataCallback; import org.apache.olingo.odata2.api.commons.HttpStatusCodes; import org.apache.olingo.odata2.api.commons.InlineCount; import org.apache.olingo.odata2.api.edm.EdmEntitySet; import org.apache.olingo.odata2.api.edm.EdmEntityType; import org.apache.olingo.odata2.api.edm.EdmException; import org.apache.olingo.odata2.api.edm.EdmFunctionImport; import org.apache.olingo.odata2.api.edm.EdmLiteralKind; import org.apache.olingo.odata2.api.edm.EdmMultiplicity; import org.apache.olingo.odata2.api.edm.EdmNavigationProperty; import org.apache.olingo.odata2.api.edm.EdmProperty; import org.apache.olingo.odata2.api.edm.EdmSimpleType; import org.apache.olingo.odata2.api.edm.EdmStructuralType; import org.apache.olingo.odata2.api.edm.EdmType; import org.apache.olingo.odata2.api.edm.EdmTypeKind; import org.apache.olingo.odata2.api.ep.EntityProvider; import org.apache.olingo.odata2.api.ep.EntityProviderException; import org.apache.olingo.odata2.api.ep.EntityProviderWriteProperties; import org.apache.olingo.odata2.api.ep.EntityProviderWriteProperties.ODataEntityProviderPropertiesBuilder; import org.apache.olingo.odata2.api.ep.callback.TombstoneCallback; import org.apache.olingo.odata2.api.exception.ODataException; import org.apache.olingo.odata2.api.exception.ODataHttpException; import org.apache.olingo.odata2.api.exception.ODataNotFoundException; import org.apache.olingo.odata2.api.processor.ODataContext; import org.apache.olingo.odata2.api.processor.ODataResponse; import org.apache.olingo.odata2.api.uri.*; import org.apache.olingo.odata2.api.uri.info.DeleteUriInfo; import org.apache.olingo.odata2.api.uri.info.GetEntityLinkUriInfo; import org.apache.olingo.odata2.api.uri.info.GetEntitySetLinksUriInfo; import org.apache.olingo.odata2.api.uri.info.GetEntitySetUriInfo; import org.apache.olingo.odata2.api.uri.info.GetEntityUriInfo; import org.apache.olingo.odata2.api.uri.info.GetFunctionImportUriInfo; import org.apache.olingo.odata2.api.uri.info.PostUriInfo; import org.apache.olingo.odata2.api.uri.info.PutMergePatchUriInfo; import org.apache.olingo.odata2.core.uri.UriInfoImpl; import org.apache.olingo.odata2.jpa.processor.api.ODataJPAContext; import org.apache.olingo.odata2.jpa.processor.api.ODataJPAResponseBuilder; import org.apache.olingo.odata2.jpa.processor.api.ODataJPATombstoneContext; import org.apache.olingo.odata2.jpa.processor.api.access.JPAPaging; import org.apache.olingo.odata2.jpa.processor.api.exception.ODataJPARuntimeException; import org.apache.olingo.odata2.jpa.processor.core.access.data.JPAEntityParser; import org.apache.olingo.odata2.jpa.processor.core.access.data.ReflectionUtil; import org.apache.olingo.odata2.jpa.processor.core.callback.JPAExpandCallBack; import org.apache.olingo.odata2.jpa.processor.core.callback.JPATombstoneCallBack; public final class ODataJPAResponseBuilderDefault implements ODataJPAResponseBuilder { private final ODataJPAContext oDataJPAContext; private long count = -1; public ODataJPAResponseBuilderDefault(final ODataJPAContext context) { oDataJPAContext = context; } public void setCount(long count) { this.count = count; } /* Response for Read Entity Set */ @Override public ODataResponse build(final GetEntitySetUriInfo resultsView, final List<Object> jpaEntities, final String contentType) throws ODataJPARuntimeException { EdmEntityType edmEntityType = null; ODataResponse odataResponse = null; List<ArrayList<NavigationPropertySegment>> expandList = null; try { edmEntityType = resultsView.getTargetEntitySet().getEntityType(); List<Map<String, Object>> edmEntityList = null; JPAEntityParser jpaResultParser = new JPAEntityParser(oDataJPAContext, (UriInfo) resultsView); final List<SelectItem> selectedItems = resultsView.getSelect(); if (selectedItems != null && !selectedItems.isEmpty()) { edmEntityList = jpaResultParser.parse2EdmEntityList((UriInfo) resultsView, jpaEntities, buildSelectItemList(selectedItems, edmEntityType), edmEntityType); } else { edmEntityList = jpaResultParser.parse2EdmEntityList(jpaEntities, edmEntityType); } expandList = resultsView.getExpand(); if (expandList != null && !expandList.isEmpty()) { int count = 0; List<EdmNavigationProperty> edmNavPropertyList = constructListofNavProperty(expandList); for (Object jpaEntity : jpaEntities) { Map<String, Object> relationShipMap = edmEntityList.get(count); HashMap<String, Object> navigationMap = jpaResultParser.parse2EdmNavigationValueMap(jpaEntity, edmNavPropertyList); relationShipMap.putAll(navigationMap); count++; } } EntityProviderWriteProperties feedProperties = null; feedProperties = getEntityProviderProperties(oDataJPAContext, resultsView, edmEntityList, count); odataResponse = EntityProvider.writeFeed(contentType, resultsView.getTargetEntitySet(), edmEntityList, feedProperties); odataResponse = ODataResponse.fromResponse(odataResponse).status(HttpStatusCodes.OK).build(); } catch (EntityProviderException e) { throw ODataJPARuntimeException.throwException(ODataJPARuntimeException.GENERAL.addContent(e.getMessage()), e); } catch (EdmException e) { throw ODataJPARuntimeException.throwException(ODataJPARuntimeException.GENERAL.addContent(e.getMessage()), e); } return odataResponse; } /* Response for Read Entity */ @Override public ODataResponse build(final GetEntityUriInfo resultsView, final Object jpaEntity, final String contentType) throws ODataJPARuntimeException, ODataNotFoundException { List<ArrayList<NavigationPropertySegment>> expandList = null; if (jpaEntity == null) { throw new ODataNotFoundException(ODataNotFoundException.ENTITY); } EdmEntityType edmEntityType = null; ODataResponse odataResponse = null; try { edmEntityType = resultsView.getTargetEntitySet().getEntityType(); Map<String, Object> edmPropertyValueMap = null; JPAEntityParser jpaResultParser = new JPAEntityParser(oDataJPAContext, (UriInfo) resultsView); final List<SelectItem> selectedItems = resultsView.getSelect(); if (selectedItems != null && !selectedItems.isEmpty()) { edmPropertyValueMap = jpaResultParser.parse2EdmPropertyValueMap(jpaEntity, buildSelectItemList(selectedItems, resultsView .getTargetEntitySet().getEntityType()), edmEntityType); } else { edmPropertyValueMap = jpaResultParser.parse2EdmPropertyValueMap(jpaEntity, edmEntityType); } expandList = resultsView.getExpand(); if (expandList != null && !expandList.isEmpty()) { HashMap<String, Object> navigationMap = jpaResultParser.parse2EdmNavigationValueMap(jpaEntity, constructListofNavProperty(expandList)); edmPropertyValueMap.putAll(navigationMap); } EntityProviderWriteProperties feedProperties = null; feedProperties = getEntityProviderProperties(oDataJPAContext, resultsView); if (resultsView.getTargetType() instanceof EdmEntityType) { odataResponse = EntityProvider.writeEntry(contentType, resultsView.getTargetEntitySet(), edmPropertyValueMap, feedProperties); } else { EdmProperty property = ((UriInfoImpl) resultsView).getPropertyPath().get(0); if (((UriInfoImpl) resultsView).isValue()) { odataResponse = EntityProvider.writePropertyValue(property, edmPropertyValueMap.get(property.getName())); } else { odataResponse = EntityProvider.writeProperty(contentType, property, edmPropertyValueMap.get(property.getName())); } } odataResponse = ODataResponse.fromResponse(odataResponse).status(HttpStatusCodes.OK).build(); } catch (EntityProviderException e) { throw ODataJPARuntimeException.throwException(ODataJPARuntimeException.GENERAL.addContent(e.getMessage()), e); } catch (EdmException e) { throw ODataJPARuntimeException.throwException(ODataJPARuntimeException.GENERAL.addContent(e.getMessage()), e); } return odataResponse; } /* Response for $count */ @Override public ODataResponse build(final long jpaEntityCount) throws ODataJPARuntimeException { ODataResponse odataResponse = null; try { odataResponse = EntityProvider.writeText(String.valueOf(jpaEntityCount)); odataResponse = ODataResponse.fromResponse(odataResponse).build(); } catch (EntityProviderException e) { throw ODataJPARuntimeException.throwException(ODataJPARuntimeException.GENERAL.addContent(e.getMessage()), e); } return odataResponse; } /* Response for Create Entity */ @Override public ODataResponse build(final PostUriInfo uriInfo, final Object createdObject, final String contentType) throws ODataJPARuntimeException, ODataNotFoundException { if (createdObject == null) { throw new ODataNotFoundException(ODataNotFoundException.ENTITY); } EdmEntityType edmEntityType = null; ODataResponse odataResponse = null; try { edmEntityType = uriInfo.getTargetEntitySet().getEntityType(); Map<String, Object> edmPropertyValueMap = null; JPAEntityParser jpaResultParser = new JPAEntityParser(oDataJPAContext, (UriInfo) uriInfo); edmPropertyValueMap = jpaResultParser.parse2EdmPropertyValueMap(createdObject, edmEntityType); EntityProviderWriteProperties feedProperties = null; try { feedProperties = getEntityProviderPropertiesforPost(oDataJPAContext); feedProperties.setClientCallbacks(((UriInfo) uriInfo).getClientCallbacks()); } catch (ODataException e) { throw ODataJPARuntimeException.throwException(ODataJPARuntimeException.INNER_EXCEPTION, e); } if (uriInfo.getTargetType() instanceof EdmEntityType) { odataResponse = EntityProvider.writeEntry(contentType, uriInfo.getTargetEntitySet(), edmPropertyValueMap, feedProperties); } else { EdmProperty property = ((UriInfoImpl) uriInfo).getPropertyPath().get(0); if (((UriInfo) uriInfo).isValue()) { odataResponse = EntityProvider.writePropertyValue(property, edmPropertyValueMap.get(property.getName())); } else { odataResponse = EntityProvider.writeProperty(contentType, property, edmPropertyValueMap.get(property.getName())); } } odataResponse = ODataResponse.fromResponse(odataResponse).status(HttpStatusCodes.CREATED).build(); } catch (EntityProviderException e) { throw ODataJPARuntimeException.throwException(ODataJPARuntimeException.GENERAL.addContent(e.getMessage()), e); } catch (EdmException e) { throw ODataJPARuntimeException.throwException(ODataJPARuntimeException.GENERAL.addContent(e.getMessage()), e); } return odataResponse; } /* Response for Update Entity */ @Override public ODataResponse build(final PutMergePatchUriInfo putUriInfo, final Object updatedObject, final String contentType) throws ODataJPARuntimeException, ODataNotFoundException { if (updatedObject == null) { throw new ODataNotFoundException(ODataNotFoundException.ENTITY); } return build((PostUriInfo) putUriInfo, updatedObject, contentType); } /* Response for Delete Entity */ @Override public ODataResponse build(final DeleteUriInfo deleteUriInfo, final Object deletedObject) throws ODataJPARuntimeException, ODataNotFoundException { if (deletedObject == null) { throw new ODataNotFoundException(ODataNotFoundException.ENTITY); } return ODataResponse.status(HttpStatusCodes.NO_CONTENT).build(); } /* Response for Function Import Single Result */ @Override public ODataResponse build(final GetFunctionImportUriInfo resultsView, final Object result) throws ODataJPARuntimeException { try { final EdmFunctionImport functionImport = resultsView.getFunctionImport(); final EdmSimpleType type = (EdmSimpleType) functionImport.getReturnType().getType(); if (result != null) { ODataResponse response = null; if (type.getDefaultType().equals(byte[].class)) { response = EntityProvider.writeBinary("application/octet-stream", (byte[]) result); } else { final String value = type.valueToString(result, EdmLiteralKind.DEFAULT, null); response = EntityProvider.writeText(value); } return ODataResponse.fromResponse(response).build(); } else { throw new ODataNotFoundException(ODataHttpException.COMMON); } } catch (EdmException e) { throw ODataJPARuntimeException.throwException(ODataJPARuntimeException.GENERAL.addContent(e.getMessage()), e); } catch (EntityProviderException e) { throw ODataJPARuntimeException.throwException(ODataJPARuntimeException.GENERAL.addContent(e.getMessage()), e); } catch (ODataException e) { throw ODataJPARuntimeException.throwException(ODataJPARuntimeException.INNER_EXCEPTION, e); } } /* Response for Function Import Multiple Result */ @Override public ODataResponse build(final GetFunctionImportUriInfo resultsView, final List<Object> resultList, final String contentType) throws ODataJPARuntimeException, ODataNotFoundException { ODataResponse odataResponse = null; if (resultList != null) { JPAEntityParser jpaResultParser = new JPAEntityParser(oDataJPAContext, (UriInfo) resultsView); EdmType edmType = null; EdmFunctionImport functionImport = null; Map<String, Object> edmPropertyValueMap = null; List<Map<String, Object>> edmEntityList = null; Object result = null; try { EntityProviderWriteProperties feedProperties = EntityProviderWriteProperties.serviceRoot(oDataJPAContext.getODataContext().getPathInfo().getServiceRoot()) .build(); functionImport = resultsView.getFunctionImport(); edmType = functionImport.getReturnType().getType(); if (edmType.getKind().equals(EdmTypeKind.ENTITY) || edmType.getKind().equals(EdmTypeKind.COMPLEX)) { if (functionImport.getReturnType().getMultiplicity().equals(EdmMultiplicity.MANY)) { edmEntityList = new ArrayList<Map<String, Object>>(); for (Object jpaEntity : resultList) { edmPropertyValueMap = jpaResultParser.parse2EdmPropertyValueMap(jpaEntity, (EdmStructuralType) edmType); edmEntityList.add(edmPropertyValueMap); } result = edmEntityList; } else { Object resultObject = resultList.get(0); edmPropertyValueMap = jpaResultParser.parse2EdmPropertyValueMap(resultObject, (EdmStructuralType) edmType); result = edmPropertyValueMap; } } else if (edmType.getKind().equals(EdmTypeKind.SIMPLE)) { result = resultList.get(0); } odataResponse = EntityProvider.writeFunctionImport(contentType, resultsView.getFunctionImport(), result, feedProperties); odataResponse = ODataResponse.fromResponse(odataResponse).status(HttpStatusCodes.OK).build(); } catch (EdmException e) { throw ODataJPARuntimeException.throwException(ODataJPARuntimeException.GENERAL.addContent(e.getMessage()), e); } catch (EntityProviderException e) { throw ODataJPARuntimeException.throwException(ODataJPARuntimeException.GENERAL.addContent(e.getMessage()), e); } catch (ODataException e) { throw ODataJPARuntimeException.throwException(ODataJPARuntimeException.INNER_EXCEPTION, e); } } else { throw new ODataNotFoundException(ODataHttpException.COMMON); } return odataResponse; } /* Response for Read Entity Link */ @Override public ODataResponse build(final GetEntityLinkUriInfo resultsView, final Object jpaEntity, final String contentType) throws ODataNotFoundException, ODataJPARuntimeException { if (jpaEntity == null) { throw new ODataNotFoundException(ODataNotFoundException.ENTITY); } EdmEntityType edmEntityType = null; ODataResponse odataResponse = null; try { EdmEntitySet entitySet = resultsView.getTargetEntitySet(); edmEntityType = entitySet.getEntityType(); Map<String, Object> edmPropertyValueMap = null; JPAEntityParser jpaResultParser = new JPAEntityParser(oDataJPAContext, (UriInfo) resultsView); edmPropertyValueMap = jpaResultParser.parse2EdmPropertyValueMap(jpaEntity, edmEntityType.getKeyProperties(), edmEntityType); EntityProviderWriteProperties entryProperties = EntityProviderWriteProperties.serviceRoot(oDataJPAContext.getODataContext().getPathInfo().getServiceRoot()) .build(); ODataResponse response = EntityProvider.writeLink(contentType, entitySet, edmPropertyValueMap, entryProperties); odataResponse = ODataResponse.fromResponse(response).build(); } catch (ODataException e) { throw ODataJPARuntimeException.throwException(ODataJPARuntimeException.INNER_EXCEPTION, e); } return odataResponse; } /* Response for Read Entity Links */ @Override public ODataResponse build(final GetEntitySetLinksUriInfo resultsView, final List<Object> jpaEntities, final String contentType) throws ODataJPARuntimeException { EdmEntityType edmEntityType = null; ODataResponse odataResponse = null; try { EdmEntitySet entitySet = resultsView.getTargetEntitySet(); edmEntityType = entitySet.getEntityType(); List<EdmProperty> keyProperties = edmEntityType.getKeyProperties(); List<Map<String, Object>> edmEntityList = new ArrayList<Map<String, Object>>(); Map<String, Object> edmPropertyValueMap = null; JPAEntityParser jpaResultParser = new JPAEntityParser(oDataJPAContext, (UriInfo) resultsView); for (Object jpaEntity : jpaEntities) { edmPropertyValueMap = jpaResultParser.parse2EdmPropertyValueMap(jpaEntity, keyProperties, edmEntityType); edmEntityList.add(edmPropertyValueMap); } Integer count = null; if (resultsView.getInlineCount() != null) { if ((resultsView.getSkip() != null || resultsView.getTop() != null)) { // when $skip and/or $top is present with $inlinecount count = getInlineCountForNonFilterQueryLinks(edmEntityList, resultsView); } else { // In all other cases count = resultsView.getInlineCount() == InlineCount.ALLPAGES ? edmEntityList.size() : null; } } ODataContext context = oDataJPAContext.getODataContext(); EntityProviderWriteProperties entryProperties = EntityProviderWriteProperties.serviceRoot(context.getPathInfo().getServiceRoot()).inlineCountType( resultsView.getInlineCount()) .clientCallbacks(resultsView.getClientCallbacks()).callback(resultsView.getCallback()).inlineCount(count).build(); odataResponse = EntityProvider.writeLinks(contentType, entitySet, edmEntityList, entryProperties); odataResponse = ODataResponse.fromResponse(odataResponse).build(); } catch (ODataException e) { throw ODataJPARuntimeException.throwException(ODataJPARuntimeException.GENERAL.addContent(e.getMessage()), e); } return odataResponse; } /* * This method handles $inlinecount request. It also modifies the list of results in case of * $inlinecount and $top/$skip combinations. Specific to LinksUriInfo. * * @param edmEntityList * * @param resultsView * * @return */ private static Integer getInlineCountForNonFilterQueryLinks(final List<Map<String, Object>> edmEntityList, final GetEntitySetLinksUriInfo resultsView) { // when $skip and/or $top is present with $inlinecount, first get the total count Integer count = null; if (resultsView.getInlineCount() == InlineCount.ALLPAGES) { if (resultsView.getSkip() != null || resultsView.getTop() != null) { count = edmEntityList.size(); // Now update the list if (resultsView.getSkip() != null) { // Index checks to avoid IndexOutOfBoundsException if (resultsView.getSkip() > edmEntityList.size()) { edmEntityList.clear(); return count; } edmEntityList.subList(0, resultsView.getSkip()).clear(); } if (resultsView.getTop() != null && resultsView.getTop() >= 0 && resultsView.getTop() < edmEntityList.size()) { edmEntityList.subList(0, resultsView.getTop()); } } }// Inlinecount of None is handled by default - null return count; } /* * Method to build the entity provider Property.Callbacks for $expand would * be registered here */ private static EntityProviderWriteProperties getEntityProviderProperties(final ODataJPAContext odataJPAContext, final GetEntitySetUriInfo resultsView, final List<Map<String, Object>> edmEntityList, long queryCount) throws ODataJPARuntimeException { ODataEntityProviderPropertiesBuilder entityFeedPropertiesBuilder = null; ODataContext context = odataJPAContext.getODataContext(); Integer count = null; if (queryCount != -1) { count = Integer.valueOf((int)queryCount); } try { PathInfo pathInfo = context.getPathInfo(); URI serviceRoot = pathInfo.getServiceRoot(); entityFeedPropertiesBuilder = EntityProviderWriteProperties.serviceRoot(pathInfo.getServiceRoot()); JPAPaging paging = odataJPAContext.getPaging(); if (odataJPAContext.getPageSize() > 0 && paging != null && paging.getNextPage() > 0) { String nextLink = serviceRoot.relativize(pathInfo.getRequestUri()).toString(); nextLink = percentEncodeNextLink(nextLink); nextLink += (nextLink != null ? nextLink.contains("?") ? "&" : "?" : "?") + "$skiptoken=" + odataJPAContext.getPaging().getNextPage(); entityFeedPropertiesBuilder.nextLink(nextLink); } entityFeedPropertiesBuilder.inlineCount(count); entityFeedPropertiesBuilder.clientCallbacks(resultsView.getClientCallbacks()); entityFeedPropertiesBuilder.callback(resultsView.getCallback()); entityFeedPropertiesBuilder.inlineCountType(resultsView.getInlineCount()); ExpandSelectTreeNode expandSelectTree = UriParser.createExpandSelectTree(resultsView.getSelect(), resultsView.getExpand()); Map<String, ODataCallback> expandCallBack = JPAExpandCallBack.getCallbacks(odataJPAContext, serviceRoot, expandSelectTree, resultsView.getExpand()); Map<String, ODataCallback> callBackMap = new HashMap<String, ODataCallback>(); callBackMap.putAll(expandCallBack); String deltaToken = ODataJPATombstoneContext.getDeltaToken(); if (deltaToken != null) { callBackMap.put(TombstoneCallback.CALLBACK_KEY_TOMBSTONE, new JPATombstoneCallBack(serviceRoot.toString(), resultsView, deltaToken)); } entityFeedPropertiesBuilder.callbacks(callBackMap); entityFeedPropertiesBuilder.expandSelectTree(expandSelectTree); } catch (ODataException e) { throw ODataJPARuntimeException.throwException(ODataJPARuntimeException.INNER_EXCEPTION, e); } return entityFeedPropertiesBuilder.build(); } private static String percentEncodeNextLink(final String link) { if (link == null) { return null; } return link.replaceAll("\\$skiptoken=.+?(?:&|$)", "") .replaceAll("\\$skip=.+?(?:&|$)", "") .replaceFirst("(?:\\?|&)$", ""); // Remove potentially trailing "?" or "&" left over from remove actions } /* * This method handles $inlinecount request. It also modifies the list of results in case of * $inlinecount and $top/$skip combinations. Specific to Entity Set. */ private static Integer getInlineCountForNonFilterQueryEntitySet(final List<Map<String, Object>> edmEntityList, final GetEntitySetUriInfo resultsView) { // when $skip and/or $top is present with $inlinecount, first get the total count Integer count = null; if (resultsView.getInlineCount() == InlineCount.ALLPAGES) { if (resultsView.getSkip() != null || resultsView.getTop() != null) { count = edmEntityList.size(); // Now update the list if (resultsView.getSkip() != null) { // Index checks to avoid IndexOutOfBoundsException if (resultsView.getSkip() > edmEntityList.size()) { edmEntityList.clear(); return count; } edmEntityList.subList(0, resultsView.getSkip()).clear(); } if (resultsView.getTop() != null && resultsView.getTop() >= 0 && resultsView.getTop() < edmEntityList.size()) { final List<Map<String, Object>> edmEntitySubList = new ArrayList<Map<String, Object>>(edmEntityList.subList(0, resultsView.getTop())); edmEntityList.retainAll(edmEntitySubList); } } }// Inlinecount of None is handled by default - null return count; } private static EntityProviderWriteProperties getEntityProviderProperties(final ODataJPAContext odataJPAContext, final GetEntityUriInfo resultsView) throws ODataJPARuntimeException { ODataEntityProviderPropertiesBuilder entityFeedPropertiesBuilder = null; ExpandSelectTreeNode expandSelectTree = null; try { entityFeedPropertiesBuilder = EntityProviderWriteProperties.serviceRoot(odataJPAContext.getODataContext().getPathInfo().getServiceRoot()); expandSelectTree = UriParser.createExpandSelectTree(resultsView.getSelect(), resultsView.getExpand()); entityFeedPropertiesBuilder.expandSelectTree(expandSelectTree); entityFeedPropertiesBuilder.clientCallbacks(resultsView.getClientCallbacks()); entityFeedPropertiesBuilder.callback(resultsView.getCallback()); entityFeedPropertiesBuilder.callbacks(JPAExpandCallBack.getCallbacks(odataJPAContext, odataJPAContext.getODataContext() .getPathInfo().getServiceRoot(), expandSelectTree, resultsView.getExpand())); } catch (ODataException e) { throw ODataJPARuntimeException.throwException(ODataJPARuntimeException.INNER_EXCEPTION, e); } return entityFeedPropertiesBuilder.build(); } private static EntityProviderWriteProperties getEntityProviderPropertiesforPost( final ODataJPAContext odataJPAContext) throws ODataJPARuntimeException { ODataEntityProviderPropertiesBuilder entityFeedPropertiesBuilder = null; try { entityFeedPropertiesBuilder = EntityProviderWriteProperties.serviceRoot(odataJPAContext.getODataContext().getPathInfo().getServiceRoot()); } catch (ODataException e) { throw ODataJPARuntimeException.throwException(ODataJPARuntimeException.INNER_EXCEPTION, e); } return entityFeedPropertiesBuilder.build(); } private static List<EdmProperty> buildSelectItemList(final List<SelectItem> selectItems, final EdmEntityType entity) throws ODataJPARuntimeException { boolean flag = false; List<EdmProperty> selectPropertyList = new ArrayList<EdmProperty>(); try { for (SelectItem selectItem : selectItems) { if (selectItem.getNavigationPropertySegments().size() <= 0) { if (selectItem.isStar()) { selectPropertyList.addAll(getEdmProperties(entity)); return selectPropertyList; } else { selectPropertyList.add(selectItem.getProperty()); } } } for (EdmProperty keyProperty : entity.getKeyProperties()) { flag = true; for (SelectItem selectedItem : selectItems) { if (!selectedItem.isStar() && keyProperty.equals(selectedItem.getProperty())) { flag = false; break; } } if (flag) { selectPropertyList.add(keyProperty); } } } catch (EdmException e) { throw ODataJPARuntimeException.throwException(ODataJPARuntimeException.GENERAL.addContent(e.getMessage()), e); } return selectPropertyList; } private static List<EdmNavigationProperty> constructListofNavProperty( final List<ArrayList<NavigationPropertySegment>> expandList) { List<EdmNavigationProperty> navigationPropertyList = new ArrayList<EdmNavigationProperty>(); for (ArrayList<NavigationPropertySegment> navpropSegment : expandList) { navigationPropertyList.add(navpropSegment.get(0).getNavigationProperty()); } return navigationPropertyList; } private static List<EdmProperty> getEdmProperties(final EdmStructuralType structuralType) throws ODataJPARuntimeException { List<EdmProperty> edmProperties = new ArrayList<EdmProperty>(); try { for (String propertyName : structuralType.getPropertyNames()) { edmProperties.add((EdmProperty) structuralType.getProperty(propertyName)); } } catch (EdmException e) { throw ODataJPARuntimeException.throwException(ODataJPARuntimeException.INNER_EXCEPTION, e); } return edmProperties; } }
43.99422
150
0.72543
b3956ae39057474448693de7498f0a33b70921e1
237
package kpatell.sorting; /** * @author Krishan Patel * Interface for the sorting object to use when updating the UI */ interface ISortPanel { /** * Ask the panel to update the panel with the given array */ void updateArray(); }
19.75
63
0.704641
04489fb9ccedb2b84eff98f1dce40a5303f39e4d
1,492
package seedu.address.model.client; import static java.util.Objects.requireNonNull; import static seedu.address.commons.util.AppUtil.checkArgument; public class RiskAppetite extends NumberComparable<RiskAppetite> implements OptionalStringBasedField { public static final String MESSAGE_CONSTRAINTS = "Risk Appetite number should be a single digit integer between 1 and 5"; public static final String VALIDATION_REGEX = "^([1-5])"; public final String value; /** * Constructs a {@code Risk Appetite}. * * @param riskAppetite A valid risk appetite number. */ public RiskAppetite(String riskAppetite) { requireNonNull(riskAppetite); checkArgument(isValidRiskAppetite(riskAppetite), MESSAGE_CONSTRAINTS); value = riskAppetite; } /** * Returns true if a given string is a valid phone number. */ public static boolean isValidRiskAppetite(String test) { return (IS_BLANK_VALUE_ALLOWED && test.isEmpty()) || test.matches(VALIDATION_REGEX); } @Override public String toString() { return value; } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof RiskAppetite // instanceof handles nulls && value.equals(((RiskAppetite) other).value)); // state check } @Override public int hashCode() { return value.hashCode(); } }
28.692308
102
0.670241
fdaa22c17d8e1621673f5b3596c5a38d4c721613
7,436
package funct.smt; import static utils.MessageTools.concatenate; import static utils.MessageTools.first; import static utils.MessageTools.second; import funct.pkienc.Decryptor; import funct.pkienc.Encryptor; import funct.pkienc.RegisterEnc; import funct.pkisig.RegisterSig; import funct.pkisig.Signer; import funct.pkisig.Verifier; import lib.network.NetworkClient; import lib.network.NetworkError; import lib.network.NetworkServer; import utils.MessageTools; /** * Real functionality for SMT (Secure Authenticated Message Transmission). * See smt.ideal.SMT for typical usage pattern. */ public class SMT { //// The public interface //// @SuppressWarnings("serial") static public class SMTError extends Exception {} @SuppressWarnings("serial") static public class RegistrationError extends Exception {} @SuppressWarnings("serial") static public class ConnectionError extends Exception {} /** * Pair message, sender_id. * * Objects of this class are returned when an agent try to read a message from its queue. */ static public class AuthenticatedMessage { public byte[] message; public int sender_id; private AuthenticatedMessage(byte[] message, int sender) { this.sender_id = sender; this.message = message; } } static public class Sender { public final int id; private final Signer signer; public void sendTo(byte[] message, int receiver_id, String server, int port) throws SMTError, RegistrationError, ConnectionError { if (registrationInProgress) throw new SMTError(); // get the encryptor for the receiver Encryptor recipient_encryptor; try { recipient_encryptor = RegisterEnc.getEncryptor(receiver_id, DOMAIN_SMT_ENCRYPTION); } catch (RegisterEnc.PKIError e) { throw new RegistrationError(); } catch (NetworkError e) { throw new ConnectionError(); } // format the message (sign and encrypt) byte[] recipient_id_as_bytes = MessageTools.intToByteArray(receiver_id); byte[] message_with_recipient_id = concatenate(recipient_id_as_bytes, message); byte[] signature = signer.sign(message_with_recipient_id); byte[] signed = MessageTools.concatenate(signature, message_with_recipient_id); byte[] signedAndEncrypted = recipient_encryptor.encrypt(signed); byte[] sender_id_as_bytes = MessageTools.intToByteArray(id); byte[] outputMessage = MessageTools.concatenate(sender_id_as_bytes, signedAndEncrypted); // send it out try { NetworkClient.send(outputMessage, server, port); } catch (NetworkError e) { throw new ConnectionError(); } } private Sender(int id, Signer signer) { this.id = id; this.signer = signer; } } static public class Receiver { public final int id; private final Decryptor decryptor; public void listenOn(int port) throws ConnectionError { try { NetworkServer.listenForRequests(port); } catch (NetworkError e) { throw new ConnectionError(); } } public AuthenticatedMessage getMessage(int port) throws SMTError { if (registrationInProgress) throw new SMTError(); try { // read a message from the network // (it may end up with a network error) byte[] inputMessage = NetworkServer.read(port); if (inputMessage == null) return null; // get the sender id and her verifier byte[] sender_id_as_bytes = MessageTools.first(inputMessage); int sender_id = MessageTools.byteArrayToInt(sender_id_as_bytes); Verifier sender_verifier = RegisterSig.getVerifier(sender_id, DOMAIN_SMT_VERIFICATION); // retrieve the recipient id and the signature byte[] signedAndEncrypted = MessageTools.second(inputMessage); byte[] signed = decryptor.decrypt(signedAndEncrypted); byte[] signature = MessageTools.first(signed); byte[] message_with_recipient_id = MessageTools.second(signed); // verify the signature if( !sender_verifier.verify(signature, message_with_recipient_id) ) return null; // invalid signature // make sure that the message is intended for this receiver byte[] recipient_id_as_bytes = MessageTools.first(message_with_recipient_id); int recipient_id = MessageTools.byteArrayToInt(recipient_id_as_bytes); if( recipient_id != id ) return null; // message not intended for this receiver byte[] message = MessageTools.second(message_with_recipient_id); return new AuthenticatedMessage(message, sender_id); } catch (NetworkError | RegisterSig.PKIError e) { return null; } } private Receiver(int id, Decryptor decryptor) { this.id = id; this.decryptor = decryptor; } } public static Sender registerSender(int id) throws SMTError, RegistrationError, ConnectionError { if (registrationInProgress) throw new SMTError(); registrationInProgress = true; try { // create and register a new signer Signer signer = new Signer(); RegisterSig.registerVerifier(signer.getVerifier(), id, DOMAIN_SMT_VERIFICATION); // registration successful; return a new Sender object registrationInProgress = false; return new Sender(id, signer); } catch (RegisterSig.PKIError err) { registrationInProgress = false; throw new RegistrationError(); } catch (NetworkError err) { registrationInProgress = false; throw new ConnectionError(); } } public static Receiver registerReceiver(int id) throws SMTError, RegistrationError, ConnectionError { if (registrationInProgress) throw new SMTError(); registrationInProgress = true; try { // create a new decryptor Decryptor decryptor = new Decryptor(); RegisterEnc.registerEncryptor(decryptor.getEncryptor(), id, DOMAIN_SMT_ENCRYPTION); // registration successful; return a new Receiver object registrationInProgress = false; return new Receiver(id, decryptor); } catch (RegisterEnc.PKIError err) { registrationInProgress = false; throw new RegistrationError(); } catch (NetworkError err) { registrationInProgress = false; throw new ConnectionError(); } } //////////////////////////////////////////////////////////////////////////// private static boolean registrationInProgress = false; public static final byte[] DOMAIN_SMT_VERIFICATION = new byte[] {0x02, 0x01}; public static final byte[] DOMAIN_SMT_ENCRYPTION = new byte[] {0x02, 0x02}; /** * Serialization Sender -> Bytes */ public static byte[] senderToBytes(Sender sender) { byte[] id = MessageTools.intToByteArray(sender.id); byte[] signer = sender.signer.toBytes(); byte[] out = concatenate(id, signer); return out; } /** * Serialization Receiver -> Bytes */ public static byte[] receiverToBytes(Receiver receiver) { byte[] id = MessageTools.intToByteArray(receiver.id); byte[] signer = receiver.decryptor.toBytes(); byte[] out = concatenate(id, signer); return out; } /** * Deserialization Sender <- Bytes */ public static Sender senderFromBytes(byte[] bytes) { byte[] bId = first(bytes); int id = MessageTools.byteArrayToInt(bId); byte[] bSigner = second(bytes); Signer signer = Signer.fromBytes(bSigner); return new Sender(id, signer); } /** * Deserialization Receiver <- Bytes */ public static Receiver receiverFromBytes(byte[] bytes) { byte[] bId = first(bytes); int id = MessageTools.byteArrayToInt(bId); byte[] bDecryptor = second(bytes); Decryptor decryptor = Decryptor.fromBytes(bDecryptor); return new Receiver(id, decryptor); } }
30.47541
132
0.723238
d9559c591a2e6f3532ac04db14a2349c5125f0f0
1,079
import java.io.BufferedReader; import java.io.InputStreamReader; class TestClass { public static void main(String args[] ) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line = br.readLine(); int N = Integer.parseInt(line); for (int i = 0; i < N; i++) { String liner = br.readLine(); String line2 = new StringBuilder(liner).reverse().toString(); Boolean flag = check(liner,line2); if(flag) { System.out.println("Funny"); } else { System.out.println("Not Funny"); } } } public static Boolean check(String s1,String s2) { char[] t1 = s1.toCharArray(); char[] t2 = s2.toCharArray(); for(int j=1;j<s1.length();j++) { if(Math.abs(t1[j]-t1[j-1]) != Math.abs(t2[j] - t2[j-1])) { return false; } } return true; } }
25.690476
81
0.486562
acfc59be084cd4cd1a1f20887eda89fa60a03596
718
package fr.xephi.authme.command.executable.authme; import fr.xephi.authme.command.PlayerCommand; import fr.xephi.authme.settings.SpawnLoader; import org.bukkit.entity.Player; import javax.inject.Inject; import java.util.List; /** * Teleports the player to the first spawn. */ public class FirstSpawnCommand extends PlayerCommand { @Inject private SpawnLoader spawnLoader; @Override public void runCommand(Player player, List<String> arguments) { if (spawnLoader.getFirstSpawn() == null) { player.sendMessage("[AuthMe] First spawn has failed, please try to define the first spawn"); } else { player.teleport(spawnLoader.getFirstSpawn()); } } }
26.592593
104
0.706128
8ab7136dbb6f3f5f764c7171b9825dc96d459ee9
507
package com.indiraactive.fulfillmentplatform.utility; import org.springframework.stereotype.Component; import java.io.IOException; /** * Abstract out the runtime for modularity and testability. */ @Component public class RuntimeWrapper { /** * Runs a command on the systems runtime * @return the process that the command was executed in. */ public Process executeCommand(String commandToExec) throws IOException { return Runtime.getRuntime().exec(commandToExec); } }
25.35
76
0.7357
db71a2939ea02e9d6f5f246113941349c0ae4b94
13,894
package com.github.skjolber.desfire.libfreefare; public class Util { //COMMAND CODES public final static byte AUTHENTICATE= (byte) 0x0A;// public final static byte AUTHENTICATE_ISO=(byte)0x1A; public final static byte AUTHENTICATE_AES=(byte)0xAA; public final static byte CHANGE_KEY_SETTINGS=(byte)0x54;// public final static byte SET_CONFIGURATION = (byte) 0x5C; public final static byte CHANGE_KEY= (byte) 0xC4;// public final static byte GET_KEY_VERSION= (byte)0x64; public final static byte CREATE_APPLICATION = (byte) 0xCA;// public final static byte DELETE_APPLICATION = (byte) 0xDA;// public final static byte GET_APPLICATION_IDS= (byte)0x6A;// public final static byte FREE_MEMORY=(byte)0x6E; public final static byte GET_DF_NAMES=(byte)0x6D; public final static byte GET_KEY_SETTINGS=(byte)0x45; public final static byte SELECT_APPLICATION = (byte) 0x5A;// public final static byte FORMAT_PICC=(byte) 0xFC; public final static byte GET_VERSION=(byte)0x60; public final static byte GET_CARD_UID=(byte)0x51; public final static byte GET_FILE_IDS = (byte) 0x6F;// public final static byte GET_FILE_SETTINGS=(byte)0xF5; public final static byte CHANGE_FILE_SETTINGS=(byte)0x5F; public final static byte CREATE_STDDATAFILE = (byte) 0xCD;// public final static byte CREATE_BACKUPDATAFILE = (byte) 0xCB;// public final static byte CREATE_VALUE_FILE=(byte) 0xCC;// public final static byte CREATE_LINEAR_RECORD_FILE=(byte)0xC1;// public final static byte CREATE_CYCLIC_RECORD_FILE=(byte)0xC0;// public final static byte DELETE_FILE=(byte)0xDF;// public final static byte GET_ISO_FILE_IDS=(byte)0x61; public final static byte READ_DATA = (byte) 0x8D;// public final static byte WRITE_DATA = (byte) 0x3D;// public final static byte GET_VALUE=(byte)0x6C;// public final static byte CREDIT=(byte)0x0C;// public final static byte DEBIT=(byte)0xDC;// public final static byte LIMITED_CREDIT=(byte)0x1C; public final static byte WRITE_RECORD=(byte)0x3B;// public final static byte READ_RECORDS=(byte)0xBB;// public final static byte CLEAR_RECORD_FILE=(byte)0xEB;// public final static byte COMMIT_TRANSACTION=(byte)0xC7;// public final static byte ABORT_TRANSACTION=(byte)0xA7;// public final static byte CONTINUE = (byte) 0xAF; //CommandToContinue public final static byte NO_COMMAND_TO_CONTINUE = 0; //Authenticated public final static byte NO_KEY_AUTHENTICATED=-1; /* Status codes */ public static final byte OPERATION_OK = (byte)0x00; public static final byte NO_CHANGES = (byte)0x0C; public static final byte OUT_OF_EEPROM_ERROR = (byte)0x0E; public static final byte ILLEGAL_COMMAND_CODE = (byte)0x1C; public static final byte INTEGRITY_ERROR = (byte)0x1E; public static final byte NO_SUCH_KEY = (byte)0x40; public static final byte LENGTH_ERROR = (byte)0x7E; public static final byte PERMISSION_ERROR = (byte)0x9D; public static final byte PARAMETER_ERROR = (byte)0x9E; public static final byte APPLICATION_NOT_FOUND = (byte)0xA0; public static final byte APPL_INTEGRITY_ERROR = (byte)0xA1; public static final byte AUTHENTICATION_ERROR = (byte)0xAE; public static final byte ADDITIONAL_FRAME = (byte)0xAF; public static final byte BOUNDARY_ERROR = (byte)0xBE; public static final byte PICC_INTEGRITY_ERROR = (byte)0xC1; public static final byte COMMAND_ABORTED = (byte)0xCA; public static final byte PICC_DISABLED_ERROR = (byte)0xCD; public static final byte COUNT_ERROR = (byte)0xCE; public static final byte DUPLICATE_ERROR = (byte)0xDE; public static final byte EEPROM_ERROR = (byte)0xEE; public static final byte FILE_NOT_FOUND = (byte)0xF0; public static final byte FILE_INTEGRITY_ERROR = (byte)0xF1; public final static byte[] masterFileAID = {(byte)0x00,(byte)0x00,(byte)0x00}; //Key types final static byte TDES = (byte) 0x00; final static byte TKTDES = (byte) 0x01; final static byte AES = (byte) 0x02; //File types final static byte STANDARD_DATA_FILE=(byte)0x00; final static byte BACKUP_DATA_FILE=(byte)0X01; final static byte VALUE_FILE=(byte)0x02; final static byte LINEAR_RECORD_FILE=(byte)0x03; final static byte CYCLIC_RECORD_FILE=(byte)0x04; //Transmission modes public final static byte PLAIN_COMMUNICATION=(byte)0x00; public final static byte PLAIN_COMMUNICATION_MAC=(byte)0x01; public final static byte FULLY_ENCRYPTED=(byte)0x02; public final static byte[] DEFAULT_MASTER_KEY={(byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00, (byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00};// 3DES; public final static byte[] RANDOM_A={(byte)0xBB,(byte)0xCC,(byte)0xBB,(byte)0xCC,(byte)0xBB,(byte)0xCC,(byte)0xBB,(byte)0xCC}; public final static byte[] CHECKSUM_IV={(byte) 0x00,(byte) 0x00,(byte) 0x00,(byte) 0x00}; //New Errors public final static short WRONG_VALUE_ERROR=(short)0x916E; //Others public final static byte MAX_DATA_SIZE=100;//MEJORAR ESTE VALOR //FALTA public static byte[] rotateLeft(byte[] c){ byte[] c1=new byte[c.length]; c1[(byte)(c.length-1)]=c[0]; for (byte i = 1; i < c1.length; i++) { c1[(byte)(i-1)]=c[i]; } return c1; } public static byte[] rotateRight(byte[] c){ byte[] c1=new byte[c.length]; c1[0]=c[(byte)(c.length-1)]; for (byte i = 1; i < c1.length; i++) { c1[i]=c[(byte)(i-1)]; } return c1; } public static final byte[] shortToByteArray(final short value) { return new byte[] { (byte) (value >>> 8), (byte) (value) }; } public static final short byteArrayToShort(final byte[] b) { return (short) (((b[0] & 0xFF) << 8) + (b[1] & 0xFF)); } public static final short valueByteArrayToShort(final byte[] b) { return (short) (((b[2] & 0xFF) << 8) + (b[3] & 0xFF)); } public static final byte[] concatByteArray(byte[] a,byte[]b){ byte[] result=new byte[(short)(a.length+b.length)]; for (short i = 0; i < a.length; i++) { result[i]=a[i]; } for (short i = 0; i < b.length; i++) { result[(short)(i+a.length)]=b[i]; } return result; } /** * Makes a new array with a length multiple of 8 padding with 0 * */ public static byte[] preparePaddedByteArray(byte[] a){ if((short)(a.length%8)!=(short)0){ byte[] result=new byte[(short)(a.length+(8-a.length%8))]; for (short i = 0; i < (short)a.length; i++) { result[i]=a[i]; } result[a.length]=(byte)0x80; return result; } else return a; } /** * Copy a byte array over the bytes of another byte array * @param input * @param offsetInput * @param length * @param offsetOutput * @return Output */ public static byte[] copyByteArray( byte[] input, short offsetInput, short length,byte[] output, short offsetOutput){ for (short i = offsetOutput; i < (short)(length+offsetOutput); i++) { output[i]=input[(short)(i+offsetInput-offsetOutput)]; } return output; } public static byte[] create3DESSessionKey(byte[]a,byte[] b){ byte[] result=new byte[16]; result[0]=a[0]; result[1]=a[1]; result[2]=a[2]; result[3]=a[3]; result[4]=b[0]; result[5]=b[1]; result[6]=b[2]; result[7]=b[3]; result[8]=a[4]; result[9]=a[5]; result[10]=a[6]; result[11]=a[7]; result[12]=b[4]; result[13]=b[5]; result[14]=b[6]; result[15]=b[7]; return result; } public static byte[] switchBytes(byte[] a) { byte[] result=new byte[a.length]; for (byte i = 0; i < result.length; i++) { result[i]=a[(byte)(result.length-i-1)]; } return result; } /** * Takes a part of the byte array * * @param input * @param inputInit * Index of the first byte copied to the subarray * @param inputEnd * Index of the last byte copied to the subarray * @return */ public static byte[] subByteArray(byte[]input,short inputInit,short inputEnd){ byte[] result=new byte[(byte)(inputEnd-inputInit+1)]; for (short i = inputInit; i <= inputEnd; i++) { result[(short)(i-inputInit)]=input[i]; } return result; } public static short max(short a, short b) { if(a>b)return a; if(a<b)return b; return a; } public static byte[] crc16(byte[]data){ short crc = 0x0000; short[] table = { (short) 0x0000, (short) 0xC0C1, (short) 0xC181, (short) 0x0140, (short) 0xC301, (short) 0x03C0, (short) 0x0280, (short) 0xC241, (short) 0xC601, (short) 0x06C0, (short) 0x0780, (short) 0xC741, (short) 0x0500, (short) 0xC5C1, (short) 0xC481, (short) 0x0440, (short) 0xCC01, (short) 0x0CC0, (short) 0x0D80, (short) 0xCD41, (short) 0x0F00, (short) 0xCFC1, (short) 0xCE81, (short) 0x0E40, (short) 0x0A00, (short) 0xCAC1, (short) 0xCB81, (short) 0x0B40, (short) 0xC901, (short) 0x09C0, (short) 0x0880, (short) 0xC841, (short) 0xD801, (short) 0x18C0, (short) 0x1980, (short) 0xD941, (short) 0x1B00, (short) 0xDBC1, (short) 0xDA81, (short) 0x1A40, (short) 0x1E00, (short) 0xDEC1, (short) 0xDF81, (short) 0x1F40, (short) 0xDD01, (short) 0x1DC0, (short) 0x1C80, (short) 0xDC41, (short) 0x1400, (short) 0xD4C1, (short) 0xD581, (short) 0x1540, (short) 0xD701, (short) 0x17C0, (short) 0x1680, (short) 0xD641, (short) 0xD201, (short) 0x12C0, (short) 0x1380, (short) 0xD341, (short) 0x1100, (short) 0xD1C1, (short) 0xD081, (short) 0x1040, (short) 0xF001, (short) 0x30C0, (short) 0x3180, (short) 0xF141, (short) 0x3300, (short) 0xF3C1, (short) 0xF281, (short) 0x3240, (short) 0x3600, (short) 0xF6C1, (short) 0xF781, (short) 0x3740, (short) 0xF501, (short) 0x35C0, (short) 0x3480, (short) 0xF441, (short) 0x3C00, (short) 0xFCC1, (short) 0xFD81, (short) 0x3D40, (short) 0xFF01, (short) 0x3FC0, (short) 0x3E80, (short) 0xFE41, (short) 0xFA01, (short) 0x3AC0, (short) 0x3B80, (short) 0xFB41, (short) 0x3900, (short) 0xF9C1, (short) 0xF881, (short) 0x3840, (short) 0x2800, (short) 0xE8C1, (short) 0xE981, (short) 0x2940, (short) 0xEB01, (short) 0x2BC0, (short) 0x2A80, (short) 0xEA41, (short) 0xEE01, (short) 0x2EC0, (short) 0x2F80, (short) 0xEF41, (short) 0x2D00, (short) 0xEDC1, (short) 0xEC81, (short) 0x2C40, (short) 0xE401, (short) 0x24C0, (short) 0x2580, (short) 0xE541, (short) 0x2700, (short) 0xE7C1, (short) 0xE681, (short) 0x2640, (short) 0x2200, (short) 0xE2C1, (short) 0xE381, (short) 0x2340, (short) 0xE101, (short) 0x21C0, (short) 0x2080, (short) 0xE041, (short) 0xA001, (short) 0x60C0, (short) 0x6180, (short) 0xA141, (short) 0x6300, (short) 0xA3C1, (short) 0xA281, (short) 0x6240, (short) 0x6600, (short) 0xA6C1, (short) 0xA781, (short) 0x6740, (short) 0xA501, (short) 0x65C0, (short) 0x6480, (short) 0xA441, (short) 0x6C00, (short) 0xACC1, (short) 0xAD81, (short) 0x6D40, (short) 0xAF01, (short) 0x6FC0, (short) 0x6E80, (short) 0xAE41, (short) 0xAA01, (short) 0x6AC0, (short) 0x6B80, (short) 0xAB41, (short) 0x6900, (short) 0xA9C1, (short) 0xA881, (short) 0x6840, (short) 0x7800, (short) 0xB8C1, (short) 0xB981, (short) 0x7940, (short) 0xBB01, (short) 0x7BC0, (short) 0x7A80, (short) 0xBA41, (short) 0xBE01, (short) 0x7EC0, (short) 0x7F80, (short) 0xBF41, (short) 0x7D00, (short) 0xBDC1, (short) 0xBC81, (short) 0x7C40, (short) 0xB401, (short) 0x74C0, (short) 0x7580, (short) 0xB541, (short) 0x7700, (short) 0xB7C1, (short) 0xB681, (short) 0x7640, (short) 0x7200, (short) 0xB2C1, (short) 0xB381, (short) 0x7340, (short) 0xB101, (short) 0x71C0, (short) 0x7080, (short) 0xB041, (short) 0x5000, (short) 0x90C1, (short) 0x9181, (short) 0x5140, (short) 0x9301, (short) 0x53C0, (short) 0x5280, (short) 0x9241, (short) 0x9601, (short) 0x56C0, (short) 0x5780, (short) 0x9741, (short) 0x5500, (short) 0x95C1, (short) 0x9481, (short) 0x5440, (short) 0x9C01, (short) 0x5CC0, (short) 0x5D80, (short) 0x9D41, (short) 0x5F00, (short) 0x9FC1, (short) 0x9E81, (short) 0x5E40, (short) 0x5A00, (short) 0x9AC1, (short) 0x9B81, (short) 0x5B40, (short) 0x9901, (short) 0x59C0, (short) 0x5880, (short) 0x9841, (short) 0x8801, (short) 0x48C0, (short) 0x4980, (short) 0x8941, (short) 0x4B00, (short) 0x8BC1, (short) 0x8A81, (short) 0x4A40, (short) 0x4E00, (short) 0x8EC1, (short) 0x8F81, (short) 0x4F40, (short) 0x8D01, (short) 0x4DC0, (short) 0x4C80, (short) 0x8C41, (short) 0x4400, (short) 0x84C1, (short) 0x8581, (short) 0x4540, (short) 0x8701, (short) 0x47C0, (short) 0x4680, (short) 0x8641, (short) 0x8201, (short) 0x42C0, (short) 0x4380, (short) 0x8341, (short) 0x4100, (short) 0x81C1, (short) 0x8081, (short) 0x4040, }; for (short i = 0; i < data.length; i++) { crc = (short) ((crc >>> 8) ^ table[(crc ^ data[i]) & (short) 0xff]); } return shortToByteArray(crc); } public static boolean byteArrayCompare(byte[]a,byte[] b){ if(a.length!=b.length)return false; for (byte i = 0; i < a.length; i++) { if(a[i]!=b[i])return false; } return true; } public static byte[] getZeroArray(short length){ byte[] zeroArray=new byte[length]; for (short i = 0; i < zeroArray.length; i++) { zeroArray[i]=0; } return zeroArray; } public static byte[] xorByteArray(byte[]a,byte[]b){ byte[] result=new byte[a.length]; for (byte i = 0; i < a.length; i++) { result[i]=(byte)(a[i]^b[i]); } return result; } }
46.624161
146
0.646826
11baeba4ff772130587bfc921b3fa729f4906e65
20,453
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ package com.microsoft.graph.models.extensions; import com.microsoft.graph.serializer.ISerializer; import com.microsoft.graph.serializer.IJsonBackedObject; import com.microsoft.graph.serializer.AdditionalDataManager; import java.util.EnumSet; import com.microsoft.graph.models.extensions.Account; import com.microsoft.graph.models.extensions.AgedAccountsPayable; import com.microsoft.graph.models.extensions.AgedAccountsReceivable; import com.microsoft.graph.models.extensions.CompanyInformation; import com.microsoft.graph.models.extensions.CountryRegion; import com.microsoft.graph.models.extensions.Currency; import com.microsoft.graph.models.extensions.CustomerPaymentJournal; import com.microsoft.graph.models.extensions.CustomerPayment; import com.microsoft.graph.models.extensions.Customer; import com.microsoft.graph.models.extensions.Dimension; import com.microsoft.graph.models.extensions.DimensionValue; import com.microsoft.graph.models.extensions.Employee; import com.microsoft.graph.models.extensions.GeneralLedgerEntry; import com.microsoft.graph.models.extensions.ItemCategory; import com.microsoft.graph.models.extensions.Item; import com.microsoft.graph.models.extensions.JournalLine; import com.microsoft.graph.models.extensions.Journal; import com.microsoft.graph.models.extensions.PaymentMethod; import com.microsoft.graph.models.extensions.PaymentTerm; import com.microsoft.graph.models.extensions.Picture; import com.microsoft.graph.models.extensions.PurchaseInvoiceLine; import com.microsoft.graph.models.extensions.PurchaseInvoice; import com.microsoft.graph.models.extensions.SalesCreditMemoLine; import com.microsoft.graph.models.extensions.SalesCreditMemo; import com.microsoft.graph.models.extensions.SalesInvoiceLine; import com.microsoft.graph.models.extensions.SalesInvoice; import com.microsoft.graph.models.extensions.SalesOrderLine; import com.microsoft.graph.models.extensions.SalesOrder; import com.microsoft.graph.models.extensions.SalesQuoteLine; import com.microsoft.graph.models.extensions.SalesQuote; import com.microsoft.graph.models.extensions.ShipmentMethod; import com.microsoft.graph.models.extensions.TaxArea; import com.microsoft.graph.models.extensions.TaxGroup; import com.microsoft.graph.models.extensions.UnitOfMeasure; import com.microsoft.graph.models.extensions.Vendor; import com.microsoft.graph.models.extensions.Entity; import com.microsoft.graph.requests.extensions.AccountCollectionPage; import com.microsoft.graph.requests.extensions.AgedAccountsPayableCollectionPage; import com.microsoft.graph.requests.extensions.AgedAccountsReceivableCollectionPage; import com.microsoft.graph.requests.extensions.CompanyInformationCollectionPage; import com.microsoft.graph.requests.extensions.CountryRegionCollectionPage; import com.microsoft.graph.requests.extensions.CurrencyCollectionPage; import com.microsoft.graph.requests.extensions.CustomerPaymentJournalCollectionPage; import com.microsoft.graph.requests.extensions.CustomerPaymentCollectionPage; import com.microsoft.graph.requests.extensions.CustomerCollectionPage; import com.microsoft.graph.requests.extensions.DimensionCollectionPage; import com.microsoft.graph.requests.extensions.DimensionValueCollectionPage; import com.microsoft.graph.requests.extensions.EmployeeCollectionPage; import com.microsoft.graph.requests.extensions.GeneralLedgerEntryCollectionPage; import com.microsoft.graph.requests.extensions.ItemCategoryCollectionPage; import com.microsoft.graph.requests.extensions.ItemCollectionPage; import com.microsoft.graph.requests.extensions.JournalLineCollectionPage; import com.microsoft.graph.requests.extensions.JournalCollectionPage; import com.microsoft.graph.requests.extensions.PaymentMethodCollectionPage; import com.microsoft.graph.requests.extensions.PaymentTermCollectionPage; import com.microsoft.graph.requests.extensions.PictureCollectionPage; import com.microsoft.graph.requests.extensions.PurchaseInvoiceLineCollectionPage; import com.microsoft.graph.requests.extensions.PurchaseInvoiceCollectionPage; import com.microsoft.graph.requests.extensions.SalesCreditMemoLineCollectionPage; import com.microsoft.graph.requests.extensions.SalesCreditMemoCollectionPage; import com.microsoft.graph.requests.extensions.SalesInvoiceLineCollectionPage; import com.microsoft.graph.requests.extensions.SalesInvoiceCollectionPage; import com.microsoft.graph.requests.extensions.SalesOrderLineCollectionPage; import com.microsoft.graph.requests.extensions.SalesOrderCollectionPage; import com.microsoft.graph.requests.extensions.SalesQuoteLineCollectionPage; import com.microsoft.graph.requests.extensions.SalesQuoteCollectionPage; import com.microsoft.graph.requests.extensions.ShipmentMethodCollectionPage; import com.microsoft.graph.requests.extensions.TaxAreaCollectionPage; import com.microsoft.graph.requests.extensions.TaxGroupCollectionPage; import com.microsoft.graph.requests.extensions.UnitOfMeasureCollectionPage; import com.microsoft.graph.requests.extensions.VendorCollectionPage; import com.google.gson.JsonObject; import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.Expose; // **NOTE** This file was generated by a tool and any changes will be overwritten. /** * The class for the Company. */ public class Company extends Entity implements IJsonBackedObject { /** * The Business Profile Id. * */ @SerializedName(value = "businessProfileId", alternate = {"BusinessProfileId"}) @Expose public String businessProfileId; /** * The Display Name. * */ @SerializedName(value = "displayName", alternate = {"DisplayName"}) @Expose public String displayName; /** * The Name. * */ @SerializedName(value = "name", alternate = {"Name"}) @Expose public String name; /** * The System Version. * */ @SerializedName(value = "systemVersion", alternate = {"SystemVersion"}) @Expose public String systemVersion; /** * The Accounts. * */ @SerializedName(value = "accounts", alternate = {"Accounts"}) @Expose public AccountCollectionPage accounts; /** * The Aged Accounts Payable. * */ @SerializedName(value = "agedAccountsPayable", alternate = {"AgedAccountsPayable"}) @Expose public AgedAccountsPayableCollectionPage agedAccountsPayable; /** * The Aged Accounts Receivable. * */ @SerializedName(value = "agedAccountsReceivable", alternate = {"AgedAccountsReceivable"}) @Expose public AgedAccountsReceivableCollectionPage agedAccountsReceivable; /** * The Company Information. * */ @SerializedName(value = "companyInformation", alternate = {"CompanyInformation"}) @Expose public CompanyInformationCollectionPage companyInformation; /** * The Countries Regions. * */ @SerializedName(value = "countriesRegions", alternate = {"CountriesRegions"}) @Expose public CountryRegionCollectionPage countriesRegions; /** * The Currencies. * */ @SerializedName(value = "currencies", alternate = {"Currencies"}) @Expose public CurrencyCollectionPage currencies; /** * The Customer Payment Journals. * */ @SerializedName(value = "customerPaymentJournals", alternate = {"CustomerPaymentJournals"}) @Expose public CustomerPaymentJournalCollectionPage customerPaymentJournals; /** * The Customer Payments. * */ @SerializedName(value = "customerPayments", alternate = {"CustomerPayments"}) @Expose public CustomerPaymentCollectionPage customerPayments; /** * The Customers. * */ @SerializedName(value = "customers", alternate = {"Customers"}) @Expose public CustomerCollectionPage customers; /** * The Dimensions. * */ @SerializedName(value = "dimensions", alternate = {"Dimensions"}) @Expose public DimensionCollectionPage dimensions; /** * The Dimension Values. * */ @SerializedName(value = "dimensionValues", alternate = {"DimensionValues"}) @Expose public DimensionValueCollectionPage dimensionValues; /** * The Employees. * */ @SerializedName(value = "employees", alternate = {"Employees"}) @Expose public EmployeeCollectionPage employees; /** * The General Ledger Entries. * */ @SerializedName(value = "generalLedgerEntries", alternate = {"GeneralLedgerEntries"}) @Expose public GeneralLedgerEntryCollectionPage generalLedgerEntries; /** * The Item Categories. * */ @SerializedName(value = "itemCategories", alternate = {"ItemCategories"}) @Expose public ItemCategoryCollectionPage itemCategories; /** * The Items. * */ @SerializedName(value = "items", alternate = {"Items"}) @Expose public ItemCollectionPage items; /** * The Journal Lines. * */ @SerializedName(value = "journalLines", alternate = {"JournalLines"}) @Expose public JournalLineCollectionPage journalLines; /** * The Journals. * */ @SerializedName(value = "journals", alternate = {"Journals"}) @Expose public JournalCollectionPage journals; /** * The Payment Methods. * */ @SerializedName(value = "paymentMethods", alternate = {"PaymentMethods"}) @Expose public PaymentMethodCollectionPage paymentMethods; /** * The Payment Terms. * */ @SerializedName(value = "paymentTerms", alternate = {"PaymentTerms"}) @Expose public PaymentTermCollectionPage paymentTerms; /** * The Picture. * */ @SerializedName(value = "picture", alternate = {"Picture"}) @Expose public PictureCollectionPage picture; /** * The Purchase Invoice Lines. * */ @SerializedName(value = "purchaseInvoiceLines", alternate = {"PurchaseInvoiceLines"}) @Expose public PurchaseInvoiceLineCollectionPage purchaseInvoiceLines; /** * The Purchase Invoices. * */ @SerializedName(value = "purchaseInvoices", alternate = {"PurchaseInvoices"}) @Expose public PurchaseInvoiceCollectionPage purchaseInvoices; /** * The Sales Credit Memo Lines. * */ @SerializedName(value = "salesCreditMemoLines", alternate = {"SalesCreditMemoLines"}) @Expose public SalesCreditMemoLineCollectionPage salesCreditMemoLines; /** * The Sales Credit Memos. * */ @SerializedName(value = "salesCreditMemos", alternate = {"SalesCreditMemos"}) @Expose public SalesCreditMemoCollectionPage salesCreditMemos; /** * The Sales Invoice Lines. * */ @SerializedName(value = "salesInvoiceLines", alternate = {"SalesInvoiceLines"}) @Expose public SalesInvoiceLineCollectionPage salesInvoiceLines; /** * The Sales Invoices. * */ @SerializedName(value = "salesInvoices", alternate = {"SalesInvoices"}) @Expose public SalesInvoiceCollectionPage salesInvoices; /** * The Sales Order Lines. * */ @SerializedName(value = "salesOrderLines", alternate = {"SalesOrderLines"}) @Expose public SalesOrderLineCollectionPage salesOrderLines; /** * The Sales Orders. * */ @SerializedName(value = "salesOrders", alternate = {"SalesOrders"}) @Expose public SalesOrderCollectionPage salesOrders; /** * The Sales Quote Lines. * */ @SerializedName(value = "salesQuoteLines", alternate = {"SalesQuoteLines"}) @Expose public SalesQuoteLineCollectionPage salesQuoteLines; /** * The Sales Quotes. * */ @SerializedName(value = "salesQuotes", alternate = {"SalesQuotes"}) @Expose public SalesQuoteCollectionPage salesQuotes; /** * The Shipment Methods. * */ @SerializedName(value = "shipmentMethods", alternate = {"ShipmentMethods"}) @Expose public ShipmentMethodCollectionPage shipmentMethods; /** * The Tax Areas. * */ @SerializedName(value = "taxAreas", alternate = {"TaxAreas"}) @Expose public TaxAreaCollectionPage taxAreas; /** * The Tax Groups. * */ @SerializedName(value = "taxGroups", alternate = {"TaxGroups"}) @Expose public TaxGroupCollectionPage taxGroups; /** * The Units Of Measure. * */ @SerializedName(value = "unitsOfMeasure", alternate = {"UnitsOfMeasure"}) @Expose public UnitOfMeasureCollectionPage unitsOfMeasure; /** * The Vendors. * */ @SerializedName(value = "vendors", alternate = {"Vendors"}) @Expose public VendorCollectionPage vendors; /** * The raw representation of this class */ private JsonObject rawObject; /** * The serializer */ private ISerializer serializer; /** * Gets the raw representation of this class * * @return the raw representation of this class */ public JsonObject getRawObject() { return rawObject; } /** * Gets serializer * * @return the serializer */ protected ISerializer getSerializer() { return serializer; } /** * Sets the raw JSON object * * @param serializer the serializer * @param json the JSON object to set this object to */ public void setRawObject(final ISerializer serializer, final JsonObject json) { this.serializer = serializer; rawObject = json; if (json.has("accounts")) { accounts = serializer.deserializeObject(json.get("accounts").toString(), AccountCollectionPage.class); } if (json.has("agedAccountsPayable")) { agedAccountsPayable = serializer.deserializeObject(json.get("agedAccountsPayable").toString(), AgedAccountsPayableCollectionPage.class); } if (json.has("agedAccountsReceivable")) { agedAccountsReceivable = serializer.deserializeObject(json.get("agedAccountsReceivable").toString(), AgedAccountsReceivableCollectionPage.class); } if (json.has("companyInformation")) { companyInformation = serializer.deserializeObject(json.get("companyInformation").toString(), CompanyInformationCollectionPage.class); } if (json.has("countriesRegions")) { countriesRegions = serializer.deserializeObject(json.get("countriesRegions").toString(), CountryRegionCollectionPage.class); } if (json.has("currencies")) { currencies = serializer.deserializeObject(json.get("currencies").toString(), CurrencyCollectionPage.class); } if (json.has("customerPaymentJournals")) { customerPaymentJournals = serializer.deserializeObject(json.get("customerPaymentJournals").toString(), CustomerPaymentJournalCollectionPage.class); } if (json.has("customerPayments")) { customerPayments = serializer.deserializeObject(json.get("customerPayments").toString(), CustomerPaymentCollectionPage.class); } if (json.has("customers")) { customers = serializer.deserializeObject(json.get("customers").toString(), CustomerCollectionPage.class); } if (json.has("dimensions")) { dimensions = serializer.deserializeObject(json.get("dimensions").toString(), DimensionCollectionPage.class); } if (json.has("dimensionValues")) { dimensionValues = serializer.deserializeObject(json.get("dimensionValues").toString(), DimensionValueCollectionPage.class); } if (json.has("employees")) { employees = serializer.deserializeObject(json.get("employees").toString(), EmployeeCollectionPage.class); } if (json.has("generalLedgerEntries")) { generalLedgerEntries = serializer.deserializeObject(json.get("generalLedgerEntries").toString(), GeneralLedgerEntryCollectionPage.class); } if (json.has("itemCategories")) { itemCategories = serializer.deserializeObject(json.get("itemCategories").toString(), ItemCategoryCollectionPage.class); } if (json.has("items")) { items = serializer.deserializeObject(json.get("items").toString(), ItemCollectionPage.class); } if (json.has("journalLines")) { journalLines = serializer.deserializeObject(json.get("journalLines").toString(), JournalLineCollectionPage.class); } if (json.has("journals")) { journals = serializer.deserializeObject(json.get("journals").toString(), JournalCollectionPage.class); } if (json.has("paymentMethods")) { paymentMethods = serializer.deserializeObject(json.get("paymentMethods").toString(), PaymentMethodCollectionPage.class); } if (json.has("paymentTerms")) { paymentTerms = serializer.deserializeObject(json.get("paymentTerms").toString(), PaymentTermCollectionPage.class); } if (json.has("picture")) { picture = serializer.deserializeObject(json.get("picture").toString(), PictureCollectionPage.class); } if (json.has("purchaseInvoiceLines")) { purchaseInvoiceLines = serializer.deserializeObject(json.get("purchaseInvoiceLines").toString(), PurchaseInvoiceLineCollectionPage.class); } if (json.has("purchaseInvoices")) { purchaseInvoices = serializer.deserializeObject(json.get("purchaseInvoices").toString(), PurchaseInvoiceCollectionPage.class); } if (json.has("salesCreditMemoLines")) { salesCreditMemoLines = serializer.deserializeObject(json.get("salesCreditMemoLines").toString(), SalesCreditMemoLineCollectionPage.class); } if (json.has("salesCreditMemos")) { salesCreditMemos = serializer.deserializeObject(json.get("salesCreditMemos").toString(), SalesCreditMemoCollectionPage.class); } if (json.has("salesInvoiceLines")) { salesInvoiceLines = serializer.deserializeObject(json.get("salesInvoiceLines").toString(), SalesInvoiceLineCollectionPage.class); } if (json.has("salesInvoices")) { salesInvoices = serializer.deserializeObject(json.get("salesInvoices").toString(), SalesInvoiceCollectionPage.class); } if (json.has("salesOrderLines")) { salesOrderLines = serializer.deserializeObject(json.get("salesOrderLines").toString(), SalesOrderLineCollectionPage.class); } if (json.has("salesOrders")) { salesOrders = serializer.deserializeObject(json.get("salesOrders").toString(), SalesOrderCollectionPage.class); } if (json.has("salesQuoteLines")) { salesQuoteLines = serializer.deserializeObject(json.get("salesQuoteLines").toString(), SalesQuoteLineCollectionPage.class); } if (json.has("salesQuotes")) { salesQuotes = serializer.deserializeObject(json.get("salesQuotes").toString(), SalesQuoteCollectionPage.class); } if (json.has("shipmentMethods")) { shipmentMethods = serializer.deserializeObject(json.get("shipmentMethods").toString(), ShipmentMethodCollectionPage.class); } if (json.has("taxAreas")) { taxAreas = serializer.deserializeObject(json.get("taxAreas").toString(), TaxAreaCollectionPage.class); } if (json.has("taxGroups")) { taxGroups = serializer.deserializeObject(json.get("taxGroups").toString(), TaxGroupCollectionPage.class); } if (json.has("unitsOfMeasure")) { unitsOfMeasure = serializer.deserializeObject(json.get("unitsOfMeasure").toString(), UnitOfMeasureCollectionPage.class); } if (json.has("vendors")) { vendors = serializer.deserializeObject(json.get("vendors").toString(), VendorCollectionPage.class); } } }
34.784014
159
0.698675
a545981abebbf627b6eec7997a28f1326d5f94ad
2,223
package ee.taltech.cs.mbt.tdl.commons.utils.strings; import ee.taltech.cs.mbt.tdl.commons.utils.collections.CollectionUtils; import java.util.Collection; import java.util.Map; import java.util.Set; import java.util.function.Function; public class StringUtils { public static boolean isEmpty(String str) { return str == null || str.trim().isEmpty(); } public static String stripWhitespace(String str) { return str.replaceAll("\\s", ""); } public static String trimAndNormalizeWS(String str) { return normalizeWhitespace(trim(str)); } public static String trim(String str) { return str .replaceFirst("^[\\s]+", "") .replaceFirst("[\\s]+$", ""); } public static String normalizeWhitespace(String str) { return str.replaceAll("[\\s]+", " "); } public static String defaultString(String str, String defaultStr) { return !isEmpty(str) ? str : defaultStr; } public static String defaultString(String str) { return defaultString(str, ""); } public static boolean containsCharacters(String str, Character... characters) { return !isEmpty(str) && containsCharacters(str, CollectionUtils.arrayToSet(characters)); } public static boolean containsCharacters(String str, Collection<Character> characters) { for (int i = 0; i < str.length(); i++) { if (characters.contains(str.charAt(i))) return true; } return false; } public static String replaceCharacters(String str, Map<Character, String> replacements) { return replaceCharacters(str, replacements.keySet(), replacements::get); } public static String replaceCharacters(String str, Set<Character> chars, Function<Character, String> remappingFunction) { StringBuilder buf = new StringBuilder(); for (int i = 0; i < str.length(); i++) { Character chr = str.charAt(i); if (chars.contains(chr)) { buf.append(remappingFunction.apply(chr)); } else { buf.append(chr); } } return buf.toString(); } public static StringLineIterator lineExtractor(String str) { return StringLineIterator.newInstance(str); } public static boolean equalsIgnoreCase(String a, String b) { return StringUtils.defaultString(a).toLowerCase().equals( StringUtils.defaultString(b).toLowerCase() ); } }
27.7875
122
0.7157
077267feda29c932f88d4f6b2167f7de190c7e0a
3,600
package com.example.android.githubrepolist; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ProgressBar; import android.widget.TextView; import com.example.android.githubrepolist.database.DatabaseAdapter; import com.example.android.githubrepolist.database.DatabaseTableHelper; import java.util.ArrayList; public class RepoActivity extends AppCompatActivity { private RecyclerView mRecyclerView; private RepoAdapter mRepoAdapter; private TextView mErrorMessageDisplay; private ProgressBar mLoadingIndicator; private int page = 1; private String user; private ArrayList<RepoData> lastItemsList =new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); } Intent intent = getIntent(); if(intent!=null){ String owner= intent.getStringExtra("owner"); DatabaseAdapter adapter = new DatabaseAdapter(getApplicationContext()); DatabaseTableHelper table = adapter.getTable(); lastItemsList= table.getAllRepoDataRecord(getApplicationContext(),owner); } mRecyclerView = (RecyclerView) findViewById(R.id.recyclerview_repo); mErrorMessageDisplay = (TextView) findViewById(R.id.tv_error_message_display); FloatingActionButton fab =(FloatingActionButton)findViewById(R.id.fab); fab.setVisibility(View.GONE); final LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false); mRecyclerView.setLayoutManager(layoutManager); mRecyclerView.setHasFixedSize(true); mRepoAdapter = new RepoAdapter(getApplicationContext(),lastItemsList); mRecyclerView.setAdapter(mRepoAdapter); mLoadingIndicator = (ProgressBar) findViewById(R.id.pb_loading_indicator); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. // show menu only when home fragment is selected // if/* (navItemIndex == 0) { /* getMenuInflater().inflate(R.menu.main, menu); } // when fragment is notifications, load the menu created for notifications if (navItemIndex == 3) {*/ //} return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case android.R.id.home: finish(); break; default: return super.onOptionsItemSelected(item); } return true; } /** * Calls showRepoDataView that makes the view visible. * Calls execute on the async task. */ /** * If there's an error, show error message. */ private void showErrorMessage() { mRecyclerView.setVisibility(View.INVISIBLE); mErrorMessageDisplay.setVisibility(View.VISIBLE); } }
27.272727
86
0.685
c533ff08dc5a6767bb55683edce558ab4d078616
4,133
/* ### * IP: GHIDRA * * 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 ghidra.util; import java.math.BigInteger; import java.util.Objects; /** * Helper class to convert a byte array to Java primitives and primitives to a * byte array in Big endian. * * * */ public class BigEndianDataConverter implements DataConverter { public static final BigEndianDataConverter INSTANCE = new BigEndianDataConverter(); private static final long serialVersionUID = 1L; /** * Don't use this constructor to create new instances of this class. Use the static {@link #INSTANCE} instead. */ public BigEndianDataConverter() { // empty } @Override public short getShort(byte[] b, int offset) { Objects.checkFromIndexSize(offset, Short.BYTES, b.length); return (short) (((b[offset] & 0xff) << 8) | (b[offset + 1] & 0xff)); } @Override public int getInt(byte[] b, int offset) { Objects.checkFromIndexSize(offset, Integer.BYTES, b.length); int v = b[offset]; for (int i = 1; i < 4; i++) { v = (v << 8) | (b[offset + i] & 0xff); } return v; } @Override public long getLong(byte[] b, int offset) { Objects.checkFromIndexSize(offset, Long.BYTES, b.length); long v = b[offset]; for (int i = 1; i < 8; i++) { v = (v << 8) | (b[offset + i] & 0xff); } return v; } @Override public long getValue(byte[] b, int offset, int size) { Objects.checkFromIndexSize(offset, size, b.length); Objects.checkIndex(size, Long.BYTES + 1); long val = 0; for (int i = 0; i < size; i++) { val = (val << 8) | (b[offset + i] & 0xff); } return val; } @Override public final BigInteger getBigInteger(byte[] b, int offset, int size, boolean signed) { Objects.checkFromIndexSize(offset, size, b.length); if (offset != 0 || size != b.length) { int index = 0; if (!signed && b[offset] < 0) { // keep unsigned - prepend 0 byte ++size; index = 1; } byte[] bytes = new byte[size]; System.arraycopy(b, offset, bytes, index, size - index); b = bytes; } else if (!signed && b[0] < 0) { // keep unsigned - prepend 0 byte byte[] bytes = new byte[size + 1]; System.arraycopy(b, 0, bytes, 1, size); b = bytes; } return new BigInteger(b); } @Override public void putShort(byte[] b, int offset, short value) { Objects.checkFromIndexSize(offset, Short.BYTES, b.length); b[offset] = (byte) (value >> 8); b[offset + 1] = (byte) (value & 0xff); } @Override public void putInt(byte[] b, int offset, int value) { Objects.checkFromIndexSize(offset, Integer.BYTES, b.length); b[offset + 3] = (byte) (value); for (int i = 2; i >= 0; i--) { value >>= 8; b[offset + i] = (byte) (value); } } @Override public void putValue(long value, int size, byte[] b, int offset) { Objects.checkFromIndexSize(offset, size, b.length); Objects.checkIndex(size, Long.BYTES + 1); for (int i = size - 1; i >= 0; i--) { b[offset + i] = (byte) value; value >>= 8; } } @Override public void putBigInteger(byte[] b, int offset, int size, BigInteger value) { Objects.checkFromIndexSize(offset, size, b.length); int fillIndex = offset; // start fill from MSB int srcIndex; byte[] valBytes = value.toByteArray(); int fillCnt = valBytes.length; if (valBytes.length >= size) { srcIndex = valBytes.length - size; fillCnt = valBytes.length - srcIndex; } else { srcIndex = 0; byte signbits = (value.signum() < 0) ? (byte) 0xff : 0; for (int i = valBytes.length; i < size; i++) { b[fillIndex++] = signbits; } } System.arraycopy(valBytes, srcIndex, b, fillIndex, fillCnt); } }
25.83125
112
0.642632
bb2e9c66e000a0420f01e8c796501ab60178902d
1,924
package com.hyperlink; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.CompoundButton; import android.widget.Toast; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity implements SpannableHyperlinkBuilder.OnTextSpannableClick, CompoundButton.OnCheckedChangeListener { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); AgreementView viewById = findViewById(R.id.agreementView); //设置事件监听 viewById.setOnTextClick(this); viewById.setOnCheckedListener(this); //绑定数据 viewById.setAgreementText(getHyperlinks()); } @NonNull private List<SpannableHyperlinkBuilder.Hyperlink> getHyperlinks() { List<SpannableHyperlinkBuilder.Hyperlink> list = new ArrayList<>(); list.add(new SpannableHyperlinkBuilder.Hyperlink("阅读并同意")); list.add(new SpannableHyperlinkBuilder.Hyperlink("《服务协议书一》", "www.google.com", R.color.colorAccent)); list.add(new SpannableHyperlinkBuilder.Hyperlink("和", R.color.colorPrimary)); list.add(new SpannableHyperlinkBuilder.Hyperlink("《安融告知书及征信授权书》", "www.google.com")); return list; } @Override public void onSpannableClick(View widget, SpannableHyperlinkBuilder.Hyperlink hyperlink) { Toast.makeText(this, "text = " + hyperlink.getHlText() + "\n" + hyperlink.getHlUrl(), Toast.LENGTH_SHORT).show(); } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { Toast.makeText(this, "勾选", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, "取消勾选", Toast.LENGTH_SHORT).show(); } } }
36.301887
151
0.713098
05ae0c28a35bed40a1a601c93a12bb610cea758d
429
package com.louji.vedio; public class VedioList { private VedioInfo first; public VedioList() { this.first = null; } public VedioInfo getFirst() { return this.first; } public void setFirst(VedioInfo first) { this.first = first; } public boolean isEmpty() { return first == null; } public VedioListIterator getIterator() { return new VedioListIterator(this); } }
12.617647
40
0.634033
557d35d8c0dcb70038f36b77015d86b1017e7e1b
915
package com.photo.bas.core.web.convert; import java.text.ParseException; import org.json.JSONArray; import org.json.JSONObject; import org.springframework.core.convert.converter.Converter; import org.springframework.stereotype.Component; import com.photo.bas.core.utils.Strings; /** * @author FengYu * */ @Component("jsonArrayConverter") public class JSONArrayConverter implements Converter<String, JSONArray> { public JSONArray convert(String source) { JSONArray jsonArray = null; if (!Strings.isEmpty(source)) { try { if(source.startsWith("[")){ jsonArray = new JSONArray(source); }else if(source.startsWith("{")){ jsonArray = new JSONArray(); jsonArray.put(new JSONObject(source)); } } catch (ParseException e) { e.printStackTrace(); } } else { jsonArray = new JSONArray(); } return jsonArray; } }
22.875
74
0.668852
006891daad1ad176d12867689070177b40376571
1,576
package com.brsrker.emerald.jwt.auth.security; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.stereotype.Component; import java.util.ArrayList; @Component public class CustomAuthenticationProvider implements AuthenticationProvider { @Autowired private AuthenticationManager authenticationManager; @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String name = authentication.getName(); String password = authentication.getCredentials().toString(); if (shouldAuthenticateAgainstThirdPartySystem()) { // use the credentials // and authenticate against the third-party system return new UsernamePasswordAuthenticationToken( name, password, new ArrayList<>()); } else { return authenticationManager.authenticate( new UsernamePasswordAuthenticationToken(name, password)); } } private boolean shouldAuthenticateAgainstThirdPartySystem() { return false; } @Override public boolean supports(Class<?> aClass) { return false; } }
35.022222
102
0.748731
e51515c47713825c993b4f5ad6121ca897460260
1,609
package io.github.thecreamedcorn; import java.util.HashSet; import java.util.List; public class SqlStatementData implements Cloneable { private String sql; private HashSet<String> parameterSearch; private List<String> parameters; public SqlStatementData(String sql) { this.sql = sql; int colonLoc = sql.indexOf(':'); while (colonLoc > 0) { int i = colonLoc + 1; while (i < sql.length() && (Character.isAlphabetic(sql.charAt(i)) || Character.isDigit(sql.charAt(i)) || sql.charAt(i) == '_')) { i++; } String name = sql.substring(i + 1, colonLoc); if (!name.equals("")) { if (parameterSearch.contains(name)) { throw new AssertionError("two parameters have the same name in the same statement"); } parameterSearch.add(name); parameters.add(name); } colonLoc = sql.indexOf(colonLoc + 1, ':'); } } public String getSql() { return sql; } public List<String> getParameters() { return parameters; } public boolean containsParameter(String paramName) { return parameterSearch.contains(paramName); } public SqlStatementData clone() { try { return (SqlStatementData) super.clone(); } catch (CloneNotSupportedException e) { System.err.println("unable to clone SqlStatementData object"); return null; } } }
28.732143
104
0.548167
9a0cf3cc7cebe0e1c7006ad3580e198660159447
6,861
/******************************************************************************* * Copyright (c) 2000, 2015 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.debug.tests.breakpoints; import java.util.ArrayList; import java.util.List; import org.eclipse.core.runtime.CoreException; import org.eclipse.debug.core.DebugException; import org.eclipse.debug.core.model.IBreakpoint; import org.eclipse.debug.core.model.ILineBreakpoint; import org.eclipse.jdt.core.dom.Message; import org.eclipse.jdt.debug.core.IJavaBreakpoint; import org.eclipse.jdt.debug.core.IJavaBreakpointListener; import org.eclipse.jdt.debug.core.IJavaDebugTarget; import org.eclipse.jdt.debug.core.IJavaLineBreakpoint; import org.eclipse.jdt.debug.core.IJavaTargetPatternBreakpoint; import org.eclipse.jdt.debug.core.IJavaThread; import org.eclipse.jdt.debug.core.IJavaType; import org.eclipse.jdt.debug.tests.AbstractDebugTest; import org.eclipse.jdt.internal.debug.core.JDIDebugPlugin; /** * Tests deferred target pattern breakpoints. */ public class TargetPatternBreakpointTests extends AbstractDebugTest implements IJavaBreakpointListener { /** * Constructor * @param name */ public TargetPatternBreakpointTests(String name) { super(name); } /** * Tests that several pattern breakpoints are suspending properly * @throws Exception */ public void testTargetPatternBreakpoints() throws Exception { JDIDebugPlugin.getDefault().addJavaBreakpointListener(this); String sourceName = "Breakpoints.java"; List<IJavaTargetPatternBreakpoint> bps = new ArrayList<IJavaTargetPatternBreakpoint>(); // anonymous class bps.add(createTargetPatternBreakpoint(43, sourceName)); // blocks bps.add(createTargetPatternBreakpoint(102, sourceName)); // constructor bps.add(createTargetPatternBreakpoint(77, sourceName)); // else bps.add(createTargetPatternBreakpoint(66, sourceName)); //finally after catch bps.add(createTargetPatternBreakpoint(120, sourceName)); //finally after try bps.add(createTargetPatternBreakpoint(128, sourceName)); // for loop bps.add(createTargetPatternBreakpoint(93, sourceName)); // if bps.add(createTargetPatternBreakpoint(81, sourceName)); // initializer bps.add(createTargetPatternBreakpoint(17, sourceName)); // inner class bps.add(createTargetPatternBreakpoint(22, sourceName)); // return true bps.add(createTargetPatternBreakpoint(72, sourceName)); // instance method bps.add(createTargetPatternBreakpoint(107, sourceName)); // static method bps.add(createTargetPatternBreakpoint(53, sourceName)); // case statement bps.add(createTargetPatternBreakpoint(133, sourceName)); // default statement bps.add(createTargetPatternBreakpoint(140, sourceName)); // synchronized blocks bps.add(createTargetPatternBreakpoint(146, sourceName)); // try bps.add(createTargetPatternBreakpoint(125, sourceName)); //catch bps.add(createTargetPatternBreakpoint(118, sourceName)); // while bps.add(createTargetPatternBreakpoint(97, sourceName)); IJavaThread thread = null; try { thread = launchToBreakpoint("Breakpoints", false); assertNotNull("Breakpoint not hit within timeout period", thread); while (!bps.isEmpty()) { IBreakpoint hit = getBreakpoint(thread); assertNotNull("suspended, but not by breakpoint", hit); assertTrue("hit un-registered breakpoint", bps.contains(hit)); assertTrue("suspended, but not by line breakpoint", hit instanceof ILineBreakpoint); ILineBreakpoint breakpoint = (ILineBreakpoint) hit; int lineNumber = breakpoint.getLineNumber(); int stackLine = thread.getTopStackFrame().getLineNumber(); assertEquals("line numbers of breakpoint and stack frame do not match", lineNumber, stackLine); bps.remove(breakpoint); breakpoint.delete(); if (!bps.isEmpty()) { thread = resume(thread); } } } finally { terminateAndRemove(thread); removeAllBreakpoints(); JDIDebugPlugin.getDefault().removeJavaBreakpointListener(this); } } /** * @see IJavaBreakpointListener#addingBreakpoint(IJavaDebugTarget, IJavaBreakpoint) */ @Override public void addingBreakpoint(IJavaDebugTarget target, IJavaBreakpoint breakpoint) { if (breakpoint instanceof IJavaTargetPatternBreakpoint) { IJavaTargetPatternBreakpoint bp = (IJavaTargetPatternBreakpoint) breakpoint; try { bp.setPattern(target, "Breakp"); } catch (CoreException e) { assertTrue("Failed to set pattern", false); } } } /** * @see IJavaBreakpointListener#breakpointHit(IJavaThread, IJavaBreakpoint) */ @Override public int breakpointHit(IJavaThread thread, IJavaBreakpoint breakpoint) { return DONT_CARE; } /** * @see IJavaBreakpointListener#breakpointInstalled(IJavaDebugTarget, IJavaBreakpoint) */ @Override public void breakpointInstalled(IJavaDebugTarget target, IJavaBreakpoint breakpoint) { } /** * @see IJavaBreakpointListener#breakpointRemoved(IJavaDebugTarget, IJavaBreakpoint) */ @Override public void breakpointRemoved(IJavaDebugTarget target, IJavaBreakpoint breakpoint) { } /** * @see IJavaBreakpointListener#installingBreakpoint(IJavaDebugTarget, IJavaBreakpoint, IJavaType) */ @Override public int installingBreakpoint(IJavaDebugTarget target, IJavaBreakpoint breakpoint, IJavaType type) { return DONT_CARE; } /** * @see IJavaBreakpointListener#breakpointHasCompilationErrors(IJavaLineBreakpoint, Message[]) */ @Override public void breakpointHasCompilationErrors(IJavaLineBreakpoint breakpoint, Message[] errors) { } /** * @see IJavaBreakpointListener#breakpointHasRuntimeException(IJavaLineBreakpoint, DebugException) */ @Override public void breakpointHasRuntimeException(IJavaLineBreakpoint breakpoint, DebugException exception) { } }
39.431034
111
0.676286
d322f2d2f3ee168d87cacc92e9a5a428b67f2f00
5,598
/* * Copyright 2018 Tinkoff Bank * 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 ru.tinkoff.eclair.core; import org.aopalliance.aop.Advice; import org.aopalliance.intercept.MethodInterceptor; import org.hamcrest.Matcher; import org.hamcrest.Matchers; import org.junit.Test; import java.io.Serializable; import java.math.BigDecimal; import java.util.*; import static java.util.Arrays.asList; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; /** * @author Vyacheslav Klapatnyuk */ public class RelationResolverTest { @Test public void calculateInheritanceDistanceUnassignable() { // given Class<?> parent = Error.class; Class<?> child = RuntimeException.class; // when int distance = RelationResolver.calculateInheritanceDistance(parent, child); // then assertThat(distance, is(-1)); } @Test(expected = IllegalArgumentException.class) public void calculateInheritanceDistanceAssignableInterfaces() { // given Class<?> parent = Advice.class; Class<?> child = MethodInterceptor.class; // when RelationResolver.calculateInheritanceDistance(parent, child); // then expected exception } @Test public void calculateInheritanceDistanceObjects() { // given Class<?> parent = Object.class; Class<?> child = Object.class; // when int distance = RelationResolver.calculateInheritanceDistance(parent, child); // then assertThat(distance, is(0)); } @Test public void calculateInheritanceDistanceEquals() { // given Class<?> parent = String.class; Class<?> child = String.class; // when int distance = RelationResolver.calculateInheritanceDistance(parent, child); // then assertThat(distance, is(0)); } @Test public void calculateInheritanceDistance() { // given Class<?> parent = Throwable.class; Class<?> child = ArrayIndexOutOfBoundsException.class; // when int distance = RelationResolver.calculateInheritanceDistance(parent, child); // then assertThat(distance, is(4)); } @Test public void calculateInheritanceDistanceReverse() { // given Class<?> parent = ArrayIndexOutOfBoundsException.class; Class<?> child = Throwable.class; // when int distance = RelationResolver.calculateInheritanceDistance(parent, child); // then assertThat(distance, is(-1)); } @Test public void findMostSpecificAncestorEmpty() { // given Set<Class<?>> parents = Collections.emptySet(); Class<?> child = Object.class; // when Class<?> ancestor = RelationResolver.findMostSpecificAncestor(parents, child); // then assertThat(ancestor, nullValue()); } @Test public void findMostSpecificAncestorNotFound() { // given Set<Class<?>> parents = new HashSet<>(asList(String.class, Integer.class, Void.class)); Class<?> child = Double.class; // when Class<?> ancestor = RelationResolver.findMostSpecificAncestor(parents, child); // then assertThat(ancestor, nullValue()); } @Test(expected = IllegalArgumentException.class) public void findMostSpecificAncestorAssignableInterfaces() { // given Set<Class<?>> parents = Collections.singleton(Serializable.class); Class<?> child = Double.class; // when RelationResolver.findMostSpecificAncestor(parents, child); // then expected exception } @Test public void findMostSpecificAncestor() { // given Set<Class<?>> parents = new HashSet<>(asList(String.class, BigDecimal.class, Object.class, Number.class)); Class<?> child = Number.class; // when Class<?> ancestor = RelationResolver.findMostSpecificAncestor(parents, child); // then assertEquals(Number.class, ancestor); } @Test public void reduceDescendantsEmpty() { // given List<Class<?>> classes = Collections.emptyList(); // when Set<Class<?>> set = RelationResolver.reduceDescendants(classes); // then assertThat(set, is(empty())); } @Test public void reduceDescendants() { // given List<Class<?>> classes = asList(Number.class, BigDecimal.class, ArrayList.class, AbstractList.class); // when Set<Class<?>> reduced = RelationResolver.reduceDescendants(classes); // then assertThat(reduced, hasSize(2)); @SuppressWarnings("unchecked") Matcher<Iterable<? extends Class<?>>> matcher = Matchers.containsInAnyOrder(Number.class, AbstractList.class); assertThat(reduced, matcher); } }
32.546512
118
0.65577
dbb0b661cf68632c8ee82ac33b9adb4b23620819
3,475
package resourceModel; import gov.loc.zing.srw.DiagnosticsType; import gov.loc.zing.srw.RecordType; import gov.loc.zing.srw.RecordsType; import gov.loc.zing.srw.SearchRetrieveResponseDocument; import gov.loc.zing.srw.SearchRetrieveResponseType; import gov.loc.zing.srw.diagnostic.DiagnosticType; import java.util.ArrayList; import java.util.List; import org.purl.dc.elements.x11.ElementType; import srw.schema.x1.dcSchema.DcDocument; import srw.schema.x1.dcSchema.SrwDcType; import submissionAppAlmaIntegration.Logger; public class ParseSRWResponse { static Logger log= new Logger(); private List<SRWRecord> resultsObjects = new ArrayList<SRWRecord>(); int numberOfRecords = 0; int recordsRetrived = 0; public ParseSRWResponse(String input) throws EREException { parse(input); } private void parse(String in)throws EREException { try { SearchRetrieveResponseDocument retriveDoc = SearchRetrieveResponseDocument.Factory.parse(in); SearchRetrieveResponseType rootDoc = retriveDoc.getSearchRetrieveResponse(); numberOfRecords = rootDoc.getNumberOfRecords().intValue(); DiagnosticsType diagnostics = rootDoc.getDiagnostics(); String message = ""; if ( diagnostics != null ){ DiagnosticType[] diagnosticArray = diagnostics.getDiagnosticArray(); for (int d= 0; d < diagnosticArray.length; d++){ DiagnosticType dtype = diagnosticArray[d]; message += dtype.getMessage() + " - " + dtype.getDetails(); } } if (numberOfRecords > 0 ){ RecordsType records = rootDoc.getRecords(); RecordType [] recordsArray = records.getRecordArray(); for ( int i=0; i < recordsArray.length; i++){ RecordType record = recordsArray[i]; if (record.getRecordData()==null) { log.error("Failed to parse record #"+ (i+1) +" - record.getRecordData()==null"); continue; } SRWRecord srwrecord = new SRWRecord(); String xml = record.getRecordData().toString(); srwrecord.setData(xml); DcDocument dcDoc = DcDocument.Factory.parse(xml); SrwDcType srwdc = dcDoc.getDc(); setIdentifierData(srwrecord, srwdc.getIdentifierArray()); resultsObjects.add(srwrecord); } } else if (message.length() > 0){ throw new EREException(message); } else { throw new EREException("This term is unable to fetch a record. Please redefine search term."); } } catch (Exception xmlex){ throw new EREException(xmlex.getMessage()); } } public int getNumberOfRecords() { return numberOfRecords; } public void setNumberOfRecords(int numberOfRecords) { this.numberOfRecords = numberOfRecords; } public int getRecordsRetrived() { return recordsRetrived; } public void setRecordsRetrived(int recordsRetrived) { this.recordsRetrived = recordsRetrived; } private void setIdentifierData(SRWRecord srwrecord, ElementType[] data ) throws EREException{ boolean identifierExists = false; if (data != null){ for (int i=0; i <data.length; i++){ ElementType elmt = data[i]; String value = elmt.getStringValue(); // special handling srwrecord.setRepositoryCode(value); srwrecord.setRepositoryId(value); identifierExists = true; } } if (!identifierExists) { throw new EREException("Identifier field is missing"); } } public List<SRWRecord> getResultsObjects() { return resultsObjects; } public void setResultsObjects(List<SRWRecord> resultsObjects) { this.resultsObjects = resultsObjects; } }
28.719008
98
0.721439
fad7b7aca1425af87c53bcf171274174c82aa6e0
10,902
package org.openntf.domino.demoApp.subpages.database; /* <!-- Copyright 2017 Paul Withers Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License --> */ import java.text.MessageFormat; /* <!-- Copyright 2015 Paul Withers 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 org.openntf.domino.Database.FTDomainSearchOption; import org.openntf.domino.Database.FTDomainSortOption; import org.openntf.domino.Database.FTIndexFrequency; import org.openntf.domino.Database.FTIndexOption; import org.openntf.domino.Database.FTSearchOption; import org.openntf.domino.Database.FTSortOption; import org.openntf.domino.demoApp.components.Html_Separator; import org.openntf.domino.demoApp.components.Html_Separator.SeparatorType; import org.openntf.domino.demoApp.pages.BaseView; import org.openntf.domino.demoApp.subpages.BaseSubPage; import org.openntf.domino.demoApp.utils.FactoryUtils; import com.vaadin.shared.ui.label.ContentMode; import com.vaadin.ui.Button; import com.vaadin.ui.Button.ClickEvent; import com.vaadin.ui.Button.ClickListener; import com.vaadin.ui.Label; import com.vaadin.ui.Panel; import com.vaadin.ui.VerticalLayout; import com.vaadin.ui.themes.ValoTheme; public class Database_FTIndex extends BaseSubPage { private static final long serialVersionUID = 1L; private Panel subContentPanel = new Panel(); private VerticalLayout ftIndexLayout = null; private VerticalLayout ftFrequencyLayout = null; private VerticalLayout ftSearchOptionLayout = null; private VerticalLayout ftSortOptionLayout = null; private VerticalLayout ftDomainSearchOptionLayout = null; private VerticalLayout ftDomainSortOptionLayout = null; public Database_FTIndex(BaseView parentView) { super(parentView); } @Override public void loadContent() { Label label1 = new Label(getProps().getProperty("indexIntro")); Button button1 = new Button("FTIndexOption"); button1.addStyleName(ValoTheme.BUTTON_FRIENDLY); button1.addStyleName("floating-btn"); button1.addClickListener(new ClickListener() { private static final long serialVersionUID = 1L; @Override public void buttonClick(ClickEvent event) { getSubContentPanel().setContent(getFtIndexLayout()); } }); Button button2 = new Button("FTIndexFrequency"); button2.addStyleName(ValoTheme.BUTTON_FRIENDLY); button2.addStyleName("floating-btn"); button2.addClickListener(new ClickListener() { private static final long serialVersionUID = 1L; @Override public void buttonClick(ClickEvent event) { getSubContentPanel().setContent(getFtFrequencyLayout()); } }); Button button3 = new Button("FTSearchOption"); button3.addStyleName(ValoTheme.BUTTON_FRIENDLY); button3.addStyleName("floating-btn"); button3.addClickListener(new ClickListener() { private static final long serialVersionUID = 1L; @Override public void buttonClick(ClickEvent event) { getSubContentPanel().setContent(getFtSearchOptionLayout()); } }); Button button4 = new Button("FTSortOption"); button4.addStyleName(ValoTheme.BUTTON_FRIENDLY); button4.addStyleName("floating-btn"); button4.addClickListener(new ClickListener() { private static final long serialVersionUID = 1L; @Override public void buttonClick(ClickEvent event) { getSubContentPanel().setContent(getFtSortOptionLayout()); } }); Button button5 = new Button("FTDomainSearchOption"); button5.addStyleName(ValoTheme.BUTTON_FRIENDLY); button5.addStyleName("floating-btn"); button5.addClickListener(new ClickListener() { private static final long serialVersionUID = 1L; @Override public void buttonClick(ClickEvent event) { getSubContentPanel().setContent(getFtDomainSearchOptionLayout()); } }); Button button6 = new Button("FTDomainSortOption"); button6.addStyleName(ValoTheme.BUTTON_FRIENDLY); button6.addStyleName("floating-btn"); button6.addClickListener(new ClickListener() { private static final long serialVersionUID = 1L; @Override public void buttonClick(ClickEvent event) { getSubContentPanel().setContent(getFtDomainSortOptionLayout()); } }); addComponents(label1, new Html_Separator(SeparatorType.NEW_LINE), button1, button2, button3, button4, button5, button6, new Html_Separator(SeparatorType.NEW_LINE), getSubContentPanel()); } private Panel getSubContentPanel() { return subContentPanel; } private void setSubContentPanel(Panel subContentPanel) { this.subContentPanel = subContentPanel; } private VerticalLayout getFtIndexLayout() { if (null == ftIndexLayout) { setFtIndexLayout(); } return ftIndexLayout; } private void setFtIndexLayout() { ftIndexLayout = new VerticalLayout(); Label label1 = new Label("FTIndexOption"); label1.setStyleName(ValoTheme.LABEL_H3); Label label2 = new Label(MessageFormat.format(getProps().getProperty("indexOptIntro"), FactoryUtils.addCodeString("Database.createFTIndex()"))); label2.setContentMode(ContentMode.HTML); ftIndexLayout.addComponents(label1, label2); for (FTIndexOption elem : FTIndexOption.values()) { Label label3 = new Label("<li>" + elem + " - " + elem.getValue() + "</li>", ContentMode.HTML); ftIndexLayout.addComponent(label3); } Label label4 = new Label("</ul>", ContentMode.HTML); ftIndexLayout.addComponent(label4); } private VerticalLayout getFtFrequencyLayout() { if (null == ftFrequencyLayout) { setFtFrequencyLayout(); } return ftFrequencyLayout; } private void setFtFrequencyLayout() { ftFrequencyLayout = new VerticalLayout(); Label label1 = new Label("FTIndexFrequency"); label1.setStyleName(ValoTheme.LABEL_H3); Label label2 = new Label(MessageFormat.format(getProps().getProperty("indexFreqIntro"), FactoryUtils.addCodeString("Database.setFTIndexFrequency()"))); label2.setContentMode(ContentMode.HTML); ftFrequencyLayout.addComponents(label1, label2); for (FTIndexFrequency elem : FTIndexFrequency.values()) { Label label3 = new Label("<li>" + elem + " - " + elem.getValue() + "</li>", ContentMode.HTML); ftFrequencyLayout.addComponent(label3); } Label label4 = new Label("</ul>", ContentMode.HTML); ftFrequencyLayout.addComponent(label4); } private VerticalLayout getFtSearchOptionLayout() { if (null == ftSearchOptionLayout) { setFtSearchOptionLayout(); } return ftSearchOptionLayout; } private void setFtSearchOptionLayout() { ftSearchOptionLayout = new VerticalLayout(); Label label1 = new Label("FTSearchOption"); label1.setStyleName(ValoTheme.LABEL_H3); Label label2 = new Label(MessageFormat.format(getProps().getProperty("searchOptIntro"), FactoryUtils.addCodeString("Database.FTSearch()"))); label2.setContentMode(ContentMode.HTML); ftSearchOptionLayout.addComponents(label1, label2); for (FTSearchOption elem : FTSearchOption.values()) { Label label3 = new Label("<li>" + elem + " - " + elem.getValue() + "</li>", ContentMode.HTML); ftSearchOptionLayout.addComponent(label3); } Label label4 = new Label("</ul>", ContentMode.HTML); ftSearchOptionLayout.addComponent(label4); } private VerticalLayout getFtSortOptionLayout() { if (null == ftSortOptionLayout) { setFtSortOptionLayout(); } return ftSortOptionLayout; } private void setFtSortOptionLayout() { ftSortOptionLayout = new VerticalLayout(); Label label1 = new Label("FTSortOption"); label1.setStyleName(ValoTheme.LABEL_H3); Label label2 = new Label(MessageFormat.format(getProps().getProperty("sortOptIntro"), FactoryUtils.addCodeString("Database.FTSearch()"))); label2.setContentMode(ContentMode.HTML); ftSortOptionLayout.addComponents(label1, label2); for (FTSortOption elem : FTSortOption.values()) { Label label3 = new Label("<li>" + elem + " - " + elem.getValue() + "</li>", ContentMode.HTML); ftSortOptionLayout.addComponent(label3); } Label label4 = new Label("</ul>", ContentMode.HTML); ftSortOptionLayout.addComponent(label4); } private VerticalLayout getFtDomainSearchOptionLayout() { if (null == ftDomainSearchOptionLayout) { setFtDomainSearchOptionLayout(); } return ftDomainSearchOptionLayout; } private void setFtDomainSearchOptionLayout() { ftDomainSearchOptionLayout = new VerticalLayout(); Label label1 = new Label("FTDomainSearchOption"); label1.setStyleName(ValoTheme.LABEL_H3); Label label2 = new Label(MessageFormat.format(getProps().getProperty("domainSearchOptsIntro"), FactoryUtils.addCodeString("Database.FTDomainSearch()"), FactoryUtils.addCodeString("Database.FTSearchOption"))); label2.setContentMode(ContentMode.HTML); ftDomainSearchOptionLayout.addComponents(label1, label2); for (FTDomainSearchOption elem : FTDomainSearchOption.values()) { Label label3 = new Label("<li>" + elem + " - " + elem.getValue() + "</li>", ContentMode.HTML); ftDomainSearchOptionLayout.addComponent(label3); } Label label4 = new Label("</ul>", ContentMode.HTML); ftDomainSearchOptionLayout.addComponent(label4); } private VerticalLayout getFtDomainSortOptionLayout() { if (null == ftDomainSortOptionLayout) { setFtDomainSortOptionLayout(); } return ftDomainSortOptionLayout; } private void setFtDomainSortOptionLayout() { ftDomainSortOptionLayout = new VerticalLayout(); Label label1 = new Label("FTDomainSortOption"); label1.setStyleName(ValoTheme.LABEL_H3); Label label2 = new Label(MessageFormat.format(getProps().getProperty("domainSortOptsIntro"), FactoryUtils.addCodeString("Database.FTDomainSearch()"), FactoryUtils.addCodeString("Database.FTSortOption"))); label2.setContentMode(ContentMode.HTML); ftDomainSortOptionLayout.addComponents(label1, label2); for (FTDomainSortOption elem : FTDomainSortOption.values()) { Label label3 = new Label("<li>" + elem + " - " + elem.getValue() + "</li>", ContentMode.HTML); ftDomainSortOptionLayout.addComponent(label3); } Label label4 = new Label("</ul>", ContentMode.HTML); ftDomainSortOptionLayout.addComponent(label4); } }
36.583893
112
0.762521
0be2f807a55eb383cb7dbdbfefc6feba4df3b82f
1,528
package com.github.jolice.game.death.handler; import com.github.jolice.game.player.GamePlayer; import com.github.jolice.game.player.GamePlayerStatus; import com.github.jolice.game.player.repository.GamePlayerStorage; import com.github.jolice.game.player.status.PlayerLives; import com.github.jolice.game.death.Respawn; import org.junit.Test; import java.util.UUID; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class LivesDeathHandlerTest { @Test public void onPlayerDeath() { PlayerLives playerLives = mock(PlayerLives.class); GamePlayerStorage storage = mock(GamePlayerStorage.class); Respawn respawn = mock(Respawn.class); LivesDeathHandler livesDeathHandler = new LivesDeathHandler( playerLives, storage, respawn ); UUID uuid =UUID.randomUUID(); when(playerLives.decrementLives(eq(uuid))).thenReturn(3); GamePlayer player = mock(GamePlayer.class); when(storage.getPlayer(eq(uuid))).thenReturn(player); GamePlayerStatus playerStatus = mock(GamePlayerStatus.class); when(player.getStatus()).thenReturn(playerStatus); livesDeathHandler.onPlayerDeath(uuid); verify(respawn).markForRespawn(eq(player)); when(playerLives.decrementLives(eq(uuid))).thenReturn(0); livesDeathHandler.onPlayerDeath(uuid); verify(playerStatus).dropOut(); } }
36.380952
69
0.73233
6f8b29621bff083cad4e3b8daf7d9259079c5a84
1,981
// Copyright (c) 2021, the R8 project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. package com.android.tools.r8.ir.optimize.redundantfieldloadelimination; import com.android.tools.r8.CompilationMode; import com.android.tools.r8.TestBase; import com.android.tools.r8.TestParameters; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameter; import org.junit.runners.Parameterized.Parameters; @RunWith(Parameterized.class) public class FieldReadBeforeOtherwiseRedundantStoreTest extends TestBase { @Parameter(0) public CompilationMode mode; @Parameter(1) public TestParameters parameters; @Parameters(name = "{1}, mode: {0}") public static List<Object[]> data() { return buildParameters( CompilationMode.values(), getTestParameters().withDexRuntimes().withAllApiLevels().build()); } @Test public void test() throws Exception { testForD8() .addInnerClasses(FieldReadBeforeOtherwiseRedundantStoreTest.class) .setMinApi(parameters.getApiLevel()) .setMode(mode) .compile() .run(parameters.getRuntime(), Main.class) .assertSuccess(); } static class Main { public static int field = 0; public int testLoop() { int iterations = 50; for (int i = 0; i < iterations; i++) { int a = field; field = a + i; int b = field; field = b + 2 * i; } assertIntEquals(field, 3675); return field; } public static void main(String[] args) { Main obj = new Main(); obj.testLoop(); } public static void assertIntEquals(int expected, int result) { if (expected != result) { throw new Error("Expected: " + expected + ", found: " + result); } } } }
27.901408
100
0.674912
835840c82a9ffe2f0bd259115eb47844bb08ec71
7,690
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Graphics.Base.UI; import Graphics.Base.ScreenUI; import Graphics.Base.UIManager; import Graphics.Forum.ActionKeys; import Graphics.UserActions.UIZone; import Graphics.UserActions.UserInterfaceAction; import Graphics.Utils.Camera2D; import Holder.Texture; import org.lwjgl.input.Mouse; import org.lwjgl.util.vector.Vector2f; /** * * @author Allazham */ public class ScrollBar extends Panel{ private final ScreenUI Tile; private static Camera2D cam = Camera2D.getCamera(); private int mouseB; private UserInterfaceAction uia; private boolean horizonal; private double barSize= 1,totalSize = 12; private double greater = 1, lesser = 0; public ScrollBar(boolean disabled,boolean horizonal){ super(disabled); this.horizonal = horizonal; this.Tile = new ScreenUI(0,0,1,1,CENTER,false); super.addRenderObject(Tile); this.setup(); } public ScrollBar(float x, float y, float width, float height, int orintation,boolean disabled,boolean horizonal){ super(x,y,width,height,orintation,disabled); this.horizonal = horizonal; this.Tile = new ScreenUI(0,0,1,1,CENTER,false); super.addRenderObject(Tile); this.setup(); } public ScrollBar(float x, float y, float width, float height, int orintation,Texture t,boolean disabled,boolean horizonal){ super(x,y,width,height,orintation,t,disabled); this.horizonal = horizonal; this.Tile = new ScreenUI(0,0,1,1,CENTER,false); super.addRenderObject(Tile); this.setup(); } public void setBoxTexture(Texture t){ this.Tile.setTexture(t); } public Texture getBoxTexture(){ return this.Tile.getTexture(); } public void setHorizional(){ this.horizonal = true; this.setup(); } public void setVertical(){ this.horizonal = false; this.setup(); } public boolean isHorizional(){ return this.horizonal; } public boolean isVertical(){ return !this.horizonal; } public double getLesser(){ return lesser; } public double getGreater(){ return greater; } public UserInterfaceAction getScrollAction(){ if(uia == null){ this.uia = new Scroll(super.getUIZone()); } return uia; } public void setTotalSize(double size){ this.totalSize = size; this.setup(); } public void setBarSize(double size){ this.barSize = size; this.setup(); } public final void setup(){ ActionTaken(new Vector2f(1,1)); } private void ActionTaken(Vector2f v){ double DFC = barSize/totalSize; double lesserV,greaterV,loc,dist,preDist; float width = super.getActualWidth(); float height = super.getActualHeight(); int choose = this.getActaulOrientation(); float x = super.getActualX(),y = super.getActualY(); System.out.println(height); if(DFC < 1){ if(this.horizonal){ if(choose != CENTER && choose != DOWN &&choose != UP){ x += width/2; } this.Tile.setWidth((float) (DFC)); if(choose == CENTER || choose == LEFT || choose == RIGHT){ this.Tile.setY(0); } else{ this.Tile.setY(-.5f); } this.Tile.setHeight(1); lesserV = ScreenUI.ConvertWorldToScreenX(x, choose)-ScreenUI.ConvertWorldToScreenXDistance(width); greaterV = ScreenUI.ConvertWorldToScreenX(x, choose)+ScreenUI.ConvertWorldToScreenXDistance(width); loc = v.x - lesserV; dist = greaterV - lesserV; preDist = loc/dist; DFC = 1 -DFC; DFC /= 2; preDist -=.5; preDist *= 2; if(preDist > DFC){ preDist = DFC; } else if(preDist < -DFC){ preDist = -DFC; } DFC = .5 - DFC; if(choose == CENTER || choose == DOWN || choose == UP){ this.Tile.setX((float) (preDist)); } else{ this.Tile.setX((float) (preDist-DFC)); } this.lesser = ((preDist-DFC)+.5); this.greater = ((preDist+DFC)+.5); } else{ if(choose != CENTER && choose != LEFT && choose != RIGHT){ y += height/2; } this.Tile.setHeight((float) (DFC)); if(choose == CENTER || choose == UP || choose == DOWN){ this.Tile.setX(0); } else{ this.Tile.setX(-.5f); } this.Tile.setHeight(1); lesserV = ScreenUI.ConvertWorldToScreenX(x, choose)-ScreenUI.ConvertWorldToScreenXDistance(width); greaterV = ScreenUI.ConvertWorldToScreenX(x, choose)+ScreenUI.ConvertWorldToScreenXDistance(width); loc = v.x - lesserV; dist = greaterV - lesserV; preDist = loc/dist; DFC = 1 -DFC; DFC /= 2; preDist -=.5; preDist *= 2; if(preDist > DFC){ preDist = DFC; } else if(preDist < -DFC){ preDist = -DFC; } DFC = .5 - DFC; if(choose == CENTER || choose == DOWN || choose == UP){ this.Tile.setY((float) (preDist)); } else{ this.Tile.setY((float) (preDist-DFC)); } this.lesser = ((preDist-DFC)+.5); this.greater = ((preDist+DFC)+.5); } } else{ if(choose == CENTER || choose == LEFT || choose == RIGHT){ this.Tile.setY(0); } else{ this.Tile.setY(-.5f); } if(choose == CENTER||choose == UP||choose == DOWN){ this.Tile.setX(0); } else{ this.Tile.setX(-.5f); } this.Tile.setWidth(1); this.Tile.setHeight(1); this.lesser = 0; this.greater = DFC; } super.update(); } @Override public void setUIManager(UIManager ui){ super.setUIManager(ui); this.setup(); } @Override public void ProcessChanges(UIManager ui,float x, float y, float width, float height,int Orinentation){ super.ProcessChanges(ui, x, y, width, height, Orinentation); this.setup(); } private class Scroll extends UserInterfaceAction{ public Scroll(UIZone uiz){ super(uiz); } @Override public void Action(ActionKeys k) { if(Mouse.isButtonDown(mouseB)){ ActionTaken(cam.getMousePointOnGraphics()); } } } }
33.580786
128
0.491938
17936ae509903e816b634b9de9cbcb7a6f7b6dd0
5,754
/* * ============LICENSE_START======================================================= * PNF-REGISTRATION-HANDLER * ================================================================================ * Copyright (C) 2018 NOKIA 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.onap.dcaegen2.services.prh.tasks; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import com.google.gson.JsonObject; import io.netty.handler.codec.http.HttpResponseStatus; import javax.net.ssl.SSLException; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.function.Executable; import org.onap.dcaegen2.services.prh.TestAppConfiguration; import org.onap.dcaegen2.services.prh.adapter.aai.api.ConsumerDmaapModel; import org.onap.dcaegen2.services.prh.adapter.aai.api.ImmutableConsumerDmaapModel; import org.onap.dcaegen2.services.prh.adapter.aai.impl.AaiHttpPatchClient; import org.onap.dcaegen2.services.prh.adapter.aai.main.AaiClientConfiguration; import org.onap.dcaegen2.services.prh.configuration.CbsConfiguration; import org.onap.dcaegen2.services.prh.exceptions.PrhTaskException; import org.onap.dcaegen2.services.sdk.rest.services.adapters.http.HttpResponse; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; /** * @author <a href="mailto:[email protected]">Przemysław Wąsala</a> on 5/14/18 */ class AaiProducerTaskImplTest { private ConsumerDmaapModel consumerDmaapModel; private AaiProducerTaskImpl aaiProducerTask; private AaiClientConfiguration aaiClientConfiguration; private AaiHttpPatchClient aaiReactiveHttpPatchClient; private CbsConfiguration cbsConfiguration; private HttpResponse clientResponse; @BeforeEach void setUp() { clientResponse = mock(HttpResponse.class); aaiClientConfiguration = TestAppConfiguration.createDefaultAaiClientConfiguration(); consumerDmaapModel = ImmutableConsumerDmaapModel.builder() .ipv4("10.16.123.234") .ipv6("0:0:0:0:0:FFFF:0A10:7BEA") .correlationId("NOKQTFCOC540002E") .serialNumber("QTFCOC540002E") .equipVendor("nokia") .equipModel("3310") .equipType("type") .nfRole("role") .swVersion("v4.5.0.1") .additionalFields(new JsonObject()) .build(); cbsConfiguration = mock(CbsConfiguration.class); } @Test void whenPassedObjectDoesntFit_ThrowsPrhTaskException() { //given/when/ when(cbsConfiguration.getAaiClientConfiguration()).thenReturn(aaiClientConfiguration); aaiProducerTask = new AaiProducerTaskImpl(aaiReactiveHttpPatchClient); Executable executableCode = () -> aaiProducerTask.execute(null); //then Assertions .assertThrows(PrhTaskException.class, executableCode, "Passing wrong object type to execute function"); } @Test void whenPassedObjectFits_ReturnsCorrectStatus() throws PrhTaskException, SSLException { //given/when getAaiProducerTask_whenMockingResponseObject(HttpResponseStatus.OK); Mono<ConsumerDmaapModel> response = aaiProducerTask.execute(consumerDmaapModel); //then verify(aaiReactiveHttpPatchClient, times(1)).getAaiResponse(any()); verifyNoMoreInteractions(aaiReactiveHttpPatchClient); Assertions.assertEquals(consumerDmaapModel, response.block()); } @Test void whenPassedObjectFits_butIncorrectResponseReturns() throws PrhTaskException, SSLException { //given/when getAaiProducerTask_whenMockingResponseObject(HttpResponseStatus.BAD_REQUEST); StepVerifier.create(aaiProducerTask.execute(consumerDmaapModel)).expectSubscription() .expectError(PrhTaskException.class).verify(); //then verify(aaiReactiveHttpPatchClient, times(1)).getAaiResponse(any()); verifyNoMoreInteractions(aaiReactiveHttpPatchClient); } private void getAaiProducerTask_whenMockingResponseObject(HttpResponseStatus httpResponseStatus) throws SSLException { //given doReturn(httpResponseStatus.code()).when(clientResponse).statusCode(); Mono<HttpResponse> clientResponseMono = Mono.just(clientResponse); aaiReactiveHttpPatchClient = mock(AaiHttpPatchClient.class); when(aaiReactiveHttpPatchClient.getAaiResponse(any())) .thenReturn(clientResponseMono); when(cbsConfiguration.getAaiClientConfiguration()).thenReturn(aaiClientConfiguration); aaiProducerTask = spy(new AaiProducerTaskImpl(aaiReactiveHttpPatchClient)); } }
44.953125
122
0.706291
971c586b73417dfe8b157b3a0ec11732f6548784
19,224
/* * $Id$ * * Copyright (c) 2018, Simsilica, LLC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.simsilica.demo.bullet; import java.util.*; import org.slf4j.*; import com.jme3.anim.*; import com.jme3.anim.tween.action.Action; import com.jme3.app.Application; import com.jme3.app.state.BaseAppState; import com.jme3.math.*; import com.jme3.scene.*; import com.jme3.util.SafeArrayList; import com.simsilica.es.*; import com.simsilica.mathd.Vec3d; import com.simsilica.mathd.filter.*; /** * * * @author Paul Speed */ public class MobAnimationState extends BaseAppState { static Logger log = LoggerFactory.getLogger(MobAnimationState.class); private EntityData ed; private ModelViewState models; // Keep track of the mob animation objects we've already created private Map<EntityId, MobAnimation> mobIndex = new HashMap<>(); // Keep a list of the mob animation objects for convenient per-frame updates. private SafeArrayList<MobAnimation> mobs = new SafeArrayList<>(MobAnimation.class); private MobilityContainer mobStates; private ActionContainer mobActions; private GroundContainer mobGrounds; public MobAnimationState() { } @Override protected void initialize( Application app ) { this.ed = getState(GameSystemsState.class).get(EntityData.class); this.models = getState(ModelViewState.class); this.mobStates = new MobilityContainer(ed); this.mobActions = new ActionContainer(ed); this.mobGrounds = new GroundContainer(ed); } @Override protected void cleanup( Application app ) { } @Override protected void onEnable() { mobStates.start(); mobActions.start(); mobGrounds.start(); } @Override public void update( float tpf ) { mobStates.update(); mobActions.update(); mobGrounds.update(); for( MobAnimation mob : mobs.getArray() ) { mob.update(tpf); } } @Override protected void onDisable() { mobActions.stop(); mobStates.stop(); mobGrounds.stop(); } protected MobAnimation getMobAnimation( EntityId id ) { return getMobAnimation(id, true); } protected MobAnimation getMobAnimation( EntityId id, boolean create ) { MobAnimation result = mobIndex.get(id); if( result != null || !create ) { return result; } result = new MobAnimation(id); mobIndex.put(id, result); mobs.add(result); return result; } protected void removeMobAnimation( EntityId id ) { MobAnimation mob = mobIndex.remove(id); mobs.remove(mob); } protected void addMobility( EntityId parent, Mobility mobility ) { getMobAnimation(parent).addMobility(mobility); } protected void removeMobility( EntityId parent, Mobility mobility ) { getMobAnimation(parent).removeMobility(mobility); } protected void addAction( EntityId parent, CharacterAction action ) { getMobAnimation(parent).addAction(action.getCharacterActionName(ed)); } protected void removeAction( EntityId parent, CharacterAction action ) { getMobAnimation(parent).removeAction(action.getCharacterActionName(ed)); } protected void updateGround( EntityId mob, CharacterGround ground ) { getMobAnimation(mob).setGround(ground); } protected void removeGround( EntityId mob ) { MobAnimation mobAnim = getMobAnimation(mob); if( mobAnim != null ) { mobAnim.setGround(null); } } protected Spatial findAnimRoot( Spatial s ) { if( s.getControl(AnimComposer.class) != null ) { return s; } if( s instanceof Node ) { for( Spatial child : ((Node)s).getChildren() ) { Spatial result = findAnimRoot(child); if( result != null ) { return result; } } } return null; } /** * Manages the animation state for a specific MOB. */ private class MobAnimation { private EntityId id; private Set<Mobility> mobility = new HashSet<>(); private Mobility primary; private String currentBase; private String action; // only one at a time right now private Spatial model; private Spatial animRoot; private AnimComposer animComposer; private Action animAction; private double lastSpeed; private Vector3f lastLocation = new Vector3f(); private Quaternion lastRotation = new Quaternion(); private Vector3f velocity = new Vector3f(); private CharacterGround ground; private Vec3d groundVelocity = new Vec3d(); private boolean onGround = false; public MobAnimation( EntityId id ) { this.id = id; } public void setGround( CharacterGround ground ) { //System.out.println("setGround(" + ground + ")"); this.ground = ground; if( ground != null && ground.getVelocity() != null ) { groundVelocity.set(ground.getVelocity()); onGround = true; } else { groundVelocity.set(0,0,0); onGround = false; } } protected Spatial getAnimRoot() { if( animRoot == null ) { this.model = models.getModel(id); System.out.println("model:" + model); if( model == null ) { return null; // have to wait until later I guess. } // Find spatial with the composer // For the moment, we'll guess animRoot = ((Node)model).getChild("Root"); if( animRoot == null ) { // Have to find it the hard way animRoot = findAnimRoot(model); if( animRoot.getControl(AnimComposer.class) != null ) { log.info("Anim clip names:" + animRoot.getControl(AnimComposer.class).getAnimClipsNames()); } } System.out.println("animRoot:" + animRoot); lastLocation.set(model.getWorldTranslation()); lastRotation.set(model.getWorldRotation()); } return animRoot; } protected AnimComposer getAnimComposer() { if( animComposer == null ) { Spatial s = getAnimRoot(); animComposer = s == null ? null : s.getControl(AnimComposer.class); } return animComposer; } public void addMobility( Mobility m ) { mobility.add(m); // Just override whatever is there for now... I don't remember why I allow // multiple mobilities but when we manage how we pick which one is active // or layered at any given time then we can also use its base speed, etc. primary = m; } public void removeMobility( Mobility m ) { mobility.remove(m); if( mobility.isEmpty() ) { // Remove ourselves from being managed... there is no mobility component set anymore removeMobAnimation(id); } } public void addAction( String a ) { if( Objects.equals(a, this.action) ) { return; } this.action = a; // Set the animation on the character } public void removeAction( String a ) { if( !Objects.equals(a, this.action) ) { return; } this.action = null; // Stop the animation on the character } protected void setBaseAnimation( String a, double speed ) { //System.out.println("setBaseAnimation(" + a + ", " + speed + ")"); AnimComposer ac = getAnimComposer(); if( ac == null ) { return; } if( Objects.equals(a, currentBase) ) { if( animAction != null ) { speed = Math.round(speed * 10) / 10.0; if( speed != lastSpeed ) { animAction.setSpeed(speed); lastSpeed = speed; } } return; } this.currentBase = a; this.animAction = ac.setCurrentAction(currentBase); animAction.setSpeed(speed); } private Filterd lowPass = new SimpleMovingMean(10); // 1/6th second of data public void update( float tpf ) { Spatial s = getAnimRoot(); if( s == null ) { return; // nothing to do } // Right now since we can't layer... an action will override // any mobility if( action != null ) { setBaseAnimation(action, 1); return; } // See what kind of movement is happening velocity.set(model.getWorldTranslation()).subtractLocal(lastLocation); // We don't account for up/down right now velocity.y = 0; // Extrapolate the real velocity using tpf if( tpf > 0 ) { velocity.x /= tpf; velocity.y /= tpf; velocity.z /= tpf; } // Adjust for the ground velocity. Our "foot" velocity is whatever our // body velocity is minus the velocity of where we are standing. velocity.x = (float)(velocity.x - groundVelocity.x); velocity.z = (float)(velocity.z - groundVelocity.z); // Track the current values for next time lastLocation.set(model.getWorldTranslation()); lastRotation.set(model.getWorldRotation()); float rawSpeed = velocity.length(); //System.out.println("Foot velocity:" + velocity + " speed:" + rawSpeed); // If the raw speed is less than a certain threshold then // just clamp the velocity to 0. //if( rawSpeed < 0. // Because we aren't interpolating over known good physics frames // like we would in a network app, we have the possibility of seeing // the same position in two visual frames even if the object is moving. // For example: // JME thread Game Systems Thread // update update // // update // update // // // update // pudate // // That would look like the object is standing still as a tiny single // frame blip. We have filtering code to remove these blips but it's // bypassed if we 'early out' for rawSpeed = 0. //if( rawSpeed > 0.001 ) { //float speed = (tpf > 0 && rawSpeed > 0) ? rawSpeed / tpf : 0; // Just a simple heuristic for now //if( speed > 0.01 ) { float forward = lastRotation.mult(Vector3f.UNIT_Z).dot(velocity); float left = lastRotation.mult(Vector3f.UNIT_X).dot(velocity); //System.out.println("Raw forward:" + forward + " rawLeft:" + left); //forward = tpf > 0 ? forward / tpf : 0; //left = tpf > 0 ? left / tpf : 0; //System.out.println("rawSpeed:" + rawSpeed + " Adjusted tpf:" + tpf + " forward:" + forward + " left:" + left); // Clamp the speed by some threshold to avoid math errors creeping // in as slow animations //if( Math.abs(forward) < // rawSpeed = 0; //} double normalWalkSpeed = primary.getBaseSpeed(); double animSpeed = forward / normalWalkSpeed; // Pass the anim speed through a low-pass filter using // a moving average lowPass.addValue(animSpeed); animSpeed = lowPass.getFilteredValue(); //System.out.println("rawSpeed:" + rawSpeed + " forward:" + forward + " left:" + left + " animSpeed:" + animSpeed); //System.out.println("animSpeed:" + animSpeed); if( !onGround ) { setBaseAnimation("Jumping", 1); return; } else { // Clamp the animation speed at some minimum threshold that // won't look silly. if( Math.abs(animSpeed) > 0.2 ) { setBaseAnimation("Walk", animSpeed); return; } } //} //} else { //System.out.println("rawSpeed:" + rawSpeed); // } // If nothing else set an animation then go back to idle setBaseAnimation("Idle", 1); } } /** * Just need to keep track of the parent and value relationship * so that we can properly remove the value when the tagging entity * goes away. Generally it's fields have been cleared so we don't * have them anymore. */ private class ParentedComponent<T> { EntityId parentId; T value; public ParentedComponent( EntityId parentId, T value ) { this.parentId = parentId; this.value = value; } } @SuppressWarnings("unchecked") private class MobilityContainer extends EntityContainer<ParentedComponent<Mobility>> { public MobilityContainer( EntityData ed ) { super(ed, Mobility.class, Parent.class); } @Override protected ParentedComponent<Mobility> addObject( Entity e ) { Parent p = e.get(Parent.class); Mobility m = e.get(Mobility.class); addMobility(p.getParentId(), m); return new ParentedComponent<>(p.getParentId(), m); } @Override protected void updateObject( ParentedComponent<Mobility> object, Entity e ) { } @Override protected void removeObject( ParentedComponent<Mobility> object, Entity e ) { removeMobility(object.parentId, object.value); } } @SuppressWarnings("unchecked") private class ActionContainer extends EntityContainer<ParentedComponent<CharacterAction>> { public ActionContainer( EntityData ed ) { super(ed, CharacterAction.class, Parent.class); } @Override protected ParentedComponent<CharacterAction> addObject( Entity e ) { Parent p = e.get(Parent.class); CharacterAction a = e.get(CharacterAction.class); addAction(p.getParentId(), a); return new ParentedComponent<>(p.getParentId(), a); } @Override protected void updateObject( ParentedComponent<CharacterAction> object, Entity e ) { } @Override protected void removeObject( ParentedComponent<CharacterAction> object, Entity e ) { removeAction(object.parentId, object.value); } } @SuppressWarnings("unchecked") private class GroundContainer extends EntityContainer<CharacterGround> { public GroundContainer( EntityData ed ) { super(ed, CharacterGround.class); } @Override protected CharacterGround addObject( Entity e ) { CharacterGround ground = e.get(CharacterGround.class); updateObject(ground, e); return ground; } @Override protected void updateObject( CharacterGround object, Entity e ) { // Remember, we have to look up the component again even if we // are using it as our object... else we only ever see the original // value when we were created. CharacterGround ground = e.get(CharacterGround.class); //System.out.println("updateGroud:" + e.getId() + " -> " + ground); updateGround(e.getId(), ground); } @Override protected void removeObject( CharacterGround object, Entity e ) { removeGround(e.getId()); } } }
36.898273
135
0.536361
0dc6a9c6266d7f9c68c9f358aa7be69b59322072
682
/* * Copyright 2019 Equipment & Tool Institute */ package org.etools.j1939_84.bus.j1939.packets; import org.etools.j1939_84.bus.Packet; public class EngineHoursPacket extends GenericPacket { public static final int PGN = 65253; public static EngineHoursPacket create(int address, long engineHours) { long hours = (long) (engineHours / 0.05); int[] data = ParsedPacket.to4Ints(hours); return new EngineHoursPacket(Packet.create(PGN, address, data)); } public EngineHoursPacket(Packet packet) { super(packet); } public double getEngineHours() { return getSpnValue(247).findFirst().orElse(NOT_AVAILABLE); } }
26.230769
75
0.692082
317d1ad008521b0d64a87cf711de79d7be086d09
16,334
package com.huawei.agentdemo.servlet; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.nio.file.Files; import java.text.Normalizer; import java.text.Normalizer.Form; import java.util.List; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.tomcat.util.http.fileupload.FileItem; import org.apache.tomcat.util.http.fileupload.FileUploadException; import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory; import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload; import org.apache.tomcat.util.http.fileupload.servlet.ServletRequestContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.huawei.agentdemo.service.TextChatService; import com.huawei.demo.request.Request; import com.huawei.demo.util.FileUtil; import com.huawei.demo.util.LogUtils; import com.huawei.demo.util.StringUtils; /** * <p>Title: text chat interface servlet </p> * <p>Description: text chat interface servlet </p> */ public class TextChatServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final Logger LOG = LoggerFactory.getLogger(TextChatServlet.class); /** * @see HttpServlet#HttpServlet() */ public TextChatServlet() { super(); } /** * @throws UnsupportedEncodingException * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) { try { String filePath = request.getParameter("filePath"); String identifyMark = request.getParameter("identityMark"); if (null == filePath || "".equals(filePath)) { LOG.error("filePath is null or empity."); return; } filePath = Request.getProjectPath()+"/"+"file"+"/"+identifyMark+"/"+filePath; String prefix = Request.getProjectPath() + "/file"; if (!FileUtil.isSafePath(filePath)&&filePath.startsWith(prefix)) { LOG.info("filePath is invalid."); return; } filePath = FileUtil.checkFile(filePath); File file = new File(filePath); try { file = file.getCanonicalFile(); } catch (IOException e) { LOG.error("IOException \r\n {}", LogUtils.encodeForLog(e.getMessage())); return; } if (file.exists()) { FileInputStream in = null; ServletOutputStream out = null; try { in = new FileInputStream(file); response.addHeader("Cache-Control", "public"); response.addHeader("Pragma", "public"); String filename = java.net.URLEncoder.encode(file.getName(),"utf-8"); response.addHeader("Content-Disposition","attachment;filename=" + filename); out = response.getOutputStream(); byte[] bt = new byte[1024]; int count; while ((count = in.read(bt)) > 0) { out.write(bt, 0, count); } } catch(FileNotFoundException e) { LOG.error("FileNotFoundException \r\n {}", LogUtils.encodeForLog(e.getMessage())); } catch(UnsupportedEncodingException e) { LOG.error("UnsupportedEncodingException \r\n {}", LogUtils.encodeForLog(e.getMessage())); } catch(IOException e) { LOG.error("IOException \r\n {}", LogUtils.encodeForLog(e.getMessage())); } finally { if (null != out) { try { out.flush(); out.close(); } catch(Exception e) { LOG.error("Close ServletOutputStream error"); } } if (null != in) { try { in.close(); } catch(Exception e) { LOG.error("Close PrintWriter error"); } } } } } catch(Throwable throwable) { LOG.error("catch throwable at TextChatServlet: ",throwable); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) { try { try { request.setCharacterEncoding("utf-8"); } catch (UnsupportedEncodingException e1) { LOG.error("request set character encoding error"); } response.setCharacterEncoding("utf-8"); response.setContentType("text/html"); String workNo = request.getParameter("identityMark"); String type = request.getParameter("type"); String callId = request.getParameter("callId"); String content = request.getParameter("content"); String called = request.getParameter("called"); String addresstype = request.getParameter("addresstype"); String destaddr = request.getParameter("destaddr"); String mode = request.getParameter("mode"); String filePath = request.getParameter("filePath"); String skillId = request.getParameter("skillId"); String chatId = request.getParameter("chatId"); String chatReceiver = request.getParameter("chatReceiver"); String jauIP = request.getParameter("jauIP"); String jauPort = request.getParameter("jauPort"); String result = StringUtils.EMPTY_STRING; if (StringUtils.isNullOrBlank(workNo)) { LOG.warn("workNo is null or blank"); return; } if (StringUtils.isNullOrBlank(type)) { LOG.warn("type is null or blank"); return; } switch(type) { case "ANSWER": if (StringUtils.isNullOrBlank(callId)) { LOG.warn("callId is null or blank"); return; } result = TextChatService.textAnswer(workNo, callId); break; case "REJECT": if (StringUtils.isNullOrBlank(callId)) { LOG.warn("callId is null or blank"); return; } result = TextChatService.textReject(workNo, callId); break; case "RELEASE": if (StringUtils.isNullOrBlank(callId)) { LOG.warn("callId is null or blank"); return; } result = TextChatService.textDrop(workNo, callId); break; case "SENDMESSAGE": if (StringUtils.isNullOrBlank(callId)) { LOG.warn("callId is null or blank"); return; } if (StringUtils.isNullOrBlank(content)) { LOG.warn("content is null or blank"); return; } result = TextChatService.textSendmessage(workNo, callId, content); break; case "CALLINNER": if (StringUtils.isNullOrBlank(called)) { LOG.warn("called is null or blank"); return; } result = TextChatService.textCallinner(workNo,called); break; case "TRANSFER": if (StringUtils.isNullOrBlank(addresstype)) { LOG.warn("addresstype is null or blank"); return; } if (StringUtils.isNullOrBlank(destaddr)) { LOG.warn("destaddr is null or blank"); return; } if (StringUtils.isNullOrBlank(callId)) { LOG.warn("callId is null or blank"); return; } if (StringUtils.isNullOrBlank(mode)) { LOG.warn("mode is null or blank"); return; } result = TextChatService.textTransfer(workNo,addresstype,destaddr,callId,mode); break; case "FILEUPLOAD": if (StringUtils.isNullOrBlank(callId)) { LOG.warn("callId is null or blank"); return; } ServletRequestContext requestContext = new ServletRequestContext(request); InputStream is = null; byte[] mediaData = null; FileItem item = null; try { DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload fileUpload = new ServletFileUpload(factory); List<FileItem> items = fileUpload.parseRequest(requestContext); if (items.size() != 1) { result = "file upload failed, because FileItem is over one."; break; } item = items.get(0); if (item.isFormField()) { result = "FileItem is form field."; break; } String name = item.getName(); is = item.getInputStream(); mediaData = FileUtil.inputStreamToByte(is); if (null != mediaData) { result = TextChatService.uploadFile(workNo, callId,mediaData,name); } else { result = "input stream to byte failed"; } } catch (FileUploadException e) { LOG.error("catch FileUploadException"); } catch (IOException e) { LOG.error("catch IOException"); } finally { if (null != is) { try { is.close(); } catch (IOException e) { LOG.error("close inputstream failed"); } } if (null != item) { item.delete(); } } break; case "FILEDOWNLOAD": if (StringUtils.isNullOrBlank(filePath)) { LOG.warn("filePath is null or blank"); return; } result = TextChatService.downloadFile(workNo, filePath); if (StringUtils.isNullOrBlank(result)) { return; } break; /****************************全量接口示例开始************************/ //无呼叫发送内容给用户 case "DISCONNECT": if (StringUtils.isNullOrBlank(skillId)) { LOG.warn("skillId is null or blank"); return; } if (StringUtils.isNullOrBlank(chatId)) { LOG.warn("chatId is null or blank"); return; } if (StringUtils.isNullOrBlank(chatReceiver)) { LOG.warn("chatReceiver is null or blank"); return; } if (StringUtils.isNullOrBlank(content)) { LOG.warn("content is null or blank"); return; } if (StringUtils.isNullOrBlank(jauIP)) { LOG.warn("jauIP is null or blank"); return; } if (StringUtils.isNullOrBlank(jauPort)) { LOG.warn("jauPort is null or blank"); return; } result = TextChatService.sendMessageWithoutCall(workNo, skillId, chatId, chatReceiver, content, jauIP, jauPort); break; /****************************全量接口示例结束************************/ default: break; } PrintWriter out = null; try { out = response.getWriter(); out.println(encodeHtml(result)); // out.println(result); } catch (IOException e) { LOG.error("catch IOException"); } finally { if (null != out) { try { out.flush(); out.close(); } catch(Exception e) { LOG.error("Close PrintWriter error"); } } } } catch(Throwable throwable) { LOG.error("catch throwable at TextChatServlet: ",throwable); } } private String encodeHtml(String result) { String normalize = Normalizer.normalize(result, Form.NFKC); return normalize; } }
36.541387
109
0.414779
44e8034bb9af038f3f0c190a7504370301ca4349
1,929
/* * Copyright 2012 jMethods, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.myjavaworld.jftp; import java.awt.Component; import javax.swing.Icon; import javax.swing.JTable; import com.myjavaworld.gui.MTableCellRenderer; /** * A table cell renderer used to render Local files. * * @author Sai Pullabhotla, psai [at] jMethods [dot] com * @version 2.0 */ public class LocalFileCellRenderer extends MTableCellRenderer { private Icon directoryIcon = null; private Icon fileIcon = null; public LocalFileCellRenderer() { super(); directoryIcon = JFTPUtil.getIcon("directory16.gif"); fileIcon = JFTPUtil.getIcon("file16.gif"); } @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int col) { if (value == null) { setText(""); setIcon(null); } else { LocalFile file = (LocalFile) value; setText(file.getDisplayName()); Icon icon = file.getIcon(); if (icon != null) { setIcon(file.getIcon()); } else { setIcon(file.isDirectory() ? directoryIcon : fileIcon); } } setBackground(isSelected ? table.getSelectionBackground() : table .getBackground()); setForeground(isSelected ? table.getSelectionForeground() : table .getForeground()); setFont(table.getFont()); return this; } }
29.676923
76
0.692068
de3004411e6c207e7fb0fd50099091565d1a8359
281
package com.picker.model; import java.io.Serializable; public class Album implements Serializable { private static final long serialVersionUID = 1L; public String id; public String photoId; public String name; public String url; public String count; }
17.5625
52
0.725979
7210799d3baf95be8eadab88b33dafd3fdab22bb
1,701
package com.grazeten.download; import java.net.URISyntaxException; import java.net.URL; import java.util.concurrent.Callable; import android.content.Context; import com.grazeten.PL; import com.grazeten.jobs.Job; import com.grazeten.util.Timing; import com.grazeten.util.U; public class DownloadImageTask implements Callable<Asset> { private WebPageDownloadDirector wpdd; private NewsRobHttpClient httpClient; private Asset asset; private long started; private URL pageUrl; private Job job; private Context context; DownloadImageTask(Context context, WebPageDownloadDirector wpdd, NewsRobHttpClient httpClient, Job job, URL pageUrl, long started, Asset asset) { this.context = context; this.httpClient = httpClient; this.wpdd = wpdd; this.job = job; this.pageUrl = pageUrl; this.asset = asset; this.started = started; PL.log("DownloadImageTask " + asset.remoteUrl + " as part of " + pageUrl + " created", context); } @Override public Asset call() throws Exception { try { U.setLowPrio(); PL.log("DownloadImageTask " + asset.remoteUrl + " started", context); Timing t = new Timing("DownloadImageTask " + asset.remoteUrl + " as part of " + pageUrl, context); try { wpdd.downloadBinaryAsset(httpClient, asset, started, job, pageUrl); } catch (URISyntaxException e) { asset.exception = e; } t.stop(); PL.log("DownloadImageTask " + asset.remoteUrl + " done", context); } catch (Exception e) { throw e; } return asset; } }
25.772727
145
0.636096
08f319de458bc8a6a266a367ce999594e93348f3
634
package l2f.gameserver.network.serverpackets; public class KeyPacket extends L2GameServerPacket { //private final int[] _signatures; private byte[] _key; public KeyPacket(byte key[]) { _key = key; //_signatures = ClickersSignatureDao.getInstance().getSignatures(); } @Override public void writeImpl() { writeC(0x2E); if (_key == null || _key.length == 0) { writeC(0x00); return; } writeC(0x01); writeB(_key); writeD(0x01); writeD(0x00); writeC(0x00); writeD(0x00); // Seed (obfuscation key) //writeD(_signatures.length); //for(int sig : _signatures) //{ // writeD(sig); //} } }
17.135135
69
0.652997
bbfff0d4f18410369a16180250e2e83034eda1ac
624
package ru.betterend.item; import net.minecraft.world.entity.EntityType; import net.minecraft.world.item.FishBucketItem; import net.minecraft.world.level.material.Fluids; import ru.betterend.patterns.Patterned; import ru.betterend.patterns.Patterns; import ru.betterend.registry.EndItems; public class EndBucketItem extends FishBucketItem implements Patterned { public EndBucketItem(EntityType<?> type) { super(type, Fluids.WATER, EndItems.makeItemSettings().stacksTo(1)); } @Override public String getModelPattern(String name) { return Patterns.createJson(Patterns.ITEM_GENERATED, name); } }
31.2
73
0.783654
b7689c8c4a47eee9c37f2c12ba87d20127ae537c
2,684
package Date; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class DateFunction { public static String getCurrentDate(){ Date date = new Date(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); return simpleDateFormat.format(date); } public static String getCurrentShortDate (){ Date date = new Date(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); return simpleDateFormat.format(date); } public static String getCurrentDateTime(){ Date date = new Date(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); return simpleDateFormat.format(date); } public static String getCurrentChineseDate(){ Date date = new Date(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日"); return simpleDateFormat.format(date); } public static java.util.Date convertToDate(String currentDate) throws Exception{ if (currentDate.matches("((((19|20)\\d{2})-(0?(1|[3-9])|1[012])-(0?[1-9]|[12]\\d|30))|(((19|20)\\d{2})-(0?[13578]|1[02])-31)|(((19|20)\\d{2})-0?2-(0?[1-9]|1\\d|2[0-8]))|((((19|20)([13579][26]|[2468][048]|0[48]))|(2000))-0?2-29))$")){ SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); return simpleDateFormat.parse(currentDate); }else{ throw new Exception("格式错误"); } } public static java.util.Date convertToLongDate(String currentDate) throws ConvertException, ParseException { if (currentDate.matches("((((19|20)\\d{2})-(0?(1|[3-9])|1[012])-(0?[1-9]|[12]\\d|30))|(((19|20)\\d{2})-(0?[13578]|1[02])-31)|(((19|20)\\d{2})-0?2-(0?[1-9]|1\\d|2[0-8]))|((((19|20)([13579][26]|[2468][048]|0[48]))|(2000))-0?2-29))$")){ SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); return simpleDateFormat.parse(currentDate); }else{ throw new ConvertException("格式错误"); } } public static String convertToDateString(java.sql.Date date) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); return simpleDateFormat.format(date); } public static String convertToDateTimeString(java.sql.Date date) { SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); return simpleDateFormat.format(date); } private static class ConvertException extends Exception { public ConvertException(String message) { super(message); } } }
44
241
0.636364
c137b2e0fd2397fdf3bcfa9c3521f6962a906c87
2,414
/* * Copyright 2017 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kie.workbench.common.forms.jbpm.server.service.impl; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Optional; public class ProcessTaskFormsGenerationResult { private String processId; private Map<String, String> taskIdFormNameMap = new HashMap<>(); private Map<String, TaskFormVariables> taskFormVariablesRegistry = new HashMap<>(); public ProcessTaskFormsGenerationResult(String processId) { this.processId = processId; } public String getProcessId() { return processId; } public TaskFormVariables getTaskFormVariablesByTaskId(String taskId) { if (!taskIdFormNameMap.containsKey(taskId)) { return null; } return getTaskFormVariablesByFormName(taskIdFormNameMap.get(taskId)); } public TaskFormVariables getTaskFormVariablesByFormName(String formName) { return taskFormVariablesRegistry.get(formName); } public Collection<TaskFormVariables> getAllTaskFormVariables() { return taskFormVariablesRegistry.values(); } public void registerTaskFormVariables(String taskId, TaskFormVariables taskFormVariables) { taskIdFormNameMap.put(taskId, taskFormVariables.getTaskName()); Optional<TaskFormVariables> optional = Optional.ofNullable(getTaskFormVariablesByFormName(taskFormVariables.getTaskName())); if (optional.isPresent()) { optional.get().merge(taskFormVariables); } else { taskFormVariables.setProcessId(processId); taskFormVariablesRegistry.put(taskFormVariables.getTaskName(), taskFormVariables); } } }
34.485714
132
0.693455
ff56fd610cb6e87c54033698740f7493787c475b
919
package topcoder.tco2009.round3; public class CampaignTrail { public double probWin(int[] electors, int[] winCurrent, int[] winIfVisited, int visits) { int n = electors.length; int sum = 0; for (int i : electors) { sum += i; } double[][][] a = new double[n + 1][sum + 1][visits + 1]; for (int x = 0; x <= sum; x++) { if (2 * x > sum) { for (int v = 0; v <= visits; v++) { a[n][x][v] = 1; } } } int ss = sum; for (int i = n - 1; i >= 0; i--) { ss -= electors[i]; for (int s = 0; s <= ss; s++) { for (int v = 0; v <= visits; v++) { double p = 0; if (v < visits) { p = (winIfVisited[i] * a[i + 1][s + electors[i]][v + 1] + (100 - winIfVisited[i]) * a[i + 1][s][v + 1]); } p = Math.max(p, winCurrent[i] * a[i + 1][s + electors[i]][v] + (100 - winCurrent[i]) * a[i + 1][s][v]); a[i][s][v] = p * 0.01; } } } return a[0][0][0]; } }
27.029412
110
0.468988
4d61786c097283d0c6660bc46efc9f159faeb2bd
940
package info.novatec.testit.webtester.conditions.syntax; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import org.junit.Test; import info.novatec.testit.webtester.conditions.Condition; public class NotTest { Object object = new Object(); @Test public void trueConditionEvaluatesToFalse() { Not<Object> cut = new Not<>(object -> true); assertThat(cut.test(object)).isFalse(); } @Test public void falseConditionEvaluatesToTrue() { Not<Object> cut = new Not<>(object -> false); assertThat(cut.test(object)).isTrue(); } @Test public void toStringIsGeneratedCorrectly() { Condition<Object> condition = mock(Condition.class); doReturn("condition").when(condition).toString(); assertThat(new Not<>(condition)).hasToString("not(condition)"); } }
26.111111
71
0.689362
96595a532d9717c9fb2e6264b2ab50e0b01985f5
807
public class Bug1429 { public Set<String> getAttributeTuples() { return (Set<String>) (this.attributes == null ? Collections.<String> emptySet() : new HashSet<String>( CollectionUtils.collect(this.attributes.keySet(), new Transformer() { @Override public Object transform(final Object obj) { final String key = (String) obj; final String value = HGXLIFFTypeConfiguration.this.attributes.get(key); String result = key; if (StringUtils.isNotEmpty(value)) { result = result.concat(":").concat(value); } return result; } }))); } }
44.833333
110
0.484511
2113da02664704969c718b1a24ccc9584cd1786d
320
package org.sng.shortener.json; public class AccountOkResponse extends ResponseBase { private final String password; public AccountOkResponse(String password) { super(true, "Your account is opened"); this.password = password; } public String getPassword() { return password; } }
21.333333
53
0.690625
6b851886aac41844d56150b9fd00fb12dd1ecbd4
1,203
package com.dell.doradus.logservice.search.filter; import com.dell.doradus.logservice.ChunkField; import com.dell.doradus.logservice.ChunkInfo; import com.dell.doradus.logservice.ChunkReader; import com.dell.doradus.olap.io.BSTR; import com.dell.doradus.olap.store.BitVector; public class FilterField implements IFilter { private BSTR m_fieldName; private IValuesFilter m_valuesFilter; public FilterField(String field, IValuesFilter valuesFilter) { m_fieldName = new BSTR(field); m_valuesFilter = valuesFilter; } @Override public void check(ChunkReader reader, BitVector docs) { int fieldIndex = reader.getFieldIndex(m_fieldName); if(fieldIndex < 0) return; ChunkField field = reader.getField(fieldIndex); BitVector values = new BitVector(field.getValuesCount()); m_valuesFilter.check(field, values); if(values.isAllBitsCleared()) return; int[] indexes = field.getIndexes(); for(int i = 0; i < indexes.length; i++) { if(values.get(indexes[i])) { docs.set(i); } } } @Override public int check(ChunkInfo info) { return 0; } }
33.416667
69
0.66916
60014432f1f9a1f159cb896e90f0aa89f02afe96
1,395
package org.spoofax.jsglr.client.imploder; import java.io.Serializable; /** * @author Lennart Kats <lennart add lclnet.nl> */ public class LineStartOffsetList implements Serializable { private static final long serialVersionUID = 2435789615135832945L; private static final double EXPECTED_NEWLINES_DIVIDER = 12; private int[] lineStarts; private int lastLineStartOffset; public LineStartOffsetList(String input) { int size = (int) (input.length() / EXPECTED_NEWLINES_DIVIDER) + 1; lineStarts = new int[size]; addLineStartOffset(0); for (int i = 0, max = input.length(); i < max; i++) { if (input.charAt(i) == '\n') addLineStartOffset(i); } } public void addLineStartOffset(int lineStartOffset) { if (lastLineStartOffset == lineStarts.length) { int[] oldLineStarts = lineStarts; lineStarts = new int[lineStarts.length * 2]; System.arraycopy(oldLineStarts, 0, lineStarts, 0, oldLineStarts.length); } lineStarts[lastLineStartOffset++] = lineStartOffset; } public int getLine(int index) { return index + 1; } public int getColumn(int index, int offset) { assert offset >= lineStarts[index]; return offset - lineStarts[index]; } public int getIndex(int offset) { // TODO: Optimize - binary search? for (int i = 0, max = lineStarts.length; i < max; i++) { if (offset > lineStarts[i]) return i; } return 0; } }
25.363636
75
0.697491
5b5de16debb92d1add951484f15955a574cf44e6
7,238
/* * 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.webbeans.web.tomcat7.test; import org.apache.catalina.Context; import org.apache.catalina.connector.Request; import org.apache.catalina.connector.Response; import org.apache.catalina.core.StandardContext; import org.apache.catalina.startup.Tomcat; import org.apache.tomcat.util.http.fileupload.IOUtils; import org.apache.webbeans.config.WebBeansContext; import org.apache.webbeans.spi.ContextsService; import org.apache.webbeans.web.tomcat7.ContextLifecycleListener; import org.junit.Test; import javax.enterprise.context.RequestScoped; import javax.enterprise.context.SessionScoped; import javax.enterprise.inject.spi.BeanManager; import javax.enterprise.inject.spi.CDI; import javax.servlet.ServletRequestEvent; import java.io.File; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Writer; import java.lang.reflect.Method; import java.util.logging.Level; import java.util.logging.Logger; import static java.util.Arrays.asList; import static org.junit.Assert.assertEquals; public class TomcatNormalScopeProxyFactoryTest { private static final Logger log = Logger.getLogger(TomcatNormalScopeProxyFactoryTest.class.getName()); @Test public void checkDeserialisation() throws Exception { final File base = dir(new File("target/TomcatNormalScopeProxyFactoryTest-" + System.nanoTime())); final File war = createWar(dir(new File(base, "test")), MyWrapper.class, MySessionScoped.class); String sessionId = null; for (final String expected : asList("init", "new")) { final Tomcat tomcat = new Tomcat(); tomcat.setPort(0); tomcat.setBaseDir(base.getAbsolutePath()); final Context ctx = tomcat.addContext("/test", war.getAbsolutePath()); ctx.addLifecycleListener(new ContextLifecycleListener()); // needed for Java9 if (ctx instanceof StandardContext) { ((StandardContext) ctx).setClearReferencesRmiTargets(false); } tomcat.start(); try { Thread thread = Thread.currentThread(); ClassLoader old = thread.getContextClassLoader(); final ClassLoader webappLoader = ctx.getLoader().getClassLoader(); thread.setContextClassLoader(webappLoader); try { // we don't want test type but webapp one...even if named the same final Class<?> webapptype = webappLoader.loadClass(MySessionScoped.class.getName()); final Method setValue = webapptype.getMethod("setValue", String.class); final Method getValue = webapptype.getMethod("getValue"); final Class<?> wrapperType = webappLoader.loadClass(MyWrapper.class.getName()); final Method m = wrapperType.getMethod("getProxy"); final BeanManager bm = CDI.current().getBeanManager(); final Response response = new Response(); response.setConnector(tomcat.getConnector()); response.setCoyoteResponse(new org.apache.coyote.Response()); final Request request = new Request(); request.setContext(ctx); request.setResponse(response); request.setRequestedSessionId(sessionId); final ContextsService contextsService = WebBeansContext.currentInstance().getContextsService(); final ServletRequestEvent startParameter = new ServletRequestEvent(ctx.getServletContext(), request); contextsService.startContext(RequestScoped.class, startParameter); if (request.getSession() != null) { contextsService.startContext(SessionScoped.class, request.getSession()); } { //final Object bean = bm.getReference(bm.resolve(bm.getBeans(webapptype)), webapptype, null); final Object bean = m.invoke(bm.getReference(bm.resolve(bm.getBeans(wrapperType)), wrapperType, null)); assertEquals(expected, getValue.invoke(bean)); setValue.invoke(bean, "new"); assertEquals("new", getValue.invoke(bean)); } sessionId = request.getSession().getId(); contextsService.endContext(RequestScoped.class, startParameter); // don't do to not destroy the instance // contextsService.endContext(SessionScoped.class, request.getSession()); } catch (Exception e) { log.log(Level.SEVERE, "Exception during test execution", e); } finally { thread.setContextClassLoader(old); } } finally { try { tomcat.stop(); } catch (Exception e) { log.log(Level.SEVERE, "This _might_ happen on Java9 currently. I hope it gets soon fixed.", e); } } } } private static File createWar(final File test, final Class<?>... classes) throws IOException { for (final Class<?> clazz : classes) { final String name = clazz.getName().replace('.', '/') + ".class"; final InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(name); if (is == null) { throw new IllegalArgumentException(name); } final File out = new File(test, "WEB-INF/classes/" + name); dir(out.getParentFile()); final OutputStream os = new FileOutputStream(out); IOUtils.copy(is, os); is.close(); os.close(); } final Writer w = new FileWriter(new File(test, "WEB-INF/beans.xml")); w.write("<beans />"); w.close(); return test; } private static File dir(final File file) { file.mkdirs(); return file; } }
40.435754
127
0.612186
d323e140c86a98f82c0d69278847517500f82201
3,499
package nickqiao.com.oahelper; import android.accessibilityservice.AccessibilityService; import android.annotation.TargetApi; import android.os.Build; import android.util.Log; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityNodeInfo; import java.util.List; /** * Created by chenyuqiao on 2017/6/15 . */ public class AutoInstallAccessibility extends AccessibilityService { private static String TAG = "Accessibility"; //AutoInstallAccessibility.class.getSimpleName(); @Override public void onAccessibilityEvent(AccessibilityEvent event){ int eventType = event.getEventType();//事件类型 Log.d(TAG, "onAccessibilityEvent"); switch(eventType){ case AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED:// 通知栏事件 break; case AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED://窗体状态改变 break; case AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED://View获取到焦点 break; case AccessibilityEvent.TYPE_GESTURE_DETECTION_START: break; case AccessibilityEvent.TYPE_GESTURE_DETECTION_END: break; case AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED: break; case AccessibilityEvent.TYPE_VIEW_CLICKED: break; case AccessibilityEvent.TYPE_VIEW_TEXT_CHANGED: break; case AccessibilityEvent.TYPE_VIEW_SCROLLED: break; case AccessibilityEvent.TYPE_VIEW_TEXT_SELECTION_CHANGED: break; } for(CharSequence txt : event.getText()){ Log.e(TAG, "text:" + txt);//输出当前事件包含的文本信息 } try{ // findAndPerformActionButton("继续"); // findAndPerformActionButton("安装"); // findAndPerformActionButton("下一步"); // findAndPerformActionButton("打开"); findAndPerformActionTextView("继续"); findAndPerformActionTextView("下一步"); findAndPerformActionTextView("安装"); findAndPerformActionTextView("打开"); }catch(Exception e){ } } @Override public void onInterrupt(){ } @TargetApi(Build.VERSION_CODES.JELLY_BEAN) private void findAndPerformActionButton(String text){ if(getRootInActiveWindow() == null)//取得当前激活窗体的根节点 return; //通过文字找到当前的节点 List<AccessibilityNodeInfo> nodes = getRootInActiveWindow().findAccessibilityNodeInfosByText(text); for(int i = 0; i < nodes.size(); i++){ AccessibilityNodeInfo node = nodes.get(i); // 执行点击行为 if(node.getClassName().equals("android.widget.Button") && node.isEnabled()){ node.performAction(AccessibilityNodeInfo.ACTION_CLICK); } } } @TargetApi(Build.VERSION_CODES.JELLY_BEAN) private void findAndPerformActionTextView(String text){ if(getRootInActiveWindow() == null) return; //通过文字找到当前的节点 List<AccessibilityNodeInfo> nodes = getRootInActiveWindow().findAccessibilityNodeInfosByText(text); for(int i = 0; i < nodes.size(); i++){ AccessibilityNodeInfo node = nodes.get(i); // 执行按钮点击行为 if(node.getClassName().equals("android.widget.TextView") && node.isEnabled()){ node.performAction(AccessibilityNodeInfo.ACTION_CLICK); } } } }
36.072165
107
0.638468
536ead215b963002d8f2d49ddec0615e83346eda
4,513
/* * 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.geode.redis.internal.executor.sortedset; import java.util.List; import org.apache.geode.cache.Region; import org.apache.geode.cache.Region.Entry; import org.apache.geode.cache.query.Query; import org.apache.geode.cache.query.SelectResults; import org.apache.geode.cache.query.Struct; import org.apache.geode.redis.internal.ByteArrayWrapper; import org.apache.geode.redis.internal.Coder; import org.apache.geode.redis.internal.Command; import org.apache.geode.redis.internal.DoubleWrapper; import org.apache.geode.redis.internal.ExecutionHandlerContext; import org.apache.geode.redis.internal.RedisConstants.ArityDef; import org.apache.geode.redis.internal.RedisDataType; import org.apache.geode.redis.internal.executor.SortedSetQuery; public class ZRemRangeByRankExecutor extends SortedSetExecutor { private final int NONE_REMOVED = 0; private final String ERROR_NOT_NUMERIC = "The index provided is not numeric"; @Override public void executeCommand(Command command, ExecutionHandlerContext context) { List<byte[]> commandElems = command.getProcessedCommand(); if (commandElems.size() < 4) { command.setResponse( Coder.getErrorResponse(context.getByteBufAllocator(), ArityDef.ZREMRANGEBYRANK)); return; } ByteArrayWrapper key = command.getKey(); checkDataType(key, RedisDataType.REDIS_SORTEDSET, context); Region<ByteArrayWrapper, DoubleWrapper> keyRegion = getRegion(context, key); if (keyRegion == null) { command.setResponse(Coder.getIntegerResponse(context.getByteBufAllocator(), NONE_REMOVED)); return; } int startRank; int stopRank; try { startRank = Coder.bytesToInt(commandElems.get(2)); stopRank = Coder.bytesToInt(commandElems.get(3)); } catch (NumberFormatException e) { command.setResponse(Coder.getErrorResponse(context.getByteBufAllocator(), ERROR_NOT_NUMERIC)); return; } int sSetSize = keyRegion.size(); startRank = getBoundedStartIndex(startRank, sSetSize); stopRank = getBoundedEndIndex(stopRank, sSetSize); if (stopRank > sSetSize - 1) { stopRank = sSetSize - 1; } if (startRank > stopRank) { command.setResponse(Coder.getIntegerResponse(context.getByteBufAllocator(), 0)); return; } int numRemoved = 0; List<?> removeList = null; try { if (startRank == 0 && stopRank == sSetSize - 1) { numRemoved = keyRegion.size(); context.getRegionProvider().removeKey(key); } else { removeList = getRemoveKeys(context, key, startRank, stopRank); } } catch (Exception e) { throw new RuntimeException(e); } if (removeList != null) { for (Object entry : removeList) { ByteArrayWrapper removeKey; if (entry instanceof Entry) { removeKey = (ByteArrayWrapper) ((Entry<?, ?>) entry).getKey(); } else { removeKey = (ByteArrayWrapper) ((Struct) entry).getFieldValues()[0]; } Object oldVal = keyRegion.remove(removeKey); if (oldVal != null) { numRemoved++; } } if (keyRegion.isEmpty()) { context.getRegionProvider().removeKey(key); } } command.setResponse(Coder.getIntegerResponse(context.getByteBufAllocator(), numRemoved)); } private List<?> getRemoveKeys(ExecutionHandlerContext context, ByteArrayWrapper key, int startRank, int stopRank) throws Exception { Query query = getQuery(key, SortedSetQuery.ZREMRANGEBYRANK, context); Object[] params = {stopRank + 1}; SelectResults<?> results = (SelectResults<?>) query.execute(params); return results.asList().subList(startRank, stopRank + 1); } }
35.81746
100
0.710392
a33c89dcd654def2b056ed69a01f2124456064d7
10,750
package com.ralfbox.quickdialog; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.res.Resources; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.StringRes; import android.support.v4.app.DialogFragment; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v7.app.AlertDialog; import android.util.Log; import com.ralfbox.quickdialog.core.CallResultQuickDialogEngineer; import java.lang.reflect.Constructor; /** * @author Rafal Pudelko * Created by Admin on 30.08.2016. */ public class QuickDialog extends DialogFragment implements DialogInterface.OnClickListener{ private static final String ARG_TITLE = "qd-title"; private static final String ARG_MESSAGE = "qd-message"; private static final String ARG_CANCELLABLE = "qd-cancellable"; private static final String ARG_POSITIVE_BUTTON = "qd-bt-positive"; private static final String ARG_NEGATIVE_BUTTON = "qd-bt-negative"; private static final String ARG_NEUTRAL_BUTTON = "qd-bt-neutral"; private static final String ARG_STYLE = "qd-style"; private static final String ARG_RESULT_TO_ACTIVITY = "qd-resutl-to-activity"; private static final String ARG_FRAGMENT_ID = "qd-fragment-id"; private static final String ARG_FRAGMENT_TAG = "qd-fragment-tag"; private static final String ARG_REQUEST_TAG = "qd-tag-quick-alert"; private static final String ARG_FINISH_ACTIVITY_IF_POSITIVE_CLICKED = "qd-finish-positive"; private static final String ARG_FINISH_ACTIVITY_IF_NEGATIVE_CLICKED = "qd-finish-negative"; private static final String ARG_FINISH_ACTIVITY_IF_NEUTRAL_CLICKED = "qd-finish-neutral"; private static final String ARG_CONTROLLER = "qd-controllerQD"; private static final String TAG = QuickDialog.class.getSimpleName(); private String requestTag; private boolean resultToActivity; private String resultFragmentTag; private int resultFragmentId; private ControllerQD controllerQD; @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { Bundle args = getArguments(); String controolerNameClass = args.getString(ARG_CONTROLLER); if (controolerNameClass != null) createController(controolerNameClass); init(args); if (controllerQD != null) controllerQD.onCreate(this, savedInstanceState); return buildDialog(savedInstanceState, args).create(); } private void init(Bundle args) { setCancelable(args.getBoolean(ARG_CANCELLABLE, true)); requestTag = args.getString(ARG_REQUEST_TAG); resultToActivity = args.getBoolean(ARG_RESULT_TO_ACTIVITY, true); if (!resultToActivity){ if (args.containsKey(ARG_FRAGMENT_TAG)) resultFragmentTag = args.getString(ARG_FRAGMENT_TAG); else resultFragmentId = args.getInt(ARG_FRAGMENT_ID); } } private AlertDialog.Builder buildDialog(Bundle savedInstanceState, Bundle args){ CharSequence tmp; //MyBundle args = new MyBundle(getContext(), args); AlertDialog.Builder ret = args.containsKey(ARG_STYLE) ? new AlertDialog.Builder(getActivity(), args.getInt(ARG_STYLE)) : new AlertDialog.Builder(getActivity()); if ( (tmp = args.getCharSequence(ARG_TITLE)) != null) ret.setTitle(tmp); if ( (tmp = args.getCharSequence(ARG_MESSAGE)) != null) ret.setMessage(tmp); if ( (tmp = args.getCharSequence(ARG_POSITIVE_BUTTON)) != null) ret.setPositiveButton(tmp, this); if ( (tmp = args.getCharSequence(ARG_NEGATIVE_BUTTON)) != null) ret.setNegativeButton(tmp, this); if ( (tmp = args.getCharSequence(ARG_NEUTRAL_BUTTON)) != null) ret.setNeutralButton(tmp, this); if (controllerQD != null) ret = controllerQD.onCreateBuilder(ret, savedInstanceState); return ret; } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (controllerQD != null) controllerQD.onSaveInstanceState(outState); } @Override public void onPause() { if (controllerQD != null) controllerQD.onPause(); super.onPause(); } @Override public void onResume() { super.onResume(); if (controllerQD != null) controllerQD.onResume(); } @Override public void onClick(DialogInterface dialog, int which) { if ( (which == DialogInterface.BUTTON_POSITIVE && getArguments().getBoolean(ARG_FINISH_ACTIVITY_IF_POSITIVE_CLICKED, false)) || (which == DialogInterface.BUTTON_NEGATIVE && getArguments().getBoolean(ARG_FINISH_ACTIVITY_IF_NEGATIVE_CLICKED, false)) || (which == DialogInterface.BUTTON_NEUTRAL && getArguments().getBoolean(ARG_FINISH_ACTIVITY_IF_NEUTRAL_CLICKED, false))){ getActivity().finish(); }else{ new CallResultQuickDialogEngineer(this, which).execute(); } } public Object getBaseObjectToCallResult() { if (resultToActivity) return getActivity(); if (resultFragmentTag != null) return getFragmentManager().findFragmentByTag(resultFragmentTag); return getFragmentManager().findFragmentById(resultFragmentId); } public String getRequestTag() { return requestTag; } private void createController(String controllerNameClass) { try { Class<?> c = Class.forName(controllerNameClass); Constructor constructor = c.getConstructor(); Object obj = constructor.newInstance(); controllerQD = (ControllerQD) obj; } catch (ClassNotFoundException e) { Log.e(TAG, "Can not found ControllerQD class: " + controllerNameClass); } catch (NoSuchMethodException e) { Log.e(TAG, "Controller must have a constructor without parameters, and must be a public static class, " + e.getMessage()); } catch (IllegalAccessException e) { Log.e(TAG, "Controller constructor must be a public"); } catch (ClassCastException e) { Log.e(TAG, "The controller must inherit " + ControllerQD.class.getSimpleName()); } catch (Exception e) { Log.e(TAG, null, e); } } public ControllerQD getControllerQD() { return controllerQD; } public static class Builder{ private final Resources resources; private final Bundle bundle; private final String tag; public Builder(Context context, String requestTag){ this(context, requestTag, true); } public Builder(Fragment fragment, String requestTag){ this(fragment.getContext(), requestTag, false); String tagFragment = fragment.getTag(); if (tagFragment == null) bundle.putInt(ARG_FRAGMENT_ID, fragment.getId()); else bundle.putString(ARG_FRAGMENT_TAG, tagFragment); } private Builder(Context context, String tag, boolean toActivity) { resources = context.getResources(); this.tag = tag; bundle = new Bundle(); bundle.putBoolean(ARG_RESULT_TO_ACTIVITY, true); bundle.putString(ARG_REQUEST_TAG, tag); bundle.putBoolean(ARG_RESULT_TO_ACTIVITY, toActivity); } public Builder title(CharSequence title){ return putCharSequence(ARG_TITLE, title); } public Builder title(@StringRes int title){ return title(getText(title)); } public Builder message(CharSequence message) { return putCharSequence(ARG_MESSAGE, message); } public Builder message(@StringRes int message){ return message(getText(message)); } public Builder positiveButton(CharSequence positiveButton) { return putCharSequence(ARG_POSITIVE_BUTTON, positiveButton); } public Builder positiveButton(@StringRes int positiveButton) { return positiveButton(getText(positiveButton)); } public Builder negativeButton(CharSequence negativeButton) { return putCharSequence(ARG_NEGATIVE_BUTTON, negativeButton); } public Builder negativeButton(@StringRes int negativeButton) { return negativeButton(getText(negativeButton)); } public Builder neutralButton(CharSequence neutralButton) { return putCharSequence(ARG_NEUTRAL_BUTTON, neutralButton); } public Builder neutralButton(@StringRes int neutralButton) { return neutralButton(getText(neutralButton)); } public Builder finishActivityIfPositiveBTClicked(){ bundle.putBoolean(ARG_FINISH_ACTIVITY_IF_POSITIVE_CLICKED, true); return this; } public Builder finishActivityIfNegativeBTClicked(){ bundle.putBoolean(ARG_FINISH_ACTIVITY_IF_NEGATIVE_CLICKED, true); return this; } public Builder finishActivityIfNeutralBTClicked(){ bundle.putBoolean(ARG_FINISH_ACTIVITY_IF_NEUTRAL_CLICKED, true); return this; } public Builder cancelable(boolean cancelable) { bundle.putBoolean(ARG_CANCELLABLE, cancelable); return this; } public Builder controller(Class<? extends ControllerQD> controllerClass){ bundle.putString(ARG_CONTROLLER, controllerClass.getName()); return this; } public Bundle getBundle(){ return bundle; } public Builder putAnyCharSequence(String key, CharSequence value) { bundle.putCharSequence(key, value); return this; } public Builder putAnyString(String key, String value) { bundle.putString(key, value); return this; } public Builder putAnyInt(String key, int value) { bundle.putInt(key, value); return this; } public QuickDialog build(){ QuickDialog ret = new QuickDialog(); ret.setArguments(bundle); return ret; } public void show(FragmentManager fragmentManager){ build().show(fragmentManager, tag); } private Builder putCharSequence(String key, CharSequence text) { bundle.putCharSequence(key, text); return this; } private CharSequence getText(@StringRes int id){ return resources.getText(id); } } }
36.073826
138
0.665116
9018fd08bdf2aa8783dce40cff84f32b9e948ee7
249
package cn.micro.biz.service.unified; import cn.micro.biz.entity.unified.AppEntity; import com.baomidou.mybatisplus.extension.service.IService; /** * App Service * * @author lry */ public interface IAppService extends IService<AppEntity> { }
17.785714
59
0.763052
ce69daf25904865b10c3b1aab686a895d6c6995b
1,623
// ============================================================================ // // Copyright (C) 2006-2021 Talend Inc. - www.talend.com // // This source code is available under agreement available at // %InstallDIR%\features\org.talend.rcp.branding.%PRODUCTNAME%\%PRODUCTNAME%license.txt // // You should have received a copy of the agreement // along with this program; if not, write to Talend SA // 9 rue Pages 92150 Suresnes, France // // ============================================================================ package org.talend.dataquality.record.linkage.ui.section; import org.eclipse.swt.custom.CTabFolder; import org.eclipse.swt.custom.CTabFolderRenderer; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; /** * DOC yyi MatchRuleCTabFolderRenderer class global comment. Detailled comment */ public class MatchRuleCTabFolderRenderer extends CTabFolderRenderer { public MatchRuleCTabFolderRenderer(CTabFolder parent) { super(parent); } @Override protected Point computeSize(int part, int state, GC gc, int wHint, int hHint) { // resize width if (part == CTabFolderRenderer.PART_MAX_BUTTON) { int width = 0, height = 0; height = 18; width = 20; Rectangle trim = computeTrim(part, state, 0, 0, width, height); width = trim.width; height = trim.height; return new Point(width, height); } return super.computeSize(part, state, gc, wHint, hHint); } }
36.066667
88
0.600123
b7bc57e780040e54882505dcdc2302d1f4b3ad51
9,704
/* * 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 liquibase.lockservice; import static org.ngrinder.common.util.NoOp.noOp; import java.text.DateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import liquibase.database.Database; import liquibase.exception.DatabaseException; import liquibase.exception.LockException; import liquibase.exception.UnexpectedLiquibaseException; import liquibase.executor.Executor; import liquibase.executor.ExecutorService; import liquibase.logging.LogFactory; import liquibase.statement.SqlStatement; import liquibase.statement.core.LockExDatabaseChangeLogStatement; import liquibase.statement.core.RawSqlStatement; import liquibase.statement.core.SelectFromDatabaseChangeLogLockStatement; import liquibase.statement.core.UnlockDatabaseChangeLogStatement; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Extended {@link LockService} to use 'T' or 'F' for the lock table's boolean * column. * * @author JunHo Yoon * @since 3.0 */ public final class LockServiceEx { private final Logger LOGGER = LoggerFactory.getLogger(LockServiceEx.class); private Database database; private boolean hasChangeLogLock = false; private long changeLogLockWaitTime = 1000 * 60 * 5; // default to 5 mins private long changeLogLocRecheckTime = 1000 * 10; // default to every 10 // seconds private static Map<Database, LockServiceEx> instances = new ConcurrentHashMap<Database, LockServiceEx>(); private LockServiceEx(Database database) { this.database = database; } /** * Get {@link LockServiceEx} instance. * * @param database * corresponding database instance * @return {@link LockServiceEx} instance */ public static LockServiceEx getInstance(Database database) { if (!instances.containsKey(database)) { instances.put(database, new LockServiceEx(database)); } return instances.get(database); } public void setChangeLogLockWaitTime(long changeLogLockWaitTime) { this.changeLogLockWaitTime = changeLogLockWaitTime; } public void setChangeLogLockRecheckTime(long changeLogLocRecheckTime) { this.changeLogLocRecheckTime = changeLogLocRecheckTime; } /** * Check if it has change log lock. * * @return true if it has the change lock */ public boolean hasChangeLogLock() { return hasChangeLogLock; } /** * Wait for lock. * * @throws LockException * occurs when lock manipulation is failed. */ public void waitForLock() throws LockException { boolean locked = false; long timeToGiveUp = new Date().getTime() + changeLogLockWaitTime; while (!locked && new Date().getTime() < timeToGiveUp) { locked = acquireLock(); if (!locked) { LOGGER.info("Waiting for changelog lock...."); try { Thread.sleep(changeLogLocRecheckTime); } catch (InterruptedException e) { noOp(); } } } if (!locked) { DatabaseChangeLogLock[] locks = listLocks(); String lockedBy; if (locks.length > 0) { DatabaseChangeLogLock lock = locks[0]; lockedBy = lock.getLockedBy() + " since " + DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT).format( lock.getLockGranted()); } else { lockedBy = "UNKNOWN"; } throw new LockException("Could not acquire change log lock. Currently locked by " + lockedBy); } } /** * Acquire lock. Instead of liquibase implementation, nGrinder added the * type resolution for boolean value. * * @return true if successful * @throws LockException * occurs when the lock aquire is failed. */ public boolean acquireLock() throws LockException { if (hasChangeLogLock) { return true; } Executor executor = ExecutorService.getInstance().getExecutor(database); try { database.rollback(); database.checkDatabaseChangeLogLockTable(); Object lockObject = (Object) ExecutorService.getInstance().getExecutor(database) .queryForObject(new SelectFromDatabaseChangeLogLockStatement("LOCKED"), Object.class); if (checkReturnValue(lockObject)) { // To here return false; } else { executor.comment("Lock Database"); int rowsUpdated = executor.update(new LockExDatabaseChangeLogStatement()); if (rowsUpdated > 1) { throw new LockException("Did not update change log lock correctly"); } if (rowsUpdated == 0) { // another node was faster return false; } database.commit(); LOGGER.info("Successfully acquired change log lock"); hasChangeLogLock = true; database.setCanCacheLiquibaseTableInfo(true); return true; } } catch (Exception e) { throw new LockException(e); } finally { try { database.rollback(); } catch (DatabaseException e) { noOp(); } } } /** * Check return value is boolean or not. * * @param value * returnValue * @return true if true */ public boolean checkReturnValue(Object value) { if (value instanceof String) { String trim = StringUtils.trim((String) value); if ("T".equals(trim)) { return true; } else if ("F".equals(trim) || StringUtils.isEmpty((String) value) || "0".equals(trim)) { return false; } else { throw new UnexpectedLiquibaseException("Unknown boolean value: " + value); } } else if (value == null) { return false; } else if (value instanceof Integer) { return !(Integer.valueOf(0).equals(value)); } else if (value instanceof Long) { return !(Long.valueOf(0).equals(value)); } else if (value instanceof Boolean) { return ((Boolean) value); } else { return false; } } /** * Release Lock. * * @throws LockException * exception. */ public void releaseLock() throws LockException { Executor executor = ExecutorService.getInstance().getExecutor(database); try { if (database.hasDatabaseChangeLogLockTable()) { executor.comment("Release Database Lock"); database.rollback(); int updatedRows = executor.update(new UnlockDatabaseChangeLogStatement()); if (updatedRows != 1) { throw new LockException("Did not update change log lock correctly.\n\n" + updatedRows + " rows were updated instead of the expected 1 row using executor " + executor.getClass().getName() + " there are " + executor.queryForInt(new RawSqlStatement("select count(*) from " + database.getDatabaseChangeLogLockTableName())) + " rows in the table"); } database.commit(); hasChangeLogLock = false; instances.remove(this.database); database.setCanCacheLiquibaseTableInfo(false); LOGGER.info("Successfully released change log lock"); } } catch (Exception e) { throw new LockException(e); } finally { try { database.rollback(); } catch (DatabaseException e) { noOp(); } } } /** * List up locks. * * @return {@link DatabaseChangeLogLock} array. * @throws LockException * occurs when lock list up is failed. */ @SuppressWarnings("rawtypes") public DatabaseChangeLogLock[] listLocks() throws LockException { try { if (!database.hasDatabaseChangeLogLockTable()) { return new DatabaseChangeLogLock[0]; } List<DatabaseChangeLogLock> allLocks = new ArrayList<DatabaseChangeLogLock>(); SqlStatement sqlStatement = new SelectFromDatabaseChangeLogLockStatement("ID", "LOCKED", "LOCKGRANTED", "LOCKEDBY"); List<Map> rows = ExecutorService.getInstance().getExecutor(database).queryForList(sqlStatement); for (Map columnMap : rows) { Object lockedValue = columnMap.get("LOCKED"); Boolean locked; if (lockedValue instanceof Number) { locked = ((Number) lockedValue).intValue() == 1; } else if (lockedValue instanceof String) { locked = ("T".equals(lockedValue)); } else { locked = (Boolean) lockedValue; } if (locked != null && locked) { allLocks.add(new DatabaseChangeLogLock(((Number) columnMap.get("ID")).intValue(), (Date) columnMap .get("LOCKGRANTED"), (String) columnMap.get("LOCKEDBY"))); } } return allLocks.toArray(new DatabaseChangeLogLock[allLocks.size()]); } catch (Exception e) { throw new LockException(e); } } /** * Releases whatever locks are on the database change log table. * * @throws LockException * exception * @throws DatabaseException * exception */ public void forceReleaseLock() throws LockException, DatabaseException { database.checkDatabaseChangeLogLockTable(); releaseLock(); /* * try { releaseLock(); } catch (LockException e) { // ignore ? * LoggerFactory.getLogger().info("Ignored exception in forceReleaseLock: " * + e.getMessage()); } */ } /** * Clears information the lock handler knows about the tables. Should only * be called by Liquibase internal calls */ public void reset() { hasChangeLogLock = false; } /** * Reset all locks. */ public static void resetAll() { for (Map.Entry<Database, LockServiceEx> entity : instances.entrySet()) { entity.getValue().reset(); } } }
28.880952
106
0.69425
9d9ac28a563344d8093631ced527fb6d6785258b
1,149
package org.twocentsforthoughts.problems.common; import java.util.Map; import java.util.TreeMap; /** * Simple utility that generates the fibonacci sequence; * @author Andre * */ public class FibonnaciCalculator { class NumberCache { Map<Integer, Long> termCache = new TreeMap<Integer, Long>(); public long getTermTermValue(int term) { return termCache.get(term); } public boolean isTermCalculated(int term) { return termCache.containsKey(term); } public void putTermValue(int term, long value) { termCache.put(term, value); } } NumberCache cache = new NumberCache(); public long calculateTerm(int n) { if (n == 0) { return 0; } else if (n == 1 || n == 2) { return 1; } else { if (!cache.isTermCalculated(n)) { long firstValue = calculateTerm(n - 1); long secondValue = calculateTerm(n - 2); cache.putTermValue(n, firstValue + secondValue); } return cache.getTermTermValue(n); } } }
23.44898
68
0.563098
f5d8ad3421126aa8bae3f5f8ac7134fea0a5eaf1
1,185
package com.vingcoz.orderadmin.model; public class Customers { private String NAME; private String ADDRESS; private String PLACE; private String PINCODE; private String PHONE_NO; private String EMAIL_ID; private String X_CORD; private String Y_CORD; public Customers(String NAME, String ADDRESS, String PLACE, String PINCODE, String PHONE_NO, String EMAIL_ID, String X_CORD, String Y_CORD) { this.NAME = NAME; this.ADDRESS = ADDRESS; this.PLACE = PLACE; this.PINCODE = PINCODE; this.PHONE_NO = PHONE_NO; this.EMAIL_ID = EMAIL_ID; this.X_CORD = X_CORD; this.Y_CORD = Y_CORD; } public String getName() { return NAME; } public String getAddress() { return ADDRESS; } public String getPlace() { return PLACE; } public String getPincode() { return PINCODE; } public String getPhone_no() { return PHONE_NO; } public String getEmail_id() { return EMAIL_ID; } public String getX_code() { return X_CORD; } public String getBio() { return Y_CORD; } }
20.431034
145
0.609283
2285c00bb172a94c5c30c3bd760821cc129c0f74
4,246
package net.sf.l2j.gameserver.skills; import java.io.File; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import net.sf.l2j.gameserver.model.item.kind.Item; import net.sf.l2j.gameserver.skills.conditions.Condition; import net.sf.l2j.gameserver.templates.StatsSet; import org.w3c.dom.Document; import org.w3c.dom.Node; /** * @author mkizub, JIV */ public final class DocumentItem extends DocumentBase { public class NewItem { public int id; public String type; public String name; public StatsSet set; public int currentLevel; public Item item; } private NewItem _currentItem; private final List<Item> _itemsInFile = new ArrayList<>(); public DocumentItem(File file) { super(file); } @Override protected StatsSet getStatsSet() { return _currentItem.set; } @Override protected String getTableValue(String name) { return _tables.get(name)[_currentItem.currentLevel]; } @Override protected String getTableValue(String name, int idx) { return _tables.get(name)[idx - 1]; } @Override protected void parseDocument(Document doc) { for (Node n = doc.getFirstChild(); n != null; n = n.getNextSibling()) { if ("list".equalsIgnoreCase(n.getNodeName())) { for (Node d = n.getFirstChild(); d != null; d = d.getNextSibling()) { if ("item".equalsIgnoreCase(d.getNodeName())) { try { _currentItem = new NewItem(); parseItem(d); _itemsInFile.add(_currentItem.item); resetTable(); } catch (Exception e) { _log.log(Level.WARNING, "Cannot create item " + _currentItem.id, e); } } } } } } protected void parseItem(Node n) throws InvocationTargetException { int itemId = Integer.parseInt(n.getAttributes().getNamedItem("id").getNodeValue()); String className = n.getAttributes().getNamedItem("type").getNodeValue(); String itemName = n.getAttributes().getNamedItem("name").getNodeValue(); _currentItem.id = itemId; _currentItem.name = itemName; _currentItem.type = className; _currentItem.set = new StatsSet(); _currentItem.set.set("item_id", itemId); _currentItem.set.set("name", itemName); Node first = n.getFirstChild(); for (n = first; n != null; n = n.getNextSibling()) { if ("table".equalsIgnoreCase(n.getNodeName())) { if (_currentItem.item != null) throw new IllegalStateException("Item created but table node found! Item " + itemId); parseTable(n); } else if ("set".equalsIgnoreCase(n.getNodeName())) { if (_currentItem.item != null) throw new IllegalStateException("Item created but set node found! Item " + itemId); parseBeanSet(n, _currentItem.set, 1); } else if ("for".equalsIgnoreCase(n.getNodeName())) { makeItem(); parseTemplate(n, _currentItem.item); } else if ("cond".equalsIgnoreCase(n.getNodeName())) { makeItem(); Condition condition = parseCondition(n.getFirstChild(), _currentItem.item); Node msg = n.getAttributes().getNamedItem("msg"); Node msgId = n.getAttributes().getNamedItem("msgId"); if (condition != null && msg != null) condition.setMessage(msg.getNodeValue()); else if (condition != null && msgId != null) { condition.setMessageId(Integer.decode(getValue(msgId.getNodeValue(), null))); Node addName = n.getAttributes().getNamedItem("addName"); if (addName != null && Integer.decode(getValue(msgId.getNodeValue(), null)) > 0) condition.addName(); } _currentItem.item.attach(condition); } } // bah! in this point item doesn't have to be still created makeItem(); } private void makeItem() throws InvocationTargetException { if (_currentItem.item != null) return; // item is already created try { Constructor<?> c = Class.forName("net.sf.l2j.gameserver.model.item.kind." + _currentItem.type).getConstructor(StatsSet.class); _currentItem.item = (Item) c.newInstance(_currentItem.set); } catch (Exception e) { throw new InvocationTargetException(e); } } public List<Item> getItemList() { return _itemsInFile; } }
26.04908
129
0.679463
a6c710622db45e97df423d1e501220c30f53d338
2,113
package lark.db.jsd.template; import lark.db.jsd.Mapper; import lark.db.jsd.result.BuildResult; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Created by Administrator on 2015/11/18. */ class SimpleTemplate implements SqlTemplate { private String sql; private String[] args; public SimpleTemplate(String tpl) { StringBuilder sb = new StringBuilder(); int start = -1; List<String> args = new ArrayList<>(); for (int i=0; i<tpl.length(); i++) { char c = tpl.charAt(i); switch (c) { case '{': if (start == -1) start = i; else sb.append(c); break; case '}': if (start == -1) sb.append(c); else { String arg = tpl.substring(start + 1, i); args.add(arg); sb.append('?'); start = -1; } break; default: if (start == -1) sb.append(c); break; } } this.sql = sb.toString(); this.args = args.toArray(new String[0]); } @Override public BuildResult execute(Object obj) { List<Object> args; if (obj instanceof Map) { args = executeByMap((Map)obj); } else { Mapper.EntityInfo info = Mapper.getEntityInfo(obj.getClass()); args = executeByEntity(info, obj); } return new BuildResult(sql, args); } private List<Object> executeByMap(Map obj) { List<Object> list = new ArrayList<>(args.length); for (String arg : args) { list.add(obj.get(arg)); } return list; } private List<Object> executeByEntity(Mapper.EntityInfo info, Object obj) { List<Object> list = new ArrayList<>(args.length); for (String arg : args) { list.add(info.getValue(obj, arg)); } return list; } }
27.802632
78
0.488405
ec3d607b67efe375872114998662ed998e76a715
64
package java_solution.ap_1; public class WordsWithout { }
10.666667
27
0.734375
60b18e965fcab8faf8439eb48fa334b46434525f
3,601
package ru.stqa.pft.addressbook.tests.contacts.withgroups; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import ru.stqa.pft.addressbook.models.ContactData; import ru.stqa.pft.addressbook.models.Contacts; import ru.stqa.pft.addressbook.models.GroupData; import ru.stqa.pft.addressbook.models.Groups; import ru.stqa.pft.addressbook.tests.TestBase; import java.util.stream.Collectors; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.MatcherAssert.assertThat; public class ContactFromGroupRemovalTests extends TestBase { private ContactData contact; private GroupData group; @BeforeMethod public void ensurePreconditions() { GroupData groupData = new GroupData() .withId(app.group().id()) .withName("Looney Tunes"); ContactData contactData = new ContactData() .withId(app.contact().id()) .withFirstName("Bunny") .withLastName("Bugs"); Contacts contacts = app.db().contacts(); Groups groups = app.db().groups(); // Проверяем наличие контактов (что в приложении есть хотя бы один контакт) // Если нет, то создаем через бд (с проверкой) if (contacts.isEmpty()) { app.db().addContact(contactData); } // Проверяем наличие групп (что в приложении есть хотя бы одна группа) // Если нет, то создаем через бд (с проверкой) if (groups.isEmpty()) { app.db().addGroup(groupData); } // Проверяем, что существуют контакты, которые можно удалить из группы // Если есть, то возвращаем такой контакт и любую группу, в которую он добавлен if (!(contacts.isEmpty() && groups.isEmpty())) { for (ContactData c : contacts) { if (!c.getGroups().isEmpty()) { contact = c; group = c.getGroups().iterator().next(); return; } } } // Если все контакты удалены из всех групп, то берем любой контакт и добавляем в любую группу через интерфейс contact = app.db().contacts().iterator().next(); group = app.db().groups().iterator().next(); app.goTo().homePage(); // Обновляем страницу, чтоб визуально получить актуальный список контактов app.goTo().refreshPage(); app.contact().addToGroup(contact, group); } @Test public void testContactGroupDeletion() { // Hibernate кеширует результаты, поэтому получаем список контактов из бд и обновляем данные по нашему контакту Contacts before = app.db().contacts(); contact = before.stream().filter(c -> (c.getId() == contact.getId())).collect(Collectors.toSet()).iterator().next(); // Получаем список групп контакта Groups groupsBefore = contact.getGroups(); // Переходим на страницу с контактами app.goTo().homePage(); // Обновляем страницу, чтоб визуально получить актуальный список контактов app.goTo().refreshPage(); // Удаляем контакт из группы app.contact().removeFromGroup(contact, group); // Hibernate кеширует результаты, поэтому снова получаем список контактов из бд и обновляем данные по нашему контакту Contacts after = app.db().contacts(); contact = after.stream().filter(c -> (c.getId() == contact.getId())).collect(Collectors.toSet()).iterator().next(); // Сравниваем размер списков групп контакта до и после удаления assertThat(contact.getGroups().size(), equalTo(groupsBefore.size() - 1)); // Получаем список групп контакта Groups groupsAfter = contact.getGroups(); // Сравниваем изменившиеся списки групп контакта assertThat(groupsAfter, equalTo(groupsBefore.without(group))); } }
37.123711
121
0.692585
cc31b60bf249a048e47b14d6760d893f248de7b7
3,613
package com.snezana.doctorpractice.dto; import org.hibernate.validator.constraints.NotEmpty; /** * Mail DTO (Data Transfer Object) class message format for sending email from a Spring * Boot app (with annotations used for field validation) */ public class MailDto { private Long id; private String userEmail; private String username; private String firstLastName; private String telephone; @NotEmpty private String subjectEmail; @NotEmpty private String messageEmail; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getSubjectEmail() { return subjectEmail; } public void setSubjectEmail(String subjectEmail) { this.subjectEmail = subjectEmail; } public String getMessageEmail() { return messageEmail; } public void setMessageEmail(String messageEmail) { this.messageEmail = messageEmail; } public String getUserEmail() { return userEmail; } public void setUserEmail(String userEmail) { this.userEmail = userEmail; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getFirstLastName() { return firstLastName; } public void setFirstLastName(String firstLastName) { this.firstLastName = firstLastName; } public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((firstLastName == null) ? 0 : firstLastName.hashCode()); result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((messageEmail == null) ? 0 : messageEmail.hashCode()); result = prime * result + ((subjectEmail == null) ? 0 : subjectEmail.hashCode()); result = prime * result + ((telephone == null) ? 0 : telephone.hashCode()); result = prime * result + ((userEmail == null) ? 0 : userEmail.hashCode()); result = prime * result + ((username == null) ? 0 : username.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; MailDto other = (MailDto) obj; if (firstLastName == null) { if (other.firstLastName != null) return false; } else if (!firstLastName.equals(other.firstLastName)) return false; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (messageEmail == null) { if (other.messageEmail != null) return false; } else if (!messageEmail.equals(other.messageEmail)) return false; if (subjectEmail == null) { if (other.subjectEmail != null) return false; } else if (!subjectEmail.equals(other.subjectEmail)) return false; if (telephone == null) { if (other.telephone != null) return false; } else if (!telephone.equals(other.telephone)) return false; if (userEmail == null) { if (other.userEmail != null) return false; } else if (!userEmail.equals(other.userEmail)) return false; if (username == null) { if (other.username != null) return false; } else if (!username.equals(other.username)) return false; return true; } @Override public String toString() { return "MailDto [id=" + id + ", userEmail=" + userEmail + ", username=" + username + ", firstLastName=" + firstLastName + ", telephone=" + telephone + ", subjectEmail=" + subjectEmail + ", messageEmail=" + messageEmail + "]"; } }
23.769737
105
0.675062
526d60485c49301646987d4f2148b1050088506d
1,223
/* Generated SBE (Simple Binary Encoding) message codec */ package sbe.msg; public enum AdminTypeEnum { SimulationComplete((short)0), WarmUpComplete((short)1), LOB((short)2), ShutDown((short)3), VWAP((short)4), StartLOB((short)5), EndLOB((short)6), BestBidOfferRequest((short)7), StartMessage((short)8), EndMessage((short)9), NULL_VAL((short)255); private final short value; AdminTypeEnum(final short value) { this.value = value; } public short value() { return value; } public static AdminTypeEnum get(final short value) { switch (value) { case 0: return SimulationComplete; case 1: return WarmUpComplete; case 2: return LOB; case 3: return ShutDown; case 4: return VWAP; case 5: return StartLOB; case 6: return EndLOB; case 7: return BestBidOfferRequest; case 8: return StartMessage; case 9: return EndMessage; } if ((short)255 == value) { return NULL_VAL; } throw new IllegalArgumentException("Unknown value: " + value); } }
22.648148
70
0.566639
3086d7616a9bfbad5171e7663b4e9f4fc6f50555
3,722
/* * Copyright (c) 2017 One Hill Technologies, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.onehilltech.promises; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.support.annotation.NonNull; /** * Proxy that run the OnResolved handler on the UI thread. * * If the handler is already on the UI thread, then the handler continues processing * the execute value on the same thread. If the handler is not on the UI thread, then * it will run on the UI thread. * * This design make is so the caller does not experience any context switches if the * root promise starts on the UI thread, and the handler needs to run on the UI thread. */ public final class ResolvedOnUIThread { /** * Factory method that supports using a lambda function. It also removes the need * for using the new method so its usage in the Promise statements reads more fluid. * * @param onResolved The real handler * @param <T> Parameter type of the current value * @param <U> Parameter type of the next value * @return Promise.OnResolved object */ public static <T, U> OnResolvedExecutor<T, U> onUiThread (@NonNull OnResolved<T, U> onResolved) { return new Executor <> (onResolved); } /** * Private implementation of the executor. * * @param <T> * @param <U> */ private static class Executor <T, U> extends OnResolvedExecutor <T, U> { /// Mock continuation promise. private ContinuationPromise cont_ = new ContinuationPromise (); /// The value of the settlement. private T value_; /** * Initializing constructor. * * @param onResolved The real handler */ Executor (OnResolved<T, U> onResolved) { super (onResolved); } @SuppressWarnings ("unchecked") @Override void execute (java.util.concurrent.Executor executor, Object obj, ContinuationPromise continuation) { if (this.isUiThread ()) { // We are already running on the UI thread. Let's just continue with the // continuation promise so the original caller does not see any disruption. T value = (T)obj; this.execute (value, continuation); } else { // Schedule the rejection handler to run on the UI thread. this.value_ = (T)obj; this.cont_ = continuation; this.runOnUiThread (); } } private boolean isUiThread () { return Looper.getMainLooper ().equals (Looper.myLooper ()); } /** * Run the handler on the UI thread. */ private void runOnUiThread () { Message message = uiHandler_.obtainMessage (0, this); message.sendToTarget (); } /** * Implementation of the Looper that runs the handler on the UI thread. */ private static final Handler uiHandler_ = new Handler (Looper.getMainLooper ()) { @SuppressWarnings ("unchecked") @Override public void handleMessage (Message msg) { Executor onUIThread = (Executor) msg.obj; onUIThread.execute (onUIThread.value_, onUIThread.cont_); } }; } }
30.260163
103
0.658786
884c011a79e2ee68a5825b681970e46b9b70bcf9
1,694
/* * Copyright 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.gwtproject.i18n.client; import com.google.gwt.junit.client.GWTTestCase; import org.gwtproject.i18n.shared.cldr.LocaleInfo; import org.gwtproject.i18n.shared.cldr.LocalizedNames; /** Tests LocalizedNames defaults. */ public class LocalizedNames_default_Test extends GWTTestCase { private LocalizedNames names; @Override public String getModuleName() { return "org.gwtproject.i18n.I18NTest"; } @Override protected void gwtSetUp() throws Exception { names = LocaleInfo.getCurrentLocale().getLocalizedNames(); } /* public void testLikelyRegionCodes() { String[] regionCodes = names.getLikelyRegionCodes(); assertEquals("Default locale should have no likely locales", 0, regionCodes.length); } public void testRegionName() { assertEquals("United States", names.getRegionName("US")); assertEquals("Canada", names.getRegionName("CA")); } public void testSortedRegionCodes() { String[] regionCodes = names.getSortedRegionCodes(); assertTrue("Should have at least 200 region codes", regionCodes.length >= 200); }*/ }
31.37037
80
0.734357
2bee1dd1897d8ba77adf243fa771c4df3f7eeaa6
3,199
package com.krishagni.catissueplus.core.administrative.events; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Set; import org.apache.commons.lang3.BooleanUtils; import com.krishagni.catissueplus.core.administrative.services.ContainerSelectionRule; import com.krishagni.catissueplus.core.biospecimen.events.SpecimenDetail; import com.krishagni.catissueplus.core.common.access.SiteCpPair; public class ContainerCriteria { private SpecimenDetail specimen; private int minFreePositions; private Date reservedLaterThan; private int numContainers; private Set<SiteCpPair> siteCps; private String ruleName; private Map<String, Object> ruleParams = new HashMap<>(); private ContainerSelectionRule rule; public ContainerCriteria() { } public SpecimenDetail specimen() { return specimen; } public void setSpecimen(SpecimenDetail specimen) { this.specimen = specimen; } public ContainerCriteria specimen(SpecimenDetail specimen) { this.specimen = specimen; return this; } public int minFreePositions() { return minFreePositions; } public void setMinFreePositions(int minFreePositions) { this.minFreePositions = minFreePositions; } public ContainerCriteria minFreePositions(int minFreePositions) { this.minFreePositions = minFreePositions; return this; } public int getRequiredPositions(Boolean aliquotsInSameContainer) { return BooleanUtils.isTrue(aliquotsInSameContainer) && minFreePositions() > 1 ? minFreePositions() : 1; } public Date reservedLaterThan() { return reservedLaterThan; } public ContainerCriteria reservedLaterThan(Date reservedLaterThan) { this.reservedLaterThan = reservedLaterThan; return this; } public int numContainers() { return numContainers <= 0 ? 1 : numContainers; } public ContainerCriteria numContainers(int numContainers) { this.numContainers = numContainers; return this; } public Set<SiteCpPair> siteCps() { return siteCps; } public ContainerCriteria siteCps(Set<SiteCpPair> siteCps) { this.siteCps = siteCps; return this; } public String ruleName() { return ruleName; } public void setRuleName(String ruleName) { this.ruleName = ruleName; } public ContainerCriteria ruleName(String restrictionType) { this.ruleName = restrictionType; return this; } public Map<String, Object> ruleParams() { return ruleParams; } public void setRuleParams(Map<String, Object> ruleParams) { this.ruleParams = ruleParams; } public ContainerCriteria ruleParams(Map<String, Object> restrictionInput) { this.ruleParams = restrictionInput; return this; } public ContainerSelectionRule rule() { return rule; } public ContainerCriteria rule(ContainerSelectionRule restriction) { this.rule = restriction; return this; } public String key() { StringBuilder key = new StringBuilder() .append(specimen.getCpId()).append("#") .append(specimen.getSpecimenClass()).append("#") .append(specimen.getType()).append("#") .append(ruleName); for (Map.Entry<String, Object> kv : ruleParams.entrySet()) { key.append("#").append(kv.getKey()).append(kv.getValue().toString()); } return key.toString(); } }
22.687943
105
0.757424
02207048328b92f4317f77edb1d6ae8a4eaac0af
1,751
package com.ociweb.gl.network; import com.ociweb.gl.api.Builder; import com.ociweb.gl.api.GreenApp; import com.ociweb.gl.api.GreenRuntime; import com.ociweb.gl.api.HTTPResponseService; import com.ociweb.gl.api.HeaderWritable; import com.ociweb.gl.api.Writable; import com.ociweb.pronghorn.network.config.HTTPHeaderDefaults; public class OpenCloseTestServer implements GreenApp { private final Appendable target; private final int port; private final boolean telemetry; private int neverCloseRoute; private int alwaysCloseRoute; public OpenCloseTestServer(int port, boolean telemetry, Appendable target) { this.target = target; this.port = port; this.telemetry = telemetry; } @Override public void declareConfiguration(Builder builder) { if (telemetry) { builder.enableTelemetry(8076); } builder.useHTTP1xServer(port) .setHost("127.0.0.1") .setMaxConnectionBits(3)//only 8 connections .useInsecureServer(); neverCloseRoute = builder.defineRoute().path("neverclose").routeId(); alwaysCloseRoute = builder.defineRoute().path("alwaysclose").routeId(); } @Override public void declareBehavior(GreenRuntime runtime) { HTTPResponseService respClose = runtime.newCommandChannel().newHTTPResponseService(); runtime.addRestListener((r) -> { HeaderWritable headers = (w)->{ w.write(HTTPHeaderDefaults.CONNECTION, "close"); }; return respClose.publishHTTPResponse(r, headers, Writable.NO_OP); }).includeRoutes(alwaysCloseRoute); HTTPResponseService respOpen = runtime.newCommandChannel().newHTTPResponseService(); runtime.addRestListener((r) -> { respOpen.publishHTTPResponse(r, 200); return true; }).includeRoutes(neverCloseRoute); } }
26.530303
87
0.746431
9b60d7b6bf5c3c628bc07ecc1c4788ba144472d9
2,693
package com.necomplus.mvvm.lastfm.adapter; import android.content.Context; import android.content.Intent; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.necomplus.mvvm.lastfm.R; import com.necomplus.mvvm.lastfm.model.Top.Artist; import com.necomplus.mvvm.lastfm.view.TrackActivity; import java.util.ArrayList; public class ArtitsAdapter extends RecyclerView.Adapter<ArtitsAdapter.ViewHolder> { private Context context; ArrayList<Artist> articleArrayList; public ArtitsAdapter(Context context, ArrayList<Artist> articleArrayList) { this.context = context; this.articleArrayList = articleArrayList; } @NonNull @Override public ArtitsAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { View view=LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.artits_list_item,viewGroup,false); return new ViewHolder(view); } @Override public void onBindViewHolder(@NonNull ArtitsAdapter.ViewHolder viewHolder, int i) { Artist artist=articleArrayList.get(i); viewHolder.tvname.setText(artist.getName()); viewHolder.tvplaycount.setText(artist.getListeners()); viewHolder.tvurl.setText(artist.getUrl()); viewHolder.button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Log.e("onBindViewHolder", artist.getName()); Intent intent = new Intent(context, TrackActivity.class); intent.putExtra("name",artist.getName()); intent.putExtra("playcount",artist.getListeners()); intent.putExtra("url",artist.getUrl()); context.startActivity(intent); } }); } @Override public int getItemCount() { return articleArrayList.size(); } public class ViewHolder extends RecyclerView.ViewHolder { private final TextView tvname; private final TextView tvplaycount; private final TextView tvurl; private final Button button; public ViewHolder(@NonNull View itemView) { super(itemView); tvname=(TextView) itemView.findViewById(R.id.tvname); tvplaycount=(TextView) itemView.findViewById(R.id.tvplaycount); tvurl=(TextView) itemView.findViewById(R.id.tvurl); button=(Button) itemView.findViewById(R.id.btn_view_post); } } }
33.246914
113
0.691051
de986a3c58de257965140d171f13b5ce0c2dcc0f
9,392
package com.mall.cloud.console.web.controller.system; import com.mall.cloud.common.annotation.ApplicationAuthorize; import com.mall.cloud.common.annotation.dubbo.DubboConsumerClient; import com.mall.cloud.common.constant.Constants; import com.mall.cloud.common.constant.ScopeType; import com.mall.cloud.common.exception.ConsoleServerException; import com.mall.cloud.common.exception.PassportServerException; import com.mall.cloud.common.persistence.controller.BaseController; import com.mall.cloud.common.restful.DatagridResult; import com.mall.cloud.common.restful.ResponseResult; import com.mall.cloud.common.utils.CheckEmptyUtil; import com.mall.cloud.model.entity.system.RoleInfo; import com.mall.cloud.model.entity.user.AdminUser; import com.mall.cloud.passport.api.param.RequestRoleParam; import com.mall.cloud.passport.api.service.RoleServerService; import org.apache.commons.lang3.StringUtils; import org.springframework.web.bind.annotation.*; import java.time.LocalDateTime; import java.util.List; /** * <p>封装Qicloud项目RoleCenterController类.<br></p> * <p>//TODO...<br></p> * * @author Powered by marklin 2020-10-27 15:26 * @version 1.0.0 * <p>Copyright © 2018-2020 Pivotal Cloud Technology Systems Incorporated. All rights reserved.<br></p> */ @RestController @RequestMapping("/api/console/role/") public class ConsoleRoleController extends BaseController { @DubboConsumerClient private RoleServerService roleServerService; /** * * @param pageSize * @param pageLimit * @param name * @param status * @param scope * @param companyId * @return * @throws PassportServerException */ @ApplicationAuthorize(authorizeResources = false, authorizeScope = ScopeType.WEB) @PostMapping(value = "list", produces = "application/json;charset=UTF-8") public String list( @RequestParam(value = "pageSize", required = false, defaultValue = "1") Integer pageSize, @RequestParam(value = "pageLimit", required = false, defaultValue = "10") Integer pageLimit, @RequestParam(value = "name", required = false) String name, @RequestParam(value = "status", required = false) Integer status, @RequestParam(value = "scope", required = false) Integer scope, @RequestParam(value = "companyId", required = false) String companyId ) throws PassportServerException { ResponseResult result = new ResponseResult(); // [1].用户登录鉴权 AdminUser user = (AdminUser) request.getAttribute(Constants.ADMIN_USER); if (CheckEmptyUtil.isEmpty(user)) { throw new ConsoleServerException("系统繁忙,请稍后再试!"); } // [2] 业务请求处理 try { RequestRoleParam param = new RequestRoleParam(); param.setName(name); param.setCompanyId(companyId); param.setName(name); param.setScope(scope); param.setStatus(status); DatagridResult datagrid = roleServerService.list(pageSize, pageLimit, param); List<RoleInfo> roleList = datagrid.getDataList(); result.putResult("list", roleList); result.putResult("pageCount", datagrid.getPageCount()); result.putResult("pageSize", pageSize); result.putResult("pageLimit", pageLimit); result.putResult("totalPage", datagrid.getTotalPage()); } catch (PassportServerException exception) { logger.error("查询后台用户列表失败:{},{}", user.getId(), exception); result.setError("系统繁忙,请稍后再试"); } return result.parseToJson(result); } /** * 后台管理平台-系统中心-菜单管理-列表 * * @return 返回结果 * @throws PassportServerException */ @ApplicationAuthorize(authorizeResources = false, authorizeScope = ScopeType.WEB) @PostMapping(value = "save", produces = "application/json;charset=UTF-8") public String save(@ModelAttribute RequestRoleParam param) throws PassportServerException { ResponseResult result = new ResponseResult(); // [1].用户登录鉴权 AdminUser user = (AdminUser) request.getAttribute(Constants.ADMIN_USER); if (CheckEmptyUtil.isEmpty(user)) { throw new ConsoleServerException("系统繁忙,请稍后再试!"); } RoleInfo role = new RoleInfo(); role.setMessage(param.getMessage()); role.setCode(param.getCode()); role.setName(param.getName()); role.setScope(param.getScope()); role.setStatus(Constants.YES); role.setIsDelete(Constants.NO); role.setCreateBy(user.getId()); role.setCreateTime(LocalDateTime.now()); role.setUpdateBy(user.getId()); role.setUpdateTime(LocalDateTime.now()); int count = roleServerService.save(role); if (count < 0) { result.setError("500"); } return result.parseToJson(result); } /** * 后台管理平台-系统中心-菜单管理-列表 * * @param pageSize 页码数 * @param pageCount 条目数 * @param name 菜单名称 * @return 返回结果 * @throws PassportServerException */ @ApplicationAuthorize(authorizeResources = false, authorizeScope = ScopeType.WEB) @PostMapping(value = "edit", produces = "application/json;charset=UTF-8") public String edit( @RequestParam(value = "pageSize", required = false, defaultValue = "1") Integer pageSize, @RequestParam(value = "pageCount", required = false, defaultValue = "10") Integer pageCount, @RequestParam(value = "name", required = false, defaultValue = "") String name) throws PassportServerException { return StringUtils.EMPTY; } /** * 后台管理平台-系统中心-菜单管理-列表 * * @param pageSize 页码数 * @param pageCount 条目数 * @param name 菜单名称 * @return 返回结果 * @throws PassportServerException */ @ApplicationAuthorize(authorizeResources = false, authorizeScope = ScopeType.WEB) @PostMapping(value = "update", produces = "application/json;charset=UTF-8") public String update( @RequestParam(value = "pageSize", required = false, defaultValue = "1") Integer pageSize, @RequestParam(value = "pageCount", required = false, defaultValue = "10") Integer pageCount, @RequestParam(value = "name", required = false, defaultValue = "") String name) throws PassportServerException { return StringUtils.EMPTY; } /** * 后台管理平台-系统中心-菜单管理-列表 * * @param pageSize 页码数 * @param pageCount 条目数 * @param name 菜单名称 * @return 返回结果 * @throws PassportServerException */ @ApplicationAuthorize(authorizeResources = false, authorizeScope = ScopeType.WEB) @PostMapping(value = "delete", produces = "application/json;charset=UTF-8") public String delete( @RequestParam(value = "pageSize", required = false, defaultValue = "1") Integer pageSize, @RequestParam(value = "pageCount", required = false, defaultValue = "10") Integer pageCount, @RequestParam(value = "name", required = false, defaultValue = "") String name) throws PassportServerException { return StringUtils.EMPTY; } /** * 后台管理平台-系统中心-菜单管理-列表 * * @param pageSize 页码数 * @param pageCount 条目数 * @param name 菜单名称 * @return 返回结果 * @throws PassportServerException */ @ApplicationAuthorize(authorizeResources = false, authorizeScope = ScopeType.WEB) @PostMapping(value = "show", produces = "application/json;charset=UTF-8") public String show( @RequestParam(value = "pageSize", required = false, defaultValue = "1") Integer pageSize, @RequestParam(value = "pageCount", required = false, defaultValue = "10") Integer pageCount, @RequestParam(value = "name", required = false, defaultValue = "") String name) throws PassportServerException { return StringUtils.EMPTY; } /** * 后台管理平台-系统中心-菜单管理-列表 * * @return 返回结果 * @throws PassportServerException */ @ApplicationAuthorize(authorizeResources = false, authorizeScope = ScopeType.WEB) @PostMapping(value = "detail", produces = "application/json;charset=UTF-8") public String detail(@RequestParam(value = "id") String id) throws PassportServerException { ResponseResult result = new ResponseResult(); try { RoleInfo role = roleServerService.detail(id); result.putResult("role", role); } catch (PassportServerException exception) { result.setError(exception.getMessage()); } return result.parseToJson(result); } /** * 后台管理平台-系统中心-菜单管理-列表 * * @param pageSize 页码数 * @param pageCount 条目数 * @param name 菜单名称 * @return 返回结果 * @throws PassportServerException */ @ApplicationAuthorize(authorizeResources = false, authorizeScope = ScopeType.WEB) @PostMapping(value = "sort", produces = "application/json;charset=UTF-8") public String sort( @RequestParam(value = "pageSize", required = false, defaultValue = "1") Integer pageSize, @RequestParam(value = "pageCount", required = false, defaultValue = "10") Integer pageCount, @RequestParam(value = "name", required = false, defaultValue = "") String name) throws PassportServerException { return StringUtils.EMPTY; } }
40.658009
124
0.658007
6d2f3f2fe64d7bb7c311691f8b77619e1cd16bc8
5,188
package com.tony.ngeno.ridealong; import android.app.Activity; import android.content.Intent; import android.graphics.Color; import android.os.Handler; import androidx.viewpager.widget.PagerAdapter; import androidx.viewpager.widget.ViewPager; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; import devlight.io.library.ntb.NavigationTabBar; public class NavBar{ private Activity activity; private NavigationTabBar navigationTabBar; private static NavBar instance = null; private boolean initialized = false; private int INDEX; Runnable mDelay; Handler mHandler; private NavBar(){ } public static NavBar getInstance(){ if(instance == null){ instance = new NavBar(); } return instance; } public void initializeTab(Activity a){ this.activity = a; navigationTabBar = (NavigationTabBar) activity.findViewById(R.id.ntb); ViewPager viewPager = (ViewPager) activity.findViewById(R.id.vp_horizontal_ntb); viewPager.setAdapter(new PagerAdapter() { @Override public int getCount() { return 3; } @Override public boolean isViewFromObject(View view, Object object) { return view.equals(object); } @Override public void destroyItem(final View container, final int position, final Object object) { ((ViewPager) container).removeView((View) object); } @Override public Object instantiateItem(final ViewGroup container, final int position) { return null; } }); final String[] colors = activity.getResources().getStringArray(R.array.ntb_colors); final ArrayList<NavigationTabBar.Model> models = new ArrayList<>(); models.add( new NavigationTabBar.Model.Builder(activity.getResources().getDrawable(R.drawable.ic_home_white_24dp), Color.parseColor(colors[0])).title("Heart").badgeTitle("NTB").build() ); models.add( new NavigationTabBar.Model.Builder(activity.getResources().getDrawable(R.drawable.ic_person_white_24dp),Color.parseColor(colors[1])).title("Cup").badgeTitle("with").build() ); models.add(new NavigationTabBar.Model.Builder(activity.getResources().getDrawable(R.drawable.ic_account_balance_white_24dp),Color.parseColor(colors[2])).title("Diploma").badgeTitle("state").build() ); navigationTabBar.setModels(models); if(activity instanceof MainActivity) { navigationTabBar.setViewPager(viewPager, 0); }else if(activity instanceof ProfilePageActivity){ navigationTabBar.setViewPager(viewPager, 1); } else if(activity instanceof ShowOrganizationsActivity){ navigationTabBar.setViewPager(viewPager, 2); } navigationTabBar.setTitleMode(NavigationTabBar.TitleMode.ACTIVE); navigationTabBar.setBadgeGravity(NavigationTabBar.BadgeGravity.BOTTOM); navigationTabBar.setBadgePosition(NavigationTabBar.BadgePosition.CENTER); navigationTabBar.setTypeface("fonts/custom_font.ttf"); navigationTabBar.setIsBadged(true); navigationTabBar.setIsTitled(true); navigationTabBar.setIsTinted(true); navigationTabBar.setIsBadgeUseTypeface(true); navigationTabBar.setBadgeBgColor(Color.RED); navigationTabBar.setBadgeTitleColor(Color.WHITE); navigationTabBar.setIsSwiped(true); navigationTabBar.setBadgeSize(10); navigationTabBar.setTitleSize(10); navigationTabBar.setIconSizeFraction(0.5f); } public void tabListener(final Activity current){ mHandler = new Handler(); mDelay = new Runnable() { @Override public void run() { int index = NavBar.this.INDEX; if(index==0 && !(current instanceof MainActivity)){ Intent intent = new Intent(current, MainActivity.class); current.startActivity(intent); } if(index==1 && !(current instanceof ProfilePageActivity)){ Intent intent = new Intent(current, ProfilePageActivity.class); current.startActivity(intent); } if(index==2 && !(current instanceof ShowOrganizationsActivity)){ Intent intent = new Intent(current, ShowOrganizationsActivity.class); current.startActivity(intent); } } }; navigationTabBar.setOnTabBarSelectedIndexListener(new NavigationTabBar.OnTabBarSelectedIndexListener() { @Override public void onStartTabSelected(NavigationTabBar.Model model, int index) { NavBar.this.INDEX = index; System.out.println(index); mHandler.postDelayed(mDelay, 250); } @Override public void onEndTabSelected(NavigationTabBar.Model model, int index) { } }); } }
37.594203
205
0.640709
0d0bcac771cee2a5ead76ff2a746ce8118e53389
26,002
import java.io.IOException; import net.runelite.mapping.Export; import net.runelite.mapping.ObfuscatedGetter; import net.runelite.mapping.ObfuscatedName; import net.runelite.mapping.ObfuscatedSignature; import net.runelite.rs.ScriptOpcodes; @ObfuscatedName("gt") public class class184 implements WorldMapSection { @ObfuscatedName("l") @ObfuscatedSignature( descriptor = "Lkk;" ) @Export("Widget_spritesArchive") public static AbstractArchive Widget_spritesArchive; @ObfuscatedName("bz") @ObfuscatedSignature( descriptor = "Loi;" ) @Export("worldSelectLeftSprite") static IndexedSprite worldSelectLeftSprite; @ObfuscatedName("ce") @ObfuscatedSignature( descriptor = "Lcu;" ) @Export("mouseRecorder") static MouseRecorder mouseRecorder; @ObfuscatedName("n") @ObfuscatedGetter( intValue = 1787653751 ) int field2093; @ObfuscatedName("c") @ObfuscatedGetter( intValue = -488133759 ) int field2085; @ObfuscatedName("m") @ObfuscatedGetter( intValue = -1976143363 ) int field2095; @ObfuscatedName("k") @ObfuscatedGetter( intValue = -2143369535 ) int field2087; @ObfuscatedName("o") @ObfuscatedGetter( intValue = -353178983 ) int field2094; @ObfuscatedName("g") @ObfuscatedGetter( intValue = 768564603 ) int field2089; @ObfuscatedName("z") @ObfuscatedGetter( intValue = -1740450095 ) int field2084; @ObfuscatedName("a") @ObfuscatedGetter( intValue = -2133705891 ) int field2091; @ObfuscatedName("u") @ObfuscatedGetter( intValue = -1064129903 ) int field2092; @ObfuscatedName("e") @ObfuscatedGetter( intValue = 1523705091 ) int field2088; class184() { } @ObfuscatedName("n") @ObfuscatedSignature( descriptor = "(Lfr;I)V", garbageValue = "1411488256" ) @Export("expandBounds") public void expandBounds(WorldMapArea var1) { if (var1.regionLowX > this.field2094) { var1.regionLowX = this.field2094; } if (var1.regionHighX < this.field2094) { var1.regionHighX = this.field2094; } if (var1.regionLowY > this.field2089) { var1.regionLowY = this.field2089; } if (var1.regionHighY < this.field2089) { var1.regionHighY = this.field2089; } } @ObfuscatedName("c") @ObfuscatedSignature( descriptor = "(IIII)Z", garbageValue = "899981978" ) @Export("containsCoord") public boolean containsCoord(int var1, int var2, int var3) { if (var1 >= this.field2093 && var1 < this.field2085 + this.field2093) { return var2 >= (this.field2095 << 6) + (this.field2084 << 3) && var2 <= (this.field2095 << 6) + (this.field2084 << 3) + 7 && var3 >= (this.field2087 << 6) + (this.field2091 << 3) && var3 <= (this.field2087 << 6) + (this.field2091 << 3) + 7; } else { return false; } } @ObfuscatedName("m") @ObfuscatedSignature( descriptor = "(III)Z", garbageValue = "-1579388425" ) @Export("containsPosition") public boolean containsPosition(int var1, int var2) { return var1 >= (this.field2094 << 6) + (this.field2092 << 3) && var1 <= (this.field2094 << 6) + (this.field2092 << 3) + 7 && var2 >= (this.field2089 << 6) + (this.field2088 << 3) && var2 <= (this.field2089 << 6) + (this.field2088 << 3) + 7; } @ObfuscatedName("k") @ObfuscatedSignature( descriptor = "(IIII)[I", garbageValue = "-1605422008" ) @Export("getBorderTileLengths") public int[] getBorderTileLengths(int var1, int var2, int var3) { if (!this.containsCoord(var1, var2, var3)) { return null; } else { int[] var4 = new int[]{var2 + (this.field2094 * 64 - this.field2095 * 64) + (this.field2092 * 8 - this.field2084 * 8), var3 + (this.field2089 * 64 - this.field2087 * 64) + (this.field2088 * 8 - this.field2091 * 8)}; return var4; } } @ObfuscatedName("o") @ObfuscatedSignature( descriptor = "(III)Liy;", garbageValue = "1389329989" ) @Export("coord") public Coord coord(int var1, int var2) { if (!this.containsPosition(var1, var2)) { return null; } else { int var3 = this.field2095 * 64 - this.field2094 * 64 + (this.field2084 * 8 - this.field2092 * 8) + var1; int var4 = var2 + (this.field2087 * 64 - this.field2089 * 64) + (this.field2091 * 8 - this.field2088 * 8); return new Coord(this.field2093, var3, var4); } } @ObfuscatedName("g") @ObfuscatedSignature( descriptor = "(Lot;I)V", garbageValue = "-2069607106" ) @Export("read") public void read(Buffer var1) { this.field2093 = var1.readUnsignedByte(); this.field2085 = var1.readUnsignedByte(); this.field2095 = var1.readUnsignedShort(); this.field2084 = var1.readUnsignedByte(); this.field2087 = var1.readUnsignedShort(); this.field2091 = var1.readUnsignedByte(); this.field2094 = var1.readUnsignedShort(); this.field2092 = var1.readUnsignedByte(); this.field2089 = var1.readUnsignedShort(); this.field2088 = var1.readUnsignedByte(); this.method3711(); } @ObfuscatedName("z") @ObfuscatedSignature( descriptor = "(I)V", garbageValue = "-1438305611" ) void method3711() { } @ObfuscatedName("c") @ObfuscatedSignature( descriptor = "(Lkk;Lkk;ZII)V", garbageValue = "-1532489295" ) static void method3725(AbstractArchive var0, AbstractArchive var1, boolean var2, int var3) { if (Login.clearLoginScreen) { if (var3 == 4) { Message.method1113(4); } } else { if (var3 == 0) { MenuAction.method1876(var2); } else { Message.method1113(var3); } Rasterizer2D.Rasterizer2D_clear(); byte[] var4 = var0.takeFileByNames("title.jpg", ""); class318.leftTitleSprite = class17.convertJpgToSprite(var4); Login.rightTitleSprite = class318.leftTitleSprite.mirrorHorizontally(); int var5 = Client.worldProperties; if ((var5 & 536870912) != 0) { class394.logoSprite = class196.SpriteBuffer_getIndexedSpriteByName(var1, "logo_deadman_mode", ""); } else if ((var5 & 1073741824) != 0) { class394.logoSprite = class196.SpriteBuffer_getIndexedSpriteByName(var1, "logo_seasonal_mode", ""); } else { class394.logoSprite = class196.SpriteBuffer_getIndexedSpriteByName(var1, "logo", ""); } Login.titleboxSprite = class196.SpriteBuffer_getIndexedSpriteByName(var1, "titlebox", ""); Login.titlebuttonSprite = class196.SpriteBuffer_getIndexedSpriteByName(var1, "titlebutton", ""); UserComparator8.field1312 = class196.SpriteBuffer_getIndexedSpriteByName(var1, "titlebutton_large", ""); class14.field69 = class196.SpriteBuffer_getIndexedSpriteByName(var1, "play_now_text", ""); class196.SpriteBuffer_getIndexedSpriteByName(var1, "titlebutton_wide42,1", ""); Login.runesSprite = PacketBuffer.method6764(var1, "runes", ""); class92.title_muteSprite = PacketBuffer.method6764(var1, "title_mute", ""); ModelData0.options_buttons_0Sprite = class196.SpriteBuffer_getIndexedSpriteByName(var1, "options_radio_buttons,0", ""); class21.field107 = class196.SpriteBuffer_getIndexedSpriteByName(var1, "options_radio_buttons,4", ""); Client.options_buttons_2Sprite = class196.SpriteBuffer_getIndexedSpriteByName(var1, "options_radio_buttons,2", ""); PlayerComposition.field3019 = class196.SpriteBuffer_getIndexedSpriteByName(var1, "options_radio_buttons,6", ""); class1.field3 = ModelData0.options_buttons_0Sprite.subWidth; class280.field3323 = ModelData0.options_buttons_0Sprite.subHeight; Login.loginScreenRunesAnimation = new LoginScreenAnimation(Login.runesSprite); if (var2) { Login.Login_username = ""; Login.Login_password = ""; } class274.field3274 = 0; AbstractWorldMapIcon.otp = ""; Login.field893 = true; Login.worldSelectOpen = false; if (!VarbitComposition.clientPreferences.titleMusicDisabled) { Archive var6 = class276.archive6; int var7 = var6.getGroupId("scape main"); int var8 = var6.getFileId(var7, ""); class247.musicPlayerStatus = 1; class247.musicTrackArchive = var6; class247.musicTrackGroupId = var7; GrandExchangeOfferOwnWorldComparator.musicTrackFileId = var8; class196.musicTrackVolume = 255; class20.musicTrackBoolean = false; class130.pcmSampleLength = 2; } else { class16.method218(2); } if (NetCache.NetCache_socket != null) { try { Buffer var12 = new Buffer(4); var12.writeByte(3); var12.writeMedium(0); NetCache.NetCache_socket.write(var12.array, 0, 4); } catch (IOException var11) { try { NetCache.NetCache_socket.close(); } catch (Exception var10) { } ++NetCache.NetCache_ioExceptions; NetCache.NetCache_socket = null; } } Login.clearLoginScreen = true; Login.xPadding = (InvDefinition.canvasWidth - 765) / 2; Login.loginBoxX = Login.xPadding + 202; class11.loginBoxCenter = Login.loginBoxX + 180; class318.leftTitleSprite.drawAt(Login.xPadding, 0); Login.rightTitleSprite.drawAt(Login.xPadding + 382, 0); class394.logoSprite.drawAt(Login.xPadding + 382 - class394.logoSprite.subWidth / 2, 18); } } @ObfuscatedName("t") @ObfuscatedSignature( descriptor = "(ILbg;ZI)I", garbageValue = "761456408" ) static int method3721(int var0, Script var1, boolean var2) { String var7; if (var0 == ScriptOpcodes.MES) { var7 = Interpreter.Interpreter_stringStack[--Interpreter.Interpreter_stringStackSize]; SecureRandomCallable.addGameMessage(0, "", var7); return 1; } else if (var0 == ScriptOpcodes.ANIM) { class240.Interpreter_intStackSize -= 2; PacketWriter.performPlayerAnimation(class129.localPlayer, Interpreter.Interpreter_intStack[class240.Interpreter_intStackSize], Interpreter.Interpreter_intStack[class240.Interpreter_intStackSize + 1]); return 1; } else if (var0 == ScriptOpcodes.IF_CLOSE) { if (!Interpreter.field827) { Interpreter.field829 = true; } return 1; } else { int var16; if (var0 == ScriptOpcodes.RESUME_COUNTDIALOG) { var7 = Interpreter.Interpreter_stringStack[--Interpreter.Interpreter_stringStackSize]; var16 = 0; if (Timer.isNumber(var7)) { var16 = GrandExchangeOfferAgeComparator.method5303(var7); } PacketBufferNode var14 = FriendSystem.getPacketBufferNode(ClientPacket.field2665, Client.packetWriter.isaacCipher); var14.packetBuffer.writeInt(var16); Client.packetWriter.addNode(var14); return 1; } else { PacketBufferNode var12; if (var0 == ScriptOpcodes.RESUME_NAMEDIALOG) { var7 = Interpreter.Interpreter_stringStack[--Interpreter.Interpreter_stringStackSize]; var12 = FriendSystem.getPacketBufferNode(ClientPacket.field2725, Client.packetWriter.isaacCipher); var12.packetBuffer.writeByte(var7.length() + 1); var12.packetBuffer.writeStringCp1252NullTerminated(var7); Client.packetWriter.addNode(var12); return 1; } else if (var0 == ScriptOpcodes.RESUME_STRINGDIALOG) { var7 = Interpreter.Interpreter_stringStack[--Interpreter.Interpreter_stringStackSize]; var12 = FriendSystem.getPacketBufferNode(ClientPacket.field2673, Client.packetWriter.isaacCipher); var12.packetBuffer.writeByte(var7.length() + 1); var12.packetBuffer.writeStringCp1252NullTerminated(var7); Client.packetWriter.addNode(var12); return 1; } else { String var4; int var10; if (var0 == ScriptOpcodes.OPPLAYER) { var10 = Interpreter.Interpreter_intStack[--class240.Interpreter_intStackSize]; var4 = Interpreter.Interpreter_stringStack[--Interpreter.Interpreter_stringStackSize]; class328.method5845(var10, var4); return 1; } else if (var0 == ScriptOpcodes.IF_DRAGPICKUP) { class240.Interpreter_intStackSize -= 3; var10 = Interpreter.Interpreter_intStack[class240.Interpreter_intStackSize]; var16 = Interpreter.Interpreter_intStack[class240.Interpreter_intStackSize + 1]; int var9 = Interpreter.Interpreter_intStack[class240.Interpreter_intStackSize + 2]; Widget var15 = class87.getWidget(var9); Canvas.clickWidget(var15, var10, var16); return 1; } else if (var0 == ScriptOpcodes.CC_DRAGPICKUP) { class240.Interpreter_intStackSize -= 2; var10 = Interpreter.Interpreter_intStack[class240.Interpreter_intStackSize]; var16 = Interpreter.Interpreter_intStack[class240.Interpreter_intStackSize + 1]; Widget var13 = var2 ? PacketWriter.scriptDotWidget : class9.scriptActiveWidget; Canvas.clickWidget(var13, var10, var16); return 1; } else if (var0 == ScriptOpcodes.MOUSECAM) { Script.mouseCam = Interpreter.Interpreter_intStack[--class240.Interpreter_intStackSize] == 1; return 1; } else if (var0 == ScriptOpcodes.GETREMOVEROOFS) { Interpreter.Interpreter_intStack[++class240.Interpreter_intStackSize - 1] = VarbitComposition.clientPreferences.roofsHidden ? 1 : 0; return 1; } else if (var0 == ScriptOpcodes.SETREMOVEROOFS) { VarbitComposition.clientPreferences.roofsHidden = Interpreter.Interpreter_intStack[--class240.Interpreter_intStackSize] == 1; DevicePcmPlayerProvider.savePreferences(); return 1; } else if (var0 == ScriptOpcodes.OPENURL) { var7 = Interpreter.Interpreter_stringStack[--Interpreter.Interpreter_stringStackSize]; boolean var8 = Interpreter.Interpreter_intStack[--class240.Interpreter_intStackSize] == 1; Interpreter.openURL(var7, var8, false); return 1; } else if (var0 == ScriptOpcodes.RESUME_OBJDIALOG) { var10 = Interpreter.Interpreter_intStack[--class240.Interpreter_intStackSize]; var12 = FriendSystem.getPacketBufferNode(ClientPacket.field2703, Client.packetWriter.isaacCipher); var12.packetBuffer.writeShort(var10); Client.packetWriter.addNode(var12); return 1; } else if (var0 == ScriptOpcodes.BUG_REPORT) { var10 = Interpreter.Interpreter_intStack[--class240.Interpreter_intStackSize]; Interpreter.Interpreter_stringStackSize -= 2; var4 = Interpreter.Interpreter_stringStack[Interpreter.Interpreter_stringStackSize]; String var5 = Interpreter.Interpreter_stringStack[Interpreter.Interpreter_stringStackSize + 1]; if (var4.length() > 500) { return 1; } else if (var5.length() > 500) { return 1; } else { PacketBufferNode var6 = FriendSystem.getPacketBufferNode(ClientPacket.field2711, Client.packetWriter.isaacCipher); var6.packetBuffer.writeShort(1 + BufferedSink.stringCp1252NullTerminatedByteSize(var4) + BufferedSink.stringCp1252NullTerminatedByteSize(var5)); var6.packetBuffer.writeStringCp1252NullTerminated(var4); var6.packetBuffer.writeStringCp1252NullTerminated(var5); var6.packetBuffer.writeByte(var10); Client.packetWriter.addNode(var6); return 1; } } else if (var0 == ScriptOpcodes.SETSHIFTCLICKDROP) { Client.shiftClickDrop = Interpreter.Interpreter_intStack[--class240.Interpreter_intStackSize] == 1; return 1; } else if (var0 == ScriptOpcodes.SETSHOWMOUSEOVERTEXT) { Client.showMouseOverText = Interpreter.Interpreter_intStack[--class240.Interpreter_intStackSize] == 1; return 1; } else if (var0 == ScriptOpcodes.RENDERSELF) { Client.renderSelf = Interpreter.Interpreter_intStack[--class240.Interpreter_intStackSize] == 1; return 1; } else if (var0 == 3120) { if (Interpreter.Interpreter_intStack[--class240.Interpreter_intStackSize] == 1) { Client.drawPlayerNames |= 1; } else { Client.drawPlayerNames &= -2; } return 1; } else if (var0 == 3121) { if (Interpreter.Interpreter_intStack[--class240.Interpreter_intStackSize] == 1) { Client.drawPlayerNames |= 2; } else { Client.drawPlayerNames &= -3; } return 1; } else if (var0 == 3122) { if (Interpreter.Interpreter_intStack[--class240.Interpreter_intStackSize] == 1) { Client.drawPlayerNames |= 4; } else { Client.drawPlayerNames &= -5; } return 1; } else if (var0 == 3123) { if (Interpreter.Interpreter_intStack[--class240.Interpreter_intStackSize] == 1) { Client.drawPlayerNames |= 8; } else { Client.drawPlayerNames &= -9; } return 1; } else if (var0 == 3124) { Client.drawPlayerNames = 0; return 1; } else if (var0 == ScriptOpcodes.SETSHOWMOUSECROSS) { Client.showMouseCross = Interpreter.Interpreter_intStack[--class240.Interpreter_intStackSize] == 1; return 1; } else if (var0 == ScriptOpcodes.SETSHOWLOADINGMESSAGES) { Client.showLoadingMessages = Interpreter.Interpreter_intStack[--class240.Interpreter_intStackSize] == 1; return 1; } else if (var0 == ScriptOpcodes.SETTAPTODROP) { class17.setTapToDrop(Interpreter.Interpreter_intStack[--class240.Interpreter_intStackSize] == 1); return 1; } else if (var0 == ScriptOpcodes.GETTAPTODROP) { Interpreter.Interpreter_intStack[++class240.Interpreter_intStackSize - 1] = class138.getTapToDrop() ? 1 : 0; return 1; } else if (var0 == 3129) { class240.Interpreter_intStackSize -= 2; Client.oculusOrbNormalSpeed = Interpreter.Interpreter_intStack[class240.Interpreter_intStackSize]; Client.oculusOrbSlowedSpeed = Interpreter.Interpreter_intStack[class240.Interpreter_intStackSize + 1]; return 1; } else if (var0 == 3130) { class240.Interpreter_intStackSize -= 2; return 1; } else if (var0 == 3131) { --class240.Interpreter_intStackSize; return 1; } else if (var0 == ScriptOpcodes.GETCANVASSIZE) { Interpreter.Interpreter_intStack[++class240.Interpreter_intStackSize - 1] = InvDefinition.canvasWidth; Interpreter.Interpreter_intStack[++class240.Interpreter_intStackSize - 1] = GameEngine.canvasHeight; return 1; } else if (var0 == ScriptOpcodes.MOBILE_SETFPS) { --class240.Interpreter_intStackSize; return 1; } else if (var0 == ScriptOpcodes.MOBILE_OPENSTORE) { return 1; } else if (var0 == ScriptOpcodes.MOBILE_OPENSTORECATEGORY) { class240.Interpreter_intStackSize -= 2; return 1; } else if (var0 == 3136) { Client.field650 = 3; Client.field543 = Interpreter.Interpreter_intStack[--class240.Interpreter_intStackSize]; return 1; } else if (var0 == 3137) { Client.field650 = 2; Client.field543 = Interpreter.Interpreter_intStack[--class240.Interpreter_intStackSize]; return 1; } else if (var0 == 3138) { Client.field650 = 0; return 1; } else if (var0 == 3139) { Client.field650 = 1; return 1; } else if (var0 == 3140) { Client.field650 = 3; Client.field543 = var2 ? PacketWriter.scriptDotWidget.id * 296163183 * 1986537359 : class9.scriptActiveWidget.id * 296163183 * 1986537359; return 1; } else { boolean var11; if (var0 == ScriptOpcodes.SETHIDEUSERNAME) { var11 = Interpreter.Interpreter_intStack[--class240.Interpreter_intStackSize] == 1; VarbitComposition.clientPreferences.hideUsername = var11; DevicePcmPlayerProvider.savePreferences(); return 1; } else if (var0 == ScriptOpcodes.GETHIDEUSERNAME) { Interpreter.Interpreter_intStack[++class240.Interpreter_intStackSize - 1] = VarbitComposition.clientPreferences.hideUsername ? 1 : 0; return 1; } else if (var0 == ScriptOpcodes.SETREMEMBERUSERNAME) { var11 = Interpreter.Interpreter_intStack[--class240.Interpreter_intStackSize] == 1; Client.Login_isUsernameRemembered = var11; if (!var11) { VarbitComposition.clientPreferences.rememberedUsername = ""; DevicePcmPlayerProvider.savePreferences(); } return 1; } else if (var0 == ScriptOpcodes.GETREMEMBERUSERNAME) { Interpreter.Interpreter_intStack[++class240.Interpreter_intStackSize - 1] = Client.Login_isUsernameRemembered ? 1 : 0; return 1; } else if (var0 == ScriptOpcodes.SHOW_IOS_REVIEW) { return 1; } else if (var0 == 3146) { var11 = Interpreter.Interpreter_intStack[--class240.Interpreter_intStackSize] == 1; if (var11 == VarbitComposition.clientPreferences.titleMusicDisabled) { VarbitComposition.clientPreferences.titleMusicDisabled = !var11; DevicePcmPlayerProvider.savePreferences(); } return 1; } else if (var0 == 3147) { Interpreter.Interpreter_intStack[++class240.Interpreter_intStackSize - 1] = VarbitComposition.clientPreferences.titleMusicDisabled ? 0 : 1; return 1; } else if (var0 == 3148) { return 1; } else if (var0 == 3149) { Interpreter.Interpreter_intStack[++class240.Interpreter_intStackSize - 1] = 0; return 1; } else if (var0 == 3150) { Interpreter.Interpreter_intStack[++class240.Interpreter_intStackSize - 1] = 0; return 1; } else if (var0 == 3151) { Interpreter.Interpreter_intStack[++class240.Interpreter_intStackSize - 1] = 0; return 1; } else if (var0 == 3152) { Interpreter.Interpreter_intStack[++class240.Interpreter_intStackSize - 1] = 0; return 1; } else if (var0 == 3153) { Interpreter.Interpreter_intStack[++class240.Interpreter_intStackSize - 1] = Login.Login_loadingPercent; return 1; } else if (var0 == 3154) { Interpreter.Interpreter_intStack[++class240.Interpreter_intStackSize - 1] = UserComparator7.method2409(); return 1; } else if (var0 == 3155) { --Interpreter.Interpreter_stringStackSize; return 1; } else if (var0 == 3156) { return 1; } else if (var0 == 3157) { class240.Interpreter_intStackSize -= 2; return 1; } else if (var0 == 3158) { Interpreter.Interpreter_intStack[++class240.Interpreter_intStackSize - 1] = 0; return 1; } else if (var0 == 3159) { Interpreter.Interpreter_intStack[++class240.Interpreter_intStackSize - 1] = 0; return 1; } else if (var0 == 3160) { Interpreter.Interpreter_intStack[++class240.Interpreter_intStackSize - 1] = 0; return 1; } else if (var0 == 3161) { --class240.Interpreter_intStackSize; Interpreter.Interpreter_intStack[++class240.Interpreter_intStackSize - 1] = 0; return 1; } else if (var0 == 3162) { --class240.Interpreter_intStackSize; Interpreter.Interpreter_intStack[++class240.Interpreter_intStackSize - 1] = 0; return 1; } else if (var0 == 3163) { --Interpreter.Interpreter_stringStackSize; Interpreter.Interpreter_intStack[++class240.Interpreter_intStackSize - 1] = 0; return 1; } else if (var0 == 3164) { --class240.Interpreter_intStackSize; Interpreter.Interpreter_stringStack[++Interpreter.Interpreter_stringStackSize - 1] = ""; return 1; } else if (var0 == 3165) { --class240.Interpreter_intStackSize; Interpreter.Interpreter_intStack[++class240.Interpreter_intStackSize - 1] = 0; return 1; } else if (var0 == 3166) { class240.Interpreter_intStackSize -= 2; Interpreter.Interpreter_intStack[++class240.Interpreter_intStackSize - 1] = 0; return 1; } else if (var0 == 3167) { class240.Interpreter_intStackSize -= 2; Interpreter.Interpreter_intStack[++class240.Interpreter_intStackSize - 1] = 0; return 1; } else if (var0 == 3168) { class240.Interpreter_intStackSize -= 2; Interpreter.Interpreter_stringStack[++Interpreter.Interpreter_stringStackSize - 1] = ""; Interpreter.Interpreter_stringStack[++Interpreter.Interpreter_stringStackSize - 1] = ""; Interpreter.Interpreter_stringStack[++Interpreter.Interpreter_stringStackSize - 1] = ""; Interpreter.Interpreter_stringStack[++Interpreter.Interpreter_stringStackSize - 1] = ""; Interpreter.Interpreter_stringStack[++Interpreter.Interpreter_stringStackSize - 1] = ""; Interpreter.Interpreter_stringStack[++Interpreter.Interpreter_stringStackSize - 1] = ""; Interpreter.Interpreter_stringStack[++Interpreter.Interpreter_stringStackSize - 1] = ""; Interpreter.Interpreter_stringStack[++Interpreter.Interpreter_stringStackSize - 1] = ""; Interpreter.Interpreter_stringStack[++Interpreter.Interpreter_stringStackSize - 1] = ""; return 1; } else if (var0 == 3169) { return 1; } else if (var0 == 3170) { Interpreter.Interpreter_intStack[++class240.Interpreter_intStackSize - 1] = 0; return 1; } else if (var0 == 3171) { Interpreter.Interpreter_intStack[++class240.Interpreter_intStackSize - 1] = 0; return 1; } else if (var0 == 3172) { --class240.Interpreter_intStackSize; return 1; } else if (var0 == 3173) { --class240.Interpreter_intStackSize; Interpreter.Interpreter_intStack[++class240.Interpreter_intStackSize - 1] = 0; return 1; } else if (var0 == 3174) { --class240.Interpreter_intStackSize; return 1; } else if (var0 == 3175) { Interpreter.Interpreter_intStack[++class240.Interpreter_intStackSize - 1] = 0; return 1; } else if (var0 == 3176) { return 1; } else if (var0 == 3177) { return 1; } else if (var0 == 3178) { --Interpreter.Interpreter_stringStackSize; return 1; } else if (var0 == 3179) { return 1; } else if (var0 == 3180) { --Interpreter.Interpreter_stringStackSize; return 1; } else if (var0 == 3181) { var10 = 100 - Math.min(Math.max(Interpreter.Interpreter_intStack[--class240.Interpreter_intStackSize], 0), 100); Varps.method4858((double)(0.5F + (float)var10 / 200.0F)); return 1; } else if (var0 == 3182) { float var3 = ((float)VarbitComposition.clientPreferences.field1193 - 0.5F) * 200.0F; Interpreter.Interpreter_intStack[++class240.Interpreter_intStackSize - 1] = 100 - Math.round(var3); return 1; } else if (var0 != 3183 && var0 != 3184) { return 2; } else { --class240.Interpreter_intStackSize; return 1; } } } } } } }
39.39697
243
0.690293
7b093ff9c4d4c59345106ceee84d9d217a1bb959
1,673
/* * #%L * ACS AEM Commons Bundle * %% * Copyright (C) 2017 Adobe * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package com.adobe.acs.commons.wcm.vanity.impl; import com.adobe.acs.commons.wcm.vanity.WrappedRequestPathInfoWrapper; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.request.RequestPathInfo; import org.apache.sling.api.wrappers.SlingHttpServletRequestWrapper; import java.lang.reflect.Proxy; public class ExtensionlessRequestWrapper extends SlingHttpServletRequestWrapper { public ExtensionlessRequestWrapper(SlingHttpServletRequest wrappedRequest) { super(wrappedRequest); } public RequestPathInfo getRequestPathInfo() { final RequestPathInfoWrapper requestPathInfoWrapper = RequestPathInfoWrapper.createRequestPathInfoWrapper(super.getRequestPathInfo(), super.getResource()); RequestPathInfo wrappedRequestInfo = (RequestPathInfo) Proxy.newProxyInstance(WrappedRequestPathInfoWrapper.class.getClassLoader(), new Class[] { RequestPathInfo.class, WrappedRequestPathInfoWrapper.class }, requestPathInfoWrapper); return wrappedRequestInfo; } }
39.833333
241
0.777047
3643b014b4daed2fa7d6a75b07f80eb33b3bdbaf
2,482
package com.meal.sys.controller; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.meal.data.response.R; import com.meal.security.context.JwtUserContext; import com.meal.security.permission.RolePermission; import com.meal.sys.entity.SysUser; import com.meal.sys.service.ISysUserService; import com.meal.sys.to.UserDo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; /** * <p> * 系统用户表 前端控制器 * </p> * * @author 米虫先生/mebugs.com * @since 2020-10-19 */ @RestController //用户控制层涉及到登录相关,因此不在类上定义路径 //@RequestMapping("/sysUser") public class SysUserController { @Autowired private ISysUserService sysUserService; /** * 登录 * @param sysUser * @return */ @PostMapping("/auth/login") public R login(@RequestBody SysUser sysUser) { return R.ok(sysUserService.login(sysUser)); } /** * 获取用户基本信息 JwtUser对象数据 * 本方法经过过滤器 直接返回上下文中的数据即可 * @return */ @GetMapping("/user/base") public R getUserBase() { return R.ok(JwtUserContext.getUser()); } /** * 保存账号数据 新增 修改 锁定 解锁 超管权限 * @param userDo * @return */ @RolePermission(roles="admin") @PostMapping("/user/save") public R saveOne(@RequestBody UserDo userDo){ return R.ok(sysUserService.saveOne(userDo)); } /** * 查询账号分页 * @param page * @param userDo * @return */ @RolePermission(roles="admin") @GetMapping("/user/page") public R getPage(Page page, UserDo userDo){ return R.ok(sysUserService.getPage(page,userDo)); } /** * 更具账号ID查询用户信息 * @param id * @return */ @RolePermission(roles="admin") @GetMapping("/user/get") public R getUserInfo(Long id) { return R.ok(sysUserService.getUserInfo(id)); } /** * 获取自己的用户信息 * @return */ @GetMapping("/user/getMine") public R getMine(){ return R.ok(sysUserService.getMine()); } /** * 用户自行修改密码 * @param nowPwd * @param newPwd * @return */ @GetMapping("/user/resetPwd") public R resetPwd(String nowPwd,String newPwd){ return R.ok(sysUserService.resetPwd(nowPwd,newPwd)); } }
22.36036
66
0.643433
0dc8a57397b5b1fae0e0d6cc9974eb887dd677b1
1,987
package cn.icodening.console.log; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import java.util.Collections; import java.util.HashSet; import java.util.Set; /** * @author icodening * @date 2021.07.12 */ public class SystemPrintStreamDecorator extends PrintStream { private static final int DEFAULT_MAX_BUFFER_SIZE = 8 * 1024; private static final int DEFAULT_INIT_BUFFER_SIZE = 1024; private final OutputStream delegate; private final Set<BytesConsumer> flushCallbacks = Collections.synchronizedSet(new HashSet<>()); private volatile ByteArrayOutputStream bos = new ByteArrayOutputStream(DEFAULT_INIT_BUFFER_SIZE); public SystemPrintStreamDecorator(OutputStream systemOut, OutputStream delegate) { super(systemOut); this.delegate = delegate; } @Override public void write(byte[] buf, int off, int len) { try { super.write(buf, off, len); delegate.write(buf, off, len); bos.write(buf, off, len); } catch (IOException e) { e.printStackTrace(); } } public void registerFlushCallback(BytesConsumer callback) { flushCallbacks.add(callback); } public void deregisterFlushCallback(BytesConsumer callback) { flushCallbacks.remove(callback); } @Override public void flush() { try { super.flush(); delegate.flush(); for (BytesConsumer flushCallback : flushCallbacks) { flushCallback.accept(bos.toByteArray()); } if (DEFAULT_MAX_BUFFER_SIZE < bos.size()) { bos = null; bos = new ByteArrayOutputStream(DEFAULT_INIT_BUFFER_SIZE); } } catch (IOException e) { e.printStackTrace(); } finally { if (bos != null) { bos.reset(); } } } }
27.597222
101
0.626573
c72b707d4010c5fa80d333eed0a3d672d5f532e0
5,448
package ktak.parseley; import java.util.Comparator; import ktak.immutablejava.AATreeMap; import ktak.immutablejava.AATreeSet; import ktak.immutablejava.List; import ktak.immutablejava.Option; import ktak.immutablejava.Tuple; class StateSet<NT,T,R> { private final Comparator<NT> ntCmp; private final Comparator<T> tCmp; private final Comparator<Item<NT,T,R>> itemCmp; protected final AATreeSet<Item<NT,T,R>> itemsInSet; private final AATreeMap<NT,List<PredictItem<NT,T,R>>> predictItems; private final AATreeMap<NT,List<CompleteItem<NT,T,R>>> completeItems; private final List<Item<NT,T,R>> frontQueue; private final List<Item<NT,T,R>> backQueue; protected StateSet(Comparator<NT> ntCmp, Comparator<T> tCmp) { this.ntCmp = ntCmp; this.tCmp = tCmp; this.itemCmp = (i1, i2) -> Item.compare(ntCmp, i1, i2); this.itemsInSet = AATreeSet.emptySet(itemCmp); this.predictItems = AATreeMap.emptyMap(ntCmp); this.completeItems = AATreeMap.emptyMap(ntCmp); this.frontQueue = new List.Nil<>(); this.backQueue = new List.Nil<>(); } private StateSet( Comparator<NT> ntCmp, Comparator<T> tCmp, Comparator<Item<NT,T,R>> itemCmp, AATreeSet<Item<NT,T,R>> statesInSet, AATreeMap<NT,List<PredictItem<NT,T,R>>> predictItems, AATreeMap<NT,List<CompleteItem<NT,T,R>>> completeItems, List<Item<NT,T,R>> frontQueue, List<Item<NT,T,R>> backQueue) { this.ntCmp = ntCmp; this.tCmp = tCmp; this.itemCmp = itemCmp; this.itemsInSet = statesInSet; this.predictItems = predictItems; this.completeItems = completeItems; this.frontQueue = frontQueue; this.backQueue = backQueue; } protected StateSet<NT,T,R> add(Item<NT,T,R> item) { return itemsInSet.contains(item) ? this : addNewItem(item); } private StateSet<NT,T,R> addNewItem(Item<NT,T,R> item) { AATreeSet<Item<NT,T,R>> newItemsInSet = itemsInSet.insert(item); List<Item<NT,T,R>> newBackQueue = backQueue.cons(item); return item.match( (predictItem) -> newStateSet( newItemsInSet, mapListInsert( predictItems, predictItem.nextNonTerminal, predictItem), completeItems, newBackQueue), (scanItem) -> newStateSet( newItemsInSet, predictItems, completeItems, newBackQueue), (completeItem) -> newStateSet( newItemsInSet, predictItems, mapListInsert( completeItems, completeItem.leftHandSide, completeItem), newBackQueue)); } private StateSet<NT,T,R> newStateSet( AATreeSet<Item<NT,T,R>> itemsInSet, AATreeMap<NT,List<PredictItem<NT,T,R>>> predictItems, AATreeMap<NT,List<CompleteItem<NT,T,R>>> completeItems, List<Item<NT,T,R>> backQueue) { return new StateSet<>( ntCmp, tCmp, itemCmp, itemsInSet, predictItems, completeItems, frontQueue, backQueue); } private <Elem> AATreeMap<NT,List<Elem>> mapListInsert( AATreeMap<NT,List<Elem>> map, NT key, Elem element) { return map.insert( key, map.get(key).match( (unit) -> new List.Nil<Elem>().cons(element), (list) -> list.cons(element))); } protected Option<Tuple<Item<NT,T,R>,StateSet<NT,T,R>>> nextItem() { return frontQueue.match( (unit1) -> backQueue.reverse().match( (unit2) -> Option.none(), (cons) -> Option.some(Tuple.create( cons.left, new StateSet<>( ntCmp, tCmp, itemCmp, itemsInSet, predictItems, completeItems, cons.right, new List.Nil<>())))), (cons) -> Option.some(Tuple.create( cons.left, new StateSet<>( ntCmp, tCmp, itemCmp, itemsInSet, predictItems, completeItems, cons.right, backQueue)))); } protected List<CompleteItem<NT,T,R>> completeItems(NT lhs) { return completeItems.get(lhs).match( (unit) -> new List.Nil<>(), (list) -> list); } protected AATreeMap<NT,List<CompleteItem<NT,T,R>>> completeItems() { return completeItems; } protected List<PredictItem<NT,T,R>> predictItems(NT nextNonTerminal) { return predictItems.get(nextNonTerminal).match( (unit) -> new List.Nil<>(), (list) -> list); } }
35.842105
80
0.509361
1d89458cfe15b6912577b006c2d7bb3e3e9fc74a
958
package com.github.mybatis.helper.datascope.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.TYPE,ElementType.METHOD}) public @interface DataScopeSettings { boolean onlyUseSmallScope() default true; /** * 自定义dataScope生效的字段 * @return activeScopeFields */ ActiveScopeField[] activeScopeFields() default {}; /** * sql风格 * @return dataScopeSqlStyle */ DataScopeSqlStyle dataScopeSqlStyle() default DataScopeSqlStyle.OUTER; /** * 外部sql配置 * @return outerSqlStyleSettings */ OuterSqlStyleSettings outerSqlStyleSettings() default @OuterSqlStyleSettings; /** * 内部sql配置 * @return innerSqlStyleSettings */ InnerSqlStyleSettings innerSqlStyleSettings() default @InnerSqlStyleSettings; }
25.891892
81
0.730689
3c26f03e8622944b43c01fc37fc754c63295eec0
434
/* * @lc app=leetcode id=53 lang=java * * [53] Maximum Subarray */ // @lc code=start class Solution { public int maxSubArray(int[] nums) { int T = nums[0]; //T(i): max sub-array sum for x_0, ..., x_i including x_i int max = T; for (int i=1; i<nums.length; i++) { T = (T>=0)? (T+nums[i]): nums[i]; max = Math.max(max, T); } return max; } } // @lc code=end
20.666667
83
0.488479
3354d6d814ccf9f568cc6f35299e9c44947d5192
3,825
package uk.gov.hmcts.reform.sscs.ccd.presubmit.writefinaldecision.pip; import java.util.function.Function; import uk.gov.hmcts.reform.sscs.ccd.domain.SscsCaseData; import uk.gov.hmcts.reform.sscs.ccd.domain.SscsPipCaseData; import uk.gov.hmcts.reform.sscs.ccd.presubmit.writefinaldecision.ActivityQuestion; import uk.gov.hmcts.reform.sscs.ccd.presubmit.writefinaldecision.ActivityType; /** * Enum to encapsulate binding between an activity question key, and the corresponding getter method on SscsCaseData that yields that answer to that question. */ public enum PipActivityQuestion implements ActivityQuestion { PREPARING_FOOD("preparingFood", "Preparing food", PipActivityType.DAILY_LIVING, SscsPipCaseData::getPipWriteFinalDecisionPreparingFoodQuestion), TAKING_NUTRITION("takingNutrition", "Taking nutrition", PipActivityType.DAILY_LIVING, SscsPipCaseData::getPipWriteFinalDecisionTakingNutritionQuestion), MANAGING_THERAPY("managingTherapy", "Managing therapy or monitoring a health condition", PipActivityType.DAILY_LIVING, SscsPipCaseData::getPipWriteFinalDecisionManagingTherapyQuestion), WASHING_AND_BATHING("washingAndBathing", "Washing and bathing", PipActivityType.DAILY_LIVING, SscsPipCaseData::getPipWriteFinalDecisionWashAndBatheQuestion), MANAGING_TOILET_NEEDS("managingToiletNeeds", "Managing toilet needs or incontinence", PipActivityType.DAILY_LIVING, SscsPipCaseData::getPipWriteFinalDecisionManagingToiletNeedsQuestion), DRESSING_AND_UNDRESSING("dressingAndUndressing", "Dressing and undressing", PipActivityType.DAILY_LIVING, SscsPipCaseData::getPipWriteFinalDecisionDressingAndUndressingQuestion), COMMUNICATING("communicating", "Communicating", PipActivityType.DAILY_LIVING, SscsPipCaseData::getPipWriteFinalDecisionCommunicatingQuestion), READING_AND_UNDERSTANDING("readingUnderstanding", "Reading and understanding signs, symbols and words", PipActivityType.DAILY_LIVING, SscsPipCaseData::getPipWriteFinalDecisionReadingUnderstandingQuestion), ENGAGING_WITH_OTHERS("engagingWithOthers", "Engaging with other people face to face", PipActivityType.DAILY_LIVING, SscsPipCaseData::getPipWriteFinalDecisionEngagingWithOthersQuestion), MAKING_BUDGETING_DECISIONS("budgetingDecisions", "Making budgeting decisions", PipActivityType.DAILY_LIVING, SscsPipCaseData::getPipWriteFinalDecisionBudgetingDecisionsQuestion), PLANNING_AND_FOLLOWING_JOURNEYS("planningAndFollowing", "Planning and following journeys", PipActivityType.MOBILITY, SscsPipCaseData::getPipWriteFinalDecisionPlanningAndFollowingQuestion), MOVING_AROUND("movingAround", "Moving around", PipActivityType.MOBILITY, SscsPipCaseData::getPipWriteFinalDecisionMovingAroundQuestion); final String key; final String value; final ActivityType activityType; final Function<SscsCaseData, String> answerExtractor; PipActivityQuestion(String key, String value, ActivityType activityType, Function<SscsPipCaseData, String> answerExtractor) { this.key = key; this.answerExtractor = t -> answerExtractor.apply(t.getSscsPipCaseData()); this.activityType = activityType; this.value = value; } public static PipActivityQuestion getByKey(String key) { for (PipActivityQuestion mapping : PipActivityQuestion.values()) { if (mapping.key.equals(key)) { return mapping; } } throw new IllegalArgumentException("Unknown ActivityQuestion for question key:" + key); } public String getKey() { return key; } public String getValue() { return value; } @Override public ActivityType getActivityType() { return activityType; } public Function<SscsCaseData, String> getAnswerExtractor() { return answerExtractor; } }
58.846154
209
0.795033
acfdcb0ffc48d31de743a1659781fc27856a3be8
1,140
package mireka.forward; import java.util.Locale; /** * Base32Int class can encode and decode an int value using a Base32. * * @see <a href="http://tools.ietf.org/html/rfc4648">RFC 4648</a> */ class Base32Int { private static final String BASE32_TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; public static int decode(String text) throws NumberFormatException { String timestampUpperCase = text.toUpperCase(Locale.US); int value = 0; for (int i = 0; i < timestampUpperCase.length(); i++) { char ch = timestampUpperCase.charAt(i); int digitValue = BASE32_TABLE.indexOf(ch); if (digitValue == -1) throw new NumberFormatException("Invalid Base32 digit in " + text); value = (value << 5) + digitValue; } return value; } public static String encode10Bits(int value) { StringBuilder buffer = new StringBuilder(); buffer.append(BASE32_TABLE.charAt(value >> 5 & 0x1F)); buffer.append(BASE32_TABLE.charAt(value & 0x1F)); return buffer.toString(); } }
31.666667
74
0.615789
8fd1548cb7354d567c0460a8eeeaaeccb4d16dd1
419
package com.jn.web.goods.service; import com.jn.entity.Result; import java.util.Map; /** * @Author muYan * @Version 1.0 * @Since 2021-02-01 */ public interface CartService { Map<String, Object> list(String username); void addAndUpdate(String username, String skuId, Integer num); void del(String username, String skuId); void updateChecked(String username, String skuId, Boolean checked); }
18.217391
71
0.711217
9b3d06a28713aa929ed4736d1b633d11434a2817
742
package model; import view.View; import vo.Vacancy; import java.util.ArrayList; import java.util.List; public class Model { private View view; private Provider[] providers; public Model(View view, Provider... providers) throws IllegalArgumentException { if (view == null || providers == null || providers.length == 0) { throw new IllegalArgumentException("Illegal arguments"); } this.view = view; this.providers = providers; } public void selectCity(String location) { List<Vacancy> vacancies = new ArrayList<>(); for (Provider p : providers) { vacancies.addAll(p.getJavaVacancies(location)); } view.update(vacancies); } }
23.935484
84
0.633423
32c876c76e22953d4c68d8633058284de92b717e
1,139
package nl.hsac.fitnesse.fixture.util; import org.junit.Test; import java.util.LinkedHashMap; import java.util.Map; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; public class JsonHelperTest { private JsonHelper helper = new JsonHelper(); @Test public void testFormatNull() { assertNull(helper.format(null)); } @Test public void testFormatSimple() { assertEquals( "{\n" + " \"category\": \"reference\",\n" + " \"price\": 8.95\n" + "}", helper.format("{\"category\": \"reference\",\"price\": 8.95}")); } @Test public void testNullToMap() { assertNull(helper.jsonStringToMap(null)); } @Test public void testSimpleMap() { Map<String, Object> expected = new LinkedHashMap<String, Object>(); expected.put("category", "reference"); expected.put("price", 8.95); assertEquals(expected, helper.jsonStringToMap("{\"category\": \"reference\",\"price\": 8.95}")); } }
26.488372
89
0.56453
e0decd4e1932cfdaf5afe5ec1aaada9283382c62
2,129
// Copyright 2000-2021 Nokia // // Licensed under the Apache License 2.0 // SPDX-License-Identifier: Apache-2.0 // package com.nokia.as.autoconfig.file; import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE; import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE; import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY; import java.io.IOException; import java.nio.file.FileSystems; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.WatchEvent; import java.nio.file.WatchKey; import java.nio.file.WatchService; import java.util.HashMap; import java.util.Map; import com.alcatel.as.service.log.LogService; import com.nokia.as.autoconfig.AutoConfigurator; import alcatel.tess.hometop.gateways.utils.Log; public class DirectoryWatcher extends Thread { private LogService logger = Log.getLogger(AutoConfigurator.LOGGER); private final WatchService directoryWatcher; private final Map<WatchKey, Path> keys = new HashMap<>(); private final AutoConfigurator autoconf; private String path; public DirectoryWatcher(AutoConfigurator autoconf, String path) throws IOException { this.autoconf = autoconf; this.path = path; this.directoryWatcher = FileSystems.getDefault().newWatchService(); registerDir(Paths.get(path)); } private void registerDir(Path dir) throws IOException { logger.debug("DirectoryWatcher will watch %s", dir.toString()); keys.put(dir.register(directoryWatcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY), dir); } @Override public void run() { while(true) { WatchKey key; try { key = directoryWatcher.take(); Thread.sleep(500); //trying to avoid double updates } catch (InterruptedException e) { logger.debug("Interrupted watching directory %s", e, path); return; } Path dir = keys.get(key); if(dir == null) { logger.warn("Error while watching directory %s: WatchKey not recognized", path); continue; } key.pollEvents().stream() .forEach(this::consume); key.reset(); } } private void consume(WatchEvent<?> event) { autoconf.fileEvent(path); } }
27.294872
90
0.743072
ca5a0e1dd9df6ee3bcabf6a8f0b55b69a9bb5654
5,116
package org.drip.measure.discretemarginal; /* * -*- mode: java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /*! * Copyright (C) 2017 Lakshmi Krishnamurthy * Copyright (C) 2016 Lakshmi Krishnamurthy * Copyright (C) 2015 Lakshmi Krishnamurthy * * This file is part of DRIP, a free-software/open-source library for buy/side financial/trading model * libraries targeting analysts and developers * https://lakshmidrip.github.io/DRIP/ * * DRIP is composed of four main libraries: * * - DRIP Fixed Income - https://lakshmidrip.github.io/DRIP-Fixed-Income/ * - DRIP Asset Allocation - https://lakshmidrip.github.io/DRIP-Asset-Allocation/ * - DRIP Numerical Optimizer - https://lakshmidrip.github.io/DRIP-Numerical-Optimizer/ * - DRIP Statistical Learning - https://lakshmidrip.github.io/DRIP-Statistical-Learning/ * * - DRIP Fixed Income: Library for Instrument/Trading Conventions, Treasury Futures/Options, * Funding/Forward/Overnight Curves, Multi-Curve Construction/Valuation, Collateral Valuation and XVA * Metric Generation, Calibration and Hedge Attributions, Statistical Curve Construction, Bond RV * Metrics, Stochastic Evolution and Option Pricing, Interest Rate Dynamics and Option Pricing, LMM * Extensions/Calibrations/Greeks, Algorithmic Differentiation, and Asset Backed Models and Analytics. * * - DRIP Asset Allocation: Library for model libraries for MPT framework, Black Litterman Strategy * Incorporator, Holdings Constraint, and Transaction Costs. * * - DRIP Numerical Optimizer: Library for Numerical Optimization and Spline Functionality. * * - DRIP Statistical Learning: Library for Statistical Evaluation and Machine Learning. * * 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. */ /** * BoundedUniformIntegerDistribution implements the Univariate Bounded Uniform Integer Distribution, with the * Integer being generated between a(n inclusive) lower and an upper Bound. * * @author Lakshmi Krishnamurthy */ public class BoundedUniformIntegerDistribution extends org.drip.measure.continuousmarginal.R1 { private int _iStart = -1; private int _iFinish = -1; /** * Construct a Univariate Bounded Uniform Integer Distribution * * @param iStart The Starting Integer * @param iFinish The Finishing Integer * * @throws java.lang.Exception Thrown if the inputs are invalid */ public BoundedUniformIntegerDistribution ( final int iStart, final int iFinish) throws java.lang.Exception { if ((_iFinish = iFinish) <= (_iStart = iStart)) throw new java.lang.Exception ("BoundedUniformIntegerDistribution constructor: Invalid inputs"); } /** * Retrieve the Start * * @return The Start */ public int start() { return _iStart; } /** * Retrieve the Finish * * @return The Finish */ public int finish() { return _iFinish; } @Override public double cumulative ( final double dblX) throws java.lang.Exception { if (!org.drip.quant.common.NumberUtil.IsValid (dblX)) throw new java.lang.Exception ("BoundedUniformIntegerDistribution::cumulative => Invalid inputs"); if (dblX <= _iStart) return 0.; if (dblX >= _iFinish) return 1.; return (dblX - _iStart) / (_iFinish - _iStart); } @Override public double incremental ( final double dblXLeft, final double dblXRight) throws java.lang.Exception { return cumulative (dblXRight) - cumulative (dblXLeft); } @Override public double invCumulative ( final double dblY) throws java.lang.Exception { if (!org.drip.quant.common.NumberUtil.IsValid (dblY) || dblY < 0. || dblY > 1.) throw new java.lang.Exception ("BoundedUniformIntegerDistribution::invCumulative => Invalid inputs"); return dblY * (_iFinish - _iStart) + _iStart; } @Override public double density ( final double dblX) throws java.lang.Exception { throw new java.lang.Exception ("BoundedUniformIntegerDistribution::density => Not available for discrete distributions"); } @Override public double mean() { return 0.5 * (_iFinish + _iStart); } @Override public double variance() { return (_iFinish - _iStart) * (_iFinish - _iStart) / 12.; } @Override public org.drip.quant.common.Array2D histogram() { int iGridWidth = _iFinish - _iStart; double[] adblX = new double[iGridWidth]; double[] adblY = new double[iGridWidth]; for (int i = 0; i < iGridWidth; ++i) { adblY[i] = 1. / iGridWidth; adblX[i] = _iStart + (i + 1); } try { } catch (java.lang.Exception e) { e.printStackTrace(); } return null; } }
29.402299
109
0.716185
302157eddb9eae3c5a088fcf6b7547aad2551a0c
8,164
/* * 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.jena.tdb2.store.tupletable; import static org.apache.jena.atlas.lib.tuple.TupleFactory.tuple; import static org.apache.jena.tdb2.store.tupletable.NData.*; import java.util.Iterator; import java.util.Set; import org.apache.jena.atlas.iterator.Iter; import static org.junit.Assert.*; import org.apache.jena.atlas.lib.tuple.Tuple; import org.apache.jena.tdb2.store.NodeId; import org.junit.Test; /** Test TupleIndexes (general) */ public abstract class AbstractTestTupleIndex { protected abstract TupleIndex create(String description); protected static void add(TupleIndex index, NodeId x1, NodeId x2, NodeId x3) { Tuple<NodeId> tuple = tuple(x1, x2, x3); index.add(tuple); } @Test public void TupleIndex_1() { TupleIndex index = create("SPO"); add(index, n1, n2, n3); } @Test public void TupleIndexRecordSPO_1() { TupleIndex index = create("SPO"); add(index, n1, n2, n3); Tuple<NodeId> tuple2 = tuple(n1, n2, n3); Iterator<Tuple<NodeId>> iter = index.find(tuple2); assertTrue(iter.hasNext()); iter.next(); assertFalse(iter.hasNext()); } @Test public void TupleIndexRecordSPO_2() { TupleIndex index = create("SPO"); add(index, n1, n2, n3); Tuple<NodeId> tuple2 = tuple(n1, n2, null); Iterator<Tuple<NodeId>> iter = index.find(tuple2); assertTrue(iter.hasNext()); iter.next(); assertFalse(iter.hasNext()); } @Test public void TupleIndexRecordSPO_3() { TupleIndex index = create("SPO"); add(index, n1, n2, n3); Tuple<NodeId> tuple2 = tuple(n1, null, n3); Iterator<Tuple<NodeId>> iter = index.find(tuple2); assertTrue(iter.hasNext()); iter.next(); assertFalse(iter.hasNext()); } @Test public void TupleIndexRecordSPO_4() { TupleIndex index = create("SPO"); add(index, n1, n2, n3); Tuple<NodeId> tuple2 = tuple(n1, NodeId.NodeIdAny, NodeId.NodeIdAny); Iterator<Tuple<NodeId>> iter = index.find(tuple2); assertTrue(iter.hasNext()); iter.next(); assertFalse(iter.hasNext()); } @Test public void TupleIndexRecordSPO_5() { TupleIndex index = create("SPO"); add(index, n1, n2, n3); add(index, n1, n2, n4); Tuple<NodeId> tuple2 = tuple(n1, n2, n3); Iterator<Tuple<NodeId>> iter = index.find(tuple2); Set<Tuple<NodeId>> x = Iter.toSet(iter); assertEquals(1, x.size()); assertTrue(x.contains(tuple(n1, n2, n3))); assertFalse(x.contains(tuple(n1, n2, n4))); } @Test public void TupleIndexRecordSPO_6() { TupleIndex index = create("SPO"); add(index, n1, n2, n3); add(index, n1, n2, n4); Tuple<NodeId> tuple2 = tuple(n1, n2, NodeId.NodeIdAny); Iterator<Tuple<NodeId>> iter = index.find(tuple2); Set<Tuple<NodeId>> x = Iter.toSet(iter); assertEquals(2, x.size()); assertTrue(x.contains(tuple(n1, n2, n3))); assertTrue(x.contains(tuple(n1, n2, n4))); } @Test public void TupleIndexRecordSPO_7() { TupleIndex index = create("SPO"); add(index, n1, n2, n3); add(index, n1, n2, n4); Tuple<NodeId> tuple2 = tuple(n1, NodeId.NodeIdAny, NodeId.NodeIdAny); Iterator<Tuple<NodeId>> iter = index.find(tuple2); Set<Tuple<NodeId>> x = Iter.toSet(iter); assertEquals(2, x.size()); assertTrue(x.contains(tuple(n1, n2, n3))); assertTrue(x.contains(tuple(n1, n2, n4))); } @Test public void TupleIndexRecordSPO_8() { TupleIndex index = create("SPO"); add(index, n1, n2, n3); add(index, n2, n3, n4); { Tuple<NodeId> tuple2 = tuple(n1, NodeId.NodeIdAny, NodeId.NodeIdAny); Iterator<Tuple<NodeId>> iter = index.find(tuple2); Set<Tuple<NodeId>> x = Iter.toSet(iter); assertEquals(1, x.size()); assertTrue(x.contains(tuple(n1, n2, n3))); } { Tuple<NodeId> tuple2 = tuple(n2, NodeId.NodeIdAny, NodeId.NodeIdAny); Iterator<Tuple<NodeId>> iter = index.find(tuple2); Set<Tuple<NodeId>> x = Iter.toSet(iter); assertEquals(1, x.size()); assertTrue(x.contains(tuple(n2, n3, n4))); } } @Test public void TupleIndexRecordPOS_1() { TupleIndex index = create("POS"); add(index, n1, n2, n3); Tuple<NodeId> tuple2 = tuple(n1, n2, n3); Iterator<Tuple<NodeId>> iter = index.find(tuple2); assertTrue("Can't find tuple", iter.hasNext()); iter.next(); assertFalse(iter.hasNext()); } @Test public void TupleIndexRecordPOS_2() { TupleIndex index = create("POS"); add(index, n1, n2, n3); Tuple<NodeId> tuple2 = tuple(null, n2, null); Iterator<Tuple<NodeId>> iter = index.find(tuple2); assertTrue("Can't find tuple",iter.hasNext()); iter.next(); assertFalse(iter.hasNext()); } @Test public void TupleIndexRecordPOS_3() { TupleIndex index = create("POS"); add(index, n1, n2, n3); Tuple<NodeId> tuple2 = tuple(null, n2, n3); Iterator<Tuple<NodeId>> iter = index.find(tuple2); assertTrue("Can't find tuple", iter.hasNext()); iter.next(); assertFalse(iter.hasNext()); } @Test public void TupleIndexRecordFindNot_1() { TupleIndex index = create("SPO"); add(index, n1, n2, n3); Tuple<NodeId> tuple2 = tuple(n4, n5, n6); Iterator<Tuple<NodeId>> iter = index.find(tuple2); assertNotNull(iter); assertFalse(iter.hasNext()); } @Test public void TupleIndexRecordFindNot_2() { TupleIndex index = create("SPO"); add(index, n1, n2, n3); Tuple<NodeId> tuple2 = tuple(n1, n5, n6); Iterator<Tuple<NodeId>> iter = index.find(tuple2); assertFalse(iter.hasNext()); } @Test public void TupleIndexRecordFindNot_3() { TupleIndex index = create("SPO"); add(index, n1, n2, n3); Tuple<NodeId> tuple2 = tuple(n1, null, n6); Iterator<Tuple<NodeId>> iter = index.find(tuple2); assertFalse(iter.hasNext()); } @Test public void TupleIndexRecordFindNot_4() { TupleIndex index = create("SPO"); add(index, n1, n2, n3); add(index, n1, n5, n6); Tuple<NodeId> tuple2 = tuple(n4, n5, n6); Iterator<Tuple<NodeId>> iter = index.find(tuple2); assertFalse(iter.hasNext()); } @Test public void TupleIndexRecordFindNot_5() { TupleIndex index = create("SPO"); add(index, n1, n2, n3); add(index, n1, n5, n6); Tuple<NodeId> tuple2 = tuple(n2, n5, n6); Iterator<Tuple<NodeId>> iter = index.find(tuple2); assertFalse(iter.hasNext()); } @Test public void TupleIndexRecordFindNot_6() { TupleIndex index = create("SPO"); add(index, n1, n2, n3); add(index, n4, n5, n6); Tuple<NodeId> tuple2 = tuple(n1, null, n6); Iterator<Tuple<NodeId>> iter = index.find(tuple2); assertFalse(iter.hasNext()); } }
30.807547
81
0.602278
93eefbd3d955fcce3f2f9db1d68e326a986e7dcf
1,823
package mods.skipsign.fabric.client.renderer; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.MultiBufferSource; import net.minecraft.client.renderer.blockentity.BlockEntityRendererProvider; import net.minecraft.client.renderer.blockentity.ChestRenderer; import net.minecraft.core.BlockPos; import net.minecraft.world.level.block.entity.BlockEntity; import net.minecraft.world.level.block.entity.LidBlockEntity; import com.mojang.blaze3d.vertex.PoseStack; import mods.skipsign.fabric.SkipSignMod; import mods.skipsign.fabric.ViewMode; public class ChestRendererEx<T extends BlockEntity & LidBlockEntity> extends ChestRenderer<T> { public ChestRendererEx(BlockEntityRendererProvider.Context context) { super(context); } @Override public void render(T entity, float partialTicks, PoseStack matrixStackIn, MultiBufferSource bufferIn, int combinedLightIn, int combinedOverlayIn) { Minecraft client = Minecraft.getInstance(); if (!SkipSignMod.config.enableMod || entity.getBlockPos() == BlockPos.ZERO || client.player == null || isVisible(entity)) { super.render(entity, partialTicks, matrixStackIn, bufferIn, combinedLightIn, combinedOverlayIn); } } public boolean isVisible(T entity) { if (SkipSignMod.config.viewModeChest == ViewMode.FORCE) { return true; } if (SkipSignMod.config.viewModeChest == ViewMode.NONE) { return false; } if (SkipSignMod.client.isZooming()) { return true; } if (RendererHelper.IsInRangeToRenderDist( RendererHelper.GetDistancePlayerToBlockEntity(entity), SkipSignMod.config.viewRangeChest)) { return true; } return false; } }
34.396226
151
0.708722
5d487307e1ef5d6db7ac75a28903a24a6ff7c12b
1,936
/* * Copyright 2013 Haulmont * * 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 utils; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; import javax.sql.DataSource; import java.io.IOException; import java.net.URISyntaxException; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import static com.google.common.base.Preconditions.checkNotNull; public class FixtureUtils { public static void loadDb(DataSource ds, String file) throws IOException, SQLException, URISyntaxException { checkNotNull(ds); String sql = FileUtils.readFileToString(FileLoader.load(file), "UTF-8").replaceAll("--.*\r?\n+", ""); if (StringUtils.isEmpty(sql)) return; try (Connection connection = ds.getConnection()) { connection.setAutoCommit(false); for (String q: sql.split("[\\^][\\s|\\t|\\n]*")) { if (StringUtils.isEmpty(q)) continue; try (Statement statement = connection.createStatement()) { statement.executeUpdate(q); } catch (SQLException e) { connection.rollback(); throw new RuntimeException(e.getMessage(), e); } } connection.commit(); } catch (SQLException e) { throw new RuntimeException(e.getMessage(), e); } } }
34.571429
112
0.659091
fe37fa6a57d61c72308823382239b3848013ac1d
579
package com.itmuch.contentcenter.sentineltest; import com.alibaba.csp.sentinel.slots.block.BlockException; import lombok.extern.slf4j.Slf4j; @Slf4j public class TestControllerBlockHandlerClass { /** * 处理限流或者降级 * * 容错方案: * 1.超时 2,限流 3.断路器(打开 断开 半开) * * 4.仓壁模式(大家不在一个篮子里,每个Controller都有自己的线程池,所以sentinel没用) * sentinel可以分配每个COntroller的线程数 * * @param a * @param e * @return */ public static String block(String a, BlockException e) { log.warn("限流,或者降级了 block", e); return "限流,或者降级了 block"; } }
22.269231
60
0.639033
cf35e64549ef0efe04d6d1d7680e5a95470d0ee7
2,528
package org.elsys.ip.online_gun_shop.security; import com.fasterxml.jackson.databind.ObjectMapper; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import org.elsys.ip.online_gun_shop.model.User; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.AuthenticationException; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Date; import java.util.Objects; public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter { private final AuthenticationManager authenticationManager; public JWTAuthenticationFilter(AuthenticationManager authenticationManager) { this.authenticationManager = authenticationManager; } @Override public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { User user = null; try { user = new ObjectMapper().readValue(request.getInputStream(), User.class); } catch (IOException e) { e.printStackTrace(); } return this.authenticationManager.authenticate( new UsernamePasswordAuthenticationToken( Objects.requireNonNull(user).getUsername(), user.getPassword() ) ); } @Override protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException { User principal = (User) authResult.getPrincipal(); String token = Jwts.builder() .setSubject(principal.getUsername()) .setExpiration(new Date(System.currentTimeMillis() + SecurityConstants.EXPIRATION_TIME)) .signWith(SignatureAlgorithm.HS512, SecurityConstants.SECRET) .compact(); response.addHeader(SecurityConstants.HEADER_STRING, SecurityConstants.TOKEN_PREFIX.concat(token)); } }
40.774194
138
0.72587
d08708d947e1d501012371164df518ea8155f831
735
.class public final Lorg/pornaway/R$array; .super Ljava/lang/Object; .source "R.java" # annotations .annotation system Ldalvik/annotation/EnclosingClass; value = Lorg/pornaway/R; .end annotation .annotation system Ldalvik/annotation/InnerClass; accessFlags = 0x19 name = "array" .end annotation # static fields .field public static final help_donation_google_catalog_values:I = 0x7f070000 .field public static final pref_apply_method_entries:I = 0x7f070001 .field public static final pref_apply_method_entries_values:I = 0x7f070002 # direct methods .method public constructor <init>()V .registers 1 .prologue .line 11 invoke-direct {p0}, Ljava/lang/Object;-><init>()V return-void .end method
21
77
0.755102
690e972ef696eadaee8b78416649cccc78d113c0
2,619
package com.chao.cloud.common.extra.feign.annotation; import java.util.concurrent.TimeUnit; import org.springframework.beans.factory.ObjectFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.http.HttpMessageConverters; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.cloud.openfeign.FeignAutoConfiguration; import org.springframework.cloud.openfeign.support.SpringEncoder; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.chao.cloud.common.extra.feign.encoder.FeignSpringFormEncoder; import com.chao.cloud.common.extra.feign.proxy.FeignFallbackProxy; import feign.Feign; import feign.codec.Encoder; import lombok.Data; import okhttp3.ConnectionPool; /** * openFeign-okhttp 配置 * @author 薛超 * @since 2019年8月26日 * @version 1.0.7 */ @Configuration @ConditionalOnClass(Feign.class) @AutoConfigureBefore(FeignAutoConfiguration.class) @ConfigurationProperties(prefix = "chao.cloud.feign.request") @Data public class FeignConfig { private Integer connectTimeout = 120;// 连接超时 private Integer readTimeout = 120;// 读超时 private Integer writeTimeout = 120;// 写超时 private Integer maxIdleConnections = 10;// 最大连接数 private long keepAliveDuration = 5;// 保持连接时间(分钟) @Autowired private ObjectFactory<HttpMessageConverters> messageConverters; @Bean public okhttp3.OkHttpClient okHttpClient(FeignConfig config) { return new okhttp3.OkHttpClient.Builder()// .readTimeout(config.readTimeout, TimeUnit.SECONDS)// .connectTimeout(config.connectTimeout, TimeUnit.SECONDS)// .writeTimeout(config.writeTimeout, TimeUnit.SECONDS)// .retryOnConnectionFailure(true)// 是否自动重连 .connectionPool( new ConnectionPool(config.maxIdleConnections, config.keepAliveDuration, TimeUnit.MINUTES))// .build(); } /** * Multipart form encoder encoder. * * @return the encoder */ @Bean public Encoder multipartFormEncoder() { return new FeignSpringFormEncoder(new SpringEncoder(messageConverters)); } /** * Multipart logger level feign . logger . level. * * @return the feign . logger . level */ @Bean public feign.Logger.Level multipartLoggerLevel() { return feign.Logger.Level.FULL; } /** * aop处理 * @return {@link FeignFallbackProxy} */ @Bean public FeignFallbackProxy FeignFallbackProxy() { return new FeignFallbackProxy(); } }
30.453488
98
0.786942
7670504f39617fbc17675794c4f4f8df13f6ec77
3,397
/** * 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.rest.api.service.impl; import io.gravitee.common.utils.UUID; import io.gravitee.repository.exceptions.TechnicalException; import io.gravitee.repository.management.api.WorkflowRepository; import io.gravitee.repository.management.model.Workflow; import io.gravitee.rest.api.model.WorkflowReferenceType; import io.gravitee.rest.api.model.WorkflowState; import io.gravitee.rest.api.model.WorkflowType; import io.gravitee.rest.api.service.WorkflowService; import io.gravitee.rest.api.service.exceptions.TechnicalManagementException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.Date; import java.util.List; /** * @author Azize ELAMRANI (azize at graviteesource.com) * @author GraviteeSource Team */ @Component public class WorkflowServiceImpl extends TransactionalService implements WorkflowService { private final Logger LOGGER = LoggerFactory.getLogger(WorkflowServiceImpl.class); @Autowired private WorkflowRepository workflowRepository; @Override public Workflow create(final WorkflowReferenceType referenceType, final String referenceId, final WorkflowType type, final String user, final WorkflowState state, final String comment) { final Workflow workflow = new Workflow(); workflow.setId(UUID.toString(UUID.random())); workflow.setReferenceType(referenceType.name()); workflow.setReferenceId(referenceId); workflow.setType(type.name()); workflow.setUser(user); workflow.setState(state.name()); workflow.setComment(comment); workflow.setCreatedAt(new Date()); try { return workflowRepository.create(workflow); } catch (TechnicalException ex) { final String message = "An error occurs while trying to create workflow of type " + workflow.getType(); LOGGER.error(message, ex); throw new TechnicalManagementException(message, ex); } } @Override public List<Workflow> findByReferenceAndType(final WorkflowReferenceType referenceType, final String referenceId, final WorkflowType type) { try { return workflowRepository.findByReferenceAndType(referenceType.name(), referenceId, type.name()); } catch (TechnicalException ex) { final String message = "An error occurs while trying to find workflow by ref " + referenceType + "/" + referenceId + " and type " + type; LOGGER.error(message, ex); throw new TechnicalManagementException(message, ex); } } }
41.426829
120
0.71416
94189e43a6f26a5057ef1f885ed570c8e1cbd4bc
354
package vswe.stevescarts.mixins; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Mutable; import org.spongepowered.asm.mixin.gen.Accessor; import net.minecraft.screen.slot.Slot; @Mixin(Slot.class) public interface SlotAccessor { @Mutable @Accessor("x") void setX(int x); @Mutable @Accessor("y") void setY(int y); }
18.631579
48
0.762712
6358d45b5b4e15b0e08b69a5bc65682c13a84b96
2,199
package com.bysj.imageutil.adapter; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import com.bysj.imageutil.R; import com.bysj.imageutil.adapter.listener.ICropOnClickListener; import com.bysj.imageutil.bean.ICropSetBean; import java.util.ArrayList; /** * 图片裁剪设置适配器 * * Create on 2021-3-2 */ public class ICropSetAdapter extends RecyclerView.Adapter<ICropSetAdapter.SetViewHolder> { private ArrayList<ICropSetBean> data; private ICropOnClickListener listener = null; public ICropSetAdapter(ArrayList<ICropSetBean> data) { this.data = data; } public ICropSetAdapter(ArrayList<ICropSetBean> data, ICropOnClickListener listener) { this.data = data; this.listener = listener; } @NonNull @Override public SetViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_crop_set_item, parent, false); return new SetViewHolder(view); } @Override public void onBindViewHolder(@NonNull SetViewHolder holder, int position) { holder.mTv.setText(data.get(position).getTitle()); holder.mPosition = position; } @Override public int getItemCount() { return data.size(); } class SetViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { public TextView mTv; public int mPosition; public SetViewHolder(@NonNull View itemView) { super(itemView); mTv = itemView.findViewById(R.id.tv_crop); mTv.setOnClickListener(this); } @Override public void onClick(View view) { if ( listener != null ) { int id = view.getId(); if ( id == R.id.tv_crop ) { listener.onItemClick(mPosition); } } } } public void setOnItemClick(ICropOnClickListener listener) { this.listener = listener; } }
23.902174
117
0.663938
34817b20c4ec966df30168efb3f2bd3f198f5e02
6,112
/* * Copyright (c) 2001-2009, Jean Tessier * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of Jean Tessier nor the names of his contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.jeantessier.dependency; import java.io.*; import javax.xml.parsers.*; import org.xml.sax.*; import junit.framework.*; public class TestNodeLoader extends TestCase { private static final String MY_PACKAGE_NAME = "mypackage"; private static final String MY_CLASS_NAME = "mypackage.MyClass"; private static final String MY_FEATURE_NAME = "mypackage.MyClass.myFeature"; private static final String OTHER_PACKAGE_NAME = "otherpackage"; private static final String OTHER_CLASS_NAME = "otherpackage.OtherClass"; private static final String OTHER_FEATURE_NAME = "otherpackage.OtherClass.otherFeature"; public void testReadDocument() throws IOException, ParserConfigurationException, SAXException { StringBuffer xml = new StringBuffer(); xml.append("<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n"); xml.append("\n"); xml.append("<!DOCTYPE dependencies SYSTEM \"http://depfind.sourceforge.net/dtd/dependencies.dtd\">\n"); xml.append("\n"); xml.append("<dependencies>\n"); xml.append(" <package confirmed=\"yes\">\n"); xml.append(" <name>").append(MY_PACKAGE_NAME).append("</name>\n"); xml.append(" <outbound type=\"package\" confirmed=\"no\">").append(OTHER_PACKAGE_NAME).append("</outbound>\n"); xml.append(" <class confirmed=\"yes\">\n"); xml.append(" <name>").append(MY_CLASS_NAME).append("</name>\n"); xml.append(" <outbound type=\"class\" confirmed=\"no\">").append(OTHER_CLASS_NAME).append("</outbound>\n"); xml.append(" <feature confirmed=\"yes\">\n"); xml.append(" <name>").append(MY_FEATURE_NAME).append("</name>\n"); xml.append(" <outbound type=\"feature\" confirmed=\"no\">").append(OTHER_FEATURE_NAME).append("</outbound>\n"); xml.append(" </feature>\n"); xml.append(" </class>\n"); xml.append(" </package>\n"); xml.append(" <package confirmed=\"no\">\n"); xml.append(" <name>").append(OTHER_PACKAGE_NAME).append("</name>\n"); xml.append(" <inbound type=\"package\" confirmed=\"yes\">").append(MY_PACKAGE_NAME).append("</inbound>\n"); xml.append(" <class confirmed=\"no\">\n"); xml.append(" <name>").append(OTHER_CLASS_NAME).append("</name>\n"); xml.append(" <inbound type=\"class\" confirmed=\"yes\">").append(MY_CLASS_NAME).append("</inbound>\n"); xml.append(" <feature confirmed=\"no\">\n"); xml.append(" <name>").append(OTHER_FEATURE_NAME).append("</name>\n"); xml.append(" <inbound type=\"feature\" confirmed=\"yes\">").append(MY_FEATURE_NAME).append("</inbound>\n"); xml.append(" </feature>\n"); xml.append(" </class>\n"); xml.append(" </package>\n"); xml.append("</dependencies>\n"); NodeLoader loader = new NodeLoader(); NodeFactory factory = loader.load(new StringReader(xml.toString())); assertEquals("nb packages", 2, factory.getPackages().size()); assertNotNull("missing package", factory.getPackages().get(MY_PACKAGE_NAME)); assertTrue("package is inferred", factory.getPackages().get(MY_PACKAGE_NAME).isConfirmed()); assertNotNull("missing package", factory.getPackages().get(OTHER_PACKAGE_NAME)); assertFalse("package is confirmed", factory.getPackages().get(OTHER_PACKAGE_NAME).isConfirmed()); assertEquals("nb classes", 2, factory.getClasses().size()); assertNotNull("missing class", factory.getClasses().get(MY_CLASS_NAME)); assertTrue("class is inferred", factory.getClasses().get(MY_CLASS_NAME).isConfirmed()); assertNotNull("missing class", factory.getClasses().get(OTHER_CLASS_NAME)); assertFalse("class is confirmed", factory.getClasses().get(OTHER_CLASS_NAME).isConfirmed()); assertEquals("nb features", 2, factory.getFeatures().size()); assertNotNull("missing feature", factory.getFeatures().get(MY_FEATURE_NAME)); assertTrue("feature is inferred", factory.getFeatures().get(MY_FEATURE_NAME).isConfirmed()); assertNotNull("missing feature", factory.getFeatures().get(OTHER_FEATURE_NAME)); assertFalse("feature is confirmed", factory.getFeatures().get(OTHER_FEATURE_NAME).isConfirmed()); } }
57.121495
134
0.656577
f026af284dab4300743f5b81a0ff1671f17d753b
1,859
package com.tiagoespinha.popmovee.ioc.modules; import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.widget.Toast; import com.squareup.picasso.Picasso; import com.squareup.picasso.Target; import com.tiagoespinha.popmovee.R; import com.tiagoespinha.popmovee.model.MovieMetadata; import java.util.function.Function; import javax.inject.Named; import javax.inject.Singleton; import dagger.Module; import dagger.Provides; import io.reactivex.functions.Consumer; @Module public class MovieDetailsActivityModule { @Provides @Singleton public Function<Activity, Consumer<Throwable>> provideMovieDetailsFetchErrorHandler() { return activity -> new Consumer<Throwable>() { Toast toast = null; @Override public void accept(Throwable throwable) throws Exception { Context context = activity.getApplicationContext(); if (toast != null) { toast.cancel(); } toast = Toast.makeText(context, context.getString(R.string.error_loading_movies_showing_favorites), Toast.LENGTH_SHORT); toast.show(); } }; } @Provides @Singleton @Named("SavePosterToFileTarget") public Function<MovieMetadata, Target> provideSavePosterToFileTarget() { return (movieMetadata) -> new Target() { @Override public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) { } @Override public void onBitmapFailed(Drawable errorDrawable) { } @Override public void onPrepareLoad(Drawable placeHolderDrawable) { } }; } }
27.746269
91
0.642281