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
923b9eee9692112a50a95e6ddfac3aece0cc1be5
3,904
java
Java
agent/src/test/java/ua/arlabunakty/agent/transformer/servlet/http/WrittenContentTrackerTest.java
Arlabunakty/java-metric-agent
e07b54aa7febb904187374edb811ca40a7d5b78f
[ "MIT" ]
1
2020-09-25T12:29:54.000Z
2020-09-25T12:29:54.000Z
agent/src/test/java/ua/arlabunakty/agent/transformer/servlet/http/WrittenContentTrackerTest.java
Arlabunakty/java-metric-agent
e07b54aa7febb904187374edb811ca40a7d5b78f
[ "MIT" ]
null
null
null
agent/src/test/java/ua/arlabunakty/agent/transformer/servlet/http/WrittenContentTrackerTest.java
Arlabunakty/java-metric-agent
e07b54aa7febb904187374edb811ca40a7d5b78f
[ "MIT" ]
null
null
null
24.098765
79
0.682377
999,664
package ua.arlabunakty.agent.transformer.servlet.http; import static org.junit.jupiter.api.Assertions.assertEquals; import java.nio.charset.StandardCharsets; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import ua.arlabunakty.test.TestObject; class WrittenContentTrackerTest { private WrittenContentTracker tracker; @BeforeEach void init() { tracker = new WrittenContentTracker(); } @Test void shouldTrackContentLengthForTrueBoolean() { tracker.trackContentLength(true); assertEquals(4, tracker.getContentLength()); } @Test void shouldTrackContentLengthForFalseBoolean() { tracker.trackContentLength(false); assertEquals(5, tracker.getContentLength()); } @Test void shouldTrackContentLengthForChar() { tracker.trackContentLength('A'); assertEquals(1, tracker.getContentLength()); } @Test void shouldTrackContentLengthForObject() { Object object = new TestObject("string"); tracker.trackContentLength(object); assertEquals(6, tracker.getContentLength()); } @Test void shouldTrackContentLengthForNullObject() { tracker.trackContentLength((Object) null); assertEquals(4, tracker.getContentLength()); } @Test void shouldTrackContentLengthForByteArray() { tracker.trackContentLength("test111".getBytes(StandardCharsets.UTF_8)); assertEquals(7, tracker.getContentLength()); } @Test void shouldTrackContentLengthForEmptyByteArray() { tracker.trackContentLength(new byte[0]); assertEquals(0, tracker.getContentLength()); } @Test void shouldTrackContentLengthForNullByteArray() { tracker.trackContentLength((byte[]) null); assertEquals(0, tracker.getContentLength()); } @Test void shouldTrackContentLengthForCharVarArgs() { tracker.trackContentLength("test2222".toCharArray()); assertEquals(8, tracker.getContentLength()); } @Test void shouldTrackContentLengthForNullCharVarArgs() { tracker.trackContentLength((char[]) null); assertEquals(0, tracker.getContentLength()); } @Test void shouldTrackContentLengthForIntZero() { tracker.trackContentLength(0); assertEquals(1, tracker.getContentLength()); } @Test void shouldTrackContentLengthForIntMaxValue() { tracker.trackContentLength(Integer.MAX_VALUE); assertEquals(10, tracker.getContentLength()); } @Test void shouldTrackContentLengthForFloatZero() { tracker.trackContentLength(0.0); assertEquals(3, tracker.getContentLength()); } @Test void shouldTrackContentLengthForFloatMinValue() { tracker.trackContentLength(Float.MIN_VALUE); assertEquals(7, tracker.getContentLength()); } @Test void shouldTrackContentLengthForDoubleZero() { tracker.trackContentLength(0.01d); assertEquals(4, tracker.getContentLength()); } @Test void shouldTrackContentLengthForDoubleMinValue() { tracker.trackContentLength(Double.MAX_VALUE); assertEquals(22, tracker.getContentLength()); } @Test void shouldTrackContentLengthForString() { tracker.trackContentLength("string"); assertEquals(6, tracker.getContentLength()); } @Test void shouldTrackContentLengthForNullString() { tracker.trackContentLength((String) null); assertEquals(4, tracker.getContentLength()); } @Test void shouldTrackContentLengthNewLine() { tracker.trackContentLengthNewLine(); assertEquals(2, tracker.getContentLength()); } @Test void shouldAddWrittenContent() { tracker.addWrittenContent(10); assertEquals(10, tracker.getContentLength()); } }
923b9eef608900563cedaa1a613c5f1dc8922ba8
263
java
Java
src/main/java/com/example/springbootstudy/model/Group.java
loorr/campus-community
7ccc11096b79f36345884ec08b38468ad5ee2d7c
[ "MIT" ]
null
null
null
src/main/java/com/example/springbootstudy/model/Group.java
loorr/campus-community
7ccc11096b79f36345884ec08b38468ad5ee2d7c
[ "MIT" ]
null
null
null
src/main/java/com/example/springbootstudy/model/Group.java
loorr/campus-community
7ccc11096b79f36345884ec08b38468ad5ee2d7c
[ "MIT" ]
null
null
null
16.4375
42
0.692015
999,665
package com.example.springbootstudy.model; import lombok.Data; /** * @author zjianfa */ @Data public class Group { private Long groupId; private Long leaderId; private String groupName; private int maxNum = 500; private int currNum = 0; }
923b9f21410a97cbb145de504f222e43557d4229
1,171
java
Java
core/sorcer-platform/src/main/java/sorcer/service/Updatable.java
snezhko13/INN
1f84993fd7cb706bdc2322e70231106b32c01d65
[ "Apache-2.0" ]
6
2015-01-13T11:31:06.000Z
2019-03-17T03:10:50.000Z
core/sorcer-platform/src/main/java/sorcer/service/Updatable.java
vaderkos/SORCER-multiFi
02ed3c3ec536527f9b9d1a0207251425ffd9022c
[ "Apache-2.0" ]
5
2020-07-08T15:46:17.000Z
2022-01-29T17:24:51.000Z
core/sorcer-platform/src/main/java/sorcer/service/Updatable.java
vaderkos/SORCER-multiFi
02ed3c3ec536527f9b9d1a0207251425ffd9022c
[ "Apache-2.0" ]
53
2015-01-13T07:46:20.000Z
2020-05-05T03:41:17.000Z
28.560976
85
0.71819
999,666
/* * Copyright 2010 the original author or authors. * Copyright 2010 SorcerSoft.org. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package sorcer.service; import java.rmi.RemoteException; /** * An top-level interface for any kinds of updates by this object. * * @author Mike Sobolewski */ public interface Updatable { /** * A generic request for required updates. * * @param updates * required updates by this object * @throws EvaluationException * if updates failed for any reason * @throws RemoteException */ public boolean update(Object[] updates) throws EvaluationException, RemoteException; }
923ba02b3e21abe2644f8b7a9dd91f25f93ff275
2,926
java
Java
demo-redis/src/main/java/com/example/demo/controller/DemoRedisController.java
dsl1888888/demo-dd
3d5deff4f3c3e3e88d8899b6a6708d5e0d4726ac
[ "Apache-2.0" ]
null
null
null
demo-redis/src/main/java/com/example/demo/controller/DemoRedisController.java
dsl1888888/demo-dd
3d5deff4f3c3e3e88d8899b6a6708d5e0d4726ac
[ "Apache-2.0" ]
null
null
null
demo-redis/src/main/java/com/example/demo/controller/DemoRedisController.java
dsl1888888/demo-dd
3d5deff4f3c3e3e88d8899b6a6708d5e0d4726ac
[ "Apache-2.0" ]
null
null
null
30.8
337
0.65311
999,667
package com.example.demo.controller; import java.io.IOException; import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.alibaba.fastjson.JSON; import com.singleandcluster.util.StringRedisUtil; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; /* 类注解 */ @Slf4j @Api(value = "desc of class") @RestController public class DemoRedisController { private static final String solrDataName = "demo1"; @Autowired private StringRedisTemplate redisTemplate; @PostConstruct public void init() { try { log.info(redisTemplate.toString()); } catch (Exception e) { e.printStackTrace(); } } /* 方法注解 */ @ApiOperation(value = "queryById", notes = "") @RequestMapping(value = "demo/redis/queryById", method = RequestMethod.GET) public String queryById(String id) { String resp = ""; StringRedisUtil stringRedisUtil = new StringRedisUtil(); stringRedisUtil.setRedisTemplate(redisTemplate); Object object = stringRedisUtil.get(id); return "" + JSON.toJSONString(object); } /* 方法注解 */ @ApiOperation(value = "detele", notes = "") @RequestMapping(value = "demo/redis/detele", method = RequestMethod.GET) public String detele(String id) { StringRedisUtil stringRedisUtil = new StringRedisUtil(); stringRedisUtil.setRedisTemplate(redisTemplate); stringRedisUtil.deleteAll(id); return "ok"; } // /* 方法注解 */ // @ApiOperation(value = "insertBatch", notes = "") // @RequestMapping(value = "demo/redis/insertBatch", method = // RequestMethod.GET) // public String insertBatch() throws IOException { // // return "{\"name\":\"我是名字\",\"pwd\":\"我是密碼\"}"; // } /* 方法注解 */ @ApiOperation(value = "insertOne", notes = "") @RequestMapping(value = "demo/redis/insertOne", method = RequestMethod.GET) public String insertOne() throws IOException { StringRedisUtil stringRedisUtil = new StringRedisUtil(); stringRedisUtil.setRedisTemplate(redisTemplate); stringRedisUtil.set("1", "[{\"code\":\"1\",\"value\":\"https://h5.cashlena.com/web/UserNotice.html\"},{\"code\":\"2\",\"value\":\"https://h5.cashlena.com/web/PrivacyPolicy.html\"},{\"code\":\"3\",\"value\":\"https://h5.cashlena.com/Protocol/borrow\"},{\"code\":\"4\",\"value\":\"https://h5.cashlena.com/web/empower/empower.html\"}]"); return "{\"name\":\"我是名字\",\"pwd\":\"我是密碼\"}"; } }
923ba076a1878db88542dcca85228091224ee915
3,067
java
Java
src/main/java/net/zenxarch/pmixins/Mixins.java
offbeat-stuff/Some-Personal-Mixins
9fcacfec8b69a7e991f73562356aaf28ff878d1e
[ "MIT" ]
null
null
null
src/main/java/net/zenxarch/pmixins/Mixins.java
offbeat-stuff/Some-Personal-Mixins
9fcacfec8b69a7e991f73562356aaf28ff878d1e
[ "MIT" ]
null
null
null
src/main/java/net/zenxarch/pmixins/Mixins.java
offbeat-stuff/Some-Personal-Mixins
9fcacfec8b69a7e991f73562356aaf28ff878d1e
[ "MIT" ]
null
null
null
39.831169
171
0.69612
999,668
package net.zenxarch.pmixins; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Redirect; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import net.minecraft.entity.EntityType; import net.minecraft.entity.LivingEntity; import net.minecraft.entity.mob.MobEntity; import net.minecraft.entity.player.PlayerEntity; import net.minecraft.loot.condition.KilledByPlayerLootCondition; import net.minecraft.loot.context.LootContext; import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.world.GameRules; public class Mixins { @Mixin(MobEntity.class) static class MobMixin{ @Inject( method = "isAffectedByDaylight", at = @At("HEAD"), cancellable = true ) void dontBurn(CallbackInfoReturnable<Boolean> cir){ cir.setReturnValue(false); } } @Mixin(PlayerEntity.class) static class PlayerMixin { @Redirect( method = "dropInventory", at = @At(value = "INVOKE", target = "net/minecraft/world/GameRules.getBoolean(Lnet/minecraft/world/GameRules$Key;)Z")) boolean checkPlayerKillInventory(GameRules rules, GameRules.Key<GameRules.BooleanRule> key) { return rules.getBoolean(key) && (((PlayerEntity) (Object) this).getAttacker() == null || ((PlayerEntity) (Object) this).getAttacker().getType() != EntityType.PLAYER); } @Redirect( method = "getXpToDrop", at = @At(value = "INVOKE", target = "net/minecraft/world/GameRules.getBoolean(Lnet/minecraft/world/GameRules$Key;)Z")) boolean checkPlayerKillXP(GameRules rules, GameRules.Key<GameRules.BooleanRule> key) { return rules.getBoolean(key) && (((PlayerEntity) (Object) this).getAttacker() == null || ((PlayerEntity) (Object) this).getAttacker().getType() != EntityType.PLAYER); } } @Mixin(ServerPlayerEntity.class) static class ServerPlayerMixin { @Redirect( method = "copyFrom", at = @At(value = "INVOKE", target = "net/minecraft/world/GameRules.getBoolean(Lnet/minecraft/world/GameRules$Key;)Z")) public boolean onCopyFrom(GameRules rules, GameRules.Key<GameRules.BooleanRule> key, ServerPlayerEntity oldPlayer) { return rules.getBoolean(key) && (oldPlayer.getAttacker() == null || oldPlayer.getAttacker().getType() != EntityType.PLAYER); } } @Mixin(LivingEntity.class) static class LivingMixin { @Inject(at = @At("HEAD"), method = "shouldAlwaysDropXp", cancellable = true) void dropXP(CallbackInfoReturnable<Boolean> cir){ cir.setReturnValue(true); } } @Mixin(KilledByPlayerLootCondition.class) static class PlayerLootMixin { @Inject(at = @At("HEAD"), method = "test", cancellable = true) void dropPlayerLoot(LootContext lootContext, CallbackInfoReturnable<Boolean> cir){ cir.setReturnValue(true); } } }
923ba1747fa0e28b4e7f6214e9ca2f0219813937
2,602
java
Java
src/main/java/constructmod/cards/OilSpill.java
Demonvelion/StS-ConstructMod
19188b58ae6a3ed7641e6e5fb434e438b3e093c2
[ "MIT" ]
null
null
null
src/main/java/constructmod/cards/OilSpill.java
Demonvelion/StS-ConstructMod
19188b58ae6a3ed7641e6e5fb434e438b3e093c2
[ "MIT" ]
null
null
null
src/main/java/constructmod/cards/OilSpill.java
Demonvelion/StS-ConstructMod
19188b58ae6a3ed7641e6e5fb434e438b3e093c2
[ "MIT" ]
null
null
null
38.264706
157
0.793236
999,669
package constructmod.cards; import com.megacrit.cardcrawl.actions.common.ApplyPowerAction; import com.megacrit.cardcrawl.actions.common.GainBlockAction; import com.megacrit.cardcrawl.cards.AbstractCard; import com.megacrit.cardcrawl.characters.AbstractPlayer; import com.megacrit.cardcrawl.core.CardCrawlGame; import com.megacrit.cardcrawl.dungeons.AbstractDungeon; import com.megacrit.cardcrawl.localization.CardStrings; import com.megacrit.cardcrawl.monsters.AbstractMonster; import com.megacrit.cardcrawl.powers.GainStrengthPower; import com.megacrit.cardcrawl.powers.StrengthPower; import constructmod.ConstructMod; import constructmod.patches.AbstractCardEnum; import constructmod.powers.OilSpillPower; public class OilSpill extends AbstractConstructCard { public static final String ID = ConstructMod.makeID("OilSpill"); private static final CardStrings cardStrings = CardCrawlGame.languagePack.getCardStrings(ID); public static final String NAME = cardStrings.NAME; public static final String DESCRIPTION = cardStrings.DESCRIPTION; private static final String M_UPGRADE_DESCRIPTION = cardStrings.EXTENDED_DESCRIPTION[0]; private static final int COST = 1; private static final int OIL_DAMAGE = 9; public static final int OVERHEAT = 5; private static final int UPGRADE_PLUS_OIL_DAMAGE = 2; private static final int M_UPGRADE_PLUS_OIL_DAMAGE = 3; private static final int POOL = 1; public OilSpill() { super(ID, NAME, "img/cards/"+ID+".png", COST, DESCRIPTION, CardType.SKILL, AbstractCardEnum.CONSTRUCTMOD, CardRarity.UNCOMMON, CardTarget.ENEMY, POOL); this.baseMagicNumber = this.magicNumber = OIL_DAMAGE; this.overheat = OVERHEAT; } @Override public void use(AbstractPlayer p, AbstractMonster m) { if (this.megaUpgraded){ for (AbstractMonster mo : AbstractDungeon.getMonsters().monsters){ if (!mo.isDeadOrEscaped()) AbstractDungeon.actionManager.addToBottom(new ApplyPowerAction(mo,p,new OilSpillPower(mo,this.magicNumber),this.magicNumber)); } } else { AbstractDungeon.actionManager.addToBottom(new ApplyPowerAction(m, p, new OilSpillPower(m, this.magicNumber), this.magicNumber)); } } @Override public AbstractCard makeCopy() { return new OilSpill(); } @Override public void upgrade() { if (!this.upgraded) { this.upgradeName(); this.upgradeMagicNumber(UPGRADE_PLUS_OIL_DAMAGE); } else if (this.canUpgrade()) { this.megaUpgradeName(); this.upgradeMagicNumber(M_UPGRADE_PLUS_OIL_DAMAGE); this.rawDescription = M_UPGRADE_DESCRIPTION; this.target = CardTarget.ALL_ENEMY; this.initializeDescription(); } } }
923ba17b80cd0a91a7e53fc80343f7b7f7221b1f
2,019
java
Java
modules/swagger-promote-core/src/test/java/com/axway/apim/test/basic/IntiallyPublishedAPITestIT.java
vuvdoan/apimanager-swagger-promote
f6f1e1c62361544e8ce04775a6fbbcb8c6aeb9d8
[ "Apache-2.0" ]
null
null
null
modules/swagger-promote-core/src/test/java/com/axway/apim/test/basic/IntiallyPublishedAPITestIT.java
vuvdoan/apimanager-swagger-promote
f6f1e1c62361544e8ce04775a6fbbcb8c6aeb9d8
[ "Apache-2.0" ]
null
null
null
modules/swagger-promote-core/src/test/java/com/axway/apim/test/basic/IntiallyPublishedAPITestIT.java
vuvdoan/apimanager-swagger-promote
f6f1e1c62361544e8ce04775a6fbbcb8c6aeb9d8
[ "Apache-2.0" ]
null
null
null
36.709091
110
0.710253
999,670
package com.axway.apim.test.basic; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.testng.annotations.Test; import com.axway.apim.test.ImportTestAction; import com.consol.citrus.annotations.CitrusTest; import com.consol.citrus.dsl.testng.TestNGCitrusTestDesigner; import com.consol.citrus.functions.core.RandomNumberFunction; import com.consol.citrus.message.MessageType; @Test(testName="IntiallyPublishedAPITest") public class IntiallyPublishedAPITestIT extends TestNGCitrusTestDesigner { @Autowired private ImportTestAction swaggerImport; @CitrusTest(name = "Initially Pusblished API.") public void run() { description("Import an API which initially has the status published."); variable("apiNumber", RandomNumberFunction.getRandomNumber(3, true)); variable("apiPath", "/initially-published-${apiNumber}"); variable("apiName", "Initially-Published-API-${apiNumber}"); echo("####### Importing API: '${apiName}' on path: '${apiPath}' for the first time #######"); createVariable(ImportTestAction.API_DEFINITION, "/com/axway/apim/test/files/basic/petstore.json"); createVariable(ImportTestAction.API_CONFIG, "/com/axway/apim/test/files/basic/2_initially_published.json"); createVariable("expectedReturnCode", "0"); action(swaggerImport); echo("####### Validate API: '${apiName}' on path: '${apiPath}' has been imported #######"); http().client("apiManager") .send() .get("/proxies") .name("api") .header("Content-Type", "application/json"); http().client("apiManager") .receive() .response(HttpStatus.OK) .messageType(MessageType.JSON) .validate("$.[?(@.path=='${apiPath}')].name", "${apiName}") .validate("$.[?(@.path=='${apiPath}')].state", "published") .validate("$.[?(@.path=='${apiPath}')].securityProfiles[0].devices[0].type", "apiKey") .extractFromPayload("$.[?(@.path=='${apiPath}')].id", "apiId"); //echo("citrus:message(response.payload(), )"); } }
923ba293decb27cc25f0a8fd3ecca53ac736deba
16,248
java
Java
AlgAE361/graphColoring/src/main/java/edu/odu/cs/cs361/animations/GraphColoring.java
sjzeil/AlgAE---data-structures---Weiss
92643559e38f022e7566b124800f3d25b5b05165
[ "ECL-1.0" ]
1
2020-07-16T18:07:39.000Z
2020-07-16T18:07:39.000Z
AlgAE361/graphColoring/src/main/java/edu/odu/cs/cs361/animations/GraphColoring.java
sjzeil/AlgAE---data-structures---Weiss
92643559e38f022e7566b124800f3d25b5b05165
[ "ECL-1.0" ]
null
null
null
AlgAE361/graphColoring/src/main/java/edu/odu/cs/cs361/animations/GraphColoring.java
sjzeil/AlgAE---data-structures---Weiss
92643559e38f022e7566b124800f3d25b5b05165
[ "ECL-1.0" ]
1
2015-02-18T16:11:59.000Z
2015-02-18T16:11:59.000Z
38.411348
160
0.611152
999,671
package edu.odu.cs.cs361.animations; import java.awt.Color;//! import java.util.Arrays;//! import java.util.Comparator;//! import java.util.HashMap;//! import java.util.LinkedList;//! import java.util.List;//! import java.util.ListIterator;//! import edu.odu.cs.cs361.animations.graphs.CppIterator;//! import edu.odu.cs.cs361.animations.graphs.Edge;//! import edu.odu.cs.cs361.animations.graphs.Graph; import edu.odu.cs.cs361.animations.graphs.Vertex;//! import edu.odu.cs.AlgAE.Server.MemoryModel.ActivationRecord; import edu.odu.cs.AlgAE.Server.MemoryModel.Component;//! import edu.odu.cs.AlgAE.Server.MemoryModel.Connection;//! import edu.odu.cs.AlgAE.Server.Rendering.CanBeRendered;//! import edu.odu.cs.AlgAE.Server.Rendering.Renderer;//! import static edu.odu.cs.AlgAE.Server.LocalServer.activate;//! public class GraphColoring {//! public static class CompareByDegree implements Comparator<Vertex<ColoringData,X>> {//! public CompareByDegree ()//! {//! }//! @Override//! public int compare(Vertex<ColoringData,X> v, Vertex<ColoringData,X> w) {//! return v.get().degree - w.get().degree;//! }//! }//! public static class CompareByConstraints implements Comparator<Vertex<ColoringData,X>> {//! public CompareByConstraints ()//! {//! }//! @Override//! public int compare(Vertex<ColoringData,X> v, Vertex<ColoringData,X> w) {//! return w.get().constraints - v.get().constraints;//! }//! }//! public static class VList extends LinkedList<Vertex<ColoringData,X>> implements CanBeRendered<VList>, Renderer<VList> //! {//! private Color color; public VList () { super(); color = null; } public VList (Color c) { super(); color = c; } @Override//! public Renderer<VList> getRenderer() {//! return this;//! }//! @Override//! public Color getColor(VList obj) {//! return color;//! }//! @Override//! public List<Component> getComponents(VList obj) {//! LinkedList<Component> comp = new LinkedList<Component>();//! for (Vertex<ColoringData,X> v: this) {//! comp.add((new Component(v.getLabel())));//! }//! return comp;//! }//! @Override//! public List<Connection> getConnections(VList obj) {//! return new LinkedList<Connection>();//! }//! @Override//! public int getMaxComponentsPerRow(VList obj) {//! return 100;//! }//! @Override//! public String getValue(VList obj) {//! return "";//! }//! }//! private static void swapSmallestWithFront (VList array, Comparator<Vertex<ColoringData,X>> comp) //! {//! if (array.size() > 1) {//! ListIterator<Vertex<ColoringData,X>> iter0 = array.listIterator(); Vertex<ColoringData,X> v0 = iter0.next(); for (ListIterator<Vertex<ColoringData,X>> iter = array.listIterator(); iter.hasNext();) {//! Vertex<ColoringData,X> vi = iter.next(); if (comp.compare(v0, vi) > 0) {//! iter.set(v0);//! iter0.set(vi);//! v0 = vi;//! }//! }//! }//! }//! static int max (int x, int y)//! {//! return (x > y) ? x : y; //! }//! static int min (int x, int y)//! {//! return (x < y) ? x : y; //! }//! static int clashingColors (Graph<ColoringData,X> g,//!int clashingColors (Graph& g, HashMap<Vertex<ColoringData,X>, Integer> vertexNumbers,//! VertexToIntegers& vertexNumbers, BackTrack colors)//! const BackTrack& colors) { // Test to see if the current coloring is OK. If not, return the // lowest number of a vertex that we want to change for the next // potential solution. int vertexToChange = vertexNumbers.size(); for (CppIterator<Vertex<ColoringData,X>> v = g.vbegin(); !v.equals(g.vend()); v.increment())//! for (AllVertices v = g.vbegin(); v != g.vend(); ++v) { int vNum = vertexNumbers.get(v.at()).intValue();//! int vNum = vertexNumbers[*v]; int vColor = colors.get(vNum);//! int vColor = colors[vNum]; // Check to see if *v is adjacent to a // vertex of the same color. // If so, one of them has to change. int clashingVertex = -1; for (CppIterator<Edge<ColoringData,X>> e = g.outbegin(v.at()); //! for (AllOutgoingEdges e = g.outbegin(*v); (clashingVertex < 0) && (e.notEnd()); e.increment())//! (clashingVertex < 0) && (e != g.outend(*v)); ++e) { Vertex<ColoringData,X> w = e.at().dest();//! Vertex w = (*e).dest(); int wNum = vertexNumbers.get(w).intValue();//! int wNum = vertexNumbers[w]; int wColor = colors.get(wNum);//! int wColor = colors[wNum]; if (vColor == wColor) clashingVertex = max(vNum, wNum); } if (clashingVertex >= 0) vertexToChange = min(vertexToChange, clashingVertex); } return vertexToChange; } static Color colorList[] = {Color.yellow, Color.blue, Color.red,//! Color.green, Color.cyan, Color.magenta,//! Color.PINK, Color.black};//! static boolean colorGraph_backtracking (Graph<ColoringData,X> g, int numColors,//!bool colorGraph_backtracking (Graph& g, unsigned numColors, Color[] colors)//! ColorMap& colors) { ActivationRecord arec = activate(GraphColoring.class);//! HashMap<Vertex<ColoringData,X>, Integer> vertexNumbers = new HashMap<Vertex<ColoringData,X>, Integer>();//! VertexToIntegers vertexNumbers; for (CppIterator<Vertex<ColoringData,X>> v = g.vbegin(); v.notEnd(); v.increment())//! for (AllVertices v = g.vbegin(); v != g.vend(); ++v) { v.at().set(new ColoringData(true));//! vertexNumbers.put(v.at(), vertexNumbers.size());//! vertexNumbers[*v] = vertexNumbers.size(); } arec.param("g", "").param("numColors",numColors).param("colors", "").breakHere("ready to initialize backtracking");//! // Search for acceptable solution via backtracking BackTrack problem = new BackTrack(vertexNumbers.size(), numColors);//! BackTrack problem (vertexNumbers.size(), numColors); for (CppIterator<Vertex<ColoringData,X>> v = g.vbegin(); v.notEnd(); v.increment()) v.at().get().color = problem.get(vertexNumbers.get(v.at()));//! arec.var("problem",problem).breakHere("Initialized backtracking");//! boolean solved = false;//! bool solved = false; arec.pushScope();//! while (!solved && problem.more()) { for (CppIterator<Vertex<ColoringData,X>> v = g.vbegin(); v.notEnd(); v.increment()) v.at().get().color = problem.get(vertexNumbers.get(v.at()));//! arec.var("solved",solved).breakHere("Do we have a solution?");//! int pruneAt = clashingColors(g, vertexNumbers, problem); arec.var("pruneAt",pruneAt);//! if (pruneAt >= vertexNumbers.size()) {arec.breakHere("Do we have a solution? Yes!");//! solved = true; arec.var("solved",solved);//! }//! else {arec.breakHere("Not a solution. Prune indicated vertex.");//! problem.prune(pruneAt+1); }//! } arec.popScope();//! for (CppIterator<Vertex<ColoringData,X>> v = g.vbegin(); v.notEnd(); v.increment()) v.at().get().color = problem.get(vertexNumbers.get(v.at()));//! arec.var("solved",solved).breakHere("Completed backtracking");//! //! colors.clear(); //! if (solved) //! { // Construct the solution (map of vertices to colors) //! for (AllVertices v = g.vbegin(); v != g.vend(); ++v) //! colors[*v] = problem[vertexNumbers[*v]]; //! } return solved; } //!typedef hash_map<Vertex, int, VertexHash> VintMap; //!struct CompareVertices //!{ //! VintMap& vimap; //! bool lessComp; //! CompareVertices (VintMap& mp, bool compareWithLess) //! : vimap(mp), lessComp(compareWithLess) {} //! bool operator() (Vertex left, Vertex right) //! {if (lessComp) //! return vimap[left] < vimap[right]; //! else //! return vimap[left] > vimap[right]; //! } //!}; //!typedef adjustable_priority_queue<Vertex, VintMap, //! CompareVertices> //! PriorityQueue; boolean colorIsOK (Graph<ColoringData,X> g, Vertex<ColoringData,X> v, int color)//!bool colorIsOK (Graph& g, Vertex v, int color, ColorMap& colors) // return true if no node adjacent to v has color "color" { for (CppIterator<Edge<ColoringData,X>> e = g.outbegin(v); e.notEnd(); e.increment())//! for (AllOutgoingEdges e = g.outbegin(v); e != g.outend(v); ++e) { Vertex<ColoringData,X> w = e.at().dest();//! Vertex w = (*e).dest(); if ((w.get().color >= 0)//!if ((colors.find(w) != colors.end()) && (w.get().color == color))//! && (colors[w] == color)) return false; } return true; } private static int chooseColor (Graph<ColoringData,X> g, Vertex<ColoringData,X> v,//!int chooseColor (Graph& g, Vertex v, int numColors,//! unsigned numColors, //! ColorMap& colors, int startingColor) { boolean[] colorHasBeenSeen = new boolean[numColors];//! bool* colorHasBeenSeen = new bool[numColors]; Arrays.fill (colorHasBeenSeen, false);//! fill (colorHasBeenSeen, colorHasBeenSeen+numColors, false); for (CppIterator<Edge<ColoringData,X>> e = g.outbegin(v); e.notEnd(); e.increment())//! for (AllOutgoingEdges e = g.outbegin(v); e != g.outend(v); ++e) { Vertex<ColoringData,X> w = (e.at()).dest();//! Vertex w = (*e).dest(); int c = w.get().color;//! int c = colors[w]; if ((c >= 0) && !colorHasBeenSeen[c]) { colorHasBeenSeen[c] = true; } } int chosen = 0;//! int chosen = find(colorHasBeenSeen+startingColor+1, while (chosen < numColors && colorHasBeenSeen[chosen])//! colorHasBeenSeen+numColors, false) ++chosen;//! - colorHasBeenSeen; //! delete [] colorHasBeenSeen; return (chosen < numColors) ? chosen : -1; } private static int computeConstraints (Graph<ColoringData,X> g, Vertex<ColoringData,X> v,//!int computeConstraints (Graph& g, Vertex v, int numColors)//! unsigned numColors, ColorMap& colors) { boolean[] colorHasBeenSeen = new boolean[numColors];//! bool* colorHasBeenSeen = new bool[numColors]; Arrays.fill (colorHasBeenSeen, false);//! fill (colorHasBeenSeen, colorHasBeenSeen+numColors, false); int nSeen = 0; for (CppIterator<Edge<ColoringData,X>> e = g.outbegin(v); e.notEnd(); e.increment())//! for (AllOutgoingEdges e = g.outbegin(v); e != g.outend(v); ++e) { Vertex<ColoringData,X> w = (e.at()).dest();//! Vertex w = (*e).dest(); int c = w.get().color;//! int c = colors[w]; if ((c >= 0) && !colorHasBeenSeen[c]) { ++nSeen; colorHasBeenSeen[c] = true; } } //! delete [] colorHasBeenSeen; return nSeen; } static boolean colorGraph_heuristic (Graph<ColoringData,X> g, int numColors//!bool colorGraph_heuristic (Graph& g, unsigned numColors, )//! ColorMap& colors) { ActivationRecord arec = activate(GraphColoring.class);//! for (CppIterator<Vertex<ColoringData,X>> vv = g.vbegin(); vv.notEnd(); vv.increment())//! {//! vv.at().set(new ColoringData());// }//! arec.param("g", "").param("numColors",numColors).breakHere("starting");//! // Step 1 - push any vertices with degree < numColors onto a stack VList stk = new VList(Color.green);//! stack<vector<Vertex> > stk; //! VintMap degrees; //! VintMap constraints; arec.var("stk", stk).breakHere("starting");//! for (CppIterator<Vertex<ColoringData,X>> v = g.vbegin(); v.notEnd() ; v.increment())//! for (AllVertices v = g.vbegin(); v != g.vend() ; ++v) { v.at().get().color = -1;//! colors[*v] = -1; v.at().get().constraints = 0;//! constraints[*v] = 0; v.at().get().degree = g.outdegree(v.at());//!degrees[*v] = g.outdegree(*v); } arec.breakHere("set up a priority queue");//! VList pq = new VList(Color.blue);//! PriorityQueue pq (g.vbegin(), g.vend(), CompareVertices(degrees, false)); for (CppIterator<Vertex<ColoringData,X>> vv = g.vbegin(); vv.notEnd(); vv.increment()) pq.add(vv.at());//! swapSmallestWithFront(pq, new CompareByDegree());//! arec.var("pq", pq).breakHere("Push vertices with low degree onto stack");//! arec.pushScope();//! while ((!pq.isEmpty()) && (pq.get(0).get().degree < numColors))//! while ((!pq.empty()) && (degrees[v = pq.top()] < numColors)) { Vertex<ColoringData,X> v = pq.getFirst();//! Vertex v = pq.top(); arec.refVar("v",v).breakHere("push this vertex");//! pq.removeFirst();//! pq.pop(); swapSmallestWithFront(pq, new CompareByDegree());// stk.addFirst(v);//! stk.push (v); v.get().color = -2;//! colors[v] = -2; arec.pushScope();//! for (CppIterator<Edge<ColoringData,X>> e = g.outbegin(v); e.notEnd(); e.increment())//!for (AllOutgoingEdges e = g.outbegin(v); e != g.outend(v); ++e) { Vertex<ColoringData,X> w = e.at().dest();//! Vertex w = (*e).dest(); if (w.get().color == -1)//! if (colors[w] == -1) { arec.refVar("w",w).breakHere("w's degree must be reduced");//! w.get().degree = w.get().degree - 1;//! degrees[w] = degrees[w] - 1; swapSmallestWithFront(pq, new CompareByDegree());//! pq.adjust(w); } } arec.popScope();//! arec.breakHere("done with v - check pq again");//! } arec.popScope();//! // Step 2 - assign colors starting with the "most constrained" node VList pq2 = new VList(Color.blue);//! PriorityQueue pq2 (CompareVertices(constraints, true)); arec.var("pq2",pq2).breakHere("Create a new priority queue, ordered by #adj. vertices already colored");//! while (!pq.isEmpty())//! while (!pq.empty()) { arec.breakHere("Creating a new priority queue, ordered by #adj. vertices already colored");//! pq2.add (pq.getFirst());//! pq2.push (pq.top()); swapSmallestWithFront(pq2, new CompareByDegree());//! pq.removeFirst();//! pq.pop(); } arec.breakHere("Assign colors to most heavily constrained nodes"); arec.pushScope();//! while (!pq2.isEmpty())//! while (!pq2.empty()) { Vertex<ColoringData,X> v = pq2.getFirst();//! v = pq2.top(); pq2.remove(0);//! pq2.pop(); arec.refVar("v", v).breakHere("Choose a color for v");//! int c = chooseColor (g, v, numColors, -1);//! int c = chooseColor (g, v, numColors, colors, -1); arec.var("c", c);//! if (c < 0) { // Could not assign a color - give up arec.breakHere("Could not assign v a color - give up");//! return false; } v.get().color = c;//! colors[v] = c; arec.breakHere("v has been colored");//! arec.pushScope(); for (CppIterator<Edge<ColoringData,X>> e = g.outbegin(v); e.notEnd(); e.increment())//! for (AllOutgoingEdges e = g.outbegin(v); e != g.outend(v); ++e) { Vertex<ColoringData,X> w = e.at().dest();//! Vertex w = (*e).dest(); arec.refVar("w", w);//! if (w.get().color == -1)//! if (colors[w] == -1) { arec.breakHere("compute constraints on w");//! int nConstraints = computeConstraints (g, w, numColors);//! int nConstraints = computeConstraints (g, w, numColors, colors); arec.var("nConstraints",nConstraints); if (w.get().constraints != nConstraints)//! if (constraints[w] != nConstraints) { arec.var("nConstraints",nConstraints).breakHere("number of constraints on w have changed");//! w.get().constraints = nConstraints;//! constraints[w] = nConstraints; swapSmallestWithFront(pq2, new CompareByConstraints());//! pq2.adjust (w); arec.breakHere("w and pq2 have been updated");//! } } } } arec.popScope();//! // Step 3 - assign colors to the nodes saved on the stack arec.param("g", "").param("numColors",numColors).var("stk", stk).var("pq2", pq2).breakHere("assign colors to the nodes saved on the stack");//! while (!stk.isEmpty())//! while (!stk.empty()) { Vertex<ColoringData,X> v = stk.getFirst();//! v = stk.top(); stk.remove(0);//! stk.pop(); arec.refVar("v", v).breakHere("choose a color for v");//! v.get().color = chooseColor (g, v, numColors, -1);//! colors[v] = chooseColor (g, v, numColors, colors, -1); arec.breakHere("v has been colored.");//! } return true; } }
923ba2cfdc9bc9f7f1e630aa792de5bb18e93186
5,127
java
Java
iso8601/src/main/java/edu/uams/dbmi/util/iso8601/Iso8601TimeParser.java
ufbmi/iso8601
239b8fd9944711b750f17fef3ca0eb00f195eb85
[ "Apache-2.0" ]
null
null
null
iso8601/src/main/java/edu/uams/dbmi/util/iso8601/Iso8601TimeParser.java
ufbmi/iso8601
239b8fd9944711b750f17fef3ca0eb00f195eb85
[ "Apache-2.0" ]
null
null
null
iso8601/src/main/java/edu/uams/dbmi/util/iso8601/Iso8601TimeParser.java
ufbmi/iso8601
239b8fd9944711b750f17fef3ca0eb00f195eb85
[ "Apache-2.0" ]
null
null
null
30.337278
141
0.639165
999,672
/* Copyright 2011 University of Arkansas for Medical Sciences * * 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 edu.uams.dbmi.util.iso8601; import java.math.BigDecimal; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.measure.quantity.Duration; import javax.measure.unit.Unit; public class Iso8601TimeParser { static final String regex = "^T?((([0-1]\\d|2[0-3])(([0-5]\\d)(([0-5]\\d))?)?([\\.,]\\d+)?)|((24)((00)((00))?)?)([\\.,]0+)?)" + "(Z|([+-])(0[1-9]|1[0-2])(([0-5]\\d))?)?"; static final String regex_extended = "^T?((([0-1]\\d|2[0-3])(:([0-5]\\d)(:([0-5]\\d))?)?([\\.,]\\d+)?)|((24)(:(00)(:(00))?)?)([\\.,]0+)?)" + "(Z|([+-])(0[1-9]|1[0-2])(:([0-5]\\d))?)?"; static final int HOUR_GROUP = 3; static final int MIN_GROUP = 5; static final int SEC_GROUP = 7; static final int FR_GROUP = 8; static final int HR24_GROUP = 10; static final int MI24_GROUP = 12; static final int SE24_GROUP = 14; static final int FR24_GROUP = 15; static final int Z_GROUP = 16; static final int TZSIGN_GROUP = 17; static final int TZHR_GROUP = 18; static final int TZMI_GROUP = 20; Pattern p = Pattern.compile(regex); Pattern p_exp = Pattern.compile(regex_extended); boolean isExtended; boolean isExtendedConsistent; public Iso8601TimeParser() { p = Pattern.compile(regex); p_exp = Pattern.compile(regex_extended); } public Iso8601Time parse(String s) throws Iso8601TimeParseException { Iso8601Time t = null; isExtended = s.contains(":"); Matcher m = (isExtended) ? p_exp.matcher(s) : p.matcher(s); if (m.matches()) { /* * Group 3 is hour * Group 5 is minute * Group 7 is second * Group 8 is fraction * * If time is 24:00 or 24:00:00 * Group 10 is hour * Group 11 is minute * Group 13 is second * * Group 14 is "Z" if UTC * Group 15 is + or - * Group 16 is time zone hour * Group 18 is time zone minute * */ int hr_group, mi_group, se_group, fr_group; if (m.group(HOUR_GROUP) != null) { hr_group = HOUR_GROUP; mi_group = MIN_GROUP; se_group = SEC_GROUP; fr_group = FR_GROUP; } else { hr_group = HR24_GROUP; mi_group = MI24_GROUP; se_group = SE24_GROUP; fr_group = FR24_GROUP; } String frTxt = m.group(fr_group); frTxt = (frTxt == null) ? null : frTxt.replace(',', '.'); String seTxt = m.group(se_group); boolean isUnit = (frTxt == null) || (frTxt != null && seTxt != null); int hr = Integer.parseInt(m.group(hr_group)); String miTxt = m.group(mi_group); IsoTimeBuilder tb; if (isUnit) { tb = new IsoUnitTimeBuilder(hr); if (seTxt != null) { ((IsoUnitTimeBuilder)tb).setSecond( Integer.parseInt(seTxt)); } if (frTxt != null) { setSubsecondAndUnit((IsoUnitTimeBuilder)tb, frTxt); } } else { tb = new IsoFractionalTimeBuilder(hr); ((IsoFractionalTimeBuilder)tb).setFraction( Double.parseDouble(frTxt)); } if (miTxt != null) { tb.setMinute(Integer.parseInt(m.group(mi_group))); } if (m.group(Z_GROUP) != null && m.group(Z_GROUP).equals("Z")) { tb.setIsUtc(true); } else if (m.group(TZHR_GROUP) != null) { int tzHr = Integer.parseInt(m.group(TZHR_GROUP)); if (m.group(TZSIGN_GROUP).equals("-")) { tzHr = -tzHr; } tb.setTimeZoneOffsetHour(tzHr); if (m.group(TZMI_GROUP) != null) { tb.setTimeZoneOffsetMinute( Integer.parseInt(m.group(TZMI_GROUP))); } } /* * If the time string has just hour or just hour and timezone * hour offset, then it's consistent with extended, because * it has no need for : delimiter. */ isExtendedConsistent = isExtended || (tb.min == null && m.group(TZMI_GROUP) == null); if (isUnit) { t = new Iso8601UnitTime((IsoUnitTimeBuilder)tb); } else { t = new Iso8601FractionalTime((IsoFractionalTimeBuilder)tb); } } else { throw new Iso8601TimeParseException("Illegal 8601 time: " + s); } return t; } protected void setSubsecondAndUnit(IsoUnitTimeBuilder tb, String frTxt) { String frDotTxt = frTxt.replace(',', '.'); BigDecimal bd = new BigDecimal(frDotTxt); tb.setSubsecond(bd.unscaledValue().intValue()); long unitDivisor = BigDecimal.TEN.pow(bd.scale()).longValue(); Unit<Duration> u = TimeUnit.SECOND.divide(unitDivisor); if (u==null) { System.err.println("Setting null unit"); } tb.setUnit(u); } public boolean isExtended() { return isExtended; } public boolean isExtendedConsistent() { return isExtendedConsistent; } }
923ba50ea2721da2859ea4664144558da6bb3bcc
1,608
java
Java
fcrepo-server/src/test/java/org/fcrepo/server/storage/translation/MockDOSerializer.java
FLVC/fcrepo-src-3.4.2
8b31f3e627d4c8eef0d16bf8f0fe18a4803c4a52
[ "Apache-2.0" ]
15
2015-02-02T22:38:14.000Z
2018-12-31T19:38:25.000Z
fcrepo-server/src/test/java/org/fcrepo/server/storage/translation/MockDOSerializer.java
FLVC/fcrepo-src-3.4.2
8b31f3e627d4c8eef0d16bf8f0fe18a4803c4a52
[ "Apache-2.0" ]
9
2020-11-16T20:45:22.000Z
2022-02-01T01:14:11.000Z
fcrepo-server/src/test/java/org/fcrepo/server/storage/translation/MockDOSerializer.java
FLVC/fcrepo-src-3.4.2
8b31f3e627d4c8eef0d16bf8f0fe18a4803c4a52
[ "Apache-2.0" ]
30
2015-01-08T16:42:35.000Z
2021-03-17T13:36:56.000Z
28.210526
76
0.675995
999,673
/* The contents of this file are subject to the license and copyright terms * detailed in the license directory at the root of the source tree (also * available online at http://fedora-commons.org/license/). */ package org.fcrepo.server.storage.translation; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import org.fcrepo.server.errors.ObjectIntegrityException; import org.fcrepo.server.errors.StreamIOException; import org.fcrepo.server.storage.translation.DOSerializer; import org.fcrepo.server.storage.types.DigitalObject; /** * A test implementation of DOSerializer that only writes format\npid. * * @author Chris Wilper */ public class MockDOSerializer implements DOSerializer { private final String m_format; public MockDOSerializer() { m_format = new String(); } public MockDOSerializer(String format) { m_format = format; } public DOSerializer getInstance() { return new MockDOSerializer(m_format); } public void serialize(DigitalObject obj, OutputStream out, String encoding, int transContext) throws ObjectIntegrityException, StreamIOException, UnsupportedEncodingException { PrintWriter writer = new PrintWriter(new OutputStreamWriter(out, encoding)); try { writer.println(m_format); writer.print(obj.getPid()); } finally { writer.close(); } } }
923ba55664d0ea9f83bbfb4f84794243ea742e36
4,107
java
Java
openjdk/langtools/test/tools/apt/Discovery/Touch.java
liumapp/compiling-jvm
962f37e281f4d9ec03486d9380c43b7260790eaa
[ "Apache-2.0" ]
null
null
null
openjdk/langtools/test/tools/apt/Discovery/Touch.java
liumapp/compiling-jvm
962f37e281f4d9ec03486d9380c43b7260790eaa
[ "Apache-2.0" ]
null
null
null
openjdk/langtools/test/tools/apt/Discovery/Touch.java
liumapp/compiling-jvm
962f37e281f4d9ec03486d9380c43b7260790eaa
[ "Apache-2.0" ]
null
null
null
35.102564
93
0.603847
999,674
/* * Copyright (c) 2004, 2007, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ import com.sun.mirror.apt.*; import com.sun.mirror.declaration.*; import com.sun.mirror.type.*; import com.sun.mirror.util.*; import java.util.Collection; import java.util.Set; import java.util.Arrays; import java.util.Collections; import java.io.*; public class Touch implements AnnotationProcessorFactory { static class TouchProc implements AnnotationProcessor { AnnotationProcessorEnvironment ape; TouchProc(AnnotationProcessorEnvironment ape) { this.ape = ape; } public void process() { boolean result; // Only run the processor on the initial apt invocation Collection<TypeDeclaration> tdecls = ape.getSpecifiedTypeDeclarations(); if (tdecls.size() == 1) { for(TypeDeclaration decl: tdecls) { if (! decl.getSimpleName().equals("Touch") ) return; } try { // Create temporary file java.io.File f = new java.io.File("touched"); result = f.createNewFile(); Filer filer = ape.getFiler(); // Create new source file PrintWriter pw = filer.createSourceFile("HelloWorld"); pw.println("public class HelloWorld {"); pw.println(" public static void main(String argv[]) {"); pw.println(" System.out.println(\"Hello World\");"); pw.println(" }"); pw.println("}"); // Create new class file and copy Empty.class OutputStream os = filer.createClassFile("Empty"); FileInputStream fis = new FileInputStream("Empty.clazz"); int datum; while((datum = fis.read()) != -1) os.write(datum); } catch (java.io.IOException e) { result = false; } if (!result) throw new RuntimeException("touched file already exists or other error"); } } } static Collection<String> supportedTypes; static { String types[] = {"*"}; supportedTypes = Collections.unmodifiableCollection(Arrays.asList(types)); } static Collection<String> supportedOptions; static { String options[] = {""}; supportedOptions = Collections.unmodifiableCollection(Arrays.asList(options)); } public Collection<String> supportedOptions() { return supportedOptions; } public Collection<String> supportedAnnotationTypes() { return supportedTypes; } /* * Return the same processor independent of what annotations are * present, if any. */ public AnnotationProcessor getProcessorFor(Set<AnnotationTypeDeclaration> atds, AnnotationProcessorEnvironment env) { return new TouchProc(env); } }
923ba6c7789bba0a32126240991543044ec1f444
1,118
java
Java
core/src/com/smeanox/games/ld37/world/entity/EntityGreenElixir.java
SmBe19/LD37
0a55de292b1381b60eac2e194c5065c7257187e5
[ "MIT" ]
1
2021-01-09T23:17:06.000Z
2021-01-09T23:17:06.000Z
core/src/com/smeanox/games/ld37/world/entity/EntityGreenElixir.java
SmBe19/LD37
0a55de292b1381b60eac2e194c5065c7257187e5
[ "MIT" ]
null
null
null
core/src/com/smeanox/games/ld37/world/entity/EntityGreenElixir.java
SmBe19/LD37
0a55de292b1381b60eac2e194c5065c7257187e5
[ "MIT" ]
1
2021-01-09T23:17:13.000Z
2021-01-09T23:17:13.000Z
29.421053
107
0.728086
999,675
package com.smeanox.games.ld37.world.entity; import com.badlogic.gdx.graphics.g2d.TextureRegion; import com.badlogic.gdx.maps.MapObject; import com.smeanox.games.ld37.Consts; import com.smeanox.games.ld37.world.Hero; public class EntityGreenElixir extends Entity { public EntityGreenElixir(String id, TextureRegion textureRegion) { super(id, textureRegion); } public EntityGreenElixir(String id, TextureRegion textureRegion, String examineText) { super(id, textureRegion, examineText); } @Override public String useItem(Hero hero, MapObject object) { if("bodyguard".equals(object.getName())){ if(hero.getVar("fire").length() == 0){ return "The guards will notice"; } hero.removeCurrentItemFromInventory(); MapObject fire; while ((fire = Hero.findObjectByName(hero.gameWorld.level.get().map, "bodyguard")) != null){ fire.setVisible(false); } while ((fire = Hero.findObjectByName(hero.gameWorld.level.get().map, "bodyguard_frog", false)) != null){ fire.setVisible(true); } hero.setVar("greenelixir", "1"); return null; } return getWrongPersonString(); } }
923ba924466b33adf489b86146b4fff1933f7d57
4,196
java
Java
app/src/main/java/com/example/android/miwok/ColorsActivity.java
paulfranco/Miwok-Translator
559a02771164fd1e6d1e16c00f68eee6dff6a0f9
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/android/miwok/ColorsActivity.java
paulfranco/Miwok-Translator
559a02771164fd1e6d1e16c00f68eee6dff6a0f9
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/android/miwok/ColorsActivity.java
paulfranco/Miwok-Translator
559a02771164fd1e6d1e16c00f68eee6dff6a0f9
[ "Apache-2.0" ]
null
null
null
44.638298
156
0.666349
999,676
package com.example.android.miwok; import android.media.MediaPlayer; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import java.util.ArrayList; public class ColorsActivity extends AppCompatActivity { private MediaPlayer mMediaPlayer; private MediaPlayer.OnCompletionListener mOnCompletionListener = new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { releaseMediaPlayer(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.word_list); // Create a list of words final ArrayList<Word> words = new ArrayList<Word>(); // Add word objects to the list of words words.add(new Word("red", "weṭeṭṭi", R.drawable.color_red, R.raw.color_red)); words.add(new Word("green", "chokokki", R.drawable.color_green, R.raw.color_green)); words.add(new Word("brown", "ṭakaakki", R.drawable.color_brown, R.raw.color_brown)); words.add(new Word("gray", "ṭopoppi", R.drawable.color_gray, R.raw.color_gray)); words.add(new Word("black", "kululli", R.drawable.color_black, R.raw.color_black)); words.add(new Word("white", "kelelli", R.drawable.color_white, R.raw.color_white)); words.add(new Word("dusty yellow", "ṭopiisә", R.drawable.color_dusty_yellow, R.raw.color_dusty_yellow)); words.add(new Word("mustard yellow", "chiwiiṭә", R.drawable.color_mustard_yellow, R.raw.color_mustard_yellow)); // Create a new WordAdapter and we are calling it adapter. We are calling the contructor and passing it a context and the array list of word objects WordAdapter adapter = new WordAdapter(this, words, R.color.category_colors); // Create a list view ListView listView = (ListView) findViewById(R.id.list); // Passing the adapter to the list view listView.setAdapter(adapter); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // get the object ant the position clicked on and store in variable Word word = words.get(position); // Release the media player if it currently exists because we are about to play a different sound file releaseMediaPlayer(); // Create and setup the Media Player for the audio associated with the word MediaPlayer mMediaPlayer = MediaPlayer.create(ColorsActivity.this, word.getAudioResourceId()); // Start the audio file mMediaPlayer.start(); // setup a listener on the media player, so that we can stop and release the media player once the sounds has finished playing mMediaPlayer.setOnCompletionListener(mOnCompletionListener); } }); } @Override protected void onStop() { super.onStop(); // When the activity is stopped, release the media player resources because we wont be playing any sounds anymore releaseMediaPlayer(); } /** * Clean up the media player by releasing its resources. */ private void releaseMediaPlayer() { // If the media player is not null, then it may be currently playing a sound. if (mMediaPlayer != null) { // Regardless of the current state of the media player, release its resources // because we no longer need it. mMediaPlayer.release(); // Set the media player back to null. For our code, we've decided that // setting the media player to null is an easy way to tell that the media player // is not configured to play an audio file at the moment. mMediaPlayer = null; // Abandon audio focus when playback is complete mAudioManager.abandonAudioFocus(mOnAudioFocusChangeListener); } } }
923ba94428d94a6bbbd6c0ed9d2d79b0f22eb4ca
1,581
java
Java
EPE-2020-2-Estructuras-de-Datos/Tarea-1/tarea1/Pregunta1.java
jorgeireyjin/EPE-2020-2
4ae254056e63329252d5fc0def6f6a7c683ab8c2
[ "Apache-2.0" ]
null
null
null
EPE-2020-2-Estructuras-de-Datos/Tarea-1/tarea1/Pregunta1.java
jorgeireyjin/EPE-2020-2
4ae254056e63329252d5fc0def6f6a7c683ab8c2
[ "Apache-2.0" ]
null
null
null
EPE-2020-2-Estructuras-de-Datos/Tarea-1/tarea1/Pregunta1.java
jorgeireyjin/EPE-2020-2
4ae254056e63329252d5fc0def6f6a7c683ab8c2
[ "Apache-2.0" ]
null
null
null
32.9375
101
0.515497
999,677
package tarea1; import java.util.Scanner; public class Pregunta1 { public static void main(String[] args) { System.out.println("=================================="); System.out.println("===== P R E G U N T A 1 ==="); System.out.println("=================================="); double cantidad = 0; int nrollos500 = 0; int nrollos300 = 0; int nrollos75 = 0; Scanner sc = new Scanner(System.in); System.out.println("Ingresar la cantidad (pies) de alambre que necesita :"); cantidad = sc.nextDouble(); // Cantidad de rollos de 500 while ( cantidad >= 500 ) { cantidad = cantidad - 500; nrollos500 = nrollos500 + 1; } // Cantidad de rollos de 300 while ( cantidad >= 300 ) { cantidad = cantidad - 300; nrollos300 = nrollos300 + 1; } // Cantidad de rollos de 75 while ( cantidad >= 75 ) { cantidad = cantidad - 75; nrollos75 = nrollos75 + 1; } System.out.println("Se requieren " + nrollos500 + " rollo(s) de 500 pies"); System.out.println("Se requieren " + nrollos300 + " rollo(s) de 300 pies"); System.out.println("Se requieren " + nrollos75 + " rollo(s) de 75 pies"); if ( cantidad > 0 ) { System.out.println("Faltan " + (75 - cantidad) + " pies para completar el ultimo rollo"); } else { System.out.println("No hay faltantes para completar el ultimo rollo"); } } }
923ba96cf819d09d605dc929fdc715c62c4fda1f
144
java
Java
app/src/main/java/com/github/st1hy/countthemcalories/core/permissions/UserResponseForRationale.java
st1hy/Red-Calories
db5111abad35eecd9f10e4292cede66a7a9d9c4c
[ "MIT" ]
3
2017-02-23T15:53:53.000Z
2017-10-22T21:16:25.000Z
app/src/main/java/com/github/st1hy/countthemcalories/core/permissions/UserResponseForRationale.java
st1hy/Red-Calories
db5111abad35eecd9f10e4292cede66a7a9d9c4c
[ "MIT" ]
19
2016-07-16T13:53:53.000Z
2017-01-24T22:06:42.000Z
app/src/main/java/com/github/st1hy/countthemcalories/core/permissions/UserResponseForRationale.java
st1hy/Red-Calories
db5111abad35eecd9f10e4292cede66a7a9d9c4c
[ "MIT" ]
null
null
null
24
60
0.840278
999,678
package com.github.st1hy.countthemcalories.core.permissions; public enum UserResponseForRationale { CONTINUE_WITH_REQUEST, ABORT_REQUEST }
923ba9cc94b47da562a5867044b2427b413a7d67
1,010
java
Java
exportLibraries/vnxe/src/main/java/com/emc/storageos/vnxe/models/BasicSystemInfo.java
CoprHD/sds-controller
a575ec96928b1e9258313efe92c930bfe9d6753a
[ "Apache-2.0" ]
91
2015-06-06T01:40:34.000Z
2020-11-24T07:26:40.000Z
exportLibraries/vnxe/src/main/java/com/emc/storageos/vnxe/models/BasicSystemInfo.java
CoprHD/sds-controller
a575ec96928b1e9258313efe92c930bfe9d6753a
[ "Apache-2.0" ]
3
2015-07-14T18:47:53.000Z
2015-07-14T18:50:16.000Z
exportLibraries/vnxe/src/main/java/com/emc/storageos/vnxe/models/BasicSystemInfo.java
CoprHD/sds-controller
a575ec96928b1e9258313efe92c930bfe9d6753a
[ "Apache-2.0" ]
71
2015-06-05T21:35:31.000Z
2021-11-07T16:32:46.000Z
20.2
60
0.666337
999,679
/* * Copyright (c) 2014 EMC Corporation * All Rights Reserved */ package com.emc.storageos.vnxe.models; import org.codehaus.jackson.annotate.JsonIgnoreProperties; @JsonIgnoreProperties(ignoreUnknown = true) public class BasicSystemInfo extends VNXeBase { private String softwareVersion; private String model; private String apiVersion; private String name; public String getSoftwareVersion() { return softwareVersion; } public void setSoftwareVersion(String softwareVersion) { this.softwareVersion = softwareVersion; } public String getModel() { return model; } public void setModel(String model) { this.model = model; } public String getApiVersion() { return apiVersion; } public void setApiVersion(String apiVersion) { this.apiVersion = apiVersion; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
923ba9d971047267ab05aa8ff7c17200937849d2
69
java
Java
mobei_ioc/src/main/java/com/mobei/factorymethod/FactoryMethodTest.java
Liuyaowu/spring-framework-5.1.x
0d7fe153f2ac6c45bc37df1efa33596fc926ce17
[ "Apache-2.0" ]
null
null
null
mobei_ioc/src/main/java/com/mobei/factorymethod/FactoryMethodTest.java
Liuyaowu/spring-framework-5.1.x
0d7fe153f2ac6c45bc37df1efa33596fc926ce17
[ "Apache-2.0" ]
null
null
null
mobei_ioc/src/main/java/com/mobei/factorymethod/FactoryMethodTest.java
Liuyaowu/spring-framework-5.1.x
0d7fe153f2ac6c45bc37df1efa33596fc926ce17
[ "Apache-2.0" ]
null
null
null
13.8
32
0.811594
999,680
package com.mobei.factorymethod; public class FactoryMethodTest { }
923ba9fde5ab94b205afcc436bab0a8ec392e90a
2,091
java
Java
mapreduce-shared/src/main/java/ch/zhaw/mapreduce/plugins/socket/ByteArrayClassLoader.java
mxmo0rhuhn/map-reduce
b33a8f7c49fa37c9e39a50b19931929722247bc1
[ "MIT" ]
null
null
null
mapreduce-shared/src/main/java/ch/zhaw/mapreduce/plugins/socket/ByteArrayClassLoader.java
mxmo0rhuhn/map-reduce
b33a8f7c49fa37c9e39a50b19931929722247bc1
[ "MIT" ]
null
null
null
mapreduce-shared/src/main/java/ch/zhaw/mapreduce/plugins/socket/ByteArrayClassLoader.java
mxmo0rhuhn/map-reduce
b33a8f7c49fa37c9e39a50b19931929722247bc1
[ "MIT" ]
null
null
null
29.450704
119
0.703969
999,681
package ch.zhaw.mapreduce.plugins.socket; import java.util.HashMap; import java.util.Map; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * Diese Klasse erweitert die Standard-Java-Klasse ClassLoader um deren Methode defineClass public zu machen, damit wir * sie verwenden können. * * Im weiteren Sinne wird diese Klasse dazu benutzt, basierend auf einem Byte-Array eine Klassendefinition zu laden. * * @author Reto Hablützel (rethab) * */ public class ByteArrayClassLoader extends ClassLoader { /** * Die gleiche Klasse kann nicht zweimal geladen werden, also muessen wir sie cachen und ggf. die bereits geladene * Klasse zurueckgeben. */ private final Map<String, Class<?>> cache = new HashMap<String, Class<?>>(); /** * lock fuer cache-map. der lock ist fair, weil der erste thread, der die instanz beanträgt, wird sie dann erstellen * und die folgenden können diese benutzen. es macht daher keinen sinn, wenn einer den anderen 'überholt', weil sie * sowieso beide das gleich ziel haben (nämlich die klasse zu laden). */ private final ReadWriteLock rwLock = new ReentrantReadWriteLock(true); /** * Lädt die Klasse mit dem Standard-Java Cloassloader. * * @param className * Name der Implementations-Klasse * @param bytes * Bytes der Definiton * @return Instanz der Klassendefinition */ public Class<?> defineClass(String className, byte[] bytes) { Map<String, Class<?>> cache = this.cache; Lock readLock = this.rwLock.readLock(); Class<?> klass; readLock.lock(); try { klass = cache.get(className); } finally { readLock.unlock(); } if (klass != null) { return klass; } Lock writeLock = this.rwLock.writeLock(); writeLock.lock(); try { klass = cache.get(className); if (klass == null) { klass = defineClass(className, bytes, 0, bytes.length, null); cache.put(className, klass); return klass; } return klass; } finally { writeLock.unlock(); } } }
923baa17c322d6531211cb72449a98818a8b206f
393
java
Java
nablarch-testing-default-configuration/src/main/java/please/change/me/test/core/db/Oracle16DbInfo.java
nablarch/nablarch-default-configuration
acfc2f2861331c4bb423d5bd1697e211634025f4
[ "Apache-2.0" ]
null
null
null
nablarch-testing-default-configuration/src/main/java/please/change/me/test/core/db/Oracle16DbInfo.java
nablarch/nablarch-default-configuration
acfc2f2861331c4bb423d5bd1697e211634025f4
[ "Apache-2.0" ]
3
2016-10-13T01:45:37.000Z
2020-08-20T06:18:13.000Z
nablarch-testing-default-configuration/src/main/java/please/change/me/test/core/db/Oracle16DbInfo.java
nablarch/nablarch-default-configuration
acfc2f2861331c4bb423d5bd1697e211634025f4
[ "Apache-2.0" ]
null
null
null
24.5625
75
0.745547
999,682
package please.change.me.test.core.db; /** * JDK6でOracleを使用する場合の{@link nablarch.test.core.db.DbInfo}実装クラス。 * NVARCHAR2、NCHAR、NCLOBが{@link java.sql.Types#OTHER}にマッピングする問題に対処する為に使用する。 * <p> * 本クラスは実装上{@link Oracle15DbInfo}と差異は無い。 * 今後、JDKとJDBCドライバの組み合わせが増えることを想定し、 * JDK6専用クラスとして用意した。 * </p> * @author T.Kawasaki * @since 1.2 */ public class Oracle16DbInfo extends Oracle15DbInfo { }
923baa23598a5ad8ef4e9623b0ba5893542dd661
2,440
java
Java
services/ces/src/main/java/com/huaweicloud/sdk/ces/v1/model/Quotas.java
Limy569/huaweicloud-sdk-java-v3
5d1455853cb6329fdfb1788d81d3cb17e2a740c5
[ "Apache-2.0" ]
1
2021-06-05T16:17:28.000Z
2021-06-05T16:17:28.000Z
services/ces/src/main/java/com/huaweicloud/sdk/ces/v1/model/Quotas.java
Limy569/huaweicloud-sdk-java-v3
5d1455853cb6329fdfb1788d81d3cb17e2a740c5
[ "Apache-2.0" ]
null
null
null
services/ces/src/main/java/com/huaweicloud/sdk/ces/v1/model/Quotas.java
Limy569/huaweicloud-sdk-java-v3
5d1455853cb6329fdfb1788d81d3cb17e2a740c5
[ "Apache-2.0" ]
null
null
null
24.158416
86
0.606967
999,683
package com.huaweicloud.sdk.ces.v1.model; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import com.huaweicloud.sdk.ces.v1.model.Resource; import java.util.ArrayList; import java.util.List; import java.util.function.Consumer; import java.util.Objects; /** * */ public class Quotas { @JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty(value="resources") private List<Resource> resources = null; public Quotas withResources(List<Resource> resources) { this.resources = resources; return this; } public Quotas addResourcesItem(Resource resourcesItem) { if(this.resources == null) { this.resources = new ArrayList<>(); } this.resources.add(resourcesItem); return this; } public Quotas withResources(Consumer<List<Resource>> resourcesSetter) { if(this.resources == null) { this.resources = new ArrayList<>(); } resourcesSetter.accept(this.resources); return this; } /** * 资源配额列表。 * @return resources */ public List<Resource> getResources() { return resources; } public void setResources(List<Resource> resources) { this.resources = resources; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Quotas quotas = (Quotas) o; return Objects.equals(this.resources, quotas.resources); } @Override public int hashCode() { return Objects.hash(resources); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Quotas {\n"); sb.append(" resources: ").append(toIndentedString(resources)).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(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
923baabde93822a2f52452f63877629545460e46
1,857
java
Java
kie-pmml-trusty/kie-pmml-compiler/kie-pmml-compiler-commons/src/test/java/org/kie/pmml/compiler/commons/factories/KiePMMLLinearNormInstanceFactoryTest.java
baldimir/drools
3419454727d048a3cb2524ee1916ccaaab6118e1
[ "Apache-2.0" ]
null
null
null
kie-pmml-trusty/kie-pmml-compiler/kie-pmml-compiler-commons/src/test/java/org/kie/pmml/compiler/commons/factories/KiePMMLLinearNormInstanceFactoryTest.java
baldimir/drools
3419454727d048a3cb2524ee1916ccaaab6118e1
[ "Apache-2.0" ]
null
null
null
kie-pmml-trusty/kie-pmml-compiler/kie-pmml-compiler-commons/src/test/java/org/kie/pmml/compiler/commons/factories/KiePMMLLinearNormInstanceFactoryTest.java
baldimir/drools
3419454727d048a3cb2524ee1916ccaaab6118e1
[ "Apache-2.0" ]
null
null
null
41.266667
112
0.761443
999,684
/* * Copyright 2022 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kie.pmml.compiler.commons.factories; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.dmg.pmml.LinearNorm; import org.junit.Test; import org.kie.pmml.commons.model.expressions.KiePMMLLinearNorm; import static org.kie.pmml.compiler.api.testutils.PMMLModelTestUtils.getRandomLinearNorm; import static org.kie.pmml.compiler.commons.factories.InstanceFactoriesTestCommon.commonVerifyKiePMMLLinearNorm; public class KiePMMLLinearNormInstanceFactoryTest { @Test public void getKiePMMLLinearNorms() { List<LinearNorm> toConvert = IntStream.range(0, 3).mapToObj(i -> getRandomLinearNorm()).collect(Collectors.toList()); List<KiePMMLLinearNorm> retrieved = KiePMMLLinearNormInstanceFactory.getKiePMMLLinearNorms(toConvert); IntStream.range(0, 3).forEach(i -> commonVerifyKiePMMLLinearNorm(retrieved.get(i), toConvert.get(i))); } @Test public void getKiePMMLLinearNorm() { final LinearNorm toConvert = getRandomLinearNorm(); final KiePMMLLinearNorm retrieved = KiePMMLLinearNormInstanceFactory.getKiePMMLLinearNorm(toConvert); commonVerifyKiePMMLLinearNorm(retrieved, toConvert); } }
923bab9907184df9d0ad68e78173169d4528268e
17,258
java
Java
output/5db9bfc3666a42f7895435bc9a3657e2.java
comprakt/comprakt-fuzz-tests
c0082d105d7c54ad31ab4ea461c3b8319358eaaa
[ "Apache-2.0", "MIT" ]
null
null
null
output/5db9bfc3666a42f7895435bc9a3657e2.java
comprakt/comprakt-fuzz-tests
c0082d105d7c54ad31ab4ea461c3b8319358eaaa
[ "Apache-2.0", "MIT" ]
null
null
null
output/5db9bfc3666a42f7895435bc9a3657e2.java
comprakt/comprakt-fuzz-tests
c0082d105d7c54ad31ab4ea461c3b8319358eaaa
[ "Apache-2.0", "MIT" ]
null
null
null
38.181416
241
0.513153
999,685
class FZVZBvoF81U { public static void jgI3 (String[] SgQAylN) { int SMqxe2K = this.VApbIL(); if ( -true[ new int[ tge6_z()[ !!-!!!!--!-!null.VHh0p38ZAY_i()]].qZ_BHR()]) ; while ( -this.avShC0_MCH) ; int BQjNP = !false[ this.k1w8Sp] = -!-nSV8ReFLf().pFhmiSkdS; if ( -this.qjZ3fWg) return;else return; int[][][][][][] paz_UCzC2oi; while ( -!--!!-true.sy2) { boolean[] vObL; } void[][][][][][] F4aN6eDcpK5_DL = new void[ new boolean[ this.areoUQwz()].gcMFV0XJu].ouaY(); { ; } mh70Dzbmf44AA[][] OahhLuNLgVvjsO; void[][] p63_hy6OeoWU7; return; ; { return; EAjui4e()[ ( null[ -!true.y8])._yP8MDWbW6Ogv]; return; return; UN7_1n nQLYv1vvre3; return; wapv4Qy MUS7dNKuE; { int uCuKd0Hjnz; } zMvPR YjDJSX2B5cb; !false.xDi22qWhVxtj; boolean raPA; xCPPAtqE_Dwpy a; while ( -( !-this.GzLYGeqI73I)[ -null[ null[ null.Akg0WoHGmmQGSs]]]) ( --Ox6nXrwAC6.w()).Q7ajV2; } while ( !-Sqqvj9()[ _eu4cn.L()]) if ( null.l22BWtQ_eJ32) while ( new int[ tnU.bw()][ -173989.HsK5gmjhRtID]) return; if ( TVOmI1KPud[ 61.S9kAmerZT]) while ( !false.p39()) ;else { int[] XpNrrgDv3r; } void[] sGse5id; } } class ZT1QIhPG630 { } class JJ89lHLvRe { public int[] t0b8FLy0giR_2 () { void qkecY4jb_ = 94835415.jmmUfo() = new void[ !!qWI17dxo6I()[ -true.mKDlBNLP]].pAQK4Gx(); -new bO[ !( new void[ --1418.jiJIfSflCj][ true[ !!--null.YI_dhoONOu7Dti()]]).iC].u_Ev8VofcoBfRg(); int[] S; } public void e05LJHOc; } class r { public boolean[] d4rXvPQBR28HHS () { int Wp64BjKQuOsQ = null.NN2RLQutwgp = new xmWhbEbwy().SN_Ef0qei2cHU; return this.oI41Jqh9J(); while ( new int[ -( ma().IQanAQJvSjGs_t).LdAdJXG10XMA].gaxUhkM()) if ( null._U1zggsR4) if ( false.d_o2cH5MXyBi) if ( this[ new cNAD798()[ -62[ -!null.n]]]) if ( true.yGvNofk4_Bgp) { if ( -!072190.kSuFgF3jzF) ; } if ( !--d5swZJ[ -!!-!null.P73JfhItDyj3Em()]) ; w3m5J35AOFO Tm6lg6xxPU2kch; boolean Gnnk = !042.Df6l5f60fkLJ5J = this[ -d9().GeAHVd]; int sV = !-this.eOYA5() = !!927960.hUfJw2DYOr; ; if ( 38168.KBN2zBHj6NZhb) -189995896.ppB1(); if ( new boolean[ !--this.spyD9z0Ygxi2x][ --!( !-!-V3G._W).qJx()]) { int C9nQBRawhZ; } ; Lr9RVUaex[] GpRt = -!true[ false[ --new bRUzN8UC2k26().aDD7]] = -!--this.r_0OQp3O0b; } public boolean[][] qe1n (int[][] IUPqnrx, boolean[] wRpZ, boolean[][][][] u) throws h { kgVaPPS Zc2DjyjA0X0; ---false._3sinhXA_(); while ( ( !( -!this.YpypT())[ --( false[ vKiLi1().S3KFCHMm()]).KfhI0JznDZaK8()]).hG1AgxT) { a24 Lf3; } { ; lFHUS[] c8HNrWbNM; while ( false[ !4[ !-!!null.c4VcqV]]) ; { void g92SVuvD1; } while ( !O8MppUo_FTU().SjjI) { void[][] MfhsubhNPA; } if ( -677[ !true.ZHyzZy0EF]) { false.RTLeeaAnFhf8; } int tKbPM2o2w; -true.nIUIQjz; if ( new void[ -!this.no_JKfPo].oRVyRxzMNh) 8471460[ -!!-new oZuP66iNbCm565[ BhPySud5IXWAu[ -!new int[ -null.WpSJiO()][ !!true[ 07715[ new void[ ( -( yDV().HLaF).NF6I()).gIQdVzCzQ()].tcad_()]]]]].xrw()]; ZpJ EfS; boolean mJ7VI; } boolean[] A; bDk[] EiYGTxQr = !-!new lAWJ2().VCm() = this.V5; ; return; return 8951.uGr07p2; boolean[][] ylGWQ = --e().Sh3Ap4cT; int[] BlmMjzLmZ; while ( !r2VN06_YkDphR().An()) ; j9 t = -!new FK4Hw8b().vlMx2AM = !-x2CTwFSQw()[ !new r4IceCl849a[ -zhWamtiCG[ --!--!( FfNJ6kSvbn()[ -( null[ null.fZoWmSQVw]).ZKKAwC4k2f])[ !null[ new cK0Yokg0B[ false.EKS55()][ ---!-5719272.pB2b18e3oB]]]]].WmeFd1r()]; { int[][][] eRlxf7czAYNP3; boolean uNn3ertR_Bz_bH; boolean q; xl4DN0jke[] IC__ll3t; Mrw6jbBogjz5oY()[ !8679448.idmsNNAy06R_hL]; while ( Fc_vC9EDmjBYvo[ --!false[ kAKD1().pZn]]) { boolean Q2; } boolean AXBYRrSfpEvPH; return; int wwMGt4ZYpBwrt; while ( -196275.R65aLxH8e()) true.q6ke1z8SPj4(); boolean[] MqecQY5b; ; aNTJUz7V8B8[] xzpIVcBegIG; int[][][] hlPiZwTw79; return; } if ( new int[ -!--!new NhCw5()[ !!!( p040oRvf.p_mCH()).x8zx7()]].VEG()) { true.fRYFGsTn2t; } int[][][][][] HkiXr_xoXuxQ = 043056[ !!TlHpY[ this.iDbai]] = J().pdVM; return !new int[ new lpOn()[ null.JP2]].knVtybM; return; } public int FkFEN; public int JXFD3dceZN; public void[] J22GvEAWX () { { ; -!0.H4uo(); void v; } CZ4xIrf5x[] cmBt7; int XK; while ( null[ this[ -!!!!--( false.yZUfU02OCOst).gVzm2t()]]) return; boolean[][] aj; if ( this.hVAK6uNiq) LEhiQ().V4ttstrPd(); j1PivIYG[] vYv8y9JSapBLlt = AWl5Q9nbNMV_()[ -unWUxc.j1] = new r9SObPOl79q().ryr(); return; } public static void aOH8KuOJi1ICn7 (String[] fjSAg) { if ( !new dRDbnCEMI[ ( true.dyKAx80DnY4h()).WU_usG()].snDi56FbSUvkXn) ;else ; GKwQUPIRXxM_[] WnqUQG1qySXbL = false[ new void[ YRIcd6O3CkTmv.PkzCEXyu7LeHx()].kygop()] = new int[ --new boolean[ !new T64x8M9FQLXP().QQLFMSKOx0h].znVek()][ -new dZdlblD7wLw()[ ( tc1hi().fKYB).va()]]; !this.HNI7(); while ( new dNtuQ().d) { boolean[] n7v32; } XR1pfINKzm4bX8[][] s; boolean[] jtqCHuQR1; void[][][][] Iq3Ja; if ( new boolean[ CqB4bXD().gAnP_7tInm()].KAOZ) { return; }else { { tb h; } } Xg[][][] bfXgK2; ; int qLF1Ec2Nf3 = new b3L_Y2dNRxWT()[ !Bo()[ !-( -!new boolean[ !!false[ true.YbqvycDIDfJloq()]].f2qmM())[ false.LaiiX713epn7()]]]; while ( ( this[ ---( !!true[ asP7N0().J73bCZt5Y80AW()]).WQuY7()]).SETu9tWd()) 577[ -_ZHwXLk()[ q3fh().SO2uGxliW]]; if ( --null[ !r1.sQalPN()]) while ( !!( new PP9LEQMM[ this[ this[ new boolean[ -!null.yxqxTm].lEsq92RMTxFtmU]]].s()).Xa72FQBtde8fgi()) 0492[ !null.SRnxq];else ; boolean fJ = this[ this[ new TKOHwOUxU()[ null.pSPdVrpuXTG()]]]; } public static void ngKiup (String[] EcMMTNji) { if ( bKdHLyG.ToVJ6) return; while ( null.J5lfwwhw6Cf) { void[][] XQ1s0; } boolean[] y; int MBrH2F8Cps58M3; prmm P6bYN8HUIY9; ; ; int dtRJx3mnaE8Kv = false.so8c9N = true.lhSNACk34xa9K9; int fz7j9n379K0cQ = !false[ -true.qcn()]; ; } } class y2zI { public xApPr_r2 agseniADxy1SU (void cvZxCN87CuY, boolean[][] EE_W, boolean[] CLG3IOwdOBgG, _RCs[] YBQ3PpA) { ; ; void[][][] nKLsFJ_6X; int s57gOiGYld = new _h().ieqRf2 = new tU8ruCgt().QN9zDLj5c; int S0F0kzaZnDIA; int[] fW3z = !!new eocQKDnq().qk = !this.pQij(); int[][] RLTBg; int KoM = -!true[ --9945765[ -!new boolean[ -false[ !new boolean[ false.qEgbU3oKbT3NDL][ !-oke.fpAF6()]]].UuDKTPc6O()]]; return; if ( 702.catD()) return; int[] d1tLEvaJH; if ( !!!!!false.To6MIMLuuI()) ; ; { if ( this.Q) ; return; !new GvfJjh7HZ().zM80vhN1kl6669(); NRlBVyMI BD; null[ !YMCthL1z34J().xaS]; boolean WCQRF9zkADEHAS; void iTJDtHGT5Y4DF; { int[] O3ZtmQbIALxZGb; } } while ( -0772510.PKaFSaWEtMsT42()) if ( -!!-this[ XV3Zo().YA]) if ( !false[ this.EPnvm_yCcxG()]) if ( -null[ this.u7xg6Gc5V6X5()]) if ( true.ux()) while ( !null[ Pm8BKelG2xh[ --34.KrKr0]]) return; -new hHk45Ww9_3d0AW()[ --new SX7().DLv75]; if ( AWbVnAr9yvZn[ --true[ null[ 5[ new kK56w1vh3xmCz[ e0rrld[ -!65[ null.IF]]][ null.LaAUHbskrl]]]]]) if ( false.q7e) true[ null.ti7()]; int[][][] baIgfY4Rqgj = new mtvte().RqnrbMdK5 = !-!false.NKoPsFi(); } public int[][] MhJ2HTA; public mzhbB0lZPf0xh[][] g; public static void df7wWKFHrwkiS6 (String[] wXw) { -this.zW(); void mpe3DSTj = -6460.u00FYzr() = -!U.PrXjNiGW; l[] d0htBB; void[] iP8PBKyrl2BfMJ; while ( Ll5c()[ !!-false[ -!--null.xHBu3XCdM]]) TLL_Tjf1B().SHmqTqPG0d(); int n82Dz; ; boolean[] KICcaCg4F; boolean[] z3oiktN; return; { void Hrp7i75; if ( new KY2cb()[ tVpmZQMtaa[ -!--!dYD_4bh6_.aLaaMjzF()]]) -tnaJ.CQDsn1f; if ( --this.knn) return; XD D; void jylEV9; boolean[] n3LX8; return; ; boolean SF; uk[] aFk8; AQ94wBxwtjxl l1; int[][] Ke; } } public static void YCzAV4nW (String[] xX2K2bN) { while ( ( !( new boolean[ false[ new boolean[ new void[ false.KC3dC][ !new YSQye().EaEYBCVa]].sUjZq8WSkNjg]].QW()).R).FRmDbUjkPzd) if ( new U().LWCgqeoVXyuhh5) { return; } V ahmCfv4; ODzsAFweuij[] b; int[] ynlZ1BDJEQ7Fgz = false.zfjV(); { while ( true.n) ( !!--!!-new uu[ -false[ -new sBnZSbVWI().co7Vdznqlh2Vx]].uwTuw8_9tGt()).d6M99PYVD3JiB; -v_().zgCy; { { int[][] BKq; } } { while ( -622045.XZB92cUkG()) if ( ---false.VHo1ITi8NZb()) !7180710[ tGqScIlrWcy.CndoT()]; } void[][] _HVA6IA9zAZ9; JXAGZufe[ -xIqbeRcri1SCQ9.Gh1n()]; } a17EpyKN[][] luYdLrjid1VoSg; return; boolean ajgBdAGA68 = !!( this.gzbJJdonN)[ uSLLOEEM().e()] = !!this[ true[ !!!!-new KLxmAWUO().JOl_iRKhVl()]]; while ( this.LZOI164QT) { void[] UBl5GNPtt; } } public boolean A1pev (boolean[] h0BZDeqv, JPwJgANDA[][] _JBsLs, boolean[] i, void[] Tj1E9y) { N b_P1tNn3 = ( true.soNF9cc()).llpUfLwHonHF() = new boolean[ !new int[ ( !!this[ !null.iPdlz])[ -false[ VO.tV7YhI]]].kJ_zLUIXLRGFk].tlqBgVMWCsFC8; return; BTO5g2y lwcomj; ; s3c[] xVO2 = -!( !false.PzYxz_Qdo)[ this.IWjCd_j] = ( true.SY).SdsrY2mpRWSmRK; void[] AMDBMu0ic; ; if ( this.NZJNbNudMLN) new k90().wxoFdiGmRPPuwD;else return; if ( --false.ufHV7xsNwkD()) { boolean[] Lpnk66kmjBIy; }else ; while ( -true.UuY2c8z) new l7BBOW_h().uqI0V3wglbD; int FV8q; boolean[][] w = h8yEnlLoUBeWy().QBkmDF0 = 744.KNKvO4Ejsq0T; boolean bX; !E3ltEZIOjMSAw.bLByvq55(); if ( !!oLLk.yIB1Yz2LmoZr) while ( !-new s9GW7L0bh[ new EpFT_4wmnG45().Zv8fxH()].vfp) ;else if ( null[ null.yK()]) return; int[][] BIf8f; } public static void lKUITb2CtOBc (String[] OgkcGM1m) throws tlmUTsEbYZ { s[][] rBTGNFpQsQxwV = ( new i().UdrVdo3mF()).FdsS_G3W7FfW4A() = -new JcPKJ3Gj().ZlIW; void bpdHJOw = new OJH[ -O2tZPZaS()[ !--!!581743568[ false.mKOacIzvdI]]].zlMB; boolean eHtZ7LFeZ; int sI8H459stSfMQi = ( -new wNTrrbNqFU()[ -!null[ --!this.T4o()]]).wkoDa(); while ( !u().rdHTStUndyfH) return; } public YpBtagBg[] x6 (NE8[] Byg1DcY3XYt3, void[][] GpGoAjRk, int[][][][] q7glGmA, int QDDz0fQ8dD) throws ueZJrH { int[] xc; if ( 404.vhPKqmbLG) return; aIdM0zoT E8Jueu5UDNB1y7; void[][][] IKkJd8eKf = null.GFwLGmaE6_dK = !true.EWAdxXWvB7bgEi; ; } public static void b (String[] P) throws A { while ( -false.t) { MW().eYu_Ad5LqRrOU(); } void[] LR3Jkb = -!this.FDO(); ; while ( true.HmWGcPoM) return; while ( !---new cgkl().EJ()) new int[ ( true.E8jAAa_3Yh8l).tbW6()].zQSl4olgPXY(); L5S5wfWD7K4[][][] jmuWsIjtA1tY = -!this.T7neNxjV(); } public Lf4jOGF[] rm0ISP8COk () { !!true.EwHYO(); int mVtSFvPdtlm2; return; ; !-false.jmVXr; { return; ; if ( false[ dJ7SWCBJ2YnS0f.OgPmSQEJNVIYV]) ; int W9DSDAou2vAo; Y.EsWPW; boolean[][] eam6nQZ; boolean[] fEzjPp_6LuGcf; } this.cOD(); ; g p0nuXchDJM7uci = null.P7 = 275156.GKx; Evw5_a[][] _wHLITTEja6slH = new sq_TOF15vn().kzVgbQVou; void[] LY5h = -645689.D; } public static void dWn2kEHZ2 (String[] lMYRN4EH) throws Z_f1mS00SdBn { new mJnJP().vCM; boolean YdX3X3drajA; while ( -697385088.Qw) while ( fR_7r().oHyvKW6gGxwROE) !!null[ true.hQ1f()]; int qGO1p7RIbiN = true.nus = !!new boolean[ !!new x().GUZk3TJ()].Q8; if ( --!!new fSotlinlCAm().EFtv0_EJAqb) ; } public int uqggNg5IaKLg () { void lNY; ; int[][][] aibIxNyF6wTR; } } class lVSzY14L { public int EcGrD9grY9u4j; public int[][] EAfvlLwmvZE; public mv4[][] g8wUKxujG (void EH_Rr0O03s2dVP, boolean[][][][] ywaFZ, q0y dM8HA_5, qN KDovfLXuhO71N) throws mP { int kvIaef83xoThq = !--true.hKOupUC1tcN() = !-!new G().Gy; wxWQAAZp9j0cF[][][][] PZkllPAG = true.DP4qKuj9pO = H8KHVeuNx5cA5Q()[ null[ null.tRMG3LgdDOQkcw]]; i_wJD15f VJFpPkAolg0p; return null.eBFjZg(); boolean[] HhhN8fVDwdN = true.GcXYbyGjPofJm; void xYU; } public dr5jkjmQ[] nAwrzg; } class KRH { public FBy0s Q82cEcC; public int[][] A () throws dGdVGnnLcT { while ( -( -785028.GujW39x8nCZFM4())[ --!as1VdOjXlj.FK3RkmXw281KUO()]) { ; } void R4sABP; TbLnjtIwCXCp[] JPwFY1AfNSd8rx = !-!this.Khw8bIes_Ifx() = true.VqeP(); return; xamJpR5YuQ[][] MkM9If5GGpE1XH = !!-sNzdpsSaWiTV6.sjGHcCdwFCLd; boolean[] awHz7J7H; { boolean k5Migxnmf; boolean[] q; return; -!new i6dlMLQFS1_().QemD; } return _OJbd()[ new zaVp[ -( -new hBT0j5Vi[ false[ --P1bShy9BeYS().N6A]].VCyGGz7w6oM).fm()].syMALw]; return !-false[ ( --!false.U4ZHsL_6E()).CqF()]; nsYKlM[] uF2zdQQ; if ( tcbyYn49dFcF.uCq1W4e()) return;else if ( !-true.hs90S3A()) if ( true.K) if ( x4rHh().BT0e5N) while ( !new w0Sy1dFH().r_l) while ( -null[ !true.C]) while ( new wfOuvML().ouD9L92HQbe) while ( false.gvs()) !-!OdhopgA.LsEx_IDONE5d; return !nERZizaYaNdWni()[ !_6v.GzxcrIanu]; ; ; boolean[] AFu; { int[] ujkcR9m; int[][] SFKWZ; return; boolean[][] jLy7I7yLx4ja; { return; } ; QjWkCMhbxX9 aO8U0K_cBED; if ( !!false[ new boolean[ null.RBp4LS9QWK_M()][ !-Gg4hTGXGnZ172()[ -true[ null.TgSFW]]]]) ; return; } ; int[][][][] mgsC; boolean[] wxyvgfVh = -!false.NUdl0evrS1Qm4(); } public static void HRFhsmxj (String[] VmL0euY) { boolean cf; boolean xfPNd2nV; ; boolean[][][] h38OqrHtRt = !!!04[ --( !( ( !!-true.Ol9ZpgOJpzypHd()).X9iquxzWhX).BYjVbu())[ Zru7GX1YP()[ this.JtpM3kEPx0KKm]]] = 05059.jsnIjGvK6ru; boolean D = new iYB9T8McyN().e() = !vCsqct5me_w[ -31.Q_eZ()]; return -772578.N; while ( -!2495626.xT7CJ) if ( --!!!-!71811.L) while ( false.iRwU6HNBFOnuK) return; boolean Q_eN = !new int[ !-3[ !-!-( -( jn()[ !497.Sr6i3()])[ false.sp1qk2F9yCJyN()])[ !!Qlu2j_.HnF0]]].V; int LW = -true._ = false.dCprIB9c7Cw5; !true.i8scT(); return !!!-!!true.Zwoy(); } public static void WSJkRLRUn6i (String[] ddnfpMb) throws KYzgS { { int _ncr9X8BmFu2; int qtvnumNYsn; !new boolean[ false.Qb4THVc7fXRdpJ][ false.uqz2zuqY11]; boolean MEk; yDxpeV0XWS[] xuJrF4u22cpy_e; boolean E3co8TUOAXV; boolean m6Z; return; } boolean[][][][][] s3fv0PT_4U8x = !null.b_D(); if ( 145904219.g498AwzZNDV()) while ( 49526223[ null[ W5Z2Sk.Je2y2()]]) { false[ 58[ uUPFF8t().wQCr3KZISLHu()]]; } int[][][] Sp = !aaBH()[ !new X[ ( y.RIupKovVVQy)[ !-( !!!-Jb4LanmM5tRWX.R4Oa7n9qWlU()).Ej5z1eIT()]].evY()] = null.m; int[][][][] LZ = -!new kVaSCY2wzRSLs[ !null.BjOWK()].zDwgk7x = !!( new void[ !false.bh1a5Sf].g1uid).PLi957TevhK; return --!--new void[ !false.ADQcCX].yqdl; void zHF = -0[ -null.gjzNLInnT()] = true.Kw5MJPcIYe1a1; -new void[ --Pe.ynQ()].PRSe2MCQ3IDIY(); J7zwX__Jb UzPaFM; } }
923bac5846f960e4831541f020a27bf91846aec9
1,974
java
Java
src/main/java/com/coderevisited/strings/PatternSearching.java
sureshsajja/CodeRevisited
a08157ca7d6e0ef732f3c67179b58a4f2b903a74
[ "MIT" ]
4
2017-01-13T12:29:13.000Z
2020-08-20T22:45:21.000Z
src/main/java/com/coderevisited/strings/PatternSearching.java
sureshsajja/CodeRevisited
a08157ca7d6e0ef732f3c67179b58a4f2b903a74
[ "MIT" ]
null
null
null
src/main/java/com/coderevisited/strings/PatternSearching.java
sureshsajja/CodeRevisited
a08157ca7d6e0ef732f3c67179b58a4f2b903a74
[ "MIT" ]
9
2016-07-26T09:35:56.000Z
2022-02-07T06:05:16.000Z
32.9
81
0.64387
999,686
/* * The MIT License (MIT) * * Copyright (c) 2015 CodeRevisited.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package com.coderevisited.strings; /** * 1.start from 0 to N-M * 2. At each iteration, check if pattern matches. */ public class PatternSearching { public static void main(String[] args) { String text = "AAAAAAAAAAAAAAAAAB"; String pattern = "AAAAB"; findAllOccurrences(text, pattern); } private static void findAllOccurrences(String text, String pattern) { int N = text.length(); int M = pattern.length(); for (int i = 0; i <= N - M; i++) { int j = 0; for (; j < M; j++) { if (text.charAt(i + j) != pattern.charAt(j)) { break; } } if (j == M) { System.out.println("Pattern found at index " + i); } } } }
923bacf0ed5cd8b308a51e44cd0005d604581a86
1,691
java
Java
src/main/java/zmaster587/advancedRocketry/client/render/item/RendererLaserGun.java
phit/AdvancedRocketry
f9968be4ee0c7d151af99279e8b72199b43fbfb3
[ "MIT" ]
null
null
null
src/main/java/zmaster587/advancedRocketry/client/render/item/RendererLaserGun.java
phit/AdvancedRocketry
f9968be4ee0c7d151af99279e8b72199b43fbfb3
[ "MIT" ]
null
null
null
src/main/java/zmaster587/advancedRocketry/client/render/item/RendererLaserGun.java
phit/AdvancedRocketry
f9968be4ee0c7d151af99279e8b72199b43fbfb3
[ "MIT" ]
null
null
null
33.82
220
0.732703
999,687
package zmaster587.advancedRocketry.client.render.item; import org.lwjgl.opengl.GL11; import net.minecraft.client.renderer.ItemRenderer; import net.minecraft.client.renderer.Tessellator; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; import net.minecraftforge.client.IItemRenderer; public class RendererLaserGun implements IItemRenderer { @Override public boolean handleRenderType(ItemStack item, ItemRenderType type) { // TODO Auto-generated method stub return type == ItemRenderType.EQUIPPED_FIRST_PERSON || type == ItemRenderType.EQUIPPED; } @Override public boolean shouldUseRenderHelper(ItemRenderType type, ItemStack item, ItemRendererHelper helper) { return false; } @Override public void renderItem(ItemRenderType type, ItemStack item, Object... data) { IIcon icon = item.getIconIndex(); GL11.glPushMatrix(); if(type == ItemRenderType.EQUIPPED_FIRST_PERSON) { GL11.glTranslatef(1.3f, .3f, 0); GL11.glRotated(210, 0, 0, 1); GL11.glRotated(180, 1, 0, 0); ItemRenderer.renderItemIn2D(Tessellator.instance, ((IIcon)icon).getMinU(), ((IIcon)icon).getMinV(), ((IIcon)icon).getMaxU(), ((IIcon)icon).getMaxV(), ((IIcon)icon).getIconWidth(), ((IIcon)icon).getIconHeight(), 0.1f); } else if(type == ItemRenderType.EQUIPPED) { GL11.glTranslatef(0.7f, 1.3f, 0); GL11.glRotated(-70, 0, 0, 1); GL11.glRotated(180, 1, 0, 0); ItemRenderer.renderItemIn2D(Tessellator.instance, ((IIcon)icon).getMinU(), ((IIcon)icon).getMinV(), ((IIcon)icon).getMaxU(), ((IIcon)icon).getMaxV(), ((IIcon)icon).getIconWidth(), ((IIcon)icon).getIconHeight(), 0.1f); } GL11.glPopMatrix(); } }
923badc57893a0c63b4a51fb309112d6376af7ce
110
java
Java
src/main/java/com/jobsity/bowling_score_system/domain/FrameType.java
AlexDeLarge96/bowling-score-system
7a80dac98cd49b21123267cbfccfafd675afaab1
[ "Apache-2.0" ]
null
null
null
src/main/java/com/jobsity/bowling_score_system/domain/FrameType.java
AlexDeLarge96/bowling-score-system
7a80dac98cd49b21123267cbfccfafd675afaab1
[ "Apache-2.0" ]
null
null
null
src/main/java/com/jobsity/bowling_score_system/domain/FrameType.java
AlexDeLarge96/bowling-score-system
7a80dac98cd49b21123267cbfccfafd675afaab1
[ "Apache-2.0" ]
null
null
null
12.222222
48
0.736364
999,688
package com.jobsity.bowling_score_system.domain; public enum FrameType { STRIKE, SPARE, OPEN, LAST }
923badf454b2efdac19665a545d18743e9e92421
460
java
Java
src/main/java/com/example/demo/token/JWTToken.java
Mandelo/jwt-shiro-demo
a9c3d16e56685fcbe80b20ab8c428840cae55860
[ "Apache-2.0" ]
null
null
null
src/main/java/com/example/demo/token/JWTToken.java
Mandelo/jwt-shiro-demo
a9c3d16e56685fcbe80b20ab8c428840cae55860
[ "Apache-2.0" ]
null
null
null
src/main/java/com/example/demo/token/JWTToken.java
Mandelo/jwt-shiro-demo
a9c3d16e56685fcbe80b20ab8c428840cae55860
[ "Apache-2.0" ]
null
null
null
16.428571
54
0.641304
999,689
package com.example.demo.token; import org.apache.shiro.authc.AuthenticationToken; /** * @description: * @author: luox * @date: 2021/2/22 */ public class JWTToken implements AuthenticationToken { private String token; public JWTToken(String token) { this.token = token; } @Override public Object getPrincipal() { return token; } @Override public Object getCredentials() { return token; } }
923baed803aba6529f60024da78aceaa2d978d9a
1,466
java
Java
src/main/java/org/libgit2/jagged/ObjectType.java
shijinglu/jagged
62f4ddb7fc1bab55f114f3f1e07a5b191f899753
[ "MIT" ]
104
2015-01-06T18:20:59.000Z
2022-02-20T19:15:51.000Z
src/main/java/org/libgit2/jagged/ObjectType.java
shijinglu/jagged
62f4ddb7fc1bab55f114f3f1e07a5b191f899753
[ "MIT" ]
10
2015-05-05T00:15:55.000Z
2019-12-19T21:32:45.000Z
src/main/java/org/libgit2/jagged/ObjectType.java
shijinglu/jagged
62f4ddb7fc1bab55f114f3f1e07a5b191f899753
[ "MIT" ]
30
2015-03-25T20:40:34.000Z
2022-03-09T02:51:11.000Z
19.038961
97
0.569577
999,690
package org.libgit2.jagged; import java.text.MessageFormat; import java.util.EnumSet; import java.util.HashMap; import java.util.Map; public enum ObjectType { /** * An object of any type. Used only for querying by type; an object will * never have this type set. */ ANY(-2), /** An invalid object */ INVALID(-1), /** A commit */ COMMIT(1), /** A tree */ TREE(2), /** A blob */ BLOB(3), /** A tag */ TAG(4), /** * In a pack file, this object is defined as a delta from another object * identified by its offset into the pack file. */ OFFSET_DELTA(6), /** * In a pack file, this object is defined as a delta from another object * identified by its ID. */ REFERENCE_DELTA(7); private final int value; private static final Map<Integer, ObjectType> types = new HashMap<Integer, ObjectType>(); static { for (ObjectType type : EnumSet.allOf(ObjectType.class)) { types.put(type.getValue(), type); } } private ObjectType(int value) { this.value = value; } int getValue() { return value; } static ObjectType valueOf(int value) { ObjectType type = types.get(value); if (type == null) { throw new IllegalArgumentException(MessageFormat.format("Unknown type: {0}", value)); } return type; } }
923bb121f5d535a3c7dd71e0c092f8b407b9a198
6,437
java
Java
src/test/java/com/github/javafaker/FakerTest.java
sachsgit/java-faker-1
7737ac0300c34984d287bf9c13dbb7b5c1e70fb1
[ "Apache-2.0" ]
null
null
null
src/test/java/com/github/javafaker/FakerTest.java
sachsgit/java-faker-1
7737ac0300c34984d287bf9c13dbb7b5c1e70fb1
[ "Apache-2.0" ]
null
null
null
src/test/java/com/github/javafaker/FakerTest.java
sachsgit/java-faker-1
7737ac0300c34984d287bf9c13dbb7b5c1e70fb1
[ "Apache-2.0" ]
null
null
null
36.162921
158
0.672829
999,691
package com.github.javafaker; import static com.github.javafaker.matchers.MatchesRegularExpression.matchesRegularExpression; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.emptyString; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.nullValue; import java.util.Locale; import java.util.Random; import org.junit.Test; import com.github.javafaker.repeating.Repeat; public class FakerTest extends AbstractFakerTest { @Test public void bothifyShouldGenerateLettersAndNumbers() { assertThat(faker.bothify("????dycjh@example.com"), matchesRegularExpression("hzdkv@example.com")); } @Test public void letterifyShouldGenerateLetters() { assertThat(faker.bothify("????"), matchesRegularExpression("\\w{4}")); } @Test public void letterifyShouldGenerateUpperCaseLetters() { assertThat(faker.bothify("????", true), matchesRegularExpression("[A-Z]{4}")); } @Test public void letterifyShouldLeaveNonSpecialCharactersAlone() { assertThat(faker.bothify("ABC????DEF"), matchesRegularExpression("ABC\\w{4}DEF")); } @Test public void numerifyShouldGenerateNumbers() { assertThat(faker.numerify("####"), matchesRegularExpression("\\d{4}")); } @Test public void numerifyShouldLeaveNonSpecialCharactersAlone() { assertThat(faker.numerify("####123"), matchesRegularExpression("\\d{4}123")); } @Test public void regexifyShouldGenerateNumbers() { assertThat(faker.regexify("\\d"), matchesRegularExpression("\\d")); } @Test public void regexifyShouldGenerateLetters() { assertThat(faker.regexify("\\w"), matchesRegularExpression("\\w")); } @Test public void regexifyShouldGenerateAlternations() { assertThat(faker.regexify("(a|b)"), matchesRegularExpression("(a|b)")); } @Test public void regexifyShouldGenerateBasicCharacterClasses() { assertThat(faker.regexify("(aeiou)"), matchesRegularExpression("(aeiou)")); } @Test public void regexifyShouldGenerateCharacterClassRanges() { assertThat(faker.regexify("[a-z]"), matchesRegularExpression("[a-z]")); } @Test public void regexifyShouldGenerateMultipleCharacterClassRanges() { assertThat(faker.regexify("[a-z1-9]"), matchesRegularExpression("[a-z1-9]")); } @Test public void regexifyShouldGenerateSingleCharacterQuantifiers() { assertThat(faker.regexify("a*b+c?"), matchesRegularExpression("a*b+c?")); } @Test public void regexifyShouldGenerateBracketsQuantifiers() { assertThat(faker.regexify("a{2}"), matchesRegularExpression("a{2}")); } @Test public void regexifyShouldGenerateMinMaxQuantifiers() { assertThat(faker.regexify("a{2,3}"), matchesRegularExpression("a{2,3}")); } @Test public void regexifyShouldGenerateBracketsQuantifiersOnBasicCharacterClasses() { assertThat(faker.regexify("[aeiou]{2,3}"), matchesRegularExpression("[aeiou]{2,3}")); } @Test public void regexifyShouldGenerateBracketsQuantifiersOnCharacterClassRanges() { assertThat(faker.regexify("[a-z]{2,3}"), matchesRegularExpression("[a-z]{2,3}")); } @Test public void regexifyShouldGenerateBracketsQuantifiersOnAlternations() { assertThat(faker.regexify("(a|b){2,3}"), matchesRegularExpression("(a|b){2,3}")); } @Test public void regexifyShouldGenerateEscapedCharacters() { assertThat(faker.regexify("\\.\\*\\?\\+"), matchesRegularExpression("\\.\\*\\?\\+")); } @Test(expected = RuntimeException.class) public void badExpressionTooManyArgs() { faker.expression("#{regexify 'a','a'}"); } @Test(expected = RuntimeException.class) public void badExpressionTooFewArgs() { faker.expression("#{regexify}"); } @Test(expected = RuntimeException.class) public void badExpressionCouldntCoerce() { faker.expression("#{number.number_between 'x','10'}"); } @Test public void expression() { assertThat(faker.expression("#{regexify '(a|b){2,3}'}"), matchesRegularExpression("(a|b){2,3}")); assertThat(faker.expression("#{regexify '\\.\\*\\?\\+'}"), matchesRegularExpression("\\.\\*\\?\\+")); assertThat(faker.expression("#{bothify '????','true'}"), matchesRegularExpression("[A-Z]{4}")); assertThat(faker.expression("#{bothify '????','false'}"), matchesRegularExpression("[a-z]{4}")); assertThat(faker.expression("#{letterify '????','true'}"), matchesRegularExpression("[A-Z]{4}")); assertThat(faker.expression("#{Name.first_name} #{Name.first_name} #{Name.last_name}"), matchesRegularExpression("[a-zA-Z']+ [a-zA-Z']+ [a-zA-Z']+")); assertThat(faker.expression("#{number.number_between '1','10'}"), matchesRegularExpression("[1-9]")); assertThat(faker.expression("#{color.name}"), matchesRegularExpression("[a-z\\s]+")); } @Test @Repeat(times = 100) public void numberBetweenRepeated() { assertThat(faker.expression("#{number.number_between '1','10'}"), matchesRegularExpression("[1-9]")); } @Test public void regexifyShouldGenerateSameValueForFakerWithSameSeed() { long seed = 1L; String regex = "\\d"; String firstResult = new Faker(new Random(seed)).regexify(regex); String secondResult = new Faker(new Random(seed)).regexify(regex); assertThat(secondResult, is(firstResult)); } @Test public void resolveShouldReturnValueThatExists() { assertThat(faker.resolve("address.city_prefix"), not(emptyString())); } @Test(expected = RuntimeException.class) public void resolveShouldThrowExceptionWhenPropertyDoesntExist() { final String resolve = faker.resolve("address.nothing"); assertThat(resolve, is(nullValue())); } @Test public void fakerInstanceCanBeAcquiredViaUtilityMethods() { assertThat(Faker.instance(), is(instanceOf(Faker.class))); assertThat(Faker.instance(Locale.CANADA), is(instanceOf(Faker.class))); assertThat(Faker.instance(new Random(1)), is(instanceOf(Faker.class))); assertThat(Faker.instance(Locale.CHINA, new Random(2)), is(instanceOf(Faker.class))); } }
923bb41980da16c827604b4b51ad99291ca8b4de
2,099
java
Java
src/main/java/com/betomorrow/stubery/applications/domain/Application.java
ogauthier-betomorrow/api-stubs-server
e3616baf452b971b1bafb041131c62fac4f40af2
[ "MIT" ]
null
null
null
src/main/java/com/betomorrow/stubery/applications/domain/Application.java
ogauthier-betomorrow/api-stubs-server
e3616baf452b971b1bafb041131c62fac4f40af2
[ "MIT" ]
null
null
null
src/main/java/com/betomorrow/stubery/applications/domain/Application.java
ogauthier-betomorrow/api-stubs-server
e3616baf452b971b1bafb041131c62fac4f40af2
[ "MIT" ]
null
null
null
24.988095
113
0.584564
999,692
package com.betomorrow.stubery.applications.domain; import org.springframework.data.annotation.Id; public class Application { @Id private String id; private String name; private String contextPath; private String icon; public Application() { } public Application(String id, String name, String contextPath, String icon) { this.id = id; this.name = name; this.contextPath = contextPath; this.icon = icon; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getContextPath() { return contextPath; } public void setContextPath(String contextPath) { this.contextPath = contextPath; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } public void updateWith(Application data) { contextPath = data.getContextPath(); name = data.getName(); icon = data.getIcon(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Application that = (Application) o; if (id != null ? !id.equals(that.id) : that.id != null) return false; if (name != null ? !name.equals(that.name) : that.name != null) return false; if (contextPath != null ? !contextPath.equals(that.contextPath) : that.contextPath != null) return false; return icon != null ? icon.equals(that.icon) : that.icon == null; } @Override public int hashCode() { int result = id != null ? id.hashCode() : 0; result = 31 * result + (name != null ? name.hashCode() : 0); result = 31 * result + (contextPath != null ? contextPath.hashCode() : 0); result = 31 * result + (icon != null ? icon.hashCode() : 0); return result; } }
923bb46e5c6d5d69c71812c00962f336e87c620b
2,853
java
Java
src/main/java/pw/aru/libs/dicenotation/parser/DefaultGrammar.java
jibrilbot/dice-notation
a02e96a5812393ee24409c7fc920f524b6930a0a
[ "Apache-2.0" ]
null
null
null
src/main/java/pw/aru/libs/dicenotation/parser/DefaultGrammar.java
jibrilbot/dice-notation
a02e96a5812393ee24409c7fc920f524b6930a0a
[ "Apache-2.0" ]
null
null
null
src/main/java/pw/aru/libs/dicenotation/parser/DefaultGrammar.java
jibrilbot/dice-notation
a02e96a5812393ee24409c7fc920f524b6930a0a
[ "Apache-2.0" ]
null
null
null
50.946429
120
0.770067
999,693
/* * 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 pw.aru.libs.dicenotation.parser; import pw.aru.libs.dicenotation.ast.operations.BinaryOperatorType; import pw.aru.libs.dicenotation.ast.operations.UnaryOperatorType; import pw.aru.libs.dicenotation.lexer.TokenType; import pw.aru.libs.dicenotation.parser.parslets.GroupParser; import pw.aru.libs.dicenotation.parser.parslets.NameParser; import pw.aru.libs.dicenotation.parser.parslets.nodes.DecimalParser; import pw.aru.libs.dicenotation.parser.parslets.nodes.DiceNotationParser; import pw.aru.libs.dicenotation.parser.parslets.nodes.IntParser; import pw.aru.libs.dicenotation.parser.parslets.operators.BinaryOperatorParser; import pw.aru.libs.dicenotation.parser.parslets.operators.UnaryOperatorParser; public class DefaultGrammar extends Grammar { public static final Grammar INSTANCE = new DefaultGrammar(); private DefaultGrammar() { // BLOCKS prefix(TokenType.LEFT_PAREN, new GroupParser()); // NODES prefix(TokenType.INT, new IntParser()); prefix(TokenType.NUMBER, new DecimalParser()); prefix(TokenType.DICE_NOTATION, new DiceNotationParser()); prefix(TokenType.IDENTIFIER, new NameParser()); // Numeric prefix(TokenType.MINUS, new UnaryOperatorParser(UnaryOperatorType.MINUS)); prefix(TokenType.PLUS, new UnaryOperatorParser(UnaryOperatorType.PLUS)); infix(TokenType.PLUS, new BinaryOperatorParser(Precedence.ADDITIVE, true, BinaryOperatorType.PLUS)); infix(TokenType.MINUS, new BinaryOperatorParser(Precedence.ADDITIVE, true, BinaryOperatorType.MINUS)); infix(TokenType.ASTERISK, new BinaryOperatorParser(Precedence.MULTIPLICATIVE, true, BinaryOperatorType.TIMES)); infix(TokenType.SLASH, new BinaryOperatorParser(Precedence.MULTIPLICATIVE, true, BinaryOperatorType.DIVIDE)); infix(TokenType.PERCENT, new BinaryOperatorParser(Precedence.MULTIPLICATIVE, true, BinaryOperatorType.MODULUS)); infix(TokenType.CARET, new BinaryOperatorParser(Precedence.EXPONENTIAL, false, BinaryOperatorType.POWER)); infix(TokenType.SHIFT_RIGHT, new BinaryOperatorParser(Precedence.SHIFT, true, BinaryOperatorType.SHR)); infix(TokenType.SHIFT_LEFT, new BinaryOperatorParser(Precedence.SHIFT, true, BinaryOperatorType.SHL)); } }
923bb4d16acbd6b87632b74d9b2a32069d0bad8f
20,381
java
Java
java/org.apache.derby.server/org/apache/derby/mbeans/drda/NetworkServerMBean.java
Sudeepa14/derby
d6e1b1de6113257d3eba1ea7de34f1d6f54f6c88
[ "Apache-2.0" ]
282
2015-01-06T02:30:11.000Z
2022-03-23T06:40:17.000Z
java/org.apache.derby.server/org/apache/derby/mbeans/drda/NetworkServerMBean.java
Sudeepa14/derby
d6e1b1de6113257d3eba1ea7de34f1d6f54f6c88
[ "Apache-2.0" ]
null
null
null
java/org.apache.derby.server/org/apache/derby/mbeans/drda/NetworkServerMBean.java
Sudeepa14/derby
d6e1b1de6113257d3eba1ea7de34f1d6f54f6c88
[ "Apache-2.0" ]
163
2015-01-07T00:07:53.000Z
2022-03-07T08:35:03.000Z
41.090726
82
0.646975
999,694
/* Derby - Class org.apache.derby.mbeans.drda.NetworkServerMBean 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.derby.mbeans.drda; /** * <p> * This is an MBean defining a JMX management and monitoring interface of * Derby's Network Server.</p> * <p> * This MBean is created and registered automatically at Network Server startup * if all requirements are met (J2SE 5.0 or better).</p> * <p> * Key properties for the registered MBean:</p> * <ul> * <li><code>type=NetworkServer</code></li> * <li><code>system=</code><em>runtime system identifier</em> (see * <a href="../package-summary.html#package_description">description of * package org.apache.derby.mbeans</a>)</li> * </ul> * <p> * If a security manager is installed, accessing attributes and operations of * this MBean may require a <code>SystemPermission</code>; see individual method * documentation for details.</p> * <p> * For more information on Managed Beans, refer to the JMX specification.</p> * * @see org.apache.derby.drda.NetworkServerControl * @see org.apache.derby.shared.common.security.SystemPermission * @see <a href="../package-summary.html"><code>org.apache.derby.mbeans</code></a> */ public interface NetworkServerMBean { // --- // ----------------- MBean attributes ------------------------------------ // --- // Commented setters because: // No attribute setting yet due to security concerns, see DERBY-1387. /** * <p> * Gets the network interface address on which the Network Server is * listening. This corresponds to the value of the * <code>derby.drda.host</code> property.</p> * <p> * For example, the value "<code>localhost</code>" means that the * Network Server is listening on the local loopback interface only. * <p> * The special value "<code>0.0.0.0</code>" (IPv4 environments only) * represents the "unspecified address" - also known as the anylocal or * wildcard address. In this context this means that the server is * listening on all network interfaces (and may thus be able to see * connections from both the local host as well as remote hosts, depending * on which network interfaces are available).</p> * <p> * Requires <code>SystemPermission("server", "control")</code> if a security * manager is installed.</p> * * @return the the network interface address on which the Network Server is * listening (<code>derby.drda.host</code>) */ public String getDrdaHost(); /** * <p> * Reports whether or not the Derby Network Server will send keep-alive * probes and attempt to clean up connections for disconnected clients (the * value of the {@code derby.drda.keepAlive} property).</p> * <p> * If {@code true}, a keep-alive probe is sent to the client if a "long * time" (by default, more than two hours) passes with no other data being * sent or received. This will detect and clean up connections for clients * on powered-off machines or clients that have disconnected unexpectedly. * </p> * <p> * If {@code false}, Derby will not attempt to clean up connections from * disconnected clients, and will not send keep-alive probes.</p> * <p> * Requires <code>SystemPermission("server", "monitor")</code> if a security * manager is installed.</p> * <p> * See also the documentation for the property {@code derby.drda.keepAlive} * in the <em>Derby Server and Administration Guide</em>, section * <em>Managing the Derby Network Server</em>, subsection <em>Setting * Network Server Properties</em>, subsubsection <em>derby.drda.keepAlive * property</em>. * </p> * @return {@code true} if Derby Network Server will send keep-alive * probes and attempt to clean up connections for disconnected * clients ({@code derby.drda.keepAlive}) */ public boolean getDrdaKeepAlive(); /** * <p> * Reports the maximum number of client connection threads the Network * Server will allocate at any given time. This corresponds to the * <code>derby.drda.maxThreads</code> property.</p> * <p> * Requires <code>SystemPermission("server", "monitor")</code> if a security * manager is installed.</p> * * @return the maximum number of client connection threads the Network * Server will allocate at any given time * (<code>derby.drda.maxThreads</code>) */ public int getDrdaMaxThreads(); //public void setDrdaMaxThreads(int max) throws Exception; /** * <p> * Gets the port number on which the Network Server is listening for client * connections. This corresponds to the value of the * <code>derby.drda.portNumber</code> Network Server setting.</p> * <p> * Requires <code>SystemPermission("server", "control")</code> if a security * manager is installed.</p> * * @return the port number on which the Network Server is listening * for client connections. */ public int getDrdaPortNumber(); /** * <p> * The Derby security mechanism required by the Network Server for all * client connections. This corresponds to the value of the * <code>derby.drda.securityMechanism</code> property on the server.</p> * <p> * If not set, the empty String will be returned, which means that the * Network Server accepts any connection which uses a valid security * mechanism.</p> * <p> * For a list of valid security mechanisms, refer to the * documentation for the <code>derby.drda.securityMechanism</code> property * in the <i>Derby Server and Administration Guide</i>.</p> * <p> * Requires <code>SystemPermission("server", "control")</code> if a security * manager is installed.</p> * * @return the security mechanism required by the Network Server for all * client connections (<code>derby.drda.securityMechanism</code>) */ public String getDrdaSecurityMechanism(); /** * <p> * Reports whether client connections must be encrypted using Secure * Sockets Layer (SSL), and whether certificate based peer authentication * is enabled. Refers to the <code>derby.drda.sslMode</code> property.</p> * <p> * Peer authentication means that the other side of the SSL connection is * authenticated based on a trusted certificate installed locally.</p> * <p> * The value returned is one of "<code>off</code>" (no SSL encryption), * "<code>basic</code>" (SSL encryption, no peer authentication) and * "<code>peerAuthentication</code>" (SSL encryption and peer * authentication). Refer to the <i>Derby Server and Administration * Guide</i> for more details.</p> * <p> * Requires <code>SystemPermission("server", "control")</code> if a security * manager is installed.</p> * * @return whether client connections must be encrypted using Secure * Sockets Layer (SSL), and whether certificate based peer * authentication is enabled (<code>derby.drda.sslMode</code>) */ public String getDrdaSslMode(); /** * <p> * The size of the buffer used for streaming BLOB and CLOB from server to * client. Refers to the <code>derby.drda.streamOutBufferSize</code> * property.</p> * <p> * This setting may improve streaming performance when the default sizes of * packets being sent are significantly smaller than the maximum allowed * packet size in the network.</p> * <p> * Requires <code>SystemPermission("server", "monitor")</code> if a security * manager is installed.</p> * * @return the size of the buffer used for streaming blob/clob from server * to client (<code>derby.drda.streamOutBufferSize</code>) */ public int getDrdaStreamOutBufferSize(); /** * <p> * If the server property <code>derby.drda.maxThreads</code> is set to a * non-zero value, this is the number of milliseconds that each client * connection will actively use in the Network Server before yielding to * another connection. If this value is 0, a waiting connection will become * active once a currently active connection is closed.</p> * <p> * Refers to the <code>derby.drda.timeSlice</code> server property.</p> * <p> * Requires <code>SystemPermission("server", "monitor")</code> if a security * manager is installed.</p> * * @return the number of milliseconds that each client connection will * actively use in the Network Server before yielding to * another connection (<code>derby.drda.timeSlice</code>) * @see #getDrdaMaxThreads() */ public int getDrdaTimeSlice(); //public void setDrdaTimeSlice(int timeSlice) throws Exception; /** * <p> * Whether server-side tracing is enabled for all client connections * (sessions). Refers to the <code>derby.drda.traceAll</code> server * property.</p> * <p> * Tracing may for example be useful when providing technical support * information. The Network Server also supports tracing for individual * connections (sessions), see the <i>Derby Server and Administration * Guide</i> ("Controlling tracing by using the trace facility") for * details.</p> * <p> * When tracing is enabled, tracing information from each client * connection will be written to a separate trace file. * </p> * <p> * Requires <code>SystemPermission("server", "monitor")</code> if a security * manager is installed.</p> * * @return whether tracing for all client connections is enabled * (<code>derby.drda.traceAll</code>) * @see #getDrdaTraceDirectory() */ public boolean getDrdaTraceAll(); //public void setDrdaTraceAll(boolean on) throws Exception; /** * <p> * Indicates the location of tracing files on the server host, if server * tracing has been enabled.</p> * <p> * If the server setting <code>derby.drda.traceDirectory</code> is set, * its value will be returned. Otherwise, the Network Server's default * values will be taken into account when producing the result.</p> * <p> * Requires <code>SystemPermission("server", "control")</code> if a security * manager is installed.</p> * * @return the potential location of tracing files on the server host * @see #getDrdaTraceAll() */ public String getDrdaTraceDirectory(); //public void setDrdaTraceDirectory(String dir) throws Exception; /** * <p> * Gets the total number of current connections (waiting or active) to the * Network Server.</p> * <p> * Requires <code>SystemPermission("server", "monitor")</code> if a security * manager is installed.</p> * * @return the number of current connections * @see #getActiveConnectionCount() * @see #getWaitingConnectionCount() */ public int getConnectionCount(); /** * <p> * Gets the number of currently active connections. All connections are * active if the DrdaMaxThreads attribute (<code>derby.drda.maxThreads</code> * property) is 0.</p> * <p> * If DrdaMaxThreads is &gt; 0 and DrdaTimeSlice is 0, connections remain * active until they are closed. If there are more than DrdaMaxThreads * connections, inactive connections will be waiting for some active * connection to close. The connection request will return when the * connection becomes active.</p> * <p> * If DrdaMaxThreads is &gt; 0 and DrdaTimeSlice &gt; 0, connections will be * alternating beetween active and waiting according to Derby's time * slicing algorithm.</p> * <p> * Requires <code>SystemPermission("server", "monitor")</code> if a security * manager is installed.</p> * * @return the number of active connections * @see #getDrdaMaxThreads() * @see #getDrdaTimeSlice() * @see #getWaitingConnectionCount() */ public int getActiveConnectionCount(); /** * <p> * Gets the number of currently waiting connections. This number will always * be 0 if DrdaMaxThreads is 0. Otherwise, if the total number of * connections is less than or equal to DrdaMaxThreads, then no connections * are waiting.</p> * <p> * Requires <code>SystemPermission("server", "monitor")</code> if a security * manager is installed.</p> * * @return the number of waiting connections * @see #getActiveConnectionCount() * @see #getDrdaMaxThreads() * @see #getDrdaTimeSlice() */ public int getWaitingConnectionCount(); /** * <p> * Get the size of the connection thread pool. If DrdaMaxThreads * (<code>derby.drda.maxThreads</code>) is set to a non-zero value, the size * of the thread pool will not exceed this value.</p> * <p> * Requires <code>SystemPermission("server", "monitor")</code> if a security * manager is installed.</p> * * @return the size of the Network Server's connection thread pool * @see #getDrdaMaxThreads() */ public int getConnectionThreadPoolSize(); /** * <p> * Gets the accumulated number of connections. This includes all active and * waiting connections since the Network Server was started. This number * will not decrease as long as the Network Server is running.</p> * <p> * Require <code>SystemPermission("server", "monitor")</code> if a security * manager is installed.</p> * * @return the accumulated number of connections made since server startup */ public int getAccumulatedConnectionCount(); /** * <p> * Gets the total number of bytes read by the server since it was started. * </p> * <p> * Require <code>SystemPermission("server", "monitor")</code> if a security * manager is installed.</p> * * @return the total number of bytes received by the server */ public long getBytesReceived(); /** * <p> * Gets the total number of bytes written by the server since it was * started.</p> * <p> * Requires <code>SystemPermission("server", "monitor")</code> if a security * manager is installed.</p> * * @return the total number of bytes sent by the server */ public long getBytesSent(); /** * <p> * Gets the number of bytes received per second by the Network * Server. This number is calculated by taking into account the number of * bytes received since the last calculation (or since MBean startup if * it is the first time this attibute is being read).</p> * <p> * The shortest interval measured is 1 second. This means that a new value * will not be calculated unless there has been at least 1 second since the * last calculation.</p> * <p> * Requires <code>SystemPermission("server", "monitor")</code> if a security * manager is installed.</p> * * @return the number of bytes received per second */ public int getBytesReceivedPerSecond(); /** * <p> * Gets the number of bytes sent per second by the Network Server. * This number is calculated by taking into account the number of * bytes sent since the last calculation (or since MBean startup if * it is the first time this attibute is being read).</p> * <p> * The shortest interval measured is 1 second. This means that a new value * will not be calculated unless there has been at least 1 second since the * last calculation.</p> * <p> * Requires <code>SystemPermission("server", "monitor")</code> if a security * manager is installed.</p> * * @return the number of bytes sent per millisecond */ public int getBytesSentPerSecond(); /** * <p> * Gets the start time of the network server. The time is reported as * the number of milliseconds (ms) since Unix epoch (1970-01-01 00:00:00 * UTC), and corresponds to the value of * <code>java.lang.System#currentTimeMillis()</code> at the time the * Network Server was started.</p> * <p> * Requires <code>SystemPermission("server", "monitor")</code> if a security * manager is installed.</p> * * @return the difference, measured in milliseconds, between the time the * Network Server was started and Unix epoch (1970-01-01T00:00:00Z) * @see java.lang.System#currentTimeMillis() */ public long getStartTime(); /** * <p> * Gets the time (in milliseconds) the Network Server has been running. In * other words, the time passed since the server was started.</p> * <p> * Requires <code>SystemPermission("server", "monitor")</code> if a security * manager is installed.</p> * * @return the difference, measured in milliseconds, between the current * time and the time the Network Server was started * @see #getStartTime() */ public long getUptime(); // --- // ----------------- MBean operations ------------------------------------ // --- /** * <p> * Executes the network server's <code>ping</code> command. * Returns without errors if the server was successfully pinged.</p> * <p> * Note that the <code>ping</code> command itself will be executed from the * network server instance that is actually running the server, and that the * result will be transferred via JMX to the JMX client invoking this * operation. * This means that this operation will test network server connectivity * from the same host (machine) as the network server, as opposed to when * the <code>ping</code> command (or method) of * <code>NetworkServerControl</code> is executed from a remote machine.</p> * <p> * This operation requires the following permission to be granted to * the network server code base if a Java security manager is installed * in the server JVM:</p> * <codeblock> * <code> * permission java.net.SocketPermission "*", "connect,resolve"; * </code> * </codeblock> * <p>The value <code>"*"</code> will allow connections from the network * server to any host and any port, and may be replaced with a more specific * value if so desired. The required value will depend on the value of the * <code>-h</code> (or <code>derby.drda.host</code>) (host) and * <code>-p</code> (or <code>derby.drda.portNumber</code>) (port) settings * of the Network Server.</p> * <p> * Requires <code>SystemPermission("server", "monitor")</code> if a security * manager is installed.</p> * * @throws java.lang.Exception if the ping attempt fails (an indication that * the network server is not running properly) * @see org.apache.derby.drda.NetworkServerControl#ping() * @see java.net.SocketPermission */ public void ping() throws Exception; // No other management operations yet due to security concerns, see // DERBY-1387 for details. }
923bb5ab6f3c1af5d06651a5df27849b16b059ff
1,818
java
Java
src/main/java/com/emall/dao/GoodsMapper.java
Jasonrale/emall
3bd31624eed84310229860003cefdf9da0147e00
[ "Apache-2.0" ]
4
2019-06-15T08:14:21.000Z
2020-06-28T16:14:57.000Z
src/main/java/com/emall/dao/GoodsMapper.java
Jasonrale/emall
3bd31624eed84310229860003cefdf9da0147e00
[ "Apache-2.0" ]
null
null
null
src/main/java/com/emall/dao/GoodsMapper.java
Jasonrale/emall
3bd31624eed84310229860003cefdf9da0147e00
[ "Apache-2.0" ]
null
null
null
34.301887
137
0.716172
999,695
package com.emall.dao; import com.emall.entity.Category; import com.emall.entity.Goods; import org.apache.ibatis.annotations.Param; import java.util.List; /** * 商品数据接口层 */ public interface GoodsMapper { int insert(Goods goods); int count(); int deleteByGoodsId(@Param("goodsId") String goodsId); int countByKeyWord(@Param("keyWord") String keyWord); int countByKeyWordForUser(@Param("keyWord") String keyWord); int countByCategoryIdForUser(@Param("categoryId") String categoryId); Goods selectByGoodsId(@Param("goodsId") String goodsId); List<Goods> queryAll(@Param("limit") long limit, @Param("offset") long offset); List<Goods> selectByKeyWord(@Param("keyWord") String keyWord, @Param("limit") long limit, @Param("offset") long offset); List<Goods> selectByKeyWordPaged(@Param("keyWord") String keyWord, @Param("limit") long limit, @Param("offset") long offset); List<Goods> selectByKeyWordAsc(@Param("keyWord") String keyWord, @Param("limit") long limit, @Param("offset") long offset); List<Goods> selectByKeyWordDesc(@Param("keyWord") String keyWord, @Param("limit") long limit, @Param("offset") long offset); List<Goods> selectByCategoryId(@Param("categoryId") String categoryId, @Param("limit") long limit, @Param("offset") long offset); List<Goods> selectByCategoryIdAsc(@Param("categoryId") String categoryId, @Param("limit") long limit, @Param("offset") long offset); List<Goods> selectByCategoryIdDesc(@Param("categoryId") String categoryId, @Param("limit") long limit, @Param("offset") long offset); int pull(@Param("goodsId") String goodsId); int put(@Param("goodsId") String goodsId); int updateByGoodsId(Goods goods); int recoverStock(@Param("goodsId") String goodsId, @Param("count") Integer count); }
923bb64cb95a79dfd1d6aa4574b280a25ec3f076
1,402
java
Java
src/main/java/com/qianmi/open/api/qmcs/endpoint/ClientIdentity.java
howe/bm-elife-api-sdk
008f156c33d6da598198cfb221f019ad33d30109
[ "Apache-2.0" ]
null
null
null
src/main/java/com/qianmi/open/api/qmcs/endpoint/ClientIdentity.java
howe/bm-elife-api-sdk
008f156c33d6da598198cfb221f019ad33d30109
[ "Apache-2.0" ]
null
null
null
src/main/java/com/qianmi/open/api/qmcs/endpoint/ClientIdentity.java
howe/bm-elife-api-sdk
008f156c33d6da598198cfb221f019ad33d30109
[ "Apache-2.0" ]
1
2020-07-17T05:50:18.000Z
2020-07-17T05:50:18.000Z
26.45283
97
0.622682
999,696
package com.qianmi.open.api.qmcs.endpoint; import com.qianmi.open.api.qmcs.channel.ChannelException; import java.util.Map; /** * 客户端身份标识 */ public class ClientIdentity implements Identity { private String appKey; private String groupName; public ClientIdentity(String appKey, String groupName) { this.appKey = appKey; this.groupName = groupName; } @Override public Identity parse(Object data) throws ChannelException { return null; } @Override public void render(Object to) { ((Map<String, String>) to).put("app_key", this.appKey); ((Map<String, String>) to).put("group_name", this.groupName); } @Override public boolean equals(Identity id) { if (!id.getClass().equals(ClientIdentity.class)) { return false; } ClientIdentity that = (ClientIdentity) id; if (appKey != null ? !appKey.equals(that.appKey) : that.appKey != null) return false; return !(groupName != null ? !groupName.equals(that.groupName) : that.groupName != null); } @Override public int hashCode() { int result = appKey != null ? appKey.hashCode() : 0; result = 31 * result + (groupName != null ? groupName.hashCode() : 0); return result; } @Override public String toString() { return this.appKey + "~" + this.groupName; } }
923bb6882a1ca319530eb369827b225c4c03d4f7
632
java
Java
hexa.core/src/main/java/fr/lteconsulting/hexa/client/form/marshalls/MarshallBoolean.java
xiayingfeng/hexa.tools
604c804901b1bb13fe10b3823cc4a639f8993363
[ "MIT" ]
48
2015-04-01T10:31:08.000Z
2022-02-08T11:18:18.000Z
hexa.core/src/main/java/fr/lteconsulting/hexa/client/form/marshalls/MarshallBoolean.java
xiayingfeng/hexa.tools
604c804901b1bb13fe10b3823cc4a639f8993363
[ "MIT" ]
11
2015-05-18T07:33:52.000Z
2017-03-22T17:05:37.000Z
hexa.core/src/main/java/fr/lteconsulting/hexa/client/form/marshalls/MarshallBoolean.java
xiayingfeng/hexa.tools
604c804901b1bb13fe10b3823cc4a639f8993363
[ "MIT" ]
15
2015-04-09T09:19:29.000Z
2022-02-08T02:08:19.000Z
21.793103
65
0.734177
999,697
package fr.lteconsulting.hexa.client.form.marshalls; import com.google.gwt.json.client.JSONNumber; import com.google.gwt.json.client.JSONValue; import fr.lteconsulting.hexa.client.form.FormManager.Marshall; public class MarshallBoolean implements Marshall<Boolean> { private static MarshallBoolean INST = null; public static MarshallBoolean get() { if( INST == null ) INST = new MarshallBoolean(); return INST; } public Boolean get( JSONValue value ) { return (int) value.isNumber().doubleValue() > 0 ? true : false; } public JSONValue get( Boolean object ) { return new JSONNumber( object ? 1 : 0 ); } }
923bb6a0b24325fe5dbfa2d14103aeee0633fbb6
13,798
java
Java
expManagerSQL/src/main/java/edu/gatech/hpan/expmanager/service/SimulationRunQueryService.java
laurathepluralized/multi-agent-data-analysis
7ac425baab72cbc162db78a5d9db775def752f32
[ "Apache-2.0" ]
3
2018-04-07T14:35:41.000Z
2018-04-25T19:00:35.000Z
expManagerSQL/src/main/java/edu/gatech/hpan/expmanager/service/SimulationRunQueryService.java
laurathepluralized/multi-agent-data-analysis
7ac425baab72cbc162db78a5d9db775def752f32
[ "Apache-2.0" ]
6
2018-04-23T00:13:26.000Z
2018-04-27T01:17:33.000Z
expManagerSQL/src/main/java/edu/gatech/hpan/expmanager/service/SimulationRunQueryService.java
laurathepluralized/multi-agent-data-analysis
7ac425baab72cbc162db78a5d9db775def752f32
[ "Apache-2.0" ]
3
2018-04-10T01:34:06.000Z
2018-08-04T11:52:09.000Z
62.434389
174
0.697275
999,698
package edu.gatech.hpan.expmanager.service; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.domain.Specifications; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import io.github.jhipster.service.QueryService; import edu.gatech.hpan.expmanager.domain.SimulationRun; import edu.gatech.hpan.expmanager.domain.*; // for static metamodels import edu.gatech.hpan.expmanager.repository.SimulationRunRepository; import edu.gatech.hpan.expmanager.service.dto.SimulationRunCriteria; /** * Service for executing complex queries for SimulationRun entities in the database. * The main input is a {@link SimulationRunCriteria} which get's converted to {@link Specifications}, * in a way that all the filters must apply. * It returns a {@link List} of {@link SimulationRun} or a {@link Page} of {@link SimulationRun} which fulfills the criteria. */ @Service @Transactional(readOnly = true) public class SimulationRunQueryService extends QueryService<SimulationRun> { private final Logger log = LoggerFactory.getLogger(SimulationRunQueryService.class); private final SimulationRunRepository simulationRunRepository; public SimulationRunQueryService(SimulationRunRepository simulationRunRepository) { this.simulationRunRepository = simulationRunRepository; } /** * Return a {@link List} of {@link SimulationRun} which matches the criteria from the database * @param criteria The object which holds all the filters, which the entities should match. * @return the matching entities. */ @Transactional(readOnly = true) public List<SimulationRun> findByCriteria(SimulationRunCriteria criteria) { log.debug("find by criteria : {}", criteria); final Specifications<SimulationRun> specification = createSpecification(criteria); return simulationRunRepository.findAll(specification); } /** * Return a {@link Page} of {@link SimulationRun} which matches the criteria from the database * @param criteria The object which holds all the filters, which the entities should match. * @param page The page, which should be returned. * @return the matching entities. */ @Transactional(readOnly = true) public Page<SimulationRun> findByCriteria(SimulationRunCriteria criteria, Pageable page) { log.debug("find by criteria : {}, page: {}", criteria, page); final Specifications<SimulationRun> specification = createSpecification(criteria); return simulationRunRepository.findAll(specification, page); } /** * Function to convert SimulationRunCriteria to a {@link Specifications} */ private Specifications<SimulationRun> createSpecification(SimulationRunCriteria criteria) { Specifications<SimulationRun> specification = Specifications.where(null); if (criteria != null) { if (criteria.getId() != null) { specification = specification.and(buildSpecification(criteria.getId(), SimulationRun_.id)); } if (criteria.getSimulationTrial() != null) { specification = specification.and(buildStringSpecification(criteria.getSimulationTrial(), SimulationRun_.simulationTrial)); } if (criteria.getIndex() != null) { specification = specification.and(buildRangeSpecification(criteria.getIndex(), SimulationRun_.index)); } if (criteria.getTeam_id() != null) { specification = specification.and(buildRangeSpecification(criteria.getTeam_id(), SimulationRun_.team_id)); } if (criteria.getScore() != null) { specification = specification.and(buildRangeSpecification(criteria.getScore(), SimulationRun_.score)); } if (criteria.getTeamCapture() != null) { specification = specification.and(buildRangeSpecification(criteria.getTeamCapture(), SimulationRun_.teamCapture)); } if (criteria.getNonTeamCapture() != null) { specification = specification.and(buildRangeSpecification(criteria.getNonTeamCapture(), SimulationRun_.nonTeamCapture)); } if (criteria.getJob_num() != null) { specification = specification.and(buildRangeSpecification(criteria.getJob_num(), SimulationRun_.job_num)); } if (criteria.getTask_num() != null) { specification = specification.and(buildRangeSpecification(criteria.getTask_num(), SimulationRun_.task_num)); } if (criteria.getResults_dir() != null) { specification = specification.and(buildStringSpecification(criteria.getResults_dir(), SimulationRun_.results_dir)); } if (criteria.getNum_rows() != null) { specification = specification.and(buildRangeSpecification(criteria.getNum_rows(), SimulationRun_.num_rows)); } if (criteria.getAlign_weight_t_1() != null) { specification = specification.and(buildRangeSpecification(criteria.getAlign_weight_t_1(), SimulationRun_.align_weight_t_1)); } if (criteria.getAvoid_nonteam_weight_t_1() != null) { specification = specification.and(buildRangeSpecification(criteria.getAvoid_nonteam_weight_t_1(), SimulationRun_.avoid_nonteam_weight_t_1)); } if (criteria.getAvoid_team_weight_t_1() != null) { specification = specification.and(buildRangeSpecification(criteria.getAvoid_team_weight_t_1(), SimulationRun_.avoid_team_weight_t_1)); } if (criteria.getCentroid_weight_t_1() != null) { specification = specification.and(buildRangeSpecification(criteria.getCentroid_weight_t_1(), SimulationRun_.centroid_weight_t_1)); } if (criteria.getComms_range_t_1() != null) { specification = specification.and(buildRangeSpecification(criteria.getComms_range_t_1(), SimulationRun_.comms_range_t_1)); } if (criteria.getFov_az_t_1() != null) { specification = specification.and(buildRangeSpecification(criteria.getFov_az_t_1(), SimulationRun_.fov_az_t_1)); } if (criteria.getFov_el_t_1() != null) { specification = specification.and(buildRangeSpecification(criteria.getFov_el_t_1(), SimulationRun_.fov_el_t_1)); } if (criteria.getGoal_weight_t_1() != null) { specification = specification.and(buildRangeSpecification(criteria.getGoal_weight_t_1(), SimulationRun_.goal_weight_t_1)); } if (criteria.getMax_pred_speed_t_1() != null) { specification = specification.and(buildRangeSpecification(criteria.getMax_pred_speed_t_1(), SimulationRun_.max_pred_speed_t_1)); } if (criteria.getMax_speed_t_1() != null) { specification = specification.and(buildRangeSpecification(criteria.getMax_speed_t_1(), SimulationRun_.max_speed_t_1)); } if (criteria.getSphere_of_influence_t_1() != null) { specification = specification.and(buildRangeSpecification(criteria.getSphere_of_influence_t_1(), SimulationRun_.sphere_of_influence_t_1)); } if (criteria.getMotion_model_t_1() != null) { specification = specification.and(buildStringSpecification(criteria.getMotion_model_t_1(), SimulationRun_.motion_model_t_1)); } if (criteria.getVel_max_t_1() != null) { specification = specification.and(buildRangeSpecification(criteria.getVel_max_t_1(), SimulationRun_.vel_max_t_1)); } if (criteria.getMotion_model_predator() != null) { specification = specification.and(buildStringSpecification(criteria.getMotion_model_predator(), SimulationRun_.motion_model_predator)); } if (criteria.getPitch_rate_max_predator() != null) { specification = specification.and(buildRangeSpecification(criteria.getPitch_rate_max_predator(), SimulationRun_.pitch_rate_max_predator)); } if (criteria.getTurn_rate_max_predator() != null) { specification = specification.and(buildRangeSpecification(criteria.getTurn_rate_max_predator(), SimulationRun_.turn_rate_max_predator)); } if (criteria.getVel_max_predator() != null) { specification = specification.and(buildRangeSpecification(criteria.getVel_max_predator(), SimulationRun_.vel_max_predator)); } if (criteria.getAlign_weight_t_2_predator() != null) { specification = specification.and(buildRangeSpecification(criteria.getAlign_weight_t_2_predator(), SimulationRun_.align_weight_t_2_predator)); } if (criteria.getAllow_prey_switching_t_2_predator() != null) { specification = specification.and(buildSpecification(criteria.getAllow_prey_switching_t_2_predator(), SimulationRun_.allow_prey_switching_t_2_predator)); } if (criteria.getAutonomy_t_2_predator() != null) { specification = specification.and(buildStringSpecification(criteria.getAutonomy_t_2_predator(), SimulationRun_.autonomy_t_2_predator)); } if (criteria.getAvoid_nonteam_weight_t_2_predator() != null) { specification = specification.and(buildRangeSpecification(criteria.getAvoid_nonteam_weight_t_2_predator(), SimulationRun_.avoid_nonteam_weight_t_2_predator)); } if (criteria.getAvoid_team_weight_t_2_predator() != null) { specification = specification.and(buildRangeSpecification(criteria.getAvoid_team_weight_t_2_predator(), SimulationRun_.avoid_team_weight_t_2_predator)); } if (criteria.getCapture_range_t_2_predator() != null) { specification = specification.and(buildRangeSpecification(criteria.getCapture_range_t_2_predator(), SimulationRun_.capture_range_t_2_predator)); } if (criteria.getCentroid_weight_t_2_predator() != null) { specification = specification.and(buildRangeSpecification(criteria.getCentroid_weight_t_2_predator(), SimulationRun_.centroid_weight_t_2_predator)); } if (criteria.getComms_range_t_2_predator() != null) { specification = specification.and(buildRangeSpecification(criteria.getComms_range_t_2_predator(), SimulationRun_.comms_range_t_2_predator)); } if (criteria.getMax_pred_speed_t_2_predator() != null) { specification = specification.and(buildRangeSpecification(criteria.getMax_pred_speed_t_2_predator(), SimulationRun_.max_pred_speed_t_2_predator)); } if (criteria.getMax_speed_t_2_predator() != null) { specification = specification.and(buildRangeSpecification(criteria.getMax_speed_t_2_predator(), SimulationRun_.max_speed_t_2_predator)); } if (criteria.getAlign_weight_t_3_predator() != null) { specification = specification.and(buildRangeSpecification(criteria.getAlign_weight_t_3_predator(), SimulationRun_.align_weight_t_3_predator)); } if (criteria.getAllow_prey_switching_t_3_predator() != null) { specification = specification.and(buildSpecification(criteria.getAllow_prey_switching_t_3_predator(), SimulationRun_.allow_prey_switching_t_3_predator)); } if (criteria.getAutonomy_t_3_predator() != null) { specification = specification.and(buildStringSpecification(criteria.getAutonomy_t_3_predator(), SimulationRun_.autonomy_t_3_predator)); } if (criteria.getAvoid_nonteam_weight_t_3_predator() != null) { specification = specification.and(buildRangeSpecification(criteria.getAvoid_nonteam_weight_t_3_predator(), SimulationRun_.avoid_nonteam_weight_t_3_predator)); } if (criteria.getAvoid_team_weight_t_3_predator() != null) { specification = specification.and(buildRangeSpecification(criteria.getAvoid_team_weight_t_3_predator(), SimulationRun_.avoid_team_weight_t_3_predator)); } if (criteria.getCapture_range_t_3_predator() != null) { specification = specification.and(buildRangeSpecification(criteria.getCapture_range_t_3_predator(), SimulationRun_.capture_range_t_3_predator)); } if (criteria.getCentroid_weight_t_3_predator() != null) { specification = specification.and(buildRangeSpecification(criteria.getCentroid_weight_t_3_predator(), SimulationRun_.centroid_weight_t_3_predator)); } if (criteria.getComms_range_t_3_predator() != null) { specification = specification.and(buildRangeSpecification(criteria.getComms_range_t_3_predator(), SimulationRun_.comms_range_t_3_predator)); } if (criteria.getMax_pred_speed_t_3_predator() != null) { specification = specification.and(buildRangeSpecification(criteria.getMax_pred_speed_t_3_predator(), SimulationRun_.max_pred_speed_t_3_predator)); } if (criteria.getMax_speed_t_3_predator() != null) { specification = specification.and(buildRangeSpecification(criteria.getMax_speed_t_3_predator(), SimulationRun_.max_speed_t_3_predator)); } } return specification; } }
923bb756e4cf56e7be36ba0fc0aea5fa792aed2e
811
java
Java
plugins/InspectionGadgets/test/com/siyeh/igtest/visibility/class_escapes_its_scope/ClassEscapesItsScope.java
teddywest32/intellij-community
e0268d7a1da1d318b441001448cdd3e8929b2f29
[ "Apache-2.0" ]
null
null
null
plugins/InspectionGadgets/test/com/siyeh/igtest/visibility/class_escapes_its_scope/ClassEscapesItsScope.java
teddywest32/intellij-community
e0268d7a1da1d318b441001448cdd3e8929b2f29
[ "Apache-2.0" ]
null
null
null
plugins/InspectionGadgets/test/com/siyeh/igtest/visibility/class_escapes_its_scope/ClassEscapesItsScope.java
teddywest32/intellij-community
e0268d7a1da1d318b441001448cdd3e8929b2f29
[ "Apache-2.0" ]
1
2020-11-27T10:36:50.000Z
2020-11-27T10:36:50.000Z
25.34375
113
0.657213
999,699
public class ClassEscapesItsScope<T> { public T t; public <warning descr="Class 'A' is made visible outside its defined scope">A</warning> giveMeA() { return new A(); } private class A {} } class BarInside { private static class Bar {} void foo() { class LocalClass implements F<String, Bar> { public Bar bar; public Bar apply(String s) { throw new UnsupportedOperationException(); } } } class InnerClass implements F<String, Bar> { public <warning descr="Class 'Bar' is made visible outside its defined scope">Bar</warning> bar; public <warning descr="Class 'Bar' is made visible outside its defined scope">Bar</warning> apply(String s) { throw new UnsupportedOperationException(); } } interface F<T, R> { R apply(T t); } }
923bb77c72fa18da306f09e0c800eb5aa355fed7
3,964
java
Java
src/main/java/com/twilio/rest/sync/v1/service/DocumentCreator.java
ethanwood17/twilio-java
6ddb62ff40b1d45263835316e9de7afd8d3c4cb2
[ "MIT" ]
null
null
null
src/main/java/com/twilio/rest/sync/v1/service/DocumentCreator.java
ethanwood17/twilio-java
6ddb62ff40b1d45263835316e9de7afd8d3c4cb2
[ "MIT" ]
11
2018-11-19T19:46:33.000Z
2019-01-25T23:06:10.000Z
src/main/java/com/twilio/rest/sync/v1/service/DocumentCreator.java
ethanwood17/twilio-java
6ddb62ff40b1d45263835316e9de7afd8d3c4cb2
[ "MIT" ]
null
null
null
29.58209
113
0.616801
999,700
/** * This code was generated by * \ / _ _ _| _ _ * | (_)\/(_)(_|\/| |(/_ v1.0.0 * / / */ package com.twilio.rest.sync.v1.service; import com.twilio.base.Creator; import com.twilio.converter.Converter; import com.twilio.exception.ApiConnectionException; import com.twilio.exception.ApiException; import com.twilio.exception.RestException; import com.twilio.http.HttpMethod; import com.twilio.http.Request; import com.twilio.http.Response; import com.twilio.http.TwilioRestClient; import com.twilio.rest.Domains; import java.util.Map; /** * PLEASE NOTE that this class contains beta products that are subject to * change. Use them with caution. */ public class DocumentCreator extends Creator<Document> { private final String pathServiceSid; private String uniqueName; private Map<String, Object> data; private Integer ttl; /** * Construct a new DocumentCreator. * * @param pathServiceSid The service_sid */ public DocumentCreator(final String pathServiceSid) { this.pathServiceSid = pathServiceSid; } /** * Human-readable name for this document. * * @param uniqueName Human-readable name for this document * @return this */ public DocumentCreator setUniqueName(final String uniqueName) { this.uniqueName = uniqueName; return this; } /** * JSON data to be stored in this document. * * @param data JSON data to be stored in this document * @return this */ public DocumentCreator setData(final Map<String, Object> data) { this.data = data; return this; } /** * Time-to-live of this Document in seconds, defaults to no expiration. In the * range [1, 31 536 000 (1 year)], or 0 for infinity.. * * @param ttl Time-to-live of this Document in seconds, defaults to no * expiration. * @return this */ public DocumentCreator setTtl(final Integer ttl) { this.ttl = ttl; return this; } /** * Make the request to the Twilio API to perform the create. * * @param client TwilioRestClient with which to make the request * @return Created Document */ @Override @SuppressWarnings("checkstyle:linelength") public Document create(final TwilioRestClient client) { Request request = new Request( HttpMethod.POST, Domains.SYNC.toString(), "/v1/Services/" + this.pathServiceSid + "/Documents", client.getRegion() ); addPostParams(request); Response response = client.request(request); if (response == null) { throw new ApiConnectionException("Document creation failed: Unable to connect to server"); } else if (!TwilioRestClient.SUCCESS.apply(response.getStatusCode())) { RestException restException = RestException.fromJson(response.getStream(), client.getObjectMapper()); if (restException == null) { throw new ApiException("Server Error, no content"); } throw new ApiException( restException.getMessage(), restException.getCode(), restException.getMoreInfo(), restException.getStatus(), null ); } return Document.fromJson(response.getStream(), client.getObjectMapper()); } /** * Add the requested post parameters to the Request. * * @param request Request to add post params to */ private void addPostParams(final Request request) { if (uniqueName != null) { request.addPostParam("UniqueName", uniqueName); } if (data != null) { request.addPostParam("Data", Converter.mapToJson(data)); } if (ttl != null) { request.addPostParam("Ttl", ttl.toString()); } } }
923bb7f5be9ae9f94aea16f744d31405f4d01f4e
4,313
java
Java
src/main/java/com/github/markusbernhardt/proxy/jna/win/WinHttp.java
7Signal/proxy-vole
c304fb5bfad4919f127e50aa64f4efacdb1ba341
[ "Apache-2.0" ]
137
2016-06-15T14:43:56.000Z
2022-02-16T13:22:10.000Z
src/main/java/com/github/markusbernhardt/proxy/jna/win/WinHttp.java
7Signal/proxy-vole
c304fb5bfad4919f127e50aa64f4efacdb1ba341
[ "Apache-2.0" ]
69
2016-07-13T06:14:48.000Z
2022-03-22T20:41:41.000Z
src/main/java/com/github/markusbernhardt/proxy/jna/win/WinHttp.java
7Signal/proxy-vole
c304fb5bfad4919f127e50aa64f4efacdb1ba341
[ "Apache-2.0" ]
68
2016-08-17T21:08:30.000Z
2021-11-22T04:36:34.000Z
37.833333
106
0.710642
999,701
package com.github.markusbernhardt.proxy.jna.win; import com.sun.jna.LastErrorException; import com.sun.jna.Native; import com.sun.jna.platform.win32.WinDef; import com.sun.jna.win32.StdCallLibrary; import com.sun.jna.win32.W32APIOptions; /** * WinHttp.dll Interface. * * @author Markus Bernhardt, Copyright 2016 */ public interface WinHttp extends StdCallLibrary { WinHttp INSTANCE = (WinHttp) Native.loadLibrary("winhttp", WinHttp.class, W32APIOptions.UNICODE_OPTIONS); /** * Use DHCP to locate the proxy auto-configuration file. */ int WINHTTP_AUTO_DETECT_TYPE_DHCP = 0x00000001; /** * Use DNS to attempt to locate the proxy auto-configuration file at a * well-known location on the domain of the local computer. */ int WINHTTP_AUTO_DETECT_TYPE_DNS_A = 0x00000002; /** * Resolves all host names directly without a proxy. */ int WINHTTP_ACCESS_TYPE_DEFAULT_PROXY = 0; /** * Returned if WinHTTP was unable to discover the URL of the * Proxy Auto-Configuration (PAC) file using the WPAD method. */ int ERROR_WINHTTP_AUTODETECTION_FAILED = 12180; /** * Retrieves the static proxy or direct configuration from the registry. * WINHTTP_ACCESS_TYPE_DEFAULT_PROXY does not inherit browser proxy * settings. WinHTTP does not share any proxy settings with Internet * Explorer. * <p> * The WinHTTP proxy configuration is set by one of these mechanisms. * <ul> * <li>The proxycfg.exe utility on Windows XP and Windows Server 2003 or * earlier.</li> * <li>The netsh.exe utility on Windows Vista and Windows Server 2008 or * later.</li> * <li>WinHttpSetDefaultProxyConfiguration on all platforms.</li> * </ul> */ int WINHTTP_ACCESS_TYPE_NO_PROXY = 1; /** * Passes requests to the proxy unless a proxy bypass list is supplied and * the name to be resolved bypasses the proxy. In this case, this function * uses WINHTTP_ACCESS_TYPE_NAMED_PROXY. */ int WINHTTP_ACCESS_TYPE_NAMED_PROXY = 3; /** * The WinHttpDetectAutoProxyConfigUrl function finds the URL for the Proxy * Auto-Configuration (PAC) file. This function reports the URL of the PAC * file, but it does not download the file. * * @param dwAutoDetectFlags * A data type that specifies what protocols to use to locate the * PAC file. If both the DHCP and DNS auto detect flags are set, * DHCP is used first; if no PAC URL is discovered using DHCP, * then DNS is used. Set {@code WINHTTP_AUTO_DETECT_TYPE_DHCP}, * {@code WINHTTP_AUTO_DETECT_TYPE_DNS_A} or both. * @param ppwszAutoConfigUrl * A data type that returns a pointer to a null-terminated * Unicode string that contains the configuration URL that * receives the proxy data. You must free the string pointed to * by ppwszAutoConfigUrl using the GlobalFree function. * * @return {@code true} if successful; otherwise, {@code false}. * @see WinHttpHelpers#detectAutoProxyConfigUrl */ boolean WinHttpDetectAutoProxyConfigUrl( WinDef.DWORD dwAutoDetectFlags, WTypes2.LPWSTRByReference ppwszAutoConfigUrl) throws LastErrorException; /** * The WinHttpGetDefaultProxyConfiguration function retrieves the default * WinHTTP proxy configuration from the registry. * * @param pProxyInfo * A pointer to a variable of type WINHTTP_PROXY_INFO that * receives the default proxy configuration. * @return {@code true} if successful; otherwise, {@code false}. */ boolean WinHttpGetDefaultProxyConfiguration(WinHttpProxyInfo pProxyInfo); /** * The WinHttpGetIEProxyConfigForCurrentUser function retrieves the Internet * Explorer proxy configuration for the current user. * * @param pProxyConfig * A pointer, on input, to a WINHTTP_CURRENT_USER_IE_PROXY_CONFIG * structure. On output, the structure contains the Internet * Explorer proxy settings for the current active network * connection (for example, LAN, dial-up, or VPN connection). * @return {@code true} if successful; otherwise, {@code false}. */ boolean WinHttpGetIEProxyConfigForCurrentUser(WinHttpCurrentUserIEProxyConfig pProxyConfig); }
923bba76b9fcbdcc3997d5f129310fe861e48c63
4,404
java
Java
src/test/java/uk/gov/digital/ho/hocs/workflow/processes/IEDET_TRIAGE.java
UKHomeOffice/hocs-workflow
76ef4a7b2d942e2298c247591d8fc4ae49c38229
[ "MIT" ]
6
2019-08-20T15:19:20.000Z
2021-12-22T06:45:28.000Z
src/test/java/uk/gov/digital/ho/hocs/workflow/processes/IEDET_TRIAGE.java
UKHomeOffice/hocs-workflow
76ef4a7b2d942e2298c247591d8fc4ae49c38229
[ "MIT" ]
61
2018-07-09T17:14:22.000Z
2022-03-21T15:55:58.000Z
src/test/java/uk/gov/digital/ho/hocs/workflow/processes/IEDET_TRIAGE.java
UKHomeOffice/hocs-workflow
76ef4a7b2d942e2298c247591d8fc4ae49c38229
[ "MIT" ]
3
2019-07-04T12:05:42.000Z
2021-04-11T09:00:46.000Z
44.04
139
0.72911
999,702
package uk.gov.digital.ho.hocs.workflow.processes; import org.camunda.bpm.engine.test.Deployment; import org.camunda.bpm.engine.test.ProcessEngineRule; import org.camunda.bpm.engine.test.mock.Mocks; import org.camunda.bpm.extension.process_test_coverage.junit.rules.TestCoverageProcessEngineRule; import org.camunda.bpm.extension.process_test_coverage.junit.rules.TestCoverageProcessEngineRuleBuilder; import org.camunda.bpm.scenario.ProcessScenario; import org.camunda.bpm.scenario.Scenario; import org.junit.Before; import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import uk.gov.digital.ho.hocs.workflow.BpmnService; import static org.camunda.bpm.engine.test.assertions.ProcessEngineTests.withVariables; import static org.mockito.Mockito.*; @RunWith(MockitoJUnitRunner.class) @Deployment(resources = "processes/IEDET_TRIAGE.bpmn") public class IEDET_TRIAGE { @Rule @ClassRule public static TestCoverageProcessEngineRule rule = TestCoverageProcessEngineRuleBuilder.create().assertClassCoverageAtLeast(1).build(); @Rule public ProcessEngineRule processEngineRule = new ProcessEngineRule(); @Mock private BpmnService bpmnService; @Mock private ProcessScenario compServiceTriageProcess; @Before public void setup() { Mocks.register("bpmnService", bpmnService); } @Test public void testTriageSendToCch(){ when(compServiceTriageProcess.waitsAtUserTask("Validate_Accept")) .thenReturn(task -> task.complete(withVariables("valid", true, "TriageAccept", "NoCch"))); Scenario.run(compServiceTriageProcess).startByKey("IEDET_TRIAGE").execute(); verify(compServiceTriageProcess).hasCompleted("Service_CreateCase"); verify(compServiceTriageProcess).hasCompleted("EndEvent_IEDET_TRIAGE"); } @Test public void testTriageNoConsideration(){ when(compServiceTriageProcess.waitsAtUserTask("Validate_Accept")) .thenReturn(task -> task.complete(withVariables("valid", true, "TriageAccept", "NoFurtherConsideration"))); Scenario.run(compServiceTriageProcess).startByKey("IEDET_TRIAGE").execute(); verify(compServiceTriageProcess).hasCompleted("EndEvent_IEDET_TRIAGE"); } @Test public void testTriageResultCompleteYesThirdParty(){ when(compServiceTriageProcess.waitsAtUserTask("Validate_Accept")) .thenReturn(task -> task.complete(withVariables("valid", false, "TriageAccept", "false"))) .thenReturn(task -> task.complete(withVariables("valid", true, "TriageAccept", "YesThirdParty"))); when(compServiceTriageProcess.waitsAtUserTask("Validate_BusArea")) .thenReturn(task -> task.complete(withVariables("valid", false, "DIRECTION", "BACKWARD"))) .thenReturn(task -> task.complete(withVariables("valid", false, "DIRECTION", "FORWARD"))) .thenReturn(task -> task.complete(withVariables("valid", true, "DIRECTION", "FORWARD"))); Scenario.run(compServiceTriageProcess).startByKey("IEDET_TRIAGE").execute(); verify(compServiceTriageProcess, times(3)).hasCompleted("Screen_BusArea"); verify(compServiceTriageProcess).hasCompleted("EndEvent_IEDET_TRIAGE"); } @Test public void testTriageResultCompleteYesIedetCompliance(){ when(compServiceTriageProcess.waitsAtUserTask("Validate_Accept")) .thenReturn(task -> task.complete(withVariables("valid", false, "TriageAccept", "false"))) .thenReturn(task -> task.complete(withVariables("valid", true, "TriageAccept", "YesIEDETCompliance"))); when(compServiceTriageProcess.waitsAtUserTask("Validate_BusArea")) .thenReturn(task -> task.complete(withVariables("valid", false, "DIRECTION", "BACKWARD"))) .thenReturn(task -> task.complete(withVariables("valid", false, "DIRECTION", "FORWARD"))) .thenReturn(task -> task.complete(withVariables("valid", true, "DIRECTION", "FORWARD"))); Scenario.run(compServiceTriageProcess).startByKey("IEDET_TRIAGE").execute(); verify(compServiceTriageProcess, times(3)).hasCompleted("Screen_BusArea"); verify(compServiceTriageProcess).hasCompleted("EndEvent_IEDET_TRIAGE"); } }
923bbad809c14507cd4244926bbae3b0c79982b2
2,523
java
Java
src/main/java/eu/midnightdust/visualoverhaul/mixin/MixinAbstractFurnaceBlockEntity.java
SuperNoobYT/VisualOverhaul
38a406c444abf54f7887e3a4d72c7f304f43bbe7
[ "MIT" ]
null
null
null
src/main/java/eu/midnightdust/visualoverhaul/mixin/MixinAbstractFurnaceBlockEntity.java
SuperNoobYT/VisualOverhaul
38a406c444abf54f7887e3a4d72c7f304f43bbe7
[ "MIT" ]
null
null
null
src/main/java/eu/midnightdust/visualoverhaul/mixin/MixinAbstractFurnaceBlockEntity.java
SuperNoobYT/VisualOverhaul
38a406c444abf54f7887e3a4d72c7f304f43bbe7
[ "MIT" ]
null
null
null
45.053571
159
0.74237
999,703
package eu.midnightdust.visualoverhaul.mixin; import eu.midnightdust.visualoverhaul.VisualOverhaul; import io.netty.buffer.Unpooled; import net.fabricmc.fabric.api.networking.v1.PlayerLookup; import net.fabricmc.fabric.impl.networking.ServerSidePacketRegistryImpl; import net.minecraft.block.BlockState; import net.minecraft.block.entity.*; import net.minecraft.item.ItemStack; import net.minecraft.network.PacketByteBuf; import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.callback.CallbackInfo; import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable; import java.util.stream.Stream; @Mixin(AbstractFurnaceBlockEntity.class) public abstract class MixinAbstractFurnaceBlockEntity extends LockableContainerBlockEntity { private static boolean invUpdate = true; private static int playerUpdate = -1; protected MixinAbstractFurnaceBlockEntity(BlockEntityType<?> blockEntityType, BlockPos blockPos, BlockState blockState) { super(blockEntityType, blockPos, blockState); } @Inject(at = @At("TAIL"), method = "tick") private static void tick(World world, BlockPos pos, BlockState state, AbstractFurnaceBlockEntity blockEntity, CallbackInfo ci) { if (world.getBlockState(pos).hasBlockEntity()) { if (!world.isClient && (invUpdate || world.getPlayers().size() == playerUpdate)) { Stream<ServerPlayerEntity> watchingPlayers = PlayerLookup.tracking(blockEntity).stream(); PacketByteBuf passedData = new PacketByteBuf(Unpooled.buffer()); passedData.writeBlockPos(pos); passedData.writeItemStack(blockEntity.getStack(0)); passedData.writeItemStack(blockEntity.getStack(1)); passedData.writeItemStack(blockEntity.getStack(2)); watchingPlayers.forEach(player -> ServerSidePacketRegistryImpl.INSTANCE.sendToPlayer(player, VisualOverhaul.UPDATE_FURNACE_ITEMS, passedData)); invUpdate = false; } playerUpdate = world.getPlayers().size(); } } @Inject(at = @At("RETURN"), method = "getStack", cancellable = true) public void getStack(int slot, CallbackInfoReturnable<ItemStack> cir) { invUpdate = true; } }
923bbdcaf6cbb9796122980a257e36fe854ee174
656
java
Java
springboot-h2/src/main/java/cn/alexpy/service/IUserService.java
alexpycn/spring-boot-example
209d602c7736a8d71458af9a7f174e6dd2efae15
[ "MIT" ]
1
2020-07-17T12:33:29.000Z
2020-07-17T12:33:29.000Z
springboot-h2/src/main/java/cn/alexpy/service/IUserService.java
alexpycn/spring-boot-example
209d602c7736a8d71458af9a7f174e6dd2efae15
[ "MIT" ]
null
null
null
springboot-h2/src/main/java/cn/alexpy/service/IUserService.java
alexpycn/spring-boot-example
209d602c7736a8d71458af9a7f174e6dd2efae15
[ "MIT" ]
null
null
null
11.714286
33
0.439024
999,704
package cn.alexpy.service; import cn.alexpy.entity.User; import java.util.List; public interface IUserService { /** * 初始化 */ void init(); /** * 添加用户 * @param name */ void add(String name); /** * 按用户名精确查找 * * @param name * @return */ User find(String name); /** * 按用户名模糊查找 * * @param name * @return */ List<User> like(String name); /** * 查找全部 * * @return */ List<User> findAll(); /** * 删除 * * @param id */ void delete(Integer id); /** * 删除全部 */ void deleteAll(); }
923bbdd1ee05f09acdcf00ce875781becfcc4a44
37,893
java
Java
src/test/java/org/lockss/util/PluginPackager.java
lockss/lockss-core
defe3cb2319eb3dd00f89f2d85e7b9a322dc5632
[ "BSD-3-Clause" ]
2
2019-05-31T01:54:41.000Z
2020-11-26T16:44:35.000Z
src/test/java/org/lockss/util/PluginPackager.java
lockss/lockss-core
defe3cb2319eb3dd00f89f2d85e7b9a322dc5632
[ "BSD-3-Clause" ]
4
2021-06-28T08:24:01.000Z
2022-02-16T01:05:09.000Z
src/test/java/org/lockss/util/PluginPackager.java
lockss/lockss-core
defe3cb2319eb3dd00f89f2d85e7b9a322dc5632
[ "BSD-3-Clause" ]
null
null
null
29.93128
104
0.641279
999,705
/* Copyright (c) 2000-2018 Board of Trustees of Leland Stanford Jr. University, all rights reserved. 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 STANFORD UNIVERSITY 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. Except as contained in this notice, the name of Stanford University shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from Stanford University. */ package org.lockss.util; import java.io.*; import java.net.*; import java.util.*; import java.util.jar.*; import java.util.regex.*; import java.util.stream.*; import java.nio.file.*; import java.nio.file.attribute.*; import org.apache.commons.collections.*; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.BooleanUtils; import org.apache.commons.lang3.tuple.*; import org.apache.commons.lang3.builder.HashCodeBuilder; import static java.nio.file.FileVisitOption.FOLLOW_LINKS; import static java.nio.file.FileVisitResult.CONTINUE; import org.lockss.log.*; import org.lockss.config.*; import org.lockss.util.*; import org.lockss.util.io.*; import org.lockss.util.lang.*; import org.lockss.plugin.*; import org.lockss.plugin.definable.*; import org.lockss.test.*; /** * Create and optionally sign plugin jar(s). * * Includes all parent plugins and all files in plugin and parent plugin * dirs. Plugins are loaded from a user-specified classpath, if supplied, * or the current classpath. * * This is a driver class which can be invoked by main() or * programmatically to build one or more plugin jars. */ // Plugin files and dirs are represented by URLs rather than Files in order // to support jars. (E.g., a 3rd-party plugin may extend a LOCKSS base // plugin, which may be distributed in a jar so as not to require // installing a source distribution.) But jar:file: URLs aren't fully // supported yet. public class PluginPackager { static L4JLogger log = L4JLogger.getLogger(); static final String MANIFEST = JarFile.MANIFEST_NAME; static final String MANIFEST_DIR = "META-INF/"; static final String VERSION = "1.0"; // Match the signature file in a signed jar static final Pattern SIG_FILE_PAT = Pattern.compile("META-INF/[^/.]+\\.SF$", Pattern.CASE_INSENSITIVE); // Match jar entries that should *not* be exploded into plugin jar static final Pattern EXCLUDE_FROM_EXPLODE_PAT = Pattern.compile("^META-INF/\\w+\\.(mf|sf|dsa|rsa)$?", Pattern.CASE_INSENSITIVE); // Match keystore resource spec static final Pattern RESOURCE_KEYSTORE_PAT = Pattern.compile("resource:(.*)", Pattern.CASE_INSENSITIVE); MockLockssDaemon daemon; PluginManager pluginMgr; File tmpdir; ClassLoader gLoader = null; boolean forceRebuild = false; List<Result> results = new ArrayList<>(); boolean nofail = false; boolean includeLibDir = true; boolean explodeLib = false; List<String> excluded = new ArrayList<>(); List<PlugSpec> argSpecs = new ArrayList<>(); File argPlugDir; // root of plugins class tree File argOutputDir; // dir (flat) to write plugin jars List<Pattern> argExcludePats = new ArrayList<>(); List<String> argClasspath = null; boolean argForceRebuild = false; String argKeystore = null; String argKeyPass = "password"; String argStorePass = "password"; String argStoreType = null; String argAlias = null; public PluginPackager() { } /** Compatibility with maven plugin. Remove. */ public PluginPackager(String outputJar, List<String> plugins) { addSpec(new PlugSpec().addPlugs(plugins).setJar(outputJar)); } /** Set the directory to which plugin jars will be written. Used with * {@link #setPluginDir(File)} */ public PluginPackager setOutputDir(File argOutputDir) { this.argOutputDir = argOutputDir; return this; } /** Set the root of the directory tree to search for plugins and compiled * classes. Used with {@link #setOutputDir(File)} */ public PluginPackager setPluginDir(File argPlugDir) { this.argPlugDir = argPlugDir; return this; } public File getPlugDir() { return argPlugDir; } /** Add to list of plugin jars to be built */ public PluginPackager addSpec(PlugSpec spec) { argSpecs.add(spec); return this; } /** Set the classpath to search for and load plugins from. Will be * prepended to classpath used to invoke PluginPackager */ public PluginPackager setClassPath(List<String> cp) { argClasspath = cp; return this; } /** Set the classpath to search for and load plugins from. Will be * prepended to classpath used to invoke PluginPackager */ public PluginPackager setClassPath(String cpstr) { setClassPath(StringUtil.breakAt(cpstr, ":")); return this; } /** Force jars to be rebuilt even if they exist and are up-to-date */ public PluginPackager addExclusion(String patstr) { Pattern pat = Pattern.compile(patstr); argExcludePats.add(pat); return this; } /** Force jars to be rebuilt even if they exist and are up-to-date */ public PluginPackager setForceRebuild(boolean force) { argForceRebuild = force; return this; } public PluginPackager setNoFail(boolean val) { this.nofail = val; return this; } public boolean isNoFail() { return nofail; } public PluginPackager setIncludeLibDir(boolean val) { this.includeLibDir = val; return this; } public boolean isIncludeLibDir() { return includeLibDir; } public PluginPackager setExplodeLib(boolean val) { this.explodeLib = val; return this; } public boolean isExplodeLib() { return explodeLib; } /** Set the pat of the plugin signing keystore. Plugins will be signed * if this is provided */ public PluginPackager setKeystore(String ks) { argKeystore = ks; return this; } /** Set the keystore alias. Must be supplied if keystore is. */ public PluginPackager setAlias(String alias) { argAlias = alias; return this; } /** Set the password to use with the signing key. Defaults to * "password". */ public PluginPackager setKeyPass(String val) { argKeyPass = val; return this; } /** Set the password to use to unlock the keystore. Defaults to * "password". */ public PluginPackager setStorePass(String val) { argStorePass = val; return this; } /** Set the keystore type. */ public PluginPackager setStoreType(String val) { argStoreType = val; return this; } public List<Result> getResults() { return results; } public List<String> getExcluded() { return excluded; } /** Check the args and build all the plugins specified */ public void build() throws Exception { List<PlugSpec> specs = argSpecs; if (specs.isEmpty()) { // No explicit specs, look for plugins dir and output dir if (argPlugDir != null && argOutputDir != null) { FileUtil.ensureDirExists(argOutputDir); // If no classpath specified, use plugin class dir if (argClasspath == null || argClasspath.isEmpty()) { String cp = argPlugDir.toString(); argClasspath = ListUtil.list(cp.endsWith("/") ? cp : cp + "/"); } // Find plugins in tree specs = findSpecsInDir(argPlugDir, argOutputDir); } else if (argPlugDir == null) { throw new IllegalArgumentException("No plugins or plugins-dir supplied"); } else if (argOutputDir == null) { throw new IllegalArgumentException("Plugins-dir but no output-dir supplied"); } } else if (argPlugDir != null) { throw new IllegalArgumentException("Can't specify both a list of plugins and a plugins-dir"); } if (argKeystore != null && argAlias == null) { throw new IllegalArgumentException("keystore but no alias supplied"); } if (argClasspath != null && !argClasspath.isEmpty()) { log.debug("Prepending classpath: {}", argClasspath); } try { initPluginManager(); initKeystore(); for (PlugSpec ps : specs) { JarBuilder it = new JarBuilder(ps); try { it.setClassLoader(getLoader()); it.makeJar(); results.add(new Result(it) .setIsSigned(it.didSign)); } catch (Exception e) { results.add(new Result(it) .setException(e)); } } } finally { if (tmpdir != null) { FileUtil.delTree(tmpdir); } } } // Daemon uses new ClassLoader for each plugin but I don't think there's // any reason that would matter for this use. This is here to make it // easy to switch if necessary. Currently set to use same loader for all // plugins. boolean REUSE_LOADER = true; /** Return ClassLoader based on the supplied classpath. If REUSE_LOADER * is true, the same instance will be returned on each call, else a new * instance each time */ ClassLoader getLoader() { if (argClasspath == null || argClasspath.isEmpty()) { return null; } if (gLoader != null) { return gLoader; } ClassLoader res = new LoadablePluginClassLoader(ClassPathUtil.toUrlArray(argClasspath)); // new URLClassLoader(ClassPathUtil.toUrlArray(argClasspath)); if (REUSE_LOADER) { gLoader = res; } return res; } static String[] INFO_LOGS = {"PluginPackager"}; // Necessary setup in order to invoke PluginManager to load plugins private void initPluginManager() throws Exception { ConfigManager.makeConfigManager().setNoNag(); tmpdir = FileUtil.createTempDir("pluginpkg", ""); Properties p = new Properties(); // p.setProperty(ConfigManager.PARAM_ENABLE_JMS_RECEIVE, "false"); p.setProperty(ConfigManager.PARAM_PLATFORM_DISK_SPACE_LIST, tmpdir.getAbsolutePath() + File.separator); if ("warning".equalsIgnoreCase(System.getProperty(LockssLogger.SYSPROP_DEFAULT_LOCKSS_LOG_LEVEL))) { for (String s : INFO_LOGS) { p.setProperty("org.lockss.log." + s + ".level", "info"); } } // Logger.resetLogs(); ConfigurationUtil.addFromProps(p); daemon = new MyMockLockssDaemon(); pluginMgr = new PluginManager(); daemon.setPluginManager(pluginMgr); pluginMgr.initService(daemon); pluginMgr.startService(); } /** If keystore is resource:<path>, copy resource to temp file, use that * instead */ private void initKeystore() throws IOException { if (StringUtil.isNullString(argKeystore)) { return; } Matcher mat = RESOURCE_KEYSTORE_PAT.matcher(argKeystore); if (mat.matches()) { String resname = mat.group(1); final File tempfile = FileUtil.createTempFile("temp-signing", ".keystore"); tempfile.deleteOnExit(); try (final InputStream ins = this.getClass().getClassLoader().getResourceAsStream(resname); final OutputStream outs = new BufferedOutputStream(new FileOutputStream(tempfile))) { IOUtils.copy(ins, outs); } argKeystore = tempfile.toString(); } } /** Builds one plugin jar */ class JarBuilder { PlugSpec spec; // spec for what should go in jar List<PData> pds = new ArrayList<>(); // PData for each plugin in spec Collection<FileInfo> allFiles; // all files to be written to jar JarOutputStream jarOut; ClassLoader oneLoader; Exception e = null; // Exception thrown during processing boolean notModified = false; boolean didSign; JarBuilder(PlugSpec ps) { this.spec = ps; } JarBuilder setClassLoader(ClassLoader loader) { this.oneLoader = loader; return this; } PlugSpec getPlugSpec() { return spec; } boolean isNotModified() { return notModified; } public void makeJar() throws Exception { try { findPlugins(); // check file dates against jar date, exit if jar is up-to-date if (isJarUpToDate() && (argKeystore == null || isJarSigned())) { notModified = true; return; } initJar(); writeManifest(); writeFiles(); jarOut.close(); if (argKeystore != null) { signJar(); log.info("Wrote and signed {}", spec.getJar()); } else { log.info("Wrote {}", spec.getJar()); } } catch (Exception e) { log.error("Failed", e); throw e; } finally { FileUtil.delTree(tmpdir); } } String SIGN_CMD = "jarsigner -keystore %s -keypass %s -storepass %s%s %s %s"; public void signJar() throws IOException { String stype = argStoreType != null ? (" -storetype " + argStoreType) : ""; String cmd = String.format(SIGN_CMD, argKeystore, argKeyPass, argStorePass, stype, spec.getJar(), argAlias); log.debug("cmd: " + cmd); String s; Reader rdr = null; try { Process p = Runtime.getRuntime().exec(cmd); rdr = new InputStreamReader(new BufferedInputStream(p.getInputStream()), EncodingUtil.DEFAULT_ENCODING); s = IOUtils.toString(rdr); int exit = p.waitFor(); rdr.close(); if (exit == 0) { didSign = true; log.debug(s); } else { throw new RuntimeException("jarsigner failed: " + s); } } catch (InterruptedException e) { log.error("jarsigner aborted", e); throw new RuntimeException("jarsigner aborted", e); } finally { IOUtil.safeClose(rdr); } } // load all the specified plugins, find the URL of each plugin and its // parents void findPlugins() throws Exception { for (String pluginId : spec.getPluginIds()) { log.debug("Loading plugin: " + pluginId); // Plugin plug = PluginTestUtil.findPlugin(pluginId, oneLoader); Plugin plug = loadPlugin(pluginId, oneLoader); log.debug2("Loaded plugin: " + plug.getPluginId()); List<FileInfo> fis = getOnePluginInfos(packageOf(pluginId), plug); log.debug2("plugin {} URLs: {}", pluginId, fis); pds.add(new PData(pluginId, fis)); } } Plugin loadPlugin(String pluginId, ClassLoader loader) throws Exception { try { String key = pluginMgr.pluginKeyFromName(pluginId); PluginManager.PluginInfo pinfo = pluginMgr.loadPlugin(key, loader); return pinfo.getPlugin(); } catch (Exception e) { throw e; } } // Retrieve the FileInfo(s) for the plugin and its parents List<FileInfo> getOnePluginInfos(String pkg, Plugin plug) { ArrayList<FileInfo> res = new ArrayList<>(); if (plug instanceof DefinablePlugin) { DefinablePlugin dplug = (DefinablePlugin)plug; for (Pair<String,URL> pair : dplug.getIdsUrls()) { res.add(FileInfo.forFile(pair.getRight(), packageOf(pair.getLeft()))); } } else { res.add(FileInfo.forFile(findJavaPluginUrl(plug), pkg)); } return res; } URL findJavaPluginUrl(Plugin plug) { ClassLoader loader = plug.getClass().getClassLoader(); String classFileName = plug.getClass().getName().replace('.', '/'); return loader.getResource(classFileName + ".class"); } void initJar() throws IOException { OutputStream out = new BufferedOutputStream(new FileOutputStream(spec.getJarFile())); jarOut = new JarOutputStream(out); } void writeManifest() throws IOException { Manifest manifest = new Manifest(); Attributes mainAttr = manifest.getMainAttributes(); mainAttr.put(Attributes.Name.MANIFEST_VERSION, VERSION); String javaVendor = System.getProperty("java.vendor"); String jdkVersion = System.getProperty("java.version"); mainAttr.put(new Attributes.Name("Created-By"), jdkVersion + " (" + javaVendor + ")"); // Add entry that marks a LOCKSS plugin file for (PData pd : pds) { String secName = pd.getPluginPath(); manifest.getEntries().put(secName, new Attributes()); Attributes plugAttr = manifest.getAttributes(secName); plugAttr.put(new Attributes.Name("Lockss-Plugin"), "true"); } JarEntry e = new JarEntry(MANIFEST_DIR); long now = System.currentTimeMillis(); e.setTime(now); // e.setSize(0); // e.setCrc(0); jarOut.putNextEntry(e); e = new JarEntry(MANIFEST); e.setTime(now); jarOut.putNextEntry(e); manifest.write(jarOut); jarOut.closeEntry(); } // find the entire set of files to be written to the jar Collection<FileInfo> findAllFiles() throws Exception { if (allFiles == null) { Set<FileInfo> res = new LinkedHashSet<>(); for (PData pd : pds) { for (FileInfo fi : pd.listFiles()) { res.add(fi); } if (isIncludeLibDir()) { for (FileInfo fi : pd.listLibFiles()) { res.add(fi); } } } allFiles = res; } return allFiles; } // return true if the jar exists and is as recent as the most input // file boolean isJarUpToDate() throws Exception { if (argForceRebuild || !spec.getJarFile().exists()) { return false; } long latest = findAllFiles().stream() .map(FileInfo::getUrl) .map(u -> urlToFile(u)) .map(File::lastModified) .mapToLong(v -> v) .max().orElseThrow(NoSuchElementException::new); return latest <= spec.getJarFile().lastModified(); } /** Return true if the jar exists and is signed. Currently just looks * for a file named META-INF/*.SF */ boolean isJarSigned() throws Exception { if (!spec.getJarFile().exists()) { return false; } try (JarFile jf = new JarFile(spec.getJarFile())) { for (Enumeration<JarEntry> en = jf.entries(); en.hasMoreElements(); ) { JarEntry ent = en.nextElement(); if (ent.isDirectory()) { continue; } Matcher mat = SIG_FILE_PAT.matcher(ent.getName()); if (mat.matches()) { return true; } } } return false; } // write all files in plugin dir and parent plugin dirs void writeFiles() throws Exception { Set<URL> urlsAdded = new HashSet<>(); Set<String> dirsAdded = new HashSet<>(); for (FileInfo fi : findAllFiles()) { URL url = fi.getUrl(); if (urlsAdded.add(url)) { // xxx check for not jar:file: if (url.getProtocol().equalsIgnoreCase("file")) { String path = url.getPath(); if (path.equals(spec.getJarFile().toString())) { log.debug2("Skipping jar being built: {}", path); continue; } File f = new File(path); if (f.isDirectory()) continue; // ignore directories String relPath = pathOfPkg(fi.getPkg()); String dir = f.getParent(); if (dirsAdded.add(dir)) { log.debug2("Adding dir {}", relPath); String entPath = relPath + "/"; JarEntry entry = new JarEntry(entPath); entry.setTime(f.lastModified()); jarOut.putNextEntry(entry); jarOut.closeEntry(); } String entPath = relPath + "/" + f.getName(); if (fi.isJar() && isExplodeLib()) { explodeJar(url); } else { log.debug2("Adding file {}", entPath); JarEntry entry = new JarEntry(entPath); entry.setTime(f.lastModified()); jarOut.putNextEntry(entry); try (InputStream in = new BufferedInputStream(new FileInputStream(path))) { StreamUtil.copy(in, jarOut); } jarOut.closeEntry(); } } else { throw new UnsupportedOperationException("Can't handle jar: URLs yet: " + url); } } } } void explodeJar(URL jarUrl) throws IOException { try (JarInputStream jis = new JarInputStream(jarUrl.openStream())) { // Iterate across all the JAR entries JarEntry ent; while ((ent = jis.getNextJarEntry()) != null) { Matcher mat = EXCLUDE_FROM_EXPLODE_PAT.matcher(ent.getName()); if (!mat.matches()) { JarEntry destEnt = new JarEntry(ent.getName()); destEnt.setTime(ent.getTime()); try { jarOut.putNextEntry(destEnt); } catch (java.util.zip.ZipException e) { // Duplicate dir entries are expected. Other duplicate // entries can't be assumed to be benign. if (ent.isDirectory() // && StringUtil.indexOfIgnoreCase(e.toString(), "duplicate") ) { log.debug2("Not exploding duplicate dir entry: {}", ent.getName()); } else { throw e; } } StreamUtil.copy(jis, jarOut); jarOut.closeEntry(); } } } } } /** Result status of one JarBuilder operation, for reporting */ public class Result { JarBuilder bldr; Exception e; boolean isSigned; Result(JarBuilder bldr) { this.bldr = bldr; } Result setException(Exception e) { this.e = e; return this; } Result setIsSigned(boolean isSigned) { this.isSigned = isSigned; return this; } public PlugSpec getPlugSpec() { return bldr.getPlugSpec(); } public Exception getException() { return e; } public boolean isError() { return e != null; } public boolean isNotModified() { return bldr.isNotModified(); } public boolean isSigned() { return isSigned; } } /** Info about a file to be packaged: a source URL and an optional * package/dir in which it should be placed in the jar. May be either a * file and package, or a jar that should be copied into lib/ or exploded * into the proper package dirs. */ static class FileInfo { String pkg; URL url; boolean isJar; FileInfo(String pkg, URL url) { this.pkg = pkg; this.url = url; } static FileInfo forFile(URL url, String pkg) { return new FileInfo(pkg, url); } static FileInfo forJar(URL url) { return new FileInfo("lib", url).setIsJar(true); } FileInfo setIsJar(boolean val) { isJar = val; return this; } boolean isJar() { return isJar; } String getPkg() { return pkg; } URL getUrl() { return url; } @Override public int hashCode() { HashCodeBuilder hcb = new HashCodeBuilder(); hcb.append(getPkg()); hcb.append(getUrl()); return hcb.toHashCode(); } @Override public boolean equals(Object o) { if (o instanceof FileInfo) { FileInfo other = (FileInfo)o; return Objects.equals(pkg, other.getPkg()) && Objects.equals(url, other.getUrl()); } return false; } public String toString() { return "[FileInfo: " + (isJar() ? "(jar) " : "") + pkg + ", " + url + "]"; } } /** Spec (supplied by command line or client) for one plugin jar: one or * more pluginIds and an output jar name */ static class PlugSpec { List<String> pluginIds = new ArrayList<>(); String jar; PlugSpec addPlug(String plugId) { pluginIds.add(plugId); return this; } PlugSpec addPlugs(List<String> plugIds) { pluginIds.addAll(plugIds); return this; } PlugSpec setJar(String jar) { this.jar = jar; return this; } List<String> getPluginIds() { return pluginIds; } String getJar() { return jar; } File getJarFile() { return new File(jar); } public String toString() { return "[" + getPluginIds() + ", " + getJar() + "]"; } } /** Info about a single plugin */ class PData { String pluginId; List<FileInfo> fis; // FileInfo(s) of plugin and parent .xml files String file; PData(String id, List<FileInfo> fis) { this.pluginId = id; this.fis = fis; } String getPackagePath() { return pathOfPkg(packageOf(pluginId)); } String getPluginPath() throws IOException { String plugPath = fis.get(0).getUrl().getPath(); String plugName = new File(plugPath).getName(); return getPackagePath() + "/" + plugName; } /** Return list of FileInfo for all files in dir of plugin and its * parents */ List<FileInfo> listFiles() { return fis.stream() .flatMap(pu -> listFilesInDirOf(pu).stream()) .collect(Collectors.toList()); } /** Return list of FileInfo for all lib jars in plugin (& parents)'s lib/ * dirs */ List<FileInfo> listLibFiles() { return fis.stream() .flatMap(pu -> listFilesIn(FileInfo.forJar(subUrl(pu.getUrl(), "lib/")), true) .stream()) .collect(Collectors.toList()); } URL subUrl(URL url, String subdir) { try { return new URL(UrlUtil.resolveUri(url, subdir)); } catch (MalformedURLException e) { throw new RuntimeException(e); } } } /** Visitor for Files.walkFileTree(), makes a PlugSpec for each plugin in * tree */ static class FileVisitor extends SimpleFileVisitor<Path> { List<PlugSpec> res; Path root; Path outDir; PathMatcher matcher; List<Pattern> excludePats; List<String> excluded = new ArrayList<>(); FileVisitor(List<PlugSpec> res, Path root, Path outDir) { this.res = res; this.root = root; this.outDir = outDir; matcher = FileSystems.getDefault().getPathMatcher("glob:" + "*.xml"); } static Pattern PLUG_PAT = Pattern.compile("(\\w+)\\.xml$", Pattern.CASE_INSENSITIVE); FileVisitor setExclusions(List<Pattern> excludePats) { this.excludePats = excludePats; return this; } boolean isExcluded(String id) { if (excludePats == null) return false; for (Pattern pat : excludePats) { if (pat.matcher(id).matches()) return true; } return false; } List<String> getExcluded() { return excluded; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Matcher mat = PLUG_PAT.matcher(file.getFileName().toString()); if (mat.matches()) { String fname = mat.group(1); Path rel = root.relativize(file).getParent(); String pkg = rel.toString().replace("/", "."); log.debug2("file: {}, fname: {}, rel: {}, pkg: {}", file, fname, rel, pkg); String fqPlug = pkg + "." + fname; if (isExcluded(fqPlug)) { excluded.add(fqPlug); } else { PlugSpec spec = new PlugSpec() .addPlug(fqPlug) .setJar(outDir.resolve(fqPlug + ".jar").toString()); res.add(spec); } } return CONTINUE; } } public class MyMockLockssDaemon extends MockLockssDaemon { protected MyMockLockssDaemon() { super(); } } // Utility methods /** Convert URL to File */ static File urlToFile(URL url) { if (url.getProtocol().equalsIgnoreCase("file")) { String path = url.getPath(); return new File(url.getPath()); } throw new IllegalArgumentException("Can't convert non file: URL to File: " + url); } /** Return the URL for the containing directory of the URL */ static URL dirOfUrl(URL url) throws URISyntaxException, IOException{ if (!url.getProtocol().equalsIgnoreCase("file")) { throw new IllegalArgumentException("Can't handle non-file: URLs yet: " + url); } URI uri = new URI(url.toString()); // XXX if path is relative (e.g., file:target/classes), URI.getPath() // returns null. // log.debug3("url.getPath: {}", url.getPath()); // log.debug3("getPath: {}", uri.getPath()); URI parent = uri.getPath().endsWith("/") ? uri.resolve("..") : uri.resolve("."); URL res = new URL(parent.toString()); log.debug2("dirOfUrl: {} -> {}", url, res); return res; } /** Find all the files in the directory of the supplied URL, recording * the package name to make it easier to generate the necessary relative * paths for the jar */ List<FileInfo> listFilesInDirOf(FileInfo pu) { try { List<FileInfo> res; URL dirURL = dirOfUrl(pu.getUrl()); return listFilesIn(FileInfo.forFile(dirURL, pu.getPkg()), false); } catch (URISyntaxException | IOException e) { throw new RuntimeException(e); } } /** Find all the files in the supplied directory, recording the package * name */ List<FileInfo> listFilesIn(FileInfo pu, boolean jars) { try { List<FileInfo> res; URL dirURL = pu.getUrl(); switch (dirURL.getProtocol()) { case "file": res = enumerateDir(pu, dirURL, jars); break; case "jar": res = enumerateJarDir(pu, dirURL, jars); break; default: throw new UnsupportedOperationException("Cannot list files for URL "+ pu.getUrl()); } log.debug2("listFilesIn({}): {}", pu, res); return res; } catch (URISyntaxException | IOException e) { throw new RuntimeException(e); } } List<FileInfo> enumerateDir(FileInfo pu, URL dirURL, boolean jars) throws URISyntaxException, IOException { String[] files = new File(dirURL.toURI()).list(); List<FileInfo> res = new ArrayList<>(); if (files != null) { for (String f : files) { if (jars) { res.add(FileInfo.forJar(new URL(dirURL, f))); } else { res.add(FileInfo.forFile(new URL(dirURL, f), pu.getPkg())); } } } return res; } List<FileInfo> enumerateJarDir(FileInfo pu, URL dirURL, boolean jars) throws IOException { if (true) throw new UnsupportedOperationException("nyi"); JarURLConnection jarConnection = (JarURLConnection)dirURL.openConnection(); JarFile jf = jarConnection.getJarFile(); List<FileInfo> res = new ArrayList<>(); Enumeration<JarEntry> entries = jf.entries(); //gives ALL entries in jar while(entries.hasMoreElements()) { // String name = entries.nextElement().getName(); // if (name.startsWith(path)) { //filter according to the path // String entry = name.substring(path.length()); // int checkSubdir = entry.indexOf("/"); // if (checkSubdir >= 0) { // // if it is a subdirectory, we just return the directory name // entry = entry.substring(0, checkSubdir); // } // result.add(entry); // } } return res; } /** Return the package part of the fq name */ static String packageOf(String name) { return StringUtil.upToFinal(name, "."); } /** Convert a package name to a file path */ static String pathOfPkg(String pkg) { return pkg.replace('.', '/'); } static String toString(Attributes attr) { List l = new ArrayList(); for (Map.Entry ent : attr.entrySet()) { l.add(ent.getKey() + "=" + ent.getValue()); } return StringUtil.separatedString(l, "[", ", ", "]"); } /** Walk directory looking for plugins (*.xml), building a PlugSpec for * each */ List<PlugSpec> findSpecsInDir(File indir, File outdir) { Path dirPath = indir.toPath(); List<PlugSpec> res = new ArrayList<>(); FileVisitor visitor = new FileVisitor(res, dirPath, outdir.toPath()) .setExclusions(argExcludePats); try { log.debug("starting tree walk ..."); Files.walkFileTree(dirPath, EnumSet.of(FOLLOW_LINKS), 100, visitor); excluded = visitor.getExcluded(); } catch (IOException e) { throw new RuntimeException("unable to walk source tree.", e); } return res; } // Command line support static String USAGE = "Usage:\n" + "PluginPackager [common-args] -p <plugin-id> ... -o <output-jar> ...\n" + " or\n" + "PluginPackager [common-args] -pd <plugins-class-dir> -od <output-dir>\n" + "\n" + " -p <plugin-id> Fully-qualified plugin id.\n" + " -o <output-jar> Output jar path/name.\n" + " -pd <plugins-class-dir> Root of compiled plugins tree.\n" + " -od <output-dir> Dir to which to write plugin jars.\n" + " -x <exclude-pat> Used with -pd. Plugins whose id matches this\n" + " regexp will be excluded. May be repeated.\n" + " Common args:\n" + " -f Force rebuild even if jar appears to be up-to-date.\n" + " -nofail Exit with 0 status even if some plugins can't be built.\n" + " -nolib Don't include files in lib subdirs.\n" + " -explodelib Explode lib jars rather than copying to plugin jar.\n" + " -cp <classpath> Load plugins from specified colon-separated classpath.\n" + " -keystore <file> Signing keystore. (\"resource:<path>\" loads\n" + " keystore from resource on classpath.)\n" + " -alias <alias> Key alias (required if -keystore is used).\n" + " -storepass <pass> Keystore password (def \"password\").\n" + " -keypass <pass> Key password (def \"password\").\n" + "\n" + "Builds and optionally signs LOCKSS loadable plugin jars. Each jar contains\n" + "one or more plugins and their dependent files, including parent plugins.\n" + "(Currently this is all the files in the dirs of the plugin and its parents.)\n" + "\n" + "The first form allows this to be specified explicity: each -o <output-jar>\n" + "will contain the plugins listed in the -p args immediately preceding it.\n" + "More than one -p -o sequence may be used:\n" + "\n" + " PluginPackager -p org.lockss.plugin.pub1.Pub1Plugin\n" + " -o /tmp/Pub1Plugin.jar \n" + " -p org.lockss.plugin.pub2.Pub2PluginA\n" + " -p org.lockss.plugin.pub2.Pub2PluginB\n" + " -o /tmp/Pub2Plugins.jar\n" + "\n" + "will build two jars, the first containing Pub1Plugin, the second containing\n" + "Pub2PluginA and Pub2PluginB.\n" + "\n" + "The second form traverses the directory tree below <plugins-class-dir>\n" + "(which should be a compiled classes hierarchy, e.g., target/classes),\n" + "packaging each plugin into a jar named <output-dir>/<plugin-id>.jar.\n" + "\n" + " PluginPackager -pd target/classes -od target/pluginjars\n" + "\n" + "If a keystore and alias are provided, the jar will be signed.\n" + "\n" + "Plugin jars are not rebuilt or re-signed if they are at least as recent as\n" + "all the files and dirs that would be written into them. This can be\n" + "suppressed with -f.\n"; static void usage(String msg) { if (!StringUtil.isNullString(msg)) { System.err.println("Error: " + msg); } usage(); } static void usage() { System.err.println(USAGE); System.exit(1); } public static void main(String[] argv) { PlugSpec curSpec = new PlugSpec(); PluginPackager pkgr = new PluginPackager(); if (argv.length == 0) { usage(); } try { for (int ix = 0; ix < argv.length; ix++) { String arg = argv[ix]; if (arg.equals("-cp")) { pkgr.setClassPath(argv[++ix]); } else if (arg.equals("-f")) { pkgr.setForceRebuild(true); } else if (arg.equals("-nofail")) { pkgr.setNoFail(true); } else if (arg.equals("-nolib")) { pkgr.setIncludeLibDir(false); } else if (arg.equals("-explodelib")) { pkgr.setExplodeLib(true); } else if (arg.startsWith("-explodelib=")) { pkgr.setExplodeLib(BooleanUtils.toBoolean(arg.substring("-explodelib=".length()))); } else if (arg.equals("-keystore")) { pkgr.setKeystore(argv[++ix]); } else if (arg.equals("-alias")) { pkgr.setAlias(argv[++ix]); } else if (arg.equals("-keypass")) { pkgr.setKeyPass(argv[++ix]); } else if (arg.equals("-storepass")) { pkgr.setStorePass(argv[++ix]); } else if (arg.equals("-storetype")) { pkgr.setStoreType(argv[++ix]); } else if (arg.equals("-p")) { curSpec.addPlug(argv[++ix]); } else if (arg.equals("-o")) { curSpec.setJar(argv[++ix]); pkgr.addSpec(curSpec); curSpec = new PlugSpec(); } else if (arg.equals("-pd")) { pkgr.setPluginDir(new File(argv[++ix])); } else if (arg.equals("-od")) { pkgr.setOutputDir(new File(argv[++ix])); } else if (arg.equals("-x")) { pkgr.addExclusion(argv[++ix]); } else { usage(); } } } catch (ArrayIndexOutOfBoundsException e) { usage(); } if (!curSpec.getPluginIds().isEmpty()) { usage("-p arg(s) without following -o"); } try { pkgr.build(); System.exit(reportResults(pkgr)); } catch (IllegalArgumentException e) { usage(e.getMessage()); } catch (Exception e) { log.error("init() failed", e); System.exit(2); } } static int reportResults(PluginPackager pkgr) { List<Result> reslst = pkgr.getResults(); List<Result> failures = new ArrayList<>(); int success = 0; int fail = 0; int notModified = 0; for (Result res : reslst) { PlugSpec spec = res.getPlugSpec(); if (res.isError()) { fail++;; failures.add(res); } else if (res.isNotModified()) { notModified++; } else { success++; } } String msg; int excl = pkgr.getExcluded().size(); int tot = reslst.size() + excl; File pdir = pkgr.getPlugDir(); if (pdir != null) { msg = "Found " + StringUtil.numberOfUnits(tot, "plugin") + ", (re)built " + StringUtil.numberOfUnits(success, "jar") + ", " + notModified + " not modified, " + excl + " excluded. " + fail + " failed."; } else { msg = StringUtil.numberOfUnits(success, "jar") + " built, " + notModified + " not modified, " + excl + " excluded. " + fail + " failed."; } if (failures.isEmpty()) { log.info(msg); } else { log.error(msg); for (Result res : failures) { PlugSpec spec = res.getPlugSpec(); log.error(res.getException()); } return pkgr.isNoFail() ? 0 : 1; } return 0; } }
923bbe07a6799f49def7fba0cfbaab3b21445b60
1,136
java
Java
platform-common/src/test/com/bosuyun/platform/common/eventbus/PolyglotTest.java
bosuyun/apaas-community
88b01c931c2400da267bac484cf9cff7cb1b1b6f
[ "Apache-2.0" ]
2
2021-12-06T23:47:25.000Z
2022-01-06T07:33:00.000Z
platform-common/src/test/com/bosuyun/platform/common/eventbus/PolyglotTest.java
bosuyun/apaas-framework-community
88b01c931c2400da267bac484cf9cff7cb1b1b6f
[ "Apache-2.0" ]
null
null
null
platform-common/src/test/com/bosuyun/platform/common/eventbus/PolyglotTest.java
bosuyun/apaas-framework-community
88b01c931c2400da267bac484cf9cff7cb1b1b6f
[ "Apache-2.0" ]
1
2022-03-06T19:14:55.000Z
2022-03-06T19:14:55.000Z
28.4
69
0.659331
999,706
package com.bosuyun.platform.common.eventbus; import com.bosuyun.platform.common.utils.ResourceUtils; import io.quarkus.test.junit.QuarkusTest; import org.graalvm.polyglot.Context; import org.graalvm.polyglot.Source; import org.graalvm.polyglot.Value; import org.junit.jupiter.api.Test; import java.io.IOException; /** * Created by liuyuancheng on 2021/6/1 <br/> */ @QuarkusTest public class PolyglotTest { @Test void test() { Context polyglot = Context.create(); Value array = polyglot.eval("js", "[1,2,42,4]"); int result = array.getArrayElement(2).asInt(); System.out.println(result); } @Test void perform() throws IOException { String script = ResourceUtils.loadFile("perform.mjs"); Source source = Source.newBuilder("js", script, "script.mjs") .mimeType("application/javascript+module") .build(); System.out.println(source); Context polyglot = Context.create(); Value array = polyglot.eval(source); int result = array.getArrayElement(2).asInt(); System.out.println(result); } }
923bbe3c404034cbf7ebdcd0375611583e1c2c08
237
java
Java
src/main/java/spencercjh/problems/MinCostToConnectAllPoints.java
spencercjh/sync-leetcode-today-problem-java-example
aa2393f105050343696d50affe4844ea7fa259f5
[ "Apache-2.0" ]
1
2022-03-02T00:38:45.000Z
2022-03-02T00:38:45.000Z
src/main/java/spencercjh/problems/MinCostToConnectAllPoints.java
spencercjh/sync-leetcode-today-problem-java-example
aa2393f105050343696d50affe4844ea7fa259f5
[ "Apache-2.0" ]
null
null
null
src/main/java/spencercjh/problems/MinCostToConnectAllPoints.java
spencercjh/sync-leetcode-today-problem-java-example
aa2393f105050343696d50affe4844ea7fa259f5
[ "Apache-2.0" ]
null
null
null
15.8
67
0.700422
999,707
package spencercjh.problems; /** * https://leetcode-cn.com/problems/min-cost-to-connect-all-points/ * * @author spencercjh */ public class MinCostToConnectAllPoints { public int minCostConnectPoints(int[][] points) { } }
923bbec74314bfb714faa93d716e7218dc6aa948
495
java
Java
api/src/main/java/net/sf/mmm/code/api/statement/CodeAtomicStatement.java
maybeec/code
0470b864e3077d3d439dcfed87b8be8fdcd76a0e
[ "Apache-2.0" ]
1
2021-11-16T08:49:13.000Z
2021-11-16T08:49:13.000Z
api/src/main/java/net/sf/mmm/code/api/statement/CodeAtomicStatement.java
maybeec/code
0470b864e3077d3d439dcfed87b8be8fdcd76a0e
[ "Apache-2.0" ]
38
2019-05-13T09:22:07.000Z
2021-11-21T09:29:51.000Z
api/src/main/java/net/sf/mmm/code/api/statement/CodeAtomicStatement.java
maybeec/code
0470b864e3077d3d439dcfed87b8be8fdcd76a0e
[ "Apache-2.0" ]
5
2019-05-06T11:50:28.000Z
2021-11-15T21:40:45.000Z
27.5
79
0.721212
999,708
/* Copyright (c) The m-m-m Team, Licensed under the Apache License, Version 2.0 * http://www.apache.org/licenses/LICENSE-2.0 */ package net.sf.mmm.code.api.statement; import net.sf.mmm.code.api.block.CodeBlock; /** * An atomic {@link CodeStatement} (unlike a {@link CodeBlock}). * * @see net.sf.mmm.code.api.member.CodeOperation#getBody() * * @author Joerg Hohwiller (hohwille at users.sourceforge.net) * @since 1.0.0 */ public interface CodeAtomicStatement extends CodeStatement { }
923bbfd397a9f50b8fce9ca216bdbbdb66a88aa7
750
java
Java
township-api/src/main/java/pw/dotdash/township/api/nation/NationRoleService.java
Arvenwood/arven-towns
bb476a9bbd8659f6474316caee22be73dc1d5ba2
[ "MIT" ]
2
2020-02-14T15:25:00.000Z
2020-02-16T04:40:21.000Z
township-api/src/main/java/pw/dotdash/township/api/nation/NationRoleService.java
Arvenwood/arven-towns
bb476a9bbd8659f6474316caee22be73dc1d5ba2
[ "MIT" ]
2
2020-03-30T04:28:41.000Z
2021-03-15T06:06:52.000Z
township-api/src/main/java/pw/dotdash/township/api/nation/NationRoleService.java
Arvenwood/arven-towns
bb476a9bbd8659f6474316caee22be73dc1d5ba2
[ "MIT" ]
null
null
null
25
84
0.765333
999,709
package pw.dotdash.township.api.nation; import org.spongepowered.api.Sponge; import pw.dotdash.township.api.town.Town; import pw.dotdash.township.api.town.TownRole; import java.util.Collection; import java.util.Optional; import java.util.UUID; public interface NationRoleService { static NationRoleService getInstance() { return Sponge.getServiceManager().provideUnchecked(NationRoleService.class); } Collection<NationRole> getRoles(); Optional<NationRole> getRole(UUID uniqueId); Collection<NationRole> getRoles(Nation nation); Optional<NationRole> getRole(Nation nation, String name); boolean contains(NationRole role); boolean register(NationRole role); boolean unregister(NationRole role); }
923bc0c94c6a663d28002672b3cd9077eed9a7e1
1,581
java
Java
src/main/java/org/clarksnut/batchs/messages/step3/B_ValidateMailFileAttachment.java
openfact/openfact-plus-mail-collector
1444fcec2779cb1295d1a2eb00d07c341423b755
[ "Apache-2.0" ]
null
null
null
src/main/java/org/clarksnut/batchs/messages/step3/B_ValidateMailFileAttachment.java
openfact/openfact-plus-mail-collector
1444fcec2779cb1295d1a2eb00d07c341423b755
[ "Apache-2.0" ]
null
null
null
src/main/java/org/clarksnut/batchs/messages/step3/B_ValidateMailFileAttachment.java
openfact/openfact-plus-mail-collector
1444fcec2779cb1295d1a2eb00d07c341423b755
[ "Apache-2.0" ]
null
null
null
34.369565
128
0.723593
999,710
package org.clarksnut.batchs.messages.step3; import org.clarksnut.batchs.BatchLogger; import org.clarksnut.models.jpa.entity.AttachmentEntity; import org.clarksnut.models.jpa.entity.BrokerEntity; import org.clarksnut.models.jpa.entity.FileEntity; import org.clarksnut.models.jpa.entity.MessageEntity; import org.clarksnut.models.utils.XmlValidator; import javax.batch.api.chunk.ItemProcessor; import javax.inject.Inject; import javax.inject.Named; import java.util.AbstractMap; import java.util.UUID; @Named public class B_ValidateMailFileAttachment implements ItemProcessor { @Inject private XmlValidator validator; @Override public Object processItem(Object item) throws Exception { AbstractMap.SimpleEntry<AttachmentEntity, byte[]> entry = (AbstractMap.SimpleEntry<AttachmentEntity, byte[]>) item; AttachmentEntity attachmentEntity = entry.getKey(); byte[] bytes = entry.getValue(); boolean isUBLFile = validator.isUBLFile(bytes); if (isUBLFile) { FileEntity fileEntity = new FileEntity(); fileEntity.setId(UUID.randomUUID().toString()); fileEntity.setFile(bytes); fileEntity.setAttachment(attachmentEntity); return fileEntity; } else { MessageEntity messageEntity = attachmentEntity.getMessage(); BrokerEntity brokerEntity = messageEntity.getBroker(); BatchLogger.LOGGER.notValidUBLFile(brokerEntity.getType(), brokerEntity.getEmail(), attachmentEntity.getFilename()); } return null; } }
923bc132c58692ed3146ae294e742a5f1bb80e18
3,157
java
Java
application/org.openjdk.jmc.ui.celleditors/src/main/java/org/openjdk/jmc/ui/celleditors/NumberCellEditor.java
docwarems/jmc
5f83b98bbb3c946432614acc1a50198e763784cf
[ "UPL-1.0" ]
530
2019-06-13T21:11:31.000Z
2022-03-31T06:57:54.000Z
application/org.openjdk.jmc.ui.celleditors/src/main/java/org/openjdk/jmc/ui/celleditors/NumberCellEditor.java
docwarems/jmc
5f83b98bbb3c946432614acc1a50198e763784cf
[ "UPL-1.0" ]
385
2019-11-14T13:46:04.000Z
2022-03-31T19:38:10.000Z
application/org.openjdk.jmc.ui.celleditors/src/main/java/org/openjdk/jmc/ui/celleditors/NumberCellEditor.java
aptmac/jmc
a8b3614ebb29366e5835ea3b02709be3ab9a32a1
[ "UPL-1.0" ]
128
2019-07-10T07:10:31.000Z
2022-03-30T15:59:26.000Z
38.975309
117
0.725689
999,711
/* * Copyright (c) 2018, 2021 Oracle and/or its affiliates. All rights reserved. * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * The contents of this file are subject to the terms of either the Universal Permissive License * v 1.0 as shown at http://oss.oracle.com/licenses/upl * * or the following license: * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions * and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other materials provided with * the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used to * endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY * WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.openjdk.jmc.ui.celleditors; import org.eclipse.swt.SWT; import org.eclipse.swt.events.VerifyEvent; import org.eclipse.swt.events.VerifyListener; import org.eclipse.swt.widgets.Composite; public class NumberCellEditor<T extends Number> extends StringConstructorCellEditor<T> { public NumberCellEditor(Composite parent, Class<? extends T> type, boolean allowNull, final boolean allowNegative) { super(parent, type, allowNull); final boolean isFloatingPoint = (type == Double.class || type == Float.class); text.addVerifyListener(new VerifyListener() { @Override public void verifyText(VerifyEvent e) { e.doit = (e.character == 0 ? verifyString(e.text, e.start) : verifyChar(e.character, e.start)); } protected boolean verifyString(String s, int atIndex) { for (int i = 0; i < s.length(); i++) { if (!verifyChar(s.charAt(i), atIndex + i)) { return false; } } return true; } protected boolean verifyChar(char c, int atIndex) { switch (c) { case SWT.BS: case SWT.DEL: return true; case '-': return (allowNegative && atIndex == 0) || (isFloatingPoint && atIndex > 0); case '.': case 'e': case 'E': return isFloatingPoint && atIndex > 0; default: return Character.isDigit(c); } } }); } }
923bc1803dd45c49e50cca7955203896d8fe7c0c
1,031
java
Java
desafioFinalBootcamp/src/main/java/grupo3/desafioFinalBootcamp/repositories/FlightReservationRepository.java
toshi-uy/DesafioFinalGrupo3
c2f0e93dcdde8029a87b86bdcf32e7451bbdd7a0
[ "MIT" ]
null
null
null
desafioFinalBootcamp/src/main/java/grupo3/desafioFinalBootcamp/repositories/FlightReservationRepository.java
toshi-uy/DesafioFinalGrupo3
c2f0e93dcdde8029a87b86bdcf32e7451bbdd7a0
[ "MIT" ]
null
null
null
desafioFinalBootcamp/src/main/java/grupo3/desafioFinalBootcamp/repositories/FlightReservationRepository.java
toshi-uy/DesafioFinalGrupo3
c2f0e93dcdde8029a87b86bdcf32e7451bbdd7a0
[ "MIT" ]
null
null
null
44.826087
144
0.826382
999,712
package grupo3.desafioFinalBootcamp.repositories; import grupo3.desafioFinalBootcamp.models.Flight; import grupo3.desafioFinalBootcamp.models.FlightReservation; import grupo3.desafioFinalBootcamp.models.Hotel; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import java.util.Date; import java.util.List; @Repository public interface FlightReservationRepository extends JpaRepository<FlightReservation, Integer> { @Query("SELECT sum(FB.price) FROM FlightReservation FB WHERE FB.bookingDate = '2021-10-15 00:00:00'") Double getHotelFlightReservationsSumPerDay(@Param("day") Date day); @Query("SELECT FB FROM FlightReservation FB WHERE FB.bookingDate BETWEEN :firstmonthyear AND :lastmonthyear") List<FlightReservation> getReservationSumPerMonth(@Param("firstmonthyear") Date firstmonthyear, @Param("lastmonthyear") Date lastmonthyear); }
923bc18d2c2ee6e837de78a978409525f9b813ea
8,754
java
Java
certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/factory/SslContextFactoryTest.java
onap/oom-platform-cert-service
2e4a6dc4d7412b6ff5253735c3c71252648f40bf
[ "Apache-2.0", "CC-BY-4.0" ]
null
null
null
certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/factory/SslContextFactoryTest.java
onap/oom-platform-cert-service
2e4a6dc4d7412b6ff5253735c3c71252648f40bf
[ "Apache-2.0", "CC-BY-4.0" ]
null
null
null
certServiceClient/src/test/java/org/onap/oom/certservice/client/configuration/factory/SslContextFactoryTest.java
onap/oom-platform-cert-service
2e4a6dc4d7412b6ff5253735c3c71252648f40bf
[ "Apache-2.0", "CC-BY-4.0" ]
null
null
null
44.212121
102
0.701051
999,713
/* * ============LICENSE_START======================================================= * oom-certservice-client * ================================================================================ * Copyright (C) 2020 Nokia. All rights reserved. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ============LICENSE_END========================================================= */ package org.onap.oom.certservice.client.configuration.factory; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import org.onap.oom.certservice.client.configuration.EnvsForTls; import org.onap.oom.certservice.client.configuration.exception.TlsConfigurationException; import javax.net.ssl.SSLContext; import java.util.Optional; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) public class SslContextFactoryTest { public static final String INVALID_KEYSTORE_PATH = "nonexistent/keystore"; public static final String VALID_KEYSTORE_NAME = "keystore.jks"; public static final String VALID_KEYSTORE_PASSWORD = "secret"; public static final String INVALID_KEYSTORE_PASSWORD = "wrong_secret"; public static final String INVALID_TRUSTSTORE_PATH = "nonexistent/truststore"; public static final String VALID_TRUSTSTORE_PASSWORD = "secret"; public static final String INVALID_TRUSTSTORE_PASSWORD = "wrong_secret"; public static final String VALID_TRUSTSTORE_NAME = "truststore.jks"; @Mock private EnvsForTls envsForTls; @Test public void shouldThrowExceptionWhenKeystorePathEnvIsMissing() { // Given when(envsForTls.getKeystorePath()).thenReturn(Optional.empty()); SslContextFactory sslContextFactory = new SslContextFactory(envsForTls); // When, Then Exception exception = assertThrows( TlsConfigurationException.class, sslContextFactory::create ); assertThat(exception.getMessage()).contains("KEYSTORE_PATH"); } @Test public void shouldThrowExceptionWhenKeystorePasswordEnvIsMissing() { // Given when(envsForTls.getKeystorePath()).thenReturn(Optional.of("keystore")); when(envsForTls.getKeystorePassword()).thenReturn(Optional.empty()); SslContextFactory sslContextFactory = new SslContextFactory(envsForTls); // When, Then Exception exception = assertThrows( TlsConfigurationException.class, sslContextFactory::create ); assertThat(exception.getMessage()).contains("KEYSTORE_PASSWORD"); } @Test public void shouldThrowExceptionWhenTruststorePathEnvIsMissing() { // Given when(envsForTls.getKeystorePath()).thenReturn(Optional.of("keystore")); when(envsForTls.getKeystorePassword()).thenReturn(Optional.of("password")); when(envsForTls.getTruststorePath()).thenReturn(Optional.empty()); SslContextFactory sslContextFactory = new SslContextFactory(envsForTls); // When, Then Exception exception = assertThrows( TlsConfigurationException.class, sslContextFactory::create ); assertThat(exception.getMessage()).contains("TRUSTSTORE_PATH"); } @Test public void shouldThrowExceptionWhenTruststorePasswordEnvIsMissing() { // Given when(envsForTls.getKeystorePath()).thenReturn(Optional.of("keystore")); when(envsForTls.getKeystorePassword()).thenReturn(Optional.of("password")); when(envsForTls.getTruststorePath()).thenReturn(Optional.of("truststore")); when(envsForTls.getTruststorePassword()).thenReturn(Optional.empty()); SslContextFactory sslContextFactory = new SslContextFactory(envsForTls); // When, Then Exception exception = assertThrows( TlsConfigurationException.class, sslContextFactory::create ); assertThat(exception.getMessage()).contains("TRUSTSTORE_PASSWORD"); } @Test public void shouldThrowExceptionWhenKeystoreIsMissing() { // Given when(envsForTls.getKeystorePath()).thenReturn(Optional.of(INVALID_KEYSTORE_PATH)); when(envsForTls.getKeystorePassword()).thenReturn(Optional.of("secret")); when(envsForTls.getTruststorePath()).thenReturn(Optional.of("truststore.jks")); when(envsForTls.getTruststorePassword()).thenReturn(Optional.of("secret")); SslContextFactory sslContextFactory = new SslContextFactory(envsForTls); // When, Then assertThrows( TlsConfigurationException.class, sslContextFactory::create ); } @Test public void shouldThrowExceptionWhenKeystorePasswordIsWrong() { // Given String keystorePath = getResourcePath(VALID_KEYSTORE_NAME); when(envsForTls.getKeystorePath()).thenReturn(Optional.of(keystorePath)); when(envsForTls.getKeystorePassword()).thenReturn(Optional.of(INVALID_KEYSTORE_PASSWORD)); when(envsForTls.getTruststorePath()).thenReturn(Optional.of(VALID_TRUSTSTORE_NAME)); when(envsForTls.getTruststorePassword()).thenReturn(Optional.of(VALID_TRUSTSTORE_PASSWORD)); SslContextFactory sslContextFactory = new SslContextFactory(envsForTls); // When, Then assertThrows( TlsConfigurationException.class, sslContextFactory::create ); } @Test public void shouldThrowExceptionWhenTruststoreIsMissing() { // Given String keystorePath = getResourcePath(VALID_KEYSTORE_NAME); when(envsForTls.getKeystorePath()).thenReturn(Optional.of(keystorePath)); when(envsForTls.getKeystorePassword()).thenReturn(Optional.of(VALID_KEYSTORE_PASSWORD)); when(envsForTls.getTruststorePath()).thenReturn(Optional.of(INVALID_TRUSTSTORE_PATH)); when(envsForTls.getTruststorePassword()).thenReturn(Optional.of(VALID_TRUSTSTORE_PASSWORD)); SslContextFactory sslContextFactory = new SslContextFactory(envsForTls); // When, Then assertThrows( TlsConfigurationException.class, sslContextFactory::create ); } @Test public void shouldThrowExceptionWhenTruststorePasswordIsWrong() { // Given String keystorePath = getResourcePath(VALID_KEYSTORE_NAME); String truststorePath = getResourcePath(VALID_TRUSTSTORE_NAME); when(envsForTls.getKeystorePath()).thenReturn(Optional.of(keystorePath)); when(envsForTls.getKeystorePassword()).thenReturn(Optional.of(VALID_KEYSTORE_PASSWORD)); when(envsForTls.getTruststorePath()).thenReturn(Optional.of(truststorePath)); when(envsForTls.getTruststorePassword()).thenReturn(Optional.of(INVALID_TRUSTSTORE_PASSWORD)); SslContextFactory sslContextFactory = new SslContextFactory(envsForTls); // When, Then assertThrows( TlsConfigurationException.class, sslContextFactory::create ); } @Test public void shouldReturnSslContext() throws TlsConfigurationException { // Given String keystorePath = getResourcePath(VALID_KEYSTORE_NAME); String truststorePath = getResourcePath(VALID_TRUSTSTORE_NAME); when(envsForTls.getKeystorePath()).thenReturn(Optional.of(keystorePath)); when(envsForTls.getKeystorePassword()).thenReturn(Optional.of(VALID_KEYSTORE_PASSWORD)); when(envsForTls.getTruststorePath()).thenReturn(Optional.of(truststorePath)); when(envsForTls.getTruststorePassword()).thenReturn(Optional.of(VALID_TRUSTSTORE_PASSWORD)); SslContextFactory sslContextFactory = new SslContextFactory(envsForTls); // When SSLContext sslContext = sslContextFactory.create(); // Then assertNotNull(sslContext); } private String getResourcePath(String resource) { return getClass().getClassLoader().getResource(resource).getFile(); } }
923bc1c51d60a261f493bd3e41bd05d83f657995
608
java
Java
August0802/src/main/java/me/wondertwo/august0802/bean/guokr/Guokr.java
wondertwo/AugustProj
dcc58c6f6ee84fc2a463abac6e7b25c841d6cdcd
[ "Apache-2.0" ]
2
2016-08-14T13:10:59.000Z
2016-08-14T14:08:24.000Z
August0802/src/main/java/me/wondertwo/august0802/bean/guokr/Guokr.java
wondertwo/AugustProj
dcc58c6f6ee84fc2a463abac6e7b25c841d6cdcd
[ "Apache-2.0" ]
null
null
null
August0802/src/main/java/me/wondertwo/august0802/bean/guokr/Guokr.java
wondertwo/AugustProj
dcc58c6f6ee84fc2a463abac6e7b25c841d6cdcd
[ "Apache-2.0" ]
null
null
null
21.714286
72
0.685855
999,714
package me.wondertwo.august0802.bean.guokr; import com.google.gson.annotations.SerializedName; import java.util.List; /** * Created by wondertwo on 2016/8/17. */ public class Guokr { public @SerializedName("ok") Boolean response_ok; public @SerializedName("result") List<GuokrResult> response_results; public static class GuokrResult { public int id; public String title; public String headline_img_tb; // 用于文章列表页小图 public String headline_img; // 用于文章内容页大图 public String link; public String author; public String summary; } }
923bc22308b47ca184b532114224f4be531c50e2
176
java
Java
licensed/docflex-doclet/demo/java5/package-info.java
bosschaert/osgi
7319bf5b222fea2de6ef699ca4d82d9111cc9c64
[ "Apache-2.0" ]
43
2020-12-05T15:04:37.000Z
2022-03-15T07:01:31.000Z
licensed/docflex-doclet/demo/java5/package-info.java
bosschaert/osgi
7319bf5b222fea2de6ef699ca4d82d9111cc9c64
[ "Apache-2.0" ]
143
2020-12-16T14:07:26.000Z
2022-03-30T17:12:09.000Z
licensed/docflex-doclet/demo/java5/package-info.java
bosschaert/osgi
7319bf5b222fea2de6ef699ca4d82d9111cc9c64
[ "Apache-2.0" ]
23
2020-12-03T21:22:51.000Z
2022-03-08T13:29:17.000Z
19.555556
67
0.732955
999,715
/** * A few Java classes to demonstrate DocFlex/Doclet capabilities and * how it handles some of Java5 features. * * @prj:type demo */ @Author("Filigris Works") package java5;
923bc2d5ac5e3c3d38814d80f60d69251ea47b98
159
java
Java
AlgorithmSamples/src/Main.java
FrewenWong/NyxJava
51ad1aed6cc59cbbe0064adf16a680ba28d7c8d9
[ "Apache-2.0" ]
null
null
null
AlgorithmSamples/src/Main.java
FrewenWong/NyxJava
51ad1aed6cc59cbbe0064adf16a680ba28d7c8d9
[ "Apache-2.0" ]
null
null
null
AlgorithmSamples/src/Main.java
FrewenWong/NyxJava
51ad1aed6cc59cbbe0064adf16a680ba28d7c8d9
[ "Apache-2.0" ]
null
null
null
10.6
44
0.559748
999,716
/** * https://leetcode-cn.com/ */ public class Main { public static void main(String[] args) { System.out.println("Hello World!"); } }
923bc346ed908f2c542530551e5d2244fbc99c68
154
java
Java
src/me/jurij/ProceduralDungeonGenerator/ProceduralDungeonGenerator.java
JerzyKruszewski/ProceduralDungeonGenerator
5e236b74bbef4d41b8d0c07ce731a718c8f00825
[ "MIT" ]
null
null
null
src/me/jurij/ProceduralDungeonGenerator/ProceduralDungeonGenerator.java
JerzyKruszewski/ProceduralDungeonGenerator
5e236b74bbef4d41b8d0c07ce731a718c8f00825
[ "MIT" ]
null
null
null
src/me/jurij/ProceduralDungeonGenerator/ProceduralDungeonGenerator.java
JerzyKruszewski/ProceduralDungeonGenerator
5e236b74bbef4d41b8d0c07ce731a718c8f00825
[ "MIT" ]
null
null
null
15.4
44
0.694805
999,717
package me.jurij.ProceduralDungeonGenerator; public class ProceduralDungeonGenerator { public static void main(String[] args) { } }
923bc3890a77c77e81ff45320cf1f538dd44f575
347
java
Java
src/main/java/com/example/af/configuration/CoreConfiguration.java
andrzej-t/AF
c4ad9979192f2f5d9e0af9cf3b0bcb1661c40837
[ "Apache-2.0" ]
null
null
null
src/main/java/com/example/af/configuration/CoreConfiguration.java
andrzej-t/AF
c4ad9979192f2f5d9e0af9cf3b0bcb1661c40837
[ "Apache-2.0" ]
null
null
null
src/main/java/com/example/af/configuration/CoreConfiguration.java
andrzej-t/AF
c4ad9979192f2f5d9e0af9cf3b0bcb1661c40837
[ "Apache-2.0" ]
null
null
null
24.785714
60
0.783862
999,718
package com.example.af.configuration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.client.RestTemplate; @Configuration public class CoreConfiguration { @Bean public RestTemplate restTemplate() { return new RestTemplate(); } }
923bc6688315e2808a0b977166c6625a732d18ac
19,059
java
Java
gnd/src/main/java/com/google/android/gnd/ui/editsubmission/EditSubmissionFragment.java
google/gnd-android
fb675b479d8ee7c7d46b5a00c71727800f4bc3bd
[ "Apache-2.0" ]
19
2018-05-25T22:11:29.000Z
2018-12-06T01:58:47.000Z
gnd/src/main/java/com/google/android/gnd/ui/editsubmission/EditSubmissionFragment.java
google/gnd-android
fb675b479d8ee7c7d46b5a00c71727800f4bc3bd
[ "Apache-2.0" ]
19
2018-09-27T17:10:43.000Z
2018-12-06T20:10:43.000Z
gnd/src/main/java/com/google/android/gnd/ui/editsubmission/EditSubmissionFragment.java
google/gnd-android
fb675b479d8ee7c7d46b5a00c71727800f4bc3bd
[ "Apache-2.0" ]
5
2018-06-29T05:39:46.000Z
2018-12-06T18:33:14.000Z
38.118
119
0.727268
999,719
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.gnd.ui.editsubmission; import static com.google.android.gnd.rx.RxAutoDispose.autoDisposable; import static com.google.android.gnd.ui.editsubmission.AddPhotoDialogAdapter.PhotoStorageResource.PHOTO_SOURCE_CAMERA; import static com.google.android.gnd.ui.editsubmission.AddPhotoDialogAdapter.PhotoStorageResource.PHOTO_SOURCE_STORAGE; import static java.util.Objects.requireNonNull; import android.app.DatePickerDialog; import android.app.TimePickerDialog; import android.content.Context; import android.net.Uri; import android.os.Bundle; import android.text.format.DateFormat; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.widget.LinearLayout; import androidx.activity.result.ActivityResultLauncher; import androidx.activity.result.contract.ActivityResultContracts.GetContent; import androidx.activity.result.contract.ActivityResultContracts.TakePicture; import androidx.annotation.Nullable; import androidx.appcompat.app.AlertDialog; import androidx.core.content.FileProvider; import androidx.databinding.ViewDataBinding; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.google.android.gnd.BuildConfig; import com.google.android.gnd.MainActivity; import com.google.android.gnd.R; import com.google.android.gnd.databinding.DateInputFieldBinding; import com.google.android.gnd.databinding.EditSubmissionBottomSheetBinding; import com.google.android.gnd.databinding.EditSubmissionFragBinding; import com.google.android.gnd.databinding.MultipleChoiceInputFieldBinding; import com.google.android.gnd.databinding.NumberInputFieldBinding; import com.google.android.gnd.databinding.PhotoInputFieldBinding; import com.google.android.gnd.databinding.PhotoInputFieldBindingImpl; import com.google.android.gnd.databinding.TextInputFieldBinding; import com.google.android.gnd.databinding.TimeInputFieldBinding; import com.google.android.gnd.model.submission.MultipleChoiceResponse; import com.google.android.gnd.model.task.Field; import com.google.android.gnd.model.task.MultipleChoice; import com.google.android.gnd.model.task.Option; import com.google.android.gnd.model.task.Step; import com.google.android.gnd.model.task.Task; import com.google.android.gnd.repository.UserMediaRepository; import com.google.android.gnd.rx.Schedulers; import com.google.android.gnd.ui.common.AbstractFragment; import com.google.android.gnd.ui.common.BackPressListener; import com.google.android.gnd.ui.common.EphemeralPopups; import com.google.android.gnd.ui.common.Navigator; import com.google.android.gnd.ui.common.TwoLineToolbar; import com.google.android.material.bottomsheet.BottomSheetDialog; import com.google.common.collect.ImmutableList; import dagger.hilt.android.AndroidEntryPoint; import io.reactivex.Completable; import java.io.File; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; import java8.util.Optional; import java8.util.function.Consumer; import javax.inject.Inject; import timber.log.Timber; @AndroidEntryPoint public class EditSubmissionFragment extends AbstractFragment implements BackPressListener { /** * String constant keys used for persisting state in {@see Bundle} objects. */ private static final class BundleKeys { /** * Key used to store unsaved responses across activity re-creation. */ private static final String RESTORED_RESPONSES = "restoredResponses"; /** * Key used to store field ID waiting for photo response across activity re-creation. */ private static final String FIELD_WAITING_FOR_PHOTO = "photoFieldId"; /** * Key used to store captured photo Uri across activity re-creation. */ private static final String CAPTURED_PHOTO_PATH = "capturedPhotoPath"; } private final List<AbstractFieldViewModel> fieldViewModelList = new ArrayList<>(); @Inject Navigator navigator; @Inject FieldViewFactory fieldViewFactory; @Inject EphemeralPopups popups; @Inject Schedulers schedulers; @Inject UserMediaRepository userMediaRepository; private EditSubmissionViewModel viewModel; private EditSubmissionFragBinding binding; private ActivityResultLauncher<String> selectPhotoLauncher; private ActivityResultLauncher<Uri> capturePhotoLauncher; private static AbstractFieldViewModel getViewModel(ViewDataBinding binding) { if (binding instanceof TextInputFieldBinding) { return ((TextInputFieldBinding) binding).getViewModel(); } else if (binding instanceof MultipleChoiceInputFieldBinding) { return ((MultipleChoiceInputFieldBinding) binding).getViewModel(); } else if (binding instanceof NumberInputFieldBinding) { return ((NumberInputFieldBinding) binding).getViewModel(); } else if (binding instanceof PhotoInputFieldBinding) { return ((PhotoInputFieldBinding) binding).getViewModel(); } else if (binding instanceof DateInputFieldBinding) { return ((DateInputFieldBinding) binding).getViewModel(); } else if (binding instanceof TimeInputFieldBinding) { return ((TimeInputFieldBinding) binding).getViewModel(); } else { throw new IllegalArgumentException("Unknown binding type: " + binding.getClass()); } } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); viewModel = getViewModel(EditSubmissionViewModel.class); selectPhotoLauncher = registerForActivityResult(new GetContent(), viewModel::onSelectPhotoResult); capturePhotoLauncher = registerForActivityResult(new TakePicture(), viewModel::onCapturePhotoResult); } @Override public View onCreateView( LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { binding = EditSubmissionFragBinding.inflate(inflater, container, false); binding.setLifecycleOwner(this); binding.setViewModel(viewModel); binding.setFragment(this); binding.saveSubmissionBtn.setOnClickListener(this::onSaveClick); return binding.getRoot(); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); TwoLineToolbar toolbar = binding.editSubmissionToolbar; ((MainActivity) getActivity()).setActionBar(toolbar, R.drawable.ic_close_black_24dp); toolbar.setNavigationOnClickListener(__ -> onCloseButtonClick()); // Observe state changes. viewModel.getTask().observe(getViewLifecycleOwner(), this::rebuildTask); viewModel .getSaveResults() .observeOn(schedulers.ui()) .as(autoDisposable(getViewLifecycleOwner())) .subscribe(this::handleSaveResult); // Initialize view model. Bundle args = getArguments(); if (savedInstanceState != null) { args.putSerializable( BundleKeys.RESTORED_RESPONSES, savedInstanceState.getSerializable(BundleKeys.RESTORED_RESPONSES)); viewModel.setFieldWaitingForPhoto( savedInstanceState.getString(BundleKeys.FIELD_WAITING_FOR_PHOTO)); viewModel.setCapturedPhotoPath( savedInstanceState.getParcelable(BundleKeys.CAPTURED_PHOTO_PATH)); } viewModel.initialize(EditSubmissionFragmentArgs.fromBundle(args)); } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putSerializable(BundleKeys.RESTORED_RESPONSES, viewModel.getDraftResponses()); outState.putString(BundleKeys.FIELD_WAITING_FOR_PHOTO, viewModel.getFieldWaitingForPhoto()); outState.putString(BundleKeys.CAPTURED_PHOTO_PATH, viewModel.getCapturedPhotoPath()); } private void handleSaveResult(EditSubmissionViewModel.SaveResult saveResult) { switch (saveResult) { case HAS_VALIDATION_ERRORS: showValidationErrorsAlert(); break; case NO_CHANGES_TO_SAVE: popups.showFyi(R.string.no_changes_to_save); navigator.navigateUp(); break; case SAVED: popups.showSuccess(R.string.saved); navigator.navigateUp(); break; default: Timber.e("Unknown save result type: %s", saveResult); break; } } private void addFieldViewModel(Field field, ViewDataBinding binding) { if (binding instanceof PhotoInputFieldBindingImpl) { ((PhotoInputFieldBindingImpl) binding).setEditSubmissionViewModel(viewModel); } AbstractFieldViewModel fieldViewModel = getViewModel(binding); fieldViewModel.initialize(field, viewModel.getResponse(field.getId())); if (fieldViewModel instanceof PhotoFieldViewModel) { initPhotoField((PhotoFieldViewModel) fieldViewModel); } else if (fieldViewModel instanceof MultipleChoiceFieldViewModel) { observeSelectChoiceClicks((MultipleChoiceFieldViewModel) fieldViewModel); } else if (fieldViewModel instanceof DateFieldViewModel) { observeDateDialogClicks((DateFieldViewModel) fieldViewModel); } else if (fieldViewModel instanceof TimeFieldViewModel) { observeTimeDialogClicks((TimeFieldViewModel) fieldViewModel); } fieldViewModel.getResponse().observe(this, response -> viewModel.setResponse(field, response)); fieldViewModelList.add(fieldViewModel); } public void onSaveClick(View view) { hideKeyboard(view); viewModel.onSaveClick(getValidationErrors()); } private void hideKeyboard(View view) { if (getActivity() != null) { InputMethodManager inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0); } } private Map<String, String> getValidationErrors() { HashMap<String, String> errors = new HashMap<>(); for (AbstractFieldViewModel fieldViewModel : fieldViewModelList) { fieldViewModel .validate() .ifPresent(error -> errors.put(fieldViewModel.getField().getId(), error)); } return errors; } private void observeDateDialogClicks(DateFieldViewModel dateFieldViewModel) { dateFieldViewModel .getShowDialogClicks() .as(autoDisposable(this)) .subscribe(__ -> showDateDialog(dateFieldViewModel)); } private void observeTimeDialogClicks(TimeFieldViewModel timeFieldViewModel) { timeFieldViewModel .getShowDialogClicks() .as(autoDisposable(this)) .subscribe(__ -> showTimeDialog(timeFieldViewModel)); } private void rebuildTask(Task task) { LinearLayout formLayout = binding.editSubmissionLayout; formLayout.removeAllViews(); fieldViewModelList.clear(); for (Step step : task.getStepsSorted()) { switch (step.getType()) { case FIELD: Field field = step.getField(); ViewDataBinding binding = fieldViewFactory.addFieldView(field.getType(), formLayout); addFieldViewModel(field, binding); break; case UNKNOWN: default: Timber.e("%s task steps not yet supported", step.getType()); break; } } } private void observeSelectChoiceClicks(MultipleChoiceFieldViewModel viewModel) { viewModel .getShowDialogClicks() .as(autoDisposable(this)) .subscribe( __ -> createMultipleChoiceDialog( viewModel.getField(), viewModel.getCurrentResponse(), viewModel::updateResponse) .show()); } private AlertDialog createMultipleChoiceDialog( Field field, Optional<MultipleChoiceResponse> response, Consumer<ImmutableList<Option>> consumer) { MultipleChoice multipleChoice = requireNonNull(field.getMultipleChoice()); switch (multipleChoice.getCardinality()) { case SELECT_MULTIPLE: return MultiSelectDialogFactory.builder() .setContext(requireContext()) .setTitle(field.getLabel()) .setMultipleChoice(multipleChoice) .setCurrentResponse(response) .setValueConsumer(consumer) .build() .createDialog(); case SELECT_ONE: return SingleSelectDialogFactory.builder() .setContext(requireContext()) .setTitle(field.getLabel()) .setMultipleChoice(multipleChoice) .setCurrentResponse(response) .setValueConsumer(consumer) .build() .createDialog(); default: throw new IllegalArgumentException( "Unknown cardinality: " + multipleChoice.getCardinality()); } } private void initPhotoField(PhotoFieldViewModel photoFieldViewModel) { photoFieldViewModel.setEditable(true); photoFieldViewModel.setSurveyId(viewModel.getSurveyId()); photoFieldViewModel.setSubmissionId(viewModel.getSubmissionId()); observeSelectPhotoClicks(photoFieldViewModel); observePhotoResults(photoFieldViewModel); } private void observeSelectPhotoClicks(PhotoFieldViewModel fieldViewModel) { fieldViewModel .getShowDialogClicks() .observe(this, __ -> onShowPhotoSelectorDialog(fieldViewModel.getField())); } private void observePhotoResults(PhotoFieldViewModel fieldViewModel) { viewModel .getLastPhotoResult() .as(autoDisposable(getViewLifecycleOwner())) .subscribe(fieldViewModel::onPhotoResult); } private void onShowPhotoSelectorDialog(Field field) { EditSubmissionBottomSheetBinding addPhotoBottomSheetBinding = EditSubmissionBottomSheetBinding.inflate(getLayoutInflater()); addPhotoBottomSheetBinding.setViewModel(viewModel); addPhotoBottomSheetBinding.setField(field); BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(requireContext()); bottomSheetDialog.setContentView(addPhotoBottomSheetBinding.getRoot()); bottomSheetDialog.setCancelable(true); bottomSheetDialog.show(); RecyclerView recyclerView = addPhotoBottomSheetBinding.recyclerView; recyclerView.setHasFixedSize(true); recyclerView.setLayoutManager(new LinearLayoutManager(getContext())); recyclerView.setAdapter( new AddPhotoDialogAdapter( type -> { bottomSheetDialog.dismiss(); onSelectPhotoClick(type, field.getId()); })); } private void showDateDialog(DateFieldViewModel fieldViewModel) { Calendar calendar = Calendar.getInstance(); int year = calendar.get(Calendar.YEAR); int month = calendar.get(Calendar.MONTH); int day = calendar.get(Calendar.DAY_OF_MONTH); DatePickerDialog datePickerDialog = new DatePickerDialog( requireContext(), (view, updatedYear, updatedMonth, updatedDayOfMonth) -> { Calendar c = Calendar.getInstance(); c.set(Calendar.DAY_OF_MONTH, updatedDayOfMonth); c.set(Calendar.MONTH, updatedMonth); c.set(Calendar.YEAR, updatedYear); fieldViewModel.updateResponse(c.getTime()); }, year, month, day); datePickerDialog.show(); } private void showTimeDialog(TimeFieldViewModel fieldViewModel) { Calendar calendar = Calendar.getInstance(); int hour = calendar.get(Calendar.HOUR); int minute = calendar.get(Calendar.MINUTE); TimePickerDialog timePickerDialog = new TimePickerDialog( requireContext(), (view, updatedHourOfDay, updatedMinute) -> { Calendar c = Calendar.getInstance(); c.set(Calendar.HOUR_OF_DAY, updatedHourOfDay); c.set(Calendar.MINUTE, updatedMinute); fieldViewModel.updateResponse(c.getTime()); }, hour, minute, DateFormat.is24HourFormat(requireContext())); timePickerDialog.show(); } private void onSelectPhotoClick(int type, String fieldId) { switch (type) { case PHOTO_SOURCE_CAMERA: // TODO: Launch intent is not invoked if the permission is not granted by default. viewModel .obtainCapturePhotoPermissions() .andThen(Completable.fromAction(() -> launchPhotoCapture(fieldId))) .as(autoDisposable(getViewLifecycleOwner())) .subscribe(); break; case PHOTO_SOURCE_STORAGE: // TODO: Launch intent is not invoked if the permission is not granted by default. viewModel .obtainSelectPhotoPermissions() .andThen(Completable.fromAction(() -> launchPhotoSelector(fieldId))) .as(autoDisposable(getViewLifecycleOwner())) .subscribe(); break; default: throw new IllegalArgumentException("Unknown type: " + type); } } private void launchPhotoCapture(String fieldId) { File photoFile = userMediaRepository.createImageFile(fieldId); Uri uri = FileProvider.getUriForFile(requireContext(), BuildConfig.APPLICATION_ID, photoFile); viewModel.setFieldWaitingForPhoto(fieldId); viewModel.setCapturedPhotoPath(photoFile.getAbsolutePath()); capturePhotoLauncher.launch(uri); Timber.d("Capture photo intent sent"); } private void launchPhotoSelector(String fieldId) { viewModel.setFieldWaitingForPhoto(fieldId); selectPhotoLauncher.launch("image/*"); Timber.d("Select photo intent sent"); } @Override public boolean onBack() { if (viewModel.hasUnsavedChanges()) { showUnsavedChangesDialog(); return true; } return false; } private void onCloseButtonClick() { if (viewModel.hasUnsavedChanges()) { showUnsavedChangesDialog(); } else { navigator.navigateUp(); } } private void showUnsavedChangesDialog() { new AlertDialog.Builder(requireContext()) .setMessage(R.string.unsaved_changes) .setPositiveButton(R.string.discard_changes, (d, i) -> navigator.navigateUp()) .setNegativeButton(R.string.continue_editing, (d, i) -> { }) .create() .show(); } private void showValidationErrorsAlert() { new AlertDialog.Builder(requireContext()) .setMessage(R.string.invalid_data_warning) .setPositiveButton(R.string.invalid_data_confirm, (a, b) -> { }) .create() .show(); } }
923bc754563ebf57861ca0441bb1e9e4fdf13d2e
445
java
Java
automate-boot/src/main/java/com/github/gnx/automate/event/bean/EntityChangeEvent.java
geningxiang/automate2
9f27f1ab44cd795f2104b173b983008d69b1f663
[ "Apache-2.0" ]
3
2019-12-08T08:55:43.000Z
2021-06-21T00:56:28.000Z
automate-boot/src/main/java/com/github/gnx/automate/event/bean/EntityChangeEvent.java
geningxiang/automate2
9f27f1ab44cd795f2104b173b983008d69b1f663
[ "Apache-2.0" ]
2
2020-09-16T05:11:17.000Z
2021-12-14T21:53:10.000Z
automate-boot/src/main/java/com/github/gnx/automate/event/bean/EntityChangeEvent.java
geningxiang/automate2
9f27f1ab44cd795f2104b173b983008d69b1f663
[ "Apache-2.0" ]
1
2019-06-03T02:37:52.000Z
2019-06-03T02:37:52.000Z
17.8
57
0.669663
999,720
package com.github.gnx.automate.event.bean; import org.springframework.context.ApplicationEvent; /** * Created with IntelliJ IDEA. * Description: * @author genx * @date 2020/8/31 21:31 */ public class EntityChangeEvent extends ApplicationEvent { private final Object data; public EntityChangeEvent(Object data) { super(data); this.data = data; } public Object getData() { return data; } }
923bc78e422d0e21ae311615b4edab4ee576c947
2,015
java
Java
src/sources/au/gov/health/covidsafe/interactor/usecase/GetUploadOtpException.java
ghuntley/COVIDSafe_1.0.11.apk
ba4133e6c8092d7c2881562fcb0c46ec7af04ecb
[ "Apache-2.0" ]
50
2020-04-26T12:26:18.000Z
2020-05-08T12:59:45.000Z
src/sources/au/gov/health/covidsafe/interactor/usecase/GetUploadOtpException.java
ghuntley/COVIDSafe_1.0.11.apk
ba4133e6c8092d7c2881562fcb0c46ec7af04ecb
[ "Apache-2.0" ]
null
null
null
src/sources/au/gov/health/covidsafe/interactor/usecase/GetUploadOtpException.java
ghuntley/COVIDSafe_1.0.11.apk
ba4133e6c8092d7c2881562fcb0c46ec7af04ecb
[ "Apache-2.0" ]
8
2020-04-27T00:37:19.000Z
2020-05-05T07:54:07.000Z
65
673
0.722084
999,721
package au.gov.health.covidsafe.interactor.usecase; import kotlin.Metadata; @Metadata(bv = {1, 0, 3}, d1 = {"\u0000\u0016\n\u0002\u0018\u0002\n\u0002\u0018\u0002\n\u0002\u0018\u0002\n\u0002\b\u0002\n\u0002\u0018\u0002\n\u0000\b6\u0018\u00002\u00060\u0001j\u0002`\u0002:\u0001\u0004B\u0007\b\u0002¢\u0006\u0002\u0010\u0003‚\u0001\u0001\u0005¨\u0006\u0006"}, d2 = {"Lau/gov/health/covidsafe/interactor/usecase/GetUploadOtpException;", "Ljava/lang/Exception;", "Lkotlin/Exception;", "()V", "GetUploadOtpServiceException", "Lau/gov/health/covidsafe/interactor/usecase/GetUploadOtpException$GetUploadOtpServiceException;", "app_release"}, k = 1, mv = {1, 1, 16}) /* compiled from: GetUploadOtp.kt */ public abstract class GetUploadOtpException extends Exception { @Metadata(bv = {1, 0, 3}, d1 = {"\u0000\u0012\n\u0002\u0018\u0002\n\u0002\u0018\u0002\n\u0000\n\u0002\u0010\b\n\u0002\b\u0005\u0018\u00002\u00020\u0001B\u000f\u0012\b\u0010\u0002\u001a\u0004\u0018\u00010\u0003¢\u0006\u0002\u0010\u0004R\u0015\u0010\u0002\u001a\u0004\u0018\u00010\u0003¢\u0006\n\n\u0002\u0010\u0007\u001a\u0004\b\u0005\u0010\u0006¨\u0006\b"}, d2 = {"Lau/gov/health/covidsafe/interactor/usecase/GetUploadOtpException$GetUploadOtpServiceException;", "Lau/gov/health/covidsafe/interactor/usecase/GetUploadOtpException;", "code", "", "(Ljava/lang/Integer;)V", "getCode", "()Ljava/lang/Integer;", "Ljava/lang/Integer;", "app_release"}, k = 1, mv = {1, 1, 16}) /* compiled from: GetUploadOtp.kt */ public static final class GetUploadOtpServiceException extends GetUploadOtpException { private final Integer code; public GetUploadOtpServiceException(Integer num) { super((DefaultConstructorMarker) null); this.code = num; } public final Integer getCode() { return this.code; } } private GetUploadOtpException() { } public /* synthetic */ GetUploadOtpException(DefaultConstructorMarker defaultConstructorMarker) { this(); } }
923bc82c4d039aabd2b39c43447c95c4cdb05130
3,410
java
Java
activemq-unit-tests/src/test/java/org/apache/activemq/store/AbstractMessageStoreSizeTest.java
gemmellr/activemq
5bd2abf85dbda14bf41f54d09af4866e814f931f
[ "Apache-2.0" ]
2,073
2015-01-01T15:27:57.000Z
2022-03-31T09:08:51.000Z
activemq-unit-tests/src/test/java/org/apache/activemq/store/AbstractMessageStoreSizeTest.java
gemmellr/activemq
5bd2abf85dbda14bf41f54d09af4866e814f931f
[ "Apache-2.0" ]
338
2015-01-05T17:50:20.000Z
2022-03-31T17:46:12.000Z
activemq-unit-tests/src/test/java/org/apache/activemq/store/AbstractMessageStoreSizeTest.java
gemmellr/activemq
5bd2abf85dbda14bf41f54d09af4866e814f931f
[ "Apache-2.0" ]
1,498
2015-01-03T10:58:42.000Z
2022-03-28T05:11:21.000Z
34.444444
101
0.708211
999,722
/** * 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.activemq.store; import static org.junit.Assert.assertTrue; import java.util.Random; import org.apache.activemq.broker.ConnectionContext; import org.apache.activemq.command.ActiveMQMessage; import org.apache.activemq.command.ActiveMQQueue; import org.apache.activemq.command.MessageId; import org.apache.activemq.command.ProducerId; import org.apache.activemq.util.ByteSequence; import org.apache.activemq.util.IdGenerator; import org.junit.After; import org.junit.Before; import org.junit.Test; /** * This test is for AMQ-5748 to verify that {@link MessageStore} implements correctly * compute the size of the messages in the store. * */ public abstract class AbstractMessageStoreSizeTest { protected static final IdGenerator id = new IdGenerator(); protected ActiveMQQueue destination = new ActiveMQQueue("Test"); protected ProducerId producerId = new ProducerId("1.1.1"); protected static final int MESSAGE_COUNT = 20; protected static String dataDirectory = "target/test-amq-5748/datadb"; protected static int testMessageSize = 1000; @Before public void init() throws Exception { this.initStore(); } @After public void destroy() throws Exception { this.destroyStore(); } protected abstract void initStore() throws Exception; protected abstract void destroyStore() throws Exception; /** * This method tests that the message size exists after writing a bunch of messages to the store. * @throws Exception */ @Test public void testMessageSize() throws Exception { writeMessages(); long messageSize = getMessageStore().getMessageSize(); assertTrue(getMessageStore().getMessageCount() == 20); assertTrue(messageSize > 20 * testMessageSize); } /** * Write random byte messages to the store for testing. * * @throws Exception */ protected void writeMessages() throws Exception { final ConnectionContext context = new ConnectionContext(); for (int i = 0; i < MESSAGE_COUNT; i++) { ActiveMQMessage message = new ActiveMQMessage(); final byte[] data = new byte[testMessageSize]; final Random rng = new Random(); rng.nextBytes(data); message.setContent(new ByteSequence(data)); message.setDestination(destination); message.setMessageId(new MessageId(id.generateId() + ":1", i)); getMessageStore().addMessage(context, message); } } protected abstract MessageStore getMessageStore(); }
923bc96571ec0c934f94e9ed563dd7e3633bc924
592
java
Java
src/test/java/uk/gov/ons/census/fwmt/rmadapter/utils/UtilityMethods.java
ONSdigital/census-fwmt-rm-adapter
5e92d612915a0ff91990e8d9a34c3da63dc6601c
[ "MIT" ]
null
null
null
src/test/java/uk/gov/ons/census/fwmt/rmadapter/utils/UtilityMethods.java
ONSdigital/census-fwmt-rm-adapter
5e92d612915a0ff91990e8d9a34c3da63dc6601c
[ "MIT" ]
56
2019-02-28T19:47:54.000Z
2020-01-30T15:54:42.000Z
src/test/java/uk/gov/ons/census/fwmt/rmadapter/utils/UtilityMethods.java
ONSdigital/fwmt-census-rm-adapter
5e92d612915a0ff91990e8d9a34c3da63dc6601c
[ "MIT" ]
1
2021-04-11T08:01:12.000Z
2021-04-11T08:01:12.000Z
34.823529
105
0.837838
999,723
package uk.gov.ons.census.fwmt.rmadapter.utils; import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.XMLGregorianCalendar; import java.util.GregorianCalendar; public final class UtilityMethods { public static XMLGregorianCalendar getXMLGregorianCalendarNow() throws DatatypeConfigurationException { GregorianCalendar gregorianCalendar = new GregorianCalendar(); DatatypeFactory datatypeFactory = DatatypeFactory.newInstance(); return datatypeFactory.newXMLGregorianCalendar(gregorianCalendar); } }
923bca5437a8968462ebe3133080ae6e37babaff
346
java
Java
feihua-framework-cms-service/feihua-framework-cms-service-impl/src/main/java/com/feihua/framework/cms/mapper/CmsContentDownloadPoMapper.java
feihua666/feihua-framework
fd3e69e159e9c4073833a1efeac929cc6848437b
[ "MIT" ]
2
2019-06-05T09:58:09.000Z
2021-09-17T13:12:36.000Z
feihua-framework-cms-service/feihua-framework-cms-service-impl/src/main/java/com/feihua/framework/cms/mapper/CmsContentDownloadPoMapper.java
revolvernn/feihua-framework
0a6fc6e283799fef18fcb97ebe080a2f19a6db0d
[ "MIT" ]
4
2019-11-13T06:31:13.000Z
2021-01-20T23:14:41.000Z
feihua-framework-cms-service/feihua-framework-cms-service-impl/src/main/java/com/feihua/framework/cms/mapper/CmsContentDownloadPoMapper.java
revolvernn/feihua-framework
0a6fc6e283799fef18fcb97ebe080a2f19a6db0d
[ "MIT" ]
5
2018-08-25T08:05:02.000Z
2022-01-06T01:52:36.000Z
31.454545
111
0.794798
999,724
package com.feihua.framework.cms.mapper; import com.feihua.framework.cms.po.CmsContentDownloadPo; import feihua.jdbc.api.dao.CrudDao; /** * This class was generated by MyBatis Generator. * @author yangwei 2018-12-12 12:28:18 */ public interface CmsContentDownloadPoMapper extends feihua.jdbc.api.dao.CrudDao<CmsContentDownloadPo, String> { }
923bcaeb655384540ae9eefc75cfc6ea6b604e58
5,750
java
Java
src/main/java/io/objects/tl/api/request/TLRequestInitConnection.java
shahrivari/tlobjects
154f77c4cbe3ac8a64043ec6688f9e33077aa191
[ "MIT" ]
1
2019-07-23T11:00:47.000Z
2019-07-23T11:00:47.000Z
src/main/java/io/objects/tl/api/request/TLRequestInitConnection.java
shahrivari/tlobjects
154f77c4cbe3ac8a64043ec6688f9e33077aa191
[ "MIT" ]
2
2020-03-04T23:25:48.000Z
2021-01-21T00:16:40.000Z
src/main/java/io/objects/tl/api/request/TLRequestInitConnection.java
shahrivari/tlobjects
154f77c4cbe3ac8a64043ec6688f9e33077aa191
[ "MIT" ]
8
2019-07-30T15:51:32.000Z
2021-01-15T17:03:26.000Z
27.380952
133
0.658609
999,725
package io.objects.tl.api.request; import static io.objects.tl.StreamUtils.*; import static io.objects.tl.TLObjectUtils.*; import io.objects.tl.TLContext; import io.objects.tl.api.TLInputClientProxy; import io.objects.tl.core.TLMethod; import io.objects.tl.core.TLObject; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.Override; import java.lang.String; import java.lang.SuppressWarnings; /** * This class is generated by Mono's TL class generator */ public class TLRequestInitConnection<T extends TLObject> extends TLMethod<T> { public static final int CONSTRUCTOR_ID = 0x785188b8; protected int flags; protected int apiId; protected String deviceModel; protected String systemVersion; protected String appVersion; protected String systemLangCode; protected String langPack; protected String langCode; protected TLInputClientProxy proxy; protected TLMethod<T> query; private final String _constructor = "initConnection#785188b8"; public TLRequestInitConnection() { } public TLRequestInitConnection(int apiId, String deviceModel, String systemVersion, String appVersion, String systemLangCode, String langPack, String langCode, TLInputClientProxy proxy, TLMethod<T> query) { this.apiId = apiId; this.deviceModel = deviceModel; this.systemVersion = systemVersion; this.appVersion = appVersion; this.systemLangCode = systemLangCode; this.langPack = langPack; this.langCode = langCode; this.proxy = proxy; this.query = query; } @Override @SuppressWarnings({"unchecked", "SimplifiableConditionalExpression"}) public T deserializeResponse(InputStream stream, TLContext context) throws IOException { return query.deserializeResponse(stream, context); } private void computeFlags() { flags = 0; flags = proxy != null ? (flags | 1) : (flags & ~1); } @Override public void serializeBody(OutputStream stream) throws IOException { computeFlags(); writeInt(flags, stream); writeInt(apiId, stream); writeString(deviceModel, stream); writeString(systemVersion, stream); writeString(appVersion, stream); writeString(systemLangCode, stream); writeString(langPack, stream); writeString(langCode, stream); if ((flags & 1) != 0) { if (proxy == null) throwNullFieldException("proxy", flags); writeTLObject(proxy, stream); } writeTLMethod(query, stream); } @Override @SuppressWarnings({"unchecked", "SimplifiableConditionalExpression"}) public void deserializeBody(InputStream stream, TLContext context) throws IOException { flags = readInt(stream); apiId = readInt(stream); deviceModel = readTLString(stream); systemVersion = readTLString(stream); appVersion = readTLString(stream); systemLangCode = readTLString(stream); langPack = readTLString(stream); langCode = readTLString(stream); proxy = (flags & 1) != 0 ? readTLObject(stream, context, TLInputClientProxy.class, TLInputClientProxy.CONSTRUCTOR_ID) : null; query = readTLMethod(stream, context); } @Override public int computeSerializedSize() { computeFlags(); int size = SIZE_CONSTRUCTOR_ID; size += SIZE_INT32; size += SIZE_INT32; size += computeTLStringSerializedSize(deviceModel); size += computeTLStringSerializedSize(systemVersion); size += computeTLStringSerializedSize(appVersion); size += computeTLStringSerializedSize(systemLangCode); size += computeTLStringSerializedSize(langPack); size += computeTLStringSerializedSize(langCode); if ((flags & 1) != 0) { if (proxy == null) throwNullFieldException("proxy", flags); size += proxy.computeSerializedSize(); } size += query.computeSerializedSize(); return size; } @Override public String toString() { return _constructor; } @Override public int getConstructorId() { return CONSTRUCTOR_ID; } public int getApiId() { return apiId; } public void setApiId(int apiId) { this.apiId = apiId; } public String getDeviceModel() { return deviceModel; } public void setDeviceModel(String deviceModel) { this.deviceModel = deviceModel; } public String getSystemVersion() { return systemVersion; } public void setSystemVersion(String systemVersion) { this.systemVersion = systemVersion; } public String getAppVersion() { return appVersion; } public void setAppVersion(String appVersion) { this.appVersion = appVersion; } public String getSystemLangCode() { return systemLangCode; } public void setSystemLangCode(String systemLangCode) { this.systemLangCode = systemLangCode; } public String getLangPack() { return langPack; } public void setLangPack(String langPack) { this.langPack = langPack; } public String getLangCode() { return langCode; } public void setLangCode(String langCode) { this.langCode = langCode; } public TLInputClientProxy getProxy() { return proxy; } public void setProxy(TLInputClientProxy proxy) { this.proxy = proxy; } public TLMethod<T> getQuery() { return query; } public void setQuery(TLMethod<T> query) { this.query = query; } }
923bcbc08f107c7a3120a0cb993fdc066069b6f1
14,167
java
Java
src/java/com/euronext/optiq/dd/MarketUpdateEncoder.java
PeregrineTradersDevTeam/md-data-reader-euronext
ecef156b50defb24e64cc3bbabf6b26071ed05d7
[ "MIT" ]
3
2020-01-08T09:44:52.000Z
2022-03-02T02:16:24.000Z
src/java/com/euronext/optiq/dd/MarketUpdateEncoder.java
PeregrineTradersDevTeam/md-data-reader-euronext
ecef156b50defb24e64cc3bbabf6b26071ed05d7
[ "MIT" ]
null
null
null
src/java/com/euronext/optiq/dd/MarketUpdateEncoder.java
PeregrineTradersDevTeam/md-data-reader-euronext
ecef156b50defb24e64cc3bbabf6b26071ed05d7
[ "MIT" ]
1
2020-05-09T06:31:38.000Z
2020-05-09T06:31:38.000Z
21.964341
101
0.546905
999,726
/* Generated SBE (Simple Binary Encoding) message codec */ package com.euronext.optiq.dd; import org.agrona.MutableDirectBuffer; import org.agrona.DirectBuffer; @SuppressWarnings("all") public class MarketUpdateEncoder { public static final int BLOCK_LENGTH = 18; public static final int TEMPLATE_ID = 1001; public static final int SCHEMA_ID = 0; public static final int SCHEMA_VERSION = 105; public static final java.nio.ByteOrder BYTE_ORDER = java.nio.ByteOrder.LITTLE_ENDIAN; private final MarketUpdateEncoder parentMessage = this; private MutableDirectBuffer buffer; protected int offset; protected int limit; public int sbeBlockLength() { return BLOCK_LENGTH; } public int sbeTemplateId() { return TEMPLATE_ID; } public int sbeSchemaId() { return SCHEMA_ID; } public int sbeSchemaVersion() { return SCHEMA_VERSION; } public String sbeSemanticType() { return ""; } public MutableDirectBuffer buffer() { return buffer; } public int offset() { return offset; } public MarketUpdateEncoder wrap(final MutableDirectBuffer buffer, final int offset) { if (buffer != this.buffer) { this.buffer = buffer; } this.offset = offset; limit(offset + BLOCK_LENGTH); return this; } public MarketUpdateEncoder wrapAndApplyHeader( final MutableDirectBuffer buffer, final int offset, final MessageHeaderEncoder headerEncoder) { headerEncoder .wrap(buffer, offset) .blockLength(BLOCK_LENGTH) .templateId(TEMPLATE_ID) .schemaId(SCHEMA_ID) .version(SCHEMA_VERSION); return wrap(buffer, offset + MessageHeaderEncoder.ENCODED_LENGTH); } public int encodedLength() { return limit - offset; } public int limit() { return limit; } public void limit(final int limit) { this.limit = limit; } public static int mDSeqNumId() { return 1; } public static int mDSeqNumSinceVersion() { return 0; } public static int mDSeqNumEncodingOffset() { return 0; } public static int mDSeqNumEncodingLength() { return 8; } public static String mDSeqNumMetaAttribute(final MetaAttribute metaAttribute) { switch (metaAttribute) { case EPOCH: return ""; case TIME_UNIT: return ""; case SEMANTIC_TYPE: return ""; case PRESENCE: return "optional"; } return ""; } public static long mDSeqNumNullValue() { return 0xffffffffffffffffL; } public static long mDSeqNumMinValue() { return 0x0L; } public static long mDSeqNumMaxValue() { return 0xfffffffffffffffeL; } public MarketUpdateEncoder mDSeqNum(final long value) { buffer.putLong(offset + 0, value, java.nio.ByteOrder.LITTLE_ENDIAN); return this; } public static int rebroadcastIndicatorId() { return 2; } public static int rebroadcastIndicatorSinceVersion() { return 0; } public static int rebroadcastIndicatorEncodingOffset() { return 8; } public static int rebroadcastIndicatorEncodingLength() { return 1; } public static String rebroadcastIndicatorMetaAttribute(final MetaAttribute metaAttribute) { switch (metaAttribute) { case EPOCH: return ""; case TIME_UNIT: return ""; case SEMANTIC_TYPE: return ""; case PRESENCE: return "optional"; } return ""; } public static short rebroadcastIndicatorNullValue() { return (short)255; } public static short rebroadcastIndicatorMinValue() { return (short)0; } public static short rebroadcastIndicatorMaxValue() { return (short)254; } public MarketUpdateEncoder rebroadcastIndicator(final short value) { buffer.putByte(offset + 8, (byte)value); return this; } public static int eMMId() { return 3; } public static int eMMSinceVersion() { return 0; } public static int eMMEncodingOffset() { return 9; } public static int eMMEncodingLength() { return 1; } public static String eMMMetaAttribute(final MetaAttribute metaAttribute) { switch (metaAttribute) { case EPOCH: return ""; case TIME_UNIT: return ""; case SEMANTIC_TYPE: return ""; case PRESENCE: return "required"; } return ""; } public MarketUpdateEncoder eMM(final EMM_enum value) { buffer.putByte(offset + 9, (byte)value.value()); return this; } public static int eventTimeId() { return 4; } public static int eventTimeSinceVersion() { return 0; } public static int eventTimeEncodingOffset() { return 10; } public static int eventTimeEncodingLength() { return 8; } public static String eventTimeMetaAttribute(final MetaAttribute metaAttribute) { switch (metaAttribute) { case EPOCH: return ""; case TIME_UNIT: return ""; case SEMANTIC_TYPE: return ""; case PRESENCE: return "optional"; } return ""; } public static long eventTimeNullValue() { return 0xffffffffffffffffL; } public static long eventTimeMinValue() { return 0x0L; } public static long eventTimeMaxValue() { return 0xfffffffffffffffeL; } public MarketUpdateEncoder eventTime(final long value) { buffer.putLong(offset + 10, value, java.nio.ByteOrder.LITTLE_ENDIAN); return this; } private final UpdatesEncoder updates = new UpdatesEncoder(this); public static long updatesId() { return 5; } public UpdatesEncoder updatesCount(final int count) { updates.wrap(buffer, count); return updates; } public static class UpdatesEncoder { public static final int HEADER_SIZE = 2; private final MarketUpdateEncoder parentMessage; private MutableDirectBuffer buffer; private int count; private int index; private int offset; UpdatesEncoder(final MarketUpdateEncoder parentMessage) { this.parentMessage = parentMessage; } public void wrap(final MutableDirectBuffer buffer, final int count) { if (count < 0 || count > 254) { throw new IllegalArgumentException("count outside allowed range: count=" + count); } if (buffer != this.buffer) { this.buffer = buffer; } index = -1; this.count = count; final int limit = parentMessage.limit(); parentMessage.limit(limit + HEADER_SIZE); buffer.putByte(limit + 0, (byte)(short)23); buffer.putByte(limit + 1, (byte)(short)count); } public static int sbeHeaderSize() { return HEADER_SIZE; } public static int sbeBlockLength() { return 23; } public UpdatesEncoder next() { if (index + 1 >= count) { throw new java.util.NoSuchElementException(); } offset = parentMessage.limit(); parentMessage.limit(offset + sbeBlockLength()); ++index; return this; } public static int updateTypeId() { return 1; } public static int updateTypeSinceVersion() { return 0; } public static int updateTypeEncodingOffset() { return 0; } public static int updateTypeEncodingLength() { return 1; } public static String updateTypeMetaAttribute(final MetaAttribute metaAttribute) { switch (metaAttribute) { case EPOCH: return ""; case TIME_UNIT: return ""; case SEMANTIC_TYPE: return ""; case PRESENCE: return "required"; } return ""; } public UpdatesEncoder updateType(final MarketDataUpdateType_enum value) { buffer.putByte(offset + 0, (byte)value.value()); return this; } public static int symbolIndexId() { return 2; } public static int symbolIndexSinceVersion() { return 0; } public static int symbolIndexEncodingOffset() { return 1; } public static int symbolIndexEncodingLength() { return 4; } public static String symbolIndexMetaAttribute(final MetaAttribute metaAttribute) { switch (metaAttribute) { case EPOCH: return ""; case TIME_UNIT: return ""; case SEMANTIC_TYPE: return ""; case PRESENCE: return "optional"; } return ""; } public static long symbolIndexNullValue() { return 4294967295L; } public static long symbolIndexMinValue() { return 0L; } public static long symbolIndexMaxValue() { return 4294967294L; } public UpdatesEncoder symbolIndex(final long value) { buffer.putInt(offset + 1, (int)value, java.nio.ByteOrder.LITTLE_ENDIAN); return this; } public static int numberOfOrdersId() { return 3; } public static int numberOfOrdersSinceVersion() { return 0; } public static int numberOfOrdersEncodingOffset() { return 5; } public static int numberOfOrdersEncodingLength() { return 2; } public static String numberOfOrdersMetaAttribute(final MetaAttribute metaAttribute) { switch (metaAttribute) { case EPOCH: return ""; case TIME_UNIT: return ""; case SEMANTIC_TYPE: return ""; case PRESENCE: return "optional"; } return ""; } public static int numberOfOrdersNullValue() { return 65535; } public static int numberOfOrdersMinValue() { return 0; } public static int numberOfOrdersMaxValue() { return 65534; } public UpdatesEncoder numberOfOrders(final int value) { buffer.putShort(offset + 5, (short)value, java.nio.ByteOrder.LITTLE_ENDIAN); return this; } public static int priceId() { return 4; } public static int priceSinceVersion() { return 0; } public static int priceEncodingOffset() { return 7; } public static int priceEncodingLength() { return 8; } public static String priceMetaAttribute(final MetaAttribute metaAttribute) { switch (metaAttribute) { case EPOCH: return ""; case TIME_UNIT: return ""; case SEMANTIC_TYPE: return ""; case PRESENCE: return "optional"; } return ""; } public static long priceNullValue() { return -9223372036854775808L; } public static long priceMinValue() { return -9223372036854775807L; } public static long priceMaxValue() { return 9223372036854775807L; } public UpdatesEncoder price(final long value) { buffer.putLong(offset + 7, value, java.nio.ByteOrder.LITTLE_ENDIAN); return this; } public static int quantityId() { return 5; } public static int quantitySinceVersion() { return 0; } public static int quantityEncodingOffset() { return 15; } public static int quantityEncodingLength() { return 8; } public static String quantityMetaAttribute(final MetaAttribute metaAttribute) { switch (metaAttribute) { case EPOCH: return ""; case TIME_UNIT: return ""; case SEMANTIC_TYPE: return ""; case PRESENCE: return "optional"; } return ""; } public static long quantityNullValue() { return 0xffffffffffffffffL; } public static long quantityMinValue() { return 0x0L; } public static long quantityMaxValue() { return 0xfffffffffffffffeL; } public UpdatesEncoder quantity(final long value) { buffer.putLong(offset + 15, value, java.nio.ByteOrder.LITTLE_ENDIAN); return this; } } public String toString() { return appendTo(new StringBuilder(100)).toString(); } public StringBuilder appendTo(final StringBuilder builder) { MarketUpdateDecoder writer = new MarketUpdateDecoder(); writer.wrap(buffer, offset, BLOCK_LENGTH, SCHEMA_VERSION); return writer.appendTo(builder); } }
923bcbec29e77063f79187eea37b0360b8d5e501
1,632
java
Java
tmc-intellij/tmc-plugin-intellij/src/main/java/fi/helsinki/cs/tmc/intellij/services/ExerciseCheckBoxService.java
ivospijkerman/tmc-intellij
e674196ec7ff1fc0a073e06afab5542a27b64768
[ "MIT" ]
25
2016-11-08T17:25:30.000Z
2022-01-24T15:57:05.000Z
tmc-intellij/tmc-plugin-intellij/src/main/java/fi/helsinki/cs/tmc/intellij/services/ExerciseCheckBoxService.java
ivospijkerman/tmc-intellij
e674196ec7ff1fc0a073e06afab5542a27b64768
[ "MIT" ]
61
2016-09-23T18:29:55.000Z
2022-01-03T10:12:01.000Z
tmc-intellij/tmc-plugin-intellij/src/main/java/fi/helsinki/cs/tmc/intellij/services/ExerciseCheckBoxService.java
ivospijkerman/tmc-intellij
e674196ec7ff1fc0a073e06afab5542a27b64768
[ "MIT" ]
23
2016-11-28T19:24:36.000Z
2022-01-25T14:54:45.000Z
30.222222
100
0.591912
999,727
package fi.helsinki.cs.tmc.intellij.services; import fi.helsinki.cs.tmc.core.domain.Exercise; import fi.helsinki.cs.tmc.intellij.ui.exercisedownloadlist.CustomCheckBoxList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; import javax.swing.JCheckBox; public class ExerciseCheckBoxService { private static final Logger logger = LoggerFactory.getLogger(ExerciseCheckBoxService.class); public static List<Exercise> filterDownloads( CustomCheckBoxList checkBoxes, List<Exercise> exercises) { logger.info("Filtering exercises. @ExerciseCheckBoxService"); List<Exercise> downloadThese = new ArrayList<>(); for (JCheckBox box : checkBoxes) { if (box.isSelected()) { for (Exercise ex : exercises) { if (box.getText().equals(ex.getName())) { downloadThese.add(ex); } } } } return downloadThese; } public static void toggleAllCheckBoxes(CustomCheckBoxList exerciselist) { logger.info( "Toggling all exercise check boxes checked or unchecked. @ExerciseCheckBoxService"); int checked = 0; int all = 0; for (JCheckBox box : exerciselist) { all++; if (box.isSelected()) { checked++; } box.setSelected(true); } if (all == checked) { for (JCheckBox box : exerciselist) { box.setSelected(false); } } } }
923bcc49cea9b313355afa8e9121b999aba67f36
4,243
java
Java
src/Eclipse-IDE/org.robotframework.ide.eclipse.main.plugin.tests/src/org/robotframework/ide/eclipse/main/plugin/launch/local/RobotLaunchConfigurationDelegateTest.java
polusaleksandra/RED
f071c56faed86da97ce5a32919c961f177210684
[ "Apache-2.0" ]
null
null
null
src/Eclipse-IDE/org.robotframework.ide.eclipse.main.plugin.tests/src/org/robotframework/ide/eclipse/main/plugin/launch/local/RobotLaunchConfigurationDelegateTest.java
polusaleksandra/RED
f071c56faed86da97ce5a32919c961f177210684
[ "Apache-2.0" ]
null
null
null
src/Eclipse-IDE/org.robotframework.ide.eclipse.main.plugin.tests/src/org/robotframework/ide/eclipse/main/plugin/launch/local/RobotLaunchConfigurationDelegateTest.java
polusaleksandra/RED
f071c56faed86da97ce5a32919c961f177210684
[ "Apache-2.0" ]
null
null
null
48.770115
116
0.751827
999,728
/* * Copyright 2017 Nokia Solutions and Networks * Licensed under the Apache License, Version 2.0, * see license.txt file for details. */ package org.robotframework.ide.eclipse.main.plugin.launch.local; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import org.eclipse.core.runtime.CoreException; import org.eclipse.debug.core.ILaunchConfiguration; import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy; import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; import org.rf.ide.core.environment.SuiteExecutor; import org.robotframework.ide.eclipse.main.plugin.launch.local.RobotLaunchConfigurationDelegate.ConsoleData; import org.robotframework.red.junit.ProjectProvider; import org.robotframework.red.junit.RunConfigurationProvider; public class RobotLaunchConfigurationDelegateTest { private static final String PROJECT_NAME = RobotLaunchConfigurationDelegateTest.class.getSimpleName(); @ClassRule public static ProjectProvider projectProvider = new ProjectProvider(PROJECT_NAME); @Rule public RunConfigurationProvider runConfigurationProvider = new RunConfigurationProvider( RobotLaunchConfiguration.TYPE_ID); @Test() public void pathToExecutableAndUnknownRobotVersionAreUsed_whenPathToExecutableIsSet() throws Exception { final RobotLaunchConfiguration robotConfig = createRobotLaunchConfiguration(PROJECT_NAME); robotConfig.setExecutableFilePath("some/path/to/script"); final ConsoleData consoleData = RobotLaunchConfigurationDelegate.ConsoleData.create(robotConfig, new LocalProcessInterpreter(SuiteExecutor.Python, "some/path/to/python", "RF 1.2.3")); assertThat(consoleData.getProcessLabel()).isEqualTo("some/path/to/script"); assertThat(consoleData.getSuiteExecutorVersion()).isEqualTo("<unknown>"); } @Test() public void pathToPythonAndKnownRobotVersionAreUsed_whenPathToExecutableIsNotSet() throws Exception { final RobotLaunchConfiguration robotConfig = createRobotLaunchConfiguration(PROJECT_NAME); robotConfig.setExecutableFilePath(""); final ConsoleData consoleData = RobotLaunchConfigurationDelegate.ConsoleData.create(robotConfig, new LocalProcessInterpreter(SuiteExecutor.Python, "some/path/to/python", "RF 1.2.3")); assertThat(consoleData.getProcessLabel()).isEqualTo("some/path/to/python"); assertThat(consoleData.getSuiteExecutorVersion()).isEqualTo("RF 1.2.3"); } private RobotLaunchConfiguration createRobotLaunchConfiguration(final String projectName) throws CoreException { final ILaunchConfiguration configuration = runConfigurationProvider.create("robot"); final RobotLaunchConfiguration robotConfig = new RobotLaunchConfiguration(configuration); robotConfig.fillDefaults(); robotConfig.setProjectName(projectName); return robotConfig; } @Test public void whenConfigurationVersionIsInvalid_coreExceptionIsThrown() throws Exception { final ILaunchConfiguration configuration = runConfigurationProvider.create("robot"); final RobotLaunchConfiguration robotConfig = new RobotLaunchConfiguration(configuration); robotConfig.fillDefaults(); robotConfig.setProjectName(PROJECT_NAME); final ILaunchConfigurationWorkingCopy launchCopy = configuration.getWorkingCopy(); launchCopy.setAttribute("Version of configuration", "invalid"); final RobotLaunchConfigurationDelegate launchDelegate = new RobotLaunchConfigurationDelegate(); assertThatExceptionOfType(CoreException.class) .isThrownBy(() -> launchDelegate.launch(launchCopy, "run", null, null)) .withMessage( "This configuration is incompatible with RED version you are currently using.%n" + "Expected: %s, but was: %s" + "%n%nResolution: Delete old configurations manually and create the new ones.", RobotLaunchConfiguration.CURRENT_CONFIGURATION_VERSION, "invalid") .withNoCause(); } }
923bccb2697b6b5a04ff50a6974f8d4fcdb23ca8
778
java
Java
src/main/java/io/github/synthrose/artofalchemy/blockentity/BlockEntityAstroCentrifuge.java
Neubulae/Art-of-Alchemy
d345fd02df2e79c7485df0b45c0e67c7044fdb12
[ "MIT" ]
null
null
null
src/main/java/io/github/synthrose/artofalchemy/blockentity/BlockEntityAstroCentrifuge.java
Neubulae/Art-of-Alchemy
d345fd02df2e79c7485df0b45c0e67c7044fdb12
[ "MIT" ]
null
null
null
src/main/java/io/github/synthrose/artofalchemy/blockentity/BlockEntityAstroCentrifuge.java
Neubulae/Art-of-Alchemy
d345fd02df2e79c7485df0b45c0e67c7044fdb12
[ "MIT" ]
null
null
null
45.764706
107
0.742931
999,729
package io.github.synthrose.artofalchemy.blockentity; import io.github.synthrose.artofalchemy.essentia.AoAEssentia; import io.github.synthrose.artofalchemy.essentia.EssentiaContainer; public class BlockEntityAstroCentrifuge extends AbstractBlockEntityCentrifuge { public BlockEntityAstroCentrifuge() { super(AoABlockEntities.ASTRO_CENTRIFUGE); outputs = new EssentiaContainer[]{ outputOf(AoAEssentia.MERCURY, AoAEssentia.VENUS, AoAEssentia.TELLUS, AoAEssentia.MARS), outputOf(AoAEssentia.JUPITER, AoAEssentia.SATURN, AoAEssentia.URANUS, AoAEssentia.NEPTUNE), outputOf(AoAEssentia.APOLLO, AoAEssentia.DIANA, AoAEssentia.CERES, AoAEssentia.PLUTO), outputOf(AoAEssentia.VOID) }; } }
923bccb5b31c9b9e9630a77ef999c8f3e87adbd1
457
java
Java
spring-boot-itext-generate-pdf/src/main/java/com/itext/demo/service/IBookService.java
sartorileonardo/spring-boot-demo
cea96e90d6b49dd05673fc9fd48f2feadd358710
[ "MIT" ]
13
2021-10-16T15:21:02.000Z
2022-03-23T19:49:18.000Z
spring-boot-itext-generate-pdf/src/main/java/com/itext/demo/service/IBookService.java
spfcsandro/spring-boot-demo
161f0847adf6ad9159e257160892a00576100f82
[ "MIT" ]
null
null
null
spring-boot-itext-generate-pdf/src/main/java/com/itext/demo/service/IBookService.java
spfcsandro/spring-boot-demo
161f0847adf6ad9159e257160892a00576100f82
[ "MIT" ]
null
null
null
25.388889
55
0.748359
999,730
package com.itext.demo.service; import com.itext.demo.entity.Book; import org.springframework.core.io.InputStreamResource; import java.util.List; import java.util.Optional; public interface IBookService { Book saveBook(Book book); List<Book> saveBooks(List<Book> books); void deleteBook(Integer id); void deleteBooks(); Optional<Book> getBook(Integer id); List<Book> getBooks(); InputStreamResource getContentBooksReport(); }
923bcd50ac83bf457dcf0fa560ca9b8c583b6fee
354
java
Java
src/chapter1/section3/test/Reverse.java
tongji4m3/algorithm
90745b5cfd5e7acaaf6d8c912348e9635cb3f047
[ "MIT" ]
null
null
null
src/chapter1/section3/test/Reverse.java
tongji4m3/algorithm
90745b5cfd5e7acaaf6d8c912348e9635cb3f047
[ "MIT" ]
null
null
null
src/chapter1/section3/test/Reverse.java
tongji4m3/algorithm
90745b5cfd5e7acaaf6d8c912348e9635cb3f047
[ "MIT" ]
null
null
null
22.125
51
0.533898
999,731
package chapter1.section3.test; import chapter1.section3.Stack; public class Reverse { public static void main(String[] args) { Stack<String> stack = new Stack<>(); for (String s : "1 3 4 5 7 8".split(" ")) { stack.push(s); } for (String s : stack) { System.out.println(s); } } }
923bcd84a2d5a062272b48463c58788c7e34929e
1,694
java
Java
src/main/java/github/cnkeep/loadbalance/weight/WeightNode.java
cnkeep/loadbalance-algorithm
c4ede7d630571b28ec3f718ceb45d4750220b03d
[ "Apache-2.0" ]
2
2020-12-26T05:14:07.000Z
2021-04-17T05:33:11.000Z
src/main/java/github/cnkeep/loadbalance/weight/WeightNode.java
cnkeep/loadbalance-algorithm
c4ede7d630571b28ec3f718ceb45d4750220b03d
[ "Apache-2.0" ]
null
null
null
src/main/java/github/cnkeep/loadbalance/weight/WeightNode.java
cnkeep/loadbalance-algorithm
c4ede7d630571b28ec3f718ceb45d4750220b03d
[ "Apache-2.0" ]
null
null
null
19.101124
60
0.536471
999,732
package github.cnkeep.loadbalance.weight; import github.cnkeep.loadbalance.Node; import java.util.UUID; /** * 描述: 带有权重的节点 * * @Author <a href="upchh@example.com">LeiLi.Zhang</a> * @Version 0.0.0 * @Date 2019/4/28 */ public class WeightNode implements Node<String> { /** * 配置的权重 **/ private int weight; /** * 当前的权重 **/ private int currentWeight; private String key; public WeightNode() { this(UUID.randomUUID().toString()); } public WeightNode(String key) { this(key,5); } public WeightNode(String key, int weight) { this.key = key; this.weight = weight; this.currentWeight = weight; } @Override public String getKey() { return key; } public int getWeight() { return weight; } public void setWeight(int weight) { this.weight = weight; } public int getCurrentWeight() { return currentWeight; } public void setCurrentWeight(int currentWeight) { this.currentWeight = currentWeight; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } WeightNode node = (WeightNode) o; return key.equals(node.key); } @Override public int hashCode() { return key.hashCode(); } @Override public String toString() { return "WeightNode{" + "weight=" + weight + ", currentWeight=" + currentWeight + ", key='" + key + '\'' + '}'; } }
923bce374a8776778b3c44ff4a39840190df33bd
127
java
Java
Atividades/src/OO/Polimofismo/Soverte.java
israelmessias/Atividades_Java
8dda9fe69022a216ea372f2a4909d47a5b5400cf
[ "MIT" ]
null
null
null
Atividades/src/OO/Polimofismo/Soverte.java
israelmessias/Atividades_Java
8dda9fe69022a216ea372f2a4909d47a5b5400cf
[ "MIT" ]
null
null
null
Atividades/src/OO/Polimofismo/Soverte.java
israelmessias/Atividades_Java
8dda9fe69022a216ea372f2a4909d47a5b5400cf
[ "MIT" ]
null
null
null
12.7
36
0.653543
999,733
package OO.Polimofismo; public class Soverte extends Comida{ public Soverte(double peso){ super(peso); } }
923bcf2fff885872e6ebd3c92e8d275d920a8501
1,484
java
Java
src/main/java/com/dyn/robot/network/messages/MessageRobotError.java
CityOfLearning/Robot
d6e971472afe785eebcfd98f1ffa08d95fee8e56
[ "MIT" ]
7
2018-05-23T15:22:38.000Z
2021-05-25T07:36:38.000Z
src/main/java/com/dyn/robot/network/messages/MessageRobotError.java
CityOfLearning/Robot
d6e971472afe785eebcfd98f1ffa08d95fee8e56
[ "MIT" ]
4
2018-05-16T19:39:22.000Z
2018-07-16T06:12:44.000Z
src/main/java/com/dyn/robot/network/messages/MessageRobotError.java
CityOfLearning/Robot
d6e971472afe785eebcfd98f1ffa08d95fee8e56
[ "MIT" ]
4
2019-10-09T17:46:30.000Z
2021-05-25T07:18:49.000Z
23.1875
96
0.753369
999,734
package com.dyn.robot.network.messages; import com.dyn.robot.RobotMod; import io.netty.buffer.ByteBuf; import net.minecraftforge.fml.common.network.ByteBufUtils; import net.minecraftforge.fml.common.network.simpleimpl.IMessage; import net.minecraftforge.fml.common.network.simpleimpl.IMessageHandler; import net.minecraftforge.fml.common.network.simpleimpl.MessageContext; public class MessageRobotError implements IMessage { public static class Handler implements IMessageHandler<MessageRobotError, IMessage> { @Override public IMessage onMessage(MessageRobotError message, MessageContext ctx) { RobotMod.proxy.addScheduledTask(() -> { RobotMod.proxy.handleErrorMessage(message.getError(), message.getCode(), message.getLine()); }); return null; } } private String code; private String error; private int line; public MessageRobotError() { } public MessageRobotError(String code, String error, int line, int robotid) { this.code = code; this.error = error; this.line = line; } @Override public void fromBytes(ByteBuf buf) { code = ByteBufUtils.readUTF8String(buf); error = ByteBufUtils.readUTF8String(buf); line = buf.readInt(); } public String getCode() { return code; } public String getError() { return error; } public int getLine() { return line; } @Override public void toBytes(ByteBuf buf) { ByteBufUtils.writeUTF8String(buf, code); ByteBufUtils.writeUTF8String(buf, error); buf.writeInt(line); } }
923bd1a282d46d442c70f354f58acbf3a98fd5f8
2,396
java
Java
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/inspiratie_si_teste/autonomtest_senzorculoare.java
Vlad20405/Cod_Robotica_2021-22
aa659c008e0f3087960f1612270dd0ec08f4b65b
[ "MIT" ]
null
null
null
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/inspiratie_si_teste/autonomtest_senzorculoare.java
Vlad20405/Cod_Robotica_2021-22
aa659c008e0f3087960f1612270dd0ec08f4b65b
[ "MIT" ]
null
null
null
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/inspiratie_si_teste/autonomtest_senzorculoare.java
Vlad20405/Cod_Robotica_2021-22
aa659c008e0f3087960f1612270dd0ec08f4b65b
[ "MIT" ]
null
null
null
28.86747
81
0.657346
999,735
package org.firstinspires.ftc.teamcode.inspiratie_si_teste; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import com.qualcomm.robotcore.eventloop.opmode.Disabled; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.hardware.ColorSensor; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.hardware.DistanceSensor; @Autonomous(name = "testtt") @Disabled public class autonomtest_senzorculoare extends LinearOpMode { ColorSensor sensorColor; DistanceSensor sensorDistance; // declararea motoarelor private DcMotor Stanga_f = null; private DcMotor Stanga_s = null; private DcMotor Dreapta_f = null; private DcMotor Dreapta_s = null; int contor = 0; @Override public void runOpMode() { sensorColor = hardwareMap.get(ColorSensor.class, "senzorCuloare"); sensorDistance = hardwareMap.get(DistanceSensor.class, "senzorDistanta"); Stanga_f = hardwareMap.get(DcMotor.class, "Stanga_f"); Stanga_s = hardwareMap.get(DcMotor.class, "Stanga_s"); Dreapta_f = hardwareMap.get(DcMotor.class, "Dreapta_f"); Dreapta_s = hardwareMap.get(DcMotor.class, "Dreapta_s"); Stanga_f.setDirection(DcMotor.Direction.FORWARD); Stanga_s.setDirection(DcMotor.Direction.FORWARD); Dreapta_f.setDirection(DcMotor.Direction.REVERSE); Dreapta_s.setDirection(DcMotor.Direction.REVERSE); waitForStart(); sensorColor.enableLed(false); sensorColor.enableLed(true); Stanga_f.setPower(1); Stanga_s.setPower(1); Dreapta_f.setPower(1); Dreapta_s.setPower(1); while (sensorColor.red() < 150 && contor == 0) { contor++; Stanga_f.setPower(0.5); Stanga_s.setPower(0.5); Dreapta_f.setPower(0.5); Dreapta_s.setPower(0.5); } while (sensorColor.red() < 150 && contor == 1) { Stanga_f.setPower(0); Stanga_s.setPower(0); Dreapta_f.setPower(0); Dreapta_s.setPower(0); } Stanga_f.setPower(0); Stanga_s.setPower(0); Dreapta_f.setPower(0); Dreapta_s.setPower(0); while (opModeIsActive()) { telemetry.addData("ARGB", sensorColor.argb()); telemetry.update(); } } }
923bd2348a20102f160640cf2680b1b6655b0974
11,275
java
Java
snomed/com.b2international.snowowl.snomed.core.rest.tests/src/com/b2international/snowowl/snomed/core/rest/ext/SnomedComponentEffectiveTimeRestoreTest.java
kalufya/snow-owl
538fe7eaa3e9a8f5f2b712ddaea08b525d9744c3
[ "Apache-2.0" ]
259
2017-02-03T16:33:21.000Z
2022-03-31T09:51:25.000Z
snomed/com.b2international.snowowl.snomed.core.rest.tests/src/com/b2international/snowowl/snomed/core/rest/ext/SnomedComponentEffectiveTimeRestoreTest.java
kalufya/snow-owl
538fe7eaa3e9a8f5f2b712ddaea08b525d9744c3
[ "Apache-2.0" ]
381
2017-02-17T15:07:10.000Z
2022-03-29T13:13:41.000Z
snomed/com.b2international.snowowl.snomed.core.rest.tests/src/com/b2international/snowowl/snomed/core/rest/ext/SnomedComponentEffectiveTimeRestoreTest.java
kalufya/snow-owl
538fe7eaa3e9a8f5f2b712ddaea08b525d9744c3
[ "Apache-2.0" ]
25
2017-02-08T10:00:16.000Z
2022-02-21T10:58:49.000Z
48.809524
176
0.794501
999,736
/* * Copyright 2020-2021 B2i Healthcare Pte Ltd, http://b2i.sg * * 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.b2international.snowowl.snomed.core.rest.ext; import static com.b2international.snowowl.snomed.core.rest.SnomedComponentRestRequests.getComponent; import static com.b2international.snowowl.snomed.core.rest.SnomedRestFixtures.createNewConcept; import static com.b2international.snowowl.snomed.core.rest.SnomedRestFixtures.inactivateConcept; import static com.b2international.snowowl.snomed.core.rest.SnomedRestFixtures.reactivateConcept; import static com.b2international.snowowl.test.commons.codesystem.CodeSystemRestRequests.createCodeSystem; import static com.b2international.snowowl.test.commons.codesystem.CodeSystemVersionRestRequests.createVersion; import static com.b2international.snowowl.test.commons.codesystem.CodeSystemVersionRestRequests.getNextAvailableEffectiveDate; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.nullValue; import static org.junit.Assert.assertEquals; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.Map; import org.junit.Test; import com.b2international.snowowl.core.ResourceURI; import com.b2international.snowowl.core.codesystem.CodeSystem; import com.b2international.snowowl.core.date.EffectiveTimes; import com.b2international.snowowl.snomed.common.SnomedConstants.Concepts; import com.b2international.snowowl.snomed.core.domain.SnomedConcept; import com.b2international.snowowl.snomed.core.rest.SnomedComponentType; import com.b2international.snowowl.test.commons.SnomedContentRule; /** * @since 7.14 */ public class SnomedComponentEffectiveTimeRestoreTest extends AbstractSnomedExtensionApiTest { private static final String EXT_UPGRADE_SI_VERSION = "2020-01-31"; private static final String EXT_VERSION = "2019-10-31"; private final ResourceURI upgradeInternationalCodeSystem = SnomedContentRule.SNOMEDCT.withPath(EXT_UPGRADE_SI_VERSION); @Test public void restoreEffectiveTimeOnReleasedConcept() throws Exception { String conceptId = createNewConcept(branchPath); String shortName = "SNOMEDCT-CON-1"; createCodeSystem(branchPath, shortName).statusCode(201); LocalDate effectiveDate = getNextAvailableEffectiveDate(shortName); createVersion(shortName, "v1", effectiveDate).statusCode(201); // After versioning, the concept should be released and have an effective time set on it getComponent(branchPath, SnomedComponentType.CONCEPT, conceptId).statusCode(200) .body("active", equalTo(true)) .body("released", equalTo(true)) .body("effectiveTime", equalTo(effectiveDate.format(DateTimeFormatter.BASIC_ISO_DATE))); inactivateConcept(branchPath, conceptId); // An inactivation should unset the effective time field getComponent(branchPath, SnomedComponentType.CONCEPT, conceptId).statusCode(200) .body("active", equalTo(false)) .body("released", equalTo(true)) .body("effectiveTime", nullValue()); reactivateConcept(branchPath, conceptId); // Getting the concept back to its originally released state should restore the effective time getComponent(branchPath, SnomedComponentType.CONCEPT, conceptId).statusCode(200) .body("active", equalTo(true)) .body("released", equalTo(true)) .body("effectiveTime", equalTo(effectiveDate.format(DateTimeFormatter.BASIC_ISO_DATE))); } @Test public void restoreExtensionEffectiveTimeOnExtension() throws Exception { // create extension on the base SI VERSION final CodeSystem extension = createExtension(baseInternationalCodeSystem, branchPath.lastSegment()); // create the module to represent the extension String moduleId = createModule(extension); // create an extension version, concept receives effective time createVersion(extension.getId(), EXT_VERSION, LocalDate.parse("2019-10-31")) .statusCode(201); SnomedConcept concept = getConcept(extension.getResourceURI(), moduleId); assertEquals(EffectiveTimes.parse(EXT_VERSION), concept.getEffectiveTime()); // create a change on the concept, like change the definition status updateConcept(extension.getResourceURI(), moduleId, Map.of( "definitionStatusId", Concepts.FULLY_DEFINED )); concept = getConcept(extension.getResourceURI(), moduleId); assertEquals(null, concept.getEffectiveTime()); // revert the change, so it reverts the effective time to the EXT_VER effective time updateConcept(extension.getResourceURI(), moduleId, Map.of( "definitionStatusId", Concepts.PRIMITIVE )); concept = getConcept(extension.getResourceURI(), moduleId); assertEquals(EffectiveTimes.parse(EXT_VERSION), concept.getEffectiveTime()); } @Test public void restoreInternationalEffectiveTimeOnExtension() throws Exception { // create extension on the base SI VERSION CodeSystem extension = createExtension(baseInternationalCodeSystem, branchPath.lastSegment()); // get the first concept from the Base SI version SnomedConcept concept = searchConcepts(baseInternationalCodeSystem, Map.of("module", Concepts.MODULE_SCT_CORE), 1).stream().findFirst().get(); LocalDate lastReleasedEffectiveTime = concept.getEffectiveTime(); String conceptId = concept.getId(); // create a change on the concept, like change the definition status updateConcept(extension.getResourceURI(), concept.getId(), Map.of( "definitionStatusId", Concepts.FULLY_DEFINED )); concept = getConcept(extension.getResourceURI(), conceptId); assertEquals(null, concept.getEffectiveTime()); // revert the change, so it reverts the effective time to the EXT_VER effective time updateConcept(extension.getResourceURI(), conceptId, Map.of( "definitionStatusId", Concepts.PRIMITIVE )); concept = getConcept(extension.getResourceURI(), conceptId); assertEquals(lastReleasedEffectiveTime, concept.getEffectiveTime()); } @Test public void restoreInternationalEffectiveTimeOnExtensionUpgrade() throws Exception { // create extension on the base SI VERSION CodeSystem extension = createExtension(baseInternationalCodeSystem, branchPath.lastSegment()); // start the extension upgrade process CodeSystem upgradeCodeSystem = createExtensionUpgrade(extension.getResourceURI(), upgradeInternationalCodeSystem); // get the first concept from the Base SI version SnomedConcept concept = searchConcepts(upgradeInternationalCodeSystem, Map.of("module", Concepts.MODULE_SCT_CORE, "effectiveTime", "20200131"), 1).stream().findFirst().get(); LocalDate lastReleasedEffectiveTime = concept.getEffectiveTime(); String conceptId = concept.getId(); // create a change on the concept, like change the definition status updateConcept(upgradeCodeSystem.getResourceURI(), concept.getId(), Map.of( "moduleId", Concepts.MODULE_SCT_MODEL_COMPONENT )); concept = getConcept(upgradeCodeSystem.getResourceURI(), conceptId); assertEquals(null, concept.getEffectiveTime()); // revert the change, so it reverts the effective time to the EXT_VER effective time updateConcept(upgradeCodeSystem.getResourceURI(), conceptId, Map.of( "moduleId", Concepts.MODULE_SCT_CORE )); concept = getConcept(upgradeCodeSystem.getResourceURI(), conceptId); assertEquals(lastReleasedEffectiveTime, concept.getEffectiveTime()); } @Test public void restoreExtensionEffectiveTimeOnExtensionUpgrade() throws Exception { // create extension on the base SI VERSION final CodeSystem extension = createExtension(baseInternationalCodeSystem, branchPath.lastSegment()); // create the module concept to represent the extension String moduleId = createModule(extension); // create an extension version, concept receives effective time createVersion(extension.getId(), EXT_VERSION, LocalDate.parse("2019-10-31")) .statusCode(201); SnomedConcept concept = getConcept(extension.getResourceURI(), moduleId); assertEquals(EffectiveTimes.parse(EXT_VERSION), concept.getEffectiveTime()); // start the extension upgrade process CodeSystem upgradeCodeSystem = createExtensionUpgrade(extension.getResourceURI(), upgradeInternationalCodeSystem); // create a change on the concept, like change the definition status updateConcept(upgradeCodeSystem.getResourceURI(), concept.getId(), Map.of( "definitionStatusId", Concepts.FULLY_DEFINED )); concept = getConcept(upgradeCodeSystem.getResourceURI(), moduleId); assertEquals(null, concept.getEffectiveTime()); // revert the change, so it reverts the effective time to the EXT_VER effective time updateConcept(upgradeCodeSystem.getResourceURI(), moduleId, Map.of( "definitionStatusId", Concepts.PRIMITIVE )); concept = getConcept(upgradeCodeSystem.getResourceURI(), moduleId); assertEquals(EffectiveTimes.parse(EXT_VERSION), concept.getEffectiveTime()); } @Test public void restoreExtensionEffectiveTimeOnExtensionVersionUpgrade() throws Exception { final String codeSystemId = branchPath.lastSegment(); // create extension on the base SI VERSION final CodeSystem extension = createExtension(baseInternationalCodeSystem, codeSystemId); // create the module concept to represent the extension String moduleId = createModule(extension); // create an extension version, concept receives effective time LocalDate effectiveTime = getNextAvailableEffectiveDate(codeSystemId); createVersion(codeSystemId, effectiveTime).statusCode(201); ResourceURI upgradeExtVersion = CodeSystem.uri(codeSystemId, effectiveTime.toString()); SnomedConcept concept = getConcept(extension.getResourceURI(), moduleId); assertEquals(effectiveTime, concept.getEffectiveTime()); //Update extension concept updateConcept(extension.getResourceURI(), concept.getId(), Map.of( "moduleId", Concepts.MODULE_SCT_MODEL_COMPONENT )); //Create second version LocalDate effectiveDate2 = getNextAvailableEffectiveDate(codeSystemId); createVersion(codeSystemId, effectiveDate2).statusCode(201); // start the extension upgrade process CodeSystem upgradeCodeSystem = createExtensionUpgrade(upgradeExtVersion, upgradeInternationalCodeSystem); // create a change on the concept, like change the definition status updateConcept(upgradeCodeSystem.getResourceURI(), concept.getId(), Map.of( "definitionStatusId", Concepts.FULLY_DEFINED )); concept = getConcept(upgradeCodeSystem.getResourceURI(), moduleId); assertEquals(null, concept.getEffectiveTime()); // revert the change, so it reverts the effective time to the 'effectiveDate' effective time updateConcept(upgradeCodeSystem.getResourceURI(), moduleId, Map.of( "definitionStatusId", Concepts.PRIMITIVE )); concept = getConcept(upgradeCodeSystem.getResourceURI(), moduleId); assertEquals(effectiveTime, concept.getEffectiveTime()); } }
923bd37794b45b95c4d96404a6407e3b1771eb62
532
java
Java
doma-processor/src/test/java/org/seasar/doma/internal/apt/processor/domain/OfAbstractDomain.java
lunch2000/doma
2aa38c75aacdbff43e8c1045597751d5cf7e2c27
[ "Apache-2.0" ]
310
2015-01-19T02:44:27.000Z
2022-03-19T07:16:42.000Z
doma-processor/src/test/java/org/seasar/doma/internal/apt/processor/domain/OfAbstractDomain.java
lunch2000/doma
2aa38c75aacdbff43e8c1045597751d5cf7e2c27
[ "Apache-2.0" ]
163
2015-01-25T03:41:54.000Z
2022-03-22T09:42:13.000Z
doma-processor/src/test/java/org/seasar/doma/internal/apt/processor/domain/OfAbstractDomain.java
lunch2000/doma
2aa38c75aacdbff43e8c1045597751d5cf7e2c27
[ "Apache-2.0" ]
81
2015-02-21T07:00:54.000Z
2022-03-24T05:50:01.000Z
18.344828
54
0.697368
999,737
package org.seasar.doma.internal.apt.processor.domain; import org.seasar.doma.Domain; @Domain(valueType = int.class, factoryMethod = "of") public abstract class OfAbstractDomain { private final int value; private OfAbstractDomain(int value) { this.value = value; } public int getValue() { return value; } public static OfAbstractDomain of(int value) { return new MyDomain(value); } static class MyDomain extends OfAbstractDomain { public MyDomain(int value) { super(value); } } }
923bd46fb9f1fc3549a8dcf8914b4614058951eb
4,388
java
Java
DeviceSettings/src/com/cyanogenmod/settings/device/SensorsFragmentActivity.java
LineageOS/android_device_samsung_msm8660-common
57d1e6fb0f9f93616f20277c5b8cb49f2cf20fbf
[ "FTL" ]
1
2017-11-22T14:47:45.000Z
2017-11-22T14:47:45.000Z
DeviceSettings/src/com/cyanogenmod/settings/device/SensorsFragmentActivity.java
LineageOS/android_device_samsung_msm8660-common
57d1e6fb0f9f93616f20277c5b8cb49f2cf20fbf
[ "FTL" ]
null
null
null
DeviceSettings/src/com/cyanogenmod/settings/device/SensorsFragmentActivity.java
LineageOS/android_device_samsung_msm8660-common
57d1e6fb0f9f93616f20277c5b8cb49f2cf20fbf
[ "FTL" ]
null
null
null
44.77551
124
0.72402
999,738
/* * Copyright (C) 2012 The CyanogenMod Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.cyanogenmod.settings.device; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.CheckBoxPreference; import android.preference.ListPreference; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.PreferenceFragment; import android.preference.PreferenceManager; import android.preference.PreferenceScreen; import android.util.Log; import com.cyanogenmod.settings.device.R; public class SensorsFragmentActivity extends PreferenceFragment { private static final String PREF_ENABLED = "1"; private static final String TAG = "GalaxyS2Parts_General"; private static final String FILE_USE_GYRO_CALIB = "/sys/class/sec/gsensorcal/calibration"; private static final String FILE_TOUCHKEY_LIGHT = "/data/.disable_touchlight"; private static final String FILE_TOUCHKEY_TOGGLE = "/sys/class/misc/sec_touchkey/brightness"; private static final String FILE_BLN_TOGGLE = "/sys/class/misc/backlightnotification/enabled"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.sensors_preferences); PreferenceScreen prefSet = getPreferenceScreen(); } @Override public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) { String boxValue; String key = preference.getKey(); Log.w(TAG, "key: " + key); if (key.compareTo(DeviceSettings.KEY_USE_GYRO_CALIBRATION) == 0) { boxValue = (((CheckBoxPreference)preference).isChecked() ? "1" : "0"); Utils.writeValue(FILE_USE_GYRO_CALIB, boxValue); } else if (key.compareTo(DeviceSettings.KEY_CALIBRATE_GYRO) == 0) { // when calibration data utilization is disablen and enabled back, // calibration is done at the same time by driver Utils.writeValue(FILE_USE_GYRO_CALIB, "0"); Utils.writeValue(FILE_USE_GYRO_CALIB, "1"); Utils.showDialog((Context)getActivity(), "Calibration done", "The gyroscope has been successfully calibrated!"); } else if (key.compareTo(DeviceSettings.KEY_TOUCHKEY_LIGHT) == 0) { Utils.writeValue(FILE_TOUCHKEY_LIGHT, ((CheckBoxPreference)preference).isChecked() ? "0" : "1"); Utils.writeValue(FILE_TOUCHKEY_TOGGLE, ((CheckBoxPreference)preference).isChecked() ? "1" : "2"); } else if (key.compareTo(DeviceSettings.KEY_TOUCHKEY_BLN) == 0) { Utils.writeValue(FILE_BLN_TOGGLE, ((CheckBoxPreference)preference).isChecked() ? "1" : "0"); } return true; } public static boolean isSupported(String FILE) { return Utils.fileExists(FILE); } public static void restore(Context context) { SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context); // When use gyro calibration value is set to 1, calibration is done at the same time, which // means it is reset at each boot, providing wrong calibration most of the time at each reboot. // So we only set it to "0" if user wants it, as it defaults to 1 at boot if (!sharedPrefs.getBoolean(DeviceSettings.KEY_USE_GYRO_CALIBRATION, true)) Utils.writeValue(FILE_USE_GYRO_CALIB, "0"); Utils.writeValue(FILE_TOUCHKEY_LIGHT, sharedPrefs.getBoolean(DeviceSettings.KEY_TOUCHKEY_LIGHT, true) ? "0" : "1"); Utils.writeValue(FILE_TOUCHKEY_TOGGLE, sharedPrefs.getBoolean(DeviceSettings.KEY_TOUCHKEY_LIGHT, true) ? "1" : "2"); Utils.writeValue(FILE_BLN_TOGGLE, sharedPrefs.getBoolean(DeviceSettings.KEY_TOUCHKEY_BLN, false) ? "1" : "0"); } }
923bd550fde7fc9dcd60a465193a7613846a8b57
742
java
Java
tutorial-3/src/main/java/id/ac/ui/cs/advprog/tutorial3/composite/higherups/Cto.java
ichlaffterlalu/advprog-lab
80c26294d4516ac31cf5207ebcf3127b2174bcc7
[ "BSD-3-Clause" ]
null
null
null
tutorial-3/src/main/java/id/ac/ui/cs/advprog/tutorial3/composite/higherups/Cto.java
ichlaffterlalu/advprog-lab
80c26294d4516ac31cf5207ebcf3127b2174bcc7
[ "BSD-3-Clause" ]
null
null
null
tutorial-3/src/main/java/id/ac/ui/cs/advprog/tutorial3/composite/higherups/Cto.java
ichlaffterlalu/advprog-lab
80c26294d4516ac31cf5207ebcf3127b2174bcc7
[ "BSD-3-Clause" ]
null
null
null
21.823529
89
0.622642
999,739
package id.ac.ui.cs.advprog.tutorial3.composite.higherups; import id.ac.ui.cs.advprog.tutorial3.composite.Employees; public class Cto extends Employees { private static final double MINIMUM_SALARY = 100000.00; public Cto(String name, double salary) { //TODO Implement if (salary < MINIMUM_SALARY) { throw new IllegalArgumentException("Salary must not below" + MINIMUM_SALARY); } this.name = name; this.salary = salary; } @Override public String getName() { return name; } @Override public String getRole() { return "CTO"; } @Override public double getSalary() { //TODO Implement return this.salary; } }
923bd5636c1423b25a384ddbeae2031ff0a4eea7
279
java
Java
main/java/org/testory/plumbing/format/Body.java
perunlabs/testory
558523be532bfe0667b9398d7ad405f4c37a3dbf
[ "Apache-2.0" ]
1
2021-12-20T05:26:40.000Z
2021-12-20T05:26:40.000Z
main/java/org/testory/plumbing/format/Body.java
maciejmikosik/testory
558523be532bfe0667b9398d7ad405f4c37a3dbf
[ "Apache-2.0" ]
6
2017-12-14T10:06:13.000Z
2019-10-05T10:40:01.000Z
main/java/org/testory/plumbing/format/Body.java
perunlabs/testory
558523be532bfe0667b9398d7ad405f4c37a3dbf
[ "Apache-2.0" ]
1
2019-01-08T01:37:55.000Z
2019-01-08T01:37:55.000Z
17.4375
54
0.713262
999,740
package org.testory.plumbing.format; import org.testory.common.Nullable; public class Body { public final Object object; private Body(Object object) { this.object = object; } public static Object body(@Nullable Object object) { return new Body(object); } }
923bd6ec6340b4ea8b2d47952ee2161d6b7fdd07
249
java
Java
weiminbackup/weiminmall/src/test/java/com/weimin/junittest/DemoTest.java
MrLiam/LiamDemo
cf921c7bda288b0bae5000825a45c4b131e08769
[ "MIT" ]
null
null
null
weiminbackup/weiminmall/src/test/java/com/weimin/junittest/DemoTest.java
MrLiam/LiamDemo
cf921c7bda288b0bae5000825a45c4b131e08769
[ "MIT" ]
null
null
null
weiminbackup/weiminmall/src/test/java/com/weimin/junittest/DemoTest.java
MrLiam/LiamDemo
cf921c7bda288b0bae5000825a45c4b131e08769
[ "MIT" ]
null
null
null
15.5625
72
0.694779
999,741
package com.weimin.junittest; import org.junit.Test; import com.weimin.common.util.SmsTool; public class DemoTest { /** * 测试发送短信 */ @Test public void sendMsg(){ System.out.println(SmsTool.sendMsg("17708075597","233333","3", true)); } }
923bd772e61382352b4786d9c303ba21ac4672e4
953
java
Java
src/main/java/com/ccnode/codegenerator/database/handler/oracle/OracleAutoComplateHandler.java
coffee377/MyBatisCodeHelper
0172a2f7d9c5de5c6838cca6ca2c73ff846ce1bf
[ "Apache-2.0" ]
2
2019-09-26T02:45:29.000Z
2021-02-06T13:05:26.000Z
src/main/java/com/ccnode/codegenerator/database/handler/oracle/OracleAutoComplateHandler.java
coffee377/MyBatisCodeHelper
0172a2f7d9c5de5c6838cca6ca2c73ff846ce1bf
[ "Apache-2.0" ]
null
null
null
src/main/java/com/ccnode/codegenerator/database/handler/oracle/OracleAutoComplateHandler.java
coffee377/MyBatisCodeHelper
0172a2f7d9c5de5c6838cca6ca2c73ff846ce1bf
[ "Apache-2.0" ]
3
2018-11-13T01:25:45.000Z
2021-02-06T13:05:29.000Z
28.029412
111
0.686254
999,742
package com.ccnode.codegenerator.database.handler.oracle; import com.ccnode.codegenerator.database.handler.AutoCompleteHandler; import com.intellij.psi.PsiParameter; /** * @Author bruce.ge * @Date 2017/2/27 * @Description */ public class OracleAutoComplateHandler implements AutoCompleteHandler { private static volatile OracleAutoComplateHandler mInstance; private OracleAutoComplateHandler() { } public static OracleAutoComplateHandler getInstance() { if (mInstance == null) { synchronized (OracleAutoComplateHandler.class) { if (mInstance == null) { mInstance = new OracleAutoComplateHandler(); } } } return mInstance; } @Override public boolean isSupportedParam(PsiParameter psiParameter) { return OracleHandlerUtils.getTypePropByQulitifiedName(psiParameter.getType().getCanonicalText())!=null; } }
923bd865e8358a549c682971abe0d07d7291746b
2,002
java
Java
platforms/karaf/commands/src/main/java/org/apache/camel/karaf/commands/completers/CamelContextCompleter.java
mpaetzold/camel
826a00507239cf8e97fd33f2827a41284f4d1349
[ "Apache-2.0" ]
17
2020-03-24T13:10:36.000Z
2022-03-30T06:02:42.000Z
platforms/karaf/commands/src/main/java/org/apache/camel/karaf/commands/completers/CamelContextCompleter.java
mpaetzold/camel
826a00507239cf8e97fd33f2827a41284f4d1349
[ "Apache-2.0" ]
13
2020-04-06T13:17:42.000Z
2022-03-30T06:21:10.000Z
platforms/karaf/commands/src/main/java/org/apache/camel/karaf/commands/completers/CamelContextCompleter.java
mpaetzold/camel
826a00507239cf8e97fd33f2827a41284f4d1349
[ "Apache-2.0" ]
46
2020-03-24T13:10:40.000Z
2022-03-30T06:06:45.000Z
39.254902
92
0.732268
999,743
/* * 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.camel.karaf.commands.completers; import java.util.List; import org.apache.camel.CamelContext; import org.apache.camel.karaf.commands.internal.CamelControllerImpl; import org.apache.karaf.shell.api.action.lifecycle.Service; import org.apache.karaf.shell.api.console.CommandLine; import org.apache.karaf.shell.api.console.Completer; import org.apache.karaf.shell.api.console.Session; import org.apache.karaf.shell.support.completers.StringsCompleter; /** * A completer for the Camel contexts. */ @Service public class CamelContextCompleter extends CamelControllerImpl implements Completer { @Override public int complete(Session session, CommandLine commandLine, List<String> candidates) { try { StringsCompleter delegate = new StringsCompleter(); List<CamelContext> camelContexts = getLocalCamelContexts(); for (CamelContext camelContext : camelContexts) { delegate.getStrings().add(camelContext.getName()); } return delegate.complete(session, commandLine, candidates); } catch (Exception e) { // nothing to do, no completion } return 0; } }
923bd8f1510a1a8810003c9945539a631bd06fce
6,408
java
Java
oak-solr-core/src/test/java/org/apache/jackrabbit/oak/plugins/index/solr/query/SolrQueryEngineIT.java
joansmith3/jackrabbit-oak
e0450b7a1e710b0ce391393ab773d10efa1c9f55
[ "Apache-2.0" ]
1
2019-02-22T02:48:51.000Z
2019-02-22T02:48:51.000Z
oak-solr-core/src/test/java/org/apache/jackrabbit/oak/plugins/index/solr/query/SolrQueryEngineIT.java
joansmith2/jackrabbit-oak
e0450b7a1e710b0ce391393ab773d10efa1c9f55
[ "Apache-2.0" ]
10
2020-03-04T21:42:31.000Z
2022-01-21T23:17:15.000Z
oak-solr-core/src/test/java/org/apache/jackrabbit/oak/plugins/index/solr/query/SolrQueryEngineIT.java
joansmith2/jackrabbit-oak
e0450b7a1e710b0ce391393ab773d10efa1c9f55
[ "Apache-2.0" ]
null
null
null
43.297297
109
0.691479
999,744
/* * 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.jackrabbit.oak.plugins.index.solr.query; import java.util.HashSet; import java.util.Set; import org.apache.jackrabbit.oak.api.Root; import org.apache.jackrabbit.oak.api.Tree; import org.apache.jackrabbit.oak.plugins.index.solr.SolrBaseTest; import org.apache.jackrabbit.oak.query.QueryEngineSettings; import org.apache.jackrabbit.oak.query.ast.Operator; import org.apache.jackrabbit.oak.query.ast.SelectorImpl; import org.apache.jackrabbit.oak.query.index.FilterImpl; import org.apache.jackrabbit.oak.spi.query.Cursor; import org.apache.jackrabbit.oak.spi.query.Filter; import org.apache.jackrabbit.oak.spi.query.PropertyValues; import org.apache.jackrabbit.oak.spi.query.QueryIndex; import org.junit.Test; import static com.google.common.collect.Sets.newHashSet; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertNotNull; import static junit.framework.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * Integration test for {@link org.apache.jackrabbit.oak.plugins.index.solr.query.SolrQueryIndex} working * together */ public class SolrQueryEngineIT extends SolrBaseTest { @Test public void testExactPathFiltering() throws Exception { Root root = createRoot(); Tree tree = root.getTree("/"); tree.addChild("somenode"); tree.addChild("someothernode"); root.commit(); QueryIndex index = new SolrQueryIndex("solr", server, configuration); FilterImpl filter = new FilterImpl(mock(SelectorImpl.class), "", new QueryEngineSettings()); filter.restrictPath("/somenode", Filter.PathRestriction.EXACT); Cursor cursor = index.query(filter, store.getRoot()); assertCursor(cursor, "/somenode"); } @Test public void testDirectChildrenPathFiltering() throws Exception { Root root = createRoot(); Tree tree = root.getTree("/"); Tree parent = tree.addChild("somenode"); parent.addChild("child1"); Tree child2 = parent.addChild("child2"); child2.addChild("descendant"); Tree someothernode = tree.addChild("someothernode"); someothernode.addChild("someotherchild"); root.commit(); QueryIndex index = new SolrQueryIndex("solr", server, configuration); FilterImpl filter = new FilterImpl(mock(SelectorImpl.class), "", new QueryEngineSettings()); filter.restrictPath("/somenode", Filter.PathRestriction.DIRECT_CHILDREN); Cursor cursor = index.query(filter, store.getRoot()); assertCursor(cursor, "/somenode/child1", "/somenode/child2"); } @Test public void testAllChildrenPathFiltering() throws Exception { Root root = createRoot(); Tree tree = root.getTree("/"); Tree parent = tree.addChild("somenode"); parent.addChild("child1"); Tree child2 = parent.addChild("child2"); child2.addChild("descendant"); Tree someothernode = tree.addChild("someothernode"); someothernode.addChild("someotherchild"); root.commit(); QueryIndex index = new SolrQueryIndex("solr", server, configuration); FilterImpl filter = new FilterImpl(mock(SelectorImpl.class), "", new QueryEngineSettings()); filter.restrictPath("/somenode", Filter.PathRestriction.ALL_CHILDREN); Cursor cursor = index.query(filter, store.getRoot()); assertCursor( cursor, "/somenode", "/somenode/child1", "/somenode/child2", "/somenode/child2/descendant"); } @Test public void testPropertyFiltering() throws Exception { Root root = createRoot(); Tree tree = root.getTree("/"); tree.addChild("somenode").setProperty("foo", "bar"); tree.addChild("someothernode").setProperty("foo", "bard"); tree.addChild("anotherone").setProperty("foo", "a fool's bar"); root.commit(); QueryIndex index = new SolrQueryIndex("solr", server, configuration); FilterImpl filter = new FilterImpl(mock(SelectorImpl.class), "", new QueryEngineSettings()); filter.restrictProperty("foo", Operator.EQUAL, PropertyValues.newString("bar")); Cursor cursor = index.query(filter, store.getRoot()); assertCursor(cursor, "/somenode", "/anotherone"); } @Test public void testPrimaryTypeFiltering() throws Exception { Root root = createRoot(); Tree tree = root.getTree("/"); tree.addChild("asamplenode").setProperty("jcr:primaryType", "nt:unstructured"); tree.addChild("afoldernode").setProperty("jcr:primaryType", "nt:folder"); tree.addChild("anothersamplenode").setProperty("jcr:primaryType", "nt:unstructured"); root.commit(); QueryIndex index = new SolrQueryIndex("solr", server, configuration); SelectorImpl selector = mock(SelectorImpl.class); Set<String> primaryTypes = new HashSet<String>(); primaryTypes.add("nt:folder"); when(selector.getPrimaryTypes()).thenReturn(primaryTypes); FilterImpl filter = new FilterImpl(selector, "select * from [nt:folder]", new QueryEngineSettings()); Cursor cursor = index.query(filter, store.getRoot()); assertCursor(cursor, "/afoldernode"); } private void assertCursor(Cursor cursor, String... paths) { assertNotNull(cursor); Set<String> set = newHashSet(); while (cursor.hasNext()) { assertTrue(set.add(cursor.next().getPath())); } assertEquals(newHashSet(paths), set); } }
923bd9cd2a90e5572dfa1243a2cf7b671ec62183
2,041
java
Java
plugin/jvm/src/main/java/com/twosigma/beaker/chart/xychart/plotitem/Stems.java
tbenst/beaker-webppl
d02e3f7788e398aec41e0f473c63644e9287c44b
[ "Apache-2.0" ]
7
2017-07-17T03:47:43.000Z
2020-02-18T07:32:41.000Z
plugin/jvm/src/main/java/com/twosigma/beaker/chart/xychart/plotitem/Stems.java
tbenst/beaker-webppl
d02e3f7788e398aec41e0f473c63644e9287c44b
[ "Apache-2.0" ]
null
null
null
plugin/jvm/src/main/java/com/twosigma/beaker/chart/xychart/plotitem/Stems.java
tbenst/beaker-webppl
d02e3f7788e398aec41e0f473c63644e9287c44b
[ "Apache-2.0" ]
5
2017-05-17T02:19:51.000Z
2018-11-15T11:17:26.000Z
27.581081
91
0.655561
999,745
/* * Copyright 2014 TWO SIGMA OPEN SOURCE, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.twosigma.beaker.chart.xychart.plotitem; import com.twosigma.beaker.chart.Filter; import java.util.EnumSet; import java.util.List; public class Stems extends BasedXYGraphics { private final static EnumSet<Filter> POSSIBLE_LOD_FILTERS = EnumSet.of(Filter.STEAM, Filter.STEAM_PLUS, Filter.BOX); private Float width = 1.5f; private StrokeType baseStyle = StrokeType.SOLID; private List<StrokeType> styles; public void setWidth(Float width) { this.width = width; } public Float getWidth() { return this.width; } public void setStyle(Object style) { if (style instanceof StrokeType) { this.baseStyle = (StrokeType) style; } else if (style instanceof List) { @SuppressWarnings("unchecked") List<StrokeType> ss = (List<StrokeType>) style; setStyles(ss); } else { throw new IllegalArgumentException( "setStyle takes ShapeType or List of ShapeType"); } } private void setStyles(List<StrokeType> styles) { this.styles = styles; } public StrokeType getStyle() { return this.baseStyle; } public List<StrokeType> getStyles() { return this.styles; } @Override protected EnumSet<Filter> getPossibleFilters() { return POSSIBLE_LOD_FILTERS; } }
923bd9d0600960dcd445a385a3477d5dbe9c4e34
867
java
Java
easyTask-X-core/src/main/java/com/github/liuche51/easyTaskX/socket/CmdService.java
liuche51/easyTask-X
635480337e2b2d0ff9f724cabae64615bae2921a
[ "Apache-2.0" ]
2
2021-08-22T07:38:35.000Z
2021-12-12T15:03:28.000Z
easyTask-X-core/src/main/java/com/github/liuche51/easyTaskX/socket/CmdService.java
liuche51/easyTask-X
635480337e2b2d0ff9f724cabae64615bae2921a
[ "Apache-2.0" ]
null
null
null
easyTask-X-core/src/main/java/com/github/liuche51/easyTaskX/socket/CmdService.java
liuche51/easyTask-X
635480337e2b2d0ff9f724cabae64615bae2921a
[ "Apache-2.0" ]
null
null
null
34.68
95
0.615917
999,746
package com.github.liuche51.easyTaskX.socket; import com.alibaba.fastjson.JSONObject; import com.github.liuche51.easyTaskX.monitor.ClusterMonitor; import java.util.HashMap; import java.util.Map; public class CmdService { public static String excuteCmd(Command cmd){ switch (cmd.getType()){ case "get": switch (cmd.getMethod()){ case "brokerRegisterInfo": return JSONObject.toJSONString(ClusterMonitor.getBrokerRegisterInfo()); case "clinetRegisterInfo": return JSONObject.toJSONString(ClusterMonitor.getClinetRegisterInfo()); case "CURRENT_NODEInfo": return JSONObject.toJSONString(ClusterMonitor.getCURRENT_NODEInfo()); } } return "unknown command!"; } }
923bdb2180a2f3c9c056c90990d30b2c4a5a37f0
3,334
java
Java
CS RFID Java Multiple Reader/src/Netfinder/NetDisplay.java
cslrfid/CSL-Java-MultiReader-SDK-App
20311afdc9ad3136788e1d57da6e9090678068d4
[ "MIT" ]
null
null
null
CS RFID Java Multiple Reader/src/Netfinder/NetDisplay.java
cslrfid/CSL-Java-MultiReader-SDK-App
20311afdc9ad3136788e1d57da6e9090678068d4
[ "MIT" ]
null
null
null
CS RFID Java Multiple Reader/src/Netfinder/NetDisplay.java
cslrfid/CSL-Java-MultiReader-SDK-App
20311afdc9ad3136788e1d57da6e9090678068d4
[ "MIT" ]
null
null
null
24.335766
81
0.544691
999,747
package Netfinder; import Netfinder.Structures.DeviceInformation; /** * */ class NetDisplay { private final int MAX_ENTRIES = 256; private int m_selectedcell = 0; private int m_numcells = 0; private DeviceInformation[] m_ptr_array = new DeviceInformation[MAX_ENTRIES]; public int GetNumCells() { return m_numcells; } public DeviceInformation GetEntry(int index) { if (m_ptr_array.length > index) return m_ptr_array[index]; return null; } public boolean GetMACAddress(byte[] mac_ptr) { if (!IsCellSelected()) { return false; } if (mac_ptr == null || mac_ptr.length != 6) mac_ptr = new byte[6]; // Copy MAC address System.arraycopy(m_ptr_array[m_selectedcell].mac, 0, mac_ptr, 0, 6); return true; } public boolean GetMACAddress(int cell_number, byte[] mac_ptr) { if (cell_number >= m_numcells) { return false; } if (mac_ptr == null || mac_ptr.length != 6) mac_ptr = new byte[6]; // Copy MAC address System.arraycopy(m_ptr_array[cell_number].mac, 0, mac_ptr, 0, 6); return true; } public boolean IsCellSelected() { return (m_selectedcell != -1); } public void RemoveAllEntries() { int i; // Delete all entries for (i = 0; i < MAX_ENTRIES; i++) { if (m_ptr_array[i] != null) { m_ptr_array[i] = null; } } // Update number of cells m_numcells = 0; m_selectedcell = -1; } public boolean AddEntry(DeviceInformation pEntry) { int i; DeviceInformation pNewEntry; // Find the next available entry for (i = 0; i < MAX_ENTRIES; i++) { if (m_ptr_array[i] == null) { break; } } // If no entries could be found if (i == MAX_ENTRIES) { return false; } //----------------------------- // Add the entry at location i //----------------------------- // Create new entry pNewEntry = new DeviceInformation(); // Copy the entry data pNewEntry.mode = pEntry.mode; pNewEntry.time_on_powered = pEntry.time_on_powered; pNewEntry.time_on_network = pEntry.time_on_network; //CopyMemory(pNewEntry.mac, pEntry.mac, 6); //CopyMemory(pNewEntry.ip, pEntry.ip, 4); pNewEntry.mac = (byte[])pEntry.mac.clone(); pNewEntry.ip = (byte[])pEntry.ip.clone(); pNewEntry.port = pEntry.port; //CopyMemory(pNewEntry.subnet, pEntry.subnet, 4); //CopyMemory(pNewEntry.gateway, pEntry.gateway, 4); //pNewEntry.device_name = (byte[])pEntry.serverip.Clone(); pNewEntry.DHCP = pEntry.DHCP; pNewEntry.dhcp_retry = pEntry.dhcp_retry; pNewEntry.device_name = pEntry.device_name; pNewEntry.description = pEntry.description; pNewEntry.version = pEntry.version; // Store address in global array m_ptr_array[i] = pNewEntry; // Increment valid cell count m_numcells++; return true; } }
923bdb422fb16c1bfa81e5632db71bfe05a5dfbf
2,798
java
Java
app/src/main/java/com/duy/pascal/interperter/libraries/file/exceptions/FileException.java
tranleduy2000/pascalnide
c7f3f79ecf4cf6a81b32c7d389aad7f4034c8f01
[ "Apache-2.0" ]
81
2017-05-07T13:26:56.000Z
2022-03-03T19:39:15.000Z
app/src/main/java/com/duy/pascal/interperter/libraries/file/exceptions/FileException.java
tranleduy2000/pascalnide
c7f3f79ecf4cf6a81b32c7d389aad7f4034c8f01
[ "Apache-2.0" ]
52
2017-06-13T08:46:43.000Z
2021-06-09T09:50:07.000Z
app/src/main/java/com/duy/pascal/interperter/libraries/file/exceptions/FileException.java
tranleduy2000/pascalnide
c7f3f79ecf4cf6a81b32c7d389aad7f4034c8f01
[ "Apache-2.0" ]
28
2017-05-22T21:09:58.000Z
2021-09-07T13:05:27.000Z
36.815789
109
0.714081
999,748
/* * Copyright 2017 Tran Le Duy * * 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.duy.pascal.interperter.libraries.file.exceptions; import android.content.Context; import android.graphics.Color; import android.support.annotation.NonNull; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.style.ForegroundColorSpan; import com.duy.pascal.interperter.exceptions.runtime.RuntimePascalException; import com.duy.pascal.ui.R; import java.io.File; import static com.duy.pascal.ui.code.ExceptionManager.formatLine; /** * Created by Duy on 13-Apr-17. */ public abstract class FileException extends RuntimePascalException { public String filePath = ""; public FileException(@NonNull String filePath) { this.filePath = filePath; } public FileException(@NonNull File file) { this.filePath = file.getPath(); } @Override public Spanned getFormattedMessage(@NonNull Context context) { FileException e = this; SpannableStringBuilder builder = new SpannableStringBuilder(); builder.append(formatLine(context, e.getLineNumber())); builder.append("\n\n"); builder.append(context.getString(R.string.file)); builder.append(": "); builder.append(e.filePath); builder.setSpan(new ForegroundColorSpan(Color.YELLOW), 0, builder.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); builder.append("\n"); builder.append("\n"); if (e instanceof DiskReadErrorException) { builder.append(context.getString(R.string.DiskReadErrorException)); } else if (e instanceof FileNotAssignException) { builder.append(context.getString(R.string.FileNotAssignException)); } else if (e instanceof com.duy.pascal.interperter.libraries.file.exceptions.FileNotFoundException) { builder.append(context.getString(R.string.FileNotFoundException)); } else if (e instanceof FileNotOpenException) { builder.append(context.getString(R.string.FileNotOpenException)); } else if (e instanceof FileNotOpenForInputException) { builder.append(context.getString(R.string.FileNotOpenForInputException)); } return builder; } }
923bdb7ce8daf1ee9a6f7e5a7ba05050350d5d12
96
java
Java
codigos-de-referencia-fixed/codigos-de-referencia-core/src/main/java/br/ufsc/labsec/signature/conformanceVerifier/cades/ValidationResult.java
kyriosdata/seguranca
848529ff1f61f4341a9d9ae7b0a29e9b9e56d055
[ "Apache-2.0" ]
1
2021-11-11T13:35:47.000Z
2021-11-11T13:35:47.000Z
codigos-de-referencia-fixed/codigos-de-referencia-core/src/main/java/br/ufsc/labsec/signature/conformanceVerifier/cades/ValidationResult.java
kyriosdata/seguranca
848529ff1f61f4341a9d9ae7b0a29e9b9e56d055
[ "Apache-2.0" ]
1
2021-10-09T11:44:07.000Z
2021-10-09T11:44:07.000Z
codigos-de-referencia-fixed/codigos-de-referencia-core/src/main/java/br/ufsc/labsec/signature/conformanceVerifier/cades/ValidationResult.java
kyriosdata/seguranca
848529ff1f61f4341a9d9ae7b0a29e9b9e56d055
[ "Apache-2.0" ]
null
null
null
16
59
0.822917
999,749
package br.ufsc.labsec.signature.conformanceVerifier.cades; public class ValidationResult { }
923bdc2a320cbccccfcfcd8f63cf84fb1b385bd9
7,004
java
Java
hapi-fhir-codegen/src/main/java/ca/uhn/fhir/utils/codegen/hapi/methodgenerator/BaseExtensionMethodHandler.java
hapifhir/hapi-profile-code-generator
7c2a9baca625ce67b846d95e152417e28e348612
[ "Apache-2.0" ]
null
null
null
hapi-fhir-codegen/src/main/java/ca/uhn/fhir/utils/codegen/hapi/methodgenerator/BaseExtensionMethodHandler.java
hapifhir/hapi-profile-code-generator
7c2a9baca625ce67b846d95e152417e28e348612
[ "Apache-2.0" ]
null
null
null
hapi-fhir-codegen/src/main/java/ca/uhn/fhir/utils/codegen/hapi/methodgenerator/BaseExtensionMethodHandler.java
hapifhir/hapi-profile-code-generator
7c2a9baca625ce67b846d95e152417e28e348612
[ "Apache-2.0" ]
null
null
null
44.050314
200
0.750857
999,750
package ca.uhn.fhir.utils.codegen.hapi.methodgenerator; import org.apache.commons.lang3.StringUtils; import ca.uhn.fhir.model.dstu2.composite.CodeableConceptDt; import ca.uhn.fhir.model.dstu2.composite.ElementDefinitionDt; import ca.uhn.fhir.model.dstu2.composite.ElementDefinitionDt.Type; import ca.uhn.fhir.model.dstu2.resource.StructureDefinition; import ca.uhn.fhir.utils.codegen.hapi.MethodBodyGenerator; import ca.uhn.fhir.utils.codegen.hapi.dstu2.FhirResourceManagerDstu2; import ca.uhn.fhir.utils.codegen.hapi.HapiFhirUtils; import ca.uhn.fhir.utils.fhir.PathUtils; import ca.uhn.fhir.utils.fhir.model.FhirExtensionDefinition; public abstract class BaseExtensionMethodHandler extends BaseMethodGenerator { private String extensionUri; private ElementDefinitionDt extendedElement; private boolean skipProcessing = false;/*Nested extensions do not define a type and should be skipped*/ private boolean isExtendedStructure = false; public BaseExtensionMethodHandler(FhirResourceManagerDstu2 manager, MethodBodyGenerator template, StructureDefinition profile, ElementDefinitionDt element) { super(manager, template, profile, element); } public String getExtensionUri() { return extensionUri; } public void setExtensionUri(String extensionUri) { this.extensionUri = extensionUri; } public ElementDefinitionDt getExtendedElement() { return extendedElement; } public void setExtendedElement(ElementDefinitionDt extendedElement) { this.extendedElement = extendedElement; } public boolean isSkipProcessing() { return skipProcessing; } public void setSkipProcessing(boolean skipProcessing) { this.skipProcessing = skipProcessing; } public boolean isExtendedStructure() { return isExtendedStructure; } public void setExtendedStructure(boolean isExtendedStructure) { this.isExtendedStructure = isExtendedStructure; } /** * Method loads the extension definition and uses the extension definition to configure a * clone of the extended element. All defaults are set on the clone based * on the extension definition provided these have not been overridden in the profile. * <p> * All method generation operations will be done using the metadata specified * by the cloned element definition which represent the formal extension in the * context of this profile. * * @return */ public void handleExtensionElement() { extensionUri = getElement().getTypeFirstRep().getProfileFirstRep().getValueAsString();//TODO How to handle multiple profiles on types FhirExtensionDefinition extensionDef = getFhirResourceManager().getFhirExtension(PathUtils.getExtensionRootPath(extensionUri)); if(extensionDef == null) { LOGGER.error(extensionUri + " for element " + getElement().getName() + " has no associated extension registered"); } String extensionName = PathUtils.getExtensionName(extensionUri); extendedElement = extensionDef.getExtensionByNameDstu2(extensionName); if(extendedElement == null) { LOGGER.error("Error processing " + extensionUri + " no extension definition found. Check URI or extension directories"); } //Handle extended structure types. If it is an extended structure, it will have its own type. Set that as the type: if(getElement().getType().size() == 2 && getElement().getType().get(1).getCode().contains(getGeneratedCodePackage())) { extendedElement.setType(getElement().getType());//Override the extension type with the type of the class we will create for the extended structure } if(extensionName != null && extensionName.contains("-")) { extensionName = extensionName.substring(extensionName.lastIndexOf('-') + 1); extendedElement.setName(extensionName); } extendedElement = FhirResourceManagerDstu2.shallowCloneElement(extendedElement); if(extendedElement.getType().size() == 1) { handleType(extendedElement.getTypeFirstRep()); } else if(extendedElement.getType().size() == 0){ setFullyQualifiedType(getGeneratedCodePackage() + "." + StringUtils.capitalize(getElement().getName())); return; } else if(extendedElement.getType().size() == 2) {//TODO Is this done because index 0 is extension and index 1 is a type? Fix this behavior for legitimate multitypes given new logic. LOGIC IS WRONG. handleType(extendedElement.getType().get(1)); } else { //TODO Implement support for multi-type attributes LOGGER.error("Multitype attribute " + extendedElement.getName() + " encountered but not yet handled in code"); extendedElement.getType().clear(); extendedElement.getTypeFirstRep().setCode("unsupported"); } // if(extensionDef != null) {//Need to gracefully handle case when extensionDef is null // if(extendedElement.getType().size() >= 1 && extendedElement.getType().size() <= 2 // && extendedElement.getTypeFirstRep().getCode().equals("Extension")) { // if(extendedElement.getType().size() == 1) { // extendedElement.setType(extensionDef.getTypes()); // if(extensionDef.getTypes().size() == 1) { // handleType(extensionDef.getTypes().get(0));//TODO Hack until I figure what to do with multi-type attributes. Need a way to chain handlers. Investigate // } else { // setFullyQualifiedType(getGeneratedCodePackage() + "." + StringUtils.capitalize(getElement().getName())); // isExtendedStructure = true; // return; // } // } else { // setFullyQualifiedType(extendedElement.getType().get(1).getCode()); // isExtendedStructure = true; // } // } //Do I still need this? if(extendedElement.getPath() != null) { extendedElement.setPath(PathUtils.generateExtensionPath(extendedElement.getPath(), extendedElement.getName())); } } /** * Method that identifies the HAPI FHIR type * * @param type */ public void handleType(Type type) { Class<?> tentativeTypeClass = null; //setFullyQualifiedType(getFhirResourceManager().getFullyQualifiedJavaType(getProfile(), type)); if(type.getCode().equals("CodeableConcept")) {//type.getCode().equals("CodeableConcept")) { //setFullyQualifiedType(getFhirResourceManager().getFullyQualifiedJavaType(getProfile(), type)); //tentativeTypeClass = HapiFhirUtils.getDataTypeClass(getFhirResourceManager().getFhirContext(), type); tentativeTypeClass = CodeableConceptDt.class;//TODO Fix this! } else { tentativeTypeClass = HapiFhirUtils.getDataTypeClass(getFhirResourceManager().getFhirContext(), type); } if(tentativeTypeClass != null) { setFullyQualifiedType(tentativeTypeClass.getName()); } else { if(getFhirResourceManager().generatedTypeExists(type.getCode())) { setFullyQualifiedType(type.getCode()); } else { if(type.getCode().equals("Reference")) { setFullyQualifiedType(ca.uhn.fhir.model.dstu2.composite.ResourceReferenceDt.class.getName()); } else if(type.getCode().equals("Extension")){ setFullyQualifiedType(ca.uhn.fhir.model.api.ExtensionDt.class.getName()); } else { throw new RuntimeException("Unknown type " + type.getCode()); } } } } }
923bdc32699be285d1b46280956076194d5eb50a
1,030
java
Java
src/cz/zcu/kiv/mobile/logger/data/database/commands/InsertHeartRateCumulativeOperatingTimeCommand.java
NEUROINFORMATICS-GROUP-FAV-KIV-ZCU/elfyz-data-mobile-logger
8362299d6cb091c57a678c5a7b635851e3cb5d17
[ "CC-BY-3.0", "Apache-2.0" ]
1
2017-10-11T12:11:36.000Z
2017-10-11T12:11:36.000Z
src/cz/zcu/kiv/mobile/logger/data/database/commands/InsertHeartRateCumulativeOperatingTimeCommand.java
NEUROINFORMATICS-GROUP-FAV-KIV-ZCU/elfyz-data-mobile-logger
8362299d6cb091c57a678c5a7b635851e3cb5d17
[ "CC-BY-3.0", "Apache-2.0" ]
null
null
null
src/cz/zcu/kiv/mobile/logger/data/database/commands/InsertHeartRateCumulativeOperatingTimeCommand.java
NEUROINFORMATICS-GROUP-FAV-KIV-ZCU/elfyz-data-mobile-logger
8362299d6cb091c57a678c5a7b635851e3cb5d17
[ "CC-BY-3.0", "Apache-2.0" ]
null
null
null
44.782609
156
0.850485
999,751
package cz.zcu.kiv.mobile.logger.data.database.commands; import cz.zcu.kiv.mobile.logger.Application; import cz.zcu.kiv.mobile.logger.data.database.HeartRateCumulativeOperatingTimeTable; import cz.zcu.kiv.mobile.logger.data.database.exceptions.DatabaseException; import cz.zcu.kiv.mobile.logger.data.types.heart_rate.HeartRateCumulativeOperatingTime; public class InsertHeartRateCumulativeOperatingTimeCommand extends AInsertMeasurementCommand<HeartRateCumulativeOperatingTime> { protected static final HeartRateCumulativeOperatingTimeTable dbHrCot = Application.getInstance().getDatabase().getHeartRateCumulativeOperatingTimeTable(); public InsertHeartRateCumulativeOperatingTimeCommand(long userID, HeartRateCumulativeOperatingTime data, InsertCommandListener listener) { super(userID, data, listener); } @Override protected long insertToDatabase(long userID, HeartRateCumulativeOperatingTime measurement) throws DatabaseException { return dbHrCot.addCumulativeOperatingTime(userID, measurement); } }
923bdccfd076aa898327f8d5e954321c9af861cf
679
java
Java
src/test/java/example/IntegrationTest.java
thaingo/elide-issue
eb4fea2482ca84bc0b82a6d6da830bf30e93fcfc
[ "Apache-2.0" ]
null
null
null
src/test/java/example/IntegrationTest.java
thaingo/elide-issue
eb4fea2482ca84bc0b82a6d6da830bf30e93fcfc
[ "Apache-2.0" ]
1
2022-01-21T23:39:30.000Z
2022-01-21T23:39:30.000Z
src/test/java/example/IntegrationTest.java
thaingo/elide-issue
eb4fea2482ca84bc0b82a6d6da830bf30e93fcfc
[ "Apache-2.0" ]
null
null
null
27.16
117
0.771723
999,752
package example; import com.jayway.restassured.RestAssured; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.TestInstance; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.web.server.LocalServerPort; /** * Base class for running a set of functional Elide tests. This class sets up an Elide instance with an in-memory H2 * database. */ @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @TestInstance(TestInstance.Lifecycle.PER_CLASS) public class IntegrationTest { @LocalServerPort int port; @BeforeAll public void setUp() { RestAssured.port = port; } }
923bdd4df177c33a44eba39b93685c2327e8bf5e
170
java
Java
common/src/main/java/cn/edu/cug/cs/gtl/geom/IntervalType.java
ZhenwenHe/gtl-java
01edf4814240ef5aaa3cc4fc5df590de2228d0c1
[ "MIT" ]
2
2019-10-11T09:02:29.000Z
2019-11-19T13:26:28.000Z
common/src/main/java/cn/edu/cug/cs/gtl/geom/IntervalType.java
zhaohhit/gtl-java
63581c2bfca3ea989a4ba1497dca5e3c36190d46
[ "MIT" ]
2
2021-12-10T01:25:16.000Z
2021-12-14T21:35:12.000Z
common/src/main/java/cn/edu/cug/cs/gtl/geom/IntervalType.java
zhaohhit/gtl-java
63581c2bfca3ea989a4ba1497dca5e3c36190d46
[ "MIT" ]
1
2019-10-11T09:00:29.000Z
2019-10-11T09:00:29.000Z
14.166667
37
0.658824
999,753
package cn.edu.cug.cs.gtl.geom; /** * Created by ZhenwenHe on 2016/12/7. */ public enum IntervalType { IT_RIGHTOPEN, IT_LEFTOPEN, IT_OPEN, IT_CLOSED }
923bddef1439f0ed3afd4fc3d91c0feb24ad842c
5,174
java
Java
tools/junit/src/java_/awt/WindowTest.java
thinkum-contrib/ikvm
bb58b73e2a6b59f43d75607aa4b3c3a19444d878
[ "Zlib" ]
null
null
null
tools/junit/src/java_/awt/WindowTest.java
thinkum-contrib/ikvm
bb58b73e2a6b59f43d75607aa4b3c3a19444d878
[ "Zlib" ]
null
null
null
tools/junit/src/java_/awt/WindowTest.java
thinkum-contrib/ikvm
bb58b73e2a6b59f43d75607aa4b3c3a19444d878
[ "Zlib" ]
null
null
null
30.627219
147
0.636785
999,754
/* Copyright (C) 2009, 2010, 2012 Volker Berlin (i-net software) This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. Jeroen Frijters dycjh@example.com */ package java_.awt; import java.awt.*; import junit.ikvm.ReferenceData; import org.junit.*; import static org.junit.Assert.*; /** * @author Volker Berlin */ public class WindowTest{ protected static ReferenceData reference; @BeforeClass public static void setUpBeforeClass() throws Exception{ reference = new ReferenceData(); } @AfterClass public static void tearDownAfterClass() throws Exception{ if(reference != null){ reference.save(); } reference = null; } protected Window createWindow(){ return new Window((Window)null); } @Test public void getBackground(){ Window window = createWindow(); window.addNotify(); Color color = window.getBackground(); assertNotNull(window.getPeer()); window.dispose(); assertNull(window.getPeer()); reference.assertEquals("getBackground", color); window = createWindow(); window.setBackground(Color.RED); window.addNotify(); assertEquals(Color.RED, window.getBackground()); window.dispose(); } @Test public void setTransparentBackground() { Window window = createWindow(); if( window instanceof Frame ) { ((Frame)window).setUndecorated(true); } if( window instanceof Dialog ) { ((Dialog)window).setUndecorated(true); } Color color = new Color(128, 128, 128, 128); window.setBackground(color); window.addNotify(); assertEquals(color, window.getBackground()); window.dispose(); } @Test public void getForeground(){ Window window = createWindow(); window.addNotify(); Color color = window.getForeground(); window.dispose(); reference.assertEquals("getForeground", color); window = createWindow(); window.setForeground(Color.RED); window.addNotify(); assertEquals(Color.RED, window.getForeground()); window.dispose(); } @Test public void getFont(){ Window window = createWindow(); window.addNotify(); Font font = window.getFont(); window.dispose(); reference.assertEquals("getFont", font); font = new Font("Arial", 0, 13); window = createWindow(); window.setFont(font); window.addNotify(); assertEquals(font, window.getFont()); window.dispose(); } @Test public void setMinimumSize(){ Window window = createWindow(); window.addNotify(); window.setMinimumSize( new Dimension(0,0) ); reference.assertEquals("setMinimumSize0_0", window.getMinimumSize()); window.setMinimumSize( new Dimension(5,5) ); reference.assertEquals("setMinimumSize5_5", window.getMinimumSize()); window.setMinimumSize( new Dimension(100,100) ); reference.assertEquals("setMinimumSize100_100", window.getMinimumSize()); } @Test public void getComponentAt() throws Exception{ Window window = createWindow(); try{ window.setLayout( null ); // with a Window this test work only without a layout manager. It is unclear why. List list = new List( 10 ); TextArea textArea = new TextArea( 10, 10 ); window.setSize( 300, 300 ); textArea.setBounds( 10, 10, 100, 100 ); list.setBounds( 1, 1, 100, 100 ); textArea.setVisible( true ); list.setVisible( false ); window.add( list ); window.add( textArea ); window.setVisible( true ); assertEquals( textArea.isVisible(), true ); assertEquals( window.isVisible(), true ); assertEquals( list.isVisible(), false ); assertSame( list, window.getComponentAt( list.getLocation() ) ); assertFalse( textArea.equals( window.getComponentAt( textArea.getLocation() ) ) ); assertSame( textArea, window.getComponentAt( textArea.getX() + textArea.getWidth() - 1, textArea.getY() + textArea.getHeight() - 1 ) ); assertSame( window, window.getComponentAt( 0, 0 ) ); }finally{ window.dispose(); } } }
923bde48849932e2b4e1c094d0f8dbb2bd3bcc42
12,932
java
Java
src/main/java/org/liara/api/resource/CollectionResource.java
LIARALab/java-activity-recognition-platform
73366bd3b423554c958b1ec807dfd19f04ca03f9
[ "MIT" ]
null
null
null
src/main/java/org/liara/api/resource/CollectionResource.java
LIARALab/java-activity-recognition-platform
73366bd3b423554c958b1ec807dfd19f04ca03f9
[ "MIT" ]
null
null
null
src/main/java/org/liara/api/resource/CollectionResource.java
LIARALab/java-activity-recognition-platform
73366bd3b423554c958b1ec807dfd19f04ca03f9
[ "MIT" ]
null
null
null
34.514667
99
0.723866
999,755
/******************************************************************************* * Copyright (C) 2018 Cedric DEMONGIVERT <anpch@example.com> * * 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.liara.api.resource; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import org.liara.api.data.entity.ApplicationEntity; import org.liara.api.relation.RelationManager; import org.liara.collection.Collection; import org.liara.collection.ModelCollection; import org.liara.collection.operator.Operator; import org.liara.collection.operator.aggregate.Aggregate; import org.liara.request.validator.error.InvalidAPIRequestException; import org.liara.rest.cursor.FreeCursorHandler; import org.liara.rest.error.IllegalRestRequestException; import org.liara.rest.metamodel.FilterableRestResource; import org.liara.rest.metamodel.OrderableRestResource; import org.liara.rest.metamodel.RestResource; import org.liara.rest.processor.ProcessorHandler; import org.liara.rest.request.RestRequest; import org.liara.rest.request.handler.RestRequestHandler; import org.liara.rest.response.RestResponse; import org.liara.selection.processor.ProcessorExecutor; import org.springframework.context.ApplicationContext; import reactor.core.publisher.Mono; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.TypedQuery; import java.util.*; import java.util.function.Predicate; import java.util.logging.Logger; import java.util.regex.Pattern; public class CollectionResource<Entity extends ApplicationEntity> implements RestResource, FilterableRestResource, OrderableRestResource { @NonNull private static final Predicate<String> IS_LONG = Pattern.compile("^[0-9]+$").asPredicate(); @NonNull private static final Predicate<String> IS_UUID4 = Pattern.compile( "^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$", Pattern.CASE_INSENSITIVE ).asPredicate(); @NonNull private final Class<Entity> _modelClass; @NonNull private final RelationBasedFilteringHandlerFactory _entityFilteringHandlerFactory; @NonNull private final RelationBasedOrderingProcessorFactory _entityOrderingHandlerFactory; @NonNull private final EntityManagerFactory _entityManagerFactory; @NonNull private final RelationManager _relationManager; @NonNull private final ApplicationContext _context; protected CollectionResource ( @NonNull final Class<Entity> modelClass, @NonNull final CollectionResourceBuilder builder ) { _modelClass = modelClass; _entityManagerFactory = Objects.requireNonNull(builder.getEntityManagerFactory()); _relationManager = Objects.requireNonNull(builder.getRelationManager()); _context = Objects.requireNonNull(builder.getApplicationContext()); _entityOrderingHandlerFactory = ( Objects.requireNonNull(builder.getEntityOrderingHandlerFactory()) ); _entityFilteringHandlerFactory = ( Objects.requireNonNull(builder.getEntityFilteringHandlerFactory()) ); } @Override public boolean hasResource (@NonNull final String name) { return IS_UUID4.test(name) || IS_LONG.test(name) || "first".equalsIgnoreCase(name) || "last".equalsIgnoreCase(name) || "aggregate".equalsIgnoreCase(name) || "count".equalsIgnoreCase(name) || "sql".equalsIgnoreCase(name); } @Override public @NonNull RestResource getResource (@NonNull final String name) throws NoSuchElementException { if (IS_UUID4.test(name)) { return getModelResource(UUID.fromString(name)); } if (IS_LONG.test(name)) { return getModelResource(Long.parseLong(name)); } if ("first".equalsIgnoreCase(name)) { return getFirstModelResource(); } if ("last".equalsIgnoreCase(name)) { return getLastModelResource(); } if ("aggregate".equalsIgnoreCase(name)) { return getAggregationResource(); } if ("count".equalsIgnoreCase(name)) { return getPartialAggregationResource(Aggregate.expression("COUNT(:this)")); } if ("sql".equalsIgnoreCase(name)) { return new SQLResource(this); } return FilterableRestResource.super.getResource(name); } private @NonNull RestResource getPartialAggregationResource ( @NonNull final Aggregate expression ) { return new PartialAggregationResource<>( Collections.singletonList(expression), this, _context.getBean(AggregationResourceBuilder.class) ); } private @NonNull RestResource getAggregationResource () { return _context.getBean(AggregationResourceBuilder.class).build(this); } public @NonNull ModelResource<Entity> getFirstModelResource () throws NoSuchElementException { @NonNull final EntityManager entityManager = _entityManagerFactory.createEntityManager(); entityManager.getTransaction().begin(); @NonNull final List<@NonNull Entity> identifiers = entityManager.createQuery( "SELECT model FROM " + _modelClass.getName() + " model ORDER BY model.identifier ASC", getModelClass() ).setMaxResults(1).getResultList(); entityManager.getTransaction().commit(); entityManager.close(); if (identifiers.isEmpty()) { throw new NoSuchElementException("No first model found for this collection."); } else { return toModelResource(identifiers.get(0)); } } public @NonNull ModelResource<Entity> getLastModelResource () throws NoSuchElementException { @NonNull final EntityManager entityManager = _entityManagerFactory.createEntityManager(); entityManager.getTransaction().begin(); @NonNull final List<@NonNull Entity> identifiers = entityManager.createQuery( "SELECT model FROM " + _modelClass.getName() + " model ORDER BY model.identifier DESC", getModelClass() ).setMaxResults(1).getResultList(); entityManager.getTransaction().commit(); entityManager.close(); if (identifiers.isEmpty()) { throw new NoSuchElementException("No last model found for this collection."); } else { return toModelResource(identifiers.get(0)); } } public @NonNull ModelResource<Entity> getModelResource (@NonNull final UUID identifier) throws NoSuchElementException { @NonNull final EntityManager entityManager = _entityManagerFactory.createEntityManager(); entityManager.getTransaction().begin(); @NonNull final TypedQuery<Entity> query = entityManager.createQuery( "SELECT model " + "FROM " + _modelClass.getName() + " model " + "WHERE model.universalUniqueIdentifier = :identifier " + "ORDER BY model.identifier DESC", getModelClass() ); query.setParameter("identifier", identifier.toString()); query.setMaxResults(1); @NonNull final List<@NonNull Entity> identifiers = query.getResultList(); entityManager.getTransaction().commit(); entityManager.close(); if (identifiers.isEmpty()) { throw new NoSuchElementException( "No model with uuid " + identifier.toString() + " found into this collection." ); } else { return toModelResource(identifiers.get(0)); } } public @NonNull ModelResource<Entity> getModelResource ( @NonNull final Long identifier ) throws NoSuchElementException { @NonNull final EntityManager entityManager = _entityManagerFactory.createEntityManager(); entityManager.getTransaction().begin(); @NonNull final Optional<Entity> model = Optional.ofNullable( entityManager.find(_modelClass, identifier) ); entityManager.getTransaction().commit(); entityManager.close(); return toModelResource( model.orElseThrow( () -> new NoSuchElementException( "No model of type " + _modelClass.getName() + " with identifier " + identifier.toString() + " found into this collection." ) ) ); } protected @NonNull ModelResource<Entity> toModelResource (@NonNull final Entity entity) { @NonNull final BaseModelResourceBuilder<Entity> builder = ( _context.getBean(BaseModelResourceBuilder.class) ); builder.setModelClass(getModelClass()); builder.setModel(entity); return builder.build(); } @Override public @NonNull Mono<RestResponse> get (@NonNull final RestRequest request) throws IllegalRestRequestException { try { @NonNull final RestRequestHandler configuration = getRequestConfiguration(); configuration.validate(request.getParameters()).assertRequestIsValid(); @NonNull final Operator operator = configuration.parse(request.getParameters()); @NonNull final Collection<?> collection = operator.apply(getCollection()); @NonNull final Logger logger = Logger.getLogger(getClass().getName()); @NonNull final EntityManager entityManager = getEntityManagerFactory().createEntityManager(); entityManager.getTransaction().begin(); @NonNull final RestResponse<?> response = RestResponse.ofCollection(collection) .resolve(entityManager); entityManager.getTransaction().commit(); entityManager.close(); return Mono.just(response); } catch (@NonNull final InvalidAPIRequestException exception) { throw new IllegalRestRequestException(exception); } } protected @NonNull RestRequestHandler getRequestConfiguration () { return RestRequestHandler.all( FreeCursorHandler.INSTANCE, getResourceFilteringHandler(), RestRequestHandler.parameter("orderby", new ProcessorHandler<>(getResourceOrderingHandler())) ); } public @NonNull Collection<Entity> getCollection () { return new ModelCollection<>(getModelClass()); } public @NonNull Class<Entity> getModelClass () { return _modelClass; } @Override public @NonNull RestRequestHandler getResourceFilteringHandler () { return RestRequestHandler.all( _entityFilteringHandlerFactory.getHandlerFor(_modelClass) ); } @Override public @NonNull ProcessorExecutor<Operator> getResourceOrderingHandler () { return _entityOrderingHandlerFactory.getExecutorFor(_modelClass); } public @NonNull RelationBasedFilteringHandlerFactory getEntityFilteringHandlerFactory () { return _entityFilteringHandlerFactory; } public @NonNull RelationBasedOrderingProcessorFactory getEntityOrderingHandlerFactory () { return _entityOrderingHandlerFactory; } public @NonNull EntityManagerFactory getEntityManagerFactory () { return _entityManagerFactory; } public @NonNull RelationManager getRelationManager () { return _relationManager; } public @NonNull ApplicationContext getContext () { return _context; } @Override public boolean equals (@Nullable final Object other) { if (other == null) return false; if (other == this) return true; if (other instanceof CollectionResource) { @NonNull final CollectionResource otherCollectionResource = (CollectionResource) other; return Objects.equals( _modelClass, otherCollectionResource.getModelClass() ) && Objects.equals( _entityFilteringHandlerFactory, otherCollectionResource.getEntityFilteringHandlerFactory() ) && Objects.equals( _entityOrderingHandlerFactory, otherCollectionResource.getEntityOrderingHandlerFactory() ) && Objects.equals( _entityManagerFactory, otherCollectionResource.getEntityManagerFactory() ); } return false; } @Override public int hashCode () { return Objects.hash( _modelClass, _entityFilteringHandlerFactory, _entityOrderingHandlerFactory, _entityManagerFactory ); } }
923bde82b9b3a124e3b82c590c66f6b68b19ac6d
2,027
java
Java
influent-server/src/main/java/influent/server/spi/RestPatternSearchModule.java
humangeo/influent
b346d6c1b5f82ce95b19477d72a1074f52668c8b
[ "MIT" ]
null
null
null
influent-server/src/main/java/influent/server/spi/RestPatternSearchModule.java
humangeo/influent
b346d6c1b5f82ce95b19477d72a1074f52668c8b
[ "MIT" ]
null
null
null
influent-server/src/main/java/influent/server/spi/RestPatternSearchModule.java
humangeo/influent
b346d6c1b5f82ce95b19477d72a1074f52668c8b
[ "MIT" ]
null
null
null
30.712121
82
0.740503
999,756
/** * Copyright (c) 2013-2014 Oculus Info Inc. * http://www.oculusinfo.com/ * * Released under the MIT License. * * 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 influent.server.spi; import influent.idl.FL_PatternSearch; import influent.server.dataaccess.QuBEClient; import com.google.inject.AbstractModule; import com.google.inject.Provides; import com.google.inject.name.Named; /** * Module for pattern search services. */ public class RestPatternSearchModule extends AbstractModule { @Override protected void configure() { bind(FL_PatternSearch.class).to(QuBEClient.class); } /* * Provide the service */ @Provides public QuBEClient connect ( @Named("influent.pattern.search.remoteURL") String remoteURL, @Named("influent.pattern.search.useHMM") boolean useHMM ) { try { if(remoteURL != null && remoteURL.length() > 0) { return new QuBEClient(remoteURL, useHMM); } else { return null; } } catch (Exception e) { return null; } } }
923bdebd6c7676a3b0c8f387317c511eadd079ac
748
java
Java
src/main/java/org/github/evenjn/zip/Zip.java
evenjn/codecs
3e5a323515f2b7fd3e21b73cd635dace107ac25c
[ "Apache-2.0" ]
null
null
null
src/main/java/org/github/evenjn/zip/Zip.java
evenjn/codecs
3e5a323515f2b7fd3e21b73cd635dace107ac25c
[ "Apache-2.0" ]
null
null
null
src/main/java/org/github/evenjn/zip/Zip.java
evenjn/codecs
3e5a323515f2b7fd3e21b73cd635dace107ac25c
[ "Apache-2.0" ]
null
null
null
28.769231
75
0.731283
999,757
/** * * Copyright 2017 Marco Trevisan * * 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.github.evenjn.zip; public class Zip { public static ZipDecoderBlueprint decoder( ) { return new ZipDecoderBlueprint( ); } }
923bdf2b39328e4b3d3a02d53a3153bc8466ecf5
442
java
Java
app/src/main/java/com/tinytongtong/thinkinjavapractice/chapter08/part03/polymorphism/Sandwich.java
tinyvampirepudge/ThinkInJavaPractice
1b54ee85a22c927ae71773175639316abb5fe457
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/tinytongtong/thinkinjavapractice/chapter08/part03/polymorphism/Sandwich.java
tinyvampirepudge/ThinkInJavaPractice
1b54ee85a22c927ae71773175639316abb5fe457
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/tinytongtong/thinkinjavapractice/chapter08/part03/polymorphism/Sandwich.java
tinyvampirepudge/ThinkInJavaPractice
1b54ee85a22c927ae71773175639316abb5fe457
[ "Apache-2.0" ]
null
null
null
23.263158
75
0.733032
999,758
package com.tinytongtong.thinkinjavapractice.chapter08.part03.polymorphism; public class Sandwich extends Portable { private Bread bread = new Bread(); private Cheese cheese = new Cheese(); private Lettuce lettuce = new Lettuce(); public Sandwich() { // TODO Auto-generated constructor stub System.out.println("Sandwich()"); } public static void main(String[] args) { // TODO Auto-generated method stub new Sandwich(); } }
923be00c41813a1ae34b54fb5c50ef24bc87ea89
25,247
java
Java
snomed/com.b2international.snowowl.snomed.api.rest.tests/src/com/b2international/snowowl/snomed/api/rest/io/SnomedImportApiTest.java
IHTSDO/snow-owl
90c17b806956ad15cdc66649aa4e193bad21ff46
[ "Apache-2.0" ]
11
2017-02-03T17:02:04.000Z
2021-08-06T09:44:16.000Z
snomed/com.b2international.snowowl.snomed.api.rest.tests/src/com/b2international/snowowl/snomed/api/rest/io/SnomedImportApiTest.java
IHTSDO/snow-owl
90c17b806956ad15cdc66649aa4e193bad21ff46
[ "Apache-2.0" ]
24
2017-07-26T11:02:45.000Z
2019-05-23T08:55:43.000Z
snomed/com.b2international.snowowl.snomed.api.rest.tests/src/com/b2international/snowowl/snomed/api/rest/io/SnomedImportApiTest.java
IHTSDO/snow-owl
90c17b806956ad15cdc66649aa4e193bad21ff46
[ "Apache-2.0" ]
1
2017-10-12T17:40:43.000Z
2017-10-12T17:40:43.000Z
49.118677
153
0.811185
999,759
/* * Copyright 2011-2019 B2i Healthcare Pte Ltd, http://b2i.sg * * 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.b2international.snowowl.snomed.api.rest.io; import static com.b2international.snowowl.snomed.api.rest.CodeSystemRestRequests.createCodeSystem; import static com.b2international.snowowl.snomed.api.rest.CodeSystemVersionRestRequests.createVersion; import static com.b2international.snowowl.snomed.api.rest.CodeSystemVersionRestRequests.getVersion; import static com.b2international.snowowl.snomed.api.rest.SnomedComponentRestRequests.getComponent; import static com.b2international.snowowl.snomed.api.rest.SnomedImportRestRequests.createImport; import static com.b2international.snowowl.snomed.api.rest.SnomedImportRestRequests.deleteImport; import static com.b2international.snowowl.snomed.api.rest.SnomedImportRestRequests.getImport; import static com.b2international.snowowl.snomed.api.rest.SnomedImportRestRequests.uploadImportFile; import static com.b2international.snowowl.snomed.api.rest.SnomedImportRestRequests.waitForImportJob; import static com.b2international.snowowl.test.commons.rest.RestExtensions.lastPathSegment; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.Map; import java.util.Optional; import java.util.stream.StreamSupport; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; import com.b2international.snowowl.core.api.IBranchPath; import com.b2international.snowowl.core.domain.IComponent; import com.b2international.snowowl.snomed.SnomedConstants.Concepts; import com.b2international.snowowl.snomed.api.rest.AbstractSnomedApiTest; import com.b2international.snowowl.snomed.api.rest.SnomedBranchingRestRequests; import com.b2international.snowowl.snomed.api.rest.SnomedComponentType; import com.b2international.snowowl.snomed.common.SnomedRf2Headers; import com.b2international.snowowl.snomed.core.domain.ISnomedImportConfiguration.ImportStatus; import com.b2international.snowowl.snomed.core.domain.Rf2ReleaseType; import com.b2international.snowowl.snomed.core.domain.SnomedConcept; import com.b2international.snowowl.snomed.core.domain.refset.SnomedReferenceSetMember; import com.google.common.collect.ImmutableMap; import io.restassured.response.ValidatableResponse; /** * @since 2.0 */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class SnomedImportApiTest extends AbstractSnomedApiTest { private static final String OWL_EXPRESSION = "SubClassOf(ObjectIntersectionOf(:73211009 ObjectSomeValuesFrom(:42752001 :64572001)) :8801005)"; private void importArchive(final String fileName) { importArchive(fileName, branchPath, false, Rf2ReleaseType.DELTA); } private void importArchive(String fileName, IBranchPath path, boolean createVersion, Rf2ReleaseType releaseType) { final Map<?, ?> importConfiguration = ImmutableMap.builder() .put("type", releaseType.name()) .put("branchPath", path.getPath()) .put("createVersions", createVersion) .build(); importArchive(fileName, importConfiguration); } private void importArchive(final String fileName, Map<?, ?> importConfiguration) { final String importId = lastPathSegment(createImport(importConfiguration).statusCode(201) .extract().header("Location")); getImport(importId).statusCode(200).body("status", equalTo(ImportStatus.WAITING_FOR_FILE.name())); uploadImportFile(importId, getClass(), fileName).statusCode(204); waitForImportJob(importId).statusCode(200).body("status", equalTo(ImportStatus.COMPLETED.name())); } @Test public void import01CreateValidConfiguration() { final Map<?, ?> importConfiguration = ImmutableMap.builder() .put("type", Rf2ReleaseType.DELTA.name()) .put("branchPath", branchPath.getPath()) .put("createVersions", false) .build(); final String importId = lastPathSegment(createImport(importConfiguration).statusCode(201) .extract().header("Location")); getImport(importId).statusCode(200).body("status", equalTo(ImportStatus.WAITING_FOR_FILE.name())); } @Test public void import02DeleteConfiguration() { final Map<?, ?> importConfiguration = ImmutableMap.builder() .put("type", Rf2ReleaseType.DELTA.name()) .put("branchPath", "MAIN") .put("createVersions", false) .build(); final String importId = lastPathSegment(createImport(importConfiguration).statusCode(201) .extract().header("Location")); deleteImport(importId).statusCode(204); getImport(importId).statusCode(404); } @Test public void import03VersionsAllowedOnBranch() { final Map<?, ?> importConfiguration = ImmutableMap.builder() .put("type", Rf2ReleaseType.DELTA.name()) .put("branchPath", branchPath.getPath()) .put("createVersions", true) .build(); final String importId = lastPathSegment(createImport(importConfiguration).statusCode(201) .extract().header("Location")); getImport(importId).statusCode(200) .body("status", equalTo(ImportStatus.WAITING_FOR_FILE.name())); } @Test public void import04NewConcept() { getComponent(branchPath, SnomedComponentType.CONCEPT, "63961392103").statusCode(404); importArchive("SnomedCT_Release_INT_20150131_new_concept.zip"); SnomedConcept concept = getComponent(branchPath, SnomedComponentType.CONCEPT, "63961392103", "pt()") .statusCode(200) .body("pt.id", equalTo("13809498114")) .extract().as(SnomedConcept.class); // assert proper parent/ancestor array updates assertArrayEquals(new long[] { IComponent.ROOT_IDL }, concept.getParentIds()); assertArrayEquals(new long[0], concept.getAncestorIds()); assertArrayEquals(new long[] { Long.valueOf(Concepts.ROOT_CONCEPT) }, concept.getStatedParentIds()); assertArrayEquals(new long[] { IComponent.ROOT_IDL }, concept.getStatedAncestorIds()); } @Test public void import05NewDescription() { getComponent(branchPath, SnomedComponentType.DESCRIPTION, "11320138110").statusCode(404); importArchive("SnomedCT_Release_INT_20150131_new_concept.zip"); importArchive("SnomedCT_Release_INT_20150201_new_description.zip"); getComponent(branchPath, SnomedComponentType.DESCRIPTION, "11320138110").statusCode(200); } @Test public void import06NewRelationship() { getComponent(branchPath, SnomedComponentType.RELATIONSHIP, "24088071128").statusCode(404); importArchive("SnomedCT_Release_INT_20150131_new_concept.zip"); importArchive("SnomedCT_Release_INT_20150202_new_relationship.zip"); getComponent(branchPath, SnomedComponentType.RELATIONSHIP, "24088071128").statusCode(200); } @Test public void import07NewPreferredTerm() { getComponent(branchPath, SnomedComponentType.CONCEPT, "63961392103").statusCode(404); importArchive("SnomedCT_Release_INT_20150131_new_concept.zip"); importArchive("SnomedCT_Release_INT_20150201_new_description.zip"); importArchive("SnomedCT_Release_INT_20150203_change_pt.zip"); getComponent(branchPath, SnomedComponentType.CONCEPT, "63961392103", "pt()").statusCode(200).body("pt.id", equalTo("11320138110")); } @Test public void import08ConceptInactivation() { getComponent(branchPath, SnomedComponentType.CONCEPT, "63961392103").statusCode(404); importArchive("SnomedCT_Release_INT_20150131_new_concept.zip"); importArchive("SnomedCT_Release_INT_20150201_new_description.zip"); importArchive("SnomedCT_Release_INT_20150202_new_relationship.zip"); importArchive("SnomedCT_Release_INT_20150203_change_pt.zip"); importArchive("SnomedCT_Release_INT_20150204_inactivate_concept.zip"); getComponent(branchPath, SnomedComponentType.CONCEPT, "63961392103").statusCode(200).body("active", equalTo(false)); } @Test public void import09ImportSameConceptWithAdditionalDescription() throws Exception { getComponent(branchPath, SnomedComponentType.CONCEPT, "63961392103").statusCode(404); importArchive("SnomedCT_Release_INT_20150131_new_concept.zip"); importArchive("SnomedCT_Release_INT_20150201_new_description.zip"); importArchive("SnomedCT_Release_INT_20150202_new_relationship.zip"); importArchive("SnomedCT_Release_INT_20150203_change_pt.zip"); importArchive("SnomedCT_Release_INT_20150204_inactivate_concept.zip"); getComponent(branchPath, SnomedComponentType.CONCEPT, "63961392103", "pt()").statusCode(200) .body("active", equalTo(false)) .body("pt.id", equalTo("11320138110")); createCodeSystem(branchPath, "SNOMEDCT-EXT").statusCode(201); createVersion("SNOMEDCT-EXT", "v1", "20170301").statusCode(201); /* * In this archive, all components are backdated, so they should have no effect on the dataset, * except a new description 45527646019, which is unpublished and so should appear on the concept. */ importArchive("SnomedCT_Release_INT_20150131_index_init_bug.zip"); getComponent(branchPath, SnomedComponentType.CONCEPT, "63961392103", "pt()").statusCode(200) .body("active", equalTo(false)) .body("pt.id", equalTo("11320138110")); getComponent(branchPath, SnomedComponentType.DESCRIPTION, "45527646019").statusCode(200); } @Test public void import10InvalidBranchPath() { final Map<?, ?> importConfiguration = ImmutableMap.builder() .put("type", Rf2ReleaseType.DELTA.name()) .put("branchPath", "MAIN/x/y/z") .put("createVersions", false) .build(); createImport(importConfiguration).statusCode(404); } @Test public void import11ExtensionConceptWithVersion() { createCodeSystem(branchPath, "SNOMEDCT-NE").statusCode(201); getComponent(branchPath, SnomedComponentType.CONCEPT, "555231000005107").statusCode(404); final Map<?, ?> importConfiguration = ImmutableMap.builder() .put("type", Rf2ReleaseType.DELTA.name()) .put("branchPath", branchPath.getPath()) .put("createVersions", true) .put("codeSystemShortName", "SNOMEDCT-NE") .build(); importArchive("SnomedCT_Release_INT_20150205_new_extension_concept.zip", importConfiguration); getComponent(branchPath, SnomedComponentType.CONCEPT, "555231000005107").statusCode(200); getVersion("SNOMEDCT-NE", "2015-02-05").statusCode(200); } @Test public void import12OnlyPubContentWithVersioning() { validateBranchHeadtimestampUpdate(branchPath, "SnomedCT_RF2Release_INT_20180223_content_with_effective_time.zip", true); } @Test public void import13OnlyPubContentWithOutVersioning() { validateBranchHeadtimestampUpdate(branchPath, "SnomedCT_RF2Release_INT_20180223_content_with_effective_time.zip", false); } @Test public void import14PubAndUnpubContentWithVersioning() { validateBranchHeadtimestampUpdate(branchPath, "SnomedCT_RF2Release_INT_20180223_content_w_and_wo_effective_time.zip", true); } @Test public void import15PubAndUnpubContentWithOutVersioning() { validateBranchHeadtimestampUpdate(branchPath, "SnomedCT_RF2Release_INT_20180223_content_w_and_wo_effective_time.zip", false); } @Test public void import16OnlyUnpubContentWithoutVersioning() { validateBranchHeadtimestampUpdate(branchPath, "SnomedCT_RF2Release_INT_20180223_content_without_effective_time.zip", false); } @Test public void import17OnlyUnpubContentWithVersioning() { validateBranchHeadtimestampUpdate(branchPath, "SnomedCT_RF2Release_INT_20180223_content_without_effective_time.zip", true); } @Test public void import18OnlyPubRefsetMembersWithVersioning() { validateBranchHeadtimestampUpdate(branchPath, "SnomedCT_RF2Release_INT_20180223_only_refset_w_effective_time.zip", true); } @Test public void import19OnlyPubRefsetMembersWithoutVersioning() { validateBranchHeadtimestampUpdate(branchPath, "SnomedCT_RF2Release_INT_20180223_only_refset_w_effective_time.zip", false); } @Test public void import20PubAndUnpubRefsetMembersWithVersioning() { validateBranchHeadtimestampUpdate(branchPath, "SnomedCT_RF2Release_INT_20180223_only_refset_w_and_wo_effective_time.zip", true); } @Test public void import21PubAndUnpubRefsetMembersWithoutVersioning() { validateBranchHeadtimestampUpdate(branchPath, "SnomedCT_RF2Release_INT_20180223_only_refset_w_and_wo_effective_time.zip", false); } @Test public void import22OnlyUnpubRefsetMembersWithoutVersioning() { validateBranchHeadtimestampUpdate(branchPath, "SnomedCT_RF2Release_INT_20180223_only_refset_wo_effective_time.zip", false); } @Test public void import23OnlyUnpubRefsetMembersWithVersioning() { validateBranchHeadtimestampUpdate(branchPath, "SnomedCT_RF2Release_INT_20180223_only_refset_wo_effective_time.zip", true); } @Test public void import24IncompleteTaxonomyMustBeImported() { getComponent(branchPath, SnomedComponentType.CONCEPT, "882169191000154107").statusCode(404); getComponent(branchPath, SnomedComponentType.RELATIONSHIP, "955630781000154129").statusCode(404); importArchive("SnomedCT_RF2Release_INT_20180227_incomplete_taxonomy.zip"); getComponent(branchPath, SnomedComponentType.CONCEPT, "882169191000154107").statusCode(200); getComponent(branchPath, SnomedComponentType.RELATIONSHIP, "955630781000154129").statusCode(200); } @Test public void import25WithMultipleLanguageCodes() { final String enDescriptionId = "41320138114"; final String svDescriptionId = "24688171113"; final String enLanguageRefsetMemberId = "34d07985-48a0-41e7-b6ec-b28e6b00adfc"; final String svLanguageRefsetMemberId = "34d07985-48a0-41e7-b6ec-b28e6b00adfb"; getComponent(branchPath, SnomedComponentType.DESCRIPTION, enDescriptionId).statusCode(404); getComponent(branchPath, SnomedComponentType.DESCRIPTION, svDescriptionId).statusCode(404); getComponent(branchPath, SnomedComponentType.MEMBER, enLanguageRefsetMemberId).statusCode(404); getComponent(branchPath, SnomedComponentType.MEMBER, svLanguageRefsetMemberId).statusCode(404); importArchive("SnomedCT_Release_INT_20150201_descriptions_with_multiple_language_codes.zip"); getComponent(branchPath, SnomedComponentType.DESCRIPTION, enDescriptionId).statusCode(200); getComponent(branchPath, SnomedComponentType.DESCRIPTION, svDescriptionId).statusCode(200); getComponent(branchPath, SnomedComponentType.MEMBER, enLanguageRefsetMemberId).statusCode(200); getComponent(branchPath, SnomedComponentType.MEMBER, svLanguageRefsetMemberId).statusCode(200); } @Test public void import26OWLExpressionReferenceSetMembers() { SnomedConcept oldRoot = getComponent(branchPath, SnomedComponentType.CONCEPT, Concepts.ROOT_CONCEPT, "members()").extract().as(SnomedConcept.class); assertTrue(oldRoot.getMembers().getItems().stream() .noneMatch(m -> m.getReferenceSetId().equals(Concepts.REFSET_OWL_AXIOM) || m.getReferenceSetId().equals(Concepts.REFSET_OWL_ONTOLOGY))); importArchive("SnomedCT_Release_INT_20170731_new_owl_expression_members.zip"); SnomedConcept root = getComponent(branchPath, SnomedComponentType.CONCEPT, Concepts.ROOT_CONCEPT, "members()").extract().as(SnomedConcept.class); Optional<SnomedReferenceSetMember> axiomMember = root.getMembers().getItems().stream() .filter(m -> m.getReferenceSetId().equals(Concepts.REFSET_OWL_AXIOM)) .findFirst(); assertTrue(axiomMember.isPresent()); assertEquals("ec2cc6be-a10b-44b1-a2cc-42a3f11d406e", axiomMember.get().getId()); assertEquals(Concepts.MODULE_SCT_CORE, axiomMember.get().getModuleId()); assertEquals(Concepts.REFSET_OWL_AXIOM, axiomMember.get().getReferenceSetId()); assertEquals(Concepts.ROOT_CONCEPT, axiomMember.get().getReferencedComponent().getId()); assertEquals(OWL_EXPRESSION, axiomMember.get().getProperties().get(SnomedRf2Headers.FIELD_OWL_EXPRESSION)); Optional<SnomedReferenceSetMember> ontologyMember = root.getMembers().getItems().stream() .filter(m -> m.getReferenceSetId().equals(Concepts.REFSET_OWL_ONTOLOGY)) .findFirst(); assertTrue(ontologyMember.isPresent()); assertEquals("f81c24fb-c40a-4b28-9adb-85f748f71395", ontologyMember.get().getId()); assertEquals(Concepts.MODULE_SCT_CORE, ontologyMember.get().getModuleId()); assertEquals(Concepts.REFSET_OWL_ONTOLOGY, ontologyMember.get().getReferenceSetId()); assertEquals(Concepts.ROOT_CONCEPT, ontologyMember.get().getReferencedComponent().getId()); assertEquals("Ontology(<http://snomed.info/sct/900000000000207008>)", ontologyMember.get().getProperties().get(SnomedRf2Headers.FIELD_OWL_EXPRESSION)); } @Test public void import27MRCMReferenceSetMembers() { SnomedConcept rootConcept = getComponent(branchPath, SnomedComponentType.CONCEPT, Concepts.ROOT_CONCEPT, "members()") .extract() .as(SnomedConcept.class); assertTrue(StreamSupport.stream(rootConcept.getMembers().spliterator(), false).noneMatch(m -> { return m.getReferenceSetId().equals(Concepts.REFSET_MRCM_DOMAIN_INTERNATIONAL) || m.getReferenceSetId().equals(Concepts.REFSET_MRCM_ATTRIBUTE_DOMAIN_INTERNATIONAL) || m.getReferenceSetId().equals(Concepts.REFSET_MRCM_ATTRIBUTE_RANGE_INTERNATIONAL) || m.getReferenceSetId().equals(Concepts.REFSET_MRCM_MODULE_SCOPE); })); importArchive("SnomedCT_Release_INT_20170731_new_mrcm_members.zip"); SnomedConcept newRootConcept = getComponent(branchPath, SnomedComponentType.CONCEPT, Concepts.ROOT_CONCEPT, "members()") .extract() .as(SnomedConcept.class); Optional<SnomedReferenceSetMember> mrcmDomainMemberCandidate = StreamSupport.stream(newRootConcept.getMembers().spliterator(), false) .filter(m -> m.getReferenceSetId().equals(Concepts.REFSET_MRCM_DOMAIN_INTERNATIONAL)) .findFirst(); assertTrue(mrcmDomainMemberCandidate.isPresent()); SnomedReferenceSetMember mrcmDomainMember = mrcmDomainMemberCandidate.get(); assertEquals("28ecaa32-8f0e-4ff8-b6b1-b642e40519d8", mrcmDomainMember.getId()); assertEquals(Concepts.MODULE_SCT_MODEL_COMPONENT, mrcmDomainMember.getModuleId()); assertEquals(Concepts.REFSET_MRCM_DOMAIN_INTERNATIONAL, mrcmDomainMember.getReferenceSetId()); assertEquals(Concepts.ROOT_CONCEPT, mrcmDomainMember.getReferencedComponent().getId()); Map<String, Object> domainMemberProps = mrcmDomainMember.getProperties(); assertEquals("domainConstraint", domainMemberProps.get(SnomedRf2Headers.FIELD_MRCM_DOMAIN_CONSTRAINT)); assertEquals("parentDomain", domainMemberProps.get(SnomedRf2Headers.FIELD_MRCM_PARENT_DOMAIN)); assertEquals("proximalPrimitiveConstraint", domainMemberProps.get(SnomedRf2Headers.FIELD_MRCM_PROXIMAL_PRIMITIVE_CONSTRAINT)); assertEquals("proximalPrimitiveRefinement", domainMemberProps.get(SnomedRf2Headers.FIELD_MRCM_PROXIMAL_PRIMITIVE_REFINEMENT)); assertEquals("domainTemplateForPrecoordination", domainMemberProps.get(SnomedRf2Headers.FIELD_MRCM_DOMAIN_TEMPLATE_FOR_PRECOORDINATION)); assertEquals("domainTemplateForPostcoordination", domainMemberProps.get(SnomedRf2Headers.FIELD_MRCM_DOMAIN_TEMPLATE_FOR_POSTCOORDINATION)); assertEquals("guideURL", domainMemberProps.get(SnomedRf2Headers.FIELD_MRCM_EDITORIAL_GUIDE_REFERENCE)); Optional<SnomedReferenceSetMember> mrcmAttributeDomainMemberCandidate = StreamSupport.stream(newRootConcept.getMembers().spliterator(), false) .filter(m -> m.getReferenceSetId().equals(Concepts.REFSET_MRCM_ATTRIBUTE_DOMAIN_INTERNATIONAL)) .findFirst(); assertTrue(mrcmAttributeDomainMemberCandidate.isPresent()); SnomedReferenceSetMember mrcmAttributeDomainMember = mrcmAttributeDomainMemberCandidate.get(); assertEquals("126bf3f1-4f34-439d-ba0a-a832824d072a", mrcmAttributeDomainMember.getId()); assertEquals(Concepts.MODULE_SCT_MODEL_COMPONENT, mrcmAttributeDomainMember.getModuleId()); assertEquals(Concepts.REFSET_MRCM_ATTRIBUTE_DOMAIN_INTERNATIONAL, mrcmAttributeDomainMember.getReferenceSetId()); assertEquals(Concepts.ROOT_CONCEPT, mrcmAttributeDomainMember.getReferencedComponent().getId()); Map<String, Object> attributeDomainMemberProps = mrcmAttributeDomainMember.getProperties(); assertEquals(Concepts.ROOT_CONCEPT, attributeDomainMemberProps.get(SnomedRf2Headers.FIELD_MRCM_DOMAIN_ID)); assertEquals(Boolean.TRUE, attributeDomainMemberProps.get(SnomedRf2Headers.FIELD_MRCM_GROUPED)); assertEquals("attributeCardinality", attributeDomainMemberProps.get(SnomedRf2Headers.FIELD_MRCM_ATTRIBUTE_CARDINALITY)); assertEquals("attributeInGroupCardinality", attributeDomainMemberProps.get(SnomedRf2Headers.FIELD_MRCM_ATTRIBUTE_IN_GROUP_CARDINALITY)); assertEquals(Concepts.ROOT_CONCEPT, attributeDomainMemberProps.get(SnomedRf2Headers.FIELD_MRCM_RULE_STRENGTH_ID)); assertEquals(Concepts.ROOT_CONCEPT, attributeDomainMemberProps.get(SnomedRf2Headers.FIELD_MRCM_CONTENT_TYPE_ID)); Optional<SnomedReferenceSetMember> mrcmAttributeRangeMemberCandidate = StreamSupport.stream(newRootConcept.getMembers().spliterator(), false) .filter(m -> m.getReferenceSetId().equals(Concepts.REFSET_MRCM_ATTRIBUTE_RANGE_INTERNATIONAL)) .findFirst(); assertTrue(mrcmAttributeRangeMemberCandidate.isPresent()); SnomedReferenceSetMember mrcmAttributeRangeMember = mrcmAttributeRangeMemberCandidate.get(); assertEquals("ae090cc3-2827-4e39-80c6-364435d30c17", mrcmAttributeRangeMember.getId()); assertEquals(Concepts.MODULE_SCT_MODEL_COMPONENT, mrcmAttributeRangeMember.getModuleId()); assertEquals(Concepts.REFSET_MRCM_ATTRIBUTE_RANGE_INTERNATIONAL, mrcmAttributeRangeMember.getReferenceSetId()); assertEquals(Concepts.ROOT_CONCEPT, mrcmAttributeRangeMember.getReferencedComponent().getId()); Map<String, Object> attributeRangeMemberProps = mrcmAttributeRangeMember.getProperties(); assertEquals("rangeConstraint", attributeRangeMemberProps.get(SnomedRf2Headers.FIELD_MRCM_RANGE_CONSTRAINT)); assertEquals("attributeRule", attributeRangeMemberProps.get(SnomedRf2Headers.FIELD_MRCM_ATTRIBUTE_RULE)); assertEquals(Concepts.ROOT_CONCEPT, attributeRangeMemberProps.get(SnomedRf2Headers.FIELD_MRCM_RULE_STRENGTH_ID)); assertEquals(Concepts.ROOT_CONCEPT, attributeRangeMemberProps.get(SnomedRf2Headers.FIELD_MRCM_CONTENT_TYPE_ID)); Optional<SnomedReferenceSetMember> mrcmModuleScopeMemberCandidate = StreamSupport.stream(newRootConcept.getMembers().spliterator(), false) .filter(m -> m.getReferenceSetId().equals(Concepts.REFSET_MRCM_MODULE_SCOPE)) .findFirst(); assertTrue(mrcmModuleScopeMemberCandidate.isPresent()); SnomedReferenceSetMember mrmcModuleScopeMember = mrcmModuleScopeMemberCandidate.get(); assertEquals("52d29f1b-f7a3-4a0f-828c-383c6259c3f5", mrmcModuleScopeMember.getId()); assertEquals(Concepts.MODULE_SCT_MODEL_COMPONENT, mrmcModuleScopeMember.getModuleId()); assertEquals(Concepts.REFSET_MRCM_MODULE_SCOPE, mrmcModuleScopeMember.getReferenceSetId()); assertEquals(Concepts.ROOT_CONCEPT, mrmcModuleScopeMember.getReferencedComponent().getId()); assertEquals(Concepts.REFSET_MRCM_DOMAIN_INTERNATIONAL, mrmcModuleScopeMember.getProperties().get(SnomedRf2Headers.FIELD_MRCM_RULE_REFSET_ID)); } @Test public void import28ImportConceptAsInactive() { getComponent(branchPath, SnomedComponentType.CONCEPT, "100005").statusCode(404); importArchive("SnomedCT_Release_INT_20150131_concept_as_inactive.zip"); SnomedConcept concept = getComponent(branchPath, SnomedComponentType.CONCEPT, "100005").statusCode(200).extract().as(SnomedConcept.class); assertArrayEquals(new long[] { IComponent.ROOT_IDL }, concept.getParentIds()); assertArrayEquals(new long[0], concept.getAncestorIds()); assertArrayEquals(new long[] { IComponent.ROOT_IDL }, concept.getStatedParentIds()); assertArrayEquals(new long[0], concept.getStatedAncestorIds()); } private void validateBranchHeadtimestampUpdate(IBranchPath branch, String importArchiveFileName, boolean createVersions) { ValidatableResponse response = SnomedBranchingRestRequests.getBranch(branch); String baseTimestamp = response.extract().jsonPath().getString("baseTimestamp"); String headTimestamp = response.extract().jsonPath().getString("headTimestamp"); assertNotNull(baseTimestamp); assertNotNull(headTimestamp); assertEquals("Base and head timestamp must be equal after branch creation", baseTimestamp, headTimestamp); importArchive(importArchiveFileName, branch, createVersions, Rf2ReleaseType.DELTA); ValidatableResponse response2 = SnomedBranchingRestRequests.getBranch(branch); String baseTimestampAfterImport = response2.extract().jsonPath().getString("baseTimestamp"); String headTimestampAfterImport = response2.extract().jsonPath().getString("headTimestamp"); assertNotNull(baseTimestampAfterImport); assertNotNull(headTimestampAfterImport); assertNotEquals("Base and head timestamp must differ after import", baseTimestampAfterImport, headTimestampAfterImport); } }
923be03961badb141c5df3560a757eec8f7b5343
4,613
java
Java
src/main/java/mainpackage/views/Authors.java
BrendanOswego/csc435-assignment-2
8f03eb7ee6c5af2fb36a0e8835ae86541d4c46f4
[ "MIT" ]
null
null
null
src/main/java/mainpackage/views/Authors.java
BrendanOswego/csc435-assignment-2
8f03eb7ee6c5af2fb36a0e8835ae86541d4c46f4
[ "MIT" ]
null
null
null
src/main/java/mainpackage/views/Authors.java
BrendanOswego/csc435-assignment-2
8f03eb7ee6c5af2fb36a0e8835ae86541d4c46f4
[ "MIT" ]
null
null
null
38.764706
110
0.680251
999,760
package mainpackage.views; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import mainpackage.controller.*; import mainpackage.models.AuthorModel; public class Authors extends HttpServlet { private static final long serialVersionUID = -2767978412483553482L; public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { res.setContentType("application/json"); PrintWriter out = res.getWriter(); Gson gson = new GsonBuilder().setPrettyPrinting().create(); if (req.getPathInfo() == null) { out.println(gson.toJson(API.instance().getAllAuthors())); } else { String[] paths = req.getPathInfo().trim().substring(1).split("/"); String id = paths[0]; if (id != null) { try { if (paths.length >= 2 && paths[1].equals("books")) { out.println(gson.toJson(API.instance().getBooksByAuthor(id))); } else { AuthorModel model = API.instance().getAuthorById(id); out.println(gson.toJson(model != null ? model : "Author does not exist")); } } catch (ArrayIndexOutOfBoundsException e) { e.printStackTrace(); out.println(gson.toJson(API.instance().getAuthorById(id))); } } } out.close(); } public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { res.setContentType("application/json"); PrintWriter out = res.getWriter(); if (req.getPathInfo() == null) { addAuthor(out, req); } else { String[] paths = req.getPathInfo().substring(1).split("/"); if (paths.length == 0) addAuthor(out, req); else if (paths.length == 2) addBook(paths[0], out, req); } out.close(); } public void doPut(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { res.setContentType("application/json"); PrintWriter out = res.getWriter(); if (req.getPathInfo() != null) { String[] paths = req.getPathInfo().substring(1).split("/"); AuthorModel dbAuthor = API.instance().getAuthorById(paths[0]); if (paths.length == 1 && dbAuthor != null) updateAuthor(paths[0], out, req); else if (paths.length == 3 && dbAuthor != null) updateBook(paths[2], out, req); } out.close(); } public void doDelete(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { res.setContentType("application/json"); PrintWriter out = res.getWriter(); if (req.getPathInfo() != null) { String[] paths = req.getPathInfo().substring(1).split("/"); AuthorModel dbAuthor = API.instance().getAuthorById(paths[0]); if (paths.length == 1 && dbAuthor != null) removeAuthor(paths[0], res.getWriter(), req); else if (paths.length == 3 && dbAuthor != null) removeBookByAuthor(paths[0], paths[2], out, req); } out.close(); } private void addAuthor(PrintWriter out, HttpServletRequest req) { Gson gson = new GsonBuilder().setPrettyPrinting().create(); out.println(gson.toJson(API.instance().addAuthor(req))); } private void addBook(String author_id, PrintWriter out, HttpServletRequest req) { Gson gson = new GsonBuilder().setPrettyPrinting().create(); out.println(gson.toJson(API.instance().addBookToAuthor(author_id, req, out))); } private void updateAuthor(String author_id, PrintWriter out, HttpServletRequest req) { Gson gson = new GsonBuilder().setPrettyPrinting().create(); out.println(gson.toJson(API.instance().updateAuthor(author_id, req))); } private void updateBook(String book_id, PrintWriter out, HttpServletRequest req) { Gson gson = new GsonBuilder().setPrettyPrinting().create(); out.println(gson.toJson(API.instance().updateBook(book_id, req))); } private void removeAuthor(String author_id, PrintWriter out, HttpServletRequest req) { Gson gson = new GsonBuilder().setPrettyPrinting().create(); out.println(gson.toJson(API.instance().removeAuthor(author_id, req))); } private void removeBookByAuthor(String author_id, String book_id, PrintWriter out, HttpServletRequest req) { Gson gson = new GsonBuilder().setPrettyPrinting().create(); out.println(gson.toJson(API.instance().removeBookByAuthor(author_id, book_id, req))); } }
923be07265801124c6f5a820ca0f8ea754d50f6e
1,545
java
Java
components/sbm-support-jee/src/generated/web/java/org/springframework/sbm/project/web/api/WarPathType.java
Maarc/spring-boot-migrator
fb5c15a15aec1890df4d72ef7b02ce72a13e8bef
[ "Apache-2.0" ]
32
2022-02-28T09:21:27.000Z
2022-03-31T05:11:17.000Z
components/sbm-support-jee/src/generated/web/java/org/springframework/sbm/project/web/api/WarPathType.java
Maarc/spring-boot-migrator
fb5c15a15aec1890df4d72ef7b02ce72a13e8bef
[ "Apache-2.0" ]
32
2022-03-01T14:54:05.000Z
2022-03-31T09:43:55.000Z
components/sbm-support-jee/src/generated/web/java/org/springframework/sbm/project/web/api/WarPathType.java
Maarc/spring-boot-migrator
fb5c15a15aec1890df4d72ef7b02ce72a13e8bef
[ "Apache-2.0" ]
10
2022-02-28T11:15:36.000Z
2022-03-31T21:58:11.000Z
27.589286
95
0.693851
999,761
/* * Copyright 2021 - 2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.sbm.project.web.api; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * * * The elements that use this type designate a path starting * with a "/" and interpreted relative to the root of a WAR * file. * * * * <p>Java class for war-pathType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="war-pathType"&gt; * &lt;simpleContent&gt; * &lt;restriction base="&lt;http://xmlns.jcp.org/xml/ns/javaee&gt;string"&gt; * &lt;/restriction&gt; * &lt;/simpleContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "war-pathType") public class WarPathType extends String { }
923be0cc64b5149134fa4495f487409648f93543
4,185
java
Java
oak-solr-core/src/test/java/org/apache/jackrabbit/oak/plugins/index/solr/query/FilterQueryParserTest.java
meggermo/jackrabbit-oak
7174b4f9d8b87a5891b1b0b96cfc7bd30a49bf99
[ "Apache-2.0" ]
288
2015-01-11T04:09:03.000Z
2022-03-28T22:20:09.000Z
oak-solr-core/src/test/java/org/apache/jackrabbit/oak/plugins/index/solr/query/FilterQueryParserTest.java
meggermo/jackrabbit-oak
7174b4f9d8b87a5891b1b0b96cfc7bd30a49bf99
[ "Apache-2.0" ]
154
2016-10-30T11:31:04.000Z
2022-03-31T14:20:52.000Z
oak-solr-core/src/test/java/org/apache/jackrabbit/oak/plugins/index/solr/query/FilterQueryParserTest.java
meggermo/jackrabbit-oak
7174b4f9d8b87a5891b1b0b96cfc7bd30a49bf99
[ "Apache-2.0" ]
405
2015-01-15T16:15:56.000Z
2022-03-24T08:27:08.000Z
45.48913
126
0.712067
999,762
/* * 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.jackrabbit.oak.plugins.index.solr.query; import org.apache.jackrabbit.oak.plugins.index.solr.configuration.DefaultSolrConfiguration; import org.apache.jackrabbit.oak.plugins.index.solr.configuration.OakSolrConfiguration; import org.apache.jackrabbit.oak.spi.query.Filter; import org.apache.jackrabbit.oak.spi.query.QueryIndex; import org.apache.solr.client.solrj.SolrQuery; import org.junit.Test; import java.util.Arrays; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * Testcase for {@link FilterQueryParser} */ public class FilterQueryParserTest { @Test public void testMatchAllConversionWithNoConstraints() throws Exception { Filter filter = mock(Filter.class); OakSolrConfiguration configuration = mock(OakSolrConfiguration.class); QueryIndex.IndexPlan plan = mock(QueryIndex.IndexPlan.class); SolrQuery solrQuery = FilterQueryParser.getQuery(filter, plan, configuration); assertNotNull(solrQuery); assertEquals("*:*", solrQuery.getQuery()); } @Test public void testAllChildrenQueryParsing() throws Exception { String query = "select [jcr:path], [jcr:score], * from [nt:hierarchy] as a where isdescendantnode(a, '/')"; Filter filter = mock(Filter.class); OakSolrConfiguration configuration = new DefaultSolrConfiguration(){ @Override public boolean useForPathRestrictions() { return true; } }; when(filter.getQueryStatement()).thenReturn(query); Filter.PathRestriction pathRestriction = Filter.PathRestriction.ALL_CHILDREN; when(filter.getPathRestriction()).thenReturn(pathRestriction); when(filter.getPath()).thenReturn("/"); QueryIndex.IndexPlan plan = mock(QueryIndex.IndexPlan.class); SolrQuery solrQuery = FilterQueryParser.getQuery(filter, plan, configuration); assertNotNull(solrQuery); String[] filterQueries = solrQuery.getFilterQueries(); assertTrue(Arrays.asList(filterQueries).contains(configuration.getFieldForPathRestriction(pathRestriction) + ":\\/")); assertEquals("*:*", solrQuery.get("q")); } @Test public void testCollapseJcrContentNodes() throws Exception { String query = "select [jcr:path], [jcr:score], * from [nt:hierarchy] as a where isdescendantnode(a, '/')"; Filter filter = mock(Filter.class); OakSolrConfiguration configuration = new DefaultSolrConfiguration(){ @Override public boolean collapseJcrContentNodes() { return true; } }; when(filter.getQueryStatement()).thenReturn(query); QueryIndex.IndexPlan plan = mock(QueryIndex.IndexPlan.class); SolrQuery solrQuery = FilterQueryParser.getQuery(filter, plan, configuration); assertNotNull(solrQuery); String[] filterQueries = solrQuery.getFilterQueries(); assertTrue(Arrays.asList(filterQueries).contains("{!collapse field=" + configuration.getCollapsedPathField() + " min=" + configuration.getPathDepthField() + " hint=top_fc nullPolicy=expand}")); assertEquals("*:*", solrQuery.get("q")); } }
923be0e498f701abf96dae55b2f99184f4ced6e7
7,183
java
Java
lib/src/main/java/io/xpush/chat/view/adapters/MessageListAdapter.java
xpush/lib-xpush-android
6e36c50d54a9b7c8c0071c3c32f71c8c85426329
[ "MIT" ]
6
2015-08-22T12:35:23.000Z
2017-07-11T07:52:33.000Z
lib/src/main/java/io/xpush/chat/view/adapters/MessageListAdapter.java
xpush/lib-xpush-android
6e36c50d54a9b7c8c0071c3c32f71c8c85426329
[ "MIT" ]
null
null
null
lib/src/main/java/io/xpush/chat/view/adapters/MessageListAdapter.java
xpush/lib-xpush-android
6e36c50d54a9b7c8c0071c3c32f71c8c85426329
[ "MIT" ]
3
2016-08-15T11:00:58.000Z
2021-05-12T23:00:04.000Z
38.827027
136
0.624252
999,763
package io.xpush.chat.view.adapters; import android.content.Context; import android.graphics.Bitmap; import android.net.Uri; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.bumptech.glide.Glide; import com.bumptech.glide.load.engine.DiskCacheStrategy; import com.bumptech.glide.request.animation.GlideAnimation; import com.bumptech.glide.request.target.SimpleTarget; import com.facebook.drawee.view.SimpleDraweeView; import org.json.JSONException; import org.json.JSONObject; import java.util.List; import io.xpush.chat.R; import io.xpush.chat.models.XPushMessage; import io.xpush.chat.util.ContentUtils; import io.xpush.chat.util.DateUtils; public class MessageListAdapter extends RecyclerView.Adapter<MessageListAdapter.ViewHolder> { private List<XPushMessage> mXPushMessages; private static MessageClickListener mMessageClickListener; private Context mContext; public MessageListAdapter(Context context, List<XPushMessage> xpushMessages) { mContext = context; mXPushMessages = xpushMessages; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { int layout = -1; if (viewType == XPushMessage.TYPE_SEND_MESSAGE ) { layout = R.layout.item_send_message; } else if (viewType == XPushMessage.TYPE_RECEIVE_MESSAGE ) { layout = R.layout.item_receive_message; } else if (viewType == XPushMessage.TYPE_INVITE || viewType == XPushMessage.TYPE_LEAVE ) { layout = R.layout.item_invite_message; } else if (viewType == XPushMessage.TYPE_SEND_IMAGE ) { layout = R.layout.item_send_image; } else if (viewType == XPushMessage.TYPE_RECEIVE_IMAGE ) { layout = R.layout.item_receive_image; } View v = LayoutInflater.from(parent.getContext()).inflate(layout, parent, false); return new ViewHolder(v); } @Override public void onBindViewHolder(ViewHolder viewHolder, int position) { XPushMessage xpushMessage = mXPushMessages.get(position); viewHolder.setUsername(xpushMessage.getSenderName()); viewHolder.setTime(xpushMessage.getUpdated()); viewHolder.setImage(xpushMessage.getImage()); viewHolder.setMessage(xpushMessage.getMessage(), xpushMessage.getType(), xpushMessage.getMetadata()); } @Override public int getItemCount() { return mXPushMessages.size(); } @Override public int getItemViewType(int position) { return mXPushMessages.get(position).getType(); } public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener { private TextView tvUser; private TextView tvTime; private SimpleDraweeView thumbNail; private View vMessage; private View vClickableView; private ViewHolder(View itemView) { super(itemView); tvTime = (TextView) itemView.findViewById(R.id.tvTime); tvUser = (TextView) itemView.findViewById(R.id.tvUser); thumbNail = (SimpleDraweeView) itemView.findViewById(R.id.thumbnail); vMessage = (View) itemView.findViewById(R.id.vMessage); vClickableView = (View)itemView.findViewById(R.id.bubble); vClickableView.setOnClickListener(this); vClickableView.setOnLongClickListener(this); } @Override public void onClick(View view) { int position = ViewHolder.super.getAdapterPosition(); mMessageClickListener.onMessageClick(mXPushMessages.get(position).getMessage(), mXPushMessages.get(position).getType()); } @Override public boolean onLongClick(View view) { int position = ViewHolder.super.getAdapterPosition(); mMessageClickListener.onMessageLongClick(mXPushMessages.get(position).getMessage(), mXPushMessages.get(position).getType()); return true; } public void setUsername(String username) { if (null == tvUser) return; tvUser.setText(username); } public void setMessage(String message, int type, final JSONObject metatdata) { if (null == vMessage) return; if( type == XPushMessage.TYPE_SEND_IMAGE || type == XPushMessage.TYPE_RECEIVE_IMAGE ) { final ImageView imageView = ((ImageView) vMessage); if( metatdata != null ){ try { int metaWidth = metatdata.getInt("W"); int metaHeight = metatdata.getInt("H"); if( metaWidth > 0 && metaHeight > 0 ) { int results[] = ContentUtils.getActualImageSize(metaWidth, metaHeight, mContext); LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(results[0], results[1]); imageView.setLayoutParams(layoutParams); } } catch ( JSONException e ){ e.printStackTrace(); } } Glide.with(mContext) .load(Uri.parse(message)) .asBitmap() .diskCacheStrategy(DiskCacheStrategy.ALL) .fitCenter() .into(new SimpleTarget<Bitmap>() { @Override public void onResourceReady(Bitmap bitmap, GlideAnimation anim) { int originalWidth = bitmap.getWidth(); int originalHeight = bitmap.getHeight(); if( metatdata == null ) { //int results[] = ContentUtils.getActualImageSize(originalWidth, originalHeight, mContext); //LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(results[0], results[1]); //imageView.setLayoutParams(layoutParams); } imageView.setImageBitmap(bitmap); } }); } else { ( (TextView) vMessage ).setText(message); } } public void setTime(long timestamp) { if (null == tvTime) return; tvTime.setText(DateUtils.getDate(timestamp, "a h:mm")); } public void setImage(String image) { if (null == image || null == thumbNail) return; thumbNail.setImageURI(Uri.parse(image)); } } public void setOnItemClickListener(MessageClickListener clickListener) { MessageListAdapter.mMessageClickListener = clickListener; } public interface MessageClickListener { public void onMessageClick(String message, int type); public void onMessageLongClick(String message, int type); } }