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
fe5b3b1668513432cd091c61dd16c0924060455e
2,751
package test.ethereum.blockstore; import org.ethereum.core.Block; import org.ethereum.core.Genesis; import org.ethereum.db.InMemoryBlockStore; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.spongycastle.util.encoders.Hex; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.util.List; import static org.junit.Assert.*; /** * @author: Roman Mandeleil * Created on: 30/01/2015 11:04 */ public class InMemoryBlockStoreTest { private static final Logger logger = LoggerFactory.getLogger("test"); private InMemoryBlockStore blockStore; @Before public void setup() throws URISyntaxException, IOException { blockStore = new InMemoryBlockStore(); URL scenario1 = ClassLoader .getSystemResource("blockstore/load.dmp"); File file = new File(scenario1.toURI()); List<String> strData = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8); for (String blockRLP : strData) { Block block = new Block( Hex.decode(blockRLP)); logger.info("adding block.hash: {}", Hex.toHexString(block.getHash()).substring(6)); blockStore.saveBlock(block, null); } } @Test public void testSaving8001Blocks() { Block bestBlock = blockStore.getBestBlock(); Long bestIndex = blockStore.getBestBlock().getNumber(); Long firstIndex = bestIndex - InMemoryBlockStore.MAX_BLOCKS; assertTrue(bestIndex == 8001); assertTrue(firstIndex == 7001); assertTrue(blockStore.getBlockByNumber(7000) == null); assertTrue(blockStore.getBlockByNumber(8002) == null); Block byHashBlock = blockStore.getBlockByHash(bestBlock.getHash()); assertTrue(bestBlock.getNumber() == byHashBlock.getNumber()); byte[] hashFor8500 = blockStore.getBlockByNumber(7500).getHash(); Block block8500 = blockStore.getBlockByHash(hashFor8500); assertTrue(block8500.getNumber() == 7500); } @Test public void testListOfHashes(){ Block block = blockStore.getBlockByNumber(7500); byte[] hash = block.getHash(); List<byte[]> hashes = blockStore.getListOfHashesStartFrom(hash, 700); byte[] lastHash = hashes.get(hashes.size() - 1); assertEquals(Hex.toHexString(blockStore.getBestBlock().getHash()), Hex.toHexString(lastHash)); assertTrue(hashes.size() == 502); } }
29.902174
96
0.659397
526a9aeb4de5479babae70fbe37a237e5b3954cc
4,989
/* * Copyright (c) 2019, TheStonedTurtle <https://github.com/TheStonedTurtle> * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package net.runelite.client.plugins.miscplugins.itemskeptondeath; import com.google.common.collect.ImmutableMap; import lombok.AllArgsConstructor; import lombok.Getter; import net.runelite.api.ItemID; import javax.annotation.Nullable; import java.util.Map; /** * Degradable/Non-rechargeable Jewelry death prices are usually determined by the amount of charges the item has left. * The price of each charge is based on the GE price of the fully charged item divided by the maximum item charges * Charge price = GE Price / Max Charges * Death Price = Charge price * Current Charges */ @AllArgsConstructor @Getter enum DynamicPriceItem { GAMES_NECKLACE1(ItemID.GAMES_NECKLACE1, 1, 8, ItemID.GAMES_NECKLACE8), GAMES_NECKLACE2(ItemID.GAMES_NECKLACE2, 2, 8, ItemID.GAMES_NECKLACE8), GAMES_NECKLACE3(ItemID.GAMES_NECKLACE3, 3, 8, ItemID.GAMES_NECKLACE8), GAMES_NECKLACE4(ItemID.GAMES_NECKLACE4, 4, 8, ItemID.GAMES_NECKLACE8), GAMES_NECKLACE5(ItemID.GAMES_NECKLACE5, 5, 8, ItemID.GAMES_NECKLACE8), GAMES_NECKLACE6(ItemID.GAMES_NECKLACE6, 6, 8, ItemID.GAMES_NECKLACE8), GAMES_NECKLACE7(ItemID.GAMES_NECKLACE7, 7, 8, ItemID.GAMES_NECKLACE8), RING_OF_DUELING1(ItemID.RING_OF_DUELING1, 1, 8, ItemID.RING_OF_DUELING8), RING_OF_DUELING2(ItemID.RING_OF_DUELING2, 2, 8, ItemID.RING_OF_DUELING8), RING_OF_DUELING3(ItemID.RING_OF_DUELING3, 3, 8, ItemID.RING_OF_DUELING8), RING_OF_DUELING4(ItemID.RING_OF_DUELING4, 4, 8, ItemID.RING_OF_DUELING8), RING_OF_DUELING5(ItemID.RING_OF_DUELING5, 5, 8, ItemID.RING_OF_DUELING8), RING_OF_DUELING6(ItemID.RING_OF_DUELING6, 6, 8, ItemID.RING_OF_DUELING8), RING_OF_DUELING7(ItemID.RING_OF_DUELING7, 7, 8, ItemID.RING_OF_DUELING8), RING_OF_RETURNING1(ItemID.RING_OF_RETURNING1, 1, 5, ItemID.RING_OF_RETURNING5), RING_OF_RETURNING2(ItemID.RING_OF_RETURNING2, 2, 5, ItemID.RING_OF_RETURNING5), RING_OF_RETURNING3(ItemID.RING_OF_RETURNING3, 3, 5, ItemID.RING_OF_RETURNING5), RING_OF_RETURNING4(ItemID.RING_OF_RETURNING4, 4, 5, ItemID.RING_OF_RETURNING5), NECKLACE_OF_PASSAGE1(ItemID.NECKLACE_OF_PASSAGE1, 1, 5, ItemID.NECKLACE_OF_PASSAGE5), NECKLACE_OF_PASSAGE2(ItemID.NECKLACE_OF_PASSAGE2, 2, 5, ItemID.NECKLACE_OF_PASSAGE5), NECKLACE_OF_PASSAGE3(ItemID.NECKLACE_OF_PASSAGE3, 3, 5, ItemID.NECKLACE_OF_PASSAGE5), NECKLACE_OF_PASSAGE4(ItemID.NECKLACE_OF_PASSAGE4, 4, 5, ItemID.NECKLACE_OF_PASSAGE5), BURNING_AMULET1(ItemID.BURNING_AMULET1, 1, 5, ItemID.BURNING_AMULET5), BURNING_AMULET2(ItemID.BURNING_AMULET2, 2, 5, ItemID.BURNING_AMULET5), BURNING_AMULET3(ItemID.BURNING_AMULET3, 3, 5, ItemID.BURNING_AMULET5), BURNING_AMULET4(ItemID.BURNING_AMULET4, 4, 5, ItemID.BURNING_AMULET5); private final int itemId; private final int currentCharges; private final int maxCharges; private final int chargedId; private static final Map<Integer, DynamicPriceItem> DYNAMIC_ITEMS; static { final ImmutableMap.Builder<Integer, DynamicPriceItem> map = ImmutableMap.builder(); for (final DynamicPriceItem p : values()) { map.put(p.itemId, p); } DYNAMIC_ITEMS = map.build(); } /** * Calculates the price off the partially charged jewelry based on the base items price * @param basePrice price of the base item, usually the trade-able variant * @return death price of the current DynamicPriceItem */ int calculateDeathPrice(final int basePrice) { return (basePrice / maxCharges) * currentCharges; } @Nullable static DynamicPriceItem find(int itemId) { return DYNAMIC_ITEMS.get(itemId); } }
45.770642
119
0.775306
e38f557348ea1f36efc2d13bfa5b7e8e462785f3
1,262
//James Shively III //ITC155 - Data Structures //Stani Meredith //Assignment Eight - ArrayIntList.java //Part 4 of 4 //this is just an extension of the class exercise we did last Thursday import java.util.NoSuchElementException; //provides a set of utilities for iterating public class ArrayListIterator { //instance variables private ArrayIntList list; //list to iterate over private int position; //current position within the list private boolean removeOK; //constructor public ArrayListIterator(ArrayIntList list) { this.list = list; position = 0; removeOK = false; } //return true if there are more elements public boolean hasNext() { return position < list.size(); } //pre: hasNext() //post: return the next element in the iteration public int next() { if(!hasNext()) { throw new NoSuchElementException(); } int result = list.get(position); position++; removeOK = true; return result; } //pre: next() has been called without a call on remove //post: remove the last element returned by the iterator public void remove() { if(!removeOK) { throw new IllegalStateException(); } list.remove(position - 1); position--; removeOK = false; } }
23.37037
71
0.68225
0f6fe9532bee939388781b2c66431277d0880c5b
472
package org.malagu.panda.security.access.provider; import java.util.Collection; import java.util.Map; import org.springframework.security.access.ConfigAttribute; /** * 组件权限信息提供者 * @author Kevin Yang (mailto:[email protected]) * @since 2016年1月22日 */ public interface ComponentConfigAttributeProvider { /** * 提供组件权限信息,以Map结构返回,Key为组件唯一标示,格式:{path}#{componentId}<br> * Value为对应的权限信息 * @return 权限信息 */ Map<String, Collection<ConfigAttribute>> provide(); }
22.47619
60
0.752119
d5cac859044bdd754d5ea4a7423a44c4c2e57a1d
2,995
/* * Copyright 2021 Shulie Technology, Co.Ltd * Email: [email protected] * 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, * See the License for the specific language governing permissions and * limitations under the License. */ package com.pamirs.tro.entity.domain.entity; import java.util.Date; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import com.pamirs.tro.common.util.DateToStringFormatSerialize; import com.pamirs.tro.common.util.LongToStringFormatSerialize; import org.springframework.format.annotation.DateTimeFormat; /** * 说明: prada获取http接口表 * * @author shulie * @version v1.0 * @Date: Create in 2019/3/4 19:59 */ public class TPradaHttpData { /** * 表id */ @JsonSerialize(using = LongToStringFormatSerialize.class) private Long tphdId; /** * 应用名称 */ private String appName; /** * 接口名称 */ private String interfaceName; /** * 接口类型 */ private String interfaceType; /** * 接口类型中文名称 */ private String interfaceValueName; /** * 创建时间 */ @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") @JsonSerialize(using = DateToStringFormatSerialize.class) private Date createTime; public String getInterfaceValueName() { return interfaceValueName; } public void setInterfaceValueName(String interfaceValueName) { this.interfaceValueName = interfaceValueName; } public Long getTphdId() { return tphdId; } public void setTphdId(Long tphdId) { this.tphdId = tphdId; } public String getAppName() { return appName; } public void setAppName(String appName) { this.appName = appName; } public String getInterfaceName() { return interfaceName; } public void setInterfaceName(String interfaceName) { this.interfaceName = interfaceName; } public String getInterfaceType() { return interfaceType; } public void setInterfaceType(String interfaceType) { this.interfaceType = interfaceType; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } @Override public String toString() { return "TPradaHttpData{" + "tphdId=" + tphdId + ", appName='" + appName + '\'' + ", interfaceName='" + interfaceName + '\'' + ", interfaceType='" + interfaceType + '\'' + ", interfaceValueName='" + interfaceValueName + '\'' + ", createTime=" + createTime + '}'; } }
23.582677
70
0.638397
faeb482159116f7b9a949ef7e56556c14938239e
2,246
/* * Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.connector.amazons3.pojo; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import java.util.List; @XmlRootElement(name = "CORSRule") public class CORSRule { private List<String> allowedHeader; private List<String> allowedMethod; private List<String> allowedOrigin; private List<String> exposeHeader; private int maxAgeSeconds; @XmlElement(name = "AllowedHeader") public List<String> getAllowedHeader() { return allowedHeader; } public void setAllowedHeader(List<String> allowedHeader) { this.allowedHeader = allowedHeader; } @XmlElement(name = "AllowedMethod") public List<String> getAllowedMethod() { return allowedMethod; } public void setAllowedMethod(List<String> allowedMethod) { this.allowedMethod = allowedMethod; } @XmlElement(name = "AllowedOrigin") public List<String> getAllowedOrigin() { return allowedOrigin; } public void setAllowedOrigin(List<String> allowedOrigin) { this.allowedOrigin = allowedOrigin; } @XmlElement(name = "ExposeHeader") public List<String> getExposeHeader() { return exposeHeader; } public void setExposeHeader(List<String> exposeHeader) { this.exposeHeader = exposeHeader; } @XmlElement(name = "MaxAgeSeconds") public int getMaxAgeSeconds() { return maxAgeSeconds; } public void setMaxAgeSeconds(int maxAgeSeconds) { this.maxAgeSeconds = maxAgeSeconds; } }
29.168831
75
0.702582
93ab5ae290c941d9cba95290fe07d3a86c3323f7
1,765
/* * Copyright 2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.internal.resource.transport.http; import org.gradle.api.resources.ResourceException; import org.gradle.internal.resource.ExternalResourceName; import org.gradle.internal.resource.transfer.ExternalResourceLister; import java.util.List; public class HttpResourceLister implements ExternalResourceLister { private final HttpResourceAccessor accessor; public HttpResourceLister(HttpResourceAccessor accessor) { this.accessor = accessor; } @Override public List<String> list(final ExternalResourceName directory) { return accessor.withContent(directory, true, (inputStream, metaData) -> { String contentType = metaData.getContentType(); ApacheDirectoryListingParser directoryListingParser = new ApacheDirectoryListingParser(); try { return directoryListingParser.parse(directory.getUri(), inputStream, contentType); } catch (Exception e) { throw new ResourceException(directory.getUri(), String.format("Unable to parse HTTP directory listing for '%s'.", directory.getUri()), e); } }); } }
39.222222
154
0.724646
ea5309ffe1287afe2f52f900a90359cef2e89705
2,448
package com.shijingsh.ai.jsat.math.integration; import com.shijingsh.ai.jsat.math.Function1D; import com.shijingsh.ai.jsat.math.Function1D; /** * This class provides an implementation of the Adaptive Simpson method for * numerically computing an integral * * @author Edward Raff */ public class AdaptiveSimpson { /** * Numerically computes the integral of the given function * * @param f the function to integrate * @param tol the precision for the desired result * @param a the lower limit of the integral * @param b the upper limit of the integral * @return an approximation of the integral of &int;<sub>a</sub><sup>b</sup>f(x) * , dx */ static public double integrate(Function1D f, double tol, double a, double b) { return integrate(f, tol, a, b, 100); } /** * Numerically computes the integral of the given function * * @param f the function to integrate * @param tol the precision for the desired result * @param a the lower limit of the integral * @param b the upper limit of the integral * @param maxDepth the maximum recursion depth * @return an approximation of the integral of &int;<sub>a</sub><sup>b</sup>f(x) * , dx */ static public double integrate(Function1D f, double tol, double a, double b, int maxDepth) { if (a == b) return 0; else if (a > b) throw new RuntimeException("Integral upper limit (" + b + ") must be larger than the lower-limit (" + a + ")"); double h = b - a; double c = (a + b) / 2; double f_a = f.f(a); double f_b = f.f(b); double f_c = f.f(c); double one_simpson = h * (f_a + 4 * f_c + f_b) / 6; double d = (a + c) / 2; double e = (c + b) / 2; double two_simpson = h * (f_a + 4 * f.f(d) + 2 * f_c + 4 * f.f(e) + f_b) / 12; if (maxDepth <= 0) return two_simpson; if (Math.abs(one_simpson - two_simpson) < 15 * tol) return two_simpson + (two_simpson - one_simpson) / 15; else { double left_simpson = integrate(f, tol / 2, a, c, maxDepth - 1); double right_simpson = integrate(f, tol / 2, c, b, maxDepth - 1); return left_simpson + right_simpson; } } }
34.971429
124
0.5625
1bdcc67d89b82a920771a977b116cf082f5b7836
3,095
/* Copyright 2013 the original author or authors. Licensed under the Apache License, Version 2.0 the "License"; you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package io.neba.core.util; import org.assertj.core.api.AbstractAssert; import java.util.Arrays; import java.util.Collection; /** * @author Olaf Otto */ @SuppressWarnings({ "unchecked", "rawtypes" }) public class ConcurrentMultiValueMapAssert extends AbstractAssert<ConcurrentMultiValueMapAssert, ConcurrentDistinctMultiValueMap> { public static ConcurrentMultiValueMapAssert assertThat(ConcurrentDistinctMultiValueMap<?, ?> map) { return new ConcurrentMultiValueMapAssert(map); } public ConcurrentMultiValueMapAssert contains(Object key, Object value) { Collection<?> values = valuesForKey(key); if (!values.contains(value)) { failWithMessage(values + " does not contain the value " + value + "."); } return myself; } public ConcurrentMultiValueMapAssert contains(Object key, Object... values) { Collection<?> containedValues = valuesForKey(key); if (!containedValues.containsAll(Arrays.asList(values))) { failWithMessage(Arrays.toString(values) + " do not contain the values " + Arrays.toString(values) + "."); } return myself; } public ConcurrentMultiValueMapAssert containsOnly(Object key, Object... values) { Collection<?> containedValues = valuesForKey(key); if (containedValues.size() != values.length || !containedValues.containsAll(Arrays.asList(values))) { failWithMessage("Expected " + containedValues + " to only contain " + Arrays.toString(values) + "."); } return myself; } void containsExactlyOneValueFor(Object key) { Collection<?> values = valuesOrFail(key); if (values.size() != 1) { failWithMessage("Expected exactly one value for " + key + ", but got " + values + "."); } } void doesNotContain(Object key) { if (this.actual.get(key) != null) { failWithMessage(this.actual + " does contains the key " + key + "."); } } private Collection<?> valuesForKey(Object key) { return valuesOrFail(key); } private ConcurrentMultiValueMapAssert(ConcurrentDistinctMultiValueMap map) { super(map, ConcurrentMultiValueMapAssert.class); } private Collection<?> valuesOrFail(Object key) { Collection<?> values = this.actual.get(key); if (values == null) { failWithMessage(this.actual + " does not contain the key " + key + "."); } return values; } }
35.574713
131
0.671729
033e1f870fe84337f0d9180b82c915d9d40edad6
748
package online.zhaopei.myproject.sqlprovide.para; import java.io.Serializable; import org.apache.ibatis.jdbc.SQL; public class CustomsSqlProvide implements Serializable { /** * serialVersionUID */ private static final long serialVersionUID = -1630423204207078524L; public String getCustomsByCodeSql() { return new SQL() {{ this.SELECT("*"); this.FROM("customs"); this.WHERE("customs_code = #{customsCode}"); }}.toString(); } public String getCustomsSql() { return new SQL() {{ this.SELECT("customs_code"); this.SELECT("abbr_cust"); this.FROM("customs"); }}.toString(); } public String countCustomsSql() { return new SQL() {{ this.SELECT("count(1)"); this.FROM("customs"); }}.toString(); } }
20.216216
68
0.676471
1ef705adbd2562529bb29dc2283fd0c69a58640c
257
package com.ztiany.ndk.importlibs; /** * @author Ztiany * Email: [email protected] * Date : 2017-11-04 23:07 */ class JniUtils { public native String stringFromJNI(); static { System.loadLibrary("hello-libs"); } }
16.0625
41
0.595331
d9d26e8c48db9df3e5aeb536783cb02834d41f50
1,241
package casadocodigo.casadocodigo.util.validators; import casadocodigo.casadocodigo.dto.AutorDTO; import casadocodigo.casadocodigo.gateway.repositories.AutorRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.Errors; import org.springframework.validation.ValidationUtils; import org.springframework.validation.Validator; public class AutorValidator implements Validator { @Autowired private AutorRepository autorRepository; @Override public boolean supports(Class<?> aClass) { return AutorDTO.class.equals(aClass); } @Override public void validate(Object o, Errors errors) { ValidationUtils.rejectIfEmpty(errors, "nomeAutor", "O nome do autor não pode estar vazio"); ValidationUtils.rejectIfEmpty(errors, "emailAutor", "O e-mail do autor não pode estar vazio"); ValidationUtils.rejectIfEmpty(errors, "descAutor", "A descrição do autor não pode estar vazia"); AutorDTO autorDTO = (AutorDTO) o; var listaAutores = autorRepository.findByEmail(autorDTO.getEmailAutor()); if (!listaAutores.isEmpty()){ errors.rejectValue("emailAutor", "O e-mail já existe!"); } } }
31.820513
104
0.737309
6a5c00d08def663f249184e27979ae570ff0beb4
3,033
/* Copyright (C) 2013-2021 TU Dortmund * This file is part of AutomataLib, http://www.automatalib.net/. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.automatalib.modelcheckers.ltsmin; import java.io.File; import java.io.IOException; import java.util.Collection; import net.automatalib.automata.transducers.MealyMachine; import net.automatalib.automata.transducers.impl.compact.CompactMealy; import net.automatalib.serialization.etf.writer.Mealy2ETFWriterAlternating; import net.automatalib.serialization.fsm.parser.FSM2MealyParserAlternating; import net.automatalib.words.impl.Alphabets; /** * A model checker using LTSmin for Mealy machines using alternating edge semantics. * * The implementation uses {@link FSM2MealyParserAlternating}, and {@link Mealy2ETFWriterAlternating}, to read the * {@link MealyMachine}, and write the {@link MealyMachine} respectively. * * @param <I> the input type. * @param <O> the output type. * @param <R> the type of a counterexample * * @author Jeroen Meijer */ public interface LTSminAlternating<I, O, R> extends LTSminMealy<I, O, R> { /** * Whether this model checker requires the original Mealy machine to read the Mealy machines from an FSM. * * @return whether the original automaton is required. */ boolean requiresOriginalAutomaton(); @Override default CompactMealy<I, O> fsm2Mealy(File fsm, MealyMachine<?, I, ?, O> originalAutomaton, Collection<? extends I> inputs) throws IOException { // Here we optionally provide the parse method with the original automaton. So that an implementation can // decide whether undefined outputs are allowed in the fsm or not. // If the original automaton is not required, yet there is an undefined output in the FSM an exception will // be thrown. return FSM2MealyParserAlternating.getParser(inputs, requiresOriginalAutomaton() ? originalAutomaton : null, getString2Input(), getString2Output()).readModel(fsm); } @Override default void mealy2ETF(MealyMachine<?, I, ?, O> automaton, Collection<? extends I> inputs, File etf) throws IOException { Mealy2ETFWriterAlternating.<I, O>getInstance().writeModel(etf, automaton, Alphabets.fromCollection(inputs)); } }
43.328571
116
0.683482
0d16504b4ce57d58cad1d2bad7948c4d73d91c1d
1,947
/* * 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.eventmesh.runtime.core.protocol.http.push; import com.google.common.collect.Lists; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.RandomUtils; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import java.util.Iterator; import java.util.List; public class HTTPClientPool { private List<CloseableHttpClient> clients = Lists.newArrayList(); private int core = 1; public HTTPClientPool(int core) { this.core = core; } public CloseableHttpClient getClient() { if (CollectionUtils.size(clients) < core) { CloseableHttpClient client = HttpClients.createDefault(); clients.add(client); return client; } return clients.get(RandomUtils.nextInt(core, 2 * core) % core); } public void shutdown() throws Exception { Iterator<CloseableHttpClient> itr = clients.iterator(); while (itr.hasNext()) { CloseableHttpClient client = itr.next(); client.close(); itr.remove(); } } }
33.568966
75
0.706215
9c5562219f7580a740b025ab2118a88039dffea1
1,564
package com.chx.plugin.memo; import com.intellij.openapi.components.ApplicationComponent; import com.intellij.openapi.components.PersistentStateComponent; import com.intellij.openapi.components.State; import com.intellij.openapi.components.Storage; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * @author chenxi */ //@State(name = "MemoApplicationComponent", storages = @Storage(StoragePathMacros.WORKSPACE_FILE)) /* Unknown macro: $WORKSPACE_FILE$ ? */ @State(name = "MemoApplicationComponent", storages = @Storage("~/idea-plugin/memo.xml")) public class MemoApplicationComponent implements ApplicationComponent, PersistentStateComponent<Memos> { private Memos memos = new Memos(); public MemoApplicationComponent() { } @Override public void initComponent() { // insert component initialization logic here } @Override public void disposeComponent() { // insert component disposal logic here } @Override @NotNull public String getComponentName() { return "Memo"; } /** * called every time the settings are saved * * @return */ @Nullable @Override public Memos getState() { memos.setLastSaveTimestamp(System.currentTimeMillis()); return memos; } @Override public void loadState(Memos memoState) { this.memos = memoState; } public Memos getMemos() { return memos; } public void setMemos(Memos memos) { this.memos = memos; } }
24.4375
104
0.685422
868442fdbf434d58577a198a1fd66051658cde4a
6,032
/* * Copyright (c) 2020, 2021, NECSTLab, Politecnico di Milano. 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 NECSTLab nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * Neither the name of Politecnico di Milano 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 ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.nvidia.grcuda.runtime.executioncontext; import com.nvidia.grcuda.GrCUDAContext; import com.nvidia.grcuda.GrCUDALogger; import com.nvidia.grcuda.runtime.CUDARuntime; import com.nvidia.grcuda.runtime.computation.GrCUDAComputationalElement; import com.nvidia.grcuda.runtime.computation.dependency.DependencyPolicyEnum; import com.nvidia.grcuda.runtime.computation.prefetch.PrefetcherEnum; import com.nvidia.grcuda.runtime.stream.GrCUDAStreamManager; import com.oracle.truffle.api.TruffleLanguage; import com.oracle.truffle.api.interop.UnsupportedTypeException; /** * Class used to monitor the state of GrCUDA execution, keep track of memory allocated, * kernels and other executable functions, and dependencies between elements. */ public class GrCUDAExecutionContext extends AbstractGrCUDAExecutionContext { /** * Reference to the {@link com.nvidia.grcuda.runtime.stream.GrCUDAStreamManager} that takes care of * scheduling computations on different streams; */ private final GrCUDAStreamManager streamManager; public GrCUDAExecutionContext(GrCUDAContext context, TruffleLanguage.Env env, DependencyPolicyEnum dependencyPolicy, PrefetcherEnum inputPrefetch) { this(new CUDARuntime(context, env), dependencyPolicy, inputPrefetch); } public GrCUDAExecutionContext(CUDARuntime cudaRuntime, DependencyPolicyEnum dependencyPolicy, PrefetcherEnum inputPrefetch) { this(cudaRuntime, new GrCUDAStreamManager(cudaRuntime), dependencyPolicy, inputPrefetch); } public GrCUDAExecutionContext(CUDARuntime cudaRuntime, GrCUDAStreamManager streamManager, DependencyPolicyEnum dependencyPolicy) { super(cudaRuntime, dependencyPolicy, PrefetcherEnum.NONE, ExecutionPolicyEnum.ASYNC); this.streamManager = streamManager; } public GrCUDAExecutionContext(CUDARuntime cudaRuntime, GrCUDAStreamManager streamManager, DependencyPolicyEnum dependencyPolicy, PrefetcherEnum inputPrefetch) { super(cudaRuntime, dependencyPolicy, inputPrefetch, ExecutionPolicyEnum.ASYNC); this.streamManager = streamManager; } /** * Register this computation for future execution by the {@link GrCUDAExecutionContext}, * and add it to the current computational DAG. * The actual execution might be deferred depending on the inferred data dependencies; */ @Override public Object registerExecution(GrCUDAComputationalElement computation) throws UnsupportedTypeException { // Add the new computation to the DAG ExecutionDAG.DAGVertex vertex = dag.append(computation); // Compute the stream where the computation will be done, if the computation can be performed asynchronously; streamManager.assignStream(vertex); // Prefetching; arrayPrefetcher.prefetchToGpu(vertex); // Start the computation; Object result = executeComputationSync(vertex); // Associate a CUDA event to this computation, if performed asynchronously; streamManager.assignEventStop(vertex); GrCUDALogger.getLogger(GrCUDALogger.EXECUTIONCONTEXT_LOGGER).finest("-- running " + vertex.getComputation()); return result; } @Override public boolean isAnyComputationActive() { return this.streamManager.isAnyComputationActive(); } public GrCUDAStreamManager getStreamManager() { return streamManager; } /** * Delete internal structures that require manual cleanup operations; */ @Override public void cleanup() { streamManager.cleanup(); } private Object executeComputationSync(ExecutionDAG.DAGVertex vertex) throws UnsupportedTypeException { // Before starting this computation, ensure that all its parents have finished their computation; streamManager.syncParentStreams(vertex); // Perform the computation; vertex.getComputation().setComputationStarted(); vertex.getComputation().updateIsComputationArrayAccess(); // Associate a CUDA event to the starting phase of the computation in order to get the Elapsed time from start to the end streamManager.assignEventStart(vertex); return vertex.getComputation().execute(); } }
46.045802
164
0.75945
381cf8edc545dca8f9c54e07698d6b36660d1bb4
356
package robot_components.radar; import robocode.AdvancedRobot; import robot_components.Manager; import robot_components.data_management.DataManager; public abstract class Radar implements Manager { protected AdvancedRobot _self; protected DataManager _data; public Radar(AdvancedRobot self, DataManager data) { _self = self; _data = data; } }
19.777778
52
0.803371
7354d2f475ee4c325dac08c061f8132763e2fb1d
495
package de.mineformers.investiture.allomancy.api.metal.stack; import de.mineformers.investiture.allomancy.api.metal.Metal; import javax.annotation.Nonnull; import java.util.List; import java.util.Set; import java.util.function.Supplier; public interface MetalStackProvider extends Supplier<List<MetalStack>> { List<MetalStack> consume(List<MetalStack> stacks, boolean simulate); @Nonnull List<MetalStack> getStored(Metal metal); @Nonnull Set<Metal> getStoredMetals(); }
24.75
72
0.779798
ecb14bac2c61c33a9d0a22959ee8ffca7bcbceb7
90
public interface Shared { String HELLO_WORLD_TASK_QUEUE = "HELLO_WORLD_TASK_QUEUE"; }
22.5
61
0.788889
a240747818fa0667ae81bd2dab654b4a7aab6b93
1,058
package com.tinytongtong.leetcodetest.targetoffer.question57; import java.util.Arrays; /** * @Description: https://leetcode-cn.com/problems/he-wei-sde-liang-ge-shu-zi-lcof/ * 剑指 Offer 57. 和为s的两个数字 * @Author tinytongtong * @Date 2020/9/15 5:06 PM * @Version */ public class FindTwoNumbersWithSum { private static int[] findTwoNumbersWithSum(int[] nums, int target) { if (nums == null || nums.length < 2) { return new int[0]; } int index1 = 0; int index2 = nums.length - 1; while (index2 > index1) { if (nums[index1] + nums[index2] == target) { return new int[]{nums[index1], nums[index2]}; } else if (nums[index1] + nums[index2] > target) { index2--; } else { index1++; } } return new int[0]; } public static void main(String[] args) { int[] nums = new int[]{1, 2, 4, 7, 11, 15}; System.out.println(Arrays.toString(findTwoNumbersWithSum(nums, 15))); } }
29.388889
82
0.556711
e4186e0cc153f56e7300cf39fe151114a31d3006
5,767
/* * The MIT License (MIT) * Copyright (c) 2016 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of * the Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.intel.genomicsdb; import htsjdk.tribble.Feature; import htsjdk.tribble.FeatureCodec; import htsjdk.variant.bcf2.BCF2Codec; import org.apache.hadoop.conf.Configurable; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.mapreduce.*; import org.apache.log4j.Logger; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class GenomicsDBInputFormat<VCONTEXT extends Feature, SOURCE> extends InputFormat<String, VCONTEXT> implements Configurable { private GenomicsDBConfiguration genomicsDBConfiguration; private Configuration configuration; Logger logger = Logger.getLogger(GenomicsDBInputFormat.class); /** * When this function is called, it is already assumed that configuration * object is set * * @param jobContext Hadoop Job context passed from newAPIHadoopRDD * defined in SparkContext * @return Returns a list of input splits * @throws FileNotFoundException Thrown if creaing configuration object fails */ public List<InputSplit> getSplits(JobContext jobContext) throws FileNotFoundException { genomicsDBConfiguration = new GenomicsDBConfiguration(configuration); genomicsDBConfiguration.setLoaderJsonFile( configuration.get(GenomicsDBConfiguration.LOADERJSON)); genomicsDBConfiguration.setQueryJsonFile( configuration.get(GenomicsDBConfiguration.QUERYJSON)); genomicsDBConfiguration.setHostFile( configuration.get(GenomicsDBConfiguration.MPIHOSTFILE)); List<String> hosts = genomicsDBConfiguration.getHosts(); ArrayList<InputSplit> inputSplits = new ArrayList<>(hosts.size()); for (int i = 0; i < hosts.size(); ++i) { GenomicsDBInputSplit split = new GenomicsDBInputSplit(); inputSplits.add(split); } return inputSplits; } public RecordReader<String, VCONTEXT> createRecordReader(InputSplit inputSplit, TaskAttemptContext taskAttemptContext) throws IOException, InterruptedException { String loaderJson; String queryJson; GenomicsDBFeatureReader<VCONTEXT, SOURCE> featureReader; GenomicsDBRecordReader<VCONTEXT, SOURCE> recordReader; if (taskAttemptContext != null) { Configuration configuration = taskAttemptContext.getConfiguration(); loaderJson = configuration.get(GenomicsDBConfiguration.LOADERJSON); queryJson = configuration.get(GenomicsDBConfiguration.QUERYJSON); } else { // If control comes here, means this method is called from // GenomicsDBRDD. Hence, the configuration object must be // set by setConf method, else this will lead to // NullPointerException assert(configuration!=null); loaderJson = configuration.get(GenomicsDBConfiguration.LOADERJSON); queryJson = configuration.get(GenomicsDBConfiguration.QUERYJSON); } featureReader = new GenomicsDBFeatureReader<VCONTEXT, SOURCE>( loaderJson, queryJson, (FeatureCodec<VCONTEXT, SOURCE>) new BCF2Codec()); recordReader = new GenomicsDBRecordReader<VCONTEXT, SOURCE>(featureReader); return recordReader; } /** * default constructor */ public GenomicsDBInputFormat() { } public GenomicsDBInputFormat(GenomicsDBConfiguration conf) { genomicsDBConfiguration = conf; } /** * Set the loader JSON file path * * @param jsonFile Full qualified path of the loader JSON file * @return Returns the same object for forward function calls */ public GenomicsDBInputFormat<VCONTEXT, SOURCE> setLoaderJsonFile(String jsonFile) { genomicsDBConfiguration.setLoaderJsonFile(jsonFile); return this; } /** * Set the query JSON file path * @param jsonFile Full qualified path of the query JSON file * @return Returns the same object for forward function calls */ public GenomicsDBInputFormat<VCONTEXT, SOURCE> setQueryJsonFile(String jsonFile) { genomicsDBConfiguration.setQueryJsonFile(jsonFile); return this; } /** * Set the host file path * @param hostFile Full qualified path of the hosts file * @return Returns the same object for forward function calls * @throws FileNotFoundException thrown if the hosts file is not found */ public GenomicsDBInputFormat<VCONTEXT, SOURCE> setHostFile(String hostFile) throws FileNotFoundException { genomicsDBConfiguration.setHostFile(hostFile); return this; } @Override public void setConf(Configuration configuration) { this.configuration = configuration; } @Override public Configuration getConf() { return configuration; } }
36.04375
89
0.751864
f0afddacf812e1f2e878f42e54778b075871d25c
2,711
package com.northgateps.nds.beis.ui.selenium.pagehelper; import java.util.Locale; import java.util.Random; import org.openqa.selenium.WebDriver; import com.northgateps.nds.beis.ui.selenium.pageobject.PersonalisedChangeEmailAddressPageObject; import com.northgateps.nds.platform.ui.selenium.PageObject; import com.northgateps.nds.platform.ui.selenium.core.BasePageHelper; import com.northgateps.nds.platform.ui.selenium.core.FormFiller; import com.northgateps.nds.platform.ui.selenium.core.PageHelper; /** * Selenium test helper class for personalised-change-email-address page */ @PageObject(pageObjectClass = PersonalisedChangeEmailAddressPageObject.class) public class PersonalisedChangeEmailAddressPageHelper extends BasePageHelper<PersonalisedChangeEmailAddressPageObject> implements PageHelper { //set default Form Filler { setFormFiller(new FormFiller() { @Override public void fill(BasePageHelper<?> pageHelper) { String emailAddress = generateRandomEmailAddress(); fillInForm(emailAddress,emailAddress,"password01"); } }); } public PersonalisedChangeEmailAddressPageHelper(WebDriver driver) { super(driver); } public PersonalisedChangeEmailAddressPageHelper(WebDriver driver, Locale locale) { super(driver, locale); } public void fillInForm(String emailAddress,String confirmEmailAddress,String password) { PersonalisedChangeEmailAddressPageObject changeEmailAddressPageObject = getNewPageObject(); changeEmailAddressPageObject.setTextNdsInputEmail(emailAddress); changeEmailAddressPageObject.setTextNdsInputConfirmEmail(confirmEmailAddress); changeEmailAddressPageObject.setTextNdsInputPassword(password); } @Override public PageHelper skipPage() { final PersonalisedChangeEmailAddressPageObject pageObject = getPageObject(); fillInForm(); pageObject.invalidateDcId(); pageObject.clickNext(); BasePageHelper.waitUntilPageLoading(getPageObject().getDriver()); return PageHelperFactory.build(getPageObject().getDcId(), getPageObject().getDriver(), getLocale()); } private static String generateRandomEmailId(Random rng, String characters, int length) { char[] text = new char[length]; for (int i = 0; i < length; i++) { text[i] = characters.charAt(rng.nextInt(characters.length())); } return new String(text); } private String generateRandomEmailAddress() { final String testMail = generateRandomEmailId(new Random(), "test", 10); return testMail + "@northgateps.com"; } }
38.183099
142
0.727407
e41384c97c56bc472f4172b037ed0833d996e563
5,947
package edu.asupoly.ser422.grocery; import java.util.*; import org.json.JSONObject; import org.json.JSONArray; import java.util.logging.Logger; public class GroceryItem { private static Logger log = Logger.getLogger(GroceryItem.class.getName()); int aisle = 999999; // default value int qty; String pname, diet; String bname = "N/A"; // default value final static String AISLE_KEY = "aisle"; final static String QTY_KEY = "qty"; final static String PNAME_KEY = "pname"; final static String BNAME_KEY = "bname"; final static String DIET_KEY = "diet"; public void setAisle(int aisle){ this.aisle = aisle; } public void setQty(int qty){ this.qty = qty; } public void setPname(String pname){ this.pname = pname; } public void setBname(String bname){ this.bname = bname; } public void setDiet(String diet){ this.diet = diet; } public int getAisle(){ return this.aisle; } public String getPname(){ return this.pname; } public String getBname(){ return this.bname; } public int getQty(){ return this.qty; } public String getDiet(){ return this.diet; } public String translateToString(int val) { if(val == -1) return "N/A"; return Integer.toString(val); } /** Blueprint of the Class object. A mapping of this classes variables and the form data on the landing (index.html) page. @return Map<String, Boolean>. */ public static Map<String, Boolean> getGroceryItemBlueprint(){ Map<String, Boolean> blueprint = new HashMap<String, Boolean>(); blueprint.put(AISLE_KEY, true); blueprint.put(BNAME_KEY, true); blueprint.put(QTY_KEY, true); blueprint.put(PNAME_KEY, true); blueprint.put(DIET_KEY, true); return blueprint; } /** Create a GroceryItem object from the given JSONObject blueprint - a key-value mapping of the Class variables and their values. */ public static GroceryItem getGroceryItemObjFromBlueprint(JSONObject blueprint) throws NegativeValueException, NumberFormatException, UnknownKeyException { Map<String, Boolean> blueprintReq = getGroceryItemBlueprint(); Map<String, String> blueprintFinal = new Hashtable<String, String>(); for(Map.Entry<String, Boolean> entry : blueprintReq.entrySet()){ String key = entry.getKey(); if(blueprint.has(key)){ Object object = blueprint.get(key); if (object instanceof Integer) blueprintFinal.put(key, Integer.toString((int) object)); else blueprintFinal.put(key, (String) object); } } return GroceryItem.getGroceryItemObjFromBlueprint(blueprintFinal); } /** Create a GroceryItem object from the given blueprint - a key-value mapping of the Class variables and their values. */ public static GroceryItem getGroceryItemObjFromBlueprint(Map<String, String> blueprint) throws NegativeValueException, NumberFormatException, UnknownKeyException { Map<String, Boolean> blueprintReq = getGroceryItemBlueprint(); // check if all required keys are present //log.info("Checking for required keys"); for(Map.Entry<String, Boolean> entry : blueprintReq.entrySet()){ Boolean required = entry.getValue(); String key = entry.getKey(); if(required && !blueprint.containsKey(key)) throw new UnknownKeyException("Required Key: '" + key + "' not present in sent blueprint"); } //log.info("Checking for 'unexpected' keys"); // check if any 'non-existant' key has been sent for(Map.Entry<String, String> entry : blueprint.entrySet()){ String key = entry.getKey(); if(!blueprintReq.containsKey(key)) // invalid key sent throw new UnknownKeyException("Key: '" + key + "' does not exits for GroceryItem."); } log.info("Populating 'GroceryItem'."); // populate grocery item object from blueprint GroceryItem groceryItem = new GroceryItem(); for(Map.Entry<String, String> entry : blueprint.entrySet()){ String key = entry.getKey(); String value = entry.getValue(); //log.info("Key: "+ key + " Value: "+ value); if(key.equals(AISLE_KEY)){ if(!(value.length() == 0) || !value.isEmpty()){ int valueInt = 0; try { valueInt = Integer.parseInt(value); } catch (NumberFormatException ex){ //log.info("NumberFormatException: " + ex.getMessage()); throw new NumberFormatException(ex.getMessage()); } if(valueInt <= 0){ //log.info("NegativeValueException:"); throw new NegativeValueException("Quantity/Aisle value cannot be negative or 0!"); } groceryItem.setAisle(valueInt); } } else if(key.equals(QTY_KEY)){ int valueInt = 0; try { valueInt = Integer.parseInt(value); } catch (NumberFormatException ex){ //log.info("NumberFormatException: " + ex.getMessage()); throw new NumberFormatException(ex.getMessage()); } if(valueInt <= 0){ //log.info("NegativeValueException:"); throw new NegativeValueException("Quantity/Aisle value cannot be negative or 0!"); } groceryItem.setQty(valueInt); } else if(key.equals(PNAME_KEY)) groceryItem.setPname(value); else if(key.equals(BNAME_KEY)) groceryItem.setBname(value); else if(key.equals(DIET_KEY)) groceryItem.setDiet(value); } //log.info("Done populating grocery items."); return groceryItem; } /** JSONObject representation of the Class object. @return JSONObject. JSONObject representation of the Class object. */ public JSONObject getJSONObject(){ JSONObject jObject = new JSONObject(); Map<String, Boolean> blueprint = GroceryItem.getGroceryItemBlueprint(); for(String key: blueprint.keySet()) { if(key.equals(AISLE_KEY)) jObject.put(AISLE_KEY, this.getAisle()); else if(key.equals(PNAME_KEY)) jObject.put(PNAME_KEY, this.getPname()); else if(key.equals(BNAME_KEY)) jObject.put(BNAME_KEY, this.getBname()); else if(key.equals(QTY_KEY)) jObject.put(QTY_KEY, this.getQty()); else if(key.equals(DIET_KEY)) jObject.put(DIET_KEY, this.getDiet()); } return jObject; } }
32.320652
164
0.70153
b18d6e6c596d4ca484d157029e28db486243f3cf
1,354
package com.sparrowwallet.sparrow.io; import com.sparrowwallet.drongo.crypto.*; import com.sparrowwallet.drongo.wallet.Wallet; import java.util.Map; public class WalletAndKey implements Comparable<WalletAndKey> { private final Wallet wallet; private final ECKey encryptionKey; private final Key key; private final Map<WalletAndKey, Storage> childWallets; public WalletAndKey(Wallet wallet, ECKey encryptionKey, AsymmetricKeyDeriver keyDeriver, Map<WalletAndKey, Storage> childWallets) { this.wallet = wallet; this.encryptionKey = encryptionKey; this.key = encryptionKey == null ? null : new Key(encryptionKey.getPrivKeyBytes(), keyDeriver.getSalt(), EncryptionType.Deriver.ARGON2); this.childWallets = childWallets; } public Wallet getWallet() { return wallet; } public ECKey getEncryptionKey() { return encryptionKey; } public Key getKey() { return key; } public Map<WalletAndKey, Storage> getChildWallets() { return childWallets; } public void clear() { if(encryptionKey != null) { encryptionKey.clear(); } if(key != null) { key.clear(); } } @Override public int compareTo(WalletAndKey other) { return wallet.compareTo(other.wallet); } }
26.54902
144
0.661743
e8f10fa659128e9d459861ef5ebe3f27427213a1
16,091
package paketGUI; import java.awt.Color; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Set; import com.vaadin.flow.component.ClickEvent; import com.vaadin.flow.component.Component; import com.vaadin.flow.component.ComponentEventListener; import com.vaadin.flow.component.button.Button; import com.vaadin.flow.component.combobox.ComboBox; import com.vaadin.flow.component.dialog.Dialog; import com.vaadin.flow.component.grid.Grid; import com.vaadin.flow.component.grid.Grid.SelectionMode; import com.vaadin.flow.component.html.Div; import com.vaadin.flow.component.html.Label; import com.vaadin.flow.component.icon.VaadinIcon; import com.vaadin.flow.component.notification.Notification; import com.vaadin.flow.component.orderedlayout.FlexComponent.Alignment; import com.vaadin.flow.component.orderedlayout.FlexComponent.JustifyContentMode; import com.vaadin.flow.component.orderedlayout.HorizontalLayout; import com.vaadin.flow.component.orderedlayout.VerticalLayout; import com.vaadin.flow.component.textfield.TextArea; import com.vaadin.flow.component.textfield.TextField; import net.bytebuddy.dynamic.scaffold.subclass.ConstructorStrategy.ForDefaultConstructor; import paketDatenbankzugriff.DBZugriff_Mitarbeiter; import paketDatenbankzugriff.DBZugriff_Unternehmen; import paketDatenbankzugriff.DBVerbindung; import paketFachklassen.Mitarbeiter; import paketFachklassen.Unternehmen; public class Fenster_Mitarbeiter extends Div { DBVerbindung verbindung; private Mitarbeiter aktuellerMitarbeiter; private DBZugriff_Mitarbeiter aktuellerZugriffMit; private DBZugriff_Unternehmen aktuellerZugriffUnt; private List<Mitarbeiter> mitarbeiterList; private List<Unternehmen> uidList; private int uid; VerticalLayout leftLayout; Dialog loeschDialog; Mitarbeiter meinMitarbeiter; Grid<Mitarbeiter> grid; ArrayList<String> uidArrayList; ArrayList<String> mitNrArrayList; private int mitarbeiterNr; private String mitarbeiterName; TextField txtMaNr = new TextField(); TextField txtName = new TextField(); TextField txtVorname = new TextField(); TextField txtGehalt = new TextField(); TextArea txtrAllemitarbeiter = new TextArea(); ComboBox<String> cbUID = new ComboBox<>(); ComboBox<String> cbMitNr = new ComboBox<>(); private Grid<Mitarbeiter> createGrid(Collection<Mitarbeiter> mitarbeiterListe) { this.grid = new Grid<>(); grid.setHeightByRows(true); // grid.getStyle().set("background-color", "gray"); grid.setWidthFull(); grid.getElement().setAttribute("theme", "compact"); grid.setSelectionMode(SelectionMode.SINGLE); grid.setVerticalScrollingEnabled(true); // TODO: StringArray richtig auslesen grid.addSelectionListener(event -> { Set<Mitarbeiter> selected = event.getAllSelectedItems(); Notification.show("will be added later"); }); return grid; } public Fenster_Mitarbeiter() { aktuellerZugriffMit = new DBZugriff_Mitarbeiter(); aktuellerZugriffUnt = new DBZugriff_Unternehmen(); meinMitarbeiter = new Mitarbeiter(); uidArrayList = new ArrayList<>(); mitNrArrayList = new ArrayList<>(); mitarbeiterList = aktuellerZugriffMit.mitarbeiterliste_db(); // Liste der UID für die ComboBox uidList = aktuellerZugriffUnt.unternehmensliste_db(); for (int i = 0; i < uidList.size(); i++) { this.uid = uidList.get(i).getUnternehmensID(); uidArrayList.add(Integer.toString(uid)); } if (uidList == null) { leeren(); Notification.show("keine passenden Unternehmen gefunden"); } else { } // Liste der Mitarbeiternummern für die ComboBox for (int i = 0; i < mitarbeiterList.size(); i++) { this.mitarbeiterNr = mitarbeiterList.get(i).getMitarbeiternummer(); this.mitarbeiterName = mitarbeiterList.get(i).getName(); mitNrArrayList.add(Integer.toString(mitarbeiterNr) + " " + mitarbeiterName); } this.setSizeFull(); HorizontalLayout layout = new HorizontalLayout(); // layout.getStyle().set("background-color", "red"); layout.setHeight("600px"); layout.setWidth("1000px"); layout.setSpacing(true); layout.setPadding(true); // ------------------------------ linkes Layout ------------------------------ // // VerticalLayout leftLayout = new VerticalLayout(); // leftLayout.getStyle().set("background-color", "cyan"); leftLayout.setPadding(true); leftLayout.setHeightFull(); leftLayout.setWidth("600px"); Label headline = new Label("Mitarbeiterdaten verwalten"); headline.getStyle().set("font-size", "24px"); headline.getStyle().set("line-weight", "6px"); leftLayout.add(headline); HorizontalLayout mitarbeiterNrLayout = new HorizontalLayout(); Label mitNrLabel = new Label("Mitarbeiter Nummer eingeben:"); mitNrLabel.getStyle().set("align-self", "center"); mitNrLabel.setWidth("250px"); txtMaNr.setWidth("275px"); txtMaNr.setReadOnly(true); mitarbeiterNrLayout.add(mitNrLabel, txtMaNr); leftLayout.add(mitarbeiterNrLayout); HorizontalLayout namelayout = new HorizontalLayout(); Label nameLabel = new Label("Name:"); nameLabel.setWidth("20%"); nameLabel.getStyle().set("align-self", "center"); txtName.setWidth("40%"); Label vornameLabel = new Label("Vorname:"); vornameLabel.getStyle().set("align-self", "center"); txtVorname.setWidth("40%"); namelayout.add(nameLabel, txtName, vornameLabel, txtVorname); leftLayout.add(namelayout); HorizontalLayout gehaltLayout = new HorizontalLayout(); Label gehaltLabel = new Label("Gehalt:"); gehaltLabel.getStyle().set("align-self", "center"); txtGehalt.setWidth("475px"); gehaltLayout.add(gehaltLabel, txtGehalt); leftLayout.add(gehaltLayout); HorizontalLayout untLayout = new HorizontalLayout(); Label uidLabel = new Label("UID: "); uidLabel.getStyle().set("align-self", "center"); this.cbUID = new ComboBox<>(); cbUID.setItems(uidArrayList); cbUID.setPlaceholder("wähle UID"); cbUID.getStyle().set("align-self", "center"); cbUID.addValueChangeListener(event -> Notification.show("UID gewechselt auf: " + cbUID.getValue())); untLayout.add(uidLabel, cbUID); leftLayout.add(untLayout); // ------------------------------ GRID ------------------------------ // this.grid = createGrid(mitarbeiterList); leftLayout.add(grid); // ------------------------------ rechtes Layout ------------------------------ // VerticalLayout rightLayout = new VerticalLayout(); rightLayout.setDefaultHorizontalComponentAlignment(Alignment.CENTER); rightLayout.setHeightFull(); rightLayout.setWidth("350px"); Button leerenBtn = new Button("Felder leeren", VaadinIcon.TRASH.create()); leerenBtn.addClickListener(e -> leeren()); leerenBtn.setWidth("250px"); Label mitALabel = new Label("Mitarbeiter: "); mitALabel.getStyle().set("padding-right", "175px"); Button anlegenBtn = new Button("anlegen", VaadinIcon.ANCHOR.create()); anlegenBtn.setWidth("125px"); anlegenBtn.addClickListener(e -> nextNumber()); Button speichernBtn = new Button("Speichern", VaadinIcon.CLIPBOARD_USER.create()); speichernBtn.setWidth("125px"); speichernBtn.addClickListener(e -> anlegenMitarbeiter()); HorizontalLayout anlegenNspeichernBtnLayout = new HorizontalLayout(); anlegenNspeichernBtnLayout.add(anlegenBtn, speichernBtn); Label mitLabel = new Label("auswählen"); mitLabel.getStyle().set("align-self", "center"); this.cbMitNr = new ComboBox<>(); cbMitNr.setItems(mitNrArrayList); cbMitNr.setValue(mitNrArrayList.get(0)); cbMitNr.setWidth("175px"); cbMitNr.getStyle().set("align-self", "center"); cbMitNr.addValueChangeListener(event -> { if (event.getSource().isEmpty()) { cbMitNr.setValue(mitNrArrayList.get(0)); } else { suchenMitarbeiterCB(); } }); HorizontalLayout mitNcbMitNrLayout = new HorizontalLayout(); mitNcbMitNrLayout.add(mitLabel, cbMitNr); Button aendernBtn = new Button("Mitarbeiter ändern", VaadinIcon.EDIT.create()); aendernBtn.setWidth("250px"); aendernBtn.addClickListener(e -> aendernMitarbeiter()); Button loeschenBtn = new Button("Mitarbeiter löschen", VaadinIcon.ERASER.create()); loeschenBtn.setWidth("250px"); loeschenBtn.addClickListener(e -> loeschenMitarbeiter()); Button removeTableBtn = new Button("Aktualisieren", VaadinIcon.REFRESH.create()); removeTableBtn.setWidth("250px"); removeTableBtn.addClickListener(e -> onRemoveTableBtn()); Button arbeiternehmerBtn = new Button("Arbeitnehmer finden", VaadinIcon.SEARCH.create()); arbeiternehmerBtn.setWidth("250px"); arbeiternehmerBtn.addClickListener(e -> onArbeiternehmerBtn()); Button alleMitarbeiterBtn = new Button("Alle Mitarbeiter", VaadinIcon.ACADEMY_CAP.create()); alleMitarbeiterBtn.setWidth("250px"); alleMitarbeiterBtn.addClickListener(e -> onAlleMitarbeiterBtn()); rightLayout.add(leerenBtn, mitALabel, anlegenNspeichernBtnLayout, mitNcbMitNrLayout, aendernBtn, loeschenBtn, arbeiternehmerBtn, alleMitarbeiterBtn); layout.add(leftLayout, rightLayout); this.add(layout); } /** * flushed die aktuellen Daten */ private void leeren() { txtMaNr.clear(); txtName.clear(); txtVorname.clear(); txtGehalt.clear(); cbUID.clear(); } /** * Erfasst Inhalt aus der ComboBox cbMitNr und gibt ihn an die Methode * sucheMitarbeiter() weiter. sucheMitarbeiter erfasst die Werte aus der * Datenbank und gibt sie wieder zurück. Die ausgelesenen Werte werden an die * Methode anzeigenMitarbeiterdaten() weitergeleitet. */ public void suchenMitarbeiterCB() { aktuellerMitarbeiter = aktuellerZugriffMit.sucheMitarbeiter(cbMitNr.getValue()); if (aktuellerMitarbeiter == null) { leeren(); Notification.show("keinen Mitarbeiter gefunden"); } else { anzeigenMitarbeiterdaten(); } } /** * Benutzt die ausgelesenen Werte der Methode sucheMitarbeiter() und setzt sie * in die entsprechenden Textfelder. */ private void anzeigenMitarbeiterdaten() { leeren(); txtMaNr.setValue(Integer.toString(aktuellerMitarbeiter.getMitarbeiternummer())); txtName.setValue(aktuellerMitarbeiter.getName()); txtVorname.setValue(aktuellerMitarbeiter.getVorname()); txtGehalt.setValue(Double.toString(aktuellerMitarbeiter.getGehalt())); cbUID.setItems(Integer.toString(aktuellerMitarbeiter.getUID())); } /** * legt durch den Button anlegenBtn ("Mitarbeiter anlegen") einen neuen * Mitarbeiter an und fügt die Daten hinzu. die Methode erfasseMitarbeiter() * oeffnet die Verbindung mit der Datenbank und fügt die Daten hinzu */ private void anlegenMitarbeiter() { Mitarbeiter neuerMitarbeiter = new Mitarbeiter(); try { neuerMitarbeiter.setMitarbeiternummer(Integer.parseInt(txtMaNr.getValue())); neuerMitarbeiter.setName(txtName.getValue()); neuerMitarbeiter.setVorname(txtVorname.getValue()); // (txtVorname.getText()); neuerMitarbeiter.setGehalt(Double.parseDouble(txtGehalt.getValue())); neuerMitarbeiter.setUID(Integer.parseInt(cbUID.getValue())); boolean ok = aktuellerZugriffMit.erfasseMitarbeiter(neuerMitarbeiter); // Auswertung der Variablen ok if (ok == true) { Notification.show("Mitarbeiter erfasst"); } else { Notification.show("Mitarbeiter nicht erfasst"); } } // Abfangen von Eingabefehlern catch (Exception e) { Notification.show("Eingabefehler"); } } /** * ändert die Daten des Mitarbeiters in der Datenbank durch den Button * aendernBtn ("Mitarbeiter ändern") */ private void aendernMitarbeiter() { // Übertragung der geänderten Daten aus den Textfeldern in das Objekt if(cbUID.isEmpty() == false) { aktuellerMitarbeiter.setUID(Integer.parseInt(cbUID.getValue().substring(0,3))); } aktuellerMitarbeiter.setName(txtName.getValue()); aktuellerMitarbeiter.setVorname(txtVorname.getValue()); aktuellerMitarbeiter.setGehalt(Double.parseDouble(txtGehalt.getValue())); // Methode aendereMitarbeiter für das Objekt aktuellerZugriff ausführen und das // Ergebnis in die Variable ok (boolean) übernehmen boolean ok = aktuellerZugriffMit.aendereMitarbeiter(); // Rückgabewert der methode boolean aendereMitarbeiter() auswerten if (ok) { Notification.show("Datensatz geändert!"); } else { Notification.show("Datensatz nicht geändert!"); } } /** * Führt ein Entscheidungsdialog aus, ob man den Mitarbeiter wirklich löschen * will. "Ja" => Mitarbeiter wird gelöscht "Nein" => Mitarbeiter wird nicht * gelöscht "Abbrechen" => Dialog wird geschlossen */ private void loeschenMitarbeiter() { // Eingabedialogfenster this.loeschDialog = new Dialog(); loeschDialog.setWidth("400px"); loeschDialog.setHeight("50px"); Label wirklichLoeschenLbl = new Label("Wirklich Löschen?"); loeschDialog.add(wirklichLoeschenLbl); Button yesBtn = new Button("Ja", event -> mitarbeiterLoeschenAbfrage()); Button noBtn = new Button("Nein", event -> mitarbeiterNichtLoeschenAbfrage()); Button cancelnBtn = new Button("Abbrechen", event -> loeschDialog.close()); loeschDialog.add(yesBtn, noBtn, cancelnBtn); loeschDialog.open(); } /** * loeschenMitarbeiter() Option: "Ja" */ public void mitarbeiterLoeschenAbfrage() { meinMitarbeiter.setMitarbeiternummer(Integer.parseInt(txtMaNr.getValue())); boolean ok = aktuellerZugriffMit.loescheMitarbeiter(); if (ok) { Notification.show("Mitarbeiter gelöscht!!"); this.loeschDialog.close(); } else { Notification.show("Mitarbeiter nicht gelöscht!"); this.loeschDialog.close(); } leeren(); } /** * loeschenMitarbeiter() Option: "Nein" */ public void mitarbeiterNichtLoeschenAbfrage() { Notification.show("Mitarbeiter nicht gelöscht!"); this.loeschDialog.close(); } private void onRemoveTableBtn() { } /** * Erstellt Mitarbeiterliste/Tabelle des zugehörigen Unternehmens durch eingegebene UID */ private void onArbeiternehmerBtn() { mitarbeiterList.clear(); mitarbeiterList = aktuellerZugriffMit.sucheArbeitnehmer(this.cbUID.getValue()); grid.setItems(mitarbeiterList); grid.removeAllColumns(); grid.addColumn(entry -> entry.getMitarbeiternummer()).setHeader("MitNr").setSortable(true); grid.addColumn(entry -> entry.getName()).setHeader("Name").setSortable(true); grid.addColumn(entry -> entry.getVorname()).setHeader("Vorname").setSortable(true); grid.addColumn(entry -> entry.getGehalt()).setHeader("Gehalt").setSortable(true); grid.addColumn(entry -> entry.getUID()).setHeader("UID").setSortable(true); } /** * Erstellt Tabelle mit allen Mitarbeiter / Default Tabelle */ private void onAlleMitarbeiterBtn() { mitarbeiterList.clear(); mitarbeiterList = aktuellerZugriffMit.mitarbeiterliste_db(); grid.setItems(mitarbeiterList); grid.removeAllColumns(); grid.addColumn(entry -> entry.getMitarbeiternummer()).setHeader("MitNr").setSortable(true); grid.addColumn(entry -> entry.getName()).setHeader("Name").setSortable(true); grid.addColumn(entry -> entry.getVorname()).setHeader("Vorname").setSortable(true); grid.addColumn(entry -> entry.getGehalt()).setHeader("Gehalt").setSortable(true); grid.addColumn(entry -> entry.getUID()).setHeader("UID").setSortable(true); } /** * Methode für die nächst höchste MitarbeiterNr für Neuanlegungen */ private void nextNumber() { int maxNr = 0; leeren(); mitarbeiterList = aktuellerZugriffMit.mitarbeiterliste_db(); for (int i = 0; i < mitarbeiterList.size(); i++) { if (mitarbeiterList.get(i).getMitarbeiternummer() > maxNr) { maxNr = mitarbeiterList.get(i).getMitarbeiternummer(); } } txtMaNr.setValue(Integer.toString(maxNr + 1)); txtMaNr.setReadOnly(true); Notification.show("Mitarbeiterdaten eingeben, dann speichern"); } }
37.595794
112
0.721646
20c0cbd829201ba67fc225d24d241c68513786f6
3,453
/* * Copyright 2008-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nominanuda.zen.reactivestreams; import static com.nominanuda.zen.reactivestreams.ReactiveUtils.cappedSum; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.Executor; import java.util.function.Consumer; import org.reactivestreams.Subscriber; import org.reactivestreams.Subscription; import com.nominanuda.zen.concurrent.SynchExecutor; public class DelegatingSubscription implements ListenableSubscription { private volatile boolean canceled = false; private volatile long unrecordedDemand = 0; private final CopyOnWriteArrayList<Runnable> cancelCallbacks = new CopyOnWriteArrayList<Runnable>(); private Executor callbackExecutor = new SynchExecutor(); private Subscription delegee; @Override public void cancel() { if(! canceled) { canceled = true; if(delegee != null) { delegee.cancel(); } for(Runnable onCancel : cancelCallbacks ) { callbackExecutor.execute(onCancel); } } } public void setSubscription(Subscription s) { this.delegee = s; if(canceled) { this.delegee.cancel(); } else if(unrecordedDemand > 0) { this.delegee.request(unrecordedDemand); } } public void setCallbackExecutor(Executor callbackExecutor) { this.callbackExecutor = callbackExecutor; } @Override public void onCancel(Runnable cb) { cancelCallbacks.add(cb); } @Override public void request(long n) { if(! canceled) { if(delegee != null) { delegee.request(n); } else { unrecordedDemand = cappedSum(unrecordedDemand, n); } //trick to avoid creation of new Runnables //assumes that request() is not signaled concurrently this.n = n; callbackExecutor.execute(onRequestCallbacks); } } /* the two lines above, together with the following allow for request() callbacks; the problem is how to comply with rule 3.3 Subscription.request MUST place an upper bound on possible synchronous recursion between Publisher and Subscriber An example for undesirable synchronous, open recursion would be Subscriber.onNext -> Subscription.request -> Subscriber.onNext -> ..., as it very quickly would result in blowing the calling Thread´s stack. */ private final CopyOnWriteArrayList<Consumer<Long>> requestCallbacks = new CopyOnWriteArrayList<Consumer<Long>>(); private long n; private Runnable onRequestCallbacks = () -> { for(Consumer<Long> onRequest : requestCallbacks) { callbackExecutor.execute(() -> onRequest.accept(n)); } }; /** * It is very important that the supplied {@link Consumer} does not call {@link Subscriber#onNext(Object)} * on the same {@link Thread} see Reactive Streams specification rule 3.3. * Still this capability is exposed for other uses that can be handy. * @param cb */ @Override public void onRequest(Consumer<Long> cb) { requestCallbacks.add(cb); } }
31.390909
114
0.743991
41a9b773a4712938192bcb0ab28ab948159bb313
727
package com.flexicore.request; import com.fasterxml.jackson.annotation.JsonIgnore; import com.flexicore.model.FileResource; public class FinallizeFileResource { private String fileResourceId; @JsonIgnore private FileResource fileResource; public String getFileResourceId() { return fileResourceId; } public FinallizeFileResource setFileResourceId(String fileResourceId) { this.fileResourceId = fileResourceId; return this; } @JsonIgnore public FileResource getFileResource() { return fileResource; } public FinallizeFileResource setFileResource(FileResource fileResource) { this.fileResource = fileResource; return this; } }
24.233333
77
0.723521
2f1a666806deed7c6450cecd26151b33d35cd2c7
1,433
package com.zebrunner.agent.core.logging.log4j; import com.zebrunner.agent.core.logging.Log; import com.zebrunner.agent.core.registrar.LogsBuffer; import org.apache.log4j.AppenderSkeleton; import org.apache.log4j.spi.LoggingEvent; import java.util.function.Function; public class ReportingAppender extends AppenderSkeleton { private final static Function<LoggingEvent, Log> CONVERTER = e -> Log.builder() .message(e.getRenderedMessage()) .level(e.getLevel().toString()) .timestamp(e.getTimeStamp()) .build(); private static volatile LogsBuffer<LoggingEvent> logsBuffer; @Override protected void append(LoggingEvent event) { getBuffer().put(event); } private static LogsBuffer<LoggingEvent> getBuffer() { if (logsBuffer == null) { synchronized (ReportingAppender.class) { if (logsBuffer == null) { logsBuffer = LogsBuffer.create(CONVERTER); } } } return logsBuffer; } @Override public void close() { } @Override public boolean requiresLayout() { return false; } }
31.152174
105
0.526867
06dd7019866bd683a6549532d28eacb8af03e8bb
2,806
package expansioncontent.cards; import com.megacrit.cardcrawl.actions.animations.VFXAction; import com.megacrit.cardcrawl.actions.common.ApplyPowerAction; import com.megacrit.cardcrawl.actions.common.HealAction; import com.megacrit.cardcrawl.actions.unique.RemoveDebuffsAction; import com.megacrit.cardcrawl.actions.utility.ShakeScreenAction; import com.megacrit.cardcrawl.characters.AbstractPlayer; import com.megacrit.cardcrawl.dungeons.AbstractDungeon; import com.megacrit.cardcrawl.helpers.ScreenShake; import com.megacrit.cardcrawl.monsters.AbstractMonster; import com.megacrit.cardcrawl.monsters.city.Champ; import com.megacrit.cardcrawl.powers.StrengthPower; import com.megacrit.cardcrawl.vfx.MegaSpeechBubble; import com.megacrit.cardcrawl.vfx.combat.InflameEffect; import expansioncontent.expansionContentMod; public class LastStand extends AbstractExpansionCard { public final static String ID = makeID("LastStand"); private static final int MAGIC = 10; private static final int UPGRADE_MAGIC = 10; public LastStand() { super(ID, 2, CardType.POWER, CardRarity.UNCOMMON, CardTarget.SELF); this.setBackgroundTexture("expansioncontentResources/images/512/bg_boss_champ.png", "expansioncontentResources/images/1024/bg_boss_champ.png"); tags.add(expansionContentMod.STUDY_CHAMP); tags.add(expansionContentMod.STUDY); baseMagicNumber = magicNumber = MAGIC; this.exhaust = true; } public void use(AbstractPlayer p, AbstractMonster m) { //if (upgraded) this.poison = this.magicNumber +3; else {this.poison = this.magicNumber +2;} atb(new ShakeScreenAction(0.3F, ScreenShake.ShakeDur.MED, ScreenShake.ShakeIntensity.LOW)); atb(new VFXAction(p, new InflameEffect(p), 0.15F)); atb(new RemoveDebuffsAction(p)); atb(new ApplyPowerAction(p, p, new StrengthPower(p, 1), 1)); double currentPct = p.currentHealth * 1.001 / p.maxHealth * 1.001; if (currentPct < 0.5) { AbstractDungeon.effectList.add(new MegaSpeechBubble(p.hb.cX, p.hb.cY, 1.0F, Champ.DIALOG[6], true)); atb(new VFXAction(p, new InflameEffect(p), 0.1F)); atb(new ApplyPowerAction(p, p, new StrengthPower(p, 2), 2)); atb(new VFXAction(p, new InflameEffect(p), 0.1F)); if (upgraded) atb(new HealAction(p, p, this.magicNumber)); } } @Override public void triggerOnGlowCheck() { this.glowColor = AbstractDungeon.player.currentHealth < AbstractDungeon.player.maxHealth / 2 ? GOLD_BORDER_GLOW_COLOR : BLUE_BORDER_GLOW_COLOR; } public void upgrade() { if (!upgraded) { upgradeName(); rawDescription = UPGRADE_DESCRIPTION; initializeDescription(); } } }
36.441558
151
0.716322
2e9e17c2d201543f6729f5009f5400f3b0df9758
1,170
package com.revature.util; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.List; import com.revature.beans.Accounts; public class Files { public static final String accountFile = "Account.txt"; @SuppressWarnings("unchecked") public static void readFile() { try { ObjectInputStream readFile = new ObjectInputStream(new FileInputStream(accountFile)); AccountList.accountList = (ArrayList<Accounts>) readFile.readObject(); readFile.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public static void writeFile(List<Accounts> List) { try { ObjectOutputStream writeFile = new ObjectOutputStream(new FileOutputStream(accountFile)); writeFile.writeObject(List); writeFile.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
26.590909
92
0.747863
c1c0e4d87b11bc25c1d23ec8a407b4f0678b7ec2
19,754
package com.capitalone.dashboard.service; import com.capitalone.dashboard.model.Collector; import com.capitalone.dashboard.model.CollectorItem; import com.capitalone.dashboard.model.CollectorType; import com.capitalone.dashboard.model.Component; import com.capitalone.dashboard.model.DataResponse; import com.capitalone.dashboard.model.Feature; import com.capitalone.dashboard.model.QScopeOwner; import com.capitalone.dashboard.model.SprintEstimate; import com.capitalone.dashboard.repository.CollectorRepository; import com.capitalone.dashboard.repository.ComponentRepository; import com.capitalone.dashboard.repository.FeatureRepository; import com.capitalone.dashboard.util.FeatureCollectorConstants; import com.mysema.query.BooleanBuilder; import org.bson.types.ObjectId; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import javax.xml.bind.DatatypeConverter; import java.util.ArrayList; import java.util.Calendar; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.TimeZone; /** * The feature service. * <p> * Features can currently belong to 2 sprint types: scrum and kanban. In order to be considered part of the sprint * the feature must not be deleted and must have an "active" sprint asset state if the sprint is set. The following * logic also applies: * <p> * A feature is part of a scrum sprint if any of the following are true: * <ol> * <li>the feature has a sprint set that has start <= now <= end and end < EOT (9999-12-31T59:59:59.999999)</li> * </ol> * <p> * A feature is part of a kanban sprint if any of the following are true: * <ol> * <li>the feature does not have a sprint set</li> * <li>the feature has a sprint set that does not have an end date</li> * <li>the feature has a sprint set that has an end date >= EOT (9999-12-31T59:59:59.999999)</li> * </ol> */ @Service public class FeatureServiceImpl implements FeatureService { private final ComponentRepository componentRepository; private final FeatureRepository featureRepository; private final CollectorRepository collectorRepository; /** * Default autowired constructor for repositories * * @param componentRepository * Repository containing components used by the UI (populated by * UI) * @param collectorRepository * Repository containing all registered collectors * @param featureRepository * Repository containing all features */ @Autowired public FeatureServiceImpl(ComponentRepository componentRepository, CollectorRepository collectorRepository, FeatureRepository featureRepository) { this.componentRepository = componentRepository; this.featureRepository = featureRepository; this.collectorRepository = collectorRepository; } /** * Retrieves a single story based on a back-end story number * * @param componentId * The ID of the related UI component that will reference * collector item content from this collector * @param storyNumber * A back-end story ID used by a source system * @return A data response list of type Feature containing a single story */ @Override public DataResponse<List<Feature>> getStory(ObjectId componentId, String storyNumber) { Component component = componentRepository.findOne(componentId); if ((component == null) || CollectionUtils.isEmpty(component.getCollectorItems()) || CollectionUtils .isEmpty(component.getCollectorItems().get(CollectorType.ScopeOwner)) || (component.getCollectorItems().get(CollectorType.ScopeOwner).get(0) == null)) { return getEmptyLegacyDataResponse(); } CollectorItem item = component.getCollectorItems().get(CollectorType.ScopeOwner).get(0); QScopeOwner team = new QScopeOwner("team"); BooleanBuilder builder = new BooleanBuilder(); builder.and(team.collectorItemId.eq(item.getId())); // Get one story based on story number, based on component List<Feature> story = featureRepository.getStoryByNumber(storyNumber); Collector collector = collectorRepository.findOne(item.getCollectorId()); return new DataResponse<>(story, collector.getLastExecuted()); } /** * Retrieves all stories for a given team and their current sprint * * @param componentId * The ID of the related UI component that will reference * collector item content from this collector * @param teamId * A given scope-owner's source-system ID * @return A data response list of type Feature containing all features for * the given team and current sprint */ @Override public DataResponse<List<Feature>> getRelevantStories(ObjectId componentId, String teamId, Optional<String> agileType) { Component component = componentRepository.findOne(componentId); if ((component == null) || CollectionUtils.isEmpty(component.getCollectorItems()) || CollectionUtils .isEmpty(component.getCollectorItems().get(CollectorType.ScopeOwner)) || (component.getCollectorItems().get(CollectorType.ScopeOwner).get(0) == null)) { return getEmptyLegacyDataResponse(); } CollectorItem item = component.getCollectorItems().get(CollectorType.ScopeOwner).get(0); QScopeOwner team = new QScopeOwner("team"); BooleanBuilder builder = new BooleanBuilder(); builder.and(team.collectorItemId.eq(item.getId())); // Get teamId first from available collector item, based on component List<Feature> relevantStories = getFeaturesForCurrentSprints(teamId, agileType.isPresent()? agileType.get() : null, false); Collector collector = collectorRepository.findOne(item.getCollectorId()); return new DataResponse<>(relevantStories, collector.getLastExecuted()); } /** * Retrieves all unique super features and their total sub feature estimates * for a given team and their current sprint * * @param componentId * The ID of the related UI component that will reference * collector item content from this collector * @param teamId * A given scope-owner's source-system ID * @return A data response list of type Feature containing the unique * features plus their sub features' estimates associated to the * current sprint and team */ @Override public DataResponse<List<Feature>> getFeatureEpicEstimates(ObjectId componentId, String teamId, Optional<String> agileType, Optional<String> estimateMetricType) { Component component = componentRepository.findOne(componentId); if ((component == null) || CollectionUtils.isEmpty(component.getCollectorItems()) || CollectionUtils .isEmpty(component.getCollectorItems().get(CollectorType.ScopeOwner)) || (component.getCollectorItems().get(CollectorType.ScopeOwner).get(0) == null)) { return getEmptyLegacyDataResponse(); } CollectorItem item = component.getCollectorItems().get(CollectorType.ScopeOwner).get(0); List<Feature> relevantFeatureEstimates = getFeaturesForCurrentSprints(teamId, agileType.isPresent()? agileType.get() : null, true); // epicID : epic information (in the form of a Feature object) Map<String, Feature> epicIDToEpicFeatureMap = new HashMap<>(); for (Feature tempRs : relevantFeatureEstimates) { String epicID = tempRs.getsEpicID(); if (StringUtils.isEmpty(epicID)) continue; Feature feature = epicIDToEpicFeatureMap.get(epicID); if (feature == null) { feature = new Feature(); feature.setId(null); feature.setsEpicID(epicID); feature.setsEpicNumber(tempRs.getsEpicNumber()); feature.setsEpicName(tempRs.getsEpicName()); feature.setsEstimate("0"); epicIDToEpicFeatureMap.put(epicID, feature); } // if estimateMetricType is hours accumulate time estimate in minutes for better precision ... divide by 60 later int estimate = getEstimate(tempRs, estimateMetricType); feature.setsEstimate(String.valueOf(Integer.valueOf(feature.getsEstimate()) + estimate)); } if (isEstimateTime(estimateMetricType)) { // time estimate is in minutes but we want to return in hours for (Feature f : epicIDToEpicFeatureMap.values()) { f.setsEstimate(String.valueOf(Integer.valueOf(f.getsEstimate()) / 60)); } } Collector collector = collectorRepository.findOne(item.getCollectorId()); return new DataResponse<>(new ArrayList<>(epicIDToEpicFeatureMap.values()), collector.getLastExecuted()); } @Override public DataResponse<SprintEstimate> getAggregatedSprintEstimates(ObjectId componentId, String teamId, Optional<String> agileType, Optional<String> estimateMetricType) { Component component = componentRepository.findOne(componentId); if ((component == null) || CollectionUtils.isEmpty(component.getCollectorItems()) || CollectionUtils .isEmpty(component.getCollectorItems().get(CollectorType.ScopeOwner)) || (component.getCollectorItems().get(CollectorType.ScopeOwner).get(0) == null)) { return new DataResponse<SprintEstimate>(new SprintEstimate(), 0); } CollectorItem item = component.getCollectorItems().get(CollectorType.ScopeOwner).get(0); Collector collector = collectorRepository.findOne(item.getCollectorId()); SprintEstimate estimate = getSprintEstimates(teamId, agileType, estimateMetricType); return new DataResponse<>(estimate, collector.getLastExecuted()); } /** * Retrieves estimate total of all features in the current sprint and for * the current team. * * @param componentId * The ID of the related UI component that will reference * collector item content from this collector * @param teamId * A given scope-owner's source-system ID * @return A data response list of type Feature containing the total * estimate number for all features */ @Override @Deprecated public DataResponse<List<Feature>> getTotalEstimate(ObjectId componentId, String teamId, Optional<String> agileType, Optional<String> estimateMetricType) { Component component = componentRepository.findOne(componentId); if ((component == null) || CollectionUtils.isEmpty(component.getCollectorItems()) || CollectionUtils .isEmpty(component.getCollectorItems().get(CollectorType.ScopeOwner)) || (component.getCollectorItems().get(CollectorType.ScopeOwner).get(0) == null)) { return getEmptyLegacyDataResponse(); } CollectorItem item = component.getCollectorItems().get(CollectorType.ScopeOwner).get(0); SprintEstimate estimate = getSprintEstimates(teamId, agileType, estimateMetricType); List<Feature> list = Collections.singletonList(new Feature()); list.get(0).setsEstimate(Integer.toString(estimate.getTotalEstimate())); Collector collector = collectorRepository.findOne(item.getCollectorId()); return new DataResponse<>(list, collector.getLastExecuted()); } /** * Retrieves estimate in-progress of all features in the current sprint and * for the current team. * * @param componentId * The ID of the related UI component that will reference * collector item content from this collector * @param teamId * A given scope-owner's source-system ID * @return A data response list of type Feature containing the in-progress * estimate number for all features */ @Override @Deprecated public DataResponse<List<Feature>> getInProgressEstimate(ObjectId componentId, String teamId, Optional<String> agileType, Optional<String> estimateMetricType) { Component component = componentRepository.findOne(componentId); if ((component == null) || CollectionUtils.isEmpty(component.getCollectorItems()) || CollectionUtils .isEmpty(component.getCollectorItems().get(CollectorType.ScopeOwner)) || (component.getCollectorItems().get(CollectorType.ScopeOwner).get(0) == null)) { return getEmptyLegacyDataResponse(); } CollectorItem item = component.getCollectorItems().get(CollectorType.ScopeOwner).get(0); SprintEstimate estimate = getSprintEstimates(teamId, agileType, estimateMetricType); List<Feature> list = Collections.singletonList(new Feature()); list.get(0).setsEstimate(Integer.toString(estimate.getInProgressEstimate())); Collector collector = collectorRepository.findOne(item.getCollectorId()); return new DataResponse<>(list, collector.getLastExecuted()); } /** * Retrieves estimate done of all features in the current sprint and for the * current team. * * @param componentId * The ID of the related UI component that will reference * collector item content from this collector * @param teamId * A given scope-owner's source-system ID * @return A data response list of type Feature containing the done estimate * number for all features */ @Override @Deprecated public DataResponse<List<Feature>> getDoneEstimate(ObjectId componentId, String teamId, Optional<String> agileType, Optional<String> estimateMetricType) { Component component = componentRepository.findOne(componentId); if ((component == null) || CollectionUtils.isEmpty(component.getCollectorItems()) || CollectionUtils .isEmpty(component.getCollectorItems().get(CollectorType.ScopeOwner)) || (component.getCollectorItems().get(CollectorType.ScopeOwner).get(0) == null)) { return getEmptyLegacyDataResponse(); } CollectorItem item = component.getCollectorItems().get(CollectorType.ScopeOwner).get(0); SprintEstimate estimate = getSprintEstimates(teamId, agileType, estimateMetricType); List<Feature> list = Collections.singletonList(new Feature()); list.get(0).setsEstimate(Integer.toString(estimate.getCompleteEstimate())); Collector collector = collectorRepository.findOne(item.getCollectorId()); return new DataResponse<>(list, collector.getLastExecuted()); } /** * Retrieves the current sprint's detail for a given team. * * @param componentId * The ID of the related UI component that will reference * collector item content from this collector * @param teamId * A given scope-owner's source-system ID * @return A data response list of type Feature containing several relevant * sprint fields for the current team's sprint */ @Override public DataResponse<List<Feature>> getCurrentSprintDetail(ObjectId componentId, String teamId, Optional<String> agileType) { Component component = componentRepository.findOne(componentId); if ((component == null) || CollectionUtils.isEmpty(component.getCollectorItems()) || CollectionUtils .isEmpty(component.getCollectorItems().get(CollectorType.ScopeOwner)) || (component.getCollectorItems().get(CollectorType.ScopeOwner).get(0) == null)) { return getEmptyLegacyDataResponse(); } CollectorItem item = component.getCollectorItems().get(CollectorType.ScopeOwner).get(0); // Get teamId first from available collector item, based on component List<Feature> sprintResponse = getFeaturesForCurrentSprints(teamId, agileType.isPresent()? agileType.get() : null, true); Collector collector = collectorRepository.findOne(item.getCollectorId()); return new DataResponse<>(sprintResponse, collector.getLastExecuted()); } private SprintEstimate getSprintEstimates(String teamId, Optional<String> agileType, Optional<String> estimateMetricType) { List<Feature> storyEstimates = getFeaturesForCurrentSprints(teamId, agileType.isPresent()? agileType.get() : null, true); int totalEstimate = 0; int wipEstimate = 0; int doneEstimate = 0; for (Feature tempRs : storyEstimates) { String tempStatus = tempRs.getsStatus() != null? tempRs.getsStatus().toLowerCase() : null; // if estimateMetricType is hours accumulate time estimate in minutes for better precision ... divide by 60 later int estimate = getEstimate(tempRs, estimateMetricType); totalEstimate += estimate; if (tempStatus != null) { switch (tempStatus) { case "in progress": case "waiting": case "impeded": wipEstimate += estimate; break; case "done": case "accepted": doneEstimate += estimate; break; } } } int openEstimate = totalEstimate - wipEstimate - doneEstimate; if (isEstimateTime(estimateMetricType)) { // time estimate is in minutes but we want to return in hours totalEstimate /= 60; openEstimate /= 60; wipEstimate /= 60; doneEstimate /= 60; } SprintEstimate response = new SprintEstimate(); response.setOpenEstimate(openEstimate); response.setInProgressEstimate(wipEstimate); response.setCompleteEstimate(doneEstimate); response.setTotalEstimate(totalEstimate); return response; } /** * Get the features that belong to the current sprints * * @param teamId the team id * @param agileType the agile type. Defaults to "scrum" if null * @param minimal if the resulting list of Features should be minimally populated (see queries for fields) * @return */ private List<Feature> getFeaturesForCurrentSprints(String teamId, String agileType, boolean minimal) { List<Feature> rt = new ArrayList<Feature>(); String now = getCurrentISODateTime(); if ( FeatureCollectorConstants.SPRINT_KANBAN.equalsIgnoreCase(agileType)) { /* * A feature is part of a kanban sprint if any of the following are true: * - the feature does not have a sprint set * - the feature has a sprint set that does not have an end date * - the feature has a sprint set that has an end date >= EOT (9999-12-31T59:59:59.999999) */ if (minimal) { rt.addAll(featureRepository.findByNullSprintsMinimal(teamId)); rt.addAll(featureRepository.findByUnendingSprintsMinimal(teamId)); } else { rt.addAll(featureRepository.findByNullSprints(teamId)); rt.addAll(featureRepository.findByUnendingSprints(teamId)); } } else { // default to scrum /* * A feature is part of a scrum sprint if any of the following are true: * - the feature has a sprint set that has start <= now <= end and end < EOT (9999-12-31T59:59:59.999999) */ if (minimal) { rt.addAll(featureRepository.findByActiveEndingSprintsMinimal(teamId, now)); } else { rt.addAll(featureRepository.findByActiveEndingSprints(teamId, now)); } } return rt; } private DataResponse<List<Feature>> getEmptyLegacyDataResponse() { Feature f = new Feature(); List<Feature> l = new ArrayList<>(); l.add(f); return new DataResponse<>(l, 0); } /** * Retrieves the current system time stamp in ISO date time format. Because * this is not using SimpleTimeFormat, this should be thread safe. * * @return A string representation of the current date time stamp in ISO * format from the current time zone */ private String getCurrentISODateTime() { return DatatypeConverter.printDateTime(Calendar.getInstance(TimeZone.getTimeZone("UTC"))); } private boolean isEstimateTime(Optional<String> estimateMetricType) { return estimateMetricType.isPresent() && FeatureCollectorConstants.STORY_HOURS_ESTIMATE.equalsIgnoreCase(estimateMetricType.get()); } private int getEstimate(Feature feature, Optional<String> estimateMetricType) { int rt = 0; if (isEstimateTime(estimateMetricType)) { if (feature.getsEstimateTime() != null) { rt = feature.getsEstimateTime().intValue(); } } else { // default to story points since that should be the most common use case if (!StringUtils.isEmpty(feature.getsEstimate())) { rt = Integer.parseInt(feature.getsEstimate()); } } return rt; } }
39.666667
133
0.737218
3ec4560667b1b6ae23c7e4a5a8c6d8e1fec5a65e
2,853
package com.pureon.pur_wallet.activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.annotation.Nullable; import android.text.TextUtils; import com.pureon.pur_wallet.R; import com.pureon.pur_wallet.constant.ConstantUtil; import com.pureon.pur_wallet.util.RootUtil; import com.pureon.pur_wallet.util.db.SharePrefUtil; /** * Created by duanyytop on 2018/6/12 */ public class SplashActivity extends BaseActivity { public static final String EXTRA_FIRST = "extra_first"; public static final String LOCK_TO_MAIN = "lock_to_main"; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (!isTaskRoot()) { finish(); return; } setContentView(R.layout.activity_splash); inLoginPage = true; if (RootUtil.isDeviceRooted()) { new AlertDialog.Builder(mActivity) .setTitle(R.string.safe_hint) .setMessage(R.string.root_hint) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); finish(); } }).setNegativeButton(R.string.go_on, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { gotoMainPage(); } }).setCancelable(false) .create().show(); } else { new Thread() { @Override public void run() { super.run(); try { sleep(1000); gotoMainPage(); } catch (InterruptedException e) { e.printStackTrace(); } } }.start(); } } private void gotoMainPage() { if (!TextUtils.isEmpty(SharePrefUtil.getCurrentWalletName())) { if (SharePrefUtil.getBoolean(ConstantUtil.FINGERPRINT, false)) { Intent intent = new Intent(mActivity, FingerPrintActivity.class); intent.putExtra(LOCK_TO_MAIN, true); startActivity(intent); } else { startActivity(new Intent(mActivity, MainActivity.class)); } } else { Intent intent = new Intent(mActivity, AddWalletActivity.class); startActivity(intent); } finish(); } }
35.6625
96
0.545741
82496c071b87068f99bb8730970dafd8b5c8a809
408
package week1.day1.assignments; public class SumOfDigits { public static void main(String[] args) { int input =123; int sum=0,remainder=0; while(input>0) { remainder = input % 10; System.out.println(remainder); sum=sum + remainder; System.out.println(sum); input= input/10; System.out.println(input); } System.out.println("The Sum of Digit is :" +sum); } }
17
51
0.637255
94ac7f830110038ed1bc7460432556b4fc796ae8
3,012
package pl.codecity.main.controller.guest; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.security.crypto.password.StandardPasswordEncoder; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.util.ObjectUtils; import org.springframework.validation.BindingResult; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.mvc.support.RedirectAttributes;; import pl.codecity.main.model.User; import pl.codecity.main.request.PasswordUpdateRequest; import pl.codecity.main.service.UserService; import pl.codecity.main.utility.AuthorizedUser; import javax.inject.Inject; @Controller @RequestMapping("/settings/password") public class PasswordUpdateController { public static final String FORM_MODEL_KEY = "form"; public static final String ERRORS_MODEL_KEY = BindingResult.MODEL_KEY_PREFIX + FORM_MODEL_KEY; @Inject private UserService userService; @ModelAttribute(FORM_MODEL_KEY) public PasswordUpdateForm setupPasswordUpdateForm() { return new PasswordUpdateForm(); } @RequestMapping(method = RequestMethod.GET) public String init(Model model) { PasswordUpdateForm form = new PasswordUpdateForm(); model.addAttribute(FORM_MODEL_KEY, form); return edit(model); } @RequestMapping(method = RequestMethod.GET, params = "step.edit") public String edit(Model model) { return "user/password-update"; } @RequestMapping(method = RequestMethod.PUT) public String update( @Validated @ModelAttribute(FORM_MODEL_KEY) PasswordUpdateForm form, BindingResult errors, AuthorizedUser authorizedUser, RedirectAttributes redirectAttributes) { redirectAttributes.addFlashAttribute(FORM_MODEL_KEY, form); redirectAttributes.addFlashAttribute(ERRORS_MODEL_KEY, errors); if (!errors.hasFieldErrors("newPassword")) { if (!ObjectUtils.nullSafeEquals(form.getNewPassword(), form.getNewPasswordRetype())) { errors.rejectValue("newPasswordRetype", "MatchRetype"); } } if (!errors.hasErrors()) { User user = userService.getUserById(authorizedUser.getId()); PasswordEncoder passwordEncoder = new StandardPasswordEncoder(); if (!passwordEncoder.matches(form.getCurrentPassword(), user.getLoginPassword())) { errors.rejectValue("currentPassword", "MatchCurrentPassword"); } } if (errors.hasErrors()) { return "redirect:/settings/password?step.edit"; } PasswordUpdateRequest request = new PasswordUpdateRequest() .withUserId(authorizedUser.getId()) .withPassword(form.getNewPassword()); userService.updatePassword(request, authorizedUser); redirectAttributes.getFlashAttributes().clear(); redirectAttributes.addFlashAttribute("updatedPassword", true); return "redirect:/settings/password"; } }
35.435294
95
0.798473
c3c2c8ccf50aebe80a58c8bec3413687b43e215b
1,275
package estatico.pilha.exercicios; import java.util.Scanner; import estatico.pilha.Pilha; public class Exer01 { public static void main(String[] args) { Pilha<Integer> pilha = new Pilha<>(); Scanner teclado = new Scanner(System.in); for (int i = 0; i < 10; i++) { System.out.print("Digite um número: "); int num = teclado.nextInt(); if (num % 2 == 0) { pilha.empilha(num); System.out.println("Número par, empilhando o número: " + num); } else { Integer desempilhado = pilha.desempilha(); if (desempilhado == null) { System.out.println("Pilha está vazia"); } else { System.out.println("Número ímpar, desempilhando o número: " + desempilhado); } } System.out.println(); } System.out.println("\nTodos os números foram lidos, agora o restante será desempilhado:"); while (!pilha.vazio()) { System.out.println("Desempilhando: " + pilha.desempilha()); } teclado.close(); } }
25
98
0.480784
c9d8b84ef0153ab2cace1d42cc7b3fe8aa4745d8
3,571
package io.eventdriven.ecommerce.shoppingcarts; import io.eventdriven.ecommerce.core.aggregates.AbstractAggregate; import io.eventdriven.ecommerce.pricing.ProductPriceCalculator; import io.eventdriven.ecommerce.shoppingcarts.ShoppingCartEvent.*; import io.eventdriven.ecommerce.shoppingcarts.productitems.PricedProductItem; import io.eventdriven.ecommerce.shoppingcarts.productitems.ProductItem; import io.eventdriven.ecommerce.shoppingcarts.productitems.ProductItems; import java.time.LocalDateTime; import java.util.UUID; class ShoppingCart extends AbstractAggregate<ShoppingCartEvent, UUID> { UUID clientId() { return clientId; } public ProductItems productItems() { return productItems; } ShoppingCartStatus status() { return status; } private UUID clientId; private ProductItems productItems; private ShoppingCartStatus status; private ShoppingCart() { } public static ShoppingCart empty() { return new ShoppingCart(); } ShoppingCart( UUID id, UUID clientId ) { this.id = id; this.clientId = clientId; enqueue(new ShoppingCartOpened(id, clientId)); } static ShoppingCart open(UUID shoppingCartId, UUID clientId) { return new ShoppingCart( shoppingCartId, clientId ); } void addProductItem( ProductPriceCalculator productPriceCalculator, ProductItem productItem ) { if (isClosed()) throw new IllegalStateException("Removing product item for cart in '%s' status is not allowed.".formatted(status)); var pricedProductItem = productPriceCalculator.calculate(productItem); enqueue(new ProductItemAddedToShoppingCart( id, pricedProductItem )); } void removeProductItem( PricedProductItem productItem ) { if (isClosed()) throw new IllegalStateException("Adding product item for cart in '%s' status is not allowed.".formatted(status)); productItems.assertThatCanRemove(productItem); enqueue(new ProductItemRemovedFromShoppingCart( id, productItem )); } void confirm() { if (isClosed()) throw new IllegalStateException("Confirming cart in '%s' status is not allowed.".formatted(status)); enqueue(new ShoppingCartConfirmed( id, LocalDateTime.now() )); } void cancel() { if (isClosed()) throw new IllegalStateException("Canceling cart in '%s' status is not allowed.".formatted(status)); enqueue(new ShoppingCartCanceled( id, LocalDateTime.now() )); } private boolean isClosed() { return this.status.isClosed(); } static String mapToStreamId(UUID shoppingCartId) { return "ShoppingCart-%s".formatted(shoppingCartId); } @Override public void when(ShoppingCartEvent event) { switch (event) { case ShoppingCartOpened shoppingCartOpened -> { id = shoppingCartOpened.shoppingCartId(); clientId = shoppingCartOpened.clientId(); productItems = ProductItems.empty(); status = ShoppingCartStatus.Pending; } case ProductItemAddedToShoppingCart productItemAddedToShoppingCart -> productItems = productItems.add(productItemAddedToShoppingCart.productItem()); case ProductItemRemovedFromShoppingCart productItemRemovedFromShoppingCart -> productItems = productItems.remove(productItemRemovedFromShoppingCart.productItem()); case ShoppingCartConfirmed ignored -> status = ShoppingCartStatus.Confirmed; case ShoppingCartCanceled ignored -> status = ShoppingCartStatus.Canceled; } } }
26.649254
121
0.723047
ce51766c1de41803238db9851ef348d39196e3e4
2,113
/** * 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.ctakes.ytex.kernel.evaluator; import org.apache.ctakes.ytex.kernel.tree.Node; /** * Evaluate negation status and certainty of named entities. If negation status * differs, multiply convolution on concepts by -1. If certainty differs, * multiply by 0.5. This assumes that possible values for certainty are * certain/uncertain. */ public class NamedEntityNegationKernel extends ConvolutionKernel { private static final String CONF_ATTR = "confidence"; private static final String CERT_ATTR = "certainty"; @Override public double evaluate(Object c1, Object c2) { Node ne1 = (Node) c1; Node ne2 = (Node) c2; Number confidence1 = (Number) ne1.getValue().get(CONF_ATTR); Number confidence2 = (Number) ne2.getValue().get(CONF_ATTR); Integer certainty1 = (Integer) ne1.getValue().get(CERT_ATTR); Integer certainty2 = (Integer) ne2.getValue().get(CERT_ATTR); double negationFactor = 1; if (confidence1 != null && confidence2 != null && !confidence1.equals(confidence2)) negationFactor = -1; double certaintyFactor = 1; if (certainty1 != null && certainty1 != null && !certainty1.equals(certainty2)) certaintyFactor = 0.5; return negationFactor * certaintyFactor * super.evaluate(c1, c2); } }
39.867925
80
0.721723
7b05ce41cad3bb4fc3e319defc731dbf818fa42a
145
package com.tngtech.jgiven.example.bookstore.entity; public class Order extends Entity { public Customer customer; public Book book; }
18.125
52
0.758621
bc21f2ced736d81b885dfdbd92935ae5f36cacba
8,589
package org.mbari.m3.vars.annotation.ui.deployeditor; import com.google.common.collect.Lists; import io.reactivex.Observable; import io.reactivex.disposables.Disposable; import javafx.beans.InvalidationListener; import javafx.beans.property.SimpleObjectProperty; import javafx.collections.ObservableList; import javafx.scene.control.*; import org.mbari.m3.vars.annotation.EventBus; import org.mbari.m3.vars.annotation.UIToolBox; import org.mbari.m3.vars.annotation.commands.*; import org.mbari.m3.vars.annotation.events.*; import org.mbari.m3.vars.annotation.model.Annotation; import org.mbari.m3.vars.annotation.services.MediaService; import org.mbari.m3.vars.annotation.ui.shared.AnnotationTableViewFactory; import org.mbari.m3.vars.annotation.util.AsyncUtils; import org.mbari.m3.vars.annotation.util.JFXUtilities; import org.mbari.m3.vars.annotation.util.ListUtils; import javax.annotation.Nonnull; import java.net.URI; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.prefs.Preferences; import java.util.stream.Collectors; /** * @author Brian Schlining * @since 2018-04-05T15:00:00 */ public class AnnotationTableController { private TableView<Annotation> tableView; private final ResourceBundle i18n; private final Map<UUID, URI> videoReferenceUriMap = new ConcurrentHashMap<>(); private final UIToolBox toolBox; private final List<Disposable> disposables = new ArrayList<>(); private final EventBus eventBus; private boolean disabled = true; public AnnotationTableController(@Nonnull UIToolBox toolBox, @Nonnull EventBus eventBus) { this.toolBox = toolBox; this.i18n = toolBox.getI18nBundle(); this.eventBus = eventBus; Observable<Object> observable = eventBus.toObserverable(); // Forward this tables annotation mutating events to main event bus EventBus mainEventBus = toolBox.getEventBus(); ArrayList<Class<? extends Command>> commandsToForward = Lists.newArrayList(ChangeGroupCmd.class, ChangeActivityCmd.class, //MoveAnnotationsCmd.class, MoveAnnotationsAndImagesCmd.class, ChangeConceptCmd.class, DeleteAssociationsCmd.class); for (Class<? extends Command> clazz : commandsToForward) { observable.ofType(clazz) .subscribe(mainEventBus::send); } // Load the column visibility and width loadPreferences(); // After annotations are added do lookup of video URI for video URI column getTableView().getItems() .addListener((InvalidationListener) obs -> updateVideoReferenceUris()); } private void select(Collection<Annotation> annos) { JFXUtilities.runOnFXThread(() -> { TableView.TableViewSelectionModel<Annotation> selectionModel = getTableView().getSelectionModel(); selectionModel.clearSelection(); annos.forEach(selectionModel::select); selectionModel.getSelectedIndices() .stream() .min(Comparator.naturalOrder()) .ifPresent(i -> getTableView().scrollTo(i)); }); } private void updateVideoReferenceUris() { ObservableList<Annotation> items = getTableView().getItems(); List<UUID> uuids = items.stream() .map(Annotation::getVideoReferenceUuid) .distinct() .collect(Collectors.toList()); Set<UUID> existingUuids = videoReferenceUriMap.keySet(); List<UUID> newUuids = new ArrayList<>(uuids); newUuids.removeAll(existingUuids); if (newUuids.size() > 0) { videoReferenceUriMap.clear(); MediaService mediaService = toolBox.getServices().getMediaService(); AsyncUtils.collectAll(uuids, mediaService::findByUuid) .thenAccept(medias -> medias.forEach(m -> videoReferenceUriMap.put(m.getVideoReferenceUuid(), m.getUri()))) .thenAccept(v -> getTableView().refresh()); } } private void loadPreferences() { // Load the column visibility and width Preferences prefs = Preferences.userNodeForPackage(getClass()); Preferences columnPrefs = prefs.node("table-columns"); getTableView().getColumns() .forEach(tc -> { Preferences p = columnPrefs.node(tc.getId()); String s = p.get("visible", "true"); boolean isVisible = s.equals("true"); String w = p.get("width", "100"); double width = Double.parseDouble(w); JFXUtilities.runOnFXThread(() -> { tc.setVisible(isVisible); tc.setPrefWidth(width); }); }); } public void savePreferences() { Preferences prefs = Preferences.userNodeForPackage(getClass()); Preferences columnPrefs = prefs.node("table-columns"); getTableView().getColumns() .forEach(tc -> { Preferences p = columnPrefs.node(tc.getId()); p.put("visible", "false"); p.put("width", tc.getWidth() + ""); }); getTableView().getVisibleLeafColumns() .forEach(tc -> { Preferences p = columnPrefs.node(tc.getId()); p.put("visible", "true"); }); } public TableView<Annotation> getTableView() { if (tableView == null) { tableView = AnnotationTableViewFactory.newTableView(i18n); TableColumn<Annotation, URI> vruCol = new TableColumn<>(i18n.getString("annotable.col.videoreference")); vruCol.setCellValueFactory(param -> { URI uri = null; if (param.getValue() != null) { uri = videoReferenceUriMap.get(param.getValue().getVideoReferenceUuid()); } return new SimpleObjectProperty<>(uri); }); vruCol.setId("videoReferenceUuid"); // TODO get column order from preferences tableView.getColumns().add(vruCol); } return tableView; } private void enable() { Observable<Object> observable = eventBus.toObserverable(); Disposable disposable1 = observable.ofType(AnnotationsAddedEvent.class) .subscribe(e -> JFXUtilities.runOnFXThread(() -> { tableView.getItems().addAll(e.get()); tableView.sort(); })); disposables.add(disposable1); Disposable disposable2 = observable.ofType(AnnotationsRemovedEvent.class) .subscribe(e -> JFXUtilities.runOnFXThread(() -> tableView.getItems().removeAll(e.get()))); disposables.add(disposable2); Disposable disposable3 = observable.ofType(AnnotationsChangedEvent.class) .subscribe(e -> { JFXUtilities.runOnFXThread(() -> { Collection<Annotation> annotations = e.get(); ObservableList<Annotation> items = getTableView().getItems(); List<Annotation> intersection = ListUtils.intersection(annotations, items); for (Annotation a : intersection) { int idx = items.indexOf(a); items.remove(idx); items.add(idx, a); } tableView.refresh(); tableView.sort(); eventBus.send(new AnnotationsSelectedEvent(intersection)); }); }); disposables.add(disposable3); Disposable disposable4 = observable.ofType(AnnotationsSelectedEvent.class) .subscribe(e -> select(e.get())); disposables.add(disposable4); } private void disable() { disposables.forEach(Disposable::dispose); } public boolean isDisabled() { return disabled; } public void setDisabled(boolean disabled) { if (this.disabled != disabled) { if (disabled) { disable(); } else { enable(); } } this.disabled = disabled; } }
38.34375
113
0.590756
a463cc9beac884bf092d43eb34f3e3df7d3bd4ee
4,245
/* * Code by Shawn M. Chapla, 27 May 2016. * * ServerRequestProcessorThread processes commands from clients. Manages a processing * lock on ClientConnections. In the event of disaster, clears a client's inBound queue * and unlocks them so as to spare their connection. * */ package Challenge268EASY_server; public class ServerRequestProcessorThread extends Thread { private SynchronizedConnectionList connections; private ClientConnection processingClient; private DelayedPriorityBlockingQueue<String> messages; public ServerRequestProcessorThread(ClientConnection c, SynchronizedConnectionList cs, DelayedPriorityBlockingQueue<String> m) { super("ServerRequestProcessorThread"); processingClient = c; connections = cs; messages = m; } private void dropConnection(String dropMSG) { for(ClientConnection cli_con : connections) cli_con.outBound.delayAdd(processingClient.getUsername() + " has logged off."); messages.delayAdd(dropMSG); connections.remove(processingClient); } private void listUsers() { for(String un : connections.usernameSet()) processingClient.outBound.delayAdd(un); } private void sendAll(String command) { String message = processingClient.getUsername() + ": " + command.substring(8); messages.delayAdd("User message to all:\n{" + message + "}"); for(ClientConnection cli_con : connections) cli_con.outBound.delayAdd(message); } private void sendUser(String toUser, String command) { ClientConnection targetUser; if((targetUser = connections.getByUsername(toUser)) != null) { String clientUN = processingClient.getUsername(); String message = "(PM) " + clientUN + ": " + command.substring(10 + toUser.length()); // trim it up processingClient.outBound.delayAdd(message); targetUser.outBound.delayAdd(message); messages.delayAdd("Private message from " + clientUN + " to " + toUser + ":\n{" + message + "}"); } else { processingClient.outBound.delayAdd("Invalid user."); } } // here we handle all of the commands from clients @Override public void run() { processingClient.lockConnection(); // prevent a second processing thread from starting try { for(String command : processingClient.inBound) { String[] commandArray = command.split("\\s+"); switch(commandArray[0]) { case "CON": continue; // we ignore the con signal case "quit": dropConnection("Dropping connection to " + processingClient.userAtAddr() + " in response to 'quit' request."); return; case "sendall": if(commandArray.length >= 2) sendAll(command); else processingClient.outBound.delayAdd("Usage: sendall <message>"); break; case "senduser": if(commandArray.length >= 3) sendUser(commandArray[1], command); else processingClient.outBound.delayAdd("Usage: senduser <user> <message>"); break; case "listusers": listUsers(); break; default: processingClient.outBound.delayAdd("Command not found."); } processingClient.inBound.remove(command); } } catch (Exception e) { // it's highly unlikely that we should catch any kind of exception // but if we do, we don't want it to happen again processingClient.inBound.clear(); } finally { // and even if we do, we have to unlock the connection so it can be serviced again later processingClient.unlockConnection(); } } }
41.213592
100
0.570082
98a783ad402d610786e2bb2bb105055c0fe510cf
1,031
package org.springframework.boot.context.properties; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Indicates that a getter in a {@link ConfigurationProperties} object is deprecated. This * annotation has no bearing on the actual binding processes, but it is used by the * {@code spring-boot-configuration-processor} to add deprecation meta-data. * <p> * This annotation <strong>must</strong> be used on the getter of the deprecated element. * * @author Phillip Webb * @since 1.3.0 */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface DeprecatedConfigurationProperty { /** * The reason for the deprecation. * @return the deprecation reason */ String reason() default ""; /** * The field that should be used instead (if any). * @return the replacement field */ String replacement() default ""; }
26.435897
90
0.751697
1400f9822b1308f7319e4d5e6afb9b7f0c6aaa76
2,031
package org.jenkinsci.plugins.github.status.err; import hudson.Extension; import hudson.model.Descriptor; import hudson.model.Result; import hudson.model.Run; import hudson.model.TaskListener; import hudson.util.ListBoxModel; import org.jenkinsci.plugins.github.extension.status.StatusErrorHandler; import org.kohsuke.stapler.DataBoundConstructor; import javax.annotation.Nonnull; import static hudson.model.Result.FAILURE; import static hudson.model.Result.UNSTABLE; import static org.apache.commons.lang3.StringUtils.trimToEmpty; /** * Can change build status in case of errors * * @author lanwen (Merkushev Kirill) * @since 1.19.0 */ public class ChangingBuildStatusErrorHandler extends StatusErrorHandler { private String result; @DataBoundConstructor public ChangingBuildStatusErrorHandler(String result) { this.result = result; } public String getResult() { return result; } /** * Logs error to build console and changes build result * * @return true as of it terminating handler */ @Override public boolean handle(Exception e, @Nonnull Run<?, ?> run, @Nonnull TaskListener listener) { Result toSet = Result.fromString(trimToEmpty(result)); listener.error("[GitHub Commit Status Setter] - %s, setting build result to %s", e.getMessage(), toSet); run.setResult(toSet); return true; } @Extension public static class ChangingBuildStatusErrorHandlerDescriptor extends Descriptor<StatusErrorHandler> { private static final Result[] SUPPORTED_RESULTS = {FAILURE, UNSTABLE}; @Override public String getDisplayName() { return "Change build status"; } @SuppressWarnings("unused") public ListBoxModel doFillResultItems() { ListBoxModel items = new ListBoxModel(); for (Result supported : SUPPORTED_RESULTS) { items.add(supported.toString()); } return items; } } }
28.208333
112
0.6903
d68d2abcb09e825115597e4adfef3c01f046eb67
5,476
/* * Copyright 2014 Shazam Entertainment Limited * * 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.shazam.fork; import com.shazam.fork.model.DevicePool; import com.shazam.fork.model.Devices; import com.shazam.fork.model.TestClass; import com.shazam.fork.pooling.DevicePoolLoader; import com.shazam.fork.runtime.SwimlaneConsoleLogger; import com.shazam.fork.summary.OutcomeAggregator; import com.shazam.fork.summary.ReportGeneratorHook; import com.shazam.fork.summary.Summary; import com.shazam.fork.summary.SummaryPrinter; import com.shazam.fork.system.DeviceLoader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Collection; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import static com.shazam.fork.Utils.namedExecutor; public class ForkRunner { private static final Logger logger = LoggerFactory.getLogger(ForkRunner.class); private final Configuration configuration; private final RuntimeConfiguration runtimeConfiguration; private final DeviceLoader deviceLoader; private final DevicePoolLoader poolLoader; private final ScreenshotService screenshotService; private final TestClassScanner testClassScanner; private final TestClassFilter testClassFilter; private final DevicePoolRunner devicePoolRunner; private final SwimlaneConsoleLogger swimlaneConsoleLogger; private final SummaryPrinter summaryPrinter; public ForkRunner(Configuration configuration, RuntimeConfiguration runtimeConfiguration, DeviceLoader deviceLoader, DevicePoolLoader poolLoader, ScreenshotService screenshotService, TestClassScanner testClassScanner, TestClassFilter testClassFilter, DevicePoolRunner devicePoolRunner, SwimlaneConsoleLogger swimlaneConsoleLogger, SummaryPrinter summaryPrinter) { this.configuration = configuration; this.runtimeConfiguration = runtimeConfiguration; this.deviceLoader = deviceLoader; this.poolLoader = poolLoader; this.screenshotService = screenshotService; this.testClassScanner = testClassScanner; this.testClassFilter = testClassFilter; this.devicePoolRunner = devicePoolRunner; this.swimlaneConsoleLogger = swimlaneConsoleLogger; this.summaryPrinter = summaryPrinter; } public boolean run() { ExecutorService poolExecutor = null; try { // Get all connected devices & pools, fail if none Devices devices = deviceLoader.loadDevices(); if (devices.getDevices().isEmpty()) { logger.error("No devices found, so marking as failure"); return false; } Collection<DevicePool> devicePools = poolLoader.loadPools(devices); if (devicePools.isEmpty()) { logger.error("No device pools found, so marking as failure"); return false; } screenshotService.start(devices); List<TestClass> allTestClasses = testClassScanner.scanForTestClasses(); final List<TestClass> testClasses = testClassFilter.anyUserFilter(allTestClasses); int numberOfPools = devicePools.size(); final CountDownLatch poolCountDownLatch = new CountDownLatch(numberOfPools); poolExecutor = namedExecutor(numberOfPools, "PoolExecutor-%d"); // Only need emergency shutdown hook once tests have started. ReportGeneratorHook reportGeneratorHook = new ReportGeneratorHook( configuration, runtimeConfiguration, devicePools, testClasses, summaryPrinter); Runtime.getRuntime().addShutdownHook(reportGeneratorHook); for (final DevicePool devicePool : devicePools) { poolExecutor.execute(new Runnable() { @Override public void run() { try { TestClassProvider testsProvider = new TestClassProvider(testClasses); devicePoolRunner.runTestsOnDevicePool(devicePool, testsProvider); } catch (Exception e) { throw new RuntimeException(e); } finally { poolCountDownLatch.countDown(); logger.info("Pools remaining: " + poolCountDownLatch.getCount()); } } }); } poolCountDownLatch.await(); swimlaneConsoleLogger.complete(); Summary summary = reportGeneratorHook.generateReportOnlyOnce(); boolean overallSuccess = summary != null && new OutcomeAggregator().aggregate(summary); logger.info("Overall success: " + overallSuccess); return overallSuccess; } catch (Exception e) { logger.error("Error while Fork runner was executing", e); return false; } finally { if (poolExecutor != null) { poolExecutor.shutdown(); } screenshotService.stop(); } } }
42.123077
118
0.703616
2533fc47db5343a7e71633cec0ef7bdd1fe45ee8
386
package hr.fer.zemris.jcms.dao; import java.util.List; import hr.fer.zemris.jcms.model.Course; import javax.persistence.EntityManager; public interface CourseDAO { public Course get(EntityManager em, String isvuCode); public List<Course> getAllWithoutCategory(EntityManager em); public void save(EntityManager em, Course c); public void remove(EntityManager em, Course c); }
22.705882
61
0.787565
21d84d6808608e0446e165f16aad0b8e1ade5611
2,312
/* * Copyright (c) 2008-2019, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.client.impl.clientside; import java.util.ArrayList; import java.util.Iterator; import java.util.NoSuchElementException; public class ClientDiscoveryService implements Iterator<CandidateClusterContext> { private final ArrayList<CandidateClusterContext> discoveryServices; private final long size; private final int configsMaxTryCount; private long head; private long currentTryCount; public ClientDiscoveryService(int configsTryCount, ArrayList<CandidateClusterContext> discoveryServices) { this.discoveryServices = discoveryServices; this.size = discoveryServices.size(); this.configsMaxTryCount = configsTryCount; } public void resetSearch() { currentTryCount = 0; } public boolean hasNext() { return currentTryCount != configsMaxTryCount; } public CandidateClusterContext current() { return discoveryServices.get((int) (head % size)); } public CandidateClusterContext next() { if (currentTryCount == configsMaxTryCount) { throw new NoSuchElementException("Has no alternative cluster"); } head++; CandidateClusterContext candidateClusterContext = discoveryServices.get((int) (head % size)); if (head % size == 0) { currentTryCount++; } return candidateClusterContext; } @Override public void remove() { throw new UnsupportedOperationException("remove"); } public void shutdown() { for (CandidateClusterContext discoveryService : discoveryServices) { discoveryService.getCredentialsFactory().destroy(); } } }
32.111111
110
0.702855
432b092716da88914435e28dc49450160debd6d1
1,755
package com.education.entity; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import java.time.LocalDateTime; import java.io.Serializable; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; /** * <p> * 学生考勤表 * </p> * * @author dell * @since 2020-05-31 */ @Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) @ApiModel(value = "StudentSigninInfo对象", description = "学生考勤表") public class StudentSigninInfo implements Serializable { private static final long serialVersionUID = 1L; @TableId(value = "id", type = IdType.AUTO) private Long id; @ApiModelProperty(value = "外键(学生表student_info)", example = "0") private Long studentId; @ApiModelProperty(value = "外键(考勤表signin_info)", example = "0") private Long signinId; private LocalDateTime signTime; @ApiModelProperty(value = "0为没考勤,1为考勤", example = "0") private Integer status; private LocalDateTime dataCreate; private LocalDateTime dataModified; @ApiModelProperty(value = "status=2的总数", example = "0") @TableField(exist = false) private Integer signinAttendance; @ApiModelProperty(value = "status=1的总数", example = "0") @TableField(exist = false) private Integer signinUnAttendance; @ApiModelProperty(value = "status=0的总数", example = "0") @TableField(exist = false) private Integer signinNoAttendance; @TableField(exist = false) private StudentInfo studentInfo; @TableField(exist = false) private CourseName courseName; @TableField(exist = false) private String classNumber; }
25.071429
65
0.750997
98b55deba7d70fe0cfdc770fe96900a0cbbf60d6
395
package managers; import models.Person; /** * Created by jesu on 16/09/2015. */ public class PersonManager extends DataManager<Person> { private static PersonManager instance; private PersonManager() { super(Person.class); } public static PersonManager instance() { if ( instance == null ) instance = new PersonManager(); return instance; } }
17.954545
63
0.655696
449d4cea1c3016a2ea280cfe04dedb81fd1fcfca
520
/* Copyright (c) 2004-2010, The Dojo Foundation All Rights Reserved. Available via Academic Free License >= 2.1 OR the modified BSD license. see: http://dojotoolkit.org/license for details */ package org.dojotoolkit.json; import java.io.IOException; /** * */ public class JSONParseException extends IOException { /** * */ public JSONParseException() { super(); } /** * */ public JSONParseException(String message) { super(message); } }
17.931034
75
0.613462
859d365e77af4f18c5c07fbdc218f1c7d2beb2b2
1,857
/* * Apache License * * Copyright (c) 2020 HuahuiData * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.datasphere.datasource; import java.io.Serializable; public class FileValidationResponse implements Serializable { boolean isValid; String warning = null; public FileValidationResponse(boolean isValid, String warning) { this.isValid = isValid; this.warning = warning; } public FileValidationResponse(boolean isValid) { this.isValid = isValid; } public boolean isValid() { return isValid; } public void setValid(boolean isValid) { this.isValid = isValid; } public String getWarning() { return warning; } public void setWarning(String warning) { this.warning = warning; } public enum WarningType { SEEMS_NOT_FORMAL("FV001"), HEADER_MERGED("FV002"), DUPLICATED_HEADER("FV003"), TOO_LONG_HEADER("FV004"), NULL_HEADER("FV005"); private String warning; private WarningType(String warning) { this.warning = warning; } public String getCode() { return warning; } } }
24.116883
75
0.712439
7b920574a2e765a3e62217a6f72bae8b7fc77b13
2,053
/* * (c) Copyright 2022 Palantir Technologies Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.palantir.atlasdb.keyvalue.dbkvs; import com.palantir.atlasdb.AtlasDbConstants; import com.palantir.logsafe.Preconditions; import com.palantir.logsafe.SafeArg; import org.immutables.value.Value; /** * Tracks length limits on tables and identifier names within Oracle. */ @Value.Immutable public interface OracleIdentifierLengthLimits { int identifierLengthLimit(); int tablePrefixLengthLimit(); int overflowTablePrefixLengthLimit(); @Value.Derived default int tableNameLengthLimit() { return identifierLengthLimit() - AtlasDbConstants.PRIMARY_KEY_CONSTRAINT_PREFIX.length(); } @Value.Check default void check() { Preconditions.checkState( tablePrefixLengthLimit() < tableNameLengthLimit(), "Table prefix length limit must be shorter than the table name length limit", SafeArg.of("tablePrefixLengthLimit", tablePrefixLengthLimit()), SafeArg.of("tableNameLengthLimit", tableNameLengthLimit())); Preconditions.checkState( overflowTablePrefixLengthLimit() < tableNameLengthLimit(), "Overflow table prefix length limit must be shorter than the table name length limit", SafeArg.of("overflowTablePrefixLengthLimit", overflowTablePrefixLengthLimit()), SafeArg.of("tableNameLengthLimit", tableNameLengthLimit())); } }
38.018519
102
0.718948
e3151f22e1ff0e237c6eeba00f3397d3c30a16a9
3,314
package com.engelhardt.data; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Map; public class HealthKitData { //e.g. 2016-10-22 15:48:07 +0200 private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z"); private Map<Long, Float> weights = new HashMap<>(); private Map<Long, Float> consumedProtein = new HashMap<>(); private Map<Long, Float> consumedFat = new HashMap<>(); private Map<Long, Float> consumedCarbohydrate = new HashMap<>(); private Map<Long, Float> consumedEnergy = new HashMap<>(); public void addWeight(String date, float weight) throws ParseException{ weights.put(parseDate(date), weight); } public void addConsumedProtein(String date, float protein) throws ParseException{ long parsedDate = parseDate(date); Float overallProtein = consumedProtein.get(parsedDate); if(overallProtein == null){ overallProtein = 0.0f; } overallProtein += protein; consumedProtein.put(parsedDate, overallProtein); } public void addConsumedFat(String date, float fat) throws ParseException{ long parsedDate = parseDate(date); Float overallFat = consumedFat.get(parsedDate); if (overallFat == null){ overallFat = 0.0f; } overallFat += fat; consumedFat.put(parsedDate, overallFat); } public void addConsumedCarboHydrate(String date, float carbo) throws ParseException{ long parsedDate = parseDate(date); Float overallCarbs = consumedCarbohydrate.get(parsedDate); if (overallCarbs == null){ overallCarbs = 0.0f; } overallCarbs += carbo; consumedCarbohydrate.put(parsedDate, overallCarbs); } public void addConsumedEnergy(String date, float cals) throws ParseException{ long parsedDate = parseDate(date); Float overallCals = consumedEnergy.get(parsedDate); if(overallCals == null){ overallCals = 0.0f; } overallCals += cals; consumedEnergy.put(parsedDate, overallCals); } public Map<Long, Float> getWeights() { return weights; } public Map<Long, Float> getConsumedProtein() { return consumedProtein; } public Map<Long, Float> getConsumedFat() { return consumedFat; } public Map<Long, Float> getConsumedCarbohydrate() { return consumedCarbohydrate; } public float getConsumedCarbohydrate(long date) { return consumedCarbohydrate.get(date) == null ? 0.0f : consumedCarbohydrate.get(date); } public float getConsumedProtein(long date) { return consumedProtein.get(date) == null ? 0.0f : consumedProtein.get(date); } public float getConsumedFat(long date) { return consumedFat.get(date) == null ? 0.0f : consumedFat.get(date); } public SimpleDateFormat getSdf() { return sdf; } private long parseDate(String dateString) throws ParseException{ Date date = sdf.parse(dateString); Calendar cal = Calendar.getInstance(); cal.setTime(date); cal.set(Calendar.HOUR_OF_DAY, 12); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); return cal.getTimeInMillis(); } public Map<Long, Float> getConsumedEnergy() { return consumedEnergy; } public void setConsumedEnergy(Map<Long, Float> consumedEnergy) { this.consumedEnergy = consumedEnergy; } }
27.163934
88
0.725407
7da8b677f4326bdfba6de6cf8744c9e3f0800d51
1,408
import java.util.regex.Matcher; import java.util.regex.Pattern; public class regexlib_3365 { /* 3365 * ([a-zA-Z1-9]*)\.(((a|A)(s|S)(p|P)(x|X))|((h|H)(T|t)(m|M)(l|L))|((h|H)(t|T)(M|m))|((a|A)(s|S)(p|P))|((t|T)(x|X)(T|x))|((m|M)(S|s)(P|p)(x|X))|((g|G)(i|I)(F|f))|((d|D)(o|O)(c|C))) * POLYNOMIAL * nums:2 * POLYNOMIAL AttackString:""+"a"*10000+"◎@! _1SLQ_1" */ public static void main(String[] args) throws InterruptedException { String regex = "([a-zA-Z1-9]*)\\.(((a|A)(s|S)(p|P)(x|X))|((h|H)(T|t)(m|M)(l|L))|((h|H)(t|T)(M|m))|((a|A)(s|S)(p|P))|((t|T)(x|X)(T|x))|((m|M)(S|s)(P|p)(x|X))|((g|G)(i|I)(F|f))|((d|D)(o|O)(c|C)))"; for (int i = 0; i < 1000; i++) { StringBuilder attackString = new StringBuilder(); // 前缀 attackString.append(""); // 歧义点 for (int j = 0; j < i * 10000; j++) { attackString.append("a"); } // 后缀 attackString.append("◎@! _1SLQ_1"); // System.out.println(attackString); long time1 = System.nanoTime(); // boolean isMatch = Pattern.matches(regex, attackString); boolean isMatch = Pattern.compile(regex).matcher(attackString).find(); long time2 = System.nanoTime(); System.out.println(i * 10000 + " " + isMatch + " " + (time2 - time1)/1e9); } } }
44
203
0.478693
c96c422d9af4738f800f88e6ac2a6e9ddacaaebb
2,474
/* * Copyright 2012-2020 Sergey Ignatov * * 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.intellij.erlang.search; import com.intellij.find.findUsages.PsiElement2UsageTargetAdapter; import com.intellij.openapi.fileTypes.FileType; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.psi.PsiElement; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.usages.UsageTarget; import com.intellij.usages.UsageTargetProvider; import org.intellij.erlang.ErlangFileType; import org.intellij.erlang.index.ErlangModuleIndex; import org.intellij.erlang.psi.ErlangFile; import org.intellij.erlang.psi.ErlangModule; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; public class ErlangTargetProvider implements UsageTargetProvider { @Nullable @Override public UsageTarget[] getTargets(@NotNull PsiElement psiElement) { if (psiElement instanceof ErlangFile){ ErlangFile psiFile = (ErlangFile)psiElement; FileType fileType = ((ErlangFile) psiElement).getFileType(); PsiElement findElement = psiElement; if (ErlangFileType.MODULE == fileType) { if (psiFile.getModule() != null) { findElement = psiFile.getModule(); } } if (ErlangFileType.TERMS == fileType){ String moduleName = psiFile.getVirtualFile().getNameWithoutExtension(); Module module = ModuleUtilCore.findModuleForPsiElement(psiFile); assert module != null; List<ErlangModule> modulesByName = ErlangModuleIndex.getModulesByName(psiFile.getProject(), moduleName, GlobalSearchScope.moduleWithDependentsScope(module)); if (modulesByName.size() > 0) findElement = modulesByName.get(0); } assert findElement != null; return new UsageTarget[]{new PsiElement2UsageTargetAdapter(findElement)}; } return new UsageTarget[0]; } }
38.65625
165
0.751819
6e927a34393c6b2461a45744127e1a1a7281b77e
17,329
package main; import Utils.Utility; import com.xilinx.rapidwright.design.Design; import com.xilinx.rapidwright.device.ClockRegion; import com.xilinx.rapidwright.device.Site; import java.io.*; import java.util.List; import java.util.Map; public class Vivado { static String checkpoint = System.getProperty("RAPIDWRIGHT_PATH") + "/checkpoint/"; static String tcl = System.getProperty("RAPIDWRIGHT_PATH") + "/tcl/"; static String result = System.getProperty("RAPIDWRIGHT_PATH") + "/result/"; static String root = System.getProperty("RAPIDWRIGHT_PATH") + "/"; public static Design synthesize_with_seed(int block_num, String device, int depth, String part, boolean verbose) throws IOException { long start_time = System.nanoTime(); // synthesize seed first, if seed is not available String seed_path = checkpoint + device + "_seed_" + depth; File seed_file = new File(seed_path + ".dcp"); if (!seed_file.exists()) synthesize_seed(part, depth, seed_path, verbose); else{ Design d = Design.readCheckpoint(seed_path + ".dcp"); Design temp_d = new Design("temp", device); if (!d.getPartName().equals(temp_d.getPartName())) { // if the seed is not compatible System.out.println(">>>>WARNING<<<< -- Seed's Device Part Name is different from requested, redo seed synthesis......"); synthesize_seed(part, depth, seed_path, verbose); } } Design seed = Design.readCheckpoint(seed_path + ".dcp"); // Replicate Design design = Tool.replicateConvBlocks(seed, block_num); long end_time = System.nanoTime(); String s = "Synthesis - " + block_num + " conv blocks, time = " + (end_time-start_time)/1e9 + " s"; System.out.println(">>>-----------------------------------------------"); System.out.println(s); System.out.println(">>>-----------------------------------------------"); //Design new_design = legalize_process(design); String synthDCP = checkpoint + "blockNum=" + block_num + "_synth.dcp"; design.writeCheckpoint(synthDCP); return design; } public static Design synthesize_vivado(int block_num, String part, int depth, boolean verbose){ String tcl_path = tcl + "synth.tcl"; String output_path = checkpoint + block_num + "_" + part + "_" + depth; File checkpoint = new File(output_path+".dcp"); if (checkpoint.exists()) return Design.readCheckpoint(output_path+".dcp"); // write tcl script try (FileWriter write = new FileWriter(tcl_path)) { PrintWriter printWriter = new PrintWriter(write, true); printWriter.println("read_verilog ../verilog/addr_gen.v ../verilog/dsp_conv.v ../verilog/dsp_conv_top.v ../verilog/dsp_conv_chip.sv"); printWriter.println("set_property generic {NUMBER_OF_REG=" + depth + " Y="+block_num+"} [current_fileset]"); printWriter.println("synth_design -mode out_of_context -part "+ part +" -top dsp_conv_chip;"); printWriter.println("write_checkpoint -force -file " + output_path + ".dcp"); printWriter.println("write_edif -force -file " + output_path + ".edf"); printWriter.println("exit"); printWriter.close(); } catch (IOException e) { e.printStackTrace(); } long start_time = System.nanoTime(); vivado_cmd("vivado -mode tcl -source " + tcl_path, verbose); long end_time = System.nanoTime(); String s = "Synthesis - " + block_num + " conv blocks, time = " + (end_time-start_time)/1e9/60 + " min"; System.out.println(">>>-----------------------------------------------"); System.out.println(s); System.out.println(">>>-----------------------------------------------"); return Design.readCheckpoint(output_path+".dcp"); } public static void synthesize_seed(String part, int depth, String output_path, boolean verbose){ String tcl_path = tcl + "synth_seed.tcl"; // write tcl script try (FileWriter write = new FileWriter(tcl_path)) { PrintWriter printWriter = new PrintWriter(write, true); printWriter.println("read_verilog ../verilog/addr_gen.v ../verilog/dsp_conv.v ../verilog/dsp_conv_top.v ../verilog/dsp_conv_chip.sv"); printWriter.println("set_property generic {NUMBER_OF_REG=" + depth + " Y=1} [current_fileset]"); printWriter.println("synth_design -mode out_of_context -part "+ part +" -top dsp_conv_chip;"); printWriter.println("write_checkpoint -force -file " + output_path + ".dcp"); printWriter.println("write_edif -force -file " + output_path + ".edf"); printWriter.println("exit"); printWriter.close(); } catch (IOException e) { e.printStackTrace(); } long start_time = System.nanoTime(); vivado_cmd("vivado -mode tcl -source " + tcl_path, verbose); long end_time = System.nanoTime(); String s = "Synthesis - " + 1 + " conv blocks, time = " + (end_time-start_time)/1e9/60 + " min"; System.out.println(">>>-----------------------------------------------"); System.out.println(s); System.out.println(">>>-----------------------------------------------"); } // Vivado-only implementation, given placement and block number public static double implementation(int block_num, String part, String device, Map<Integer, List<Site[]>> placement, boolean save, boolean verbose) throws IOException { String xdc_path = result + "blockNum=" + block_num + ".xdc"; String tcl_path = tcl + "full_implementation.tcl"; String output_path = checkpoint + "Vivado_routed_" + block_num + ".dcp"; String verilog_path = root + "src/verilog/"; // write tcl script try (FileWriter write = new FileWriter(tcl_path)) { PrintWriter printWriter = new PrintWriter(write, true); printWriter.println("read_verilog " + verilog_path +"addr_gen.v " + verilog_path + "dsp_conv.v " + verilog_path + "dsp_conv_top.v " + verilog_path + "dsp_conv_chip.sv"); printWriter.println("set_property generic Y=" + block_num + " [current_fileset]"); File synth = new File(checkpoint + "blockNum=" + block_num + "_synth.dcp"); if (synth.exists()) printWriter.println("open_checkpoint " + synth.getAbsolutePath()); else printWriter.println("synth_design -mode out_of_context -part "+ part +" -top dsp_conv_chip;"); printWriter.println("create_clock -period 1.000 -waveform {0.000 0.500} [get_nets clk];"); PBlockConstraint(printWriter, placement, device); printWriter.println("read_xdc " + xdc_path); printWriter.println("place_design; route_design; report_utilization; report_timing;"); if (save) printWriter.println("write_checkpoint -force -file " + output_path); printWriter.println("exit"); printWriter.close(); } long start_time = System.nanoTime(); String slack = vivado_cmd("vivado -mode tcl -source " + tcl_path, verbose); long end_time = System.nanoTime(); System.out.println(">>>-----------------------------------------------"); System.out.println("Full Vivado Implementation time = " + (end_time-start_time)/1e9/60 + " min"); System.out.println(">>>-----------------------------------------------"); double violation = Double.parseDouble(slack.substring(slack.indexOf("-"), slack.indexOf("ns"))); double clk_period = 1 - violation; double frequency = 1e9 / clk_period; return frequency; } public static String vivado_cmd(String cmd, boolean verbose) { String command = "export PATH=$PATH:~/Vivado/2018.3/bin/;" + cmd; String vivado_path = System.getenv("VIVADO_PATH"); if (vivado_path != null) { command = "export PATH:$PATH:" + vivado_path + ";" + cmd; } String slack = ""; try { ProcessBuilder builder = new ProcessBuilder("/bin/bash", "-c", command); builder.redirectErrorStream(true); builder.directory(new File(root + "src/main")); Process p = builder.start(); BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream())); StringBuffer buffer = new StringBuffer(); String line = ""; while (true) { buffer.append(line).append("\n"); line = r.readLine(); if (line == null) { break; } if (line.startsWith("Slack")) slack = line; if (verbose){ System.out.println(line); } } p.waitFor(); r.close(); } catch (IOException | InterruptedException e) { e.printStackTrace(); } return slack; } public static void PBlockConstraint(PrintWriter tcl, Map<Integer, List<Site[]>> placement, String dev) { tcl.println("startgroup"); tcl.println("create_pblock {pblock_name.dut}"); Utility utils = new Utility(placement, dev); ClockRegion[] r = utils.getClockRegionRange(); tcl.println("resize_pblock {pblock_name.dut} -add " + "CLOCKREGION_" + r[0].getName() + ":" + "CLOCKREGION_" + r[1].getName()); tcl.println("add_cells_to_pblock {pblock_name.dut} -top"); tcl.println("endgroup"); tcl.println("set_property CONTAIN_ROUTING true [get_pblocks pblock_name.dut]"); } public static double finishPlacementNRoute(String placedDCP, int block_num, boolean verbose) throws IOException { String tcl_path = tcl + "finish_placement.tcl"; String output_path = checkpoint + "blockNum=" + block_num + "_routed"; // write tcl script try (FileWriter write = new FileWriter(tcl_path)) { PrintWriter printWriter = new PrintWriter(write, true); printWriter.println("open_checkpoint " + placedDCP); printWriter.println("create_clock -period 1.000 -waveform {0.000 0.500} [get_nets clk];"); printWriter.println("place_design; route_design; report_timing"); printWriter.println("write_checkpoint -force -file " + output_path + ".dcp"); printWriter.println("write_edif -force -file " + output_path + ".edf"); printWriter.println("exit"); printWriter.close(); } long start_time = System.nanoTime(); String slack = Vivado.vivado_cmd("vivado -mode tcl -source " + tcl_path, verbose); long end_time = System.nanoTime(); System.out.println(">>>-----------------------------------------------"); System.out.println("Continued Placement and Route (Vivado) time = " + (end_time-start_time)/1e9/60 + " min"); System.out.println(">>>-----------------------------------------------"); double violation = Double.parseDouble(slack.substring(slack.indexOf("-"), slack.indexOf("ns"))); double clk_period = 1 - violation; double frequency = 1e9 / clk_period; return frequency; } public static double finishPlacementNRoutePBlock(String placedDCP, int block_num, Map<Integer, List<Site[]>> placement, String device, boolean verbose) throws IOException { String tcl_path = tcl + "finish_placement.tcl"; String output_path = checkpoint + "blockNum=" + block_num + "_routed.dcp"; String output_edif = checkpoint + "blockNum=" + block_num + "_routed.edf"; // write tcl script try (FileWriter write = new FileWriter(tcl_path)) { PrintWriter printWriter = new PrintWriter(write, true); printWriter.println("open_checkpoint " + placedDCP); printWriter.println("write_checkpoint -force " + placedDCP); printWriter.println("open_checkpoint " + placedDCP); PBlockConstraint(printWriter, placement, device); printWriter.println("create_clock -period 1.000 -waveform {0.000 0.500} [get_nets clk];"); printWriter.println("place_design;"); printWriter.println("route_design"); printWriter.println("report_timing;"); printWriter.println("write_checkpoint -force -file " + output_path); printWriter.println("write_edf -force -file " + output_edif); printWriter.println("exit"); printWriter.close(); } long start_time = System.nanoTime(); String slack = Vivado.vivado_cmd("vivado -mode tcl -source " + tcl_path, verbose); long end_time = System.nanoTime(); System.out.println(">>>-----------------------------------------------"); System.out.println("Continued Placement and Route (Vivado) time = " + (end_time-start_time)/1e9/60 + " min"); System.out.println(">>>-----------------------------------------------"); double violation = Double.parseDouble(slack.substring(slack.indexOf("-"), slack.indexOf("ns"))); double clk_period = 1 - violation; return 1e9 / clk_period; } public static double implement_pipelined_design(String pipelinedDCP, String xdc_path, int block_num, boolean verbose) throws IOException { String tcl_path = tcl + "finish_placement.tcl"; String output_path = checkpoint + "blockNum=" + block_num + "_routed"; // write tcl script try (FileWriter write = new FileWriter(tcl_path)) { PrintWriter printWriter = new PrintWriter(write, true); printWriter.println("open_checkpoint " + pipelinedDCP); printWriter.println("read_xdc " + xdc_path); printWriter.println("create_clock -period 1.000 -waveform {0.000 0.500} [get_nets clk];"); printWriter.println("place_design; route_design; report_timing"); printWriter.println("write_checkpoint -force -file " + output_path + ".dcp"); printWriter.println("write_edif -force -file " + output_path + ".edf"); printWriter.println("exit"); printWriter.close(); } long start_time = System.nanoTime(); String slack = Vivado.vivado_cmd("vivado -mode tcl -source " + tcl_path, verbose); long end_time = System.nanoTime(); System.out.println(">>>-----------------------------------------------"); System.out.println("Continued Placement and Route (Vivado) time = " + (end_time-start_time)/1e9/60 + " min"); System.out.println(">>>-----------------------------------------------"); double violation = Double.parseDouble(slack.substring(slack.indexOf("-"), slack.indexOf("ns"))); double clk_period = 1 - violation; double frequency = 1e9 / clk_period; System.out.println("$$$$ frequency = " + frequency/1e6 + " MHz"); return frequency; } public static double post_impl_retiming(String implementedDesign) throws IOException { String tcl_path = tcl + "retiming.tcl"; // write tcl script try (FileWriter write = new FileWriter(tcl_path)) { PrintWriter printWriter = new PrintWriter(write, true); printWriter.println("open_checkpoint " + implementedDesign); printWriter.println("create_clock -period 1.000 -waveform {0.000 0.500} [get_nets clk];"); printWriter.println("report_timing"); printWriter.println("exit"); printWriter.close(); } String slack = Vivado.vivado_cmd("vivado -mode tcl -source " + tcl_path, true); double violation = Double.parseDouble(slack.substring(slack.indexOf("-"), slack.indexOf("ns"))); double clk_period = 1 - violation; double frequency = 1e9 / clk_period; System.out.println("$$$$ frequency = " + frequency/1e6 + " MHz"); return frequency; } public static Design legalize_process(Design d) throws IOException { String temp_dcp = System.getProperty("RAPIDWRIGHT_PATH") + "/checkpoint/temp.dcp"; String new_dcp = System.getProperty("RAPIDWRIGHT_PATH") + "/checkpoint/temp2.dcp"; String new_edif = System.getProperty("RAPIDWRIGHT_PATH") + "/checkpoint/temp2.edf"; d.writeCheckpoint(temp_dcp); // vivado: read in and write out the temp dcp String tclFile = System.getProperty("RAPIDWRIGHT_PATH") + "/tcl/temp.tcl"; PrintWriter tcl = new PrintWriter(new FileWriter(tclFile), true); tcl.println("open_checkpoint " + temp_dcp); tcl.println("write_checkpoint -force -file " + new_dcp); tcl.println("write_edif -force -file " + new_edif); tcl.println("exit"); tcl.close(); Vivado.vivado_cmd("vivado -mode tcl -source " + tclFile, true); d = Design.readCheckpoint(new_dcp); return d; } }
49.090652
146
0.592187
dcc1ed3be2e27a5c2e368f0d3a1113f7c97a1503
622
package _020_Sum_OddRange; public class SumOddRange { public static boolean isOdd(int number) { boolean odd = false; if (number > 0 && number % 2 == 1) { odd = true; } return odd; } public static int sumOdd(int start, int end) { if (start < 1 || end < 1 || start > end) { return -1; } if (start == end && isOdd(start)) { return start; } int sum = 0; for (int i=start; i<=end; i++) { if (isOdd(i)) { sum += i; } } return sum; } }
20.064516
50
0.426045
743797047436a1ceeedc713955b31d6159069110
3,481
package org.kilocraft.essentials.user; import com.mojang.brigadier.exceptions.CommandSyntaxException; import net.minecraft.nbt.CompoundTag; import net.minecraft.text.Text; import org.jetbrains.annotations.Nullable; import org.kilocraft.essentials.api.text.MessageReceptionist; import org.kilocraft.essentials.api.user.User; import org.kilocraft.essentials.api.user.settting.Setting; import org.kilocraft.essentials.api.user.settting.UserSettings; import org.kilocraft.essentials.api.world.location.Location; import java.io.IOException; import java.util.Date; import java.util.Optional; import java.util.UUID; public class NeverJoinedUser implements org.kilocraft.essentials.api.user.NeverJoinedUser { @Override public UUID getUuid() { return null; } @Override public String getUsername() { return null; } @Override public UserSettings getSettings() { return null; } @Override public <T> T getSetting(Setting<T> setting) { return null; } @Override public boolean isOnline() { return false; } @Override public boolean hasNickname() { return false; } @Override public String getDisplayName() { return null; } @Override public String getFormattedDisplayName() { return null; } @Override public Text getRankedDisplayName() { return null; } @Override public Text getRankedName() { return null; } @Override public String getNameTag() { return null; } @Override public Optional<String> getNickname() { return Optional.empty(); } @Override public Location getLocation() { return null; } @Override public @Nullable Location getLastSavedLocation() { return null; } @Override public void saveLocation() { } @Override public void setNickname(String name) { } @Override public void clearNickname() { } @Override public void setLastLocation(Location loc) { } @Override public boolean hasJoinedBefore() { return false; } @Override public @Nullable Date getFirstJoin() { return null; } @Override public @Nullable Date getLastOnline() { return null; } @Override public UserHomeHandler getHomesHandler() { return null; } @Override public @Nullable String getLastSocketAddress() { return null; } @Override public int getTicksPlayed() { return 0; } @Override public void setTicksPlayed(int ticks) { } @Override public void saveData() throws IOException { } @Override public void trySave() throws CommandSyntaxException { } @Override public boolean equals(User anotherUser) { return false; } @Override public boolean ignored(UUID uuid) { return false; } @Override public MessageReceptionist getLastMessageReceptionist() { return null; } @Override public void setLastMessageReceptionist(MessageReceptionist receptionist) { } @Override public CompoundTag toTag() { return null; } @Override public void fromTag(CompoundTag tag) { } @Override public String getName() { return null; } @Override public UUID getId() { return null; } }
17.943299
91
0.633726
dd478fe0eb0593304a828cd00a00b73e337bacf5
262
package kodlama.io.HRMS.dataAccess.abstracts; import org.springframework.data.jpa.repository.JpaRepository; import kodlama.io.HRMS.entities.concretes.User; public interface UserDao extends JpaRepository<User, Integer>{ boolean existsByEmail(String email); }
26.2
62
0.828244
10c09808656f35fe9c10f0dfd98caed5904a44b8
3,436
/* * Copyright 2014 NAVER Corp. * * 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.navercorp.pinpoint.common.util; import junit.framework.Assert; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.navercorp.pinpoint.common.util.MathUtils; /** * @author emeroad */ public class MathUtilsTest { private final Logger logger = LoggerFactory.getLogger(this.getClass()); @Test public void fastAbs() { Assert.assertTrue(MathUtils.fastAbs(-1) > 0); Assert.assertTrue(MathUtils.fastAbs(0) == 0); Assert.assertTrue(MathUtils.fastAbs(1) > 0); } @Test public void overflow() { logger.debug("abs:{}", Math.abs(Integer.MIN_VALUE)); logger.debug("fastabs:{}", MathUtils.fastAbs(Integer.MIN_VALUE)); int index = Integer.MIN_VALUE - 2; for (int i = 0; i < 5; i++) { logger.debug("{}------------", i); logger.debug("{}", index); logger.debug("mod:{}", index % 3); logger.debug("abs:{}", Math.abs(index)); logger.debug("fastabs:{}", MathUtils.fastAbs(index)); index++; } } @Test public void roundToNearestMultipleOf() { Assert.assertEquals(1, MathUtils.roundToNearestMultipleOf(1, 1)); Assert.assertEquals(4, MathUtils.roundToNearestMultipleOf(1, 4)); Assert.assertEquals(4, MathUtils.roundToNearestMultipleOf(2, 4)); Assert.assertEquals(4, MathUtils.roundToNearestMultipleOf(3, 4)); Assert.assertEquals(4, MathUtils.roundToNearestMultipleOf(4, 4)); Assert.assertEquals(4, MathUtils.roundToNearestMultipleOf(5, 4)); Assert.assertEquals(8, MathUtils.roundToNearestMultipleOf(6, 4)); Assert.assertEquals(8, MathUtils.roundToNearestMultipleOf(7, 4)); Assert.assertEquals(8, MathUtils.roundToNearestMultipleOf(8, 4)); Assert.assertEquals(10, MathUtils.roundToNearestMultipleOf(10, 5)); Assert.assertEquals(10, MathUtils.roundToNearestMultipleOf(11, 5)); Assert.assertEquals(10, MathUtils.roundToNearestMultipleOf(12, 5)); Assert.assertEquals(15, MathUtils.roundToNearestMultipleOf(13, 5)); Assert.assertEquals(15, MathUtils.roundToNearestMultipleOf(14, 5)); Assert.assertEquals(15, MathUtils.roundToNearestMultipleOf(15, 5)); Assert.assertEquals(15, MathUtils.roundToNearestMultipleOf(16, 5)); Assert.assertEquals(15, MathUtils.roundToNearestMultipleOf(17, 5)); Assert.assertEquals(20, MathUtils.roundToNearestMultipleOf(18, 5)); Assert.assertEquals(20, MathUtils.roundToNearestMultipleOf(19, 5)); Assert.assertEquals(20, MathUtils.roundToNearestMultipleOf(20, 5)); Assert.assertEquals(5000, MathUtils.roundToNearestMultipleOf(6000, 5000)); Assert.assertEquals(10000, MathUtils.roundToNearestMultipleOf(9000, 5000)); } }
40.423529
83
0.686554
56e4dbdc5bd64737d4ce28a66032c88ddae33a3f
2,190
package io.quarkus.reactive.datasource.runtime; import io.vertx.core.AsyncResult; import io.vertx.core.Future; import io.vertx.core.Handler; import io.vertx.core.Promise; import io.vertx.sqlclient.PreparedQuery; import io.vertx.sqlclient.Query; import io.vertx.sqlclient.Row; import io.vertx.sqlclient.RowSet; import io.vertx.sqlclient.SqlConnection; final class TestableThreadLocalPool extends ThreadLocalPool<TestPoolInterface> { public TestableThreadLocalPool() { super(null, null); } @Override protected TestPoolInterface createThreadLocalPool() { return new TestPoolWrapper(new TestPool()); } private class TestPoolWrapper implements TestPoolInterface { private final TestPool delegate; private boolean open = true; private TestPoolWrapper(TestPool delegate) { this.delegate = delegate; } @Override public void getConnection(Handler<AsyncResult<SqlConnection>> handler) { delegate.getConnection(handler); } @Override public Future<SqlConnection> getConnection() { Promise<SqlConnection> promise = Promise.promise(); getConnection(promise); return promise.future(); } @Override public Query<RowSet<Row>> query(String s) { return delegate.query(s); } @Override public PreparedQuery<RowSet<Row>> preparedQuery(String s) { return delegate.preparedQuery(s); } @Override public void close(Handler<AsyncResult<Void>> handler) { if (open) { delegate.close(); TestableThreadLocalPool.this.removeSelfFromTracking(this); } handler.handle(Future.succeededFuture()); } @Override public Future<Void> close() { if (open) { delegate.close(); TestableThreadLocalPool.this.removeSelfFromTracking(this); } return Future.succeededFuture(); } @Override public boolean isClosed() { return delegate.isClosed(); } } }
27.375
80
0.621005
004ce8c3c3d7b0e0852001208a26b7f38fe305d1
3,103
/* * 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.lealone.hansql.exec.planner; import org.lealone.hansql.optimizer.plan.Context; import org.lealone.hansql.optimizer.plan.Contexts; import org.lealone.hansql.optimizer.plan.RelOptCluster; import org.lealone.hansql.optimizer.plan.RelOptSchema; import org.lealone.hansql.optimizer.rel.RelNode; import org.lealone.hansql.optimizer.rel.core.RelFactories; import org.lealone.hansql.optimizer.tools.RelBuilder; import org.lealone.hansql.optimizer.tools.RelBuilderFactory; import org.lealone.hansql.optimizer.util.Util; public class DrillRelBuilder extends RelBuilder { private final RelFactories.FilterFactory filterFactory; protected DrillRelBuilder(Context context, RelOptCluster cluster, RelOptSchema relOptSchema) { super(context, cluster, relOptSchema); this.filterFactory = Util.first(context.unwrap(RelFactories.FilterFactory.class), RelFactories.DEFAULT_FILTER_FACTORY); } /** * Original method {@link RelBuilder#empty} returns empty values rel. * In the order to preserve data row types, filter with false predicate is created. */ @Override public RelBuilder empty() { // pops the frame from the stack and returns its relational expression RelNode relNode = build(); // creates filter with false in the predicate final RelNode filter = filterFactory.createFilter(relNode, cluster.getRexBuilder().makeLiteral(false)); push(filter); return this; } /** Creates a {@link RelBuilderFactory}, a partially-created DrillRelBuilder. * Just add a {@link RelOptCluster} and a {@link RelOptSchema} */ public static RelBuilderFactory proto(final Context context) { return new RelBuilderFactory() { public RelBuilder create(RelOptCluster cluster, RelOptSchema schema) { return new DrillRelBuilder(context, cluster, schema); } }; } /** Creates a {@link RelBuilderFactory} that uses a given set of factories. */ public static RelBuilderFactory proto(Object... factories) { return proto(Contexts.of(factories)); } /** * Disables combining of consecutive {@link org.lealone.hansql.optimizer.rel.core.Project} nodes. * See comments under CALCITE-2470 for details. * @return false */ @Override protected boolean shouldMergeProject() { return false; } }
38.308642
107
0.750564
05609728b88c29b6c346fafd2b8fcc77d1eea153
336
package pr3; public class DailyTemperature extends Temperature { public DailyTemperature(int month, int day){ sMonth = month; sDay = day; high = new int[DATA_SIZE]; low = new int[DATA_SIZE]; for(int i=0; i<DATA_SIZE; i++) { high[i] = UNKNOWN_TEMP; low[i] = UNKNOWN_TEMP; } } }
14
52
0.589286
30d65c63109b7900e5a13bebddc09d59631fcaca
1,922
/* * Copyright (c) 2008-2012 Sonatype, Inc. All rights reserved. * * This program is licensed to you under the Apache License Version 2.0, * and you may not use this file except in compliance with the Apache License Version 2.0. * You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, * software distributed under the Apache License Version 2.0 is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under. */ package fathom.mailer; import com.google.inject.Inject; import org.sonatype.micromailer.MailType; import org.sonatype.micromailer.MailTypeSource; import org.sonatype.micromailer.imp.DefaultMailType; import org.sonatype.micromailer.imp.HtmlMailType; import javax.inject.Named; import javax.inject.Singleton; import java.util.Collection; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * The provider of MailTypes for Fathom Mailer. * * @author James Moger */ @Singleton @Named public class FtmMailTypes implements MailTypeSource { private final Map<String, MailType> mailTypes; @Inject public FtmMailTypes() { mailTypes = new ConcurrentHashMap<>(); addMailType(new DefaultMailType()); addMailType(new HtmlMailType()); } public synchronized void addMailType(MailType mailType) { mailTypes.put(mailType.getTypeId(), mailType); } @Override public Collection<MailType> getKnownMailTypes() { return mailTypes.values(); } @Override public MailType getMailType(String id) { if (mailTypes.containsKey(id)) { return mailTypes.get(id); } else { return null; } } }
30.507937
114
0.721124
672c228b5e119c760867902d3e0e073d51529e55
2,404
// GsonDemo (c) 2018 Baltasar MIT License <[email protected]> import java.io.IOException; import java.util.Collection; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; /** Util class for saving and retrieving books. */ public class BooksPersistence { public static String ETQ_AUTHOR = "author"; public static String ETQ_TITLE = "title"; /** @return A book read from JSON. */ public static Book readBook(JsonReader reader) throws IOException { String author = ""; String title = ""; reader.beginObject(); while( reader.hasNext() ) { String label = reader.nextName(); if ( label.equals( ETQ_AUTHOR ) ) { author = reader.nextString(); } else if ( label.equals( ETQ_TITLE ) ) { title = reader.nextString(); } else { // Unknown name found reader.skipValue(); } } reader.endObject(); if ( author.isEmpty() ) { throw new IOException( "missing book's author" ); } if ( title.isEmpty() ) { throw new IOException( "missing book's title" ); } return new Book( author, title ); } /** Reads a list of books from JSON. * @param reader the reader to get the list of books from. * @param books the collection to fill with the read books. */ public static void readBooks(JsonReader reader, Collection<Book> books) throws IOException { reader.beginArray(); while ( reader.hasNext() ) { books.add( readBook( reader ) ); } reader.endArray(); } /** Writes a list of books to JSON. * @param writer the writer to output the list of books to. * @param books the collection containing all the books. */ public static void writeBooks(JsonWriter writer, Collection<Book> books) throws IOException { writer.beginArray(); for(Book book: books) { writer.beginObject(); writer.name( ETQ_AUTHOR ).value( book.getAuthor() ); writer.name( ETQ_TITLE ).value( book.getTitle() ); writer.endObject(); } writer.endArray(); } }
28.963855
95
0.551997
b055c25bd4c7dc75124e264bf7822e9980e1c9f9
4,889
package org.vocobox.model.note; import java.io.File; import org.vocobox.io.EzRgx; public class Note extends EzRgx { public static NoteParser NOTE_PARSER = new NoteParser(); public String name; public String sign; public int octave; public int instance; public File file; public Voyel voyel; public Note(){ } public Note(String filename) { this(new File(filename)); } public Note(File file) { this(file, NOTE_PARSER); } public Note(File file, NoteParser parser) { this.file = file; parser.parseNoteFileName(this, file); } public NoteDescriptor getDescriptor(){ String fullName = (toString()).toUpperCase(); return getDescriptor(fullName); } public NoteDescriptor getDescriptor(String fullName) { return NoteDescriptors.PIANO.getNoteByName(fullName); } /** * order of the note in its octave, where A as order 0. */ public int orderStartAtA() { if ("a".equals(name)) { if("#".equals(sign)){ return 1; } else if("b".equals(sign)){ return 12; } else return 0; } else if ("b".equals(name)) { if("#".equals(sign)){ return 3; } else if("b".equals(sign)){ return 1; } else { return 2; } } else if ("c".equals(name)) { if("#".equals(sign)){ return 4; } else if("b".equals(sign)){ return 2; } else { return 3; } } else if ("d".equals(name)) { if("#".equals(sign)){ return 6; } else if("b".equals(sign)){ return 4; } else { return 5; } } else if ("e".equals(name)) { if("#".equals(sign)){ return 8; } else if("b".equals(sign)){ return 6; } else { return 7; } } else if ("f".equals(name)) { if("#".equals(sign)){ return 9; } else if("b".equals(sign)){ return 7; } else { return 8; } } else if ("g".equals(name)) { if("#".equals(sign)){ return 11; } else if("b".equals(sign)){ return 9; } else { return 10; } } return -1; } /** * order of the note in its octave, where A as order 0. */ public int orderStartAtC() { if ("c".equals(name)) { if("#".equals(sign)){ return 1; } else if("b".equals(sign)){ return 12; } else return 0; } else if ("d".equals(name)) { if("#".equals(sign)){ return 3; } else if("b".equals(sign)){ return 1; } else { return 2; } } else if ("e".equals(name)) { if("#".equals(sign)){ return 5; } else if("b".equals(sign)){ return 3; } else { return 4; } } else if ("f".equals(name)) { if("#".equals(sign)){ return 6; } else if("b".equals(sign)){ return 4; } else { return 5; } } else if ("g".equals(name)) { if("#".equals(sign)){ return 8; } else if("b".equals(sign)){ return 6; } else { return 7; } } else if ("a".equals(name)) { if("#".equals(sign)){ return 10; } else if("b".equals(sign)){ return 8; } else { return 9; } } else if ("b".equals(name)) { if("#".equals(sign)){ return 12; } else if("b".equals(sign)){ return 10; } else { return 11; } } return -1; } @Override public String toString() { return name + "" + sign + "" + octave; } /* */ }
22.529954
61
0.36081
5f8d6bc8e9553e95c9afde88525d80bc65953c1c
522
package com.orientechnologies.common.factory; import java.util.LinkedHashMap; import java.util.Map; public class ODynamicFactory<K, V> { protected final Map<K, V> registry = new LinkedHashMap<K, V>(); public V get(final K iKey) { return registry.get(iKey); } public void register(final K iKey, final V iValue) { registry.put(iKey, iValue); } public void unregister(final K iKey) { registry.remove(iKey); } public void unregisterAll() { registry.clear(); } }
20.88
66
0.657088
627e7b07278c50c95a7a46188eb109031fcc3328
4,150
package com.toquery.framework.example.test.java.streamex; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.Lists; import io.github.toquery.framework.common.util.JacksonUtils; import one.util.streamex.EntryStream; import one.util.streamex.StreamEx; import org.junit.Before; import org.junit.Test; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; /** * @author toquery * @version 1 */ public class StreamExTest { //配置ObjectMapper对象 private static final ObjectMapper objectMapper = new ObjectMapper(); static { objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); objectMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true); objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true); objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true); objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true); } private List<User> users = Lists.newArrayList(); @Before public void test0() { User user1 = new User(); user1.setName("zhangsan"); Role role1 = new Role("admin"); user1.setRole(role1); users.add(user1); User user2 = new User(); user2.setName("李四"); Role role2 = new Role("edit"); user2.setRole(role2); users.add(user2); } @Test public void test1() { List<String> userNames = StreamEx.of(users) .map(User::getName) .toList(); System.out.println(JacksonUtils.object2String(userNames)); Map<Role, List<User>> role2users = StreamEx.of(users).groupingBy(User::getRole); System.out.println(JacksonUtils.object2String(role2users)); List usersAndRoles = Arrays.asList(new User(), new Role()); List<Role> roles = StreamEx.of(usersAndRoles) .select(Role.class) .toList(); System.out.println(JacksonUtils.object2String(roles)); List<String> appendedUsers = StreamEx.of(users) .map(User::getName) .prepend("(none)") .append("LAST") .toList(); System.out.println(JacksonUtils.object2String(appendedUsers)); for (String line : StreamEx.of(users).map(User::getName).nonNull()) { System.out.println(line); } } @Test public void mapOperations() throws JsonProcessingException { Map<String, Role> nameToRole = new HashMap<>(); nameToRole.put("first", new Role()); nameToRole.put("second", null); Set<String> nonNullRoles = StreamEx.ofKeys(nameToRole, Objects::nonNull) .toSet(); System.out.println(JacksonUtils.object2String(nonNullRoles)); Map<Role, List<User2>> role2users = new HashMap<>(); User2 root = new User2("root"); role2users.put(new Role("admin"), Lists.newArrayList(root)); role2users.put(new Role("edit"), Lists.newArrayList(root, new User2("zhangsan"))); Map<User2, List<Role>> users2roles = transformMap(role2users); //Json对象转为String字符串 System.out.println(objectMapper.writeValueAsString(users2roles)); System.out.println(JacksonUtils.object2String(users2roles)); Map<String, String> mapToString = EntryStream.of(users2roles) .mapKeys(String::valueOf) .mapValues(String::valueOf) .toMap(); System.out.println(JacksonUtils.object2String(mapToString)); } public Map<User2, List<Role>> transformMap(Map<Role, List<User2>> role2users) { Map<User2, List<Role>> users2roles = EntryStream.of(role2users) .flatMapValues(List::stream) .invert() .grouping(); return users2roles; } }
31.203008
90
0.651807
395b9b8126efbb8a01301d0c4bd481e4dd273774
854
package comp5216.sydney.edu.au.todolist; import com.orm.SugarRecord; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; public class ToDoItem extends SugarRecord implements Serializable { private String todo; private String date; static SimpleDateFormat dateFormatter = new SimpleDateFormat("dd/MM/yyyy hh:mm a", Locale.getDefault()); public ToDoItem() { } public ToDoItem(String ToDo, Date date) { this.todo = ToDo; this.date = dateFormatter.format(date); } public String getTodo() { return todo; } public String getDate() { return date; } public void setTodo(String todo) { this.todo = todo; } public void setDate(Date date) { this.date = dateFormatter.format(date); } }
20.333333
108
0.663934
07b60208b52852ea15ad921da9aa7bd716eb8953
4,346
/* * Copyright 2014 the RoboWorkshop Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.rwshop.nb.motion.dynamixel; import org.jflux.impl.services.rk.osgi.OSGiUtils; import org.jflux.impl.services.rk.osgi.SingleServiceListener; import org.mechio.api.motion.servos.ServoController; import org.netbeans.api.settings.ConvertAsProperties; import org.openide.awt.ActionID; import org.openide.awt.ActionReference; import org.openide.util.NbBundle; import org.openide.windows.TopComponent; import org.osgi.framework.BundleContext; /** * Top component which displays something. */ @ConvertAsProperties(dtd = "-//org.rwshop.nb.motion.dynamixel//DynamixelControlSettings//EN", autostore = false) @TopComponent.Description(preferredID = "DynamixelControlSettingsTopComponent", //iconBase="SET/PATH/TO/ICON/HERE", persistenceType = TopComponent.PERSISTENCE_ALWAYS) @TopComponent.Registration(mode = "rightSlidingSide", openAtStartup = false) @ActionID(category = "Window", id = "org.rwshop.nb.motion.dynamixel.DynamixelControlSettingsTopComponent") @ActionReference(path = "Menu/Window" /* * , position = 333 */) @TopComponent.OpenActionRegistration(displayName = "#CTL_DynamixelControlSettingsAction", preferredID = "DynamixelControlSettingsTopComponent") public final class DynamixelControlSettingsTopComponent extends TopComponent { private SingleServiceListener<ServoController> myServiceListener; public DynamixelControlSettingsTopComponent() { initComponents(); setName(NbBundle.getMessage(DynamixelControlSettingsTopComponent.class, "CTL_DynamixelControlSettingsTopComponent")); setToolTipText(NbBundle.getMessage(DynamixelControlSettingsTopComponent.class, "HINT_DynamixelControlSettingsTopComponent")); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { dynamixelControlLoopPanel1 = new org.rwshop.swing.motion.dynamixel.DynamixelControlLoopPanel(); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(dynamixelControlLoopPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 265, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(dynamixelControlLoopPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private org.rwshop.swing.motion.dynamixel.DynamixelControlLoopPanel dynamixelControlLoopPanel1; // End of variables declaration//GEN-END:variables @Override public void componentOpened() { if (myServiceListener != null) { return; } BundleContext context = OSGiUtils.getBundleContext(ServoController.class); if (context == null) { return; } dynamixelControlLoopPanel1.initialize(context); } @Override public void componentClosed() { // TODO add custom code on component closing } void writeProperties(java.util.Properties p) { // better to version settings since initial version as advocated at // http://wiki.apidesign.org/wiki/PropertyFiles p.setProperty("version", "1.0"); // TODO store your settings } void readProperties(java.util.Properties p) { String version = p.getProperty("version"); // TODO read your settings according to their version } }
39.87156
146
0.765992
c32a8428e8efcff761e9ead615ec01d1ab704aad
1,361
package com.example.spacenetdemo; import java.util.ArrayList; import android.content.Context; import com.example.spacenetdemo.abstractclass.ButtonBounds; import com.example.spacenetdemo.abstractclass.Screen; import com.example.spacenetdemo.common.Planets; import com.example.spacenetdemo.common.TouchEvent; import com.example.spacenetdemo.common.User; public class Constants { public static int S_W = 1; public static int S_H = 1; public static float SZ = 1; public static float WY = 1; public static Context ctx;// = null; public static ArrayList<TouchEvent> touchEventBuffer = new ArrayList<TouchEvent>(); public static ArrayList<TouchEvent> touchEvents = new ArrayList<TouchEvent>(); public static float positionJetOnTheScreenY = 1; public static float positionJetOnTheScreenX = 1; public static float angle = 0; public static float speed = 0; public static int animationFrame = 0; public static Screen screen = null; public static ArrayList<ButtonBounds> buttons = new ArrayList<ButtonBounds>(); public static void copyTouchEvents() { synchronized(touchEventBuffer) { touchEvents.clear(); touchEvents.addAll(touchEventBuffer); touchEventBuffer.clear(); } } public static Planets planets = new Planets(); public static User user;// = new User(); }
29.586957
84
0.735489
07a0e29ddf300a1b87c3e957f716dadfcdf25b8c
4,456
// Copyright (c) 2014 The Chromium Embedded Framework Authors. All rights // reserved. Use of this source code is governed by a BSD-style license that // can be found in the LICENSE file. package org.cef.network; import java.util.Vector; import org.cef.callback.CefCompletionCallback; import org.cef.callback.CefCookieVisitor; /** * Class used for managing cookies. The methods of this class may be called on * any thread unless otherwise indicated. */ public abstract class CefCookieManager { // This CTOR can't be called directly. Call method create() instead. CefCookieManager() { } /** * Returns the global cookie manager. By default data will be stored at * CefSettings.cache_path if specified or in memory otherwise. */ public static final CefCookieManager getGlobalManager() { return CefCookieManager_N.getGlobalManagerNative(); } /** * Creates a new cookie manager. If |path| is empty data will be stored in * memory only. Otherwise, data will be stored at the specified |path|. To * persist session cookies (cookies without an expiry date or validity * interval) set |persistSessionCookies| to true. Session cookies are * generally intended to be transient and most Web browsers do not persist * them. * * @return null if creation fails. */ public static final CefCookieManager createManager(String path, boolean persistSessionCookies) { return CefCookieManager_N.createNative(path, persistSessionCookies); } /** * Set the schemes supported by this manager. By default only "http" and * "https" schemes are supported. Must be called before any cookies are * accessed. */ public abstract void setSupportedSchemes(Vector<String> schemes); /** * Visit all cookies. The returned cookies are ordered by longest path, then * by earliest creation date. Returns false if cookies cannot be accessed. */ public abstract boolean visitAllCookies(CefCookieVisitor visitor); /** * Visit a subset of cookies. The results are filtered by the given url * scheme, host, domain and path. If |includeHttpOnly| is true HTTP-only * cookies will also be included in the results. The returned cookies are * ordered by longest path, then by earliest creation date. Returns false if * cookies cannot be accessed. */ public abstract boolean visitUrlCookies(String url, boolean includeHttpOnly, CefCookieVisitor visitor); /** * Sets a cookie given a valid URL and explicit user-provided cookie * attributes. This function expects each attribute to be well-formed. It will * check for disallowed characters (e.g. the ';' character is disallowed * within the cookie value attribute). This method will be called on the * IO thread. If posting the task was successful the method returns true. */ public abstract boolean setCookie(String url, CefCookie cookie); /** * Delete all cookies that match the specified parameters. If both |url| and * values |cookieName| are specified all host and domain cookies matching * both will be deleted. If only |url| is specified all host cookies (but not * domain cookies) irrespective of path will be deleted. If |url| is empty all * cookies for all hosts and domains will be deleted. This method will be * called on the IO thread. If posting the task was successful the method * returns true. */ public abstract boolean deleteCookies(String url, String cookieName); /** * Sets the directory path that will be used for storing cookie data. If * |path| is empty data will be stored in memory only. Otherwise, data will be * stored at the specified |path|. To persist session cookies (cookies without * an expiry date or validity interval) set |persistSessionCookies| to true. * Session cookies are generally intended to be transient and most Web browsers * do not persist them. Returns false if cookies cannot be accessed. */ public abstract boolean setStoragePath(String path, boolean persistSessionCookies); /** * Flush the backing store (if any) to disk and execute the specified * |handler| on the IO thread when done. Returns false if cookies cannot be * accessed. */ public abstract boolean flushStore(CefCompletionCallback handler); }
41.64486
85
0.710054
d216cb2147b5475894b49613a7d514fe9bb78356
1,332
package solution; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; public class Knight implements ChessPiece { private ChessPosition pos; public Knight(ChessPosition pos) { this.pos = pos; } @Override public ChessPosition getPosition() { return pos; } @Override public void setPosition(ChessPosition position) { pos = position; } @Override public List<ChessPosition> allowedMoves() { List<ChessPosition> result = new ArrayList<>(); result.add(new ChessPosition((char) (pos.x - 1), pos.y - 2)); result.add(new ChessPosition((char) (pos.x + 1), pos.y - 2)); result.add(new ChessPosition((char) (pos.x + 2), pos.y - 1)); result.add(new ChessPosition((char) (pos.x + 2), pos.y + 1)); result.add(new ChessPosition((char) (pos.x + 1), pos.y + 2)); result.add(new ChessPosition((char) (pos.x - 1), pos.y + 2)); result.add(new ChessPosition((char) (pos.x - 2), pos.y - 1)); result.add(new ChessPosition((char) (pos.x - 2), pos.y + 1)); return result.stream().filter(ChessPosition::isValid).collect(Collectors.toList()); } @Override public boolean captures(ChessPosition pos) { return allowedMoves().contains(pos); } }
27.75
91
0.617868
c22bc4fa5f6abc91344c74c22b1ffa103686fbc5
838
// Runtime: 0 ms, faster than 100.00% of Java online submissions for Reverse Linked List. // Memory Usage: 38.7 MB, less than 64.30% of Java online submissions for Reverse Linked List. /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode reverseList(ListNode head) { if (head == null) { return head; } ListNode curr = head; while (curr.next != null) { ListNode tmp = curr.next.next; curr.next.next = head; head = curr.next; curr.next = tmp; } return head; } }
24.647059
94
0.548926
d809cd83931ddd3d6a889fda91b441e9dcddfb14
4,017
// // Este archivo ha sido generado por la arquitectura JavaTM para la implantación de la referencia de enlace (JAXB) XML v2.2.11 // Visite <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Todas las modificaciones realizadas en este archivo se perderán si se vuelve a compilar el esquema de origen. // Generado el: 2018.04.15 a las 06:28:31 PM CEST // package vrmsConnectionServices.wsdl; import java.math.BigInteger; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; /** * <p>Clase Java para GoogleMaps complex type. * * <p>El siguiente fragmento de esquema especifica el contenido que se espera que haya en esta clase. * * <pre> * &lt;complexType name="GoogleMaps"&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="Latitude" type="{http://www.w3.org/2001/XMLSchema}string"/&gt; * &lt;element name="Longitude" type="{http://www.w3.org/2001/XMLSchema}string"/&gt; * &lt;element name="MaxZoom" type="{http://www.w3.org/2001/XMLSchema}nonNegativeInteger" minOccurs="0"/&gt; * &lt;element name="Zoom" type="{http://www.w3.org/2001/XMLSchema}nonNegativeInteger" minOccurs="0"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "GoogleMaps", propOrder = { "latitude", "longitude", "maxZoom", "zoom" }) public class GoogleMaps { @XmlElement(name = "Latitude", required = true) protected String latitude; @XmlElement(name = "Longitude", required = true) protected String longitude; @XmlElement(name = "MaxZoom") @XmlSchemaType(name = "nonNegativeInteger") protected BigInteger maxZoom; @XmlElement(name = "Zoom") @XmlSchemaType(name = "nonNegativeInteger") protected BigInteger zoom; /** * Obtiene el valor de la propiedad latitude. * * @return * possible object is * {@link String } * */ public String getLatitude() { return latitude; } /** * Define el valor de la propiedad latitude. * * @param value * allowed object is * {@link String } * */ public void setLatitude(String value) { this.latitude = value; } /** * Obtiene el valor de la propiedad longitude. * * @return * possible object is * {@link String } * */ public String getLongitude() { return longitude; } /** * Define el valor de la propiedad longitude. * * @param value * allowed object is * {@link String } * */ public void setLongitude(String value) { this.longitude = value; } /** * Obtiene el valor de la propiedad maxZoom. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getMaxZoom() { return maxZoom; } /** * Define el valor de la propiedad maxZoom. * * @param value * allowed object is * {@link BigInteger } * */ public void setMaxZoom(BigInteger value) { this.maxZoom = value; } /** * Obtiene el valor de la propiedad zoom. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getZoom() { return zoom; } /** * Define el valor de la propiedad zoom. * * @param value * allowed object is * {@link BigInteger } * */ public void setZoom(BigInteger value) { this.zoom = value; } }
25.424051
127
0.592233
301614a29b9f97ab8a2ab00ec11ac07ae5fcd479
1,461
package com.android.hikepeaks.Fragments; import android.app.Activity; import android.content.Context; import android.support.v4.app.Fragment; import com.android.hikepeaks.Utilities.Connectivity; public class BaseFragment extends Fragment { protected Activity mActivity; protected OnFragmentInteractionListener mListener; public BaseFragment() { // Required empty public constructor } @Override public void onHiddenChanged(boolean hidden) { super.onHiddenChanged(hidden); if (!this.isHidden()) { onVisible(); } else { onHidden(); } } public boolean isNetworkAvailable() { return Connectivity.isNetworkOnline(getContext()); } public void onVisible() { } public void onHidden() { } @Override public void onAttach(Activity activity) { super.onAttach(activity); mActivity = activity; } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof OnFragmentInteractionListener) { mListener = (OnFragmentInteractionListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mActivity = null; mListener = null; } }
22.136364
71
0.633128
d2b2223f7ed9d0e64dea7a10f8b4a1fb90fd639b
1,952
package main; import command.Command; import command.commands.admin.*; import command.commands.bang.Bang; import command.commands.bang.BangScore; import command.commands.blackjack.Bet; import command.commands.blackjack.Hit; import command.commands.blackjack.MyHand; import command.commands.blackjack.Stand; import command.commands.economy.Buy; import command.commands.Help; import command.commands.economy.Gift; import command.commands.economy.Market; import command.commands.misc.*; import command.commands.bang.Daily; import java.util.ArrayList; /** * Container class for a list of all the commands * available in the server. */ public final class CommandList { private static ArrayList<Command> commands; private CommandList() { } static { commands = new ArrayList<>(); addAllCommands(); } /** * Commands list getter. * * @return the ArrayList of all commands */ public static ArrayList<Command> getCommands() { return commands; } /** * Populates the commands list with every command. */ private static void addAllCommands() { // Admin commands commands.add(new Echo()); commands.add(new Notify()); commands.add(new Purge()); commands.add(new ResetChannels()); //commands.add(new DeleteCourseChannels()); // Everyone commands commands.add(new Bang()); commands.add(new BangScore()); commands.add(new Bet()); commands.add(new Buy()); commands.add(new Daily()); commands.add(new Flip()); commands.add(new Gift()); commands.add(new Help()); commands.add(new Hit()); commands.add(new Id()); commands.add(new Info()); commands.add(new Market()); commands.add(new MyHand()); commands.add(new Ping()); commands.add(new Profile()); commands.add(new Stand()); } }
26.026667
54
0.642418
b53c29fa90ffcf36b98d04307bc95d16db9b3442
9,829
// Generated from /home/elyan/Documents/KLinguaMachina/src/main/antlr/org/linguamachina/klinguamachina/parser/antlr/LinguaMachina.g4 by ANTLR 4.9.1 package org.linguamachina.klinguamachina.parser.antlr; import org.antlr.v4.runtime.Lexer; import org.antlr.v4.runtime.CharStream; import org.antlr.v4.runtime.Token; import org.antlr.v4.runtime.TokenStream; import org.antlr.v4.runtime.*; import org.antlr.v4.runtime.atn.*; import org.antlr.v4.runtime.dfa.DFA; import org.antlr.v4.runtime.misc.*; @SuppressWarnings({"all", "warnings", "unchecked", "unused", "cast"}) public class LinguaMachinaLexer extends Lexer { static { RuntimeMetaData.checkVersion("4.9.1", RuntimeMetaData.VERSION); } protected static final DFA[] _decisionToDFA; protected static final PredictionContextCache _sharedContextCache = new PredictionContextCache(); public static final int T__0=1, T__1=2, T__2=3, T__3=4, T__4=5, T__5=6, T__6=7, T__7=8, T__8=9, T__9=10, T__10=11, T__11=12, T__12=13, T__13=14, T__14=15, T__15=16, T__16=17, T__17=18, T__18=19, T__19=20, T__20=21, T__21=22, WS=23, COMMENT=24, IntegerLiteral=25, DoubleLiteral=26, StringLiteral=27, CharLiteral=28, SymbolLiteral=29, Identifier=30, LowerOrEq=31, GreaterOrEq=32, Lower=33, Greater=34, Equal=35, NotEqual=36, Plus=37, Minus=38; public static String[] channelNames = { "DEFAULT_TOKEN_CHANNEL", "HIDDEN" }; public static String[] modeNames = { "DEFAULT_MODE" }; private static String[] makeRuleNames() { return new String[] { "T__0", "T__1", "T__2", "T__3", "T__4", "T__5", "T__6", "T__7", "T__8", "T__9", "T__10", "T__11", "T__12", "T__13", "T__14", "T__15", "T__16", "T__17", "T__18", "T__19", "T__20", "T__21", "WS", "COMMENT", "Digit", "Ident", "IntegerLiteral", "DoubleLiteral", "StringLiteral", "CharLiteral", "SymbolLiteral", "Identifier", "LowerOrEq", "GreaterOrEq", "Lower", "Greater", "Equal", "NotEqual", "Plus", "Minus" }; } public static final String[] ruleNames = makeRuleNames(); private static String[] makeLiteralNames() { return new String[] { null, "'['", "','", "']'", "'{'", "'|'", "'}'", "'||'", "'&&'", "'*'", "'/'", "'%'", "'('", "')'", "'!'", "':'", "'|>'", "':='", "'='", "'>>'", "'::'", "'^'", "';'", null, null, null, null, null, null, null, null, "'<='", "'>='", "'<'", "'>'", "'=='", "'!='", "'+'", "'-'" }; } private static final String[] _LITERAL_NAMES = makeLiteralNames(); private static String[] makeSymbolicNames() { return new String[] { null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, "WS", "COMMENT", "IntegerLiteral", "DoubleLiteral", "StringLiteral", "CharLiteral", "SymbolLiteral", "Identifier", "LowerOrEq", "GreaterOrEq", "Lower", "Greater", "Equal", "NotEqual", "Plus", "Minus" }; } private static final String[] _SYMBOLIC_NAMES = makeSymbolicNames(); public static final Vocabulary VOCABULARY = new VocabularyImpl(_LITERAL_NAMES, _SYMBOLIC_NAMES); /** * @deprecated Use {@link #VOCABULARY} instead. */ @Deprecated public static final String[] tokenNames; static { tokenNames = new String[_SYMBOLIC_NAMES.length]; for (int i = 0; i < tokenNames.length; i++) { tokenNames[i] = VOCABULARY.getLiteralName(i); if (tokenNames[i] == null) { tokenNames[i] = VOCABULARY.getSymbolicName(i); } if (tokenNames[i] == null) { tokenNames[i] = "<INVALID>"; } } } @Override @Deprecated public String[] getTokenNames() { return tokenNames; } @Override public Vocabulary getVocabulary() { return VOCABULARY; } public LinguaMachinaLexer(CharStream input) { super(input); _interp = new LexerATNSimulator(this,_ATN,_decisionToDFA,_sharedContextCache); } @Override public String getGrammarFileName() { return "LinguaMachina.g4"; } @Override public String[] getRuleNames() { return ruleNames; } @Override public String getSerializedATN() { return _serializedATN; } @Override public String[] getChannelNames() { return channelNames; } @Override public String[] getModeNames() { return modeNames; } @Override public ATN getATN() { return _ATN; } public static final String _serializedATN = "\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2(\u00df\b\1\4\2\t"+ "\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t\7\4\b\t\b\4\t\t\t\4\n\t\n\4\13"+ "\t\13\4\f\t\f\4\r\t\r\4\16\t\16\4\17\t\17\4\20\t\20\4\21\t\21\4\22\t\22"+ "\4\23\t\23\4\24\t\24\4\25\t\25\4\26\t\26\4\27\t\27\4\30\t\30\4\31\t\31"+ "\4\32\t\32\4\33\t\33\4\34\t\34\4\35\t\35\4\36\t\36\4\37\t\37\4 \t \4!"+ "\t!\4\"\t\"\4#\t#\4$\t$\4%\t%\4&\t&\4\'\t\'\4(\t(\4)\t)\3\2\3\2\3\3\3"+ "\3\3\4\3\4\3\5\3\5\3\6\3\6\3\7\3\7\3\b\3\b\3\b\3\t\3\t\3\t\3\n\3\n\3\13"+ "\3\13\3\f\3\f\3\r\3\r\3\16\3\16\3\17\3\17\3\20\3\20\3\21\3\21\3\21\3\22"+ "\3\22\3\22\3\23\3\23\3\24\3\24\3\24\3\25\3\25\3\25\3\26\3\26\3\27\3\27"+ "\3\30\6\30\u0087\n\30\r\30\16\30\u0088\3\30\3\30\3\31\3\31\7\31\u008f"+ "\n\31\f\31\16\31\u0092\13\31\3\31\3\31\3\31\3\31\3\32\3\32\3\33\3\33\7"+ "\33\u009c\n\33\f\33\16\33\u009f\13\33\3\34\6\34\u00a2\n\34\r\34\16\34"+ "\u00a3\3\35\3\35\3\35\3\35\3\35\3\35\3\35\3\35\3\35\3\35\3\35\3\35\3\35"+ "\3\35\5\35\u00b4\n\35\3\36\3\36\3\36\3\36\7\36\u00ba\n\36\f\36\16\36\u00bd"+ "\13\36\3\36\3\36\3\37\3\37\3\37\3 \3 \6 \u00c6\n \r \16 \u00c7\3!\3!\3"+ "\"\3\"\3\"\3#\3#\3#\3$\3$\3%\3%\3&\3&\3&\3\'\3\'\3\'\3(\3(\3)\3)\2\2*"+ "\3\3\5\4\7\5\t\6\13\7\r\b\17\t\21\n\23\13\25\f\27\r\31\16\33\17\35\20"+ "\37\21!\22#\23%\24\'\25)\26+\27-\30/\31\61\32\63\2\65\2\67\339\34;\35"+ "=\36?\37A C!E\"G#I$K%M&O\'Q(\3\2\t\5\2\13\f\17\17\"\"\3\2%%\3\2\62;\5"+ "\2C\\aac|\6\2\62;C\\aac|\3\2$$\7\2&&\60<C\\aac|\2\u00e5\2\3\3\2\2\2\2"+ "\5\3\2\2\2\2\7\3\2\2\2\2\t\3\2\2\2\2\13\3\2\2\2\2\r\3\2\2\2\2\17\3\2\2"+ "\2\2\21\3\2\2\2\2\23\3\2\2\2\2\25\3\2\2\2\2\27\3\2\2\2\2\31\3\2\2\2\2"+ "\33\3\2\2\2\2\35\3\2\2\2\2\37\3\2\2\2\2!\3\2\2\2\2#\3\2\2\2\2%\3\2\2\2"+ "\2\'\3\2\2\2\2)\3\2\2\2\2+\3\2\2\2\2-\3\2\2\2\2/\3\2\2\2\2\61\3\2\2\2"+ "\2\67\3\2\2\2\29\3\2\2\2\2;\3\2\2\2\2=\3\2\2\2\2?\3\2\2\2\2A\3\2\2\2\2"+ "C\3\2\2\2\2E\3\2\2\2\2G\3\2\2\2\2I\3\2\2\2\2K\3\2\2\2\2M\3\2\2\2\2O\3"+ "\2\2\2\2Q\3\2\2\2\3S\3\2\2\2\5U\3\2\2\2\7W\3\2\2\2\tY\3\2\2\2\13[\3\2"+ "\2\2\r]\3\2\2\2\17_\3\2\2\2\21b\3\2\2\2\23e\3\2\2\2\25g\3\2\2\2\27i\3"+ "\2\2\2\31k\3\2\2\2\33m\3\2\2\2\35o\3\2\2\2\37q\3\2\2\2!s\3\2\2\2#v\3\2"+ "\2\2%y\3\2\2\2\'{\3\2\2\2)~\3\2\2\2+\u0081\3\2\2\2-\u0083\3\2\2\2/\u0086"+ "\3\2\2\2\61\u008c\3\2\2\2\63\u0097\3\2\2\2\65\u0099\3\2\2\2\67\u00a1\3"+ "\2\2\29\u00b3\3\2\2\2;\u00b5\3\2\2\2=\u00c0\3\2\2\2?\u00c3\3\2\2\2A\u00c9"+ "\3\2\2\2C\u00cb\3\2\2\2E\u00ce\3\2\2\2G\u00d1\3\2\2\2I\u00d3\3\2\2\2K"+ "\u00d5\3\2\2\2M\u00d8\3\2\2\2O\u00db\3\2\2\2Q\u00dd\3\2\2\2ST\7]\2\2T"+ "\4\3\2\2\2UV\7.\2\2V\6\3\2\2\2WX\7_\2\2X\b\3\2\2\2YZ\7}\2\2Z\n\3\2\2\2"+ "[\\\7~\2\2\\\f\3\2\2\2]^\7\177\2\2^\16\3\2\2\2_`\7~\2\2`a\7~\2\2a\20\3"+ "\2\2\2bc\7(\2\2cd\7(\2\2d\22\3\2\2\2ef\7,\2\2f\24\3\2\2\2gh\7\61\2\2h"+ "\26\3\2\2\2ij\7\'\2\2j\30\3\2\2\2kl\7*\2\2l\32\3\2\2\2mn\7+\2\2n\34\3"+ "\2\2\2op\7#\2\2p\36\3\2\2\2qr\7<\2\2r \3\2\2\2st\7~\2\2tu\7@\2\2u\"\3"+ "\2\2\2vw\7<\2\2wx\7?\2\2x$\3\2\2\2yz\7?\2\2z&\3\2\2\2{|\7@\2\2|}\7@\2"+ "\2}(\3\2\2\2~\177\7<\2\2\177\u0080\7<\2\2\u0080*\3\2\2\2\u0081\u0082\7"+ "`\2\2\u0082,\3\2\2\2\u0083\u0084\7=\2\2\u0084.\3\2\2\2\u0085\u0087\t\2"+ "\2\2\u0086\u0085\3\2\2\2\u0087\u0088\3\2\2\2\u0088\u0086\3\2\2\2\u0088"+ "\u0089\3\2\2\2\u0089\u008a\3\2\2\2\u008a\u008b\b\30\2\2\u008b\60\3\2\2"+ "\2\u008c\u0090\7%\2\2\u008d\u008f\n\3\2\2\u008e\u008d\3\2\2\2\u008f\u0092"+ "\3\2\2\2\u0090\u008e\3\2\2\2\u0090\u0091\3\2\2\2\u0091\u0093\3\2\2\2\u0092"+ "\u0090\3\2\2\2\u0093\u0094\7%\2\2\u0094\u0095\3\2\2\2\u0095\u0096\b\31"+ "\2\2\u0096\62\3\2\2\2\u0097\u0098\t\4\2\2\u0098\64\3\2\2\2\u0099\u009d"+ "\t\5\2\2\u009a\u009c\t\6\2\2\u009b\u009a\3\2\2\2\u009c\u009f\3\2\2\2\u009d"+ "\u009b\3\2\2\2\u009d\u009e\3\2\2\2\u009e\66\3\2\2\2\u009f\u009d\3\2\2"+ "\2\u00a0\u00a2\5\63\32\2\u00a1\u00a0\3\2\2\2\u00a2\u00a3\3\2\2\2\u00a3"+ "\u00a1\3\2\2\2\u00a3\u00a4\3\2\2\2\u00a48\3\2\2\2\u00a5\u00a6\5\67\34"+ "\2\u00a6\u00a7\7\60\2\2\u00a7\u00a8\5\67\34\2\u00a8\u00a9\7g\2\2\u00a9"+ "\u00aa\5\67\34\2\u00aa\u00b4\3\2\2\2\u00ab\u00ac\5\67\34\2\u00ac\u00ad"+ "\7\60\2\2\u00ad\u00ae\5\67\34\2\u00ae\u00b4\3\2\2\2\u00af\u00b0\5\67\34"+ "\2\u00b0\u00b1\7g\2\2\u00b1\u00b2\5\67\34\2\u00b2\u00b4\3\2\2\2\u00b3"+ "\u00a5\3\2\2\2\u00b3\u00ab\3\2\2\2\u00b3\u00af\3\2\2\2\u00b4:\3\2\2\2"+ "\u00b5\u00bb\7$\2\2\u00b6\u00b7\7^\2\2\u00b7\u00ba\13\2\2\2\u00b8\u00ba"+ "\n\7\2\2\u00b9\u00b6\3\2\2\2\u00b9\u00b8\3\2\2\2\u00ba\u00bd\3\2\2\2\u00bb"+ "\u00b9\3\2\2\2\u00bb\u00bc\3\2\2\2\u00bc\u00be\3\2\2\2\u00bd\u00bb\3\2"+ "\2\2\u00be\u00bf\7$\2\2\u00bf<\3\2\2\2\u00c0\u00c1\7&\2\2\u00c1\u00c2"+ "\n\2\2\2\u00c2>\3\2\2\2\u00c3\u00c5\7)\2\2\u00c4\u00c6\t\b\2\2\u00c5\u00c4"+ "\3\2\2\2\u00c6\u00c7\3\2\2\2\u00c7\u00c5\3\2\2\2\u00c7\u00c8\3\2\2\2\u00c8"+ "@\3\2\2\2\u00c9\u00ca\5\65\33\2\u00caB\3\2\2\2\u00cb\u00cc\7>\2\2\u00cc"+ "\u00cd\7?\2\2\u00cdD\3\2\2\2\u00ce\u00cf\7@\2\2\u00cf\u00d0\7?\2\2\u00d0"+ "F\3\2\2\2\u00d1\u00d2\7>\2\2\u00d2H\3\2\2\2\u00d3\u00d4\7@\2\2\u00d4J"+ "\3\2\2\2\u00d5\u00d6\7?\2\2\u00d6\u00d7\7?\2\2\u00d7L\3\2\2\2\u00d8\u00d9"+ "\7#\2\2\u00d9\u00da\7?\2\2\u00daN\3\2\2\2\u00db\u00dc\7-\2\2\u00dcP\3"+ "\2\2\2\u00dd\u00de\7/\2\2\u00deR\3\2\2\2\13\2\u0088\u0090\u009d\u00a3"+ "\u00b3\u00b9\u00bb\u00c7\3\2\3\2"; public static final ATN _ATN = new ATNDeserializer().deserialize(_serializedATN.toCharArray()); static { _decisionToDFA = new DFA[_ATN.getNumberOfDecisions()]; for (int i = 0; i < _ATN.getNumberOfDecisions(); i++) { _decisionToDFA[i] = new DFA(_ATN.getDecisionState(i), i); } } }
48.900498
147
0.612779
547e25378718eee54a8365bd244cc61748840d03
2,595
package cc.mrbird.febs.server.member.controller.app.vo; import com.baomidou.mybatisplus.annotation.TableField; import lombok.Data; import javax.validation.constraints.*; import java.io.Serializable; import java.util.Date; @Data public class MemberVo implements Serializable { private static final long serialVersionUID = 108450005959091728L; /** * 昵称 */ @TableField("nickname") @NotBlank(message = "{required}") @Size(max = 20, message = "{noMoreThan}") private String nickname; /** * 姓名 */ @TableField("name") @NotBlank(message = "{required}") @Size(max = 20, message = "{noMoreThan}") private String name; /** * 性别 设定后禁止修改0-女,1-男,2-保密 */ @TableField("sex") private Boolean sex; /** * 身份证号 */ @TableField("idcard") @NotBlank(message = "{required}") @Size(min = 18, message = "{noMinThan}") @Size(max = 18, message = "{noMoreThan}") private String idcard; /** * 身份证正面照片 */ @TableField("frontcardPhoto") @NotBlank(message = "{required}") @Size(max = 255, message = "{noMoreThan}") private String frontcardphoto; /** * 身高(厘米) */ @TableField("height") @Min(value = 50,message = "{noMinThan}") @Max(value = 300,message = "{noMaxThan}") private Integer height; /** * 体重(KG) */ @TableField("weight") @Min(value = 30,message = "{noMinThan}") @Max(value = 600,message = "{noMaxThan}") private Integer weight; /** * 籍贯 */ @TableField("nativeplace") @NotBlank(message = "{required}") @Size(max = 150, message = "{noMoreThan}") private String nativeplace; /** * 工作城市 */ @TableField("workcity") @NotBlank(message = "{required}") @Size(max = 20, message = "{noMoreThan}") private String workcity; /** * 是否停用,0-停用,1-未停用 */ @TableField("status") private Boolean status; /** * 是否审核通过,0-未通过,1-通过,2-待审核 */ @TableField("isverify") private Integer isverify; /** * 是否离异,0-未婚,1-离异 */ @TableField("isdivorce") @NotNull private Boolean isdivorce; /** * 是否有孩子,0-没有,1-有 */ @TableField("haschildern") @NotNull private Boolean haschildern; /** * 是否有房,0-无,1-有 */ @TableField("hasroom") @NotNull private Boolean hasroom; /** * 是否有车,0-无,1-有 */ @TableField("hascar") @NotNull private Boolean hascar; /** * 会员注册时间 */ @TableField("createtime") private Date createtime; }
19.961538
69
0.569171
73c5d6492788b9020481a1445103e02efdf8fa7f
1,403
package com.immomo.wink.patch; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.nio.channels.FileChannel; public class Utils { public static boolean copyFile(File src, String destPath) { boolean result = false; if ((src == null) || (destPath== null)) { return result; } File dest= new File(destPath); if (dest!= null && dest.exists()) { dest.delete(); // delete file } try { dest.createNewFile(); } catch (IOException e) { e.printStackTrace(); } FileChannel srcChannel = null; FileChannel dstChannel = null; try { srcChannel = new FileInputStream(src).getChannel(); dstChannel = new FileOutputStream(dest).getChannel(); srcChannel.transferTo(0, srcChannel.size(), dstChannel); result = true; } catch (FileNotFoundException e) { e.printStackTrace(); return result; } catch (IOException e) { e.printStackTrace(); return result; } try { srcChannel.close(); dstChannel.close(); } catch (IOException e) { e.printStackTrace(); } return result; } }
26.980769
68
0.559515
116d3a28657b11007a98a0afebca45d9b4580769
468
package com.linkedpipes.plugin.transformer.rdfToHdt; public final class RdfToHdtVocabulary { private static final String PREFIX = "http://plugins.linkedpipes.com/ontology/t-rdfToHdt#"; public static final String CONFIG = PREFIX + "Configuration"; public static final String HAS_FILE_NAME = PREFIX + "fileName"; public static final String HAS_BASE_IRI = PREFIX + "baseIri"; private RdfToHdtVocabulary() { } }
26
69
0.690171
22aa027ad675e00d8fe6314f092b966225367454
1,232
package seedu.project.logic.commands; import static java.util.Objects.requireNonNull; import seedu.project.commons.core.Messages; import seedu.project.logic.CommandHistory; import seedu.project.logic.LogicManager; import seedu.project.model.Model; /** * Clears the project. */ public class ClearCommand extends Command { public static final String COMMAND_WORD = "clear"; public static final String COMMAND_ALIAS = "cl"; public static final String MESSAGE_SUCCESS = "Project has been cleared!"; @Override public CommandResult execute(Model model, CommandHistory history) { requireNonNull(model); if (LogicManager.getState()) { /*Project clearedProject = new Project(); clearedProject.setName(model.getProject().getName().toString()); clearedProject.setTasks(new ArrayList<>()); model.setProject(model.getSelectedProject(), clearedProject);*/ model.clearTasks(); model.commitProject(); model.commitProjectList(); return new CommandResult(MESSAGE_SUCCESS); } else { return new CommandResult(String.format(Messages.MESSAGE_GO_TO_TASK_LEVEL, COMMAND_WORD)); } } }
33.297297
101
0.688312
4ad9be446d575c9a674d6ee47f120f964374dcac
2,513
package com.demo.test.exceptions; import com.college.etut.model.response.ExceptionResponse; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import java.time.LocalDateTime; @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(ResourceNotFoundException.class) public ResponseEntity<ExceptionResponse> resourceNotFound(ResourceNotFoundException ex) { ExceptionResponse response = new ExceptionResponse(); response.setErrorCode(HttpStatus.NOT_FOUND.value()); response.setErrorMessage(ex.getMessage()); response.setErrorReason(HttpStatus.NOT_FOUND.getReasonPhrase()); response.setErrorCreateTime(LocalDateTime.now()); return new ResponseEntity<>(response, HttpStatus.NOT_FOUND); } @ExceptionHandler(ResourceAlreadyExists.class) public ResponseEntity<ExceptionResponse> resourceAlreadyExists(ResourceAlreadyExists ex) { ExceptionResponse response = new ExceptionResponse(); response.setErrorCode(HttpStatus.CONFLICT.value()); response.setErrorMessage(ex.getMessage()); response.setErrorReason(HttpStatus.CONFLICT.getReasonPhrase()); response.setErrorCreateTime(LocalDateTime.now()); return new ResponseEntity<>(response, HttpStatus.CONFLICT); } @ExceptionHandler(CustomException.class) public ResponseEntity<ExceptionResponse> customException(CustomException ex) { ExceptionResponse response = new ExceptionResponse(); response.setErrorCode(HttpStatus.BAD_REQUEST.value()); response.setErrorMessage(ex.getMessage()); response.setErrorReason(HttpStatus.BAD_REQUEST.getReasonPhrase()); response.setErrorCreateTime(LocalDateTime.now()); return new ResponseEntity<>(response, HttpStatus.BAD_REQUEST); } @ExceptionHandler(UnauthorizedException.class) public ResponseEntity<ExceptionResponse> unauthorizedException(UnauthorizedException ex) { ExceptionResponse response = new ExceptionResponse(); response.setErrorCode(HttpStatus.UNAUTHORIZED.value()); response.setErrorMessage(ex.getMessage()); response.setErrorReason(HttpStatus.UNAUTHORIZED.getReasonPhrase()); response.setErrorCreateTime(LocalDateTime.now()); return new ResponseEntity<>(response, HttpStatus.UNAUTHORIZED); } }
45.690909
94
0.766017
5a742ed86173887348f0248341c81349dd17d8d2
1,090
package net.folivo.springframework.security.abac.demo.config; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { public static final String ROLE_ADMIN = "ADMIN"; public static final String ROLE_NORMAL = "NORMAL"; @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable(); http.authorizeRequests().anyRequest().permitAll(); http.httpBasic(); } @Override public void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().// withUser("admin").password("{noop}password").roles(ROLE_ADMIN).and().// withUser("normal").password("{noop}password").roles(ROLE_NORMAL); } }
38.928571
107
0.810092
43003efc1c6cc63fa31b9abefe4be95c14e5ee61
234
package com.dao; import com.pojo.User; import com.baomidou.mybatisplus.core.mapper.BaseMapper; /** * <p> * Mapper 接口 * </p> * * @author linqin * @since 2019-04-22 */ public interface UserMapper extends BaseMapper<User> { }
13.764706
55
0.679487
f67389ad5a3e026a1ad050e615155ed01d0e45a5
12,748
package mx.emite.sdk; import lombok.Getter; import lombok.Setter; import mx.emite.sdk.clientes.ClienteJson; import mx.emite.sdk.clientes.operaciones.emisores.DescargaMasiva; import mx.emite.sdk.clientes.operaciones.emisores.Estatus; import mx.emite.sdk.clientes.operaciones.emisores.Servicios; import mx.emite.sdk.clientes.operaciones.emisores.cfdi32.Cfdi32Cancelador; import mx.emite.sdk.clientes.operaciones.emisores.cfdi32.Cfdi32Correo; import mx.emite.sdk.clientes.operaciones.emisores.cfdi32.Cfdi32DescargaAcuseXml; import mx.emite.sdk.clientes.operaciones.emisores.cfdi32.Cfdi32DescargaXml; import mx.emite.sdk.clientes.operaciones.emisores.cfdi32.Cfdi32Pdf; import mx.emite.sdk.clientes.operaciones.emisores.cfdi32.Cfdi32PdfAcuse; import mx.emite.sdk.clientes.operaciones.emisores.cfdi32.Cfdi32SelladorYTimbrador; import mx.emite.sdk.clientes.operaciones.emisores.cfdi32.Cfdi32SelladorYTimbradorGenericoTxt; import mx.emite.sdk.clientes.operaciones.emisores.cfdi32.Cfdi32SelladorYTimbradorGenericoXml; import mx.emite.sdk.clientes.operaciones.emisores.cfdi32.Cfdi32Timbrador; import mx.emite.sdk.clientes.operaciones.emisores.nom32.Nom32Cancelador; import mx.emite.sdk.clientes.operaciones.emisores.nom32.Nom32Correo; import mx.emite.sdk.clientes.operaciones.emisores.nom32.Nom32DescargaAcuseXml; import mx.emite.sdk.clientes.operaciones.emisores.nom32.Nom32DescargaXml; import mx.emite.sdk.clientes.operaciones.emisores.nom32.Nom32Pdf; import mx.emite.sdk.clientes.operaciones.emisores.nom32.Nom32PdfAcuse; import mx.emite.sdk.clientes.operaciones.emisores.nom32.Nom32SelladorYTimbrador; import mx.emite.sdk.clientes.operaciones.emisores.nom32.Nom32SelladorYTimbradorGenericoTxt; import mx.emite.sdk.clientes.operaciones.emisores.nom32.Nom32SelladorYTimbradorGenericoXml; import mx.emite.sdk.clientes.operaciones.emisores.nom32.Nom32Timbrador; import mx.emite.sdk.clientes.operaciones.emisores.ret10.Ret10Cancelador; import mx.emite.sdk.clientes.operaciones.emisores.ret10.Ret10Correo; import mx.emite.sdk.clientes.operaciones.emisores.ret10.Ret10DescargaXml; import mx.emite.sdk.clientes.operaciones.emisores.ret10.Ret10Pdf; import mx.emite.sdk.clientes.operaciones.emisores.ret10.Ret10SelladorYTimbrador; import mx.emite.sdk.clientes.operaciones.emisores.ret10.Ret10Timbrador; import mx.emite.sdk.clientes.operaciones.emisores.valida32.Valida32Validador; import mx.emite.sdk.enums.Ambiente; /** * @author enrique * * EmiteAPI es la clase principal de consumo de emisores * * */ public class EmiteAPI { private final ClienteJson cliente; private final Servicios servicios; private final DescargaMasiva descargamasiva; private final Valida32Validador valida32_validador; private final Estatus estatus; private final Cfdi32Timbrador cfdi32_timbrador; private final Cfdi32SelladorYTimbrador cfdi32_selladorytimbrador; private final Cfdi32SelladorYTimbradorGenericoXml cfdi32_selladorytimbradorgenericoxml; private final Cfdi32SelladorYTimbradorGenericoTxt cfdi32_selladorytimbradorgenericotxt; private final Cfdi32Cancelador cfdi32_cancelador; private final Cfdi32DescargaXml cfdi32_descargaxml; private final Cfdi32DescargaAcuseXml cfdi32_descargaacusexml; private final Cfdi32Pdf cfdi32_pdf; private final Cfdi32PdfAcuse cfdi32_pdfacuse; private final Cfdi32Correo cfdi32_correo; private final Nom32Timbrador nom32_timbrador; private final Nom32SelladorYTimbrador nom32_selladorytimbrador; private final Nom32SelladorYTimbradorGenericoXml nom32_selladorytimbradorgenericoxml; private final Nom32SelladorYTimbradorGenericoTxt nom32_selladorytimbradorgenericotxt; private final Nom32DescargaXml nom32_descargaxml; private final Nom32DescargaAcuseXml nom32_descargaacusexml; private final Nom32Pdf nom32_pdf; private final Nom32PdfAcuse nom32_pdfacuse; private final Nom32Cancelador nom32_cancelador; private final Nom32Correo nom32_correo; private final Ret10SelladorYTimbrador ret10_selladorytimbrador; private final Ret10Timbrador ret10_timbrador; private final Ret10Correo ret10_correo; private final Ret10Pdf ret10_pdf; private final Ret10Cancelador ret10_cancelador; private final Ret10DescargaXml ret10_descargaxml; @Getter @Setter private String usuarioWs,contrasenaWs; /** * Se crea un objeto de tipo api, mediante el cual se ejecutarán todos los servicios implementados * * @param ambiente * <h3>PRODUCCION</h3><p>Ambiente productivo</p> * <h3>PRUEBAS</h3><p>Ambiente de pruebas</p> * <h3>LOCAL</h3><p>Ambiente de uso exclusivo emite</p> * @see Ambiente */ public EmiteAPI(final Ambiente ambiente){ this(ambiente,null,null); } /** * Se crea un objeto de tipo api, mediante el cual se ejecutarán todos los servicios implementados * * @param ambiente * <h3>PRODUCCION</h3><p>Ambiente productivo</p> * <h3>PRUEBAS</h3><p>Ambiente de pruebas</p> * <h3>LOCAL</h3><p>Ambiente de uso exclusivo emite</p> * @param usuarioWs usuario del WebService para almacenamiento local * @param contrasenaWs contraseña del WebService para almacenamiento local * @see Ambiente */ public EmiteAPI(final Ambiente ambiente,final String usuarioWs,final String contrasenaWs){ this.cliente=new ClienteJson(ambiente); this.usuarioWs=usuarioWs; this.contrasenaWs=contrasenaWs; this.servicios=new Servicios(this.cliente); this.estatus=new Estatus(this.cliente); this.cfdi32_timbrador=new Cfdi32Timbrador(this.cliente); this.cfdi32_cancelador=new Cfdi32Cancelador(this.cliente); this.cfdi32_selladorytimbrador=new Cfdi32SelladorYTimbrador(this.cliente); this.cfdi32_selladorytimbradorgenericoxml=new Cfdi32SelladorYTimbradorGenericoXml(this.cliente); this.cfdi32_selladorytimbradorgenericotxt=new Cfdi32SelladorYTimbradorGenericoTxt(this.cliente); this.cfdi32_descargaxml=new Cfdi32DescargaXml(this.cliente); this.cfdi32_descargaacusexml=new Cfdi32DescargaAcuseXml(this.cliente); this.cfdi32_pdf = new Cfdi32Pdf(this.cliente); this.cfdi32_pdfacuse = new Cfdi32PdfAcuse(this.cliente); this.cfdi32_correo=new Cfdi32Correo(this.cliente); this.descargamasiva=new DescargaMasiva(this.cliente); this.valida32_validador=new Valida32Validador(this.cliente); this.nom32_timbrador=new Nom32Timbrador(this.cliente); this.nom32_selladorytimbrador=new Nom32SelladorYTimbrador(this.cliente); this.nom32_cancelador=new Nom32Cancelador(this.cliente); this.nom32_selladorytimbradorgenericoxml=new Nom32SelladorYTimbradorGenericoXml(this.cliente); this.nom32_selladorytimbradorgenericotxt=new Nom32SelladorYTimbradorGenericoTxt(this.cliente); this.nom32_descargaxml=new Nom32DescargaXml(this.cliente); this.nom32_descargaacusexml=new Nom32DescargaAcuseXml(this.cliente); this.nom32_pdf = new Nom32Pdf(this.cliente); this.nom32_pdfacuse = new Nom32PdfAcuse(this.cliente); this.nom32_correo=new Nom32Correo(this.cliente); this.ret10_selladorytimbrador=new Ret10SelladorYTimbrador(this.cliente); this.ret10_cancelador=new Ret10Cancelador(this.cliente); this.ret10_correo=new Ret10Correo(this.cliente); this.ret10_descargaxml=new Ret10DescargaXml(this.cliente); this.ret10_pdf=new Ret10Pdf(this.cliente); this.ret10_timbrador=new Ret10Timbrador(this.cliente); } /** * Servicio de listado de Servicios * @return servicios * @since 0.0.1 */ public Servicios servicios(){ return servicios; } /** * Servicio Timbrado de CFDI 3.2 * @return cfdi32_timbrador * @since 0.0.1 */ public Cfdi32Timbrador cfdi32_Timbrador(){ return cfdi32_timbrador; } /** * Servicio de Sellado y Timbrado de CFDI 3.2 * @return cfdi32_selladorytimbrador * @since 0.0.1 */ public Cfdi32SelladorYTimbrador cfdi32_SelladorTimbrador(){ return cfdi32_selladorytimbrador; } /** * Servicio de Cancelación de CFDI 3.2 * @return cfdi32_cancelador * @since 0.0.2 */ public Cfdi32Cancelador cfdi32_Cancelador(){ return cfdi32_cancelador; } /** * Servicio de Descarga de CFDI 3.2 * @return cfdi32_descargaxml * @since 0.0.2 */ public Cfdi32DescargaXml cfdi32_DescargaXml(){ return cfdi32_descargaxml; } /** * Servicio de Descarga Acuses de Cancelación * @return cfdi32_descargaacusexml * @since 0.0.2 */ public Cfdi32DescargaAcuseXml cfdi32_DescargaAcuseXml(){ return cfdi32_descargaacusexml; } /** * Servicio de Descarga de Pdf * @return cfdi32_pdf * @since 0.0.2 */ public Cfdi32Pdf cfdi32_pdf(){ return cfdi32_pdf; } /** * Servicio de Descarga de Pdf de acuse * @return cfdi32_pdfacuse * @since 0.0.2 */ public Cfdi32PdfAcuse cfdi32_DescargaAcusePdf(){ return cfdi32_pdfacuse; } /** * Servicio de Envio de Correos * @return cfdi32_correo * @since 0.0.2 */ public Cfdi32Correo cfdi32_Correo(){ return cfdi32_correo; } /** * Servicio Timbrado de Xml Genérico 3.2 * @return cfdi32_selladorytimbradorgenericoxml * @since 0.1.1 */ public Cfdi32SelladorYTimbradorGenericoXml cfdi32_SelladorTimbradorGenericoXml(){ return cfdi32_selladorytimbradorgenericoxml; } /** * Servicio Timbrado de Txt Genérico 3.2 * @return cfdi32_selladorytimbradorgenericotxt * @since 0.1.1 */ public Cfdi32SelladorYTimbradorGenericoTxt cfdi32_SelladorTimbradorGenericoTxt(){ return cfdi32_selladorytimbradorgenericotxt; } /** * Servicio de Descarga Masiva * @return descargamasiva * @since 0.0.2 */ public DescargaMasiva descargamasiva(){ return descargamasiva; } /** * Servicio de Validación de CFDI * @return valida32_validador * @since 0.0.9 */ public Valida32Validador valida32_Validador(){ return valida32_validador; } /** * Servicio de Sellado y Timbrado de Nomina 3.2 * @return nom32_selladorytimbrador * @since 0.1.0 */ public Nom32SelladorYTimbrador nom32_SelladorTimbrador(){ return nom32_selladorytimbrador; } /** * Servicio Timbrado de Nómina de CFDI 3.2 * @return nom32_timbrador * @since 0.1.0 */ public Nom32Timbrador nom32_Timbrador(){ return nom32_timbrador; } /** * Servicio de Cancelación de CFDI 3.2 * @return nom32_cancelador * @since 0.1.1 */ public Nom32Cancelador nom32_Cancelador(){ return nom32_cancelador; } /** * Servicio de Envio de Correos de nómina * @return nom32_correo * @since 0.1.1 */ public Nom32Correo nom32_Correo(){ return nom32_correo; } /** * Servicio Timbrado de Xml Genérico 3.2 de nómina * @return nom32_selladorytimbradorgenericoxml * @since 0.1.1 */ public Nom32SelladorYTimbradorGenericoXml nom32_SelladorTimbradorGenericoXml(){ return nom32_selladorytimbradorgenericoxml; } /** * Servicio Timbrado de Txt Genérico 3.2 de nómina * @return nom32_selladorytimbradorgenericotxt * @since 0.1.1 */ public Nom32SelladorYTimbradorGenericoTxt nom32_SelladorTimbradorGenericoTxt(){ return nom32_selladorytimbradorgenericotxt; } /** * Servicio de Descarga de Pdf de nomina * @return nom32_pdf * @since 0.1.1 */ public Nom32Pdf nom32_pdf(){ return nom32_pdf; } /** * Servicio de Descarga de Pdf de acuse * @return nom32_pdfacuse * @since 0.1.1 */ public Nom32PdfAcuse nom32_DescargaAcusePdf(){ return nom32_pdfacuse; } /** * Servicio de Descarga de CFDI 3.2 de nómina * @return nom32_descargaxml * @since 0.1.1 */ public Nom32DescargaXml nom32_DescargaXml(){ return nom32_descargaxml; } /** * Servicio de Descarga Acuses de Cancelación de Nómina * @return nom32_descargaacusexml * @since 0.1.1 */ public Nom32DescargaAcuseXml nom32_DescargaAcuseXml(){ return nom32_descargaacusexml; } /** * Servicio de Consulta de Estatus de Emisores * @return estatus * @since 0.1.2 */ public Estatus estatus(){ return estatus; } /** * Servicio de Sellado y Timbrado de Retenciones * @return estatus * @since 0.1.4 */ public Ret10SelladorYTimbrador ret10_SelladorTimbrador(){ return ret10_selladorytimbrador; } /** * Servicio de Descarga de Pdf de retenciones * @return ret10_pdf * @since 0.1.5 */ public Ret10Pdf ret10_Pdf(){ return ret10_pdf; } /** * Servicio de envio de correo de retenciones * @return nom32_pdf * @since 0.1.5 */ public Ret10Correo ret10_Correo(){ return ret10_correo; } /** * Servicio de Cancelación de Retenciones 1.0 * @return ret10_cancelador * @since 0.1.5 */ public Ret10Cancelador ret10_Cancelador(){ return ret10_cancelador; } /** * Servicio Timbrado de Retenciones 1.0 * @return ret10_timbrador * @since 0.1.5 */ public Ret10Timbrador ret10_Timbrador(){ return ret10_timbrador; } /** * Servicio de Descarga de Retenciones 1.0 * @return ret10_descargaxml * @since 0.1.5 */ public Ret10DescargaXml ret10_DescargaXml(){ return ret10_descargaxml; } }
29.509259
99
0.778004
d03d69f114ef227f54eb24c95b832d76cbaeb80a
2,929
package net.violet.platform.api.actions.files; import java.util.List; import net.violet.platform.api.actions.AbstractAction; import net.violet.platform.api.actions.ActionParam; import net.violet.platform.api.authentication.SessionManager; import net.violet.platform.api.exceptions.ForbiddenException; import net.violet.platform.api.exceptions.InternalErrorException; import net.violet.platform.api.exceptions.InvalidParameterException; import net.violet.platform.api.exceptions.InvalidSessionException; import net.violet.platform.api.exceptions.TTSGenerationFailedException; import net.violet.platform.api.maps.FilesInformationMap; import net.violet.platform.datamodel.Application; import net.violet.platform.datamodel.Application.ApplicationClass; import net.violet.platform.dataobjects.FilesData; import net.violet.platform.dataobjects.TtsVoiceData; import net.violet.platform.dataobjects.UserData; import org.apache.log4j.Logger; /** * This action is used to synthetize TTS into mp3 * optional, save in user's library if session param is given */ public class Synthetize extends AbstractAction { static final Logger LOGGER = Logger.getLogger(Synthetize.class); @Override public Object doProcessRequest(ActionParam inParam) throws InvalidParameterException, TTSGenerationFailedException, InternalErrorException, ForbiddenException, InvalidSessionException { final String tts = inParam.getString("text", true); final String voice = inParam.getString("voice", false); final Integer ttl = inParam.getInt("time_to_live", false); // default value : 24hours from now final String languageCode = inParam.getString("language", null); final String theUserSession = inParam.getString(ActionParam.SESSION_PARAM_KEY, false); UserData theUserData = null; String theLabel = null; boolean save = false; if (theUserSession != null) {// save tts in user's library theUserData = SessionManager.getUserFromSessionId(theUserSession, inParam.getCaller()); theLabel = tts; if (theLabel.length() > 200) { theLabel = theLabel.substring(0, 200) + "..."; } save = true; } final TtsVoiceData voiceData = TtsVoiceData.getByParams(voice, languageCode, tts, null); if (Synthetize.LOGGER.isDebugEnabled()) { Synthetize.LOGGER.debug("violet.voices.synthetize : generating tts message \"" + tts + "\" with voice : " + voiceData.getLibelle()); } final FilesData ttsFileData = FilesData.postTTS(theUserData, tts, theLabel, voiceData, save, save, save); if ((ttl == null) && (save == false)) { ttsFileData.scheduleDeletion(); } return new FilesInformationMap(inParam.getCaller(), ttsFileData); } public ActionType getType() { return ActionType.CREATE; } public boolean isCacheable() { return false; } public long getExpirationTime() { return 0; } @Override public List<ApplicationClass> getAuthorizedApplicationClasses() { return Application.CLASSES_ALL; } }
33.666667
186
0.774326
86b1287e13f38e190cc75ddf4b9a0ae039a3d31d
2,223
package com.ruoyi.cgb.service.impl; import com.ruoyi.cgb.domain.RmInvoiceDetaiil; import com.ruoyi.cgb.mapper.RmInvoiceDetaiilMapper; import com.ruoyi.cgb.service.IRmInvoiceDetaiilService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.ruoyi.common.core.text.Convert; import java.util.List; /** * 发货单明细Service业务层处理 * * @author ruoyi * @date 2020-08-03 */ @Service public class RmInvoiceDetaiilServiceImpl implements IRmInvoiceDetaiilService { @Autowired private RmInvoiceDetaiilMapper rmInvoiceDetaiilMapper; /** * 查询发货单明细 * * @param wlxxid 发货单明细ID * @return 发货单明细 */ @Override public RmInvoiceDetaiil selectRmInvoiceDetaiilById(String wlxxid) { return rmInvoiceDetaiilMapper.selectRmInvoiceDetaiilById(wlxxid); } /** * 查询发货单明细列表 * * @param rmInvoiceDetaiil 发货单明细 * @return 发货单明细 */ @Override public List<RmInvoiceDetaiil> selectRmInvoiceDetaiilList(RmInvoiceDetaiil rmInvoiceDetaiil) { return rmInvoiceDetaiilMapper.selectRmInvoiceDetaiilList(rmInvoiceDetaiil); } /** * 新增发货单明细 * * @param rmInvoiceDetaiil 发货单明细 * @return 结果 */ @Override public int insertRmInvoiceDetaiil(RmInvoiceDetaiil rmInvoiceDetaiil) { return rmInvoiceDetaiilMapper.insertRmInvoiceDetaiil(rmInvoiceDetaiil); } /** * 修改发货单明细 * * @param rmInvoiceDetaiil 发货单明细 * @return 结果 */ @Override public int updateRmInvoiceDetaiil(RmInvoiceDetaiil rmInvoiceDetaiil) { return rmInvoiceDetaiilMapper.updateRmInvoiceDetaiil(rmInvoiceDetaiil); } /** * 删除发货单明细对象 * * @param ids 需要删除的数据ID * @return 结果 */ @Override public int deleteRmInvoiceDetaiilByIds(String ids) { return rmInvoiceDetaiilMapper.deleteRmInvoiceDetaiilByIds(Convert.toStrArray(ids)); } /** * 删除发货单明细信息 * * @param wlxxid 发货单明细ID * @return 结果 */ @Override public int deleteRmInvoiceDetaiilById(String wlxxid) { return rmInvoiceDetaiilMapper.deleteRmInvoiceDetaiilById(wlxxid); } }
23.15625
95
0.687809
95f40e4c44dae12a835c9b972ff0f969a6847ee5
803
/* * Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package com.sun.mirror.type; import com.sun.mirror.declaration.MethodDeclaration; /** * A pseudo-type representing the type of <tt>void</tt>. * * @author Joseph D. Darcy * @author Scott Seligman * * @deprecated All components of this API have been superseded by the * standardized annotation processing API. The replacement for the * functionality of this interface is included in {@link * javax.lang.model.type.NoType}. * * @see MethodDeclaration#getReturnType() * @since 1.5 */ @Deprecated @SuppressWarnings("deprecation") public interface VoidType extends TypeMirror { }
16.06
73
0.686177
271c3f77cbf44bdf914c3bc20e08f4650166e83e
2,525
package com.openrest.v1_1; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.wix.restaurants.i18n.LocalizedString; import java.io.Serializable; import java.util.LinkedHashSet; import java.util.Objects; import java.util.Set; @JsonIgnoreProperties(ignoreUnknown = true) public class CreditcardsInfo implements Serializable, Cloneable { private static final long serialVersionUID = 1L; /** Default constructor for JSON deserialization. */ public CreditcardsInfo() {} public CreditcardsInfo(Set<String> networks, Set<String> fields, String collectionMethod, LocalizedString comment) { this.networks = networks; this.fields = fields; this.collectionMethod = collectionMethod; this.comment = comment; } @Override public CreditcardsInfo clone() { return new CreditcardsInfo( ((networks != null) ? new LinkedHashSet<>(networks) : null), ((fields != null) ? new LinkedHashSet<>(fields) : null), collectionMethod, (comment != null) ? comment.clone() : null); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CreditcardsInfo that = (CreditcardsInfo) o; return Objects.equals(networks, that.networks) && Objects.equals(fields, that.fields) && Objects.equals(collectionMethod, that.collectionMethod) && Objects.equals(comment, that.comment); } @Override public int hashCode() { return Objects.hash(networks, fields, collectionMethod, comment); } /** Accepted networks, e.g. "visa", "mastercard", "amex". */ @JsonInclude(Include.NON_NULL) public Set<String> networks = new LinkedHashSet<>(); /** Required credit card fields, e.g. "csc", "holderId". */ @JsonInclude(Include.NON_NULL) public Set<String> fields = new LinkedHashSet<>(); /** * Card collection method. * @see com.wix.restaurants.CollectionMethods */ @JsonInclude(Include.NON_NULL) public String collectionMethod; /** Message to show when customer opts to pay by card. */ @JsonInclude(Include.NON_DEFAULT) public LocalizedString comment = LocalizedString.empty; }
35.56338
121
0.650693
584b2dd23a39293a7786ffe684410db428c9b7ab
6,197
package bank.storage; import bank.exception.ExistAccountException; import bank.exception.ExistStorageException; import bank.exception.LimitMoneyException; import bank.exception.NotExistAccountException; import bank.exception.NotExistStorageException; import bank.models.Account; import bank.models.User; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.TreeMap; /** * Bank. * * @author Maxim Vanny * @version 3.0 * @since 0.1 */ public class Bank { /** * Storage safe user's account. */ private final Map<User, List<Account>> map = new TreeMap<>(); /** * Method get all user accounts. * * @return the list of user in storage */ public final List<User> getAllUser() { return new ArrayList<>(map.keySet()); } /** * Method add new user. * * @param user new user * @throws ExistStorageException user is in storage */ public final void addUser(final User user) throws ExistStorageException { Objects.requireNonNull(user, "user must not be null"); if (this.map.containsKey(user)) { throw new ExistStorageException("user is in storage."); } else { this.map.put(user, new ArrayList<>()); } } /** * Method delete user from storage. * * @param user user * @throws NotExistStorageException user is't in storage */ public final void deleteUser(final User user) throws NotExistStorageException { Objects.requireNonNull(user, "user must not be null"); if (!this.map.containsKey(user)) { throw new NotExistStorageException("user is't in storage."); } else { this.map.remove(user); } } /** * Method delete the account of user. * * @param passport the passport of user * @param account the account of user * @throws NotExistAccountException account is't in storage */ public final void deleteAccountFromUser(final String passport, final Account account) throws NotExistAccountException { Objects.requireNonNull(passport, "passport must not be null"); Objects.requireNonNull(account, "account must not be null"); final List<Account> userAccounts = getUserAccounts(passport); if (!userAccounts.isEmpty()) { if (!userAccounts.remove(account)) { throw new NotExistAccountException("account is't in storage"); } } else { System.out.println("Storage is empty."); } } /** * Method add account for user. * * @param passport the passport of user * @param account new account for user * @throws ExistAccountException account is in storage */ public final void addAccountToUser(final String passport, final Account account) throws ExistAccountException { Objects.requireNonNull(passport, "passport must not be null"); Objects.requireNonNull(account, "account must not be null"); final List<Account> userAccounts = getUserAccounts(passport); if (!userAccounts.contains(account)) { userAccounts.add(account); } else { throw new ExistAccountException("account is in storage"); } } /** * Method get all user account. * * @param passport the passport of user * @return all user account */ public final List<Account> getUserAccounts(final String passport) { Objects.requireNonNull(passport, "passport must not be null"); List<Account> result = new ArrayList<>(); for (Map.Entry<User, List<Account>> entry : this.map.entrySet()) { if (entry.getKey().getPassport().equals(passport)) { result = entry.getValue(); break; } } return result; } /** * Method transfer amount between accounts. * * @param srcPass the passport of user * @param srcReq the requisite of account user * @param dstPass the passport destination * @param dstReq the requisite destination * @param amount the sum for transfer */ public final void transferMoney(final String srcPass, final String srcReq, final String dstPass, final String dstReq, final double amount) { Objects.requireNonNull(srcPass, "passport must not be null"); Objects.requireNonNull(dstPass, "passport must not be null"); Objects.requireNonNull(srcReq, "requisite must not be null"); Objects.requireNonNull(dstReq, "requisite must not be null"); try { Account resource = getUserAccount(srcPass, srcReq); Account target = getUserAccount(dstPass, dstReq); resource.transfer(target, amount); } catch (LimitMoneyException lme) { System.out.println("Limit out. Check balance."); } catch (NotExistAccountException nae) { System.out.println("Account is't in storage."); } } /** * Method gets index account in storage. * * @param passport the user's passport * @param requisite the user's requisite * @return the index in storage * @throws NotExistAccountException account is't storage */ protected final Account getUserAccount(final String passport, final String requisite) throws NotExistAccountException { Account account = null; final List<Account> userAccounts = getUserAccounts(passport); if (!userAccounts.isEmpty()) { for (Account dst : userAccounts) { if (dst.getRequisites().equals(requisite)) { account = dst; break; } } } if (account == null) { throw new NotExistAccountException("account is't in storage."); } return account; } }
33.317204
78
0.602388
7c581911b694e90db7c8564a7b75419b6109df40
1,372
package live.fanxing.codegenerator.core.gen; import live.fanxing.codegenerator.core.code.Dao; import live.fanxing.codegenerator.core.code.Entity; import lombok.Data; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * @auther fanxing * 2021/6/6 */ @Data public class Table { // 表名 String tableName; // 类名 String className; // 属性名 String attrName; // 表中的字段 List<Filed> fileds; Map<String,Filed> filedMap; // 表的外键关系(或自定义关系) List<Table> left; Map<String, Table> leftMap; // 关联查询的时候的on List<Keyon> keyOns; // 当前表关联的实体类 Entity entity; // 关联的Dao类 Dao dao; public Table(String tableName, String className, String attrName) { this.tableName = tableName; this.className = className; this.attrName = attrName; this.fileds = new ArrayList<>(); this.left = new ArrayList<>(); this.filedMap = new HashMap<>(); this.leftMap = new HashMap<>(); this.keyOns = new ArrayList<>(); } public void addFiled(String key,Filed filed){ this.fileds.add(filed); this.filedMap.put(key,filed); } public void addLeft(String key,Keyon keyOn,Table table){ this.left.add(table); this.leftMap.put(key, table); this.keyOns.add(keyOn); } }
20.787879
71
0.627551
cbac6353bc41e002770489572ffca025979b97ed
207
package br.com.mxti.backend.dao; import org.springframework.data.jpa.repository.JpaRepository; import br.com.mxti.backend.entidade.Turma; public interface TurmaDao extends JpaRepository<Turma, Long> { }
20.7
62
0.806763
55ba11497deacc5be325af93f693bba7a7eaf25c
7,750
/** * Copyright (C) 2012 Philip W. Sorst <[email protected]> * and individual contributors as indicated * by the @authors tag. * * 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.dontdrinkandroot.lastfm.api.ws; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.ProtocolException; import java.net.URL; import java.net.URLEncoder; import java.util.Map; import java.util.Map.Entry; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import net.dontdrinkandroot.lastfm.api.LastfmWebServicesException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.xml.sax.SAXException; /** * This class is responsible for actually fetching the data from last.fm and converting it to a dom * Document. * * @author Philip W. Sorst * */ public class Fetcher { /** The base URL, needed if you want to proxy requests somewhere. */ private URL baseUrl; /** Default connection timeout */ private final int defaultConnectionTimeout = 5000; /** Connection timeout */ private final int connectionTimeout = this.defaultConnectionTimeout; /** We need to enforce the last.fm fetch limit */ private final FetchLimitEnforcer limitEnforcer = new FetchLimitEnforcer(); private final Logger logger = LoggerFactory.getLogger(Fetcher.class); private final DocumentBuilderFactory factory; public Fetcher() throws ParserConfigurationException { /* Set base URL */ try { this.baseUrl = new URL("http://ws.audioscrobbler.com/2.0/"); } catch (final MalformedURLException e) { /* This really shouldn't happen, if it does, fail hard */ throw new RuntimeException(e); } /* Create JAXB unmarshaller */ /* * We explicity choose the SAXParser Factory here as there may be many implementations on * the classpath */ System.setProperty( "javax.xml.parsers.SAXParserFactory", "com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl"); this.factory = DocumentBuilderFactory.newInstance(); } public final LastfmResponse get(final Map<String, String> parameters) throws LastfmWebServicesException { final URL url = this.buildUrl(parameters); this.logger.trace("Query url is " + url); /* Respect last.fm fetch limit */ this.limitEnforcer.waitForTimeslot(); /* Open http connection */ final HttpURLConnection conn = this.openConnection(url); /* Do the actual fetch */ final LastfmResponse response = this.fetchResponse(conn); return response; } public final LastfmResponse post(final Map<String, String> parameters) throws LastfmWebServicesException { /* Respect last.fm fetch limit */ this.limitEnforcer.waitForTimeslot(); final String parameterString = this.buildParameterString(parameters); this.logger.trace("ParameterString: " + parameterString); /* Open http connection */ final HttpURLConnection conn = this.openConnection(this.baseUrl); /* Mark as POST */ try { conn.setRequestMethod("POST"); } catch (final ProtocolException e) { throw new LastfmWebServicesException(LastfmWebServicesException.UNSUPPORTED_PROTOCOL, e.getMessage()); } conn.setDoOutput(true); /* Write POST data */ try { final OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream()); osw.write(parameterString); osw.flush(); } catch (final IOException e) { throw new LastfmWebServicesException(LastfmWebServicesException.WRITING_POST_DATA_FAILED, e.getMessage()); } final LastfmResponse response = this.fetchResponse(conn); return response; } private String buildParameterString(final Map<String, String> parameters) { final StringBuffer parameterString = new StringBuffer(); int count = 0; for (final Entry<String, String> parameter : parameters.entrySet()) { if (count != 0) { parameterString.append("&"); } try { parameterString.append(URLEncoder.encode(parameter.getKey(), "UTF-8") + "=" + URLEncoder.encode(parameter.getValue(), "UTF-8")); } catch (final UnsupportedEncodingException e) { /* UTF-8 should be always available */ throw new RuntimeException("Encoding UTF-8 not found!", e); } count++; } return parameterString.toString(); } private LastfmResponse fetchResponse(final HttpURLConnection conn) throws LastfmWebServicesException { /* Open input stream */ InputStream is = null; try { is = conn.getInputStream(); } catch (final IOException e) { is = conn.getErrorStream(); } if (is == null) { conn.disconnect(); throw new LastfmWebServicesException(LastfmWebServicesException.STREAM_WAS_NULL, "Stream was null"); } /* Read document from inputstream */ final Document doc = this.parseDoc(is); /* Close connection */ try { is.close(); conn.disconnect(); } catch (final IOException e) { this.logger.error("Closing Http connection failed", e); } final long expiration = conn.getExpiration(); final LastfmResponse response = new LastfmResponse(doc, expiration); return response; } /** * * @param is * The InputStream to unmarshall. * @return The Document that was parsed. * @throws LastfmWebServicesException * Thrown if reading the document fails. */ private Document parseDoc(final InputStream is) throws LastfmWebServicesException { /* For debugging */ // String xml = null; // try { // xml = new String(IOUtils.toByteArray(is)); // System.out.println(xml); // } catch (final IOException e) { // e.printStackTrace(); // } // final InputStream is2 = IOUtils.toInputStream(xml); try { final Document doc = this.factory.newDocumentBuilder().parse(is); return doc; } catch (final SAXException e) { throw new LastfmWebServicesException(LastfmWebServicesException.READING_DOC_FAILED, e.getMessage()); } catch (final IOException e) { throw new LastfmWebServicesException(LastfmWebServicesException.READING_DOC_FAILED, e.getMessage()); } catch (final ParserConfigurationException e) { throw new LastfmWebServicesException(LastfmWebServicesException.READING_DOC_FAILED, e.getMessage()); } } private HttpURLConnection openConnection(final URL url) throws LastfmWebServicesException { try { final HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(this.connectionTimeout); conn.setConnectTimeout(this.connectionTimeout); return conn; } catch (final IOException e) { throw new LastfmWebServicesException(LastfmWebServicesException.OPENING_CONNECTION_FAILED, e.getMessage()); } } private URL buildUrl(final Map<String, String> parameters) { /* Build url */ final String urlString = this.baseUrl.toString() + "?" + this.buildParameterString(parameters); try { return new URL(urlString); } catch (final MalformedURLException e) { /* Shouldn't happen */ this.logger.error("Constructed URL is invalid", e); return null; } } public final double getWebRequestsPerSecond() { return this.limitEnforcer.getWebRequestsPerSecond(); } }
28.07971
110
0.731613
cb3f3450dbc92d732c8c6dd63f77bb7c0ecc8e0c
3,309
package edu.miami.ccs.dcic; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Properties; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.json.simple.JSONArray; import org.json.simple.JSONObject; public class KnockDown extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doGet(req, resp); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json"); Properties props = new Properties(); InputStream is = null; try { is = getClass().getClassLoader().getResourceAsStream("db_config.properties"); } catch (Exception e3) { e3.printStackTrace(); } try { props.load(is); } catch (IOException e2) { e2.printStackTrace(); } String id = request.getParameter("id"); System.out.println(); DBConnection dbCon = new DBConnection(props.getProperty("JDBC_URL"), props.getProperty("USERNAME"), props.getProperty("PASSWORD")); Connection con = dbCon.getConnection(); PreparedStatement stmt; String query = null; try { JSONArray jsArray = new JSONArray(); if(id==null){ query="select distinct perturbagen_class[1],nucleic_acid_reagent_type[1],nucleic_acid_reagent_subtype[1],nucleic_acid_reagent_target_locus[1],nucleic_acid_reagent_target_locus_species[1],nucleic_acid_reagent_entrez_gene_id[1],max(perturbagen_id[1]) as perturbagen_id" + " from dm.lookup_signature_object_perturbation_nucleic_acid_reagent " + " where nucleic_acid_reagent_type[1] = 'Coding'" + " group by perturbagen_class[1],nucleic_acid_reagent_type[1],nucleic_acid_reagent_subtype[1],nucleic_acid_reagent_target_locus[1],nucleic_acid_reagent_target_locus_species[1],nucleic_acid_reagent_entrez_gene_id[1]"; }else{ query = "select object_id,object_class,efo_term,efo_id,mesh_heading,mesh_id,max_phase_for_ind from dm.small_molecule_clinical_annotations where object_id = ? "; } stmt = con.prepareStatement(query); if(id!=null){ stmt.setInt(1, Integer.parseInt(id)); } try { System.out.println(query); ResultSet rs = stmt.executeQuery(); int columns = rs.getMetaData().getColumnCount(); while (rs.next()) { JSONObject obj = new JSONObject(); for (int i = 1; i <= columns; i++) { Object tempObject=rs.getObject(i); obj.put(rs.getMetaData().getColumnLabel(i), tempObject); } jsArray.add(obj); } response.getWriter().print(jsArray); response.flushBuffer(); con.close(); } catch (SQLException e1) { e1.printStackTrace(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
33.424242
269
0.729526
6daeec93f3544dc722732cb13878c725371aa8b9
5,375
package com.nuwarobotics.example.activity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.WindowManager; import android.widget.ImageButton; import com.nuwarobotics.example.R; import com.nuwarobotics.example.motion.base.BaseAppCompatActivity; import com.nuwarobotics.service.IClientId; import com.nuwarobotics.service.agent.NuwaRobotAPI; import com.nuwarobotics.service.agent.RobotEventListener; /** * Some 3rd app prefer not leave app by press power key * Example of call disablePowerKey() and enablePowerKey() API. * Target SDK : 2.0.0.08 */ public class DisablePowerkeyExampleActivity extends BaseAppCompatActivity { private final static String TAG = "DisablePowerkeyExampleActivity"; //nuwa general style of close button ImageButton mCloseBtn; NuwaRobotAPI mRobotAPI; IClientId mClientId; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_disablepowerkey); mCloseBtn = findViewById(R.id.imgbtn_quit); mCloseBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //Please make sure enable power key when leave ui if(mRobotAPI!=null){ //如果 powerkey有被無效化>>恢復他 mRobotAPI.enablePowerKey(); } finish(); } }); //Step 1 : Initial Nuwa API Object mClientId = new IClientId(this.getPackageName()); mRobotAPI = new NuwaRobotAPI(this,mClientId); //Step 2 : Register receive Robot Event Log.d(TAG,"register EventListener ") ; mRobotAPI.registerRobotEventListener(robotEventListener);//listen callback of robot service event } @Override protected int getLayoutRes(){ return R.layout.activity_disablepowerkey; } @Override protected int getToolBarTitleRes(){ return R.string.disablepowerkey_sdk_example_title; } @Override protected void onResume() { super.onResume(); hideSystemUi(); } @Override protected void onPause() { super.onPause(); //Please make sure enable power key when leave ui if(mRobotAPI!=null){ mRobotAPI.enablePowerKey(); } } @Override protected void onDestroy() { super.onDestroy(); } protected void hideSystemUi() { getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); View decorView = getWindow().getDecorView(); decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE); } RobotEventListener robotEventListener = new RobotEventListener() { @Override public void onWikiServiceStart() { // Nuwa Robot SDK is ready now, you call call Nuwa SDK API now. Log.d(TAG,"onWikiServiceStart, robot ready to be control ") ; Log.d(TAG,"disablePowerKey"); mRobotAPI.disablePowerKey(); } @Override public void onWikiServiceStop() { } @Override public void onWikiServiceCrash() { } @Override public void onWikiServiceRecovery() { } @Override public void onStartOfMotionPlay(String s) { } @Override public void onPauseOfMotionPlay(String s) { } @Override public void onStopOfMotionPlay(String s) { } @Override public void onCompleteOfMotionPlay(String s) { } @Override public void onPlayBackOfMotionPlay(String s) { } @Override public void onErrorOfMotionPlay(int i) { } @Override public void onPrepareMotion(boolean b, String s, float v) { } @Override public void onCameraOfMotionPlay(String s) { } @Override public void onGetCameraPose(float v, float v1, float v2, float v3, float v4, float v5, float v6, float v7, float v8, float v9, float v10, float v11) { } @Override public void onTouchEvent(int i, int i1) { } @Override public void onPIREvent(int i) { } @Override public void onTap(int i) { } @Override public void onLongPress(int i) { } @Override public void onWindowSurfaceReady() { } @Override public void onWindowSurfaceDestroy() { } @Override public void onTouchEyes(int i, int i1) { } @Override public void onRawTouch(int i, int i1, int i2) { } @Override public void onFaceSpeaker(float v) { } @Override public void onActionEvent(int i, int i1) { } @Override public void onDropSensorEvent(int i) { } @Override public void onMotorErrorEvent(int i, int i1) { } }; }
23.783186
158
0.610419
ec2ab1600159bea173a27dc9a989055f7fb56fd5
1,233
package org.sylrsykssoft.java.musbands.admin.musical.genre.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.sylrsykssoft.coreapi.framework.web.BaseAdminController; import org.sylrsykssoft.java.musbands.admin.musical.genre.configuration.MusicalGenreConstants; import org.sylrsykssoft.java.musbands.admin.musical.genre.domain.MusicalGenre; import org.sylrsykssoft.java.musbands.admin.musical.genre.resource.MusicalGenreResource; import org.sylrsykssoft.java.musbands.admin.musical.genre.service.MusicalGenreService; /** * Rest Controller for Musical Genre API * * @author juan.gonzalez.fernandez.jgf * * @see https://restfulapi.net/http-methods/ * */ @RestController(MusicalGenreConstants.CONTROLLER_TEST_NAME) @RequestMapping(MusicalGenreConstants.CONTROLLER_REQUEST_MAPPING_TEST) public class MusicalGenreControllerTest extends BaseAdminController<MusicalGenreResource, MusicalGenre> { @Autowired private MusicalGenreService musicalGenreService; /** * {@inherit} */ public MusicalGenreService getAdminService() { return musicalGenreService; } }
35.228571
105
0.832928
f3ba5196036d26b6022233cbca820870135bef02
3,051
package com.kelystor.boatcross.vendor.gitlab; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.PropertyNamingStrategy; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import com.kelystor.boatcross.vendor.exception.ApiRequestException; import com.kelystor.boatcross.vendor.gitlab.model.GitLabMergeRequest; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; public class GitLabAPI { private static final Logger LOGGER = LoggerFactory.getLogger(GitLabAPI.class); private static final ObjectMapper MAPPER = new ObjectMapper().setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE).configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false).registerModule(new JavaTimeModule()); private static final String DEFAULT_API_NAMESPACE = "/api/v4"; private String hostUrl; private String apiToken; private GitLabAPI(String hostUrl, String apiToken) { this.hostUrl = hostUrl; this.apiToken = apiToken; } public static GitLabAPI connect(String hostUrl, String apiToken) { return new GitLabAPI(hostUrl, apiToken); } public GitLabMergeRequest getProjectLastMergeRequest(String projectId) { HttpGet get = new HttpGet(hostUrl + DEFAULT_API_NAMESPACE + "/projects/" + sanitizeProjectId(projectId) + "/merge_requests?state=opened&state=merged&scope=all&order_by=created_at&sort=desc&page=1&per_page=1"); String content = executeRequest(get); try { return MAPPER.convertValue(MAPPER.readTree(content).get(0), GitLabMergeRequest.class); } catch (IOException ignore) { return null; } } private String executeRequest(HttpUriRequest request) { try (CloseableHttpClient client = HttpClientBuilder.create().build()) { request.addHeader("Private-Token", apiToken); try (CloseableHttpResponse response = client.execute(request)) { HttpEntity entity = response.getEntity(); return EntityUtils.toString(entity, StandardCharsets.UTF_8); } } catch (IOException ignore) { return null; } } private String sanitizeProjectId(String projectId) { try { return URLEncoder.encode(projectId, StandardCharsets.UTF_8.name()); } catch (UnsupportedEncodingException e) { throw new ApiRequestException("GitLab项目名称 " + projectId + " URLEncoder.encode失败"); } } }
42.971831
232
0.740085
2a3ff32523a75c873addca34aa94235a890bc5e7
7,923
package com.xlk.cache; import java.util.HashSet; import java.util.Set; import org.springframework.beans.factory.annotation.Value; import org.springframework.cache.interceptor.KeyGenerator; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.data.redis.connection.RedisClusterConfiguration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.connection.RedisNode; import org.springframework.data.redis.connection.RedisSentinelConfiguration; import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; import redis.clients.jedis.JedisPoolConfig; @Configuration @PropertySource("classpath:redis.properties")//读取配置文件 public class RedisConfigure { @Value("${redis.hostName}") private String hostName; @Value("${redis.port}") private Integer port; @Value("${redis.maxIdle}") private Integer maxIdle; @Value("${redis.maxTotal}") private Integer maxTotal; @Value("${redis.maxWaitMillis}") private Integer maxWaitMillis; @Value("${redis.minEvictableIdleTimeMillis}") private Integer minEvictableIdleTimeMillis; @Value("${redis.numTestsPerEvictionRun}") private Integer numTestsPerEvictionRun; @Value("${redis.timeBetweenEvictionRunsMillis}") private long timeBetweenEvictionRunsMillis; @Value("${redis.testOnBorrow}") private boolean testOnBorrow; @Value("${redis.testWhileIdle}") private boolean testWhileIdle; @Value("${spring.redis.cluster.nodes}") private String clusterNodes; //集群的节点 @Value("${spring.redis.cluster.max-redirects}") private Integer maxRedirectsac; /* @Value("${redis.sentinel.host1}") private String sentinelHost1; @Value("${redis.sentinel.port1}") private Integer sentinelport1; @Value("${redis.sentinel.host2}") private String sentinelHost2; @Value("${redis.sentinel.port2}") private Integer sentinelport2;*/ //key生成策略 @Bean public KeyGenerator keyGenerator() { return new KeyGenerator(){ @Override public Object generate(Object target, java.lang.reflect.Method method, Object... params) { StringBuffer sb = new StringBuffer(); sb.append(target.getClass().getName()); sb.append(method.getName()); for(Object obj:params){ sb.append(obj.toString()); } return sb.toString(); } }; } //redis连接池 @Bean public JedisPoolConfig jedisPoolConfig() { /** * 非springboot下 redis连接池 * JedisPool jedisPool = new JedisPool(new GenericObjectPoolConfig(), "127.0.0.1", 6379); * Jedis jedis = jedisPool.getResource(); * jedis.set()/.get(); * jedis.close();最后需要关闭连接,代表归还连接池 */ JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); // 最大空闲数 jedisPoolConfig.setMaxIdle(maxIdle); // 连接池的最大数据库连接数 jedisPoolConfig.setMaxTotal(maxTotal); // 最大建立连接等待时间 jedisPoolConfig.setMaxWaitMillis(maxWaitMillis); // 逐出连接的最小空闲时间 默认1800000毫秒(30分钟) jedisPoolConfig.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis); // 每次逐出检查时 逐出的最大数目 如果为负数就是 : 1/abs(n), 默认3 jedisPoolConfig.setNumTestsPerEvictionRun(numTestsPerEvictionRun); // 逐出扫描的时间间隔(毫秒) 如果为负数,则不运行逐出线程, 默认-1 jedisPoolConfig.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis); // 是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个 jedisPoolConfig.setTestOnBorrow(testOnBorrow); // 在空闲时检查有效性, 默认false jedisPoolConfig.setTestWhileIdle(testWhileIdle); return jedisPoolConfig; } //单机版 /*@Bean public JedisConnectionFactory jedisConnectionFactory(JedisPoolConfig jedisPoolConfig) { JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(jedisPoolConfig); jedisConnectionFactory.setPoolConfig(jedisPoolConfig);//连接池 jedisConnectionFactory.setHostName(hostName);//ip jedisConnectionFactory.setPort(port);//端口 jedisConnectionFactory.setPassword(""); jedisConnectionFactory.setTimeout(5000); return jedisConnectionFactory; }*/ /** * redis集群 * @return * */ @Bean public RedisClusterConfiguration redisClusterConfiguration() { RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration(); String[] serverArray = clusterNodes.split(","); Set<RedisNode> set = new HashSet<RedisNode>(); for(String redisNode : serverArray) { String[] ipAndPort = redisNode.split(":"); set.add(new RedisNode(ipAndPort[0].trim(),Integer.valueOf(ipAndPort[1]))); } redisClusterConfiguration.setClusterNodes(set); redisClusterConfiguration.setMaxRedirects(maxRedirectsac); return redisClusterConfiguration; } //配置集群工厂 @Bean public JedisConnectionFactory JedisConnectionFactory(JedisPoolConfig jedisPoolConfig,RedisClusterConfiguration redisClusterConfiguration){ JedisConnectionFactory JedisConnectionFactory = new JedisConnectionFactory(redisClusterConfiguration,jedisPoolConfig); return JedisConnectionFactory; } /** * 配置redis的哨兵 * @param redisConnectionFactory * @return @Bean public RedisSentinelConfiguration redisSentinelConfiguration () { RedisSentinelConfiguration redisSentinelConfiguration = new RedisSentinelConfiguration(); //配置matser的名称 RedisNode masterredisNode = new RedisNode(sentinelHost1,sentinelport1); masterredisNode.setName("mymaster"); redisSentinelConfiguration.master(masterredisNode); //配置redis的哨兵sentinel RedisNode senredisNode1 = new RedisNode(sentinelHost2,sentinelport2);//哨兵1 RedisNode senredisNode2 = new RedisNode("172.20.1.232",26379);////哨兵2 Set<RedisNode> redisSet = new HashSet<RedisNode>(); redisSet.add(senredisNode1); redisSet.add(senredisNode2); redisSentinelConfiguration.setSentinels(redisSet); return redisSentinelConfiguration; } //配置工厂 public JedisConnectionFactory jedisConnectionFactory(RedisSentinelConfiguration redisSentinelConfiguration,JedisPoolConfig jedisPoolConfig) { JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(redisSentinelConfiguration,jedisPoolConfig); return jedisConnectionFactory; } */ //实例化 RedisTemplate 对象 @Bean public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>(); initDomainRedisTemplate(redisTemplate, redisConnectionFactory); return redisTemplate; } private void initDomainRedisTemplate(RedisTemplate<String,Object> redisTemplate, RedisConnectionFactory redisConnectionFactory) { redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer()); redisTemplate.setHashKeySerializer(new StringRedisSerializer()); redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer()); //开启事务 redisTemplate.setEnableTransactionSupport(true); redisTemplate.setConnectionFactory(redisConnectionFactory); } }
37.728571
147
0.712988
60ffb6b5291f06f795b98c800ae6ab37a673b729
2,375
package com.bespectacled.modernbeta.world.biome.beta; import com.bespectacled.modernbeta.world.biome.OldBiomeColors; import com.bespectacled.modernbeta.world.biome.OldBiomeFeatures; import com.bespectacled.modernbeta.world.biome.OldBiomeMobs; import com.bespectacled.modernbeta.world.biome.OldBiomeStructures; import net.minecraft.world.biome.Biome; import net.minecraft.world.biome.BiomeEffects; import net.minecraft.world.biome.GenerationSettings; import net.minecraft.world.biome.SpawnSettings; import net.minecraft.world.gen.surfacebuilder.ConfiguredSurfaceBuilders; public class FrozenOcean { public static final Biome BIOME = create(); private static Biome create() { SpawnSettings.Builder spawnSettings = new SpawnSettings.Builder(); OldBiomeMobs.addFrozenOceanMobs(spawnSettings); GenerationSettings.Builder genSettings = new GenerationSettings.Builder(); genSettings.surfaceBuilder(ConfiguredSurfaceBuilders.GRASS); OldBiomeFeatures.addDefaultFeatures(genSettings, true, BetaBiomes.ADD_LAKES, BetaBiomes.ADD_SPRINGS); OldBiomeFeatures.addMineables(genSettings, BetaBiomes.ADD_ALTERNATE_STONES, BetaBiomes.ADD_NEW_MINEABLES); OldBiomeFeatures.addOres(genSettings); OldBiomeStructures.addOceanStructures(genSettings, false); OldBiomeFeatures.addVegetalPatches(genSettings); OldBiomeFeatures.addBetaFrozenTopLayer(genSettings); OldBiomeFeatures.addCarvers(genSettings, true); OldBiomeFeatures.addOceanCarvers(genSettings); return (new Biome.Builder()) .precipitation(Biome.Precipitation.SNOW) .category(Biome.Category.OCEAN) .depth(-1.0F) .scale(0.1F) .temperature(0.0F) .downfall(0.5F) .effects((new BiomeEffects.Builder()) .skyColor(OldBiomeColors.BETA_COLD_SKY_COLOR) .fogColor(OldBiomeColors.BETA_FOG_COLOR) .waterColor(OldBiomeColors.USE_DEBUG_OCEAN_COLOR ? 16777215 : OldBiomeColors.VANILLA_FROZEN_WATER_COLOR) .waterFogColor(OldBiomeColors.VANILLA_FROZEN_WATER_FOG_COLOR) .build()) .spawnSettings(spawnSettings.build()) .generationSettings(genSettings.build()) .build(); } }
43.181818
120
0.712421
f96235de2e3af5b0b252c42baa68339a80fbb02e
669
package io.github.aaronchenwei.demorxjava; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @Slf4j public class DemoRxjavaApplication implements CommandLineRunner { public static void main(String[] args) { SpringApplication.run(DemoRxjavaApplication.class, args); } @Override public void run(String... args) { log.info("EXECUTING : command line runner"); for (int i = 0, len = args.length; i < len; i += 1) { log.info("args[{}]: {}", i, args[i]); } } }
26.76
68
0.732436
6c0ff47713bd4011fcf39ff4d3ddcbc863b695f4
1,716
package com.evbox.everon.ocpp.simulator.station.handlers.ocpp; import com.evbox.everon.ocpp.simulator.station.StationMessageSender; import com.evbox.everon.ocpp.simulator.station.StationStore; import com.evbox.everon.ocpp.v20.message.MessageTriggerEnum; import com.evbox.everon.ocpp.v20.message.TriggerMessageRequest; import com.evbox.everon.ocpp.v20.message.TriggerMessageResponse; import com.evbox.everon.ocpp.v20.message.TriggerMessageStatusEnum; import lombok.extern.slf4j.Slf4j; import java.util.concurrent.Executor; import java.util.concurrent.Executors; /** * Handler for {@link TriggerMessageRequest} request. */ @Slf4j public class TriggerMessageRequestHandler implements OcppRequestHandler<TriggerMessageRequest> { private static final Executor executor = Executors.newSingleThreadExecutor(); private StationStore stationStore; private StationMessageSender stationMessageSender; public TriggerMessageRequestHandler(StationStore stationStore, StationMessageSender stationMessageSender) { this.stationStore = stationStore; this.stationMessageSender = stationMessageSender; } @Override public void handle(String callId, TriggerMessageRequest request) { if (request.getRequestedMessage() == MessageTriggerEnum.SIGN_CHARGING_STATION_CERTIFICATE) { executor.execute(new SignCertificateRequestHandler(stationStore, stationMessageSender)); stationMessageSender.sendCallResult(callId, new TriggerMessageResponse().withStatus(TriggerMessageStatusEnum.ACCEPTED)); } else { stationMessageSender.sendCallResult(callId, new TriggerMessageResponse().withStatus(TriggerMessageStatusEnum.REJECTED)); } } }
42.9
132
0.797203