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
7d93ffd0feef923df1f9dc8f7cda6710d475abac
4,522
package com.beimi.web.handler.api.rest.user; import com.beimi.core.BMDataContext; import com.beimi.util.cache.CacheHelper; import com.beimi.web.model.*; import com.beimi.web.service.repository.es.PcddPeriodsESRepository; import com.beimi.web.service.repository.es.TokenESRepository; import com.beimi.web.service.repository.jpa.PlayUserRepository; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Sort; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import javax.validation.Valid; import java.util.Date; import java.util.Iterator; /** * Created by fanling on 2018/2/7. */ @RestController @RequestMapping("/api/lottery") public class ApiLotteryController { @Autowired private PcddPeriodsESRepository pcddPeriodsESRepository; @Autowired private TokenESRepository tokenESRes ; @Autowired private PlayUserRepository playUserRes ; @RequestMapping public ResponseEntity<PcData> Lottery(HttpServletRequest request,@Valid int type){ Token userToken = tokenESRes.findById(request.getHeader("token")); PlayUser playUser = playUserRes.findByToken(userToken.getId()); if (playUser==null) return new ResponseEntity<>(new PcData("201","未知用户",null), HttpStatus.OK); PcddPeriods pcddPeriods = getCurLottery(type); PcData resu; int intervalSec; // type 1北京 2加拿大 if (type == 1){ intervalSec = 300; }else{ intervalSec = 210; } if (pcddPeriods != null){ LotteryClient lottery = new LotteryClient(pcddPeriods.getPeriods(), pcddPeriods.getRes(),pcddPeriods.getResname(),pcddPeriods.getStatus(),0,pcddPeriods.getOpentime(),pcddPeriods.getColorid()); long nexttime = Integer.parseInt(pcddPeriods.getOpentime()) - new Date().getTime()/1000; if (nexttime < 0){ lottery.setNextOpenSec(0); if(nexttime < -intervalSec){ //停盘 lottery.setStauts(3); }else{ //客户端显示?,?,? 同时进行下一期下注 lottery.setStauts(4); lottery.setNextOpenSec(intervalSec + nexttime - 15); lottery.setCurNo(lottery.getCurNo()+1); lottery.setCurRes("?,?,?=?"); } }else if (nexttime > 15){ // lottery.setStauts(1); lottery.setNextOpenSec(nexttime - 15); }else{ //提前20s封盘 lottery.setStauts(2); lottery.setNextOpenSec(0); } lottery.setCurPoint(playUser.getGoldcoins()); resu=new PcData("200","请求成功",lottery); }else{ resu=new PcData("201","暂无信息",null); } return new ResponseEntity<>(resu, HttpStatus.OK); } private PcddPeriods getCurLottery(int type){ PcddPeriods pcddPeriods = null; if (type == 1){ pcddPeriods = (PcddPeriods) CacheHelper.getSystemCacheBean().getCacheObject(BMDataContext.BET_TYPE_BJ_LOTTERY, BMDataContext.SYSTEM_ORGI); if (pcddPeriods == null){ Iterator<PcddPeriods> iterator = pcddPeriodsESRepository.findByType(type,new Sort(Sort.Direction.DESC, "periods")).iterator(); if (iterator.hasNext()){ pcddPeriods = iterator.next(); CacheHelper.getSystemCacheBean().put(BMDataContext.BET_TYPE_BJ_LOTTERY,pcddPeriods,BMDataContext.SYSTEM_ORGI); } } }else{ pcddPeriods = (PcddPeriods) CacheHelper.getSystemCacheBean().getCacheObject(BMDataContext.BET_TYPE_JND_LOTTERY, BMDataContext.SYSTEM_ORGI); if (pcddPeriods == null){ Iterator<PcddPeriods> iterator = pcddPeriodsESRepository.findByType(type,new Sort(Sort.Direction.DESC, "periods")).iterator(); if (iterator.hasNext()){ pcddPeriods = iterator.next(); CacheHelper.getSystemCacheBean().put(BMDataContext.BET_TYPE_JND_LOTTERY,pcddPeriods,BMDataContext.SYSTEM_ORGI); } } } return pcddPeriods; } }
40.738739
151
0.634675
cf50ab03bcdc76d5324542013d2a14f4b2682315
3,433
// // 此文件是由 JavaTM Architecture for XML Binding (JAXB) 引用实现 v2.2.8-b130911.1802 生成的 // 请访问 <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // 在重新编译源模式时, 对此文件的所有修改都将丢失。 // 生成时间: 2015.11.18 时间 11:24:52 PM CST // package com.leonoss.jgeotag.gpx; import java.math.BigDecimal; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlType; /** * * Two lat/lon pairs defining the extent of an element. * * * <p>boundsType complex type的 Java 类。 * * <p>以下模式片段指定包含在此类中的预期内容。 * * <pre> * &lt;complexType name="boundsType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;attribute name="minlat" use="required" type="{http://www.topografix.com/GPX/1/1}latitudeType" /> * &lt;attribute name="minlon" use="required" type="{http://www.topografix.com/GPX/1/1}longitudeType" /> * &lt;attribute name="maxlat" use="required" type="{http://www.topografix.com/GPX/1/1}latitudeType" /> * &lt;attribute name="maxlon" use="required" type="{http://www.topografix.com/GPX/1/1}longitudeType" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "boundsType") public class BoundsType { @XmlAttribute(name = "minlat", required = true) protected BigDecimal minlat; @XmlAttribute(name = "minlon", required = true) protected BigDecimal minlon; @XmlAttribute(name = "maxlat", required = true) protected BigDecimal maxlat; @XmlAttribute(name = "maxlon", required = true) protected BigDecimal maxlon; /** * 获取minlat属性的值。 * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getMinlat() { return minlat; } /** * 设置minlat属性的值。 * * @param value * allowed object is * {@link BigDecimal } * */ public void setMinlat(BigDecimal value) { this.minlat = value; } /** * 获取minlon属性的值。 * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getMinlon() { return minlon; } /** * 设置minlon属性的值。 * * @param value * allowed object is * {@link BigDecimal } * */ public void setMinlon(BigDecimal value) { this.minlon = value; } /** * 获取maxlat属性的值。 * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getMaxlat() { return maxlat; } /** * 设置maxlat属性的值。 * * @param value * allowed object is * {@link BigDecimal } * */ public void setMaxlat(BigDecimal value) { this.maxlat = value; } /** * 获取maxlon属性的值。 * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getMaxlon() { return maxlon; } /** * 设置maxlon属性的值。 * * @param value * allowed object is * {@link BigDecimal } * */ public void setMaxlon(BigDecimal value) { this.maxlon = value; } }
22.585526
110
0.56656
29b1afad56306fb51eddf1f2b3aefe320586eaf6
333
package com.lukatu.agenerator.label; /** * Created by vberegovoy on 14.12.16. */ public class LabelRaw extends Label { public enum Type { string; } public final String name; public final Type type; public LabelRaw(String name, Type type) { this.name = name; this.type = type; } }
17.526316
45
0.615616
972ba9586f0db8c13074a87a1274901bec9d3a95
3,762
/* * If not stated otherwise in this file or this component's Licenses.txt file the * following copyright and licenses apply: * * Copyright 2018 RDK Management * * 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. * * Author: rdolomansky * Created: 3/18/16 1:18 PM */ package com.comcast.xconf.thucydides.tests.telemetry; import com.beust.jcommander.internal.Lists; import com.comcast.apps.hesperius.ruleengine.domain.standard.StandardOperation; import com.comcast.xconf.estbfirmware.factory.RuleFactory; import com.comcast.xconf.logupload.telemetry.PermanentTelemetryProfile; import com.comcast.xconf.logupload.telemetry.TelemetryRule; import com.comcast.xconf.thucydides.steps.GenericSteps; import com.comcast.xconf.thucydides.steps.RuleViewSteps; import com.comcast.xconf.thucydides.steps.telemetry.TestFormPageSteps; import com.comcast.xconf.thucydides.util.GenericTestUtils; import com.comcast.xconf.thucydides.util.RuleUtils; import com.comcast.xconf.thucydides.util.TestConstants; import com.comcast.xconf.thucydides.util.telemetry.TelemetryUtils; import net.thucydides.core.annotations.Managed; import net.thucydides.core.annotations.ManagedPages; import net.thucydides.core.annotations.Steps; import net.thucydides.core.pages.Pages; import net.thucydides.junit.runners.ThucydidesRunner; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.openqa.selenium.WebDriver; @RunWith(ThucydidesRunner.class) public class TelemetryTestFormPageTest { @Managed(uniqueSession = false) private WebDriver webdriver; @ManagedPages(defaultUrl = TestConstants.UX_URL + "#") private Pages pages; @Steps private TestFormPageSteps testFormPageSteps; @Steps private RuleViewSteps ruleViewSteps; @Steps private GenericSteps genericSteps; @Before @After public void cleanup() throws Exception { GenericTestUtils.deleteEntities(TelemetryUtils.PERMANENT_PROFILE_URL, PermanentTelemetryProfile.class); GenericTestUtils.deleteEntities(TelemetryUtils.TARGETING_RULE_URL, TelemetryRule.class); } @Test public void testTelemetryTestPage() throws Exception { PermanentTelemetryProfile telemetryProfile = TelemetryUtils.createAndSavePermanentTelemetryProfile("profile123"); String modelId = "MODEL_ID"; String envId = "ENV_ID"; String firmwareVersion = "FIRMWARE_VERSION"; TelemetryUtils.createAndSaveTargetingRule(telemetryProfile.getId(), Lists.newArrayList( RuleUtils.createCondition(RuleFactory.MODEL, StandardOperation.IS, modelId), RuleUtils.createCondition(RuleFactory.ENV, StandardOperation.IS, envId), RuleUtils.createCondition(RuleFactory.VERSION, StandardOperation.IS, firmwareVersion) )); testFormPageSteps.open() .typeKey(RuleFactory.ENV.getName()).clickTypeaheadListItem(RuleFactory.ENV.getName()) .typeValue(envId) .clickTestButton() .waitRuleViewDirective(); ruleViewSteps.verifyFreeArg("model"); } }
40.451613
122
0.736045
1184649020258b3c16c89c5058eb627a19839e1f
265
public class PapagaioInterface extends AveInterface{ @Override public void emitirSom(){ System.out.println("piu piu piu"); } @Override public void voar(){ System.out.println("O papagaio esta voando"); } }
13.947368
53
0.588679
6819e4d79aea33654608821de985131abc18b00b
1,029
package com.sunzequn.sdfs.socket.client; import java.io.InputStream; import java.io.ObjectInputStream; import java.net.Socket; /** * Created by Sloriac on 2016/12/16. */ public class ReceiveHandler extends Thread { private Socket socket; private SockClient client; public ReceiveHandler(Socket socket, SockClient client) { this.socket = socket; this.client = client; } @Override public void run() { while (true) { try { if (socket.isClosed()) return; InputStream in = socket.getInputStream(); if (in.available() > 0) { ObjectInputStream ois = new ObjectInputStream(in); Object obj = ois.readObject(); client.receive(obj); } else { Thread.sleep(500); } } catch (Exception e) { e.printStackTrace(); stop(); } } } }
24.5
70
0.511176
fa79f5b9427f7a3a5a8001f22c991d25453d749c
1,513
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. package com.microsoft.commondatamodel.objectmodel.cdm.cdmtraitdefinition; import com.microsoft.commondatamodel.objectmodel.cdm.CdmTraitDefinition; import com.microsoft.commondatamodel.objectmodel.cdm.CdmTraitReference; import com.microsoft.commondatamodel.objectmodel.cdm.CdmCorpusDefinition; import org.testng.Assert; import org.testng.annotations.Test; public class CdmTraitDefinitionTest { @Test public void testExtendsTraitPropertyOptional() { final CdmCorpusDefinition corpus = new CdmCorpusDefinition(); final CdmTraitReference extendTraitRef1 = new CdmTraitReference(corpus.getCtx(), "testExtendTraitName1", true, false); final CdmTraitReference extendTraitRef2 = new CdmTraitReference(corpus.getCtx(), "testExtendTraitName2", true, false); final CdmTraitDefinition traitDefinition = new CdmTraitDefinition(corpus.getCtx(), "testTraitName", extendTraitRef1); Assert.assertEquals(extendTraitRef1, traitDefinition.getExtendsTrait()); traitDefinition.setExtendsTrait(null); Assert.assertNull(traitDefinition.getExtendsTrait()); traitDefinition.setExtendsTrait(extendTraitRef2); Assert.assertEquals(extendTraitRef2, traitDefinition.getExtendsTrait()); traitDefinition.setExtendsTrait(null); Assert.assertNull(traitDefinition.getExtendsTrait()); } }
52.172414
126
0.787839
3560e2161ebf025b16840f95065910ebc51a31d4
604
package com.imooc.file; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; public class FileInputDemo1 { public static void main(String[] args) { try { FileInputStream fis = new FileInputStream("E:\\my_JavaIO\\imooc.txt"); // int n=fis.read(); int n=0; // while(n!=-1) { // System.out.print((char)n); // n=fis.read(); // } while((n=fis.read())!=-1) { System.out.print((char)n); } fis.close(); } catch (FileNotFoundException e) { e.printStackTrace(); }catch(IOException e) { e.printStackTrace(); } } }
20.133333
73
0.630795
b7f53b54859a76ead9ea02d0f1e51666fc2527d6
1,954
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package edu.pse.beast.codearea.ErrorHandling; import java.util.ArrayList; import javax.swing.JTextPane; /** * This class facillitates communication between the various error finders * and error displays. Whenever the concurrently running error finder find * a new error, it receives a message. It then asks the injected error * displayer to display the codeerror on the pane. * @author Holger-Desktop */ public class ErrorController { private ErrorFinderList errorFinderList; private JTextPane pane; private ErrorDisplayer displayer; private boolean changed = false; private int currentCaretPos; private ErrorFinderThread t; public ErrorController(JTextPane pane, ErrorDisplayer displayer) { this.pane = pane; errorFinderList = new ErrorFinderList(); this.displayer = displayer; t = new ErrorFinderThread(errorFinderList, pane, this); int i = 0; } /** * stops the concurrently running errorfinder */ public void stopThread() { t.stop(); } public void addErrorFinder(ErrorFinder finder) { errorFinderList.add(finder); } public ErrorDisplayer getDisplayer() { return displayer; } public ErrorFinderList getErrorFinderList() { return errorFinderList; } /** * this function is called by error finder classes if they find new errors * @param lastFoundErrors the list of newly found errors */ public void foundNewErrors(ArrayList<CodeError> lastFoundErrors) { displayer.showErrors(lastFoundErrors); } public void pauseErrorFinding() { t.pauseChecking(); } public void resumeErrorFinding() { t.resumeChecking(); } }
27.521127
79
0.683214
d2fbfd9bcf1120e34ee53724708597d1405c2919
2,303
/* * Copyright 2018-2020 The Code Department. * * 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.tcdng.unify.core.util; import java.lang.reflect.Method; /** * Getter setter information. * * @author Lateef Ojulari * @since 1.0 */ public class GetterSetterInfo { private String name; private Method getter; private Method setter; private Class<?> type; private Class<?> argumentType0; private Class<?> argumentType1; private boolean field; public GetterSetterInfo(String name, Method getter, Method setter, Class<?> type, Class<?> argumentType0, Class<?> argumentType1, boolean field) { this.name = name; this.getter = getter; this.setter = setter; this.type = type; this.argumentType0 = argumentType0; this.argumentType1 = argumentType1; this.field = field; } public String getName() { return name; } public Method getGetter() { return getter; } public Method getSetter() { return setter; } public Class<?> getType() { return type; } public Class<?> getArgumentType0() { return argumentType0; } public Class<?> getArgumentType1() { return argumentType1; } public boolean isGetter() { return this.getter != null; } public boolean isSetter() { return this.setter != null; } public boolean isParameterArgumented0() { return this.argumentType0 != null; } public boolean isParameterArgumented1() { return this.argumentType1 != null; } public boolean isProperty() { return field; } }
23.742268
110
0.616153
fd76efedea7c02d1ee615ec6ea831e135174553a
34,999
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ end_comment begin_package DECL|package|org.apache.hadoop.fs.azure.integration package|package name|org operator|. name|apache operator|. name|hadoop operator|. name|fs operator|. name|azure operator|. name|integration package|; end_package begin_import import|import name|java operator|. name|io operator|. name|BufferedReader import|; end_import begin_import import|import name|java operator|. name|io operator|. name|BufferedWriter import|; end_import begin_import import|import name|java operator|. name|io operator|. name|IOException import|; end_import begin_import import|import name|java operator|. name|io operator|. name|InputStreamReader import|; end_import begin_import import|import name|java operator|. name|io operator|. name|OutputStreamWriter import|; end_import begin_import import|import name|java operator|. name|net operator|. name|URI import|; end_import begin_import import|import name|java operator|. name|util operator|. name|List import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|Assert import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|Assume import|; end_import begin_import import|import name|org operator|. name|junit operator|. name|internal operator|. name|AssumptionViolatedException import|; end_import begin_import import|import name|org operator|. name|slf4j operator|. name|Logger import|; end_import begin_import import|import name|org operator|. name|slf4j operator|. name|LoggerFactory import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|commons operator|. name|lang3 operator|. name|StringUtils import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|conf operator|. name|Configuration import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|fs operator|. name|FSDataInputStream import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|fs operator|. name|FSDataOutputStream import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|fs operator|. name|FileContext import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|fs operator|. name|FileSystem import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|fs operator|. name|Path import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|fs operator|. name|azure operator|. name|AzureBlobStorageTestAccount import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|fs operator|. name|azure operator|. name|NativeAzureFileSystem import|; end_import begin_import import|import static name|org operator|. name|junit operator|. name|Assume operator|. name|assumeTrue import|; end_import begin_import import|import static name|org operator|. name|apache operator|. name|hadoop operator|. name|fs operator|. name|azure operator|. name|AzureBlobStorageTestAccount operator|. name|WASB_ACCOUNT_NAME_DOMAIN_SUFFIX_REGEX import|; end_import begin_import import|import static name|org operator|. name|apache operator|. name|hadoop operator|. name|fs operator|. name|azure operator|. name|AzureBlobStorageTestAccount operator|. name|WASB_TEST_ACCOUNT_NAME_WITH_DOMAIN import|; end_import begin_import import|import static name|org operator|. name|apache operator|. name|hadoop operator|. name|fs operator|. name|azure operator|. name|integration operator|. name|AzureTestConstants operator|. name|* import|; end_import begin_import import|import static name|org operator|. name|apache operator|. name|hadoop operator|. name|fs operator|. name|azurebfs operator|. name|constants operator|. name|TestConfigurationKeys operator|. name|FS_AZURE_TEST_NAMESPACE_ENABLED_ACCOUNT import|; end_import begin_import import|import static name|org operator|. name|apache operator|. name|hadoop operator|. name|test operator|. name|MetricsAsserts operator|. name|getLongCounter import|; end_import begin_import import|import static name|org operator|. name|apache operator|. name|hadoop operator|. name|test operator|. name|MetricsAsserts operator|. name|getLongGauge import|; end_import begin_import import|import static name|org operator|. name|apache operator|. name|hadoop operator|. name|test operator|. name|MetricsAsserts operator|. name|getMetrics import|; end_import begin_comment comment|/** * Utilities for the Azure tests. Based on {@code S3ATestUtils}, so * (initially) has unused method. */ end_comment begin_class DECL|class|AzureTestUtils specifier|public specifier|final class|class name|AzureTestUtils extends|extends name|Assert block|{ DECL|field|LOG specifier|private specifier|static specifier|final name|Logger name|LOG init|= name|LoggerFactory operator|. name|getLogger argument_list|( name|AzureTestUtils operator|. name|class argument_list|) decl_stmt|; comment|/** * Value to set a system property to (in maven) to declare that * a property has been unset. */ DECL|field|UNSET_PROPERTY specifier|public specifier|static specifier|final name|String name|UNSET_PROPERTY init|= literal|"unset" decl_stmt|; comment|/** * Create the test filesystem. * * If the test.fs.wasb.name property is not set, this will * raise a JUnit assumption exception * * @param conf configuration * @return the FS * @throws IOException IO Problems * @throws AssumptionViolatedException if the FS is not named */ DECL|method|createTestFileSystem (Configuration conf) specifier|public specifier|static name|NativeAzureFileSystem name|createTestFileSystem parameter_list|( name|Configuration name|conf parameter_list|) throws|throws name|IOException block|{ name|String name|fsname init|= name|conf operator|. name|getTrimmed argument_list|( name|TEST_FS_WASB_NAME argument_list|, literal|"" argument_list|) decl_stmt|; name|boolean name|liveTest init|= operator|! name|StringUtils operator|. name|isEmpty argument_list|( name|fsname argument_list|) decl_stmt|; name|URI name|testURI init|= literal|null decl_stmt|; if|if condition|( name|liveTest condition|) block|{ name|testURI operator|= name|URI operator|. name|create argument_list|( name|fsname argument_list|) expr_stmt|; name|liveTest operator|= name|testURI operator|. name|getScheme argument_list|() operator|. name|equals argument_list|( name|WASB_SCHEME argument_list|) expr_stmt|; block|} if|if condition|( operator|! name|liveTest condition|) block|{ comment|// Skip the test throw|throw operator|new name|AssumptionViolatedException argument_list|( literal|"No test filesystem in " operator|+ name|TEST_FS_WASB_NAME argument_list|) throw|; block|} name|NativeAzureFileSystem name|fs1 init|= operator|new name|NativeAzureFileSystem argument_list|() decl_stmt|; name|fs1 operator|. name|initialize argument_list|( name|testURI argument_list|, name|conf argument_list|) expr_stmt|; return|return name|fs1 return|; block|} comment|/** * Create a file context for tests. * * If the test.fs.wasb.name property is not set, this will * trigger a JUnit failure. * * Multipart purging is enabled. * @param conf configuration * @return the FS * @throws IOException IO Problems * @throws AssumptionViolatedException if the FS is not named */ DECL|method|createTestFileContext (Configuration conf) specifier|public specifier|static name|FileContext name|createTestFileContext parameter_list|( name|Configuration name|conf parameter_list|) throws|throws name|IOException block|{ name|String name|fsname init|= name|conf operator|. name|getTrimmed argument_list|( name|TEST_FS_WASB_NAME argument_list|, literal|"" argument_list|) decl_stmt|; name|boolean name|liveTest init|= operator|! name|StringUtils operator|. name|isEmpty argument_list|( name|fsname argument_list|) decl_stmt|; name|URI name|testURI init|= literal|null decl_stmt|; if|if condition|( name|liveTest condition|) block|{ name|testURI operator|= name|URI operator|. name|create argument_list|( name|fsname argument_list|) expr_stmt|; name|liveTest operator|= name|testURI operator|. name|getScheme argument_list|() operator|. name|equals argument_list|( name|WASB_SCHEME argument_list|) expr_stmt|; block|} if|if condition|( operator|! name|liveTest condition|) block|{ comment|// This doesn't work with our JUnit 3 style test cases, so instead we'll comment|// make this whole class not run by default throw|throw operator|new name|AssumptionViolatedException argument_list|( literal|"No test filesystem in " operator|+ name|TEST_FS_WASB_NAME argument_list|) throw|; block|} name|FileContext name|fc init|= name|FileContext operator|. name|getFileContext argument_list|( name|testURI argument_list|, name|conf argument_list|) decl_stmt|; return|return name|fc return|; block|} comment|/** * Get a long test property. *<ol> *<li>Look up configuration value (which can pick up core-default.xml), * using {@code defVal} as the default value (if conf != null). *</li> *<li>Fetch the system property.</li> *<li>If the system property is not empty or "(unset)": * it overrides the conf value. *</li> *</ol> * This puts the build properties in charge of everything. It's not a * perfect design; having maven set properties based on a file, as ant let * you do, is better for customization. * * As to why there's a special (unset) value, see * {@link http://stackoverflow.com/questions/7773134/null-versus-empty-arguments-in-maven} * @param conf config: may be null * @param key key to look up * @param defVal default value * @return the evaluated test property. */ DECL|method|getTestPropertyLong (Configuration conf, String key, long defVal) specifier|public specifier|static name|long name|getTestPropertyLong parameter_list|( name|Configuration name|conf parameter_list|, name|String name|key parameter_list|, name|long name|defVal parameter_list|) block|{ return|return name|Long operator|. name|valueOf argument_list|( name|getTestProperty argument_list|( name|conf argument_list|, name|key argument_list|, name|Long operator|. name|toString argument_list|( name|defVal argument_list|) argument_list|) argument_list|) return|; block|} comment|/** * Get a test property value in bytes, using k, m, g, t, p, e suffixes. * {@link org.apache.hadoop.util.StringUtils.TraditionalBinaryPrefix#string2long(String)} *<ol> *<li>Look up configuration value (which can pick up core-default.xml), * using {@code defVal} as the default value (if conf != null). *</li> *<li>Fetch the system property.</li> *<li>If the system property is not empty or "(unset)": * it overrides the conf value. *</li> *</ol> * This puts the build properties in charge of everything. It's not a * perfect design; having maven set properties based on a file, as ant let * you do, is better for customization. * * As to why there's a special (unset) value, see * {@link http://stackoverflow.com/questions/7773134/null-versus-empty-arguments-in-maven} * @param conf config: may be null * @param key key to look up * @param defVal default value * @return the evaluated test property. */ DECL|method|getTestPropertyBytes (Configuration conf, String key, String defVal) specifier|public specifier|static name|long name|getTestPropertyBytes parameter_list|( name|Configuration name|conf parameter_list|, name|String name|key parameter_list|, name|String name|defVal parameter_list|) block|{ return|return name|org operator|. name|apache operator|. name|hadoop operator|. name|util operator|. name|StringUtils operator|. name|TraditionalBinaryPrefix operator|. name|string2long argument_list|( name|getTestProperty argument_list|( name|conf argument_list|, name|key argument_list|, name|defVal argument_list|) argument_list|) return|; block|} comment|/** * Get an integer test property; algorithm described in * {@link #getTestPropertyLong(Configuration, String, long)}. * @param key key to look up * @param defVal default value * @return the evaluated test property. */ DECL|method|getTestPropertyInt (Configuration conf, String key, int defVal) specifier|public specifier|static name|int name|getTestPropertyInt parameter_list|( name|Configuration name|conf parameter_list|, name|String name|key parameter_list|, name|int name|defVal parameter_list|) block|{ return|return operator|( name|int operator|) name|getTestPropertyLong argument_list|( name|conf argument_list|, name|key argument_list|, name|defVal argument_list|) return|; block|} comment|/** * Get a boolean test property; algorithm described in * {@link #getTestPropertyLong(Configuration, String, long)}. * @param key key to look up * @param defVal default value * @return the evaluated test property. */ DECL|method|getTestPropertyBool (Configuration conf, String key, boolean defVal) specifier|public specifier|static name|boolean name|getTestPropertyBool parameter_list|( name|Configuration name|conf parameter_list|, name|String name|key parameter_list|, name|boolean name|defVal parameter_list|) block|{ return|return name|Boolean operator|. name|valueOf argument_list|( name|getTestProperty argument_list|( name|conf argument_list|, name|key argument_list|, name|Boolean operator|. name|toString argument_list|( name|defVal argument_list|) argument_list|) argument_list|) return|; block|} comment|/** * Get a string test property. *<ol> *<li>Look up configuration value (which can pick up core-default.xml), * using {@code defVal} as the default value (if conf != null). *</li> *<li>Fetch the system property.</li> *<li>If the system property is not empty or "(unset)": * it overrides the conf value. *</li> *</ol> * This puts the build properties in charge of everything. It's not a * perfect design; having maven set properties based on a file, as ant let * you do, is better for customization. * * As to why there's a special (unset) value, see * @see<a href="http://stackoverflow.com/questions/7773134/null-versus-empty-arguments-in-maven"> * Stack Overflow</a> * @param conf config: may be null * @param key key to look up * @param defVal default value * @return the evaluated test property. */ DECL|method|getTestProperty (Configuration conf, String key, String defVal) specifier|public specifier|static name|String name|getTestProperty parameter_list|( name|Configuration name|conf parameter_list|, name|String name|key parameter_list|, name|String name|defVal parameter_list|) block|{ name|String name|confVal init|= name|conf operator|!= literal|null condition|? name|conf operator|. name|getTrimmed argument_list|( name|key argument_list|, name|defVal argument_list|) else|: name|defVal decl_stmt|; name|String name|propval init|= name|System operator|. name|getProperty argument_list|( name|key argument_list|) decl_stmt|; return|return name|StringUtils operator|. name|isNotEmpty argument_list|( name|propval argument_list|) operator|&& operator|! name|UNSET_PROPERTY operator|. name|equals argument_list|( name|propval argument_list|) condition|? name|propval else|: name|confVal return|; block|} comment|/** * Verify the class of an exception. If it is not as expected, rethrow it. * Comparison is on the exact class, not subclass-of inference as * offered by {@code instanceof}. * @param clazz the expected exception class * @param ex the exception caught * @return the exception, if it is of the expected class * @throws Exception the exception passed in. */ DECL|method|verifyExceptionClass (Class clazz, Exception ex) specifier|public specifier|static name|Exception name|verifyExceptionClass parameter_list|( name|Class name|clazz parameter_list|, name|Exception name|ex parameter_list|) throws|throws name|Exception block|{ if|if condition|( operator|! operator|( name|ex operator|. name|getClass argument_list|() operator|. name|equals argument_list|( name|clazz argument_list|) operator|) condition|) block|{ throw|throw name|ex throw|; block|} return|return name|ex return|; block|} comment|/** * Turn off FS Caching: use if a filesystem with different options from * the default is required. * @param conf configuration to patch */ DECL|method|disableFilesystemCaching (Configuration conf) specifier|public specifier|static name|void name|disableFilesystemCaching parameter_list|( name|Configuration name|conf parameter_list|) block|{ name|conf operator|. name|setBoolean argument_list|( literal|"fs.wasb.impl.disable.cache" argument_list|, literal|true argument_list|) expr_stmt|; block|} comment|/** * Create a test path, using the value of * {@link AzureTestUtils#TEST_UNIQUE_FORK_ID} if it is set. * @param defVal default value * @return a path */ DECL|method|createTestPath (Path defVal) specifier|public specifier|static name|Path name|createTestPath parameter_list|( name|Path name|defVal parameter_list|) block|{ name|String name|testUniqueForkId init|= name|System operator|. name|getProperty argument_list|( name|AzureTestConstants operator|. name|TEST_UNIQUE_FORK_ID argument_list|) decl_stmt|; return|return name|testUniqueForkId operator|== literal|null condition|? name|defVal else|: operator|new name|Path argument_list|( literal|"/" operator|+ name|testUniqueForkId argument_list|, literal|"test" argument_list|) return|; block|} comment|/** * Create a test page blob path using the value of * {@link AzureTestConstants#TEST_UNIQUE_FORK_ID} if it is set. * @param filename filename at the end of the path * @return an absolute path */ DECL|method|blobPathForTests (FileSystem fs, String filename) specifier|public specifier|static name|Path name|blobPathForTests parameter_list|( name|FileSystem name|fs parameter_list|, name|String name|filename parameter_list|) block|{ name|String name|testUniqueForkId init|= name|System operator|. name|getProperty argument_list|( name|AzureTestConstants operator|. name|TEST_UNIQUE_FORK_ID argument_list|) decl_stmt|; return|return name|fs operator|. name|makeQualified argument_list|( operator|new name|Path argument_list|( name|PAGE_BLOB_DIR argument_list|, name|testUniqueForkId operator|== literal|null condition|? name|filename else|: operator|( name|testUniqueForkId operator|+ literal|"/" operator|+ name|filename operator|) argument_list|) argument_list|) return|; block|} comment|/** * Create a test path using the value of * {@link AzureTestConstants#TEST_UNIQUE_FORK_ID} if it is set. * @param filename filename at the end of the path * @return an absolute path */ DECL|method|pathForTests (FileSystem fs, String filename) specifier|public specifier|static name|Path name|pathForTests parameter_list|( name|FileSystem name|fs parameter_list|, name|String name|filename parameter_list|) block|{ name|String name|testUniqueForkId init|= name|System operator|. name|getProperty argument_list|( name|AzureTestConstants operator|. name|TEST_UNIQUE_FORK_ID argument_list|) decl_stmt|; return|return name|fs operator|. name|makeQualified argument_list|( operator|new name|Path argument_list|( name|testUniqueForkId operator|== literal|null condition|? operator|( literal|"/test/" operator|+ name|filename operator|) else|: operator|( name|testUniqueForkId operator|+ literal|"/" operator|+ name|filename operator|) argument_list|) argument_list|) return|; block|} comment|/** * Get a unique fork ID. * Returns a default value for non-parallel tests. * @return a string unique for all test VMs running in this maven build. */ DECL|method|getForkID () specifier|public specifier|static name|String name|getForkID parameter_list|() block|{ return|return name|System operator|. name|getProperty argument_list|( name|AzureTestConstants operator|. name|TEST_UNIQUE_FORK_ID argument_list|, literal|"fork-1" argument_list|) return|; block|} comment|/** * Flag to indicate that this test is being executed in parallel. * This is used by some of the scale tests to validate test time expectations. * @return true if the build indicates this test is being run in parallel. */ DECL|method|isParallelExecution () specifier|public specifier|static name|boolean name|isParallelExecution parameter_list|() block|{ return|return name|Boolean operator|. name|getBoolean argument_list|( name|KEY_PARALLEL_TEST_EXECUTION argument_list|) return|; block|} comment|/** * Asserts that {@code obj} is an instance of {@code expectedClass} using a * descriptive assertion message. * @param expectedClass class * @param obj object to check */ DECL|method|assertInstanceOf (Class<?> expectedClass, Object obj) specifier|public specifier|static name|void name|assertInstanceOf parameter_list|( name|Class argument_list|< name|? argument_list|> name|expectedClass parameter_list|, name|Object name|obj parameter_list|) block|{ name|Assert operator|. name|assertTrue argument_list|( name|String operator|. name|format argument_list|( literal|"Expected instance of class %s, but is %s." argument_list|, name|expectedClass argument_list|, name|obj operator|. name|getClass argument_list|() argument_list|) argument_list|, name|expectedClass operator|. name|isAssignableFrom argument_list|( name|obj operator|. name|getClass argument_list|() argument_list|) argument_list|) expr_stmt|; block|} comment|/** * Builds a comma-separated list of class names. * @param classes list of classes * @return comma-separated list of class names */ DECL|method|buildClassListString ( List<T> classes) specifier|public specifier|static parameter_list|< name|T extends|extends name|Class argument_list|< name|? argument_list|> parameter_list|> name|String name|buildClassListString parameter_list|( name|List argument_list|< name|T argument_list|> name|classes parameter_list|) block|{ name|StringBuilder name|sb init|= operator|new name|StringBuilder argument_list|() decl_stmt|; for|for control|( name|int name|i init|= literal|0 init|; name|i operator|< name|classes operator|. name|size argument_list|() condition|; operator|++ name|i control|) block|{ if|if condition|( name|i operator|> literal|0 condition|) block|{ name|sb operator|. name|append argument_list|( literal|',' argument_list|) expr_stmt|; block|} name|sb operator|. name|append argument_list|( name|classes operator|. name|get argument_list|( name|i argument_list|) operator|. name|getName argument_list|() argument_list|) expr_stmt|; block|} return|return name|sb operator|. name|toString argument_list|() return|; block|} comment|/** * This class should not be instantiated. */ DECL|method|AzureTestUtils () specifier|private name|AzureTestUtils parameter_list|() block|{ } comment|/** * Assert that a configuration option matches the expected value. * @param conf configuration * @param key option key * @param expected expected value */ DECL|method|assertOptionEquals (Configuration conf, String key, String expected) specifier|public specifier|static name|void name|assertOptionEquals parameter_list|( name|Configuration name|conf parameter_list|, name|String name|key parameter_list|, name|String name|expected parameter_list|) block|{ name|assertEquals argument_list|( literal|"Value of " operator|+ name|key argument_list|, name|expected argument_list|, name|conf operator|. name|get argument_list|( name|key argument_list|) argument_list|) expr_stmt|; block|} comment|/** * Assume that a condition is met. If not: log at WARN and * then throw an {@link AssumptionViolatedException}. * @param message message in an assumption * @param condition condition to probe */ DECL|method|assume (String message, boolean condition) specifier|public specifier|static name|void name|assume parameter_list|( name|String name|message parameter_list|, name|boolean name|condition parameter_list|) block|{ if|if condition|( operator|! name|condition condition|) block|{ name|LOG operator|. name|warn argument_list|( name|message argument_list|) expr_stmt|; block|} name|Assume operator|. name|assumeTrue argument_list|( name|message argument_list|, name|condition argument_list|) expr_stmt|; block|} comment|/** * Gets the current value of the given gauge. * @param fs filesystem * @param gaugeName gauge name * @return the gauge value */ DECL|method|getLongGaugeValue (NativeAzureFileSystem fs, String gaugeName) specifier|public specifier|static name|long name|getLongGaugeValue parameter_list|( name|NativeAzureFileSystem name|fs parameter_list|, name|String name|gaugeName parameter_list|) block|{ return|return name|getLongGauge argument_list|( name|gaugeName argument_list|, name|getMetrics argument_list|( name|fs operator|. name|getInstrumentation argument_list|() argument_list|) argument_list|) return|; block|} comment|/** * Gets the current value of the given counter. * @param fs filesystem * @param counterName counter name * @return the counter value */ DECL|method|getLongCounterValue (NativeAzureFileSystem fs, String counterName) specifier|public specifier|static name|long name|getLongCounterValue parameter_list|( name|NativeAzureFileSystem name|fs parameter_list|, name|String name|counterName parameter_list|) block|{ return|return name|getLongCounter argument_list|( name|counterName argument_list|, name|getMetrics argument_list|( name|fs operator|. name|getInstrumentation argument_list|() argument_list|) argument_list|) return|; block|} comment|/** * Delete a path, catching any exception and downgrading to a log message. * @param fs filesystem * @param path path to delete * @param recursive recursive delete? * @throws IOException IO failure. */ DECL|method|deleteQuietly (FileSystem fs, Path path, boolean recursive) specifier|public specifier|static name|void name|deleteQuietly parameter_list|( name|FileSystem name|fs parameter_list|, name|Path name|path parameter_list|, name|boolean name|recursive parameter_list|) throws|throws name|IOException block|{ if|if condition|( name|fs operator|!= literal|null operator|&& name|path operator|!= literal|null condition|) block|{ try|try block|{ name|fs operator|. name|delete argument_list|( name|path argument_list|, name|recursive argument_list|) expr_stmt|; block|} catch|catch parameter_list|( name|IOException name|e parameter_list|) block|{ name|LOG operator|. name|warn argument_list|( literal|"When deleting {}" argument_list|, name|path argument_list|, name|e argument_list|) expr_stmt|; block|} block|} block|} comment|/** * Clean up the test account if non-null; return null to put in the * field. * @param testAccount test account to clean up * @return null * @throws Execption cleanup problems */ DECL|method|cleanup ( AzureBlobStorageTestAccount testAccount) specifier|public specifier|static name|AzureBlobStorageTestAccount name|cleanup parameter_list|( name|AzureBlobStorageTestAccount name|testAccount parameter_list|) throws|throws name|Exception block|{ if|if condition|( name|testAccount operator|!= literal|null condition|) block|{ name|testAccount operator|. name|cleanup argument_list|() expr_stmt|; name|testAccount operator|= literal|null expr_stmt|; block|} return|return literal|null return|; block|} comment|/** * Clean up the test account; any thrown exceptions are caught and * logged. * @param testAccount test account * @return null, so that any fields can be reset. */ DECL|method|cleanupTestAccount ( AzureBlobStorageTestAccount testAccount) specifier|public specifier|static name|AzureBlobStorageTestAccount name|cleanupTestAccount parameter_list|( name|AzureBlobStorageTestAccount name|testAccount parameter_list|) block|{ if|if condition|( name|testAccount operator|!= literal|null condition|) block|{ try|try block|{ name|testAccount operator|. name|cleanup argument_list|() expr_stmt|; block|} catch|catch parameter_list|( name|Exception name|e parameter_list|) block|{ name|LOG operator|. name|error argument_list|( literal|"While cleaning up test account: " argument_list|, name|e argument_list|) expr_stmt|; block|} block|} return|return literal|null return|; block|} comment|/** * Assume that the scale tests are enabled by the relevant system property. */ DECL|method|assumeScaleTestsEnabled (Configuration conf) specifier|public specifier|static name|void name|assumeScaleTestsEnabled parameter_list|( name|Configuration name|conf parameter_list|) block|{ name|boolean name|enabled init|= name|getTestPropertyBool argument_list|( name|conf argument_list|, name|KEY_SCALE_TESTS_ENABLED argument_list|, name|DEFAULT_SCALE_TESTS_ENABLED argument_list|) decl_stmt|; name|assume argument_list|( literal|"Scale test disabled: to enable set property " operator|+ name|KEY_SCALE_TESTS_ENABLED argument_list|, name|enabled argument_list|) expr_stmt|; block|} comment|/** * Check the account name for WASB tests is set correctly and return. */ DECL|method|verifyWasbAccountNameInConfig (Configuration conf) specifier|public specifier|static name|String name|verifyWasbAccountNameInConfig parameter_list|( name|Configuration name|conf parameter_list|) block|{ name|String name|accountName init|= name|conf operator|. name|get argument_list|( name|ACCOUNT_NAME_PROPERTY_NAME argument_list|) decl_stmt|; if|if condition|( name|accountName operator|== literal|null condition|) block|{ name|accountName operator|= name|conf operator|. name|get argument_list|( name|WASB_TEST_ACCOUNT_NAME_WITH_DOMAIN argument_list|) expr_stmt|; block|} name|assumeTrue argument_list|( literal|"Account for WASB is missing or it is not in correct format" argument_list|, name|accountName operator|!= literal|null operator|&& operator|! name|accountName operator|. name|endsWith argument_list|( name|WASB_ACCOUNT_NAME_DOMAIN_SUFFIX_REGEX argument_list|) argument_list|) expr_stmt|; return|return name|accountName return|; block|} comment|/** * Write string into a file. */ DECL|method|writeStringToFile (FileSystem fs, Path path, String value) specifier|public specifier|static name|void name|writeStringToFile parameter_list|( name|FileSystem name|fs parameter_list|, name|Path name|path parameter_list|, name|String name|value parameter_list|) throws|throws name|IOException block|{ name|FSDataOutputStream name|outputStream init|= name|fs operator|. name|create argument_list|( name|path argument_list|, literal|true argument_list|) decl_stmt|; name|writeStringToStream argument_list|( name|outputStream argument_list|, name|value argument_list|) expr_stmt|; block|} comment|/** * Write string into a file. */ DECL|method|writeStringToStream (FSDataOutputStream outputStream, String value) specifier|public specifier|static name|void name|writeStringToStream parameter_list|( name|FSDataOutputStream name|outputStream parameter_list|, name|String name|value parameter_list|) throws|throws name|IOException block|{ name|BufferedWriter name|writer init|= operator|new name|BufferedWriter argument_list|( operator|new name|OutputStreamWriter argument_list|( name|outputStream argument_list|) argument_list|) decl_stmt|; name|writer operator|. name|write argument_list|( name|value argument_list|) expr_stmt|; name|writer operator|. name|close argument_list|() expr_stmt|; block|} comment|/** * Read string from a file. */ DECL|method|readStringFromFile (FileSystem fs, Path testFile) specifier|public specifier|static name|String name|readStringFromFile parameter_list|( name|FileSystem name|fs parameter_list|, name|Path name|testFile parameter_list|) throws|throws name|IOException block|{ name|FSDataInputStream name|inputStream init|= name|fs operator|. name|open argument_list|( name|testFile argument_list|) decl_stmt|; name|String name|ret init|= name|readStringFromStream argument_list|( name|inputStream argument_list|) decl_stmt|; name|inputStream operator|. name|close argument_list|() expr_stmt|; return|return name|ret return|; block|} comment|/** * Read string from stream. */ DECL|method|readStringFromStream (FSDataInputStream inputStream) specifier|public specifier|static name|String name|readStringFromStream parameter_list|( name|FSDataInputStream name|inputStream parameter_list|) throws|throws name|IOException block|{ name|BufferedReader name|reader init|= operator|new name|BufferedReader argument_list|( operator|new name|InputStreamReader argument_list|( name|inputStream argument_list|) argument_list|) decl_stmt|; specifier|final name|int name|BUFFER_SIZE init|= literal|1024 decl_stmt|; name|char index|[] name|buffer init|= operator|new name|char index|[ name|BUFFER_SIZE index|] decl_stmt|; name|int name|count init|= name|reader operator|. name|read argument_list|( name|buffer argument_list|, literal|0 argument_list|, name|BUFFER_SIZE argument_list|) decl_stmt|; if|if condition|( name|count operator|> name|BUFFER_SIZE condition|) block|{ throw|throw operator|new name|IOException argument_list|( literal|"Exceeded buffer size" argument_list|) throw|; block|} name|inputStream operator|. name|close argument_list|() expr_stmt|; return|return operator|new name|String argument_list|( name|buffer argument_list|, literal|0 argument_list|, name|count argument_list|) return|; block|} comment|/** * Assume hierarchical namespace is disabled for test account. */ DECL|method|assumeNamespaceDisabled (Configuration conf) specifier|public specifier|static name|void name|assumeNamespaceDisabled parameter_list|( name|Configuration name|conf parameter_list|) block|{ name|Assume operator|. name|assumeFalse argument_list|( literal|"Hierarchical namespace is enabled for test account." argument_list|, name|conf operator|. name|getBoolean argument_list|( name|FS_AZURE_TEST_NAMESPACE_ENABLED_ACCOUNT argument_list|, literal|false argument_list|) argument_list|) expr_stmt|; block|} block|} end_class end_unit
18.726057
986
0.782051
a430a294f868d85a6e29d1453edab4f1d0248b97
531
package mazes.svg; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public final class SVGComment implements SVGElement { private final List<String> content; public SVGComment(List<String> content) { this.content = content; } public SVGComment(String content) { this.content = Arrays.asList(content.split("\\n")); } @Override public List<String> toSVGCode() { List<String> code = new ArrayList<>(); code.add("<!--"); code.addAll(content); code.add("-->"); return code; } }
19.666667
53
0.691149
6bcb9a39f6a52fa1af449ab1e23a8843fe1dfa78
955
package com.yiie.utils; /** * Time:2020-1-4 1:39 * Email: [email protected] * Desc: * * @author: yiie * @version:1.0.0 */ public class CodeUtil { private static final String DEPT_TPYE="YXD"; private static final String PERMISSION_TPYE="YXP"; /** *右补位,左对齐 * @param oriStr 原字符串 * @param len 目标字符串长度 * @param alexin 补位字符 * @return */ public static String padRight(String oriStr,int len,String alexin){ String str = ""; int strlen = oriStr.length(); if(strlen < len){ for(int i=0;i<len-strlen;i++){ str=str+alexin; } } str=str+oriStr; return str; } /** * 获取机构编码 YXD0001 * @param oriStr 初始值 * @param len 位数 * @param alexin 补齐字符 * @return */ public static String deptCode(String oriStr,int len,String alexin){ return DEPT_TPYE+padRight(oriStr, len, alexin); } }
20.76087
72
0.553927
820e41bf7c393b59b9daf1ad28b7361916783471
4,337
package br.usp.ime.retrobreaker.forms; import android.util.Log; import br.usp.ime.retrobreaker.game.Game.State; public class MobileBrick extends Brick { private int mFramesToWait; //number of frames update to wait until the brick move again. private int mToWait; //countdown (which starts with mFramesToWait) that says when the the mobile brick can move (mToWait == 0) private float mSpeedX; //the mobile brick only moves in the X axis. It stores the increment in the movement. private boolean mCollided; //flat to say when the brick hit the wall or another brick. //used to index the global vector of bricks (mBricks) in Game private int mIndexI, mIndexJ; public MobileBrick(float[] colors, float posX, float posY, Type type, int wait, int i, int j, float speedX) { super(colors, posX, posY, type); mCollided = false; mIndexI = i; mIndexJ = j; //Basically, we have two ways to set brick's speed: the number of frames without moving the ball and the increment in the movement. mToWait = mFramesToWait = wait; mSpeedX = speedX; } public int getIndexI() { return mIndexI; } public int getIndexJ() { return mIndexJ; } public void move() { if (mToWait == 0) { if (mCollided) mSpeedX *= 2; //I want to get out very quickly from the collision area Log.v(TAG, "Moving MobileBrick[" + mIndexI + "][" + mIndexJ + "], speed: " + mSpeedX + ", posX: " + mPosX); mPosX += mSpeedX; if (mCollided) { mSpeedX /= 2; //restore the normal value mCollided = false; } mToWait = mFramesToWait; } mToWait--; } /* * I only invert the direction when the ball is ready to move. This is necessary because a lot of frame updates can happen between two movements * of the brick, so the brick could change its direction a lot of times which could lead the brick to get the wrong direction. */ public void invertDirection() { if (mToWait == 0) { Log.v(TAG, "Inverted MobileBrick[" + mIndexI + "][" + mIndexJ + "]"); mSpeedX *= -1; } } /* * I only detect collision between the bricks when this brick is ready to move. * See the comments above the invertDirection() function. */ public boolean detectCollisionWithBrick(Brick other) { if (mToWait > 0) return false; if (this.getTopY() >= other.getBottomY() && this.getBottomY() <= other.getTopY() && //this isn't necessary, but we keep it to make compatible with other detection codes. this.getRightX() >= other.getLeftX() && this.getLeftX() <= other.getRightX()) { if (this.getLeftX() < other.getLeftX()) { //collided with the right brick if (mSpeedX < 0) mSpeedX *= -1; //hack: the brick should be moving to the right as it collided with the right brick Log.v(TAG, "Collided in the right brick, MobileBrick[" + mIndexI + "][" + mIndexJ + "]"); } else { //collided with the left brick if (mSpeedX > 0) mSpeedX *= -1; //hack: the brick should be moving to the left as it collided with the left brick Log.v(TAG, "Collided in the left brick, MobileBrick[" + mIndexI + "][" + mIndexJ + "]"); } mCollided = true; return true; } else return false; } /* * I only detect collision between the brick and wall when the brick is ready to move. * See the comments above the invertDirection() function. */ public boolean detectCollisionWithWall() { if (mToWait > 0) return false; if ((this.getRightX() >= State.getScreenHigherX()) // collided with the right wall || (this.getLeftX() <= State.getScreenLowerX())) { // collided with the left wall if (this.getRightX() >= State.getScreenHigherX()) { // collided with the right wall if (mSpeedX < 0) mSpeedX *= -1; //hack: the brick should be moving to the right as it collided with the right wall Log.v(TAG, "Collided in the right wall, MobileBrick[" + mIndexI + "][" + mIndexJ + "]"); } else { //collided with the left wall if (mSpeedX > 0) mSpeedX *= -1; //hack: the brick should be moving to the left as it collided with the left wall Log.v(TAG, "Collided in the left wall, MobileBrick[" + mIndexI + "][" + mIndexJ + "]"); } mCollided = true; return true; } else return false; } public boolean equal(int i, int j) { if ((mIndexI == i) && (mIndexJ == j)){ return true; } else { return false; } } }
37.713043
171
0.66267
c790f57d737415c51fa213aeed8a5bb030804f22
7,069
package mx.ipn.escom.prueba.coffeeapp.viewmodel; import android.app.Application; import android.util.Log; import java.lang.reflect.Field; import java.net.ConnectException; import java.net.SocketTimeoutException; import java.util.concurrent.ExecutionException; import androidx.lifecycle.LiveData; import androidx.lifecycle.MutableLiveData; import androidx.lifecycle.ViewModel; import mx.ipn.escom.prueba.coffeeapp.business.SignUpBusiness; import mx.ipn.escom.prueba.coffeeapp.constants.Constants; import mx.ipn.escom.prueba.coffeeapp.constants.ErroresGeneralesConstants; import mx.ipn.escom.prueba.coffeeapp.constants.FieldErrorContants; import mx.ipn.escom.prueba.coffeeapp.constants.NetWorkConstants; import mx.ipn.escom.prueba.coffeeapp.entities.Persona; import mx.ipn.escom.prueba.coffeeapp.entities.PostResponse; import mx.ipn.escom.prueba.coffeeapp.exception.ConexionNoDisponibleException; import mx.ipn.escom.prueba.coffeeapp.exception.CuentaExisteException; import mx.ipn.escom.prueba.coffeeapp.ui.UiUitls; public class SignUpViewModel extends ViewModel { /*Cadenas*/ public MutableLiveData<String> nombrePersona = new MutableLiveData<>(); public MutableLiveData<String> primerApellido = new MutableLiveData<>(); public MutableLiveData<String> segundoApellido = new MutableLiveData<>(); public MutableLiveData<String> correoElectronico = new MutableLiveData<>(); public MutableLiveData<String> nombreUsuario = new MutableLiveData<>(); public MutableLiveData<String> contrasena = new MutableLiveData<>(); /*Errores*/ private MutableLiveData<Integer> errorGeneral = new MutableLiveData<>(); private MutableLiveData<Integer> errorNombrePersona = new MutableLiveData<>(); private MutableLiveData<Integer> errorPrimerApellido = new MutableLiveData<>(); private MutableLiveData<Integer> errorSegundoApellido = new MutableLiveData<>(); private MutableLiveData<Integer> errorCorreoElectronico = new MutableLiveData<>(); private MutableLiveData<Integer> errorNombreUsuario = new MutableLiveData<>(); private MutableLiveData<Integer> errorContrasena = new MutableLiveData<>(); private SignUpBusiness signUpBusiness; private MutableLiveData<PostResponse> postResponseMutableLiveData; public SignUpViewModel(){ } public void setSignUpBusiness(Application application){ this.signUpBusiness = new SignUpBusiness(application); } public LiveData<PostResponse> getPostResponseMutableLiveData() { if (postResponseMutableLiveData == null) postResponseMutableLiveData = new MutableLiveData<>(); return postResponseMutableLiveData; } public LiveData<Integer> getErrorGeneral() { if (errorGeneral == null) errorGeneral = new MutableLiveData<>(); return errorGeneral; } public LiveData<Integer> getErrorNombrePersona() { if (errorNombrePersona == null) errorNombrePersona = new MutableLiveData<>(); return errorNombrePersona; } public LiveData<Integer> getErrorPrimerApellido() { if (errorPrimerApellido == null) errorPrimerApellido = new MutableLiveData<>(); return errorPrimerApellido; } public LiveData<Integer> getErrorSegundoApellido() { if (errorSegundoApellido == null) errorSegundoApellido = new MutableLiveData<>(); return errorSegundoApellido; } public LiveData<Integer> getErrorCorreoElectronico() { if (errorCorreoElectronico== null) errorCorreoElectronico = new MutableLiveData<>(); return errorCorreoElectronico; } public LiveData<Integer> getErrorNombreUsuario() { if (errorNombreUsuario == null) errorNombreUsuario = new MutableLiveData<>(); return errorNombreUsuario; } public LiveData<Integer> getErrorContrasena() { if (errorContrasena == null) errorContrasena = new MutableLiveData<>(); return errorContrasena; } /** * Realiza la inserción del registro en la BD * * @return * */ public boolean onSignUp(){ if (validateUi()){ try{ PostResponse postResponse = signUpBusiness.onSignUp( nombrePersona.getValue() , primerApellido.getValue() , segundoApellido.getValue() , correoElectronico.getValue() , nombreUsuario.getValue() , contrasena.getValue()); postResponseMutableLiveData.setValue(postResponse); }catch (CuentaExisteException e){ e.printStackTrace(); errorGeneral.setValue(Constants.CUENTA_EXISTE); } catch (SocketTimeoutException | ExecutionException | InterruptedException e){ e.printStackTrace(); errorGeneral.setValue(NetWorkConstants.TIEMPO_LIMITE); }catch (ConnectException | ConexionNoDisponibleException e){ e.printStackTrace(); errorGeneral.setValue(NetWorkConstants.CONEXION_NO_DISPONIBLE); }catch (Exception e){ e.printStackTrace(); } }else{ errorGeneral.setValue(ErroresGeneralesConstants.SIGUNP_INVALIDO); } return true; } /** * * @return Regresa true si la pantalla tiene la entrada de datos correcta, * devuelve false si existe almenos un error en la pantalla. * */ private boolean validateUi(){ boolean validated = true; errorNombrePersona.setValue(UiUitls.stringValidate(nombrePersona.getValue(),null)); errorPrimerApellido.setValue(UiUitls.stringValidate(primerApellido.getValue(),null)); errorSegundoApellido.setValue(UiUitls.stringValidate(segundoApellido.getValue(),null)); errorCorreoElectronico.setValue(UiUitls.stringValidate(correoElectronico.getValue(),null)); errorNombreUsuario.setValue(UiUitls.stringValidate(nombreUsuario.getValue(),null)); errorContrasena.setValue(UiUitls.stringValidate(contrasena.getValue(),null)); if (!errorNombrePersona.getValue().equals(FieldErrorContants.SIN_ERRORES)) validated = false; if (!errorPrimerApellido.getValue().equals(FieldErrorContants.SIN_ERRORES)) validated = false; if (!errorSegundoApellido.getValue().equals(FieldErrorContants.SIN_ERRORES)) validated = false; if (!errorContrasena.getValue().equals(FieldErrorContants.SIN_ERRORES)) validated = false; if (!errorNombreUsuario.getValue().equals(FieldErrorContants.SIN_ERRORES)) validated = false; if (!errorContrasena.getValue().equals(FieldErrorContants.SIN_ERRORES)) validated = false; return validated; } }
42.329341
99
0.677889
0926969cda7d3efcbbf9b6bc886e093db181ba6a
15,901
package ru.kontur.vostok.hercules.gate.client; import org.apache.http.HttpEntity; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.entity.ContentType; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.DefaultHttpRequestRetryHandler; import org.apache.http.impl.client.HttpClientBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import ru.kontur.vostok.hercules.gate.client.exception.BadRequestException; import ru.kontur.vostok.hercules.gate.client.exception.HttpProtocolException; import ru.kontur.vostok.hercules.gate.client.exception.UnavailableClusterException; import ru.kontur.vostok.hercules.gate.client.exception.UnavailableHostException; import ru.kontur.vostok.hercules.util.concurrent.Topology; import ru.kontur.vostok.hercules.util.properties.PropertyDescription; import ru.kontur.vostok.hercules.util.properties.PropertyDescriptions; import ru.kontur.vostok.hercules.util.validation.IntegerValidators; import java.io.Closeable; import java.io.IOException; import java.util.Properties; import java.util.Random; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; /** * Client for Hercules Gateway API * * @author Daniil Zhenikhov */ public class GateClient implements Closeable { private static final Logger LOGGER = LoggerFactory.getLogger(GateClient.class); private static final Random RANDOM = new Random(); private static final String PING = "/ping"; private static final String SEND_ACK = "/stream/send"; private static final String SEND_ASYNC = "/stream/sendAsync"; private final CloseableHttpClient client; private final BlockingQueue<GreyListTopologyElement> greyList; private final Topology<String> whiteList; private final int greyListElementsRecoveryTimeMs; private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); public GateClient(Properties properties, CloseableHttpClient client, Topology<String> whiteList) { this.greyListElementsRecoveryTimeMs = Props.GREY_LIST_ELEMENTS_RECOVERY_TIME_MS.extract(properties); this.client = client; this.whiteList = whiteList; this.greyList = new ArrayBlockingQueue<>(whiteList.size()); scheduler.scheduleWithFixedDelay(this::updateTopology, greyListElementsRecoveryTimeMs, greyListElementsRecoveryTimeMs, TimeUnit.MILLISECONDS); } public GateClient(Properties properties, Topology<String> whiteList) { final int requestTimeout = Props.REQUEST_TIMEOUT.extract(properties); final int connectionTimeout = Props.CONNECTION_TIMEOUT.extract(properties); final int connectionCount = Props.CONNECTION_COUNT.extract(properties); this.greyListElementsRecoveryTimeMs = Props.GREY_LIST_ELEMENTS_RECOVERY_TIME_MS.extract(properties); this.whiteList = whiteList; this.greyList = new ArrayBlockingQueue<>(whiteList.size()); this.client = createHttpClient(requestTimeout, connectionTimeout, connectionCount); scheduler.scheduleWithFixedDelay(this::updateTopology, greyListElementsRecoveryTimeMs, greyListElementsRecoveryTimeMs, TimeUnit.MILLISECONDS); } /** * Request to {@value #PING} * * @param url Gate Url * @throws BadRequestException throws if was error on client side: 4xx errors or http protocol errors * @throws UnavailableHostException throws if was error on server side: 5xx errors or connection errors */ public void ping(String url) throws BadRequestException, UnavailableHostException, HttpProtocolException { sendToHost(url, urlParam -> { HttpGet httpGet = new HttpGet(urlParam + PING); return sendRequest(httpGet); }); } /** * Request to {@value #SEND_ASYNC} * * @param url Gate url * @param apiKey key for sending * @param stream topic name in kafka * @param data payload * @throws BadRequestException throws if was error on client side: 4xx errors or http protocol errors * @throws UnavailableHostException throws if was error on server side: 5xx errors or connection errors */ public void sendAsync(String url, String apiKey, String stream, final byte[] data) throws BadRequestException, UnavailableHostException, HttpProtocolException { sendToHost(url, urlParam -> { HttpPost httpPost = buildRequest(url, apiKey, SEND_ASYNC, stream, data); return sendRequest(httpPost); }); } /** * Request to {@value #SEND_ACK} * * @param url Gate url * @param apiKey key for sending * @param stream topic name in kafka * @param data payload * @throws BadRequestException throws if was error on client side: 4xx errors or http protocol errors * @throws UnavailableHostException throws if was error on server side: 5xx errors or connection errors */ public void send(String url, String apiKey, String stream, final byte[] data) throws BadRequestException, UnavailableHostException, HttpProtocolException { sendToHost(url, urlParam -> { HttpPost httpPost = buildRequest(url, apiKey, SEND_ACK, stream, data); return sendRequest(httpPost); }); } /** * Request to {@value #PING} * * @param retryLimit count of attempt to send data to one of the <code>urls</code>' hosts * @throws BadRequestException throws if was error on client side: 4xx errors or http protocol errors * @throws UnavailableClusterException throws if was error on addresses pool side: no one of address is unavailable */ public void ping(int retryLimit) throws BadRequestException, UnavailableClusterException { sendToPool(retryLimit, this::ping); } /** * Request to {@value #SEND_ASYNC} * * @param retryLimit count of attempt to send data to one of the <code>urls</code>' hosts * @param apiKey key for sending * @param stream topic name in kafka * @param data payload * @throws BadRequestException throws if was error on client side: 4xx errors or http protocol errors * @throws UnavailableClusterException throws if was error on addresses pool side: no one of address is unavailable */ public void sendAsync(int retryLimit, String apiKey, String stream, final byte[] data) throws BadRequestException, UnavailableClusterException { sendToPool(retryLimit, url -> sendAsync(url, apiKey, stream, data)); } /** * Request to {@value #SEND_ACK} * * @param retryLimit count of attempt to send data to one of the <code>urls</code>' hosts * @param apiKey key for sending * @param stream topic name in kafka * @param data payload * @throws BadRequestException throws if was error on client side: 4xx errors or http protocol errors * @throws UnavailableClusterException throws if was error on addresses pool side: no one of address is unavailable */ public void send(int retryLimit, String apiKey, String stream, final byte[] data) throws BadRequestException, UnavailableClusterException { sendToPool(retryLimit, url -> send(url, apiKey, stream, data)); } /** * Request to {@value #PING}. Count of retry is <code>whitelist.size() + 1</code> * * @throws BadRequestException throws if was error on client side: 4xx errors or http protocol errors * @throws UnavailableClusterException throws if was error on addresses pool side: no one of address is unavailable */ public void ping() throws BadRequestException, UnavailableClusterException { ping(whiteList.size() + 1); } /** * Request to {@value #SEND_ASYNC}. Count of retry is <code>whitelist.size() + 1</code> * * @param apiKey key for sending * @param stream topic name in kafka * @param data payload * @throws BadRequestException throws if was error on client side: 4xx errors or http protocol errors * @throws UnavailableClusterException throws if was error on addresses pool side: no one of address is unavailable */ public void sendAsync(String apiKey, String stream, final byte[] data) throws BadRequestException, UnavailableClusterException { sendAsync(whiteList.size() + 1, apiKey, stream, data); } /** * Request to {@value #SEND_ACK}. Count of retry is <code>whitelist.size() + 1</code> * * @param apiKey key for sending * @param stream topic name in kafka * @param data payload * @throws BadRequestException throws if was error on client side: 4xx errors or http protocol errors * @throws UnavailableClusterException throws if was error on addresses pool side: no one of address is unavailable */ public void send(String apiKey, String stream, final byte[] data) throws BadRequestException, UnavailableClusterException { send(whiteList.size() + 1, apiKey, stream, data); } public void close() { try { client.close(); } catch (IOException e) { LOGGER.error("Error while closing http client: " + e.getLocalizedMessage()); } } /** * Strategy of updating urls in topology */ private void updateTopology() { if (greyList.isEmpty()) { return; } for (int i = 0; i < greyList.size(); i++) { GreyListTopologyElement element = greyList.peek(); if (System.currentTimeMillis() - element.getEntryTime() >= greyListElementsRecoveryTimeMs) { GreyListTopologyElement pollElement = greyList.poll(); whiteList.add(pollElement.getUrl()); } else { return; } } } //TODO: metrics /** * Strategy of sending data to addresses pool */ private void sendToPool(int retryLimit, HerculesRequestSender sender) throws BadRequestException, UnavailableClusterException { for (int count = 0; count < retryLimit; count++) { if (whiteList.isEmpty()) { throw new UnavailableClusterException(); } String url = whiteList.next(); try { sender.send(url); return; } catch (HttpProtocolException | UnavailableHostException e) { whiteList.remove(url); if (!greyList.offer(new GreyListTopologyElement(url))) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Send fails", e); } whiteList.add(url); } } } throw new UnavailableClusterException(); } //TODO: metrics /** * Strategy of sending data to single host */ private void sendToHost(String url, ApacheRequestSender sender) throws BadRequestException, UnavailableHostException, HttpProtocolException { try { int statusCode = sender.send(url); if (statusCode >= 400 && statusCode < 500) { throw new BadRequestException(statusCode); } else if (statusCode >= 500) { throw new UnavailableHostException(url); } } catch (ClientProtocolException e) { throw new HttpProtocolException(e); } catch (IOException e) { throw new UnavailableHostException(url, e); } } private int sendRequest(HttpUriRequest request) throws IOException { CloseableHttpResponse response = client.execute(request); int statusCode = response.getStatusLine().getStatusCode(); response.close(); return statusCode; } /** * Build http post request * * @param url gateway url * @param apiKey key for sending * @param action Command in Hercules Gateway * @param stream topic name in kafka * @param data payload * @return formatted http post request */ private HttpPost buildRequest(String url, String apiKey, String action, String stream, byte[] data) { HttpPost httpPost = new HttpPost(url + action + "?stream=" + stream); httpPost.addHeader("apiKey", apiKey); HttpEntity entity = new ByteArrayEntity(data, ContentType.APPLICATION_OCTET_STREAM); httpPost.setEntity(entity); return httpPost; } /** * Tuning of {@link CloseableHttpClient} * * @param requestTimeout request timeout aka socket timeout (in millis) * @param connectionTimeout connection timeout (in millis) * @param connectionCount maximum client connections * @return Customized http client */ private static CloseableHttpClient createHttpClient(int requestTimeout, int connectionTimeout, int connectionCount) { RequestConfig requestConfig = RequestConfig .custom() .setSocketTimeout(requestTimeout) .setConnectTimeout(connectionTimeout) .setConnectionRequestTimeout(connectionTimeout) .build(); return HttpClientBuilder .create() .setDefaultRequestConfig(requestConfig) .setMaxConnPerRoute(connectionCount) .setMaxConnTotal(connectionCount) .setRetryHandler(new DefaultHttpRequestRetryHandler(0, false)) .build(); } @FunctionalInterface private interface ApacheRequestSender { int send(String url) throws IOException; } @FunctionalInterface private interface HerculesRequestSender { void send(String url) throws BadRequestException, UnavailableHostException, HttpProtocolException; } private static class Props { static final PropertyDescription<Integer> REQUEST_TIMEOUT = PropertyDescriptions .integerProperty("requestTimeout") .withDefaultValue(GateClientDefaults.DEFAULT_TIMEOUT) .withValidator(IntegerValidators.positive()) .build(); static final PropertyDescription<Integer> CONNECTION_TIMEOUT = PropertyDescriptions .integerProperty("connectionTimeout") .withDefaultValue(GateClientDefaults.DEFAULT_TIMEOUT) .withValidator(IntegerValidators.positive()) .build(); static final PropertyDescription<Integer> CONNECTION_COUNT = PropertyDescriptions .integerProperty("connectionCount") .withDefaultValue(GateClientDefaults.DEFAULT_CONNECTION_COUNT) .withValidator(IntegerValidators.positive()) .build(); static final PropertyDescription<Integer> GREY_LIST_ELEMENTS_RECOVERY_TIME_MS = PropertyDescriptions .integerProperty("greyListElementsRecoveryTimeMs") .withDefaultValue(GateClientDefaults.DEFAULT_RECOVERY_TIME) .withValidator(IntegerValidators.positive()) .build(); } }
40.563776
121
0.667442
c0227a89f36c0eeb2bf604ebcc193897aa576d70
3,391
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.maserven.dao; import com.maserven.utils.ConexionConfig; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import org.json.simple.JSONArray; import org.json.simple.JSONObject; /** * * @author Finpac01 */ public class ClientesDAO { public String getNuevaConsulta(String usuario, String identificacion){ String valor = ""; JSONObject json = new JSONObject(); JSONArray itemSelectedJson = new JSONArray(); try{ ConexionConfig cxConfig=new ConexionConfig(); PreparedStatement pst; ResultSet rs; // exec dbo.SP_CONSULTA_CLIENTE 'RSO','','[email protected]','A' pst = cxConfig.getconexion().prepareStatement("exec dbo.SP_CONSULTA_CLIENTE '"+identificacion+"','"+usuario+"';"); rs = pst.executeQuery(); while(rs.next()) { json = new JSONObject(); json.put("codigo",rs.getString(1)); json.put("identificacion", rs.getString(3)); json.put("razon_social", rs.getString(2)); json.put("mensaje", "ok"); json.put("codigo_error", 1); itemSelectedJson.add(json); } rs.close(); pst.close(); cxConfig.cierraConexion(); return itemSelectedJson.toString(); }catch (SQLException ex) { System.err.println( ex.getMessage() ); json = new JSONObject(); json.put("codigo",null); json.put("identificacion", null); json.put("razon_social", null); json.put("mensaje", "No existen datos"); json.put("codigo_error", 0); itemSelectedJson.add(json); return itemSelectedJson.toString(); } } public String getConsultaCliente(String tipo, String usuario, String identificacion, String nombre_cliente){ String valor = ""; JSONObject json = new JSONObject(); JSONArray itemSelectedJson = new JSONArray(); String query=""; query="exec dbo.SP_CONSULTA_CLIENTE '"+tipo+"','"+identificacion+"','"+usuario+"','"+nombre_cliente+"';"; try{ ConexionConfig cxConfig=new ConexionConfig(); PreparedStatement pst; ResultSet rs; // exec dbo.SP_CONSULTA_CLIENTE 'RSO','','[email protected]','A' pst = cxConfig.getconexion().prepareStatement(query); rs = pst.executeQuery(); while(rs.next()) { json = new JSONObject(); json.put("codigo",rs.getString(1)); json.put("identificacion", rs.getString(3)); json.put("razon_social", rs.getString(2)); itemSelectedJson.add(json); } rs.close(); pst.close(); cxConfig.cierraConexion(); return itemSelectedJson.toString(); }catch (SQLException ex) { System.err.println( ex.getMessage() ); return itemSelectedJson.toString(); } } }
36.858696
126
0.565615
afd7094578fbd4bfbbbf8e478e22ef77c7bf19ec
1,321
public class Solution { public List<Integer> topKFrequent(int[] nums, int k) { /* Use a map to store the integer with its corresponding appearance times. Convert the map to a sequence of buckets to store the integers. the appearence times of an int is same as (the index of a bucket in which it located)-1. */ ArrayList<Integer>[] buckets = new ArrayList[nums.length]; HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); for(int i: nums){ if (map.containsKey(i)){ int temp = map.get(i); //get the emergence times of i before. map.remove(i); map.put(i,temp+1); } else{ map.put(i,1); } } for(int i = 0; i < buckets.length; i++){ buckets[i] = new ArrayList<Integer>(); } for(int key : map.keySet()){ buckets[map.get(key)-1].add(key); } List<Integer> output = new ArrayList<Integer>(); for(int i = nums.length-1; i >= 0; i--){ for(int temp: buckets[i]){ output.add(temp); if(output.size() >= k){ return output; } } } return output; } }
35.702703
96
0.492051
a8c1568b9297bab02299267519dc039a45d5247d
3,103
/** * Copyright (c) 2002-2013 "Neo Technology," * Network Engine for Objects in Lund AB [http://neotechnology.com] * * This file is part of Neo4j. * * Neo4j is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.neo4j.kernel.impl.core; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import org.junit.Test; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.graphdb.Transaction; import org.neo4j.graphdb.factory.GraphDatabaseFactory; import org.neo4j.helpers.Pair; import static org.junit.Assert.*; import static org.neo4j.kernel.impl.AbstractNeo4jTestCase.deleteFileOrDirectory; import static org.neo4j.kernel.impl.nioneo.store.TestXa.*; public class TestChangingOfLogFormat { @Test public void inabilityToStartFromOldFormatFromNonCleanShutdown() throws Exception { File storeDir = new File("target/var/oldlog"); deleteFileOrDirectory( storeDir ); GraphDatabaseService db = new GraphDatabaseFactory().newEmbeddedDatabase( storeDir.getPath() ); Transaction tx = db.beginTx(); db.createNode(); tx.success(); tx.finish(); Pair<Pair<File, File>, Pair<File, File>> copy = copyLogicalLog( storeDir ); decrementLogFormat( copy.other().other() ); db.shutdown(); renameCopiedLogicalLog( storeDir ); try { db = new GraphDatabaseFactory().newEmbeddedDatabase( storeDir.getPath() ); fail( "Shouldn't be able to do recovery (and upgrade log format version) on non-clean shutdown" ); } catch ( Exception e ) { // Good e.printStackTrace(); } } private void decrementLogFormat( File file ) throws IOException { // Gotten from LogIoUtils class RandomAccessFile raFile = new RandomAccessFile( file, "rw" ); FileChannel channel = raFile.getChannel(); ByteBuffer buffer = ByteBuffer.wrap( new byte[8] ); channel.read( buffer ); buffer.flip(); long version = buffer.getLong(); long logFormatVersion = (version >>> 56); version = version & 0x00FFFFFFFFFFFFFFL; long oldVersion = version | ( ((long) logFormatVersion-1) << 56 ); channel.position( 0 ); buffer.clear(); buffer.putLong( oldVersion ); buffer.flip(); channel.write( buffer ); raFile.close(); } }
36.081395
110
0.673219
21c8663f8a704f15a49206c2008d2ea983f83360
3,271
package seedu.addressbook.ui; import java.util.List; import static seedu.addressbook.common.Messages.*; public class Formatter { /** A decorative prefix added to the beginning of lines printed by AddressBook */ public static final String LINE_PREFIX = "|| "; /** A platform independent line separator. */ public static final String LS = System.lineSeparator(); public static final String DIVIDER = "==================================================="; /** Format of indexed list item */ private static final String MESSAGE_INDEXED_LIST_ITEM = "\t%1$d. %2$s"; /** Offset required to convert between 1-indexing and 0-indexing. */ public static final int DISPLAYED_INDEX_OFFSET = 1; /** Format of a comment input line. Comment lines are silently consumed when reading user input. */ private static final String COMMENT_LINE_FORMAT_REGEX = "#.*"; /** * Returns true if the user input line should be ignored. * Input should be ignored if it is parsed as a comment, is only whitespace, or is empty. * * @param rawInputLine full raw user input line. * @return true if the entire user input line should be ignored. */ public static boolean shouldIgnore(String rawInputLine) { return rawInputLine.trim().isEmpty() || isCommentLine(rawInputLine); } /** * Returns true if the user input line is a comment line. * * @param rawInputLine full raw user input line. * @return true if input line is a comment. */ private static boolean isCommentLine(String rawInputLine) { return rawInputLine.trim().matches(COMMENT_LINE_FORMAT_REGEX); } /** Formats a list of strings as a viewable indexed list. */ public static String getIndexedListForViewing(List<String> listItems) { final StringBuilder formatted = new StringBuilder(); int displayIndex = 0 + DISPLAYED_INDEX_OFFSET; for (String listItem : listItems) { formatted.append(getIndexedListItem(displayIndex, listItem)).append("\n"); displayIndex++; } return formatted.toString(); } public static String getEnterCommandMessage() { return LINE_PREFIX + "Enter command: "; } public static String getCommandEnteredMessage(String fullInputLine) { return "[Command entered:" + fullInputLine + "]"; } public static String[] getWelcomeMessage(String version, String storageFileInfo) { return new String[]{DIVIDER, DIVIDER, MESSAGE_WELCOME, version, MESSAGE_PROGRAM_LAUNCH_ARGS_USAGE, storageFileInfo, DIVIDER}; } public static String[] getInitFailedMessage() { return new String[]{MESSAGE_INIT_FAILED, DIVIDER, DIVIDER}; } public static String[] getGoodbyeMessage() { return new String[]{MESSAGE_GOODBYE, DIVIDER, DIVIDER}; } /** * Formats a string as a viewable indexed list item. * * @param visibleIndex visible index for this listing */ public static String getIndexedListItem(int visibleIndex, String listItem) { return String.format(MESSAGE_INDEXED_LIST_ITEM, visibleIndex, listItem); } }
34.431579
103
0.65454
56188ee18b9c9b5248f154b6ac4a06f820b37fc3
4,080
/* * This source code is licensed under the MIT-style license found in the * LICENSE file in the root directory of this source tree. */ package com.netease.hearttouch.hthotfix; import com.netease.hearttouch.hthotfix.inject.HackInjector; import org.apache.commons.io.IOUtils; import org.gradle.api.Project; import org.gradle.api.logging.Logger; import org.objectweb.asm.ClassReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.util.Enumeration; import java.util.jar.JarEntry; import java.util.jar.JarFile; /** * Created by zw on 16/5/27. */ public class HashTransformExecutor { private final Project project; private final Logger logger; private final HashFileGenerator hashFileGenerator; private final HTHotfixExtension extension; private HackInjector hackInjector; public HashTransformExecutor(Project project,HTHotfixExtension extension) { this.project = project; this.logger = project.getLogger(); hashFileGenerator = new HashFileGenerator(project); this.extension = extension; this.hackInjector = new HackInjector(project,extension.getIncludePackage(),extension.getExcludeClass()); } public void transformDirectory(File inputFile, File outputFile) throws IOException { Path inputDir = inputFile.toPath(); Path outputDir = outputFile.toPath(); if (!Files.isDirectory(inputDir)) { return; } final OutputDirectory outputDirectory = new OutputDirectory(outputDir); Files.walkFileTree(inputDir, new ClasspathVisitor() { @Override protected void visitClass(Path path,byte[] bytecode) throws IOException { ClassReader cr = new ClassReader(bytecode); String className = cr.getClassName(); if(!extension.getGeneratePatch()){ hashFileGenerator.addClass(bytecode); outputDirectory.writeClass(className,hackInjector.inject(className,bytecode)); }else{ outputDirectory.writeClass(className,bytecode); } } @Override protected void visitResource(Path relativePath, byte[] content) throws IOException { outputDirectory.writeFile(relativePath, content); } }); } public void transformJar(File inputFile,File outputFile) throws IOException { logger.info("HASHTRANSFORMJAR\t" + outputFile.getAbsolutePath()); final JarFile jar = new JarFile(inputFile); final OutputJar outputJar = new OutputJar(outputFile); for (final Enumeration<JarEntry> entries = jar.entries(); entries.hasMoreElements(); ) { final JarEntry entry = entries.nextElement(); if (entry.isDirectory()) { // new File(outFile, entry.getName()).mkdirs(); continue; } final InputStream is = jar.getInputStream(entry); try { byte[] bytecode = IOUtils.toByteArray(is); if (entry.getName().endsWith(".class")) { if(!extension.getGeneratePatch()) { hashFileGenerator.addClass(bytecode); ClassReader cr = new ClassReader(bytecode); outputJar.writeEntry(entry, hackInjector.inject(cr.getClassName(),bytecode)); }else{ outputJar.writeEntry(entry, bytecode); } } else { outputJar.writeEntry(entry, bytecode); } } finally { IOUtils.closeQuietly(is); } } outputJar.close(); } public void transformFinish(){ if(!extension.getGeneratePatch()) { try{ hashFileGenerator.generate(); }catch (IOException e){ e.printStackTrace(); } } } }
35.789474
112
0.614216
08af01e993130046b8250e4072430a5b17e7991b
7,587
/* * Copyright (c) 2011-2016, Peter Abeles. All Rights Reserved. * * This file is part of BoofCV (http://boofcv.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package boofcv.core.encoding; import boofcv.struct.image.*; /** * NV21: The format is densely packed. Y is full resolution and UV are interlaced and 1/2 resolution. * So same UV values within a 2x2 square * * @author Peter Abeles */ public class ImplConvertNV21 { /** * First block contains gray-scale information and UV data can be ignored. */ public static void nv21ToGray(byte[] dataNV, GrayU8 output) { final int yStride = output.width; // see if the whole thing can be copied as one big block to maximize speed if( yStride == output.width && !output.isSubimage() ) { System.arraycopy(dataNV,0,output.data,0,output.width*output.height); } else { // copy one row at a time for( int y = 0; y < output.height; y++ ) { int indexOut = output.startIndex + y*output.stride; System.arraycopy(dataNV,y*yStride,output.data,indexOut,output.width); } } } /** * First block contains gray-scale information and UV data can be ignored. */ public static void nv21ToGray(byte[] dataNV, GrayF32 output) { for( int y = 0; y < output.height; y++ ) { int indexIn = y*output.width; int indexOut = output.startIndex + y*output.stride; for( int x = 0; x < output.width; x++ ) { output.data[ indexOut++ ] = dataNV[ indexIn++ ] & 0xFF; } } } public static void nv21ToMultiYuv_U8(byte[] dataNV, Planar<GrayU8> output) { GrayU8 Y = output.getBand(0); GrayU8 U = output.getBand(1); GrayU8 V = output.getBand(2); final int uvStride = output.width/2; nv21ToGray(dataNV, Y); int startUV = output.width*output.height; for( int row = 0; row < output.height; row++ ) { int indexUV = startUV + (row/2)*(2*uvStride); int indexOut = output.startIndex + row*output.stride; for( int col = 0; col < output.width; col++ , indexOut++ ) { U.data[indexOut] = dataNV[ indexUV ]; V.data[indexOut] = dataNV[ indexUV + 1 ]; indexUV += 2*(col&0x1); } } } public static void nv21ToMultiYuv_F32(byte[] dataNV, Planar<GrayF32> output) { GrayF32 Y = output.getBand(0); GrayF32 U = output.getBand(1); GrayF32 V = output.getBand(2); final int uvStride = output.width/2; nv21ToGray(dataNV, Y); final int startUV = output.width*output.height; for( int row = 0; row < output.height; row++ ) { int indexUV = startUV + (row/2)*(2*uvStride); int indexOut = output.startIndex + row*output.stride; for( int col = 0; col < output.width; col++ , indexOut++ ) { U.data[indexOut] = (dataNV[ indexUV ]&0xFF)-128; V.data[indexOut] = (dataNV[ indexUV + 1 ]&0xFF)-128; indexUV += 2*(col&0x1); } } } public static void nv21ToMultiRgb_U8(byte[] dataNV, Planar<GrayU8> output) { GrayU8 R = output.getBand(0); GrayU8 G = output.getBand(1); GrayU8 B = output.getBand(2); final int yStride = output.width; final int uvStride = output.width/2; final int startUV = yStride*output.height; for( int row = 0; row < output.height; row++ ) { int indexY = row*yStride; int indexUV = startUV + (row/2)*(2*uvStride); int indexOut = output.startIndex + row*output.stride; for( int col = 0; col < output.width; col++ , indexOut++ ) { int y = 1191*((dataNV[indexY++] & 0xFF) - 16); int cr = (dataNV[ indexUV ] & 0xFF) - 128; int cb = (dataNV[ indexUV+1] & 0xFF) - 128; if( y < 0 ) y = 0; int r = (y + 1836*cr) >> 10; int g = (y - 547*cr - 218*cb) >> 10; int b = (y + 2165*cb) >> 10; if( r < 0 ) r = 0; else if( r > 255 ) r = 255; if( g < 0 ) g = 0; else if( g > 255 ) g = 255; if( b < 0 ) b = 0; else if( b > 255 ) b = 255; R.data[indexOut] = (byte)r; G.data[indexOut] = (byte)g; B.data[indexOut] = (byte)b; indexUV += 2*(col&0x1); } } } public static void nv21ToInterleaved_U8(byte[] dataNV, InterleavedU8 output) { final int yStride = output.width; final int uvStride = output.width/2; final int startUV = yStride*output.height; for( int row = 0; row < output.height; row++ ) { int indexY = row*yStride; int indexUV = startUV + (row/2)*(2*uvStride); int indexOut = output.startIndex + row*output.stride; for( int col = 0; col < output.width; col++ ) { int y = 1191*((dataNV[indexY++] & 0xFF) - 16); int cr = (dataNV[ indexUV ] & 0xFF) - 128; int cb = (dataNV[ indexUV+1] & 0xFF) - 128; if( y < 0 ) y = 0; int r = (y + 1836*cr) >> 10; int g = (y - 547*cr - 218*cb) >> 10; int b = (y + 2165*cb) >> 10; if( r < 0 ) r = 0; else if( r > 255 ) r = 255; if( g < 0 ) g = 0; else if( g > 255 ) g = 255; if( b < 0 ) b = 0; else if( b > 255 ) b = 255; output.data[indexOut++] = (byte)r; output.data[indexOut++] = (byte)g; output.data[indexOut++] = (byte)b; indexUV += 2*(col&0x1); } } } public static void nv21ToMultiRgb_F32(byte[] dataNV, Planar<GrayF32> output) { GrayF32 R = output.getBand(0); GrayF32 G = output.getBand(1); GrayF32 B = output.getBand(2); final int yStride = output.width; final int uvStride = output.width/2; final int startUV = yStride*output.height; for( int row = 0; row < output.height; row++ ) { int indexY = row*yStride; int indexUV = startUV + (row/2)*(2*uvStride); int indexOut = output.startIndex + row*output.stride; for( int col = 0; col < output.width; col++ , indexOut++ ) { int y = 1191*((dataNV[indexY++] & 0xFF) - 16); int cr = (dataNV[ indexUV ] & 0xFF) - 128; int cb = (dataNV[ indexUV+1] & 0xFF) - 128; if( y < 0 ) y = 0; int r = (y + 1836*cr) >> 10; int g = (y - 547*cr - 218*cb) >> 10; int b = (y + 2165*cb) >> 10; if( r < 0 ) r = 0; else if( r > 255 ) r = 255; if( g < 0 ) g = 0; else if( g > 255 ) g = 255; if( b < 0 ) b = 0; else if( b > 255 ) b = 255; R.data[indexOut] = r; G.data[indexOut] = g; B.data[indexOut] = b; indexUV += 2*(col&0x1); } } } public static void nv21ToInterleaved_F32(byte[] dataNV, InterleavedF32 output) { final int yStride = output.width; final int uvStride = output.width/2; final int startUV = yStride*output.height; for( int row = 0; row < output.height; row++ ) { int indexY = row*yStride; int indexUV = startUV + (row/2)*(2*uvStride); int indexOut = output.startIndex + row*output.stride; for( int col = 0; col < output.width; col++ ) { int y = 1191*((dataNV[indexY++] & 0xFF) - 16); int cr = (dataNV[ indexUV ] & 0xFF) - 128; int cb = (dataNV[ indexUV+1] & 0xFF) - 128; if( y < 0 ) y = 0; int r = (y + 1836*cr) >> 10; int g = (y - 547*cr - 218*cb) >> 10; int b = (y + 2165*cb) >> 10; if( r < 0 ) r = 0; else if( r > 255 ) r = 255; if( g < 0 ) g = 0; else if( g > 255 ) g = 255; if( b < 0 ) b = 0; else if( b > 255 ) b = 255; output.data[indexOut++] = r; output.data[indexOut++] = g; output.data[indexOut++] = b; indexUV += 2*(col&0x1); } } } }
28.309701
103
0.600764
bd5dd6996ea8249fb73265b251ddc2c4d7be46b3
5,837
package br.com.mesttra.mcs.orcamento.service.impl; import java.math.BigDecimal; import java.time.LocalDateTime; import java.util.LinkedList; import java.util.List; import java.util.NoSuchElementException; import java.util.Objects; import java.util.stream.Collectors; import org.springframework.data.domain.Example; import org.springframework.data.domain.ExampleMatcher; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import br.com.mesttra.mcs.orcamento.entity.Budget; import br.com.mesttra.mcs.orcamento.entity.BudgetAllocation; import br.com.mesttra.mcs.orcamento.entity.Destination; import br.com.mesttra.mcs.orcamento.enums.DestinationTypeEnum; import br.com.mesttra.mcs.orcamento.exception.ApplicationException; import br.com.mesttra.mcs.orcamento.exception.ServiceEnumValidation; import br.com.mesttra.mcs.orcamento.repository.BudgetRepository; import br.com.mesttra.mcs.orcamento.service.BudgetAllocationService; import br.com.mesttra.mcs.orcamento.service.BudgetService; import br.com.mesttra.mcs.orcamento.service.DestinationService; import br.com.mesttra.mcs.orcamento.validation.ValidationCustom; import lombok.RequiredArgsConstructor; /** * Classe que implementa os métodos do serviço para manter o orçamento. * @author Yallamy Nascimento ([email protected]) * @since 2 de set de 2021 */ @Service @Transactional @RequiredArgsConstructor public class BudgetServiceImpl implements BudgetService { private final BudgetRepository repository; private final DestinationService destinationService; private final BudgetAllocationService budgetAllocationService; /* * * (non-Javadoc) * @see br.com.mesttra.mcs.orcamento.service.BudgetService#create(br.com.mesttra.mcs.orcamento.entity.Budget) */ @Override public Budget create(Budget budget) throws ApplicationException { ValidationCustom.validateConsistency(budget); budget.setDtBudget(LocalDateTime.now()); ValidationCustom.validateDataViolation(budget, budget.getClass()); Budget newBudget = repository.save(budget); List<Destination> destinationList = new LinkedList<Destination>(); for (Destination destination : budget.getDestinations()) { destination.setBudget(newBudget); destinationList.add(destinationService.create(destination)); } newBudget.setDestinations(destinationList); return newBudget; } /* * * (non-Javadoc) * @see br.com.mesttra.mcs.orcamento.service.BudgetService#createBudgetAllocation(java.lang.Long, br.com.mesttra.mcs.orcamento.entity.BudgetAllocation) */ @Override public Budget createBudgetAllocation(Long id, BudgetAllocation allocation) throws ApplicationException { ValidationCustom.validateConsistency(id, allocation); Budget budget = retrieve(id); BigDecimal totalSpentAmount = budgetAllocationService.getTotalSpentAmount(budget); if(totalSpentAmount.add(allocation.getSpentAmount()).compareTo(budget.getTotalAmount()) == 1) { throw new ApplicationException(ServiceEnumValidation.INSUFFICIENT_FUNDS); } allocation.setBudget(budget); budgetAllocationService.create(allocation); return budget; } /* * * (non-Javadoc) * @see br.com.mesttra.mcs.orcamento.service.BudgetService#retrieve(java.lang.Long) */ @Override public Budget retrieve(Long id) throws ApplicationException { ValidationCustom.validateConsistency(id); try { return repository.findById(id).get(); } catch(NoSuchElementException ex) { throw new ApplicationException(ServiceEnumValidation.BUDGET_NOT_FOUND); } } /* * * (non-Javadoc) * @see br.com.mesttra.mcs.orcamento.service.BudgetService#getTotalSpentAmount(br.com.mesttra.mcs.orcamento.entity.Budget) */ @Override public BigDecimal getTotalSpentAmount(Budget budget) throws ApplicationException { ValidationCustom.validateConsistency(budget); return budgetAllocationService.getTotalSpentAmount(budget); } /* * * (non-Javadoc) * @see br.com.mesttra.mcs.orcamento.service.BudgetService#list(br.com.mesttra.mcs.orcamento.entity.Budget, org.springframework.data.domain.Pageable) */ @Override public Page<Budget> list(Budget budget, Pageable pageable) throws ApplicationException { ValidationCustom.validateConsistency(pageable); if(Objects.isNull(budget)) { budget = Budget.builder().build(); } ExampleMatcher matcher = ExampleMatcher.matching().withIgnoreNullValues(); Example<Budget> example = Example.of(budget, matcher); Page<Budget> page = repository.findAll(example, pageable); if(Objects.nonNull(budget.getDestinations())) { page = filtroPorDestino(page, budget.getDestinations().get(0).getDestinationType()); } return page; } /** * Método que filtra por destino * @param page - página de origem * @param filtro - DestinationTypeEnum * @return Page<Budget> * @author Yallamy Nascimento ([email protected]) * @since 20 de set de 2021 */ private Page<Budget> filtroPorDestino(Page<Budget> page, DestinationTypeEnum filtro) { List<Budget> resultado = new LinkedList<Budget>(); List<Budget> dados = page.getContent(); for (Budget budget : dados) { List<Destination> destinations = budget.getDestinations(); List<Destination> filteredListDest = destinations.stream() .filter(d -> d.getDestinationType().equals(filtro)) .collect(Collectors.toList()); if(Objects.nonNull(filteredListDest) && !filteredListDest.isEmpty()) { resultado.add(budget); } } return new PageImpl<>(resultado, PageRequest.of(page.getNumber(), page.getSize(), page.getSort()), dados.size()); } }
31.047872
152
0.770087
faa949d8e26a4fcdc9a2787076d00cefd1fa9497
1,214
package com.aegean.icsd.mciobjects.common.daos; import java.util.List; import com.aegean.icsd.engine.common.beans.BaseGameObject; import com.aegean.icsd.engine.rules.beans.EntityProperty; import com.aegean.icsd.mciobjects.common.beans.ProviderException; public interface IObjectsDao { <T extends BaseGameObject> List<String> getObjectIds(Class<T> object) throws ProviderException; <T extends BaseGameObject> List<String> getNewObjectIdsFor(String forEntity, Class<T> object) throws ProviderException; <T extends BaseGameObject> List<String> getAssociatedObjectsOfEntityId(String id, Class<T> object) throws ProviderException; <T extends BaseGameObject> List<String> getAssociatedIdsOnPropertyForEntityId(String id, EntityProperty onProperty, Class<T> object) throws ProviderException; <T extends BaseGameObject> boolean areObjectsAssociatedOn(T thisObj, T thatObj, EntityProperty onProperty) throws ProviderException; List<String> getIdAssociatedWithOtherOnProperty(String otherId, EntityProperty onProperty) throws ProviderException; List<String> getIdAssociatedWithOtherOnProperty(String thisType, String otherType, String otherId, EntityProperty onProperty) throws ProviderException; }
46.692308
160
0.832784
93201ba42810b923e0c75f79b1e801d5633ea736
953
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package keno.widgets; /** * * @author mark */ public class PayTable { // PICKS, PICK_COUNT, PAY, PAYOUT public final static int[][] pay = { { 2 }, { 1, 14 }, { 0, 5, 65 }, { 0, 3, 20, 300 }, { 0, 2, 9, 75, 1400 }, { 0, 0, 6, 32, 300, 7500 }, { 1, 0, 4, 16, 100, 1200, 40000 }, { 1, 0, 1, 10, 50, 400, 6000, 230000 }, { 2, 0, 2, 7, 28, 165, 1600, 30000, 1320000 }, { 2, 0, 1, 5, 18, 86, 600, 7200, 163000, 9000000 } }; }
35.296296
68
0.303253
c628367a6fc472568f82fa3d375fb45abed45a63
225
package io.github.jonarzz.kata.fizz.buzz; class InvertedNestedModuloBasedFizzBuzzTest extends BaseFizzBuzzTest { InvertedNestedModuloBasedFizzBuzzTest() { super(new InvertedNestedModuloBasedFizzBuzz()); } }
25
70
0.786667
841794108fb8b633d4777645b8accd295cec9c55
1,155
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.aot.nativex; import org.springframework.aot.hint.RuntimeHints; /** * Generate GraalVM native configuration. * * @author Sebastien Deleuze * @since 6.0 * @see <a href="https://www.graalvm.org/22.0/reference-manual/native-image/BuildConfiguration/">Native Image Build Configuration</a> */ public interface NativeConfigurationGenerator { /** * Generate the GraalVM native configuration from the provided hints. * @param hints the hints to serialize */ void generate(RuntimeHints hints); }
31.216216
133
0.74632
0c1ff2c1a2d480b8070f6116c6fd9ec3f5a32a48
3,401
/* * Copyright (c) 2016, salesforce.com, inc. * All rights reserved. * Licensed under the BSD 3-Clause license. * For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause */ /* * This class represents the Bean object for code coverage computation for source classes * * @author [email protected] */ package com.sforce.cd.apexUnit.report; import java.util.List; public class ApexClassCodeCoverageBean implements Comparable<ApexClassCodeCoverageBean> { private String apexTestClassID; private String apexClassorTriggerId; private String apexClassName; private int numLinesCovered = 0; private int numLinesUncovered = 0; private ApexMethodCodeCoverageBean[] testMethodNames; private String apiVersion; private String lengthWithoutComments; private List<Long> coveredLinesList; private List<Long> uncoveredLinesList; public List<Long> getCoveredLinesList() { return coveredLinesList; } public void setCoveredLinesList(List<Long> coveredLinesList) { this.coveredLinesList = coveredLinesList; } public List<Long> getUncoveredLinesList() { return uncoveredLinesList; } public void setUncoveredLinesList(List<Long> uncoveredLinesList) { this.uncoveredLinesList = uncoveredLinesList; } public String getApexTestClassID() { return apexTestClassID; } public void setApexTestClassID(String apexTestClassID) { this.apexTestClassID = apexTestClassID; } public String getApexClassorTriggerId() { return apexClassorTriggerId; } public void setApexClassorTriggerId(String apexClassorTriggerId) { this.apexClassorTriggerId = apexClassorTriggerId; } public String getApexClassName() { return apexClassName; } public void setApexClassName(String apexClassName) { this.apexClassName = apexClassName; } public int getNumLinesCovered() { return numLinesCovered; } public void setNumLinesCovered(int numLinesCovered) { this.numLinesCovered = numLinesCovered; } public int getNumLinesUncovered() { return numLinesUncovered; } public void setNumLinesUncovered(int numLinesUncovered) { this.numLinesUncovered = numLinesUncovered; } public ApexMethodCodeCoverageBean[] getTestMethodNames() { return testMethodNames; } public void setTestMethodNames(ApexMethodCodeCoverageBean[] testMethodNames) { this.testMethodNames = testMethodNames; } public String getApiVersion() { return apiVersion; } public void setApiVersion(String apiVersion) { this.apiVersion = apiVersion; } public String getLengthWithoutComments() { return lengthWithoutComments; } public void setLengthWithoutComments(String lengthWithoutComments) { this.lengthWithoutComments = lengthWithoutComments; } public double getCoveragePercentage() { double totalLines = numLinesCovered + numLinesUncovered; if (totalLines > 0) { return (numLinesCovered / (totalLines)) * 100.0; } else { return 100.0; } } /* * over riding compareTo method of Comparable interface * * (non-Javadoc) * * @see java.lang.Comparable#compareTo(java.lang.Object) */ public int compareTo(ApexClassCodeCoverageBean codeCoverageBean) { if (this.getCoveragePercentage() < codeCoverageBean.getCoveragePercentage()) { return -1; } else if (this.getCoveragePercentage() > codeCoverageBean.getCoveragePercentage()) { return 1; } else { return 0; } } }
24.644928
112
0.768009
6ae984ed96fac7b9a1b73b8f1dc783f548353698
1,008
package com.leemon.wushiwan.entity; import com.leemon.wushiwan.entity.BaseEntity; import com.baomidou.mybatisplus.annotation.TableField; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; /** * <p> * * </p> * * @author leemon * @since 2019-08-18 */ @Data @EqualsAndHashCode(callSuper = true) @Accessors(chain = true) public class CoreVersion extends BaseEntity { private static final long serialVersionUID = 1L; /** * 版本号 */ @TableField("version_code") private Integer versionCode; /** * 版本名 */ @TableField("version_name") private String versionName; /** * wgt文件 */ @TableField("wgt_filename") private String wgtFilename; /** * 强制更新 */ @TableField("force_update") private Boolean forceUpdate; /** * wgt和html是否部署完成 */ @TableField("deployed") private Boolean deployed; }
17.684211
55
0.681548
22e6af0cffa1cf9a51661c2343ee90144877b008
33,180
import java.awt.Color; import java.awt.Graphics; import java.awt.Image; import java.awt.Rectangle; import org.dvb.ui.DVBBufferedImage; /** * Класс реализует отображение игрового процесса * @author Igor Maznitsa * @version 1.03 */ public class GameView { private static final String IMAGE_BRDRLEFT = "gfx/brdrlft.gif"; private static final String IMAGE_BRDRRIGHT = "gfx/brdrght.gif"; private static final String IMAGE_BRDRTOP = "gfx/brdrtop.gif"; private static final String IMAGE_PANEL = "gfx/panel.gif"; /** * Картинка, содержащая изображение левого бордюра */ private static Image p_LeftBorderImage; /** * Картинка, содержащая изображение верхнего бордюра */ private static Image p_TopBorderImage; /** * Картинка, содержащая изображение правого бордюра */ private static Image p_RightBorderImage; /** * Картинка, содержащая изображение панели очков и шариков */ private static Image p_PanelImage; /** * Бэкбуфер */ private static DVBBufferedImage p_BackBuffer; /** * Графический контекст бэкбуфера */ private static Graphics p_BackBufferGraphics; /** * Ширина игровой зоны */ private static final int BACKBUFFERWIDTH = 480; /** * Высота игровой зоны */ private static final int BACKBUFFERHEIGHT = 400; /** * Флаг, показывающий что требуется перерисовать весь экран */ private static boolean lg_PaintAll; /** * Цвет фона для заливки областей на игровом поле */ private static final Color BACKGROUNDCOLOR = new Color(0x8CB500); /** * Счетчик количества областей для перерисовки */ public static int i_AreasForDrawingNumber; /** * Координаты областей для перерисовки */ private static final long [] al_areasForDrawing = new long[32]; /** * Инициализация визуализатора * @param _width ширина теневого буфера * @param _height высота теневого буфера * @throws Throwable порождается в случае проблем при инициализации */ public static final void initResources(int _width,int _height) throws Throwable { p_LeftBorderImage = Utils.loadImageFromResource(IMAGE_BRDRLEFT); p_RightBorderImage = Utils.loadImageFromResource(IMAGE_BRDRRIGHT); p_TopBorderImage = Utils.loadImageFromResource(IMAGE_BRDRTOP); p_PanelImage = Utils.loadImageFromResource(IMAGE_PANEL); p_BackBuffer = new DVBBufferedImage(BACKBUFFERWIDTH,BACKBUFFERHEIGHT); p_BackBufferGraphics = p_BackBuffer.getGraphics(); ImageManager.init(true); lg_PaintAll = true; } /** * Освобождение ресурсов визуализатора * */ public static final void releaseResources() { ImageManager.release(); p_LeftBorderImage = null; p_RightBorderImage = null; p_TopBorderImage = null; p_PanelImage = null; if (p_BackBuffer!=null) p_BackBuffer.dispose(); } public static final void showNotify() { lg_PaintAll = true; } public static final void gameAction(int _action,int _optionaldata) { try { switch(_action) { case Gamelet.GAMEACTION_UPDATEBALLAREA : addAreaForDrawing(XOFFSET_BALLSPANEL,YOFFSET_PANEL,PANELWIDTH,PANELHEIGHT);break; case Gamelet.GAMEACTION_ADDREFLECTIONLINE : drawFullReflectionLine();break; case Gamelet.GAMEACTION_UPDATEMAINGAMEFIELD : drawBlockAt(_optionaldata);break; case Gamelet.GAMEACTION_UPDATEREFLECTIONFIELD : drawReflectBlockAt(_optionaldata);break; case Gamelet.GAMEACTION_BEATTOROCKET : { if (startup.i_Options_SoundLevel>0) SoundManager.playSound(SoundManager.SOUND_BALLBIT,startup.i_Options_SoundLevel); };break; case Gamelet.GAMEACTION_EXPLOSION : { if (startup.i_Options_SoundLevel>0) SoundManager.playSound(SoundManager.SOUND_EXPLOSION,startup.i_Options_SoundLevel); };break; } }catch(Throwable _thr) { _thr.printStackTrace(); } } public static final void beforeGameIteration() throws Throwable { // заполняем оптимизатор значениями позиций спрайтов Graphics p_g = p_BackBufferGraphics; ImageManager.p_DestinationGraphics = p_g; SpriteCollection [] ap_collection = Gamelet.ap_SpriteCollections; for(int li=0;li<ap_collection.length;li++) { //ap_collection[li].fillOptimizer(p_DrawOptimizer,false); clearBackgroundForSpriteCollection(ap_collection[li],p_g); } //p_DrawOptimizer.pack(); // System.out.println("p_DrawOptimizer = "+p_DrawOptimizer.i_StackPointer); // очищаем позиции спрайтов //clearBackground(p_DrawOptimizer); } public static final void clearBackgroundForSpriteCollection(SpriteCollection _collection,Graphics _g) throws Throwable { int i_offset = _collection.i_lastActiveSpriteOffset; final int[] ai_spriteData = _collection.ai_spriteDataArray; final short[] ash_spriteAnimationData = _collection.ash_spriteAnimationDataArray; _g.setColor(BACKGROUNDCOLOR); while(i_offset>=0) { final int i_listData = ai_spriteData[i_offset]; int i_prev = (i_listData & SpriteCollection.MASK_LISTPREVINDEX) >>> SpriteCollection.SHR_LISTPREVINDEX; int i_dataOffset = ai_spriteData[i_offset + SpriteCollection.OFFSET_STATICDATAOFFSET] + SpriteCollection.ANIMATIONTABLEEOFFSET_WIDTH; int i_w = ash_spriteAnimationData[i_dataOffset++]; int i_h = ash_spriteAnimationData[i_dataOffset]; i_dataOffset = i_offset + SpriteCollection.OFFSET_SCREENX; int i_x = (ai_spriteData[i_dataOffset++] + 0x7F) >> 8; int i_y = (ai_spriteData[i_dataOffset] + 0x7F) >> 8; _g.fillRect(i_x,i_y,i_w,i_h); //_optimizer.addRectangleArea(i_x,i_y,i_w,i_h,_withOptimization); // производим восстановление тайлов игрового поля if (i_y<(Gamelet.I8_STARTGAMEFIELDY>>8)) { int i_startcellx = i_x / (Gamelet.I8_CELLWIDTH>>8); int i_startcelly = i_y / (Gamelet.I8_CELLHEIGHT>>8); int i_endcellx = (i_x+i_w) / (Gamelet.I8_CELLWIDTH>>8); int i_endcelly = (i_y+i_h) / (Gamelet.I8_CELLHEIGHT>>8); int i_cellsw = (i_endcellx - i_startcellx)+1; int i_cellsh = (i_endcelly - i_startcelly)+1; if (i_startcellx+i_cellsw>Gamelet.FIELDCELLWIDTH) { i_cellsw = Gamelet.FIELDCELLWIDTH - i_startcellx; } if (i_startcelly+i_cellsh>Gamelet.FIELDCELLHEIGHT) { i_cellsh = Gamelet.FIELDCELLHEIGHT - i_startcelly; } int i_startareax = i_startcellx*(Gamelet.I8_CELLWIDTH>>8); int i_startareay = i_startcelly*(Gamelet.I8_CELLHEIGHT>>8); int i_startoffset = i_startcellx + i_startcelly*Gamelet.FIELDCELLWIDTH; final int [] ai_gamefieldsblocks = Gamelet.ai_GameField; while(i_cellsh>0) { int i_xoffset = i_startoffset; int i_strlen = i_cellsw; int i_xcoord = i_startareax; while(i_strlen>0) { int i_block = ai_gamefieldsblocks[i_xoffset++]; //p_BackBufferGraphics.setColor(Color.blue); //p_BackBufferGraphics.draw3DRect(i_xcoord,i_startareay,(Gamelet.I8_CELLWIDTH>>8),(Gamelet.I8_CELLHEIGHT>>8),true); switch(i_block) { case Gamelet.BLOCK_TELEPORTIN_DOWN: { ImageManager.drawImage(MAP_TELE_IN,i_xcoord,i_startareay-(Gamelet.I8_CELLHEIGHT>>8)); };break; case Gamelet.BLOCK_TELEPORTOUT_DOWN: { ImageManager.drawImage(MAP_TELE_OUT,i_xcoord,i_startareay-(Gamelet.I8_CELLHEIGHT>>8)); };break; case Gamelet.BLOCK_BONUSGENERATOR_DOWN: { ImageManager.drawImage(MAP_BONUS_GEN,i_xcoord,i_startareay-(Gamelet.I8_CELLHEIGHT>>8)); };break; case Gamelet.BLOCK_TELEPORT1IN : case Gamelet.BLOCK_TELEPORT2IN : { ImageManager.drawImage(MAP_TELE_IN,i_xcoord,i_startareay); };break; case Gamelet.BLOCK_TELEPORT1OUT : case Gamelet.BLOCK_TELEPORT2OUT : { ImageManager.drawImage(MAP_TELE_OUT,i_xcoord,i_startareay); };break; case Gamelet.BLOCK_BONUSGENERATOR : { ImageManager.drawImage(MAP_BONUS_GEN,i_xcoord,i_startareay); };break; case Gamelet.BLOCK_NONE: { _g.fillRect(i_xcoord,i_startareay,Gamelet.I8_CELLWIDTH>>8,Gamelet.I8_CELLHEIGHT>>8); };break; case Gamelet.BLOCK_BOMBA : { ImageManager.drawImage(MAP_BLOCK_BOMB,i_xcoord,i_startareay); };break; case Gamelet.BLOCK_IRON : { ImageManager.drawImage(MAP_BLOCK_IRON,i_xcoord,i_startareay); };break; case Gamelet.BLOCK_NORMAL1 : { ImageManager.drawImage(MAP_BLOCK_YELLOW01,i_xcoord,i_startareay); };break; case Gamelet.BLOCK_NORMAL2 : { ImageManager.drawImage(MAP_BLOCK_BLUE01,i_xcoord,i_startareay); };break; case Gamelet.BLOCK_NORMAL3 : { ImageManager.drawImage(MAP_BLOCK_MAGNA01,i_xcoord,i_startareay); };break; case Gamelet.BLOCK_SAND : { ImageManager.drawImage(MAP_BLOCK_SAND,i_xcoord,i_startareay); };break; } i_xcoord += (Gamelet.I8_CELLWIDTH>>8); i_strlen--; } i_startareay += (Gamelet.I8_CELLHEIGHT>>8); if (i_startareay>=(Gamelet.I8_STARTGAMEFIELDY>>8)) break; i_startoffset += Gamelet.FIELDCELLWIDTH; i_cellsh--; } } // проверяем на взаимодействие с линией отражателей if(i_y+i_h>=Gamelet.YOFREFLECTIONLINE) { // попадает, значит отрисовываем final int [] ai_reflection = Gamelet.ai_ReflectionLine; int i_startcellx = i_x / (Gamelet.I8_CELLWIDTH>>8); int i_endcellx = (i_x+i_w) / (Gamelet.I8_CELLWIDTH>>8); int i_width = (i_endcellx-i_startcellx)+1; if (i_startcellx+i_width>Gamelet.FIELDCELLWIDTH) { i_width = Gamelet.FIELDCELLWIDTH-i_startcellx; } // отрисовываем int i_xcoord = i_startcellx*(Gamelet.I8_CELLWIDTH>>8); while(i_width!=0) { int i_block = ai_reflection[i_startcellx++]; if (i_block!=Gamelet.BLOCK_NONE) { // отрисовываем ImageManager.drawImage(MAP_BLOCK_MIRROR,i_xcoord,Gamelet.YOFREFLECTIONLINE); } i_xcoord += (Gamelet.I8_CELLWIDTH>>8); i_width--; } } if (i_prev == 0xFFFF) i_prev = -1; i_offset = i_prev; } } private static final void drawFullReflectionLine() throws Throwable { ImageManager.p_DestinationGraphics = p_BackBufferGraphics; final int [] ai_reflection = Gamelet.ai_ReflectionLine; p_BackBufferGraphics.setColor(BACKGROUNDCOLOR); p_BackBufferGraphics.fillRect(0,Gamelet.YOFREFLECTIONLINE,BACKBUFFERWIDTH,Gamelet.I8_CELLHEIGHT>>8); int i_startcellx = 0; int i_width = Gamelet.FIELDCELLWIDTH; // отрисовываем int i_xcoord = 0; while(i_width!=0) { int i_block = ai_reflection[i_startcellx++]; if (i_block!=Gamelet.BLOCK_NONE) { // отрисовываем ImageManager.drawImage(MAP_BLOCK_MIRROR,i_xcoord,Gamelet.YOFREFLECTIONLINE); } i_xcoord += (Gamelet.I8_CELLWIDTH>>8); i_width--; } } public static final void afterGameIteration() throws Throwable { // отрисовываем ракетку // отрисовываем ракетку игрока SpriteCollection p_sprCol = Gamelet.ap_SpriteCollections[Gamelet.COLLECTIONID_PLAYERROCKET]; p_sprCol.initIterator(); ImageManager.p_DestinationGraphics = p_BackBufferGraphics; final Graphics p_g = p_BackBufferGraphics; while(true) { int i_sprite = p_sprCol.nextActiveSpriteOffset(); if (i_sprite<0) break; int i_spriteShield = 0; int i_spriteBaseOffset = 0; int i_y = p_sprCol.getScreenXY(i_sprite); int i_x = (short)(i_y>>>16); i_y = (short)(i_y); int i_frame = p_sprCol.getFrameNumber(i_sprite); switch(p_sprCol.getType(i_sprite)) { case Gamelet.SPRITE_OBJ_PLAYERROCKETLONG: { i_spriteShield = MAP_SHIELD_BIG; i_spriteBaseOffset = 34; };break; case Gamelet.SPRITE_OBJ_PLAYERROCKETNORMAL: { i_spriteShield = MAP_SHIELD_NORMAL; i_spriteBaseOffset = 15; };break; case Gamelet.SPRITE_OBJ_PLAYERROCKETSHORT: { i_spriteShield = MAP_SHIELD_SMALL; i_spriteBaseOffset = 4; };break; case Gamelet.SPRITE_OBJ_EXPLOSION: { ImageManager.drawImage(MAP_EXPLOSION1_01+(i_frame*7),i_x,i_y); continue; } default: System.out.println("Unknown type"); } ImageManager.drawImage(i_spriteShield,i_x,i_y); ImageManager.drawImage(MAP_WAGON01+i_frame*7,i_x+i_spriteBaseOffset,i_y+5); //int i_h = p_sprCol.getWidthHeight(i_sprite); //int i_w = i_h>>>16; //i_h &= 0xFFFF; //p_g.fillRect(i_x,i_y,i_w,i_h); } // отрисовываем взрывы p_sprCol = Gamelet.ap_SpriteCollections[Gamelet.COLLECTIONID_EXPLOSIONS]; p_sprCol.initIterator(); while(true) { int i_sprite = p_sprCol.nextActiveSpriteOffset(); if (i_sprite<0) break; int i_map = 0; switch(p_sprCol.getType(i_sprite)) { case Gamelet.SPRITE_OBJ_EXPLOSION: { switch(p_sprCol.getState(i_sprite)) { case Gamelet.SPRITE_STATE_EXPLOSION_EXPLOSION1 : { i_map = MAP_EXPLOSION1_01; };break; case Gamelet.SPRITE_STATE_EXPLOSION_EXPLOSION2 : { i_map = MAP_EXPLOSION2_01; };break; case Gamelet.SPRITE_STATE_EXPLOSION_EXPLOSION3 : { i_map = MAP_EXPLOSION3_01; };break; default: System.err.println("unfnown state"); } };break; default: { System.out.println("Unknown type"); } } int i_y = p_sprCol.getScreenXY(i_sprite); int i_x = (short)(i_y>>>16); i_y = (short)(i_y); ImageManager.drawImage(i_map+p_sprCol.getFrameNumber(i_sprite)*7,i_x,i_y); //int i_h = p_sprCol.getWidthHeight(i_sprite); //int i_w = i_h>>>16; //i_h &= 0xFFFF; //p_g.fillRect(i_x,i_y,i_w,i_h); } // отрисовываем бонусы p_sprCol = Gamelet.ap_SpriteCollections[Gamelet.COLLECTIONID_BONUSES]; p_sprCol.initIterator(); while(true) { int i_sprite = p_sprCol.nextActiveSpriteOffset(); if (i_sprite<0) break; int i_mapBonus = -1; switch(p_sprCol.getType(i_sprite)) { case Gamelet.SPRITE_OBJ_BONUSES: { switch(p_sprCol.getState(i_sprite)) { case Gamelet.SPRITE_STATE_BONUSES_ADDBALL : i_mapBonus = MAP_BONUS_BALLS;break; case Gamelet.SPRITE_STATE_BONUSES_LIFE :i_mapBonus = MAP_BONUS_LIFE;break; case Gamelet.SPRITE_STATE_BONUSES_ADDSCORE :i_mapBonus = MAP_BONUS_POINTS;break; //case Gamelet.SPRITE_STATE_BONUSES_ : i_mapBonus = MAP_BONUS_DEATH;break; case Gamelet.SPRITE_STATE_BONUSES_BALLDECREASE : i_mapBonus = MAP_BONUS_SMALL_BALL;break; case Gamelet.SPRITE_STATE_BONUSES_BALLSPEEDMINUS : i_mapBonus = MAP_BONUS_SLOW_BALL;break; case Gamelet.SPRITE_STATE_BONUSES_SMALLROCKET : i_mapBonus = MAP_BONUS_SMALL_PLATFORM;break; case Gamelet.SPRITE_STATE_BONUSES_BALLINCREASE : i_mapBonus = MAP_BONUS_BIG_BALL;break; case Gamelet.SPRITE_STATE_BONUSES_BALLSPEEDPLUS : i_mapBonus = MAP_BONUS_QUICK_BALL;break; case Gamelet.SPRITE_STATE_BONUSES_BIGROCKET :i_mapBonus = MAP_BONUS_BIG_PLATFORM;break; case Gamelet.SPRITE_STATE_BONUSES_MAGNET :i_mapBonus = MAP_BONUS_MAGNET;break; case Gamelet.SPRITE_STATE_BONUSES_NEXTLEVEL :i_mapBonus = MAP_BONUS_NEXT_LEVEL;break; case Gamelet.SPRITE_STATE_BONUSES_BALLNORMAL :i_mapBonus = MAP_BONUS_NORMAL_BALL;break; case Gamelet.SPRITE_STATE_BONUSES_REFLECTIONLINE :i_mapBonus = MAP_BONUS_MIRROR;break; } };break; default: { System.out.println("Unknown type"); } } int i_y = p_sprCol.getScreenXY(i_sprite); int i_x = (short)(i_y>>>16); i_y = (short)(i_y); ImageManager.drawImage(MAP_BONUS_BACKGROUND01+p_sprCol.getFrameNumber(i_sprite)*7,i_x,i_y); ImageManager.drawImage(i_mapBonus,i_x+15,i_y+15); //int i_h = p_sprCol.getWidthHeight(i_sprite); //int i_w = i_h>>>16; //i_h &= 0xFFFF; //p_g.fillRect(i_x,i_y,i_w,i_h); } // отрисовываем мячик p_sprCol = Gamelet.ap_SpriteCollections[Gamelet.COLLECTIONID_PLAYERBALLS]; p_sprCol.initIterator(); while(true) { int i_sprite = p_sprCol.nextActiveSpriteOffset(); if (i_sprite<0) break; int i_map = 0; switch(p_sprCol.getType(i_sprite)) { case Gamelet.SPRITE_OBJ_BALL: { switch(p_sprCol.getState(i_sprite)) { case Gamelet.SPRITE_STATE_BALL_BIG : { i_map = MAP_BALL_BIG01; };break; case Gamelet.SPRITE_STATE_BALL_NORMAL : { i_map = MAP_BALL_NORMAL01; };break; case Gamelet.SPRITE_STATE_BALL_SMALL : { i_map = MAP_BALL_SMALL01; };break; default: System.err.println("unfnown state"); } };break; case Gamelet.SPRITE_OBJ_EXPLOSION: { i_map = MAP_EXPLOSION1_01; };break; } int i_y = p_sprCol.getScreenXY(i_sprite); int i_x = (short)(i_y>>>16); i_y = (short)(i_y); ImageManager.drawImage(i_map+p_sprCol.getFrameNumber(i_sprite)*7,i_x,i_y); //int i_h = p_sprCol.getWidthHeight(i_sprite); //int i_w = i_h>>>16; //i_h &= 0xFFFF; //p_g.fillRect(i_x,i_y,i_w,i_h); } } private static final void drawReflectBlockAt(int _offset) throws Throwable { int i_scrX = _offset * (Gamelet.I8_CELLWIDTH>>8); int i_block = Gamelet.ai_ReflectionLine[_offset]; Graphics p_g = p_BackBufferGraphics; p_g.setColor(BACKGROUNDCOLOR); switch(i_block) { case Gamelet.BLOCK_NONE : { p_g.fillRect(i_scrX,Gamelet.YOFREFLECTIONLINE,Gamelet.I8_CELLWIDTH>>8,Gamelet.I8_CELLHEIGHT>>8); };break; default: { ImageManager.drawImage(MAP_BLOCK_MIRROR,i_scrX,Gamelet.YOFREFLECTIONLINE); } } } private static final void drawBlockAt(int _offset) throws Throwable { int i_x = _offset % Gamelet.FIELDCELLWIDTH; int i_y = _offset / Gamelet.FIELDCELLWIDTH; int i_scrX = i_x * (Gamelet.I8_CELLWIDTH>>8); int i_scrY = i_y * (Gamelet.I8_CELLHEIGHT>>8); int i_block = Gamelet.ai_GameField[_offset]; Graphics p_g = p_BackBufferGraphics; ImageManager.p_DestinationGraphics = p_g; p_g.setColor(BACKGROUNDCOLOR); switch(i_block) { case Gamelet.BLOCK_NONE : { p_g.fillRect(i_scrX,i_scrY,Gamelet.I8_CELLWIDTH>>8,Gamelet.I8_CELLHEIGHT>>8); };break; case Gamelet.BLOCK_TELEPORTIN_DOWN: { ImageManager.drawImage(MAP_TELE_IN,i_scrX,i_scrY-(Gamelet.I8_CELLHEIGHT>>8)); };break; case Gamelet.BLOCK_TELEPORTOUT_DOWN: { ImageManager.drawImage(MAP_TELE_OUT,i_scrX,i_scrY-(Gamelet.I8_CELLHEIGHT>>8)); };break; case Gamelet.BLOCK_BONUSGENERATOR_DOWN: { ImageManager.drawImage(MAP_BONUS_GEN,i_scrX,i_scrY-(Gamelet.I8_CELLHEIGHT>>8)); };break; case Gamelet.BLOCK_TELEPORT1IN : case Gamelet.BLOCK_TELEPORT2IN : { ImageManager.drawImage(MAP_TELE_IN,i_scrX,i_scrY); };break; case Gamelet.BLOCK_TELEPORT1OUT : case Gamelet.BLOCK_TELEPORT2OUT : { ImageManager.drawImage(MAP_TELE_OUT,i_scrX,i_scrY); };break; case Gamelet.BLOCK_BONUSGENERATOR : { ImageManager.drawImage(MAP_BONUS_GEN,i_scrX,i_scrY); };break; case Gamelet.BLOCK_BOMBA : { ImageManager.drawImage(MAP_BLOCK_BOMB,i_scrX,i_scrY); };break; case Gamelet.BLOCK_IRON : { ImageManager.drawImage(MAP_BLOCK_IRON,i_scrX,i_scrY); };break; case Gamelet.BLOCK_NORMAL1 : { ImageManager.drawImage(MAP_BLOCK_YELLOW01,i_scrX,i_scrY); };break; case Gamelet.BLOCK_NORMAL2 : { ImageManager.drawImage(MAP_BLOCK_BLUE01,i_scrX,i_scrY); };break; case Gamelet.BLOCK_NORMAL3 : { ImageManager.drawImage(MAP_BLOCK_MAGNA01,i_scrX,i_scrY); };break; case Gamelet.BLOCK_SAND : { ImageManager.drawImage(MAP_BLOCK_SAND,i_scrX,i_scrY); };break; } } public static final void afterInitGameStage() throws Throwable { ImageManager.p_DestinationGraphics = p_BackBufferGraphics; clearBackground(); // отрисовываем поле final int [] ai_gamefield = Gamelet.ai_GameField; int i_len = ai_gamefield.length; while(i_len>0) { drawBlockAt(--i_len); } drawFullReflectionLine(); showNotify(); } public static final void prepareDrawingList() { if (lg_PaintAll) { addAreaForDrawing(0,0,640,480); lg_PaintAll = false; } else { addAreaForDrawing(82,80,BACKBUFFERWIDTH,BACKBUFFERHEIGHT); } } private static final int XOFFSET_LEVELPANEL = 72; private static final int XOFFSET_BALLSPANEL = 405; private static final int YOFFSET_PANEL = 38; private static final int PANELWIDTH = 164; private static final int PANELHEIGHT = 42; private static final void drawPanelLevel(Graphics _g) throws Throwable { ImageManager.p_DestinationGraphics = _g; _g.drawImage(p_PanelImage,XOFFSET_LEVELPANEL,YOFFSET_PANEL,null); ImageManager.drawImage(MAP_LEVEL,83,41); int i_level = Gamelet.i_StageID+1; int i_mapNum1 = i_level<10 ? MAP_DIGIT0 : MAP_DIGIT0+7*(i_level/10); int i_mapNum2 = MAP_DIGIT0+(i_level%10)*7; ImageManager.drawImage(i_mapNum1,175,42); ImageManager.drawImage(i_mapNum2,200,42); } private static final void drawPanelBalls(Graphics _g) throws Throwable { ImageManager.p_DestinationGraphics = _g; _g.drawImage(p_PanelImage,XOFFSET_BALLSPANEL,YOFFSET_PANEL,null); ImageManager.drawImage(MAP_LIFE_ICO,428,41); int i_att = Gamelet.i_PlayerAttemptionsNumber; int i_mapNum1 = i_att<10 ? MAP_DIGIT0 : MAP_DIGIT0+7*(i_att/10); int i_mapNum2 = MAP_DIGIT0+(i_att%10)*7; ImageManager.drawImage(MAP_DIGITX,475,47); ImageManager.drawImage(i_mapNum1,503,42); ImageManager.drawImage(i_mapNum2,528,42); } public static final void clearBackground() throws Throwable { p_BackBufferGraphics.setColor(BACKGROUNDCOLOR); p_BackBufferGraphics.fillRect(0,0,BACKBUFFERWIDTH,BACKBUFFERHEIGHT); } public static final void addAreaForDrawing(int _x,int _y,int _w,int _h) { long l_area = (((long)_x)<<48) | (((long)_y)<<32) | (((long)_w)<<16) | (long)_h; al_areasForDrawing[i_AreasForDrawingNumber++] = l_area; } public static final long getRepaintArea() { while(i_AreasForDrawingNumber>0) { return al_areasForDrawing[--i_AreasForDrawingNumber]; } return -1L; } public static final void paint(Graphics _g,boolean _outputField) throws Throwable { Rectangle p_clipBounds = _g.getClipBounds(); switch(p_clipBounds.x) { case 0: { //System.out.println("Draw full game screen"); // full screen // отрисовываем бордюры _g.setColor(new Color((145<<16)|(182<<8)|7)); _g.fillRect(0,0,640,480); _g.drawImage(p_LeftBorderImage,0,0,null); _g.drawImage(p_TopBorderImage,80,0,null); _g.drawImage(p_RightBorderImage,560,0,null); // отрисовываем панели drawPanelLevel(_g); drawPanelBalls(_g); // поле if (_outputField) _g.drawImage(p_BackBuffer,82,82,null); };break; case XOFFSET_BALLSPANEL : case XOFFSET_LEVELPANEL : { //System.out.println("PANELS "+p_clipBounds); _g.drawImage(p_TopBorderImage,80,0,null); // панель шариков drawPanelBalls(_g); // панель уровня drawPanelLevel(_g); };break; default: { if (_outputField) _g.drawImage(p_BackBuffer,82,82,null); } } } private static final int MAP_BALL_BIG01 = 0; private static final int MAP_BALL_BIG02 = 7; private static final int MAP_BALL_BIG03 = 14; private static final int MAP_BALL_BIG04 = 21; private static final int MAP_BALL_BIG05 = 28; private static final int MAP_BALL_BIG06 = 35; private static final int MAP_BALL_NORMAL01 = 42; private static final int MAP_BALL_NORMAL02 = 49; private static final int MAP_BALL_NORMAL03 = 56; private static final int MAP_BALL_SMALL01 = 63; private static final int MAP_BALL_SMALL02 = 70; private static final int MAP_BLOCK_BLUE01 = 77; private static final int MAP_BLOCK_BOMB = 84; private static final int MAP_BLOCK_IRON = 91; private static final int MAP_BLOCK_MAGNA01 = 98; private static final int MAP_BLOCK_MIRROR = 105; private static final int MAP_BLOCK_SAND = 112; private static final int MAP_BLOCK_YELLOW01 = 119; private static final int MAP_BONUS_BACKGROUND01 = 126; private static final int MAP_BONUS_BACKGROUND02 = 133; private static final int MAP_BONUS_BACKGROUND03 = 140; private static final int MAP_BONUS_BALLS = 147; private static final int MAP_BONUS_BIG_BALL = 154; private static final int MAP_BONUS_BIG_PLATFORM = 161; private static final int MAP_BONUS_DEATH = 168; private static final int MAP_BONUS_GEN = 175; private static final int MAP_BONUS_LIFE = 182; private static final int MAP_BONUS_MAGNET = 189; private static final int MAP_BONUS_MIRROR = 196; private static final int MAP_BONUS_NEXT_LEVEL = 203; private static final int MAP_BONUS_NORMAL_BALL = 210; private static final int MAP_BONUS_POINTS = 217; private static final int MAP_BONUS_QUICK_BALL = 224; private static final int MAP_BONUS_SLOW_BALL = 231; private static final int MAP_BONUS_SMALL_BALL = 238; private static final int MAP_BONUS_SMALL_PLATFORM = 245; public static final int MAP_DIGIT0 = 252; private static final int MAP_DIGIT1 = 259; private static final int MAP_DIGIT2 = 266; private static final int MAP_DIGIT3 = 273; private static final int MAP_DIGIT4 = 280; private static final int MAP_DIGIT5 = 287; private static final int MAP_DIGIT6 = 294; private static final int MAP_DIGIT7 = 301; private static final int MAP_DIGIT8 = 308; private static final int MAP_DIGIT9 = 315; private static final int MAP_DIGITX = 322; private static final int MAP_EXPLOSION1_01 = 329; private static final int MAP_EXPLOSION1_02 = 336; private static final int MAP_EXPLOSION1_03 = 343; private static final int MAP_EXPLOSION1_04 = 350; private static final int MAP_EXPLOSION1_05 = 357; private static final int MAP_EXPLOSION1_06 = 364; private static final int MAP_EXPLOSION1_07 = 371; private static final int MAP_EXPLOSION1_08 = 378; private static final int MAP_EXPLOSION2_01 = 385; private static final int MAP_EXPLOSION2_02 = 392; private static final int MAP_EXPLOSION2_03 = 399; private static final int MAP_EXPLOSION2_04 = 406; private static final int MAP_EXPLOSION2_05 = 413; private static final int MAP_EXPLOSION2_06 = 420; private static final int MAP_EXPLOSION3_01 = 427; private static final int MAP_EXPLOSION3_02 = 434; private static final int MAP_EXPLOSION3_03 = 441; private static final int MAP_EXPLOSION3_04 = 448; private static final int MAP_EXPLOSION3_05 = 455; private static final int MAP_EXPLOSION3_06 = 462; private static final int MAP_EXPLOSION3_07 = 469; private static final int MAP_EXPLOSION3_08 = 476; private static final int MAP_LEVEL = 483; private static final int MAP_LIFE_ICO = 490; private static final int MAP_SHIELD_BIG = 497; private static final int MAP_SHIELD_NORMAL = 504; private static final int MAP_SHIELD_SMALL = 511; private static final int MAP_TELE_IN = 518; private static final int MAP_TELE_OUT = 525; private static final int MAP_WAGON01 = 532; private static final int MAP_WAGON02 = 539; private static final int MAP_WAGON03 = 546; private static final int MAP_WAGON04 = 553; }
37.155655
145
0.584027
f25d33b149dc0ba296fd465e103abb9197e13d29
3,128
package org.gt; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.gt.pipeline.ReaderWriterConfig; import org.gt.pipeline.TransformConfig; import java.util.List; public class Configuration { private static final Logger logger = LogManager.getLogger(); private static final String SOURCE_USERNAME = "SOURCE_USERNAME"; private static final String SOURCE_PASSWORD = "SOURCE_PASSWORD"; private static final String TARGET_USERNAME = "TARGET_USERNAME"; private static final String TARGET_PASSWORD = "TARGET_PASSWORD"; private static final long DEFAULT_TIMEOUT = 3600; private ReaderWriterConfig source; private ReaderWriterConfig target; private String sourceConversion; private String targetConversion; private List<TransformConfig> transforms; private String sourceUsername; private String sourcePassword; private String targetUsername; private String targetPassword; private long timeout; public ReaderWriterConfig getSource() { return source; } public void setSource(ReaderWriterConfig source) { this.source = source; } public ReaderWriterConfig getTarget() { return target; } public void setTarget(ReaderWriterConfig target) { this.target = target; } public String getSourceConversion() { return sourceConversion; } public void setSourceConversion(String sourceConversion) { this.sourceConversion = sourceConversion; } public String getTargetConversion() { return targetConversion; } public void setTargetConversion(String targetConversion) { this.targetConversion = targetConversion; } public List<TransformConfig> getTransforms() { return transforms; } public void setTransforms(List<TransformConfig> transforms) { this.transforms = transforms; } public long getTimeout() { if (timeout <= 0) { return DEFAULT_TIMEOUT; } return timeout; } public void setTimeout(long timeout) { this.timeout = timeout; } public String getSourceUsername() { return sourceUsername; } public String getSourcePassword() { return sourcePassword; } public String getTargetUsername() { return targetUsername; } public String getTargetPassword() { return targetPassword; } public void configure() throws GenevereException { this.sourceUsername = getEnvVar(SOURCE_USERNAME); this.sourcePassword = getEnvVar(SOURCE_PASSWORD); this.targetUsername = getEnvVar(TARGET_USERNAME); this.targetPassword = getEnvVar(TARGET_PASSWORD); } private String getEnvVar(String name) throws GenevereException { String property = System.getenv(name); if (property == null) { logger.error("Environment variable " + name + " is not configured"); throw new GenevereException("Environment variable " + name + " is not configured"); } return property; } }
26.735043
95
0.685742
426b7c9d47171345e31b34952e8116f4c1064d32
2,850
/* * JBoss, Home of Professional Open Source * * Copyright 2013 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.picketlink.social.standalone.google; import java.io.IOException; import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse; import com.google.api.client.http.HttpResponseException; import org.apache.log4j.Logger; import org.picketlink.social.standalone.oauth.SocialException; /** * Wrap Google operation within block of code to handle errors (and possibly restore access token and invoke operation again) * * @author <a href="mailto:[email protected]">Marek Posolda</a> */ abstract class GoogleRequest<T> { protected static Logger log = Logger.getLogger(GoogleRequest.class); protected abstract T invokeRequest(GoogleAccessTokenContext accessTokenContext) throws IOException; protected abstract SocialException createException(IOException cause); public T executeRequest(GoogleAccessTokenContext accessTokenContext, GoogleProcessor googleProcessor) { GoogleTokenResponse tokenData = accessTokenContext.getTokenData(); try { return invokeRequest(accessTokenContext); } catch (IOException ioe) { if (ioe instanceof HttpResponseException) { HttpResponseException googleException = (HttpResponseException)ioe; if (googleException.getStatusCode() == 400 && tokenData.getRefreshToken() != null) { try { // Refresh token and retry revocation with refreshed token googleProcessor.refreshToken(accessTokenContext); return invokeRequest(accessTokenContext); } catch (SocialException refreshException) { // Log this one with trace level. We will rethrow original exception if (log.isTraceEnabled()) { log.trace("Refreshing token failed", refreshException); } } catch (IOException ioe2) { ioe = ioe2; } } } log.warn("Error when calling Google operation. Details: " + ioe.getMessage()); throw createException(ioe); } } }
41.911765
125
0.664912
e872c425ec7b74a1802a648f8b1725217a59f62b
21,762
package com.juchao.upg.android.net; import android.content.Context; import android.text.TextUtils; import android.util.Log; import com.juchao.upg.android.entity.AccountEquipment; import com.juchao.upg.android.entity.BaseEquipmentAttachment; import com.juchao.upg.android.entity.BaseImage; import com.juchao.upg.android.entity.BaseResult; import com.juchao.upg.android.entity.InspectionTaskEquipmentItem; import com.juchao.upg.android.entity.MaintenaceTaskEquipmentItem; import com.juchao.upg.android.entity.ResAccountTask; import com.juchao.upg.android.entity.ResAccountTaskEquipment; import com.juchao.upg.android.entity.ResAppUpdate; import com.juchao.upg.android.entity.ResInspectionTask; import com.juchao.upg.android.entity.ResInspectionTaskEquipment; import com.juchao.upg.android.entity.ResLogin; import com.juchao.upg.android.entity.ResMaintenaceTask; import com.juchao.upg.android.entity.ResMaintenaceTaskEquipment; import com.juchao.upg.android.entity.ResMessage; import com.juchao.upg.android.entity.ResQuerySparePart; import com.juchao.upg.android.util.ClientUtil; import com.juchao.upg.android.util.Constants; import com.juchao.upg.android.util.DefaultShared; import com.juchao.upg.android.util.FileUtil; import com.juchao.upg.android.util.JsonMapperUtils; import org.json.JSONObject; import java.io.File; import java.util.Date; import java.util.HashMap; import java.util.Map; public class NetAccessor { private static final String TAG = NetAccessor.class.getSimpleName(); private static String THEME_LIST_URL; /** * 登陆 * * @param mContext * @param token * @return */ public static ResLogin login(Context mContext, String userName, String userPwd, String mac) { ResLogin mResLogin = null; try { Map<String, String> params = new HashMap<String, String>(); params.put("username", userName); params.put("password", userPwd); params.put("mac", mac); String jsonString = HttpUtils.doGet(HttpUtils.getBaseUrl() + "/mobileapp/login.action", params); if (!TextUtils.isEmpty(jsonString)) { mResLogin = JsonMapperUtils .toObject(jsonString, ResLogin.class); } } catch (Exception e) { e.printStackTrace(); } return mResLogin; } /** * 获取点检列表 * * @param mContext * @param token * @return */ public static ResInspectionTask getInspectionTaskList(Context mContext, String token) { ResInspectionTask mResInspectionTask = null; try { Map<String, String> params = new HashMap<String, String>(); params.put("token", token); params.put("status", "3"); // String jsonString = Data.task_list; String jsonString = HttpUtils.doGet(HttpUtils.getBaseUrl() + "/mobileapp/inspectionTask/list.action", params); if (!TextUtils.isEmpty(jsonString)) { mResInspectionTask = JsonMapperUtils.toObject(jsonString, ResInspectionTask.class); } } catch (Exception e) { e.printStackTrace(); } return mResInspectionTask; } /** * 下载点检任务 * * @param mContext * @param token * @param taskId * @return */ public static ResInspectionTaskEquipment downloadInspectionTask( Context mContext, String token, long taskId,int style) { ResInspectionTaskEquipment mResInspectionTaskEquipment = null; try { Map<String, String> params = new HashMap<String, String>(); params.put("id", taskId + ""); params.put("token", token); params.put("status", style + ""); // String jsonString = null; // if(taskId == 1){ // jsonString = Data.down_task_1; // }else if(taskId == 2){ // jsonString = Data.down_task_2; // }else if(taskId == 3){ // jsonString = Data.down_task_3; // } String jsonString = HttpUtils.doGet(HttpUtils.getBaseUrl() + "/mobileapp/inspectionTask/load.action", params); if (!TextUtils.isEmpty(jsonString)) { mResInspectionTaskEquipment = JsonMapperUtils.toObject( jsonString, ResInspectionTaskEquipment.class); } } catch (Exception e) { e.printStackTrace(); } return mResInspectionTaskEquipment; } /** * 数据更新接口 * * @param mContext * @param token * @param type * 数据结果的类名 * @param lastTime * 增量更新时间 * @return */ public static <T> T updateData(Context mContext, String token, String type, String lastTime, Class<T> clazz) { T t = null; try { Map<String, String> params = new HashMap<String, String>(); params.put("token", token); params.put("type", type); params.put("lastTime", lastTime); // String jsonString = null; // if(type.equals("EquipmentSpotcheck")){ // jsonString = Data.BASE_EquipmentSpotcheck; // }else if(type.equals("Equipment")){ // jsonString = Data.BASE_Equipment; // }else{ // jsonString = HttpUtils.doGet(HttpUtils.getBaseUrl() + // "/mobileapp/updateData.action", params); // } String jsonString = HttpUtils.doGet(HttpUtils.getBaseUrl() + "/mobileapp/updateData.action", params); if (!TextUtils.isEmpty(jsonString)) { t = JsonMapperUtils.toObject(jsonString, clazz); } } catch (Exception e) { e.printStackTrace(); } return t; } /** * 应用更新检查接口 */ public static ResAppUpdate getAppUpdateInfo(Context mContext) { ResAppUpdate mResAppUpdate = null; try { String jsonString = HttpUtils.doGet(HttpUtils.getBaseUrl() + "/mobileapp/getVersion.action", null); // String jsonString = // "{\"versionCode\":2,\"versionName\":\"1.2.1\",\"code\":0,\"log\":\"1、更新\\n2、修改\",\"msg\":\"操作成功\",\"url\":\"http://count.liqucn.com/d.php?id=79846&ArticleOS=Android&content_url=http://www.liqucn.com/rj/79846.shtml&down_url=kpa.moc.ncuqil_2.5_ncrennacsregnif.diordna.egnahckniht.ibom/nauqna/2102/daolpu/moc.ncuqil.elif//:ptth&Pink=0&from_type=web\"}"; if (!TextUtils.isEmpty(jsonString)) { mResAppUpdate = JsonMapperUtils.toObject(jsonString, ResAppUpdate.class); } } catch (Exception e) { e.printStackTrace(); } return mResAppUpdate; } /** * 提交点检项目 * * @param mContext * @param token * @param type * 数据结果的类名 * @param lastTime * 增量更新时间 * @return */ public static int commitInspectionItemData(Context mContext, String token, InspectionTaskEquipmentItem inspectionItem) { // 上传图片 try { if (inspectionItem != null && !TextUtils.isEmpty(inspectionItem.imageNames)) { inspectionItem.imageIds = ""; String[] mImageNames = inspectionItem.imageNames.split(","); for (int i = 0; i < mImageNames.length; i++) { File imageFile = new File(ClientUtil.getImageDir() + File.separator + mImageNames[i]); System.out.println("image file: "+ imageFile); String responeStr = HttpPostFileUtils.postContentAndPic( mContext, HttpUtils.getBaseUrl() + "/mobileapp/uploadImage.action", token, imageFile); Log.d(TAG, "upload image responeStr : " + responeStr); if (!TextUtils.isEmpty(responeStr)) { JSONObject jsonObj = new JSONObject(responeStr); if (jsonObj != null && jsonObj.optInt("code") == 0) { String imageId = jsonObj.optString("id"); if (i == mImageNames.length - 1) { inspectionItem.imageIds += imageId; } else { inspectionItem.imageIds += imageId + ","; } } else { return -1; } } else { return -1; } } } } catch (Exception e) { e.printStackTrace(); return -1; } try { Log.d("begin submit Result:", new Date()+""); Map<String, String> params = new HashMap<String, String>(); params.put("token", token); params.put("id", inspectionItem.id == null ? "" : inspectionItem.id + ""); params.put("result", inspectionItem.result); params.put("costTime", inspectionItem.costTime + ""); params.put("faultDescribe", inspectionItem.faultDescribe == null ? "" : inspectionItem.faultDescribe); params.put("imageIds", inspectionItem.imageIds == null ? "" : inspectionItem.imageIds); params.put("startTime", inspectionItem.startTime); params.put("endTime", inspectionItem.endTime); params.put("status", inspectionItem.style+""); String jsonString = HttpUtils.doPost(HttpUtils.getBaseUrl() + "/mobileapp/inspectionTask/submitResult.action", params); Log.d("end submit Result:", new Date()+""); if (!TextUtils.isEmpty(jsonString)) { BaseResult result = JsonMapperUtils.toObject(jsonString, BaseResult.class); if (result != null) { return result.code; } } } catch (Exception e) { e.printStackTrace(); } return -1; } public static ResMessage findMsg(String token) { try { Map<String, String> params = new HashMap<String, String>(); params.put("token", token); String jsonString = HttpUtils.doGet(HttpUtils.getBaseUrl() + "/mobileapp/message/findMsg.action", params); if (!TextUtils.isEmpty(jsonString)) { ResMessage result = JsonMapperUtils.toObject(jsonString, ResMessage.class); return result; } } catch (Exception e) { e.printStackTrace(); } return null; } public static ResMaintenaceTaskEquipment downloadMaintenaceTask( Context mContext, String token, long taskId) { // TODO Auto-generated method stub ResMaintenaceTaskEquipment mResMaintenaceTaskEquipment = null; try { Map<String, String> params = new HashMap<String, String>(); params.put("id", taskId + ""); params.put("token", token); String jsonString = HttpUtils.doGet(HttpUtils.getBaseUrl() + "/mobileapp/maintenaceTask/load.action", params); if (!TextUtils.isEmpty(jsonString)) { mResMaintenaceTaskEquipment = JsonMapperUtils.toObject( jsonString, ResMaintenaceTaskEquipment.class); } } catch (Exception e) { e.printStackTrace(); } return mResMaintenaceTaskEquipment; } public static ResMaintenaceTask getMaintenaceTaskList(Context mContext, String token) { ResMaintenaceTask mResMaintenaceTask = null; try { Map<String, String> params = new HashMap<String, String>(); params.put("token", token); String jsonString = HttpUtils.doGet(HttpUtils.getBaseUrl() + "/mobileapp/maintenaceTask/list.action", params); // Toast.makeText(this, text, duration) if (!TextUtils.isEmpty(jsonString)) { mResMaintenaceTask = JsonMapperUtils.toObject(jsonString, ResMaintenaceTask.class); } } catch (Exception e) { e.printStackTrace(); } return mResMaintenaceTask; } public static int commitMaintenaceItemData(Context mContext, String token, MaintenaceTaskEquipmentItem maintenaceItem) { // 上传图片 try { if (maintenaceItem != null && !TextUtils.isEmpty(maintenaceItem.imageNames)) { maintenaceItem.imageIds = ""; String[] mImageNames = maintenaceItem.imageNames.split(","); for (int i = 0; i < mImageNames.length; i++) { File imageFile = new File(ClientUtil.getImageDir() + File.separator + mImageNames[i]); String responeStr = HttpPostFileUtils.postContentAndPic( mContext, HttpUtils.getBaseUrl() + "/mobileapp/uploadImage.action", token, imageFile); Log.d(TAG, "upload image responeStr : " + responeStr); if (!TextUtils.isEmpty(responeStr)) { JSONObject jsonObj = new JSONObject(responeStr); if (jsonObj != null && jsonObj.optInt("code") == 0) { String imageId = jsonObj.optString("id"); if (i == mImageNames.length - 1) { maintenaceItem.imageIds += imageId; } else { maintenaceItem.imageIds += imageId + ","; } } else { return -1; } } else { return -1; } } } } catch (Exception e) { e.printStackTrace(); return -1; } try { Map<String, String> params = new HashMap<String, String>(); params.put("token", token); params.put("id", maintenaceItem.id == null ? "" : maintenaceItem.id + ""); // params.put("result", maintenaceItem.result); // params.put("costTime", maintenaceItem.costTime + ""); params.put("startTime", maintenaceItem.startTime); params.put("endTime", maintenaceItem.endTime); params.put("describe", maintenaceItem.faultDescribe == null ? "" : maintenaceItem.faultDescribe); params.put("imageIds", maintenaceItem.imageIds == null ? "" : maintenaceItem.imageIds); // params.put("sparePartIds", maintenaceItem.terminalNumber); params.put("sparePartIds", maintenaceItem.terminalNumber == null ? "" : maintenaceItem.terminalNumber); String jsonString = ""; if (maintenaceItem.state == 3) { jsonString = HttpUtils.doPost(HttpUtils.getBaseUrl() + "/mobileapp/maintenaceTask" + "/submitResult.action", params); } else if (maintenaceItem.state == 4) { jsonString = HttpUtils.doPost( HttpUtils.getBaseUrl() + "/mobileapp/maintenaceTask" + "/submitConfirm.action", params); } if (!TextUtils.isEmpty(jsonString)) { BaseResult result = JsonMapperUtils.toObject(jsonString, BaseResult.class); if (result != null) { return result.code; } } } catch (Exception e) { e.printStackTrace(); } return -1; } public static ResMaintenaceTask getMaintenaceEffectConfirmTaskList( Context context, String token) { ResMaintenaceTask mResMaintenaceTask = null; try { Map<String, String> params = new HashMap<String, String>(); params.put("token", token); String jsonString = HttpUtils.doGet(HttpUtils.getBaseUrl() + "/mobileapp/maintenaceTask/listConfirm.action", params); if (!TextUtils.isEmpty(jsonString)) { mResMaintenaceTask = JsonMapperUtils.toObject(jsonString, ResMaintenaceTask.class); } } catch (Exception e) { e.printStackTrace(); } return mResMaintenaceTask; } /** * 效果确认任务下载接口需要修改: * * @param mContext * @param token * @param taskId * @return */ public static ResMaintenaceTaskEquipment downloadMaintenaceEffectConfirmTask( Context mContext, String token, long taskId) { ResMaintenaceTaskEquipment mResMaintenaceTaskEquipment = null; try { Map<String, String> params = new HashMap<String, String>(); params.put("id", taskId + ""); params.put("token", token); String jsonString = HttpUtils.doGet(HttpUtils.getBaseUrl() + "/mobileapp/maintenaceTask/loadConfirm.action", params); if (!TextUtils.isEmpty(jsonString)) { mResMaintenaceTaskEquipment = JsonMapperUtils.toObject( jsonString, ResMaintenaceTaskEquipment.class); } } catch (Exception e) { e.printStackTrace(); } return mResMaintenaceTaskEquipment; } public static int confirmMaintenaceItemData(Context mContext, String token, MaintenaceTaskEquipmentItem maintenaceItem) { // 上传图片 try { if (maintenaceItem != null && !TextUtils.isEmpty(maintenaceItem.imageNames)) { maintenaceItem.imageIds = ""; String[] mImageNames = maintenaceItem.imageNames.split(","); for (int i = 0; i < mImageNames.length; i++) { File imageFile = new File(ClientUtil.getImageDir() + File.separator + mImageNames[i]); String responeStr = HttpPostFileUtils.postContentAndPic( mContext, HttpUtils.getBaseUrl() + "/mobileapp/uploadImage.action", token, imageFile); Log.d(TAG, "upload image responeStr : " + responeStr); if (!TextUtils.isEmpty(responeStr)) { JSONObject jsonObj = new JSONObject(responeStr); if (jsonObj != null && jsonObj.optInt("code") == 0) { String imageId = jsonObj.optString("id"); if (i == mImageNames.length - 1) { maintenaceItem.imageIds += imageId; } else { maintenaceItem.imageIds += imageId + ","; } } else { return -1; } } else { return -1; } } } } catch (Exception e) { e.printStackTrace(); return -1; } try { Map<String, String> params = new HashMap<String, String>(); params.put("token", token); params.put("id", maintenaceItem.id == null ? "" : maintenaceItem.id + ""); // params.put("result", maintenaceItem.result); // params.put("costTime", maintenaceItem.costTime + ""); params.put("startTime", maintenaceItem.startTime); params.put("endTime", maintenaceItem.endTime); params.put("describe", maintenaceItem.faultDescribe == null ? "" : maintenaceItem.faultDescribe); params.put("imageIds", maintenaceItem.imageIds == null ? "" : maintenaceItem.imageIds); params.put("sparePartIds", maintenaceItem.terminalNumber == null ? "" : maintenaceItem.terminalNumber); String jsonString = HttpUtils.doPost(HttpUtils.getBaseUrl() + "/mobileapp/maintenaceTask" + "/submitConfirm.action", params); if (!TextUtils.isEmpty(jsonString)) { BaseResult result = JsonMapperUtils.toObject(jsonString, BaseResult.class); if (result != null) { return result.code; } } } catch (Exception e) { e.printStackTrace(); } return -1; } public static ResQuerySparePart querySparePart(Context mContext,String token,String equipmentId,String keyword){ ResQuerySparePart result=new ResQuerySparePart(); try{ Map<String,String> params=new HashMap<String,String>(); params.put("token", token); params.put("equid", equipmentId); params.put("keyword", keyword); String jsonString=HttpUtils.doPost(HttpUtils.getBaseUrl() +"/mobileapp/sparePart/search.action", params); if(!TextUtils.isEmpty(jsonString)){ result=JsonMapperUtils.toObject(jsonString, ResQuerySparePart.class); } }catch(Exception e){ e.printStackTrace(); } return result; } /** * 获取盘点任务列表 * @param mContext * @param token * @return */ public static ResAccountTask getAccountTaskList(Context mContext, String token) { ResAccountTask mResAccountTask=null; try{ Map<String,String> params=new HashMap<String,String>(); params.put("token", token); String jsonString=HttpUtils.doGet(HttpUtils.getBaseUrl() + "/mobileapp/account/list.action", params); if(!TextUtils.isEmpty(jsonString)){ mResAccountTask=JsonMapperUtils.toObject(jsonString,ResAccountTask.class); } }catch(Exception e){ e.printStackTrace(); } return mResAccountTask; } public static ResAccountTaskEquipment downloadAccountTask(Context mContext, String token, long taskId) { ResAccountTaskEquipment entity = null; try{ Map<String,String> params=new HashMap<String,String>(); params.put("id", taskId+""); params.put("token", token); String jsonString = HttpUtils.doGet(HttpUtils.getBaseUrl() + "/mobileapp/account/load.action", params); if(!TextUtils.isEmpty(jsonString)){ entity=JsonMapperUtils.toObject(jsonString, ResAccountTaskEquipment.class); } }catch(Exception e){ e.printStackTrace(); } return entity; } public static int commitAccountItemData(Context mContext, String token, AccountEquipment item) { int result = -1; try { BaseResult baseResult=new BaseResult(); Map<String, String> params = new HashMap<String, String>(); params.put("token", token); params.put("id", item.accountId + ""); JSONObject json=new JSONObject(); json.put("equipmentId", item.equipmentId); json.put("status", item.status); json.put("scanCodeTime", item.scanCodeTime); String resultJson=json.toString(); params.put("equAccount", resultJson); String jsonString=HttpUtils.doPost(HttpUtils.getBaseUrl() + "/mobileapp/account/submitResult.action", params); if(!TextUtils.isEmpty(jsonString)){ baseResult=JsonMapperUtils.toObject(jsonString, BaseResult.class); if(baseResult !=null){ return baseResult.code; } } } catch (Exception e){ e.printStackTrace(); result = -1; } return result; } // public static ResBaseImage downloadImages(Context context,String token){ // ResBaseImage images = null; // try{ // Map<String,String> params = new HashMap<String,String>(); // params.put("token", token); // String jsonString=HttpUtils.doGet(HttpUtils.getBaseUrl()+"/mobileapp/BaseImage.action", // params); // if(!TextUtils.isEmpty(jsonString)){ // images = JsonMapperUtils.toObject(jsonString, ResBaseImage.class); // } // }catch(Exception e){ // e.printStackTrace(); // } // return images; // } public static void DownloadBaseImage(Context mContext, String token,BaseImage image) { try{ Map<String,String> params=new HashMap<String,String>(); String url=image.url; String id=image.id; params.put("token", token); String curUrl=""; if(image.id ==null || image.id.trim() == "0"){ curUrl = HttpUtils.getBaseUrl() +"/" +url; }else{ //curUrl = HttpUtils.getBaseUrl() + "/fileuploadCom/showPic.action?id=" +id; //curUrl = HttpUtils.getBaseUrl() + "fileuploadCom/readFile.action?id=" +id; curUrl= HttpUtils.getBaseUrl() + "/mobileapp/downloadImage.action?id=" +id +"&token="+token; } HttpUtils.downloadImage(curUrl,params,image); }catch(Exception e){ e.printStackTrace(); } } public static void DownloadBaseEquipmentAttachment(Context mContext, String token, BaseEquipmentAttachment att) { try{ String curUrl = HttpUtils.getBaseUrl() + "/mobileapp/downloadAttachment.action?id="+att.fileId+"&token="+token; HttpUtils.downloadAttachment(curUrl,att); }catch(Exception e){ e.printStackTrace(); } } public static void DownloadPic(Context mContext,String token,String picId){ try{ File file; file = new File(FileUtil.getMaintenacePicDir(), picId+".jpg"); if(file.exists()){ return; } String url =HttpUtils.getBaseUrl() + "/mobileapp/downloadAttachment.action?id="+picId+"&token="+token; CustomHttpURLConnection.downloadFile(url,file); }catch(Exception e){ e.printStackTrace(); } } }
30.436364
356
0.676546
42802aff03435482d7e83aa0015f34b9cfee30d5
1,012
package slimeknights.tconstruct.tables.item; import slimeknights.mantle.item.RetexturedBlockItem; import java.util.function.BooleanSupplier; import net.minecraft.core.NonNullList; import net.minecraft.tags.Tag; import net.minecraft.world.item.CreativeModeTab; import net.minecraft.world.item.Item; import net.minecraft.world.item.ItemStack; import net.minecraft.world.level.block.Block; /** Retextured block that conditionally enables show all variants */ public class TableBlockItem extends RetexturedBlockItem { private final BooleanSupplier showAllCondition; public TableBlockItem(Block block, Tag<Item> textureTag, Properties builder, BooleanSupplier showAllCondition) { super(block, textureTag, builder); this.showAllCondition = showAllCondition; } @Override public void fillItemCategory(CreativeModeTab group, NonNullList<ItemStack> items) { if (this.allowdedIn(group)) { addTagVariants(this.getBlock(), this.textureTag, items, showAllCondition.getAsBoolean()); } } }
36.142857
114
0.797431
74526afa09eff28573e6ffa22f58aa8a45b5b4b1
1,010
package javacore.Yserializacao.test; import javacore.Yserializacao.classes.Aluno; import javacore.Yserializacao.classes.Turma; import java.io.*; public class SerializacaoTest { public static void main(String[] args) { gravadorObjeto(); leitorObjeto(); } private static void gravadorObjeto() { Turma t = new Turma("Copa 2006"); Aluno aluno = new Aluno(1L,"Quaresma","2129219012"); aluno.setTurma(t); try(ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("aluno.ser"))) { oos.writeObject(aluno); } catch (IOException e) { e.printStackTrace(); } } private static void leitorObjeto() { try(ObjectInputStream ois = new ObjectInputStream(new FileInputStream("aluno.ser"))) { Aluno aluno = (Aluno) ois.readObject(); System.out.println(aluno); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } }
29.705882
97
0.629703
852774fad18df58c7d4667487386e21891d97f0d
5,751
package io.invertase.firebase; import android.app.ActivityManager; import android.content.Context; import android.util.Log; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.ReactContext; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.WritableMap; import com.facebook.react.modules.core.DeviceEventManagerModule; import java.util.List; import java.util.Map; import javax.annotation.Nullable; @SuppressWarnings("WeakerAccess") public class Utils { private static final String TAG = "Utils"; /** * send a JS event **/ public static void sendEvent(final ReactContext context, final String eventName, Object body) { if (context != null) { context .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) .emit(eventName, body); } else { Log.d(TAG, "Missing context - cannot send event!"); } } /** * Takes a value and calls the appropriate setter for its type on the target map + key * * @param key String key to set on target map * @param value Object value to set on target map * @param map WritableMap target map to write the value to */ @SuppressWarnings("unchecked") public static void mapPutValue(String key, @Nullable Object value, WritableMap map) { if (value == null) { map.putNull(key); } else { String type = value .getClass() .getName(); switch (type) { case "java.lang.Boolean": map.putBoolean(key, (Boolean) value); break; case "java.lang.Long": Long longVal = (Long) value; map.putDouble(key, (double) longVal); break; case "java.lang.Float": float floatVal = (float) value; map.putDouble(key, (double) floatVal); break; case "java.lang.Double": map.putDouble(key, (Double) value); break; case "java.lang.Integer": map.putInt(key, (int) value); break; case "java.lang.String": map.putString(key, (String) value); break; case "org.json.JSONObject$1": map.putString(key, value.toString()); break; default: if (List.class.isAssignableFrom(value.getClass())) { map.putArray(key, Arguments.makeNativeArray((List<Object>) value)); } else if (Map.class.isAssignableFrom(value.getClass())) { WritableMap childMap = Arguments.createMap(); Map<String, Object> valueMap = (Map<String, Object>) value; for (Map.Entry<String, Object> entry : valueMap.entrySet()) { mapPutValue(entry.getKey(), entry.getValue(), childMap); } map.putMap(key, childMap); } else { Log.d(TAG, "utils:mapPutValue:unknownType:" + type); map.putNull(key); } } } } /** * Convert a ReadableMap to a WritableMap for the purposes of re-sending back to JS * TODO This is now a legacy util - internally uses RN functionality * * @param map ReadableMap * @return WritableMap */ public static WritableMap readableMapToWritableMap(ReadableMap map) { WritableMap writableMap = Arguments.createMap(); // https://github.com/facebook/react-native/blob/master/ReactAndroid/src/main/java/com/facebook/react/bridge/WritableNativeMap.java#L54 writableMap.merge(map); return writableMap; } /** * Convert a ReadableMap into a native Java Map * TODO This is now a legacy util - internally uses RN functionality * * @param readableMap ReadableMap * @return Map */ public static Map<String, Object> recursivelyDeconstructReadableMap(ReadableMap readableMap) { // https://github.com/facebook/react-native/blob/master/ReactAndroid/src/main/java/com/facebook/react/bridge/ReadableNativeMap.java#L216 return readableMap.toHashMap(); } /** * Convert a ReadableArray into a native Java Map * TODO This is now a legacy util - internally uses RN functionality * * @param readableArray ReadableArray * @return List<Object> */ public static List<Object> recursivelyDeconstructReadableArray(ReadableArray readableArray) { // https://github.com/facebook/react-native/blob/master/ReactAndroid/src/main/java/com/facebook/react/bridge/ReadableNativeArray.java#L175 return readableArray.toArrayList(); } /** * We need to check if app is in foreground otherwise the app will crash. * http://stackoverflow.com/questions/8489993/check-android-application-is-in-foreground-or-not * * @param context Context * @return boolean */ public static boolean isAppInForeground(Context context) { ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); if (activityManager == null) return false; List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses(); if (appProcesses == null) return false; final String packageName = context.getPackageName(); for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) { if ( appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals(packageName) ) { return true; } } return false; } public static int getResId(Context ctx, String resName) { int resourceId = ctx .getResources() .getIdentifier(resName, "string", ctx.getPackageName()); if (resourceId == 0) { Log.e(TAG, "resource " + resName + " could not be found"); } return resourceId; } }
33.631579
142
0.668753
6c967fd084bf5a552181baf8ed972257f7cf59f9
1,256
package com.eshop.ordering.api.application.commands; import an.awesome.pipelinr.Command; import com.eshop.ordering.domain.aggregatesmodel.order.OrderId; import com.eshop.ordering.domain.aggregatesmodel.order.OrderRepository; import com.eshop.ordering.shared.CommandHandler; import lombok.RequiredArgsConstructor; import lombok.SneakyThrows; import org.springframework.transaction.annotation.Transactional; @CommandHandler @RequiredArgsConstructor public class SetStockConfirmedOrderStatusCommandHandler implements Command.Handler<SetStockConfirmedOrderStatusCommand, Boolean> { private final OrderRepository orderRepository; /** * Handler which processes the command when Stock service confirms the * request. */ @SneakyThrows @Override @Transactional public Boolean handle(SetStockConfirmedOrderStatusCommand command) { // Simulate a work time for confirming the stock Thread.sleep(10000); final var orderToUpdate = orderRepository.findById(OrderId.of(command.orderNumber())).orElse(null); if (orderToUpdate == null) { return false; } orderToUpdate.setStockConfirmedStatus(); orderRepository.save(orderToUpdate); return true; } }
33.052632
130
0.757962
1fd539a6c54b083cde179d947a158f6d625bcade
850
package org.onap.ccsdk.apps.services; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonRootName; import com.fasterxml.jackson.annotation.JsonValue; @JsonRootName(value = "error") public class RestTransportError extends RestError { public RestTransportError() { this.errorType = "transport"; } public RestTransportError(String errorTag, String errorMessage) { this.errorType = "transport"; this.errorTag = errorTag; this.errorMessage = errorMessage; this.errorInfo = errorMessage; } public RestTransportError(String errorTag, String errorMessage, Throwable t) { this.errorType = "transport"; this.errorTag = errorTag; this.errorMessage = errorMessage; this.errorInfo = t.getLocalizedMessage(); } }
27.419355
82
0.708235
44df5c1e898d9547bc4c6a21e4c805e3a6e30c7c
6,497
/* * Copyright (C) 2020 ActiveJ LLC. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.activej.launchers.crdt; import io.activej.config.Config; import io.activej.config.converter.ConfigConverters; import io.activej.crdt.CrdtServer; import io.activej.crdt.CrdtStorageClient; import io.activej.crdt.storage.CrdtStorage; import io.activej.crdt.storage.cluster.CrdtPartitions; import io.activej.crdt.storage.cluster.CrdtRepartitionController; import io.activej.crdt.storage.cluster.CrdtStorageCluster; import io.activej.crdt.storage.cluster.DiscoveryService; import io.activej.crdt.storage.local.CrdtStorageFs; import io.activej.crdt.storage.local.CrdtStorageMap; import io.activej.eventloop.Eventloop; import io.activej.fs.ActiveFs; import io.activej.inject.Key; import io.activej.inject.annotation.Provides; import io.activej.inject.annotation.QualifierAnnotation; import io.activej.inject.module.AbstractModule; import io.activej.types.Types; import org.jetbrains.annotations.NotNull; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.net.InetSocketAddress; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import static io.activej.common.Checks.checkState; import static io.activej.config.converter.ConfigConverters.ofInteger; import static io.activej.launchers.crdt.Initializers.ofFsCrdtClient; import static io.activej.launchers.initializers.Initializers.ofAbstractServer; import static io.activej.launchers.initializers.Initializers.ofEventloop; public abstract class CrdtNodeLogicModule<K extends Comparable<K>, S> extends AbstractModule { @Override protected void configure() { Type genericSuperclass = getClass().getGenericSuperclass(); Type[] typeArguments = ((ParameterizedType) genericSuperclass).getActualTypeArguments(); @NotNull Type supertype = Types.parameterizedType(CrdtStorage.class, typeArguments); bind((Key<?>) Key.ofType(supertype, InMemory.class)) .to(Key.ofType(Types.parameterizedType(CrdtStorageMap.class, typeArguments))); bind((Key<?>) Key.ofType(supertype, Persistent.class)) .to(Key.ofType(Types.parameterizedType(CrdtStorageFs.class, typeArguments))); Type[] clusterStorageTypes = Arrays.copyOf(typeArguments, 3); clusterStorageTypes[2] = String.class; bind((Key<?>) Key.ofType(supertype, Cluster.class)) .to(Key.ofType(Types.parameterizedType(CrdtStorageCluster.class, clusterStorageTypes))); } @Provides CrdtStorageMap<K, S> runtimeCrdtClient(Eventloop eventloop, CrdtDescriptor<K, S> descriptor) { return CrdtStorageMap.create(eventloop, descriptor.getCrdtFunction()); } @Provides CrdtStorageFs<K, S> fsCrdtClient(Eventloop eventloop, Config config, ActiveFs activeFs, CrdtDescriptor<K, S> descriptor) { return CrdtStorageFs.create(eventloop, activeFs, descriptor.getSerializer(), descriptor.getCrdtFunction()) .withInitializer(ofFsCrdtClient(config)); } @Provides DiscoveryService<K, S, String> discoveryService(CrdtStorageMap<K, S> localClient, CrdtDescriptor<K, S> descriptor, Config config) { config = config.getChild("crdt.cluster"); Eventloop eventloop = localClient.getEventloop(); Map<String, CrdtStorage<K, S>> partitions = new HashMap<>(); partitions.put(config.get("localPartitionId"), localClient); Map<String, Config> partitionsConfigmap = config.getChild("partitions").getChildren(); checkState(!partitionsConfigmap.isEmpty(), "Cluster could not operate without partitions, config had none"); for (Map.Entry<String, Config> entry : partitionsConfigmap.entrySet()) { InetSocketAddress address = ConfigConverters.ofInetSocketAddress().get(entry.getValue()); partitions.put(entry.getKey(), CrdtStorageClient.create(eventloop, address, descriptor.getSerializer())); } return DiscoveryService.constant(partitions); } @Provides CrdtPartitions<K, S, String> partitions(Eventloop eventloop, DiscoveryService<K, S, String> discoveryService) { return CrdtPartitions.create(eventloop, discoveryService); } @Provides CrdtStorageCluster<K, S, String> clusterCrdtClient(CrdtPartitions<K, S, String> partitions, CrdtDescriptor<K, S> descriptor, Config config) { return CrdtStorageCluster.create( partitions, descriptor.getCrdtFunction()) .withReplicationCount(config.get(ofInteger(), "crdt.cluster.replicationCount", 1)); } @Provides CrdtRepartitionController<K, S, String> crdtRepartitionController(CrdtStorageCluster<K, S, String> clusterClient, Config config) { return CrdtRepartitionController.create(clusterClient, config.get("crdt.cluster.localPartitionId")); } @Provides CrdtServer<K, S> crdtServer(Eventloop eventloop, CrdtStorageMap<K, S> client, CrdtDescriptor<K, S> descriptor, Config config) { return CrdtServer.create(eventloop, client, descriptor.getSerializer()) .withInitializer(ofAbstractServer(config.getChild("crdt.server"))); } @Provides @Cluster CrdtServer<K, S> clusterServer(Eventloop eventloop, CrdtStorageCluster<K, S, String> client, CrdtDescriptor<K, S> descriptor, Config config) { return CrdtServer.create(eventloop, client, descriptor.getSerializer()) .withInitializer(ofAbstractServer(config.getChild("crdt.cluster.server"))); } @Provides Eventloop eventloop(Config config) { return Eventloop.create() .withInitializer(ofEventloop(config)); } @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER}) @QualifierAnnotation public @interface InMemory {} @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER}) @QualifierAnnotation public @interface Persistent {} @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER}) @QualifierAnnotation public @interface Cluster {} }
40.861635
143
0.789595
7c3570944e982a2c14133467ad94f2fac459087b
4,188
/* * 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.beam.sdk.extensions.sql.zetasql.translation; import com.google.zetasql.resolvedast.ResolvedColumn; import com.google.zetasql.resolvedast.ResolvedJoinScanEnums.JoinType; import com.google.zetasql.resolvedast.ResolvedNode; import com.google.zetasql.resolvedast.ResolvedNodes.ResolvedJoinScan; import java.util.List; import org.apache.beam.vendor.calcite.v1_26_0.org.apache.calcite.rel.RelNode; import org.apache.beam.vendor.calcite.v1_26_0.org.apache.calcite.rel.core.JoinRelType; import org.apache.beam.vendor.calcite.v1_26_0.org.apache.calcite.rel.logical.LogicalJoin; import org.apache.beam.vendor.calcite.v1_26_0.org.apache.calcite.rel.type.RelDataTypeField; import org.apache.beam.vendor.calcite.v1_26_0.org.apache.calcite.rex.RexNode; import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableList; import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableMap; import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableSet; /** Converts joins if neither side of the join is a WithRefScan. */ class JoinScanConverter extends RelConverter<ResolvedJoinScan> { private static final ImmutableMap<JoinType, JoinRelType> JOIN_TYPES = ImmutableMap.of( JoinType.INNER, JoinRelType.INNER, JoinType.FULL, JoinRelType.FULL, JoinType.LEFT, JoinRelType.LEFT, JoinType.RIGHT, JoinRelType.RIGHT); JoinScanConverter(ConversionContext context) { super(context); } @Override public boolean canConvert(ResolvedJoinScan zetaNode) { return true; } @Override public List<ResolvedNode> getInputs(ResolvedJoinScan zetaNode) { return ImmutableList.of(zetaNode.getLeftScan(), zetaNode.getRightScan()); } @Override public RelNode convert(ResolvedJoinScan zetaNode, List<RelNode> inputs) { RelNode convertedLeftInput = inputs.get(0); RelNode convertedRightInput = inputs.get(1); List<ResolvedColumn> combinedZetaFieldsList = ImmutableList.<ResolvedColumn>builder() .addAll(zetaNode.getLeftScan().getColumnList()) .addAll(zetaNode.getRightScan().getColumnList()) .build(); List<RelDataTypeField> combinedCalciteFieldsList = ImmutableList.<RelDataTypeField>builder() .addAll(convertedLeftInput.getRowType().getFieldList()) .addAll(convertedRightInput.getRowType().getFieldList()) .build(); final RexNode condition; if (zetaNode.getJoinExpr() == null) { condition = getExpressionConverter().trueLiteral(); } else { condition = getExpressionConverter() .convertRexNodeFromResolvedExpr( zetaNode.getJoinExpr(), combinedZetaFieldsList, combinedCalciteFieldsList, ImmutableMap.of()); } return LogicalJoin.create( convertedLeftInput, convertedRightInput, ImmutableList.of(), condition, ImmutableSet.of(), convertResolvedJoinType(zetaNode.getJoinType())); } static JoinRelType convertResolvedJoinType(JoinType joinType) { if (!JOIN_TYPES.containsKey(joinType)) { throw new UnsupportedOperationException("JOIN type: " + joinType + " is unsupported."); } return JOIN_TYPES.get(joinType); } }
38.422018
93
0.723973
e052b64532c753f31b57a48dc781d205bb3edc44
5,940
/* * Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tencentcloudapi.cdb.v20170320.models; import com.tencentcloudapi.common.AbstractModel; import com.google.gson.annotations.SerializedName; import com.google.gson.annotations.Expose; import java.util.HashMap; public class ModifyBackupDownloadRestrictionRequest extends AbstractModel{ /** * NoLimit 不限制,内外网都可以下载; LimitOnlyIntranet 仅内网可下载; Customize 用户自定义vpc:ip可下载。 只有该值为 Customize 时,才可以设置 LimitVpc 和 LimitIp 。 */ @SerializedName("LimitType") @Expose private String LimitType; /** * 该参数仅支持 In, 表示 LimitVpc 指定的vpc可以下载。默认为In。 */ @SerializedName("VpcComparisonSymbol") @Expose private String VpcComparisonSymbol; /** * In: 指定的ip可以下载; NotIn: 指定的ip不可以下载。 默认为In。 */ @SerializedName("IpComparisonSymbol") @Expose private String IpComparisonSymbol; /** * 限制下载的vpc设置。 */ @SerializedName("LimitVpc") @Expose private BackupLimitVpcItem [] LimitVpc; /** * 限制下载的ip设置 */ @SerializedName("LimitIp") @Expose private String [] LimitIp; /** * Get NoLimit 不限制,内外网都可以下载; LimitOnlyIntranet 仅内网可下载; Customize 用户自定义vpc:ip可下载。 只有该值为 Customize 时,才可以设置 LimitVpc 和 LimitIp 。 * @return LimitType NoLimit 不限制,内外网都可以下载; LimitOnlyIntranet 仅内网可下载; Customize 用户自定义vpc:ip可下载。 只有该值为 Customize 时,才可以设置 LimitVpc 和 LimitIp 。 */ public String getLimitType() { return this.LimitType; } /** * Set NoLimit 不限制,内外网都可以下载; LimitOnlyIntranet 仅内网可下载; Customize 用户自定义vpc:ip可下载。 只有该值为 Customize 时,才可以设置 LimitVpc 和 LimitIp 。 * @param LimitType NoLimit 不限制,内外网都可以下载; LimitOnlyIntranet 仅内网可下载; Customize 用户自定义vpc:ip可下载。 只有该值为 Customize 时,才可以设置 LimitVpc 和 LimitIp 。 */ public void setLimitType(String LimitType) { this.LimitType = LimitType; } /** * Get 该参数仅支持 In, 表示 LimitVpc 指定的vpc可以下载。默认为In。 * @return VpcComparisonSymbol 该参数仅支持 In, 表示 LimitVpc 指定的vpc可以下载。默认为In。 */ public String getVpcComparisonSymbol() { return this.VpcComparisonSymbol; } /** * Set 该参数仅支持 In, 表示 LimitVpc 指定的vpc可以下载。默认为In。 * @param VpcComparisonSymbol 该参数仅支持 In, 表示 LimitVpc 指定的vpc可以下载。默认为In。 */ public void setVpcComparisonSymbol(String VpcComparisonSymbol) { this.VpcComparisonSymbol = VpcComparisonSymbol; } /** * Get In: 指定的ip可以下载; NotIn: 指定的ip不可以下载。 默认为In。 * @return IpComparisonSymbol In: 指定的ip可以下载; NotIn: 指定的ip不可以下载。 默认为In。 */ public String getIpComparisonSymbol() { return this.IpComparisonSymbol; } /** * Set In: 指定的ip可以下载; NotIn: 指定的ip不可以下载。 默认为In。 * @param IpComparisonSymbol In: 指定的ip可以下载; NotIn: 指定的ip不可以下载。 默认为In。 */ public void setIpComparisonSymbol(String IpComparisonSymbol) { this.IpComparisonSymbol = IpComparisonSymbol; } /** * Get 限制下载的vpc设置。 * @return LimitVpc 限制下载的vpc设置。 */ public BackupLimitVpcItem [] getLimitVpc() { return this.LimitVpc; } /** * Set 限制下载的vpc设置。 * @param LimitVpc 限制下载的vpc设置。 */ public void setLimitVpc(BackupLimitVpcItem [] LimitVpc) { this.LimitVpc = LimitVpc; } /** * Get 限制下载的ip设置 * @return LimitIp 限制下载的ip设置 */ public String [] getLimitIp() { return this.LimitIp; } /** * Set 限制下载的ip设置 * @param LimitIp 限制下载的ip设置 */ public void setLimitIp(String [] LimitIp) { this.LimitIp = LimitIp; } public ModifyBackupDownloadRestrictionRequest() { } /** * NOTE: Any ambiguous key set via .set("AnyKey", "value") will be a shallow copy, * and any explicit key, i.e Foo, set via .setFoo("value") will be a deep copy. */ public ModifyBackupDownloadRestrictionRequest(ModifyBackupDownloadRestrictionRequest source) { if (source.LimitType != null) { this.LimitType = new String(source.LimitType); } if (source.VpcComparisonSymbol != null) { this.VpcComparisonSymbol = new String(source.VpcComparisonSymbol); } if (source.IpComparisonSymbol != null) { this.IpComparisonSymbol = new String(source.IpComparisonSymbol); } if (source.LimitVpc != null) { this.LimitVpc = new BackupLimitVpcItem[source.LimitVpc.length]; for (int i = 0; i < source.LimitVpc.length; i++) { this.LimitVpc[i] = new BackupLimitVpcItem(source.LimitVpc[i]); } } if (source.LimitIp != null) { this.LimitIp = new String[source.LimitIp.length]; for (int i = 0; i < source.LimitIp.length; i++) { this.LimitIp[i] = new String(source.LimitIp[i]); } } } /** * Internal implementation, normal users should not use it. */ public void toMap(HashMap<String, String> map, String prefix) { this.setParamSimple(map, prefix + "LimitType", this.LimitType); this.setParamSimple(map, prefix + "VpcComparisonSymbol", this.VpcComparisonSymbol); this.setParamSimple(map, prefix + "IpComparisonSymbol", this.IpComparisonSymbol); this.setParamArrayObj(map, prefix + "LimitVpc.", this.LimitVpc); this.setParamArraySimple(map, prefix + "LimitIp.", this.LimitIp); } }
32.108108
143
0.658081
9a8f749c498611fe847a5f91200d4adc3fb532b3
3,864
package com.alibaba.jvm.sandbox.api.resource; import com.alibaba.jvm.sandbox.api.Information; import java.net.InetSocketAddress; /** * 沙箱配置信息 * * @author [email protected] */ public interface ConfigInfo { /** * 获取沙箱的命名空间 * * @return 沙箱的命名空间 * @since {@code sandbox-common-api:1.0.2} */ String getNamespace(); /** * 获取沙箱的加载模式 * * @return 沙箱加载模式 */ Information.Mode getMode(); /** * 判断沙箱是否启用了unsafe * <p>unsafe功能启用之后,沙箱将能修改被BootstrapClassLoader所加载的类</p> * <p>在<b>${SANDBOX_HOME}/cfg/sandbox.properties#unsafe.enable</b>中进行开启关闭</p> * * @return true:功能启用;false:功能未启用 */ boolean isEnableUnsafe(); /** * 获取沙箱的HOME目录(沙箱主程序目录) * 默认是在<b>${HOME}/.sandbox</b> * * @return 沙箱HOME目录 */ String getHome(); /** * 获取沙箱的系统模块目录地址 * * @return 系统模块目录地址 * @deprecated 已经废弃, 可以参考{@link #getSystemModuleLibPath()} */ @Deprecated String getModuleLibPath(); /** * 获取沙箱的系统模块目录地址 * <p>沙箱将会从该模块目录中寻找并加载所有的模块</p> * <p>默认路径在<b>${SANDBOX_HOME}/module</b>目录下</p> * * @return 系统模块目录地址 */ String getSystemModuleLibPath(); /** * 获取沙箱内部服务提供库目录 * * @return 沙箱内部服务提供库目录 */ String getSystemProviderLibPath(); /** * 获取沙箱的用户模块目录地址 * <p>沙箱将会优先从系统模块地址{@link #getModuleLibPath()}加载模块,然后再从用户模块目录地址加载模块</p> * <p>固定在<b>${HOME}/.sandbox-module</b>目录下</p> * * @return 用户模块目录地址 * @deprecated 已经废弃,因为用户地址允许配置多条,可以通过{@link #getUserModuleLibPaths()}来获取所有的用户模块地址 */ @Deprecated String getUserModuleLibPath(); /** * 获取沙箱的用户模块目录地址(集合) * * @return 用户模块目录地址(集合) */ String[] getUserModuleLibPaths(); /** * 判断沙箱是否启用了事件对象池 * <p>启用事件对象池之后将会极大降低沙箱对JVM新生代的压力,但同时会带来一定的调用开销</p> * <p>是否启用对象池需要根据当前拦截的事件频繁程度来判断</p> * <p>在<b>${SANDBOX_HOME}/cfg/sandbox.properties#event.pool.enable</b>中进行开启关闭</p> * * @return true:启用;false:不启用 * @deprecated 后续不再支持事件池 */ @Deprecated boolean isEnableEventPool(); /** * 沙箱事件对象池单个事件类型缓存最小数量,{@link #isEnableEventPool()}==true时候有意义 * * @return 单个事件类型缓存最小数量 * @deprecated 后续不再支持事件池 */ @Deprecated int getEventPoolKeyMin(); /** * 沙箱事件对象池单个事件类型缓存最大数量,{@link #isEnableEventPool()}==true时候有意义 * * @return 单个事件类型缓存最大数量 * @deprecated 后续不再支持事件池 */ @Deprecated int getEventPoolKeyMax(); /** * 沙箱事件对象池所有事件类型缓存最大总数量,{@link #isEnableEventPool()}==true时候有意义 * * @return 所有事件类型缓存最大总数量 * @deprecated 后续不再支持事件池 */ @Deprecated int getEventPoolTotal(); /** * 获取事件池最大容量 * * @return 事件池最大容量 * @since {@code sandbox-common-api:1.0.1} * @deprecated 后续不再支持事件池 */ @Deprecated int getEventPoolMaxTotal(); /** * 获取事件池每个事件最小空闲容量 * * @return 事件池每个事件最小空闲容量 * @since {@code sandbox-common-api:1.0.1} * @deprecated 后续不再支持事件池 */ @Deprecated int getEventPoolMinIdlePerEvent(); /** * 获取事件池每个事件最大空闲容量 * * @return 事件池每个事件最大空闲容量 * @since {@code sandbox-common-api:1.0.1} * @deprecated 后续不再支持事件池 */ @Deprecated int getEventPoolMaxIdlePerEvent(); /** * 获取事件池每个事件最大容量 * * @return 事件池每个事件最大容量 * @since {@code sandbox-common-api:1.0.1} * @deprecated 后续不再支持事件池 */ @Deprecated int getEventPoolMaxTotalPerEvent(); /** * 获取沙箱HTTP服务侦听地址 * 如果服务器未能完成端口的绑定,则返回("0.0.0.0:0") * * @return 沙箱HTTP服务侦听地址 */ InetSocketAddress getServerAddress(); /** * 获取沙箱HTTP服务返回编码 * * @return 沙箱HTTP服务返回编码 * @since 1.2.2 */ String getServerCharset(); /** * 获取沙箱版本号 * * @return 沙箱版本号 */ String getVersion(); }
20.020725
85
0.582039
5c320acea266bdad93d07006ed8bc20949341a54
471
/******************************************************************************* * Copyright 2012 Josh Attenberg. Not for re-use or redistribution. ******************************************************************************/ package com.dsi.parallax.optimization.linesearch; import com.dsi.parallax.ml.vector.LinearVector; public interface LineOptimizer { /** Returns the last step size used. */ public double optimize (LinearVector line, double initialStep); }
39.25
80
0.515924
ccab15aa1b765b2c58d4c72d617569533bc0931e
6,134
/** * blackduck-installer * * Copyright (c) 2021 Synopsys, Inc. * * 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.synopsys.integration.blackduck.installer.hash; import java.util.HashSet; import java.util.Set; public class PreComputedHashes { //alert 5.0.0 public static final String ALERT_DOCKER_COMPOSE_LOCAL_OVERRIDES_YML_5_0_0 = "57c73ab627cdf6e9e791390626bda0b8fe5588262f455564e7a15c8e0b1fed20"; //alert 5.0.1 public static final String ALERT_DOCKER_COMPOSE_LOCAL_OVERRIDES_YML_5_0_1 = "57c73ab627cdf6e9e791390626bda0b8fe5588262f455564e7a15c8e0b1fed20"; //alert 5.1.0 public static final String ALERT_DOCKER_COMPOSE_LOCAL_OVERRIDES_YML_5_1_0 = "2850f36c29f36b75ef68b0b760500a00c7d88bd9b0b42d67ed2c0f03c4ed3754"; //alert 5.2.0 public static final String ALERT_DOCKER_COMPOSE_LOCAL_OVERRIDES_YML_5_2_0 = "17b30f5a66b7e048b9f8227d2b5aea3d636587f795c66f33a65bfe3cd26a88a4"; //alert 6.0.0 public static final String ALERT_DOCKER_COMPOSE_LOCAL_OVERRIDES_YML_6_0_0 = "b40d870285a2c2c712674efc6e1f3fb3046718d3d56c2b5cbad2dbbbd06db82b"; //alert 6.0.1 public static final String ALERT_DOCKER_COMPOSE_LOCAL_OVERRIDES_YML_6_0_1 = "b40d870285a2c2c712674efc6e1f3fb3046718d3d56c2b5cbad2dbbbd06db82b"; //alert 6.1.0 public static final String ALERT_DOCKER_COMPOSE_LOCAL_OVERRIDES_YML_6_1_0 = "b40d870285a2c2c712674efc6e1f3fb3046718d3d56c2b5cbad2dbbbd06db82b"; //alert 6.2.0 public static final String ALERT_DOCKER_COMPOSE_LOCAL_OVERRIDES_YML_6_2_0 = "c6fbe0c526590bd9ad6fdda8a7841abb2659dd8aa71524e5c19fdb83f3baf793"; //blackduck 2019.8.1 public static final String BLACKDUCK_CONFIG_ENV_2019_8_1 = "65bd2a53f058b2822990f71162dfb91d3e5a0afb70f15dbcf4497f80cf55c513"; public static final String DOCKER_COMPOSE_LOCAL_OVERRIDES_YML_2019_8_1 = "cc8ee040db78cfa3416bc1f1d5ba8e10a0377446f0cc7ff4a9e5ea8b21182359"; public static final String HUB_WEBSERVER_ENV_2019_8_1 = "dc0f2bde00cc96a5f5cb796875a21d17c25b9aff5ff62b48637a2c70bebe9f70"; //blackduck 2019.10.0 public static final String BLACKDUCK_CONFIG_ENV_2019_10_1 = "c3ed57ee811aa41159ef5db147767072894f92bab5f3130974881f3cdae212a0"; public static final String DOCKER_COMPOSE_LOCAL_OVERRIDES_YML_2019_10_1 = "cc8ee040db78cfa3416bc1f1d5ba8e10a0377446f0cc7ff4a9e5ea8b21182359"; public static final String HUB_WEBSERVER_ENV_2019_10_1 = "dc0f2bde00cc96a5f5cb796875a21d17c25b9aff5ff62b48637a2c70bebe9f70"; //blackduck 2019.10.1 public static final String BLACKDUCK_CONFIG_ENV_2019_10_0 = "312f3b10c1851582ab3c6bcd67a5402ac958ffce52b7cd0fc7ed79c18b67d032"; public static final String DOCKER_COMPOSE_LOCAL_OVERRIDES_YML_2019_10_0 = "cc8ee040db78cfa3416bc1f1d5ba8e10a0377446f0cc7ff4a9e5ea8b21182359"; public static final String HUB_WEBSERVER_ENV_2019_10_0 = "dc0f2bde00cc96a5f5cb796875a21d17c25b9aff5ff62b48637a2c70bebe9f70"; //blackduck 2019.12.0 public static final String BLACKDUCK_CONFIG_ENV_2019_12_0 = "d76b15b344b207755b27ee7972355534bb4a8bf14cfb8b2805000427e8efed60"; public static final String DOCKER_COMPOSE_LOCAL_OVERRIDES_YML_2019_12_0 = "cc8ee040db78cfa3416bc1f1d5ba8e10a0377446f0cc7ff4a9e5ea8b21182359"; public static final String HUB_WEBSERVER_ENV_2019_12_0 = "dc0f2bde00cc96a5f5cb796875a21d17c25b9aff5ff62b48637a2c70bebe9f70"; public static final Set<String> HUB_WEBSERVER_ENV = new HashSet<>(); public static final Set<String> DOCKER_COMPOSE_LOCAL_OVERRIDES_YML = new HashSet<>(); public static final Set<String> BLACKDUCK_CONFIG_ENV = new HashSet<>(); public static final Set<String> ALERT_DOCKER_COMPOSE_LOCAL_OVERRIDES_YML = new HashSet<>(); static { HUB_WEBSERVER_ENV.add(HUB_WEBSERVER_ENV_2019_8_1); HUB_WEBSERVER_ENV.add(HUB_WEBSERVER_ENV_2019_10_0); HUB_WEBSERVER_ENV.add(HUB_WEBSERVER_ENV_2019_10_1); HUB_WEBSERVER_ENV.add(HUB_WEBSERVER_ENV_2019_12_0); DOCKER_COMPOSE_LOCAL_OVERRIDES_YML.add(DOCKER_COMPOSE_LOCAL_OVERRIDES_YML_2019_8_1); DOCKER_COMPOSE_LOCAL_OVERRIDES_YML.add(DOCKER_COMPOSE_LOCAL_OVERRIDES_YML_2019_10_0); DOCKER_COMPOSE_LOCAL_OVERRIDES_YML.add(DOCKER_COMPOSE_LOCAL_OVERRIDES_YML_2019_10_1); DOCKER_COMPOSE_LOCAL_OVERRIDES_YML.add(DOCKER_COMPOSE_LOCAL_OVERRIDES_YML_2019_12_0); BLACKDUCK_CONFIG_ENV.add(BLACKDUCK_CONFIG_ENV_2019_8_1); BLACKDUCK_CONFIG_ENV.add(BLACKDUCK_CONFIG_ENV_2019_10_0); BLACKDUCK_CONFIG_ENV.add(BLACKDUCK_CONFIG_ENV_2019_10_1); BLACKDUCK_CONFIG_ENV.add(BLACKDUCK_CONFIG_ENV_2019_12_0); ALERT_DOCKER_COMPOSE_LOCAL_OVERRIDES_YML.add(ALERT_DOCKER_COMPOSE_LOCAL_OVERRIDES_YML_5_0_0); ALERT_DOCKER_COMPOSE_LOCAL_OVERRIDES_YML.add(ALERT_DOCKER_COMPOSE_LOCAL_OVERRIDES_YML_5_0_1); ALERT_DOCKER_COMPOSE_LOCAL_OVERRIDES_YML.add(ALERT_DOCKER_COMPOSE_LOCAL_OVERRIDES_YML_5_1_0); ALERT_DOCKER_COMPOSE_LOCAL_OVERRIDES_YML.add(ALERT_DOCKER_COMPOSE_LOCAL_OVERRIDES_YML_5_2_0); ALERT_DOCKER_COMPOSE_LOCAL_OVERRIDES_YML.add(ALERT_DOCKER_COMPOSE_LOCAL_OVERRIDES_YML_6_0_0); ALERT_DOCKER_COMPOSE_LOCAL_OVERRIDES_YML.add(ALERT_DOCKER_COMPOSE_LOCAL_OVERRIDES_YML_6_0_1); ALERT_DOCKER_COMPOSE_LOCAL_OVERRIDES_YML.add(ALERT_DOCKER_COMPOSE_LOCAL_OVERRIDES_YML_6_1_0); ALERT_DOCKER_COMPOSE_LOCAL_OVERRIDES_YML.add(ALERT_DOCKER_COMPOSE_LOCAL_OVERRIDES_YML_6_2_0); } }
57.867925
147
0.830942
ae0e2ec93401a7036aa18675f5950955acb49aac
3,382
/* * Copyright 2019 Miroslav Pokorny (github.com/mP1) * * 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 walkingkooka.net.header; import org.junit.jupiter.api.Test; import java.util.Optional; import static org.junit.jupiter.api.Assertions.assertThrows; public abstract class HeaderParameterNameTestCase<N extends HeaderParameterName<?>, C extends Comparable<C>> extends HeaderName2TestCase<N, C> { HeaderParameterNameTestCase() { super(); } @Test public final void testIsStarParameter() { final N name = this.createName(); this.checkEquals(name.value().endsWith("*"), name.isStarParameter(), () -> name + " is star parameter"); } @Test public final void testParameterValueNullFails() { assertThrows(NullPointerException.class, () -> this.createName().parameterValue(null)); } @Test public final void testParameterValueOrFailNullFails() { assertThrows(NullPointerException.class, () -> this.createName().parameterValueOrFail(null)); } final <VV> void parameterValueAndCheckAbsent(final HeaderParameterName<VV> name, final HeaderWithParameters<? extends HeaderParameterName<?>> hasParameters) { this.parameterValueAndCheck2(name, hasParameters, Optional.empty()); } final <VV> void parameterValueAndCheckPresent(final HeaderParameterName<VV> name, final HeaderWithParameters<? extends HeaderParameterName<?>> hasParameters, final VV value) { this.parameterValueAndCheck2(name, hasParameters, Optional.of(value)); } private <VV> void parameterValueAndCheck2(final HeaderParameterName<VV> name, final HeaderWithParameters<? extends HeaderParameterName<?>> hasParameters, final Optional<VV> value) { this.checkEquals(value, name.parameterValue(hasParameters), "wrong parameter value " + name + " in " + hasParameters); } @Override public final String nameText() { return "param-22"; } @Override public final String differentNameText() { return "different"; } @Override public final String nameTextLess() { return "param-1"; } @Override public final int minLength() { return 1; } @Override public final int maxLength() { return Integer.MAX_VALUE; } @Override public final String possibleValidChars(final int position) { return RFC2045; } @Override public final String possibleInvalidChars(final int position) { return CONTROL + BYTE_NON_ASCII + WHITESPACE; } }
32.209524
126
0.63838
ceb6a0549f4601093440de107f82765fd2942cfc
2,346
package com.github.unidbg; import capstone.api.Disassembler; import capstone.api.DisassemblerFactory; import capstone.api.Instruction; import capstone.api.RegsAccess; import com.github.unidbg.arm.ARM; import com.github.unidbg.utils.Inspector; import junit.framework.TestCase; import org.apache.commons.codec.binary.Hex; import org.apache.commons.io.FileUtils; import java.io.File; import java.io.FileOutputStream; import java.io.PrintStream; import java.nio.charset.StandardCharsets; import java.util.Arrays; public class HexTest extends TestCase { public void testHex() throws Exception { byte[] data = Hex.decodeHex("37ff000026f40100084c00004687000025704001583e000094eb0200140000009d469901222d0b00d52f01000c0000002a020000a02c00009d0c0000".toCharArray()); Inspector.inspect(data, "testHex"); StringBuilder builder = new StringBuilder(); ARM.appendHex(builder, 8, 8, '0', false); assertEquals(String.format("0x%08x", 8), builder.toString()); } public void testDisassembler() throws Exception { Disassembler disassembler = DisassemblerFactory.createArm64Disassembler(); disassembler.setDetail(true); byte[] code = Hex.decodeHex("017544bd".toCharArray()); Instruction instruction = disassembler.disasm(code, 0)[0]; assertNotNull(instruction); RegsAccess regsAccess = instruction.regsAccess(); assertNotNull(regsAccess); System.out.println("regsRead=" + Arrays.toString(regsAccess.getRegsRead())); System.out.println("regsWrite=" + Arrays.toString(regsAccess.getRegsWrite())); } public void testStream() throws Exception { File testFile = new File("target/streamTest.txt"); new PrintStream(testFile).println(123); new PrintStream(testFile).println("abc"); assertEquals("abc\n", FileUtils.readFileToString(testFile, StandardCharsets.UTF_8)); new PrintStream(new FileOutputStream(testFile, true), false).println(123); assertEquals("abc\n123\n", FileUtils.readFileToString(testFile, StandardCharsets.UTF_8)); } public void testFormat() { byte[] code = new byte[2]; assertEquals(" 0000", String.format("%8s", Hex.encodeHexString(code))); assertEquals("00000000", String.format("%8s", Hex.encodeHexString(new byte[4]))); } }
39.762712
174
0.719949
5ab1b1a7f4e84a4399e995f7522499748fb4e139
16,224
/****************************************************************** * Copyright (c) 2017 Nhi Vu, Victor Diego, Tyler Wood * * Zachary Pfister-Shanders, Derek Keeton, Chris Norton * * Please see the file COPYRIGHT in the source * * distribution of this software for further copyright * * information and license terms. * +/****************************************************************/ package com.groupc.officelocator; import android.app.Dialog; import android.content.Context; import android.content.SharedPreferences; import android.content.res.ColorStateList; import android.graphics.Typeface; import android.os.Bundle; import android.content.Intent; import android.support.v4.content.res.ResourcesCompat; import android.support.v7.app.AppCompatActivity; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.CheckBox; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import android.support.annotation.NonNull; import android.support.design.widget.BottomNavigationView; /* This class sets the behavior for the campus map screen. Included is set-up of layout elements, including listener events for satellite option, navigation bar, color change, all campus buildings. */ public class campus extends AppCompatActivity { RelativeLayout relativeLayout; public mapdata data; //Parses building data public ImageButton satelliteview; //Button to switch between campus maps and satellite views private static int globesetting = 0; //Flag used to switch between campus maps and satellite views ImageView mapimage; //Campus map variable Bundle dataContainer; //Used to pass data between activity pages //Change color feature variables Button changeColors; //Button user clicks on to change color themes private static String colorValue; //Variable used to determine which theme the user selects Dialog colorDialog; //Dialog that pops up allowing user to choose a color theme TextView colorCancel, colorSubmit, colorPrompt; //Different aspects of the Change color popup dialog CheckBox colorOrange, colorGreen; //Checkboxes user uses to select which color theme they want SharedPreferences colorPreferences; //Stores user color preference. 1 = Green, 2 = Orange SharedPreferences.Editor editor; //Editor to edit user color preferences in SharedPreference file @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_campus); //Zoom layout - allows user to pinch-zoom on campus map ZoomLayout myZoomView = new ZoomLayout(campus.this); relativeLayout = (RelativeLayout) findViewById(R.id.zoom); relativeLayout.addView(myZoomView); //Sets font for page header TextView text = (TextView) findViewById(R.id.campus); Typeface myCustomfont = Typeface.createFromAsset(getAssets(), "fonts/newsgothiccondensedbold.ttf"); text.setTypeface(myCustomfont); //Sets up data with campus buttons on campus map Intent priorInt = getIntent(); dataContainer = priorInt.getExtras(); data = new mapdata(); data = dataContainer.getParcelable("parse"); if(data == null) android.os.Process.killProcess(android.os.Process.myPid()); Button[] buttons = new Button[data.buildings.size()]; //Sets Listener Events for all campus building buttons and sets appropriate //variables for floorplan class. for (int i = 0; i < data.buildings.size(); i++) { final int j = i; String temp = data.buildings.get(i).buildingName.toLowerCase().replaceAll("\\s", ""); int id = getResources().getIdentifier(temp, "id", getPackageName()); buttons[i] = (Button) findViewById(id); buttons[i].setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent goToFloorPlan = new Intent(campus.this, floorplan.class); goToFloorPlan.putExtras(dataContainer); floorplan.fromSearch = 1; floorplan.fromCampus = 1; floorplan.floorNumber = "0"; floorplan.fpname = data.buildings.get(j).buildingName; floorplan.imageName = data.buildings.get(j).buildingName.replaceAll("\\s","").toLowerCase() + 1; floorplan.spinnerNumber = j; floorplan.numberOfFloors = data.buildings.get(j).numberofFloors; floorplan.buildingselected = j + 1; startActivity(goToFloorPlan); } }); } //Grab user color preferences from SharedPreference file colorPreferences = getSharedPreferences("ColorPreferences", Context.MODE_PRIVATE); colorValue = colorPreferences.getString("color", "default"); //CHANGING TO AND FROM SATELLITE VIEW mapimage = (ImageView)findViewById(R.id.campusmap); satelliteview = (ImageButton)findViewById(R.id.satelliteViewButton); satelliteview.setOnClickListener(new View.OnClickListener(){ public void onClick(View v){ colorValue = colorPreferences.getString("color", "default"); //Normal View -> satellite view if(globesetting == 0){ mapimage.setImageResource(R.drawable.satellite); satelliteview.setImageResource(R.drawable.globe2); if(colorValue.equals("1") || colorValue.equals("default")) satelliteview.setColorFilter(getResources().getColor(R.color.colorPrimary)); else satelliteview.setColorFilter(getResources().getColor(R.color.NikeOrange)); globesetting = 1; } //Satellite View -> Normal else{ if(colorValue.equals("1") || colorValue.equals("default")) mapimage.setImageResource(R.drawable.campus); else mapimage.setImageResource(R.drawable.campusorange); satelliteview.setImageResource(R.drawable.globe); satelliteview.setColorFilter(getResources().getColor(R.color.white)); globesetting = 0; } } }); } //Sets up color dialog private void createColorDialog(){ colorDialog = new Dialog(campus.this); colorDialog.requestWindowFeature(Window.FEATURE_NO_TITLE); colorDialog.setContentView(R.layout.colordialog); colorCancel = (TextView) colorDialog.findViewById(R.id.cancel); colorPrompt = (TextView) colorDialog.findViewById(R.id.prompt); Typeface myCustomfont = Typeface.createFromAsset(getAssets(), "fonts/newsgothiccondensedbold.ttf"); colorPrompt.setTypeface(myCustomfont); colorSubmit = (TextView) colorDialog.findViewById(R.id.submit); colorOrange = (CheckBox) colorDialog.findViewById(R.id.checkorange); colorGreen = (CheckBox) colorDialog.findViewById(R.id.checkneongreen); } //Setting up the bottom navigation toolbar private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener = new BottomNavigationView.OnNavigationItemSelectedListener() { @Override public boolean onNavigationItemSelected(@NonNull MenuItem item) { Intent theintent = null; switch (item.getItemId()) { case R.id.navigation_home: return true; case R.id.navigation_search: theintent = new Intent(campus.this, masterSearchWithHeaders.class); theintent.putExtras(dataContainer); break; case R.id.navigation_favorites: theintent = new Intent(campus.this, favoritesList.class); theintent.putExtras(dataContainer); break; } startActivity(theintent); return true; } }; //When the user presses the back button to get back to the Home page then the Home icon in the //bottom navigation toolbar should be set. Further, color settings are reset. @Override public void onResume(){ //Bottom navigation toolbar. Set "HOME" to checked BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation); navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener); navigation.getMenu().getItem(0).setChecked(true); //Grab user color preferences from SharedPreference file colorPreferences = getSharedPreferences("ColorPreferences", Context.MODE_PRIVATE); colorValue = colorPreferences.getString("color", "default"); //Code to allow user to change color preferences RelativeLayout universalLayout = (RelativeLayout)findViewById(R.id.universal_layout); View gradientBlock = (View) universalLayout.findViewById(R.id.gradientBlock); //Color block in theme editor = colorPreferences.edit(); changeColors = (Button) findViewById(R.id.colors); //Button user clicks on to change color preference createColorDialog(); //Sets up color pop up dialog where user makes their color preference changeColors.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { colorDialog.show(); //Default theme is "Nike Green" (SharedPreference value = 1, default) //Set the appropriate checkedboxes if (colorValue.equals("1") || colorValue.equals("default")) { colorGreen.setChecked(true); colorOrange.setChecked(false); } else { colorOrange.setChecked(true); colorGreen.setChecked(false); } editor.clear(); } }); //If user selects the Nike Orange checkbox colorOrange.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v){ colorOrange.setChecked(true); colorGreen.setChecked(false); editor.putString("color", "2"); } }); //If user selects the Nike Green checkbox colorGreen.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v){ colorGreen.setChecked(true); colorOrange.setChecked(false); editor.putString("color", "1"); } }); //If user submits their preference change, we must change the screen colorSubmit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v){ editor.commit(); colorDialog.dismiss(); finish(); overridePendingTransition( 0, 0); startActivity(getIntent()); overridePendingTransition( 0, 0); } }); //If user cancels their color preference change, reset the checkboxes and exit the pop up dialog colorCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v){ if (colorValue.equals("1") || colorValue.equals("default")){ colorGreen.setChecked(true); colorOrange.setChecked(false); } else { colorOrange.setChecked(true); colorGreen.setChecked(false); } colorDialog.dismiss(); } }); //Setting colors for bottom navigation bar //Different icon states int[][] iconStates = new int[][]{ new int[]{android.R.attr.state_checked},//checked state new int[]{-android.R.attr.state_checked},//unchecked state new int[]{} //default color }; //Different icon colors - Green theme int[] greenColors = new int[]{ ResourcesCompat.getColor(getResources(),R.color.colorPrimary, null), ResourcesCompat.getColor(getResources(),R.color.iconColor, null), ResourcesCompat.getColor(getResources(),R.color.iconColor, null), }; //Different icon colors - Orange theme int[] orangeColors = new int[]{ ResourcesCompat.getColor(getResources(),R.color.NikeOrange, null), ResourcesCompat.getColor(getResources(),R.color.iconColor, null), ResourcesCompat.getColor(getResources(),R.color.iconColor, null), }; switch (colorValue) { //Green Theme case "default": case "1": mapimage.setImageResource(R.drawable.campus); //set campus map to white-gray version gradientBlock.setBackgroundResource(R.drawable.greengradient); //set color block to green ((TextView)colorDialog.findViewById(R.id.submit)).setBackgroundResource(R.drawable.greengradient); //set submit box color in dialog to green ColorStateList navigationColorStateList = new ColorStateList(iconStates, greenColors); //set icons in navigation toolbar to green when checked navigation.setItemTextColor(navigationColorStateList); navigation.setItemIconTintList(navigationColorStateList); break; //Orange Theme case "2": mapimage.setImageResource(R.drawable.campusorange); //set campus map to orange version gradientBlock.setBackgroundResource(R.drawable.orangegradient); //set color block to orange ((TextView)colorDialog.findViewById(R.id.submit)).setBackgroundResource(R.drawable.orangegradient); //set submit box color in dialog to orange ColorStateList navigationColorStateList2 = new ColorStateList(iconStates, orangeColors); //set icons in navigation toolbar to orange when checked navigation.setItemTextColor(navigationColorStateList2); navigation.setItemIconTintList(navigationColorStateList2); break; } //Set to satellite view when going back to the campusorange map from another page if(globesetting == 1){ //Set to satellite view mapimage.setImageResource(R.drawable.satellite); satelliteview.setImageResource(R.drawable.globe2); if(colorValue.equals("1") || colorValue.equals("default")) satelliteview.setColorFilter(getResources().getColor(R.color.colorPrimary)); else satelliteview.setColorFilter(getResources().getColor(R.color.NikeOrange)); globesetting = 1; //Satellite view -> Normal }else{ if(colorValue.equals("1") || colorValue.equals("default")) mapimage.setImageResource(R.drawable.campus); else mapimage.setImageResource(R.drawable.campusorange); satelliteview.setImageResource(R.drawable.globe); satelliteview.setColorFilter(getResources().getColor(R.color.white)); globesetting = 0; } super.onResume(); } }
47.026087
161
0.613104
6596298a107da355bc9c2a9d53a92f909d49ec33
148
package pl.dzielins42.dmtools.model.enumeration; public enum Size { FINE, DIMINUTIVE, TINY, SMALL, MEDIUM, LARGE, HUGE, GARGANTUAN, COLOSSAL; }
29.6
77
0.756757
60499d5e7f51f04dd1845bae1545f1a9bb1e6a92
6,449
/* Copyright (c) 2013-2014, Imperial College London * All rights reserved. * * Distributed Algorithms, CO347 * * Partially based on R. Sedgewick's and K. Wayne's implementation * Algorithms, 4th edition */ import java.io.*; import java.util.*; public class RoutingOracle { /* cost[u][v] is the length of the shortest path from v to w */ private int [][] cost; /* Edges, read from file */ private int [][] edge; private int [][] last; private int [][] next; private Hashtable<Integer, ArrayList<Integer>> nodes; /* G = (V, E) */ private int _V_; private int _E_; private int INF; /* Infeasible path length */ private int INV; /* Invalid next/last hop */ public RoutingOracle (int N, String filename) { _V_ = N; INF = _V_ + 1; /* No path should be greater that N + 1 */ INV = _V_; _E_ = 0; cost = new int[_V_][_V_]; edge = new int[_V_][_V_]; last = new int[_V_][_V_]; next = new int[_V_][_V_]; nodes = new Hashtable<Integer, ArrayList<Integer>>(); /* Initialise edges * * This operation is unsafe. It assumes that the file * is formatted correctly. */ load (filename); if (! isGraphUndirected()) Utils.out("Warning: graph is directed\n"); } public int getV() { return _V_; } /* |E| = E / 2 because graph G is an undirected graph */ public int getE() { return _E_ / 2; } public boolean reset() { initialise(); computeShortestPaths(); /* Compute last [][] */ computeRoutingTables(); /* Compute next [][] */ return check(); } public boolean remove (int w) { Integer key = new Integer(w); if (nodes.containsKey(key)) return false; ArrayList<Integer> values = getNeighbours(w); nodes.put(key, values); for (Integer U: values) { int u = U.intValue(); edge[u][w] = 0; edge[w][u] = 0; } return reset (); /* Hm. Too expensive, needs more work. */ } public boolean repair (int w) { Integer key = new Integer(w); if (! nodes.containsKey(key)) return false; ArrayList<Integer> values = nodes.remove(key); for (Integer U: values) { int u = U.intValue(); edge[u][w] = 1; edge[w][u] = 1; } return reset (); } private void initialise() { /* Initialize costs based on connectivity */ for (int u = 0; u < _V_; u++) { for (int v = 0; v < _V_; v++) { if (u == v) { cost[u][v] = 0; last[u][v] = u; } else if (edge[u][v] == 1) { /* They are neighbors */ cost[u][v] = edge[u][v]; last[u][v] = u; } else { cost[u][v] = INF; last[u][v] = INV; } } } return ; } private void computeShortestPaths() { for (int i = 0; i < _V_; i++) { /* Pivot */ for (int u = 0; u < _V_; u++) { if (u == i) /* Skip diagonal */ continue; for (int v = 0; v < _V_; v++) { if (cost[u][v] > cost[u][i] + cost[i][v]) { cost[u][v] = cost[u][i] + cost[i][v]; last[u][v] = last[i][v]; } } } } return ; } private boolean isGraphUndirected() { for (int u = 0; u < _V_; u++) { for (int v = 0; v < _V_; v++) { if (edge[u][v] != edge[v][u]) return false; } } return true; } private void load (String filename) { FileInputStream f; DataInputStream d; BufferedReader b; String line; int u = 0, v; try { f = new FileInputStream(filename); d = new DataInputStream(f); b = new BufferedReader(new InputStreamReader(d)); while ((line = b.readLine()) != null) { String [] link = line.split(","); /* Assumes link.length == V */ for (v = 0; v < link.length; v++) { int value = (link[v].equals("1") && u != v ? 1 : 0); edge[u][v] = value; _E_ += value; } u ++; } if (u != _V_) { System.err.println(String.format("Error: %s is incorrect", filename)); System.exit(1); } } catch (Exception e) { System.err.println("Error: cannot read file " + filename); } return ; } public boolean hasPath(int u, int v) { return (cost[u][v] < INF); } public int getPathLength(int u, int v) { return cost[u][v]; } public int getNextHop(int u, int v) { return next[u][v]; } public boolean areNeighbours(int u, int v) { boolean result = false; if (u >= 0 && u < _V_ && v >= 0 && v < _V_) /* Is within bounds? */ result = (edge[u][v] == 1); return result; } public boolean isBestNextHop(int u, int v, int w) { if (! areNeighbours(u, w)) return false; if (getPathLength(u, v) < (getPathLength(u, w) + getPathLength(w, v))) return false; return true; } public ArrayList<Integer> getNeighbours(int u) { ArrayList<Integer> neighbours = new ArrayList<Integer>(); for (int v = 0; v < _V_; v++) if (edge[u][v] == 1 && u != v) neighbours.add(v); return neighbours; } private void dumpRoutingTable(int u) { Utils.out(String.format("%d's routing table", u)); for (int w = 0; w < _V_; w++) Utils.out(String.format("%d: %d", w, next[u][w])); } public Stack<Integer> getPath(int u, int v) { if (! hasPath(u, v)) return null; Stack<Integer> path = new Stack<Integer>(); path.push(v); int w = last[u][v]; while (w != u) { path.push(w); w = last[u][w]; } return path; } private void computeRoutingTables() { for (int u = 0; u < _V_; u++) { for (int v = 0; v < _V_; v++) { Stack<Integer> s = getPath(u, v); if (s != null) next[u][v] = s.peek().intValue(); } } } private boolean check () { for (int u = 0; u < _V_; u++) { for (int v = 0; v < _V_; v++) { ArrayList<Integer> neighbours = getNeighbours(u); for (Integer w: neighbours) { int z = w.intValue(); if (cost[u][v] > cost[u][z] + cost[z][v]) return false; } } } return true; } /* Unit tests */ public static void main(String[] args) { int N = Integer.parseInt(args[0]); String filename = args[1]; /* Floyd-Warshall algorithm */ RoutingOracle o = new RoutingOracle(N, filename); /* Is it connected? */ for (int u = 0; u < N; u++) { for (int v = 0; v < N; v++) { if (! o.hasPath(u, v)) { System.err.println( "Error: path from " + u + " to " + v + " does not exist" ); return; } } } /* Print neighbors */ for (int u = 0; u < N; u++) { System.out.println(String.format("%2d's neighbors are %s", u, o.getNeighbours(u))); } System.out.println(String.format("Path from %d to %d is %s", 0, 4, o.getPath(0, 4))); } }
22.950178
87
0.556675
869c1a696f69eefe9ca5a4519a08c9a7cc81e8d7
709
package br.com.pokemon.dtos.pokemon; import java.io.Serializable; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.v3.oas.annotations.media.Schema; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor @Schema(description = "The pokemon model") public class PokemonDTO implements Serializable { private static final long serialVersionUID = -7750174946326484179L; @Schema(description = "The order the Pokémon's types are listed in.") @JsonProperty("slot") private Integer pokemonOrder; @Schema(description = "The Pokémon's collection for a specific type.") private PokemonNameUrlDTO pokemon; }
25.321429
71
0.802539
96936fbf98883d5a9ed9d9455a16eea4b0d3e6fd
1,864
/* * Copyright 2021 The Chromium OS Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ package org.chromium.arc.testapp.arcstandardizedtouchscreentest; import android.app.Activity; import android.os.Bundle; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; public class MainActivity extends Activity { private LinearLayout mLayoutMain; private Button mBtnTap; private int mBtnTapCounter = 1; private Button mBtnLongTap; private int mBtnLongTapCounter = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mLayoutMain = findViewById(R.id.layoutMain); // Add the text 'Touchscreen Tap' when the button is pressed. // Always add the counter so the tast test can make sure a single tap // doesn't fire two events. mBtnTap = findViewById(R.id.btnTap); mBtnTap.setOnClickListener(v -> { addTextViewToLayout(String.format("TOUCHSCREEN TAP (%d)", mBtnTapCounter)); mBtnTapCounter++; }); // Add the text 'Touchscreen Long Tap' when a long tap is performed. Use the same // counter logic as above to make sure multiple events aren't fired for a single event. mBtnLongTap = findViewById(R.id.btnLongTap); mBtnLongTap.setOnLongClickListener(v -> { addTextViewToLayout(String.format("TOUCHSCREEN LONG TAP (%d)", mBtnLongTapCounter)); mBtnLongTapCounter++; return true; }); } private void addTextViewToLayout(String text) { TextView el = new TextView(this); el.setText(text); mLayoutMain.addView(el); } }
32.701754
96
0.682403
7624c9f6c2878ab5e4f2e15e718f003ba523754a
921
package org.kodejava.example.commons.beanutils; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class Recording { private Long id; private String title; private List<Track> tracks = new ArrayList<>(); private Map<String, Track> mapTracks = new HashMap<>(); public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public List<Track> getTracks() { return tracks; } public void setTracks(List<Track> tracks) { this.tracks = tracks; } public void setMapTracks(Map<String, Track> mapTracks) { this.mapTracks = mapTracks; } public Map<String, Track> getMapTracks() { return mapTracks; } }
20.021739
60
0.619978
e322e21063ea06ce5855ddd490a44285ef2b4bf8
1,814
package helpers; /** * Created by xjpz on 2021/8/9. */ import java.util.LinkedList; import java.util.List; /** * 参考 https://github.com/andyzty/sensitivewd-filter */ public class WordNode { private int value; // 节点名称 private List<WordNode> subNodes; // 子节点 private boolean isLast;// 默认false public WordNode(int value) { this.value = value; } public WordNode(int value, boolean isLast) { this.value = value; this.isLast = isLast; } /** * * @param subNode * @return 就是传入的subNode */ private WordNode addSubNode(final WordNode subNode) { if (subNodes == null) subNodes = new LinkedList<WordNode>(); subNodes.add(subNode); return subNode; } /** * 有就直接返回该子节点, 没有就创建添加并返回该子节点 * * @param value * @return */ public WordNode addIfNoExist(final int value, final boolean isLast) { if (subNodes == null) { return addSubNode(new WordNode(value, isLast)); } for (WordNode subNode : subNodes) { if (subNode.value == value) { if (!subNode.isLast && isLast) subNode.isLast = true; return subNode; } } return addSubNode(new WordNode(value, isLast)); } public WordNode querySub(final int value) { if (subNodes == null) { return null; } for (WordNode subNode : subNodes) { if (subNode.value == value) return subNode; } return null; } public boolean isLast() { return isLast; } public void setLast(boolean isLast) { this.isLast = isLast; } @Override public int hashCode() { return value; } }
20.613636
73
0.542999
8c8fa811d02b70e9e173e8892455fef48a43ab33
94
package me.yifeiyuan.fantasy; /** * Created by 程序亦非猿 on 2019-07-01. */ public class H { }
10.444444
34
0.648936
3b04ec91b0467e7bb1007da916ffc0558a482505
2,594
package com.iut.as.controller.facade; import static com.iut.as.enumerations.EPersistance.MYSQL; import static com.iut.as.factory.dao.DaoFactory.getDaoFactory; import java.util.List; import org.apache.log4j.Logger; import com.iut.as.exceptions.BankBusinessException; import com.iut.as.factory.dao.DaoFactory; import com.iut.as.modele.Client; import com.iut.as.modele.Compte; /*** * Utilisation du design pattern 'Facade' qui cache la complexité de code. * * @author stephane.joyeux * */ public class BankManager { private DaoFactory dao; private static final Logger logger = Logger.getLogger(BankManager.class); public BankManager() throws Exception { // Ici je me connecte à ma base de données. dao = getDaoFactory(MYSQL); } /** * Fonction qui permet de savoir si un utilisateur existe et si le mot de passe * est correct. * * @param userCde * @param userPwd * @return */ public Client userIsAllowed(String userCde, String userPwd) { // 1er appel DB : logger.info("======= Appel DB"); Client client = dao.getDaoClient().readByKey(userCde); if (client == null) { logger.info("Le client n'existe pas !"); throw new BankBusinessException("userIsAllowed()", "- Utilisateur non trouvé - "); } boolean passwordOk = client.getPassword().equals(userPwd); if (passwordOk) { logger.info("Le client existe et le mode de passe est correct !"); // Récupération de tous les comptes du client : // getComptesByClient(client); return client; } else { logger.error("Le client existe et le mode de passe est INcorrect !"); throw new BankBusinessException("userIsAllowed()", "- Mot de passe incorrect - "); } } public List<Compte> getComptesByClient(String numeroClient) { // 2ème appel DB : logger.info("======= Appel DB"); return dao.getDaoCompte().getComptesByClient(numeroClient); } public void getComptesByClient(Client client) { // 2ème appel DB : logger.info("======= Appel DB"); List<Compte> comptes = dao.getDaoCompte().getComptesByClient(client.getNumeroClient()); // Itération : for (Compte compte : comptes) { client.addCompte(compte); } if (client.getComptes() != null) { logger.info("le client possède : " + client.getComptes().size() + " compte(s)"); } } //Ajout examen public double crediter(String numeroClient, String numCompte, double montant) { logger.info("======= Appel DB"); Client client= dao.getDaoClient().readByKey(numeroClient);; Compte compte = dao.getDaoCompte().readByKey(numCompte); compte.crediter(montant); return compte.getSolde(); } }
27.892473
89
0.701234
184c48d8f3ee1d87bb3e8d22f9409f6a4cff5f4a
8,934
/* * Copyright 2013-2014 S. Webber * * 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.projog.core.udp; import java.util.Iterator; import java.util.concurrent.ConcurrentHashMap; import org.projog.core.KnowledgeBase; import org.projog.core.Predicate; import org.projog.core.PredicateKey; import org.projog.core.SpyPoints; import org.projog.core.term.Term; import org.projog.core.udp.interpreter.ClauseAction; import org.projog.core.udp.interpreter.ClauseActionFactory; import org.projog.core.udp.interpreter.InterpretedUserDefinedPredicate; /** * Maintains a record of the clauses that represents a "dynamic" user defined predicate. * <p> * A "dynamic" user defined predicate is one that can have clauses added and removed <i>after</i> it has been first * defined. This is normally done using the {@code asserta/1}, {@code assertz/1} and {@code retract/1} predicates. * * @see org.projog.core.udp.interpreter.InterpretedUserDefinedPredicate */ public final class DynamicUserDefinedPredicateFactory implements UserDefinedPredicateFactory { // use array rather than two instances so that references not lost between // copies when heads or tails alter private static final int FIRST = 0; private static final int LAST = 1; private final Object LOCK = new Object(); private final KnowledgeBase kb; private final SpyPoints.SpyPoint spyPoint; private final ClauseActionMetaData[] ends = new ClauseActionMetaData[2]; private ConcurrentHashMap<Term, ClauseActionMetaData> index; private boolean hasPrimaryKey; public DynamicUserDefinedPredicateFactory(KnowledgeBase kb, PredicateKey predicateKey) { this.kb = kb; if (predicateKey.getNumArgs() == 0) { this.hasPrimaryKey = false; this.index = null; } else { this.hasPrimaryKey = true; index = new ConcurrentHashMap<>(); } this.spyPoint = kb.getSpyPoints().getSpyPoint(predicateKey); } @Override public Predicate getPredicate(Term[] args) { if (hasPrimaryKey) { Term firstArg = args[0]; if (firstArg.isImmutable()) { ClauseActionMetaData match = index.get(firstArg); if (match == null) { return PredicateUtils.createFailurePredicate(spyPoint, args); } else { return PredicateUtils.createSingleClausePredicate(match.clause, spyPoint, args); } } } ClauseActionIterator itr = new ClauseActionIterator(ends[FIRST]); return new InterpretedUserDefinedPredicate(itr, spyPoint, args); } @Override public PredicateKey getPredicateKey() { return spyPoint.getPredicateKey(); } @Override public boolean isDynamic() { return true; } /** * Returns an iterator over the clauses of this user defined predicate. * <p> * The iterator returned will have the following characteristics: * <ul> * <li>Calls to {@link java.util.Iterator#next()} return a <i>new copy</i> of the {@link ClauseModel} to avoid the * original being altered.</li> * <li>Calls to {@link java.util.Iterator#remove()} <i>do</i> alter the underlying structure of this user defined * predicate.</li> * <li></li> * </ul> */ @Override public Iterator<ClauseModel> getImplications() { return new ImplicationsIterator(); } @Override public void addFirst(ClauseModel clauseModel) { synchronized (LOCK) { ClauseActionMetaData newClause = createClauseActionMetaData(clauseModel); addToIndex(clauseModel, newClause); // if first used in a implication antecedent before being used as a consequent, // it will originally been created with first and last both null ClauseActionMetaData first = ends[FIRST]; if (first == null) { ends[FIRST] = newClause; ends[LAST] = newClause; return; } newClause.next = first; first.previous = newClause; ends[FIRST] = newClause; } } @Override public void addLast(ClauseModel clauseModel) { synchronized (LOCK) { ClauseActionMetaData newClause = createClauseActionMetaData(clauseModel); addToIndex(clauseModel, newClause); // if first used in a implication antecedent before being used as a consequent, // it will originally been created with first and last both null ClauseActionMetaData last = ends[LAST]; if (last == null) { ends[FIRST] = newClause; ends[LAST] = newClause; return; } last.next = newClause; newClause.previous = last; ends[LAST] = newClause; } } private void addToIndex(ClauseModel clauseModel, ClauseActionMetaData metaData) { if (hasPrimaryKey) { Term firstArg = clauseModel.getConsequent().getArgument(0); if (!firstArg.isImmutable() || index.put(firstArg, metaData) != null) { hasPrimaryKey = false; index.clear(); } } } @Override public ClauseModel getClauseModel(int index) { ClauseActionMetaData next = ends[FIRST]; for (int i = 0; i < index; i++) { if (next == null) { return null; } next = next.next; } if (next == null) { return null; } return next.clause.getModel().copy(); } private ClauseActionMetaData createClauseActionMetaData(ClauseModel clauseModel) { return new ClauseActionMetaData(kb, clauseModel); } private static class ClauseActionIterator implements Iterator<ClauseAction> { private ClauseActionMetaData next; ClauseActionIterator(ClauseActionMetaData first) { next = first; } @Override public boolean hasNext() { return next != null; } /** need to call getFree on result */ @Override public ClauseAction next() { ClauseAction c = next.clause; next = next.next; return c; } @Override public void remove() { throw new UnsupportedOperationException(); } } private class ImplicationsIterator implements Iterator<ClauseModel> { private ClauseActionMetaData previous; @Override public boolean hasNext() { return getNext() != null; } /** * Returns a <i>new copy</i> to avoid the original being altered. */ @Override public ClauseModel next() { ClauseActionMetaData next = getNext(); ClauseModel clauseModel = next.clause.getModel(); previous = next; return clauseModel.copy(); } private ClauseActionMetaData getNext() { return previous == null ? ends[FIRST] : previous.next; } @Override public void remove() { // TODO find way to use index when retracting synchronized (LOCK) { if (hasPrimaryKey) { Term firstArg = previous.clause.getModel().getConsequent().getArgument(0); if (index.remove(firstArg) == null) { throw new IllegalStateException(); } } if (previous.previous != null) { previous.previous.next = previous.next; } else { ClauseActionMetaData newHead = previous.next; if (newHead != null) { newHead.previous = null; } ends[FIRST] = newHead; } if (previous.next != null) { previous.next.previous = previous.previous; } else { ClauseActionMetaData newTail = previous.previous; if (newTail != null) { newTail.next = null; } ends[LAST] = newTail; } if (ends[FIRST] == null && ends[LAST] == null) { hasPrimaryKey = index != null; } } } } private static class ClauseActionMetaData { final ClauseAction clause; ClauseActionMetaData previous; ClauseActionMetaData next; ClauseActionMetaData(KnowledgeBase kb, ClauseModel clauseModel) { this.clause = ClauseActionFactory.createClauseAction(kb, clauseModel); } } @Override public boolean isRetryable() { return true; } }
32.487273
117
0.629281
0423f926ef1bd068fb0b049a4d98daaa0bb68cdd
14,893
package com.deleidos.rtws.tools.devconsole; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSeparator; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.ListSelectionModel; import com.amazonaws.AmazonClientException; import com.amazonaws.auth.AWSCredentials; import com.amazonaws.auth.PropertiesCredentials; import com.amazonaws.services.ec2.AmazonEC2; import com.amazonaws.services.ec2.AmazonEC2Client; import com.amazonaws.services.ec2.model.AuthorizeSecurityGroupIngressRequest; import com.amazonaws.services.ec2.model.CreateSecurityGroupRequest; import com.amazonaws.services.ec2.model.DeleteSecurityGroupRequest; import com.amazonaws.services.ec2.model.DescribeSecurityGroupsResult; import com.amazonaws.services.ec2.model.IpPermission; import com.amazonaws.services.ec2.model.RevokeSecurityGroupIngressRequest; import com.amazonaws.services.ec2.model.SecurityGroup; import com.amazonaws.services.ec2.model.UserIdGroupPair; import com.deleidos.rtws.commons.config.PropertiesUtils; /** * Development Console for AWS environment. */ @SuppressWarnings("serial") public final class SecConsole extends JPanel implements ActionListener { private JTable table; private JTextField from,to,range; private JButton delete; private JComboBox groups; private static int lastselected=0; private JButton addButton, updateButton ,last, backup, restor,deletegroup, creategroup; private JList protocol, selectgourps; private JScrollPane listScrollPane, chooseScrollPane; private JFileChooser fc; static AmazonEC2 ec2; static JFrame frame ; static List<SecurityGroup> input; private List<IpPermission> permissions = new ArrayList<IpPermission>(); /** Constructor. */ private SecConsole() { super(new BorderLayout()); input = getData(); Object groupname[]= new Object[input.size()]; for (int c=0;c<input.size();c++){ groupname[c]=input.get(c).getGroupName(); } permissions = input.get(lastselected).getIpPermissions(); // Object[][] data=new Object[permissions.size()][4]; // for(int index=0;index<permissions.size();index++){ // data[index][0]=permissions.get(index).getIpProtocol(); // data[index][1]=permissions.get(index).getFromPort(); // data[index][2]=permissions.get(index).getToPort(); // data[index][3]=permissions.get(index).getIpRanges(); // } // table=new JTable(data,new String[]{"Protocol","From","To","Ranges"}); selectgourps=new JList(groupname); selectgourps.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); protocol=new JList(new Object[]{"TCP","UDP","ICMP"}); protocol.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); protocol.setSelectedIndex(0); chooseScrollPane= new JScrollPane(selectgourps); listScrollPane = new JScrollPane(table); groups= new JComboBox(groupname); groups.addActionListener(this); groups.setSelectedIndex(lastselected); table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); addButton=new JButton("Add"); addButton.addActionListener(new SelectListener()); updateButton=new JButton("Reload"); updateButton.addActionListener(new UpdateListener()); delete =new JButton("Remove"); delete.addActionListener(new SelectListener()); backup =new JButton("Backup Groups"); //backup.addActionListener(new SelectListener()); backup.setEnabled(false); creategroup=new JButton("Create Group"); creategroup.addActionListener(new SelectListener()); deletegroup=new JButton("Delete Group"); deletegroup.addActionListener(new SelectListener()); restor=new JButton("Restor Group"); //restor.addActionListener(new SelectListener()); restor.setEnabled(false); from=new JTextField("0"); to=new JTextField("0"); range=new JTextField("0.0.0.0/0"); add(listScrollPane,BorderLayout.CENTER); JPanel buttons=new JPanel(); buttons.setLayout(new BoxLayout(buttons, BoxLayout.Y_AXIS)); JPanel newip=new JPanel(); newip.setLayout(new BoxLayout(newip, BoxLayout.X_AXIS)); JPanel tofrom=new JPanel(); tofrom.setLayout(new BoxLayout(tofrom, BoxLayout.Y_AXIS)); newip.add(new JLabel("Add new rule: ")); newip.add(new JSeparator(1)); newip.add(new JLabel(" Protocol:")); newip.add(new JSeparator(1)); newip.add(protocol); newip.add(new JSeparator(1)); newip.add(new JLabel(" Port Range: ")); tofrom.add(new JLabel("From:")); tofrom.add(from); tofrom.add(new JLabel("To:")); tofrom.add(to); newip.add(tofrom); newip.add(new JLabel(" IP Range(s):")); newip.add(range); newip.add(new JLabel(" Groups:")); newip.add(chooseScrollPane); add(newip,BorderLayout.SOUTH); buttons.add(new JLabel("Domains")); buttons.add(groups); buttons.add(new JSeparator()); buttons.add(updateButton); buttons.add(new JSeparator()); buttons.add(creategroup); buttons.add(deletegroup); buttons.add(backup); buttons.add(restor); buttons.add(new JSeparator()); buttons.add(addButton); buttons.add(delete); add(buttons,BorderLayout.WEST); fc =new JFileChooser(); } // class ChangeListener implements ActionListener { public void actionPerformed(final ActionEvent e) { this.remove(listScrollPane); int pos=groups.getSelectedIndex(); String groupnames=""; permissions = input.get(pos).getIpPermissions(); Object[][] data=new Object[permissions.size()][5]; for(int index=0;index<permissions.size();index++){ data[index][0]=permissions.get(index).getIpProtocol(); data[index][1]=permissions.get(index).getFromPort(); data[index][2]=permissions.get(index).getToPort(); data[index][3]=permissions.get(index).getIpRanges(); for(int c=0;c<permissions.get(index).getUserIdGroupPairs().size();c++){ groupnames+=permissions.get(index).getUserIdGroupPairs().get(c).getGroupName()+ ", "; } data[index][4]=groupnames; groupnames=""; //System.out.println(permissions.get(index)); } table=new JTable(data,new String[]{"Protocal","From","To","Ranges", "Groups"}); listScrollPane = new JScrollPane(table); this.add(listScrollPane,BorderLayout.CENTER); Dimension d= frame.getSize(); frame.pack(); frame.setSize(d); } // } class UpdateListener implements ActionListener { public void actionPerformed(final ActionEvent e) { reload(true); }} class LoadListener implements ActionListener { public void actionPerformed(final ActionEvent e) { String path=""; if (e.getSource().equals(last)){ path="S:\\Software\\PuTTY\\script.txt"; } else{ int returnVal = fc.showOpenDialog(SecConsole.this); if (returnVal != JFileChooser.APPROVE_OPTION) { return; } path=fc.getSelectedFile().getPath(); } try { FileReader file = new FileReader(path); BufferedReader in= new BufferedReader(file); String read=in.readLine(); String newcmd=""; while(read!=null){ newcmd+=read+";"; read=in.readLine(); } //protocol.setText(newcmd); } catch (FileNotFoundException e1) { e1.printStackTrace(); } catch (IOException e1) { // e1.printStackTrace(); } }} class SelectListener implements ActionListener { public void actionPerformed(final ActionEvent e) { if (e.getSource().equals(delete)){ List<IpPermission> tempper = new ArrayList<IpPermission>(); IpPermission temp=new IpPermission(); int select[]=table.getSelectedRows(); for(int c=0;c<select.length;c++){ temp=(input.get(groups.getSelectedIndex()).getIpPermissions().get(select[c])); for(int i=0;i<temp.getUserIdGroupPairs().size();i++){ temp.getUserIdGroupPairs().get(i).setGroupId(null); } tempper.add(temp); } RevokeSecurityGroupIngressRequest r1 = new RevokeSecurityGroupIngressRequest(); r1.setGroupName(groups.getSelectedItem().toString()); r1.setIpPermissions(tempper); ec2.revokeSecurityGroupIngress(r1); reload(true); } else if (e.getSource().equals(addButton)){ AuthorizeSecurityGroupIngressRequest r2 = new AuthorizeSecurityGroupIngressRequest(); r2.setGroupName(groups.getSelectedItem().toString()); IpPermission permission = new IpPermission(); permission.setIpProtocol(protocol.getSelectedValue().toString().toLowerCase()); permission.setFromPort(Integer.decode(from.getText())); permission.setToPort(Integer.decode(to.getText())); List<String> ipRanges = new ArrayList<String>(); String[] iprange=range.getText().replace(" ", "").split(","); for(int c=0;c<iprange.length;c++) ipRanges.add(iprange[c]); List<UserIdGroupPair> uid=new ArrayList<UserIdGroupPair>(); int[] selected=selectgourps.getSelectedIndices(); for(int c=0;c<selected.length;c++){ UserIdGroupPair temp=new UserIdGroupPair(); temp.setGroupName(input.get(selected[c]).getGroupName()); uid.add(temp); } if (!uid.isEmpty()) permission.setUserIdGroupPairs(uid); if(range.getText().length()>2&&!ipRanges.isEmpty()) permission.setIpRanges(ipRanges); List<IpPermission> permissionlist = new ArrayList<IpPermission>(); permissionlist.add(permission); r2.setIpPermissions(permissionlist); try{ ec2.authorizeSecurityGroupIngress(r2); }catch(AmazonClientException e1){ JOptionPane.showMessageDialog(null, "Failed to add: "+e1.getMessage()); } reload(true); } else if(e.getSource().equals(restor)){ } else if (e.getSource().equals(deletegroup)){ if(JOptionPane.showConfirmDialog(null,"Are you sure you want to delete this group?")==0){ DeleteSecurityGroupRequest remover=new DeleteSecurityGroupRequest(); remover.setGroupName(groups.getSelectedItem().toString()); ec2.deleteSecurityGroup(remover); reload(true); } } else if (e.getSource().equals(creategroup)){ JTextField name=new JTextField("Name"); JTextField discription=new JTextField("Description"); JPanel create=new JPanel(); create.setLayout(new BoxLayout(create, BoxLayout.Y_AXIS)); create.add(name); create.add(discription); if(JOptionPane.showConfirmDialog(null,create,"New Security Group:",2)==0&&name.getText().trim().length()>1){ CreateSecurityGroupRequest r1 = new CreateSecurityGroupRequest(name.getText().trim(),discription.getText().trim()); try{ ec2.createSecurityGroup(r1); }catch(AmazonClientException ex){ JOptionPane.showMessageDialog(null, "Group already exists"); }; reload(true); int c=0; for(;!name.getText().trim().equals(input.get(c).getGroupName());c++){}; lastselected=c; reload(false); } } else{ } } } /** * Initialization routine. */ private static void init() { AWSCredentials credentials=null; // Load in the AWSCredentials try { credentials = new PropertiesCredentials(PropertiesUtils.loadResource("src/config/AwsCredentials.properties")); } catch (IOException e) { System.out.println("Failed to load credentials"); e.printStackTrace(); } // Initialize the object with the credentials ec2 = new AmazonEC2Client(credentials); } /** * Get all the instances from AWS. * @return Array of instance objects. */ protected static List<SecurityGroup> getData() { //CreateSecurityGroupRequest r1 = new CreateSecurityGroupRequest("SecConsole", "This is Elan's test security group"); //ec2.createSecurityGroup(r1); DescribeSecurityGroupsResult describeSecurityGroupsResult = ec2.describeSecurityGroups(); List<SecurityGroup> securityGroups = describeSecurityGroupsResult.getSecurityGroups(); return securityGroups; } /** * Set the AmazonEC2Client client. * @param client AmazonEC2Client */ private void reload(boolean changeindex){ if(changeindex) lastselected=groups.getSelectedIndex(); Dimension d= frame.getSize(); JComponent newContentPane = new SecConsole(); newContentPane.setOpaque(true); frame.setContentPane(newContentPane); frame.pack(); frame.setSize(d); } private static void createAndShowGUI() { frame= new JFrame("Sec Console"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JComponent newContentPane = new SecConsole(); newContentPane.setOpaque(true); frame.setContentPane(newContentPane); frame.setLocation(100, 100); frame.pack(); frame.setVisible(true); } public static void main(final String[] args) { init(); javax.swing.SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } }
38.483204
122
0.635466
579881b831ff4f4f254e9200bea5a74fc555b767
993
package com.gochinatv.cdn.api.basic.logger; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class LogLevelTest { /** * 这里使用 this.getClass() 那么子类调用,打印的则是子类的类名称 */ Logger logger = LoggerFactory.getLogger(this.getClass()); Logger sysout = LoggerFactory.getLogger("System.out"); Logger syserr= LoggerFactory.getLogger("System.err"); public static void main(String[] args) { LogLevelTest t = new LogLevelTest(); t.testDebugLevel(); } /** * com.gochinatv.cdn.api logback.xml 指定日志级别 */ public void testDebugLevel(){ //System.setOut(new LoggerPrintStream(sysout)); System.setErr(new LoggerPrintStream(syserr)); //如果把System.err写入到日志文件,需要自定义一个PrintStream System.err.println("============调试日志级别开始=========="); logger.trace("***********trace");//比 DEBUG 级别的粒度更细 logger.debug("***********debug"); logger.info("***********info"); logger.warn("***********warn"); logger.error("***********error"); } }
27.583333
93
0.632427
241da4112c1d5225d10a60ee58b2562a6e79505e
407
package com.youhualife.modules.topprod.service; import com.baomidou.mybatisplus.extension.service.IService; import com.youhualife.modules.topprod.entity.OCCEntity; import java.util.List; public interface OCCService extends IService<OCCEntity> { List<OCCEntity> getInfos(); /** * 根据occ01返回客户信息 * @param codes * @return */ List<OCCEntity> getByOcc01(List<String> codes); }
22.611111
59
0.727273
897284bc233cf047bcfcef74ab9ef50bf03c4678
2,867
package cool.happycoding.code.mybatis; import cn.hutool.core.util.ObjectUtil; import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; import org.apache.ibatis.reflection.MetaObject; import java.util.Date; /** * description * * @author lanlanhappy 2020/12/06 11:25 上午 */ public class HappyMybatisMetaObjectHandler implements MetaObjectHandler { private final AutoFieldFillHandler autoFieldFillHandler; public HappyMybatisMetaObjectHandler(AutoFieldFillHandler autoFieldFillHandler){ this.autoFieldFillHandler = autoFieldFillHandler; } @Override public void insertFill(MetaObject metaObject) { if (!checkField(metaObject, AutoFieldFillHandler.CREATED_TIME)) { this.strictInsertFill(metaObject, AutoFieldFillHandler.CREATED_TIME, Date::new, Date.class); } if (!checkField(metaObject, AutoFieldFillHandler.CREATED_BY)){ this.strictInsertFill(metaObject, AutoFieldFillHandler.CREATED_BY, autoFieldFillHandler::createdBy, String.class); } if (!checkField(metaObject, AutoFieldFillHandler.CREATED_BY_ID)){ this.strictInsertFill(metaObject, AutoFieldFillHandler.CREATED_BY_ID, autoFieldFillHandler::createdById, String.class); } if (!checkField(metaObject, AutoFieldFillHandler.UPDATED_TIME)){ this.strictInsertFill(metaObject, AutoFieldFillHandler.UPDATED_TIME, Date::new, Date.class); } if (!checkField(metaObject, AutoFieldFillHandler.UPDATED_BY)){ this.strictInsertFill(metaObject, AutoFieldFillHandler.UPDATED_BY, autoFieldFillHandler::updatedBy, String.class); } if (!checkField(metaObject, AutoFieldFillHandler.UPDATED_BY_ID)){ this.strictInsertFill(metaObject, AutoFieldFillHandler.UPDATED_BY_ID, autoFieldFillHandler::updatedById, String.class); } } @Override public void updateFill(MetaObject metaObject) { if (!checkField(metaObject, AutoFieldFillHandler.UPDATED_TIME)){ this.strictUpdateFill(metaObject, AutoFieldFillHandler.UPDATED_TIME, Date::new, Date.class); } if (!checkField(metaObject, AutoFieldFillHandler.UPDATED_BY)){ this.strictUpdateFill(metaObject, AutoFieldFillHandler.UPDATED_BY, autoFieldFillHandler::updatedBy, String.class); } if (!checkField(metaObject, AutoFieldFillHandler.UPDATED_BY_ID)){ this.strictUpdateFill(metaObject, AutoFieldFillHandler.UPDATED_BY_ID, autoFieldFillHandler::updatedById, String.class); } } /** * 当不存在该字段或该字段有值的时候不做自动填充处理 * @param metaObject * @param fieldName * @return */ protected boolean checkField(MetaObject metaObject, String fieldName){ return !metaObject.hasSetter(fieldName) || ObjectUtil.isNotNull(metaObject.getValue(fieldName)); } }
36.75641
131
0.728636
a9aa9355070b5c08bf7c0280ff62c7f4c0a6e916
125
package com.alibaba.sreworks.job.taskhandler; public enum ApiContentMethod { GET, POST, PUT, DELETE; }
8.928571
45
0.648
88c476b456a78933a30ce5f989be34ae46900533
394
package com.homw.test.bean; /** * @description 常量定义 * @author Hom * @version 1.0 * @since 2020-04-03 */ public class Constants { public static final int REDIS_TIME_OUT = 500; public static final String REDIS_NULL_VALUE = "null"; public static final String REDIS_EMPTY_KEY = "empty:key:"; public static final String REDIS_OPTIMISTIC_LOCK_KEY = "optimistic:lock:key:"; }
24.625
80
0.708122
079b3d57b33ca61da86b0c6f1614e94d4e885788
1,903
package me.peridot.premiumlogintest.storage; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.mashape.unirest.http.Unirest; import com.mashape.unirest.http.exceptions.UnirestException; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import java.util.concurrent.TimeUnit; public class PremiumNicknameCache { private final Cache<String, Boolean> premiumNicknameCache = CacheBuilder.newBuilder().expireAfterWrite(10, TimeUnit.MINUTES).build(); public boolean isPremium(String nickname) { boolean premium = false; Boolean value = premiumNicknameCache.getIfPresent(nickname); if (value == null) { if (getUUIDOfUsername(nickname) != null) { premium = true; } } else { premium = value; } return premium; } public String getUUIDOfUsername(String username) { try { return (String) getJSONObject("https://api.mojang.com/users/profiles/minecraft/" + username).get("id"); } catch (Exception ex) { return null; } } private JSONObject getJSONObject(String url) { JSONObject obj; try { obj = (JSONObject) new JSONParser().parse(Unirest.get(url).asString().getBody()); String err = (String) (obj.get("error")); if (err != null) { switch (err) { case "IllegalArgumentException": throw new IllegalArgumentException((String) obj.get("errorMessage")); default: throw new RuntimeException(err); } } } catch (ParseException | UnirestException ex) { throw new RuntimeException(ex); } return obj; } }
31.716667
137
0.607987
6a3449914e0b61befa29c371e1e2cca6d32b1846
1,465
/* * Copyright © 2014 Cask Data, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package co.cask.cdap.app.verification; import co.cask.cdap.proto.Id; /** * A verifier for verifying the specifications provided. * <p> * Implementors of this interface will take Specification as input * and verify the information within the specification meets satisfies * all the checkpoints. * </p> * <p/> * <p> * Implementation of this interface are expected to be thread-safe, * an can be safely accessed by multiple concurrent threads. * </p> * * @param <T> Type of object to be verified. */ public interface Verifier<T> { /** * Verifies <code>input</code> and returns {@link VerifyResult} * containing the status of verification. * * @param appId the application where this is verified * @param input to be verified * @return An instance of {@link VerifyResult} */ VerifyResult verify(Id.Application appId, T input); }
30.520833
80
0.719454
ca4317482f87009f51c16045c4a3114c6a93ff09
1,503
package com.stream.stumanager.control; import java.util.List; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import com.stream.stumanager.R; import com.stream.stumanager.model.Student; public class StudentAdapter extends ArrayAdapter<Student> { private int resourceId; public StudentAdapter(Context context, int resource, List<Student> objects) { super(context, resource, objects); resourceId = resource; } @Override public View getView(int position, View convertView, ViewGroup parent) { Student s = getItem(position); View view; ViewHolder viewHolder; if(convertView==null){ view = LayoutInflater.from(getContext()).inflate(resourceId, null); viewHolder = new ViewHolder(); viewHolder.id = (TextView)view.findViewById(R.id.stu_id); viewHolder.name = (TextView)view.findViewById(R.id.stu_name); viewHolder.sex = (TextView)view.findViewById(R.id.stu_sex); viewHolder.birth = (TextView)view.findViewById(R.id.stu_birth); view.setTag(viewHolder); }else{ view = convertView; viewHolder = (ViewHolder)view.getTag(); } viewHolder.id.setText(s.getStu_id()); viewHolder.name.setText(s.getStu_name()); viewHolder.sex.setText(s.getStu_sex()); viewHolder.birth.setText(s.getStu_birth()); return view; } class ViewHolder{ TextView id; TextView name; TextView sex; TextView birth; } }
26.839286
78
0.749168
9393eb663a96033dcb6115bcf4adacd04455c60d
356
/* * Copyright 2018, EnMasse authors. * License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html). */ package io.enmasse.iot.service.base; import io.fabric8.kubernetes.client.KubernetesClient; @FunctionalInterface public interface KubernetesOperation<T> { T run(KubernetesClient client) throws Exception; }
27.384615
101
0.769663
43868da2581a9caf524853e4f1e90bde01ad7106
3,357
/* * Copyright 2016 higherfrequencytrading.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.openhft.chronicle.wire; import net.openhft.chronicle.bytes.Bytes; import net.openhft.chronicle.bytes.BytesStore; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /* * Created by Peter Lawrey on 24/12/15. */ public class TextReadDocumentContext implements ReadDocumentContext { @SuppressWarnings("rawtypes") public static final BytesStore MSG_SEP = BytesStore.from("---"); @Nullable protected TextWire wire; protected boolean present, notComplete; private boolean metaData; private long readPosition, readLimit; public TextReadDocumentContext(@Nullable TextWire wire) { this.wire = wire; } @Override public boolean isMetaData() { return metaData; } @Override public void metaData(boolean metaData) { // NOTE: this will not change the entry in the queue just read. this.metaData = metaData; } @Override public boolean isPresent() { return present; } @Override public void closeReadPosition(long readPosition) { this.readPosition = readPosition; } @Override public void closeReadLimit(long readLimit) { this.readLimit = readLimit; } @Nullable @Override public Wire wire() { return wire; } @Override public void close() { long readLimit = this.readLimit; long readPosition = this.readPosition; AbstractWire wire0 = this.wire; wire0.bytes.readLimit(readLimit); wire0.bytes.readPosition(readPosition); present = false; } @Override public void start() { wire.getValueOut().resetBetweenDocuments(); @NotNull final Bytes<?> bytes = wire.bytes(); present = false; wire.consumePadding(); if (wire.bytes().startsWith(MSG_SEP)) { wire.bytes().readSkip(3); wire.consumePadding(); } if (bytes.readRemaining() < 1) { readLimit = readPosition = bytes.readLimit(); notComplete = false; return; } long position = bytes.readPosition(); wire.getValueIn().skipValue(); metaData = false; readLimit = bytes.readLimit(); readPosition = bytes.readPosition(); bytes.readLimit(bytes.readPosition()); bytes.readPosition(position); present = true; } @Override public long index() { return 0; } @Override public int sourceId() { return -1; } @Override public boolean isNotComplete() { return notComplete; } @Override public String toString() { return Wires.fromSizePrefixedBlobs(this); } }
25.240602
75
0.642836
01196071bbfe9f728f945088fe6385e66698c88a
2,073
package net.mobz.Entity; import net.mobz.glomod; import net.minecraft.entity.mob.PillagerEntity; import net.minecraft.sound.SoundEvent; import net.minecraft.sound.SoundEvents; import net.minecraft.util.math.BlockPos; import net.minecraft.entity.EntityType; import net.minecraft.entity.attribute.EntityAttributes; import net.minecraft.entity.damage.DamageSource; import net.minecraft.world.Difficulty; import net.minecraft.world.ViewableWorld; import net.minecraft.world.World; public class Archer2Entity extends PillagerEntity { public Archer2Entity(EntityType<? extends PillagerEntity> entityType, World world) { super(entityType, world); } @Override public boolean canSpawn(ViewableWorld viewableWorld_1) { BlockPos entityPos = new BlockPos(this.x, this.y - 1, this.z); return viewableWorld_1.intersectsEntities(this) && !viewableWorld_1.intersectsFluid(this.getBoundingBox()) && !viewableWorld_1.isAir(entityPos) && this.world.getLocalDifficulty(entityPos).getGlobalDifficulty() != Difficulty.PEACEFUL && this.world.isDaylight(); } @Override protected void dropEquipment(DamageSource damageSource_1, int int_1, boolean boolean_1) { return; } @Override public boolean cannotDespawn() { return false; } @Override public boolean canImmediatelyDespawn(double double_1) { return true; } @Override protected void initAttributes() { super.initAttributes(); this.getAttributeInstance(EntityAttributes.MAX_HEALTH).setBaseValue(30.0D); this.getAttributeInstance(EntityAttributes.ATTACK_DAMAGE).setBaseValue(6.0D); } @Override protected SoundEvent getHurtSound(DamageSource damageSource_1) { return SoundEvents.ENTITY_PLAYER_HURT; } @Override protected SoundEvent getDeathSound() { return SoundEvents.ENTITY_PLAYER_DEATH; } @Override protected SoundEvent getAmbientSound() { return glomod.NOTHINGEVENT; } }
30.485294
114
0.714906
4679890fd3cbc7091ea747a883311ef03d2c0b3a
13,535
/* * 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 leap.db.platform.mysql; import leap.db.DbLimitQuery; import leap.db.DbMetadata; import leap.db.DbVersion; import leap.db.change.ColumnDefinitionChange; import leap.db.change.SchemaChangeContext; import leap.db.model.DbColumn; import leap.db.model.DbColumnBuilder; import leap.db.model.DbSchemaObjectName; import leap.db.platform.GenericDbDialect; import leap.db.support.JsonColumnSupport; import leap.lang.Collections2; import leap.lang.New; import leap.lang.Strings; import leap.lang.convert.Converts; import leap.lang.value.Limit; import java.io.BufferedReader; import java.sql.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.function.Function; public class MySql5Dialect extends GenericDbDialect { /** * the reserved sql keywords not defined in {@link leap.db.platform.GenericDbDialectBase#SQL92_RESERVED_WORDS}. <p/> * * <p> * see:http://www.mysql.com/doc/en/Reserved_words.html. */ private static final String[] NONSQL92_RESERVED_WORDS = new String[]{ "ANALYZE", "AUTO_INCREMENT", "BDB", "BERKELEYDB", "BIGINT", "BINARY", "BLOB", "BTREE", "CHANGE", "COLUMNS", "DATABASE", "DATABASES", "DAY_HOUR", "DAY_MINUTE", "DAY_SECOND", "DELAYED", "DISTINCTROW", "DIV", "ENCLOSED", "ERRORS", "ESCAPED", "EXPLAIN", "FIELDS", "FORCE", "FULLTEXT", "FUNCTION", "GEOMETRY", "HASH", "HELP", "HIGH_PRIORITY", "HOUR_MINUTE", "HOUR_SECOND", "IF", "IGNORE", "INDEX", "INFILE", "INNODB", "KEYS", "KEY", "KILL", "LIMIT", "LINES", "LOAD", "LOCALTIME", "LOCALTIMESTAMP", "LOCK", "LONG", "LONGBLOB", "LONGTEXT", "LOW_PRIORITY", "MASTER_SERVER_ID", "MEDIUMBLOB", "MEDIUMINT", "MEDIUMTEXT", "MIDDLEINT", "MINUTE_SECOND", "MOD", "MRG_MYISAM", "OPTIMIZE", "OPTIONALLY", "OUTFILE", "PURGE", "REGEXP", "RENAME", "REPLACE", "REQUIRE", "RETURNS", "RLIKE", "RTREE", "SHOW", "SONAME", "SPATIAL", "SQL_BIG_RESULT", "SQL_CALC_FOUND_ROWS", "SQL_SMALL_RESULT", "SSL", "STARTING", "STRAIGHT_JOIN", "STRIPED", "TABLES", "TERMINATED", "TINYBLOB", "TINYINT", "TINYTEXT", "TYPES", "UNLOCK", "UNSIGNED", "USE", "USER_RESOURCES", "VARBINARY", "VARCHARACTER", "WARNINGS", "XOR", "YEAR_MONTH", "ZEROFILL", "INT", "INT1", "INT2", "INT3", "INT4", "INT8", "USAGE"}; private static final String[] SYSTEM_SCHEMAS = new String[]{"INFORMATION_SCHEMA", "PERFORMANCE_SCHEMA"}; protected JsonColumnSupport jsonColumnSupport; protected MySql5Dialect() { } @Override protected void registerMetadata(DbMetadata metadata) { super.registerMetadata(metadata); //json support starts from 5.7.8, but better support starts from 5.7.13 //https://dev.mysql.com/doc/refman/5.7/en/json-search-functions.html#operator_json-inline-path if (version.ge(DbVersion.of(5, 7, 13))) { jsonColumnSupport = new MySqlJsonColumnSupport(); } } @Override public boolean useTableAliasAfterDelete() { return true; } @Override protected String getAutoIncrementColumnDefinitionEnd(DbColumn column) { return "AUTO_INCREMENT"; } @Override protected String getTestDriverSupportsGetParameterTypeSQL() { return "select 1 from dual where 1 = ?"; } @Override public String getDefaultSchemaName(Connection connection, DatabaseMetaData dm) throws SQLException { return connection.getCatalog(); } @Override protected void setNonNullParameter(PreparedStatement ps, int index, Object value, int type) throws SQLException { super.setNonNullParameter(ps, index, value, type); } @Override protected Object getColumnValueTypeKnown(ResultSet rs, int index, int type) throws SQLException { //https://dev.mysql.com/doc/refman/5.7/en/binary-varbinary.html /* The BINARY and VARBINARY types are similar to CHAR and VARCHAR, except that they contain binary strings rather than nonbinary strings. That is, they contain byte strings rather than character strings. This means that they have no character set, and sorting and comparison are based on the numeric values of the bytes in the values */ if (type == Types.BINARY || type == Types.VARBINARY) { return rs.getString(index); } return super.getColumnValueTypeKnown(rs, index, type); } @Override protected Object getColumnValueTypeKnown(ResultSet rs, String name, int type) throws SQLException { if (type == Types.BINARY || type == Types.VARBINARY) { return rs.getString(name); } return super.getColumnValueTypeKnown(rs, name, type); } @Override protected String getColumnDatetimeDef(DbColumn column) { return "datetime"; } @Override protected String getColumnDefaultDefinition(DbColumn column) { if (Types.TIMESTAMP == column.getTypeCode()) { if ((!column.isNullable()) && !column.isDatetime() && Strings.isEmpty(column.getDefaultValue())) { return "DEFAULT NOW(3)"; } } return super.getColumnDefaultDefinition(column); } @Override public String qualifySchemaObjectName(String catalog, String schema, String name) { return super.qualifySchemaObjectName(null, schema, name); } @Override public String readDefaultValue(int typeCode, String nativeDefaultValue) { // MySQL converts illegal date/time/timestamp values to "0000-00-00 00:00:00", but this // is an illegal ISO value, so we replace it with NULL if ((typeCode == Types.TIMESTAMP) && "0000-00-00 00:00:00".equals(nativeDefaultValue)) { return null; } else if (Strings.equals("b'0'", nativeDefaultValue)) { return "0"; } else if (Strings.equals("b'1'", nativeDefaultValue)) { return "1"; } return super.readDefaultValue(typeCode, nativeDefaultValue); } @Override public String getLimitQuerySql(DbLimitQuery query) { //[LIMIT {[offset,] row_count | row_count OFFSET offset}] //The offset of the initial row is 0 (not 1): Limit limit = query.getLimit(); int offset = limit.getStart() - 1; int rows = limit.getEnd() - offset; String sql = query.getSql(db) + " limit ?,?"; query.getArgs().add(offset); query.getArgs().add(rows); return sql; } @Override protected List<String> createSafeAlterColumnSqlsForChange(SchemaChangeContext context, ColumnDefinitionChange change) { List<String> sqls = new ArrayList<String>(); if (change.isUniqueChanged()) { sqls.add(getAddUniqueColumnSql(change.getTable(), change.getOldColumn().getName())); if (change.getPropertyChanges().size() > 1) { DbColumn c = new DbColumnBuilder(change.getNewColumn()).setUnique(false).build(); sqls.add(getAlterColumnSql(change.getTable(), c)); } } else { sqls.add(getAlterColumnSql(change.getTable(), change.getNewColumn())); } return sqls; } protected String getAddUniqueColumnSql(DbSchemaObjectName tableName, String columnName) { return "ALTER TABLE " + qualifySchemaObjectName(tableName) + " ADD UNIQUE(" + quoteIdentifier(columnName) + ")"; } protected String getAlterColumnSql(DbSchemaObjectName tableName, DbColumn column) { return "ALTER TABLE " + qualifySchemaObjectName(tableName) + " MODIFY COLUMN " + getColumnDefinitionForAlterTable(column); } @Override public List<String> getDropForeignKeySqls(DbSchemaObjectName tableName, String fkName) { return New.arrayList("ALTER TABLE " + qualifySchemaObjectName(tableName) + " DROP FOREIGN KEY " + fkName); } @Override public List<String> getDropIndexSqls(DbSchemaObjectName tableName, String ixName) { return New.arrayList("DROP INDEX " + ixName + " ON " + qualifySchemaObjectName(tableName)); } @Override protected void registerSQLKeyWords() { super.registerSQLKeyWords(); this.sqlKeyWords.addAll(Arrays.asList(NONSQL92_RESERVED_WORDS)); } @Override protected void registerSystemSchemas() { Collections2.addAll(systemSchemas, SYSTEM_SCHEMAS); } @Override protected void registerColumnTypes() { //see http://dev.mysql.com/doc/refman/5.6/en/storage-requirements.html columnTypes.add(Types.BOOLEAN, "boolean", 0, 0, Types.BIT); columnTypes.add(Types.BIT, "bit"); columnTypes.add(Types.TINYINT, "tinyint"); columnTypes.add(Types.SMALLINT, "smallint"); columnTypes.add(Types.INTEGER, "integer"); columnTypes.add(Types.BIGINT, "bigint"); //JDBC's real type mapping to java's float, JDBC's float type mapping to java's double columnTypes.add(Types.REAL, "float"); columnTypes.add(Types.FLOAT, "double precision"); columnTypes.add(Types.DOUBLE, "double precision"); columnTypes.add(Types.DECIMAL, "decimal($p,$s)"); columnTypes.add(Types.NUMERIC, "decimal($p,$s)"); columnTypes.add(Types.CHAR, "char($l)", 0, 255); columnTypes.add(Types.VARCHAR, "varchar($l)", 0, 65535); columnTypes.add(Types.VARCHAR, "longtext"); columnTypes.add(Types.LONGVARCHAR, "longtext"); columnTypes.add(Types.BINARY, "binary($l)", 1, 255); columnTypes.add(Types.BINARY, "longblob"); columnTypes.add(Types.VARBINARY, "varbinary($l)", 1, 65535); columnTypes.add(Types.VARBINARY, "longblob"); columnTypes.add(Types.LONGVARBINARY, "longblob"); columnTypes.add(Types.DATE, "date"); columnTypes.add(Types.TIME, "time"); columnTypes.add(Types.BLOB, "blob"); columnTypes.add(Types.CLOB, "text"); //https://dev.mysql.com/doc/refman/5.6/en/timestamp-initialization.html //Before 5.6.5, this is true only for TIMESTAMP, and for at most one TIMESTAMP column per table. columnTypes.add(Types.TIMESTAMP, "timestamp(3)"); } @Override protected String getOpenQuoteString() { return "`"; } @Override protected String getCloseQuoteString() { return "`"; } @Override protected String parseDelimiter(BufferedReader reader, String delimiter, String line) { if (Strings.startsWithIgnoreCase(line, "delimiter ")) { String newDelimiter = Strings.removeStartIgnoreCase(line, "delimiter").trim(); while (newDelimiter.length() > 0 && newDelimiter.endsWith(delimiter)) { newDelimiter = Strings.removeEnd(newDelimiter, delimiter); } if (newDelimiter.length() > 0) { return newDelimiter; } } return null; } @Override public String quoteIdentifier(String identifier, boolean quoteKeywordOnly) { if (Strings.equalsIgnoreCase(identifier, "dual")) { return identifier; } return super.quoteIdentifier(identifier, quoteKeywordOnly); } @Override public JsonColumnSupport getJsonColumnSupport() { return jsonColumnSupport; } @Override public String getJsonColumnValue(ResultSet rs, int column, int type) throws SQLException { if (null == jsonColumnSupport) { return super.getJsonColumnValue(rs, column, type); } else { Object value = super.getJsonColumnValue(rs, column, type); if (null == value) { return null; } value = jsonColumnSupport.readValue(value); return Converts.toString(value); } } protected class MySqlJsonColumnSupport implements JsonColumnSupport { @Override public String getUpdateExpr(String alias, String column, String[] keys, Function<String, String> nameToParam) { final StringBuilder s = new StringBuilder(); if (null != alias) { s.append(alias).append('.'); } s.append(column); s.append(" = JSON_SET(COALESCE("); if (null != alias) { s.append(alias).append('.'); } s.append(column).append(",'{}')"); for (String key : keys) { s.append(','); s.append("'$.").append(key).append("',"); s.append(nameToParam.apply(key)); } s.append(')'); return s.toString(); } @Override public String getSelectItemExpr(String column, String key) { return column + "->>'$." + key + "'"; } } }
37.082192
123
0.637237
f486b4315f69ce5679080bc164fb7eb1c7fd599d
3,061
/* * Copyright 2019 Ramon. * * 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.ahp.service; import com.ahp.domain.Lista; import com.ahp.domain.Usuario; import com.ahp.eis.ListaDao; import java.util.List; import javax.ejb.Stateless; import javax.inject.Inject; /** * * @author Ramon */ @Stateless public class ListaServiceImp implements ListaService { @Inject ListaDao listaDao; /** * * @return */ @Override public List<Lista> listarListas() { return listaDao.listarListas(); } /** * * @param lista * @return */ @Override public Lista buscarListaPorId(Lista lista) { return listaDao.buscarListaPorId(lista); } /** * * @param lista * @return */ @Override public Lista buscarListaPorNombre(Lista lista) { return listaDao.buscarListaPorNombre(lista); } /** * * @param lista * @return */ @Override public List<Lista> buscarListaPorFechaCreacion(Lista lista) { return listaDao.buscarListaPorFechaCreacion(lista); } /** * * @param lista * @return */ @Override public List<Lista> buscarListaAnteriorFecha(Lista lista) { return listaDao.buscarListaAnteriorFecha(lista); } /** * * @param lista * @return */ @Override public List<Lista> buscarListaPosteriorFecha(Lista lista) { return listaDao.buscarListaPosteriorFecha(lista); } /** * * @param usuario * @return */ @Override public List<Lista> buscarListaPorUsuario(Usuario usuario) { return listaDao.buscarListaPorUsuario(usuario); } /** * * @param lista * @return */ @Override public List<Lista> buscarListaPorNombreYUsuario(Lista lista){ return listaDao.buscarListaPorNombreYUsuario(lista); } /** * * @param lista */ @Override public void agregarLista(Lista lista) { listaDao.agregarLista(lista); } /** * * @param lista */ @Override public void actualizarLista(Lista lista) { if (lista != null) listaDao.actualizarLista(lista); } /** * * @param lista */ @Override public void borrarLista(Lista lista) { listaDao.borrarLista(lista); } }
21.256944
76
0.582816
0d237da64e38bda473692e1e91349b845fa3c4d9
678
package com.liumapp.convert.cell; import junit.framework.TestCase; import org.junit.Test; import java.io.FileNotFoundException; /** * @author liumapp * @file CellToPDFTest.java * @email [email protected] * @homepage http://www.liumapp.com * @date 4/26/18 */ public class CellToPDFTest extends TestCase { private String pdfPath = "/usr/local/tomcat/project/convert-excel-to-pdf/test.pdf"; private String excelPath = "/usr/local/tomcat/project/convert-excel-to-pdf/excel/test.xlsx"; @Test public void testConvert () throws FileNotFoundException { CellToPDF doc2PDF = new CellToPDF(); doc2PDF.excel2pdf(pdfPath,excelPath); } }
23.37931
96
0.718289
952ae042c2e082ed2bfba028c8b30b47ba88390f
1,695
/* * Copyright 2021 pi. * * 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.huberb.apacheactivemq.examples.picocli.jms.main; import picocli.CommandLine; /** * * @author pi */ public class ActivemqOptions { //--- activemq @CommandLine.Option( names = {"--activemq-userName"}, paramLabel = "USERNAME", defaultValue = "admin", description = "activemq userName") private String userName; @CommandLine.Option( names = {"--activemq-password"}, paramLabel = "PASSWORD", defaultValue = "password", description = "activemq password") private String password; @CommandLine.Option( names = {"--activemq-brokerURL"}, paramLabel = "BROKER_URL", defaultValue = "tcp://localhost:61616", description = "activemq brokerURL, format tcp://{host}:{port}, eg. `tcp://localost:61616'") private String brokerURL; public String getUserName() { return userName; } public String getPassword() { return password; } public String getBrokerURL() { return brokerURL; } }
28.728814
103
0.637168
742d2add0fab254558f0f1cff72430ba7822a071
996
/* $This file is distributed under the terms of the license in LICENSE$ */ package edu.cornell.mannlib.vitro.webapp.edit.n3editing.VTwo; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import stubs.javax.servlet.http.HttpServletRequestStub; import edu.cornell.mannlib.vitro.webapp.controller.VitroRequest; public class EditConfigurationUtilsTest { @Before public void setUp() throws Exception { } @Test public void testGetEditKey() { HttpServletRequestStub req = new HttpServletRequestStub(); req.addParameter("datapropKey", "2343"); Integer hash = EditConfigurationUtils.getDataHash(new VitroRequest(req)); Assert.assertNotNull(hash); Assert.assertEquals(new Integer(2343), hash); req = new HttpServletRequestStub(); hash = EditConfigurationUtils.getDataHash(new VitroRequest(req)); Assert.assertNull( hash); } }
26.918919
81
0.677711
0c51b7bb935691de6e581609ee197f7c9de344ca
1,786
package net.sourceforge.mayfly.evaluation.from; import junit.framework.TestCase; import net.sourceforge.mayfly.MayflyException; import net.sourceforge.mayfly.Options; import net.sourceforge.mayfly.datastore.DataStore; import net.sourceforge.mayfly.datastore.Schema; import net.sourceforge.mayfly.evaluation.ResultRow; import net.sourceforge.mayfly.evaluation.expression.SingleColumn; import net.sourceforge.mayfly.evaluation.select.StoreEvaluator; public class FromTableTest extends TestCase { public void testCaseSensitiveTableName() throws Exception { Options options = new Options(true); DataStore store = new DataStore( new Schema().createTable("foo", "x")); try { new FromTable("Foo", "f") .dummyRow( new StoreEvaluator(store, DataStore.ANONYMOUS_SCHEMA_NAME, options)); fail(); } catch (MayflyException e) { assertEquals( "attempt to refer to table foo as Foo " + "(with case sensitive table names enabled)", e.getMessage()); } } public void testOptionsPassedToRows() throws Exception { Options options = new Options(true); DataStore store = new DataStore( new Schema().createTable("foo", "x")); ResultRow dummyRow = new FromTable("foo", "f") .dummyRow( new StoreEvaluator(store, DataStore.ANONYMOUS_SCHEMA_NAME, options)); assertEquals(1, dummyRow.size()); SingleColumn expression = (SingleColumn) dummyRow.expression(0); assertEquals("f", expression.tableOrAlias()); assertTrue(expression.options.tableNamesCaseSensitive()); } }
36.44898
72
0.638858
766400dbfe966ea21c40fa727337dd315a9e502b
454
package category.thread.ch03.ThreadLocal11.test; public class Run { public static ThreadLocal tl = new ThreadLocal(); public static void main(String[] args) { System.out.println(tl.get()); if (tl.get() == null) { System.out.println("从未放过值"); tl.set("我的值"); } System.out.println(tl.get()); System.out.println(tl.get()); tl.set("dfdf"); System.out.println(tl.get()); // System.out.println(tl.getMap(Thread.currentThread())); } }
22.7
58
0.662996
1718032bb93a228035d97ec5d72a762a94915c00
233
/** * */ package com.model; /** * @author Ashwin * */ public class Conditional { private String ans; public String getAns() { return ans; } public void setAns(String ans) { this.ans = ans; } }
10.590909
34
0.545064
9dfc74763c35a11770b8b342fef911083f94327d
1,671
package org.drools.rule.builder.dialect.java.parser; import java.util.ArrayList; import java.util.List; import org.drools.rule.builder.dialect.java.parser.JavaBlockDescr.BlockType; public class JavaTryBlockDescr extends AbstractJavaContainerBlockDescr implements JavaBlockDescr, JavaContainerBlockDescr { private int start; private int end; private int textStart; private List<JavaCatchBlockDescr> catchBlocks = new ArrayList<JavaCatchBlockDescr>(); private JavaFinalBlockDescr finalBlock; public JavaTryBlockDescr() { } public int getStart() { return start; } public void setStart(int start) { this.start = start; } public int getEnd() { return end; } public void setEnd(int end) { this.end = end; } public int getTextStart() { return textStart; } public void setTextStart(int textStart) { this.textStart = textStart; } public BlockType getType() { return BlockType.TRY; } public String getTargetExpression() { throw new UnsupportedOperationException(); } public void setTargetExpression(String str) { throw new UnsupportedOperationException(); } public void addCatch(JavaCatchBlockDescr cd) { this.catchBlocks.add( cd ); } public void setFinally(JavaFinalBlockDescr fd) { this.finalBlock = fd; } public List<JavaCatchBlockDescr> getCatches() { return catchBlocks; } public JavaFinalBlockDescr getFinal() { return finalBlock; } }
21.986842
89
0.635548
d695a9d6672a274c010cd3d5066f4a212d544407
2,761
package ch.virt.trayutils.modules; import ch.virt.trayutils.event.MainEventBus; import ch.virt.trayutils.event.InputBus; import ch.virt.trayutils.settings.ModuleSettings; import javax.swing.*; import java.util.HashMap; /** * Loads and handles the modules * @author VirtCode * @version 1.0 */ public class ModuleLoader { private static final String TAG = "[ModuleLoader] "; private HashMap<Integer, Module> modules; private MainEventBus events; private InputBus inputs; /** * Creates a Module Loader * @param bus main event bus * @param inputs input bus */ public ModuleLoader(MainEventBus bus, InputBus inputs) { modules = new HashMap<>(); this.events = bus; this.inputs = inputs; } /** * Registers a new module to the loader * @param module module to register */ public void registerModule(Module module){ module.setBuses(events, inputs); module.create(); modules.put(module.getId(), module); System.out.println(TAG + "Registered Module " + module.getName()); } /** * Calls a key event ot a module * @param id id of that module */ public void keyEventForModule(int id){ Module module = modules.get(id); if (module instanceof ActionModule && module.isEnabled()) ((ActionModule)module).keyStrokeCalled(); } /** * applies the new module settings to a module * @param settings settings to apply */ public void distributeSettings(ModuleSettings[] settings){ for (ModuleSettings setting : settings) { if(modules.get(setting.getId()) != null){ setting.apply(modules.get(setting.getId())); } } } /** * Fetches all settings of present modules * @return fetched settings */ public ModuleSettings[] fetchSettings(){ ModuleSettings[] settings = new ModuleSettings[modules.size()]; Module[] modules = this.modules.values().toArray(new Module[0]); for (int i = 0; i < modules.length; i++) { settings[i] = new ModuleSettings(modules[i]); } return settings; } /** * Returns all the modules in a array * @return modules */ public Module[] getModules(){ return modules.values().toArray(new Module[0]); } /** * Returns a keybind to module hashMap * @return map */ public HashMap<Integer, Integer> getKeyModuleMap(){ HashMap<Integer, Integer> map = new HashMap<>(); for (Module module : modules.values()) { if(module instanceof ActionModule) map.put(((ActionModule) module).getKeyBind(), module.getId()); } return map; } }
28.173469
109
0.614632
519c7899b102b4911d74b41b9974cc5264f6f068
714
package com.gitee.myclouds.gateway; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.zuul.EnableZuulProxy; import org.springframework.context.annotation.Bean; import com.gitee.myclouds.gateway.filter.MyDemoFilter; /** * MyClouds网关系统 * * @author xiongchun * */ @SpringBootApplication @EnableZuulProxy public class StartGatewayApplication{ public static void main(String[] args) throws Exception { SpringApplication.run(StartGatewayApplication.class, args); } //初始化演示Filter @Bean public MyDemoFilter myDemoFilter() { return new MyDemoFilter(); } }
23.032258
69
0.761905
959c1f0941e9b422bbd831ecc538ff5ea170bc8d
5,035
package com.example.nidhisingh.todo.adapter; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.example.nidhisingh.todo.R; import com.example.nidhisingh.todo.activities.DetailActivity; import com.example.nidhisingh.todo.database.DatabaseHandler; import com.example.nidhisingh.todo.model.Task; import java.util.ArrayList; /** * Created by nidhisingh on 7/26/17. */ public class TaskRecyclerAdapter extends RecyclerView.Adapter<TaskRecyclerAdapter.TaskViewHolder> { private ArrayList<Task> listTask; private Context mContext; private ArrayList<Task> mFilteredList; private DatabaseHandler dbHandler; public TaskRecyclerAdapter(ArrayList<Task> listTask, Context mContext, DatabaseHandler dbhandler) { this.listTask = listTask; this.mContext = mContext; this.mFilteredList = listTask; this.dbHandler = dbhandler; } public class TaskViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { public TextView textViewName; public TextView textViewDate; public TextView textViewTime; private Context context; private ImageView deleteImage; private View priorityView; private TextView categoryTextView; private TextView notesTextView; public TaskViewHolder(Context context, View view) { super(view); textViewName = (TextView) view.findViewById(R.id.taskname1); textViewDate = (TextView) view.findViewById(R.id.taskDate); textViewTime = (TextView) view.findViewById(R.id.taskTime); deleteImage = (ImageView) view.findViewById(R.id.deleteimage); priorityView = view.findViewById(R.id.taskprioritycolor); categoryTextView = (TextView) view.findViewById(R.id.categoryTextView); notesTextView = (TextView) view.findViewById(R.id.notestextView); this.context = context; view.setOnClickListener(this); deleteImage.setOnClickListener(this); } @Override public void onClick(View v) { int position = getAdapterPosition(); if (position != RecyclerView.NO_POSITION) { Task t = listTask.get(position); String status = t.getStatus(); long row = t.getId(); if (v.getId() == R.id.deleteimage) { //remove from recycler view list listTask.remove(getAdapterPosition()); notifyItemRemoved(getAdapterPosition()); notifyItemRangeChanged(getAdapterPosition(), listTask.size()); //remove from DB dbHandler.deleteRow(row); } else { Context context = v.getContext(); Intent intent = new Intent(context, DetailActivity.class); intent.putExtra("taskname", t.getTaskName()); intent.putExtra("tasknotes", t.getTaskNotes()); intent.putExtra("duedate", t.getDueDate()); intent.putExtra("duetime", t.getDueTime()); intent.putExtra("priority", t.getPriority()); intent.putExtra("status", t.getStatus()); intent.putExtra("id", t.getId()); intent.putExtra("category", t.getCategory()); intent.putExtra("type", "Edittask"); context.startActivity(intent); } } } } @Override public TaskViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { // inflating recycler item view View itemView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.task_data, parent, false); return new TaskViewHolder(parent.getContext(), itemView); } @Override public void onBindViewHolder(final TaskViewHolder holder, int position) { Task task = listTask.get(position); holder.textViewName.setText(task.getTaskName()); holder.categoryTextView.setText("in " + task.getCategory()); if (!TextUtils.isEmpty(task.getTaskNotes())) { holder.notesTextView.setText("Notes : " + task.getTaskNotes()); } if (task.getPriority().equalsIgnoreCase("high")) { holder.priorityView.setBackgroundColor(Color.RED); } else { holder.priorityView.setBackgroundColor(Color.rgb(56, 142, 60)); //388e3c } holder.textViewDate.setText(task.getDueDate()); holder.textViewTime.setText(task.getDueTime()); } @Override public int getItemCount() { return mFilteredList.size(); } }
36.223022
103
0.631778
1c191857fc94c29d08a1f00056cb9edcb7661648
239
package org.gentar.biology.plan.attempt.crispr.mutagenesis_strategy; import org.springframework.data.repository.CrudRepository; public interface MutagenesisStrategyTypeRepository extends CrudRepository<MutagenesisStrategyType, Long> { }
34.142857
106
0.870293
643562480891cef5054ac977d89a53c963a6a4de
2,681
package com.theodinspire.codeadvent.WeekOne; import java.security.*; /** * Created by ecormack on 12/16/2016. */ public class DoorHasher { public static void main(String[] args) { String doorID = "ugkcyxxp"; //System.out.println("First door: " + firstDoor(doorID)); System.out.println(secondDoor(doorID)); } private static String firstDoor(String input) { MessageDigest md; String algorithm = "MD5"; StringBuilder builder = new StringBuilder(); int count = 0; int index = 0; try { md = MessageDigest.getInstance(algorithm); while (count < 8) { byte[] hash = md.digest((input + index++).getBytes()); if (hash[0] == 0 && hash[1] == 0 && (hash[2] & 0xf0) == 0) { builder.append(String.format("%x", hash[2])); ++count; } } } catch (NoSuchAlgorithmException e) { System.out.println("Algorithm " + algorithm + " does not exist"); e.printStackTrace(); System.exit(1); } return builder.toString(); } private static String secondDoor(String input) { PassBuilder passBuilder = new PassBuilder(); MessageDigest md; String algorithm = "MD5"; int index = 0; try { md = MessageDigest.getInstance(algorithm); while (!passBuilder.isComplete()) { byte[] hash = md.digest((input + index++).getBytes()); if (hash[0] == 0 && hash[1] == 0 && (hash[2] & 0xf0) == 0) { passBuilder.addCharacter(hash[2], hash[3]); } } } catch (NoSuchAlgorithmException e) { System.out.println("Algorithm " + algorithm + " does not exist"); e.printStackTrace(); System.exit(1); } return passBuilder.getPassword(); } private static class PassBuilder { private boolean complete = false; private String password = "ABCDEFGH"; public boolean isComplete() { return complete; } public String getPassword() { return password; } public void addCharacter(byte index, byte replacement) { char nova = String.format("%02x", replacement).charAt(0); char olda = (char) (index + 65); password = password.replace(olda, nova); System.out.println(password.replaceAll("[A-H]", "-")); if (!password.matches("\\w*[A-H]\\w*")) { complete = true; } } } }
28.221053
77
0.51809
6d722f3278e6a8684654b59d12df6cc36baf6765
2,699
package net.coding.program.common; import android.content.Context; import android.graphics.drawable.Drawable; import android.text.Html; import android.util.Log; import net.coding.program.R; import java.lang.reflect.Field; /** * Created by chaochen on 14-9-15. */ public class MyImageGetter implements Html.ImageGetter { private Context mActivity; public MyImageGetter(Context activity) { mActivity = activity; } static public int getResourceId(String s) { String name = s.replace('-', '_'); if (name.equals("e_mail")) { name = "e_mail"; } else if (name.equals("non_potable_water")) { name = "non_potable_water"; } else if (name.equals("+1")) { name = "a00001"; } else if (name.equals("_1")) { name = "a00002"; } else if (name.equals("new")) { name = "my_new_1"; } else if (name.equals("8ball")) { name = "my8ball"; } else if (name.equals("100")) { name = "my100"; } else if (name.equals("1234")) { name = "my1234"; } try { Field field = R.drawable.class.getField(name); return Integer.parseInt(field.get(null).toString()); } catch (Exception e) { Global.errorLog(e); } return R.drawable.app_icon_emoji; } @Override public Drawable getDrawable(String source) { Log.d("", "text drawable " + source); String name = getPhotoName(source); int id = getResourceId(name); Drawable drawable; drawable = mActivity.getResources().getDrawable(id); zoomDrwable(drawable, isMonkey(name)); return drawable; } // todo 删除 public static void zoomDrwable(Drawable drawable, boolean isMonkey) { int width = isMonkey ? GlobalData.sEmojiMonkey : GlobalData.sEmojiNormal; drawable.setBounds(0, 0, width, width); } private String getPhotoName(String s) { try { if (s == null) { return ""; } int begin = s.lastIndexOf('/'); if (begin == -1) { return s; } ++begin; int end = s.lastIndexOf('.'); if (end == -1) { return s; } return s.substring(begin, end); } catch (Exception e) { return ""; } } private boolean isMonkey(String name) { if (name.equalsIgnoreCase("coding")) { return false; } return name.indexOf("coding") == 0 || name.indexOf("festival") == 0; } }
25.704762
81
0.530937
237436b69e43b7b86ba41cae1b8506e3751c6eb9
215
package team.fjut.cf.mapper; import team.fjut.cf.pojo.po.SystemInfo; import tk.mybatis.mapper.common.Mapper; /** * @author axiang [2019/10/30] */ public interface SystemInfoMapper extends Mapper<SystemInfo> { }
19.545455
62
0.753488
66bd53f577731fa71b6ffb47bd4793b734777c8f
541
package techdomotica.objs.comps; public class ACondicionado extends Componente { private double temperatura = 23.0; public ACondicionado(String nombre, String marca, double uso) { super(nombre, marca, uso); } public ACondicionado(String nombre, String marca) { super(nombre, marca); } public double getTemperatura() { return temperatura; } public void changeTemperatura(double newtemp) { temperatura = newtemp; } }
22.541667
68
0.600739
9da4f374ba2c154a10647262491d84dcfe527ddd
2,405
package com.mcxtzhang.reflect; import java.lang.reflect.Field; /** * Intro: * Author: zhangxutong * E-mail: [email protected] * Home Page: http://blog.csdn.net/zxt0601 * Created: 2017/8/12. * History: */ public class ReplaceFieldTest { public static void main(String[] args){ Work programmer = new Work("程序员"); Work pm = new Work("产品经理"); Person person = new Person("mcxtzhang","男",pm); System.out.println(person); try { Field mWork = person.getClass().getDeclaredField("mWork"); mWork.setAccessible(true); mWork.set(person,programmer); System.out.println("After replace:"+person); } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } public static class Person { private String name; private String sex; private Work mWork; public Person(String name, String sex, Work work) { this.name = name; this.sex = sex; mWork = work; } public String getName() { return name; } public Person setName(String name) { this.name = name; return this; } public String getSex() { return sex; } public Person setSex(String sex) { this.sex = sex; return this; } public Work getWork() { return mWork; } public Person setWork(Work work) { mWork = work; return this; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", sex='" + sex + '\'' + ", mWork=" + mWork + '}'; } } public static class Work { private String work; @Override public String toString() { return "Work{" + "work='" + work + '\'' + '}'; } public Work(String work) { this.work = work; } public String getWork() { return work; } public Work setWork(String work) { this.work = work; return this; } } }
22.904762
70
0.474012
a1b800ddea9b059bf477effd4944ffaa4a36c976
1,089
/*----------------------------------------------------------------------------*/ /* Copyright (c) 2018-2019 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ package frc.robot.commands.auto.trajectories; import edu.wpi.first.wpilibj.geometry.Pose2d; import edu.wpi.first.wpilibj.geometry.Rotation2d; import edu.wpi.first.wpilibj.util.Units; /** * An abstract line trajectory that has a length. */ public abstract class TLine extends TBase { /** Length of the line trajectory in inches */ public abstract double getLengthIn(); @Override public final boolean isReversed() { return getLengthIn()<0; } @Override void build() { start = new Pose2d(); end = new Pose2d(Units.inchesToMeters(getLengthIn()), 0, new Rotation2d()); } }
33
80
0.550046
89b8b57dddbb18a92a09b378b98297f9b7fd31c8
955
package Model; /** * @author John Wayne Carreon */ public class Feedback { private String name; private double grade; private String comment; public Feedback(String name, double grade, String comment) { this.name = name; this.grade = grade; this.comment = comment; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Feedback(Feedback feedback) { } public void valoration() { } public double getGrade() { return grade; } public void setPunctuation(double punctuation) { this.grade = punctuation; } public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } @Override public String toString() { return getName() + "," + getGrade() + "," + getComment(); } }
17.685185
65
0.581152
a539ffd1ff194c675ddecff5eaa0b794acf7450c
12,512
package jp.co.sony.csl.dcoes.apis.main.app.mediator; import io.vertx.core.AbstractVerticle; import io.vertx.core.AsyncResult; import io.vertx.core.Future; import io.vertx.core.Handler; import io.vertx.core.buffer.Buffer; import io.vertx.core.json.JsonObject; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; import java.io.File; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; import jp.co.sony.csl.dcoes.apis.common.Deal; import jp.co.sony.csl.dcoes.apis.common.Error; import jp.co.sony.csl.dcoes.apis.common.ServiceAddress; import jp.co.sony.csl.dcoes.apis.common.util.StringUtil; import jp.co.sony.csl.dcoes.apis.common.util.vertx.FileSystemUtil; import jp.co.sony.csl.dcoes.apis.common.util.vertx.JsonObjectUtil; import jp.co.sony.csl.dcoes.apis.common.util.vertx.VertxConfig; import jp.co.sony.csl.dcoes.apis.main.app.PolicyKeeping; import jp.co.sony.csl.dcoes.apis.main.app.mediator.util.DealUtil; import jp.co.sony.csl.dcoes.apis.main.util.ApisConfig; import jp.co.sony.csl.dcoes.apis.main.util.ErrorExceptionUtil; import jp.co.sony.csl.dcoes.apis.main.util.ErrorUtil; /** * A Verticle that records interchange information in the file system. * Launched from the {@link Mediator} Verticle. * Periodically write the information of interchanges in which this unit participates to the file system. * This data is written even if externally requested. * @author OES Project * * 融通情報をファイルシステムに記録する Verticle. * {@link Mediator} Verticle から起動される. * 自ユニットが参加する融通情報を定期的にファイルシステムに書き込む. * 外部からの要求があったときにも書き込む. * @author OES Project */ public class DealLogging extends AbstractVerticle { private static final Logger log = LoggerFactory.getLogger(DealLogging.class); /** * Default duration of the interchange information storage cycle [ms]. * Value: {@value}. * * 融通情報保存周期のデフォルト値 [ms]. * 値は {@value}. */ private static final Long DEFAULT_DEAL_LOGGING_PERIOD_MSEC = 5000L; /** * Default value for interchange information save path format. * Value: {@value}. * * 融通情報保存パスのフォーマットのデフォルト値. * 値は {@value}. */ private static final JsonObjectUtil.DefaultString DEFAULT_DEAL_LOG_DIR_FORMAT = new JsonObjectUtil.DefaultString("'" + StringUtil.TMPDIR + "/apis/dealLog/'uuuu'/'MM'/'dd"); private long dealLoggingTimerId_ = 0L; private boolean stopped_ = false; /** * Called at startup. * Launches the {@link io.vertx.core.eventbus.EventBus} service. * Start a timer that records interchange information periodically. * @param startFuture {@inheritDoc} * @throws Exception {@inheritDoc} * * 起動時に呼び出される. * {@link io.vertx.core.eventbus.EventBus} サービスを起動する. * 定期的に融通を記録するタイマを起動する. * @param startFuture {@inheritDoc} * @throws Exception {@inheritDoc} */ @Override public void start(Future<Void> startFuture) throws Exception { startDealLoggingService_(resDealLogging -> { if (resDealLogging.succeeded()) { dealLoggingTimerHandler_(0L); if (log.isTraceEnabled()) log.trace("started : " + deploymentID()); startFuture.complete(); } else { startFuture.fail(resDealLogging.cause()); } }); } /** * Called when stopped. * Set a flag to stop the timer. * @throws Exception {@inheritDoc} * * 停止時に呼び出される. * タイマを止めるためのフラグを立てる. * @throws Exception {@inheritDoc} */ @Override public void stop() throws Exception { stopped_ = true; if (log.isTraceEnabled()) log.trace("stopped : " + deploymentID()); } //// /** * Launch the {@link io.vertx.core.eventbus.EventBus} service. * Address: {@link ServiceAddress.Mediator#dealLogging()} * Scope: global * Function: Records an interchange * If this unit is participating in the received interchange, store it in the file system. * Pass through if this unit is not participating in the received interchange. * Message body: Interchange information [{@link JsonObject}] * Message header: none * Response: ID of this unit if it is participating in the received interchange [{@link String}]. * {@code "N/A"} if this unit is not participating in the received interchange. * Fails if an error occurs. * @param completionHandler the completion handler * * {@link io.vertx.core.eventbus.EventBus} サービス起動. * アドレス : {@link ServiceAddress.Mediator#dealLogging()} * 範囲 : グローバル * 処理 : 融通を記録する. *    受け取った融通に自ユニットが参加していたらファイルシステムに保存する. *    受け取った融通に自ユニットが参加していなければスルー. * メッセージボディ : 融通情報 [{@link JsonObject}] * メッセージヘッダ : なし * レスポンス : 受け取った融通に自ユニットが参加していたら自ユニットの ID [{@link String}]. *       受け取った融通に自ユニットが参加していなかったら {@code "N/A"}. *       エラーが起きたら fail. * @param completionHandler the completion handler */ private void startDealLoggingService_(Handler<AsyncResult<Void>> completionHandler) { vertx.eventBus().<JsonObject>consumer(ServiceAddress.Mediator.dealLogging(), req -> { JsonObject deal = req.body(); if (deal != null) { if (Deal.isInvolved(deal, ApisConfig.unitId()) && Deal.isSaveworthy(deal)) { // Only record details if this unit is participating in the interchange and is in an internal state that should be recorded // 自ユニットがその融通に参加しており記録しておくべき内部状態である場合にのみ記録する List<JsonObject> deals = new ArrayList<>(1); deals.add(deal); new DealLogging_(deals, resLogging -> { if (resLogging.succeeded()) { req.reply(ApisConfig.unitId()); } else { req.fail(-1, resLogging.cause().getMessage()); } }).doLoop_(); } else { req.reply("N/A"); } } else { ErrorUtil.reportAndFail(vertx, Error.Category.LOGIC, Error.Extent.LOCAL, Error.Level.WARN, "deal is null", req); } }).completionHandler(completionHandler); } /** * Set an interchange storage timer. * The timeout duration is {@code POLICY.mediator.dealLoggingPeriodMsec} (default: {@link #DEFAULT_DEAL_LOGGING_PERIOD_MSEC}). * * 融通保存タイマ設定. * 待ち時間は {@code POLICY.mediator.dealLoggingPeriodMsec} ( デフォルト値 {@link #DEFAULT_DEAL_LOGGING_PERIOD_MSEC} ). */ private void setDealLoggingTimer_() { Long delay = PolicyKeeping.cache().getLong(DEFAULT_DEAL_LOGGING_PERIOD_MSEC, "mediator", "dealLoggingPeriodMsec"); setDealLoggingTimer_(delay); } /** * Set an interchange storage timer. * @param delay cycle duration [ms] * * 融通保存タイマ設定. * @param delay 周期 [ms] */ private void setDealLoggingTimer_(long delay) { dealLoggingTimerId_ = vertx.setTimer(delay, this::dealLoggingTimerHandler_); } /** * Perform interchange storage timer processing. * @param timerId timer ID * * 融通保存タイマ処理. * @param timerId タイマ ID */ private void dealLoggingTimerHandler_(Long timerId) { if (stopped_) return; if (null == timerId || timerId.longValue() != dealLoggingTimerId_) { ErrorUtil.report(vertx, Error.Category.LOGIC, Error.Extent.LOCAL, Error.Level.WARN, "illegal timerId : " + timerId + ", dealLoggingTimerId_ : " + dealLoggingTimerId_); return; } doDealLogging_(res -> { setDealLoggingTimer_(); }); } private void doDealLogging_(Handler<AsyncResult<Void>> completionHandler) { // Get the interchange that this unit is participating in // 自ユニットが参加している融通を取得 DealUtil.withUnitId(vertx, ApisConfig.unitId(), resWithUnitId -> { if (resWithUnitId.succeeded()) { List<JsonObject> deals = resWithUnitId.result(); if (!deals.isEmpty()) { // Exclude items that do not have to be recorded // 記録する必要がないものは除外する List<JsonObject> filtered = new ArrayList<>(deals.size()); for (JsonObject aDeal : deals) { if (Deal.isSaveworthy(aDeal)) { filtered.add(aDeal); } } deals = filtered; } if (!deals.isEmpty()) { new DealLogging_(deals, completionHandler).doLoop_(); } else { completionHandler.handle(Future.succeededFuture()); } } else { ErrorExceptionUtil.reportIfNeedAndFail(vertx, resWithUnitId.cause(), completionHandler); } }); } private static final DateTimeFormatter LOG_DIR_FORMATTER_; static { String s = VertxConfig.config.getString(DEFAULT_DEAL_LOG_DIR_FORMAT, "dealLogDirFormat"); s = StringUtil.fixFilePath(s); LOG_DIR_FORMATTER_ = DateTimeFormatter.ofPattern(s); } /** * A class that stores interchange information in the file system. * @author OES Project * * 融通情報をファイルシステムに保存するクラス. * @author OES Project */ private class DealLogging_ { private List<JsonObject> deals_; private Handler<AsyncResult<Void>> completionHandler_; private List<JsonObject> dealsForLoop_; /** * Make an instance. * @param deals a list of DEAL objects * @param completionHandler the completion handler * * インスタンス作成. * @param deals DEAL オブジェクトのリスト * @param completionHandler the completion handler */ private DealLogging_(List<JsonObject> deals, Handler<AsyncResult<Void>> completionHandler) { deals_ = deals; completionHandler_ = completionHandler; dealsForLoop_ = new ArrayList<>(deals_); } private void doLoop_() { if (dealsForLoop_.isEmpty()) { completionHandler_.handle(Future.succeededFuture()); } else { JsonObject aDeal = dealsForLoop_.remove(0); writeToFile_(aDeal, resWriteToFile -> { doLoop_(); }); } } private void writeToFile_(JsonObject deal, Handler<AsyncResult<Void>> completionHandler) { LocalDateTime createDateTime = JsonObjectUtil.getLocalDateTime(deal, "createDateTime"); String logDir = LOG_DIR_FORMATTER_.format(createDateTime); String filename = Deal.dealId(deal); String path = logDir + File.separatorChar + filename; if (log.isDebugEnabled()) log.debug("path : " + path); ensureFile_(logDir, filename, path, resEnsureFile -> { if (resEnsureFile.succeeded()) { vertx.fileSystem().writeFile(path, Buffer.buffer(deal.encode()), resWriteFile -> { if (resWriteFile.succeeded()) { completionHandler.handle(Future.succeededFuture()); } else { ErrorUtil.reportAndFail(vertx, Error.Category.FRAMEWORK, Error.Extent.LOCAL, Error.Level.FATAL, "Operation failed on File System", resWriteFile.cause(), completionHandler); } }); } else { completionHandler.handle(resEnsureFile); } }); } private void ensureFile_(String logDir, String filename, String path, Handler<AsyncResult<Void>> completionHandler) { FileSystemUtil.ensureDirectory(vertx, logDir, resEnsureDir -> { if (resEnsureDir.succeeded()) { vertx.fileSystem().exists(path, resExists -> { if (resExists.succeeded()) { if (resExists.result()) { completionHandler.handle(Future.succeededFuture()); } else { vertx.fileSystem().createFile(path, resCreate -> { if (resCreate.succeeded()) { completionHandler.handle(Future.succeededFuture()); } else { // Failed when attempting to create a file that doesn't exist... // 無いから作ろうとしたら失敗したけど... vertx.fileSystem().exists(path, resExistsAgain -> { if (resExistsAgain.succeeded()) { if (resExistsAgain.result()) { // Checked again and it was there // 再確認してみたらあった // → Someone else must have created this file while we were trying to do so // → 作ろうとしている隙に誰かが作ったに違いない // → Maybe this is OK // → たぶん OK completionHandler.handle(Future.succeededFuture()); } else { // Checked again and it's not there // 再確認してみたけどなかった // → NG // → NG ErrorUtil.reportAndFail(vertx, Error.Category.FRAMEWORK, Error.Extent.LOCAL, Error.Level.FATAL, "Operation failed on File System", resCreate.cause(), completionHandler); } } else { ErrorUtil.reportAndFail(vertx, Error.Category.FRAMEWORK, Error.Extent.LOCAL, Error.Level.FATAL, "Operation failed on File System", resExistsAgain.cause(), completionHandler); } }); } }); } } else { ErrorUtil.reportAndFail(vertx, Error.Category.FRAMEWORK, Error.Extent.LOCAL, Error.Level.FATAL, "Operation failed on File System", resExists.cause(), completionHandler); } }); } else { ErrorUtil.reportAndFail(vertx, Error.Category.FRAMEWORK, Error.Extent.LOCAL, Error.Level.FATAL, "Operation failed on File System", resEnsureDir.cause(), completionHandler); } }); } } }
37.238095
186
0.6879
f444cdfcadb529a54963bae4472eb3b2e3112dcd
1,690
package org.apache.maven.index.treeview; /* * 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. */ import java.io.IOException; import java.util.List; public interface TreeNode { enum Type { G, A, V, artifact }; Type getType(); void setType( Type t ); boolean isLeaf(); void setLeaf( boolean leaf ); String getNodeName(); void setNodeName( String name ); String getPath(); void setPath( String path ); String getGroupId(); void setGroupId( String groupId ); String getArtifactId(); void setArtifactId( String artifactId ); String getVersion(); void setVersion( String version ); String getRepositoryId(); void setRepositoryId( String repositoryId ); List<TreeNode> getChildren(); List<TreeNode> listChildren() throws IOException; TreeNode findChildByPath( String path, Type type ) throws IOException; }
23.472222
63
0.698225
b6fc2d28e7de14ec226122f91db0238817033c63
1,774
package com.rapps.utility.learning.lms.persistence.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.rapps.utility.learning.lms.exception.LmsException; import com.rapps.utility.learning.lms.persistence.bean.Session; import com.rapps.utility.learning.lms.persistence.repository.SessionRepository; /** * Session service * * @author vkirodia * */ @Service public class SessionService extends BaseService<Session> { @Autowired SessionRepository sessionRepository; /** * Get List of session with last access time less than the passed time. * * @param lastAccessTime * Access time * @return List of Session */ public List<Session> findByLastAccessTimeLessThan(long lastAccessTime) { return sessionRepository.findByLastAccessTimeLessThan(lastAccessTime); } /** * Get session details for given session id. * * @param sessionId * Sessoin Id * @return Session * @throws LmsException * Session not found for given Id */ public Session getSession(String sessionId) throws LmsException { return super.findById(sessionId); } /** * Persist user session. * * @param session * Session * @return Session */ @Transactional public Session saveSession(Session session) { return sessionRepository.save(session); } /** * Deletes the session. * * @param session * Session */ @Transactional public void deleteSession(Session session) { sessionRepository.delete(session); } /** * Delete all sessions */ public void deleteAllSessions() { sessionRepository.deleteAll(); } }
22.175
79
0.719842
8f8bd8d044c5ebf4b14c9a558390efc425599872
1,655
package org.innovateuk.ifs.competitionsetup.completionstage.populator; import org.innovateuk.ifs.competition.resource.CompetitionCompletionStage; import org.innovateuk.ifs.competition.resource.CompetitionResource; import org.innovateuk.ifs.competition.resource.CompetitionSetupSection; import org.innovateuk.ifs.competitionsetup.completionstage.form.CompletionStageForm; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.innovateuk.ifs.competition.builder.CompetitionResourceBuilder.newCompetitionResource; public class CompletionStageFormPopulatorTest { @Test public void populateForm() { CompetitionResource competition = newCompetitionResource(). withCompletionStage(CompetitionCompletionStage.RELEASE_FEEDBACK). build(); CompletionStageForm form = new CompletionStageFormPopulator().populateForm(competition); assertThat(form.getSelectedCompletionStage()).isEqualTo(CompetitionCompletionStage.RELEASE_FEEDBACK); assertThat(form.isAutoSaveAction()).isFalse(); assertThat(form.isMarkAsCompleteAction()).isTrue(); } @Test public void populateFormWithCompletionStageNotYetSelected() { CompetitionResource competition = newCompetitionResource().build(); CompletionStageForm form = new CompletionStageFormPopulator().populateForm(competition); assertThat(form.getSelectedCompletionStage()).isNull();; } @Test public void sectionToFill() { assertThat(new CompletionStageFormPopulator().sectionToFill()).isEqualTo(CompetitionSetupSection.COMPLETION_STAGE); } }
41.375
123
0.781269
229d3b0aaa17bfa2b81e54534bc30a6511739b96
2,946
package com.kunlun.basedata.controller; import com.kunlun.basedata.model.DepartmentModel; import com.kunlun.basedata.service.IDepartmentService; import com.kunlun.common.model.Page; import com.kunlun.common.utils.ResponseUtil; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * 部门Controller类 */ @RestController @RequestMapping(value = "/department") public class DepartmentController { private Logger logger = LogManager.getLogger(); @Autowired private IDepartmentService departmentService; @RequestMapping(value = "/getAllDepartment", method = RequestMethod.GET) public Object getAllDepartment(DepartmentModel departmentModel, int currentPage, int pageSize) { try { Page<DepartmentModel> departments = departmentService.getAllDepartment(departmentModel, currentPage, pageSize); return ResponseUtil.successResponse(departments); } catch (Exception e) { logger.error("DepartmentController getAllDepartment Error: ", e); return ResponseUtil.failedResponse("获取部门数据失败!", e.getMessage()); } } @RequestMapping(value = "/addDepartment", method = RequestMethod.POST) public Object addDepartment(DepartmentModel departmentModel) { try { departmentService.addDepartment(departmentModel); return ResponseUtil.successResponse("SUCCESS"); } catch (Exception e) { logger.error("DepartmentController addDepartment Error: ", e); return ResponseUtil.failedResponse("添加部门失败!", e.getMessage()); } } @RequestMapping(value = "/updateDepartment", method = RequestMethod.POST) public Object updateDepartment(DepartmentModel departmentModel) { try { departmentService.updateDepartment(departmentModel); return ResponseUtil.successResponse("SUCCESS"); } catch (Exception e) { logger.error("DepartmentController updateDepartment Error: ", e); return ResponseUtil.failedResponse("更新部门失败!", e.getMessage()); } } @RequestMapping(value = "/deleteDepartment", method = RequestMethod.POST) public Object deleteDepartment(String ids) { try { List<String> list = Arrays.asList(ids.split(",")); departmentService.deleteDepartment(list); return ResponseUtil.successResponse("SUCCESS"); } catch (Exception e) { logger.error("DepartmentController deleteDepartment Error: ", e); return ResponseUtil.failedResponse("删除部门失败!", e.getMessage()); } } }
39.28
123
0.7074
42ca72b218c01930f610498f64830e9f581ebec2
584
package com.hzy.nofity; import android.app.NotificationManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.widget.Toast; public class MyBroadCast extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Toast.makeText(context, intent.getAction()+"",Toast.LENGTH_LONG).show(); NotificationManager notificationManager=(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.cancel(200); } }
32.444444
125
0.782534
f6e4e9d6b952683b62f325704ca198f3fad0ca01
3,750
package com.simibubi.create.content.logistics.block.redstone; import static net.minecraft.state.properties.BlockStateProperties.POWERED; import java.util.List; import org.apache.commons.lang3.tuple.Pair; import com.simibubi.create.AllBlocks; import com.simibubi.create.foundation.tileEntity.SmartTileEntity; import com.simibubi.create.foundation.tileEntity.TileEntityBehaviour; import com.simibubi.create.foundation.tileEntity.behaviour.ValueBoxTransform; import com.simibubi.create.foundation.tileEntity.behaviour.linked.LinkBehaviour; import net.minecraft.block.BlockState; import net.minecraft.nbt.CompoundNBT; import net.minecraft.tileentity.TileEntityType; import net.minecraft.util.Direction; import net.minecraft.util.math.BlockPos; public class RedstoneLinkTileEntity extends SmartTileEntity { private boolean receivedSignalChanged; private int receivedSignal; private int transmittedSignal; private LinkBehaviour link; private boolean transmitter; public RedstoneLinkTileEntity(TileEntityType<? extends RedstoneLinkTileEntity> type) { super(type); } @Override public void addBehaviours(List<TileEntityBehaviour> behaviours) { } @Override public void addBehavioursDeferred(List<TileEntityBehaviour> behaviours) { createLink(); behaviours.add(link); } protected void createLink() { Pair<ValueBoxTransform, ValueBoxTransform> slots = ValueBoxTransform.Dual.makeSlots(RedstoneLinkFrequencySlot::new); link = transmitter ? LinkBehaviour.transmitter(this, slots, this::getSignal) : LinkBehaviour.receiver(this, slots, this::setSignal); } public int getSignal() { return transmittedSignal; } public void setSignal(int power) { if (receivedSignal != power) receivedSignalChanged = true; receivedSignal = power; } public void transmit(int strength) { transmittedSignal = strength; if (link != null) link.notifySignalChange(); } @Override public void write(CompoundNBT compound, boolean clientPacket) { compound.putBoolean("Transmitter", transmitter); compound.putInt("Receive", getReceivedSignal()); compound.putBoolean("ReceivedChanged", receivedSignalChanged); compound.putInt("Transmit", transmittedSignal); super.write(compound, clientPacket); } @Override protected void read(CompoundNBT compound, boolean clientPacket) { transmitter = compound.getBoolean("Transmitter"); super.read(compound, clientPacket); receivedSignal = compound.getInt("Receive"); receivedSignalChanged = compound.getBoolean("ReceivedChanged"); if (world == null || world.isRemote || !link.newPosition) transmittedSignal = compound.getInt("Transmit"); } @Override public void tick() { super.tick(); if (isTransmitterBlock() != transmitter) { transmitter = isTransmitterBlock(); LinkBehaviour prevlink = link; removeBehaviour(LinkBehaviour.TYPE); createLink(); link.copyItemsFrom(prevlink); attachBehaviourLate(link); } if (transmitter) return; if (world.isRemote) return; BlockState blockState = getBlockState(); if (!AllBlocks.REDSTONE_LINK.has(blockState)) return; if ((getReceivedSignal() > 0) != blockState.get(POWERED)) { receivedSignalChanged = true; world.setBlockState(pos, blockState.cycle(POWERED)); } if (receivedSignalChanged) { Direction attachedFace = blockState.get(RedstoneLinkBlock.FACING).getOpposite(); BlockPos attachedPos = pos.offset(attachedFace); world.notifyNeighbors(pos, world.getBlockState(pos).getBlock()); world.notifyNeighbors(attachedPos, world.getBlockState(attachedPos).getBlock()); } } protected Boolean isTransmitterBlock() { return !getBlockState().get(RedstoneLinkBlock.RECEIVER); } public int getReceivedSignal() { return receivedSignal; } }
28.846154
87
0.770667
d8c078ad8de871606c63058f28d3cfa6990285f4
3,661
/* * Licensed to the Technische Universität Darmstadt under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The Technische Universität Darmstadt * 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. * * 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 de.tudarmstadt.ukp.inception.recommendation.service; import static java.util.stream.Collectors.toList; import java.util.ArrayList; import java.util.Collection; import java.util.List; import de.tudarmstadt.ukp.inception.recommendation.api.model.AnnotationSuggestion; import de.tudarmstadt.ukp.inception.recommendation.api.model.RelationSuggestion; import de.tudarmstadt.ukp.inception.recommendation.api.model.SpanSuggestion; import de.tudarmstadt.ukp.inception.recommendation.api.model.SuggestionDocumentGroup; import de.tudarmstadt.ukp.inception.recommendation.api.model.SuggestionGroup; public class Fixtures { // AnnotationSuggestion private final static long RECOMMENDER_ID = 1; private final static String RECOMMENDER_NAME = "TestEntityRecommender"; private final static String DOC_NAME = "TestDocument"; private final static String UI_LABEL = "TestUiLabel"; private final static double CONFIDENCE = 0.2; private final static String CONFIDENCE_EXPLANATION = "Predictor A: 0.05 | Predictor B: 0.15"; private final static String COVERED_TEXT = "TestText"; static <T extends AnnotationSuggestion> List<T> getInvisibleSuggestions( Collection<SuggestionGroup<T>> aSuggestions) { return aSuggestions.stream() // .flatMap(SuggestionGroup::stream) // .filter(s -> !s.isVisible()) // .collect(toList()); } static <T extends AnnotationSuggestion> List<T> getVisibleSuggestions( Collection<SuggestionGroup<T>> aSuggestions) { return aSuggestions.stream() // .flatMap(SuggestionGroup::stream) // .filter(s -> s.isVisible()) // .collect(toList()); } static SuggestionDocumentGroup<SpanSuggestion> makeSpanSuggestionGroup(long layerId, String feature, int[][] vals) { List<SpanSuggestion> suggestions = new ArrayList<>(); for (int[] val : vals) { suggestions.add(new SpanSuggestion(val[0], RECOMMENDER_ID, RECOMMENDER_NAME, layerId, feature, DOC_NAME, val[1], val[2], COVERED_TEXT, null, UI_LABEL, CONFIDENCE, CONFIDENCE_EXPLANATION)); } return new SuggestionDocumentGroup<>(suggestions); } static SuggestionDocumentGroup<RelationSuggestion> makeRelationSuggestionGroup(long layerId, String feature, int[][] vals) { List<RelationSuggestion> suggestions = new ArrayList<>(); for (int[] val : vals) { suggestions.add(new RelationSuggestion(val[0], RECOMMENDER_ID, RECOMMENDER_NAME, layerId, feature, DOC_NAME, val[1], val[2], val[3], val[4], null, UI_LABEL, CONFIDENCE, CONFIDENCE_EXPLANATION)); } return new SuggestionDocumentGroup<>(suggestions); } }
42.08046
97
0.699536
2978f5909088fdceff480a6341cf99de2ca49eed
223
package tech.jhipster.lite.generator.client.common.domain; import tech.jhipster.lite.generator.project.domain.Project; public interface ClientCommonService { void excludeInTsconfigJson(Project project, String value); }
27.875
60
0.829596
f0f60da2a1563aa3b53c9620f9bf0f936d5fc76e
672
package org.folio.service.finance.transaction; import org.folio.service.orders.OrderWorkflowType; import java.util.EnumMap; import java.util.Map; import java.util.Set; public class EncumbranceWorkflowStrategyFactory { private final Map<OrderWorkflowType, EncumbranceWorkflowStrategy> strategyMap = new EnumMap<>(OrderWorkflowType.class); public EncumbranceWorkflowStrategyFactory(Set<EncumbranceWorkflowStrategy> strategies) { strategies.forEach(strategy -> this.strategyMap.put(strategy.getStrategyName(), strategy)); } public EncumbranceWorkflowStrategy getStrategy(OrderWorkflowType name) { return strategyMap.get(name); } }
30.545455
124
0.787202
e8a943f2449eaa2353b2dc0cfc5013e96c6a34df
6,086
/* * Copyright 2019 the original author or authors. * See the notice.md file distributed with this work for additional * information regarding copyright ownership. * * 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.github.galbiston.geosparql_jena.geo.topological; import static io.github.galbiston.geosparql_jena.geo.topological.QueryRewriteTestData.FEATURE_B; import static io.github.galbiston.geosparql_jena.geo.topological.QueryRewriteTestData.GEOMETRY_B; import static io.github.galbiston.geosparql_jena.geo.topological.QueryRewriteTestData.GEO_FEATURE_LITERAL; import static io.github.galbiston.geosparql_jena.geo.topological.QueryRewriteTestData.GEO_FEATURE_Y; import static io.github.galbiston.geosparql_jena.geo.topological.QueryRewriteTestData.LITERAL_B; import org.apache.jena.graph.Graph; import org.apache.jena.graph.Node; import org.apache.jena.rdf.model.Model; import org.apache.jena.rdf.model.Resource; import org.apache.jena.rdf.model.ResourceFactory; import org.junit.After; import org.junit.AfterClass; import static org.junit.Assert.*; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; /** * * */ public class SpatialObjectGeometryLiteralTest { private static Model MODEL; public SpatialObjectGeometryLiteralTest() { } @BeforeClass public static void setUpClass() { MODEL = QueryRewriteTestData.createTestData(); } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of retrieve method, of class SpatialObjectGeometryLiteral. */ @Test public void testRetrieve() { System.out.println("retrieve"); Graph graph = MODEL.getGraph(); Node targetSpatialObject = null; SpatialObjectGeometryLiteral instance = SpatialObjectGeometryLiteral.retrieve(graph, targetSpatialObject); boolean expResult = false; boolean result = instance.isValid(); //System.out.println("Exp: " + expResult); //System.out.println("Res: " + result); assertEquals(expResult, result); } /** * Test of retrieve method, of class SpatialObjectGeometryLiteral. */ @Test public void testRetrieveGeometryLiteral_geometry() { System.out.println("retrieve_geometry"); Graph graph = MODEL.getGraph(); Resource targetSpatialObject = GEOMETRY_B; SpatialObjectGeometryLiteral expResult = new SpatialObjectGeometryLiteral(GEOMETRY_B.asNode(), LITERAL_B.asNode()); SpatialObjectGeometryLiteral result = SpatialObjectGeometryLiteral.retrieve(graph, targetSpatialObject.asNode()); //System.out.println("Exp: " + expResult); //System.out.println("Res: " + result); assertEquals(expResult, result); } /** * Test of retrieve method, of class SpatialObjectGeometryLiteral. */ @Test public void testRetrieveGeometryLiteral_feature() { System.out.println("retrieve_feature"); Resource targetSpatialObject = FEATURE_B; SpatialObjectGeometryLiteral expResult = new SpatialObjectGeometryLiteral(FEATURE_B.asNode(), LITERAL_B.asNode()); SpatialObjectGeometryLiteral result = SpatialObjectGeometryLiteral.retrieve(MODEL.getGraph(), targetSpatialObject.asNode()); //System.out.println("Exp: " + expResult); //System.out.println("Res: " + result); assertEquals(expResult, result); } /** * Test of retrieve method, of class SpatialObjectGeometryLiteral. */ @Test public void testRetrieveGeometryLiteral_missing_property() { System.out.println("retrieve_missing_property"); Resource targetSpatialObject = ResourceFactory.createResource("http://example.org#GeometryE"); SpatialObjectGeometryLiteral instance = SpatialObjectGeometryLiteral.retrieve(MODEL.getGraph(), targetSpatialObject.asNode()); boolean expResult = false; boolean result = instance.isValid(); //System.out.println("Exp: " + expResult); //System.out.println("Res: " + result); assertEquals(expResult, result); } /** * Test of retrieve method, of class SpatialObjectGeometryLiteral. */ @Test public void testRetrieveGeometryLiteral_not_feature_geometry() { System.out.println("retrieve_not_feature_geometry"); Resource targetSpatialObject = ResourceFactory.createResource("http://example.org#X"); SpatialObjectGeometryLiteral instance = SpatialObjectGeometryLiteral.retrieve(MODEL.getGraph(), targetSpatialObject.asNode()); boolean expResult = false; boolean result = instance.isValid(); //System.out.println("Exp: " + expResult); //System.out.println("Res: " + result); assertEquals(expResult, result); } /** * Test of retrieve method, of class SpatialObjectGeometryLiteral. */ @Test public void testRetrieveGeometryLiteral_feature_lat_lon() { System.out.println("retrieve_feature"); Resource targetSpatialObject = GEO_FEATURE_Y; SpatialObjectGeometryLiteral expResult = new SpatialObjectGeometryLiteral(GEO_FEATURE_Y.asNode(), GEO_FEATURE_LITERAL.asNode()); SpatialObjectGeometryLiteral result = SpatialObjectGeometryLiteral.retrieve(MODEL.getGraph(), targetSpatialObject.asNode()); //System.out.println("Exp: " + expResult); //System.out.println("Res: " + result); assertEquals(expResult, result); } }
35.383721
136
0.714427
3e3be6d4ce6368a1e63f2a19e0f2ca42ef79570f
2,594
/* * * * Copyright (c) 2022 - Manifold Systems LLC * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * */ package manifold.ij.template.psi; import com.intellij.lang.ASTNode; import com.intellij.lang.ParserDefinition; import com.intellij.lang.PsiParser; import com.intellij.lexer.Lexer; import com.intellij.openapi.project.Project; import com.intellij.psi.FileViewProvider; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.tree.IElementType; import com.intellij.psi.tree.IFileElementType; import com.intellij.psi.tree.TokenSet; import com.intellij.psi.util.PsiUtilCore; import manifold.ij.template.ManTemplateLanguage; import org.jetbrains.annotations.NotNull; public class ManTemplateParserDefinition implements ParserDefinition { private static final IFileElementType FILE = new IFileElementType( ManTemplateLanguage.INSTANCE ); @NotNull @Override public Lexer createLexer( Project project ) { return new ManTemplateLexer(); } @Override public PsiParser createParser( Project project ) { return new ManTemplateParser(); } @Override public IFileElementType getFileNodeType() { return FILE; } @NotNull @Override public TokenSet getWhitespaceTokens() { return TokenSet.EMPTY; } @NotNull @Override public TokenSet getCommentTokens() { return TokenSet.EMPTY; } @NotNull @Override public TokenSet getStringLiteralElements() { return TokenSet.EMPTY; } @NotNull @Override public PsiElement createElement( ASTNode node ) { IElementType type = node.getElementType(); if( type instanceof ManTemplateElementType ) { return new ManTemplateElementImpl( node ); } return PsiUtilCore.NULL_PSI_ELEMENT; } @Override public PsiFile createFile( FileViewProvider viewProvider ) { return new ManTemplateFile( viewProvider ); } @Override public SpaceRequirements spaceExistenceTypeBetweenTokens( ASTNode left, ASTNode right ) { return SpaceRequirements.MAY; } }
24.242991
100
0.735929