hexsha
stringlengths
40
40
size
int64
3
1.05M
ext
stringclasses
1 value
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
5
1.02k
max_stars_repo_name
stringlengths
4
126
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
list
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
5
1.02k
max_issues_repo_name
stringlengths
4
114
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
list
max_issues_count
float64
1
92.2k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
5
1.02k
max_forks_repo_name
stringlengths
4
136
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
list
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
avg_line_length
float64
2.55
99.9
max_line_length
int64
3
1k
alphanum_fraction
float64
0.25
1
index
int64
0
1M
content
stringlengths
3
1.05M
9233643d834f9e4449755318b6905d3064f3d3f8
113
java
Java
org.openntf.domino/src/org/openntf/domino/ext/ViewNavigator.java
hakuseki/org.openntf.domino
9de76b134d1c7031c386d19e41b4155029727099
[ "Apache-2.0" ]
1
2019-04-01T12:33:21.000Z
2019-04-01T12:33:21.000Z
org.openntf.domino/src/org/openntf/domino/ext/ViewNavigator.java
hakuseki/org.openntf.domino
9de76b134d1c7031c386d19e41b4155029727099
[ "Apache-2.0" ]
null
null
null
org.openntf.domino/src/org/openntf/domino/ext/ViewNavigator.java
hakuseki/org.openntf.domino
9de76b134d1c7031c386d19e41b4155029727099
[ "Apache-2.0" ]
null
null
null
8.692308
32
0.60177
996,553
/** * */ package org.openntf.domino.ext; /** * @author withersp * */ public interface ViewNavigator { }
92336581fd169b59ef107a19a19a1b1c23f0ff46
3,321
java
Java
aws-java-sdk-ec2/src/main/java/com/amazonaws/services/ec2/model/transform/DescribeFleetInstancesResultStaxUnmarshaller.java
jplippi/aws-sdk-java
147eefec220e2944dc571283af6552611bc94301
[ "Apache-2.0" ]
1
2020-08-27T17:36:34.000Z
2020-08-27T17:36:34.000Z
aws-java-sdk-ec2/src/main/java/com/amazonaws/services/ec2/model/transform/DescribeFleetInstancesResultStaxUnmarshaller.java
jplippi/aws-sdk-java
147eefec220e2944dc571283af6552611bc94301
[ "Apache-2.0" ]
3
2020-04-15T20:08:15.000Z
2021-06-30T19:58:16.000Z
aws-java-sdk-ec2/src/main/java/com/amazonaws/services/ec2/model/transform/DescribeFleetInstancesResultStaxUnmarshaller.java
jplippi/aws-sdk-java
147eefec220e2944dc571283af6552611bc94301
[ "Apache-2.0" ]
1
2020-10-10T15:59:17.000Z
2020-10-10T15:59:17.000Z
40.012048
138
0.681722
996,554
/* * Copyright 2015-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.amazonaws.services.ec2.model.transform; import java.util.ArrayList; import javax.xml.stream.events.XMLEvent; import javax.annotation.Generated; import com.amazonaws.services.ec2.model.*; import com.amazonaws.transform.Unmarshaller; import com.amazonaws.transform.StaxUnmarshallerContext; import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*; /** * DescribeFleetInstancesResult StAX Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class DescribeFleetInstancesResultStaxUnmarshaller implements Unmarshaller<DescribeFleetInstancesResult, StaxUnmarshallerContext> { public DescribeFleetInstancesResult unmarshall(StaxUnmarshallerContext context) throws Exception { DescribeFleetInstancesResult describeFleetInstancesResult = new DescribeFleetInstancesResult(); int originalDepth = context.getCurrentDepth(); int targetDepth = originalDepth + 1; if (context.isStartOfDocument()) targetDepth += 1; while (true) { XMLEvent xmlEvent = context.nextEvent(); if (xmlEvent.isEndDocument()) return describeFleetInstancesResult; if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) { if (context.testExpression("activeInstanceSet", targetDepth)) { describeFleetInstancesResult.withActiveInstances(new ArrayList<ActiveInstance>()); continue; } if (context.testExpression("activeInstanceSet/item", targetDepth)) { describeFleetInstancesResult.withActiveInstances(ActiveInstanceStaxUnmarshaller.getInstance().unmarshall(context)); continue; } if (context.testExpression("nextToken", targetDepth)) { describeFleetInstancesResult.setNextToken(StringStaxUnmarshaller.getInstance().unmarshall(context)); continue; } if (context.testExpression("fleetId", targetDepth)) { describeFleetInstancesResult.setFleetId(StringStaxUnmarshaller.getInstance().unmarshall(context)); continue; } } else if (xmlEvent.isEndElement()) { if (context.getCurrentDepth() < originalDepth) { return describeFleetInstancesResult; } } } } private static DescribeFleetInstancesResultStaxUnmarshaller instance; public static DescribeFleetInstancesResultStaxUnmarshaller getInstance() { if (instance == null) instance = new DescribeFleetInstancesResultStaxUnmarshaller(); return instance; } }
92336631c260a1d16fcf292ec9048122b7bcc1e8
4,703
java
Java
src/main/java/org/whitehole/binary/pe/PEHeader.java
BenoitPerrot/whitehole-lib
0de253b5b5a4b4132df58a77efb63fa8de25bb6f
[ "BSD-3-Clause" ]
null
null
null
src/main/java/org/whitehole/binary/pe/PEHeader.java
BenoitPerrot/whitehole-lib
0de253b5b5a4b4132df58a77efb63fa8de25bb6f
[ "BSD-3-Clause" ]
null
null
null
src/main/java/org/whitehole/binary/pe/PEHeader.java
BenoitPerrot/whitehole-lib
0de253b5b5a4b4132df58a77efb63fa8de25bb6f
[ "BSD-3-Clause" ]
null
null
null
38.54918
152
0.746545
996,555
// Copyright (c) 2004-2015, Benoit PERROT. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // // * Neither the name of the White Hole Project nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package org.whitehole.binary.pe; import java.io.IOException; import java.math.BigInteger; import java.util.ArrayList; import org.whitehole.infra.io.LargeByteBuffer; import org.whitehole.infra.types.LittleEndianReader; import org.whitehole.infra.types.StringAsciiz; import org.whitehole.infra.types.UInt32; public class PEHeader { private final COFFHeader _coffHeader; private final OptionalHeader _optionalHeader; private final ArrayList<SectionHeader> _sectionHeaders; public PEHeader(LargeByteBuffer buffer, long offset) throws IOException { // Signature offset is at 0x3c long n = 0x3c; final UInt32 signatureOffset = LittleEndianReader.readUInt32(buffer, offset + n); // Check signature n = signatureOffset.toBigInteger().intValue(); final UInt32 signature = LittleEndianReader.readUInt32(buffer, offset + n); n += 4; if (signature.getByte0() != 'P' || signature.getByte1() != 'E' || signature.getByte2() != 0 || signature.getByte3() != 0) throw new IOException(); // TODO: call buffer.get() directly // Read COFF header _coffHeader = COFFHeader.read(buffer, offset + n); n += COFFHeader.byteSize; // Read optional header (actually required for image files) if (_coffHeader.getSizeOfOptionalHeader().toBigInteger().intValue() == 0) throw new IOException(); _optionalHeader = new OptionalHeader(buffer, offset + n); n += _optionalHeader.byteSize; // Read section table, if any _sectionHeaders = new ArrayList<SectionHeader>(); for (int i = _coffHeader.getNumberOfSections().toBigInteger().intValue(); 0 < i; --i) { SectionHeader sh = SectionHeader.read(buffer, offset + n); n += SectionHeader.byteSize; _sectionHeaders.add(sh); } } public COFFHeader getCOFFHeader() { return _coffHeader; } public OptionalHeader getOptionalHeader() { return _optionalHeader; } public ArrayList<SectionHeader> getSectionHeaders() { return _sectionHeaders; } // // Shortcuts public BigInteger getAddressOfEntryPoint() { return getOptionalHeader().getStandardFields().getAddressOfEntryPoint().toBigInteger(); } public boolean isPE32x() { return getOptionalHeader().getStandardFields().getMagic().toValid() == org.whitehole.binary.pe.MagicNumber.Valid.PE32x; } public BigInteger getImageBase() { final WindowsSpecificPEFields wsf = getOptionalHeader().getWindowsSpecificFields(); return (wsf instanceof OptionalHeaderPE32xFields) ? ((OptionalHeaderPE32xFields) wsf).getImageBase().toBigInteger() : ((OptionalHeaderPE32Fields) wsf) .getImageBase().toBigInteger(); } public SectionHeader findSectionHeaderByRVA(long rva) { for (SectionHeader sh : getSectionHeaders()) { final long sectionRVA = sh.getVirtualAddress().toLong(); final long sectionSize = sh.getVirtualSize().toLong(); if (sectionRVA <= rva && rva < sectionSize + sectionRVA) return sh; } return null; } public SectionHeader findSectionHeaderByName(String name) { for (SectionHeader sh : getSectionHeaders()) if (name.equals(StringAsciiz.readLittleEndian(sh.getName()))) return sh; return null; } }
9233665322cd95039c1cf243f0fa6a08d46fa791
1,099
java
Java
shared/liveandgov-commons/src/main/java/eu/liveandgov/wp1/serialization/impl/ActivitySerialization.java
Institute-Web-Science-and-Technologies/LiveGovWP1
8640cd4409a8eafff5b549a6f35fd0e51518dd4f
[ "MIT" ]
null
null
null
shared/liveandgov-commons/src/main/java/eu/liveandgov/wp1/serialization/impl/ActivitySerialization.java
Institute-Web-Science-and-Technologies/LiveGovWP1
8640cd4409a8eafff5b549a6f35fd0e51518dd4f
[ "MIT" ]
null
null
null
shared/liveandgov-commons/src/main/java/eu/liveandgov/wp1/serialization/impl/ActivitySerialization.java
Institute-Web-Science-and-Technologies/LiveGovWP1
8640cd4409a8eafff5b549a6f35fd0e51518dd4f
[ "MIT" ]
1
2018-10-06T07:27:18.000Z
2018-10-06T07:27:18.000Z
28.179487
101
0.738854
996,556
package eu.liveandgov.wp1.serialization.impl; import eu.liveandgov.wp1.data.impl.Activity; import java.util.Scanner; import static eu.liveandgov.wp1.serialization.SerializationCommons.appendString; import static eu.liveandgov.wp1.serialization.SerializationCommons.nextString; /** * <p>Serialization of the activity item</p> * Created by Lukas Härtel on 09.02.14. */ public class ActivitySerialization extends AbstractSerialization<Activity> { /** * The one instance of the serialization */ public static final ActivitySerialization ACTIVITY_SERIALIZATION = new ActivitySerialization(); /** * Hidden constructor */ protected ActivitySerialization() { } @Override protected void serializeRest(StringBuilder stringBuilder, Activity activity) { appendString(stringBuilder, activity.activity); } @Override protected Activity deSerializeRest(String type, long timestamp, String device, Scanner scanner) { final String activity = nextString(scanner); return new Activity(timestamp, device, activity); } }
9233669a96e4ecd73af4e9681b6842d97f5e24be
1,330
java
Java
src/main/java/net/gegy1000/psf/server/block/remote/GuiSelectCraft.java
PracticalSpaceFireworks/PracticalSpaceFireworks
30b6b76db30fa0864b9e1863d1da4ad4e479fc39
[ "Apache-2.0" ]
8
2018-04-29T18:36:03.000Z
2021-02-13T00:05:53.000Z
src/main/java/net/gegy1000/psf/server/block/remote/GuiSelectCraft.java
PracticalSpaceFireworks/PracticalSpaceFireworks
30b6b76db30fa0864b9e1863d1da4ad4e479fc39
[ "Apache-2.0" ]
14
2018-04-09T10:10:13.000Z
2022-03-13T17:36:36.000Z
src/main/java/net/gegy1000/psf/server/block/remote/GuiSelectCraft.java
gegy1000/PracticalSpaceFireworks
30b6b76db30fa0864b9e1863d1da4ad4e479fc39
[ "Apache-2.0" ]
2
2018-07-24T14:57:35.000Z
2021-11-29T16:42:48.000Z
30.227273
138
0.681955
996,557
package net.gegy1000.psf.server.block.remote; import org.lwjgl.input.Mouse; import java.io.IOException; import net.minecraftforge.fml.client.GuiScrollingList; public class GuiSelectCraft extends GuiRemoteControl { private GuiScrollingList craftList; public GuiSelectCraft(TileRemoteControlSystem te) { super(null, te); } @Override public void initGui() { super.initGui(); craftList = new GuiCraftList(this, mc, xSize - 20, ySize - 10, guiTop + 10, guiTop + ySize - 10, guiLeft + 10, 20, width, height); } @Override public void handleMouseInput() throws IOException { int mouseX = Mouse.getEventX() * this.width / this.mc.displayWidth; int mouseY = this.height - Mouse.getEventY() * this.height / this.mc.displayHeight - 1; super.handleMouseInput(); if (this.craftList != null) this.craftList.handleMouseInput(mouseX, mouseY); } @Override protected void drawGuiContainerBackgroundLayer(float partialTicks, int mouseX, int mouseY) { super.drawGuiContainerBackgroundLayer(partialTicks, mouseX, mouseY); craftList.drawScreen(mouseX, mouseY, partialTicks); } public void selectCraft(int index) { mc.displayGuiScreen(new GuiCraftDetails(this, index, getTe())); } }
923368c1a48f3f8d3268b96f08cc3d1d0bee889a
1,892
java
Java
gulimall-coupon/src/main/java/com/gulimall/coupon/controller/SpuBoundsController.java
AppleEggX/Java-WebMall
1c04e37736c930b9991551ce98138d52477ac059
[ "Apache-2.0" ]
null
null
null
gulimall-coupon/src/main/java/com/gulimall/coupon/controller/SpuBoundsController.java
AppleEggX/Java-WebMall
1c04e37736c930b9991551ce98138d52477ac059
[ "Apache-2.0" ]
5
2020-07-21T00:42:23.000Z
2021-09-20T20:58:56.000Z
gulimall-coupon/src/main/java/com/gulimall/coupon/controller/SpuBoundsController.java
AppleEggX/Java-WebMall
1c04e37736c930b9991551ce98138d52477ac059
[ "Apache-2.0" ]
null
null
null
22.282353
62
0.684794
996,558
package com.gulimall.coupon.controller; import java.util.Arrays; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.gulimall.coupon.entity.SpuBoundsEntity; import com.gulimall.coupon.service.SpuBoundsService; import com.common.utils.PageUtils; import com.common.utils.R; /** * 商品spu积分设置 * * @author Shawn * @email lyhxr@example.com * @date 2020-05-24 11:53:33 */ @RestController @RequestMapping("coupon/spubounds") public class SpuBoundsController { @Autowired private SpuBoundsService spuBoundsService; /** * 列表 */ @RequestMapping("/list") public R list(@RequestParam Map<String, Object> params){ PageUtils page = spuBoundsService.queryPage(params); return R.ok().put("page", page); } /** * 信息 */ @RequestMapping("/info/{id}") public R info(@PathVariable("id") Long id){ SpuBoundsEntity spuBounds = spuBoundsService.getById(id); return R.ok().put("spuBounds", spuBounds); } /** * 保存 */ @RequestMapping("/save") public R save(@RequestBody SpuBoundsEntity spuBounds){ spuBoundsService.save(spuBounds); return R.ok(); } /** * 修改 */ @RequestMapping("/update") public R update(@RequestBody SpuBoundsEntity spuBounds){ spuBoundsService.updateById(spuBounds); return R.ok(); } /** * 删除 */ @RequestMapping("/delete") public R delete(@RequestBody Long[] ids){ spuBoundsService.removeByIds(Arrays.asList(ids)); return R.ok(); } }
9233691bfd397aade7f8c228e0491d260cfa1358
319
java
Java
_/0182OS_09_code/src/main/java/org/cdibook/chapter9/enums/OrderStatus.java
paullewallencom/jboss-978-1-7821-6018-2
572ff8ef634ff7e38c9a97c33bceef7f076332eb
[ "Apache-2.0" ]
null
null
null
_/0182OS_09_code/src/main/java/org/cdibook/chapter9/enums/OrderStatus.java
paullewallencom/jboss-978-1-7821-6018-2
572ff8ef634ff7e38c9a97c33bceef7f076332eb
[ "Apache-2.0" ]
null
null
null
_/0182OS_09_code/src/main/java/org/cdibook/chapter9/enums/OrderStatus.java
paullewallencom/jboss-978-1-7821-6018-2
572ff8ef634ff7e38c9a97c33bceef7f076332eb
[ "Apache-2.0" ]
null
null
null
17.722222
36
0.677116
996,559
package org.cdibook.chapter9.enums; public enum OrderStatus { CREATED, ADDRESS_VERIFIED, PAYMENT_PROCESSED, PAYMENT_RETRY_ATTEMPTED, PAYMENT_FAILED, PREPARING_SHIPMENT, SHIPPED, DELIVERED, DELIVERY_FAILURE, RETURN_REQUESTED, RETURN_PROCESSED, CLOSED }
923369ae778c60962f8ed32e477581f3bb572c48
1,096
java
Java
marklogic-client-api/src/main/java/com/marklogic/client/MarkLogicInternalException.java
kshitizmittal/java-client-api
7ea967dc9ec08171b802dd3f17087baad7112389
[ "Apache-2.0" ]
null
null
null
marklogic-client-api/src/main/java/com/marklogic/client/MarkLogicInternalException.java
kshitizmittal/java-client-api
7ea967dc9ec08171b802dd3f17087baad7112389
[ "Apache-2.0" ]
null
null
null
marklogic-client-api/src/main/java/com/marklogic/client/MarkLogicInternalException.java
kshitizmittal/java-client-api
7ea967dc9ec08171b802dd3f17087baad7112389
[ "Apache-2.0" ]
null
null
null
28.842105
88
0.748175
996,560
/* * Copyright 2012-2018 MarkLogic Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.marklogic.client; /** * An InternalException suggests a defect in the API. Please contact MarkLogic support. */ @SuppressWarnings("serial") public class MarkLogicInternalException extends RuntimeException { public MarkLogicInternalException(String message) { super(message); } public MarkLogicInternalException(Throwable cause) { super(cause); } public MarkLogicInternalException(String message, Throwable cause) { super(message, cause); } }
923369f66af93c9be6320a69b15a37dc6f939632
1,014
java
Java
src/main/java/com/ssm/cluster/dao/UserDao.java
ZHENFENG13/ssm-cluster
c60e5c8cea26040ec8d0ec10315a94c8ae6932ce
[ "Apache-2.0" ]
151
2017-09-14T09:38:15.000Z
2021-05-12T15:39:37.000Z
src/main/java/com/ssm/cluster/dao/UserDao.java
jimwangshua/ssm-cluster
c60e5c8cea26040ec8d0ec10315a94c8ae6932ce
[ "Apache-2.0" ]
5
2020-06-30T23:11:11.000Z
2022-03-31T20:48:59.000Z
src/main/java/com/ssm/cluster/dao/UserDao.java
jimwangshua/ssm-cluster
c60e5c8cea26040ec8d0ec10315a94c8ae6932ce
[ "Apache-2.0" ]
72
2017-11-08T12:21:44.000Z
2022-01-10T06:39:46.000Z
13.342105
50
0.464497
996,561
package com.ssm.cluster.dao; import com.ssm.cluster.entity.User; import java.util.List; import java.util.Map; /** * @author 13 * @date 2018-02-11 13:39:08 */ public interface UserDao { /** * 登录 * * @param user * @return */ User login(User user); /** * 查找用户列表 * * @param map * @return */ List<User> findUsers(Map<String, Object> map); /** * @param map * @return */ int getTotalUser(Map<String, Object> map); /** * 实体修改 * * @param user * @return */ int updateUser(User user); /** * 添加用户 * * @param user * @return */ int addUser(User user); /** * 删除用户 * * @param id * @return */ int deleteUser(Integer id); /** * 批量删除 * * @param id * @return */ int deleteBatch(Object[] id); /** * 根据id查询用户 * * @param id * @return */ User getUserById(Integer id); }
92336ac2aac261a64f15e3ebed52dec41e6dbbf2
522
java
Java
02springcloud/codes/springcloud_parent/springcloud_06category/src/main/java/com/baizhi/CategoryApplication.java
AshlynZhang/self-study-SpringCloud
8bf83c3d5ee22b77e3a2a0ffa900495813a89992
[ "Apache-2.0" ]
null
null
null
02springcloud/codes/springcloud_parent/springcloud_06category/src/main/java/com/baizhi/CategoryApplication.java
AshlynZhang/self-study-SpringCloud
8bf83c3d5ee22b77e3a2a0ffa900495813a89992
[ "Apache-2.0" ]
null
null
null
02springcloud/codes/springcloud_parent/springcloud_06category/src/main/java/com/baizhi/CategoryApplication.java
AshlynZhang/self-study-SpringCloud
8bf83c3d5ee22b77e3a2a0ffa900495813a89992
[ "Apache-2.0" ]
null
null
null
32.625
72
0.829502
996,562
package com.baizhi; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.openfeign.EnableFeignClients; @SpringBootApplication @EnableDiscoveryClient//开启服务注册 @EnableFeignClients //开启openfein客户端调用 public class CategoryApplication { public static void main(String[] args) { SpringApplication.run(CategoryApplication.class,args); } }
92336adc7138e32e62e208f3c6e5e08fbcaa8795
325
java
Java
chapter_001/src/main/java/ru/job4j/loop/Counter.java
alexustmsk/job4j
dfc159fd52c50d23a7fcd97881794a5b4c1a13a9
[ "Apache-2.0" ]
null
null
null
chapter_001/src/main/java/ru/job4j/loop/Counter.java
alexustmsk/job4j
dfc159fd52c50d23a7fcd97881794a5b4c1a13a9
[ "Apache-2.0" ]
null
null
null
chapter_001/src/main/java/ru/job4j/loop/Counter.java
alexustmsk/job4j
dfc159fd52c50d23a7fcd97881794a5b4c1a13a9
[ "Apache-2.0" ]
null
null
null
21.666667
51
0.473846
996,563
package ru.job4j.loop; public class Counter { public int add(int start, int finish) { int result = 0; for (start = 0; start <= finish; start++) { if (start % 2 == 0) { result += start; } } System.out.println(result); return result; } }
92336aecf983ad6ec7e2280d1a9375873a77118a
1,636
java
Java
cs599-content-enrichment/src/main/java/geoparser/GeoWrapperParser.java
harshfatepuria/Scientific-Content-Enrichment-in-the-Text-Retrieval-Conference-TREC-Polar-Dynamic-Domain-Dataset
0527c6358b555387934f566ac3947288c4c69901
[ "Apache-2.0" ]
1
2016-05-05T21:32:07.000Z
2016-05-05T21:32:07.000Z
cs599-content-enrichment/src/main/java/geoparser/GeoWrapperParser.java
harshfatepuria/Scientific-Content-Enrichment-in-the-Text-Retrieval-Conference-TREC-Polar-Dynamic-Domain-Dataset
0527c6358b555387934f566ac3947288c4c69901
[ "Apache-2.0" ]
null
null
null
cs599-content-enrichment/src/main/java/geoparser/GeoWrapperParser.java
harshfatepuria/Scientific-Content-Enrichment-in-the-Text-Retrieval-Conference-TREC-Polar-Dynamic-Domain-Dataset
0527c6358b555387934f566ac3947288c4c69901
[ "Apache-2.0" ]
null
null
null
29.745455
103
0.76956
996,564
package geoparser; import java.io.IOException; import java.io.InputStream; import java.net.URL; import org.apache.commons.io.IOUtils; import org.apache.tika.exception.TikaException; import org.apache.tika.metadata.Metadata; import org.apache.tika.parser.ParseContext; import org.apache.tika.parser.geo.topic.GeoParser; import org.apache.tika.sax.XHTMLContentHandler; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; import shared.TikaExtractedTextBasedParser; /** * A wrapper for org.apache.tika.parser.geo.topic.GeoParser * To make it able to take Tika extracted text as input * */ public class GeoWrapperParser extends TikaExtractedTextBasedParser { private static final long serialVersionUID = 4050364333648695218L; private GeoParser geoParser; private String nerLocationModelPath = "org/apache/tika/parser/geo/topic/en-ner-location.bin"; public GeoWrapperParser() throws Exception { initializeParser(); } private void initializeParser() { geoParser = new GeoParser(); URL modelUrl = this.getClass().getResource(nerLocationModelPath); geoParser.initialize(modelUrl); } @Override public void parse(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException { String text = getParsedText(stream); try(InputStream plainTextStream = IOUtils.toInputStream(text);){ geoParser.parse(plainTextStream, handler, metadata, context); } XHTMLContentHandler xhtml = new XHTMLContentHandler(handler, metadata); xhtml.startDocument(); xhtml.endDocument(); } }
92336afe5ede0d3f7502e410fd24e1804422da5d
378
java
Java
cornerstone/src/main/java/com/ctrip/framework/cs/enterprise/EnAuthentication.java
birdie7761/vi
39e870cd8b18d07d15a58f2bab12b68a0e5e7b39
[ "Apache-2.0" ]
240
2018-05-18T09:17:59.000Z
2022-01-12T10:38:06.000Z
cornerstone/src/main/java/com/ctrip/framework/cs/enterprise/EnAuthentication.java
birdie7761/vi
39e870cd8b18d07d15a58f2bab12b68a0e5e7b39
[ "Apache-2.0" ]
12
2018-05-20T12:17:53.000Z
2020-09-28T18:00:07.000Z
cornerstone/src/main/java/com/ctrip/framework/cs/enterprise/EnAuthentication.java
birdie7761/vi
39e870cd8b18d07d15a58f2bab12b68a0e5e7b39
[ "Apache-2.0" ]
99
2018-05-30T12:48:28.000Z
2022-02-28T15:03:20.000Z
25.2
147
0.772487
996,565
package com.ctrip.framework.cs.enterprise; import java.util.Map; /** * Created by jiang.j on 2016/10/19. */ public interface EnAuthentication { String authentication(String user,String token,String ip,String requestUrl,Map<String,Object> parameters) throws AuthenticationFailedException; String getJumpUrl(String reqUrl); String getLogoutUrl(String reqUrl); }
92336c5d8cb2b32bdd7f02428fa45fd2e52c4f48
584
java
Java
channel.proxy/src/main/java/com/robot/channel/proxy/utils/Constants.java
RobotGao/mqchannel
0bb13e518abec7fadfa50d79abdc43964f22e918
[ "MIT" ]
1
2018-12-27T08:19:13.000Z
2018-12-27T08:19:13.000Z
channel.proxy/src/main/java/com/robot/channel/proxy/utils/Constants.java
RobotGao/mqchannel
0bb13e518abec7fadfa50d79abdc43964f22e918
[ "MIT" ]
null
null
null
channel.proxy/src/main/java/com/robot/channel/proxy/utils/Constants.java
RobotGao/mqchannel
0bb13e518abec7fadfa50d79abdc43964f22e918
[ "MIT" ]
null
null
null
30.736842
76
0.763699
996,566
package com.robot.channel.proxy.utils; import io.netty.channel.Channel; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; public class Constants { public static String CLIENT_HOST=""; public static Integer CLIENT_PORT; public static String MESSAGE_TOPIC_PUBLISH=""; public static String APPID=""; public static String APP_TCP_CHANNEL="CHANNEL_"; public static Map<String,Channel> channelMap = new ConcurrentHashMap<>(); public static Map<String,String> MESSAGE_FLAG = new ConcurrentHashMap<>(); public static String SECURITY_KEY=""; }
92336cf19bd143d33fb59fa22d390303157820bd
52
java
Java
Inheritance/src/Father.java
yavuzahmet1/Patika
c36091bb0ed137606ee55022ebd86bda32b5481d
[ "MIT" ]
1
2022-01-03T19:22:24.000Z
2022-01-03T19:22:24.000Z
Inheritance/src/Father.java
yavuzahmet1/Patika
c36091bb0ed137606ee55022ebd86bda32b5481d
[ "MIT" ]
null
null
null
Inheritance/src/Father.java
yavuzahmet1/Patika
c36091bb0ed137606ee55022ebd86bda32b5481d
[ "MIT" ]
null
null
null
13
46
0.75
996,567
public interface Father extends GrandMother { }
92336d3a50430da9aa7a2ea47317f430246fa3cd
1,261
java
Java
sample/src/main/java/com/csp/sample/adapter/adapter/TopItemView.java
jefshi/lib-android-adapter
42358192b462c9ec13915a83c8098f7510714dd3
[ "Apache-2.0" ]
null
null
null
sample/src/main/java/com/csp/sample/adapter/adapter/TopItemView.java
jefshi/lib-android-adapter
42358192b462c9ec13915a83c8098f7510714dd3
[ "Apache-2.0" ]
null
null
null
sample/src/main/java/com/csp/sample/adapter/adapter/TopItemView.java
jefshi/lib-android-adapter
42358192b462c9ec13915a83c8098f7510714dd3
[ "Apache-2.0" ]
1
2019-09-05T06:27:45.000Z
2019-09-05T06:27:45.000Z
26.270833
75
0.57732
996,568
package com.csp.sample.adapter.adapter; import com.csp.adapter.recyclerview.ItemViewHolder; import com.csp.adapter.recyclerview.MultipleAdapter; import com.csp.sample.adapter.R; import com.csp.sample.adapter.dto.TopDto; /** * 内容布局 * * @author csp */ class TopItemView implements MultipleAdapter.IItemView<TopDto> { private final static int[] IMG_GRADE_RES = new int[]{ R.drawable.ic_grade_s, R.drawable.ic_grade_a, R.drawable.ic_grade_b, }; @Override public int getLayoutId() { return R.layout.item_top; } @Override public void onBind(ItemViewHolder holder, TopDto datum, int position) { int grade; switch (datum.getGameGrade()) { case "S": grade = 0; break; case "A": grade = 1; break; default: case "B": grade = 2; break; } holder.setText(R.id.txt_label, datum.getChineseName()) .setText(R.id.txt_booster, datum.getGameService()) .setText(R.id.txt_describe, datum.getGameRecommendText()) .setImageResource(R.id.img_grade, IMG_GRADE_RES[grade]); } }
92336e00ab76b2e4536b4bb1e64c646c4e222897
782
java
Java
mybatis-plus/src/main/test/com/mybatisplus/demo/service/MySQLUserServiceTest.java
HeyChiang/java
e4443f6f5eb3ed1ed672d09c0ed171282df8759a
[ "MIT" ]
null
null
null
mybatis-plus/src/main/test/com/mybatisplus/demo/service/MySQLUserServiceTest.java
HeyChiang/java
e4443f6f5eb3ed1ed672d09c0ed171282df8759a
[ "MIT" ]
null
null
null
mybatis-plus/src/main/test/com/mybatisplus/demo/service/MySQLUserServiceTest.java
HeyChiang/java
e4443f6f5eb3ed1ed672d09c0ed171282df8759a
[ "MIT" ]
null
null
null
23
64
0.76087
996,569
package com.mybatisplus.demo.service; import com.mybatisplus.demo.mapper.MySQLMapper; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.annotation.Rollback; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; /** * 在Test模式下,事务会自动回滚,所以用Rollback=false * @author JiangHao at 10/31/2021 10:59 AM */ @Rollback(value = false) @SpringBootTest class MySQLUserServiceTest { @Resource private MySQLMapper mySQLMapper; @Resource private MySQLUserService userService; @Test @Transactional public void intoDataBySelect(){ boolean status = mySQLMapper.intoDataBySelect(); throw new RuntimeException("test"); } }
92336e9416ea7c2c8686cf02cd90cba212f37e25
491
java
Java
src/main/java/com/simplapi/jersey/doc/annotation/ApiVersion.java
Deisss/jersey-doc-annotation
dde38dce071f1b964d102e79d0b7efd9c2308ac3
[ "MIT" ]
2
2015-07-28T13:54:18.000Z
2015-10-15T05:58:48.000Z
src/main/java/com/simplapi/jersey/doc/annotation/ApiVersion.java
Deisss/jersey-doc-annotation
dde38dce071f1b964d102e79d0b7efd9c2308ac3
[ "MIT" ]
null
null
null
src/main/java/com/simplapi/jersey/doc/annotation/ApiVersion.java
Deisss/jersey-doc-annotation
dde38dce071f1b964d102e79d0b7efd9c2308ac3
[ "MIT" ]
null
null
null
25.842105
47
0.810591
996,570
package com.simplapi.jersey.doc.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Define the ApiVersion currently in use */ @Documented @Target({ElementType.TYPE, ElementType.METHOD}) @Inherited @Retention(RetentionPolicy.RUNTIME) public @interface ApiVersion { String value(); }
92336ee72484d3c064f734e33e9e85fd595827a9
9,511
java
Java
app/src/main/java/com/zhiyi/ukafu/NotificationMonitorService.java
lshile/paytts
9b5886228d35280012649a8627e9843a43a358e5
[ "MIT" ]
null
null
null
app/src/main/java/com/zhiyi/ukafu/NotificationMonitorService.java
lshile/paytts
9b5886228d35280012649a8627e9843a43a358e5
[ "MIT" ]
null
null
null
app/src/main/java/com/zhiyi/ukafu/NotificationMonitorService.java
lshile/paytts
9b5886228d35280012649a8627e9843a43a358e5
[ "MIT" ]
3
2020-01-05T08:42:06.000Z
2020-02-15T14:10:46.000Z
37.444882
133
0.599832
996,571
/** * 个人收款 https://gitee.com/DaLianZhiYiKeJi/xpay * 大连致一科技有限公司 */ package com.zhiyi.ukafu; import android.app.Notification; import android.app.NotificationChannel; import android.app.NotificationManager; import android.app.Service; import android.content.Intent; import android.media.MediaPlayer; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.PowerManager; import android.service.notification.NotificationListenerService; import android.service.notification.StatusBarNotification; import android.support.v4.app.NotificationCompat; import android.text.TextUtils; import android.util.Log; import android.widget.Toast; import com.zhiyi.ukafu.consts.ActionName; import com.zhiyi.ukafu.util.AppUtil; import com.zhiyi.ukafu.util.DBManager; import com.zhiyi.ukafu.util.LogUtil; import com.zhiyi.ukafu.util.RequestUtils; import com.zhiyi.ukafu.worker.NotifyFilter; import org.json.JSONException; import java.io.IOException; import java.util.HashMap; import java.util.regex.Matcher; import java.util.regex.Pattern; public class NotificationMonitorService extends NotificationListenerService { private static final String AliPay = "ALIPAY"; private static final String WeixinPay = "WXPAY"; private static final String JxYmf_Pay = "JXYMF"; private static final String JxYmf_PKG = "com.buybal.buybalpay.nxy.jxymf"; // public long lastTimePosted = System.currentTimeMillis(); private Pattern pJxYmf_Nofity; private Pattern pAlipay; private Pattern pAlipay2; private Pattern pAlipayDianyuan; private Pattern pWeixin; private MediaPlayer payRecv; private DBManager dbManager; private PowerManager.WakeLock wakeLock; private NotifyFilter filter; public void onCreate() { super.onCreate(); initFilter(); Log.i(AppConst.TAG_LOG, "Notification posted "); Toast.makeText(getApplicationContext(), "启动服务", Toast.LENGTH_LONG).show(); //支付宝 String pattern = "(\\S*)通过扫码向你付款([\\d\\.]+)元"; pAlipay = Pattern.compile(pattern); pattern = "成功收款([\\d\\.]+)元。享免费提现等更多专属服务,点击查看"; pAlipay2 = Pattern.compile(pattern); pAlipayDianyuan = Pattern.compile("支付宝成功收款([\\d\\.]+)元。收钱码收钱提现免费,赶紧推荐顾客使用"); pWeixin = Pattern.compile("微信支付收款([\\d\\.]+)元"); pJxYmf_Nofity = Pattern.compile("一笔收款交易已完成,金额([\\d\\.]+)元"); payRecv = MediaPlayer.create(this, R.raw.payrecv); dbManager = new DBManager(this); if (AppConst.AppId < 1) { String appid = dbManager.getConfig(AppConst.KeyAppId); if (!TextUtils.isEmpty(appid)) { AppConst.AppId = Integer.parseInt(appid); String token = dbManager.getConfig(AppConst.KeyToken); if (!TextUtils.isEmpty(token)) { AppConst.Token = token; } String secret = dbManager.getConfig(AppConst.KeySecret); if (!TextUtils.isEmpty(secret)) { AppConst.Secret = secret; } } // 推送前判断下playSounds String mute = dbManager.getConfig(AppConst.KeyMute); if(!TextUtils.isEmpty(mute)){ AppConst.PlaySounds = Boolean.parseBoolean(mute); } } Log.i(AppConst.TAG_LOG, "Notification Monitor Service start"); NotificationManager mNM = (NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && mNM != null) { NotificationChannel mNotificationChannel = mNM.getNotificationChannel(AppConst.CHANNEL_ID); if (mNotificationChannel == null) { mNotificationChannel = new NotificationChannel(AppConst.CHANNEL_ID, "Ukafu", NotificationManager.IMPORTANCE_DEFAULT); mNotificationChannel.setDescription("监控专家"); mNM.createNotificationChannel(mNotificationChannel); } } NotificationCompat.Builder nb = new NotificationCompat.Builder(this, AppConst.CHANNEL_ID);// nb.setContentTitle("Ukafu监控专家").setTicker("Ukafu监控专家").setSmallIcon(R.drawable.icon); nb.setContentText("监控专家运行中.请保持此通知一直存在"); //nb.setContent(new RemoteViews(getPackageName(),R.layout.layout)); nb.setWhen(System.currentTimeMillis()); Notification notification = nb.build(); startForeground(1, notification); Log.i(AppConst.TAG_LOG, "Notification Monitor Service started"); } public void onDestroy() { if (wakeLock != null) { wakeLock.release(); wakeLock = null; } Intent localIntent = new Intent(); localIntent.setClass(this, NotificationMonitorService.class); startService(localIntent); } public void onNotificationPosted(StatusBarNotification sbn) { Bundle bundle = sbn.getNotification().extras; String pkgName = sbn.getPackageName(); if (getPackageName().equals(pkgName)) { //测试成功 Log.i(AppConst.TAG_LOG, "测试成功"); Intent intent = new Intent(); intent.setAction(AppConst.IntentAction); Uri uri = new Uri.Builder().scheme("app").path("log").query("msg=测试成功").build(); intent.setData(uri); sendBroadcast(intent); //payRecv.start(); playMedia(payRecv); return; } String title = bundle.getString("android.title"); String text = bundle.getString("android.text"); LogUtil.i("Notification posted [" + pkgName + "]:" + title + " & " + text); if(text == null){ //没有消息.垃圾 return; } HashMap<String,String> fdata = filter.test(bundle,pkgName); if(fdata!=null){ postMethod(fdata); return; } // this.lastTimePosted = System.currentTimeMillis(); //支付宝com.eg.android.AlipayGphone //com.eg.android.AlipayGphone]:支付宝通知 & 新哥通过扫码向你付款0.01元 if (pkgName.equals("com.eg.android.AlipayGphone")) { // 现在创建 matcher 对象 do { Matcher m = pAlipay.matcher(text); if (m.find()) { String uname = m.group(1); String money = m.group(2); postMethod(AliPay, money, uname, false); break; } m = pAlipay2.matcher(text); if (m.find()) { String money = m.group(1); postMethod(AliPay, money, "支付宝用户", false); break; } m = pAlipayDianyuan.matcher(text); if (m.find()) { String money = m.group(1); postMethod(AliPay, money, "支付宝-店员", true); break; } Log.w(AppConst.TAG_LOG, "匹配失败" + text); } while (false); } //微信 //com.tencent.mm]:微信支付 & 微信支付收款0.01元 else if (pkgName.equals("com.tencent.mm")) { // 现在创建 matcher 对象 Matcher m = pWeixin.matcher(text); if (m.find()) { String uname = "微信用户"; String money = m.group(1); postMethod(WeixinPay, money, uname, false); } }else if(pkgName.equals(JxYmf_PKG)){ Matcher m = pJxYmf_Nofity.matcher(text); if(m.find()){ String uname = "一码付"; String money = m.group(1); postMethod(JxYmf_Pay, money, uname, false); } } } public void onNotificationRemoved(StatusBarNotification paramStatusBarNotification) { if (Build.VERSION.SDK_INT >= 19) { Bundle localObject = paramStatusBarNotification.getNotification().extras; String pkgName = paramStatusBarNotification.getPackageName(); String title = localObject.getString("android.title"); String text = (localObject).getString("android.text"); Log.i(AppConst.TAG_LOG, "Notification removed [" + pkgName + "]:" + title + " & " + text); } } public int onStartCommand(Intent paramIntent, int paramInt1, int paramInt2) { return START_NOT_STICKY; } private void postMethod(final String payType, final String money, final String username, boolean dianYuan) { sendBroadcast(AppUtil.sendOrder(payType,money,username,dianYuan)); } private void postMethod(HashMap<String,String> data) { if(data.isEmpty()){ return; } Intent intent = new Intent(ActionName.ONORDER_NOTIFY); intent.putExtra("data",data); sendBroadcast(intent); } private void playMedia(MediaPlayer media) { if (AppConst.PlaySounds) { media.start(); } } public void initFilter() { filter = new NotifyFilter(); RequestUtils.post("https://www.ukafu.com/api.php/portal/filter/nfilter", "appid="+AppConst.AppId, new IHttpResponse() { @Override public void OnHttpData(String data) { try { filter.initData(data); } catch (JSONException e) { Log.e(AppConst.TAG_LOG,"filter init error",e); } } @Override public void OnHttpDataError(IOException e) { } }); } }
923370b17d40ccd1b88729eaac6687f581fa5097
9,748
java
Java
dsb-gui/src/main/java/com/spectralogic/dsbrowser/gui/util/GetStorageLocations.java
irahulgautam/ds3_java_browser
c38dc9dbb00e74295c704736908db0e882ee3bba
[ "Apache-2.0" ]
null
null
null
dsb-gui/src/main/java/com/spectralogic/dsbrowser/gui/util/GetStorageLocations.java
irahulgautam/ds3_java_browser
c38dc9dbb00e74295c704736908db0e882ee3bba
[ "Apache-2.0" ]
null
null
null
dsb-gui/src/main/java/com/spectralogic/dsbrowser/gui/util/GetStorageLocations.java
irahulgautam/ds3_java_browser
c38dc9dbb00e74295c704736908db0e882ee3bba
[ "Apache-2.0" ]
null
null
null
49.989744
196
0.646184
996,572
package com.spectralogic.dsbrowser.gui.util; import com.google.common.collect.ImmutableList; import com.spectralogic.ds3client.models.*; import com.spectralogic.dsbrowser.util.GuavaCollectors; import javafx.geometry.Pos; import javafx.scene.control.Label; import javafx.scene.control.Tooltip; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.layout.HBox; import java.util.ArrayList; import java.util.List; public class GetStorageLocations { private static final Image ONLINEDISK = new Image(ImageURLs.ONLINEDISK); private static final Image NEARLINEDISK = new Image(ImageURLs.NEARLINEDISK); private static final Image STORAGETAPES = new Image(ImageURLs.STORAGETAPES); private static final Image EJECTEDTAPES = new Image(ImageURLs.EJECTEDTAPES); private static final Image BLACKPEARLCACHE = new Image(ImageURLs.BLACKPEARLCACHE); private static final Image REPLICATION = new Image(ImageURLs.REPLICATION); public static HBox addPlacementIconsandTooltip(final BulkObject objects) { final HBox placementIconTooltipHbox = new HBox(); placementIconTooltipHbox.setAlignment(Pos.CENTER); placementIconTooltipHbox.setSpacing(3.0); if (objects != null && objects.getPhysicalPlacement().getTapes() != null) { final ImmutableList<Tape> ejectedTapes = objects.getPhysicalPlacement().getTapes().stream().filter(i -> i.getEjectDate() != null).collect(GuavaCollectors.immutableList()); final int storageTapeCount = objects.getPhysicalPlacement().getTapes().size(); if (ejectedTapes.size() != 0) { final ImageView ejectedTapeIcon = new ImageView(); ejectedTapeIcon.setImage(EJECTEDTAPES); ejectedTapeIcon.setFitHeight(15); ejectedTapeIcon.setFitWidth(15); Tooltip.install(ejectedTapeIcon, new Tooltip(Integer.toString(ejectedTapes.size()) + " copy ejected")); placementIconTooltipHbox.getChildren().add(ejectedTapeIcon); } if ((storageTapeCount - ejectedTapes.size()) != 0) { final ImageView storageTapeIcon = new ImageView(); storageTapeIcon.setImage(STORAGETAPES); storageTapeIcon.setFitHeight(15); storageTapeIcon.setFitWidth(15); Tooltip.install(storageTapeIcon, new Tooltip(Integer.toString(storageTapeCount - ejectedTapes.size()) + " copy on Storage Tape")); placementIconTooltipHbox.getChildren().add(storageTapeIcon); } } if (objects.getPhysicalPlacement().getPools() != null) { final ImmutableList<Pool> nearLineDisk = objects.getPhysicalPlacement().getPools().stream().filter(i -> i.getType().equals(PoolType.NEARLINE)).collect(GuavaCollectors.immutableList()); final int onlineDiskCount = objects.getPhysicalPlacement().getPools().size(); if (nearLineDisk.size() != 0) { final ImageView nearlineDiskIcon = new ImageView(); nearlineDiskIcon.setImage(NEARLINEDISK); nearlineDiskIcon.setFitHeight(15); nearlineDiskIcon.setFitWidth(15); Tooltip.install(nearlineDiskIcon, new Tooltip(Integer.toString(nearLineDisk.size()) + " copy on ArcticBlue")); placementIconTooltipHbox.getChildren().add(nearlineDiskIcon); } if ((onlineDiskCount - nearLineDisk.size()) != 0) { final ImageView onlineDiskIcon = new ImageView(); onlineDiskIcon.setImage(ONLINEDISK); onlineDiskIcon.setFitHeight(15); onlineDiskIcon.setFitWidth(15); Tooltip.install(onlineDiskIcon, new Tooltip(Integer.toString(onlineDiskCount - nearLineDisk.size()) + " copy on Online Disk")); placementIconTooltipHbox.getChildren().add(onlineDiskIcon); } } if (objects.getInCache()) { final ImageView blackPearlCacheIcon = new ImageView(); blackPearlCacheIcon.setImage(BLACKPEARLCACHE); blackPearlCacheIcon.setFitHeight(15); blackPearlCacheIcon.setFitWidth(15); Tooltip.install(blackPearlCacheIcon, new Tooltip("In BlackPearl cache")); placementIconTooltipHbox.getChildren().add(blackPearlCacheIcon); } placementIconTooltipHbox.setAlignment(Pos.CENTER); if (placementIconTooltipHbox.getChildren().size() == 0) { final HBox hbox = new HBox(); hbox.getChildren().add(new Label("----")); hbox.setAlignment(Pos.CENTER); placementIconTooltipHbox.getChildren().add(hbox); } if (objects.getPhysicalPlacement().getDs3Targets() != null) { final List<Ds3Target> ds3Targets = objects.getPhysicalPlacement().getDs3Targets(); if (ds3Targets.size() != 0) { final ImageView replicationIcon = new ImageView(); replicationIcon.setImage(REPLICATION); replicationIcon.setFitHeight(15); replicationIcon.setFitWidth(15); Tooltip.install(replicationIcon, new Tooltip(Integer.toString(ds3Targets.size()) + "BP Replicated copy")); placementIconTooltipHbox.getChildren().add(replicationIcon); } } return placementIconTooltipHbox; } public static HBox addPlacementIconsandTooltip(final PhysicalPlacement placement , final boolean inCache) { final HBox placementIconTooltipHbox = new HBox(); placementIconTooltipHbox.setAlignment(Pos.CENTER); placementIconTooltipHbox.setSpacing(3.0); if (placement != null && placement.getTapes() != null) { final ImmutableList<Tape> ejectedTapes = placement.getTapes().stream().filter(i -> i.getEjectDate() != null).collect(GuavaCollectors.immutableList()); final int storageTapeCount = placement.getTapes().size(); if (ejectedTapes.size() != 0) { final ImageView ejectedTapeIcon = new ImageView(); ejectedTapeIcon.setImage(EJECTEDTAPES); ejectedTapeIcon.setFitHeight(15); ejectedTapeIcon.setFitWidth(15); Tooltip.install(ejectedTapeIcon, new Tooltip(Integer.toString(ejectedTapes.size()) + " copy ejected")); placementIconTooltipHbox.getChildren().add(ejectedTapeIcon); } if ((storageTapeCount - ejectedTapes.size()) != 0) { final ImageView storageTapeIcon = new ImageView(); storageTapeIcon.setImage(STORAGETAPES); storageTapeIcon.setFitHeight(15); storageTapeIcon.setFitWidth(15); Tooltip.install(storageTapeIcon, new Tooltip(Integer.toString(storageTapeCount - ejectedTapes.size()) + " copy on Storage Tape")); placementIconTooltipHbox.getChildren().add(storageTapeIcon); } } if (placement.getPools() != null) { final ImmutableList<Pool> nearLineDisk = placement.getPools().stream().filter(i -> i.getType().equals(PoolType.NEARLINE)).collect(GuavaCollectors.immutableList()); final int onlineDiskCount = placement.getPools().size(); if (nearLineDisk.size() != 0) { final ImageView nearlineDiskIcon = new ImageView(); nearlineDiskIcon.setImage(NEARLINEDISK); nearlineDiskIcon.setFitHeight(15); nearlineDiskIcon.setFitWidth(15); Tooltip.install(nearlineDiskIcon, new Tooltip(Integer.toString(nearLineDisk.size()) + " copy on Nearline Disk")); placementIconTooltipHbox.getChildren().add(nearlineDiskIcon); } if ((onlineDiskCount - nearLineDisk.size()) != 0) { final ImageView onlineDiskIcon = new ImageView(); onlineDiskIcon.setImage(ONLINEDISK); onlineDiskIcon.setFitHeight(15); onlineDiskIcon.setFitWidth(15); Tooltip.install(onlineDiskIcon, new Tooltip(Integer.toString(onlineDiskCount - nearLineDisk.size()) + " copy on Online Disk")); placementIconTooltipHbox.getChildren().add(onlineDiskIcon); } } if (inCache) { final ImageView blackPearlCacheIcon = new ImageView(); blackPearlCacheIcon.setImage(BLACKPEARLCACHE); blackPearlCacheIcon.setFitHeight(15); blackPearlCacheIcon.setFitWidth(15); Tooltip.install(blackPearlCacheIcon, new Tooltip("In cache")); placementIconTooltipHbox.getChildren().add(blackPearlCacheIcon); } placementIconTooltipHbox.setAlignment(Pos.CENTER); if (placementIconTooltipHbox.getChildren().size() == 0) { final HBox hbox = new HBox(); hbox.getChildren().add(new Label("----")); hbox.setAlignment(Pos.CENTER); placementIconTooltipHbox.getChildren().add(hbox); } if (placement.getDs3Targets() != null) { final List<Ds3Target> ds3Targets = placement.getDs3Targets(); if (ds3Targets.size() != 0) { final ImageView replicationIcon = new ImageView(); replicationIcon.setImage(REPLICATION); replicationIcon.setFitHeight(15); replicationIcon.setFitWidth(15); Tooltip.install(replicationIcon, new Tooltip(Integer.toString(ds3Targets.size()) + " Replicated copy")); placementIconTooltipHbox.getChildren().add(replicationIcon); } } return placementIconTooltipHbox; } }
92337120cda1deb1129469a37b84d7bc3cf07b77
590
java
Java
src/main/java/dtprogrammer/github/io/p230/Solution.java
dtprogrammer/leetcode-solutions
0a49f359e8232f9703044b02283777f7fd9361fd
[ "MIT" ]
null
null
null
src/main/java/dtprogrammer/github/io/p230/Solution.java
dtprogrammer/leetcode-solutions
0a49f359e8232f9703044b02283777f7fd9361fd
[ "MIT" ]
null
null
null
src/main/java/dtprogrammer/github/io/p230/Solution.java
dtprogrammer/leetcode-solutions
0a49f359e8232f9703044b02283777f7fd9361fd
[ "MIT" ]
null
null
null
21.851852
58
0.584746
996,573
package dtprogrammer.github.io.p230; import dtprogrammer.github.io.common.TreeNode; public class Solution { int counter = 0; int result = Integer.MIN_VALUE; public int kthSmallest(TreeNode root, int k) { kthSmallestHelper(root, k); return result; } private void kthSmallestHelper(TreeNode root, int k) { if (root == null) return; kthSmallestHelper(root.left, k); counter++; if (k == counter) { result = root.val; return; } kthSmallestHelper(root.right, k); } }
92337207e25d63af84e44d0b3182113287190e89
3,497
java
Java
src/main/java/es/redmic/es/administrative/taxonomy/mapper/MisidentificationESMapper.java
redmic-project/server-library-elasticsearch
885a7fe3c0aafa57bebd135a55ece96490bb1855
[ "Apache-2.0" ]
null
null
null
src/main/java/es/redmic/es/administrative/taxonomy/mapper/MisidentificationESMapper.java
redmic-project/server-library-elasticsearch
885a7fe3c0aafa57bebd135a55ece96490bb1855
[ "Apache-2.0" ]
1
2021-05-25T13:49:55.000Z
2021-05-25T13:49:55.000Z
src/main/java/es/redmic/es/administrative/taxonomy/mapper/MisidentificationESMapper.java
redmic-project/server-library-elasticsearch
885a7fe3c0aafa57bebd135a55ece96490bb1855
[ "Apache-2.0" ]
null
null
null
39.292135
109
0.798399
996,574
package es.redmic.es.administrative.taxonomy.mapper; /*- * #%L * ElasticSearch * %% * Copyright (C) 2019 REDMIC Project / Server * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Component; import es.redmic.es.administrative.service.DocumentESService; import es.redmic.es.administrative.taxonomy.service.TaxonESService; import es.redmic.es.common.utils.DataMapperUtils; import es.redmic.es.geodata.citation.service.CitationESService; import es.redmic.models.es.administrative.dto.DocumentDTO; import es.redmic.models.es.administrative.model.DocumentCompact; import es.redmic.models.es.administrative.taxonomy.dto.MisidentificationDTO; import es.redmic.models.es.administrative.taxonomy.dto.TaxonDTO; import es.redmic.models.es.administrative.taxonomy.model.Misidentification; import es.redmic.models.es.administrative.taxonomy.model.TaxonAncestorsCompact; import es.redmic.models.es.geojson.citation.dto.CitationDTO; import ma.glasnost.orika.CustomMapper; import ma.glasnost.orika.MappingContext; @Component public class MisidentificationESMapper extends CustomMapper<Misidentification, MisidentificationDTO> { @Autowired DocumentESService documentService; @Autowired @Qualifier("TaxonServiceES") private TaxonESService taxonESService; @Autowired private CitationESService citationService; @Override public void mapAtoB(Misidentification a, MisidentificationDTO b, MappingContext context) { b.setDocument(mapperFacade.map(a.getDocument(), DocumentDTO.class)); b.setTaxon(mapperFacade.map(a.getTaxon(), TaxonDTO.class)); b.setBadIdentity(mapperFacade.map(a.getBadIdentity(), TaxonDTO.class)); b.setCitations(getCitationIdsByMisidentification(a.getId())); } @Override public void mapBtoA(MisidentificationDTO b, Misidentification a, MappingContext context) { a.setDocument(mapperFacade.map(mapperFacade.newObject(b.getDocument(), DataMapperUtils.getBaseType(), DataMapperUtils.getObjectFactoryContext(documentService)), DocumentCompact.class)); a.setTaxon(mapperFacade.map(mapperFacade.newObject(b.getTaxon(), DataMapperUtils.getBaseType(), DataMapperUtils.getObjectFactoryContext(taxonESService)), TaxonAncestorsCompact.class)); a.setBadIdentity(mapperFacade.map(mapperFacade.newObject(b.getBadIdentity(), DataMapperUtils.getBaseType(), DataMapperUtils.getObjectFactoryContext(taxonESService)), TaxonAncestorsCompact.class)); } private List<String> getCitationIdsByMisidentification(Long misidentificationId) { List<CitationDTO> result = citationService.findByMisidentification(String.valueOf(misidentificationId)); List<String> citationIds = new ArrayList<String>(); for (int i=0; i<result.size(); i++) { citationIds.add(result.get(i).getUuid()); } return citationIds; } }
9233723ffa7fd70b682404a8513a6bf7e5529695
182
java
Java
src/main/java/com/philihp/weblabora/model/Wonder.java
philihp/WebLabora
737717fd59c1301da6584a6874a20420eba4e71e
[ "Apache-2.0" ]
5
2015-03-28T03:13:48.000Z
2019-06-10T03:53:25.000Z
src/main/java/com/philihp/weblabora/model/Wonder.java
philihp/WebLabora
737717fd59c1301da6584a6874a20420eba4e71e
[ "Apache-2.0" ]
null
null
null
src/main/java/com/philihp/weblabora/model/Wonder.java
philihp/WebLabora
737717fd59c1301da6584a6874a20420eba4e71e
[ "Apache-2.0" ]
3
2015-03-28T03:13:41.000Z
2019-04-23T03:07:40.000Z
15.166667
36
0.703297
996,575
package com.philihp.weblabora.model; public class Wonder { private String name; public Wonder(String name) { this.name = name; } public String getName() { return name; } }
92337242c8406ea467dc5a2463d5d69fd7f42319
1,239
java
Java
src/test/java/org/onedatashare/server/ServerApplicationTests.java
mythreyi1996/onedatashare
91762d5b8724823a5259141ba57262aa16eb8f2d
[ "Apache-2.0" ]
18
2017-10-24T19:05:49.000Z
2021-11-16T09:57:06.000Z
src/test/java/org/onedatashare/server/ServerApplicationTests.java
mythreyi1996/onedatashare
91762d5b8724823a5259141ba57262aa16eb8f2d
[ "Apache-2.0" ]
144
2017-07-20T12:13:01.000Z
2021-12-15T21:25:51.000Z
src/test/java/org/onedatashare/server/ServerApplicationTests.java
mythreyi1996/onedatashare
91762d5b8724823a5259141ba57262aa16eb8f2d
[ "Apache-2.0" ]
17
2017-09-12T08:32:08.000Z
2022-02-10T14:35:56.000Z
31.275
76
0.660272
996,576
/** ##************************************************************** ## ## Copyright (C) 2018-2020, OneDataShare Team, ## Department of Computer Science and Engineering, ## University at Buffalo, Buffalo, NY, 14260. ## ## 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.onedatashare.server; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; kenaa@example.com) //@SpringBootTest public class ServerApplicationTests { @Ignore @Test public void contextLoads() { } }
923373715b097022c5f8315711334a0456d308f2
1,645
java
Java
app/src/main/java/com/verside/appsera/PenjumlahanActivity.java
verdipratama/Appsera
f44dbebd5b40ee7ca759526ae0ef92fc1a70b0d9
[ "MIT" ]
null
null
null
app/src/main/java/com/verside/appsera/PenjumlahanActivity.java
verdipratama/Appsera
f44dbebd5b40ee7ca759526ae0ef92fc1a70b0d9
[ "MIT" ]
null
null
null
app/src/main/java/com/verside/appsera/PenjumlahanActivity.java
verdipratama/Appsera
f44dbebd5b40ee7ca759526ae0ef92fc1a70b0d9
[ "MIT" ]
null
null
null
27.416667
81
0.664438
996,577
package com.verside.appsera; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class PenjumlahanActivity extends AppCompatActivity { EditText bil1,bil2; TextView hasil; Button hitung; private int hasil_akhir=0; private String sBil1=""; private String sBil2=""; private Button btnLogout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_penjumlahan); bil1 = (EditText)findViewById(R.id.txtbil1); bil2 = (EditText)findViewById(R.id.txtbil2); hasil = (TextView) findViewById(R.id.text_hasil); hitung = (Button) findViewById(R.id.cb_hitung); btnLogout = (Button)findViewById(R.id.btnLogout); btnLogout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { logout(); } }); } public void klikHitung(View view){ sBil1 = bil1.getText().toString(); sBil2 = bil2.getText().toString(); hasil_akhir = Integer.parseInt(sBil1)*Integer.parseInt(sBil2); tampilkan(hasil_akhir); } public void tampilkan(int hasil_akhir){ hasil.setText(""+hasil_akhir); } private void logout(){ startActivity(new Intent(PenjumlahanActivity.this,Activity_Login.class)); } public void keluar (View view){ finish(); } }
923373f1ea937c8da6d59b2e4071accf2608518c
2,815
java
Java
spring-boot-client-produtos/src/main/java/com/github/douglsantos/dataprovider/pedidos/PedidosTratamentoDataProvider.java
douglsantos/proc-apache-camel-integration-spring-boot-protobuf
91c701b1408dd88670785224d4b4605652784065
[ "Apache-2.0" ]
null
null
null
spring-boot-client-produtos/src/main/java/com/github/douglsantos/dataprovider/pedidos/PedidosTratamentoDataProvider.java
douglsantos/proc-apache-camel-integration-spring-boot-protobuf
91c701b1408dd88670785224d4b4605652784065
[ "Apache-2.0" ]
null
null
null
spring-boot-client-produtos/src/main/java/com/github/douglsantos/dataprovider/pedidos/PedidosTratamentoDataProvider.java
douglsantos/proc-apache-camel-integration-spring-boot-protobuf
91c701b1408dd88670785224d4b4605652784065
[ "Apache-2.0" ]
null
null
null
29.020619
146
0.761989
996,578
package com.github.douglsantos.dataprovider.pedidos; import java.util.ArrayList; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.github.douglsantos.domain.Cliente; import com.github.douglsantos.domain.Pedido; import com.github.douglsantos.domain.Produto; import com.github.douglsantos.http.constants.HeaderConstants; import com.github.douglsantos.usecase.gateway.ProtobufGateway; import com.github.douglsantos.usecase.gateway.RestGateway; import lombok.extern.log4j.Log4j2; @Log4j2 @Component public class PedidosTratamentoDataProvider { private RestGateway restGateway; private ProtobufGateway protobufGateway; @Autowired public PedidosTratamentoDataProvider(RestGateway restGateway, ProtobufGateway protobufGateway) { this.restGateway = restGateway; this.protobufGateway = protobufGateway; } public List<Pedido> listarTodos(int quantidadePedidos, String contentType) { try { if (contentType.contentEquals(HeaderConstants.CONTENT_TYPE_PROTOBUF)) { return protobufListarTodos(quantidadePedidos); } if (contentType.contentEquals(HeaderConstants.CONTENT_TYPE_JSON)) { return restListarTodos(quantidadePedidos); } } catch (Exception ex) { log.catching(ex); } return null; } /* * Metodo que chama DataProvider com response em JSon */ private List<Pedido> restListarTodos(int quantidadePedidos) { return restGateway.listarTodos(quantidadePedidos); } /* * Metodo que chama DataProvider com response em Protobuf */ private List<Pedido> protobufListarTodos(int quantidadePedidos) { List<Pedido> pedidos = new ArrayList<Pedido>(); List<Produto> produtos = new ArrayList<Produto>(); List<com.github.douglsantos.domain.proto.PedidosProto.Pedido> pedidosProtobuf = protobufGateway.listarTodos(quantidadePedidos).getPedidosList(); for(com.github.douglsantos.domain.proto.PedidosProto.Pedido pedidoProtobuf : pedidosProtobuf) { Cliente cliente = Cliente.builder() .clienteId(pedidoProtobuf.getCliente().getClienteId()) .nome(pedidoProtobuf.getCliente().getNome()) .build(); Produto produto = null; for(com.github.douglsantos.domain.proto.PedidosProto.Produto produtoProtobuf : pedidoProtobuf.getProdutoList()) { produto = Produto.builder() .produtoId(produtoProtobuf.getProdutoId()) .descricaoProduto(produtoProtobuf.getDescricao()) .parceiro(produtoProtobuf.getParceiro()) .valorUnitario(produtoProtobuf.getValorUnitario()) .build(); produtos.add(produto); } Pedido pedido = Pedido.builder() .pedidoId(pedidoProtobuf.getPedidoId()) .produtos(produtos) .cliente(cliente) .build(); pedidos.add(pedido); } return pedidos; } }
9233747f5749d1ac7f7fcebd3fec7cefb6185bc9
3,184
java
Java
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/OffSeason2019/Hardware/TankDrive.java
PMBradley/ftc_app
e99184b1b67d628892f04d75c88a74c9a1d207c6
[ "MIT" ]
null
null
null
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/OffSeason2019/Hardware/TankDrive.java
PMBradley/ftc_app
e99184b1b67d628892f04d75c88a74c9a1d207c6
[ "MIT" ]
null
null
null
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/OffSeason2019/Hardware/TankDrive.java
PMBradley/ftc_app
e99184b1b67d628892f04d75c88a74c9a1d207c6
[ "MIT" ]
null
null
null
46.144928
107
0.776696
996,579
/* Copyright (c) 2017 FIRST. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted (subject to the limitations in the disclaimer below) provided that * the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or * other materials provided with the distribution. * * Neither the name of FIRST nor the names of its contributors may be used to endorse or * promote products derived from this software without specific prior written permission. * * NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED BY THIS * LICENSE. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.firstinspires.ftc.teamcode.OffSeason2019.Hardware; import com.qualcomm.robotcore.eventloop.opmode.Disabled; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.util.ElapsedTime; import com.qualcomm.robotcore.util.Range; /** * This file contains an minimal example of a Linear "OpMode". An OpMode is a 'program' that runs in either * the autonomous or the teleop period of an FTC match. The names of OpModes appear on the menu * of the FTC Driver Station. When an selection is made from the menu, the corresponding OpMode * class is instantiated on the Robot Controller and executed. * * This particular OpMode just executes a basic Tank Drive Teleop for a two wheeled robot * It includes all the skeletal structure that all linear OpModes contain. * * Use Android Studios to Copy this Class, and Paste it into your team's code folder with a new name. * Remove or comment out the @Disabled line to add this opmode to the Driver Station OpMode list */ public class TankDrive extends LinearOpMode { private ElapsedTime runtime = new ElapsedTime(); private DcMotor leftDrive = hardwareMap.get(DcMotor.class, "left_drive"); private DcMotor rightDrive = hardwareMap.get(DcMotor.class, "right_drive"); double leftPower; double rightPower; leftDrive.setPower(leftPower); rightDrive.setPower(rightPower); }
923375be6c0342ab1253622b41c059b9177d5459
2,122
java
Java
components/org.wso2.carbon.identity.conditional.auth.functions.http/src/main/java/org/wso2/carbon/identity/conditional/auth/functions/http/HTTPPostFunctionImpl.java
minolih/identity-conditional-auth-functions
5c280a67146614b77dd028561f57cad5f840a8f1
[ "Apache-2.0" ]
8
2018-07-22T04:19:55.000Z
2021-02-10T19:56:18.000Z
components/org.wso2.carbon.identity.conditional.auth.functions.http/src/main/java/org/wso2/carbon/identity/conditional/auth/functions/http/HTTPPostFunctionImpl.java
minolih/identity-conditional-auth-functions
5c280a67146614b77dd028561f57cad5f840a8f1
[ "Apache-2.0" ]
32
2018-05-11T08:45:34.000Z
2022-03-30T06:13:15.000Z
components/org.wso2.carbon.identity.conditional.auth.functions.http/src/main/java/org/wso2/carbon/identity/conditional/auth/functions/http/HTTPPostFunctionImpl.java
minolih/identity-conditional-auth-functions
5c280a67146614b77dd028561f57cad5f840a8f1
[ "Apache-2.0" ]
45
2018-05-12T06:26:45.000Z
2022-03-22T15:37:31.000Z
34.786885
108
0.728558
996,580
/* * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.carbon.identity.conditional.auth.functions.http; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.json.simple.JSONObject; import java.nio.charset.StandardCharsets; import java.util.Map; import static org.apache.http.HttpHeaders.ACCEPT; import static org.apache.http.HttpHeaders.CONTENT_TYPE; /** * Implementation of the {@link HTTPPostFunction} */ public class HTTPPostFunctionImpl extends AbstractHTTPFunction implements HTTPPostFunction { private static final Log LOG = LogFactory.getLog(HTTPPostFunctionImpl.class); public HTTPPostFunctionImpl() { super(); } @Override public void httpPost(String epUrl, Map<String, Object> payloadData, Map<String, Object> eventHandlers) { HttpPost request = new HttpPost(epUrl); request.setHeader(ACCEPT, TYPE_APPLICATION_JSON); request.setHeader(CONTENT_TYPE, TYPE_APPLICATION_JSON); JSONObject jsonObject = new JSONObject(); for (Map.Entry<String, Object> dataElements : payloadData.entrySet()) { jsonObject.put(dataElements.getKey(), dataElements.getValue()); } request.setEntity(new StringEntity(jsonObject.toJSONString(), StandardCharsets.UTF_8)); executeHttpMethod(request, eventHandlers); } }
923376896eddaf7bdb5cfe67bdb87e815cf4ee24
867
java
Java
src/com5/Linked/ListNode.java
lishangwu/liuyubobobo2
ac0306fa3b740b654549689c5d0a36df75d2c021
[ "MIT" ]
1
2019-07-16T01:39:24.000Z
2019-07-16T01:39:24.000Z
src/com5/Linked/ListNode.java
lishangwu/liuyubobobo2
ac0306fa3b740b654549689c5d0a36df75d2c021
[ "MIT" ]
null
null
null
src/com5/Linked/ListNode.java
lishangwu/liuyubobobo2
ac0306fa3b740b654549689c5d0a36df75d2c021
[ "MIT" ]
null
null
null
18.0625
48
0.487889
996,581
/** * Created by IntelliJ IDEA * * @author robin * @create 2019/6/22 19:14 */ package com5.Linked; public class ListNode { int val; ListNode next; public ListNode(int val) { this.val = val; } public ListNode(int[] arr) { if(arr == null || arr.length == 0) return; this.val = arr[0]; ListNode cur = this; for (int i = 1; i < arr.length; i++) { cur.next = new ListNode(arr[i]); cur = cur.next; } } // 以当前节点为头结点的链表信息字符串 @Override public String toString() { StringBuilder res = new StringBuilder(); res.append(""); ListNode cur = this; while (cur != null){ res.append(cur.val + "->"); cur = cur.next; } res.append(" NULL "); return res.toString(); } }
923376d1492d755dbda7e5fdb6753b8f4bbc910e
3,208
java
Java
src/main/java/dns/discover/service/controller/AuthController.java
marekdlugos/dns-discover-service-spring
d144b3d0176310b7dce898e213bc1f663a7a2806
[ "Apache-2.0" ]
null
null
null
src/main/java/dns/discover/service/controller/AuthController.java
marekdlugos/dns-discover-service-spring
d144b3d0176310b7dce898e213bc1f663a7a2806
[ "Apache-2.0" ]
null
null
null
src/main/java/dns/discover/service/controller/AuthController.java
marekdlugos/dns-discover-service-spring
d144b3d0176310b7dce898e213bc1f663a7a2806
[ "Apache-2.0" ]
null
null
null
37.741176
109
0.676434
996,582
//package dns.discover.service.controller; // //import dns.discover.service.entity.Account; //import dns.discover.service.repository.UserRepository; //import dns.discover.service.service.UserService; //import org.springframework.beans.factory.annotation.Autowired; //import org.springframework.beans.factory.annotation.Value; //import org.springframework.boot.SpringApplication; //import org.springframework.boot.autoconfigure.security.SecurityProperties; //import org.springframework.context.annotation.Configuration; //import org.springframework.core.annotation.Order; //import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; //import org.springframework.security.config.annotation.web.builders.HttpSecurity; //import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; //import org.springframework.security.core.userdetails.UserDetails; //import org.springframework.security.core.userdetails.UserDetailsService; //import org.springframework.security.core.userdetails.UsernameNotFoundException; //import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; //import org.springframework.stereotype.Controller; //import org.springframework.web.bind.annotation.RequestMapping; //import org.springframework.web.bind.annotation.ResponseBody; // //import java.security.Principal; //import java.util.Collections; //import java.util.HashMap; //import java.util.Map; // //@Configuration //@Controller //public class AuthController { // // private String defaultPath = "forward:/views/login.html"; // // @RequestMapping("/") // public String defaultPath() { // return defaultPath; // } // // @RequestMapping("/logged") // @ResponseBody // public Map<String, Object> login(Principal user) { // Map map = new HashMap(); // map.put("name", user.getName()); // map.put("role", "watcher"); // // return map; // } // // @Configuration // @Order(SecurityProperties.ACCESS_OVERRIDE_ORDER) // protected static class SecurityConfiguration extends WebSecurityConfigurerAdapter { // // @Autowired // UserService userService; // // @Autowired // public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception { // // auth.userDetailsService(new UserDetailsService() { // @Override // public UserDetails loadUserById(Long id) throws UsernameNotFoundException { // Account user = userService.getUser(id); // return (UserDetails)user; // // return convert account to UserDetails; // } // }).passwordEncoder(new BCryptPasswordEncoder()); // } // // @Override // protected void configure(HttpSecurity http) throws Exception { // http // .httpBasic() // .and() // .authorizeRequests() // .antMatchers("/js/**", "/css/**", "/fonts/**", "/").permitAll() // .anyRequest().authenticated() // .and() // .csrf().disable(); // } // // // } // //}
9233778ca184e8a5f7543588b52417c912e96c7e
729
java
Java
app/src/main/java/com/devlight/logcat_app/MainActivity.java
YurkivTaras/logcat
88ce819167de6d3f58527d28af596205fc0e0bed
[ "Apache-2.0" ]
5
2019-07-25T13:58:04.000Z
2020-01-24T20:56:45.000Z
app/src/main/java/com/devlight/logcat_app/MainActivity.java
YurkivTaras/logcat
88ce819167de6d3f58527d28af596205fc0e0bed
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/devlight/logcat_app/MainActivity.java
YurkivTaras/logcat
88ce819167de6d3f58527d28af596205fc0e0bed
[ "Apache-2.0" ]
null
null
null
26.035714
89
0.786008
996,583
package com.devlight.logcat_app; import android.content.Intent; import android.os.Bundle; import android.view.View; import androidx.appcompat.app.AppCompatActivity; import com.devlight.logcat.LogcatActivity; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.btn_main_open_logcat).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(MainActivity.this, LogcatActivity.class); intent.putExtra(LogcatActivity.BUFFER_SIZE_EXTRA, 1000); startActivity(intent); } }); } }
923377d2d42a0c37fdc66b9665e84f305ce6d412
1,239
java
Java
src/testU/InitReponsesTest.java
AurelieDigeon/CrossWorld
e3cc78fe158d28fbaa62aad2564a9964526dc88b
[ "Apache-2.0" ]
null
null
null
src/testU/InitReponsesTest.java
AurelieDigeon/CrossWorld
e3cc78fe158d28fbaa62aad2564a9964526dc88b
[ "Apache-2.0" ]
null
null
null
src/testU/InitReponsesTest.java
AurelieDigeon/CrossWorld
e3cc78fe158d28fbaa62aad2564a9964526dc88b
[ "Apache-2.0" ]
null
null
null
24.294118
99
0.696529
996,584
package testU; import java.sql.ResultSet; import java.sql.SQLException; import model.ConnexionSingleton; public class InitReponsesTest { private static ConnexionSingleton connexion; public InitReponsesTest(){ connexion = ConnexionSingleton.getInstance(null); createReponse(); insertReponses(); } public void createReponse(){ connexion.executeUpdate("create table reponse (id int,idDialogue int, texte TEXT,idAction int)"); } public void insertReponses(){ connexion.executeUpdate("insert into reponse values(1,3, 'Pikachu',0)"); connexion.executeUpdate("insert into reponse values(2,3, 'Abra',0)"); connexion.executeUpdate("insert into reponse values(3,3, 'Conconfort',0)"); connexion.executeUpdate("insert into reponse values(4,3, 'Mais qu est ce que j en sais ?!',0)"); } public static void main(String[] args) { ResultSet rs = connexion.executeQuery("select * from reponse"); try { while(rs.next()) { for(int i = 1; i <= rs.getMetaData().getColumnCount(); i++) { System.out.print(rs.getObject(i) + "\t"); } System.out.println(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } connexion.closeConnection(); } }
923377eb01aad69b0667200c040cfc1903453726
10,150
java
Java
flink-end-to-end-tests/flink-end-to-end-tests-common-kafka/src/test/java/org/apache/flink/tests/util/kafka/SQLClientKafkaITCase.java
littlesquare/flink
16486ee4453391a91393ec822a9a7f196ff3249b
[ "Apache-2.0" ]
4
2020-05-28T03:36:05.000Z
2022-02-22T13:46:05.000Z
flink-end-to-end-tests/flink-end-to-end-tests-common-kafka/src/test/java/org/apache/flink/tests/util/kafka/SQLClientKafkaITCase.java
Alan1022/flink
490e2af0f9cc3021b6423535768e9f3604b27519
[ "Apache-2.0" ]
3
2019-11-21T12:22:42.000Z
2019-11-21T12:22:42.000Z
flink-end-to-end-tests/flink-end-to-end-tests-common-kafka/src/test/java/org/apache/flink/tests/util/kafka/SQLClientKafkaITCase.java
Alan1022/flink
490e2af0f9cc3021b6423535768e9f3604b27519
[ "Apache-2.0" ]
5
2019-11-11T01:22:27.000Z
2021-11-22T08:37:30.000Z
41.260163
171
0.709064
996,585
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.tests.util.kafka; import org.apache.flink.tests.util.TestUtils; import org.apache.flink.tests.util.categories.Hadoop; import org.apache.flink.tests.util.categories.TravisGroup1; import org.apache.flink.tests.util.flink.ClusterController; import org.apache.flink.tests.util.flink.FlinkResource; import org.apache.flink.tests.util.flink.FlinkResourceSetup; import org.apache.flink.tests.util.flink.LocalStandaloneFlinkResourceFactory; import org.apache.flink.tests.util.flink.SQLJobSubmission; import org.apache.flink.testutils.junit.FailsOnJava11; import org.apache.flink.util.FileUtils; import org.apache.flink.util.TestLogger; import org.apache.flink.shaded.guava18.com.google.common.base.Charsets; import org.apache.commons.lang3.StringUtils; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.Map; import static org.hamcrest.Matchers.arrayContainingInAnyOrder; import static org.junit.Assert.assertThat; /** * End-to-end test for the kafka SQL connectors. */ @RunWith(Parameterized.class) @Category(value = {TravisGroup1.class, FailsOnJava11.class, Hadoop.class}) public class SQLClientKafkaITCase extends TestLogger { private static final Logger LOG = LoggerFactory.getLogger(SQLClientKafkaITCase.class); private static final String KAFKA_JSON_SOURCE_SCHEMA_YAML = "kafka_json_source_schema.yaml"; @Parameterized.Parameters(name = "{index}: kafka-version:{1} kafka-sql-version:{2}") public static Collection<Object[]> data() { return Arrays.asList(new Object[][]{ {"0.10.2.0", "0.10", ".*kafka-0.10.jar"}, {"0.11.0.2", "0.11", ".*kafka-0.11.jar"}, {"2.2.0", "universal", ".*kafka.jar"} }); } @Rule public final FlinkResource flink = new LocalStandaloneFlinkResourceFactory() .create(FlinkResourceSetup.builder().build()); @Rule public final KafkaResource kafka; @Rule public final TemporaryFolder tmp = new TemporaryFolder(); private final String kafkaSQLVersion; private Path result; private Path sqlClientSessionConf; private static final Path sqlAvroJar = TestUtils.getResourceJar(".*avro.jar"); private static final Path sqlJsonJar = TestUtils.getResourceJar(".*json.jar"); private static final Path sqlToolBoxJar = TestUtils.getResourceJar(".*SqlToolbox.jar"); private final Path sqlConnectorKafkaJar; public SQLClientKafkaITCase(String kafkaVersion, String kafkaSQLVersion, String kafkaSQLJarPattern) { this.kafka = KafkaResource.get(kafkaVersion); this.kafkaSQLVersion = kafkaSQLVersion; this.sqlConnectorKafkaJar = TestUtils.getResourceJar(kafkaSQLJarPattern); } @Before public void before() { Path tmpPath = tmp.getRoot().toPath(); LOG.info("The current temporary path: {}", tmpPath); this.sqlClientSessionConf = tmpPath.resolve("sql-client-session.conf"); this.result = tmpPath.resolve("result"); } @Test public void testKafka() throws Exception { try (ClusterController clusterController = flink.startCluster(2)) { // Create topic and send message String testJsonTopic = "test-json"; String testAvroTopic = "test-avro"; kafka.createTopic(1, 1, testJsonTopic); String[] messages = new String[]{ "{\"timestamp\": \"2018-03-12T08:00:00Z\", \"user\": \"Alice\", \"event\": { \"type\": \"WARNING\", \"message\": \"This is a warning.\"}}", "{\"timestamp\": \"2018-03-12T08:10:00Z\", \"user\": \"Alice\", \"event\": { \"type\": \"WARNING\", \"message\": \"This is a warning.\"}}", "{\"timestamp\": \"2018-03-12T09:00:00Z\", \"user\": \"Bob\", \"event\": { \"type\": \"WARNING\", \"message\": \"This is another warning.\"}}", "{\"timestamp\": \"2018-03-12T09:10:00Z\", \"user\": \"Alice\", \"event\": { \"type\": \"INFO\", \"message\": \"This is a info.\"}}", "{\"timestamp\": \"2018-03-12T09:20:00Z\", \"user\": \"Steve\", \"event\": { \"type\": \"INFO\", \"message\": \"This is another info.\"}}", "{\"timestamp\": \"2018-03-12T09:30:00Z\", \"user\": \"Steve\", \"event\": { \"type\": \"INFO\", \"message\": \"This is another info.\"}}", "{\"timestamp\": \"2018-03-12T09:30:00Z\", \"user\": null, \"event\": { \"type\": \"WARNING\", \"message\": \"This is a bad message because the user is missing.\"}}", "{\"timestamp\": \"2018-03-12T10:40:00Z\", \"user\": \"Bob\", \"event\": { \"type\": \"ERROR\", \"message\": \"This is an error.\"}}" }; kafka.sendMessages(testJsonTopic, messages); // Create topic test-avro kafka.createTopic(1, 1, testAvroTopic); // Initialize the SQL client session configuration file Map<String, String> varsMap = new HashMap<>(); varsMap.put("$TABLE_NAME", "JsonSourceTable"); varsMap.put("$KAFKA_SQL_VERSION", this.kafkaSQLVersion); varsMap.put("$TOPIC_NAME", testJsonTopic); varsMap.put("$RESULT", this.result.toAbsolutePath().toString()); varsMap.put("$KAFKA_ZOOKEEPER_ADDRESS", kafka.getZookeeperAddress().toString()); varsMap.put("$KAFKA_BOOTSTRAP_SERVERS", StringUtils.join(kafka.getBootstrapServerAddresses().toArray(), ",")); String schemaContent = initializeSessionYaml(varsMap); Files.write(this.sqlClientSessionConf, schemaContent.getBytes(Charsets.UTF_8), StandardOpenOption.CREATE, StandardOpenOption.WRITE); // Executing SQL, redirect the data from Kafka JSON to Kafka Avro. insertIntoAvroTable(clusterController); // Executing SQL, redirect the data from Kafka Avro to CSV sink. insertIntoCsvSinkTable(clusterController); // Wait until all the results flushed to the CSV file. LOG.info("Verify the CSV result."); checkCsvResultFile(); LOG.info("The Kafka({}) SQL client test run successfully.", this.kafkaSQLVersion); } } private void insertIntoAvroTable(ClusterController clusterController) throws IOException { LOG.info("Executing SQL: Kafka {} JSON -> Kafka {} Avro", kafkaSQLVersion, kafkaSQLVersion); String sqlStatement1 = "INSERT INTO AvroBothTable\n" + " SELECT\n" + " CAST(TUMBLE_START(rowtime, INTERVAL '1' HOUR) AS VARCHAR) AS event_timestamp,\n" + " user,\n" + " RegReplace(event.message, ' is ', ' was ') AS message,\n" + " COUNT(*) AS duplicate_count\n" + " FROM JsonSourceTable\n" + " WHERE user IS NOT NULL\n" + " GROUP BY\n" + " user,\n" + " event.message,\n" + " TUMBLE(rowtime, INTERVAL '1' HOUR)"; clusterController.submitSQLJob(new SQLJobSubmission.SQLJobSubmissionBuilder(sqlStatement1) .addJar(sqlAvroJar) .addJar(sqlJsonJar) .addJar(sqlConnectorKafkaJar) .addJar(sqlToolBoxJar) .setSessionEnvFile(this.sqlClientSessionConf.toAbsolutePath().toString()) .build()); } private void insertIntoCsvSinkTable(ClusterController clusterController) throws IOException { LOG.info("Executing SQL: Kafka {} Avro -> Csv sink", kafkaSQLVersion); String sqlStatement2 = "INSERT INTO CsvSinkTable\n" + " SELECT AvroBothTable.*, RegReplace('Test constant folding.', 'Test', 'Success') AS constant\n" + " FROM AvroBothTable"; clusterController.submitSQLJob(new SQLJobSubmission.SQLJobSubmissionBuilder(sqlStatement2) .addJar(sqlAvroJar) .addJar(sqlJsonJar) .addJar(sqlConnectorKafkaJar) .addJar(sqlToolBoxJar) .setSessionEnvFile(this.sqlClientSessionConf.toAbsolutePath().toString()) .build() ); } private String initializeSessionYaml(Map<String, String> vars) throws IOException { URL url = SQLClientKafkaITCase.class.getClassLoader().getResource(KAFKA_JSON_SOURCE_SCHEMA_YAML); if (url == null) { throw new FileNotFoundException(KAFKA_JSON_SOURCE_SCHEMA_YAML); } String schema = FileUtils.readFileUtf8(new File(url.getFile())); for (Map.Entry<String, String> var : vars.entrySet()) { schema = schema.replace(var.getKey(), var.getValue()); } return schema; } private void checkCsvResultFile() throws Exception { boolean success = false; long maxRetries = 10, duration = 5000L; for (int i = 0; i < maxRetries; i++) { if (Files.exists(result)) { byte[] bytes = Files.readAllBytes(result); String[] lines = new String(bytes, Charsets.UTF_8).split("\n"); if (lines.length == 4) { success = true; assertThat( lines, arrayContainingInAnyOrder( "2018-03-12 08:00:00.000,Alice,This was a warning.,2,Success constant folding.", "2018-03-12 09:00:00.000,Bob,This was another warning.,1,Success constant folding.", "2018-03-12 09:00:00.000,Steve,This was another info.,2,Success constant folding.", "2018-03-12 09:00:00.000,Alice,This was a info.,1,Success constant folding." ) ); break; } } else { LOG.info("The target CSV {} does not exist now", result); } Thread.sleep(duration); } Assert.assertTrue("Timeout(" + (maxRetries * duration) + " sec) to read the correct CSV results.", success); } }
92337802c558f8c76397abc30cf3a5b1d0f166c8
7,364
java
Java
src/main/jbake/assets/docs/scribble/modules/core/src/main/java/org/scribble/codegen/java/endpointapi/OutputSocketGenerator.java
scribble/scribble.github.io
7c8647be9784e9d1bab0ac4e7286b5122c24358c
[ "Apache-2.0" ]
5
2015-09-11T11:27:38.000Z
2021-01-19T01:10:46.000Z
src/main/jbake/assets/docs/scribble/modules/core/src/main/java/org/scribble/codegen/java/endpointapi/OutputSocketGenerator.java
scribble/scribble.github.io
7c8647be9784e9d1bab0ac4e7286b5122c24358c
[ "Apache-2.0" ]
1
2017-06-19T14:30:26.000Z
2017-06-19T14:30:26.000Z
src/main/jbake/assets/docs/scribble/modules/core/src/main/java/org/scribble/codegen/java/endpointapi/OutputSocketGenerator.java
scribble/scribble.github.io
7c8647be9784e9d1bab0ac4e7286b5122c24358c
[ "Apache-2.0" ]
2
2018-01-14T18:19:34.000Z
2020-12-26T06:26:57.000Z
32.584071
149
0.715915
996,586
package org.scribble.codegen.java.endpointapi; import java.util.Iterator; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.scribble.ast.DataTypeDecl; import org.scribble.ast.MessageSigNameDecl; import org.scribble.ast.Module; import org.scribble.codegen.java.util.JavaBuilder; import org.scribble.codegen.java.util.MethodBuilder; import org.scribble.main.ScribbleException; import org.scribble.model.endpoint.EState; import org.scribble.model.endpoint.actions.EAction; import org.scribble.sesstype.name.DataType; import org.scribble.sesstype.name.MessageSigName; import org.scribble.sesstype.name.PayloadType; public class OutputSocketGenerator extends ScribSocketGenerator { public OutputSocketGenerator(StateChannelApiGenerator apigen, EState curr) { super(apigen, curr); } @Override protected String getSuperClassType() { return OUTPUTSOCKET_CLASS + "<" + getSessionClassName() + ", " + getSelfClassName() + ">"; } @Override protected void addImports() { this.cb.addImports("java.io.IOException"); super.addImports(); } // A method for each successor state //private void addSendMethods(ClassBuilder cb, EndpointState curr) @Override protected void addMethods() throws ScribbleException { final String ROLE_PARAM = "role"; // Mixed sends and connects boolean hasConnect = false; boolean hasWrap = false; for (EAction a : curr.getActions()) // (Scribble ensures all "a" are input or all are output) { EState succ = curr.getSuccessor(a); MethodBuilder mb = this.cb.newMethod(); if (a.isSend()) { setSendHeaderWithoutReturnType(apigen, a, mb); } else if (a.isConnect()) { hasConnect = true; setConnectHeaderWithoutReturnType(apigen, a, mb); } else if (a.isDisconnect()) { setDisconnectHeaderWithoutReturnType(apigen, a, mb); } else if (a.isWrapClient()) { hasWrap = true; setWrapClientHeaderWithoutReturnType(apigen, a, mb); } else { throw new RuntimeException("[TODO] OutputSocket API generation for: " + a); } setNextSocketReturnType(this.apigen, mb, succ); if (a.mid.isOp()) { this.cb.addImports(getOpsPackageName() + ".*"); // FIXME: repeated } if (a.isSend()) { if (a.mid.isOp()) { List<String> args = getSendPayloadArgs(a); String body = JavaBuilder.SUPER + ".writeScribMessage(" + ROLE_PARAM + ", " + getSessionApiOpConstant(a.mid); if (!a.payload.isEmpty()) { body += ", " + args.stream().collect(Collectors.joining(", ")); } body += ");\n"; mb.addBodyLine(body); } else //if (a.mid.isMessageSigName()) { final String MESSAGE_PARAM = "m"; // FIXME: factor out mb.addBodyLine(JavaBuilder.SUPER + ".writeScribMessage(" + ROLE_PARAM + ", " + MESSAGE_PARAM + ");"); } } else if (a.isConnect()) { //throw new RuntimeException("Shouldn't get in here: " + a); mb.addBodyLine(JavaBuilder.SUPER + ".connect(" + ROLE_PARAM + ", cons, host, port);\n"); } else if (a.isDisconnect()) { mb.addBodyLine(JavaBuilder.SUPER + ".disconnect(" + ROLE_PARAM + ");\n"); } else if (a.isWrapClient()) { mb.addBodyLine(JavaBuilder.SUPER + ".wrapClient(" + ROLE_PARAM + ", wrapper);\n"); } else { throw new RuntimeException("Shouldn't get in here: " + a); } addReturnNextSocket(mb, succ); } if (hasConnect) { this.cb.addImports("java.util.concurrent.Callable"); this.cb.addImports("org.scribble.net.session.BinaryChannelEndpoint"); } if (hasWrap) { this.cb.addImports("java.util.concurrent.Callable"); this.cb.addImports("org.scribble.net.session.BinaryChannelWrapper"); } } private static List<String> getSendPayloadArgs(EAction a) { final String ARG_PREFIX = "arg"; return IntStream.range(0, a.payload.elems.size()).mapToObj((i) -> ARG_PREFIX + i++).collect(Collectors.toList()); // FIXME: factor out with params } public static void setSendHeaderWithoutReturnType(StateChannelApiGenerator apigen, EAction a, MethodBuilder mb) throws ScribbleException { final String ROLE_PARAM = "role"; Module main = apigen.getMainModule(); // FIXME: main not necessarily the right module? mb.setName("send"); mb.addModifiers(JavaBuilder.PUBLIC); mb.addExceptions(StateChannelApiGenerator.SCRIBBLERUNTIMEEXCEPTION_CLASS, "IOException"); mb.addParameters(SessionApiGenerator.getRoleClassName(a.obj) + " " + ROLE_PARAM); // More params added below if (a.mid.isOp()) { addSendOpParams(apigen, mb, main, a); } else //if (a.mid.isMessageSigName()) { MessageSigNameDecl msd = main.getMessageSigDecl(((MessageSigName) a.mid).getSimpleName()); // FIXME: might not belong to main module addSendMessageSigNameParams(mb, msd); } } public static void setConnectHeaderWithoutReturnType(StateChannelApiGenerator apigen, EAction a, MethodBuilder mb) { final String ROLE_PARAM = "role"; mb.setName("connect"); mb.addModifiers(JavaBuilder.PUBLIC); mb.addExceptions(StateChannelApiGenerator.SCRIBBLERUNTIMEEXCEPTION_CLASS, "IOException"); mb.addParameters(SessionApiGenerator.getRoleClassName(a.obj) + " " + ROLE_PARAM); // More params added below mb.addParameters("Callable<? extends BinaryChannelEndpoint> cons"); mb.addParameters("String host"); mb.addParameters("int port"); } public static void setDisconnectHeaderWithoutReturnType(StateChannelApiGenerator apigen, EAction a, MethodBuilder mb) { final String ROLE_PARAM = "role"; mb.setName("disconnect"); mb.addModifiers(JavaBuilder.PUBLIC); mb.addExceptions(StateChannelApiGenerator.SCRIBBLERUNTIMEEXCEPTION_CLASS, "IOException"); mb.addParameters(SessionApiGenerator.getRoleClassName(a.obj) + " " + ROLE_PARAM); } public static void setWrapClientHeaderWithoutReturnType(StateChannelApiGenerator apigen, EAction a, MethodBuilder mb) { final String ROLE_PARAM = "role"; mb.setName("wrapClient"); mb.addModifiers(JavaBuilder.PUBLIC); mb.addExceptions(StateChannelApiGenerator.SCRIBBLERUNTIMEEXCEPTION_CLASS, "IOException"); mb.addParameters(SessionApiGenerator.getRoleClassName(a.obj) + " " + ROLE_PARAM); mb.addParameters("Callable<? extends BinaryChannelWrapper> wrapper"); } protected static void addSendOpParams(StateChannelApiGenerator apigen, MethodBuilder mb, Module main, EAction a) throws ScribbleException { List<String> args = getSendPayloadArgs(a); mb.addParameters(SessionApiGenerator.getOpClassName(a.mid) + " op"); // opClass -- op param not actually used in body if (!a.payload.isEmpty()) { Iterator<String> as = args.iterator(); for (PayloadType<?> pt : a.payload.elems) { if (!pt.isDataType()) { throw new ScribbleException("[TODO] API generation not supported for non- data type payloads: " + pt); } DataTypeDecl dtd = main.getDataTypeDecl((DataType) pt); // FIXME: might not belong to main module // TODO: if not DataType ScribSocketGenerator.checkJavaDataTypeDecl(dtd); mb.addParameters(dtd.extName + " " + as.next()); } } } protected static void addSendMessageSigNameParams(MethodBuilder mb, MessageSigNameDecl msd) throws ScribbleException { final String MESSAGE_PARAM = "m"; ScribSocketGenerator.checkMessageSigNameDecl(msd); mb.addParameters(msd.extName + " " + MESSAGE_PARAM); } }
9233788e65195a95728044754bd4c6426eb6d088
4,889
java
Java
src/main/java/org/foxlabs/peg4j/debug/RuleTracer.java
foxinboxx/foxlabs-peg4j
cae464267d29ac56ae83b2bddece444d24cc9bfc
[ "Apache-2.0" ]
1
2015-12-19T08:11:58.000Z
2015-12-19T08:11:58.000Z
src/main/java/org/foxlabs/peg4j/debug/RuleTracer.java
foxinboxx/foxlabs-peg4j
cae464267d29ac56ae83b2bddece444d24cc9bfc
[ "Apache-2.0" ]
null
null
null
src/main/java/org/foxlabs/peg4j/debug/RuleTracer.java
foxinboxx/foxlabs-peg4j
cae464267d29ac56ae83b2bddece444d24cc9bfc
[ "Apache-2.0" ]
null
null
null
26.144385
93
0.703007
996,587
/* * Copyright (C) 2014 FoxLabs * * 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.foxlabs.peg4j.debug; import java.io.IOException; import org.foxlabs.peg4j.BacktrackingReader; import org.foxlabs.peg4j.grammar.Action; import org.foxlabs.peg4j.grammar.Rule; import org.foxlabs.peg4j.grammar.Reference; public interface RuleTracer { void open(BacktrackingReader stream) throws IOException; void onRuleTrace(Rule rule) throws IOException; void onRuleBacktrace(Rule rule, boolean success) throws IOException; void onBeforeAction(Action action) throws IOException; void onAfterAction(Action action, boolean success) throws IOException; void onCacheGet(Reference reference, boolean hit) throws IOException; void onCachePut(Reference reference) throws IOException; void close(boolean result) throws IOException; // Adapter class Adapter implements RuleTracer { @Override public void open(BacktrackingReader stream) throws IOException {} @Override public void onRuleTrace(Rule rule) throws IOException {} @Override public void onRuleBacktrace(Rule rule, boolean success) throws IOException {} @Override public void onBeforeAction(Action action) throws IOException {} @Override public void onAfterAction(Action action, boolean success) throws IOException {} @Override public void onCacheGet(Reference reference, boolean hit) throws IOException {} @Override public void onCachePut(Reference reference) throws IOException {} @Override public void close(boolean result) throws IOException {} } // Wrapper class Wrapper implements RuleTracer { protected final RuleTracer tracer; public Wrapper(RuleTracer tracer) { this.tracer = tracer; } @Override public void open(BacktrackingReader stream) throws IOException { tracer.open(stream); } @Override public void onRuleTrace(Rule rule) throws IOException { tracer.onRuleTrace(rule); } @Override public void onBeforeAction(Action action) throws IOException { tracer.onBeforeAction(action); } @Override public void onAfterAction(Action action, boolean success) throws IOException { tracer.onAfterAction(action, success); } @Override public void onRuleBacktrace(Rule rule, boolean success) throws IOException { tracer.onRuleBacktrace(rule, success); } @Override public void onCacheGet(Reference reference, boolean hit) throws IOException { tracer.onCacheGet(reference, hit); } @Override public void onCachePut(Reference reference) throws IOException { tracer.onCachePut(reference); } @Override public void close(boolean result) throws IOException { tracer.close(result); } } // Chain class Chain implements RuleTracer { protected final RuleTracer[] chain; public Chain(RuleTracer... chain) { this.chain = chain; } @Override public void open(BacktrackingReader stream) throws IOException { for (RuleTracer tracer : chain) { tracer.open(stream); } } @Override public void onRuleTrace(Rule rule) throws IOException { for (RuleTracer tracer : chain) { tracer.onRuleTrace(rule); } } @Override public void onBeforeAction(Action action) throws IOException { for (RuleTracer tracer : chain) { tracer.onBeforeAction(action); } } @Override public void onAfterAction(Action action, boolean success) throws IOException { for (RuleTracer tracer : chain) { tracer.onAfterAction(action, success); } } @Override public void onRuleBacktrace(Rule rule, boolean success) throws IOException { for (RuleTracer tracer : chain) { tracer.onRuleBacktrace(rule, success); } } @Override public void onCacheGet(Reference reference, boolean hit) throws IOException { for (RuleTracer tracer : chain) { tracer.onCacheGet(reference, hit); } } @Override public void onCachePut(Reference reference) throws IOException { for (RuleTracer tracer : chain) { tracer.onCachePut(reference); } } @Override public void close(boolean result) throws IOException { for (RuleTracer tracer : chain) { tracer.close(result); } } } }
92337a4ba7dc1af6924ed70a25bdf5a9813f969b
5,222
java
Java
software/SIW/src/java/gov/nih/nci/ncicb/cadsr/loader/ui/AssociationDetailViewPanel.java
CBIIT/cadsr-semantic-tools
e65bd3cdb9608724c7cc0bf208e09678f4d63c97
[ "BSD-3-Clause" ]
null
null
null
software/SIW/src/java/gov/nih/nci/ncicb/cadsr/loader/ui/AssociationDetailViewPanel.java
CBIIT/cadsr-semantic-tools
e65bd3cdb9608724c7cc0bf208e09678f4d63c97
[ "BSD-3-Clause" ]
null
null
null
software/SIW/src/java/gov/nih/nci/ncicb/cadsr/loader/ui/AssociationDetailViewPanel.java
CBIIT/cadsr-semantic-tools
e65bd3cdb9608724c7cc0bf208e09678f4d63c97
[ "BSD-3-Clause" ]
null
null
null
42.844262
630
0.727377
996,588
/* * Copyright 2000-2003 Oracle, Inc. This software was developed in conjunction with the National Cancer Institute, and so to the extent government employees are co-authors, any rights in such works shall be subject to Title 17 of the United States Code, section 105. * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the disclaimer of Article 3, below. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * 2. The end-user documentation included with the redistribution, if any, must include the following acknowledgment: * * "This product includes software developed by Oracle, Inc. and the National Cancer Institute." * * If no such end-user documentation is to be included, this acknowledgment shall appear in the software itself, wherever such third-party acknowledgments normally appear. * * 3. The names "The National Cancer Institute", "NCI" and "Oracle" must not be used to endorse or promote products derived from this software. * * 4. This license does not authorize the incorporation of this software into any proprietary programs. This license does not authorize the recipient to use any trademarks owned by either NCI or Oracle, Inc. * * 5. THIS SOFTWARE IS PROVIDED "AS IS," AND ANY EXPRESSED OR IMPLIED WARRANTIES, (INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE) ARE DISCLAIMED. IN NO EVENT SHALL THE NATIONAL CANCER INSTITUTE, ORACLE, OR THEIR AFFILIATES BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE */ package gov.nih.nci.ncicb.cadsr.loader.ui; import javax.swing.*; import java.awt.*; import java.awt.event.*; import gov.nih.nci.ncicb.cadsr.loader.ui.util.UIUtil; import gov.nih.nci.ncicb.cadsr.domain.ObjectClassRelationship; import gov.nih.nci.ncicb.cadsr.domain.DomainObjectFactory; /** * The Association viewer * * @author <a href="mailto:efpyi@example.com">Christophe Ludet</a> */ public class AssociationDetailViewPanel extends JPanel { private ObjectClassRelationship ocr; private JLabel[] labels = new JLabel[] { new JLabel("Direction"), new JLabel("Source Class"), new JLabel("Source Role"), new JLabel("Source Multiplicity"), new JLabel("Target Class"), new JLabel("Target Role"), new JLabel("Target Multiplicity") }; private JLabel dirLbl = new JLabel(), srcClassLbl = new JLabel(), srcRoleLbl = new JLabel(), srcMultLbl = new JLabel(), tgtClassLbl = new JLabel(), tgtRoleLbl = new JLabel(), tgtMultLbl = new JLabel(); public AssociationDetailViewPanel(ObjectClassRelationship ocr) { this.ocr = ocr; initValues(); initUI(); } public void update(ObjectClassRelationship ocr) { this.ocr = ocr; initValues(); } private void initUI() { JPanel scrollPanel = new JPanel(new BorderLayout()); JPanel mainPanel = new JPanel(new GridBagLayout()); UIUtil.insertInBag(mainPanel, labels[0], 0, 0); UIUtil.insertInBag(mainPanel, labels[1], 0, 1); UIUtil.insertInBag(mainPanel, labels[2], 0, 2); UIUtil.insertInBag(mainPanel, labels[3], 0, 3); UIUtil.insertInBag(mainPanel, labels[4], 0, 4); UIUtil.insertInBag(mainPanel, labels[5], 0, 5); UIUtil.insertInBag(mainPanel, labels[6], 0, 6); UIUtil.insertInBag(mainPanel, dirLbl, 1, 0); UIUtil.insertInBag(mainPanel, srcClassLbl, 1, 1); UIUtil.insertInBag(mainPanel, srcRoleLbl, 1, 2); UIUtil.insertInBag(mainPanel, srcMultLbl, 1, 3); UIUtil.insertInBag(mainPanel, tgtClassLbl, 1, 4); UIUtil.insertInBag(mainPanel, tgtRoleLbl, 1, 5); UIUtil.insertInBag(mainPanel, tgtMultLbl, 1, 6); scrollPanel.add(mainPanel, BorderLayout.CENTER); // this.setViewportView(scrollPanel); this.add(scrollPanel); } private void initValues() { dirLbl.setText(ocr.getDirection()); srcClassLbl.setText(ocr.getSource().getLongName()); srcRoleLbl.setText(ocr.getSourceRole()); srcMultLbl.setText(ocr.getSourceLowCardinality() + ".." + (ocr.getSourceHighCardinality() == -1 ? "*" : Integer.valueOf(ocr.getSourceHighCardinality()).toString())); tgtClassLbl.setText(ocr.getTarget().getLongName()); tgtRoleLbl.setText(ocr.getTargetRole()); tgtMultLbl.setText(ocr.getTargetLowCardinality() + ".." + (ocr.getTargetHighCardinality() == -1 ? "*" : Integer.valueOf(ocr.getTargetHighCardinality()).toString())); } public static void main(String[] args) { JFrame frame = new JFrame(); frame.setLayout(new BorderLayout()); frame.setSize(500, 400); frame.show(); } }
92337ab487df21d3966726e1098967bdae40d0a3
2,496
java
Java
src/main/java/nl/igorski/mmg/utils/FileSystem.java
alda-pirates/molecular-music-generator
577f7bdf8856f5d2139850e8add533d4fa0a209b
[ "MIT" ]
89
2015-01-09T13:39:33.000Z
2022-03-18T10:36:46.000Z
src/main/java/nl/igorski/mmg/utils/FileSystem.java
alda-pirates/molecular-music-generator
577f7bdf8856f5d2139850e8add533d4fa0a209b
[ "MIT" ]
1
2020-03-09T22:12:01.000Z
2020-03-14T04:42:00.000Z
src/main/java/nl/igorski/mmg/utils/FileSystem.java
igorski/molecular-music-generator
577f7bdf8856f5d2139850e8add533d4fa0a209b
[ "MIT" ]
16
2015-06-14T06:13:53.000Z
2020-06-09T01:41:27.000Z
32.842105
81
0.684295
996,589
/** * The MIT License (MIT) * * Copyright (c) 2015-2019 Igor Zinken * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package nl.igorski.mmg.utils; import java.io.File; import java.nio.file.Files; import java.nio.file.Paths; public final class FileSystem { private static String RELATIVE_DIR = ""; public static String getDirectoryNameFromString( String path ) { final int lastIndex = path.lastIndexOf( File.separator ); if ( lastIndex > -1 ) return path.substring( 0, lastIndex ); return RELATIVE_DIR; } public static String getFileNameFromString( String path ) { final int lastIndex = path.lastIndexOf( File.separator ); if ( lastIndex > -1 ) return path.substring( lastIndex ); return path; } public static boolean createDirectory( String directoryName ) { File directory = new File( directoryName ); // build directory structure if it didn't exist return directory.mkdirs(); } public static File createFile( String fileName ) { String directoryName = getDirectoryNameFromString( fileName ); if ( ! Files.exists(Paths.get(directoryName)) && ! directoryName.equals( RELATIVE_DIR )) { final boolean createdDir = createDirectory(directoryName); if ( !createdDir ) return null; } return new File( fileName ); } }
92337b18ad6cf9525e2de26fba64daddce2cf9ae
4,110
java
Java
src/main/java/tconstruct/modifiers/tools/ModAttack.java
Mortvana/TinkersConstruct
cf0653dfb2eef4cc71631f3d6788a5b049f2a239
[ "CC-BY-3.0", "CC0-1.0" ]
1
2017-04-17T22:21:58.000Z
2017-04-17T22:21:58.000Z
src/main/java/tconstruct/modifiers/tools/ModAttack.java
Mortvana/TinkersConstruct
cf0653dfb2eef4cc71631f3d6788a5b049f2a239
[ "CC-BY-3.0", "CC0-1.0" ]
null
null
null
src/main/java/tconstruct/modifiers/tools/ModAttack.java
Mortvana/TinkersConstruct
cf0653dfb2eef4cc71631f3d6788a5b049f2a239
[ "CC-BY-3.0", "CC0-1.0" ]
null
null
null
31.860465
122
0.554015
996,590
package tconstruct.modifiers.tools; import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTTagCompound; import tconstruct.library.modifier.IModifyable; public class ModAttack extends ItemModTypeFilter { String tooltipName; int max; int threshold; String guiType; String modifierType; public ModAttack(String type, int effect, ItemStack[] items, int[] value) { super(effect, "ModAttack", items, value); tooltipName = "\u00a7fSharpness"; guiType = type; max = 72; threshold = 24; modifierType = "Tool"; } public ModAttack(String type, int effect, ItemStack[] items, int[] value, int max, int threshold, String modifierType) { super(effect, "ModAttack", items, value); tooltipName = "\u00a7fKnuckles"; guiType = type; this.max = max; this.threshold = threshold; this.modifierType = modifierType; } @Override protected boolean canModify (ItemStack tool, ItemStack[] input) { if (tool.getItem() instanceof IModifyable) { IModifyable toolItem = (IModifyable) tool.getItem(); if (!validType(toolItem)) return false; if (matchingAmount(input) > max) return false; NBTTagCompound tags = tool.getTagCompound().getCompoundTag(toolItem.getBaseTagName()); if (!tags.hasKey(key)) return tags.getInteger("Modifiers") > 0 && matchingAmount(input) <= max; int keyPair[] = tags.getIntArray(key); if (keyPair[0] + matchingAmount(input) <= keyPair[1]) return true; else if (keyPair[0] == keyPair[1]) return tags.getInteger("Modifiers") > 0; } return false; } @Override public boolean validType (IModifyable input) { String type = input.getModifyType(); return type.equals(modifierType); } @Override public void modify (ItemStack[] input, ItemStack tool) { IModifyable toolItem = (IModifyable) tool.getItem(); NBTTagCompound tags = tool.getTagCompound().getCompoundTag(toolItem.getBaseTagName()); if (tags.hasKey(key)) { int[] keyPair = tags.getIntArray(key); int increase = matchingAmount(input); int leftToBoost = threshold - (keyPair[0] % threshold); if (increase >= leftToBoost) { int attack = tags.getInteger("Attack"); attack += 1; tags.setInteger("Attack", attack); } if (keyPair[0] % max == 0) { keyPair[0] += increase; keyPair[1] += max; tags.setIntArray(key, keyPair); int modifiers = tags.getInteger("Modifiers"); modifiers -= 1; tags.setInteger("Modifiers", modifiers); } else { keyPair[0] += increase; tags.setIntArray(key, keyPair); } updateModTag(tool, keyPair); } else { int modifiers = tags.getInteger("Modifiers"); modifiers -= 1; tags.setInteger("Modifiers", modifiers); int increase = matchingAmount(input); String modName = "\u00a7f" + guiType + " (" + increase + "/" + max + ")"; int tooltipIndex = addToolTip(tool, tooltipName, modName); int[] keyPair = new int[] { increase, max, tooltipIndex }; tags.setIntArray(key, keyPair); int attack = tags.getInteger("Attack"); attack += 1; tags.setInteger("Attack", attack); } } void updateModTag (ItemStack tool, int[] keys) { NBTTagCompound tags = tool.getTagCompound().getCompoundTag(getTagName(tool)); String tip = "ModifierTip" + keys[2]; String modName = "\u00a7f" + guiType + " (" + keys[0] + "/" + keys[1] + ")"; tags.setString(tip, modName); } }
92337bcfb44b030106607ea1c158bbad2bcbf532
247
java
Java
scrimage-core/src/main/java/com/sksamuel/scrimage/composite/LuminosityComposite.java
gipeshka/scrimage
de467304de8c9ac7b1b790c3e05a2b40f2227837
[ "Apache-2.0" ]
772
2015-01-02T14:28:59.000Z
2022-03-29T05:33:06.000Z
scrimage-core/src/main/java/com/sksamuel/scrimage/composite/LuminosityComposite.java
gipeshka/scrimage
de467304de8c9ac7b1b790c3e05a2b40f2227837
[ "Apache-2.0" ]
189
2015-01-02T16:41:27.000Z
2022-03-29T02:14:43.000Z
scrimage-core/src/main/java/com/sksamuel/scrimage/composite/LuminosityComposite.java
gipeshka/scrimage
de467304de8c9ac7b1b790c3e05a2b40f2227837
[ "Apache-2.0" ]
130
2015-01-23T21:21:56.000Z
2022-01-13T22:00:57.000Z
24.7
59
0.781377
996,591
package com.sksamuel.scrimage.composite; import thirdparty.romainguy.BlendingMode; public class LuminosityComposite extends BlenderComposite { public LuminosityComposite(double alpha) { super(BlendingMode.LUMINOSITY, alpha); } }
92337c9f382e377ac03fdbbd478c928b726ef7ea
89
java
Java
order-service/src/main/java/com/justpickup/orderservice/global/dto/Code.java
Development-team-1/just-pickup
8fd4561f5bd0065c19b690db618c5c46c112e059
[ "MIT" ]
12
2022-01-21T05:25:15.000Z
2022-02-18T10:57:46.000Z
order-service/src/main/java/com/justpickup/orderservice/global/dto/Code.java
Development-team-1/just-pickup
8fd4561f5bd0065c19b690db618c5c46c112e059
[ "MIT" ]
40
2022-01-26T05:27:37.000Z
2022-03-31T07:22:39.000Z
order-service/src/main/java/com/justpickup/orderservice/global/dto/Code.java
Development-team-1/just-pickup
8fd4561f5bd0065c19b690db618c5c46c112e059
[ "MIT" ]
null
null
null
14.833333
47
0.752809
996,592
package com.justpickup.orderservice.global.dto; public enum Code { SUCCESS, ERROR }
92337cc0246363fae3d5a4c3559e83b1a490ecde
2,713
java
Java
samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ArrayTest.java
d0x/swagger-codegen
873e3974ed703155e257b0c05667394f2aa84f48
[ "Apache-2.0" ]
1
2019-08-21T13:57:59.000Z
2019-08-21T13:57:59.000Z
samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayTest.java
atlassian/swagger-codegen
bd705a49d6ba3f1074b8f13c5f5814566d80d8ea
[ "Apache-2.0" ]
null
null
null
samples/client/petstore/java/retrofit2rx/src/main/java/io/swagger/client/model/ArrayTest.java
atlassian/swagger-codegen
bd705a49d6ba3f1074b8f13c5f5814566d80d8ea
[ "Apache-2.0" ]
null
null
null
27.40404
102
0.696646
996,593
package io.swagger.client.model; import java.util.Objects; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.ArrayList; import java.util.List; import com.google.gson.annotations.SerializedName; public class ArrayTest { @SerializedName("array_of_string") private List<String> arrayOfString = new ArrayList<String>(); @SerializedName("array_array_of_integer") private List<List<Long>> arrayArrayOfInteger = new ArrayList<List<Long>>(); @SerializedName("array_array_of_model") private List<List<ReadOnlyFirst>> arrayArrayOfModel = new ArrayList<List<ReadOnlyFirst>>(); /** **/ @ApiModelProperty(value = "") public List<String> getArrayOfString() { return arrayOfString; } public void setArrayOfString(List<String> arrayOfString) { this.arrayOfString = arrayOfString; } /** **/ @ApiModelProperty(value = "") public List<List<Long>> getArrayArrayOfInteger() { return arrayArrayOfInteger; } public void setArrayArrayOfInteger(List<List<Long>> arrayArrayOfInteger) { this.arrayArrayOfInteger = arrayArrayOfInteger; } /** **/ @ApiModelProperty(value = "") public List<List<ReadOnlyFirst>> getArrayArrayOfModel() { return arrayArrayOfModel; } public void setArrayArrayOfModel(List<List<ReadOnlyFirst>> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ArrayTest arrayTest = (ArrayTest) o; return Objects.equals(arrayOfString, arrayTest.arrayOfString) && Objects.equals(arrayArrayOfInteger, arrayTest.arrayArrayOfInteger) && Objects.equals(arrayArrayOfModel, arrayTest.arrayArrayOfModel); } @Override public int hashCode() { return Objects.hash(arrayOfString, arrayArrayOfInteger, arrayArrayOfModel); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class ArrayTest {\n"); sb.append(" arrayOfString: ").append(toIndentedString(arrayOfString)).append("\n"); sb.append(" arrayArrayOfInteger: ").append(toIndentedString(arrayArrayOfInteger)).append("\n"); sb.append(" arrayArrayOfModel: ").append(toIndentedString(arrayArrayOfModel)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
92337eb9f9f560906d1c5bc2a4488c3bc251cbb3
1,310
java
Java
src/main/java/com/uddernetworks/lak/sounds/modulation/ModulatorData.java
RubbaBoy/Lak
295339ebe035c161433958852d73545f0c171f2d
[ "MIT" ]
null
null
null
src/main/java/com/uddernetworks/lak/sounds/modulation/ModulatorData.java
RubbaBoy/Lak
295339ebe035c161433958852d73545f0c171f2d
[ "MIT" ]
null
null
null
src/main/java/com/uddernetworks/lak/sounds/modulation/ModulatorData.java
RubbaBoy/Lak
295339ebe035c161433958852d73545f0c171f2d
[ "MIT" ]
null
null
null
24.716981
95
0.585496
996,594
package com.uddernetworks.lak.sounds.modulation; import java.util.HashMap; import java.util.Map; /** * Essentially a wrapper for a Map< String, Object > from endpoint data, to ensure type safety. */ public class ModulatorData { private final Map<String, Object> data; public ModulatorData() { this(new HashMap<>()); } public ModulatorData(Map<String, Object> data) { this.data = data; } public Map<String, Object> getData() { return data; } /** * Gets the value for the given key if it matches the type T. * * @param key The key * @param <T> The type to get * @return The value associated with the given key, or null */ public <T> T get(String key) { return get(key, null); } /** * Gets the value for the given key if it matches the type T, or a default value. * * @param key The key * @param def The default value instead of null * @param <T> The type to get * @return The value associated with the given key, or the default */ public <T> T get(String key, T def) { try { var gotten = data.get(key); return gotten == null ? def : (T) gotten; } catch (Exception ignored) { return def; } } }
92337f20f9efef18d95c1bb6b32cd0163562e88b
321
java
Java
src/main/java/com/zoght/spring/boot/sample/HealthController.java
tzoght/dockerized-spring-boot
b0fe7c64b501dd54b7d162f23acb68b4733244c3
[ "Apache-2.0" ]
null
null
null
src/main/java/com/zoght/spring/boot/sample/HealthController.java
tzoght/dockerized-spring-boot
b0fe7c64b501dd54b7d162f23acb68b4733244c3
[ "Apache-2.0" ]
null
null
null
src/main/java/com/zoght/spring/boot/sample/HealthController.java
tzoght/dockerized-spring-boot
b0fe7c64b501dd54b7d162f23acb68b4733244c3
[ "Apache-2.0" ]
null
null
null
24.692308
62
0.757009
996,595
package com.zoght.spring.boot.sample; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HealthController { @RequestMapping("/health") public String health() { return "All systems nominal!"; } }
92337f64ecf1eed406f66ab234e38d28dddbc251
1,231
java
Java
test/ooga/engine/physics/physicsCalculator/PhysicsCalculatorTest.java
alexqxu/java-game-development-environment
9c0efa46aa0d3dacca1f0b79411a9f08ad5f0542
[ "MIT" ]
null
null
null
test/ooga/engine/physics/physicsCalculator/PhysicsCalculatorTest.java
alexqxu/java-game-development-environment
9c0efa46aa0d3dacca1f0b79411a9f08ad5f0542
[ "MIT" ]
null
null
null
test/ooga/engine/physics/physicsCalculator/PhysicsCalculatorTest.java
alexqxu/java-game-development-environment
9c0efa46aa0d3dacca1f0b79411a9f08ad5f0542
[ "MIT" ]
null
null
null
34.194444
110
0.749797
996,596
package ooga.engine.physics.physicsCalculator; import ooga.controller.ParameterController; import ooga.model.Entity; import ooga.model.backEndEntities.PlayerEntity; import ooga.parser.components.GeneralInfoParser; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; class PhysicsCalculatorTest { private static final String GAME_FOLDER_PATH = "data/Games/Doodle/level_1.xml"; private static final int LEVEL_NUMBER = 1; private List<Entity> entityList=new ArrayList<>(); private ParameterController pc=new ParameterController(); private PlayerEntity playerEntity=new PlayerEntity(pc); @Test void update() { playerEntity.setCoordinate(10,12); playerEntity.setForce(10,20); playerEntity.setAcceleration(5,10); playerEntity.setVelocity(20,20); entityList.add(playerEntity); PhysicsCalculator physicsCalculator=new PhysicsCalculator(entityList, GAME_FOLDER_PATH, LEVEL_NUMBER); physicsCalculator.update(); assertEquals(37, entityList.get(0).getCoordinate().getX()); assertEquals(47, entityList.get(0).getCoordinate().getY()); } }
9233804b7153721bb7ec38e174b219c271d3bab4
1,131
java
Java
src/com/thoughtworks/pos/domains/Report.java
BJUT-2016-YU-LT/Pos-seed-12
bc9e31966cc9560aa890190e7cfe2f5f0f04dc27
[ "MIT" ]
null
null
null
src/com/thoughtworks/pos/domains/Report.java
BJUT-2016-YU-LT/Pos-seed-12
bc9e31966cc9560aa890190e7cfe2f5f0f04dc27
[ "MIT" ]
null
null
null
src/com/thoughtworks/pos/domains/Report.java
BJUT-2016-YU-LT/Pos-seed-12
bc9e31966cc9560aa890190e7cfe2f5f0f04dc27
[ "MIT" ]
null
null
null
26.928571
84
0.597701
996,597
package com.thoughtworks.pos.domains; import java.util.List; /** * Created by Administrator on 2014/12/31. */ public class Report{ private List<ItemGroup> itemGroupies; public Report(List<ItemGroup> itemGroupies){ this.itemGroupies = itemGroupies; } public List<ItemGroup> getItemGroupies() { return itemGroupies; } public double getTotal(Vip user){ double result = 0.00; for (ItemGroup itemGroup : itemGroupies) { if (itemGroup.promotion() == true) result -= itemGroup.groupPrice(); result += itemGroup.subTotal(user); } return result; } public double getSaving(Vip user){ double result = 0.00; for (ItemGroup itemGroup : itemGroupies) { if(itemGroup.promotion() == true) result += itemGroup.groupPrice(); result += itemGroup.saving(user); } return result; } public boolean getPromotion(){ for (ItemGroup itemGroup : itemGroupies) if (itemGroup.promotion() == true) return true; return false; } }
9233811fd7bdff7320ca591fa0433403fccfbc1f
6,033
java
Java
src/main/java/com/amazonaws/services/identitymanagement/model/DeleteAccessKeyRequest.java
scode/aws-sdk-for-java
c0bbbf7e6a6c0953e67b925c0b0732b264e87c33
[ "Apache-2.0" ]
null
null
null
src/main/java/com/amazonaws/services/identitymanagement/model/DeleteAccessKeyRequest.java
scode/aws-sdk-for-java
c0bbbf7e6a6c0953e67b925c0b0732b264e87c33
[ "Apache-2.0" ]
null
null
null
src/main/java/com/amazonaws/services/identitymanagement/model/DeleteAccessKeyRequest.java
scode/aws-sdk-for-java
c0bbbf7e6a6c0953e67b925c0b0732b264e87c33
[ "Apache-2.0" ]
1
2020-04-06T19:05:22.000Z
2020-04-06T19:05:22.000Z
31.920635
180
0.607326
996,598
/* * Copyright 2010-2011 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.identitymanagement.model; import com.amazonaws.AmazonWebServiceRequest; /** * Container for the parameters to the {@link com.amazonaws.services.identitymanagement.AmazonIdentityManagement#deleteAccessKey(DeleteAccessKeyRequest) DeleteAccessKey operation}. * <p> * Deletes the access key associated with the specified User. * </p> * <p> * If you do not specify a User name, IAM determines the User name * implicitly based on the AWS Access Key ID signing the request. Because * this action works for access keys under the AWS Account, you can use * this API to manage root credentials even if the AWS Account has no * associated Users. * </p> * * @see com.amazonaws.services.identitymanagement.AmazonIdentityManagement#deleteAccessKey(DeleteAccessKeyRequest) */ public class DeleteAccessKeyRequest extends AmazonWebServiceRequest { /** * Name of the User whose key you want to delete. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - 128<br/> * <b>Pattern: </b>[\w+=,.@-]*<br/> */ private String userName; /** * The Access Key ID for the Access Key ID and Secret Access Key you want * to delete. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>16 - 32<br/> * <b>Pattern: </b>[\w]*<br/> */ private String accessKeyId; /** * Default constructor for a new DeleteAccessKeyRequest object. Callers should use the * setter or fluent setter (with...) methods to initialize this object after creating it. */ public DeleteAccessKeyRequest() {} /** * Constructs a new DeleteAccessKeyRequest object. * Callers should use the setter or fluent setter (with...) methods to * initialize any additional object members. * * @param accessKeyId The Access Key ID for the Access Key ID and Secret * Access Key you want to delete. */ public DeleteAccessKeyRequest(String accessKeyId) { this.accessKeyId = accessKeyId; } /** * Name of the User whose key you want to delete. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - 128<br/> * <b>Pattern: </b>[\w+=,.@-]*<br/> * * @return Name of the User whose key you want to delete. */ public String getUserName() { return userName; } /** * Name of the User whose key you want to delete. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - 128<br/> * <b>Pattern: </b>[\w+=,.@-]*<br/> * * @param userName Name of the User whose key you want to delete. */ public void setUserName(String userName) { this.userName = userName; } /** * Name of the User whose key you want to delete. * <p> * Returns a reference to this object so that method calls can be chained together. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - 128<br/> * <b>Pattern: </b>[\w+=,.@-]*<br/> * * @param userName Name of the User whose key you want to delete. * * @return A reference to this updated object so that method calls can be chained * together. */ public DeleteAccessKeyRequest withUserName(String userName) { this.userName = userName; return this; } /** * The Access Key ID for the Access Key ID and Secret Access Key you want * to delete. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>16 - 32<br/> * <b>Pattern: </b>[\w]*<br/> * * @return The Access Key ID for the Access Key ID and Secret Access Key you want * to delete. */ public String getAccessKeyId() { return accessKeyId; } /** * The Access Key ID for the Access Key ID and Secret Access Key you want * to delete. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>16 - 32<br/> * <b>Pattern: </b>[\w]*<br/> * * @param accessKeyId The Access Key ID for the Access Key ID and Secret Access Key you want * to delete. */ public void setAccessKeyId(String accessKeyId) { this.accessKeyId = accessKeyId; } /** * The Access Key ID for the Access Key ID and Secret Access Key you want * to delete. * <p> * Returns a reference to this object so that method calls can be chained together. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>16 - 32<br/> * <b>Pattern: </b>[\w]*<br/> * * @param accessKeyId The Access Key ID for the Access Key ID and Secret Access Key you want * to delete. * * @return A reference to this updated object so that method calls can be chained * together. */ public DeleteAccessKeyRequest withAccessKeyId(String accessKeyId) { this.accessKeyId = accessKeyId; return this; } /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); sb.append("UserName: " + userName + ", "); sb.append("AccessKeyId: " + accessKeyId + ", "); sb.append("}"); return sb.toString(); } }
923381ef748c06abeb416f6647524aaf1ceeca7b
921
java
Java
src/main/java/com/anchor/api/services/stellar/circle/models/Wallet.java
vaibhavantil2/stellar_anchor_backend
79b8a5d6cb137d9c932b50338e59be59d285547f
[ "MIT" ]
null
null
null
src/main/java/com/anchor/api/services/stellar/circle/models/Wallet.java
vaibhavantil2/stellar_anchor_backend
79b8a5d6cb137d9c932b50338e59be59d285547f
[ "MIT" ]
4
2021-12-14T21:53:11.000Z
2022-03-15T02:46:16.000Z
src/main/java/com/anchor/api/services/stellar/circle/models/Wallet.java
malengatiger/stellar_anchor_backend
79b8a5d6cb137d9c932b50338e59be59d285547f
[ "MIT" ]
1
2021-12-22T06:58:02.000Z
2021-12-22T06:58:02.000Z
20.021739
62
0.646037
996,599
package com.anchor.api.services.stellar.circle.models; import java.util.ArrayList; import java.util.List; public class Wallet { private String walletId; private String entityId; private String type; private String description; List<BalanceData> balances = new ArrayList<BalanceData>(); public String getWalletId() { return walletId; } public String getEntityId() { return entityId; } public String getType() { return type; } public String getDescription() { return description; } public void setWalletId(String walletId) { this.walletId = walletId; } public void setEntityId(String entityId) { this.entityId = entityId; } public void setType(String type) { this.type = type; } public void setDescription(String description) { this.description = description; } }
923383011b8bd6d83721d9808bfe7b281c8f1ad9
1,083
java
Java
src/main/java/win/demonlegion/wechatservice/module/message/LinkMessage.java
lin199231/WechatService
9e048d1b65b53a367daca7a4ed8f000822138aad
[ "Apache-2.0" ]
null
null
null
src/main/java/win/demonlegion/wechatservice/module/message/LinkMessage.java
lin199231/WechatService
9e048d1b65b53a367daca7a4ed8f000822138aad
[ "Apache-2.0" ]
null
null
null
src/main/java/win/demonlegion/wechatservice/module/message/LinkMessage.java
lin199231/WechatService
9e048d1b65b53a367daca7a4ed8f000822138aad
[ "Apache-2.0" ]
null
null
null
20.055556
72
0.642659
996,600
package win.demonlegion.wechatservice.module.message; import com.alibaba.fastjson.annotation.JSONField; import java.io.Serializable; /** * 链接消息 */ public class LinkMessage extends WechatMessage implements Serializable { private static final long serialVersionUID = 3110581222015154785L; private String Title; private String Description; private String Url; private String MsgId; @JSONField(name = "Title") public String getTitle() { return Title; } @JSONField(name = "Description") public String getDescription() { return Description; } @JSONField(name = "Url") public String getUrl() { return Url; } @JSONField(name = "MsgId") public String getMsgId() { return MsgId; } public void setTitle(String title) { Title = title; } public void setDescription(String description) { Description = description; } public void setUrl(String url) { Url = url; } public void setMsgId(String msgId) { MsgId = msgId; } }
92338344332f37b9665273fdd5a210db6f67c74f
351
java
Java
src/main/java/dev/remoran/clone/reddit/SpringRedditCloneApplication.java
remorandev-Never-Stop-Learning/spring-reddit-clone
ddd9491db592739c1f66c9e510f3a19c16685c6a
[ "MIT" ]
null
null
null
src/main/java/dev/remoran/clone/reddit/SpringRedditCloneApplication.java
remorandev-Never-Stop-Learning/spring-reddit-clone
ddd9491db592739c1f66c9e510f3a19c16685c6a
[ "MIT" ]
null
null
null
src/main/java/dev/remoran/clone/reddit/SpringRedditCloneApplication.java
remorandev-Never-Stop-Learning/spring-reddit-clone
ddd9491db592739c1f66c9e510f3a19c16685c6a
[ "MIT" ]
null
null
null
25.071429
72
0.803419
996,601
package dev.remoran.clone.reddit; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SpringRedditCloneApplication { public static void main(String[] args) { SpringApplication.run(SpringRedditCloneApplication.class, args); } }
9233842b46d9d02da3f3a717781114c62c552a45
3,511
java
Java
src/main/java/org/jenkinsci/plugins/imagegallery/ImageGallery.java
jenkinsci/image-gallery-plugin
43a18776150bc882a32dee31b73ec8d9516ef545
[ "MIT" ]
4
2015-08-04T20:52:48.000Z
2020-08-27T16:13:19.000Z
src/main/java/org/jenkinsci/plugins/imagegallery/ImageGallery.java
jenkinsci/image-gallery-plugin
43a18776150bc882a32dee31b73ec8d9516ef545
[ "MIT" ]
1
2017-03-10T11:37:36.000Z
2019-11-26T08:29:39.000Z
src/main/java/org/jenkinsci/plugins/imagegallery/ImageGallery.java
biouno/image-gallery-plugin
43a18776150bc882a32dee31b73ec8d9516ef545
[ "MIT" ]
12
2017-02-07T21:16:05.000Z
2020-06-26T07:01:27.000Z
32.509259
136
0.749644
996,602
/* * The MIT License * * Copyright (c) 2012-2015 Bruno P. Kinoshita, BioUno * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.jenkinsci.plugins.imagegallery; import java.io.IOException; import java.io.Serializable; import java.util.Collection; import hudson.DescriptorExtensionList; import hudson.model.AbstractBuild; import hudson.model.AbstractProject; import hudson.model.Action; import hudson.model.BuildListener; import hudson.model.Describable; import hudson.model.Descriptor; import hudson.model.Node; import jenkins.model.Jenkins; /** * Image gallery extension point. Multiple image gallery types extend this class. * * @author Bruno P. Kinoshita - http://www.kinoshita.eti.br * @since 0.1 */ public abstract class ImageGallery implements Serializable, Describable<ImageGallery>, Comparable<ImageGallery> { /* * serial version UID. */ private static final long serialVersionUID = 3016249288702988364L; /** * Title. */ private final String title; private final String imageWidthText; public ImageGallery(String title, String imageWidthText) { this.title = title; this.imageWidthText = imageWidthText; } /** * @return the title */ public String getTitle() { return title; } /** * @return the imageWidthText */ public String getImageWidthText() { return imageWidthText; } /* (non-Javadoc) * @see java.lang.Comparable#compareTo(java.lang.Object) */ public int compareTo(ImageGallery o) { return o != null ? this.getDescriptor().getDisplayName().compareTo(o.getDescriptor().getDisplayName()) : 0; } /* (non-Javadoc) * @see hudson.model.Describable#getDescriptor() */ public Descriptor<ImageGallery> getDescriptor() { return (ImageGalleryDescriptor) Jenkins.get().getDescriptor(getClass()); } public static DescriptorExtensionList<ImageGallery, Descriptor<ImageGallery>> all() { return Jenkins.get().<ImageGallery, Descriptor<ImageGallery>> getDescriptorList(ImageGallery.class); } public static DescriptorExtensionList<ImageGallery, Descriptor<ImageGallery>> allExcept(Node current) { return Jenkins.get().<ImageGallery, Descriptor<ImageGallery>> getDescriptorList(ImageGallery.class); } public Collection<? extends Action> getProjectActions(AbstractProject<?, ?> project) { return null; } public abstract boolean createImageGallery(AbstractBuild<?, ?> build, BuildListener listener) throws InterruptedException, IOException; }
92338481550658858de30665c5b30e4846830c8a
380
java
Java
IPersistence/src/main/java/com/fude/utils/ParameterMapping.java
zjr1169965021/common-member
d78ff856dcb2343f903f86269b7659d8b14bae00
[ "MIT" ]
null
null
null
IPersistence/src/main/java/com/fude/utils/ParameterMapping.java
zjr1169965021/common-member
d78ff856dcb2343f903f86269b7659d8b14bae00
[ "MIT" ]
null
null
null
IPersistence/src/main/java/com/fude/utils/ParameterMapping.java
zjr1169965021/common-member
d78ff856dcb2343f903f86269b7659d8b14bae00
[ "MIT" ]
null
null
null
15.833333
45
0.621053
996,603
package com.fude.utils; /** * @author zhoujr * created at 15:31 2022/6/7 * **/ public class ParameterMapping { private String content; public ParameterMapping(String content) { this.content = content; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } }
92338538af107aa1ef3d918ac132c37cc6f61924
339
java
Java
smilcool-server/src/main/java/com/smilcool/server/core/service/MessageService.java
Angus-Liu/smilcool
bfa71f320f46c136269af3e48ec21f7696c08155
[ "MIT" ]
70
2020-03-06T03:20:13.000Z
2022-03-31T08:19:50.000Z
smilcool-server/src/main/java/com/smilcool/server/core/service/MessageService.java
calokkk/smilcool
bfa71f320f46c136269af3e48ec21f7696c08155
[ "MIT" ]
8
2020-04-08T11:01:01.000Z
2022-02-26T20:19:45.000Z
smilcool-server/src/main/java/com/smilcool/server/core/service/MessageService.java
calokkk/smilcool
bfa71f320f46c136269af3e48ec21f7696c08155
[ "MIT" ]
12
2020-07-07T15:16:19.000Z
2022-03-23T16:48:08.000Z
17.842105
64
0.740413
996,604
package com.smilcool.server.core.service; import com.smilcool.server.core.pojo.po.Message; import java.util.List; /** * @author Angus * @date 2019/5/8 */ public interface MessageService { Message addMessage(Message message); List<Message> getUnsignedMessageList(Integer receiveUserId); void signMessage(Integer id); }
923385ea9c22c8208ce9d92226e218a0d213896b
20,036
java
Java
ycsoft-lib/src/main/java/com/ycsoft/business/dao/core/common/CDoneCodeDao.java
wangjun518/boss-cambodia
bfdd5e9ca7578f1554ed175ab3689bbd2cd73fc0
[ "Apache-2.0" ]
6
2015-07-16T01:36:40.000Z
2019-10-14T07:43:32.000Z
ycsoft-lib/src/main/java/com/ycsoft/business/dao/core/common/CDoneCodeDao.java
leopardoooo/cambodia
a6b552e3ceb60237f058bf8dfea369f47769542c
[ "Apache-2.0" ]
null
null
null
ycsoft-lib/src/main/java/com/ycsoft/business/dao/core/common/CDoneCodeDao.java
leopardoooo/cambodia
a6b552e3ceb60237f058bf8dfea369f47769542c
[ "Apache-2.0" ]
5
2015-07-15T02:44:07.000Z
2020-07-02T09:40:22.000Z
50.59596
200
0.713566
996,605
/** * CDoneCodeDao.java 2010/03/16 */ package com.ycsoft.business.dao.core.common; import static com.ycsoft.commons.helper.StringHelper.append; import java.util.ArrayList; import java.util.List; import org.springframework.stereotype.Component; import com.ycsoft.beans.core.common.CDoneCode; import com.ycsoft.beans.system.SOptr; import com.ycsoft.business.dto.core.cust.DoneCodeDto; import com.ycsoft.business.dto.core.cust.DoneInfoDto; import com.ycsoft.business.dto.core.fee.QueryFeeInfo; import com.ycsoft.business.dto.print.BusiDocPrintItemDto; import com.ycsoft.commons.constants.BusiCodeConstants; import com.ycsoft.commons.constants.StatusConstants; import com.ycsoft.commons.constants.SystemConstants; import com.ycsoft.commons.helper.StringHelper; import com.ycsoft.daos.abstracts.BaseEntityDao; import com.ycsoft.daos.core.JDBCException; import com.ycsoft.daos.core.Pager; /** * CDoneCodeDao -> C_DONE_CODE table's operator */ @Component public class CDoneCodeDao extends BaseEntityDao<CDoneCode> { private static final long serialVersionUID = 142913821221838946L; /** * default empty constructor */ public CDoneCodeDao() {} public void saveCancel(int doneCode,String busiCode) throws Exception{ String sql ="insert into c_done_code_cancel (done_code,cancel_date,flag,busi_code) " + " values (?,sysdate,?,?)"; this.executeUpdate(sql, doneCode,SystemConstants.BOOLEAN_FALSE,busiCode); } public void updateCancelFlag(int doneCode) throws Exception{ String sql ="update c_done_code set flag=? where done_code=?"; this.executeUpdate(sql,SystemConstants.BOOLEAN_TRUE, doneCode); } public void updateRemark(int doneCode,String remark) throws Exception{ String sql ="update c_done_code set remark=? where done_code=?"; this.executeUpdate(sql,remark, doneCode); } /** * 根据用户ID,获取用户受理记录 * @param custId * @param countyId */ public List<CDoneCode> queryUserDoneCode(String userId,String countyId)throws Exception{ List<CDoneCode> doneCodeList = null; String sql = "select distinct a.done_code,a.busi_code,done_date,a.optr_id,a.remark " + " from c_done_code a, c_done_code_detail b" + " where a.done_code=b.done_code " + " and b.user_id= ? and a.county_id=? "; doneCodeList = this.createQuery( sql,userId,countyId).list(); return doneCodeList; } /** * 查询在当前donecode之前可以回退的流水 * @param custId * @param countyId */ public List<CDoneCode> queryAfterDoneCode(Integer doneCode,String custId,String countyId)throws Exception{ List<CDoneCode> doneCodeList = null; String sql = " select distinct a.done_code,a.busi_code,done_date,a.optr_id,a.remark" + " from c_done_code a ,c_done_code_detail b,t_busi_code c " + " where a.done_code=b.done_code and a.busi_code = c.busi_code " + " and b.cust_id=? and status=? and a.county_id=? " + " and c.ignore=? and busi_type='1' " + " and done_date > (select done_date from c_done_code where done_code=?)"; doneCodeList = this.createQuery(sql,custId,StatusConstants.ACTIVE,countyId,SystemConstants.BOOLEAN_FALSE,doneCode).list(); return doneCodeList; } /** * 根据客户ID,获取客户受理记录 * @param custId * @param countyId */ public Pager<DoneCodeDto> queryCustDoneCode(String custId, QueryFeeInfo queryFeeInfo,String countyId,Integer start,Integer limit)throws Exception{ String sql = append("select distinct a.done_code,b.user_id, ", " a.remark,a.busi_code,a.done_date,a.optr_id,a.status,t3.cancel,t3.ignore,t3.busi_fee,a.dept_id,(select sum(real_pay) from c_fee f where f.create_done_code =a.done_code) real_pay ", " from c_done_code a, c_done_code_detail b,t_busi_code t3 ", " where t3.busi_type(+)='1' and a.done_code = b.done_code", " and a.busi_code = t3.busi_code(+) ", " and b.cust_id = ? ", " and a.county_id = ?"); if(queryFeeInfo != null){ if(StringHelper.isNotEmpty(queryFeeInfo.getStatus())){ sql += " and a.status='" + queryFeeInfo.getStatus() + "'"; } if(StringHelper.isNotEmpty(queryFeeInfo.getBusi_name())){ sql += " and t3.busi_name like '%" + queryFeeInfo.getBusi_name() + "%'"; } if(StringHelper.isNotEmpty(queryFeeInfo.getOptr_name())){ sql += " and a.optr_id in (select optr_id from s_optr where county_id='"+countyId+"' and optr_name like '%"+queryFeeInfo.getOptr_name()+"%')"; } } sql += " order by a.done_code desc"; return this.createQuery(DoneCodeDto.class, sql, custId, countyId) .setStart(start).setLimit(limit).page(); } /** * 根据done_code查询作废信息 * @param doneCode * @param custId * @return * @throws Exception */ public List<DoneCodeDto> queryCfeeByDoneCode(String[] doneCode,String custId)throws Exception{ if (doneCode==null || doneCode.length==0) return new ArrayList<DoneCodeDto>(); String sql = "select t.create_done_code done_code ,t.reverse_done_code,t.real_pay,t.fee_id from c_fee t where t.cust_id =? " + " and ("+getSqlGenerator().setWhereInArray("t.create_done_code",doneCode)+") "; return createQuery(DoneCodeDto.class, sql,custId).list(); } /** * @param doneCode */ public void delete(Integer doneCode) throws Exception{ String sql ="update c_done_code set status =? where done_code=?"; executeUpdate(sql, StatusConstants.INVALID,doneCode); } /** * 获取用户在几个月内临时授权的次数 * @param userId * @param months * @param county_id * @return */ public int queryOpenTempTimes(String userId, int months, String countyId) throws Exception{ String sql = "select count(1) " + " from c_done_code a, c_done_code_detail b" + " where a.done_code=b.done_code " + " and a.status=? and a.county_id=? " + " and a.busi_code=? and b.user_id= ? " + " and a.done_date>= add_months(sysdate,?) "; return Integer.parseInt(findUnique(sql, StatusConstants.ACTIVE,countyId,BusiCodeConstants.USER_OPEN_TEMP,userId,months*-1).toString()); } /** * 查询数据库时间 * @throws Exception * @throws JDBCException */ public String queryDataBaseTime() throws JDBCException, Exception{ String sql="select to_char(sysdate,'yyyy-mm-dd hh24:mi:ss') from dual"; String dateStr = this.findUnique(sql); return dateStr; } public Pager<DoneInfoDto> getUserOpenDate(Integer cDoneCode, Integer start, Integer limit) throws Exception { String sql = "select T.STB_ID,T.CARD_ID,T.MODEM_MAC,t.user_type from C_USER T,c_done_code T1,c_done_code_detail T2 " + " WHERE T1.DONE_CODE =? AND T1.DONE_CODE=T2.DONE_CODE AND T2.USER_ID=T.USER_ID"; return this.createQuery(DoneInfoDto.class, sql, cDoneCode) .setStart(start).setLimit(limit).page(); } public Pager<DoneInfoDto> getOrderProdDate(Integer doneCode, String custId, Integer start, Integer limit) throws Exception { /*String sql = "select pp.prod_name,ppt.tariff_name,cp.invalid_date,cu.stb_id,cu.card_id,cu.user_type ,cp.status" + " from c_prod cp,p_prod pp,c_user cu,p_prod_tariff ppt " + " where cp.done_code=? and cp.county_id=? and cu.county_id=?" + " and ppt.tariff_id(+)=cp.tariff_id and cp.prod_id=pp.prod_id(+) and cp.user_id = cu.user_id" + " union select pp.prod_name,ppt.tariff_name,cp.invalid_date,cu.stb_id,cu.card_id,cu.user_type ,cp.status " + " from c_prod_his cp,p_prod pp,c_user cu,p_prod_tariff ppt where cp.order_done_code=? " + " and cp.county_id=? and cu.county_id=?"+ " and ppt.tariff_id(+)=cp.tariff_id and cp.prod_id=pp.prod_id(+) and cp.user_id = cu.user_id "; return this.createQuery(DoneInfoDto.class, sql, cDoneCode,countyId,countyId,cDoneCode,countyId,countyId) .setStart(start).setLimit(limit).page();*/ String sql = "select '订购Order' remark,t.order_sn,t.done_code,t.prod_id,t.order_time,t.order_fee,t.active_fee,t.order_months,t.eff_date,t.exp_date," + " p.prod_name,pf.tariff_name" + " from c_prod_order t,p_prod p,p_prod_tariff pf" + " where t.package_sn is null and t.prod_id=p.prod_id and t.tariff_id=pf.tariff_id " + " and t.done_code=? and t.cust_id=?" + " union all" + " select '订购Order' remark,t.order_sn,t.done_code,t.prod_id,t.order_time,t.order_fee,t.active_fee,t.order_months,t.eff_date,t.exp_date," + " p.prod_name,pf.tariff_name" + " from c_prod_order_his t ,p_prod p,p_prod_tariff pf" + " where t.package_sn is null and t.prod_id=p.prod_id and t.tariff_id=pf.tariff_id " + " and t.done_code=? and t.cust_id=?" + " union all" + " select '退订Unsubscribe' remark,t.order_sn,t.delete_done_code done_code,t.prod_id,t.order_time,t.order_fee,t.active_fee,t.order_months,t.eff_date,t.exp_date," + " p.prod_name,pf.tariff_name" + " from c_prod_order_his t ,p_prod p,p_prod_tariff pf" + " where t.package_sn is null and t.prod_id=p.prod_id and t.tariff_id=pf.tariff_id " + " and t.delete_done_code=? and t.cust_id=?" + " order by remark"; return this.createQuery(DoneInfoDto.class, sql, doneCode, custId, doneCode, custId, doneCode, custId).setStart(start).setLimit(limit).page(); } public Pager<DoneInfoDto> getDeviceBuyDate(Integer cDoneCode, String countyId, Integer start, Integer limit) throws Exception { String sql = "select t.device_type,t.device_code,t.pair_card_code,t.pair_modem_code,t.status,t.buy_mode " + " from c_cust_device T,c_done_code_detail cd WHERE cd.done_code=t.done_code and cd.DONE_CODE =? and t.cust_id=cd.cust_id and t.county_id =? and cd.county_id = ? " + " union select t.device_type,t.device_code,t.pair_card_code,t.pair_modem_code,t.status,t.buy_mode " + " from c_cust_device_his T,c_done_code_detail cd WHERE cd.done_code=t.buy_DONE_CODE and cd.DONE_CODE =? and t.cust_id=cd.cust_id and t.county_id =? and cd.county_id = ?"; return this.createQuery(DoneInfoDto.class, sql, cDoneCode,countyId,countyId,cDoneCode,countyId,countyId) .setStart(start).setLimit(limit).page(); } public Pager<DoneInfoDto> getDeviceChangeDate(Integer cDoneCode, String countyId, Integer start, Integer limit) throws Exception { String sql = "select cu.column_name,cu.old_value,cu.new_value, tt.comments column_name_text,c.user_type " + " from c_user_prop_change cu, t_tab_define tt,c_user c where cu.done_code =? and cu.county_id=? " + " and c.county_id=? and c.user_id = cu.user_id " + " and cu.column_name=tt.column_name and tt.status =? and tt.table_name in ('CUSER','CUSERBROADBAND','CUSERATV','CUSERDTV')"; return this.createQuery(DoneInfoDto.class, sql, cDoneCode,countyId,countyId,StatusConstants.ACTIVE) .setStart(start).setLimit(limit).page(); } public Pager<DoneInfoDto> getPromotionDate(Integer cDoneCode, String countyId, Integer start, Integer limit) throws Exception { String sql = "select c.status,p.promotion_name from c_promotion c,p_promotion p,c_done_code_detail t " + " where c.promotion_id=p.promotion_id and c.user_id=t.user_id and t.done_code=c.done_code and t.done_code = ? and c.county_id= ? and t.county_id = ? " + " union select c.status,p.promotion_name from c_promotion_his c,p_promotion p,c_done_code_detail t " + " where c.promotion_id=p.promotion_id and c.user_id=t.user_id and t.done_code=c.done_code and t.done_code = ? and c.county_id= ? and t.county_id = ? "; return this.createQuery(DoneInfoDto.class, sql, cDoneCode,countyId,countyId,cDoneCode,countyId,countyId) .setStart(start).setLimit(limit).page(); } public Pager<DoneInfoDto> getPromFeeDate(Integer cDoneCode, String countyId, Integer start, Integer limit) throws Exception { String sql = "select cpfp.user_id,cpfp.months,cpfp.real_pay,cpfp.should_pay,cpfp.bind_invalid_date,pp.prod_name ,sum(cr.refund_pay) refund_pay,pp.remark " + " from c_prom_fee cpf,c_prom_fee_prod cpfp,p_prod pp,c_prom_prod_Refund cr,p_prom_fee pp " + " where pp.prod_id = cpfp.prod_id and cpf.county_id = ? and cpf.done_code =? and cpf.prom_fee_sn = cpfp.prom_fee_sn " + " and cpfp.prom_fee_sn = cr.prom_fee_sn(+) and cpfp.prod_sn = cr.prod_sn(+) and cpf.prom_fee_id=pp.prom_fee_id " + " group by cpfp.user_id,cpfp.months,cpfp.real_pay,cpfp.should_pay,cpfp.bind_invalid_date,pp.prod_name,pp.remark " + " order by cpfp.user_id"; return this.createQuery(DoneInfoDto.class, sql, countyId,cDoneCode) .setStart(start).setLimit(limit).page(); } public Pager<DoneInfoDto> getBandUpgradeDate(Integer doneCode, String countyId, Integer start, Integer limit) throws Exception { String sql = "select t.*,p1.prod_name old_prod_name,p2.prod_name prod_name,pt1.tariff_name old_tariff_name,pt2.tariff_name tariff_name" + " from C_BAND_UPGRADE_RECORD t,p_prod p1,p_prod p2,p_prod_tariff pt1,p_prod_tariff pt2" + " where t.old_prod_id=p1.prod_id and t.new_prod_id=p2.prod_id" + " and t.old_tariff_id=pt1.tariff_id and t.new_tariff_id=pt2.tariff_id" + " and t.done_code=? and t.county_id=?"; return this.createQuery(DoneInfoDto.class, sql, doneCode, countyId).setStart(start).setLimit(limit).page(); } public List<DoneCodeDto> queryOnelineUserBusi(String optrId)throws Exception{ String sql = "select optr_id , busi_code, count(1) done_num, sum(decode(status,'ACTIVE',1,0)) active_num ," + "sum(decode(status,'INVALID',1,0)) INVALID_num , max(done_date) last_done_date from busi.c_done_code " + "where optr_id=? and done_date >= trunc(sysdate) and done_date < trunc(sysdate) + 1 " + "group by busi_code,optr_id order by last_done_date desc"; return this.createQuery(DoneCodeDto.class, sql,optrId).list(); } /** * 查询客户未打印的业务单据按业务分类 * @param countyId * @param custId */ public List<BusiDocPrintItemDto> queryDocPrintBusiCodeByCust(SOptr optr ,String custId,String docSn)throws Exception{ String sql = " SELECT distinct t.busi_code,T.doneCode done_code ,si.BUSI_CODE_SPAN,si.GROUP_COLUMN , si.condition, " +" (case when si.GROUP_COLUMN='CUST' then '' when si.GROUP_COLUMN is null then '' else t.user_id end )user_id" +" FROM (SELECT T2.INFO, T.BUSI_CODE, t2.done_code doneCode,t2.last_print, t.done_date,cdcd.user_id " +" FROM C_DONE_CODE T, C_DONE_CODE_INFO T2 ,busi.c_done_code_detail cdcd " +" WHERE T.COUNTY_ID =? " +" AND T2.COUNTY_ID =? " +" AND T2.CUST_ID =? " + ( StringHelper.isEmpty(docSn)? " and t.status = '" + StatusConstants.ACTIVE + "' " : "" ) +" and t.done_code =cdcd.done_code and t2.done_code=cdcd.done_code " // +" AND T.DONE_CODE = T2.DONE_CODE and t.optr_id = ? ) T, " +" AND T.DONE_CODE = T2.DONE_CODE ) T, "//不限制操作员 +" (SELECT T2.TEMPLATE_FILENAME, T2.BUSI_CODE, t2.height, t2.width " +" FROM T_TEMPLATE_COUNTY T, T_BUSI_DOC_TEMPLATEFILE_DETAIL T2 " +" WHERE T.TEMPLATE_TYPE = 'DOC' " +" AND T.COUNTY_ID =? " +" AND T.TEMPLATE_ID = T2.TEMLATE_ID " +" AND T2.DOC_TYPE = 'DOC') T1,busi.t_busi_doc_templatefile_span si " +" WHERE T.BUSI_CODE = T1.BUSI_CODE and si.busi_code = t.busi_code "; //重打 if(!StringHelper.isEmpty(docSn)){ sql +=" and exists ( "; sql+=" select 1 from busi.c_doc_item cdi where cdi.doc_sn = '"+docSn+"' and cdi.docitem_sn=t.doneCode ) "; }else{ //第一次打印 ,获取未打印信息 sql +=" and t.last_print is null and T.DONE_DATE BETWEEN TRUNC(SYSDATE) AND TRUNC(SYSDATE+1)"; } sql+=" group by t.busi_code, T.doneCode, si.busi_code_span, si.GROUP_COLUMN,t.user_id,si.condition"; sql+=" ORDER BY doneCode"; String county_id = optr.getCounty_id(); // return createQuery(BusiDocPrintItemDto.class, sql, county_id,county_id,custId,optr.getOptr_id(),county_id).list(); return createQuery(BusiDocPrintItemDto.class, sql, county_id,county_id,custId,county_id).list(); } public String queryProtocolInfo(String done_code)throws Exception{ final String sql = "SELECT t1.protocol_desc " +" FROM EXT_C_DONE_CODE T, P_PROTOCOL T1 " +" WHERE T.DONE_CODE = ? " +" AND T.ATTRIBUTE_ID = ? " +" AND T.ATTRIBUTE_VALUE = T1.PROTOCOL_ID"; return findUnique(sql, done_code, SystemConstants.EXT_ATTRID_PROTOCOL); } /** * 查询客户未打印的业务单据 增加排序 * @param countyId * @param custId */ public List<BusiDocPrintItemDto> queryDocPrintContentByCust(String busiCode,SOptr optr ,String custId,String userId,String condition,String docSn)throws Exception{ String condSql = ""; //重打 if(!StringHelper.isEmpty(docSn)){ condSql =" and exists (select 1 from busi.c_doc_item cdi where cdi.doc_sn = '"+docSn+"' and cdi.docitem_sn=t.done_code ) "; }else{ //第一次打印 condSql =" and t.last_print is null and T.DONE_DATE BETWEEN TRUNC(SYSDATE) AND TRUNC(SYSDATE+1)"; } String optr_id = optr.getOptr_id(); String county_id = optr.getCounty_id(); if(StringHelper.isEmpty(userId)){ String sql = "SELECT t.info,t.INFO1,t.INFO2,t.INFO3,t.INFO4,t.INFO5,t.INFO6,t.INFO7,t.INFO8,t.INFO9,t.INFO10, t.busi_code, t.done_code, t1.template_filename,t1.height, t1.width,si.busi_code_idx " +" FROM (SELECT T2.INFO,t2.INFO1,t2.INFO2,t2.INFO3,t2.INFO4,t2.INFO5,t2.INFO6,t2.INFO7,t2.INFO8,t2.INFO9,t2.INFO10, T.BUSI_CODE, t2.done_code,t2.last_print, t.done_date " +" FROM C_DONE_CODE T, C_DONE_CODE_INFO T2" +" WHERE T.COUNTY_ID = ?" +" AND T2.COUNTY_ID = ?" +" AND T2.CUST_ID = ?" +" and t.busi_code=?" // +" and t.optr_id =? " +" AND T.DONE_CODE = T2.DONE_CODE) T," +" (SELECT T2.TEMPLATE_FILENAME, T2.BUSI_CODE, t2.height, t2.width" +" FROM T_TEMPLATE_COUNTY T, T_BUSI_DOC_TEMPLATEFILE_DETAIL T2" +" WHERE T.TEMPLATE_TYPE = 'DOC'" +" AND T.COUNTY_ID = ?" +" AND T.TEMPLATE_ID = T2.TEMLATE_ID" +" AND T2.DOC_TYPE = 'DOC') T1,busi.t_busi_doc_templatefile_span si " +" WHERE T.BUSI_CODE = T1.BUSI_CODE and si.busi_code = t.busi_code " ; if(!StringHelper.isEmpty(condition)){ sql+=" and "+condition+" "; } sql += condSql; sql+=" ORDER BY T.done_date "; // return createQuery(BusiDocPrintItemDto.class, sql, county_id,county_id,custId,busiCode,optr_id,county_id).list() ; return createQuery(BusiDocPrintItemDto.class, sql, county_id,county_id,custId,busiCode,county_id).list() ; }else{ String sql = " SELECT t.info,t.INFO1,t.INFO2,t.INFO3,t.INFO4,t.INFO5,t.INFO6,t.INFO7,t.INFO8,t.INFO9,t.INFO10, t.busi_code, t.done_code, t1.template_filename,t1.height, t1.width,si.busi_code_idx " +" FROM (SELECT T2.INFO,t2.INFO1,t2.INFO2,t2.INFO3,t2.INFO4,t2.INFO5,t2.INFO6,t2.INFO7,t2.INFO8,t2.INFO9,t2.INFO10, T.BUSI_CODE, t2.done_code,t2.last_print, t.done_date " +" FROM C_DONE_CODE T, C_DONE_CODE_INFO T2,c_done_code_detail cdcd" +" WHERE T.COUNTY_ID = ?" +" AND T2.COUNTY_ID = ?" +" AND T2.CUST_ID = ?" +" and cdcd.user_id=?" +" and T2.user_id=?" +" and t.busi_code=?" // +" and t.optr_id =? " +" and t.done_code=cdcd.done_code and T2.done_code=cdcd.done_code " +" AND T.DONE_CODE = T2.DONE_CODE) T," +" (SELECT T2.TEMPLATE_FILENAME, T2.BUSI_CODE, t2.height, t2.width" +" FROM T_TEMPLATE_COUNTY T, T_BUSI_DOC_TEMPLATEFILE_DETAIL T2" +" WHERE T.TEMPLATE_TYPE = 'DOC'" +" AND T.COUNTY_ID = ?" +" AND T.TEMPLATE_ID = T2.TEMLATE_ID" +" AND T2.DOC_TYPE = 'DOC') T1,busi.t_busi_doc_templatefile_span si " +" WHERE T.BUSI_CODE = T1.BUSI_CODE and si.busi_code = t.busi_code " ; if(!StringHelper.isEmpty(condition)){ sql+=" and "+condition+" "; } sql += condSql; sql+=" ORDER BY T.done_date "; return createQuery(BusiDocPrintItemDto.class, sql, county_id,county_id,custId,userId,userId,busiCode,county_id).list() ; // return createQuery(BusiDocPrintItemDto.class, sql, county_id,county_id,custId,userId,userId,busiCode,optr_id,county_id).list() ; } } public List<CDoneCode> queryCardCaDoneCode(String cardId ,String countyId)throws Exception{ List<CDoneCode> doneCodeList = null; String str = "%CARD:"+cardId; String sql = "select * from c_done_code t where t.busi_code='1722' and t.remark like '"+str+"' and t.county_id=? order by done_date asc "; doneCodeList = this.createQuery( sql,countyId).list(); return doneCodeList; } }
923386c1e69b35442aca3c0a278f9b56e63c553f
487
java
Java
px-services/src/main/java/com/mercadopago/android/px/internal/services/IdentificationService.java
nicolasfrugoni/px-android
6f9d535e5b1debe21a65309273f2c65f0179a47f
[ "MIT" ]
null
null
null
px-services/src/main/java/com/mercadopago/android/px/internal/services/IdentificationService.java
nicolasfrugoni/px-android
6f9d535e5b1debe21a65309273f2c65f0179a47f
[ "MIT" ]
null
null
null
px-services/src/main/java/com/mercadopago/android/px/internal/services/IdentificationService.java
nicolasfrugoni/px-android
6f9d535e5b1debe21a65309273f2c65f0179a47f
[ "MIT" ]
null
null
null
32.466667
98
0.796715
996,606
package com.mercadopago.android.px.internal.services; import com.mercadopago.android.px.internal.callbacks.MPCall; import com.mercadopago.android.px.model.IdentificationType; import java.util.List; import retrofit2.http.GET; import retrofit2.http.Query; public interface IdentificationService { @GET("/v1/identification_types") MPCall<List<IdentificationType>> getIdentificationTypes(@Query("public_key") String publicKey, @Query("access_token") String privateKey); }
923386d49eed6210da23096a65c785b33b4ee507
3,812
java
Java
src/charactermanaj/model/Layer.java
dsapandora/DSACharacterMaker
7db6b3b429b6fae846df8ea949fcf9d58d13704b
[ "Apache-2.0" ]
null
null
null
src/charactermanaj/model/Layer.java
dsapandora/DSACharacterMaker
7db6b3b429b6fae846df8ea949fcf9d58d13704b
[ "Apache-2.0" ]
null
null
null
src/charactermanaj/model/Layer.java
dsapandora/DSACharacterMaker
7db6b3b429b6fae846df8ea949fcf9d58d13704b
[ "Apache-2.0" ]
null
null
null
18.326923
82
0.585257
996,607
package charactermanaj.model; import java.io.File; import java.io.Serializable; /** * レイヤー情報.<br> * 重ね合わせ順による比較が可能.<br> * immutableなクラスであり、構築された後に変更されることはない.<br> * 同値であるかは、ID、順序、Dirのみで判断され、それ以外の情報は無視される.<br> * @author seraphy */ public final class Layer implements Comparable<Layer>, Serializable { private static final long serialVersionUID = -6437516046486547811L; /** * 重ね合わせ順 */ private final int order; /** * レイヤー識別名 */ private final String id; /** * レイヤー表示名 */ private final String localizedName; /** * カラーグループ */ private final ColorGroup colorGroup; /** * カラーグループ同期(初期) */ private final boolean initSync; /** * 対象ディレクトリ */ private final String dir; /** * カラーモデル名 */ private final String colorModelName; /** * レイヤー情報を構築する * * @param id * @param localizedName * @param order * @param colorGroup * @param initSync * @param dir * @param colorModelName */ public Layer(String id, String localizedName, int order, ColorGroup colorGroup, boolean initSync, String dir, String colorModelName) { if (id == null || id.length() == 0 || order < 0 || dir == null) { throw new IllegalArgumentException(); } if (localizedName == null || localizedName.length() == 0) { localizedName = id; } if (colorGroup == null) { colorGroup = ColorGroup.NA; } if (colorModelName == null || colorModelName.trim().length() == 0) { colorModelName = null; } this.id = id; this.localizedName = localizedName; this.order = order; this.colorGroup = colorGroup; this.initSync = initSync; this.dir = dir; this.colorModelName = colorModelName; } /** * 重ね合わせ順に比較する. * 同順位の場合は名前・ディレクトリから順序を決める. */ public int compareTo(Layer o) { int ret = order - o.order; if (ret == 0) { ret = id.compareTo(o.id); } if (ret == 0) { File d1 = new File(dir); File d2 = new File(o.dir); ret = d1.compareTo(d2); } return ret; } /** * レイヤー識別名を取得する * @return レイヤー識別名 */ public String getId() { return id; } /** * レイヤー表示名を取得する * @return レイヤー表示名 */ public String getLocalizedName() { return localizedName; } /** * 重ね合わせ順を取得する. * @return 重ね合わせ順 */ public int getOrder() { return order; } /** * カラーグループを取得する. * @return カラーグループ */ public ColorGroup getColorGroup() { return colorGroup; } /** * カラーグループの同期フラグ(初期)を取得する. * @return 同期フラグ */ public boolean isInitSync() { return initSync; } /** * 対象ディレクトリを取得する. * @return 対象ディレクトリ */ public String getDir() { return dir; } /** * カラーモデル名を取得する. * * @return カラーモデル名 */ public String getColorModelName() { return colorModelName; } /** * 同一レイヤーであるか判断する.<br> * ID、順序、Dirで判断する.<br> * (カラーグループ、カラーグループ同期、表示名、は無視される.)<br> */ @Override public boolean equals(Object obj) { if (obj == this) { return true; } if (obj != null && obj instanceof Layer) { Layer o = (Layer) obj; File d1 = new File(dir); File d2 = new File(o.dir); return id.equals(o.id) && order == o.order && d1.equals(d2); } return false; } /** * 同一レイヤーであるか判断する.<br> * IDのみで判断する.<br> * (カラーグループ、カラーグループ同期、表示名、順序、Dirは無視される.)<br> * @param a 比較1 * @param b 比較2 * @return 等しければtrue、そうでなければfalse */ public static boolean equals(Layer a, Layer b) { if (a == b) { return true; } if (a == null || b == null) { return false; } return a.equals(b); } @Override public int hashCode() { return id.hashCode(); } @Override public String toString() { return "Layer(id=" + id + ", name=" + localizedName + ", order=" + order + ")"; } }
923386f8105bf98b241bfc2758e52d22e410f7b7
944
java
Java
src/one/nio/mem/Allocator.java
alexeykotelevskiy/one-nio
902602346eca47a0c79987b038e116cb29169655
[ "Apache-2.0" ]
525
2015-01-23T19:41:15.000Z
2022-03-29T02:01:09.000Z
src/one/nio/mem/Allocator.java
alexeykotelevskiy/one-nio
902602346eca47a0c79987b038e116cb29169655
[ "Apache-2.0" ]
50
2015-03-02T11:02:23.000Z
2022-02-23T00:07:45.000Z
src/one/nio/mem/Allocator.java
alexeykotelevskiy/one-nio
902602346eca47a0c79987b038e116cb29169655
[ "Apache-2.0" ]
106
2015-04-14T02:48:19.000Z
2022-02-21T16:37:08.000Z
26.222222
92
0.704449
996,608
/* * Copyright 2015-2016 Odnoklassniki Ltd, Mail.Ru Group * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package one.nio.mem; /** * Memory allocator * * @author Vadim Tsesko */ public interface Allocator { long malloc(int size); long calloc(int size); void free(long address); /** * Verify the layout of the heap. Expensive operation, used only for debugging purposes. */ void verify(); }
9233871e2d9b68e5ca59dd06eeb5cb01fee7d04c
641
java
Java
sdk/model/QuotaModeType.java
lllucius/fauxvirt
59bfebd602cc49f8c5f6e25875a7acc9e2ba3c89
[ "Apache-2.0" ]
null
null
null
sdk/model/QuotaModeType.java
lllucius/fauxvirt
59bfebd602cc49f8c5f6e25875a7acc9e2ba3c89
[ "Apache-2.0" ]
null
null
null
sdk/model/QuotaModeType.java
lllucius/fauxvirt
59bfebd602cc49f8c5f6e25875a7acc9e2ba3c89
[ "Apache-2.0" ]
null
null
null
25.64
83
0.622465
996,609
package org.ovirt.engine.api.model; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public enum QuotaModeType { ENABLED, DISABLED, AUDIT; private static final Logger log = LoggerFactory.getLogger(QuotaModeType.class); public String value() { return name().toLowerCase(); } public static QuotaModeType fromValue(String value) { try { return valueOf(value.toUpperCase()); } catch (IllegalArgumentException e) { log.error("The value '{}' isn't a valid quota mode.", value); log.error("Exception", e); return null; } } }
923387394f631862a8e3319d6e6873f814c90808
5,323
java
Java
aws-logs-metricfilter/src/main/java/software/amazon/logs/metricfilter/UpdateHandler.java
arashkamzn/aws-cloudformation-resource-providers-logs
6db90de4559f6a4ad4a88fa461fba82ff1ac0812
[ "Apache-2.0" ]
null
null
null
aws-logs-metricfilter/src/main/java/software/amazon/logs/metricfilter/UpdateHandler.java
arashkamzn/aws-cloudformation-resource-providers-logs
6db90de4559f6a4ad4a88fa461fba82ff1ac0812
[ "Apache-2.0" ]
null
null
null
aws-logs-metricfilter/src/main/java/software/amazon/logs/metricfilter/UpdateHandler.java
arashkamzn/aws-cloudformation-resource-providers-logs
6db90de4559f6a4ad4a88fa461fba82ff1ac0812
[ "Apache-2.0" ]
null
null
null
52.186275
130
0.716138
996,610
package software.amazon.logs.metricfilter; import software.amazon.awssdk.services.cloudwatchlogs.CloudWatchLogsClient; import software.amazon.awssdk.services.cloudwatchlogs.model.InvalidParameterException; import software.amazon.awssdk.services.cloudwatchlogs.model.LimitExceededException; import software.amazon.awssdk.services.cloudwatchlogs.model.OperationAbortedException; import software.amazon.awssdk.services.cloudwatchlogs.model.PutMetricFilterRequest; import software.amazon.awssdk.services.cloudwatchlogs.model.PutMetricFilterResponse; import software.amazon.awssdk.services.cloudwatchlogs.model.ResourceNotFoundException; import software.amazon.awssdk.services.cloudwatchlogs.model.ServiceUnavailableException; import software.amazon.cloudformation.exceptions.CfnAlreadyExistsException; import software.amazon.cloudformation.exceptions.CfnInvalidRequestException; import software.amazon.cloudformation.exceptions.CfnNotFoundException; import software.amazon.cloudformation.exceptions.CfnResourceConflictException; import software.amazon.cloudformation.exceptions.CfnServiceInternalErrorException; import software.amazon.cloudformation.exceptions.CfnServiceLimitExceededException; import software.amazon.cloudformation.proxy.AmazonWebServicesClientProxy; import software.amazon.cloudformation.proxy.HandlerErrorCode; import software.amazon.cloudformation.proxy.Logger; import software.amazon.cloudformation.proxy.OperationStatus; import software.amazon.cloudformation.proxy.ProgressEvent; import software.amazon.cloudformation.proxy.ProxyClient; import software.amazon.cloudformation.proxy.ResourceHandlerRequest; public class UpdateHandler extends BaseHandlerStd { private Logger logger; protected ProgressEvent<ResourceModel, CallbackContext> handleRequest( final AmazonWebServicesClientProxy proxy, final ResourceHandlerRequest<ResourceModel> request, final CallbackContext callbackContext, final ProxyClient<CloudWatchLogsClient> proxyClient, final Logger logger) { this.logger = logger; final ResourceModel model = request.getDesiredResourceState(); final ResourceModel previousModel = request.getPreviousResourceState(); this.logger.log(String.format("Trying to update model %s", model.getPrimaryIdentifier())); return ProgressEvent.progress(model, callbackContext) .then(progress -> { if (!isUpdatable(model, previousModel)) { return ProgressEvent.<ResourceModel, CallbackContext>builder() .errorCode(HandlerErrorCode.NotUpdatable) .status(OperationStatus.FAILED) .build(); } return progress; }) .then(progress -> preCreateCheck(proxy, callbackContext, proxyClient, model) .done((response) -> { if (response.metricFilters().isEmpty()) { return ProgressEvent.defaultFailureHandler(new CfnNotFoundException(null), HandlerErrorCode.NotFound); } return ProgressEvent.progress(model, callbackContext); }) ) .then(progress -> proxy.initiate("AWS-Logs-MetricFilter::Update", proxyClient, model, callbackContext) .translateToServiceRequest(Translator::translateToUpdateRequest) .makeServiceCall(this::updateResource) .progress()) .then(progress -> new ReadHandler().handleRequest(proxy, request, callbackContext, proxyClient, logger)); } private boolean isUpdatable(final ResourceModel model, final ResourceModel previousModel) { // An update request MUST return a NotUpdatable error if the user attempts to change a property // that is defined as create-only in the resource provider schema. if (previousModel != null) { return previousModel.getFilterName().equals(model.getFilterName()) && previousModel.getLogGroupName().equals(model.getLogGroupName()); } return true; } private PutMetricFilterResponse updateResource( final PutMetricFilterRequest awsRequest, final ProxyClient<CloudWatchLogsClient> proxyClient) { PutMetricFilterResponse awsResponse; try { awsResponse = proxyClient.injectCredentialsAndInvokeV2(awsRequest, proxyClient.client()::putMetricFilter); } catch (final ResourceNotFoundException e) { logger.log("Resource not found. " + e.getMessage()); throw new CfnNotFoundException(e); } catch (final InvalidParameterException e) { throw new CfnInvalidRequestException(ResourceModel.TYPE_NAME, e); } catch (final LimitExceededException e) { throw new CfnServiceLimitExceededException(e); } catch (final ServiceUnavailableException e) { throw new CfnServiceInternalErrorException(e); } catch (final OperationAbortedException e) { throw new CfnResourceConflictException(e); } logger.log(String.format("%s has successfully been updated.", ResourceModel.TYPE_NAME)); return awsResponse; } }
9233876385a57dd782725f78fc69a7375e142e39
3,096
java
Java
module/nvt-consensus/nvt-consensus-pocbft/src/main/java/nerve/network/pocbft/utils/validator/WithdrawValidator.java
arkDelphi/nerve
b0950a2f882e7858db7f75beb4cf12f130f098a3
[ "MIT" ]
1
2020-05-06T11:52:36.000Z
2020-05-06T11:52:36.000Z
module/nvt-consensus/nvt-consensus-pocbft/src/main/java/nerve/network/pocbft/utils/validator/WithdrawValidator.java
m37x/nerve
b0950a2f882e7858db7f75beb4cf12f130f098a3
[ "MIT" ]
null
null
null
module/nvt-consensus/nvt-consensus-pocbft/src/main/java/nerve/network/pocbft/utils/validator/WithdrawValidator.java
m37x/nerve
b0950a2f882e7858db7f75beb4cf12f130f098a3
[ "MIT" ]
1
2020-04-15T06:33:39.000Z
2020-04-15T06:33:39.000Z
39.692308
166
0.695413
996,611
package nerve.network.pocbft.utils.validator; import io.nuls.base.data.CoinData; import io.nuls.base.data.Transaction; import io.nuls.core.basic.Result; import io.nuls.core.core.annotation.Autowired; import io.nuls.core.core.annotation.Component; import io.nuls.core.exception.NulsException; import nerve.network.pocbft.constant.ConsensusErrorCode; import nerve.network.pocbft.model.bo.Chain; import nerve.network.pocbft.model.bo.tx.txdata.CancelDeposit; import nerve.network.pocbft.model.po.DepositPo; import nerve.network.pocbft.storage.DepositStorageService; import nerve.network.pocbft.utils.enumeration.DepositTimeType; import nerve.network.pocbft.utils.enumeration.DepositType; import nerve.network.pocbft.utils.validator.base.BaseValidator; import java.io.IOException; import java.util.Arrays; import static nerve.network.pocbft.utils.ConsensusNetUtil.getSuccess; /** * 减少保证金交易验证器 * @author tag * */ @Component public class WithdrawValidator extends BaseValidator { @Autowired private DepositStorageService depositStorageService; @Override public Result validate(Chain chain, Transaction tx) throws NulsException, IOException { CancelDeposit txData = new CancelDeposit(); txData.parse(tx.getTxData(), 0); DepositPo depositPo = depositStorageService.get(txData.getJoinTxHash(), chain.getConfig().getChainId()); if (depositPo == null || depositPo.getDelHeight() > 0) { chain.getLogger().error("Withdraw -- Deposit transaction does not exist"); return Result.getFailed(ConsensusErrorCode.DATA_NOT_EXIST); } //交易发起者是否为委托者 if(!Arrays.equals(depositPo.getAddress(), txData.getAddress())){ chain.getLogger().error("Withdraw -- Account is not the agent Creator"); return Result.getFailed(ConsensusErrorCode.ACCOUNT_IS_NOT_CREATOR); } //如果为定期委托则验证委托是否到期 if(depositPo.getDepositType() == DepositType.REGULAR.getCode()){ DepositTimeType depositTimeType = DepositTimeType.getValue(depositPo.getTimeType()); if(depositTimeType == null){ chain.getLogger().error("Recurring delegation type does not exist"); return Result.getFailed(ConsensusErrorCode.REGULAR_DEPOSIT_TIME_TYPE_NOT_EXIST); } long periodicTime = depositPo.getTime() + depositTimeType.getTime(); if(tx.getTime() < periodicTime){ chain.getLogger().error("Term commission not due"); return Result.getFailed(ConsensusErrorCode.DEPOSIT_NOT_DUE); } } //coinData验证 CoinData coinData = new CoinData(); coinData.parse(tx.getCoinData(),0); Result rs = reduceDepositCoinDataValid(chain, depositPo.getDeposit(), coinData, depositPo.getAddress(), 0,depositPo.getAssetChainId(),depositPo.getAssetId()); if(rs.isFailed()){ return rs; } //验证手续费 rs = validFee(chain, coinData, tx); if(rs.isFailed()){ return rs; } return getSuccess(); } }
92338814a0ec33a16553bf44e4df9b09bc296fd8
1,277
java
Java
XmlBase/src/main/java/com/bluebrim/xml/shared/CoDefaultXmlBuilder.java
goranstack/bluebrim
eb6edbeada72ed7fd1294391396432cb25575fe0
[ "Apache-2.0" ]
null
null
null
XmlBase/src/main/java/com/bluebrim/xml/shared/CoDefaultXmlBuilder.java
goranstack/bluebrim
eb6edbeada72ed7fd1294391396432cb25575fe0
[ "Apache-2.0" ]
null
null
null
XmlBase/src/main/java/com/bluebrim/xml/shared/CoDefaultXmlBuilder.java
goranstack/bluebrim
eb6edbeada72ed7fd1294391396432cb25575fe0
[ "Apache-2.0" ]
null
null
null
29.022727
96
0.759593
996,612
package com.bluebrim.xml.shared; import org.apache.crimson.tree.*; /** * This XML builder serves as a default builder, which does not alter the * behavior of attribute, element and data export to the XML representation. * This class has been added to keep down the number of builder classes that * are equivalent except for the tag it returns when the getTag method is called. * A CoDefaultXmlBuilder must be initialized with a tag after it has been created * Creation date: (1999-10-01 11:54:05) * @author: Mikael Printz */ public class CoDefaultXmlBuilder extends CoXmlBuilder implements CoDefaultXmlBuilderIF { private String m_tag = "none"; /** * CoDefaultXmlBuilder constructor comment. */ public CoDefaultXmlBuilder() { super(); } /** * CoDefaultXmlBuilder constructor comment. * @param xmlDoc XmlDocument */ public CoDefaultXmlBuilder(XmlDocument xmlDoc) { super(xmlDoc); } /** * CoDefaultXmlBuilder constructor comment. * @param xmlDoc com.sun.xml.tree.XmlDocument * @param builder com.bluebrim.xml.shared.CoXmlBuilderIF */ public CoDefaultXmlBuilder(XmlDocument xmlDoc, com.bluebrim.xml.shared.CoXmlBuilderIF builder) { super(xmlDoc, builder); } protected String getTag() { return m_tag; } public void setTag(String tag) { m_tag = tag; } }
923389046f82a4a07bb2bab6c2468c1fc3148154
647
java
Java
java/src/main/java/leetcode/leet7.java
orcakill/leetcode
d1aa266f66a5a42ec629022eac0b9a541f0a3b93
[ "Apache-2.0" ]
1
2020-10-04T11:12:36.000Z
2020-10-04T11:12:36.000Z
java/src/main/java/leetcode/leet7.java
orcakill/leetcode
d1aa266f66a5a42ec629022eac0b9a541f0a3b93
[ "Apache-2.0" ]
19
2021-01-27T07:31:11.000Z
2022-03-31T20:02:53.000Z
java/src/main/java/leetcode/leet7.java
orcakill/leetcode
d1aa266f66a5a42ec629022eac0b9a541f0a3b93
[ "Apache-2.0" ]
null
null
null
20.870968
64
0.418856
996,613
package leetcode; public class leet7 { public static void main(String[] args) { int s1 = 0; System.out.println(reverse(s1)); } public static int reverse(int x) { int res = 0; while(x!=0) { //每次取末尾数字 int tmp = x%10; //判断是否 大于 最大32位整数 if (res>214748364 || (res==214748364 && tmp>7)) { return 0; } //判断是否 小于 最小32位整数 if (res<-214748364 || (res==-214748364 && tmp<-8)) { return 0; } res = res*10 + tmp; x /= 10; } return res; } }
92338a0e97b304452eb74e462d2812ad2c60918e
709
java
Java
Jeliot/src/jeliot/theater/Trace.java
moegyver/mJeliot
191a1ce138ae3f39cf60d5c69cae89727e898c5c
[ "MIT" ]
null
null
null
Jeliot/src/jeliot/theater/Trace.java
moegyver/mJeliot
191a1ce138ae3f39cf60d5c69cae89727e898c5c
[ "MIT" ]
null
null
null
Jeliot/src/jeliot/theater/Trace.java
moegyver/mJeliot
191a1ce138ae3f39cf60d5c69cae89727e898c5c
[ "MIT" ]
null
null
null
18.657895
57
0.592384
996,614
package jeliot.theater; import java.awt.Graphics; /** * The trace that an actor leaves when moving. * Currently this is just a stub implementation. * What could be done is to show the path that * Actor was moving along. * * @author Pekka Uronen * @author Niko Myller * * @see jeliot.theater.Actor * @see jeliot.theater.Actor#fly(Point,int) */ public class Trace { // DOC: Document! /** * Paint the path that the trace contains. * * @param g */ public void paint(Graphics g) { } /** * Store the points along which the actor is moving. * * @param x * @param y */ public void putTrace(int x, int y) { } }
92338a408ad47f782b59419df689f8376b6c90b2
10,232
java
Java
src/jpl/mipl/mdms/FileService/komodo/ui/savannah/tools/ChangePasswordPanel.java
nasa/FEI
f75c7c56222c129ac078bdf77ef776bb4217ec56
[ "Apache-2.0" ]
2
2020-07-20T05:00:47.000Z
2020-09-17T07:57:30.000Z
src/jpl/mipl/mdms/FileService/komodo/ui/savannah/tools/ChangePasswordPanel.java
nasa/FEI
f75c7c56222c129ac078bdf77ef776bb4217ec56
[ "Apache-2.0" ]
null
null
null
src/jpl/mipl/mdms/FileService/komodo/ui/savannah/tools/ChangePasswordPanel.java
nasa/FEI
f75c7c56222c129ac078bdf77ef776bb4217ec56
[ "Apache-2.0" ]
2
2019-11-04T02:29:56.000Z
2019-11-13T17:00:38.000Z
34.106667
90
0.609167
996,615
package jpl.mipl.mdms.FileService.komodo.ui.savannah.tools; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.util.List; import java.util.Vector; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JPanel; public class ChangePasswordPanel extends JPanel { private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JPasswordField new2PassField; private javax.swing.JPasswordField newPassField; private javax.swing.JPasswordField oldPassField; private javax.swing.JComboBox sgComboBox; private javax.swing.JTextField usernameField; protected List<String> servergroups; protected String username; protected String oldPassword; protected String newPassword; protected String servergroup; public ChangePasswordPanel(String[] groups, String currentGroup, String username, String password) { super(); this.servergroups = new Vector<String>(); for (String groupname : groups) this.servergroups.add(groupname); this.servergroup = currentGroup; this.username = username; this.oldPassword = password; buildUI(); } protected void buildUI() { initComponents(); initValues(); initListeners(); } private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); sgComboBox = new javax.swing.JComboBox(); usernameField = new javax.swing.JTextField(); oldPassField = new javax.swing.JPasswordField(); newPassField = new javax.swing.JPasswordField(); new2PassField = new javax.swing.JPasswordField(); setLayout(new java.awt.GridBagLayout()); jLabel1.setText("Server group:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 0); add(jLabel1, gridBagConstraints); jLabel2.setText("User name:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 1; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 0); add(jLabel2, gridBagConstraints); jLabel3.setText("Old password:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 2; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 0); add(jLabel3, gridBagConstraints); jLabel4.setText("New password:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 3; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 0); add(jLabel4, gridBagConstraints); jLabel5.setText("Repeat password:"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 4; gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST; gridBagConstraints.insets = new java.awt.Insets(0, 10, 0, 0); add(jLabel5, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.weightx = 0.8; gridBagConstraints.insets = new java.awt.Insets(2, 10, 0, 10); add(sgComboBox, gridBagConstraints); usernameField.setText("<username>"); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 1; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(2, 10, 0, 10); add(usernameField, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 2; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(2, 10, 0, 10); add(oldPassField, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 3; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(2, 10, 0, 10); add(newPassField, gridBagConstraints); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 1; gridBagConstraints.gridy = 4; gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL; gridBagConstraints.insets = new java.awt.Insets(2, 10, 2, 10); add(new2PassField, gridBagConstraints); } protected void initListeners() { this.sgComboBox.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent ie) { servergroup = (String) sgComboBox.getSelectedItem(); } }); //hack to convert action events into focus events for the field this.usernameField.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { usernameField.transferFocus(); } }); this.usernameField.addFocusListener(new FocusAdapter() { public void focusLost(FocusEvent fe) { String txt = usernameField.getText(); username = txt; } }); //hack to convert action events into focus events for the field this.oldPassField.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { oldPassField.transferFocus(); } }); this.oldPassField.addFocusListener(new FocusAdapter() { public void focusLost(FocusEvent fe) { char[] txt = oldPassField.getPassword(); oldPassword = new String(txt); } }); //hack to convert action events into focus events for the field this.newPassField.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { newPassField.transferFocus(); } }); this.newPassField.addFocusListener(new FocusAdapter() { public void focusLost(FocusEvent fe) { char[] txt = newPassField.getPassword(); newPassword = new String(txt); } }); //hack to convert action events into focus events for the field this.new2PassField.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { new2PassField.transferFocus(); } }); this.new2PassField.addFocusListener(new FocusAdapter() { public void focusLost(FocusEvent fe) { char[] txt = new2PassField.getPassword(); String copy = new String(txt); if (copy != null && !copy.equals(newPassword)) { JOptionPane.showMessageDialog(ChangePasswordPanel.this, "New password fields do not match", "Password Error", JOptionPane.ERROR_MESSAGE); newPassField.requestFocus(); } } }); } protected void initValues() { for (String item : this.servergroups) this.sgComboBox.addItem(item); if (this.servergroup == null) { this.servergroup = (String) this.sgComboBox.getItemAt(0); } else { this.sgComboBox.setSelectedItem(this.servergroup); } if (this.username == null) username = System.getProperty("user.name"); if (this.username != null) this.usernameField.setText(this.username); if (this.oldPassword != null) this.oldPassField.setText(this.oldPassword); } public String getUsername() { return this.username; } public String getOldPassword() { return this.oldPassword; } public String getNewPassword() { return this.newPassword; } public String getGroup() { return this.servergroup; } public static void main(String[] args) { String[] groups = { "my group", "group grope", "music group"}; String username = "mr_peterman"; ChangePasswordPanel panel = new ChangePasswordPanel(groups, null, username, null); JFrame frame = new JFrame("Test"); frame.getContentPane().add(panel); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setVisible(true); } }
92338ad1217cb20db3e1cb30bf84b47184f4aa57
1,639
java
Java
core/src/main/java/io/jshift/odo/api/OdoConfiguration.java
dev-gaur/odo-java
b9c394e9952034a589f0ba3720788a9480a64cbe
[ "Apache-2.0" ]
4
2019-03-26T17:42:29.000Z
2019-07-24T08:29:04.000Z
core/src/main/java/io/jshift/odo/api/OdoConfiguration.java
dev-gaur/odo-java
b9c394e9952034a589f0ba3720788a9480a64cbe
[ "Apache-2.0" ]
16
2019-03-26T12:37:30.000Z
2019-08-07T15:08:26.000Z
core/src/main/java/io/jshift/odo/api/OdoConfiguration.java
dev-gaur/odo-java
b9c394e9952034a589f0ba3720788a9480a64cbe
[ "Apache-2.0" ]
7
2019-03-26T08:51:45.000Z
2019-08-13T14:37:52.000Z
23.414286
87
0.690055
996,616
package io.jshift.odo.api; import java.nio.file.Path; public class OdoConfiguration { private String version; private Path localOdo; private Path installationDir; private boolean printStandardStreamToConsole = true; private boolean printErrorStreamToConsole = true; public OdoConfiguration() { } public boolean isInstallationDirSet() { return this.installationDir != null; } public boolean isLocalOdoSet() { return this.localOdo != null; } public boolean isVersionSet() { return this.version != null && !this.version.isEmpty(); } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public void setLocalOdo(Path localOdo) { this.localOdo = localOdo; } public Path getLocalOdo() { return localOdo; } public Path getInstallationDir() { return installationDir; } public void setInstallationDir(Path installationDir) { this.installationDir = installationDir; } public boolean isPrintStandardStreamToConsole() { return printStandardStreamToConsole; } public void setPrintStandardStreamToConsole(boolean printStandardStreamToConsole) { this.printStandardStreamToConsole = printStandardStreamToConsole; } public boolean isPrintErrorStreamToConsole() { return printErrorStreamToConsole; } public void setPrintErrorStreamToConsole(boolean printErrorStreamToConsole) { this.printErrorStreamToConsole = printErrorStreamToConsole; } }
92338baec3d7995cc14dfe7c12bc0fb8061fdcb2
577
java
Java
src/main/java/com/pattern/proxy/dynamicproxy/jdkproxy/Test.java
healker/BasisDemo
fe595caf2fcc1d727efa5e2c7ab9b4c7d8b30333
[ "Apache-2.0" ]
null
null
null
src/main/java/com/pattern/proxy/dynamicproxy/jdkproxy/Test.java
healker/BasisDemo
fe595caf2fcc1d727efa5e2c7ab9b4c7d8b30333
[ "Apache-2.0" ]
null
null
null
src/main/java/com/pattern/proxy/dynamicproxy/jdkproxy/Test.java
healker/BasisDemo
fe595caf2fcc1d727efa5e2c7ab9b4c7d8b30333
[ "Apache-2.0" ]
null
null
null
23.08
71
0.651646
996,617
package com.pattern.proxy.dynamicproxy.jdkproxy; import com.pattern.proxy.dynamicproxy.jdkproxy.ZhangSan; /** * Created by Tom. */ public class Test { public static void main(String[] args) { JdkPaotui jdkPaotui = new JdkPaotui(); IOrde zhangsan = jdkPaotui.getInstance(new ZhangSan()); zhangsan.orde(); IOrde zhaoliu = jdkPaotui.getInstance(new ZhaoLiu()); zhaoliu.orde(); JdkProxy jdkProxy = new JdkProxy(); IOrde zhangsan1 = (IOrde) jdkProxy.getInstance(new ZhangSan()); zhangsan1.orde(); } }
92338c207bf7d0ac780dd51b6f15132269e90c36
1,253
java
Java
api-gateway/src/main/java/com/fansolomon/apiGateway/filter/AccessFilter.java
FanSolomon/Booking-Center
c7d8dddecc9e96d231d424b8c56fef7dc117012c
[ "MIT" ]
null
null
null
api-gateway/src/main/java/com/fansolomon/apiGateway/filter/AccessFilter.java
FanSolomon/Booking-Center
c7d8dddecc9e96d231d424b8c56fef7dc117012c
[ "MIT" ]
null
null
null
api-gateway/src/main/java/com/fansolomon/apiGateway/filter/AccessFilter.java
FanSolomon/Booking-Center
c7d8dddecc9e96d231d424b8c56fef7dc117012c
[ "MIT" ]
null
null
null
24.096154
99
0.64565
996,618
package com.fansolomon.apiGateway.filter; import com.netflix.zuul.ZuulFilter; import com.netflix.zuul.context.RequestContext; import com.netflix.zuul.exception.ZuulException; import lombok.extern.slf4j.Slf4j; import javax.servlet.http.HttpServletRequest; /** * Zuul过滤器,对请求进行过滤 * * @author zhangyuting * @since 2020-4-24 09:56:24 */ @Slf4j public class AccessFilter extends ZuulFilter { @Override public String filterType() { return "pre"; } @Override public int filterOrder() { return 0; } @Override public boolean shouldFilter() { return true; } @Override public Object run() throws ZuulException { RequestContext ctx = RequestContext.getCurrentContext(); HttpServletRequest request = ctx.getRequest(); log.info("send {} request to {}", request.getMethod(), request.getRequestURL().toString()); Object accessToken = request.getParameter("accessToken"); if (accessToken == null) { log.warn("access token is empty! :("); ctx.setSendZuulResponse(false); ctx.setResponseStatusCode(401); return null; } log.info("access token received! :)"); return null; } }
92338e32b2eef1fccbeeffd13ceb114b54bb1afa
943
java
Java
app/src/main/java/io/digibyte/presenter/activities/intro/RecoverActivity.java
DigiByte-Core/digibytewallet-android
b7856f7eac08003107d323f52afebe1580d5d194
[ "MIT" ]
10
2019-09-08T01:41:36.000Z
2022-01-05T21:36:59.000Z
app/src/main/java/io/digibyte/presenter/activities/intro/RecoverActivity.java
DigiByte-Core/digibytewallet-android
b7856f7eac08003107d323f52afebe1580d5d194
[ "MIT" ]
15
2019-01-23T14:59:22.000Z
2022-03-05T19:23:08.000Z
app/src/main/java/io/digibyte/presenter/activities/intro/RecoverActivity.java
DigiByte-Core/digibytewallet-android
b7856f7eac08003107d323f52afebe1580d5d194
[ "MIT" ]
20
2018-10-22T16:30:12.000Z
2022-03-14T19:36:42.000Z
37.72
116
0.791092
996,619
package io.digibyte.presenter.activities.intro; import androidx.databinding.DataBindingUtil; import android.os.Bundle; import io.digibyte.R; import io.digibyte.databinding.ActivityIntroRecoverBinding; import io.digibyte.presenter.activities.InputWordsActivity; import io.digibyte.presenter.activities.callbacks.ActivityRecoverCallback; import io.digibyte.presenter.activities.util.BRActivity; public class RecoverActivity extends BRActivity { ActivityRecoverCallback callback = () -> InputWordsActivity.open(RecoverActivity.this, InputWordsActivity.Type.RESTORE); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ActivityIntroRecoverBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_intro_recover); binding.setCallback(callback); setupToolbar(); setToolbarTitle(R.string.RecoverWallet_header); } }
92338ece681aa787d2f59a8c9a814a60c07d7af7
297
java
Java
exercises/EvenDigitSum/src/EvenDigitSum.java
bart-le/java-basics
ae4d600c75502c98d1893970bee2407629d887d0
[ "MIT" ]
null
null
null
exercises/EvenDigitSum/src/EvenDigitSum.java
bart-le/java-basics
ae4d600c75502c98d1893970bee2407629d887d0
[ "MIT" ]
null
null
null
exercises/EvenDigitSum/src/EvenDigitSum.java
bart-le/java-basics
ae4d600c75502c98d1893970bee2407629d887d0
[ "MIT" ]
null
null
null
18.5625
48
0.569024
996,620
public class EvenDigitSum { public static int getEvenDigitSum(int number) { if (number >= 0) { int sum = 0, lastDigit; while (number != 0) { lastDigit = number % 10; if (lastDigit % 2 == 0) sum += lastDigit; number /= 10; } return sum; } else { return -1; } } }
92338fa8887921a18e5ee7bd6e60c50069ef87d3
3,214
java
Java
ds3-autogen-parser/src/main/java/com/spectralogic/ds3autogen/models/xml/rawspec/Element.java
RachelTucker/ds3_autogen
392ca0b3123cf16d1a7e8ea6673649f381334c68
[ "Apache-2.0" ]
5
2016-01-22T21:22:36.000Z
2021-09-19T19:47:58.000Z
ds3-autogen-parser/src/main/java/com/spectralogic/ds3autogen/models/xml/rawspec/Element.java
RachelTucker/ds3_autogen
392ca0b3123cf16d1a7e8ea6673649f381334c68
[ "Apache-2.0" ]
76
2015-11-13T20:40:08.000Z
2019-08-09T20:10:51.000Z
ds3-autogen-parser/src/main/java/com/spectralogic/ds3autogen/models/xml/rawspec/Element.java
RachelTucker/ds3_autogen
392ca0b3123cf16d1a7e8ea6673649f381334c68
[ "Apache-2.0" ]
12
2015-11-03T22:03:14.000Z
2016-08-16T15:30:10.000Z
32.464646
98
0.662726
996,621
/* * ****************************************************************************** * Copyright 2014-2017 Spectra Logic Corporation. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * **************************************************************************** */ package com.spectralogic.ds3autogen.models.xml.rawspec; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; import com.google.common.collect.ImmutableList; import com.spectralogic.ds3autogen.api.models.apispec.Ds3Annotation; import com.spectralogic.ds3autogen.api.models.apispec.Ds3Element; import java.util.List; import static com.spectralogic.ds3autogen.utils.NullableVariableUtil.isNullableElement; public class Element { @JacksonXmlProperty(isAttribute = true, localName = "Name") private String name; @JacksonXmlProperty(isAttribute = true, localName = "Type") private String type; @JacksonXmlProperty(isAttribute = true, localName = "ComponentType") private String componentType; @JsonProperty("Annotations") @JacksonXmlElementWrapper(useWrapping = true) private List<Annotation> annotations; public String getName() { return name; } public void setName(final String name) { this.name = name; } public String getType() { return type; } public void setType(final String type) { this.type = type; } public List<Annotation> getAnnotations() { return annotations; } public void setAnnotations(final List<Annotation> annotations) { this.annotations = annotations; } public String getComponentType() { return componentType; } public void setComponentType(final String componentType) { this.componentType = componentType; } public Ds3Element toDs3Element() { final ImmutableList<Ds3Annotation> ds3Annotations = toDs3Annotations(); final Ds3Element ds3Element = new Ds3Element( name, type, componentType, ds3Annotations, isNullableElement(type, ds3Annotations)); return ds3Element; } private ImmutableList<Ds3Annotation> toDs3Annotations() { if (annotations == null) { return null; } final ImmutableList.Builder<Ds3Annotation> ds3AnnotationBuilder = ImmutableList.builder(); for (final Annotation annotation : annotations) { ds3AnnotationBuilder.add(annotation.toDs3Annotation()); } return ds3AnnotationBuilder.build(); } }
92338ff90653a07469c3fa2847c76f83a07a0155
591
java
Java
src/com/cien/server/routes/DownloadImageRoute.java
CientistaVuador/ChatTest
9b3b5761c060054ffc48bafab0dc87eb082815a9
[ "Unlicense" ]
null
null
null
src/com/cien/server/routes/DownloadImageRoute.java
CientistaVuador/ChatTest
9b3b5761c060054ffc48bafab0dc87eb082815a9
[ "Unlicense" ]
null
null
null
src/com/cien/server/routes/DownloadImageRoute.java
CientistaVuador/ChatTest
9b3b5761c060054ffc48bafab0dc87eb082815a9
[ "Unlicense" ]
null
null
null
21.107143
80
0.629442
996,622
/* * 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.cien.server.routes; import com.cien.server.Route; import com.cien.server.subroutes.DownloadImage; /** * * @author Cien */ public class DownloadImageRoute extends Route { public DownloadImageRoute() { configure(); } private void configure() { setSubRoute("downloadImage", new DownloadImage()); } }
92339089f4589423b295df86016e167fe6bab746
15,916
java
Java
src/main/java/com/bmw/news/common/utils/DateUtil.java
zhouyitong/bmwnews
923ac4bdff601da3dad74776e611bf0aee3f7812
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/main/java/com/bmw/news/common/utils/DateUtil.java
zhouyitong/bmwnews
923ac4bdff601da3dad74776e611bf0aee3f7812
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/main/java/com/bmw/news/common/utils/DateUtil.java
zhouyitong/bmwnews
923ac4bdff601da3dad74776e611bf0aee3f7812
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
22.044321
126
0.655881
996,623
package com.bmw.news.common.utils; import java.sql.Timestamp; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; /** * 时间相关函数 * */ public final class DateUtil { public static final String YYYYMMDD = "yyyy-MM-dd"; public static final String YYYYMM = "yyyy-MM"; public static final String HHMMSS = "HH:mm:ss"; public static final String YYYYMMDDHHMMSS = YYYYMMDD + " " + HHMMSS; /** * 1分钟有多少秒 */ public static final Long SECONDS_IN_MINUTE = 60L; /** * 1小时有多少分钟 */ public static final Long MINUTES_IN_HOUR = 60L; /** * 1天有多少小时 */ public static final Long HOURS_IN_DAY = 24L; /** * 1周有多少天 */ public static final Long DAYS_IN_WEEK = 7L; /** * 1年有多少天 */ public static final Long DAYS_IN_YEAR = 365L; /** * 1月有多少天 */ public static final Long DAYS_IN_MONTH = 30L; /** * 1年有多少秒 */ public static final Long SECONDS_IN_YEAR = SECONDS_IN_MINUTE * MINUTES_IN_HOUR * HOURS_IN_DAY * DAYS_IN_YEAR; /** * 1个月有多少秒 */ public static final Long SECONDS_IN_MONTH = SECONDS_IN_MINUTE * MINUTES_IN_HOUR * HOURS_IN_DAY * DAYS_IN_MONTH; /** * 1周有多少秒 */ public static final Long SECONDS_IN_WEEK = SECONDS_IN_MINUTE * MINUTES_IN_HOUR * HOURS_IN_DAY * DAYS_IN_WEEK; /** * 1天有多少秒 */ public static final int SECONDS_IN_DAY = SECONDS_IN_MINUTE.intValue() * MINUTES_IN_HOUR.intValue() * HOURS_IN_DAY.intValue(); /** * 1小时有多少seconds */ public static final long SECONDS_IN_HOUR = SECONDS_IN_MINUTE * MINUTES_IN_HOUR; /** * 1秒钟有多少milliseconds */ public static final long MILLISECONDS_IN_SECOND = 1000; /** * 1分钟有多少milliseconds */ public static final long MILLISECONDS_IN_MINUTE = SECONDS_IN_MINUTE * MILLISECONDS_IN_SECOND; /** * 1小时有多少milliseconds */ public static final long MILLISECONDS_IN_HOUR = MINUTES_IN_HOUR * MILLISECONDS_IN_MINUTE; /** * 1天有多少milliseconds */ public static final long MILLISECONDS_IN_DAY = HOURS_IN_DAY * MILLISECONDS_IN_HOUR; /** * 1周有多少milliseconds */ public static final long MILLISECONDS_IN_WEEK = DAYS_IN_WEEK * MILLISECONDS_IN_DAY; private DateUtil() { } /** * 在FORM上按照指定日期范围搜索时,开始日期只能到日期,而数据库里还包含时刻,本方法把“从XX天”转换为“从XX时刻” * * @param date * @return String */ public static String getQueryDateFrom(final String date) { return new StringBuffer(date).append(" 00:00:00").toString(); } /** * 在FORM上按照指定日期范围搜索时,结束日期只能到日期,而数据库里还包含时刻,本方法把“到XX天”转换为“到XX时刻” * * @param date * @return String */ public static String getQueryDateTill(final String date) { return new StringBuffer(date).append(" 23:59:59").toString(); } public static Timestamp getTimestamp() { return (new Timestamp(System.currentTimeMillis())); } public static Timestamp getTimestamp(final Date date) { return (new Timestamp(date.getTime())); } /** * 返回本年 * * @return int */ public static int getThisYear() { Calendar calendarNow = Calendar.getInstance(); return calendarNow.get(Calendar.YEAR); } /** * 返回今天,格式yyyy-MM-dd * * @return String */ public static String todayDateStr() { return showDate(new Date()); } /** * 分钟转小时 * * @param minutes * @return String */ public static String minutesToHours(final Integer minutes) { double ret = (int) minutes / 60; ret = ret + (minutes % 60) / 60.0; DecimalFormat df = new DecimalFormat("###.0"); return df.format(ret); } /** * 获取明天日期 * * @return String */ public static String tommorowDateStr() { Date tommorow = addDay(new Date(), 1); return showDate(tommorow); } /** * 指定date转换成字符串 按照yyyy-MM-dd格式 * * @param date * @return String */ public static String showDate(final Date date) { return dateToStr(date, YYYYMMDD); } /** * 根据date输出具体时间 按照HH:mm:ss格式 * * @param date * @return String */ public static String showTime(final Date date) { return dateToStr(date, HHMMSS); } /** * 根据date输出具体日期时间 yyyy-MM-dd HH:mm:ss * * @param date * @return String */ public static String showDateTime(final Date date) { return dateToStr(date, YYYYMMDDHHMMSS); } /** * 按照指定的格式,把一个日期型转换为字符串 例如, dateToStr(new Date(),"yyyy-MM-dd hh:mm:ss"); * * @param date * @param format * @return String */ public static String dateToStr(final Date date, final String format) { if (date == null) { return ""; } SimpleDateFormat dateToStr = new SimpleDateFormat(format); return dateToStr.format(date); } /** * 按照指定的格式,把一个字符串型转换为日期 * 例如,strToDate("2000-12-11-06:23:12","yyyy-MM-dd-hh:mm:ss"); * * @param dateStr * @param format * @return Date */ public static Date strToDate(final String dateStr, final String format) { SimpleDateFormat sdf = new SimpleDateFormat(format); Date date; try { date = sdf.parse(dateStr); return date; } catch (ParseException e) { e.printStackTrace(); } return null; } /** * 按照指定的格式,把一个字符串型转换为日期 * 例如,strToDate("2000-12-11-06:23:12","yyyy-MM-dd-hh:mm:ss"); * * @param dateStr * @param format * @return Date */ public static Date strToDate(final String dateStr, final String format, Locale locale) { SimpleDateFormat sdf = new SimpleDateFormat(format, locale); Date date; try { date = sdf.parse(dateStr); return date; } catch (ParseException e) { e.printStackTrace(); } return null; } /** * 计算fromDateStr到toDateStr还有多少天 * * @param fromDateStr * @param toDateStr * @return long */ public static long daysLeftTo(final String fromDateStr, final String toDateStr) { if (!StringUtils.isNotEmpty(fromDateStr) || !StringUtils.isNotEmpty(toDateStr)) { return 0; } return Long.parseLong(CalendarUtil.getTwoDay(toDateStr, fromDateStr)); } /** * 计算fromDate到toDate还有多少天 * * @param fromDate * @param toDate * @return long */ public static long daysLeftTo(final Date fromDate, final Date toDate) { if (fromDate == null || toDate == null) { return 0; } return (toDate.getTime() - fromDate.getTime()) / MILLISECONDS_IN_DAY; } /** * 计算两个日期相差的分钟数 * * @param fromDate * @param toDate * @return */ public static long minutesLeftTo(final Date fromDate, final Date toDate) { if (fromDate == null || toDate == null) { return 0; } return (toDate.getTime() - fromDate.getTime()) / MILLISECONDS_IN_MINUTE; } /** * 返回测试时间距当前时间共多少天数, 精确到一天之内(取精确值) * * @param toDate * @return */ public static Double daysLeftTo(final Date toDate) { SimpleDateFormat d = new SimpleDateFormat(YYYYMMDDHHMMSS); // 格式化时间 String nowtime = d.format(new Date()); // 按以上格式 将当前时间转换成字符串 Double days = 0d; try { days = Long.valueOf(toDate.getTime() - d.parse(nowtime).getTime()) .doubleValue() / MILLISECONDS_IN_DAY; } catch (ParseException e) { e.getMessage(); } return days; } /** * 计算现在距离某个时间(from)已经过去了多少分钟 * * @param from * @return Long */ public static Long calMinutesPassed(final Date from) { if (from == null) { return 0L; } return (new Date().getTime() - from.getTime()) / MILLISECONDS_IN_MINUTE; } /** * 对输入的日期进行比较,带回相差的天数 * * @param s1 * @param s2 * @return int */ public static int compDate(final String s1, final String s2) { int day = 0; SimpleDateFormat sf = new SimpleDateFormat(YYYYMMDD); try { Date date1 = sf.parse(s1); Date date2 = sf.parse(s2); day = (int) ((date2.getTime() - date1.getTime()) / MILLISECONDS_IN_DAY); } catch (Exception e) { e.getMessage(); } return day; } /** * 计算当前时间与compareDateStr还剩余多少天,compareDateStr例子:2008-09-19 * 如果已经到了那一天或者已经超过了那一天,那么返回负数 * * @param compareDateStr * @return long */ public static long daysLeftTo(final String compareDateStr) { return daysLeftTo(todayDateStr(), compareDateStr); } /** * 今天与compareDateStr相差几天 * * @param compareDateStr * @return long */ public static long daysAfter(final String compareDateStr) { return -1 * daysLeftTo(compareDateStr); } /** * 判断当前时间是否在某日期之后 * * @param compareDateStr * @return boolean */ public static boolean todayIsAfter(final String compareDateStr) { return !todayIsBefore(compareDateStr); } /** * 判断fromDateStr时间是否在toDateStr日期之后 * * @param fromDateStr * @param toDateStr * @return boolean */ public static boolean isAfter(final String fromDateStr, final String toDateStr) { return daysLeftTo(fromDateStr, toDateStr) <= 0; } /** * 判断当前时间是否在某日期之前 * * @param compareDateStr * @return boolean */ public static boolean todayIsBefore(final String compareDateStr) { return daysLeftTo(compareDateStr) > 0; } /** * 判断fromDateStr时间是否在toDateStr时间之前 * * @param fromDateStr * @param toDateStr * @return boolean */ public static boolean isBefore(final String fromDateStr, final String toDateStr) { return !isAfter(fromDateStr, toDateStr); } /** * 判断今天是否是与指定的日期是同一天 * * @param compareDateStr * @return boolean */ public static boolean sameDay(final String compareDateStr) { return daysLeftTo(compareDateStr) == 0; } /** * 判断两个日期是否是同一天 * * @param fromDateStr * @param toDateStr * @return boolean */ public static boolean isSameDay(final String fromDateStr, final String toDateStr) { return daysLeftTo(fromDateStr, toDateStr) == 0; } /** * 计算出date之后days天后的日期,days可以是负数 * * @param date * @param days * @return Date */ public static Date addDay(final Date date, final int days) { Calendar cale = Calendar.getInstance(); cale.setTime(date); cale.add(Calendar.DAY_OF_YEAR, days); return cale.getTime(); } /** * 计算某个date之后(huors>0)或之前(hours<0)的Date值 * * @param date * @param hours * @return Date */ public static Date addHour(final Date date, final int hours) { Calendar cale = Calendar.getInstance(); cale.setTime(date); cale.add(Calendar.HOUR_OF_DAY, hours); return cale.getTime(); } /** * 计算某个date之后(minutes>0)或之前(minutes<0)的Date值 * * @param date * @param minutes * @return Date */ public static Date addMinute(final Date date, final int minutes) { Calendar cale = Calendar.getInstance(); cale.setTime(date); cale.add(Calendar.MINUTE, minutes); return cale.getTime(); } /** * 返回当天的最后时间 如 2013-11-26 23:59:59.999 * * @return Timestamp */ public static Timestamp getCurrentDayEnd() { Calendar c = Calendar.getInstance(); Timestamp t = new Timestamp(System.currentTimeMillis()); c.setTime(t); c.set(Calendar.HOUR_OF_DAY, 23); c.set(Calendar.MINUTE, 59); c.set(Calendar.SECOND, 59); c.set(Calendar.MILLISECOND, 999); return new Timestamp(c.getTimeInMillis()); } /** * 返回当天的开始时间 如 2013-11-26 00:00:00.0 * * @return Timestamp */ public static Timestamp getCurrentDayStart() { Calendar c = Calendar.getInstance(); Timestamp t = new Timestamp(System.currentTimeMillis()); c.setTime(t); c.set(Calendar.HOUR_OF_DAY, 0); c.set(Calendar.MINUTE, 0); c.set(Calendar.SECOND, 0); c.set(Calendar.MILLISECOND, 0); return new Timestamp(c.getTimeInMillis()); } /** * 返回测试时间距当前时间共多少分钟 入参date格式yyyy-MM-dd HH:mm:ss * * @param date * @return Long */ public static Long minutesLeftTo(final String date) { SimpleDateFormat d = new SimpleDateFormat(YYYYMMDDHHMMSS);// 格式化时间 String nowtime = d.format(new Date());// 按以上格式 将当前时间转换成字符串 Long minutes = 0L; try { minutes = d.parse(nowtime).getTime() - d.parse(date).getTime(); minutes = minutes / MILLISECONDS_IN_MINUTE; } catch (ParseException e) { e.getMessage(); } return minutes; } /** * 返回测试时间距当前时间共多少秒 入参date格式yyyy-MM-dd HH:mm:ss * * @param date * @return Long */ public static Long secondsLeftTo(final String date) { SimpleDateFormat d = new SimpleDateFormat(YYYYMMDDHHMMSS); // 格式化时间 String nowtime = d.format(new Date()); // 按以上格式 将当前时间转换成字符串 Long seconds = 0L; try { seconds = (d.parse(nowtime).getTime() - d.parse(date).getTime()) / MILLISECONDS_IN_SECOND; } catch (ParseException e) { e.getMessage(); } return seconds; } // 当前时间2014-12 返回2013-12 public static String getLastYear() { DateFormat f = new SimpleDateFormat("yyyy-MM"); Calendar c = Calendar.getInstance(); c.add(Calendar.YEAR, -1); return f.format(c.getTime()); } // 当前时间2014-12-03 返回2014-12-03 public static String getLastYear_() { DateFormat f = new SimpleDateFormat("yyyy-MM-dd"); Calendar c = Calendar.getInstance(); //c.add(Calendar.YEAR, -1); return f.format(c.getTime()); } /** * * @param dateStr * 时间字符串(Sat May 11 17:24:21 CST 2002) * @param format * 转换格式 * @return */ public static String parseStrDateToString(final String dateStr, String format) { SimpleDateFormat sdf = new SimpleDateFormat( "EEE MMM dd HH:mm:ss Z yyyy", Locale.UK); try { Date d = sdf.parse(dateStr); SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); return sdf1.format(d); } catch (ParseException e) { e.printStackTrace(); return null; } } /** * 两个时间相差距离多少天多少小时多少分多少秒 * * @param str1 * 时间参数 1 格式:1990-01-01 12:00:00 * @param str2 * 时间参数 2 格式:2009-01-01 12:00:00 * @return long[] 返回值为:{天, 时, 分, 秒} */ public static long[] getDistanceTimes(Date one, Date two) { long day = 0; long hour = 0; long min = 0; long sec = 0; long time1 = one.getTime(); long time2 = two.getTime(); long diff; if (time1 < time2) { diff = time2 - time1; } else { diff = time1 - time2; } day = diff / (24 * 60 * 60 * 1000); hour = (diff / (60 * 60 * 1000) - day * 24); min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60); sec = (diff / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60); long[] times = { day, hour, min, sec }; return times; } /** * 两个时间相差距离多少天多少小时多少分多少秒 * * @param str1 * 时间参数 1 格式:1990-01-01 12:00:00 * @param str2 * 时间参数 2 格式:2009-01-01 12:00:00 * @return String 返回值为:xx天xx小时xx分xx秒 */ public static String getDistanceTime(Date one, Date two) { long day = 0; long hour = 0; long min = 0; long sec = 0; long time1 = one.getTime(); long time2 = two.getTime(); long diff; if (time1 < time2) { diff = time2 - time1; } else { diff = time1 - time2; } day = diff / (24 * 60 * 60 * 1000); hour = (diff / (60 * 60 * 1000) - day * 24); min = ((diff / (60 * 1000)) - day * 24 * 60 - hour * 60); sec = (diff / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60); return day + "天" + hour + "小时" + min + "分" + sec + "秒"; } /** * 比较两个时间大小 * @param dt1 * @param dt2 * @return */ public static int compareDate(Date dt1,Date dt2){ if (dt1.getTime() > dt2.getTime()) { //System.out.println("dt1 在dt2前"); return 1; } else if (dt1.getTime() < dt2.getTime()) { //System.out.println("dt1在dt2后"); return -1; } else {//相等 return 0; } } /** * 计算两个日期相差的秒数 * * @param fromDate * @param toDate * @return */ public static long secondLeftTo(final Date fromDate, final Date toDate) { if (fromDate == null || toDate == null) { return 0; } long a = toDate.getTime(); long b = fromDate.getTime(); int c = (int)((a - b) / 1000); return c; } /** * 指定时间多少分钟前的时间 * * @param fromDate 时间 * @param time 分钟 * @return */ public static Date DateBefore(final Date fromDate, Long time) { Long longtime=time*60*1000;//多少分钟 Date DatebeforeDate = null; long a = fromDate.getTime(); DatebeforeDate=new Date(a-longtime);//多少分钟前的时间 return DatebeforeDate; } /** * 在指定时间上加多少分钟 * * @param fromDate 时间 * @param time 分钟 * @return */ public static Date getDateMinute(final Date fromDate, int time) { Calendar calendar = Calendar.getInstance(); calendar.setTime(fromDate); calendar.add(Calendar.MINUTE, time); Date date = calendar.getTime(); return date; } }
923390cb0ad23b9a682ffbe596632d5310a467da
1,186
java
Java
src/org/pepstock/charba/client/defaults/IsDefaultLayout.java
pepstock-org/Charba
cf6964a04bf88c77019634c4d701397560392e58
[ "Apache-2.0" ]
48
2018-02-01T09:11:02.000Z
2022-03-17T12:47:01.000Z
src/org/pepstock/charba/client/defaults/IsDefaultLayout.java
pepstock-org/Charba
cf6964a04bf88c77019634c4d701397560392e58
[ "Apache-2.0" ]
61
2018-05-03T13:38:47.000Z
2022-03-10T13:00:25.000Z
src/org/pepstock/charba/client/defaults/IsDefaultLayout.java
pepstock-org/Charba
cf6964a04bf88c77019634c4d701397560392e58
[ "Apache-2.0" ]
7
2018-02-03T10:18:00.000Z
2021-06-18T18:16:05.000Z
30.410256
99
0.703204
996,624
/** Copyright 2017 Andrea "Stock" Stocchero 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.pepstock.charba.client.defaults; /** * Interface to define layout object defaults. * * @author Andrea "Stock" Stocchero */ public interface IsDefaultLayout { /** * Returns padding object defaults. * * @return padding object defaults. */ IsDefaultPadding getPadding(); /** * Returns <code>true</code> to apply automatic padding so visible elements are completely drawn. * * @return <code>true</code> to apply automatic padding so visible elements are completely drawn */ boolean isAutoPadding(); }
923390d762043db480c83509974846d92f64b749
2,063
java
Java
src/main/java/com/summercoding/spring/faulttolerant/BatchConfiguration.java
leszko/spring-batch-fault-tolerant
60d308c1937fe31765fee4d08ff5599c8880afdf
[ "MIT" ]
null
null
null
src/main/java/com/summercoding/spring/faulttolerant/BatchConfiguration.java
leszko/spring-batch-fault-tolerant
60d308c1937fe31765fee4d08ff5599c8880afdf
[ "MIT" ]
null
null
null
src/main/java/com/summercoding/spring/faulttolerant/BatchConfiguration.java
leszko/spring-batch-fault-tolerant
60d308c1937fe31765fee4d08ff5599c8880afdf
[ "MIT" ]
1
2019-09-05T04:05:32.000Z
2019-09-05T04:05:32.000Z
29.471429
85
0.688318
996,625
package com.summercoding.spring.faulttolerant; import org.springframework.batch.core.Job; import org.springframework.batch.core.Step; import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; import org.springframework.batch.core.configuration.annotation.JobBuilderFactory; import org.springframework.batch.core.configuration.annotation.StepBuilderFactory; import org.springframework.batch.core.launch.support.RunIdIncrementer; import org.springframework.batch.item.ItemProcessor; import org.springframework.batch.item.ItemReader; import org.springframework.batch.item.ItemWriter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import javax.sql.DataSource; @Configuration @EnableBatchProcessing public class BatchConfiguration { @Autowired public JobBuilderFactory jobBuilderFactory; @Autowired public StepBuilderFactory stepBuilderFactory; @Autowired public DataSource dataSource; @Bean public ItemReader<Element> reader() { return new Reader(); } @Bean public ItemProcessor<Element, Element> processor() { return new Processor(); } @Bean public ItemWriter<Element> writer() { return new Writer(); } // @Bean // public JobExecutionListener listener() { // return new JobCompletionNotificationListener(new JdbcTemplate(dataSource)); // } @Bean public Job importUserJob() { return jobBuilderFactory.get("importUserJob") .incrementer(new RunIdIncrementer()) // .listener(listener()) .flow(step1()) .end() .build(); } @Bean public Step step1() { return stepBuilderFactory.get("step1") .<Element, Element>chunk(10) .reader(reader()) .processor(processor()) .writer(writer()) .build(); } }
9233919395a24af09bc5d2830e313ebc92db24b3
1,839
java
Java
src/com/widgetgrid/android/arimagesearch/OverlayView.java
mattbasta/ar-widgetgrid
fa56c2d4f01af0d604111641be66cac6bd0ede8a
[ "Apache-2.0", "CC0-1.0" ]
3
2017-07-03T10:52:19.000Z
2018-08-17T15:28:09.000Z
src/com/widgetgrid/android/arimagesearch/OverlayView.java
mattbasta/widgetgrid-ar
fa56c2d4f01af0d604111641be66cac6bd0ede8a
[ "Apache-2.0", "CC0-1.0" ]
null
null
null
src/com/widgetgrid/android/arimagesearch/OverlayView.java
mattbasta/widgetgrid-ar
fa56c2d4f01af0d604111641be66cac6bd0ede8a
[ "Apache-2.0", "CC0-1.0" ]
null
null
null
23.576923
124
0.62969
996,626
package com.widgetgrid.android.arimagesearch; import com.widgetgrid.android.arimagesearch.zxing.PointInfoObject; import com.widgetgrid.android.arimagesearch.zxing.PointPattern; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.view.View; public class OverlayView extends View { public Bitmap testData; public PointInfoObject points; public int _width; public int _height; public OverlayView(Context context) { super(context); } @Override protected void onDraw(Canvas canvas) { Paint paint = new Paint(); _width = canvas.getWidth(); _height = canvas.getHeight(); if(testData != null) canvas.drawBitmap(testData, 0, 0, paint); int colors[] = { Color.rgb(225, 40, 225), // Magenta Color.rgb(190, 190, 0), // Yellow Color.rgb(0, 255, 255) // Cyan }; paint.setStrokeWidth(3); paint.setColor(Color.GREEN); if(points != null) { PointPattern patterns[] = points.getPoints(); for(int x = 0; x < patterns.length; x++) { if(patterns[x] == null) continue; paint.setColor(colors[x]); PointPattern dot = patterns[x]; canvas.drawCircle(dot.x, dot.y, 4 + (3 - x) * 3, paint); } float bx, by, gx, gy; bx = patterns[0].x - patterns[1].x; by = patterns[0].y - patterns[1].y; gx = patterns[2].x - patterns[1].x; gy = patterns[2].y - patterns[1].y; SimpleVector s = new SimpleVector(bx, by, gx, gy); s.makeUnitVector(); paint.setColor(Color.GREEN); canvas.drawLine(patterns[1].x, patterns[1].y, patterns[1].x + (int)(s.i * 40), patterns[1].y + (int)(s.j * -40), paint); } super.onDraw(canvas); } }
923391cdd64098852ef3eb1a02877d46467a1fd8
8,474
java
Java
Examen#1_AngelVasquez/src/examen/pkg1_angelvasquez/Cliente.java
Angelvb18/Examen-1_AngelVasquez
bbabd8d16c7bcecb10366c4548cfa7715bd6aa5e
[ "MIT" ]
null
null
null
Examen#1_AngelVasquez/src/examen/pkg1_angelvasquez/Cliente.java
Angelvb18/Examen-1_AngelVasquez
bbabd8d16c7bcecb10366c4548cfa7715bd6aa5e
[ "MIT" ]
null
null
null
Examen#1_AngelVasquez/src/examen/pkg1_angelvasquez/Cliente.java
Angelvb18/Examen-1_AngelVasquez
bbabd8d16c7bcecb10366c4548cfa7715bd6aa5e
[ "MIT" ]
null
null
null
41.743842
131
0.635119
996,627
/* * 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 examen.pkg1_angelvasquez; import javax.swing.table.DefaultTableModel; /** * * @author Angel */ public class Cliente extends Log { /** * Creates new form Cliente */ public Cliente() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jTabbedPane1 = new javax.swing.JTabbedPane(); jPanel2 = new javax.swing.JPanel(); jPanel3 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); tabla1 = new javax.swing.JTable(); jButton1 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jTabbedPane1.addChangeListener(new javax.swing.event.ChangeListener() { public void stateChanged(javax.swing.event.ChangeEvent evt) { jTabbedPane1StateChanged(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 496, Short.MAX_VALUE) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 431, Short.MAX_VALUE) ); jTabbedPane1.addTab("Prestamo", jPanel2); tabla1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "Titulo", "Autor", "Año" } )); jScrollPane1.setViewportView(tabla1); jButton1.setText("Listar"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(jButton1) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 472, Short.MAX_VALUE)) .addContainerGap()) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addComponent(jButton1) .addGap(18, 18, 18) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 324, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(51, Short.MAX_VALUE)) ); jTabbedPane1.addTab("Listar Disponibles", jPanel3); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jTabbedPane1)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jTabbedPane1) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed String [] u= null; for (int i = 0; i < lib.size(); i++) { int cont=0; DefaultTableModel modelo = ((DefaultTableModel)tabla1.getModel()); tabla1.setModel(modelo); modelo.addRow(u); Libro l = (Libro) lib.get(i); modelo.setValueAt(l.getTitulo(), i, cont); cont++; modelo.setValueAt(l.getAutores(), i, cont); cont++; modelo.setValueAt(l.getISBN(),i,cont); cont++; } }//GEN-LAST:event_jButton1ActionPerformed private void jTabbedPane1StateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_jTabbedPane1StateChanged // TODO add your handling code here: }//GEN-LAST:event_jTabbedPane1StateChanged /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(Cliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(Cliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(Cliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(Cliente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new Cliente().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTabbedPane jTabbedPane1; private javax.swing.JTable tabla1; // End of variables declaration//GEN-END:variables }
92339288dbba4842f397c5c7bf8c75aa138357c1
1,898
java
Java
allure-e2e/src/test/java/ru/yandex/qatools/allure/e2e/TabsTest.java
margaritis/allure-core
80225915348a66470e3cb752aa3b4663069bbaea
[ "Apache-2.0" ]
1
2015-11-05T17:06:21.000Z
2015-11-05T17:06:21.000Z
allure-e2e/src/test/java/ru/yandex/qatools/allure/e2e/TabsTest.java
margaritis/allure-core
80225915348a66470e3cb752aa3b4663069bbaea
[ "Apache-2.0" ]
null
null
null
allure-e2e/src/test/java/ru/yandex/qatools/allure/e2e/TabsTest.java
margaritis/allure-core
80225915348a66470e3cb752aa3b4663069bbaea
[ "Apache-2.0" ]
null
null
null
27.507246
127
0.687566
996,628
package ru.yandex.qatools.allure.e2e; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import ru.yandex.qatools.allure.JSErrorsRule; import ru.yandex.qatools.allure.Page; import static java.util.concurrent.TimeUnit.SECONDS; import static org.hamcrest.MatcherAssert.assertThat; import static ru.yandex.qatools.allure.Helpers.existsAndVisible; import static ru.yandex.qatools.allure.UrlFragmentMatcher.hasFragment; import static ru.yandex.qatools.matchers.decorators.MatcherDecorators.should; import static ru.yandex.qatools.matchers.decorators.MatcherDecorators.timeoutHasExpired; public class TabsTest { @Rule public JSErrorsRule rule = new JSErrorsRule(); private Page page; @Before public void openBrowser() throws Exception { page = new Page(rule.driver()); assertThat(page.tabContent(), should(existsAndVisible()).whileWaitingUntil(timeoutHasExpired(SECONDS.toMillis(3)))); } public void checkHash(String expectedHash) { assertThat(rule.driver(), should(hasFragment(expectedHash)).whileWaitingUntil(timeoutHasExpired(SECONDS.toMillis(3)))); } @Test public void defectsTab() throws Exception { page.tabs().defects().click(); checkHash("/defects"); } @Test public void overviewTab() throws Exception { page.tabs().overview().click(); checkHash("/"); } @Test public void homeTab() throws Exception { checkHash("/home"); } @Test public void behaviorsTab() throws Exception { page.tabs().behaviours().click(); checkHash("/features"); } @Test public void graphTab() throws Exception { page.tabs().graph().click(); checkHash("/graph"); } @Test public void timelineTab() throws Exception { page.tabs().timeline().click(); checkHash("/timeline"); } }
923394c33c50ceaddd05887d197add9258352ec1
2,813
java
Java
testsuite/src/it/java/io/quarkus/ts/startstop/utils/WebpageTester.java
rsvoboda/quarkus-startstop
3536af585e2fa427911f3671b7e96e849d20af0d
[ "Apache-2.0" ]
5
2021-03-11T10:31:34.000Z
2021-12-15T09:29:51.000Z
testsuite/src/it/java/io/quarkus/ts/startstop/utils/WebpageTester.java
rsvoboda/quarkus-startstop
3536af585e2fa427911f3671b7e96e849d20af0d
[ "Apache-2.0" ]
69
2020-02-28T07:36:35.000Z
2022-02-16T15:12:14.000Z
testsuite/src/it/java/io/quarkus/ts/startstop/utils/WebpageTester.java
rsvoboda/quarkus-startstop
3536af585e2fa427911f3671b7e96e849d20af0d
[ "Apache-2.0" ]
12
2020-02-27T13:28:39.000Z
2021-12-15T09:28:44.000Z
37.506667
145
0.588695
996,629
package io.quarkus.ts.startstop.utils; import org.apache.commons.lang3.StringUtils; import org.jboss.logging.Logger; import java.io.IOException; import java.net.URL; import java.net.URLConnection; import java.nio.charset.StandardCharsets; import java.util.Scanner; import static org.junit.jupiter.api.Assertions.assertTrue; public class WebpageTester { private static final Logger LOGGER = Logger.getLogger(WebpageTester.class.getName()); /** * Patiently try to wait for a web page and examine it * * @param url address * @param timeoutS in seconds * @param stringToLookFor string must be present on the page */ public static long testWeb(String url, long timeoutS, String stringToLookFor, boolean measureTime) throws InterruptedException, IOException { if (StringUtils.isBlank(url)) { throw new IllegalArgumentException("url must not be empty"); } if (timeoutS < 0) { throw new IllegalArgumentException("timeoutS must be positive"); } if (StringUtils.isBlank(stringToLookFor)) { throw new IllegalArgumentException("stringToLookFor must contain a non-empty string"); } String webPage = ""; long now = System.currentTimeMillis(); final long startTime = now; boolean found = false; long foundTimestamp = -1L; while (now - startTime < 1000 * timeoutS) { URLConnection c = new URL(url).openConnection(); c.setRequestProperty("Accept", "*/*"); c.setConnectTimeout(500); try (Scanner scanner = new Scanner(c.getInputStream(), StandardCharsets.UTF_8.toString())) { scanner.useDelimiter("\\A"); webPage = scanner.hasNext() ? scanner.next() : ""; } catch (Exception e) { LOGGER.debug("Waiting `" + stringToLookFor + "' to appear on " + url); } if (webPage.contains(stringToLookFor)) { found = true; if (measureTime) { foundTimestamp = System.currentTimeMillis(); } break; } if (!measureTime) { Thread.sleep(500); } else { Thread.sleep(0, 100000); } now = System.currentTimeMillis(); } String failureMessage = "Timeout " + timeoutS + "s was reached. " + (StringUtils.isNotBlank(webPage) ? webPage + " must contain string: " : "Empty webpage does not contain string: ") + "`" + stringToLookFor + "'"; if (!found) { LOGGER.info(failureMessage); } assertTrue(found, failureMessage); return foundTimestamp - startTime; } }
92339577607a49e10186ff365c2dba24aef04f26
452
java
Java
ghost.framework.context/src/main/java/ghost/framework/context/bean/factory/scan/IScanResourceBeanTargetHandle.java
guoshucan/mpaas
8949c0c484987d9c030595b24d62a10585a814ce
[ "Apache-2.0" ]
1
2020-09-29T10:24:03.000Z
2020-09-29T10:24:03.000Z
ghost.framework.context/src/main/java/ghost/framework/context/bean/factory/scan/IScanResourceBeanTargetHandle.java
guoshucan/mpaas
8949c0c484987d9c030595b24d62a10585a814ce
[ "Apache-2.0" ]
null
null
null
ghost.framework.context/src/main/java/ghost/framework/context/bean/factory/scan/IScanResourceBeanTargetHandle.java
guoshucan/mpaas
8949c0c484987d9c030595b24d62a10585a814ce
[ "Apache-2.0" ]
3
2020-11-05T15:52:17.000Z
2021-07-27T04:37:00.000Z
23.789474
90
0.70354
996,630
package ghost.framework.context.bean.factory.scan; import ghost.framework.maven.FileArtifact; /** * package: ghost.framework.context.bean.factory.scan * * @Author: 郭树灿{guo-w541} * @link: 手机:13715848993, QQ 27048384 * @Description:扫描资源事件目标处理接口 * @Date: 2020/2/23:13:33 */ public interface IScanResourceBeanTargetHandle<O, T> extends IScanBeanTargetHandle<O, T> { /** * 获取扫描资源包信息 * @return */ FileArtifact getArtifact(); }
923395dc0443a34dc58fcd24fc0ededd9462af65
20,674
java
Java
src/org/ballerinalang/compiler/parser/BallerinaLexer.java
SupunS/BallerinaParser
8e956bd2a75fb14e9afd85be7330873bf530c3fd
[ "Apache-2.0" ]
null
null
null
src/org/ballerinalang/compiler/parser/BallerinaLexer.java
SupunS/BallerinaParser
8e956bd2a75fb14e9afd85be7330873bf530c3fd
[ "Apache-2.0" ]
null
null
null
src/org/ballerinalang/compiler/parser/BallerinaLexer.java
SupunS/BallerinaParser
8e956bd2a75fb14e9afd85be7330873bf530c3fd
[ "Apache-2.0" ]
null
null
null
30.537666
113
0.533907
996,631
/* * Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.ballerinalang.compiler.parser; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.StringReader; import java.nio.charset.StandardCharsets; public class BallerinaLexer { private static final byte EOF = -1; private final BallerinaErrorReporter errorHandler = new BallerinaErrorReporter(); private final PositionTracer tracer = new PositionTracer(); private final TokenGenerator tokenGenerator = new TokenGenerator(this.tracer); private StringBuilder sb = new StringBuilder(); private InputReader reader; public BallerinaLexer(InputStream inputStream) { this.reader = new InputReader(inputStream); } public BallerinaLexer(String source) { this.reader = new InputReader(source); } /** * Get the next lexical token. * * @return Next lexical token. */ public Token nextToken() { Token token = readToken(); this.tracer.markTokenEnd(); return token; } private Token readToken() { Token token; int startChar = consume(); switch (startChar) { case EOF: token = TokenGenerator.EOF; break; // Separators case LexerTerminals.COLON: token = this.tokenGenerator.getColon(); break; case LexerTerminals.SEMICOLON: token = this.tokenGenerator.getSemicolon(); break; case LexerTerminals.DOT: token = parseDotOrEllipsis(); break; case LexerTerminals.COMMA: token = this.tokenGenerator.getComma(); break; case LexerTerminals.LEFT_PARANTHESIS: token = this.tokenGenerator.getLeftParanthesis(); break; case LexerTerminals.RIGHT_PARANTHESIS: token = this.tokenGenerator.getRigthtParanthesis(); break; case LexerTerminals.LEFT_BRACE: token = this.tokenGenerator.getLeftBrace(); break; case LexerTerminals.RIGHT_BRACE: token = this.tokenGenerator.getRightBrace(); break; case LexerTerminals.LEFT_BRACKET: token = this.tokenGenerator.getLeftBracket(); break; case LexerTerminals.RIGHT_BRACKET: token = this.tokenGenerator.getRightBracket(); break; // Arithmetic operators case LexerTerminals.ASSIGN: token = processEqualOperator(); break; case LexerTerminals.ADD: token = this.tokenGenerator.getPlus(); break; case LexerTerminals.SUB: token = this.tokenGenerator.getMinus(); break; case LexerTerminals.MUL: token = this.tokenGenerator.getMutiplication(); break; case LexerTerminals.DIV: if (peek() == LexerTerminals.DIV) { token = processComment(); } else { token = this.tokenGenerator.getDivision(); } break; case LexerTerminals.MOD: token = this.tokenGenerator.getModulus(); break; case LexerTerminals.LT: token = this.tokenGenerator.getLessThanOp(); break; // Numbers case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': token = processNumericLiteral(startChar); break; // Other case 0x9: case 0xD: case 0x20: token = processWhiteSpace(startChar); break; case LexerTerminals.NEWLINE: token = this.tokenGenerator.getNewline(); this.tracer.markNewLine(); break; // Identifiers and keywords default: append(startChar); if (isIdentifierInitialChar(startChar)) { token = processIdentifierOrKeyword(); break; } token = processInvalidToken(); } return token; } /** * @return */ private Token parseDotOrEllipsis() { if (peek(1) == LexerTerminals.DOT && peek(2) == LexerTerminals.DOT) { consume(); consume(); return this.tokenGenerator.getEllipsis(); } return this.tokenGenerator.getDot(); } /** * <p> * Process comments. * </p> * <code>Comment := // AnyCharButNewline* * </br>AnyCharButNewline := ^ 0xA</code> * * @return A comment */ private Token processComment() { consume(); // consume the second '/' of the comment. This is already verified. while (peek() != LexerTerminals.NEWLINE) { consumeAndAppend(); } return this.tokenGenerator.getComment(getCurrentTokenText()); } /** * Process any token that starts with '='. * * @return One of the tokens: <code>'=', '==', '=>', '==='</code> */ private Token processEqualOperator() { switch (peek()) { // check for the second char case LexerTerminals.ASSIGN: consume(); if (peek() == LexerTerminals.ASSIGN) { // this is '===' consume(); return this.tokenGenerator.getRefEqualOp(); } else { // this is '==' return this.tokenGenerator.getEqualOp(); } case LexerTerminals.GT: // this is '=>' consume(); return this.tokenGenerator.getEqualGreaterOp(); default: // this is '=' return this.tokenGenerator.getAssignOp(); } } /** * <p> * Process and returns a numeric literal. * </p> * <code> * numeric-literal := int-literal | floating-point-literal * </br> * int-literal := DecimalNumber | HexIntLiteral * </br> * DecimalNumber := 0 | NonZeroDigit Digit* * </br> * Digit := 0 .. 9 * </br> * NonZeroDigit := 1 .. 9 * </code> * * @return The numeric literal. */ private Token processNumericLiteral(int startChar) { append(startChar); int nextChar = peek(); if (isHexIndicator(startChar, nextChar)) { return processHexIntLiteral(); } TokenKind kind = TokenKind.INT_LITERAL; int len = 1; while (true) { switch (nextChar) { case '.': case 'e': case 'E': // TODO: handle float Token token = processInvalidToken(); this.errorHandler.reportMissingTokenError(token, "I dont't know how to handle floats yet"); return token; default: if (isDigit(nextChar)) { consumeAndAppend(); len++; nextChar = peek(); continue; } break; } break; } if (startChar == '0' && len > 1 && kind == TokenKind.INT_LITERAL) { Token token = processInvalidToken(); this.errorHandler.reportMissingTokenError(token, "invalid int literal. cannot start with '0'."); return token; } return this.tokenGenerator.getLiteral(getCurrentTokenText(), kind); } /** * <p> * Process and returns a hex integer literal. * </p> * <code> * HexIntLiteral := HexIndicator HexNumber * </br> * HexNumber := HexDigit+ * </br> * HexIndicator := 0x | 0X * </br> * HexDigit := Digit | a .. f | A .. F * </br> * </code> * * @return */ private Token processHexIntLiteral() { consumeAndAppend(); while (isHexDigit(peek())) { consumeAndAppend(); } return this.tokenGenerator.getLiteral(getCurrentTokenText(), TokenKind.HEX_LITERAL); } /** * Process and returns an identifier or a keyword. * * @return An identifier or a keyword. */ private Token processIdentifierOrKeyword() { while (isIdentifierFollowingChar(peek())) { consumeAndAppend(); } String tokenText = getCurrentTokenText(); switch (tokenText) { case LexerTerminals.PUBLIC: return this.tokenGenerator.getPublic(); case LexerTerminals.FUNCTION: return this.tokenGenerator.getFunction(); case LexerTerminals.INT: case LexerTerminals.FLOAT: case LexerTerminals.STRING: case LexerTerminals.BOOLEAN: return this.tokenGenerator.getType(tokenText); case LexerTerminals.RETURN: return this.tokenGenerator.getReturn(); case LexerTerminals.RETURNS: return this.tokenGenerator.getReturns(); case LexerTerminals.EXTERNAL: return this.tokenGenerator.getExternal(); default: return this.tokenGenerator.getIdentifier(tokenText); } } /** * Process and returns an invalid token. Consumes the input until {@link #isEndOfInvalidToken()} * is reached. * * @return The invalid token. */ private Token processInvalidToken() { while (!isEndOfInvalidToken()) { consumeAndAppend(); } return this.tokenGenerator.getInvalidToken(getCurrentTokenText()); } /** * Process whitespace. * <code>WhiteSpaceChar := 0x9 | 0xA | 0xD | 0x20</code> * * @param startChar Starting character of the whitespace. * @return A whitespace {@link Token} */ private Token processWhiteSpace(int startChar) { append(startChar); while (isWhiteSpace(peek())) { consumeAndAppend(); } return this.tokenGenerator.getWhiteSpaces(getCurrentTokenText()); } /** * Check whether the current index is pointing to an end of an invalid lexer-token. * An invalid token is considered to end if one of the below is reached: * <ul> * <li>a whitespace</li> * <li>semicolon</li> * <li>newline</li> * </ul> * * @return <code>true</code>, if the end of an invalid token is reached, <code>false</code> otherwise */ private boolean isEndOfInvalidToken() { int currentChar = peek(); switch (currentChar) { case LexerTerminals.NEWLINE: case LexerTerminals.SEMICOLON: // TODO: add all separators (braces, parentheses, etc) // TODO: add all operators (arithmetic, binary, etc) return true; default: return isWhiteSpace(currentChar); } } /** * <p> * Check whether a given char is an identifier start char. * </p> * <code>IdentifierInitialChar := A .. Z | a .. z | _ | UnicodeIdentifierChar</code> * * @param c character to check * @return <code>true</code>, if the character is an identifier start char. <code>false</code> otherwise. */ private boolean isIdentifierInitialChar(int c) { // TODO: pre-mark all possible characters, using a mask. And use that mask here to check if ('A' <= c && c <= 'Z') return true; if ('a' <= c && c <= 'z') return true; if (c == '_') return true; // TODO: if (UnicodeIdentifierChar) return false; return false; } /** * <p> * Check whether a given char is an identifier following char. * </p> * <code>IdentifierFollowingChar := IdentifierInitialChar | Digit</code> * * @param c character to check * @return <code>true</code>, if the character is an identifier following char. <code>false</code> otherwise. */ private boolean isIdentifierFollowingChar(int c) { return isIdentifierInitialChar(c) || isDigit(c); } /** * <p> * Check whether a given char is a digit. * </p> * <code>Digit := 0..9</code> * * @param c character to check * @return <code>true</code>, if the character represents a digit. <code>false</code> otherwise. */ private boolean isDigit(int c) { return ('0' <= c && c <= '9'); } /** * <p> * Check whether a given char is a hexa digit. * </p> * <code>HexDigit := Digit | a .. f | A .. F</code> * * @param c character to check * @return <code>true</code>, if the character represents a hex digit. <code>false</code> otherwise. */ private boolean isHexDigit(int c) { if ('a' <= c && c <= 'f') return true; if ('A' <= c && c <= 'f') return true; return isDigit(c); } /** * <p> * Check whether a given char is a whitespace. * </p> * <code>WhiteSpaceChar := 0x9 | 0xD | 0x20</code> * * @param c character to check * @return <code>true</code>, if the character represents a whitespace. <code>false</code> otherwise. */ private boolean isWhiteSpace(int c) { return c == 0x9 || c == 0xD || c == 0x20; } /** * <p> * Check whether current input index points to a start of a hex-numeric literal. * </p> * <code>HexIndicator := 0x | 0X</code> * * @param startChar Starting character of the literal * @param nextChar Second character of the literal * @return <code>true</code>, if the current input points to a start of a hex-numeric literal. * <code>false</code> otherwise. */ private boolean isHexIndicator(int startChar, int nextChar) { return startChar == '0' && (nextChar == 'x' || nextChar == 'X'); } /** * Consumes and returns the next character from the reader. * * @return Next character */ private int consume() { try { this.tracer.length++; return reader.read(); } catch (IOException e) { // FIXME e.printStackTrace(); this.tracer.length--; throw new IllegalStateException(); } } /** * Returns the next character from the reader, without consuming the stream. * * @return Next character */ private int peek() { try { return this.reader.peek(); } catch (IOException e) { // FIXME e.printStackTrace(); throw new IllegalStateException(); } } /** * Returns the next k-th character from the reader, without consuming the stream. * * @return Next k-th character */ private int peek(int k) { try { return this.reader.peek(k); } catch (IOException e) { // FIXME e.printStackTrace(); throw new IllegalStateException(); } } /** * Append a given character to the currently processing token. * * @param c Character to append */ private void append(int c) { this.sb.append((char) c); } /** * Consume the next character from the input and append it to the currently processing token. */ private void consumeAndAppend() { this.sb.append((char) consume()); } /** * Get the text associated with the current token. * * @return Text associated with the current token. */ private String getCurrentTokenText() { String text = this.sb.toString(); // reset the string builder this.sb = new StringBuilder(); return text; } /** * Reader that can read characters from a given input source. * * @since 1.2.0 */ private static class InputReader { private static final int BUFFER_SIZE = 10; private CharacterBuffer charsAhead = new CharacterBuffer(BUFFER_SIZE); private Reader reader; private int currentChar; InputReader(InputStream inputStream) { // Wrapping with a buffered reader for efficiency. this.reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); } InputReader(String source) { this.reader = new StringReader(source); } /** * Consumes the input and return the next character. * * @return Next character in the input * @throws IOException */ public int read() throws IOException { if (this.charsAhead.size > 0) { // cache the head this.currentChar = charsAhead.consume(); return this.currentChar; } // cache the head this.currentChar = this.reader.read(); return this.currentChar; } /** * Lookahead in the input and returns the next character. This will not consume the input. * That means calling this method multiple times will return the same result. * * @return Next character in the input * @throws IOException */ public int peek() throws IOException { if (this.charsAhead.size == 0) { this.charsAhead.add(this.reader.read()); } return this.charsAhead.peek(); } public int peek(int k) throws IOException { while (this.charsAhead.size < k) { this.charsAhead.add(this.reader.read()); } return this.charsAhead.peek(k); } } private static class CharacterBuffer { private final int capacity; private final int[] chars; private int endIndex = -1; private int startIndex = -1; private int size = 0; CharacterBuffer(int size) { this.capacity = size; this.chars = new int[size]; } public void add(int token) { if (this.size == this.capacity) { throw new IndexOutOfBoundsException("buffer overflow"); } if (this.endIndex == this.capacity - 1) { this.endIndex = 0; } else { this.endIndex++; } if (this.size == 0) { this.startIndex = this.endIndex; } this.chars[this.endIndex] = token; this.size++; } public int consume() { int token = this.chars[this.startIndex]; this.size--; if (this.startIndex == this.capacity - 1) { this.startIndex = 0; } else { this.startIndex++; } return token; } public int peek() { return this.chars[this.startIndex]; } public int peek(int k) { if (k > this.size) { throw new IndexOutOfBoundsException("size: " + this.size + ", index: " + k); } int index = this.startIndex + k - 1; if (index >= this.capacity) { index = index - this.capacity; } return this.chars[index]; } } }
9233972d1bae3f8908b8913dfd6b3253e45d6790
1,133
java
Java
notes/CoreJava/code/v1ch09/map/src/MapTest.java
andyRon/LearnJava
ff8b0d6ae87046f4cbfe8122366e25ea25c5b1d4
[ "MIT" ]
null
null
null
notes/CoreJava/code/v1ch09/map/src/MapTest.java
andyRon/LearnJava
ff8b0d6ae87046f4cbfe8122366e25ea25c5b1d4
[ "MIT" ]
null
null
null
notes/CoreJava/code/v1ch09/map/src/MapTest.java
andyRon/LearnJava
ff8b0d6ae87046f4cbfe8122366e25ea25c5b1d4
[ "MIT" ]
null
null
null
23.122449
67
0.53045
996,632
import java.util.HashMap; import java.util.Map; /** * @author Andy Ron */ public class MapTest { public static void main(String[] args) { Map<String, Employee> staff = new HashMap<>(); staff.put("144-25-5464", new Employee("Andy Ron")); staff.put("567-25-5464", new Employee("Jack Ma")); staff.put("187-25-5464", new Employee("Bill Gates")); staff.put("456-25-5464", new Employee("Tony Ma")); System.out.println(staff); staff.remove("567-25-5464"); staff.put("456-62-5527", new Employee("Francesca Miller")); System.out.println(staff.get("187-25-5464")); staff.forEach((k, v) -> System.out.println("key="+ k + ", value=" + v)); } } class Employee { private String name; private double salary; public Employee(String n) { name = n; salary = 0; } public String getName() { return name; } @Override public String toString() { return "Employee{" + "name='" + name + '\'' + ", salary=" + salary + '}'; } }
9233982b61ec10489d48bfa68dfc71db28d30106
1,660
java
Java
src/main/java/persistent/prestige/modules/eshop/model/OrderItem.java
henanren/mycatdemo-hibernate
61008a5afff83a8280ddafd93a84812f46625552
[ "Apache-2.0" ]
null
null
null
src/main/java/persistent/prestige/modules/eshop/model/OrderItem.java
henanren/mycatdemo-hibernate
61008a5afff83a8280ddafd93a84812f46625552
[ "Apache-2.0" ]
null
null
null
src/main/java/persistent/prestige/modules/eshop/model/OrderItem.java
henanren/mycatdemo-hibernate
61008a5afff83a8280ddafd93a84812f46625552
[ "Apache-2.0" ]
null
null
null
16.6
62
0.689759
996,633
/* * Powered By agile * Web Site: http://www.agile.com * Since 2008 - 2016 */ package persistent.prestige.modules.eshop.model; import persistent.prestige.platform.base.model.AuditableModel; /** * OrderItem 实体类 * @author 雅居乐 2016-8-27 10:31:06 * @version 1.0 */ public class OrderItem extends AuditableModel{ //alias public static final String TABLE_ALIAS = "OrderItem"; //columns START /**订单ID*/ private java.lang.Integer orderId; /**商品id*/ private java.lang.Integer goodsId; private Integer skuId; /**商品单价*/ private java.lang.Long price; /**购买数量*/ private java.lang.Integer num; /**总价格*/ private java.lang.Long totalPrice; //columns END private String buyUid; public Integer getSkuId() { return skuId; } public void setSkuId(Integer skuId) { this.skuId = skuId; } public java.lang.Integer getOrderId() { return this.orderId; } public void setOrderId(java.lang.Integer value) { this.orderId = value; } public java.lang.Integer getGoodsId() { return this.goodsId; } public void setGoodsId(java.lang.Integer value) { this.goodsId = value; } public java.lang.Long getPrice() { return this.price; } public void setPrice(java.lang.Long value) { this.price = value; } public java.lang.Integer getNum() { return this.num; } public void setNum(java.lang.Integer value) { this.num = value; } public java.lang.Long getTotalPrice() { return this.totalPrice; } public void setTotalPrice(java.lang.Long value) { this.totalPrice = value; } public String getBuyUid() { return buyUid; } public void setBuyUid(String buyUid) { this.buyUid = buyUid; } }
923398e26f694ba8ec13d8f11aec78c766328783
1,940
java
Java
backup/tta/src/com/celizion/kcg/ems/tta/controller/handler/DefaultUserHandler.java
aeolusk/utils
ca48b474b3b218fc75df79e2bf7f63d2fdaafa93
[ "Apache-2.0" ]
null
null
null
backup/tta/src/com/celizion/kcg/ems/tta/controller/handler/DefaultUserHandler.java
aeolusk/utils
ca48b474b3b218fc75df79e2bf7f63d2fdaafa93
[ "Apache-2.0" ]
null
null
null
backup/tta/src/com/celizion/kcg/ems/tta/controller/handler/DefaultUserHandler.java
aeolusk/utils
ca48b474b3b218fc75df79e2bf7f63d2fdaafa93
[ "Apache-2.0" ]
null
null
null
34.642857
116
0.701546
996,634
package com.celizion.kcg.ems.tta.controller.handler; import java.util.function.BiConsumer; import java.util.function.Function; import com.celizion.kcg.ems.tta.Message; import com.celizion.kcg.ems.tta.MessageBuilder; import com.celizion.kcg.ems.tta.controller.ConnectionContext; import com.celizion.kcg.ems.tta.define.ActionParameter; import lombok.extern.slf4j.Slf4j; @Slf4j public class DefaultUserHandler { public static BiConsumer<ConnectionContext, Message> createDummyUserHandler() { return createCommandHandler((command) -> { return "input command is " + command; // echo }, (context, output) -> { log.debug(output); // log output. }); } public static BiConsumer<ConnectionContext, Message> createCommandHandler(Function<String, String> commandHandler, BiConsumer<ConnectionContext, String> outputHandler) { return (context, message) -> { switch (message.ptype) { case InputCommand: if (commandHandler != null) { String reply = null; try { reply = commandHandler.apply(message.getParameter(ActionParameter.InOutString).toString()); } catch (Exception e) { log.warn("Can't handle command (" + message.getParameter(ActionParameter.InOutString) + ")"); } if (reply != null) { TTAProtocolHandler.sendInputCommandAck(context, message.messageId, true, message.getParameter(ActionParameter.InOutString).toString()); TTAProtocolHandler.sendCommandOutputMsg(context, message.messageId, reply); } else { TTAProtocolHandler.sendInputCommandAck(context, message.messageId, false, message.getParameter(ActionParameter.InOutString).toString()); } } break; case OutputMsg: if (outputHandler != null) { outputHandler.accept(context, message.getParameter(ActionParameter.InOutString).toString()); } break; default: // do nothing. } }; } }
92339a9d57a34da8ac447ad0a80a4335e9311ced
3,142
java
Java
radixdlt-core/radixdlt/src/main/java/com/radixdlt/statecomputer/EpochProofVerifier.java
GaryHalo/radixdlt
9d8a5554d8103ff00c7624c0f51f1893c867d3c3
[ "Apache-2.0" ]
null
null
null
radixdlt-core/radixdlt/src/main/java/com/radixdlt/statecomputer/EpochProofVerifier.java
GaryHalo/radixdlt
9d8a5554d8103ff00c7624c0f51f1893c867d3c3
[ "Apache-2.0" ]
null
null
null
radixdlt-core/radixdlt/src/main/java/com/radixdlt/statecomputer/EpochProofVerifier.java
GaryHalo/radixdlt
9d8a5554d8103ff00c7624c0f51f1893c867d3c3
[ "Apache-2.0" ]
null
null
null
34.527473
102
0.751114
996,635
/* * (C) Copyright 2021 Radix DLT Ltd * * Radix DLT Ltd 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.radixdlt.statecomputer; import com.google.inject.Inject; import com.radixdlt.atommodel.system.SystemParticle; import com.radixdlt.engine.BatchVerifier; import com.radixdlt.ledger.ByzantineQuorumException; /** * Validates that the LedgerProof matches the computed state output */ public final class EpochProofVerifier implements BatchVerifier<LedgerAndBFTProof> { private final ValidatorSetBuilder validatorSetBuilder; @Inject public EpochProofVerifier(ValidatorSetBuilder validatorSetBuilder) { this.validatorSetBuilder = validatorSetBuilder; } @Override public PerStateChangeVerifier<LedgerAndBFTProof> newVerifier(ComputedState computedState) { return new PerEpochVerifier(computedState); } private final class PerEpochVerifier implements PerStateChangeVerifier<LedgerAndBFTProof> { private final long epoch; private boolean epochChangeFlag = false; private PerEpochVerifier(ComputedState initState) { this.epoch = initState.get(SystemParticle.class).getEpoch(); } @Override public void test(ComputedState computedState) { if (epochChangeFlag) { throw new ByzantineQuorumException("Additional commands added to end of epoch."); } var systemParticle = computedState.get(SystemParticle.class); long nextEpoch = systemParticle.getEpoch(); if (nextEpoch > epoch) { epochChangeFlag = true; } } @Override public void testMetadata(LedgerAndBFTProof metadata, ComputedState computedState) { // Verify that output of radix engine and signed output match // TODO: Always follow radix engine as its a deeper source of truth and just mark validator // TODO: set as malicious (RPNV1-633) if (epochChangeFlag) { if (metadata == null) { throw new IllegalStateException(); } final var reNextValidatorSet = validatorSetBuilder.buildValidatorSet( computedState.get(RegisteredValidators.class), computedState.get(Stakes.class) ); final var signedValidatorSet = metadata.getProof().getNextValidatorSet() .orElseThrow(() -> new ByzantineQuorumException("RE has changed epochs but proofs don't show.")); if (!signedValidatorSet.equals(reNextValidatorSet)) { throw new ByzantineQuorumException("RE validator set does not agree with signed validator set"); } } else { if (metadata != null) { metadata.getProof().getNextValidatorSet().ifPresent(vset -> { throw new ByzantineQuorumException("RE validator set should not be present."); }); } } } } }
92339b39a3d2e20a9490161634476bfd3c5c4603
8,873
java
Java
src/main/java/com/wrmsr/wava/util/process/FinalizedProcess.java
wrmsr/wava
212df7feef680ba6ac9166186f05110367878b2f
[ "Apache-2.0" ]
18
2016-05-02T17:03:22.000Z
2020-01-23T08:33:46.000Z
src/main/java/com/wrmsr/wava/util/process/FinalizedProcess.java
wrmsr/wava
212df7feef680ba6ac9166186f05110367878b2f
[ "Apache-2.0" ]
1
2017-04-08T17:46:39.000Z
2018-03-03T10:41:26.000Z
src/main/java/com/wrmsr/wava/util/process/FinalizedProcess.java
wrmsr/wava
212df7feef680ba6ac9166186f05110367878b2f
[ "Apache-2.0" ]
1
2017-04-18T00:14:25.000Z
2017-04-18T00:14:25.000Z
33.23221
137
0.636538
996,636
/* * Copyright 2013 John Leacox * * 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.wrmsr.wava.util.process; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Set; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.TimeUnit; /** * A {@link Closeable} wrapper for {@link Process} for running a native process. * <p> * <p> * This wrapper provides some additional functionality around {@code Process} for some of the common pitfalls with using * {@code Process} directly. * <p> * <ul> * <p> * <li>It implements {@link Closeable}. The {@link #close()} method will make sure that all of the processes' streams * are closed, and if the {@code keepProcess} flag was not set, the process is destroyed via {@link Process#destroy()}.</li> * <p> * <li>It provides the {@link #waitFor(int)} method that invokes {@link Process#waitFor()} with a timeout period. If the * process execution takes longer than the timeout, then the thread is interrupted. This method also makes sure that the * thread interrupt flag is cleared</li> * <p> * </ul> * <p> * <p> * Here is a basic example of using this class: * <p> * <pre> * {@code * FinalizedProcessBuilder pb = new FinalizedProcessBuilder("myCommand", "myArg"); * FinalizedProcess process = pb.start(); * try { * int returnVal = process.waitFor(5000); * } finally { * process.close(); * }} * </pre> * <p> * <p> * If running on Java 7, try-with-resources can be used: * <p> * <pre> * {@code * FinalizedProcessBuilder pb = new FinalizedProcessBuilder("myCommand", "myArg"); * try (FinalizedProcess process = pb.start()) { * int returnVal = process.waitFor(5000); * }} * </pre> * * @author John Leacox * @see Process * @see FinalizedProcessBuilder * @see ProcessBuilder */ public class FinalizedProcess implements Closeable { private final Process process; private final boolean keepProcess; private final Set<StreamGobbler> streamGobblers; FinalizedProcess(Process process, boolean keepProcess, Set<StreamGobbler> streamGobblers) { if (process == null) { throw new NullPointerException("process: null"); } this.process = process; this.keepProcess = keepProcess; this.streamGobblers = streamGobblers; } /** * Kills the subprocess. The subprocess represented by this {@code FinalizedProcess} object is forcibly terminated. */ public void destroy() { process.destroy(); } /** * Returns the exit value for the subprocess. * * @return the exit value of the subprocess represented by this {@code FinalizedProcess} object. By convention, the * value {@code 0} indicates normal termination. * @throws IllegalThreadStateException if the subprocess represented by this {@code FinalizedProcess} object has not yet terminated */ public int exitValue() { return process.exitValue(); } /** * Returns the input stream connected to the error output of the subprocess. The stream obtains data piped from the * error output of the process represented by this {@code FinalizedProcess} object. * <p> * <p> * If the standard error of the subprocess has been redirected using * {@link FinalizedProcessBuilder#redirectErrorStream(boolean)} then this method will return a null input * stream</a>. * <p> * <p> * Implementation note: It is a good idea for the returned input stream to be buffered. * * @return the input stream connected to the error output of the subprocess */ public InputStream getErrorStream() { return process.getErrorStream(); } /** * Returns the input stream connected to the normal output of the subprocess. The stream obtains data piped from the * standard output of the process represented by this {@code FinalizedProcess} object. * <p> * <p> * If the standard error of the subprocess has been redirected using * {@link FinalizedProcessBuilder#redirectErrorStream(boolean)} then the input stream returned by this method will * receive the merged standard output and the standard error of the subprocess. * <p> * <p> * Implementation note: It is a good idea for the returned input stream to be buffered. * * @return the input stream connected to the normal output of the subprocess */ public InputStream getInputStream() { return process.getInputStream(); } /** * Returns the output stream connected to the normal input of the subprocess. Output to the stream is piped into the * standard input of the process represented by this {@code FinalizedProcess} object. * <p> * <p> * Implementation note: It is a good idea for the returned output stream to be buffered. * * @return the output stream connected to the normal input of the subprocess */ public OutputStream getOutputStream() { return process.getOutputStream(); } /** * Causes the current thread to wait, if necessary, until the process represented by this {@code FinalizedProcess} * object has terminated. This method returns immediately if the subprocess has already terminated. If the * subprocess has not yet terminated, the calling thread will be blocked until the subprocess exits. If the * subprocess execution takes longer than the specified {@code timeoutMilliseconds}, then the blocked thread will be * interrupted. * * @param timeoutMilliseconds time, in milliseconds, to wait on the subprocess blocking thread before timing out. (must be greater * than 0) * @return the exit value of the subprocess represented by this {@code Process} object. By convention, the value * {@code 0} indicates normal termination. * @throws IllegalArgumentException if timeoutMilliseconds is negative or zero. * @throws InterruptedException if the subprocess execution times out or the current thread is interrupted by another thread while it * is waiting. */ public int waitFor(long timeoutMilliseconds) throws InterruptedException { if (timeoutMilliseconds <= 0) { throw new IllegalArgumentException("timeoutMilliseconds: <= 0"); } Timer timer = new Timer(true); try { InterruptTimerTask interrupter = new InterruptTimerTask(Thread.currentThread()); timer.schedule(interrupter, timeoutMilliseconds); return process.waitFor(); } finally { timer.cancel(); Thread.interrupted(); } } public int waitFor(long time, TimeUnit unit) throws InterruptedException { return waitFor(TimeUnit.MILLISECONDS.convert(time, unit)); } @Override public void close() throws IOException { if (streamGobblers != null) { for (StreamGobbler gobbler : streamGobblers) { try { gobbler.close(); } catch (IOException e) { } } } if (process != null) { try { if (process.getErrorStream() != null) { process.getErrorStream().close(); } } catch (IOException e) { } try { if (process.getInputStream() != null) { process.getInputStream().close(); } } catch (IOException e) { } try { if (process.getOutputStream() != null) { process.getOutputStream().close(); } } catch (IOException e) { } if (!keepProcess) { process.destroy(); } } } private static class InterruptTimerTask extends TimerTask { private final Thread thread; public InterruptTimerTask(Thread t) { this.thread = t; } @Override public void run() { thread.interrupt(); } } }
92339c42531e6d6083d4a6377993a55c04193786
2,899
java
Java
AccountSystemTranslator/src/main/java/za/ac/nwu/accountsystem/translator/impl/AccountTypeTranslatorImpl.java
Tokoshima/discoveryvitality-api
2c9cf06373a7e500e80aaf5d0601238a14222c4c
[ "MIT" ]
null
null
null
AccountSystemTranslator/src/main/java/za/ac/nwu/accountsystem/translator/impl/AccountTypeTranslatorImpl.java
Tokoshima/discoveryvitality-api
2c9cf06373a7e500e80aaf5d0601238a14222c4c
[ "MIT" ]
null
null
null
AccountSystemTranslator/src/main/java/za/ac/nwu/accountsystem/translator/impl/AccountTypeTranslatorImpl.java
Tokoshima/discoveryvitality-api
2c9cf06373a7e500e80aaf5d0601238a14222c4c
[ "MIT" ]
null
null
null
34.105882
116
0.720248
996,637
package za.ac.nwu.accountsystem.translator.impl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import za.ac.nwu.accountsystem.domain.persistence.AccountType; import za.ac.nwu.accountsystem.domain.dto.AccountTypeDto; import za.ac.nwu.accountsystem.repo.persistence.AccountTypeRepository; import za.ac.nwu.accountsystem.translator.AccountTypeTranslator; import java.util.ArrayList; import java.util.List; @Component public class AccountTypeTranslatorImpl implements AccountTypeTranslator { private static final Logger LOGGER = LoggerFactory.getLogger(AccountTypeTranslatorImpl.class); private final AccountTypeRepository accountTypeRepository; @Autowired public AccountTypeTranslatorImpl(AccountTypeRepository accountTypeRepository){ this.accountTypeRepository = accountTypeRepository; } @Override public List<AccountTypeDto> getAllAccountTypes(){ List<AccountTypeDto> accountTypeDtos = new ArrayList<>(); try{ for (AccountType accountType: accountTypeRepository.findAll()){ accountTypeDtos.add(new AccountTypeDto(accountType)); } }catch (Exception e){ throw new RuntimeException("Unable to get All Account Types from DB",e); } return accountTypeDtos; } @Override public AccountTypeDto create(AccountTypeDto accountTypeDto){ try{ AccountType accountType = accountTypeRepository.save(accountTypeDto.getAccountType()); return new AccountTypeDto(accountType); }catch (Exception e){ throw new RuntimeException("Unable to get All Account Types from DB",e); } } @Override public AccountTypeDto getAccountTypeByMnemonic(String mnemonic){ try{ AccountType accountType = accountTypeRepository.getAccountTypeByMnemonic(mnemonic); LOGGER.info("ACCOUNT TYPE TRANSLATOR getAccountTypeByMnemonic : This is the acountType {}",accountType); return new AccountTypeDto(accountType); }catch (Exception e){ throw new RuntimeException("Unable to get Account Type from Mnemonic from DB",e); } } @Override public AccountTypeDto getAccountTypeByMnemonicNativeQuery(String mnemonic){ try{ AccountType accountType = accountTypeRepository.getAccountTypeMnemonicNativeQuery(mnemonic); return new AccountTypeDto(accountType); }catch (Exception e){ throw new RuntimeException("Unable to get Account Type form Mnemonic Native Query from DB",e); } } // @Override // public AccountTypeDto getAccountTypeDtoByMnemonic(String mnemonic){ // // return accountTypeRepository.getAccountTypeDtoByMnemonic(mnemonic); // } }
92339dfb1e48bd7f2c04d80184263a891980ab6f
3,704
java
Java
app/src/main/java/com/rozdoum/socialcomponents/adapters/SearchPostsAdapter.java
iplugx/chatapp
a4a263a7d7c555e24fa1b8dbc53aeed8cc2f921d
[ "Apache-2.0" ]
493
2017-05-31T08:56:19.000Z
2022-03-16T02:04:16.000Z
app/src/main/java/com/rozdoum/socialcomponents/adapters/SearchPostsAdapter.java
ankit1057/social-app-android
a4a263a7d7c555e24fa1b8dbc53aeed8cc2f921d
[ "Apache-2.0" ]
105
2017-04-11T10:51:04.000Z
2022-01-24T09:54:38.000Z
app/src/main/java/com/rozdoum/socialcomponents/adapters/SearchPostsAdapter.java
ankit1057/social-app-android
a4a263a7d7c555e24fa1b8dbc53aeed8cc2f921d
[ "Apache-2.0" ]
316
2017-04-20T15:03:53.000Z
2022-03-27T06:36:46.000Z
34.296296
96
0.669546
996,638
/* * Copyright 2017 Rozdoum * * 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.rozdoum.socialcomponents.adapters; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.rozdoum.socialcomponents.R; import com.rozdoum.socialcomponents.adapters.holders.PostViewHolder; import com.rozdoum.socialcomponents.controllers.LikeController; import com.rozdoum.socialcomponents.main.base.BaseActivity; import com.rozdoum.socialcomponents.model.Post; import java.util.List; public class SearchPostsAdapter extends BasePostsAdapter { public static final String TAG = SearchPostsAdapter.class.getSimpleName(); private CallBack callBack; public SearchPostsAdapter(final BaseActivity activity) { super(activity); } public void setCallBack(CallBack callBack) { this.callBack = callBack; } @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(parent.getContext()); View view = inflater.inflate(R.layout.post_item_list_view, parent, false); return new PostViewHolder(view, createOnClickListener(), activity, true); } private PostViewHolder.OnClickListener createOnClickListener() { return new PostViewHolder.OnClickListener() { @Override public void onItemClick(int position, View view) { if (callBack != null && callBack.enableClick()) { selectedPostPosition = position; callBack.onItemClick(getItemByPosition(position), view); } } @Override public void onLikeClick(LikeController likeController, int position) { if (callBack != null && callBack.enableClick()) { Post post = getItemByPosition(position); likeController.handleLikeClickAction(activity, post); } } @Override public void onAuthorClick(int position, View view) { if (callBack != null && callBack.enableClick()) { callBack.onAuthorClick(getItemByPosition(position).getAuthorId(), view); } } }; } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { ((PostViewHolder) holder).bindData(postList.get(position)); } public void setList(List<Post> list) { cleanSelectedPostInformation(); postList.clear(); postList.addAll(list); notifyDataSetChanged(); } public void removeSelectedPost() { if (selectedPostPosition != RecyclerView.NO_POSITION) { postList.remove(selectedPostPosition); notifyItemRemoved(selectedPostPosition); } } public interface CallBack { void onItemClick(Post post, View view); void onAuthorClick(String authorId, View view); boolean enableClick(); } }
92339eb59ac95b60e6596ff4cc116c4f6a7075b7
4,528
java
Java
src/main/java/com/matt/forgehax/util/spam/SpamEntry.java
MikelAx7/DonHack-Client
8a3daedec3502196ab87dec810ed285f72165e92
[ "MIT" ]
78
2020-11-26T23:37:38.000Z
2021-04-15T08:45:49.000Z
src/main/java/com/matt/forgehax/util/spam/SpamEntry.java
MikelAx7/DonHack-Client
8a3daedec3502196ab87dec810ed285f72165e92
[ "MIT" ]
1
2021-01-27T19:22:26.000Z
2021-01-27T19:22:26.000Z
src/main/java/com/matt/forgehax/util/spam/SpamEntry.java
MikelAx7/DonHack-Client
8a3daedec3502196ab87dec810ed285f72165e92
[ "MIT" ]
8
2020-06-09T03:40:48.000Z
2020-09-25T19:06:19.000Z
22.868687
84
0.641122
996,639
package com.matt.forgehax.util.spam; import com.google.common.collect.Lists; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.matt.forgehax.util.serialization.ISerializableJson; import java.util.Collections; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import joptsimple.internal.Strings; /** * Created on 7/18/2017 by fr1kin */ public class SpamEntry implements ISerializableJson { /** * A unique name used to identify this entry */ private final String name; /** * List of messages (no duplicates allowed) */ private final List<String> messages = Lists.newCopyOnWriteArrayList(); private boolean enabled = true; /** * Keyword that triggers this */ private String keyword = Strings.EMPTY; /** * How the message should be selected from the list */ private SpamType type = SpamType.RANDOM; /** * What should trigger a message from being outputted */ private SpamTrigger trigger = SpamTrigger.SPAM; /** * Custom delay */ private long delay = 0; public SpamEntry(String name) { this.name = name; } public void add(String msg) { if (!Strings.isNullOrEmpty(msg) && !messages.contains(msg)) { messages.add(msg); } } public void remove(String msg) { messages.remove(msg); } private int nextIndex = 0; public String next() { if (!messages.isEmpty()) { switch (type) { case RANDOM: return messages.get(ThreadLocalRandom.current().nextInt(messages.size())); case SEQUENTIAL: return messages.get((nextIndex++ % messages.size())); } } return Strings.EMPTY; } public void reset() { nextIndex = 0; } public boolean isEnabled() { return enabled; } public String getName() { return name; } public String getKeyword() { return keyword; } public SpamType getType() { return type; } public SpamTrigger getTrigger() { return trigger; } public List<String> getMessages() { return Collections.unmodifiableList(messages); } public long getDelay() { return delay; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public void setKeyword(String keyword) { this.keyword = keyword; } public void setType(SpamType type) { if (type != null) { this.type = type; } } public void setType(String type) { setType(SpamType.valueOf(type.toUpperCase())); } public void setTrigger(SpamTrigger trigger) { if (trigger != null) { this.trigger = trigger; } } public void setTrigger(String trigger) { setTrigger(SpamTrigger.valueOf(trigger.toUpperCase())); } public void setDelay(long delay) { this.delay = delay; } public boolean isEmpty() { return messages.isEmpty(); } @Override public void serialize(JsonObject in) { JsonObject add = new JsonObject(); add.addProperty("enabled", enabled); add.addProperty("keyword", keyword); add.addProperty("type", type.name()); add.addProperty("trigger", trigger.name()); add.addProperty("delay", getDelay()); JsonArray msgs = new JsonArray(); for (String msg : messages) msgs.add(msg); add.add("messages", msgs); in.add(name, add); } @Override public void deserialize(JsonObject in) { JsonObject from = in.getAsJsonObject(name); if (from == null) return; if (from.get("enabled") != null) setEnabled(from.get("enabled").getAsBoolean()); if (from.get("keyword") != null) setKeyword(from.get("keyword").getAsString()); if (from.get("type") != null) setType(from.get("type").getAsString()); if (from.get("trigger") != null) setTrigger(from.get("trigger").getAsString()); if (from.get("delay") != null) setDelay(from.get("delay").getAsLong()); if (from.get("messages") != null) { for (JsonElement e : from.getAsJsonArray("messages")) add(e.getAsString()); } } @Override public boolean equals(Object obj) { return (obj instanceof SpamEntry && String.CASE_INSENSITIVE_ORDER.compare(name, ((SpamEntry) obj).name) == 0) || (obj instanceof String && String.CASE_INSENSITIVE_ORDER.compare(name, (String) obj) == 0); } @Override public int hashCode() { return name.toLowerCase().hashCode(); } @Override public String toString() { return name; } }
92339fdd9864137fb88a889970e358f0ee8892f5
2,612
java
Java
drivers/src/test/scriptella/driver/csv/CsvFormattingITest.java
lstefek/scriptella-etl
c9b3beb4e313753071ca9b596e4626c21dbd8649
[ "Apache-2.0" ]
100
2015-02-05T00:01:53.000Z
2022-03-21T07:01:41.000Z
drivers/src/test/scriptella/driver/csv/CsvFormattingITest.java
lstefek/scriptella-etl
c9b3beb4e313753071ca9b596e4626c21dbd8649
[ "Apache-2.0" ]
31
2015-02-05T00:36:20.000Z
2022-02-14T22:42:21.000Z
drivers/src/test/scriptella/driver/csv/CsvFormattingITest.java
lstefek/scriptella-etl
c9b3beb4e313753071ca9b596e4626c21dbd8649
[ "Apache-2.0" ]
48
2015-01-05T06:42:19.000Z
2021-10-05T20:19:32.000Z
39.575758
118
0.630934
996,640
/* * Copyright 2006-2012 The Scriptella Project Team. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package scriptella.driver.csv; import scriptella.DBTestCase; import scriptella.execution.EtlExecutor; import scriptella.execution.EtlExecutorException; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; /** * Tests CSV column formatting. * * @author Fyodor Kupolov * @version 1.1 */ public class CsvFormattingITest extends DBTestCase { public void test() throws EtlExecutorException { getConnection("csv");//Call just to close the DB final ByteArrayOutputStream out = new ByteArrayOutputStream(); testURLHandler = new TestURLHandler() { public InputStream getInputStream(final URL u) { return new ByteArrayInputStream(("Id,Text,TextNoTrim, DateCol, NumCol" + "\n10,Ten,Ten,12-07-2012 10:00,10.1" + "\n11, Eleven , Eleven , 12-07-2012 11:00, 11.1").getBytes()); } public OutputStream getOutputStream(final URL u) { return out; } public int getContentLength(final URL u) { throw new UnsupportedOperationException(); } }; final EtlExecutor se = newEtlExecutor(); se.execute(); //The last number is left padded(width 6) String expectedResult = "1,One,One,11-07-2012 22:33, 1.10\n" + "2,Two, Two ,11-07-2012 20:00, 2.10\n" + "3,Three, Three ,11-07-2012 20:00, 3.10\n" + //The last 2 are imported from CSV to db and exported back to CSV //The leading whitespaces for TextNoTrim is lost, because input was trimmed when read by a CSV driver "10,Ten,Ten,12-07-2012 10:00, 10.10\n" + "11,Eleven,Eleven,12-07-2012 11:00, 11.10\n"; assertEquals(expectedResult, out.toString()); } }
9233a0e202001a4cacf6c092f2b5be629aafda85
29,686
java
Java
app/src/main/java/com/telenav/osv/db/SequenceDB.java
openstreetcam/android
66eb0ee1ab093562e2867087084b26803fe58174
[ "MIT" ]
71
2017-01-15T07:52:21.000Z
2020-11-24T11:15:21.000Z
app/src/main/java/com/telenav/osv/db/SequenceDB.java
openstreetcam/android
66eb0ee1ab093562e2867087084b26803fe58174
[ "MIT" ]
104
2017-01-06T18:22:47.000Z
2020-11-23T00:12:59.000Z
app/src/main/java/com/telenav/osv/db/SequenceDB.java
openstreetcam/android
66eb0ee1ab093562e2867087084b26803fe58174
[ "MIT" ]
21
2017-01-20T20:20:04.000Z
2020-11-21T07:28:33.000Z
43.023188
148
0.587583
996,641
package com.telenav.osv.db; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.DatabaseUtils; import android.database.sqlite.SQLiteCantOpenDatabaseException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteException; import com.telenav.osv.item.LocalSequence; import com.telenav.osv.item.OSVFile; import com.telenav.osv.utils.Log; import com.telenav.osv.utils.Utils; /** * The DataBase of the OSV sequences * Created by Kalman on 10/7/2015. */ @SuppressWarnings("ResultOfMethodCallIgnored") public class SequenceDB { public final static String FRAME_SEQ_INDEX = "sequenceIndex"; public final static String FRAME_FILE_PATH = "filePath"; public final static String FRAME_LAT = "latitude"; public final static String FRAME_LON = "longitude"; public final static String FRAME_ACCURACY = "accuracy"; public final static String SEQUENCE_ID = "sequenceId"; public final static String SEQUENCE_LAT = "latitude"; public final static String SEQUENCE_LON = "longitude"; public final static String SEQUENCE_PATH = "thumb"; public final static String SEQUENCE_EXTERNAL = "external"; public static final String SEQUENCE_SAFE = "safe"; public final static String VIDEO_INDEX = "videoIndex"; // ------------------------------------------------------------- public final static String VIDEO_FILE_PATH = "filePath"; public final static String VIDEO_FRAME_COUNT = "count"; public final static String SCORE_COVERAGE = "coverage"; public final static String SCORE_OBD_COUNT = "obdCount"; public final static String SCORE_COUNT = "count"; /** * Name of the only table, containing photo details */ final static String FRAME_TABLE = "Frame"; final static String FRAME_SEQ_ID = "sequenceId"; final static String FRAME_VIDEO_ID = "videoId"; final static String FRAME_ORIENTATION = "orientation"; static final String FRAME_UNIQUE_CONSTRAINT = "uniqueConstraint"; static final String VIDEO_UNIQUE_CONSTRAINT = "uniqueConstraint"; static final String SCORE_UNIQUE_CONSTRAINT = "scoreUniqueConstraint"; static final String SEQUENCE_TABLE = "Sequence"; final static String SEQUENCE_ONLINE_ID = "onlineSequenceId"; final static String SEQUENCE_COUNT = "count"; // --------------------------------------------------------------- final static String SEQUENCE_ORIG_COUNT = "origCount"; final static String SEQUENCE_VIDEO_COUNT = "videoCount"; final static String SEQUENCE_PANO = "panorama"; final static String SEQUENCE_VERSION = "version"; static final String SEQUENCE_OBD = "obd"; // --------------------------------------------------------------- static final String SEQUENCE_STATUS = "status"; final static String VIDEO_TABLE = "Video"; final static String VIDEO_SEQ_ID = "sequenceId"; final static String SCORE_TABLE = "Score"; final static String SCORE_SEQ_ID = "sequenceId"; // --------------------------------------------------------------- private static final String TAG = "SequenceDB"; public static SequenceDB instance; private SQLiteDatabase database; /** * @param context context */ private SequenceDB(Context context) { SequenceDBHelper dbHelper = new SequenceDBHelper(context); try { database = dbHelper.getWritableDatabase(); } catch (SQLiteCantOpenDatabaseException e) { Log.d(TAG, "SequenceDB: " + e.getLocalizedMessage()); } SequenceDB.instance = this; } public static void instantiate(Context context) { if (instance == null) { SequenceDB.instance = new SequenceDB(context); } } public void insertVideoIfNotAdded(int seqId, int videoIndex, String filePath) { if (!isVideoAdded(seqId, videoIndex)) { ContentValues values = new ContentValues(); values.put(VIDEO_SEQ_ID, seqId); values.put(VIDEO_INDEX, videoIndex); values.put(VIDEO_FILE_PATH, filePath); values.put(VIDEO_FRAME_COUNT, -1); database.insert(VIDEO_TABLE, null, values); } } // public long insertVideo(int seqId, int videoIndex, String filePath) { // ContentValues values = new ContentValues(); // values.put(VIDEO_SEQ_ID, seqId); // values.put(VIDEO_INDEX, videoIndex); // values.put(VIDEO_FILE_PATH, filePath); // values.put(VIDEO_FRAME_COUNT, -1); // return database.insertOrThrow(VIDEO_TABLE, null, values); // } public void insertPhoto(int seqId, int videoIndex, int seqIndex, String filePath, double lat, double lon, float accuracy, int orientation) { ContentValues values = new ContentValues(); values.put(FRAME_SEQ_ID, seqId); values.put(FRAME_VIDEO_ID, videoIndex); values.put(FRAME_SEQ_INDEX, seqIndex); values.put(FRAME_FILE_PATH, filePath); values.put(FRAME_LAT, lat); values.put(FRAME_LON, lon); values.put(FRAME_ACCURACY, accuracy); values.put(FRAME_ORIENTATION, orientation); database.insertOrThrow(FRAME_TABLE, null, values); } public void insertScore(int seqId, boolean obd, int coverage) { String countColumn = (obd ? SCORE_OBD_COUNT : SCORE_COUNT); ContentValues values = new ContentValues(); if (!isScoreRowAdded(seqId, coverage)) { values.put(SCORE_SEQ_ID, seqId); values.put(SCORE_COVERAGE, coverage); values.put(countColumn, 1); database.insertOrThrow(SCORE_TABLE, null, values); } else { database.execSQL( "UPDATE " + SCORE_TABLE + " SET " + countColumn + " = " + countColumn + " + 1 " + "WHERE " + SCORE_SEQ_ID + " = " + seqId + " AND " + SCORE_COVERAGE + " = " + coverage); } } public Cursor getAllSequences() { try { String[] cols = new String[]{SEQUENCE_ID, SEQUENCE_ONLINE_ID, SEQUENCE_LAT, SEQUENCE_LON, SEQUENCE_PATH, SEQUENCE_COUNT, SEQUENCE_ORIG_COUNT, SEQUENCE_VIDEO_COUNT, SEQUENCE_PANO, SEQUENCE_EXTERNAL, SEQUENCE_VERSION, SEQUENCE_OBD, SEQUENCE_SAFE, SEQUENCE_STATUS}; Cursor mCursor = database.query(true, SEQUENCE_TABLE, cols, null, null, SEQUENCE_ID, null, null, null); if (mCursor != null && mCursor.getCount() > 0) { mCursor.moveToFirst(); } return mCursor; } catch (SQLiteException e) { if (e.getLocalizedMessage().contains("no such column") && e.getLocalizedMessage().contains("status")) { database.execSQL("ALTER TABLE " + SequenceDB.SEQUENCE_TABLE + " ADD COLUMN " + SequenceDB.SEQUENCE_STATUS + " int"); } } //retry String[] cols = new String[]{SEQUENCE_ID, SEQUENCE_ONLINE_ID, SEQUENCE_LAT, SEQUENCE_LON, SEQUENCE_PATH, SEQUENCE_COUNT, SEQUENCE_ORIG_COUNT, SEQUENCE_VIDEO_COUNT, SEQUENCE_PANO, SEQUENCE_EXTERNAL, SEQUENCE_VERSION, SEQUENCE_OBD, SEQUENCE_SAFE, SEQUENCE_STATUS}; Cursor mCursor = database.query(true, SEQUENCE_TABLE, cols, null, null, SEQUENCE_ID, null, null, null); if (mCursor != null && mCursor.getCount() > 0) { mCursor.moveToFirst(); } return mCursor; } public boolean checkSequenceExists(int sequenceId) { return DatabaseUtils.queryNumEntries(database, SEQUENCE_TABLE, SEQUENCE_ID + " = ?", new String[]{"" + sequenceId}) > 0; } public Cursor getFrames(int sequenceId) { String[] cols = new String[]{FRAME_SEQ_ID, FRAME_VIDEO_ID, FRAME_VIDEO_ID, FRAME_SEQ_INDEX, FRAME_FILE_PATH, FRAME_LAT, FRAME_LON, FRAME_ACCURACY, FRAME_ORIENTATION}; Cursor mCursor = database.query(true, FRAME_TABLE, cols, FRAME_SEQ_ID + " = ?", new String[]{"" + sequenceId}, null, null, null, null); if (mCursor != null && mCursor.getCount() > 0) { mCursor.moveToFirst(); } return mCursor; // iterate to get each value. } public Cursor getVideos(int sequenceId) { String[] cols = new String[]{VIDEO_SEQ_ID, VIDEO_INDEX, VIDEO_FILE_PATH, VIDEO_FRAME_COUNT}; Cursor mCursor = database.query(true, VIDEO_TABLE, cols, VIDEO_SEQ_ID + " = ?", new String[]{"" + sequenceId}, null, null, null, null); if (mCursor != null && mCursor.getCount() > 0) { mCursor.moveToFirst(); } return mCursor; // iterate to get each value. } public long getNumberOfFrames(int localSequenceId) { return DatabaseUtils.queryNumEntries(database, FRAME_TABLE, FRAME_SEQ_ID + "=?", new String[]{"" + localSequenceId}); } // public Cursor getAllFrames() { // String[] cols = new String[]{FRAME_SEQ_ID, FRAME_VIDEO_ID, FRAME_SEQ_INDEX, FRAME_FILE_PATH, FRAME_LAT, FRAME_LON, // FRAME_ACCURACY, FRAME_ORIENTATION}; // Cursor mCursor = database.query(true, FRAME_TABLE, cols, null // , null, null, null, null, null); // if (mCursor != null && mCursor.getCount() > 0) { // mCursor.moveToFirst(); // } // return mCursor; // iterate to get each value. // } public long getNumberOfVideos(int localSequenceId) { return DatabaseUtils.queryNumEntries(database, VIDEO_TABLE, VIDEO_SEQ_ID + "=?", new String[]{"" + localSequenceId}); } // public long getNumberOfFrames() { // return DatabaseUtils.queryNumEntries(database, FRAME_TABLE); // } public int getOriginalFrameCount(int sequenceId) { String[] cols = new String[]{SEQUENCE_ORIG_COUNT}; Cursor mCursor = database.query(true, SEQUENCE_TABLE, cols, SEQUENCE_ID + " = ?", new String[]{"" + sequenceId}, null, null, null, null); if (mCursor != null && mCursor.getCount() > 0) { mCursor.moveToFirst(); int res = mCursor.getInt(mCursor.getColumnIndex(SEQUENCE_ORIG_COUNT)); mCursor.close(); return res; } if (mCursor != null) { mCursor.close(); } return 0; } public int updateSequenceOnlineId(int sequenceId, int onlineSequenceId) { ContentValues cv = new ContentValues(); cv.put(SEQUENCE_ONLINE_ID, onlineSequenceId); return database.update(SEQUENCE_TABLE, cv, SEQUENCE_ID + " = ? AND " + SEQUENCE_ONLINE_ID + " = -1", new String[]{"" + sequenceId}); } public void updateSequenceLocation(int sequenceId, double lat, double lon) { ContentValues cv = new ContentValues(); cv.put(SEQUENCE_LAT, lat); cv.put(SEQUENCE_LON, lon); database.update(SEQUENCE_TABLE, cv, SEQUENCE_ID + " = ?", new String[]{"" + sequenceId}); } public void updateSequenceFrameCount(int sequenceId) { ContentValues cv = new ContentValues(); int imageCount = (int) getNumberOfFrames(sequenceId); int originalCount = getOriginalFrameCount(sequenceId); cv.put(SEQUENCE_COUNT, imageCount); if (originalCount < imageCount) { cv.put(SEQUENCE_ORIG_COUNT, imageCount); } else { if (imageCount != originalCount) { cv.put(SEQUENCE_STATUS, LocalSequence.STATUS_INTERRUPTED); } else if (imageCount != 0) { cv.put(SEQUENCE_STATUS, LocalSequence.STATUS_NEW); } } database.update(SEQUENCE_TABLE, cv, SEQUENCE_ID + " = ?", new String[]{"" + sequenceId}); Cursor videos = getVideos(sequenceId); while (videos != null && videos.getCount() > 0 && !videos.isAfterLast()) { int index = videos.getInt(videos.getColumnIndex(VIDEO_INDEX)); int count = (int) countVideoFrames(sequenceId, index); cv = new ContentValues(); cv.put(VIDEO_FRAME_COUNT, count); database.update(VIDEO_TABLE, cv, VIDEO_SEQ_ID + " = ? AND " + VIDEO_INDEX + " = ?", new String[]{"" + sequenceId, "" + index}); videos.moveToNext(); } if (videos != null) { videos.close(); } } // public long getVideoFrameCount(int localSequenceId, int videoIndex) { // String[] cols = new String[]{VIDEO_FRAME_COUNT}; // Cursor mCursor = database.query(true, VIDEO_TABLE, cols, VIDEO_SEQ_ID + " = ? AND " + VIDEO_INDEX + " = ?" // , new String[]{"" + localSequenceId, "" + videoIndex}, null, null, null, null); // if (mCursor != null && mCursor.getCount() > 0) { // mCursor.moveToFirst(); // int res = mCursor.getInt(mCursor.getColumnIndex(VIDEO_FRAME_COUNT)); // mCursor.close(); // return res; // } // if (mCursor != null) { // mCursor.close(); // } // return 0; // } /** * @param sequenceIdLocal sequence id * @param videoIndex startIndex of the video * @return if deleted */ public int deleteVideo(int sequenceIdLocal, int videoIndex) { int res = database .delete(FRAME_TABLE, FRAME_SEQ_ID + " = ? AND " + FRAME_VIDEO_ID + " = ?", new String[]{"" + sequenceIdLocal, "" + videoIndex}); res = res + database .delete(VIDEO_TABLE, VIDEO_SEQ_ID + " = ? AND " + VIDEO_INDEX + " = ?", new String[]{"" + sequenceIdLocal, "" + videoIndex}); return res; } public int resetOnlineSequenceId(int onlineSequenceId) { ContentValues cv = new ContentValues(); cv.put(SEQUENCE_ONLINE_ID, "-1"); return database.update(SEQUENCE_TABLE, cv, SEQUENCE_ONLINE_ID + " = ?", new String[]{"" + onlineSequenceId}); } public void deleteRecords(int sequenceIdLocal) { database.delete(FRAME_TABLE, FRAME_SEQ_ID + " = ?", new String[]{"" + sequenceIdLocal}); database.delete(VIDEO_TABLE, VIDEO_SEQ_ID + " = ?", new String[]{"" + sequenceIdLocal}); database.delete(SCORE_TABLE, SCORE_SEQ_ID + " = ?", new String[]{"" + sequenceIdLocal}); database.delete(SEQUENCE_TABLE, SEQUENCE_ID + " = ?", new String[]{"" + sequenceIdLocal}); } @SuppressWarnings("SameParameterValue") public LocalSequence createNewSequence(Context context, double lat, double lon, boolean pano, boolean external, String version, boolean obd, boolean safe) { OSVFile osv = Utils.generateOSVFolder(context); int i = 0; int limit = 100; while (limit > 0) { OSVFile file = new OSVFile(osv.getPath(), "/SEQ_" + i); if (!file.exists()) { if (!checkSequenceExists(i)) { boolean result = file.mkdir(); if (result && file.exists()) { insertSequence(i, lat, lon, file.getPath(), pano, external, version, obd, safe); return new LocalSequence(file); } else { Log.d(TAG, "createNewSequence: could not create directory " + file.getAbsolutePath()); } limit--; } } i++; } return null; } /** * deletes the image, deletes the parent folder if it remains empty * @param video video * @param sequenceIdLocal sequence id * @param sequenceIndex index */ public void deleteVideo(OSVFile video, int sequenceIdLocal, int sequenceIndex) { int result = deleteVideo(sequenceIdLocal, sequenceIndex); if (result == 0) { Log.w(TAG, "deleteVideo: No records deleted, no records found with sequenceId: " + sequenceIdLocal + " and sequenceIndex: " + sequenceIndex); } if (!video.delete()) { Log.w(TAG, "deleteVideo: delete unsuccessful: " + video.getName()); } } /** * deletes the image, deletes the parent folder if it remains empty * @param photo photo * @param sequenceIdLocal sequence id * @param sequenceIndex index */ public void deletePhoto(OSVFile photo, int sequenceIdLocal, int sequenceIndex) { int result = deletePhoto(sequenceIdLocal, sequenceIndex); if (result == 0) { Log.w(TAG, "deletePhoto: No records deleted, no records found with sequenceId: " + sequenceIdLocal + " and sequenceIndex: " + sequenceIndex); } if (!photo.delete()) { Log.w(TAG, "deletePhoto: delete unsuccessful: " + photo.getName()); } } public void consistencyCheck(Context context) { try { Cursor cur = getAllSequences(); cur.close(); } catch (SQLiteException e) { if (e.getLocalizedMessage().contains("no such column") && e.getLocalizedMessage().contains("status")) { database.execSQL("ALTER TABLE " + SequenceDB.SEQUENCE_TABLE + " ADD COLUMN " + SequenceDB.SEQUENCE_STATUS + " int"); } } Cursor sequences = getAllSequences(); while (sequences != null && sequences.getCount() > 0 && !sequences.isAfterLast()) { int id = sequences.getInt(sequences.getColumnIndex(SEQUENCE_ID)); updateSequenceFrameCount(id); if (getNumberOfFrames(id) <= 0) { int res = deleteSequenceRecord(id); res = res + deleteVideoRecord(id); Log.d(TAG, "consistencyCheck: deleted sequence with 0 items, id = " + sequences.getInt(sequences.getColumnIndex(SEQUENCE_ID)) + ", result = " + res); } sequences.moveToNext(); } if (sequences != null) { sequences.close(); } Cursor cursor = getAllVideos(); if (cursor.getCount() > 0) { while (!cursor.isAfterLast()) { String path = cursor.getString(cursor.getColumnIndex(VIDEO_FILE_PATH)); OSVFile file = new OSVFile(path); int sequenceId = cursor.getInt(cursor.getColumnIndex(VIDEO_SEQ_ID)); int index = cursor.getInt(cursor.getColumnIndex(VIDEO_INDEX)); // double lat = cursor.getDouble(cursor.getColumnIndex(VIDEO_FRAME_COUNT)); // double lon = cursor.getDouble(cursor.getColumnIndex(VIDEO_LON)); // float accuracy = cursor.getFloat(cursor.getColumnIndex(VIDEO_ACCURACY)); // int orientation = cursor.getInt(cursor.getColumnIndex(VIDEO_ORIENTATION)); //// int fileindex = ImageFile.getImageIndex(file); // if (file.exists() && fileIndex != fileindex && fileindex != -1) { // deleteVideo(sequenceId, fileIndex); // try { // insertPhoto(sequenceId, fileindex, file.getPath(), lat, lon, accuracy, orientation); // } catch (Exception e) { // Log.d(TAG, "consistencyCheck: " + Log.getStackTraceString(e)); // } // } if (file.exists() && Utils.fileSize(file) < 1000) { file.delete(); } if (!file.exists()) { deleteVideo(sequenceId, index); if (getNumberOfFrames(sequenceId) <= 0) { deleteSequenceRecord(sequenceId); } } cursor.moveToNext(); } } cursor.close(); OSVFile osv = Utils.generateOSVFolder(context); for (OSVFile sequence : osv.listFiles()) { int id = LocalSequence.getSequenceId(sequence); if (getNumberOfFrames(id) <= 0 && getNumberOfVideos(id) <= 0) { sequence.delete(); } } interruptUploading(); fixStatuses(); } public boolean isOBDSequence(int sequenceId) { return DatabaseUtils .queryNumEntries(database, SEQUENCE_TABLE, SEQUENCE_ID + " = ? AND " + SEQUENCE_OBD + " > 0", new String[]{"" + sequenceId}) > 0; } public int getOnlineId(int sequenceId) { String[] cols = new String[]{SEQUENCE_ID, SEQUENCE_ONLINE_ID}; Cursor mCursor = database.query(true, SEQUENCE_TABLE, cols, SEQUENCE_ID + " = ?", new String[]{"" + sequenceId}, null, null, null, null); if (mCursor != null && mCursor.getCount() > 0) { mCursor.moveToFirst(); int val = mCursor.getInt(mCursor.getColumnIndex(SEQUENCE_ONLINE_ID)); mCursor.close(); return val; } if (mCursor != null) { mCursor.close(); } return -1; } @SuppressWarnings("SameParameterValue") public void setOBDForSequence(int sequenceId, boolean obd) { ContentValues cv = new ContentValues(); cv.put(SEQUENCE_OBD, obd); database.update(SEQUENCE_TABLE, cv, SEQUENCE_ID + " = ?", new String[]{"" + sequenceId}); } public int getStatus(int sequenceId) { String[] cols = new String[]{SEQUENCE_STATUS}; Cursor mCursor = database.query(true, SEQUENCE_TABLE, cols, SEQUENCE_ID + " = ?", new String[]{"" + sequenceId}, null, null, null, null); if (mCursor != null && mCursor.getCount() > 0) { mCursor.moveToFirst(); int res = mCursor.getInt(mCursor.getColumnIndex(SEQUENCE_STATUS)); mCursor.close(); return res; } if (mCursor != null) { mCursor.close(); } return -1; } public void interruptUploading() { ContentValues cv = new ContentValues(); cv.put(SEQUENCE_STATUS, LocalSequence.STATUS_INTERRUPTED); int res = database.update(SEQUENCE_TABLE, cv, SEQUENCE_STATUS + " = ?", new String[]{"" + LocalSequence.STATUS_UPLOADING}); Log.d(TAG, "interruptUploading: number of reset UPLOADING statuses = " + res); cv.clear(); cv.put(SEQUENCE_STATUS, LocalSequence.STATUS_NEW); res = database.update(SEQUENCE_TABLE, cv, SEQUENCE_STATUS + " = ?", new String[]{"" + LocalSequence.STATUS_INDEXING}); Log.d(TAG, "interruptUploading: number of reset INDEXING statuses = " + res); } public void setStatus(int sequenceId, int status) { ContentValues cv = new ContentValues(); cv.put(SEQUENCE_STATUS, status); database.update(SEQUENCE_TABLE, cv, SEQUENCE_ID + " = ?", new String[]{"" + sequenceId}); } public void fixStatuses() { ContentValues cv = new ContentValues(); Cursor sequences = getAllSequences(); while (sequences != null && sequences.getCount() > 0 && !sequences.isAfterLast()) { cv.clear(); int sequenceId = sequences.getInt(sequences.getColumnIndex(SEQUENCE_ID)); int status = sequences.getInt(sequences.getColumnIndex(SEQUENCE_STATUS)); int imageCount = (int) getNumberOfFrames(sequenceId); int originalCount = getOriginalFrameCount(sequenceId); boolean untouched = imageCount > 0 && (imageCount == originalCount || Math.abs(imageCount - originalCount) < 10); if (untouched) { if (status != LocalSequence.STATUS_NEW) { cv.put(SEQUENCE_STATUS, LocalSequence.STATUS_NEW); Log.d(TAG, "fixStatuses: setting NEW"); } } else { cv.put(SEQUENCE_STATUS, LocalSequence.STATUS_INTERRUPTED); Log.d(TAG, "fixStatuses: setting INTERRUPTED"); } if (cv.size() > 0) { database.update(SEQUENCE_TABLE, cv, SEQUENCE_ID + " = ?", new String[]{"" + sequenceId}); } sequences.moveToNext(); } if (sequences != null) { sequences.close(); } } public String getSequenceVersion(int sequenceId) { String[] cols = new String[]{SEQUENCE_VERSION}; Cursor mCursor = database.query(true, SEQUENCE_TABLE, cols, SEQUENCE_ID + " = ?", new String[]{"" + sequenceId}, null, null, null, null); try { if (mCursor != null && mCursor.getCount() > 0) { mCursor.moveToFirst(); String res = mCursor.getString(mCursor.getColumnIndex(SEQUENCE_VERSION)); mCursor.close(); return res; } if (mCursor != null) { mCursor.close(); } } catch (Exception e) { Log.d(TAG, "getSequenceVersion: " + Log.getStackTraceString(e)); } if (mCursor != null) { mCursor.close(); } return ""; } // public void deleteHistory() { // Cursor sequences = getAllSequences(); // while (sequences != null && sequences.getCount() > 0 && !sequences.isAfterLast()) { // int id = sequences.getInt(sequences.getColumnIndex(SEQUENCE_ID)); // updateSequenceFrameCount(id); // if (getNumberOfFrames(id) <= 0) { // int res = deleteSequenceRecord(id); // res = res + deleteVideoRecord(id); // Log.d(TAG, "deleteHistory: deleted sequence with 0 items, id = " + sequences.getInt(sequences.getColumnIndex // (SEQUENCE_ID)) + ", result = " + res); // } // sequences.moveToNext(); // } // if (sequences != null) { // sequences.close(); // } // fixStatuses(); // } public Cursor getScores(int sequenceId) { String[] cols = new String[]{SCORE_COVERAGE, SCORE_OBD_COUNT, SCORE_COUNT}; Cursor mCursor = database.query(false, SCORE_TABLE, cols, SCORE_SEQ_ID + " = ?", new String[]{"" + sequenceId}, null, null, null, null); if (mCursor != null && mCursor.getCount() > 0) { mCursor.moveToFirst(); } return mCursor; } public boolean isSequenceSafe(int sequenceId) { return DatabaseUtils .queryNumEntries(database, SEQUENCE_TABLE, SEQUENCE_ID + " = ? AND " + SEQUENCE_SAFE + " > 0", new String[]{"" + sequenceId}) > 0; } private void insertSequence(int seqId, double lat, double lon, String path, boolean pano, boolean external, String version, boolean obd, boolean safe) { ContentValues values = new ContentValues(); values.put(SEQUENCE_ID, seqId); values.put(SEQUENCE_ONLINE_ID, -1); values.put(SEQUENCE_LAT, lat); values.put(SEQUENCE_LON, lon); values.put(SEQUENCE_PATH, path); values.put(SEQUENCE_COUNT, -1); values.put(SEQUENCE_ORIG_COUNT, -1); values.put(SEQUENCE_VIDEO_COUNT, -1); values.put(SEQUENCE_PANO, pano); values.put(SEQUENCE_EXTERNAL, external); values.put(SEQUENCE_VERSION, version); values.put(SEQUENCE_OBD, obd); values.put(SEQUENCE_SAFE, safe); values.put(SEQUENCE_STATUS, LocalSequence.STATUS_NEW); database.insertOrThrow(SEQUENCE_TABLE, null, values); } private Cursor getAllVideos() { String[] cols = new String[]{VIDEO_SEQ_ID, VIDEO_FILE_PATH, VIDEO_FRAME_COUNT, VIDEO_INDEX}; Cursor mCursor = database.query(true, VIDEO_TABLE, cols, null, null, null, null, null, null); if (mCursor != null && mCursor.getCount() > 0) { mCursor.moveToFirst(); } return mCursor; // iterate to get each value. } private boolean isVideoAdded(int localSequenceId, int videoIndex) { return DatabaseUtils.queryNumEntries(database, VIDEO_TABLE, VIDEO_SEQ_ID + "=? AND " + VIDEO_INDEX + "=?", new String[]{"" + localSequenceId, "" + videoIndex}) > 0; } private boolean isScoreRowAdded(int localSequenceId, int coverage) { return DatabaseUtils.queryNumEntries(database, SCORE_TABLE, SCORE_SEQ_ID + "=? AND " + SCORE_COVERAGE + "=?", new String[]{"" + localSequenceId, "" + coverage}) > 0; } private long countVideoFrames(int localSequenceId, int videoIndex) { return DatabaseUtils.queryNumEntries(database, FRAME_TABLE, FRAME_SEQ_ID + " = ? AND " + FRAME_VIDEO_ID + " = ?", new String[]{"" + localSequenceId, "" + videoIndex}); } private int deleteSequenceRecord(int sequenceId) { return database.delete(SEQUENCE_TABLE, SEQUENCE_ID + " = ?", new String[]{"" + sequenceId}); } private int deleteVideoRecord(int sequenceId) { return database.delete(VIDEO_TABLE, VIDEO_SEQ_ID + " = ?", new String[]{"" + sequenceId}); } /** * @param sequenceIdLocal sequence id * @param photoIndex startIndex of the video * @return if done */ private int deletePhoto(int sequenceIdLocal, int photoIndex) { return database .delete(FRAME_TABLE, FRAME_SEQ_ID + " = ? AND " + FRAME_SEQ_INDEX + " = ?", new String[]{"" + sequenceIdLocal, "" + photoIndex}); } }
9233a110c118f8bdbae235b5c4ab3a0d8365ad16
776
java
Java
gwt-tabulator/src/main/java/com/peruncs/gwt/tabulator/Tooltip.java
peruncs/gwt
1dd25d81615f0b44859da9321eb8f930aa13ff20
[ "Apache-2.0" ]
15
2017-04-28T01:43:07.000Z
2021-09-28T21:22:29.000Z
gwt-tabulator/src/main/java/com/peruncs/gwt/tabulator/Tooltip.java
peruncs/gwt
1dd25d81615f0b44859da9321eb8f930aa13ff20
[ "Apache-2.0" ]
1
2021-04-30T09:24:11.000Z
2021-05-02T23:08:54.000Z
gwt-tabulator/src/main/java/com/peruncs/gwt/tabulator/Tooltip.java
peruncs/gwt
1dd25d81615f0b44859da9321eb8f930aa13ff20
[ "Apache-2.0" ]
null
null
null
22.823529
77
0.693299
996,642
package com.peruncs.gwt.tabulator; import com.peruncs.gwt.utils.CallbackRet1; import jsinterop.annotations.JsOverlay; import jsinterop.annotations.JsPackage; import jsinterop.annotations.JsType; import jsinterop.base.Js; @JsType(isNative = true, name = "?", namespace = JsPackage.GLOBAL) public interface Tooltip { @JsOverlay static Tooltip disable() { return Js.cast(false); } @JsOverlay static Tooltip of(String tooltip) { return Js.cast(tooltip); } /** * a callback function that returns the string for the cell * @param toolTipGenerator * @return tooltip */ @JsOverlay static Tooltip of(CallbackRet1<String, CellComponent> toolTipGenerator) { return Js.cast(toolTipGenerator); } }
9233a18b172d1c813ed6a515c87dd4ed5774f50b
350
java
Java
src/com/aritu/java/eu/text/BasqueDecimalFormatSymbols.java
aritu/aritu-java-eu
46034653dc6661965aa6b99d10989ec9fa34dd09
[ "Apache-2.0" ]
null
null
null
src/com/aritu/java/eu/text/BasqueDecimalFormatSymbols.java
aritu/aritu-java-eu
46034653dc6661965aa6b99d10989ec9fa34dd09
[ "Apache-2.0" ]
null
null
null
src/com/aritu/java/eu/text/BasqueDecimalFormatSymbols.java
aritu/aritu-java-eu
46034653dc6661965aa6b99d10989ec9fa34dd09
[ "Apache-2.0" ]
null
null
null
21.875
77
0.734286
996,643
package com.aritu.java.eu.text; import java.text.DecimalFormatSymbols; import com.aritu.java.eu.constants.Locales; public final class BasqueDecimalFormatSymbols extends DecimalFormatSymbols { private static final long serialVersionUID = 1L; public BasqueDecimalFormatSymbols() { super(Locales.CASTILIAN); } }
9233a293b056013cafca080338a647dae6e13649
718
java
Java
android/versioned-abis/expoview-abi36_0_0/src/main/java/abi36_0_0/expo/modules/facedetector/FaceDetectorPackage.java
scottnich32/expo
fcb8e99941b3994d5291657587b373674014b027
[ "Apache-2.0", "MIT" ]
3
2020-09-06T17:32:53.000Z
2021-05-20T19:04:48.000Z
android/versioned-abis/expoview-abi36_0_0/src/main/java/abi36_0_0/expo/modules/facedetector/FaceDetectorPackage.java
scottnich32/expo
fcb8e99941b3994d5291657587b373674014b027
[ "Apache-2.0", "MIT" ]
16
2021-03-01T21:18:59.000Z
2022-02-27T08:18:52.000Z
android/versioned-abis/expoview-abi36_0_0/src/main/java/abi36_0_0/expo/modules/facedetector/FaceDetectorPackage.java
scottnich32/expo
fcb8e99941b3994d5291657587b373674014b027
[ "Apache-2.0", "MIT" ]
2
2020-04-25T16:31:11.000Z
2020-04-25T16:31:13.000Z
31.217391
92
0.820334
996,644
package abi36_0_0.expo.modules.facedetector; import android.content.Context; import abi36_0_0.org.unimodules.core.BasePackage; import abi36_0_0.org.unimodules.core.ExportedModule; import abi36_0_0.org.unimodules.core.interfaces.InternalModule; import java.util.Collections; import java.util.List; public class FaceDetectorPackage extends BasePackage { @Override public List<InternalModule> createInternalModules(Context context) { return Collections.singletonList((InternalModule) new ExpoFaceDetectorProvider()); } @Override public List<ExportedModule> createExportedModules(Context reactContext) { return Collections.singletonList((ExportedModule) new FaceDetectorModule(reactContext)); } }
9233a481f8448be41937786784d8c0baa26a1304
3,074
java
Java
personnel/src/main/java/com/personnel/core/exception/GlobalExceptionHandler.java
youngerboye/personPaper
af8a1d4cbcc664cd94e138030c16dded314fedf9
[ "MIT" ]
null
null
null
personnel/src/main/java/com/personnel/core/exception/GlobalExceptionHandler.java
youngerboye/personPaper
af8a1d4cbcc664cd94e138030c16dded314fedf9
[ "MIT" ]
null
null
null
personnel/src/main/java/com/personnel/core/exception/GlobalExceptionHandler.java
youngerboye/personPaper
af8a1d4cbcc664cd94e138030c16dded314fedf9
[ "MIT" ]
null
null
null
42.694444
151
0.640859
996,645
package com.personnel.core.exception; import com.common.model.PageData; import com.common.response.ResponseResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.access.AccessDeniedException; import org.springframework.validation.BindingResult; import org.springframework.validation.FieldError; import org.springframework.web.bind.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; @ControllerAdvice @ResponseBody public class GlobalExceptionHandler { private static Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class); /** * 所有异常报错 * @param request * @param exception * @return * @throws Exception */ @ExceptionHandler(value=Exception.class) public ResponseResult allExceptionHandler(HttpServletRequest request, Exception exception) throws Exception { System.out.println(request); PageData pageData = new PageData(request); System.out.println(pageData); logger.error("====================================================开始打印异常==============================================================="); exception.printStackTrace(); logger.error(exception.getLocalizedMessage()); logger.error(String.valueOf(exception.getCause())); logger.error(String.valueOf(exception.getSuppressed())); logger.error(exception.getMessage()); logger.error(String.valueOf(exception.getClass().getAnnotatedSuperclass())); logger.error(String.valueOf(exception.getStackTrace())); logger.error("======================================================end====================================================================="); if(exception instanceof AccessDeniedException){ return ResponseResult.error("无权限"); } if(exception instanceof MethodArgumentNotValidException){ BindingResult bindingResult = ((MethodArgumentNotValidException) exception).getBindingResult(); StringBuilder errorMessage = new StringBuilder(bindingResult.getFieldErrors().size() * 16); errorMessage.append("Invalid Request:"); for (int i = 0;i<bindingResult.getFieldErrors().size();++i) { if(i>0){ errorMessage.append(","); } FieldError fieldError = bindingResult.getFieldErrors().get(i); errorMessage.append(fieldError.getField()); errorMessage.append(":"); errorMessage.append(fieldError.getDefaultMessage()); } return ResponseResult.error(errorMessage.toString(),100); } if(exception instanceof RuntimeException){ return ResponseResult.error("未知错误,请稍后再试", 100); } return ResponseResult.error("服务器发生异常,请联系管理员",100); } }
9233a548fb1de27f7068659610f5e78361879290
5,874
java
Java
dConnectManager/dConnectManager/dconnect-manager-core/src/main/java/org/deviceconnect/android/manager/core/plugin/CommunicationHistory.java
TakayukiHoshi1984/DeviceConnect-AndroidSandbox
c0309b4de3661a0fba0530de9e63f710a117e822
[ "MIT" ]
54
2015-05-01T06:41:38.000Z
2021-12-18T22:10:40.000Z
dConnectManager/dConnectManager/dconnect-manager-core/src/main/java/org/deviceconnect/android/manager/core/plugin/CommunicationHistory.java
TakayukiHoshi1984/DeviceConnect-AndroidSandbox
c0309b4de3661a0fba0530de9e63f710a117e822
[ "MIT" ]
38
2015-01-15T09:37:40.000Z
2022-02-23T00:48:53.000Z
dConnectManager/dConnectManager/dconnect-manager-core/src/main/java/org/deviceconnect/android/manager/core/plugin/CommunicationHistory.java
TakayukiHoshi1984/DeviceConnect-AndroidSandbox
c0309b4de3661a0fba0530de9e63f710a117e822
[ "MIT" ]
32
2015-01-15T00:56:57.000Z
2021-10-15T11:54:09.000Z
23.309524
106
0.571331
996,646
/* CommunicationHistory.java Copyright (c) 2017 NTT DOCOMO,INC. Released under the MIT license http://opensource.org/licenses/mit-license.php */ package org.deviceconnect.android.manager.core.plugin; import android.content.Context; import android.content.SharedPreferences; import android.text.format.DateFormat; import java.util.LinkedList; import java.util.List; /** * デバイスプラグインとの通信履歴を保持するクラス. * * @author NTT DOCOMO, INC. */ public class CommunicationHistory { /** デフォルトの最大履歴サイズ. */ private static final int DEFAULT_HISTORY_MAX_SIZE = 10; /** ファイル名のプレフィクス. */ private static final String PREFIX_PREFERENCES = "plugin_report_"; /** * 設定キー: 平均通信時間. */ private static final String KEY_AVERAGE_BAUD_RATE = "average_baud_rate"; /** * 設定キー: 最遅通信時間. */ private static final String KEY_WORST_BAUD_RATE = "worst_baud_rate"; /** * 設定キー: 最遅通信時間のリクエスト. */ private static final String KEY_WORST_REQUEST = "worst_request"; /** * データを永続化するオブジェクト. */ private final SharedPreferences mPreferences; /** * 応答タイムアウトの履歴を保持するリスト. */ private final List<Info> mNotRespondedList = new LinkedList<>(); /** * 通信履歴を保持するリスト. */ private final List<Info> mRespondedList = new LinkedList<>(); /** * 最大履歴サイズ設定. */ private int mHistoryMaxSize = DEFAULT_HISTORY_MAX_SIZE; /** * コンストラクタ. * * @param context コンテキスト * @param pluginId プラグインID */ CommunicationHistory(final Context context, final String pluginId) { String prefName = PREFIX_PREFERENCES + pluginId; mPreferences = context.getSharedPreferences(prefName, Context.MODE_PRIVATE); } /** * 平均通信時間を保存します. * @param baudRate 保存する平均通信時間 */ void setAverageBaudRate(final long baudRate) { mPreferences.edit().putLong(KEY_AVERAGE_BAUD_RATE, baudRate).apply(); } /** * 平均通信時間を取得します. * @return 平均通信時間 */ public long getAverageBaudRate() { return mPreferences.getLong(KEY_AVERAGE_BAUD_RATE, 0); } /** * 最遅通信時間を保存します. * @param baudRate 最遅通信時間 */ void setWorstBaudRate(final long baudRate) { mPreferences.edit().putLong(KEY_WORST_BAUD_RATE, baudRate).apply(); } /** * 最遅通信時間を取得します. * @return 最遅通信時間 */ public long getWorstBaudRate() { return mPreferences.getLong(KEY_WORST_BAUD_RATE, 0); } /** * 最遅通信時間のリクエストを保存します. * @param request 最遅通信時間のリクエスト */ void setWorstBaudRateRequest(final String request) { mPreferences.edit().putString(KEY_WORST_REQUEST, request).apply(); } /** * 最遅通信時間のリクエストを取得します. * @return 最遅通信時間のリクエスト */ public String getWorstBaudRateRequest() { return mPreferences.getString(KEY_WORST_REQUEST, "None"); } public void add(final Info info) { if (!info.isTimeout()) { add(mRespondedList, info); } else { add(mNotRespondedList, info); } } private void add(final List<Info> list, final Info info) { synchronized (list) { list.add(info); if (list.size() > getMaxSize()) { list.remove(0); } } } private int getMaxSize() { return mHistoryMaxSize; } public List<Info> getNotRespondedCommunications() { synchronized (mNotRespondedList) { return new LinkedList<>(mNotRespondedList); } } public List<Info> getRespondedCommunications() { synchronized (mRespondedList) { return new LinkedList<>(mRespondedList); } } /** * 保持していたすべてのデータをクリアし、初期状態に戻す. */ void clear() { synchronized (this) { mPreferences.edit().clear().apply(); mRespondedList.clear(); mNotRespondedList.clear(); } } /** * 1リクエスト当たりの通信についての情報. */ public static class Info { /** * サービスID. * * NOTE: プラグイン自体へのリクエストの場合は <code>null</code> となる. */ final String mServiceId; /** * リクエストのパス. */ final String mRequestPath; /** * プラグインへのリクエスト送信時刻を示すUNIX時間. */ final long mStart; /** * プラグインからのレスポンス受信時刻を示すUNIX時間. * 負の値が設定されている場合、レスポンスタイムアウトが発生したことを示す. */ final long mEnd; Info(final String serviceId, final String path, final long start, final long end) { if (end > 0 && start > end){ throw new IllegalArgumentException("`end` is must be larger than `start` if no timeout."); } mServiceId= serviceId; mRequestPath = path; mStart = start; mEnd = end; } Info(final String serviceId, final String path, final long start) { this(serviceId, path, start, -1); } public String getServiceId() { return mServiceId; } public String getRequestPath() { return mRequestPath; } public long getStartTime() { return mStart; } public long getEndTime() { return mEnd; } /** * ラウンドトリップ時間を取得する. * 単位はミリ秒. タイムアウトが発生していた場合は負の値を返す. * @return */ public long getRoundTripTime() { if (isTimeout()) { return -1; } return mEnd - mStart; } public boolean isTimeout() { return mEnd < 0; } /** * リクエストを送信した時刻の文字列を取得します. * @return リクエストを送信した時刻 */ public String getDateString() { return DateFormat.format("yyyy/MM/dd kk:mm:ss", mStart).toString(); } } }
9233a68b5dba03a80f73c5e8e974923587e8034a
309
java
Java
super_camera/android/src/main/java/bparrishmines/superplugins/super_camera/camera2/UseCase.java
bparrishMines/super
02c25d455714800762d2300af3d52561012c5914
[ "MIT" ]
1
2020-05-16T20:16:23.000Z
2020-05-16T20:16:23.000Z
super_camera/android/src/main/java/bparrishmines/superplugins/super_camera/camera2/UseCase.java
bparrishMines/super
02c25d455714800762d2300af3d52561012c5914
[ "MIT" ]
null
null
null
super_camera/android/src/main/java/bparrishmines/superplugins/super_camera/camera2/UseCase.java
bparrishMines/super
02c25d455714800762d2300af3d52561012c5914
[ "MIT" ]
null
null
null
25.75
59
0.805825
996,647
package bparrishmines.superplugins.super_camera.camera2; import github.penguin.reference.reference.LocalReference; abstract class UseCase implements LocalReference { final androidx.camera.core.UseCase useCase; protected UseCase(androidx.camera.core.UseCase useCase) { this.useCase = useCase; } }
9233a6da4ecddcee6ce04a9036fb5b89eb60483b
1,306
java
Java
idylnlp-training-definition/idylnlp-training-definition-file/src/main/java/ai/idylnlp/training/definition/model/TrainingDefinitionException.java
fangzhimeng/idylnlp
429688ad376d7600d82194c66c0070d9c4be3a82
[ "Apache-2.0" ]
null
null
null
idylnlp-training-definition/idylnlp-training-definition-file/src/main/java/ai/idylnlp/training/definition/model/TrainingDefinitionException.java
fangzhimeng/idylnlp
429688ad376d7600d82194c66c0070d9c4be3a82
[ "Apache-2.0" ]
null
null
null
idylnlp-training-definition/idylnlp-training-definition-file/src/main/java/ai/idylnlp/training/definition/model/TrainingDefinitionException.java
fangzhimeng/idylnlp
429688ad376d7600d82194c66c0070d9c4be3a82
[ "Apache-2.0" ]
3
2020-03-21T14:23:50.000Z
2021-08-16T13:42:07.000Z
31.853659
80
0.641654
996,648
/******************************************************************************* * Copyright 2019 Mountain Fog, 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 ai.idylnlp.training.definition.model; /** * Exception that is thrown when a training definition * cannot be read. * * @author Mountain Fog, Inc. * */ public class TrainingDefinitionException extends Exception { private static final long serialVersionUID = 7557243516752367591L; /** * Creates a new training definition exception. * @param message The message of the exception. * @param ex The {@link Exception}. */ public TrainingDefinitionException(String message, Exception ex) { super(message, ex); } }
9233a7449dbff41125da78b507106121ffe38e88
111,419
java
Java
src/main/java/shadow/typecheck/StatementChecker.java
Brinsky/shadow
baa0a8e82068906f9297c4c369d9b77319bd77df
[ "Apache-2.0" ]
9
2015-04-28T00:54:31.000Z
2020-11-21T20:47:55.000Z
src/main/java/shadow/typecheck/StatementChecker.java
Brinsky/shadow
baa0a8e82068906f9297c4c369d9b77319bd77df
[ "Apache-2.0" ]
28
2015-02-02T14:47:42.000Z
2020-08-20T14:51:01.000Z
src/main/java/shadow/typecheck/StatementChecker.java
Brinsky/shadow
baa0a8e82068906f9297c4c369d9b77319bd77df
[ "Apache-2.0" ]
6
2015-04-29T01:30:03.000Z
2016-12-22T04:38:59.000Z
36.12808
247
0.680019
996,649
/* * Copyright 2017 Team Shadow * * 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 shadow.typecheck; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Set; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.tree.ParseTree; import shadow.ShadowException; import shadow.interpreter.ShadowBoolean; import shadow.interpreter.ShadowCode; import shadow.interpreter.ShadowDouble; import shadow.interpreter.ShadowFloat; import shadow.interpreter.ShadowInteger; import shadow.interpreter.ShadowNull; import shadow.interpreter.ShadowString; import shadow.interpreter.ShadowValue; import shadow.parse.Context; import shadow.parse.Context.AssignmentKind; import shadow.parse.ShadowParser; import shadow.parse.ShadowParser.CatchStatementsContext; import shadow.parse.ShadowParser.ConditionalExpressionContext; import shadow.parse.ShadowParser.LocalMethodDeclarationContext; import shadow.parse.ShadowParser.PrimaryExpressionContext; import shadow.parse.ShadowParser.SendStatementContext; import shadow.parse.ShadowParser.ThrowOrConditionalExpressionContext; import shadow.typecheck.TypeCheckException.Error; import shadow.typecheck.type.*; import shadow.typecheck.type.InstantiationException; public class StatementChecker extends ScopedChecker { /* Stack for current prefix (needed for arbitrarily long chains of expressions). */ private LinkedList<Context> curPrefix = new LinkedList<>(); public StatementChecker( Package packageTree, ErrorReporter reporter ) { super(packageTree, reporter); } public void check(Context node) throws ShadowException { // Check the whole class visit(node); printAndReportErrors(); } // Important! Set the current type on entering the body, not the declaration, otherwise extends and imports are improperly checked with the wrong outer class @Override public Void visitClassOrInterfaceBody(ShadowParser.ClassOrInterfaceBodyContext ctx) { currentType = ((Context)ctx.getParent()).getType(); //get type from declaration for( InterfaceType interfaceType : currentType.getInterfaces() ) currentType.addUsedType(interfaceType); if( currentType instanceof ClassType ) { ClassType classType = (ClassType) currentType; currentType.addUsedType(classType.getExtendType()); } visitChildren(ctx); if( currentType instanceof ClassType && currentType.isParameterized() ) { ClassType classType = (ClassType) currentType; Set<Type> partiallyInstantiated = currentType.getPartiallyInstantiatedClasses(); for( Type type : partiallyInstantiated ) classType.addDependency(new SimpleModifiedType(type)); } currentType = currentType.getOuter(); return null; } public void visitMethodPost( Context node ) { currentMethod.removeFirst(); closeScope(); } public void visitMethodPre( Context node ) { MethodSignature signature; if( node instanceof ShadowParser.LocalMethodDeclarationContext || node instanceof ShadowParser.InlineMethodDefinitionContext ){ if( node instanceof ShadowParser.InlineMethodDefinitionContext ) signature = new MethodSignature( currentType, "", node.getModifiers(), node.getDocumentation(), node); else signature = new MethodSignature( currentType, ((ShadowParser.LocalMethodDeclarationContext)node).methodDeclarator().generalIdentifier().getText(), node.getModifiers(), node.getDocumentation(), node); node.setSignature(signature); MethodType methodType = signature.getMethodType(); if( node instanceof ShadowParser.InlineMethodDefinitionContext ) methodType.setInline(true); node.setType(methodType); //what modifiers (if any) are allowed for a local method declaration? } else { signature = node.getSignature(); } for( ModifiedType modifiedType : signature.getParameterTypes() ) { currentType.addUsedType(modifiedType.getType()); } for( ModifiedType modifiedType : signature.getReturnTypes() ) currentType.addUsedType(modifiedType.getType()); // Done here because AttributeInvocationContext doesn't have references to these AttributeInvocation objects for (AttributeInvocation attribute : signature.getAttributes()) { attribute.updateFieldTypes(this.getErrorReporter()); } if(signature.isImportMethod()) { if(signature.getModifiers().isPublic()) { addError(node, Error.INVALID_MODIFIER, "Method imports cannot be public."); } // first parameter is the class where the method lives SequenceType params = signature.getParameterTypes(); Type sourceClass = params.get(0).getType(); // get the actual parameters of the method SequenceType sourceParams = new SequenceType(); for(int i = 1; i < params.size(); ++i) { sourceParams.add(params.get(i)); } // find the method in the source class MethodSignature method = sourceClass.getMatchingMethod(signature.getSymbol(), sourceParams); if(method == null || !method.getReturnTypes().equals(signature.getReturnTypes())) { addError(node, Error.INVALID_METHOD_IMPORT, "No matching method was found for method '" + signature.getSymbol() + "' in class '" + sourceClass + "'"); } else { signature.setImportSource(method); } } currentMethod.addFirst(node); openScope(); } @Override public Void visitSwitchStatement(ShadowParser.SwitchStatementContext ctx) { visitChildren(ctx); int defaultCounter = 0; Type type = ctx.conditionalExpression().getType(); if(!type.isIntegral() && !type.isString() && !(type instanceof EnumType)) { addError(ctx, Error.INVALID_TYPE, "Supplied type " + type + " cannot be used in switch statement, only integral, String, and enum types allowed", type); } for(ShadowParser.SwitchLabelContext label : ctx.switchLabel()) { if(label.getType() != null) { //default label should have null type if(!label.getType().isSubtype(type)) { addError(label,Error.INVALID_LABEL,"Label type " + label.getType() + " does not match switch type " + type, label.getType(), type); } } else { defaultCounter++; } } if( defaultCounter > 1 ) addError(ctx, Error.INVALID_LABEL, "Switch cannot have multiple default labels"); else if( defaultCounter == 1 ) ctx.hasDefault = true; return null; } @Override public Void visitSwitchLabel(ShadowParser.SwitchLabelContext ctx) { visitChildren(ctx); if( !ctx.primaryExpression().isEmpty() ) { Type result = null; for( ShadowParser.PrimaryExpressionContext child : ctx.primaryExpression() ) { Type type = child.getType(); if( result == null ) result = type; else if( result.isSubtype(type) ) result = type; else if( !type.isSubtype(result) ) { //neither is subtype of other, panic! addError(child, Error.MISMATCHED_TYPE, "Supplied type " + type + " does not match type " + result + " in switch label", type, result); result = Type.UNKNOWN; break; } if( !child.getModifiers().isConstant() ) addError(child, Error.INVALID_TYPE, "Value supplied as label must be constant"); } ctx.setType(result); ctx.addModifiers(Modifiers.CONSTANT); } return null; } @Override public Void visitBlock(ShadowParser.BlockContext ctx) { openScope(); visitChildren(ctx); closeScope(); return null; } @Override public Void visitMethodDeclaration(ShadowParser.MethodDeclarationContext ctx) { visitMethodPre(ctx); visitChildren(ctx); visitMethodPost(ctx); return null; } @Override public Void visitLocalMethodDeclaration(ShadowParser.LocalMethodDeclarationContext ctx) { addSymbol(ctx.methodDeclarator().generalIdentifier().getText(), ctx); visitMethodPre(ctx); visitChildren(ctx); visitMethodPost(ctx); return null; } @Override public Void visitFormalParameters(ShadowParser.FormalParametersContext ctx) { boolean local = (ctx.getParent() instanceof ShadowParser.InlineMethodDefinitionContext) || (ctx.getParent().getParent() instanceof ShadowParser.LocalMethodDeclarationContext); if( local ) { visitChildren(ctx); SequenceType type = new SequenceType(); for(ShadowParser.FormalParameterContext parameter : ctx.formalParameter()) { if( parameter.getType() instanceof SingletonType ) addError(parameter, Error.INVALID_PARAMETERS, "Cannot define method with singleton parameter"); type.add(parameter); } ctx.setType(type); } else { //class methods have their types constructed //but still need to have parameters added to the symbol table MethodType methodType = currentMethod.getFirst().getSignature().getMethodType(); for(String symbol : methodType.getParameterNames()) addSymbol( symbol, methodType.getParameterType(symbol)); } return null; } @Override public Void visitFormalParameter(ShadowParser.FormalParameterContext ctx) { visitChildren(ctx); Type type = ctx.type().getType(); ctx.setType( type ); addSymbol( ctx.Identifier().getText(), ctx ); return null; } @Override public Void visitCreateDeclaration(ShadowParser.CreateDeclarationContext ctx) { visitMethodPre(ctx); visitChildren(ctx); // Check for an explicit call to the parent class' create(). // For .meta files and imports, we trust that the create() is properly implemented elsewhere if(currentType instanceof ClassType && !ctx.getSignature().isImport() && !ctx.isFromMetaFile()) { ClassType classType = (ClassType) currentType; ClassType parentType = classType.getExtendType(); boolean explicitCreate = ctx.createBlock() != null && ctx.createBlock().explicitCreateInvocation() != null; if(!explicitCreate && parentType != null) { //only worry if there is no explicit invocation //explicit invocations are handled separately boolean foundDefault = false; for( MethodSignature method : parentType.getMethodOverloads("create") ) { if( method.getParameterTypes().isEmpty() ) { foundDefault = true; break; } } if( !foundDefault ) addError(ctx, Error.MISSING_CREATE, "Explicit create invocation is missing, and parent class " + parentType + " does not implement the default create", parentType); } } visitMethodPost(ctx); return null; } @Override public Void visitCreateBlock(ShadowParser.CreateBlockContext ctx) { openScope(); visitChildren(ctx); closeScope(); return null; } @Override public Void visitDestroyDeclaration(ShadowParser.DestroyDeclarationContext ctx) { visitMethodPre(ctx); visitChildren(ctx); visitMethodPost(ctx); return null; } @Override public Void visitReferenceType(ShadowParser.ReferenceTypeContext ctx) { visitChildren(ctx); Context child = (Context)ctx.getChild(0); //either primitive type or class type Type type = child.getType(); int dimensions = getDimensions( ctx ); if( dimensions != 0 ) type = new ArrayType(type, dimensions, false); ctx.setType(type); ctx.addModifiers(Modifiers.TYPE_NAME); return null; } @Override public Void visitLocalVariableDeclaration(ShadowParser.LocalVariableDeclarationContext ctx) { visitChildren(ctx); Type type; boolean isVar = false; if( ctx.type() != null ) type = ctx.type().getType(); else { // var type type = Type.VAR; isVar = true; } ctx.setType(type); // Add variables for( ShadowParser.VariableDeclaratorContext declarator : ctx.variableDeclarator() ) { if( isVar ) { if( declarator.conditionalExpression() != null ) { // Has initializer type = declarator.conditionalExpression().getType(); } else { type = Type.UNKNOWN; addError(declarator, Error.UNDEFINED_TYPE, "Variable declared with var has no initializer to infer type from"); } } if( ctx.getModifiers().isNullable() && type instanceof ArrayType ) { ArrayType arrayType = (ArrayType) type; type = arrayType.convertToNullable(); } declarator.setType(type); declarator.addModifiers(ctx.getModifiers()); addSymbol( declarator.generalIdentifier().getText(), declarator ); //add to local scope } checkInitializers( ctx.variableDeclarator() ); return null; } private void checkInitializers(List<ShadowParser.VariableDeclaratorContext> declarators) { for( ShadowParser.VariableDeclaratorContext declarator : declarators ) { if( declarator.conditionalExpression() != null ) { //has initializer addErrors(declarator, isValidInitialization(declarator, declarator.conditionalExpression())); Type leftType = declarator.getType(); Type rightType = declarator.conditionalExpression().getType(); // let unbound method type know what signature it will eventually be bound to if( rightType instanceof UnboundMethodType && leftType instanceof MethodReferenceType ) { UnboundMethodType unboundType = (UnboundMethodType) rightType; MethodType methodType = ((MethodReferenceType) leftType).getMethodType(); MethodSignature signature = unboundType.getOuter().getMatchingMethod(unboundType.getTypeName(), methodType.getParameterTypes()); unboundType.setKnownSignature( signature ); } } else if( declarator.getModifiers().isConstant() ) //only fields are ever constant addError( declarator, Error.INVALID_MODIFIER, "Variable declared with modifier constant must have an initializer"); } } @Override public Void visitFieldDeclaration(ShadowParser.FieldDeclarationContext ctx) { visitChildren(ctx); checkInitializers(ctx.variableDeclarator()); //check all initializers return null; } public boolean setTypeFromContext( Context node, String name, Type context ) { if( context instanceof TypeParameter ) { TypeParameter typeParameter = (TypeParameter) context; for( Type type : typeParameter.getBounds() ) if( setTypeFromContext( node, name, type ) ) return true; return setTypeFromContext( node, name, typeParameter.getClassBound()); } else { Modifiers methodModifiers = Modifiers.NO_MODIFIERS; if(!currentMethod.isEmpty()) methodModifiers = currentMethod.getFirst().getModifiers(); // Check fields first if(context.containsField(name)) { Context field = context.getField(name); node.setType(field.getType()); node.addModifiers(field.getModifiers()); if(!fieldIsAccessible(field, currentType)) addError(field, Error.ILLEGAL_ACCESS, "Field " + name + " not accessible from this context"); else { if( methodModifiers.isImmutable() || methodModifiers.isReadonly() ) node.getModifiers().upgradeToTemporaryReadonly(); else node.addModifiers(Modifiers.ASSIGNABLE); } return true; } // Next check methods if(context.recursivelyContainsMethod(name)) { node.setType( new UnboundMethodType( name, context ) ); if(methodModifiers != null && methodModifiers.isImmutable() ) node.addModifiers(Modifiers.IMMUTABLE); else if(methodModifiers != null && methodModifiers.isReadonly() ) node.addModifiers(Modifiers.READONLY); return true; } // Finally check constants if(context.recursivelyContainsConstant(name)) { Context field = context.recursivelyGetConstant(name); node.setType(field.getType()); node.addModifiers(field.getModifiers()); if(!fieldIsAccessible(field, currentType)) addError(field, Error.ILLEGAL_ACCESS, "Constant " + name + " not accessible from this context"); return true; } } return false; } public boolean setTypeFromName( Context node, String name ) { // next go through the scopes trying to find the variable ModifiedType declaration = findSymbol( name ); if( declaration != null ) { node.setType(declaration.getType()); node.addModifiers(declaration.getModifiers()); node.addModifiers(Modifiers.ASSIGNABLE); return true; } // now check the parameters of the methods MethodType methodType = null; for( Context method : currentMethod) { methodType = (MethodType)method.getType(); if(methodType != null && methodType.containsParam(name)) { node.setType(methodType.getParameterType(name).getType()); node.addModifiers(methodType.getParameterType(name).getModifiers()); node.addModifiers(Modifiers.ASSIGNABLE); //is this right? Shouldn't all method parameters be unassignable? return true; } } // check to see if it's a field or a method if( setTypeFromContext( node, name, currentType ) ) return true; //is it a type? Type type = lookupType( node, name ); if(type != null) { currentType.addUsedType(type); node.setType(type); node.addModifiers(Modifiers.TYPE_NAME); return true; } return false; } @Override public Void visitRelationalExpression(ShadowParser.RelationalExpressionContext ctx) { visitChildren(ctx); Type result = ((Context)ctx.getChild(0)).getType(); for( int i = 1; i < ctx.getChildCount(); i += 2 ) { String symbol = ctx.getChild(i).getText(); Context currentNode = (Context)ctx.getChild(i + 1); Type current = currentNode.getType(); if( result.hasUninstantiatedInterface(Type.CAN_COMPARE) ) { SequenceType argument = new SequenceType(currentNode); MethodSignature signature = setMethodType(ctx, result, "compare", argument ); if( signature != null ) { result = signature.getReturnTypes().getType(0); ctx.addOperation(signature); } else { addError(ctx, Error.INVALID_TYPE, "Operator " + symbol + " not defined on types " + result + " and " + current, result, current); result = Type.UNKNOWN; break; } } else { addError(ctx, Error.INVALID_TYPE, "Operator " + symbol + " not defined on types " + result + " and " + current, result, current); result = Type.UNKNOWN; break; } result = Type.BOOLEAN; //boolean after one comparison } ctx.setType(result); //also propagates type up if only one child if( ctx.getChildCount() == 1) //can make ASSIGNABLE (if only one child) ctx.addModifiers(((Context)ctx.getChild(0)).getModifiers()); return null; } @Override public Void visitConcatenationExpression(ShadowParser.ConcatenationExpressionContext ctx) { visitChildren(ctx); Type result = null; boolean first = true; for( ShadowParser.ShiftExpressionContext child : ctx.shiftExpression() ) { if( first ) { result = child.getType(); first = false; } else { result = Type.STRING; if( child.getType() instanceof SequenceType ) { addError(child, Error.INVALID_TYPE, "Cannot apply operator # to sequence type " + child.getType(), child.getType(), result); result = Type.UNKNOWN; } } } ctx.setType(result); //propagates type up if only one child if( ctx.getChildCount() == 1) //can make ASSIGNABLE (if only one child) ctx.addModifiers(((Context)ctx.getChild(0)).getModifiers()); return null; } @Override public Void visitEqualityExpression(ShadowParser.EqualityExpressionContext ctx) { visitChildren(ctx); Context first = ((Context)ctx.getChild(0)); Type resultType = first.getType(); for( int i = 1; i < ctx.getChildCount(); i += 2 ) { String symbol = ctx.getChild(i).getText(); Context currentNode = (Context)ctx.getChild(i + 1); Type current = currentNode.getType(); if( symbol.equals("==") || symbol.equals("!=") ) { if( first.getModifiers().isNullable() ) { addError(ctx, Error.INVALID_TYPE, "Cannot apply operator " + symbol + " to statement with nullable type"); resultType = Type.UNKNOWN; break; } if( resultType.hasUninstantiatedInterface(Type.CAN_EQUAL) ) { SequenceType argument = new SequenceType(); argument.add(currentNode); MethodSignature signature = setMethodType(ctx, resultType, "equal", argument ); if( signature != null ) { resultType = signature.getReturnTypes().getType(0); ctx.addOperation(signature); } else { addError(ctx, Error.INVALID_TYPE, "Cannot apply operator " + symbol + " to types " + resultType + " and " + current, resultType, current); resultType = Type.UNKNOWN; break; } } else { addError(ctx, Error.INVALID_TYPE, "Cannot apply operator " + symbol + " to types " + resultType + " and " + current, resultType, current); resultType = Type.UNKNOWN; break; } } else if( !resultType.isSubtype(current) && !current.isSubtype(resultType) ) { addError(ctx, Error.INVALID_TYPE, "Cannot apply operator " + symbol + " to types " + resultType + " and " + current, resultType, current); resultType = Type.UNKNOWN; break; } resultType = Type.BOOLEAN; //boolean after one comparison } ctx.setType(resultType); //propagates type up if only one child if( ctx.getChildCount() == 1) //can make ASSIGNABLE (if only one child) ctx.addModifiers(((Context)ctx.getChild(0)).getModifiers()); return null; } private void visitBinary( Context node ) { Type result = ((Context)node.getChild(0)).getType(); for( int i = 1; i < node.getChildCount(); i += 2 ) { String operator = node.getChild(i).getText(); Context currentNode = (Context)node.getChild(i + 1); Type current = currentNode.getType(); InterfaceType interfaceType = null; String methodName = ""; switch( operator ) { case "+": methodName = "add"; interfaceType = Type.CAN_ADD; break; case "-": methodName = "subtract"; interfaceType = Type.CAN_SUBTRACT; break; case "*": methodName = "multiply"; interfaceType = Type.CAN_MULTIPLY; break; case "/": methodName = "divide"; interfaceType = Type.CAN_DIVIDE; break; case "%": methodName = "modulus"; interfaceType = Type.CAN_MODULUS; break; case "<<": methodName = "bitShiftLeft"; interfaceType = Type.INTEGER; break; case "<<<": methodName = "bitRotateLeft"; interfaceType = Type.INTEGER; break; case ">>": methodName = "bitShiftRight"; interfaceType = Type.INTEGER; break; case ">>>": methodName = "bitRotateRight"; interfaceType = Type.INTEGER; break; } if( result.hasUninstantiatedInterface(interfaceType) ) { //we can't know which one will work //so we go with an uninstantiated version and then find an appropriate signature SequenceType argument = new SequenceType(currentNode); MethodSignature signature = setMethodType(node, result, methodName, argument ); if( signature != null ) { result = signature.getReturnTypes().getType(0); node.addOperation(signature); } else { addError(currentNode, Error.INVALID_TYPE, "Cannot apply operator " + operator + " to types " + result + " and " + current, result, current); node.setType(Type.UNKNOWN); return; } } else { addError(currentNode, Error.INVALID_TYPE, "Cannot apply operator " + operator + " to types " + result + " and " + current, result, current); node.setType(Type.UNKNOWN); return; } } node.setType(result); //propagates type up if only one child if( node.getChildCount() == 1) //can make ASSIGNABLE (if only one child) node.addModifiers(((Context)node.getChild(0)).getModifiers()); } @Override public Void visitShiftExpression(ShadowParser.ShiftExpressionContext ctx) { visitChildren(ctx); visitBinary(ctx); return null; } @Override public Void visitRotateExpression(ShadowParser.RotateExpressionContext ctx) { visitChildren(ctx); visitBinary(ctx); return null; } @Override public Void visitAdditiveExpression(ShadowParser.AdditiveExpressionContext ctx) { visitChildren(ctx); visitBinary(ctx); return null; } @Override public Void visitMultiplicativeExpression(ShadowParser.MultiplicativeExpressionContext ctx) { visitChildren(ctx); visitBinary(ctx); return null; } private Type visitUnary( ShadowParser.UnaryExpressionContext node, String method, String operator, InterfaceType interfaceType ) { Type type = node.unaryExpression().getType(); if( type.hasUninstantiatedInterface(interfaceType) ) { MethodSignature signature = setMethodType(node, type, method, new SequenceType() ); if( signature != null ) { type = signature.getReturnTypes().getType(0); node.addOperation(signature); } else { addError(node, Error.INVALID_TYPE, "Cannot apply " + operator + " to type " + type + " which does not implement interface " + interfaceType, type); type = Type.UNKNOWN; } } else { addError(node, Error.INVALID_TYPE, "Cannot apply " + operator + " to type " + type + " which does not implement interface " + interfaceType, type); type = Type.UNKNOWN; } return type; } @Override public Void visitUnaryExpression(ShadowParser.UnaryExpressionContext ctx) { visitChildren(ctx); if( ctx.unaryExpression() != null ) { String operator = ctx.getChild(0).getText(); Type type = ctx.unaryExpression().getType(); if( operator.equals("-") ) type = visitUnary( ctx, "negate", "unary -", Type.CAN_NEGATE); else if( operator.equals("~") ) type = visitUnary( ctx, "bitComplement", "operator ~", Type.INTEGER); else if( operator.equals("#") ) { if( type instanceof SequenceType ) { addError(ctx, Error.INVALID_TYPE, "Cannot apply operator # to sequence type " + type); type = Type.UNKNOWN; } else { MethodSignature signature = setMethodType(ctx, type, "toString", new SequenceType() ); ctx.addOperation(signature); //should never be null type = Type.STRING; } } else if( operator.equals("!") ) { if( !type.equals(Type.BOOLEAN)) { addError(ctx, Error.INVALID_TYPE, "Cannot apply operator ! to type " + type + " which is not boolean", type); type = Type.UNKNOWN; } } ctx.setType(type); } else { Context child = (Context)ctx.getChild(0); ctx.setType(child.getType()); ctx.addModifiers(child.getModifiers()); } return null; } @Override public Void visitConditionalExpression(ShadowParser.ConditionalExpressionContext ctx) { visitChildren(ctx); if( ctx.getChildCount() == 1 ) { ctx.setType(ctx.coalesceExpression().getType()); ctx.addModifiers(ctx.coalesceExpression().getModifiers()); } else { // ternary ThrowOrConditionalExpressionContext first = ctx.throwOrConditionalExpression(0); ThrowOrConditionalExpressionContext second = ctx.throwOrConditionalExpression(1); Type t1 = ctx.coalesceExpression().getType(); if(!t1.equals(Type.BOOLEAN)) { addError(ctx.coalesceExpression(), Error.INVALID_TYPE, "Supplied type " + t1 + " cannot be used in the condition of a ternary operator, boolean type required", t1); ctx.setType(Type.UNKNOWN); } else if(first.throwStatement() != null || second.throwStatement() != null) { if(first.throwStatement() != null && second.throwStatement() != null) { addError(ctx, Error.INVALID_STRUCTURE, "Only one throw is allowed in the clause of a ternary operator"); ctx.setType(Type.UNKNOWN); } else { ConditionalExpressionContext actual = first.throwStatement() == null ? first.conditionalExpression() : second.conditionalExpression(); ctx.setType(actual.getType()); ctx.addModifiers(actual.getModifiers()); } } else { Type t2 = first.getType(); Type t3 = second.getType(); if( first.getModifiers().isNullable() || second.getModifiers().isNullable() ) ctx.addModifiers(Modifiers.NULLABLE); if( first.getModifiers().isNullable() != second.getModifiers().isNullable() && (t2 instanceof ArrayType || t3 instanceof ArrayType ) ) addError(ctx, Error.INVALID_MODIFIER, "Cannot mix nullable and non-nullable arrays", t2, t3); if( first.getModifiers().isReadonly() || second.getModifiers().isReadonly() ) ctx.addModifiers(Modifiers.READONLY); else if( first.getModifiers().isTemporaryReadonly() || second.getModifiers().isTemporaryReadonly() ) ctx.addModifiers(Modifiers.TEMPORARY_READONLY); if( first.getModifiers().isImmutable() && second.getModifiers().isImmutable() ) ctx.addModifiers(Modifiers.IMMUTABLE); else if( first.getModifiers().isImmutable() || second.getModifiers().isImmutable() ) //immutable + regular = readonly, works for either ctx.addModifiers(Modifiers.READONLY); if( t2.isSubtype(t3) ) ctx.setType(t3); else if( t3.isSubtype(t2) ) ctx.setType(t2); else { addError(ctx, Error.MISMATCHED_TYPE, "Supplied type " + t2 + " must match " + t3 + " in execution of conditional operator", t2, t3); ctx.setType(Type.UNKNOWN); } } } return null; } @Override public Void visitThrowOrConditionalExpression(ThrowOrConditionalExpressionContext ctx) { visitChildren(ctx); ConditionalExpressionContext cond = ctx.conditionalExpression(); if(cond != null) { ctx.setType(cond.getType()); ctx.addModifiers(cond.getModifiers()); } return null; } public void visitConditional(Context node) { if( node.getChildCount() == 1 ) { Context child = (Context) node.getChild(0); node.setType(child.getType()); node.addModifiers(child.getModifiers()); } else { Type result = null; for( int i = 0; i < node.getChildCount(); i += 2 ) { Context child = (Context)node.getChild(i); result = child.getType(); if( result != Type.BOOLEAN ) { addError(child, Error.INVALID_TYPE, "Supplied type " + result + " cannot be used with a logical operator, boolean type required", result); node.setType(Type.UNKNOWN); return; } } node.setType(result); } } @Override public Void visitCoalesceExpression(ShadowParser.CoalesceExpressionContext ctx) { visitChildren(ctx); if( ctx.getChildCount() == 1 ) { Context child = (Context) ctx.getChild(0); ctx.setType(child.getType()); ctx.addModifiers(child.getModifiers()); } else { Type result = null; boolean isNullable = true; int term = 0; for( ShadowParser.ConditionalOrExpressionContext child : ctx.conditionalOrExpression() ) { //cycle through types, upgrading to broadest legal one Type type = child.getType(); Modifiers modifiers = child.getModifiers(); term++; if( !modifiers.isNullable() ) { isNullable = false; if( term < ctx.conditionalOrExpression().size() ) { //only last child can be nullable addError(child, Error.INVALID_TYPE, "Only the last term in a coalesce expression can be non-nullable"); result = Type.UNKNOWN; break; } } if( type instanceof ArrayType ) addError(child, Error.INVALID_TYPE, "Array type cannot be used in a coalesce expression"); if( result == null ) result = type; else if( result.isSubtype(type) ) result = type; else if( !type.isSubtype(result) ) { //neither is subtype of other, panic! addError(ctx, Error.MISMATCHED_TYPE, "Supplied type " + type + " does not match type " + result + " in coalesce expression", type, result); result = Type.UNKNOWN; break; } } ctx.setType(result); if( isNullable ) ctx.addModifiers(Modifiers.NULLABLE); } return null; } @Override public Void visitConditionalOrExpression(ShadowParser.ConditionalOrExpressionContext ctx) { visitChildren(ctx); visitConditional(ctx); return null; } @Override public Void visitConditionalExclusiveOrExpression(ShadowParser.ConditionalExclusiveOrExpressionContext ctx) { visitChildren(ctx); visitConditional(ctx); return null; } @Override public Void visitConditionalAndExpression(ShadowParser.ConditionalAndExpressionContext ctx) { visitChildren(ctx); visitConditional(ctx); return null; } public void visitBitwise(Context node ) { Type result = ((Context)node.getChild(0)).getType(); for( int i = 1; i < node.getChildCount(); i += 2 ) { String operator = node.getChild(i).getText(); Context currentNode = (Context)node.getChild(i + 1); Type current = currentNode.getType(); String methodName = ""; switch( operator ) { case "|": methodName = "bitOr"; break; case "&": methodName = "bitAnd"; break; case "^": methodName = "bitXor"; break; } if( result.hasUninstantiatedInterface(Type.INTEGER) ) { SequenceType argument = new SequenceType(); argument.add(currentNode); MethodSignature signature = setMethodType(node, result, methodName, argument ); if( signature != null ) { result = signature.getReturnTypes().getType(0); node.addOperation(signature); } else { addError(node, Error.INVALID_TYPE, "Operator " + operator + " not defined on types " + result + " and " + current, result, current); node.setType(Type.UNKNOWN); break; } } else { addError(node, Error.INVALID_TYPE, "Operator " + operator + " not defined on types " + result + " and " + current, result, current); node.setType(Type.UNKNOWN); break; } } node.setType(result); if( node.getChildCount() == 1) //can make ASSIGNABLE (if only one child) node.addModifiers(((Context)node.getChild(0)).getModifiers()); } @Override public Void visitBitwiseOrExpression(ShadowParser.BitwiseOrExpressionContext ctx) { visitChildren(ctx); visitBitwise(ctx); return null; } @Override public Void visitBitwiseExclusiveOrExpression(ShadowParser.BitwiseExclusiveOrExpressionContext ctx) { visitChildren(ctx); visitBitwise(ctx); return null; } @Override public Void visitBitwiseAndExpression(ShadowParser.BitwiseAndExpressionContext ctx) { visitChildren(ctx); visitBitwise(ctx); return null; } @Override public Void visitClassOrInterfaceType(ShadowParser.ClassOrInterfaceTypeContext ctx) { if( ctx.getType() != null && !(ctx.getType() instanceof UninstantiatedType) ) // Optimization if type already determined. return null; visitChildren(ctx); String typeName = ctx.Identifier(0).getText(); if( ctx.unqualifiedName() != null ) typeName = ctx.unqualifiedName().getText() + "@" + typeName; Type type = lookupType(ctx, typeName); for( int i = 1; type != null && i < ctx.Identifier().size(); ++i ) { typeName = ctx.Identifier(i).getText(); type = type.getInnerType(typeName); } if( type == null ) { ctx.setType(Type.UNKNOWN); addError(ctx, Error.UNDEFINED_TYPE, "Type " + typeName + " not defined in this context"); return null; } if( !typeIsAccessible( type, currentType ) ) addError(ctx, Error.ILLEGAL_ACCESS, "Type " + type + " not accessible from this context", type); if( ctx.typeArguments() != null ) { // Contains type arguments. SequenceType arguments = (SequenceType) ctx.typeArguments().getType(); if( type.isParameterized() ) { SequenceType parameters = type.getTypeParameters(); if( parameters.canAccept(arguments, SubstitutionKind.TYPE_PARAMETER ) ) { try { type = type.replace(parameters, arguments); } catch (InstantiationException e) { addError(ctx.typeArguments(), Error.INVALID_TYPE_ARGUMENTS, "Supplied type arguments " + arguments.toString( Type.PACKAGES | Type.TYPE_PARAMETERS | Type.PARAMETER_BOUNDS ) + " do not match type parameters " + parameters.toString( Type.PACKAGES | Type.TYPE_PARAMETERS | Type.PARAMETER_BOUNDS ) ); type = Type.UNKNOWN; } } else { addError(ctx.typeArguments(), Error.INVALID_TYPE_ARGUMENTS, "Supplied type arguments " + arguments.toString( Type.PACKAGES | Type.TYPE_PARAMETERS | Type.PARAMETER_BOUNDS ) + " do not match type parameters " + parameters.toString( Type.PACKAGES | Type.TYPE_PARAMETERS | Type.PARAMETER_BOUNDS ) ); type = Type.UNKNOWN; } } else { addError(ctx.typeArguments(), Error.UNNECESSARY_TYPE_ARGUMENTS, "Type arguments supplied for non-parameterized type " + type, type ); type = Type.UNKNOWN; } } else if( type.isParameterized() ) { // Parameterized but no parameters! addError(ctx, Error.MISSING_TYPE_ARGUMENTS, "Type arguments are not supplied for parameterized type " + type); type = Type.UNKNOWN; } // After updating type parameters if( currentType instanceof ClassType ) currentType.addUsedType(type); // Set the type now that it has been fully initialized. ctx.setType( type ); return null; } @Override public Void visitArguments(ShadowParser.ArgumentsContext ctx) { visitChildren(ctx); SequenceType sequence = new SequenceType(); for( ShadowParser.ConditionalExpressionContext child : ctx.conditionalExpression() ) sequence.add(child); ctx.setType(sequence); return null; } @Override public Void visitSequenceAssignment(ShadowParser.SequenceAssignmentContext ctx) { visitChildren(ctx); ShadowParser.SequenceLeftSideContext left = ctx.sequenceLeftSide(); SequenceType leftSequence = (SequenceType)left.getType(); ShadowParser.RightSideContext right = ctx.rightSide(); Type rightType = right.getType(); ModifiedType rightElement = right; //check lengths first if( rightType instanceof SequenceType && leftSequence.size() != ((SequenceType)rightType).size() ) { addError(ctx, Error.INVALID_ASSIGNMENT, "Right hand side " + ((SequenceType)rightType) + " cannot be assigned to left hand side " + leftSequence + " because their lengths do not match"); return null; } for( int i = 0; i < leftSequence.size(); ++i ) { ModifiedType leftElement = leftSequence.get(i); if( leftElement != null ) { //can be skipped if( rightType instanceof SequenceType ) rightElement = ((SequenceType)rightType).get(i); if( leftElement.getType().equals( Type.VAR ) ) { Type type = resolveType( rightElement).getType(); if( leftElement.getModifiers().isNullable() && type instanceof ArrayType ) { ArrayType arrayType = (ArrayType) type; type = arrayType.convertToNullable(); } leftElement.setType(type); } if( leftElement instanceof ShadowParser.SequenceVariableContext ) { //declaration if( leftElement.getModifiers().isNullable() && leftElement.getType() instanceof ArrayType && ((ArrayType)leftElement.getType()).recursivelyGetBaseType().isPrimitive() ) addError(ctx, Error.INVALID_MODIFIER, "Primitive array type " + leftElement.getType() + " cannot be marked nullable"); addErrors(ctx, isValidInitialization(leftElement, rightElement)); } else //otherwise simple assignment addErrors(ctx, isValidAssignment(leftElement, rightElement, AssignmentKind.EQUAL)); } } return null; } @Override public Void visitExpression(ShadowParser.ExpressionContext ctx) { visitChildren(ctx); if( ctx.assignmentOperator() != null ) { //if there is assignment ShadowParser.PrimaryExpressionContext left = ctx.primaryExpression(); AssignmentKind kind = AssignmentKind.getKind(ctx.assignmentOperator().getText()); ShadowParser.ConditionalExpressionContext right = ctx.conditionalExpression(); List<ShadowException> errors = isValidAssignment(left, right, kind); if( errors.isEmpty() ) { Type leftType = left.getType(); Type rightType = right.getType(); if( leftType instanceof PropertyType ) { PropertyType getSetType = (PropertyType) leftType; leftType = getSetType.getSetType().getType(); } if( rightType instanceof PropertyType ) rightType = ((PropertyType)rightType).getGetType().getType(); // let unbound method type know what signature it will eventually be bound to if( rightType instanceof UnboundMethodType && leftType instanceof MethodReferenceType ) { UnboundMethodType unboundType = (UnboundMethodType) rightType; MethodType methodType = ((MethodReferenceType) leftType).getMethodType(); MethodSignature signature = unboundType.getOuter().getMatchingMethod(unboundType.getTypeName(), methodType.getParameterTypes()); unboundType.setKnownSignature( signature ); } ctx.addOperation(leftType.getMatchingMethod(kind.getMethod(), new SequenceType(rightType))); } else addErrors(ctx, errors); } else { //did something actually happen? if( !ctx.primaryExpression().action ) addError(ctx, Error.NO_ACTION, "Statement does not perform an action"); } return null; } @Override public Void visitIsExpression(ShadowParser.IsExpressionContext ctx) { visitChildren(ctx); if( ctx.getChildCount() == 1 ) { Context child = (Context) ctx.getChild(0); ctx.setType(child.getType()); ctx.addModifiers(child.getModifiers()); } else { Type t1 = ctx.relationalExpression().getType(); Type t2 = ctx.type().getType(); if( t1.isSubtype(t2) || t2.isSubtype(t1) ) ctx.setType(Type.BOOLEAN); else { addError(ctx, Error.MISMATCHED_TYPE, "Supplied type " + t1 + " cannot be compared with type " + t2 + " in an is statement", t1, t2); ctx.setType(Type.UNKNOWN); } if( t1 instanceof SingletonType || t2 instanceof SingletonType ) addError(ctx, Error.MISMATCHED_TYPE, "Cannot use singleton types in an is statement"); else { if( ctx.relationalExpression().getModifiers().isTypeName() ) addError(ctx.relationalExpression(), Error.NOT_OBJECT, "Left hand side of is statement cannot be a type name"); if( !ctx.type().getModifiers().isTypeName() ) addError(ctx.type(), Error.NOT_TYPE, "Right hand side of is statement must be a type name"); } } return null; } @Override public Void visitTypeParameters(ShadowParser.TypeParametersContext ctx) { //skip class declarations (already done in type updater) //also means that TypeParameter will never be visited return null; } @Override public Void visitFunctionType(ShadowParser.FunctionTypeContext ctx) { visitChildren(ctx); MethodType methodType = new MethodType(); ShadowParser.ResultTypesContext parameters = ctx.resultTypes(0); SequenceType parameterTypes = (SequenceType) parameters.getType(); ShadowParser.ResultTypesContext returns = ctx.resultTypes(1); SequenceType returnTypes = (SequenceType) returns.getType(); for( ModifiedType parameter : parameterTypes ) methodType.addParameter(parameter); for( ModifiedType type : returnTypes ) methodType.addReturn(type); ctx.setType(new MethodReferenceType(methodType)); ctx.addModifiers(Modifiers.TYPE_NAME); return null; } @Override public Void visitResultTypes(ShadowParser.ResultTypesContext ctx) { visitChildren(ctx); SequenceType sequence = new SequenceType(); for( ShadowParser.ResultTypeContext child : ctx.resultType() ) sequence.add(child); ctx.setType(sequence); return null; } @Override public Void visitInlineResults(ShadowParser.InlineResultsContext ctx) { visitChildren(ctx); SequenceType sequence = new SequenceType(); for(ShadowParser.ConditionalExpressionContext child : ctx.conditionalExpression() ) sequence.add(child); ctx.setType(sequence); return null; } @Override public Void visitCastExpression(ShadowParser.CastExpressionContext ctx) { visitChildren(ctx); ShadowParser.TypeContext type = ctx.type(); ShadowParser.ConditionalExpressionContext expression = ctx.conditionalExpression(); Type t1 = type.getType(); //type Type t2 = expression.getType(); //expression ctx.addModifiers(expression.getModifiers()); ctx.getModifiers().removeModifier(Modifiers.ASSIGNABLE); if( ctx.getChild(2).getText().equals("nullable") ) { if( t1 instanceof ArrayType ) { t1 = ((ArrayType)t1).convertToNullable(); ctx.addModifiers(Modifiers.NULLABLE); } else addError(ctx, Error.INVALID_CAST, "Can only specify nullable for array types in casts"); } if( t1 instanceof MethodType && t2 instanceof UnboundMethodType ) { //casting methods MethodType method = (MethodType)t1; UnboundMethodType unboundMethod = (UnboundMethodType)t2; MethodSignature candidate = null; Type outer = unboundMethod.getOuter(); for( MethodSignature signature : outer.recursivelyGetMethodOverloads(unboundMethod.getTypeName()) ) { MethodType methodType = signature.getMethodType(); //the list of method signatures starts with the closest (current class) and then adds parents and outer classes //always stick with the current if you can //(only replace if signature is a subtype of candidate but candidate is not a subtype of signature) if( methodType.isSubtype(method)) { if( candidate == null || (candidate.getMethodType().isSubtype(methodType) )) //take the broadest method possible that matches the cast target candidate = signature; else if( !methodType.isSubtype(candidate.getMethodType()) ) { //then two acceptable signatures are not subtypes of each other addError(ctx, Error.INVALID_ARGUMENTS, "Ambiguous cast from " + unboundMethod.getTypeName() + " to " + method); break; } } } if( candidate == null ) addError(ctx, Error.INVALID_METHOD, "No definition of " + unboundMethod.getTypeName() + " matches type " + method); else ctx.setType(candidate.getMethodType()); } else if( t1.isNumerical() && t2.isNumerical() ) //some numerical types (int and uint) are not superclasses or subclasses of each other //for convenience, all numerical types should be castable ctx.setType(t1); else if( t1.isSubtype(t2) || t2.isSubtype(t1) ) ctx.setType(t1); else { addError(ctx, Error.MISMATCHED_TYPE, "Supplied type " + t2 + " cannot be cast to type " + t1, t1, t2); ctx.setType(Type.UNKNOWN); } return null; } @Override public Void visitRightSide(ShadowParser.RightSideContext ctx) { visitChildren(ctx); Context child = (Context) ctx.getChild(0); ctx.setType(child.getType()); ctx.addModifiers(child.getModifiers()); return null; } @Override public Void visitSequenceRightSide(ShadowParser.SequenceRightSideContext ctx) { visitChildren(ctx); SequenceType sequence = new SequenceType(); for(ShadowParser.ConditionalExpressionContext child : ctx.conditionalExpression() ) sequence.add(child); ctx.setType(sequence); return null; } @Override public Void visitSequenceVariable(ShadowParser.SequenceVariableContext ctx) { visitChildren(ctx); if( ctx.type() != null ) ctx.setType(ctx.type().getType()); else ctx.setType(Type.VAR); addSymbol(ctx.Identifier().getText(), ctx); return null; } @Override public Void visitSequenceLeftSide(ShadowParser.SequenceLeftSideContext ctx) { visitChildren(ctx); SequenceType sequence = new SequenceType(); //skip first because it's a parenthesis for( int i = 1; i < ctx.getChildCount(); ++i ) { ParseTree child = ctx.getChild(i); if( child instanceof Context ) { sequence.add((Context)child); ++i; //to skip the next comma } else sequence.add(null); } ctx.setType(sequence); return null; } @Override public Void visitIfStatement(ShadowParser.IfStatementContext ctx) { visitChildren(ctx); Type type = ctx.conditionalExpression().getType(); if( !type.equals(Type.BOOLEAN) ) addError(ctx.conditionalExpression(), Error.INVALID_TYPE, "Condition of if statement cannot accept non-boolean type " + type, type); return null; } @Override public Void visitWhileStatement(ShadowParser.WhileStatementContext ctx) { visitChildren(ctx); Type type = ctx.conditionalExpression().getType(); if( !type.equals(Type.BOOLEAN) ) addError(ctx.conditionalExpression(), Error.INVALID_TYPE, "Condition of while statement cannot accept non-boolean type " + type, type); return null; } @Override public Void visitDoStatement(ShadowParser.DoStatementContext ctx) { visitChildren(ctx); Type type = ctx.conditionalExpression().getType(); if( !type.equals(Type.BOOLEAN) ) addError(ctx.conditionalExpression(), Error.INVALID_TYPE, "Condition of do statement cannot accept non-boolean type " + type, type); return null; } @Override public Void visitForeachStatement(ShadowParser.ForeachStatementContext ctx) { openScope(); visitChildren(ctx); closeScope(); return null; } @Override public Void visitForeachInit(ShadowParser.ForeachInitContext ctx) { visitChildren(ctx); Type collectionType = ctx.conditionalExpression().getType(); ModifiedType element = null; boolean isVar = false; boolean iterable = true; if( ctx.type() != null ) ctx.setType(ctx.type().getType()); else { //var type ctx.setType(Type.UNKNOWN); isVar = true; } if( collectionType instanceof ArrayType ) { ArrayType array = (ArrayType)collectionType; element = new SimpleModifiedType( array.getBaseType() ); if( array.isNullable() ) element.getModifiers().addModifier(Modifiers.NULLABLE); } else if( collectionType.hasUninstantiatedInterface(Type.CAN_ITERATE) ) { for(InterfaceType _interface : collectionType.getAllInterfaces() ) if( _interface.getTypeWithoutTypeArguments().equals(Type.CAN_ITERATE)) { element = _interface.getTypeParameters().get(0); break; } } else if( collectionType.hasUninstantiatedInterface(Type.CAN_ITERATE_NULLABLE) ) { for(InterfaceType _interface : collectionType.getAllInterfaces() ) if( _interface.getTypeWithoutTypeArguments().equals(Type.CAN_ITERATE_NULLABLE)) { element = _interface.getTypeParameters().get(0); break; } } else { addError(ctx.conditionalExpression(), Error.INVALID_TYPE, "Supplied type " + collectionType + " does not implement " + Type.CAN_ITERATE + " or " + Type.CAN_ITERATE_NULLABLE + " and cannot be the target of a foreach statement", collectionType); iterable = false; } if( iterable ) { if( isVar && element != null && element.getType() != null ) { Type elementType = element.getType(); ctx.setType(elementType); if( ctx.getModifiers().isNullable() ) { if( elementType instanceof ArrayType ) { ArrayType arrayType = (ArrayType) elementType; if( arrayType.recursivelyGetBaseType().isPrimitive() ) addError(ctx, Error.INVALID_MODIFIER, "Primitive array type " + elementType + " cannot be marked nullable"); } } } List<ShadowException> errors = isValidInitialization( ctx, element); if( errors.isEmpty() ) addSymbol(ctx.Identifier().getText(), ctx); else addErrors(ctx, errors); } return null; } @Override public Void visitForStatement(ShadowParser.ForStatementContext ctx) { openScope(); visitChildren(ctx); closeScope(); Type type = ctx.conditionalExpression().getType(); if( !type.equals(Type.BOOLEAN) ) addError(ctx.conditionalExpression(), Error.INVALID_TYPE, "Condition of for statement cannot accept non-boolean type " + type, type); return null; } @Override public Void visitThrowStatement(ShadowParser.ThrowStatementContext ctx) { visitChildren(ctx); Type type = ctx.conditionalExpression().getType(); if( !(type instanceof ExceptionType) ) addError(ctx.conditionalExpression(), Error.INVALID_TYPE, "Supplied type " + type + " cannot be used in a throw clause, exception or error type required", type); return null; } @Override public Void visitCatchStatements(ShadowParser.CatchStatementsContext ctx) { visitChildren(ctx); List<Type> types = new ArrayList<Type>(); for( ShadowParser.CatchStatementContext child : ctx.catchStatement() ) { Type type = child.getType(); for( Type catchParameter : types ) if( type.isSubtype(catchParameter) ) { addError(child, Error.UNREACHABLE_CODE, "Catch block for exception " + type + " cannot be reached", type ); break; } types.add(type); } return null; } @Override public Void visitCatchStatement(ShadowParser.CatchStatementContext ctx) { openScope(); // For catch parameter visitChildren(ctx); closeScope(); ShadowParser.FormalParameterContext child = ctx.formalParameter(); Type type = child.getType(); if( !(type instanceof ExceptionType) ) { addError( child, Error.INVALID_TYPE, "Supplied type " + type + " cannot be used as a catch parameter, exception types required", type); ctx.setType(Type.UNKNOWN); } else ctx.setType(type); if( child.getModifiers().getModifiers() != 0 ) addError( child, Error.INVALID_MODIFIER, "Modifiers cannot be applied to a catch parameter"); return null; } @Override public Void visitCopyExpression(ShadowParser.CopyExpressionContext ctx) { visitChildren(ctx); ModifiedType child = ctx.conditionalExpression(); child = resolveType( child ); ctx.addModifiers(child.getModifiers()); if( ctx.getChild(0).getText().equals("freeze") ) ctx.addModifiers(Modifiers.IMMUTABLE); ctx.setType(child.getType()); return null; } @Override public Void visitCheckExpression(ShadowParser.CheckExpressionContext ctx) { visitChildren(ctx); ModifiedType child = ctx.conditionalExpression(); child = resolveType( child ); Type type = child.getType(); if( child.getModifiers().isNullable() ) { ctx.addModifiers(child.getModifiers()); ctx.getModifiers().removeModifier(Modifiers.NULLABLE); } else addError(ctx.conditionalExpression(), Error.INVALID_TYPE, "Non-nullable expression cannot be used in a check statement"); ctx.setType(type); ParserRuleContext parent = ctx.getParent(); boolean foundRecover = false; boolean foundFinally = false; /* catchStatements : tryStatement catchStatement* ('recover' block )? ; */ while(parent != null && !foundRecover) { // Trying to check out of a finally if(parent instanceof ShadowParser.BlockContext && parent.getParent() instanceof ShadowParser.FinallyStatementContext) foundFinally = true; // Legitimate recover first (we're inside of a try that has a matching recover) if( parent instanceof ShadowParser.TryStatementContext) { ShadowParser.CatchStatementsContext grandparent = (CatchStatementsContext) parent.getParent(); if(grandparent.block() != null) foundRecover = true; } else parent = parent.getParent(); } if(foundFinally) addError(ctx, Error.INVALID_STRUCTURE, "check statement cannot branch out of a finally block to a recover"); return null; } @Override public Void visitPrimaryExpression(ShadowParser.PrimaryExpressionContext ctx) { curPrefix.addFirst(null); visitChildren(ctx); if( !ctx.primarySuffix().isEmpty() ) { //has suffixes, pull type from last suffix ShadowParser.PrimarySuffixContext last = ctx.primarySuffix(ctx.primarySuffix().size() - 1); //this primary expression is the left side of an assignment if( ctx.getParent() instanceof ShadowParser.ExpressionContext || ctx.getParent() instanceof ShadowParser.SequenceLeftSideContext ) { Type type = last.getType(); //if PropertyType, preserve that ctx.addModifiers(last.getModifiers()); ctx.setType(type); } else { ModifiedType modifiedType = resolveType( last ); //otherwise, strip away the property ctx.addModifiers(modifiedType.getModifiers()); ctx.setType(modifiedType.getType()); } } else { //just prefix ShadowParser.PrimaryPrefixContext child = ctx.primaryPrefix(); ctx.setType(child.getType()); ctx.addModifiers(child.getModifiers()); if(child.spawnExpression() != null) { ctx.action = true; currentType.addUsedType(Type.THREAD); } } curPrefix.removeFirst(); //pop prefix type off stack return null; } private void checkForSingleton(Type type) { //if singleton, add to current method for initialization if( type instanceof SingletonType ) { SingletonType singletonType = (SingletonType)type; if( currentMethod.isEmpty() ) { //don't add a singleton to itself, could cause infinite recursion if( !currentType.equals(type) ) //add to all creates (since it must be declared outside a method) for( MethodSignature signature : currentType.recursivelyGetMethodOverloads("create")) signature.addSingleton(singletonType); } else { //don't add a singleton to itself, could cause infinite recursion if( !currentType.equals(type) ) { int i = 0; Context signatureNode; //find outer method, instead of adding to local or inline methods do { signatureNode = currentMethod.get(i); i++; } while( signatureNode instanceof ShadowParser.InlineMethodDefinitionContext || signatureNode instanceof ShadowParser.LocalMethodDeclarationContext ); signatureNode.getSignature().addSingleton(singletonType); } } } else if( type instanceof SequenceType ) { SequenceType sequenceType = (SequenceType) type; for(ModifiedType modifiedType : sequenceType ) checkForSingleton(modifiedType.getType()); } else if( type instanceof ArrayType ) checkForSingleton(((ArrayType)type).getBaseType()); } @Override public Void visitPrimaryPrefix(ShadowParser.PrimaryPrefixContext ctx) { visitChildren(ctx); String image = ctx.getText(); if( image.equals("this") || image.equals("super") ) { if( currentType instanceof InterfaceType ) { addError(ctx, Error.INVALID_SELF_REFERENCE, "Reference " + image + " invalid for interfaces"); ctx.setType(Type.UNKNOWN); } else { if( image.equals("this") ) ctx.setType(currentType); else ctx.setType(((ClassType) currentType).getExtendType()); if( currentType.getModifiers().isImmutable() ) ctx.addModifiers(Modifiers.IMMUTABLE); else if( currentType.getModifiers().isReadonly() ) ctx.addModifiers(Modifiers.READONLY); Modifiers methodModifiers = Modifiers.NO_MODIFIERS; if(!currentMethod.isEmpty() ) methodModifiers = currentMethod.getFirst().getModifiers(); //upgrade if current method is non-mutable if( methodModifiers.isImmutable() || methodModifiers.isReadonly() ) ctx.getModifiers().upgradeToTemporaryReadonly(); } } else if( ctx.generalIdentifier() != null ) { if(!setTypeFromName( ctx, image )) { addError(ctx, Error.UNDEFINED_SYMBOL, "Symbol " + image + " not defined in this context"); ctx.setType(Type.UNKNOWN); } } else if( ctx.conditionalExpression() != null ) { ctx.setType(ctx.conditionalExpression().getType()); ctx.addModifiers(ctx.conditionalExpression().getModifiers()); } // literal, check expression, copy expression, cast expression, // primitive and function types, and array initializer else { Context child = (Context) ctx.getChild(0); ctx.setType(child.getType()); ctx.addModifiers(child.getModifiers()); } checkForSingleton(ctx.getType()); curPrefix.set(0, ctx); //so that the suffix can figure out where it's at return null; } @Override public Void visitTypeArguments(ShadowParser.TypeArgumentsContext ctx) { visitChildren(ctx); SequenceType sequence = new SequenceType(); for( ShadowParser.TypeContext child : ctx.type() ) sequence.add(child); ctx.setType(sequence); return null; } @Override public Void visitPrimarySuffix(ShadowParser.PrimarySuffixContext ctx) { visitChildren(ctx); Context prefixNode = curPrefix.getFirst(); if( prefixNode.getModifiers().isNullable() && !(prefixNode.getType() instanceof ArrayType) ) addError(prefixNode, Error.INVALID_DEREFERENCE, "Nullable reference cannot be dereferenced"); if( ctx.property() != null || ctx.methodCall() != null || ctx.allocation() != null ) { ShadowParser.PrimaryExpressionContext parent = (PrimaryExpressionContext) ctx.getParent(); parent.action = true; } if( ctx.methodCall() != null ) { Type childType = ctx.methodCall().getType(); if( childType instanceof MethodType ) { MethodType methodType = (MethodType) childType; SequenceType returnTypes = methodType.getReturnTypes(); returnTypes.setContextType( ctx ); //used instead of setType } else ctx.setType(Type.UNKNOWN); } else { Context child = (Context) ctx.getChild(0); ctx.setType(child.getType()); ctx.addModifiers(child.getModifiers()); } checkForSingleton(ctx.getType()); curPrefix.set(0, ctx); //so that a future suffix can figure out where it's at return null; } @Override public Void visitBrackets(ShadowParser.BracketsContext ctx) { visitChildren(ctx); ModifiedType prefixNode = curPrefix.getFirst(); prefixNode = resolveType( prefixNode ); Type prefixType = prefixNode.getType(); if( prefixNode.getModifiers().isTypeName() && !(prefixType instanceof ArrayType) ) { ctx.setType(new ArrayType( prefixType, getDimensions(ctx), false) ); ctx.addModifiers(Modifiers.TYPE_NAME); } else { addError(curPrefix.getFirst(), Error.NOT_TYPE, "Can only apply brackets to a type name"); ctx.setType(Type.UNKNOWN); } return null; } @Override public Void visitSubscript(ShadowParser.SubscriptContext ctx) { visitChildren(ctx); ModifiedType prefixNode = curPrefix.getFirst(); prefixNode = resolveType( prefixNode ); Type prefixType = prefixNode.getType(); if( prefixType instanceof ArrayType && !(((ArrayType)prefixType).getBaseType() instanceof TypeParameter) ) { ArrayType arrayType = (ArrayType)prefixType; ShadowParser.ConditionalExpressionContext child = ctx.conditionalExpression(); Type childType = child.getType(); if( !childType.isSubtype(Type.LONG) ) { addError(child, Error.INVALID_SUBSCRIPT, "Subscript type " + childType + " is invalid, must be subtype of " + Type.LONG, childType); ctx.setType(Type.UNKNOWN); return null; } ctx.setType( arrayType.getBaseType() ); if( prefixNode.getModifiers().isImmutable() ) ctx.addModifiers(Modifiers.IMMUTABLE); else if( prefixNode.getModifiers().isReadonly() ) ctx.addModifiers(Modifiers.READONLY); else if( prefixNode.getModifiers().isTemporaryReadonly() ) ctx.addModifiers(Modifiers.TEMPORARY_READONLY); else ctx.addModifiers(Modifiers.ASSIGNABLE); //backdoor for creates //immutable and readonly array should only be assignable in creates if( prefixNode.getModifiers().isAssignable() ) ctx.addModifiers(Modifiers.ASSIGNABLE); //primitive arrays are initialized to default values //non-primitive array elements could be null //however, arrays of arrays are not-null //instead, they will be filled with default values, including a length of zero //thus, we don't need to check nullability, but we do need a range check //nullable array means what you get out is nullable, not the array itself if( arrayType.isNullable() ) ctx.addModifiers(Modifiers.NULLABLE); } else if( prefixType.hasUninstantiatedInterface(Type.CAN_INDEX) || prefixType.hasUninstantiatedInterface(Type.CAN_INDEX_NULLABLE) || prefixType.hasUninstantiatedInterface(Type.CAN_INDEX_STORE) || prefixType.hasUninstantiatedInterface(Type.CAN_INDEX_STORE_NULLABLE)) { SequenceType arguments = new SequenceType(); ShadowParser.ConditionalExpressionContext child = ctx.conditionalExpression(); arguments.add(child); MethodSignature signature = setMethodType( ctx, prefixType, "index", arguments); if( signature != null && (prefixNode.getModifiers().isReadonly() || prefixNode.getModifiers().isTemporaryReadonly() || prefixNode.getModifiers().isImmutable()) && signature.getModifiers().isMutable() ) { ctx.setType(Type.UNKNOWN); addError(ctx, Error.INVALID_SUBSCRIPT, "Cannot apply mutable subscript to immutable or readonly prefix"); } else { //if signature is null, then it is not a load SubscriptType subscriptType = new SubscriptType(signature, child, new UnboundMethodType("index", prefixType), prefixNode, currentType); ctx.setType(subscriptType); if( signature != null ) ctx.addModifiers(subscriptType.getGetType().getModifiers()); if( prefixNode.getModifiers().isImmutable() ) ctx.addModifiers(Modifiers.IMMUTABLE); else if( prefixNode.getModifiers().isReadonly() ) ctx.addModifiers(Modifiers.READONLY); else if( prefixNode.getModifiers().isTemporaryReadonly() ) ctx.addModifiers(Modifiers.TEMPORARY_READONLY); else if( prefixType.hasUninstantiatedInterface(Type.CAN_INDEX_STORE) || prefixType.hasUninstantiatedInterface(Type.CAN_INDEX_STORE_NULLABLE) ) ctx.addModifiers(Modifiers.ASSIGNABLE); } } else { ctx.setType(Type.UNKNOWN); addError(ctx, Error.INVALID_SUBSCRIPT, "Subscript is not permitted for type " + prefixType + " because it does not implement " + Type.CAN_INDEX + ", " + Type.CAN_INDEX_STORE + ", " + Type.CAN_INDEX_NULLABLE + ", or " + Type.CAN_INDEX_STORE_NULLABLE, prefixType); } return null; } @Override public Void visitDestroy(ShadowParser.DestroyContext ctx) { visitChildren(ctx); Context prefixNode = curPrefix.getFirst(); Type prefixType = prefixNode.getType(); if( prefixNode.getModifiers().isTypeName() ) addError(prefixNode, Error.INVALID_DESTROY, "Type name cannot be destroyed"); else if( prefixType instanceof UnboundMethodType ) addError(prefixNode, Error.INVALID_DESTROY, "Method cannot be destroyed"); else if( prefixType instanceof PropertyType ) addError(prefixNode, Error.INVALID_DESTROY, "Property cannot be destroyed"); ctx.setType(Type.UNKNOWN); //destruction has no type //TODO: make sure an error is reported if someone tries to do something to a destroy return null; } @Override public Void visitArrayCreate(ShadowParser.ArrayCreateContext ctx) { visitChildren(ctx); Context prefixNode = curPrefix.getFirst(); Type prefixType = prefixNode.getType(); SequenceType typeArguments = null; int nullOrCreateLocation = 1; ctx.prefixType = prefixType; boolean nullable = false; if( ctx.typeArguments() != null ) { typeArguments = (SequenceType)ctx.typeArguments().getType(); nullOrCreateLocation++; } ShadowParser.ArrayDimensionsContext dimensions = ctx.arrayDimensions(); if( ctx.getChild(nullOrCreateLocation).getText().equals("null") ) { nullable = true; ctx.addModifiers(Modifiers.NULLABLE); if( prefixType instanceof ArrayType ) { ArrayType arrayType = (ArrayType) prefixType; prefixType = arrayType.convertToNullable(); } } //create array if( prefixNode.getModifiers().isTypeName() ) { ArrayType arrayType = null; if( typeArguments != null ) { if( prefixType.isParameterized() ) { if( prefixType.getTypeParameters().canAccept(typeArguments, SubstitutionKind.TYPE_PARAMETER) ) { try { prefixType = prefixType.replace(prefixType.getTypeParameters(), typeArguments); arrayType = new ArrayType( prefixType, getDimensions(dimensions), nullable ); ctx.setType( arrayType ); } catch (InstantiationException e) { addError(ctx.typeArguments(), Error.INVALID_TYPE_ARGUMENTS, "Supplied type arguments " + typeArguments + " do not match type parameters " + prefixType.getTypeParameters() ); ctx.setType(Type.UNKNOWN); } } else { addError(ctx.typeArguments(), Error.INVALID_TYPE_ARGUMENTS, "Supplied type arguments " + typeArguments + " do not match type parameters " + prefixType.getTypeParameters() ); ctx.setType(Type.UNKNOWN); } } else { addError(ctx.typeArguments(), Error.UNNECESSARY_TYPE_ARGUMENTS, "Type arguments " + typeArguments + " supplied for non-parameterized type " + prefixType, prefixType); ctx.setType(Type.UNKNOWN); } } else { if( !prefixType.isParameterized() ) { arrayType = new ArrayType( prefixType, getDimensions(dimensions), nullable ); ctx.setType( arrayType ); } else { addError(ctx, Error.MISSING_TYPE_ARGUMENTS, "Type arguments not supplied for paramterized type " + prefixType); ctx.setType(Type.UNKNOWN); } } currentType.addUsedType(arrayType); currentType.addPartiallyInstantiatedClass(arrayType); if( ctx.arrayCreateCall() != null ) { SequenceType arguments = (SequenceType) ctx.arrayCreateCall().getType(); MethodSignature signature = prefixType.getMatchingMethod("create", arguments, typeArguments); if( signature == null || !methodIsAccessible( signature, currentType) ) addError(ctx, Error.INVALID_CREATE, "Cannot create array of type " + prefixType + " with specified create arguments", prefixType); else if( prefixType instanceof InterfaceType ) addError(ctx, Error.INVALID_CREATE, "Cannot create non-nullable array of interface type " + prefixType, prefixType); else ctx.setSignature(signature); } else if( ctx.arrayDefault() != null ) { ShadowParser.ArrayDefaultContext child = ctx.arrayDefault(); Type baseType = arrayType.getBaseType(); if( child.getType().isSubtype(baseType) ) { if( child.getModifiers().isNullable() && !ctx.getModifiers().isNullable() ) addError(child, Error.INVALID_MODIFIER, "Cannot apply nullable default value to non-nullable array", child.getType(), baseType); } else addError(ctx.arrayDefault(), Error.INVALID_TYPE, "Cannot apply type " + child.getType() + " as default value in array of type " + arrayType, child.getType()); } else if( !nullable && !prefixType.isPrimitive() && !(prefixType instanceof ArrayType) ) { //try default constructor MethodSignature signature = prefixType.getMatchingMethod("create", new SequenceType(), typeArguments); if( signature == null || !methodIsAccessible( signature, currentType) ) addError(ctx, Error.INVALID_CREATE, "Cannot create array of type " + prefixType + " which does not implement a default create", prefixType); else if( prefixType instanceof InterfaceType ) addError(ctx, Error.INVALID_CREATE, "Cannot create non-nullable array of interface type " + prefixType, prefixType); else ctx.setSignature(signature); } } else { addError(prefixNode, Error.NOT_TYPE, "Type name must be used to create an array"); ctx.setType(Type.UNKNOWN); } return null; } @Override public Void visitArrayCreateCall(ShadowParser.ArrayCreateCallContext ctx) { visitChildren(ctx); SequenceType sequence = new SequenceType(); for( ShadowParser.ConditionalExpressionContext child : ctx.conditionalExpression() ) sequence.add(child); ctx.setType(sequence); return null; } @Override public Void visitArrayDefault(ShadowParser.ArrayDefaultContext ctx) { visitChildren(ctx); ctx.setType(ctx.conditionalExpression().getType()); ctx.addModifiers(ctx.conditionalExpression().getModifiers()); return null; } @Override public Void visitMethod(ShadowParser.MethodContext ctx) { visitChildren(ctx); //always part of a suffix, thus always has a prefix ModifiedType prefixNode = curPrefix.getFirst(); prefixNode = resolveType( prefixNode ); Type prefixType = prefixNode.getType(); String methodName = ctx.Identifier().getText(); if( prefixNode.getModifiers().isTypeName() && !(prefixType instanceof SingletonType) ) { addError(curPrefix.getFirst(), Error.NOT_OBJECT, "Type name cannot be used to call method"); } else if( prefixType instanceof SequenceType ) { addError(curPrefix.getFirst(), Error.INVALID_TYPE, "Method cannot be called on a sequence result"); } else if(prefixType != null) { List<MethodSignature> methods = prefixType.recursivelyGetMethodOverloads(methodName); //unbound method (it gets bound when you supply arguments) if( methods != null && methods.size() > 0 ) ctx.setType( new UnboundMethodType( methodName, prefixType ) ); else addError(ctx, Error.UNDEFINED_SYMBOL, "Method " + methodName + " not defined in this context"); } if( ctx.getType() == null ) ctx.setType( Type.UNKNOWN ); //these push the immutable or readonly modifier to the prefix of the call if( prefixNode.getModifiers().isImmutable() ) ctx.addModifiers(Modifiers.IMMUTABLE); else if( prefixNode.getModifiers().isReadonly() ) ctx.addModifiers(Modifiers.READONLY); else if( prefixNode.getModifiers().isTemporaryReadonly() ) ctx.addModifiers(Modifiers.TEMPORARY_READONLY); return null; } @Override public Void visitAllocation(ShadowParser.AllocationContext ctx) { visitChildren(ctx); Context child = (Context) ctx.getChild(0); ctx.addModifiers(child.getModifiers()); //only get type from arrayCreate //create sets differently if( ctx.arrayCreate() != null ) ctx.setType(child.getType()); return null; } @Override public Void visitCreate(ShadowParser.CreateContext ctx) { visitChildren(ctx); Context prefixNode = curPrefix.getFirst(); Type prefixType = prefixNode.getType(); ctx.setType(Type.UNKNOWN); Context parent = (Context) ctx.getParent(); if( prefixType instanceof InterfaceType ) addError(curPrefix.getFirst(), Error.INVALID_CREATE, "Interfaces cannot be created"); else if( prefixType instanceof SingletonType ) addError(curPrefix.getFirst(), Error.INVALID_CREATE, "Singletons cannot be created"); else if(!( prefixType instanceof ClassType) && !(prefixType instanceof TypeParameter && !prefixType.recursivelyGetMethodOverloads("create").isEmpty())) addError(curPrefix.getFirst(), Error.INVALID_CREATE, "Type " + prefixType + " cannot be created", prefixType); else if( !prefixNode.getModifiers().isTypeName() ) addError(curPrefix.getFirst(), Error.INVALID_CREATE, "Only a type can be created"); else { SequenceType typeArguments = null; if( ctx.typeArguments() != null ) { typeArguments = (SequenceType) ctx.typeArguments().getType(); } SequenceType arguments = new SequenceType(); for( ShadowParser.ConditionalExpressionContext child : ctx.conditionalExpression() ) { arguments.add(child); } MethodSignature signature; if( typeArguments != null ) { if( prefixType.isParameterized() && prefixType.getTypeParameters().canAccept(typeArguments, SubstitutionKind.TYPE_PARAMETER) ) { try { prefixType = prefixType.replace(prefixType.getTypeParameters(), typeArguments); signature = setCreateType( ctx, prefixType, arguments); ctx.setSignature(signature); parent.setType(prefixType); //occasionally this type is only seen here with all parameters //and must be added to the referenced types //the raw type has already been added currentType.addUsedType(prefixType); currentType.addPartiallyInstantiatedClass(prefixType); } catch (InstantiationException e) { addError(ctx.typeArguments(), Error.INVALID_TYPE_ARGUMENTS, "Supplied type arguments " + typeArguments + " do match type parameters " + prefixType.getTypeParameters()); } } else addError(ctx.typeArguments(), Error.INVALID_TYPE_ARGUMENTS, "Supplied type arguments " + typeArguments + " do match type parameters " + prefixType.getTypeParameters()); } else { if( !prefixType.isParameterized() ) { signature = setCreateType( ctx, prefixType, arguments); ctx.setSignature(signature); parent.setType(prefixType); } else addError(ctx, Error.MISSING_TYPE_ARGUMENTS, "Type arguments not supplied for parameterized type " + prefixType); } } if( ctx.getType() == Type.UNKNOWN ) parent.setType(Type.UNKNOWN); return null; } @Override public Void visitClassSpecifier(ShadowParser.ClassSpecifierContext ctx) { visitChildren(ctx); //always part of a suffix, thus always has a prefix ModifiedType prefixNode = curPrefix.getFirst(); boolean isTypeName = prefixNode.getModifiers().isTypeName(); Type prefixType = prefixNode.getType(); if( isTypeName ) { if( ctx.typeArguments() != null ) { //has type arguments ShadowParser.TypeArgumentsContext arguments = ctx.typeArguments(); SequenceType parameterTypes = prefixType.getTypeParameters(); SequenceType argumentTypes = (SequenceType) arguments.getType(); if( !prefixType.isParameterized() ) addError(ctx.typeArguments(), Error.UNNECESSARY_TYPE_ARGUMENTS, "Type arguments " + argumentTypes + " supplied for non-parameterized type " + prefixType, prefixType); else if( !parameterTypes.canAccept(argumentTypes, SubstitutionKind.TYPE_PARAMETER) ) addError(ctx.typeArguments(), Error.INVALID_TYPE_ARGUMENTS, "Supplied type arguments " + argumentTypes + " do not match type parameters " + parameterTypes ); else { try { Type replacedType = prefixType.replace(parameterTypes, argumentTypes); currentType.addUsedType(replacedType); currentType.addPartiallyInstantiatedClass(replacedType); } catch(InstantiationException e) { addError(ctx.typeArguments(), Error.INVALID_TYPE_ARGUMENTS, "Supplied type arguments " + argumentTypes + " do not match type parameters " + parameterTypes ); } } } else if( prefixType.isParameterized() ) addError(ctx, Error.MISSING_TYPE_ARGUMENTS, "Type arguments not supplied for parameterized type " + prefixType); } else addError(ctx, Error.NOT_TYPE, "class specifier requires type name for access" ); ctx.setType( Type.CLASS ); ctx.addModifiers(Modifiers.IMMUTABLE); return null; } @Override public Void visitScopeSpecifier(ShadowParser.ScopeSpecifierContext ctx) { visitChildren(ctx); //always part of a suffix, thus always has a prefix ModifiedType prefixNode = curPrefix.getFirst(); prefixNode = resolveType( prefixNode ); Type prefixType = prefixNode.getType(); boolean isTypeName = prefixNode.getModifiers().isTypeName(); String name = ctx.Identifier().getText(); if( prefixType.containsField( name ) ) { Context field = prefixType.getField(name); if( !fieldIsAccessible( field, currentType )) { addError(ctx, Error.ILLEGAL_ACCESS, "Field " + name + " not accessible from this context"); } else if( !field.getModifiers().isConstant() && isTypeName ) { addError(ctx, Error.ILLEGAL_ACCESS, "Field " + name + " is only accessible from an object reference"); } else { ctx.setType(field.getType()); ctx.addModifiers(field.getModifiers()); if( !prefixNode.getModifiers().isMutable() ) ctx.getModifiers().upgradeToTemporaryReadonly(); //only in a create if //prefix is "this" //current method is create //current method is inside prefix type boolean insideCreate = false; if( currentMethod.isEmpty() ) insideCreate = true; //declaration else { MethodSignature signature = currentMethod.getFirst().getSignature(); insideCreate = curPrefix.getFirst().getText().equals("this") && signature.isCreate() && signature.getOuter().equals(prefixType); } if( ctx.getModifiers().isMutable() || insideCreate ) ctx.addModifiers(Modifiers.ASSIGNABLE); } } else if(prefixType.recursivelyContainsConstant(name)) { Context constant = prefixType.recursivelyGetConstant(name); if(!isTypeName ) addError(ctx, Error.ILLEGAL_ACCESS, "Constant " + name + " requires type name for access"); ctx.setType(constant.getType()); ctx.addModifiers(constant.getModifiers()); } else if( prefixType.containsInnerType(name) ) { Type innerType = prefixType.getInnerType(name); if( !currentType.canSee(innerType) ) addError(ctx, Error.ILLEGAL_ACCESS, "Type " + innerType + " is not accessible from this context", innerType); else { ctx.setType(innerType); ctx.addModifiers(Modifiers.TYPE_NAME); } } else addError(ctx, Error.UNDEFINED_SYMBOL, "Field or inner type " + name + " not defined in this context"); if( ctx.getType() == null ) ctx.setType( Type.UNKNOWN ); return null; } @Override public Void visitProperty(ShadowParser.PropertyContext ctx) { visitChildren(ctx); //always part of a suffix, thus always has a prefix ModifiedType prefixNode = curPrefix.getFirst(); prefixNode = resolveType( prefixNode ); Type prefixType = prefixNode.getType(); String propertyName = ctx.Identifier().getText(); boolean isTypeName = prefixNode.getModifiers().isTypeName() && !(prefixType instanceof SingletonType); if( isTypeName ) { addError(curPrefix.getFirst(), Error.NOT_OBJECT, "Object reference must be used to access property " + propertyName); ctx.setType( Type.UNKNOWN ); } else { List<MethodSignature> methods = prefixType.recursivelyGetMethodOverloads(propertyName); if( prefixNode.getModifiers().isImmutable() ) ctx.addModifiers(Modifiers.IMMUTABLE); else if( prefixNode.getModifiers().isReadonly() ) ctx.addModifiers(Modifiers.READONLY); else if( prefixNode.getModifiers().isTemporaryReadonly() ) ctx.addModifiers(Modifiers.TEMPORARY_READONLY); if( methods != null && methods.size() > 0 ) { MethodSignature getter = null; UnboundMethodType setterName = null; for( MethodSignature signature : methods ) { if( signature.getModifiers().isGet() ) getter = signature; else if( setterName == null && signature.getModifiers().isSet() ) setterName = new UnboundMethodType( signature.getSymbol(), signature.getOuter()); } boolean mutableProblem = false; boolean accessibleProblem = false; if( getter != null && !methodIsAccessible(getter, currentType)) { accessibleProblem = true; getter = null; } if( getter != null && !prefixNode.getModifiers().isMutable() && getter.getModifiers().isMutable() ) { mutableProblem = true; getter = null; } if( setterName == null ) { ctx.setType( Type.UNKNOWN ); //assume bad if( mutableProblem ) addError(ctx, Error.ILLEGAL_ACCESS, "Mutable property " + propertyName + " cannot be called from " + (prefixNode.getModifiers().isImmutable() ? "immutable" : "readonly") + " context"); else if( accessibleProblem ) addError(ctx, Error.ILLEGAL_ACCESS, "Property " + propertyName + " is not accessible in this context"); else if( getter == null ) addError(ctx, Error.INVALID_PROPERTY, "Property " + propertyName + " is not defined in this context"); else //only case where it works out ctx.setType( new PropertyType( getter, setterName, prefixNode, currentType) ); } else ctx.setType( new PropertyType( getter, setterName, prefixNode, currentType) ); } else { addError(ctx, Error.INVALID_PROPERTY, "Property " + propertyName + " not defined in this context"); ctx.setType( Type.UNKNOWN ); //if got here, some error } } return null; } private ModifiedType resolveType( ModifiedType node ) { //dereferences into PropertyType or IndexType for getter, if needed Type type = node.getType(); if( type instanceof PropertyType ) { //includes SubscriptType as well PropertyType getSetType = (PropertyType) type; if( getSetType.isGettable() ) return getSetType.getGetType(); else { String kind = (type instanceof SubscriptType) ? "Subscript " : "Property "; if( node instanceof Context) addError((Context)node, Error.ILLEGAL_ACCESS, kind + node + " does not have appropriate get access"); else addError(new TypeCheckException(Error.ILLEGAL_ACCESS, kind + node + " does not have appropriate get access")); return new SimpleModifiedType( Type.UNKNOWN ); } } else return node; } protected MethodSignature setCreateType( Context node, Type prefixType, SequenceType arguments) { return setMethodType( node, prefixType, "create", arguments, null); } protected MethodSignature setMethodType( Context node, Type type, String method, SequenceType arguments) { return setMethodType( node, type, method, arguments, null ); } protected MethodSignature setMethodType( Context node, Type type, String method, SequenceType arguments, SequenceType typeArguments ) { List<ShadowException> errors = new ArrayList<>(); MethodSignature signature = type.getMatchingMethod(method, arguments, typeArguments, errors); if( signature == null ) addErrors(node, errors); else { if(!methodIsAccessible( signature, currentType )) addError(node, Error.ILLEGAL_ACCESS, signature.getSymbol() + signature.getMethodType() + " is not accessible from this context"); //if any arguments have an UnboundMethodType, note down what their true MethodSignature must be for( int i = 0; i < arguments.size(); ++i ) { ModifiedType argument = arguments.get(i); if( argument.getType() instanceof UnboundMethodType ) { //since it matches, the parameter of the method must be a MethodType MethodType parameterType = (MethodType) signature.getParameterTypes().get(i).getType(); UnboundMethodType unboundType = (UnboundMethodType) argument.getType(); MethodSignature boundSignature = unboundType.getOuter().getMatchingMethod(unboundType.getTypeName(), parameterType.getParameterTypes()); unboundType.setKnownSignature(boundSignature); } } node.setType(signature.getMethodType()); } return signature; } @Override public Void visitMethodCall(ShadowParser.MethodCallContext ctx) { visitChildren(ctx); //always part of a suffix, thus always has a prefix ModifiedType prefixNode = curPrefix.getFirst(); prefixNode = resolveType( prefixNode ); Type prefixType = prefixNode.getType(); SequenceType arguments = new SequenceType(); for( ShadowParser.ConditionalExpressionContext child : ctx.conditionalExpression() ) { arguments.add(child); } if( prefixType instanceof UnboundMethodType ) { UnboundMethodType unboundMethod = (UnboundMethodType)(prefixType); Type outer = prefixType.getOuter(); MethodSignature signature = setMethodType(ctx, outer, unboundMethod.getTypeName(), arguments, null); //type set inside ctx.setSignature(signature); if( signature != null ) { for( ModifiedType modifiedType : signature.getReturnTypes() ) { currentType.addUsedType(modifiedType.getType()); } } if( signature != null && prefixNode.getModifiers().isImmutable() && signature.getModifiers().isMutable() ) { addError(ctx, Error.ILLEGAL_ACCESS, "Mutable method " + signature + " cannot be called from an immutable reference"); } if( signature != null && (prefixNode.getModifiers().isReadonly() || prefixNode.getModifiers().isTemporaryReadonly()) && signature.getModifiers().isMutable() ) { addError(ctx, Error.ILLEGAL_ACCESS, "Mutable method " + signature + " cannot be called from a readonly reference"); } } else if( prefixType instanceof MethodReferenceType ) { //only happens with method pointers and local methods MethodType methodType = ((MethodReferenceType)prefixType).getMethodType(); if( methodType.isInline() ) { for( Context signatureNode : currentMethod ) { if( signatureNode.getSignature().getMethodType() == methodType ) { //if literally the same MethodType, we have illegal recursion addError(ctx, Error.INVALID_STRUCTURE, "Inline method cannot be called recursively"); } } } if( methodType.canAccept( arguments ) ) ctx.setType(prefixType); else { addError(ctx, Error.INVALID_ARGUMENTS, "Supplied method arguments " + arguments + " do not match method parameters " + methodType.getParameterTypes(), arguments, methodType.getParameterTypes()); ctx.setType(Type.UNKNOWN); } if( prefixNode.getModifiers().isImmutable() && !methodType.getModifiers().isImmutable() && !methodType.getModifiers().isReadonly() ) { addError(ctx, Error.ILLEGAL_ACCESS, "Mutable method cannot be called from an immutable reference"); } if( prefixNode.getModifiers().isReadonly() && !methodType.getModifiers().isImmutable() && !methodType.getModifiers().isReadonly() ) { addError(ctx, Error.ILLEGAL_ACCESS, "Mutable method cannot be called from a readonly reference"); } } else { addError(ctx, Error.INVALID_METHOD, "Cannot apply arguments to non-method type " + prefixType, prefixType); ctx.setType(Type.UNKNOWN); } return null; } public static boolean fieldIsAccessible( Context field, Type type ) { // constants are no longer all public if ( field.getModifiers().isPublic() ) return true; //if inside class Type checkedType = type.getTypeWithoutTypeArguments(); Type enclosing = field.getEnclosingType().getTypeWithoutTypeArguments(); while( checkedType != null ) { if( enclosing.equals(checkedType) ) return true; checkedType = checkedType.getOuter(); } checkedType = type.getTypeWithoutTypeArguments(); if( field.getModifiers().isProtected() && checkedType instanceof ClassType ) { ClassType classType = ((ClassType) checkedType).getExtendType(); while( classType != null ) { if( enclosing.equals(classType)) { return true; } classType = classType.getExtendType(); } } return false; } @Override public Void visitBreakOrContinueStatement(ShadowParser.BreakOrContinueStatementContext ctx) { // No children to visit ParserRuleContext parent = ctx.getParent(); boolean foundLoop = false; boolean foundFinally = false; String name = ctx.getText().substring(0, ctx.getText().length() - 1).trim(); while(parent != null && !foundLoop) { // Trying to break or continue out of a finally if(parent instanceof ShadowParser.BlockContext && parent.getParent() instanceof ShadowParser.FinallyStatementContext) foundFinally = true; // Legitimate loop to break out of if( parent instanceof ShadowParser.DoStatementContext || parent instanceof ShadowParser.ForeachStatementContext || parent instanceof ShadowParser.ForStatementContext || parent instanceof ShadowParser.WhileStatementContext ) foundLoop = true; else parent = parent.getParent(); } if(!foundLoop) addError(ctx, Error.INVALID_STRUCTURE, name + " statement cannot occur outside of a loop body"); if(foundFinally) addError(ctx, Error.INVALID_STRUCTURE, name + " statement cannot exit a finally block"); return null; } @Override public Void visitArrayInitializer(ShadowParser.ArrayInitializerContext ctx) { visitChildren(ctx); Type result = null; boolean first = true; boolean nullable = false; List<? extends Context> children; if( !ctx.arrayInitializer().isEmpty() ) { children = ctx.arrayInitializer(); } else { children = ctx.conditionalExpression(); } for( Context child : children ) { //cycle through types, upgrading to broadest legal type Type type = child.getType(); if( first ) { result = type; first = false; } else { if( result.isSubtype(type) ) { result = type; } else if( !type.isSubtype(result) ) { //neither is subtype of other, panic! addError(ctx, Error.MISMATCHED_TYPE, "Types in array initializer list do not match"); ctx.setType(Type.UNKNOWN); return null; } } if( child.getModifiers().isNullable() ) { nullable = true; } } //new code assumes that result is array of arrays ArrayType arrayType; if( nullable ) { ctx.addModifiers(Modifiers.NULLABLE); arrayType = new ArrayType(result, 1, nullable); } else { arrayType = new ArrayType(result, 1, nullable); } ctx.setType(arrayType); currentType.addUsedType(arrayType); currentType.addPartiallyInstantiatedClass(arrayType); return null; } @Override public Void visitAssertStatement(ShadowParser.AssertStatementContext ctx) { visitChildren(ctx); Type assertType = ctx.conditionalExpression(0).getType(); if( !assertType.equals(Type.BOOLEAN)) { addError(ctx.conditionalExpression(0), Error.INVALID_TYPE, "Supplied type " + assertType + " cannot be used in the condition of an assert, boolean required", assertType); } else if( ctx.conditionalExpression().size() == 2 ) { ShadowParser.ConditionalExpressionContext child = ctx.conditionalExpression(1); Type type = child.getType(); if( child.getModifiers().isTypeName() && !(type instanceof SingletonType) ) { addError(child, Error.NOT_OBJECT, "Object type required for assert information but type name used"); } } return null; } @Override public Void visitLiteral(ShadowParser.LiteralContext ctx) { //no children visited Type type = literalToType(ctx); ctx.setType(type); if(type != Type.NULL) { currentType.addUsedType(type); } ctx.setInterpretedValue(processLiteral(ctx, getErrorReporter())); return null; } /** * Initializes a {@link ShadowValue} corresponding to the given literal node. * * Also sets the appropriate {@link Type} on the node. */ public static ShadowValue processLiteral(ShadowParser.LiteralContext ctx, ErrorReporter reporter) { // ugly but needed to find negation ParserRuleContext greatGrandparent = ctx.getParent().getParent().getParent(); boolean negated = false; if (greatGrandparent instanceof ShadowParser.UnaryExpressionContext) { ParserRuleContext greatGreat = greatGrandparent.getParent(); if (greatGreat instanceof ShadowParser.UnaryExpressionContext && greatGreat.getChild(0).getText().equals("-")) { negated = true; } } String literal = ctx.getText(); String lower = literal.toLowerCase(); int length = literal.length(); try { if (literal.equals("null")) { return new ShadowNull(Type.NULL); } else if (literal.startsWith("\'") && literal.endsWith("\'")) { return ShadowCode.parseCode(literal); } else if (literal.startsWith("\"") && literal.endsWith("\"")) { return ShadowString.parseString(literal); } else if (literal.equals("true")) { return new ShadowBoolean(true); } else if (literal.equals("false")) { return new ShadowBoolean(false); } else if (lower.endsWith("f") && !lower.startsWith("0x") && !lower.startsWith("0c") && !lower.startsWith("0b")) { return ShadowFloat.parseFloat(lower.substring(0, length - 1)); } else if (lower.endsWith("d") && !lower.startsWith("0x") && !lower.startsWith("0c") && !lower.startsWith("0b") ) { return ShadowDouble.parseDouble(lower.substring(0, length - 1)); } else if (literal.indexOf('.') != -1 || (lower.indexOf('e') != -1 && !lower.startsWith("0x") && !lower.startsWith("0c") && !lower.startsWith("0b") )) { return ShadowDouble.parseDouble(lower); } else { return ShadowInteger.parseNumber(lower, negated); } } catch (NumberFormatException e) { reporter.addError(ctx, Error.INVALID_LITERAL, "Value out of range: " + ctx.getText()); } catch (IllegalArgumentException e) { reporter.addError(ctx, Error.INVALID_LITERAL, e.getLocalizedMessage()); } return ShadowValue.INVALID; } @Override public Void visitPrimitiveType(ShadowParser.PrimitiveTypeContext ctx) { //no children ctx.setType(nameToPrimitiveType(ctx.getText())); currentType.addUsedType(ctx.getType()); ctx.addModifiers(Modifiers.TYPE_NAME); return null; } @Override public Void visitReturnStatement(ShadowParser.ReturnStatementContext ctx) { visitChildren(ctx); if( currentMethod.isEmpty() ) // Should never happen addError(ctx, Error.INVALID_STRUCTURE, "Return statement cannot be outside of method body"); else { MethodType methodType = (MethodType)(currentMethod.getFirst().getType()); ctx.setType(methodType.getReturnTypes()); //return statement set to exactly the types method returns //implicit casts are added in TAC conversion if the values don't match exactly if( currentMethod.getFirst() instanceof ShadowParser.DestroyDeclarationContext ) //The reason you can't is that a destroy needs to add in reference decrements for each field, at the end of the method //Using returns would complicate the code needed to insert these decrements, and also destroys should be simple, //ideally created entirely by the compiler in most cases. addError(ctx, Error.INVALID_RETURNS, "Cannot use a return statement inside of a destroy definition"); else if( methodType.getReturnTypes().size() == 0 ) { if( ctx.rightSide() != null ) addError(ctx, Error.INVALID_RETURNS, "Cannot return values from a method that returns nothing"); } else { ShadowParser.RightSideContext child = ctx.rightSide(); Type type = child.getType(); SequenceType sequenceType; if( type instanceof SequenceType ) sequenceType = (SequenceType) type; else sequenceType = new SequenceType( child ); SequenceType updatedTypes = new SequenceType(); //reconstitute full return types based on types with return modifiers //return modifiers can differ from regular modifiers because readonly and immutable methods //can enforce readonly constraints to keep object internals from changing during the method for( int i = 0; i < sequenceType.size(); ++i ) { Modifiers modifiers = sequenceType.get(i).getModifiers(); modifiers.removeModifier(Modifiers.TEMPORARY_READONLY); updatedTypes.add(new SimpleModifiedType(sequenceType.getType(i), modifiers ) ); } if( !updatedTypes.isSubtype(ctx.getType()) ) addError(ctx, Error.INVALID_RETURNS, "Cannot return " + updatedTypes + " when " + ctx.getType() + (methodType.getReturnTypes().size() == 1 ? " is" : " are") + " expected", ctx.getType(), updatedTypes); // update unbound method types else { for( int i = 0; i < updatedTypes.size(); i++ ) { Type leftType = methodType.getReturnTypes().get(i).getType(); Type rightType = updatedTypes.get(i).getType(); if( rightType instanceof UnboundMethodType && leftType instanceof MethodReferenceType ) { UnboundMethodType unboundType = (UnboundMethodType) rightType; MethodType returnMethodType = ((MethodReferenceType) leftType).getMethodType(); MethodSignature signature = unboundType.getOuter().getMatchingMethod(unboundType.getTypeName(), returnMethodType.getParameterTypes()); unboundType.setKnownSignature( signature ); } } } for( ModifiedType modifiedType : updatedTypes ) if( modifiedType.getModifiers().isTypeName() ) addError(ctx, Error.INVALID_RETURNS, "Cannot return type name from a method" ); ParserRuleContext parent = ctx.getParent(); boolean foundFinally = false; while(parent != null && !foundFinally) { // Trying to break or continue out of a finally if(parent instanceof ShadowParser.BlockContext && parent.getParent() instanceof ShadowParser.FinallyStatementContext) foundFinally = true; else parent = parent.getParent(); } if(foundFinally) addError(ctx, Error.INVALID_STRUCTURE, "Cannot return from inside a finally block"); } } return null; } @Override public Void visitResultType(ShadowParser.ResultTypeContext ctx) { visitChildren(ctx); Type type = ctx.type().getType(); ctx.setType(type); return null; } @Override public Void visitExplicitCreateInvocation(ShadowParser.ExplicitCreateInvocationContext ctx) { visitChildren(ctx); SequenceType arguments = new SequenceType(); for( ShadowParser.ConditionalExpressionContext child : ctx.conditionalExpression() ) arguments.add(child); if( currentType instanceof ClassType ) { ClassType type = (ClassType) currentType; //assumes "this" if( ctx.getChild(0).getText().equals("super") ){ if( type.getExtendType() != null ) type = type.getExtendType(); else addError(ctx, Error.INVALID_CREATE, "Class type " + type + " cannot invoke a parent create because it does not extend another type", type); } MethodSignature signature = setMethodType(ctx, type, "create", arguments, null); //type set inside ctx.setSignature(signature); } else addError(ctx, Error.INVALID_CREATE, "Non-class type " + currentType + " cannot be created", currentType); return null; } @Override public Void visitType(ShadowParser.TypeContext ctx) { visitChildren(ctx); Context child = (Context) ctx.getChild(0); ctx.addModifiers(child.getModifiers()); boolean isNullable = ctx.getModifiers().isNullable(); Type type = child.getType(); if( isNullable ) { if( type instanceof ArrayType ) { ArrayType arrayType = (ArrayType) type; type = arrayType.convertToNullable(); if( arrayType.recursivelyGetBaseType().isPrimitive() ) addError(ctx, Error.INVALID_MODIFIER, "Primitive array type " + type + " cannot be marked nullable"); } } ctx.setType(type); currentType.addUsedType(type); return null; } @Override public Void visitIsList(ShadowParser.IsListContext ctx) { return null; //no children } @Override public Void visitInlineMethodDefinition(ShadowParser.InlineMethodDefinitionContext ctx) { visitMethodPre(ctx); visitChildren(ctx); MethodType methodType = ctx.getSignature().getMethodType(); //add parameters ShadowParser.FormalParametersContext parameters = ctx.formalParameters(); for( ShadowParser.FormalParameterContext parameter : parameters.formalParameter() ) methodType.addParameter(parameter.Identifier().getText(), parameter); //add return types ShadowParser.InlineResultsContext results = ctx.inlineResults(); for( ShadowParser.ConditionalExpressionContext result : results.conditionalExpression() ) methodType.addReturn(result); ctx.setType(methodType); visitMethodPost(ctx); return null; } @Override public Void visitArrayDimensions(ShadowParser.ArrayDimensionsContext ctx) { visitChildren(ctx); for( ShadowParser.ConditionalExpressionContext child : ctx.conditionalExpression() ) { Type childType = child.getType(); if( !childType.isIntegral() ) { addError(child, Error.INVALID_SUBSCRIPT, "Supplied type " + childType + " cannot be used in this array creation, integral type required", childType); ctx.setType(Type.UNKNOWN); return null; } } return null; } @Override public Void visitMethodDeclarator(ShadowParser.MethodDeclaratorContext ctx) { // Non-local methods have already been handled in the type updater if( ctx.getParent() instanceof ShadowParser.LocalMethodDeclarationContext ) { visitChildren(ctx); ShadowParser.LocalMethodDeclarationContext parent = (LocalMethodDeclarationContext) ctx.getParent(); MethodSignature signature = parent.getSignature(); // Add parameters for( ShadowParser.FormalParameterContext parameter : ctx.formalParameters().formalParameter() ) signature.addParameter(parameter.Identifier().getText(), parameter); // Add return types for( ShadowParser.ResultTypeContext result : ctx.resultTypes().resultType() ) signature.addReturn(result); ctx.setType(signature.getMethodType()); } return null; } @Override public Void visitSpawnExpression(ShadowParser.SpawnExpressionContext ctx) { visitChildren(ctx); Type runnerType = ctx.type().getType(); if(runnerType.equals(Type.CAN_RUN) || !runnerType.isSubtype(Type.CAN_RUN)) { addError(ctx, Error.INVALID_TYPE, runnerType + " needs to be a subtype of the " + Type.CAN_RUN + " interface"); } List<ShadowException> errors = new ArrayList<ShadowException>(); MethodSignature runnerCreateSignature = runnerType.getMatchingMethod("create", (SequenceType)ctx.spawnRunnerCreateCall().getType(), new SequenceType(), errors); if(runnerCreateSignature == null) { addErrors(ctx, errors); } else { ctx.spawnRunnerCreateCall().setSignature(runnerCreateSignature); } // we should find the thread create since we're the ones who defined it. // Two overloads: Thread(CanRun) and Thread(String, CanRun) SequenceType sequence = new SequenceType(); if(ctx.StringLiteral() != null) { sequence.add(new SimpleModifiedType(Type.STRING)); } sequence.add(new SimpleModifiedType(Type.CAN_RUN)); ctx.setSignature(Type.THREAD.getMatchingMethod("create", sequence)); ctx.setType(Type.THREAD); return null; } @Override public Void visitSpawnRunnerCreateCall(shadow.parse.ShadowParser.SpawnRunnerCreateCallContext ctx) { visitChildren(ctx); SequenceType sequence = new SequenceType(); for(ShadowParser.ConditionalExpressionContext child : ctx.conditionalExpression()) { sequence.add(child); } ctx.setType(sequence); return null; } @Override public Void visitSendStatement(SendStatementContext ctx) { visitChildren(ctx); if(ctx.conditionalExpression().size() != 2 || !resolveType(ctx.conditionalExpression(1)).getType().equals(Type.THREAD)) { addError(ctx, Error.INVALID_ARGUMENTS, "The arguments do not match the signature: send(Object data, Thread to)"); } else { List<ShadowException> errors = new ArrayList<ShadowException>(); MethodSignature sendSignature = Type.THREAD.getMatchingMethod("sendTo", new SequenceType(resolveType(ctx.conditionalExpression().get(0))), new SequenceType(), errors); if(sendSignature == null) { addError(ctx, Error.INVALID_ARGUMENTS, "The arguments do not match the signature: send(Object data, Thread to)"); } else { ctx.setSignature(sendSignature); ctx.setType(sendSignature.getReturnTypes()); // void } } return null; } /*@Override public Void visitReceiveExpression(shadow.parse.ShadowParser.ReceiveExpressionContext ctx) { visitChildren(ctx); return null; }*/ @Override public Void visitVariableDeclarator(ShadowParser.VariableDeclaratorContext ctx) { // Must happen first to determine the types of conditional expressions visitChildren(ctx); if (ctx.getParent() instanceof ShadowParser.AttributeInvocationContext) { Type attributeType = ((ShadowParser.AttributeInvocationContext) ctx.getParent()).getType(); String fieldName = ctx.generalIdentifier().getText(); if (!attributeType.getFields().containsKey(fieldName)) { addError( ctx, Error.UNDEFINED_SYMBOL, "Field \"" + fieldName + "\" is not declared in " + attributeType.getTypeName(), attributeType); } else { addErrors(ctx, isValidInitialization(attributeType.getField(fieldName), ctx.conditionalExpression())); } } return null; } @Override public Void visitDependencyList(ShadowParser.DependencyListContext ctx) { // These only appear in .meta files and don't require statement-checking return null; } }
9233a7789b4effd5345e99e08a4ba297dc6ee86f
3,638
java
Java
ProjektJTPv3/src/game/AlienManager.java
milenadob/JavaFX-spaceinvaders
984bb857e05af2f01f3514834ed7d9ac67b151f9
[ "MIT" ]
1
2021-12-15T13:52:37.000Z
2021-12-15T13:52:37.000Z
ProjektJTPv3/src/game/AlienManager.java
milenadob/JavaFX-spaceinvaders
984bb857e05af2f01f3514834ed7d9ac67b151f9
[ "MIT" ]
null
null
null
ProjektJTPv3/src/game/AlienManager.java
milenadob/JavaFX-spaceinvaders
984bb857e05af2f01f3514834ed7d9ac67b151f9
[ "MIT" ]
null
null
null
26.948148
85
0.529412
996,650
package game; import javafx.scene.layout.AnchorPane; import java.util.ArrayList; import java.util.List; import java.util.Random; /** * Manages aliens, creates new aliens and moves them * @author Milena Dobkowska * @version 1.0 */ class AlienManager { private AnchorPane gamePane; private static final Random RAND = new Random(); /**list of all created aliens*/ private List<Alien> alienList = new ArrayList<>(); /**different images for creating aliens*/ private String[] aliens={ "file:images/ufoBlue.png", "file:images/ufoGreen.png", "file:images/ufoRed.png", "file:images/ufoYellow.png", }; //Move helper variables /**true if aliens can be moved down*/ private boolean down; /**true if aliens can be moved left*/ private boolean left; /**true if aliens can be moved right*/ private boolean right; /**for rotating aliens*/ private int angle; /** * Alien manager constructor. * Sets start moving direction to right * @param gamePane game scene layout */ AlienManager(AnchorPane gamePane) { this.gamePane=gamePane; this.down=false; this.left=false; this.right=true; this.angle=0; } /** * Creates new alien with random image from aliens table * @return alien */ private Alien newAlien(){ return new Alien(aliens[RAND.nextInt(aliens.length)],90,90); } /** * Creates aliens images at specified positions and adds them to game scene * @param howMany how many aliens needs to be created * @see #newAlien() */ void createAliens(int howMany){ for(int i=0;i<howMany;i++){ alienList.add(newAlien()); } int i=0,j=1,rowCount=0; for(Alien a:alienList){ if(rowCount==a.getImageWidth()*10){ j++; rowCount=0; i=0; } a.getImage().setLayoutX(200 + a.getImageWidth() * i); a.getImage().setLayoutY(a.getImageHeight()*j); i++; rowCount+=a.getImageWidth(); gamePane.getChildren().add(a.getImage()); } } /** * Calculating moving direction for aliens and moving their images * @see GameElement#moveDown() * @see GameElement#moveLeft() * @see GameElement#moveRight() */ void moveAliens(){ int posXL=(int)alienList.get(0).getImage().getLayoutX(); int posXR=(int)alienList.get(alienList.size()-1).getImage().getLayoutX()+91; if(posXR<=1200 &&!down && right){ for(Alien a:alienList){ a.moveRight(); } }else if(posXL>=50&&!down && left){ for(Alien a:alienList){ a.moveLeft(); } }else if(posXR>1200 || posXL<50){ down=true; } if(down){ for(Alien a:alienList){ a.moveDown(); } if(posXR>1200){right=false;left=true;} if(posXL<50){right=true;left=false;} down=false; } } /** * Rotating alien image */ void rotateAliens(){ if (angle>=360)angle=0; for(Alien a:alienList) { a.getImage().setRotate(angle); angle += 1; } } /** * Getter * @return list of aliens */ List<Alien> getAlienList() { return alienList; } }
9233a7e2029ea2fa0f1cdc436cf0a1ef7c451a9a
408
java
Java
src/main/java/frc/robot/OI.java
Navamvg/Drivetrain
3df920c4c1eaee833c1a4b0b886d084c48b24f8c
[ "BSD-3-Clause" ]
null
null
null
src/main/java/frc/robot/OI.java
Navamvg/Drivetrain
3df920c4c1eaee833c1a4b0b886d084c48b24f8c
[ "BSD-3-Clause" ]
null
null
null
src/main/java/frc/robot/OI.java
Navamvg/Drivetrain
3df920c4c1eaee833c1a4b0b886d084c48b24f8c
[ "BSD-3-Clause" ]
null
null
null
16.32
61
0.676471
996,651
package frc.robot; import edu.wpi.first.wpilibj.Joystick; public class OI { // Instantiation of joysticks Joystick driverStick = new Joystick(RobotMap.driveStick); Joystick operatorStick = new Joystick(1); // Joystick accessors public Joystick getDriverStick(){ return driverStick; } public Joystick getOperatorStick(){ return operatorStick; } }
9233a82ce5fcc7918636271d1c75c4c25493f230
3,214
java
Java
gradle/src/core/org/gradle/api/internal/changedetection/rules/OutputFilesTaskStateChanges.java
HenryHarper/Acquire-Reboot
ed7d8e3ce1953d7cf0b7e8313a9ee7ad9948bc34
[ "MIT" ]
null
null
null
gradle/src/core/org/gradle/api/internal/changedetection/rules/OutputFilesTaskStateChanges.java
HenryHarper/Acquire-Reboot
ed7d8e3ce1953d7cf0b7e8313a9ee7ad9948bc34
[ "MIT" ]
null
null
null
gradle/src/core/org/gradle/api/internal/changedetection/rules/OutputFilesTaskStateChanges.java
HenryHarper/Acquire-Reboot
ed7d8e3ce1953d7cf0b7e8313a9ee7ad9948bc34
[ "MIT" ]
null
null
null
40.175
174
0.760423
996,652
/* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.api.internal.changedetection.rules; import org.gradle.api.internal.TaskInternal; import org.gradle.api.internal.changedetection.state.FileCollectionSnapshot; import org.gradle.api.internal.changedetection.state.FileCollectionSnapshotter; import org.gradle.api.internal.changedetection.state.TaskExecution; import java.util.EnumSet; public class OutputFilesTaskStateChanges extends AbstractFileSnapshotTaskStateChanges { private final TaskExecution previousExecution; private final TaskExecution currentExecution; private final TaskInternal task; private final FileCollectionSnapshotter outputFilesSnapshotter; private final FileCollectionSnapshot outputFilesBefore; public OutputFilesTaskStateChanges(TaskExecution previousExecution, TaskExecution currentExecution, TaskInternal task, FileCollectionSnapshotter outputFilesSnapshotter) { super(task.getName()); this.previousExecution = previousExecution; this.currentExecution = currentExecution; this.task = task; this.outputFilesSnapshotter = outputFilesSnapshotter; outputFilesBefore = createSnapshot(outputFilesSnapshotter, task.getOutputs().getFiles()); } @Override protected String getInputFileType() { return "Output"; } @Override public FileCollectionSnapshot getPrevious() { return previousExecution.getOutputFilesSnapshot(); } @Override public FileCollectionSnapshot getCurrent() { return outputFilesBefore; } @Override protected FileCollectionSnapshot.ChangeIterator<String> getChanges() { return getCurrent().iterateContentChangesSince(getPrevious(), EnumSet.of(FileCollectionSnapshot.ChangeFilter.IgnoreAddedFiles)); } @Override public void saveCurrent() { FileCollectionSnapshot lastExecutionOutputFiles; if (previousExecution == null || previousExecution.getOutputFilesSnapshot() == null) { lastExecutionOutputFiles = outputFilesSnapshotter.emptySnapshot(); } else { lastExecutionOutputFiles = previousExecution.getOutputFilesSnapshot(); } FileCollectionSnapshot newOutputFiles = lastExecutionOutputFiles.updateFrom(outputFilesBefore); FileCollectionSnapshot outputFilesAfter = createSnapshot(outputFilesSnapshotter, task.getOutputs().getFiles()); currentExecution.setOutputFilesSnapshot(outputFilesAfter.applyAllChangesSince(outputFilesBefore, newOutputFiles)); } @Override protected boolean isAllowSnapshotReuse() { return false; } }