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
92348b570184e0f20492d014363dce9fa09b30f2
12,536
java
Java
src/main/java/org/kilocraft/essentials/user/ServerUser.java
MCrafterzz/KiloEssentials
6b0d952a06ab17994a0f630d5a0cf96ea58eb635
[ "MIT" ]
1
2020-03-04T17:13:20.000Z
2020-03-04T17:13:20.000Z
src/main/java/org/kilocraft/essentials/user/ServerUser.java
MCrafterzz/KiloEssentials
6b0d952a06ab17994a0f630d5a0cf96ea58eb635
[ "MIT" ]
null
null
null
src/main/java/org/kilocraft/essentials/user/ServerUser.java
MCrafterzz/KiloEssentials
6b0d952a06ab17994a0f630d5a0cf96ea58eb635
[ "MIT" ]
null
null
null
30.353511
184
0.653478
996,954
package org.kilocraft.essentials.user; import com.mojang.brigadier.exceptions.CommandSyntaxException; import com.mojang.brigadier.exceptions.SimpleCommandExceptionType; import net.minecraft.nbt.CompoundTag; import net.minecraft.server.network.ServerPlayerEntity; import net.minecraft.text.LiteralText; import net.minecraft.text.Text; import net.minecraft.util.Formatting; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.kilocraft.essentials.EssentialPermission; import org.kilocraft.essentials.api.KiloEssentials; import org.kilocraft.essentials.api.KiloServer; import org.kilocraft.essentials.api.ModConstants; import org.kilocraft.essentials.api.text.MessageReceptionist; import org.kilocraft.essentials.api.text.TextFormat; import org.kilocraft.essentials.api.user.OnlineUser; import org.kilocraft.essentials.api.user.User; import org.kilocraft.essentials.api.user.settting.Setting; import org.kilocraft.essentials.api.user.settting.UserSettings; import org.kilocraft.essentials.api.world.location.Location; import org.kilocraft.essentials.api.world.location.Vec3dLocation; import org.kilocraft.essentials.chat.UserMessageReceptionist; import org.kilocraft.essentials.config.KiloConfig; import org.kilocraft.essentials.user.setting.ServerUserSettings; import org.kilocraft.essentials.user.setting.Settings; import org.kilocraft.essentials.util.nbt.NBTUtils; import org.kilocraft.essentials.util.player.UserUtils; import org.kilocraft.essentials.util.text.Texter; import java.io.IOException; import java.text.ParseException; import java.util.*; /** * Main User Implementation * * @author CODY_AI (OnBlock) * @see User * @see ServerUserManager * @see UserHomeHandler * @see UserSettings * @see OnlineUser * @see org.kilocraft.essentials.api.user.CommandSourceUser * @see org.kilocraft.essentials.user.UserHandler * @see net.minecraft.entity.player.PlayerEntity * @see net.minecraft.server.network.ServerPlayerEntity * @since 1.5 */ public class ServerUser implements User { public static final int SYS_MESSAGE_COOL_DOWN = 400; protected static final ServerUserManager MANAGER = (ServerUserManager) KiloServer.getServer().getUserManager(); private final ServerUserSettings settings; private UserHomeHandler homeHandler; private Vec3dLocation lastLocation; private boolean hasJoinedBefore = true; private Date firstJoin = new Date(); public int messageCoolDown; public int systemMessageCoolDown; private MessageReceptionist lastDmReceptionist; final UUID uuid; String name = ""; String savedName = ""; Vec3dLocation location; boolean isStaff = false; String lastSocketAddress; int ticksPlayed = 0; Date lastOnline; public ServerUser(@NotNull final UUID uuid) { this.uuid = uuid; this.settings = new ServerUserSettings(); if (UserHomeHandler.isEnabled()) { this.homeHandler = new UserHomeHandler(this); } try { MANAGER.getHandler().handleUser(this); } catch (IOException e) { KiloEssentials.getLogger().fatal("Failed to Load User Data [" + uuid.toString() + "]", e); } } public CompoundTag toTag() { CompoundTag mainTag = new CompoundTag(); CompoundTag metaTag = new CompoundTag(); CompoundTag cacheTag = new CompoundTag(); // Here we store the players current location if (this.location != null) { this.location.shortDecimals(); mainTag.put("loc", this.location.toTag()); } if (this.lastLocation != null) { cacheTag.put("cLoc", this.lastLocation.toTag()); } if (this.lastSocketAddress != null) { cacheTag.putString("ip", this.lastSocketAddress); } metaTag.putString("firstJoin", ModConstants.DATE_FORMAT.format(this.firstJoin)); if (this.lastOnline != null) { metaTag.putString("lastOnline", ModConstants.DATE_FORMAT.format(this.lastOnline)); } if (this.ticksPlayed != -1) { metaTag.putInt("ticksPlayed", this.ticksPlayed); } if (this.isStaff) { metaTag.putBoolean("isStaff", true); } if (UserHomeHandler.isEnabled() || this.homeHandler != null) { CompoundTag homeTag = new CompoundTag(); this.homeHandler.serialize(homeTag); mainTag.put("homes", homeTag); } mainTag.put("meta", metaTag); mainTag.put("cache", cacheTag); mainTag.put("settings", this.settings.toTag()); mainTag.putString("name", this.name); return mainTag; } public void fromTag(@NotNull CompoundTag compoundTag) { CompoundTag metaTag = compoundTag.getCompound("meta"); CompoundTag cacheTag = compoundTag.getCompound("cache"); if (cacheTag.contains("lastLoc")) { this.lastLocation = Vec3dLocation.dummy(); this.lastLocation.fromTag(cacheTag.getCompound("lastLoc")); } if (compoundTag.contains("loc")) { this.location = Vec3dLocation.dummy(); this.location.fromTag(compoundTag.getCompound("loc")); this.location.shortDecimals(); } if (cacheTag.contains("ip")) { this.lastSocketAddress = cacheTag.getString("ip"); } if (cacheTag.contains("dmRec")) { CompoundTag lastDmTag = cacheTag.getCompound("dmRec"); this.lastDmReceptionist = new UserMessageReceptionist(lastDmTag.getString("name"), NBTUtils.getUUID(lastDmTag, "id")); } this.firstJoin = dateFromString(metaTag.getString("firstJoin")); this.lastOnline = dateFromString(metaTag.getString("lastOnline")); this.hasJoinedBefore = metaTag.getBoolean("hasJoinedBefore"); if (metaTag.contains("ticksPlayed")) { this.ticksPlayed = metaTag.getInt("ticksPlayed"); } if (metaTag.contains("isStaff")) { this.isStaff = true; } if (UserHomeHandler.isEnabled()) { this.homeHandler.deserialize(compoundTag.getCompound("homes")); } this.savedName = compoundTag.getString("name"); if (cacheTag.contains("IIP")) { this.lastSocketAddress = cacheTag.getString("IIP"); KiloEssentials.getLogger().info("Updating ip for " + savedName); } this.settings.fromTag(compoundTag.getCompound("settings")); } public void updateLocation() { if (this.isOnline() && ((OnlineUser) this).asPlayer().getPos() != null) { this.location = Vec3dLocation.of(((OnlineUser) this).asPlayer()).shortDecimals(); } } private Date dateFromString(String stringToParse) { Date date = new Date(); try { date = ModConstants.DATE_FORMAT.parse(stringToParse); } catch (ParseException ignored) { this.hasJoinedBefore = false; } return date; } @Nullable public UserHomeHandler getHomesHandler() { return this.homeHandler; } @Nullable @Override public String getLastSocketAddress() { return this.lastSocketAddress; } @Override public int getTicksPlayed() { return this.ticksPlayed; } @Override public void setTicksPlayed(int ticks) { this.ticksPlayed = ticks; } @Override public boolean isOnline() { return this instanceof OnlineUser || MANAGER.isOnline(this); } @Override public boolean hasNickname() { return this.getNickname().isPresent(); } public String getDisplayName() { return this.getNickname().orElseGet(() -> this.name); } @Override public String getFormattedDisplayName() { return TextFormat.translate(this.getDisplayName() + TextFormat.RESET.toString()); } @Override public Text getRankedDisplayName() { if (this.isOnline()) { return UserUtils.getDisplayNameWithMeta((OnlineUser) this, true); } return Texter.newText(this.getDisplayName()); } @Override public Text getRankedName() { if (this.isOnline()) { return UserUtils.getDisplayNameWithMeta((OnlineUser) this, false); } return Texter.newText(this.name); } @Override public String getNameTag() { String str = this.isOnline() ? KiloConfig.messages().general().userTags().online : KiloConfig.messages().general().userTags().offline; return str.replace("{USER_NAME}", this.name) .replace("{USER_DISPLAYNAME}", this.getFormattedDisplayName()); } @Override public UUID getUuid() { return this.uuid; } @Override public String getUsername() { return this.name; } @Override public UserSettings getSettings() { return this.settings; } @Override public <T> T getSetting(Setting<T> setting) { return this.settings.get(setting); } @Override public Optional<String> getNickname() { return this.getSetting(Settings.NICK); } @Override public Location getLocation() { if (this.isOnline() || (this.isOnline() && this.location == null)) { updateLocation(); } return this.location; } @Nullable @Override public Location getLastSavedLocation() { return this.lastLocation; } @Override public void saveLocation() { if (this instanceof OnlineUser) this.lastLocation = Vec3dLocation.of((OnlineUser) this).shortDecimals(); } @Override public void setNickname(String name) { this.getSettings().set(Settings.NICK, Optional.of(name)); KiloServer.getServer().getUserManager().onChangeNickname(this, this.getNickname().isPresent() ? this.getNickname().get() : ""); // This is to update the entries in UserManager. } @Override public void clearNickname() { KiloServer.getServer().getUserManager().onChangeNickname(this, null); // This is to update the entries in UserManager. this.getSettings().reset(Settings.NICK); } @Override public void setLastLocation(Location loc) { this.lastLocation = (Vec3dLocation) loc; } @Override public boolean hasJoinedBefore() { return this.hasJoinedBefore; } @Override public Date getFirstJoin() { return this.firstJoin; } @Override public @Nullable Date getLastOnline() { return this.lastOnline; } @Override public void saveData() throws IOException { if (!this.isOnline()) MANAGER.getHandler().save(this); } @Override public void trySave() throws CommandSyntaxException { if (this.isOnline()) return; try { this.saveData(); } catch (IOException e) { throw new SimpleCommandExceptionType(new LiteralText(e.getMessage()).formatted(Formatting.RED)).create(); } } public boolean isStaff() { if (this.isOnline()) this.isStaff = KiloEssentials.hasPermissionNode(((OnlineUser) this).getCommandSource(), EssentialPermission.STAFF); return this.isStaff; } @Override public boolean equals(User anotherUser) { return anotherUser == this || anotherUser.getUuid().equals(this.uuid) || anotherUser.getUsername().equals(this.getUsername()); } @Override public boolean ignored(UUID uuid) { return this.getSetting(Settings.IGNORE_LIST).containsValue(uuid); } @Override public MessageReceptionist getLastMessageReceptionist() { return this.lastDmReceptionist; } @Override public void setLastMessageReceptionist(MessageReceptionist receptionist) { this.lastDmReceptionist = receptionist; } public static void saveLocationOf(ServerPlayerEntity player) { OnlineUser user = KiloServer.getServer().getOnlineUser(player); if (user != null) { user.saveLocation(); } } public boolean shouldMessage() { return !this.getSetting(Settings.DON_NOT_DISTURB); } public ServerUser useSavedName() { this.name = this.savedName; return this; } @Override public String getName() { return this.name; } @Override public UUID getId() { return this.uuid; } }
92348d9bca7d81006d5df428bcc5177593b980fb
446
java
Java
mobile_app1/module161/src/main/java/module161packageJava0/Foo15.java
HiWong/android-build-eval
d909ab37bc8d5d3a188ba9c9f0855f846f6f3af6
[ "Apache-2.0" ]
70
2021-01-22T16:48:06.000Z
2022-02-16T10:37:33.000Z
mobile_app1/module161/src/main/java/module161packageJava0/Foo15.java
HiWong/android-build-eval
d909ab37bc8d5d3a188ba9c9f0855f846f6f3af6
[ "Apache-2.0" ]
16
2021-01-22T20:52:52.000Z
2021-08-09T17:51:24.000Z
mobile_app1/module161/src/main/java/module161packageJava0/Foo15.java
HiWong/android-build-eval
d909ab37bc8d5d3a188ba9c9f0855f846f6f3af6
[ "Apache-2.0" ]
5
2021-01-26T13:53:49.000Z
2021-08-11T20:10:57.000Z
11.15
45
0.567265
996,955
package module161packageJava0; import java.lang.Integer; public class Foo15 { Integer int0; Integer int1; Integer int2; public void foo0() { new module161packageJava0.Foo14().foo6(); } public void foo1() { foo0(); } public void foo2() { foo1(); } public void foo3() { foo2(); } public void foo4() { foo3(); } public void foo5() { foo4(); } public void foo6() { foo5(); } }
92348ead753a7e0727c31e644c95a04643d7ecfe
3,085
java
Java
src/main/java/com/inlym/lifehelper/login/scanlogin/QrcodeTicketService.java
inlym/life-helper-server
9fb4d1662b532fc3510e6480776752fe267fb34b
[ "MIT" ]
35
2022-01-18T16:45:32.000Z
2022-03-31T09:16:45.000Z
src/main/java/com/inlym/lifehelper/login/scanlogin/QrcodeTicketService.java
inlym/life-helper-server
9fb4d1662b532fc3510e6480776752fe267fb34b
[ "MIT" ]
null
null
null
src/main/java/com/inlym/lifehelper/login/scanlogin/QrcodeTicketService.java
inlym/life-helper-server
9fb4d1662b532fc3510e6480776752fe267fb34b
[ "MIT" ]
1
2022-03-30T04:33:52.000Z
2022-03-30T04:33:52.000Z
23.549618
74
0.597731
996,956
package com.inlym.lifehelper.login.scanlogin; import com.inlym.lifehelper.common.base.aliyun.oss.OssDir; import com.inlym.lifehelper.common.base.aliyun.oss.OssService; import com.inlym.lifehelper.external.weixin.WeixinService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; import java.util.UUID; /** * 小程序码凭证编码服务 * * <h2>说明 * <li>当前包中的 `Qrcode` 均指微信小程序码,不是普通的二维码。 * <li>这里提到的 “凭证编码” 就是其他处出现的 `ticket`。 * * @author <a href="https://www.inlym.com">inlym</a> * @date 2022/4/12 * @since 1.1.0 **/ @Service @Slf4j @RequiredArgsConstructor public class QrcodeTicketService { /** 凭证编码列表的 Redis 键名 */ public static final String TICKET_LIST_KEY = "scan_login:ticket_list"; private final WeixinService weixinService; private final StringRedisTemplate stringRedisTemplate; private final OssService ossService; /** * 根据凭证编号获取其在 OSS 中的存储路径 * * @param ticket 凭证编号 * * @since 1.1.0 */ public String getPathname(String ticket) { return OssDir.WXACODE + "/" + ticket + ".png"; } /** * 生成一个凭证编码 * * <h2>主要流程 * <li>使用去掉短横线的 UUID 作为凭证编码 * <li>生成对应参数的小程序码 * <li>将小程序码上传到 OSS * <li>将凭证编码存入 Redis 的对应列表,用于后续获取 * * <h2>备注 * <p>整个流程调用链较长,耗时较大,在本地开发环境实测整个方法的总耗时在 200ms ~ 600ms 之间。 * * @since 1.1.0 */ public String createTicket() { String page = "pages/scan/login"; String ticket = UUID .randomUUID() .toString() .replaceAll("-", ""); int width = 430; // 请求微信服务器获取小程序码 byte[] bytes = weixinService.generateWxacode(page, ticket, width); // 将图片上传至 OSS ossService.upload(getPathname(ticket), bytes); // 存储到 Redis stringRedisTemplate .opsForList() .leftPush(TICKET_LIST_KEY, ticket); return ticket; } /** * 批量生成指定个数的凭证编码(异步) * * <h2>主要用途 * <p>同步方法耗时较长,在请求中调用,整个请求时长会很久,因此在特定情况下,使用异步方法提前生成凭证编号,后续直接从列表中获取即可。 * * <h2>使用说明 * <p>当前方法可在任意处调用,内部处理了是否执行了逻辑。 * * @param fewNum 较低值,剩余量低于该值则执行方法批量生成若干个凭证编码 * @param createNum 生成个数 * * @since 1.1.0 */ @Async public void createTicketsWhenFewAsync(int fewNum, int createNum) { Long rest = stringRedisTemplate .opsForList() .size(TICKET_LIST_KEY); assert rest != null; if (rest <= fewNum) { for (int i = 0; i < createNum; i++) { createTicket(); } } } /** * 获取一个可用的码凭证编号 * * @since 1.1.0 */ public String getTicket() { String ticket = stringRedisTemplate .opsForList() .rightPop(TICKET_LIST_KEY); if (ticket != null) { return ticket; } // 当列表为空时,实时生成一个再返回 return createTicket(); } }
92348f2d18f413441aebbd1634b6f3747a59144d
2,504
java
Java
src/main/java/core/commands/stats/TotalArtistNumberCommand.java
ishwi/Chuu
d783ce57aab16c2040594dfe4e9f78832d054455
[ "MIT" ]
106
2021-01-05T03:09:56.000Z
2022-03-31T09:05:37.000Z
src/main/java/core/commands/stats/TotalArtistNumberCommand.java
ishwi/Chuu
d783ce57aab16c2040594dfe4e9f78832d054455
[ "MIT" ]
29
2021-01-17T22:21:27.000Z
2022-01-29T14:20:17.000Z
src/main/java/core/commands/stats/TotalArtistNumberCommand.java
ishwi/Chuu
d783ce57aab16c2040594dfe4e9f78832d054455
[ "MIT" ]
20
2021-01-11T12:26:08.000Z
2022-03-19T20:32:41.000Z
32.102564
168
0.684904
996,957
package core.commands.stats; import core.commands.Context; import core.commands.abstracts.ConcurrentCommand; import core.commands.utils.CommandCategory; import core.commands.utils.CommandUtil; import core.parsers.NumberParser; import core.parsers.OnlyUsernameParser; import core.parsers.Parser; import core.parsers.params.ChuuDataParams; import core.parsers.params.NumberParameters; import dao.ServiceView; import javax.annotation.Nonnull; import java.util.HashMap; import java.util.List; import java.util.Map; import static core.parsers.ExtraParser.LIMIT_ERROR; public class TotalArtistNumberCommand extends ConcurrentCommand<NumberParameters<ChuuDataParams>> { public TotalArtistNumberCommand(ServiceView dao) { super(dao); } @Override protected CommandCategory initCategory() { return CommandCategory.USER_STATS; } @Override public Parser<NumberParameters<ChuuDataParams>> initParser() { Map<Integer, String> map = new HashMap<>(2); map.put(LIMIT_ERROR, "The number introduced must be positive and not very big"); String s = "You can also introduce the playcount to only show artists above that number of plays"; return new NumberParser<>(new OnlyUsernameParser(db), -0L, Integer.MAX_VALUE, map, s, false, true, true, "filter"); } @Override public String getDescription() { return ("Number of artists listened by an user"); } @Override public List<String> getAliases() { return List.of("artists", "art"); } @Override protected void onCommand(Context e, @Nonnull NumberParameters<ChuuDataParams> params) { ChuuDataParams innerParams = params.getInnerParams(); String lastFmName = innerParams.getLastFMData().getName(); long discordID = innerParams.getLastFMData().getDiscordId(); String username = getUserString(e, discordID, lastFmName); int threshold = params.getExtraParam().intValue(); int plays = db.getUserArtistCount(lastFmName, threshold == 0 ? -1 : threshold); String filler = ""; if (threshold != 0) { filler += " with more than " + threshold + " plays"; } sendMessageQueue(e, String.format("**%s** has scrobbled **%d** different %s%s", username, plays, CommandUtil.singlePlural(plays, "artist", "artists"), filler)); } @Override public String getName() { return "Artist count "; } }
923491cd9436633f94d6bc5ea44a9009e45cc365
1,428
java
Java
mall-member/src/main/java/com/cmkj/mall/member/sms/SmsMultiSenderResult.java
swallowff/spring-boot-mall
1cff983474111f32b18564b0381f279afe56bed8
[ "Apache-2.0" ]
1
2021-03-18T13:33:45.000Z
2021-03-18T13:33:45.000Z
mall-member/src/main/java/com/cmkj/mall/member/sms/SmsMultiSenderResult.java
swallowff/spring-boot-mall
1cff983474111f32b18564b0381f279afe56bed8
[ "Apache-2.0" ]
null
null
null
mall-member/src/main/java/com/cmkj/mall/member/sms/SmsMultiSenderResult.java
swallowff/spring-boot-mall
1cff983474111f32b18564b0381f279afe56bed8
[ "Apache-2.0" ]
null
null
null
22.666667
83
0.536415
996,958
package com.cmkj.mall.member.sms; import java.util.ArrayList; public class SmsMultiSenderResult { /* { "result": 0, "errmsg": "OK", "ext": "", "detail": [ { "result": 0, "errmsg": "OK", "mobile": "13788888888", "nationcode": "86", "sid": "xxxxxxx", "fee": 1 }, { "result": 0, "errmsg": "OK", "mobile": "13788888889", "nationcode": "86", "sid": "xxxxxxx", "fee": 1 } ] } */ public class Detail { public int result; public String errMsg = ""; public String phoneNumber = ""; public String nationCode = ""; public String sid = ""; public int fee; public String toString() { if (0 == result) { return String.format( "Detail result %d\nerrMsg %s\nphoneNumber %s\nnationCode %s\nsid %s\nfee %d", result, errMsg, phoneNumber, nationCode, sid, fee); } else { return String.format( "result %d\nerrMsg %s\nphoneNumber %s\nnationCode %s", result, errMsg, phoneNumber, nationCode); } } } public int result; public String errMsg = ""; public String ext = ""; public ArrayList<Detail> details; public String toString() { return String.format( "SmsMultiSenderResult\nresult %d\nerrMsg %s\next %s\ndetails %s", result, errMsg, ext, details); } }
923491d0b090e91058f6e4943079e2520fc51cce
1,328
java
Java
src/main/java/com/leetcode/frog_jump/Solution1.java
magnetic1/leetcode
4577439aac13f095bc1f20adec5521520b3bef70
[ "MIT" ]
2
2021-02-23T09:07:16.000Z
2021-11-02T08:40:11.000Z
src/main/java/com/leetcode/frog_jump/Solution1.java
magnetic1/leetcode
4577439aac13f095bc1f20adec5521520b3bef70
[ "MIT" ]
null
null
null
src/main/java/com/leetcode/frog_jump/Solution1.java
magnetic1/leetcode
4577439aac13f095bc1f20adec5521520b3bef70
[ "MIT" ]
null
null
null
27.102041
58
0.415663
996,959
/** * Leetcode - frog_jump */ package com.leetcode.frog_jump; import java.util.*; import com.ciaoshen.leetcode.util.*; /** * log instance is defined in Solution interface * this is how slf4j will work in this class: * ============================================= * if (log.isDebugEnabled()) { * log.debug("a + b = {}", sum); * } * ============================================= */ class Solution1 implements Solution { public boolean canCross(int[] stones) { if (stones.length <= 0) { return false; } if (stones.length == 1) { return true; } if (stones[1] - stones[0] != 1) { return false; } Set<Integer>[] jumps = new HashSet[stones.length]; jumps[0] = new HashSet<>(); jumps[0].add(1); for (int i = 1; i < stones.length; i++) { jumps[i] = new HashSet<>(); for (int j = 0; j < i; j++) { for (int jump : jumps[j]) { if (jump + stones[j] == stones[i]) { jumps[i].add(jump); jumps[i].add(jump + 1); jumps[i].add(jump - 1); } } } } return !jumps[stones.length - 1].isEmpty(); } }
923491df51917dbb9bed51da9c1b0c300416a87d
1,512
java
Java
entity-view/testsuite/src/test/java/com/blazebit/persistence/view/testsuite/update/subview/inverse/embedded/simple/model/LegacyOrderPositionDefaultIdView.java
sullrich84/blaze-persistence
f5a374fedf8cb1a24c769e37de56bd44e91afcf3
[ "ECL-2.0", "Apache-2.0" ]
884
2015-02-17T16:29:05.000Z
2022-03-31T05:01:09.000Z
entity-view/testsuite/src/test/java/com/blazebit/persistence/view/testsuite/update/subview/inverse/embedded/simple/model/LegacyOrderPositionDefaultIdView.java
sullrich84/blaze-persistence
f5a374fedf8cb1a24c769e37de56bd44e91afcf3
[ "ECL-2.0", "Apache-2.0" ]
1,105
2015-01-07T08:49:17.000Z
2022-03-31T09:40:50.000Z
entity-view/testsuite/src/test/java/com/blazebit/persistence/view/testsuite/update/subview/inverse/embedded/simple/model/LegacyOrderPositionDefaultIdView.java
sullrich84/blaze-persistence
f5a374fedf8cb1a24c769e37de56bd44e91afcf3
[ "ECL-2.0", "Apache-2.0" ]
66
2015-03-12T16:43:39.000Z
2022-03-22T06:55:15.000Z
32.869565
109
0.758598
996,960
/* * Copyright 2014 - 2021 Blazebit. * * 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.blazebit.persistence.view.testsuite.update.subview.inverse.embedded.simple.model; import com.blazebit.persistence.view.EntityView; import com.blazebit.persistence.view.UpdatableEntityView; import com.blazebit.persistence.view.testsuite.entity.LegacyOrderPositionDefault; import com.blazebit.persistence.view.testsuite.entity.LegacyOrderPositionDefaultId; /** * * @author Christian Beikov * @since 1.2.0 */ @EntityView(LegacyOrderPositionDefault.class) public interface LegacyOrderPositionDefaultIdView extends IdHolderView<LegacyOrderPositionDefaultIdView.Id> { @UpdatableEntityView @EntityView(LegacyOrderPositionDefaultId.class) interface Id { Long getOrderId(); void setOrderId(Long orderId); Integer getPosition(); void setPosition(Integer position); Integer getSupplierId(); void setSupplierId(Integer supplierId); } }
92349206919bad29a31e0157a285deabfd278dbd
2,574
java
Java
test/framework/src/main/java/org/elasticsearch/test/InternalSettingsPlugin.java
diwasjoshi/elasticsearch
58ce0f94a0bbdf2576e0a00a62abe1854ee7fe2f
[ "Apache-2.0" ]
null
null
null
test/framework/src/main/java/org/elasticsearch/test/InternalSettingsPlugin.java
diwasjoshi/elasticsearch
58ce0f94a0bbdf2576e0a00a62abe1854ee7fe2f
[ "Apache-2.0" ]
null
null
null
test/framework/src/main/java/org/elasticsearch/test/InternalSettingsPlugin.java
diwasjoshi/elasticsearch
58ce0f94a0bbdf2576e0a00a62abe1854ee7fe2f
[ "Apache-2.0" ]
null
null
null
37.304348
107
0.735431
996,961
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.test; import org.elasticsearch.cluster.metadata.IndexMetadata; import org.elasticsearch.common.settings.Setting; import org.elasticsearch.common.settings.Setting.Property; import org.elasticsearch.core.TimeValue; import org.elasticsearch.index.IndexModule; import org.elasticsearch.index.IndexService; import org.elasticsearch.index.IndexSettings; import org.elasticsearch.monitor.fs.FsService; import org.elasticsearch.plugins.Plugin; import org.elasticsearch.transport.RemoteConnectionStrategy; import java.util.Arrays; import java.util.List; import java.util.concurrent.TimeUnit; public final class InternalSettingsPlugin extends Plugin { public static final Setting<String> PROVIDED_NAME_SETTING = Setting.simpleString( "index.provided_name", Property.IndexScope, Property.NodeScope ); public static final Setting<Boolean> MERGE_ENABLED = Setting.boolSetting( "index.merge.enabled", true, Property.IndexScope, Property.NodeScope ); public static final Setting<Long> INDEX_CREATION_DATE_SETTING = Setting.longSetting( IndexMetadata.SETTING_CREATION_DATE, -1, -1, Property.IndexScope, Property.NodeScope ); public static final Setting<TimeValue> TRANSLOG_RETENTION_CHECK_INTERVAL_SETTING = Setting.timeSetting( "index.translog.retention.check_interval", new TimeValue(10, TimeUnit.MINUTES), new TimeValue(-1, TimeUnit.MILLISECONDS), Property.Dynamic, Property.IndexScope ); @Override public List<Setting<?>> getSettings() { return Arrays.asList( MERGE_ENABLED, INDEX_CREATION_DATE_SETTING, PROVIDED_NAME_SETTING, TRANSLOG_RETENTION_CHECK_INTERVAL_SETTING, RemoteConnectionStrategy.REMOTE_MAX_PENDING_CONNECTION_LISTENERS, IndexService.GLOBAL_CHECKPOINT_SYNC_INTERVAL_SETTING, IndexService.RETENTION_LEASE_SYNC_INTERVAL_SETTING, IndexSettings.FILE_BASED_RECOVERY_THRESHOLD_SETTING, IndexModule.INDEX_QUERY_CACHE_EVERYTHING_SETTING, FsService.ALWAYS_REFRESH_SETTING ); } }
923492ee948d444d761e9df14993a8ba6c8ac896
862
java
Java
changgou-service/changgou-service-order-ribbon/src/main/java/com/changgou/order/controller/OrderController.java
xiaojiesir/changgou-parent
25c40b084c70d66f3a92f0edf7de2d41cf1b8383
[ "MIT" ]
null
null
null
changgou-service/changgou-service-order-ribbon/src/main/java/com/changgou/order/controller/OrderController.java
xiaojiesir/changgou-parent
25c40b084c70d66f3a92f0edf7de2d41cf1b8383
[ "MIT" ]
null
null
null
changgou-service/changgou-service-order-ribbon/src/main/java/com/changgou/order/controller/OrderController.java
xiaojiesir/changgou-parent
25c40b084c70d66f3a92f0edf7de2d41cf1b8383
[ "MIT" ]
1
2021-09-09T09:19:32.000Z
2021-09-09T09:19:32.000Z
30.785714
75
0.772622
996,962
package com.changgou.order.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; @RestController @RequestMapping("/order") @CrossOrigin public class OrderController { public static final String URL = "http://ribbon-goods"; private RestTemplate restTemplate; @Autowired public void setRestTemplate(RestTemplate restTemplate) { this.restTemplate = restTemplate; } @GetMapping(value = "/goods") public String getGoods() { return restTemplate.getForObject(URL + "/goods/get", String.class); } }
923492f72c059a3457679e1f2356ece678c5ff60
2,208
java
Java
core/src/main/java/org/ehcache/config/persistence/PersistentStoreConfigurationImpl.java
sreekanth-r/ehcache3
4f9dae58da13ee77ab3c9e2f306920234b4b0ad6
[ "Apache-2.0" ]
null
null
null
core/src/main/java/org/ehcache/config/persistence/PersistentStoreConfigurationImpl.java
sreekanth-r/ehcache3
4f9dae58da13ee77ab3c9e2f306920234b4b0ad6
[ "Apache-2.0" ]
null
null
null
core/src/main/java/org/ehcache/config/persistence/PersistentStoreConfigurationImpl.java
sreekanth-r/ehcache3
4f9dae58da13ee77ab3c9e2f306920234b4b0ad6
[ "Apache-2.0" ]
null
null
null
26.285714
113
0.732337
996,963
/* * Copyright Terracotta, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ehcache.config.persistence; import org.ehcache.config.EvictionPrioritizer; import org.ehcache.config.EvictionVeto; import org.ehcache.config.ResourcePools; import org.ehcache.config.ResourceType; import org.ehcache.expiry.Expiry; import org.ehcache.spi.cache.Store; /** * @author Alex Snaps */ public class PersistentStoreConfigurationImpl<K, V> implements Store.PersistentStoreConfiguration<K, V, String> { private final Store.Configuration<K, V> config; private final String identifier; public PersistentStoreConfigurationImpl(Store.Configuration<K, V> config, String identifier) { this.config = config; this.identifier = identifier; } @Override public String getIdentifier() { return identifier; } @Override public boolean isPersistent() { return config.getResourcePools().getPoolForResource(ResourceType.Core.DISK).isPersistent(); } @Override public Class<K> getKeyType() { return config.getKeyType(); } @Override public Class<V> getValueType() { return config.getValueType(); } @Override public EvictionVeto<? super K, ? super V> getEvictionVeto() { return config.getEvictionVeto(); } @Override public EvictionPrioritizer<? super K, ? super V> getEvictionPrioritizer() { return config.getEvictionPrioritizer(); } @Override public ClassLoader getClassLoader() { return config.getClassLoader(); } @Override public Expiry<? super K, ? super V> getExpiry() { return config.getExpiry(); } @Override public ResourcePools getResourcePools() { return config.getResourcePools(); } }
9234936ebc7002a4a5860096ddd44ec71c01ebd8
5,143
java
Java
src/sources/com/google/common/base/MoreObjects.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/com/google/common/base/MoreObjects.java
ghuntley/COVIDSafe_1.0.11.apk
ba4133e6c8092d7c2881562fcb0c46ec7af04ecb
[ "Apache-2.0" ]
null
null
null
src/sources/com/google/common/base/MoreObjects.java
ghuntley/COVIDSafe_1.0.11.apk
ba4133e6c8092d7c2881562fcb0c46ec7af04ecb
[ "Apache-2.0" ]
8
2020-04-27T00:37:19.000Z
2020-05-05T07:54:07.000Z
30.981928
119
0.552401
996,964
package com.google.common.base; import java.util.Arrays; import org.checkerframework.checker.nullness.compatqual.NullableDecl; public final class MoreObjects { public static <T> T firstNonNull(@NullableDecl T t, @NullableDecl T t2) { if (t != null) { return t; } if (t2 != null) { return t2; } throw new NullPointerException("Both parameters are null"); } public static ToStringHelper toStringHelper(Object obj) { return new ToStringHelper(obj.getClass().getSimpleName()); } public static ToStringHelper toStringHelper(Class<?> cls) { return new ToStringHelper(cls.getSimpleName()); } public static ToStringHelper toStringHelper(String str) { return new ToStringHelper(str); } public static final class ToStringHelper { private final String className; private final ValueHolder holderHead; private ValueHolder holderTail; private boolean omitNullValues; private ToStringHelper(String str) { ValueHolder valueHolder = new ValueHolder(); this.holderHead = valueHolder; this.holderTail = valueHolder; this.omitNullValues = false; this.className = (String) Preconditions.checkNotNull(str); } public ToStringHelper omitNullValues() { this.omitNullValues = true; return this; } public ToStringHelper add(String str, @NullableDecl Object obj) { return addHolder(str, obj); } public ToStringHelper add(String str, boolean z) { return addHolder(str, String.valueOf(z)); } public ToStringHelper add(String str, char c) { return addHolder(str, String.valueOf(c)); } public ToStringHelper add(String str, double d) { return addHolder(str, String.valueOf(d)); } public ToStringHelper add(String str, float f) { return addHolder(str, String.valueOf(f)); } public ToStringHelper add(String str, int i) { return addHolder(str, String.valueOf(i)); } public ToStringHelper add(String str, long j) { return addHolder(str, String.valueOf(j)); } public ToStringHelper addValue(@NullableDecl Object obj) { return addHolder(obj); } public ToStringHelper addValue(boolean z) { return addHolder(String.valueOf(z)); } public ToStringHelper addValue(char c) { return addHolder(String.valueOf(c)); } public ToStringHelper addValue(double d) { return addHolder(String.valueOf(d)); } public ToStringHelper addValue(float f) { return addHolder(String.valueOf(f)); } public ToStringHelper addValue(int i) { return addHolder(String.valueOf(i)); } public ToStringHelper addValue(long j) { return addHolder(String.valueOf(j)); } public String toString() { boolean z = this.omitNullValues; StringBuilder sb = new StringBuilder(32); sb.append(this.className); sb.append('{'); String str = ""; for (ValueHolder valueHolder = this.holderHead.next; valueHolder != null; valueHolder = valueHolder.next) { Object obj = valueHolder.value; if (!z || obj != null) { sb.append(str); if (valueHolder.name != null) { sb.append(valueHolder.name); sb.append('='); } if (obj == null || !obj.getClass().isArray()) { sb.append(obj); } else { String deepToString = Arrays.deepToString(new Object[]{obj}); sb.append(deepToString, 1, deepToString.length() - 1); } str = ", "; } } sb.append('}'); return sb.toString(); } private ValueHolder addHolder() { ValueHolder valueHolder = new ValueHolder(); this.holderTail.next = valueHolder; this.holderTail = valueHolder; return valueHolder; } private ToStringHelper addHolder(@NullableDecl Object obj) { addHolder().value = obj; return this; } private ToStringHelper addHolder(String str, @NullableDecl Object obj) { ValueHolder addHolder = addHolder(); addHolder.value = obj; addHolder.name = (String) Preconditions.checkNotNull(str); return this; } private static final class ValueHolder { @NullableDecl String name; @NullableDecl ValueHolder next; @NullableDecl Object value; private ValueHolder() { } } } private MoreObjects() { } }
923495565705911277b7dbded52e0bfabe468b11
5,907
java
Java
src/main/java/net/cuplex/morestructures/world/BeachHutGenerator.java
Cuplex17/cuplex-more-structures
888f76484054ad322f571cc766ba3bb9d04c72ce
[ "CC0-1.0" ]
null
null
null
src/main/java/net/cuplex/morestructures/world/BeachHutGenerator.java
Cuplex17/cuplex-more-structures
888f76484054ad322f571cc766ba3bb9d04c72ce
[ "CC0-1.0" ]
null
null
null
src/main/java/net/cuplex/morestructures/world/BeachHutGenerator.java
Cuplex17/cuplex-more-structures
888f76484054ad322f571cc766ba3bb9d04c72ce
[ "CC0-1.0" ]
null
null
null
44.75
208
0.643982
996,965
package net.cuplex.morestructures.world; import net.cuplex.morestructures.MoreStructures; import net.minecraft.block.Blocks; import net.minecraft.block.entity.LootableContainerBlockEntity; import net.minecraft.datafixers.fixes.ChunkPalettedStorageFix; import net.minecraft.entity.EntityType; import net.minecraft.entity.passive.VillagerEntity; import net.minecraft.entity.passive.WanderingTraderEntity; import net.minecraft.nbt.CompoundTag; import net.minecraft.structure.*; import net.minecraft.structure.processor.BlockIgnoreStructureProcessor; import net.minecraft.util.BlockMirror; import net.minecraft.util.BlockRotation; import net.minecraft.util.Identifier; import net.minecraft.util.math.BlockPos; import net.minecraft.util.math.ChunkPos; import net.minecraft.util.math.MutableIntBoundingBox; import net.minecraft.world.Heightmap; import net.minecraft.world.IWorld; import net.minecraft.world.World; import net.minecraft.world.gen.feature.DefaultFeatureConfig; import net.minecraft.world.loot.LootTables; import java.util.List; import java.util.Random; public class BeachHutGenerator { public static final Identifier id = new Identifier("morestructures", "beach_hut"); //public static final Identifier lootTableID = new Identifier("morestructures", "beach_hut_loot"); public static void addParts(StructureManager structureManager, BlockPos blockPos, BlockRotation rotation, List<StructurePiece> list_1, Random random, DefaultFeatureConfig defaultFeatureConfig) { list_1.add(new BeachHutGenerator.Piece(structureManager, id, blockPos, rotation)); } public static class Piece extends SimpleStructurePiece { private final Identifier identifier; public Piece(StructureManager structureManager_1, CompoundTag compoundTag_1) { super(MoreStructures.BEACH_HUT_PIECE_TYPE, compoundTag_1); this.identifier = new Identifier(compoundTag_1.getString("Template")); this.setStructureData(structureManager_1); } public Piece(StructureManager structureManager, Identifier identifier, BlockPos pos, BlockRotation rotation) { super(MoreStructures.BEACH_HUT_PIECE_TYPE, 0); this.identifier = identifier; this.pos = pos; this.setStructureData(structureManager); } public void setStructureData(StructureManager structureManager) { Structure structure_1 = structureManager.getStructureOrBlank(this.identifier); StructurePlacementData structurePlacementData_1 = (new StructurePlacementData()).setMirrored(BlockMirror.NONE).setPosition(pos).addProcessor(BlockIgnoreStructureProcessor.IGNORE_STRUCTURE_BLOCKS); this.setStructureData(structure_1, this.pos, structurePlacementData_1); } @Override protected void handleMetadata(String string_1, BlockPos blockPos, IWorld iWorld, Random random, MutableIntBoundingBox mutableIntBoundingBox) { if("loot_chest".equals(string_1)) { LootableContainerBlockEntity.setLootTable(iWorld, random, blockPos.down(), LootTables.FISHING_GAMEPLAY); } if("work_station".equals(string_1)) { Random rand_1 = new Random(); int int_1 = rand_1.nextInt(10); switch(int_1) { case 1: iWorld.setBlockState(blockPos.down(), Blocks.LOOM.getDefaultState(), 1); break; case 2: iWorld.setBlockState(blockPos.down(), Blocks.BARREL.getDefaultState(), 1); break; case 3: iWorld.setBlockState(blockPos.down(), Blocks.SMOKER.getDefaultState(), 1); break; case 4: iWorld.setBlockState(blockPos.down(), Blocks.BLAST_FURNACE.getDefaultState(), 1); break; case 5: iWorld.setBlockState(blockPos.down(), Blocks.CARTOGRAPHY_TABLE.getDefaultState(), 1); break; case 6: iWorld.setBlockState(blockPos.down(), Blocks.FLETCHING_TABLE.getDefaultState(), 1); break; case 7: iWorld.setBlockState(blockPos.down(), Blocks.GRINDSTONE.getDefaultState(), 1); break; case 8: iWorld.setBlockState(blockPos.down(), Blocks.SMITHING_TABLE.getDefaultState(), 1); break; case 9: iWorld.setBlockState(blockPos.down(), Blocks.STONECUTTER.getDefaultState(), 1); break; default: iWorld.setBlockState(blockPos.down(), Blocks.BARREL.getDefaultState(), 1); } } World world = iWorld.getWorld(); VillagerEntity villagerEntity= new VillagerEntity(EntityType.VILLAGER, world); villagerEntity.setPersistent(); villagerEntity.setPositionAndAngles(blockPos, 0.0F, 0.0F); if("villager".equals(string_1)) { iWorld.spawnEntity(villagerEntity); } iWorld.setBlockState(blockPos, Blocks.AIR.getDefaultState(), 1); } @Override public boolean generate(IWorld iWorld_1, Random random_1, MutableIntBoundingBox mutableIntBoundingBox_1, ChunkPos chunkPos_1) { int yHeight = iWorld_1.getTop(Heightmap.Type.WORLD_SURFACE_WG, this.pos.getX(), this.pos.getZ()); this.pos = this.pos.add(0, yHeight - 6, 0); return super.generate(iWorld_1, random_1, mutableIntBoundingBox_1, chunkPos_1); } } }
9234956209c85e158a73fdcc79e39790ae6960b1
1,817
java
Java
src/test/java/org/codelibs/fess/taglib/FessFunctionsTest.java
jhult/fess
2aaaae11a8492bd16e92ddd0af748b859c3ac9a8
[ "Apache-2.0" ]
null
null
null
src/test/java/org/codelibs/fess/taglib/FessFunctionsTest.java
jhult/fess
2aaaae11a8492bd16e92ddd0af748b859c3ac9a8
[ "Apache-2.0" ]
null
null
null
src/test/java/org/codelibs/fess/taglib/FessFunctionsTest.java
jhult/fess
2aaaae11a8492bd16e92ddd0af748b859c3ac9a8
[ "Apache-2.0" ]
null
null
null
37.854167
81
0.704458
996,966
/* * Copyright 2012-2019 CodeLibs Project and the Others. * * 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.codelibs.fess.taglib; import java.util.Date; import org.codelibs.fess.unit.UnitFessTestCase; public class FessFunctionsTest extends UnitFessTestCase { public void test_parseDate() { Date date; date = FessFunctions.parseDate(""); assertNull(date); date = FessFunctions.parseDate("2004-04-01T12:34:56.123Z"); assertEquals("2004-04-01T12:34:56.123Z", FessFunctions.formatDate(date)); date = FessFunctions.parseDate("2004-04-01T12:34:56Z"); assertEquals("2004-04-01T12:34:56.000Z", FessFunctions.formatDate(date)); date = FessFunctions.parseDate("2004-04-01T12:34Z"); assertEquals("2004-04-01T12:34:00.000Z", FessFunctions.formatDate(date)); date = FessFunctions.parseDate("2004-04-01"); assertEquals("2004-04-01T00:00:00.000Z", FessFunctions.formatDate(date)); date = FessFunctions.parseDate("2004-04-01T12:34:56.123+09:00"); assertEquals("2004-04-01T03:34:56.123Z", FessFunctions.formatDate(date)); date = FessFunctions.parseDate("D:20040401033456-05'00'", "pdf_date"); assertEquals("2004-04-01T08:34:56.000Z", FessFunctions.formatDate(date)); } }
9234959213433ce29d6e7c4a49d0fb480ed69818
2,726
java
Java
src/main/java/org/bian/dto/CRCurrencyExchangeTransactionRetrieveOutputModelCurrencyExchangeTransactionInstanceAnalysis.java
bianapis/sd-currency-exchange-v3
fb1332909eb50e6f60d61b1d6579bacad7cd0e50
[ "Apache-2.0" ]
null
null
null
src/main/java/org/bian/dto/CRCurrencyExchangeTransactionRetrieveOutputModelCurrencyExchangeTransactionInstanceAnalysis.java
bianapis/sd-currency-exchange-v3
fb1332909eb50e6f60d61b1d6579bacad7cd0e50
[ "Apache-2.0" ]
null
null
null
src/main/java/org/bian/dto/CRCurrencyExchangeTransactionRetrieveOutputModelCurrencyExchangeTransactionInstanceAnalysis.java
bianapis/sd-currency-exchange-v3
fb1332909eb50e6f60d61b1d6579bacad7cd0e50
[ "Apache-2.0" ]
null
null
null
41.938462
226
0.841893
996,967
package org.bian.dto; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import javax.validation.Valid; /** * CRCurrencyExchangeTransactionRetrieveOutputModelCurrencyExchangeTransactionInstanceAnalysis */ public class CRCurrencyExchangeTransactionRetrieveOutputModelCurrencyExchangeTransactionInstanceAnalysis { private String currencyExchangeTransactionInstanceAnalysisData = null; private String currencyExchangeTransactionInstanceAnalysisReportType = null; private Object currencyExchangeTransactionInstanceAnalysisReport = null; /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Text general-info: The inputs and results of the instance analysis that can be on-going, periodic and actual and projected * @return currencyExchangeTransactionInstanceAnalysisData **/ public String getCurrencyExchangeTransactionInstanceAnalysisData() { return currencyExchangeTransactionInstanceAnalysisData; } public void setCurrencyExchangeTransactionInstanceAnalysisData(String currencyExchangeTransactionInstanceAnalysisData) { this.currencyExchangeTransactionInstanceAnalysisData = currencyExchangeTransactionInstanceAnalysisData; } /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Code general-info: The type of external performance analysis report available * @return currencyExchangeTransactionInstanceAnalysisReportType **/ public String getCurrencyExchangeTransactionInstanceAnalysisReportType() { return currencyExchangeTransactionInstanceAnalysisReportType; } public void setCurrencyExchangeTransactionInstanceAnalysisReportType(String currencyExchangeTransactionInstanceAnalysisReportType) { this.currencyExchangeTransactionInstanceAnalysisReportType = currencyExchangeTransactionInstanceAnalysisReportType; } /** * `status: Not Mapped` core-data-type-reference: BIAN::DataTypesLibrary::CoreDataTypes::UNCEFACT::Binary general-info: The external analysis report in any suitable form including selection filters where appropriate * @return currencyExchangeTransactionInstanceAnalysisReport **/ public Object getCurrencyExchangeTransactionInstanceAnalysisReport() { return currencyExchangeTransactionInstanceAnalysisReport; } public void setCurrencyExchangeTransactionInstanceAnalysisReport(Object currencyExchangeTransactionInstanceAnalysisReport) { this.currencyExchangeTransactionInstanceAnalysisReport = currencyExchangeTransactionInstanceAnalysisReport; } }
9234962a5906865a5373f950aeddd3d1d9b2907c
546
java
Java
backend/src/main/java/fr/inra/urgi/datadiscovery/dao/faidare/FaidareDocumentHighlighter.java
Ninja-Squad/data-discovery
72475f4755971c44f3b39a24e71ecb0202af7c8d
[ "BSD-3-Clause" ]
null
null
null
backend/src/main/java/fr/inra/urgi/datadiscovery/dao/faidare/FaidareDocumentHighlighter.java
Ninja-Squad/data-discovery
72475f4755971c44f3b39a24e71ecb0202af7c8d
[ "BSD-3-Clause" ]
1
2022-03-10T15:39:17.000Z
2022-03-10T15:39:17.000Z
backend/src/main/java/fr/inra/urgi/datadiscovery/dao/faidare/FaidareDocumentHighlighter.java
Ninja-Squad/data-discovery
72475f4755971c44f3b39a24e71ecb0202af7c8d
[ "BSD-3-Clause" ]
null
null
null
34.125
94
0.802198
996,968
package fr.inra.urgi.datadiscovery.dao.faidare; import fr.inra.urgi.datadiscovery.dao.AbstractDocumentHighlighter; import fr.inra.urgi.datadiscovery.domain.faidare.FaidareDocument; /** * The highlighter for Faidare documents * @author JB Nizet */ public class FaidareDocumentHighlighter extends AbstractDocumentHighlighter<FaidareDocument> { @Override protected FaidareDocument clone(FaidareDocument document, String newDescription) { return FaidareDocument.builder(document).withDescription(newDescription).build(); } }
923496844e15ba70ed05d8cf071bd60bb5796583
176
java
Java
android/src/main/java/com/thebluealliance/androidclient/auth/User.java
randomtestfive/the-blue-alliance-android
5c94e11e5640a08a3547c16646efec3f018835c8
[ "MIT" ]
65
2015-01-31T16:15:24.000Z
2022-03-28T15:14:00.000Z
android/src/main/java/com/thebluealliance/androidclient/auth/User.java
randomtestfive/the-blue-alliance-android
5c94e11e5640a08a3547c16646efec3f018835c8
[ "MIT" ]
538
2015-01-16T20:48:24.000Z
2022-03-30T16:39:20.000Z
android/src/main/java/com/thebluealliance/androidclient/auth/User.java
randomtestfive/the-blue-alliance-android
5c94e11e5640a08a3547c16646efec3f018835c8
[ "MIT" ]
44
2015-01-09T01:41:09.000Z
2020-06-19T22:24:25.000Z
13.538462
47
0.715909
996,969
package com.thebluealliance.androidclient.auth; import android.net.Uri; public interface User { String getName(); String getEmail(); Uri getProfilePicUrl(); }
923496938da580e605215b015b7d7f799f8cea39
666
java
Java
src/main/java/com/biprom/bram/amcalapp/mongoRepositories/KlantenRepository.java
biprom/amcalapp
66e053b4ea05b260fbb04f7f8a0daee54d60a2d7
[ "Xnet", "X11" ]
null
null
null
src/main/java/com/biprom/bram/amcalapp/mongoRepositories/KlantenRepository.java
biprom/amcalapp
66e053b4ea05b260fbb04f7f8a0daee54d60a2d7
[ "Xnet", "X11" ]
null
null
null
src/main/java/com/biprom/bram/amcalapp/mongoRepositories/KlantenRepository.java
biprom/amcalapp
66e053b4ea05b260fbb04f7f8a0daee54d60a2d7
[ "Xnet", "X11" ]
null
null
null
37
83
0.855856
996,970
package com.biprom.bram.amcalapp.mongoRepositories; import com.biprom.bram.amcalapp.data.entity.mongodbEntities.Klanten; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface KlantenRepository extends MongoRepository<Klanten, String> { public List<Klanten> findByBedrijfsNaamContainsIgnoreCase(String bedrijfsNaam); public List<Klanten> findByBtwNummerContainsIgnoreCase(String btwNummer); public List<Klanten> findByAanvragers_VoorNaamContainsIgnoreCase(String voornaam); public List<Klanten> findByAliasContainsIgnoreCase(String alias); }
9234969e214ea9be26862d9e063d495ccb9e05f3
705
java
Java
src/main/java/uk/joshiejack/shopaholic/plugins/kubejs/event/ItemGetValueEventJS.java
Harvest-Festival/Shopaholic
1fd0f4ef0de894ced1653cb94d76ebd305a544e5
[ "MIT" ]
null
null
null
src/main/java/uk/joshiejack/shopaholic/plugins/kubejs/event/ItemGetValueEventJS.java
Harvest-Festival/Shopaholic
1fd0f4ef0de894ced1653cb94d76ebd305a544e5
[ "MIT" ]
7
2021-07-11T10:18:14.000Z
2022-01-12T19:53:12.000Z
src/main/java/uk/joshiejack/shopaholic/plugins/kubejs/event/ItemGetValueEventJS.java
Harvest-Festival/Shopaholic
1fd0f4ef0de894ced1653cb94d76ebd305a544e5
[ "MIT" ]
1
2022-02-06T20:03:53.000Z
2022-02-06T20:03:53.000Z
24.310345
57
0.700709
996,971
package uk.joshiejack.shopaholic.plugins.kubejs.event; import dev.latvian.kubejs.event.EventJS; import dev.latvian.kubejs.item.ItemStackJS; import uk.joshiejack.shopaholic.event.ItemGetValueEvent; public class ItemGetValueEventJS extends EventJS { private final ItemGetValueEvent event; public ItemGetValueEventJS(ItemGetValueEvent event) { this.event = event; } public long getValue() { return event.getValue(); } public ItemStackJS getItem() { return ItemStackJS.of(event.getStack()); } public void setNewValue(long value) { event.setNewValue(value); } public long getNewValue() { return event.getNewValue(); } }
923496ab174ff38edf55ea7aa76a1d4dc9533089
3,542
java
Java
Data/Juliet-Java/Juliet-Java-v103/000/142/757/CWE760_Predictable_Salt_One_Way_Hash__basic_04.java
b19e93n/PLC-Pyramid
6d5b57be6995a94ef7402144cee965862713b031
[ "MIT" ]
null
null
null
Data/Juliet-Java/Juliet-Java-v103/000/142/757/CWE760_Predictable_Salt_One_Way_Hash__basic_04.java
b19e93n/PLC-Pyramid
6d5b57be6995a94ef7402144cee965862713b031
[ "MIT" ]
null
null
null
Data/Juliet-Java/Juliet-Java-v103/000/142/757/CWE760_Predictable_Salt_One_Way_Hash__basic_04.java
b19e93n/PLC-Pyramid
6d5b57be6995a94ef7402144cee965862713b031
[ "MIT" ]
null
null
null
34.72549
98
0.636646
996,972
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE760_Predictable_Salt_One_Way_Hash__basic_04.java Label Definition File: CWE760_Predictable_Salt_One_Way_Hash__basic.label.xml Template File: point-flaw-04.tmpl.java */ /* * @description * CWE: 760 Use of one-way hash with a predictable salt * Sinks: * GoodSink: SHA512 with a sufficiently random salt * BadSink : SHA512 with a predictable salt * Flow Variant: 04 Control flow: if(PRIVATE_STATIC_FINAL_TRUE) and if(PRIVATE_STATIC_FINAL_FALSE) * * */ import java.security.MessageDigest; import java.security.SecureRandom; import java.util.Random; public class CWE760_Predictable_Salt_One_Way_Hash__basic_04 extends AbstractTestCase { /* The two variables below are declared "final", so a tool should * be able to identify that reads of these will always return their * initialized values. */ private static final boolean PRIVATE_STATIC_FINAL_TRUE = true; private static final boolean PRIVATE_STATIC_FINAL_FALSE = false; public void bad() throws Throwable { if (PRIVATE_STATIC_FINAL_TRUE) { Random random = new Random(); MessageDigest hash = MessageDigest.getInstance("SHA-512"); /* FLAW: SHA512 with a predictable salt */ hash.update((Integer.toString(random.nextInt())).getBytes("UTF-8")); byte[] hashValue = hash.digest("hash me".getBytes("UTF-8")); IO.writeLine(IO.toHex(hashValue)); } } /* good1() changes PRIVATE_STATIC_FINAL_TRUE to PRIVATE_STATIC_FINAL_FALSE */ private void good1() throws Throwable { if (PRIVATE_STATIC_FINAL_FALSE) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ IO.writeLine("Benign, fixed string"); } else { SecureRandom secureRandom = new SecureRandom(); MessageDigest hash = MessageDigest.getInstance("SHA-512"); /* FIX: Use a sufficiently random salt */ SecureRandom prng = SecureRandom.getInstance("SHA1PRNG"); hash.update(prng.generateSeed(32)); byte[] hashValue = hash.digest("hash me".getBytes("UTF-8")); IO.writeLine(IO.toHex(hashValue)); } } /* good2() reverses the bodies in the if statement */ private void good2() throws Throwable { if (PRIVATE_STATIC_FINAL_TRUE) { SecureRandom secureRandom = new SecureRandom(); MessageDigest hash = MessageDigest.getInstance("SHA-512"); /* FIX: Use a sufficiently random salt */ SecureRandom prng = SecureRandom.getInstance("SHA1PRNG"); hash.update(prng.generateSeed(32)); byte[] hashValue = hash.digest("hash me".getBytes("UTF-8")); IO.writeLine(IO.toHex(hashValue)); } } public void good() throws Throwable { good1(); good2(); } /* Below is the main(). It is only used when building this testcase on * its own for testing or for building a binary to use in testing binary * analysis tools. It is not used when compiling all the testcases as one * application, which is how source code analysis tools are tested. */ public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException { mainFromParent(args); } }
923496c1ee7395e5a9426f15e0b146cdeaaf9b6c
5,251
java
Java
POJ/24 - 26/poj2523.java
bilibiliShen/CodeBank
49a69b2b2c3603bf105140a9d924946ed3193457
[ "MIT" ]
1
2017-08-19T16:02:15.000Z
2017-08-19T16:02:15.000Z
POJ/24 - 26/poj2523.java
bilibiliShen/CodeBank
49a69b2b2c3603bf105140a9d924946ed3193457
[ "MIT" ]
null
null
null
POJ/24 - 26/poj2523.java
bilibiliShen/CodeBank
49a69b2b2c3603bf105140a9d924946ed3193457
[ "MIT" ]
1
2018-01-05T23:37:23.000Z
2018-01-05T23:37:23.000Z
22.440171
79
0.503523
996,973
import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.PrintWriter; import java.util.StringTokenizer; public class Main { //board[][] static final char EMPTY = ' '; static final char H = 'H'; static final char L = 'L'; //bestResult, curBoard static final char LINE_H = 'h'; static final char LINE_V = 'v'; //start with l, cw 90 static final char L_0 = 'a'; static final char L_1 = 'b'; static final char L_2 = 'c'; static final char L_3 = 'd'; static final char UP = 'U'; static final char DOWN = 'D'; static final char LEFT = 'L'; static final char RIGHT = 'R'; static char[][] bestResult = null; static char[][] curBoard = null; static char[][] board = null; static boolean[][] visited; static int count; static int bestLength; static int R; static int C; public static void main(String[] args) throws Exception{ BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); PrintWriter out = new PrintWriter(System.out); int T = Integer.parseInt(reader.readLine()); for (int t = 1; t <= T; t++){ StringTokenizer tk = new StringTokenizer(reader.readLine()); R = Integer.parseInt(tk.nextToken()); C = Integer.parseInt(tk.nextToken()); board = new char[R][C]; reader.readLine(); for (int r = 0; r < R; r++){ reader.readLine(); String line = reader.readLine(); for (int c = 0; c < C; c++){ boolean mid = line.charAt(4 * c + 2) == '*'; boolean right = line.charAt(4 * c + 3) == '*'; if (mid) { if (right) board[r][c] = H; else board[r][c] = L; } else board[r][c] = EMPTY; } reader.readLine(); reader.readLine(); } bestResult = new char[R][C]; curBoard = new char[R][C]; visited = new boolean[R][C]; count = 0; bestLength = 100; dfs(UP, 0, 0, 0); dfs(LEFT, 0, 0, 0); if (count != 0) { out.print("+"); for (int c = 0; c < C; c++) { out.print("---+"); } out.println(); for (int r = 0; r < R; r++) { //first row out.print("|"); for (int c = 0; c < C; c++) { switch (bestResult[r][c]) { case LINE_V: case L_0: case L_3: out.print(" * "); break; default: out.print(" "); break; } out.print("|"); } out.println(); //second row out.print("|"); for (int c = 0; c < C; c++) { switch (bestResult[r][c]) { case LINE_V: out.print(" * "); break; case LINE_H: out.print("***"); break; case L_0: case L_1: out.print(" **"); break; case L_2: case L_3: out.print("** "); break; default: out.print(" "); break; } out.print("|"); } out.println(); //third row out.print("|"); for (int c = 0; c < C; c++) { switch (bestResult[r][c]) { case LINE_V: case L_1: case L_2: out.print(" * "); break; default: out.print(" "); break; } out.print("|"); } out.println(); out.print("+"); for (int c = 0; c < C; c++) { out.print("---+"); } out.println(); } } out.println("Number of solutions: " + count); } out.close(); } static void p(char[][] board){ for (int r=0;r<board.length;r++){ for (int c=0;c<board[0].length;c++){ System.out.print(board[r][c]); } System.out.println(); } } //'from', and arrive in [r,c], pathlength is from start, excluding r,c static void dfs(char from, int r, int c, int pathLength) { if ((r == R && c == C-1) || (r == R-1 && c == C)) { if (bestLength > pathLength) { bestLength = pathLength; for (int i = 0; i < R; i++) for (int j = 0; j < C; j++) bestResult[i][j] = curBoard[i][j]; } count++; } else { if (r < 0 || c < 0 || r >= R || c >= C ) return; if (board[r][c] == EMPTY || visited[r][c]) return; visited[r][c] = true; if (board[r][c] == H) { switch (from) { case UP: curBoard[r][c] = LINE_V; dfs(UP, r + 1, c, pathLength + 1); break; case DOWN: curBoard[r][c] = LINE_V; dfs(DOWN, r - 1, c, pathLength + 1); break; case LEFT: curBoard[r][c] = LINE_H; dfs(LEFT, r, c + 1, pathLength + 1); break; case RIGHT: curBoard[r][c] = LINE_H; dfs(RIGHT, r, c - 1, pathLength + 1); break; } } else { //L switch (from) { case UP: curBoard[r][c] = L_0; dfs(LEFT, r, c + 1, pathLength + 1); curBoard[r][c] = L_3; dfs(RIGHT, r, c - 1, pathLength + 1); break; case DOWN: curBoard[r][c] = L_1; dfs(LEFT, r, c + 1, pathLength + 1); curBoard[r][c] = L_2; dfs(RIGHT, r, c - 1, pathLength + 1); break; case LEFT: curBoard[r][c] = L_2; dfs(UP, r + 1, c, pathLength + 1); curBoard[r][c] = L_3; dfs(DOWN, r - 1, c, pathLength + 1); break; case RIGHT: curBoard[r][c] = L_1; dfs(UP, r + 1, c, pathLength + 1); curBoard[r][c] = L_0; dfs(DOWN, r - 1, c, pathLength + 1); break; } } curBoard[r][c] = EMPTY; visited[r][c] = false; } } }
92349709942e0ae50ab3681e220bf1228c62412f
2,509
java
Java
sample-app/blog/src/test/java/com/therealdanvega/blog/web/rest/UserResourceIntTest.java
mhaberDev/kursAJ
16288816518bfb143924dde63c6767bf21399c5f
[ "Apache-2.0" ]
9
2019-04-19T23:08:51.000Z
2021-02-02T06:41:00.000Z
sample-app/blog/src/test/java/com/therealdanvega/blog/web/rest/UserResourceIntTest.java
mhaberDev/kursAJ
16288816518bfb143924dde63c6767bf21399c5f
[ "Apache-2.0" ]
8
2021-12-09T19:45:55.000Z
2022-03-17T22:27:38.000Z
sample-app/blog/src/test/java/com/therealdanvega/blog/web/rest/UserResourceIntTest.java
mhaberDev/kursAJ
16288816518bfb143924dde63c6767bf21399c5f
[ "Apache-2.0" ]
45
2019-05-18T21:52:03.000Z
2022-03-24T09:44:30.000Z
35.842857
89
0.762455
996,974
package com.therealdanvega.blog.web.rest; import com.therealdanvega.blog.BlogApp; import com.therealdanvega.blog.domain.User; import com.therealdanvega.blog.repository.UserRepository; import com.therealdanvega.blog.service.UserService; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.IntegrationTest; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.util.ReflectionTestUtils; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import javax.inject.Inject; import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; /** * Test class for the UserResource REST controller. * * @see UserResource */ @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = BlogApp.class) @WebAppConfiguration @IntegrationTest public class UserResourceIntTest { @Inject private UserRepository userRepository; @Inject private UserService userService; private MockMvc restUserMockMvc; @Before public void setup() { UserResource userResource = new UserResource(); ReflectionTestUtils.setField(userResource, "userRepository", userRepository); ReflectionTestUtils.setField(userResource, "userService", userService); this.restUserMockMvc = MockMvcBuilders.standaloneSetup(userResource).build(); } @Test public void testGetExistingUser() throws Exception { restUserMockMvc.perform(get("/api/users/admin") .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(content().contentType("application/json")) .andExpect(jsonPath("$.lastName").value("Administrator")); } @Test public void testGetUnknownUser() throws Exception { restUserMockMvc.perform(get("/api/users/unknown") .accept(MediaType.APPLICATION_JSON)) .andExpect(status().isNotFound()); } }
9234983fa23357881cf90309c9f63ac6f661c364
1,921
java
Java
Swachh/app/src/main/java/com/srkrit/swachh/ListViewAdapter.java
mysticmetal/swachh-App
525033c17e63790a4698ce60959277179d8e1bdb
[ "MIT" ]
null
null
null
Swachh/app/src/main/java/com/srkrit/swachh/ListViewAdapter.java
mysticmetal/swachh-App
525033c17e63790a4698ce60959277179d8e1bdb
[ "MIT" ]
null
null
null
Swachh/app/src/main/java/com/srkrit/swachh/ListViewAdapter.java
mysticmetal/swachh-App
525033c17e63790a4698ce60959277179d8e1bdb
[ "MIT" ]
null
null
null
25.959459
92
0.646018
996,975
package com.srkrit.swachh; /** * Created by Prabhu on 9/2/2016. */ import android.app.Activity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import java.util.List; public class ListViewAdapter extends BaseAdapter { Activity context; List<String> title; List<String> description; public ListViewAdapter(Activity context, List<String> title, List<String> description) { super(); this.context = context; this.title = title; this.description = description; } public int getCount() { // TODO Auto-generated method stub return title.size(); } public Object getItem(int position) { // TODO Auto-generated method stub return null; } public long getItemId(int position) { // TODO Auto-generated method stub return 0; } private class ViewHolder { TextView txtViewTitle; TextView txtViewDescription; } public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub ViewHolder holder; LayoutInflater inflater = context.getLayoutInflater(); if (convertView == null) { convertView = inflater.inflate(R.layout.listitem_row, null); holder = new ViewHolder(); holder.txtViewTitle = (TextView) convertView.findViewById(R.id.li_username); holder.txtViewDescription = (TextView) convertView.findViewById(R.id.li_desc); convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } holder.txtViewTitle.setText(title.get(position)); holder.txtViewDescription.setText(description.get(position)); return convertView; } }
92349853054316ce35d0460e8c166e22296b3e42
623
java
Java
src/test/java/com/github/chrisruffalo/silvering/visitor/InteruptingControlVisitor.java
chrisruffalo/silvering
6ccf72e93e2c423a6879420a2bb4b1be782571a0
[ "MIT" ]
null
null
null
src/test/java/com/github/chrisruffalo/silvering/visitor/InteruptingControlVisitor.java
chrisruffalo/silvering
6ccf72e93e2c423a6879420a2bb4b1be782571a0
[ "MIT" ]
null
null
null
src/test/java/com/github/chrisruffalo/silvering/visitor/InteruptingControlVisitor.java
chrisruffalo/silvering
6ccf72e93e2c423a6879420a2bb4b1be782571a0
[ "MIT" ]
null
null
null
23.074074
88
0.645265
996,976
package com.github.chrisruffalo.silvering.visitor; /** * <p></p> * * @author Chris Ruffalo */ public class InteruptingControlVisitor extends NavigationControlVisitor { private int visitFirst; public InteruptingControlVisitor(final int visitFirst, final VisitResult response) { super(response); this.visitFirst = visitFirst; } @Override public VisitResult visit(Class<?> instance) { final VisitResult result = super.visit(instance); if(this.visitFirst-- < 1) { return result; } else { return VisitResult.CONTINUE; } } }
9234988794fdb42627c0e76f82274fd69a40b7ef
25,956
java
Java
src/main/java/org/sitenv/contentvalidator/parsers/CCDAConstants.java
siteadmin/contentvalidator-api
c1df1c9eb8321922a65143a9dcd6d64c561eca21
[ "BSD-2-Clause-FreeBSD" ]
3
2020-08-17T13:09:32.000Z
2022-02-08T18:19:57.000Z
src/main/java/org/sitenv/contentvalidator/parsers/CCDAConstants.java
siteadmin/contentvalidator-api
c1df1c9eb8321922a65143a9dcd6d64c561eca21
[ "BSD-2-Clause-FreeBSD" ]
5
2020-06-04T20:00:45.000Z
2021-08-09T13:40:48.000Z
src/main/java/org/sitenv/contentvalidator/parsers/CCDAConstants.java
onc-healthit/content-validator-api
c1df1c9eb8321922a65143a9dcd6d64c561eca21
[ "BSD-2-Clause-FreeBSD" ]
7
2019-08-08T20:59:31.000Z
2021-08-09T13:08:48.000Z
67.243523
192
0.793998
996,977
package org.sitenv.contentvalidator.parsers; import javax.xml.namespace.NamespaceContext; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import java.util.Iterator; public class CCDAConstants { private final static CCDAConstants constants = new CCDAConstants(); static public XPath CCDAXPATH; static public XPathExpression DOC_TEMPLATE_EXP; static public XPathExpression DOC_TYPE_EXP; static public XPathExpression PATIENT_ROLE_EXP; static public XPathExpression REL_ADDR_EXP; static public XPathExpression REL_STREET_ADDR1_EXP; static public XPathExpression REL_STREET_ADDR2_EXP; static public XPathExpression REL_CITY_EXP; static public XPathExpression REL_STATE_EXP; static public XPathExpression REL_POSTAL_EXP; static public XPathExpression REL_COUNTRY_EXP; static public XPathExpression REL_PATIENT_BIRTHPLACE_EXP; static public XPathExpression REL_PATIENT_NAME_EXP; static public XPathExpression REL_PATIENT_PREV_NAME_EXP; static public XPathExpression REL_PLAY_ENTITY_NAME_EXP; static public XPathExpression REL_GIVEN_NAME_EXP; static public XPathExpression REL_MIDDLE_NAME_EXP; static public XPathExpression REL_FAMILY_NAME_EXP; static public XPathExpression REL_GIVEN_PREV_NAME_EXP; static public XPathExpression REL_SUFFIX_EXP; static public XPathExpression REL_PATIENT_ADMINGEN_EXP; static public XPathExpression REL_PATIENT_BIRTHTIME_EXP; static public XPathExpression REL_PATIENT_MARITAL_EXP; static public XPathExpression REL_PATIENT_RELIGION_EXP; static public XPathExpression REL_PATIENT_RACE_EXP; static public XPathExpression REL_PATIENT_ETHNICITY_EXP; static public XPathExpression REL_PATIENT_LANGUAGE_EXP; static public XPathExpression REL_TELECOM_EXP; static public XPathExpression REL_LANG_CODE_EXP; static public XPathExpression REL_LANG_MODE_EXP; static public XPathExpression REL_LANG_PREF_EXP; static public XPathExpression REL_TEXT_EXP; static public XPathExpression REL_TEMPLATE_ID_EXP; static public XPathExpression REL_CODE_EXP; static public XPathExpression REL_CODE_WITH_TRANS_EXP; static public XPathExpression REL_CODE_TRANS_EXP; static public XPathExpression REL_TRANS_EXP; static public XPathExpression REL_VAL_EXP; static public XPathExpression REL_VAL__WITH_TRANS_EXP; static public XPathExpression REL_STATUS_CODE_EXP; static public XPathExpression REL_INT_CODE_EXP; static public XPathExpression REL_REF_RANGE_EXP; static public XPathExpression REL_EFF_TIME_EXP; static public XPathExpression REL_EFF_TIME_LOW_EXP; static public XPathExpression REL_EFF_TIME_HIGH_EXP; static public XPathExpression REL_LOW_EXP; static public XPathExpression REL_HIGH_EXP; static public XPathExpression REL_TIME_EXP; //Encounter stuff static public XPathExpression REL_ENC_ENTRY_EXP; static public XPathExpression ENCOUNTER_EXPRESSION; static public XPathExpression ADMISSION_DIAG_EXP; static public XPathExpression DISCHARGE_DIAG_EXP; static public XPathExpression REL_HOSPITAL_ADMISSION_DIAG_EXP; static public XPathExpression REL_HOSPITAL_DISCHARGE_DIAG_EXP; // Notes and Companion Guide templates static public XPathExpression NOTES_EXPRESSION; static public XPathExpression REL_NOTES_ACTIVITY_EXPRESSION; static public XPathExpression REL_ENTRY_REL_NOTES_ACTIVITY_EXPRESSION; static public XPathExpression NOTES_ACTIVITY_EXPRESSION; static public XPathExpression REL_COMPONENT_ACTIVITY_EXPRESSION; //Problem Stuff static public XPathExpression PROBLEM_EXPRESSION; static public XPathExpression REL_PROBLEM_OBS_EXPRESSION; static public XPathExpression PAST_ILLNESS_EXP; static public XPathExpression PAST_ILLNESS_PROBLEM_OBS_EXPRESSION; //Medication stuff static public XPathExpression MEDICATION_EXPRESSION; static public XPathExpression ADM_MEDICATION_EXPRESSION; static public XPathExpression DM_MEDICATION_EXPRESSION; static public XPathExpression REL_MED_ENTRY_EXP; static public XPathExpression DM_ENTRY_EXP; static public XPathExpression DM_MED_ACT_EXP; static public XPathExpression REL_ROUTE_CODE_EXP; static public XPathExpression REL_DOSE_EXP; static public XPathExpression REL_RATE_EXP; static public XPathExpression REL_APP_SITE_CODE_EXP; static public XPathExpression REL_ADMIN_UNIT_CODE_EXP; static public XPathExpression REL_CONSUM_EXP; static public XPathExpression REL_MMAT_CODE_EXP; static public XPathExpression REL_MMAT_CODE_TRANS_EXP; static public XPathExpression REL_MANU_ORG_NAME_EXP; static public XPathExpression REL_MMAT_LOT_EXP; // Labs public static XPathExpression RESULTS_EXPRESSION; public static XPathExpression REL_LAB_RESULT_ORG_EXPRESSION; public static XPathExpression REL_LAB_TEST_ORG_EXPRESSION; public static XPathExpression REL_COMP_OBS_EXP; public static XPathExpression IMMUNIZATION_EXPRESSION; public static XPathExpression VITALSIGNS_EXPRESSION; public static XPathExpression REL_VITAL_ORG_EXPRESSION; // Procedure and Med Equipments public static XPathExpression MEDICAL_EQUIPMENT_EXPRESSION; public static XPathExpression MEDICAL_EQUIPMENT_ORG_EXPRESSION; public static XPathExpression MEDICAL_EQUIPMENT_ORG_PAP_EXPRESSION; public static XPathExpression PROCEDURE_EXPRESSION; public static XPathExpression REL_PROCEDURE_UDI_EXPRESSION; public static XPathExpression REL_PROCEDURE_SDL_EXPRESSION; public static XPathExpression REL_PROC_ACT_PROC_EXP; public static XPathExpression REL_PROC_ACT_ACT_EXP; public static XPathExpression REL_TARGET_SITE_CODE_EXP; public static XPathExpression REL_PERF_ENTITY_EXP; public static XPathExpression REL_PERF_ENTITY_ORG_EXP; public static XPathExpression REL_REP_ORG_EXP; public static XPathExpression REL_NAME_EXP; public static XPathExpression REL_ID_EXP; public static XPathExpression REL_PLAYING_DEV_CODE_EXP; public static XPathExpression REL_SCOPING_ENTITY_ID_EXP; // Allergies static public XPathExpression ALLERGIES_EXPRESSION; static public XPathExpression REL_ALLERGY_REACTION_EXPRESSION; static public XPathExpression REL_ALLERGY_SEVERITY_EXPRESSION; // CTM static public XPathExpression CARE_TEAM_EXPRESSION; static public XPathExpression CARE_TEAM_SECTION_EXPRESSION; static public XPathExpression REL_CARE_TEAM_ORG_EXPRESSION; static public XPathExpression REL_CARE_TEAM_MEMBER_ACT_EXPRESSION; static public XPathExpression REL_PERFORMER_EXP; static public XPathExpression REL_PARTICIPANT_EXP; // Social history static public XPathExpression SOCIAL_HISTORY_EXPRESSION; static public XPathExpression REL_SMOKING_STATUS_EXP; static public XPathExpression REL_TOBACCO_USE_EXP; static public XPathExpression REL_BIRTHSEX_OBS_EXP; // Care Plan static public XPathExpression INTERVENTIONS_SECTION_V3_EXP; static public XPathExpression HEALTH_STATUS_EVALUATIONS_AND_OUTCOMES_SECTION_EXP; //Generic static public XPathExpression REL_ENTRY_RELSHIP_ACT_EXP; static public XPathExpression REL_ENTRY_EXP; static public XPathExpression REL_SBDM_ENTRY_EXP; static public XPathExpression REL_PART_ROLE_EXP; static public XPathExpression REL_ENTRY_RELSHIP_OBS_EXP; static public XPathExpression REL_ACT_ENTRY_EXP; static public XPathExpression REL_PART_PLAY_ENTITY_CODE_EXP; static public XPathExpression REL_ASSN_ENTITY_ADDR; static public XPathExpression REL_ASSN_ENTITY_PERSON_NAME; static public XPathExpression REL_ASSN_ENTITY_TEL_EXP; static public XPathExpression AUTHORS_FROM_HEADER_EXP; static public XPathExpression AUTHORS_WITH_LINKED_REFERENCE_DATA_EXP; static public XPathExpression REL_AUTHOR_EXP; static public XPathExpression REL_ASSIGNED_AUTHOR_EXP; static public XPathExpression REL_ASSIGNED_PERSON_EXP; static public String RACE_EL_NAME = "raceCode"; public static final String DEFAULT_XPATH = "/ClinicalDocument"; public static final String DEFAULT_LINE_NUMBER = "0"; public static final String US_REALM_TEMPLATE = "2.16.840.1.113883.10.20.22.1.1"; public static final String CCDA_2015_AUG_EXT = "2015-08-01"; public static final String CCD_TEMPLATE = "2.16.840.1.113883.10.20.22.1.2"; public static final String CCD_CODE = "34133-9"; public static final String DS_TEMPLATE = "2.16.840.1.113883.10.20.22.1.8"; public static final String DS_CODE = "18842-5"; public static final String RN_TEMPLATE = "2.16.840.1.113883.10.20.22.1.14"; public static final String RN_CODE = "57133-1"; public static final String CP_TEMPLATE = "2.16.840.1.113883.10.20.22.1.15"; public static final String CP_CODE = "52521-2"; public static final String PROVENANCE_TEMPLATE_ID_ROOT = "2.16.840.1.113883.10.20.22.5.6"; public static final String PROVENANCE_TEMPLATE_ID_EXT = "2019-10-01"; private CCDAConstants() { initialize(); } public static CCDAConstants getInstance() { return constants; } private void initialize() { CCDAXPATH = XPathFactory.newInstance().newXPath(); try { DOC_TEMPLATE_EXP = CCDAConstants.CCDAXPATH.compile("/ClinicalDocument/templateId[not(@nullFlavor)]"); DOC_TYPE_EXP = CCDAConstants.CCDAXPATH.compile("/ClinicalDocument/code[not(@nullFlavor)]"); PATIENT_ROLE_EXP = CCDAConstants.CCDAXPATH.compile("/ClinicalDocument/recordTarget/patientRole[not(@nullFlavor)]"); REL_ADDR_EXP = CCDAConstants.CCDAXPATH.compile("./addr[not(@nullFlavor)]"); REL_STREET_ADDR1_EXP = CCDAConstants.CCDAXPATH.compile("./streetAddressLine[not(@nullFlavor)]"); REL_STREET_ADDR2_EXP = CCDAConstants.CCDAXPATH.compile("./streetAddressLine2[not(@nullFlavor)]"); REL_CITY_EXP = CCDAConstants.CCDAXPATH.compile("./city[not(@nullFlavor)]"); REL_STATE_EXP = CCDAConstants.CCDAXPATH.compile("./state[not(@nullFlavor)]"); REL_POSTAL_EXP = CCDAConstants.CCDAXPATH.compile("./postalCode[not(@nullFlavor)]"); REL_COUNTRY_EXP = CCDAConstants.CCDAXPATH.compile("./country[not(@nullFlavor)]"); REL_PATIENT_BIRTHPLACE_EXP = CCDAConstants.CCDAXPATH.compile("./patient/birthplace/place/addr[not(@nullFlavor)]"); REL_PATIENT_NAME_EXP = CCDAConstants.CCDAXPATH.compile("(./patient/name[not(@nullFlavor)])[1]"); REL_PATIENT_PREV_NAME_EXP = CCDAConstants.CCDAXPATH.compile("(./patient/name[not(@nullFlavor)])[2]"); REL_PLAY_ENTITY_NAME_EXP = CCDAConstants.CCDAXPATH.compile("./playingEntity/name[not(@nullFlavor)]"); REL_GIVEN_NAME_EXP = CCDAConstants.CCDAXPATH.compile("(./given[not(@nullFlavor)])[1]"); REL_MIDDLE_NAME_EXP = CCDAConstants.CCDAXPATH.compile("(./given[not(@nullFlavor)])[2]"); REL_GIVEN_PREV_NAME_EXP = CCDAConstants.CCDAXPATH.compile("(./given[not(@nullFlavor) and @qualifier='BR'])[1]"); REL_FAMILY_NAME_EXP = CCDAConstants.CCDAXPATH.compile("./family[not(@nullFlavor)]"); REL_SUFFIX_EXP = CCDAConstants.CCDAXPATH.compile("./suffix[not(@nullFlavor)]"); REL_PATIENT_ADMINGEN_EXP = CCDAConstants.CCDAXPATH.compile("./patient/administrativeGenderCode[not(@nullFlavor)]"); REL_PATIENT_BIRTHTIME_EXP = CCDAConstants.CCDAXPATH.compile("./patient/birthTime[not(@nullFlavor)]"); REL_PATIENT_MARITAL_EXP = CCDAConstants.CCDAXPATH.compile("./patient/maritalStatusCode[not(@nullFlavor)]"); REL_PATIENT_RELIGION_EXP = CCDAConstants.CCDAXPATH.compile("./patient/religiousAffiliationCode[not(@nullFlavor)]"); REL_PATIENT_RACE_EXP = CCDAConstants.CCDAXPATH.compile("./patient/raceCode[not(@nullFlavor)]"); REL_PATIENT_ETHNICITY_EXP = CCDAConstants.CCDAXPATH.compile("./patient/ethnicGroupCode[not(@nullFlavor)]"); REL_PATIENT_LANGUAGE_EXP = CCDAConstants.CCDAXPATH.compile("./patient/languageCommunication[not(@nullFlavor)]"); REL_LANG_CODE_EXP = CCDAConstants.CCDAXPATH.compile("./languageCode[not(@nullFlavor)]"); REL_LANG_MODE_EXP = CCDAConstants.CCDAXPATH.compile("./modeCode[not(@nullFlavor)]"); REL_LANG_PREF_EXP = CCDAConstants.CCDAXPATH.compile("./preferenceInd[not(@nullFlavor)]"); REL_TELECOM_EXP = CCDAConstants.CCDAXPATH.compile("./telecom[not(@nullFlavor)]"); REL_TEXT_EXP = CCDAConstants.CCDAXPATH.compile("./text[not(@nullFlavor)]"); AUTHORS_FROM_HEADER_EXP = CCDAConstants.CCDAXPATH.compile("/ClinicalDocument/author[not(@nullFlavor)]"); AUTHORS_WITH_LINKED_REFERENCE_DATA_EXP = CCDAConstants.CCDAXPATH.compile("/ClinicalDocument//author[not(@nullFlavor) " + "and assignedAuthor[not(@nullFlavor) and id[not(@nullFlavor) and string(@root) and string(@extension)] " + "and (code[not(@nullFlavor)] or addr[not(@nullFlavor)] or telecom[not(@nullFlavor)] or assignedPerson[not(@nullFlavor)] or representedOrganization[not(@nullFlavor)]) ] ]"); REL_AUTHOR_EXP = CCDAConstants.CCDAXPATH.compile("./author[not(@nullFlavor)]"); REL_ASSIGNED_AUTHOR_EXP = CCDAConstants.CCDAXPATH.compile("./assignedAuthor[not(@nullFlavor)]"); REL_ASSIGNED_PERSON_EXP = CCDAConstants.CCDAXPATH.compile("./assignedPerson[not(@nullFlavor)]"); ENCOUNTER_EXPRESSION = CCDAConstants.CCDAXPATH.compile("/ClinicalDocument/component/structuredBody/component/section[not(@nullFlavor) and code[@code='46240-8']]"); ADMISSION_DIAG_EXP = CCDAConstants.CCDAXPATH.compile("/ClinicalDocument/component/structuredBody/component/section[not(@nullFlavor) and code[@code='46241-6']]"); DISCHARGE_DIAG_EXP = CCDAConstants.CCDAXPATH.compile("/ClinicalDocument/component/structuredBody/component/section[not(@nullFlavor) and code[@code='11535-2']]"); REL_HOSPITAL_ADMISSION_DIAG_EXP = CCDAConstants.CCDAXPATH.compile("./entry/act[not(@nullFlavor) and templateId[@root='2.16.840.1.113883.10.20.22.4.34']]"); REL_HOSPITAL_DISCHARGE_DIAG_EXP = CCDAConstants.CCDAXPATH.compile("./entry/act[not(@nullFlavor) and templateId[@root='2.16.840.1.113883.10.20.22.4.33']]"); REL_ENC_ENTRY_EXP = CCDAConstants.CCDAXPATH.compile("./entry/encounter[not(@nullFlavor)]"); PROBLEM_EXPRESSION = CCDAConstants.CCDAXPATH.compile("/ClinicalDocument/component/structuredBody/component/section[not(@nullFlavor) and code[@code='11450-4']]"); PAST_ILLNESS_EXP = CCDAConstants.CCDAXPATH.compile("/ClinicalDocument/component/structuredBody/component/section[not(@nullFlavor) and code[@code='11348-0']]"); PAST_ILLNESS_PROBLEM_OBS_EXPRESSION = CCDAConstants.CCDAXPATH.compile("./entry/observation[not(@nullFlavor) and templateId[@root='2.16.840.1.113883.10.20.22.4.4']]"); REL_PROBLEM_OBS_EXPRESSION = CCDAConstants.CCDAXPATH.compile("./entryRelationship/observation[not(@nullFlavor) and templateId[@root='2.16.840.1.113883.10.20.22.4.4']]"); MEDICATION_EXPRESSION = CCDAConstants.CCDAXPATH.compile("/ClinicalDocument/component/structuredBody/component/section[not(@nullFlavor) and code[@code='10160-0']]"); ADM_MEDICATION_EXPRESSION = CCDAConstants.CCDAXPATH.compile("/ClinicalDocument/component/structuredBody/component/section[not(@nullFlavor) and code[@code='42346-7']]"); DM_MEDICATION_EXPRESSION = CCDAConstants.CCDAXPATH.compile("/ClinicalDocument/component/structuredBody/component/section[not(@nullFlavor) and code[@code='10183-2']]"); REL_MED_ENTRY_EXP = CCDAConstants.CCDAXPATH.compile("./entry/substanceAdministration[not(@nullFlavor)]"); DM_ENTRY_EXP = CCDAConstants.CCDAXPATH.compile("./entry/act/entryRelationship/substanceAdministration[not(@nullFlavor)]"); DM_MED_ACT_EXP = CCDAConstants.CCDAXPATH.compile("./entry/substanceAdministration[not(@nullFlavor)]"); REL_ROUTE_CODE_EXP = CCDAConstants.CCDAXPATH.compile("./routeCode[not(@nullFlavor)]"); REL_DOSE_EXP = CCDAConstants.CCDAXPATH.compile("./doseQuantity[not(@nullFlavor)]"); REL_RATE_EXP = CCDAConstants.CCDAXPATH.compile("./rateQuantity[not(@nullFlavor)]"); REL_APP_SITE_CODE_EXP = CCDAConstants.CCDAXPATH.compile("./approachSiteCode[not(@nullFlavor)]"); REL_ADMIN_UNIT_CODE_EXP = CCDAConstants.CCDAXPATH.compile("./administrationUnitCode[not(@nullFlavor)]"); REL_CONSUM_EXP = CCDAConstants.CCDAXPATH.compile("./consumable/manufacturedProduct[not(@nullFlavor)]"); REL_MMAT_CODE_EXP = CCDAConstants.CCDAXPATH.compile("./manufacturedMaterial/code[not(@nullFlavor)]"); REL_MMAT_CODE_TRANS_EXP = CCDAConstants.CCDAXPATH.compile("./manufacturedMaterial/code/translation[not(@nullFlavor)]"); REL_MANU_ORG_NAME_EXP = CCDAConstants.CCDAXPATH.compile("./manufacturerOrganization/name[not(@nullFlavor)]"); REL_MMAT_LOT_EXP = CCDAConstants.CCDAXPATH.compile("./manufacturedMaterial/lotNumberText[not(@nullFlavor)]"); ALLERGIES_EXPRESSION = CCDAConstants.CCDAXPATH.compile("/ClinicalDocument/component/structuredBody/component/section[not(@nullFlavor) and code[@code='48765-2']]"); REL_ALLERGY_REACTION_EXPRESSION = CCDAConstants.CCDAXPATH.compile("./entryRelationship/observation[not(@nullFlavor) and templateId[@root='2.16.840.1.113883.10.20.22.4.9']]"); REL_ALLERGY_SEVERITY_EXPRESSION = CCDAConstants.CCDAXPATH.compile("./entryRelationship/observation[not(@nullFlavor) and templateId[@root='2.16.840.1.113883.10.20.22.4.8']]"); SOCIAL_HISTORY_EXPRESSION = CCDAConstants.CCDAXPATH.compile("/ClinicalDocument/component/structuredBody/component/section[not(@nullFlavor) and code[@code='29762-2']]"); REL_SMOKING_STATUS_EXP = CCDAConstants.CCDAXPATH.compile("./entry/observation[not(@nullFlavor) and templateId[@root='2.16.840.1.113883.10.20.22.4.78']]"); REL_TOBACCO_USE_EXP = CCDAConstants.CCDAXPATH.compile("./entry/observation[not(@nullFlavor) and templateId[@root='2.16.840.1.113883.10.20.22.4.85']]"); REL_BIRTHSEX_OBS_EXP = CCDAConstants.CCDAXPATH.compile("./entry/observation[not(@nullFlavor) and templateId[@root='2.16.840.1.113883.10.20.22.4.200']]"); RESULTS_EXPRESSION = CCDAConstants.CCDAXPATH.compile("/ClinicalDocument/component/structuredBody/component/section[not(@nullFlavor) and code[@code='30954-2']]"); REL_LAB_RESULT_ORG_EXPRESSION = CCDAConstants.CCDAXPATH.compile("./entry/organizer[not(@nullFlavor) and statusCode[@code='completed']]"); REL_LAB_TEST_ORG_EXPRESSION = CCDAConstants.CCDAXPATH.compile("./entry/organizer[not(@nullFlavor) and statusCode[@code='active']]"); REL_COMP_OBS_EXP = CCDAConstants.CCDAXPATH.compile("./component/observation[not(@nullFlavor)]"); IMMUNIZATION_EXPRESSION = CCDAConstants.CCDAXPATH.compile("/ClinicalDocument/component/structuredBody/component/section[not(@nullFlavor) and code[@code='11369-6']]"); VITALSIGNS_EXPRESSION = CCDAConstants.CCDAXPATH.compile("/ClinicalDocument/component/structuredBody/component/section[not(@nullFlavor) and code[@code='8716-3']]"); REL_VITAL_ORG_EXPRESSION = CCDAConstants.CCDAXPATH.compile("./entry/organizer[not(@nullFlavor)]"); MEDICAL_EQUIPMENT_EXPRESSION = CCDAConstants.CCDAXPATH.compile("/ClinicalDocument/component/structuredBody/component/section[not(@nullFlavor) and code[@code='46264-8']]"); MEDICAL_EQUIPMENT_ORG_EXPRESSION = CCDAConstants.CCDAXPATH.compile("./entry/organizer[not(@nullFlavor) and not(@negationInd='true')]"); MEDICAL_EQUIPMENT_ORG_PAP_EXPRESSION = CCDAConstants.CCDAXPATH.compile("./component/procedure[not(@nullFlavor) and not(@negationInd='true')]"); PROCEDURE_EXPRESSION = CCDAConstants.CCDAXPATH.compile("/ClinicalDocument/component/structuredBody/component/section[not(@nullFlavor) and code[@code='47519-4']]"); REL_PROCEDURE_UDI_EXPRESSION = CCDAConstants.CCDAXPATH.compile("./participant[not(@nullFlavor) and @typeCode='DEV']/participantRole[not(@nullFlavor)]"); REL_PROCEDURE_SDL_EXPRESSION = CCDAConstants.CCDAXPATH.compile("./participant[not(@nullFlavor) and @typeCode='LOC']/participantRole[not(@nullFlavor)]"); REL_PROC_ACT_PROC_EXP = CCDAConstants.CCDAXPATH.compile("./entry/procedure[not(@nullFlavor) and not(@negationInd='true')]"); REL_PROC_ACT_ACT_EXP = CCDAConstants.CCDAXPATH.compile("./entry/act[not(@nullFlavor) and not(@negationInd='true') and templateId[@root='2.16.840.1.113883.10.20.22.4.12']]"); REL_TARGET_SITE_CODE_EXP = CCDAConstants.CCDAXPATH.compile("./targetSiteCode[not(@nullFlavor)]"); REL_PERF_ENTITY_EXP = CCDAConstants.CCDAXPATH.compile("./performer/assignedEntity[not(@nullFlavor)]"); REL_PERF_ENTITY_ORG_EXP = CCDAConstants.CCDAXPATH.compile("./performer/assignedEntity/representedOrganization[not(@nullFlavor)]"); REL_REP_ORG_EXP = CCDAConstants.CCDAXPATH.compile("./representedOrganization[not(@nullFlavor)]"); REL_NAME_EXP = CCDAConstants.CCDAXPATH.compile("./name[not(@nullFlavor)]"); REL_ID_EXP = CCDAConstants.CCDAXPATH.compile("./id[not(@nullFlavor)]"); REL_PLAYING_DEV_CODE_EXP = CCDAConstants.CCDAXPATH.compile("./playingDevice/code[not(@nullFlavor)]"); REL_SCOPING_ENTITY_ID_EXP = CCDAConstants.CCDAXPATH.compile("./scopingEntity/id[not(@nullFlavor)]"); CARE_TEAM_EXPRESSION = CCDAConstants.CCDAXPATH.compile("/ClinicalDocument/documentationOf/serviceEvent/performer[not(@nullFlavor)]"); CARE_TEAM_SECTION_EXPRESSION = CCDAConstants.CCDAXPATH.compile("/ClinicalDocument/component/structuredBody/component/section[not(@nullFlavor) and code[@code='85847-2']]"); REL_CARE_TEAM_ORG_EXPRESSION = CCDAConstants.CCDAXPATH.compile("./entry/organizer[not(@nullFlavor)]"); REL_CARE_TEAM_MEMBER_ACT_EXPRESSION = CCDAConstants.CCDAXPATH.compile("./component/act[not(@nullFlavor) and templateId[@root='2.16.840.1.113883.10.20.22.4.500.1']]"); REL_TEMPLATE_ID_EXP = CCDAConstants.CCDAXPATH.compile("./templateId[not(@nullFlavor)]"); REL_CODE_EXP = CCDAConstants.CCDAXPATH.compile("./code[not(@nullFlavor)]"); REL_CODE_WITH_TRANS_EXP = CCDAConstants.CCDAXPATH.compile("./code[not(@nullFlavor) or @nullFlavor='OTH']"); REL_CODE_TRANS_EXP = CCDAConstants.CCDAXPATH.compile("./code/translation[not(@nullFlavor)]"); REL_TRANS_EXP = CCDAConstants.CCDAXPATH.compile("./translation[not(@nullFlavor)]"); REL_VAL_EXP = CCDAConstants.CCDAXPATH.compile("./value[not(@nullFlavor)]"); REL_VAL__WITH_TRANS_EXP = CCDAConstants.CCDAXPATH.compile("./value[not(@nullFlavor) or @nullFlavor='OTH']"); REL_STATUS_CODE_EXP = CCDAConstants.CCDAXPATH.compile("./statusCode[not(@nullFlavor)]"); REL_INT_CODE_EXP = CCDAConstants.CCDAXPATH.compile("./interpretationCode[not(@nullFlavor)]"); REL_REF_RANGE_EXP = CCDAConstants.CCDAXPATH.compile("./referenceRange/observationRange/value[@type='IVL_PQ']"); REL_LOW_EXP = CCDAConstants.CCDAXPATH.compile("./low[not(@nullFlavor)]"); REL_HIGH_EXP = CCDAConstants.CCDAXPATH.compile("./high[not(@nullFlavor)]"); REL_PERFORMER_EXP = CCDAConstants.CCDAXPATH.compile("./performer[not(@nullFlavor)]"); REL_PARTICIPANT_EXP = CCDAConstants.CCDAXPATH.compile("./participant[not(@nullFlavor) and @typeCode='IND']"); INTERVENTIONS_SECTION_V3_EXP = CCDAConstants.CCDAXPATH.compile("/ClinicalDocument/component/structuredBody/component" + "/section[not(@nullFlavor) and templateId[@root='2.16.840.1.113883.10.20.21.2.3' and @extension='2015-08-01']]"); HEALTH_STATUS_EVALUATIONS_AND_OUTCOMES_SECTION_EXP = CCDAConstants.CCDAXPATH.compile("/ClinicalDocument/component/structuredBody/component" + "/section[not(@nullFlavor) and templateId[@root='2.16.840.1.113883.10.20.22.2.61']]"); REL_ACT_ENTRY_EXP = CCDAConstants.CCDAXPATH.compile("./entry/act[not(@nullFlavor)]"); REL_ENTRY_EXP = CCDAConstants.CCDAXPATH.compile("./entry[not(@nullFlavor)]"); REL_SBDM_ENTRY_EXP = CCDAConstants.CCDAXPATH.compile("./substanceAdministration[not(@nullFlavor)]"); REL_ENTRY_RELSHIP_ACT_EXP = CCDAConstants.CCDAXPATH.compile("./entryRelationship/act[not(@nullFlavor)]"); REL_PART_ROLE_EXP = CCDAConstants.CCDAXPATH.compile("./participant/participantRole[not(@nullFlavor)]"); REL_PART_PLAY_ENTITY_CODE_EXP = CCDAConstants.CCDAXPATH.compile("./participant/participantRole/playingEntity/code[not(@nullFlavor)]"); REL_EFF_TIME_EXP = CCDAConstants.CCDAXPATH.compile("./effectiveTime[not(@nullFlavor)]"); REL_EFF_TIME_LOW_EXP = CCDAConstants.CCDAXPATH.compile("./low[not(@nullFlavor)]"); REL_EFF_TIME_HIGH_EXP = CCDAConstants.CCDAXPATH.compile("./high[not(@nullFlavor)]"); REL_TIME_EXP = CCDAConstants.CCDAXPATH.compile("./time[not(@nullFlavor)]"); REL_ENTRY_RELSHIP_OBS_EXP = CCDAConstants.CCDAXPATH.compile("./entryRelationship/observation[not(@nullFlavor)]"); REL_ASSN_ENTITY_ADDR = CCDAConstants.CCDAXPATH.compile("./assignedEntity/addr[not(@nullFlavor)]"); REL_ASSN_ENTITY_PERSON_NAME = CCDAConstants.CCDAXPATH.compile("./assignedEntity/assignedPerson/name[not(@nullFlavor)]"); REL_ASSN_ENTITY_TEL_EXP = CCDAConstants.CCDAXPATH.compile("./assignedEntity/telecom[not(@nullFlavor)]"); NOTES_EXPRESSION = CCDAConstants.CCDAXPATH.compile("/ClinicalDocument/component/structuredBody/component/section[not(@nullFlavor) and templateId[@root='2.16.840.1.113883.10.20.22.2.65']]"); REL_COMPONENT_ACTIVITY_EXPRESSION = CCDAConstants.CCDAXPATH.compile("./component/act[not(@nullFlavor) and templateId[@root='2.16.840.1.113883.10.20.22.4.202']]"); REL_NOTES_ACTIVITY_EXPRESSION = CCDAConstants.CCDAXPATH.compile("./entry/act[not(@nullFlavor) and templateId[@root='2.16.840.1.113883.10.20.22.4.202']]"); REL_ENTRY_REL_NOTES_ACTIVITY_EXPRESSION = CCDAConstants.CCDAXPATH.compile("./entryRelationship/act[not(@nullFlavor) and templateId[@root='2.16.840.1.113883.10.20.22.4.202']]"); NOTES_ACTIVITY_EXPRESSION = CCDAConstants.CCDAXPATH.compile("//act[not(@nullFlavor) and templateId[@root='2.16.840.1.113883.10.20.22.4.202']]"); } catch (XPathExpressionException e) { // TODO Auto-generated catch block e.printStackTrace(); } } NamespaceContext ctx = new NamespaceContext() { public String getNamespaceURI(String prefix) { if(prefix.contentEquals("hl7")) { return "urn:hl7-org:v3"; } else if(prefix.contentEquals("hl7:sdtc")) { return "urn:hl7-org:v3:sdtc"; } else return null; } public Iterator getPrefixes(String val) { return null; } public String getPrefix(String uri) { return null; } }; }
923498a233423d05f99f56d2d3e24e539e2ca543
6,790
java
Java
0.4.1.5/JFP-Framework-Core/src/main/java/org/isotope/jfp/framework/support/MyDataBaseOperateSupport.java
qq744788292/cnsoft
b9b921d43ea9b06c881121ab5d98ce18e14df87d
[ "BSD-3-Clause-Clear" ]
null
null
null
0.4.1.5/JFP-Framework-Core/src/main/java/org/isotope/jfp/framework/support/MyDataBaseOperateSupport.java
qq744788292/cnsoft
b9b921d43ea9b06c881121ab5d98ce18e14df87d
[ "BSD-3-Clause-Clear" ]
null
null
null
0.4.1.5/JFP-Framework-Core/src/main/java/org/isotope/jfp/framework/support/MyDataBaseOperateSupport.java
qq744788292/cnsoft
b9b921d43ea9b06c881121ab5d98ce18e14df87d
[ "BSD-3-Clause-Clear" ]
1
2022-03-16T01:57:07.000Z
2022-03-16T01:57:07.000Z
22.633333
144
0.693078
996,978
package org.isotope.jfp.framework.support; import java.sql.Connection; import java.sql.SQLException; import java.util.List; import org.apache.ibatis.session.SqlSession; import org.isotope.jfp.framework.beans.common.FrameworkDataBean; import org.isotope.jfp.framework.beans.page.PageVOSupport; import org.isotope.jfp.framework.constants.ISDBConstants; import org.isotope.jfp.framework.constants.ISFrameworkConstants; import org.isotope.jfp.framework.utils.BeanFactoryHelper; import org.mybatis.spring.SqlSessionTemplate; import org.mybatis.spring.SqlSessionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 数据持久层超类 * * @author Spook * @since 0.1.0 * @version 0.2.1 2014/11/05 * @version 0.1.0 2014/2/8 */ public class MyDataBaseOperateSupport<T> implements ISFrameworkConstants, ISDBConstants { protected Logger logger = LoggerFactory.getLogger(this.getClass()); /** * 数据库连接 */ private SqlSession mySqlSession; public SqlSession getMySqlSession() { if (mySqlSession == null) mySqlSession = BeanFactoryHelper.getBean("mySqlSession"); return mySqlSession; } /** * 设定SQL连接 * * @param mySqlSession */ public void setMySqlSession(SqlSession mySqlSession) { this.mySqlSession = mySqlSession; } /** * 获得用于执行静态 SQL 语句并返回它所生成结果的对象 * <p> * 基于事物控制 * * @return Statement * @throws SQLException */ protected Connection getConnection() throws SQLException { SqlSessionTemplate st = (SqlSessionTemplate) getMySqlSession(); return SqlSessionUtils.getSqlSession(st.getSqlSessionFactory(), st.getExecutorType(), st.getPersistenceExceptionTranslator()).getConnection(); } ///////////////////////// /** * 获得数据库操作对象 * @deprecated * @return */ @SuppressWarnings("unchecked") public IDatabaseSupport<T> getDao() { return getMySqlSession().getMapper(IDatabaseSupport.class); } /** * 数据库分表 * * @param data */ public void changeTable(MyDataBaseObjectSupport data, int dbType) { // String companyType = ((XXXXXDBO)data).getT01(); // 分表处理 // if (ZERO.equals(companyType)) { // data.setTableName("0"); // } else if (ONE.equals(companyType)) { // data.setTableName("1"); // } // if (dbType != DB_SELECT) { // // } } ///////////// 分页查询//////////////// /** * 分页查询 * * @param formParamPageModel * @return */ public PageVOSupport<T> doSelectPage(PageVOSupport<T> formParamPageModel) { return doSelectPage(formParamPageModel, true, true); } /** * 分页查询 * * @param formParamPageModel * @param ppp * @return */ public PageVOSupport<T> doSelectPage(PageVOSupport<T> formParamPageModel, boolean ppp) { return doSelectPage(formParamPageModel, ppp, true); } /** * 分页查询 * * @param formParamPageModel * @param ppp * @return */ public PageVOSupport<T> doSelectPage(PageVOSupport<T> formParamPageModel, boolean ppp, boolean ddd) { FrameworkDataBean formParamBean = formParamPageModel.getFormParamBean(); // 查询数据 changeTable((MyDataBaseObjectSupport) formParamBean, DB_SELECT); formParamPageModel.setPageListData(getDao().doSelectPage(formParamPageModel)); return formParamPageModel; } /** * 全表查询 * * @param formParamPageModel * @return */ public List<T> doSelectData(MyDataBaseObjectSupport formParamBean) { return doSelectData(formParamBean, true, true); } /** * 全表查询 * * @param formParamPageModel * @return */ public List<T> doSelectData(MyDataBaseObjectSupport formParamBean, boolean ppp) { return doSelectData(formParamBean, ppp, true); } /** * 全表查询 * * @param formParamPageModel * @return */ public List<T> doSelectData(MyDataBaseObjectSupport formParamBean, boolean ppp, boolean ddd) { changeTable((MyDataBaseObjectSupport) formParamBean, DB_SELECT); formParamBean.prepareGroup(ppp); formParamBean.prepareDeleteFlag(ddd); return getDao().doSelectPage(formParamBean); } ///////////////// 基本操作////带有乐观锁///////////////////// /** * 根据主键,逻辑删除一条数据 */ public int toDelete(MyDataBaseObjectSupport formParamBean) { changeTable(formParamBean, DB_DELETE); return getDao().toDelete(formParamBean); } /** * 物理删除一个用户 * * @param formParamBean * @return */ public int doDelete(MyDataBaseObjectSupport formParamBean) { changeTable(formParamBean, DB_DELETE); return getDao().doDelete(formParamBean); } /** * 批量插入 * * @param datas * @return */ public int[] doInsertOrUpdate(List<? extends MyDataBaseObjectSupport> datas) { int[] rs = new int[datas.size()]; MyDataBaseObjectSupport formParamBean; for (int i = 0; i < rs.length; i++) { formParamBean = datas.get(i); changeTable(formParamBean, DB_INSERT); rs[i] = -1; try { rs[i] = doInsert(formParamBean); } catch (Exception e) { // System.err.println(e.getMessage()); rs[i] = doUpdate(formParamBean); } } return rs; } /** * 批量插入 * * @param datas * @return */ public int doInsertOrUpdate(MyDataBaseObjectSupport formParamBean) { try { return doInsert(formParamBean); } catch (Exception e) { System.err.println(e.getMessage()); return doUpdate(formParamBean); } } /** * 批量插入 * * @param datas * @return */ public int[] doInsert(List<? extends MyDataBaseObjectSupport> datas) { int[] rs = new int[datas.size()]; MyDataBaseObjectSupport formParamBean; for (int i = 0; i < rs.length; i++) { formParamBean = datas.get(i); rs[i] = -1; try { rs[i] = doInsert(formParamBean); } catch (Exception e) { System.err.println(e.getMessage()); } } return rs; } /** * 插入数据 * * @param formParamBean * @return */ public int doInsert(MyDataBaseObjectSupport formParamBean) { changeTable(formParamBean, DB_INSERT); // 有效标记、创建者、创建时间、更新者、更新时间 formParamBean.prepareCreator(); formParamBean.prepareUpdator(); return getDao().doInsert(formParamBean); } /** * 更新数据 * * @param formParamBean * @return */ public int doUpdate(MyDataBaseObjectSupport formParamBean) { changeTable(formParamBean, DB_UPDATE); // 更新者、更新时间 formParamBean.prepareUpdator(); return getDao().doUpdate(formParamBean); } public void doUpdateAll(MyDataBaseObjectSupport formParamBean) { changeTable(formParamBean, DB_UPDATE); // 更新者、更新时间 formParamBean.prepareUpdator(); getDao().doUpdateAll(formParamBean); } /** * 读取数据 * * @param formParamBean * @return */ public FrameworkDataBean doRead(MyDataBaseObjectSupport formParamBean) { changeTable(formParamBean, DB_SELECT); return doRead(formParamBean, true); } /** * 读取数据 * * @param formParamBean * @param ddd * @return */ public FrameworkDataBean doRead(MyDataBaseObjectSupport formParamBean, boolean ddd) { changeTable(formParamBean, DB_SELECT); return getDao().doRead(formParamBean); } }
923498adeeda272d7d6e3f7766c6e0f2faccd0c4
2,605
java
Java
ddlx/src/test/java/org/jaxdb/ddlx/TestTest.java
openjax/rdb
566bd41438314ab0059cb8d34966ee4d360b8836
[ "MIT" ]
3
2019-05-15T15:16:10.000Z
2021-03-23T15:50:50.000Z
ddlx/src/test/java/org/jaxdb/ddlx/TestTest.java
openjax/rdb
566bd41438314ab0059cb8d34966ee4d360b8836
[ "MIT" ]
53
2020-05-09T10:03:56.000Z
2022-02-23T14:54:57.000Z
ddlx/src/test/java/org/jaxdb/ddlx/TestTest.java
openjax/rdb
566bd41438314ab0059cb8d34966ee4d360b8836
[ "MIT" ]
null
null
null
28.626374
80
0.738964
996,979
/* Copyright (c) 2017 JAX-DB * * 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. * * You should have received a copy of The MIT License (MIT) along with this * program. If not, see <http://opensource.org/licenses/MIT/>. */ package org.jaxdb.ddlx; import static org.junit.Assert.*; import java.sql.Connection; import java.sql.SQLException; import org.jaxdb.runner.DBTestRunner; import org.jaxdb.runner.DBTestRunner.DB; import org.jaxdb.runner.Derby; import org.jaxdb.runner.MySQL; import org.jaxdb.runner.Oracle; import org.jaxdb.runner.PostgreSQL; import org.jaxdb.runner.SQLite; import org.jaxdb.vendor.DBVendor; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @RunWith(DBTestRunner.class) public abstract class TestTest { private static final Logger logger = LoggerFactory.getLogger(TestTest.class); @Ignore("Intended for hands-on dev") @DB(value=Derby.class, parallel=2) @DB(SQLite.class) public static class IntegrationTest extends TestTest { } @Ignore("Intended for hands-on dev") @DB(MySQL.class) @DB(PostgreSQL.class) @DB(Oracle.class) public static class RegressionTest extends TestTest { } @BeforeClass public static void beforeClass1() { logger.debug("before class1:"); } @BeforeClass public static void beforeClass2() { logger.debug("before class2:"); } @Before public void before() { logger.debug("before0:"); } @Before public void before(final Connection connection) throws SQLException { logger.debug("before: " + DBVendor.valueOf(connection.getMetaData())); } @Test public void test1() { logger.debug("test1:"); } @Test public void test2(final Connection connection) throws SQLException { logger.debug("test2: " + DBVendor.valueOf(connection.getMetaData())); } @Ignore("Should be ignored") public void testIgnore(final Connection connection) { fail("Should have been ignored " + connection); } }
923498e5b47e02632d116226b7ecfb7a085181a9
4,247
java
Java
src/com/example/lunboguanggao/MainActivity.java
rhymedys/LunBoGuangGaoDemo
97a9ceca2e935ac633f5077ddc5ecb1c239fbc52
[ "Apache-2.0" ]
null
null
null
src/com/example/lunboguanggao/MainActivity.java
rhymedys/LunBoGuangGaoDemo
97a9ceca2e935ac633f5077ddc5ecb1c239fbc52
[ "Apache-2.0" ]
null
null
null
src/com/example/lunboguanggao/MainActivity.java
rhymedys/LunBoGuangGaoDemo
97a9ceca2e935ac633f5077ddc5ecb1c239fbc52
[ "Apache-2.0" ]
null
null
null
24.836257
101
0.692489
996,980
package com.example.lunboguanggao; import java.util.ArrayList; import android.app.Activity; import android.content.Context; import android.hardware.Camera.Parameters; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; public class MainActivity extends Activity { private Context context; private ViewPager viewPager; private int[] intDrawables; private ArrayList<ImageView> imageViews; private ArrayList<View> pointViews; private LinearLayout ll_point_container; private android.widget.LinearLayout.LayoutParams params; private MyViewPagerAdapter myViewPagerAdapter; private String[] des; private int position; private TextView tv_description; private View pointView; private int previousSelectedPosition = 0; /** * 界面可见 可以自动 论循环 */ boolean inVisible = true; private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); viewPager.setCurrentItem(1 + viewPager.getCurrentItem()); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); this.context = this; initUI(); initData(); initAdapter(); } private void initAdapter() { myViewPagerAdapter = new MyViewPagerAdapter(context, imageViews); viewPager.setAdapter(myViewPagerAdapter); ll_point_container.getChildAt(0).setEnabled(true); tv_description.setText(des[0]); // 设置在 总数中间开始,以便左右循环 int item = 5000000 / imageViews.size(); viewPager.setCurrentItem(item); if (inVisible) { new Thread(new Runnable() { public void run() { while (true) { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } handler.sendEmptyMessage(0); } } }).start(); } } private void initData() { intDrawables = new int[] { R.drawable.a, R.drawable.b, R.drawable.c, R.drawable.d, R.drawable.e }; des = new String[intDrawables.length]; for (int i = 0; i < intDrawables.length; i++) { des[i] = String.valueOf(intDrawables[i]); } ll_point_container = (LinearLayout) findViewById(R.id.ll_point_container); imageViews = new ArrayList<ImageView>(); ImageView imageView; for (int i = 0; i < intDrawables.length; i++) { imageView = new ImageView(context); imageView.setBackgroundResource(intDrawables[i]); imageViews.add(imageView); pointView = new View(context); pointView.setBackgroundResource(R.drawable.selector_bg_point); if (i != 0) { params.rightMargin = 5; } pointView.setEnabled(false); // 设置参数 params = new LinearLayout.LayoutParams(5, 5); ll_point_container.addView(pointView, params); } viewPager.addOnPageChangeListener(new OnPageChangeListener() { @Override public void onPageSelected(int position) { // 取余获得位置 int newPosition = position % imageViews.size(); tv_description.setText(des[newPosition]); for (int i = 0; i < ll_point_container.getChildCount(); i++) { // 设置文本 tv_description.setText(des[newPosition]); // 设置小白点 ll_point_container.getChildAt(previousSelectedPosition).setEnabled(false); ll_point_container.getChildAt(newPosition).setEnabled(true); // 记录之前的位置 previousSelectedPosition = newPosition; } } @Override public void onPageScrolled(int arg0, float arg1, int arg2) { } @Override public void onPageScrollStateChanged(int arg0) { } }); } private void initUI() { viewPager = (ViewPager) findViewById(R.id.view_pager); tv_description = (TextView) findViewById(R.id.tv_description); } @Override protected void onDestroy() { inVisible = !inVisible; super.onDestroy(); } }
923499423489da1f598386a08c38aa7d873bd7a2
10,193
java
Java
android/src/main/java/com/google/android/libraries/privacy/ppn/internal/service/VpnManager.java
Condum/vpn-libraries
aa741f31c98f25e81e76fb5306c30233dd872598
[ "Apache-2.0" ]
163
2020-10-29T21:24:42.000Z
2022-03-28T15:42:24.000Z
android/src/main/java/com/google/android/libraries/privacy/ppn/internal/service/VpnManager.java
0xgpapad/vpn-libraries
aa741f31c98f25e81e76fb5306c30233dd872598
[ "Apache-2.0" ]
4
2021-02-13T20:14:53.000Z
2022-03-08T03:18:06.000Z
android/src/main/java/com/google/android/libraries/privacy/ppn/internal/service/VpnManager.java
0xgpapad/vpn-libraries
aa741f31c98f25e81e76fb5306c30233dd872598
[ "Apache-2.0" ]
25
2020-11-10T18:06:04.000Z
2022-03-08T03:11:32.000Z
37.065455
100
0.713823
996,981
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the ); // 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 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.libraries.privacy.ppn.internal.service; import android.content.Context; import android.content.pm.PackageManager.NameNotFoundException; import android.net.Network; import android.net.VpnService; import android.os.Build; import android.os.ParcelFileDescriptor; import android.util.Log; import androidx.annotation.Nullable; import androidx.annotation.VisibleForTesting; import com.google.android.libraries.privacy.ppn.PpnException; import com.google.android.libraries.privacy.ppn.internal.TunFdData; import com.google.android.libraries.privacy.ppn.xenon.PpnNetwork; import java.io.IOException; import java.net.DatagramSocket; import java.net.Socket; import java.util.Collections; import java.util.Set; /** * Wrapper around a mutable VpnService that deals with the details about how to use the service to * implement a VPN for PPN. The underlying service will be null if the service is not running. */ public class VpnManager { private static final String TAG = "VpnManager"; // The optimal Socket Buffer Size from GCS experimentation is 4MB. private static final int SOCKET_BUFFER_SIZE_BYTES = 4 * 1024 * 1024; private final Context context; // The underlying VpnService this manager is managing. // This may be null if the service is not running. @Nullable private volatile VpnServiceWrapper vpnService; @Nullable private volatile PpnNetwork network; private volatile Set<String> disallowedApplications = Collections.emptySet(); public VpnManager(Context context) { this.context = context; } /** * Resets the underlying service for this manager. This should be called whenever a service starts * or stops. */ public void setService(@Nullable VpnService service) { setServiceWrapper(service == null ? null : new VpnServiceWrapper(service)); } @VisibleForTesting void setServiceWrapper(@Nullable VpnServiceWrapper service) { this.vpnService = service; } /** Stops the underlying Service, if one is running. Otherwise, does nothing. */ public void stopService() { VpnServiceWrapper service = vpnService; if (service != null) { service.stopSelf(); } } /** Returns whether the underlying service has been set. */ public boolean isRunning() { return vpnService != null; } /** Tells the service to set its underlying network to the given network. */ public void setNetwork(PpnNetwork ppnNetwork) { network = ppnNetwork; VpnServiceWrapper service = vpnService; if (service != null) { Log.w(TAG, "Setting underlying network to " + ppnNetwork); service.setUnderlyingNetworks(new Network[] {ppnNetwork.getNetwork()}); } else { Log.w(TAG, "Failed to set underlying network because service is not running."); } } /** Changes the set of disallowed applications which will bypass the VPN. */ public void setDisallowedApplications(Set<String> disallowedApplications) { this.disallowedApplications = disallowedApplications; } @VisibleForTesting public Set<String> getDisallowApplications() { return this.disallowedApplications; } /** Gets the underlying network for the service. */ public PpnNetwork getNetwork() { return network; } /** * Establishes the VpnService and creates the TUN fd for processing requests from the device. This * can only be called after onStartService and before onStartService. * * @param tunFdData the data needed to create a TUN Fd. * @return the file descriptor of the TUN. The receiver is responsible for closing it eventually. * @throws PpnException if the service has not been set. */ public int createTunFd(TunFdData tunFdData) throws PpnException { VpnServiceWrapper service = vpnService; if (service == null) { throw new PpnException("Tried to create a TUN fd when PPN service wasn't running."); } if (VpnService.prepare(context) != null) { throw new PpnException("VpnService was not prepared or was revoked."); } VpnService.Builder builder = service.newBuilder(); setVpnServiceParametersForDisallowedApplications(builder, disallowedApplications); setVpnServiceParametersFromTunFdData(builder, tunFdData); // If the network was set before the tunnel was established, make sure to set it on the builder. PpnNetwork network = getNetwork(); if (network != null) { Log.w(TAG, "Setting initial underlying network to " + network); builder.setUnderlyingNetworks(new Network[] {network.getNetwork()}); } ParcelFileDescriptor tunFds; try { Log.w(TAG, "Establishing Tun FD"); tunFds = builder.establish(); } catch (RuntimeException e) { Log.e(TAG, "Failure when establishing Tun FD.", e); throw new PpnException("Failure when establishing TUN FD.", e); } if (tunFds == null) { throw new PpnException("establish() returned null. The VpnService was probably revoked."); } int fd = tunFds.detachFd(); if (fd <= 0) { throw new PpnException("Invalid TUN fd: " + fd); } // There could be a race condition where we set the network between when we set the Builder and // when we call establish. Android doesn't track the underlying network until establish is // called. So we double check the network here just in case it needs to be changed. PpnNetwork currentNetwork = getNetwork(); if (currentNetwork != null && !currentNetwork.equals(network)) { Log.w(TAG, "Updating underlying network to " + currentNetwork); service.setUnderlyingNetworks(new Network[] {currentNetwork.getNetwork()}); } return fd; } private static void setVpnServiceParametersForDisallowedApplications( VpnService.Builder builder, Set<String> disallowedApplications) { for (String packageName : disallowedApplications) { try { builder.addDisallowedApplication(packageName); } catch (NameNotFoundException e) { Log.e(TAG, "Disallowed application package not found: " + packageName, e); } } } private static void setVpnServiceParametersFromTunFdData( VpnService.Builder builder, TunFdData tunFdData) { if (tunFdData.hasSessionName()) { builder.setSession(tunFdData.getSessionName()); } if (tunFdData.hasMtu()) { builder.setMtu(tunFdData.getMtu()); } // VpnService.Builder.setMetered(...) is only supported in API 29+. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { Log.w(TAG, "Setting metered to " + tunFdData.getIsMetered()); builder.setMetered(tunFdData.getIsMetered()); } for (TunFdData.IpRange ipRange : tunFdData.getTunnelIpAddressesList()) { builder.addAddress(ipRange.getIpRange(), ipRange.getPrefix()); } for (TunFdData.IpRange ipRange : tunFdData.getTunnelDnsAddressesList()) { Log.w(TAG, "Adding DNS: " + ipRange.getIpRange()); builder.addDnsServer(ipRange.getIpRange()); } for (TunFdData.IpRange ipRange : tunFdData.getTunnelRoutesList()) { builder.addRoute(ipRange.getIpRange(), ipRange.getPrefix()); } RouteManager.addRoutes(builder); } /** * Creates a new protected UDP socket, which can be used by Krypton for connecting to Copper. This * can only be called after onStartService and before onStopService. * * @param ppnNetwork PpnNetwork to bind to. * @return the file descriptor of the socket. The receiver is responsible for closing it. * @throws PpnException if the service has not been set. */ public int createProtectedDatagramSocket(PpnNetwork ppnNetwork) throws PpnException { return createProtectedDatagramSocket(ppnNetwork.getNetwork()); } /** * Creates a new protected UDP socket, which can be used by Krypton for connecting to Copper. This * can only be called after onStartService and before onStopService. * * @param network Network to bind to. * @return the file descriptor of the socket. The receiver is responsible for closing it. * @throws PpnException if the service has not been set. */ private int createProtectedDatagramSocket(Network network) throws PpnException { VpnServiceWrapper service = vpnService; if (service == null) { throw new PpnException("Tried to create a protected socket when PPN service wasn't running."); } DatagramSocket socket = null; try { socket = new DatagramSocket(); socket.setReceiveBufferSize(SOCKET_BUFFER_SIZE_BYTES); socket.setSendBufferSize(SOCKET_BUFFER_SIZE_BYTES); service.protect(socket); network.bindSocket(socket); // We need to explicitly duplicate the socket otherwise it will fail for Android version 9 // (P) and older. // TODO: Find a cleaner way to support both versions. ParcelFileDescriptor pfd = service.parcelSocket(socket).dup(); // ParcelFileDescriptor duplicates the socket, so the original needs to be closed. socket.close(); int fd = pfd.detachFd(); if (fd <= 0) { throw new PpnException("Invalid file descriptor from datagram socket: " + fd); } return fd; } catch (IOException e) { if (socket != null) { socket.close(); } throw new PpnException("Unable to create socket or bind network to socket.", e); } } /** * Protects the given socket if the VpnService is running. Otherwise, does nothing. This is useful * for making TCP connections that should always bypass the VPN. */ void protect(Socket socket) { VpnServiceWrapper service = vpnService; if (service != null) { service.protect(socket); } } }
92349ad4869e88a7ac3091d5ad4e371a40d1d516
3,677
java
Java
src/main/java/com/inin/analytics/elasticsearch/example/ExampleIndexingJob.java
purecloudlabs/elasticsearch-lambda
06b76a42ff78a55ee52e95382256c7fbb38e84b6
[ "MIT" ]
12
2018-04-08T12:44:50.000Z
2021-09-25T18:53:49.000Z
src/main/java/com/inin/analytics/elasticsearch/example/ExampleIndexingJob.java
purecloudlabs/elasticsearch-lambda
06b76a42ff78a55ee52e95382256c7fbb38e84b6
[ "MIT" ]
4
2018-04-08T06:46:06.000Z
2021-08-09T20:45:08.000Z
src/main/java/com/inin/analytics/elasticsearch/example/ExampleIndexingJob.java
purecloudlabs/elasticsearch-lambda
06b76a42ff78a55ee52e95382256c7fbb38e84b6
[ "MIT" ]
2
2018-12-18T03:37:41.000Z
2022-02-17T10:06:37.000Z
39.537634
308
0.788958
996,982
package com.inin.analytics.elasticsearch.example; import org.apache.commons.lang.StringUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapred.FileInputFormat; import org.apache.hadoop.mapred.FileOutputFormat; import org.apache.hadoop.mapred.JobClient; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.SequenceFileInputFormat; import org.apache.hadoop.mapred.TextOutputFormat; import org.apache.hadoop.util.Tool; import com.inin.analytics.elasticsearch.BaseESMapper; import com.inin.analytics.elasticsearch.ConfigParams; import com.inin.analytics.elasticsearch.IndexingPostProcessor; import com.inin.analytics.elasticsearch.ShardConfig; public class ExampleIndexingJob implements Tool { private static Configuration conf; public static int main(String[] args) throws Exception { if(args.length != 9) { System.err.println("Invalid # arguments. EG: loadES [pipe separated input] [snapshot working directory (fs/nfs)] [snapshot final destination (s3/nfs/hdfs)] [snapshot repo name] [elasticsearch working data location] [num reducers] [num shards per index] [num shards per organization] [manifest location]"); return -1; } String inputPath = args[0]; String snapshotWorkingLocation = args[1]; String snapshotFinalDestination = args[2]; String snapshotRepoName = args[3]; String esWorkingDir = args[4]; Integer numReducers = new Integer(args[5]); Long numShardsPerIndex = new Long(args[6]); Long numShardsPerOrganization = new Long(args[7]); String manifestLocation = args[8]; // Remove trailing slashes from the destination snapshotFinalDestination = StringUtils.stripEnd(snapshotFinalDestination, "/"); conf = new Configuration(); conf.set(ConfigParams.SNAPSHOT_WORKING_LOCATION_CONFIG_KEY.toString(), snapshotWorkingLocation); conf.set(ConfigParams.SNAPSHOT_FINAL_DESTINATION.toString(), snapshotFinalDestination); conf.set(ConfigParams.SNAPSHOT_REPO_NAME_CONFIG_KEY.toString(), snapshotRepoName); conf.set(ConfigParams.ES_WORKING_DIR.toString(), esWorkingDir); conf.set(ConfigParams.NUM_SHARDS_PER_INDEX.toString(), numShardsPerIndex.toString()); conf.set(ConfigParams.NUM_SHARDS_PER_ORGANIZATION.toString(), numShardsPerOrganization.toString()); JobConf job = new JobConf(conf, ExampleIndexingJob.class); job.setJobName("Elastic Search Offline Index Generator"); job.setInputFormat(SequenceFileInputFormat.class); job.setOutputFormat(TextOutputFormat.class); job.setMapperClass(BaseESMapper.class); job.setReducerClass(ExampleIndexingReducerImpl.class); job.setMapOutputValueClass(Text.class); job.setMapOutputKeyClass(Text.class); job.setNumReduceTasks(numReducers); job.setSpeculativeExecution(false); Path jobOutput = new Path(manifestLocation + "/raw/"); Path manifestFile = new Path(manifestLocation + "manifest"); FileOutputFormat.setOutputPath(job, jobOutput); // Set up inputs String[]inputFolders = StringUtils.split(inputPath, "|"); for(String input : inputFolders) { FileInputFormat.addInputPath(job, new Path(input)); } JobClient.runJob(job); IndexingPostProcessor postProcessor = new IndexingPostProcessor(); postProcessor.execute(jobOutput, manifestFile, esWorkingDir, new ShardConfig(numShardsPerIndex, numShardsPerOrganization), conf, ExampleIndexingReducerImpl.class); return 0; } @Override public void setConf(Configuration conf) { this.conf = conf; } @Override public Configuration getConf() { return conf; } @Override public int run(String[] args) throws Exception { return ExampleIndexingJob.main(args); } }
92349c85e8e01389e5b117f7b7d3af2fe08d6cf5
1,599
java
Java
extractor/src/test/java/org/schabi/newpipe/extractor/services/youtube/search/YoutubeSearchCountTest.java
lulugyf/inospeech
42419aaf48c472b262ca9c4b2fe11ce8b33a1d34
[ "Apache-2.0" ]
null
null
null
extractor/src/test/java/org/schabi/newpipe/extractor/services/youtube/search/YoutubeSearchCountTest.java
lulugyf/inospeech
42419aaf48c472b262ca9c4b2fe11ce8b33a1d34
[ "Apache-2.0" ]
null
null
null
extractor/src/test/java/org/schabi/newpipe/extractor/services/youtube/search/YoutubeSearchCountTest.java
lulugyf/inospeech
42419aaf48c472b262ca9c4b2fe11ce8b33a1d34
[ "Apache-2.0" ]
null
null
null
45.685714
114
0.73671
996,983
package org.schabi.newpipe.extractor.services.youtube.search; import org.junit.BeforeClass; import org.junit.Test; import org.schabi.newpipe.Downloader; import org.schabi.newpipe.extractor.NewPipe; import org.schabi.newpipe.extractor.channel.ChannelInfoItem; import org.schabi.newpipe.extractor.services.youtube.extractors.YoutubeSearchExtractor; import org.schabi.newpipe.extractor.services.youtube.linkHandler.YoutubeSearchQueryHandlerFactory; import org.schabi.newpipe.extractor.utils.Localization; import static java.util.Collections.singletonList; import static junit.framework.TestCase.assertTrue; import static org.schabi.newpipe.extractor.ServiceList.YouTube; public class YoutubeSearchCountTest { public static class YoutubeChannelViewCountTest extends YoutubeSearchExtractorBaseTest { @BeforeClass public static void setUpClass() throws Exception { NewPipe.init(Downloader.getInstance(), new Localization("GB", "en")); extractor = (YoutubeSearchExtractor) YouTube.getSearchExtractor("pewdiepie", singletonList(YoutubeSearchQueryHandlerFactory.CHANNELS), null, new Localization("GB", "en")); extractor.fetchPage(); itemsPage = extractor.getInitialPage(); } @Test public void testViewCount() { ChannelInfoItem ci = (ChannelInfoItem) itemsPage.getItems().get(0); assertTrue("Count does not fit: " + Long.toString(ci.getSubscriberCount()), 69043316 < ci.getSubscriberCount() && ci.getSubscriberCount() < 73043316); } } }
92349cfe98f490a6c25d8d8490b1c66fbaf8bc57
15,524
java
Java
flow-server/src/test/java/com/vaadin/flow/server/communication/StreamReceiverHandlerTest.java
mortensen/flow
c0b2ffb0c5d35df46cf416e195201450c1de9e8a
[ "Apache-2.0" ]
402
2017-10-02T09:00:34.000Z
2022-03-30T06:09:40.000Z
flow-server/src/test/java/com/vaadin/flow/server/communication/StreamReceiverHandlerTest.java
mortensen/flow
c0b2ffb0c5d35df46cf416e195201450c1de9e8a
[ "Apache-2.0" ]
9,144
2017-10-02T07:12:23.000Z
2022-03-31T19:16:56.000Z
flow-server/src/test/java/com/vaadin/flow/server/communication/StreamReceiverHandlerTest.java
flyzoner/flow
3f00a72127a2191eb9b9d884370ca6c1cb2f80bf
[ "Apache-2.0" ]
167
2017-10-11T13:07:29.000Z
2022-03-22T09:02:42.000Z
35.852194
139
0.644744
996,984
package com.vaadin.flow.server.communication; import javax.servlet.ReadListener; import javax.servlet.ServletException; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Optional; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import com.vaadin.flow.component.UI; import com.vaadin.flow.component.internal.UIInternals; import com.vaadin.flow.internal.StateNode; import com.vaadin.flow.internal.StateTree; import com.vaadin.flow.server.ErrorHandler; import com.vaadin.flow.server.MockVaadinServletService; import com.vaadin.flow.server.StreamReceiver; import com.vaadin.flow.server.StreamResourceRegistry; import com.vaadin.flow.server.StreamVariable; import com.vaadin.flow.server.UploadException; import com.vaadin.flow.server.VaadinRequest; import com.vaadin.flow.server.VaadinResponse; import com.vaadin.flow.server.VaadinServletRequest; import com.vaadin.flow.server.VaadinServletService; import com.vaadin.flow.server.VaadinSession; import com.vaadin.flow.shared.ApplicationConstants; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class StreamReceiverHandlerTest { private StreamReceiverHandler handler; @Mock private VaadinResponse response; @Mock private StreamVariable streamVariable; @Mock private StateNode stateNode; // @Mock private VaadinRequest request; @Mock private UI ui; @Mock private UIInternals uiInternals; @Mock private StateTree stateTree; @Mock private VaadinSession session; @Mock private OutputStream responseOutput; @Mock private StreamReceiver streamReceiver; @Mock private StreamResourceRegistry registry; @Mock private ErrorHandler errorHandler; private VaadinServletService mockService; private final int uiId = 123; private final int nodeId = 1233; private final String variableName = "name"; private final String expectedSecurityKey = "key"; private String contentLength; private ServletInputStream inputStream; private OutputStream outputStream; private String contentType; private List<Part> parts; private boolean isGetContentLengthLongCalled; @Before public void setup() throws Exception { contentLength = "6"; inputStream = createInputStream("foobar"); outputStream = mock(OutputStream.class); contentType = "foobar"; parts = Collections.emptyList(); MockitoAnnotations.initMocks(this); handler = new StreamReceiverHandler(); mockService = new MockVaadinServletService(); mockRequest(); mockReceiverAndRegistry(); mockUi(); when(streamReceiver.getNode()).thenReturn(stateNode); when(stateNode.isAttached()).thenReturn(true); when(streamVariable.getOutputStream()) .thenAnswer(invocationOnMock -> outputStream); when(response.getOutputStream()).thenReturn(responseOutput); Mockito.when(session.getErrorHandler()) .thenReturn(Mockito.mock(ErrorHandler.class)); } private void mockReceiverAndRegistry() { when(session.getResourceRegistry()).thenReturn(registry); when(registry.getResource(Mockito.any())) .thenReturn(Optional.of(streamReceiver)); when(streamReceiver.getId()).thenReturn(expectedSecurityKey); when(streamReceiver.getStreamVariable()).thenReturn(streamVariable); } private void mockRequest() throws IOException { HttpServletRequest servletRequest = Mockito .mock(HttpServletRequest.class); when(servletRequest.getContentLength()).thenAnswer( invocationOnMock -> Integer.parseInt(contentLength)); request = new VaadinServletRequest(servletRequest, mockService) { @Override public String getParameter(String name) { if ("restartApplication".equals(name) || "ignoreRestart".equals(name) || "closeApplication".equals(name)) { return null; } return "1"; } @Override public String getPathInfo() { return "/" + StreamRequestHandler.DYN_RES_PREFIX + uiId + "/" + nodeId + "/" + variableName + "/" + expectedSecurityKey; } @Override public String getMethod() { return "POST"; } @Override public ServletInputStream getInputStream() throws IOException { return inputStream; } @Override public String getHeader(String name) { if ("content-length".equals(name.toLowerCase())) { return contentLength; } return super.getHeader(name); } @Override public String getContentType() { return contentType; } @Override public Collection<Part> getParts() throws IOException, ServletException { return parts; } @Override public long getContentLengthLong() { isGetContentLengthLongCalled = true; return 0; } }; } private ServletInputStream createInputStream(final String content) { return new ServletInputStream() { boolean finished = false; @Override public boolean isFinished() { return finished; } @Override public boolean isReady() { return true; } @Override public void setReadListener(ReadListener readListener) { } int counter = 0; byte[] msg = content.getBytes(); @Override public int read() throws IOException { if (counter > msg.length + 1) { throw new AssertionError( "-1 was ignored by StreamReceiverHandler."); } if (counter >= msg.length) { counter++; finished = true; return -1; } return msg[counter++]; } }; } private Part createPart(InputStream inputStream, String contentType, String name, long size) throws IOException { Part part = mock(Part.class); when(part.getInputStream()).thenReturn(inputStream); when(part.getContentType()).thenReturn(contentType); when(part.getSubmittedFileName()).thenReturn(name); when(part.getSize()).thenReturn(size); return part; } private void mockUi() { when(ui.getInternals()).thenReturn(uiInternals); when(uiInternals.getStateTree()).thenReturn(stateTree); when(stateTree.getNodeById(Mockito.anyInt())).thenReturn(stateNode); when(session.getUIById(uiId)).thenReturn(ui); } @Test public void doHandleXhrFilePost_outputStreamGetterThrows_responseStatusIs500() throws IOException { Mockito.doThrow(RuntimeException.class).when(streamVariable) .getOutputStream(); handler.doHandleXhrFilePost(session, request, response, streamReceiver, stateNode, 1); Mockito.verify(response) .setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } @Test public void doHandleXhrFilePost_outputStreamThrowsOnWrite_responseStatusIs500() throws IOException { Mockito.doThrow(RuntimeException.class).when(outputStream) .write(Mockito.any(), Mockito.anyInt(), Mockito.anyInt()); handler.doHandleXhrFilePost(session, request, response, streamReceiver, stateNode, 1); Mockito.verify(response) .setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } @Test public void doHandleXhrFilePost_happyPath_setContentTypeNoExplicitSetStatus() throws IOException { handler.doHandleXhrFilePost(session, request, response, streamReceiver, stateNode, 1); Mockito.verify(response).setContentType( ApplicationConstants.CONTENT_TYPE_TEXT_HTML_UTF_8); Mockito.verify(response, Mockito.times(0)).setStatus(Mockito.anyInt()); } @Test public void doHandleMultipartFileUpload_noPart_uploadFailed_responseStatusIs500_getContentLengthLongCalled() throws IOException { handler.doHandleMultipartFileUpload(session, request, response, streamReceiver, stateNode); Mockito.verify(response) .setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); Assert.assertTrue(isGetContentLengthLongCalled); } @Test public void doHandleMultipartFileUpload_hasParts_uploadFailed_responseStatusIs500() throws IOException { contentType = "multipart/form-data; boundary=----WebKitFormBoundary7NsWHeCJVZNwi6ll"; inputStream = createInputStream( "------WebKitFormBoundary7NsWHeCJVZNwi6ll\n" + "Content-Disposition: form-data; name=\"file\"; filename=\"EBookJP.txt\"\n" + "Content-Type: text/plain\n" + "\n" + "\n" + "------WebKitFormBoundary7NsWHeCJVZNwi6ll--"); Mockito.doThrow(RuntimeException.class).when(outputStream) .write(Mockito.any(), Mockito.anyInt(), Mockito.anyInt()); contentLength = "99"; parts = new ArrayList<>(); parts.add(createPart(createInputStream("foobar"), "text/plain", "EBookJP.txt", 6)); handler.doHandleMultipartFileUpload(session, request, response, streamReceiver, stateNode); Mockito.verify(response) .setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } /** * Tests whether we get infinite loop if InputStream is already read * (#10096) */ @Test public void exceptionIsThrownOnUnexpectedEnd() throws IOException { contentType = "multipart/form-data; boundary=----WebKitFormBoundary7NsWHeCJVZNwi6ll"; inputStream = createInputStream( "------WebKitFormBoundary7NsWHeCJVZNwi6ll\n" + "Content-Disposition: form-data; name=\"file\"; filename=\"EBookJP.txt\"\n" + "Content-Type: text/plain\n" + "\n" + "\n" + "------WebKitFormBoundary7NsWHeCJVZNwi6ll--"); contentLength = "99"; handler.doHandleMultipartFileUpload(session, request, response, null, null); Mockito.verify(response) .setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } @Test public void responseIsSentOnCorrectSecurityKey() throws IOException { handler.handleRequest(session, request, response, streamReceiver, String.valueOf(uiId), expectedSecurityKey); Mockito.verify(responseOutput).close(); } @Test public void responseIsNotSentOnIncorrectSecurityKey() throws IOException { when(streamReceiver.getId()).thenReturn("another key expected"); handler.handleRequest(session, request, response, streamReceiver, String.valueOf(uiId), expectedSecurityKey); Mockito.verifyNoInteractions(responseOutput); } @Test public void responseIsNotSentOnMissingSecurityKey() throws IOException { when(streamReceiver.getId()).thenReturn(null); handler.handleRequest(session, request, response, streamReceiver, String.valueOf(uiId), expectedSecurityKey); Mockito.verifyNoInteractions(responseOutput); } @Test // Vaadin Spring #381 public void partsAreUsedDirectlyIfPresentWithoutParsingInput() throws IOException { contentType = "multipart/form-data; boundary=----WebKitFormBoundary7NsWHeCJVZNwi6ll"; inputStream = createInputStream( "------WebKitFormBoundary7NsWHeCJVZNwi6ll\n" + "Content-Disposition: form-data; name=\"file\"; filename=\"EBookJP.txt\"\n" + "Content-Type: text/plain\n" + "\n" + "\n" + "------WebKitFormBoundary7NsWHeCJVZNwi6ll--"); outputStream = new ByteArrayOutputStream(); contentLength = "99"; final String fileName = "EBookJP.txt"; final String contentType = "text/plain"; parts = new ArrayList<>(); parts.add(createPart(createInputStream("foobar"), contentType, fileName, 6)); handler.handleRequest(session, request, response, streamReceiver, String.valueOf(uiId), expectedSecurityKey); Mockito.verify(responseOutput).close(); ArgumentCaptor<StreamVariable.StreamingEndEvent> endEventArgumentCaptor = ArgumentCaptor .forClass(StreamVariable.StreamingEndEvent.class); Mockito.verify(streamVariable) .streamingFinished(endEventArgumentCaptor.capture()); Assert.assertEquals("foobar", new String( ((ByteArrayOutputStream) outputStream).toByteArray())); Assert.assertEquals(fileName, endEventArgumentCaptor.getValue().getFileName()); Assert.assertEquals(contentType, endEventArgumentCaptor.getValue().getMimeType()); Mockito.verify(response).setContentType( ApplicationConstants.CONTENT_TYPE_TEXT_HTML_UTF_8); Mockito.verify(response, Mockito.times(0)).setStatus(Mockito.anyInt()); } @Test public void handleFileUploadValidationAndData_inputStreamThrowsIOException_exceptionIsNotRethrown_exceptionIsNotHandlerByErrorHandler() throws UploadException { InputStream inputStream = new InputStream() { @Override public int read() throws IOException { throw new IOException(); } }; handler.handleFileUploadValidationAndData(session, inputStream, streamReceiver, null, null, 0, stateNode); Mockito.verifyNoInteractions(errorHandler); Mockito.verify(streamVariable).streamingFailed(Mockito.any()); } @Test public void doHandleMultipartFileUpload_IOExceptionIsThrown_exceptionIsNotRethrown_exceptionIsNotHandlerByErrorHandler() throws IOException, ServletException { VaadinServletRequest request = Mockito.mock(VaadinServletRequest.class); Mockito.doThrow(IOException.class).when(request).getParts(); handler.doHandleMultipartFileUpload(session, request, response, streamReceiver, stateNode); Mockito.verifyNoInteractions(errorHandler); } }
92349d249ab134a1ff04970a88f45cd4d629fe60
4,066
java
Java
android/src/main/java/com/reactnativecolorpickerlight/ColorIndicatorView.java
JimmyTai/react-native-color-picker-light
8e1c46b6b401501fc9a37d568237eee981254d1b
[ "MIT" ]
11
2020-04-23T17:32:25.000Z
2022-03-09T10:54:36.000Z
android/src/main/java/com/reactnativecolorpickerlight/ColorIndicatorView.java
JimmyTai/react-native-color-picker-light
8e1c46b6b401501fc9a37d568237eee981254d1b
[ "MIT" ]
7
2020-06-28T02:33:00.000Z
2022-03-09T10:54:26.000Z
android/src/main/java/com/reactnativecolorpickerlight/ColorIndicatorView.java
JimmyTai/react-native-color-picker-light
8e1c46b6b401501fc9a37d568237eee981254d1b
[ "MIT" ]
4
2020-04-24T03:17:28.000Z
2022-03-10T01:52:18.000Z
33.327869
127
0.634038
996,985
package com.reactnativecolorpickerlight; import android.animation.ValueAnimator; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.view.View; /** * Created by JimmyTai on 2018/8/23. */ public class ColorIndicatorView extends View { private static final String TAG = ColorIndicatorView.class.getSimpleName(); private int color = Color.BLACK; static final float DEFAULT_RADIUS = 20f, DEFAULT_ACTIVATE_SCALE = 1.3f, DEFAULT_THICKNESS = 4f, DEFAULT_SHADOW_RADIUS = 8f; static final int DEFAULT_SHADOW_COLOR = Color.parseColor("#e0e0e0"); private int radius, thickness, shadowRadius; private float activateScale; private int shadowColor; public ColorIndicatorView(Context context, int radius, float activateScale, int thickness, int shadowRadius, int shadowColor) { super(context); this.radius = radius; this.nowRadius = radius; this.activateScale = activateScale; this.thickness = thickness; this.shadowRadius = shadowRadius; this.shadowColor = shadowColor; init(); } public ColorIndicatorView(Context context) { super(context); this.radius = dp2px(DEFAULT_RADIUS); this.nowRadius = radius; this.activateScale = DEFAULT_ACTIVATE_SCALE; this.thickness = dp2px(DEFAULT_THICKNESS); this.shadowRadius = dp2px(DEFAULT_SHADOW_RADIUS); this.shadowColor = DEFAULT_SHADOW_COLOR; init(); } protected int dp2px(float dp) { final float scale = getContext().getResources().getDisplayMetrics().density; return ((int) (dp * scale + 0.5f)); } private Paint outerPaint, innerPaint; private void init() { outerPaint = new Paint(); outerPaint.setAntiAlias(true); outerPaint.setColor(Color.WHITE); outerPaint.setStyle(Paint.Style.FILL); outerPaint.setShadowLayer(shadowRadius, 0, 0, shadowColor); innerPaint = new Paint(); innerPaint.setAntiAlias(true); innerPaint.setColor(color); innerPaint.setStyle(Paint.Style.FILL); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); } private int nowRadius; public void setActivate(boolean activate) { if (activate) { ValueAnimator animator = ValueAnimator.ofInt(radius, ((int) (activateScale * (float) radius))); animator.setDuration(150); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { nowRadius = (int) animation.getAnimatedValue(); invalidate(); } }); animator.start(); } else { ValueAnimator animator = ValueAnimator.ofInt(((int) (activateScale * (float) radius)), radius); animator.setDuration(150); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator animation) { nowRadius = (int) animation.getAnimatedValue(); invalidate(); } }); animator.start(); } } public int getColor() { return color; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); setLayerType(LAYER_TYPE_SOFTWARE, outerPaint); canvas.drawCircle(getWidth() / 2, getHeight() / 2, nowRadius, outerPaint); int innerRadius = nowRadius - thickness; innerPaint.setColor(color); canvas.drawCircle(getWidth() / 2, getHeight() / 2, innerRadius, innerPaint); } public void setColor(int color) { this.color = color; invalidate(); } }
92349d27d77fd25476d6d502edcd59983238f1f1
9,475
java
Java
build/tmp/recompileMc/sources/net/minecraft/client/renderer/tileentity/TileEntityRendererDispatcher.java
Lanolin/JustCookies
e84951ea04fea472a16fbbd9fc3275442d59d983
[ "MIT" ]
null
null
null
build/tmp/recompileMc/sources/net/minecraft/client/renderer/tileentity/TileEntityRendererDispatcher.java
Lanolin/JustCookies
e84951ea04fea472a16fbbd9fc3275442d59d983
[ "MIT" ]
null
null
null
build/tmp/recompileMc/sources/net/minecraft/client/renderer/tileentity/TileEntityRendererDispatcher.java
Lanolin/JustCookies
e84951ea04fea472a16fbbd9fc3275442d59d983
[ "MIT" ]
null
null
null
45.552885
226
0.711768
996,986
package net.minecraft.client.renderer.tileentity; import com.google.common.collect.Maps; import java.util.Map; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.client.renderer.OpenGlHelper; import net.minecraft.client.renderer.texture.TextureManager; import net.minecraft.crash.CrashReport; import net.minecraft.crash.CrashReportCategory; import net.minecraft.entity.Entity; import net.minecraft.tileentity.TileEntity; import net.minecraft.tileentity.TileEntityBanner; import net.minecraft.tileentity.TileEntityBeacon; import net.minecraft.tileentity.TileEntityChest; import net.minecraft.tileentity.TileEntityEnchantmentTable; import net.minecraft.tileentity.TileEntityEndPortal; import net.minecraft.tileentity.TileEntityEnderChest; import net.minecraft.tileentity.TileEntityMobSpawner; import net.minecraft.tileentity.TileEntityPiston; import net.minecraft.tileentity.TileEntitySign; import net.minecraft.tileentity.TileEntitySkull; import net.minecraft.util.BlockPos; import net.minecraft.util.ReportedException; import net.minecraft.world.World; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) public class TileEntityRendererDispatcher { public Map < Class <? extends TileEntity > , TileEntitySpecialRenderer <? extends TileEntity >> mapSpecialRenderers = Maps. < Class <? extends TileEntity > , TileEntitySpecialRenderer <? extends TileEntity >> newHashMap(); public static TileEntityRendererDispatcher instance = new TileEntityRendererDispatcher(); private FontRenderer fontRenderer; /** The player's current X position (same as playerX) */ public static double staticPlayerX; /** The player's current Y position (same as playerY) */ public static double staticPlayerY; /** The player's current Z position (same as playerZ) */ public static double staticPlayerZ; public TextureManager renderEngine; public World worldObj; public Entity entity; public float entityYaw; public float entityPitch; public double entityX; public double entityY; public double entityZ; private TileEntityRendererDispatcher() { this.mapSpecialRenderers.put(TileEntitySign.class, new TileEntitySignRenderer()); this.mapSpecialRenderers.put(TileEntityMobSpawner.class, new TileEntityMobSpawnerRenderer()); this.mapSpecialRenderers.put(TileEntityPiston.class, new TileEntityPistonRenderer()); this.mapSpecialRenderers.put(TileEntityChest.class, new TileEntityChestRenderer()); this.mapSpecialRenderers.put(TileEntityEnderChest.class, new TileEntityEnderChestRenderer()); this.mapSpecialRenderers.put(TileEntityEnchantmentTable.class, new TileEntityEnchantmentTableRenderer()); this.mapSpecialRenderers.put(TileEntityEndPortal.class, new TileEntityEndPortalRenderer()); this.mapSpecialRenderers.put(TileEntityBeacon.class, new TileEntityBeaconRenderer()); this.mapSpecialRenderers.put(TileEntitySkull.class, new TileEntitySkullRenderer()); this.mapSpecialRenderers.put(TileEntityBanner.class, new TileEntityBannerRenderer()); for (TileEntitySpecialRenderer<?> tileentityspecialrenderer : this.mapSpecialRenderers.values()) { tileentityspecialrenderer.setRendererDispatcher(this); } } public <T extends TileEntity> TileEntitySpecialRenderer<T> getSpecialRendererByClass(Class <? extends TileEntity > teClass) { TileEntitySpecialRenderer <? extends TileEntity > tileentityspecialrenderer = (TileEntitySpecialRenderer)this.mapSpecialRenderers.get(teClass); if (tileentityspecialrenderer == null && teClass != TileEntity.class) { tileentityspecialrenderer = this.<TileEntity>getSpecialRendererByClass((Class <? extends TileEntity >)teClass.getSuperclass()); this.mapSpecialRenderers.put(teClass, tileentityspecialrenderer); } return (TileEntitySpecialRenderer<T>)tileentityspecialrenderer; } public <T extends TileEntity> TileEntitySpecialRenderer<T> getSpecialRenderer(TileEntity tileEntityIn) { return (TileEntitySpecialRenderer<T>)(tileEntityIn == null ? null : this.getSpecialRendererByClass(tileEntityIn.getClass())); } public void cacheActiveRenderInfo(World worldIn, TextureManager textureManagerIn, FontRenderer fontrendererIn, Entity entityIn, float partialTicks) { if (this.worldObj != worldIn) { this.setWorld(worldIn); } this.renderEngine = textureManagerIn; this.entity = entityIn; this.fontRenderer = fontrendererIn; this.entityYaw = entityIn.prevRotationYaw + (entityIn.rotationYaw - entityIn.prevRotationYaw) * partialTicks; this.entityPitch = entityIn.prevRotationPitch + (entityIn.rotationPitch - entityIn.prevRotationPitch) * partialTicks; this.entityX = entityIn.lastTickPosX + (entityIn.posX - entityIn.lastTickPosX) * (double)partialTicks; this.entityY = entityIn.lastTickPosY + (entityIn.posY - entityIn.lastTickPosY) * (double)partialTicks; this.entityZ = entityIn.lastTickPosZ + (entityIn.posZ - entityIn.lastTickPosZ) * (double)partialTicks; } public void renderTileEntity(TileEntity tileentityIn, float partialTicks, int destroyStage) { if (tileentityIn.getDistanceSq(this.entityX, this.entityY, this.entityZ) < tileentityIn.getMaxRenderDistanceSquared()) { if(!tileentityIn.hasFastRenderer()) { int i = this.worldObj.getCombinedLight(tileentityIn.getPos(), 0); int j = i % 65536; int k = i / 65536; OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, (float)j / 1.0F, (float)k / 1.0F); GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); } BlockPos blockpos = tileentityIn.getPos(); this.renderTileEntityAt(tileentityIn, (double)blockpos.getX() - staticPlayerX, (double)blockpos.getY() - staticPlayerY, (double)blockpos.getZ() - staticPlayerZ, partialTicks, destroyStage); } } /** * Render this TileEntity at a given set of coordinates */ public void renderTileEntityAt(TileEntity tileEntityIn, double x, double y, double z, float partialTicks) { this.renderTileEntityAt(tileEntityIn, x, y, z, partialTicks, -1); } public void renderTileEntityAt(TileEntity tileEntityIn, double x, double y, double z, float partialTicks, int destroyStage) { TileEntitySpecialRenderer<TileEntity> tileentityspecialrenderer = this.<TileEntity>getSpecialRenderer(tileEntityIn); if (tileentityspecialrenderer != null) { try { if(tileEntityIn.hasFastRenderer()) { tileentityspecialrenderer.renderTileEntityFast(tileEntityIn, x, y, z, partialTicks, destroyStage, batchBuffer.getWorldRenderer()); } else tileentityspecialrenderer.renderTileEntityAt(tileEntityIn, x, y, z, partialTicks, destroyStage); } catch (Throwable throwable) { CrashReport crashreport = CrashReport.makeCrashReport(throwable, "Rendering Block Entity"); CrashReportCategory crashreportcategory = crashreport.makeCategory("Block Entity Details"); tileEntityIn.addInfoToCrashReport(crashreportcategory); throw new ReportedException(crashreport); } } } public void setWorld(World worldIn) { this.worldObj = worldIn; } public FontRenderer getFontRenderer() { return this.fontRenderer; } /* ======================================== FORGE START =====================================*/ /** * Buffer used for batched TESRs */ private net.minecraft.client.renderer.Tessellator batchBuffer = new net.minecraft.client.renderer.Tessellator(0x200000); /** * Prepare for a batched TESR rendering. * You probably shouldn't call this manually. */ public void preDrawBatch() { batchBuffer.getWorldRenderer().begin(org.lwjgl.opengl.GL11.GL_QUADS, net.minecraft.client.renderer.vertex.DefaultVertexFormats.BLOCK); } /** * Render all TESRs batched so far. * You probably shouldn't call this manually. */ public void drawBatch(int pass) { renderEngine.bindTexture(net.minecraft.client.renderer.texture.TextureMap.locationBlocksTexture); net.minecraft.client.renderer.RenderHelper.disableStandardItemLighting(); GlStateManager.blendFunc(org.lwjgl.opengl.GL11.GL_SRC_ALPHA, org.lwjgl.opengl.GL11.GL_ONE_MINUS_SRC_ALPHA); GlStateManager.enableBlend(); GlStateManager.disableCull(); if (net.minecraft.client.Minecraft.isAmbientOcclusionEnabled()) { GlStateManager.shadeModel(org.lwjgl.opengl.GL11.GL_SMOOTH); } else { GlStateManager.shadeModel(org.lwjgl.opengl.GL11.GL_FLAT); } if(pass > 0) { batchBuffer.getWorldRenderer().sortVertexData((float)staticPlayerX, (float)staticPlayerY, (float)staticPlayerZ); } batchBuffer.draw(); net.minecraft.client.renderer.RenderHelper.enableStandardItemLighting(); } }
92349dfa32400ec9e3cfae6cb90662d26dfc311b
337
java
Java
SpringBoot/CompanyManagement/src/main/java/com/company/management/CompanyManagementApplication.java
MithunRamKumar07/Projects
f5f835a2b4758ec4fb12df43ef63239521d22115
[ "Apache-2.0" ]
null
null
null
SpringBoot/CompanyManagement/src/main/java/com/company/management/CompanyManagementApplication.java
MithunRamKumar07/Projects
f5f835a2b4758ec4fb12df43ef63239521d22115
[ "Apache-2.0" ]
null
null
null
SpringBoot/CompanyManagement/src/main/java/com/company/management/CompanyManagementApplication.java
MithunRamKumar07/Projects
f5f835a2b4758ec4fb12df43ef63239521d22115
[ "Apache-2.0" ]
null
null
null
24.071429
68
0.833828
996,987
package com.company.management; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class CompanyManagementApplication { public static void main(String[] args) { SpringApplication.run(CompanyManagementApplication.class, args); } }
92349e07455cf7dd04904813d50b848a12b7bcb3
2,238
java
Java
ParamInit-compiler/src/main/java/com/zf/plugins/param/init/holder/binding/bundle/viewmodel/ViewModelBundleParamBindingViewModelBundleHolder.java
gjwlfeng/ParamInit
9546bd67937c20a90d262e8ef196bb1b6a1347cc
[ "Apache-2.0" ]
null
null
null
ParamInit-compiler/src/main/java/com/zf/plugins/param/init/holder/binding/bundle/viewmodel/ViewModelBundleParamBindingViewModelBundleHolder.java
gjwlfeng/ParamInit
9546bd67937c20a90d262e8ef196bb1b6a1347cc
[ "Apache-2.0" ]
null
null
null
ParamInit-compiler/src/main/java/com/zf/plugins/param/init/holder/binding/bundle/viewmodel/ViewModelBundleParamBindingViewModelBundleHolder.java
gjwlfeng/ParamInit
9546bd67937c20a90d262e8ef196bb1b6a1347cc
[ "Apache-2.0" ]
null
null
null
42.226415
149
0.750223
996,988
package com.zf.plugins.param.init.holder.binding.bundle.viewmodel; import com.squareup.javapoet.MethodSpec; import com.zf.plugins.param.init.AnnotationEnv; import com.zf.plugins.param.init.ClassNameConstant; import com.zf.plugins.param.init.MethodSpecBuilderCallBack; import com.zf.plugins.param.init.MethodSpecUtils; import com.zf.plugins.param.init.holder.action.ViewModelCreationHolder; import com.zf.plugins.param.init.holder.binding.bundle.ViewModelBundleParamBindingHolder; import javax.lang.model.element.Element; public class ViewModelBundleParamBindingViewModelBundleHolder extends ViewModelBundleParamBindingHolder { private ViewModelBundleParamBindingViewModelBundleHolder(AnnotationEnv annotationEnv, Element element, boolean isSupportV4, boolean isAndroidX) { super(annotationEnv, element, isSupportV4, isAndroidX); } @Override public boolean onSetValue(MethodSpec.Builder methodSpec) { methodSpec.beginControlFlow("if ( $N != null )", getOriginFiledName()); MethodSpecUtils.codeBlock(methodSpec, new MethodSpecBuilderCallBack() { @Override public boolean innerBlock(MethodSpec.Builder builder) { builder.addStatement("bundle.putBundle($N,$N)", getParamFiledName(), getOriginFiledName()); return false; } }); methodSpec.endControlFlow(); return true; } @Override public boolean onGetValue(MethodSpec.Builder methodSpec) { methodSpec.addStatement("return bundle.getBundle($N)", getParamFiledName()); methodSpec.addAnnotation(ClassNameConstant.getNullableClassName(isAndroidX())); return true; } public static class CreationHolder extends ViewModelCreationHolder<ViewModelBundleParamBindingViewModelBundleHolder> { public CreationHolder(AnnotationEnv annotationEnv, Element element, boolean isSupportV4, boolean isAndroidX) { super(annotationEnv, element, isSupportV4, isAndroidX); } public ViewModelBundleParamBindingViewModelBundleHolder getHolder() { return new ViewModelBundleParamBindingViewModelBundleHolder(this.annotationEnv, this.element, isSupportV4, isAndroidX); } } }
92349e0c97f14209373cb0d7e53e952f9b9a0c3c
2,236
java
Java
src/main/java/com/adidas/products/reviews/security/models/Identity.java
pedrorochaorg/Adiddas-Product-Reviews
d7eadb6ed2bed456b726c9fab0d7d71103192603
[ "MIT" ]
null
null
null
src/main/java/com/adidas/products/reviews/security/models/Identity.java
pedrorochaorg/Adiddas-Product-Reviews
d7eadb6ed2bed456b726c9fab0d7d71103192603
[ "MIT" ]
null
null
null
src/main/java/com/adidas/products/reviews/security/models/Identity.java
pedrorochaorg/Adiddas-Product-Reviews
d7eadb6ed2bed456b726c9fab0d7d71103192603
[ "MIT" ]
null
null
null
23.787234
74
0.649374
996,989
package com.adidas.products.reviews.security.models; import com.adidas.products.reviews.security.enums.IdentityType; import java.util.Collection; import lombok.AllArgsConstructor; import lombok.Data; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; /** * @author pedrorocha **/ @Data @AllArgsConstructor public class Identity implements UserDetails { public String key; public Collection<? extends GrantedAuthority> authorities; public String username; public String password; public IdentityType type; /** * Instantiates a new Identity Object settings the type to API_KEY. * * @param key Api Key * @param authorities set of authorities. * @param username Api Key Subject */ public Identity( String key, Collection<? extends GrantedAuthority> authorities, String username ) { this.key = key; this.authorities = authorities; this.username = username; this.type = IdentityType.API_KEY; } /** * Instantiates a new Identity Object settings the type to BASIC_AUTH. * * @param username username * @param password password * @param authorities set of authorities. */ public Identity( String username, String password, Collection<? extends GrantedAuthority> authorities ) { this.authorities = authorities; this.username = username; this.password = password; this.type = IdentityType.BASIC_AUTH; } @Override public Collection<? extends GrantedAuthority> getAuthorities() { return authorities; } @Override public String getPassword() { return password; } @Override public String getUsername() { return username; } @Override public boolean isAccountNonExpired() { return false; } @Override public boolean isAccountNonLocked() { return false; } @Override public boolean isCredentialsNonExpired() { return false; } @Override public boolean isEnabled() { return true; } }
92349e138549f3d02507e0437454bab0efa40dc0
1,262
java
Java
mall-product/src/main/java/com/kexin/mall/product/entity/CategoryEntity.java
Kexin34/Shopping-Mall
2be218f87b6502cac8b485535a56581fb6b234cb
[ "Apache-2.0" ]
null
null
null
mall-product/src/main/java/com/kexin/mall/product/entity/CategoryEntity.java
Kexin34/Shopping-Mall
2be218f87b6502cac8b485535a56581fb6b234cb
[ "Apache-2.0" ]
null
null
null
mall-product/src/main/java/com/kexin/mall/product/entity/CategoryEntity.java
Kexin34/Shopping-Mall
2be218f87b6502cac8b485535a56581fb6b234cb
[ "Apache-2.0" ]
null
null
null
17.108108
54
0.698262
996,990
package com.kexin.mall.product.entity; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import com.baomidou.mybatisplus.annotation.TableLogic; import com.baomidou.mybatisplus.annotation.TableName; import java.io.Serializable; import java.util.Date; import java.util.List; import com.fasterxml.jackson.annotation.JsonInclude; import lombok.Data; /** * 商品三级分类 * * @author kexinwen * @email anpch@example.com * @date 2021-03-28 16:32:03 */ @Data @TableName("pms_category") public class CategoryEntity implements Serializable { private static final long serialVersionUID = 1L; /** * 分类id */ @TableId private Long catId; /** * 分类名称 */ private String name; /** * 父分类id */ private Long parentCid; /** * 层级 */ private Integer catLevel; /** * 是否显示[0-不显示,1显示] */ @TableLogic(value = "1",delval = "0") private Integer showStatus; /** * 排序 */ private Integer sort; /** * 图标地址 */ private String icon; /** * 计量单位 */ private String productUnit; /** * 商品数量 */ private Integer productCount; /** * 包含其所有子分类, (不是数据表里面的相关属性,需要注解) */ @JsonInclude(JsonInclude.Include.NON_EMPTY) @TableField(exist = false) private List<CategoryEntity> children; }
92349e59e7157a97f532696a9efa2ae78bafe6f2
1,563
java
Java
src/main/java/uk/gov/hmcts/reform/divorce/validationservice/rules/divorce/session/ReasonForDivorceBehaviourDetails.java
hmcts/div-validation-service
10a94cc2ba74aa24c081f934aa14936dfc5b6cf1
[ "MIT" ]
null
null
null
src/main/java/uk/gov/hmcts/reform/divorce/validationservice/rules/divorce/session/ReasonForDivorceBehaviourDetails.java
hmcts/div-validation-service
10a94cc2ba74aa24c081f934aa14936dfc5b6cf1
[ "MIT" ]
18
2018-06-08T15:35:45.000Z
2019-10-01T13:55:53.000Z
src/main/java/uk/gov/hmcts/reform/divorce/validationservice/rules/divorce/session/ReasonForDivorceBehaviourDetails.java
hmcts/div-validation-service
10a94cc2ba74aa24c081f934aa14936dfc5b6cf1
[ "MIT" ]
1
2021-04-10T23:05:05.000Z
2021-04-10T23:05:05.000Z
36.348837
118
0.754958
996,991
package uk.gov.hmcts.reform.divorce.validationservice.rules.divorce.session; import com.deliveredtechnologies.rulebook.annotation.Given; import com.deliveredtechnologies.rulebook.annotation.Result; import com.deliveredtechnologies.rulebook.annotation.Rule; import com.deliveredtechnologies.rulebook.annotation.Then; import com.deliveredtechnologies.rulebook.annotation.When; import lombok.Data; import uk.gov.hmcts.reform.divorce.validationservice.domain.request.DivorceSession; import java.util.List; import java.util.Optional; @Rule(order = 15) @Data public class ReasonForDivorceBehaviourDetails { private static final String BLANK_SPACE = " "; private static final String REASON_BEHAVIOUR = "unreasonable-behaviour"; private static final String ACTUAL_DATA = "Actual data is: %s"; private static final String ERROR_MESSAGE = "reasonForDivorceBehaviourDetails can not be null or empty."; @Result public List<String> result; @Given("divorceSession") public DivorceSession divorceSession = new DivorceSession(); @When public boolean when() { return Optional.ofNullable(divorceSession.getReasonForDivorce()).orElse("").equalsIgnoreCase(REASON_BEHAVIOUR) && !Optional.ofNullable(divorceSession.getReasonForDivorceBehaviourDetails()).isPresent(); } @Then public void then() { result.add(String.join( BLANK_SPACE, // delimiter ERROR_MESSAGE, String.format(ACTUAL_DATA, divorceSession.getReasonForDivorceBehaviourDetails()) )); } }
92349eba41efb51b8c0f6dc309bdd2f0194900ae
1,569
java
Java
java/leetcode/graph/redundant_connection.java
yxun/Notebook
680ae89a32d3f7d4fdcd541e66cea97e29efbd26
[ "Apache-2.0" ]
1
2021-10-04T13:26:32.000Z
2021-10-04T13:26:32.000Z
java/leetcode/graph/redundant_connection.java
yxun/Notebook
680ae89a32d3f7d4fdcd541e66cea97e29efbd26
[ "Apache-2.0" ]
3
2020-03-24T19:34:42.000Z
2022-01-21T20:15:39.000Z
java/leetcode/graph/redundant_connection.java
yxun/Notebook
680ae89a32d3f7d4fdcd541e66cea97e29efbd26
[ "Apache-2.0" ]
1
2021-04-01T20:56:50.000Z
2021-04-01T20:56:50.000Z
32.6875
238
0.615041
996,992
/** * 684. Redundant Connection * In this problem, a tree is an undirected graph that is connected and has no cycles. The given input is a graph that started as a tree with N nodes (with distinct values 1, 2, ..., N), with one additional edge added. The added edge has two different vertices chosen from 1 to N, and was not an edge that already existed. The resulting graph is given as a 2D-array of edges. Each element of edges is a pair [u, v] with u < v, that represents an undirected edge connecting nodes u and v. Return an edge that can be removed so that the resulting graph is a tree of N nodes. If there are multiple answers, return the answer that occurs last in the given 2D-array. The answer edge [u, v] should be in the same format, with u < v. Example 1: Input: [[1,2], [1,3], [2,3]] Output: [2,3] Explanation: The given undirected graph will be like this: 1 / \ 2 - 3 Example 2: Input: [[1,2], [2,3], [3,4], [1,4], [1,5]] Output: [1,4] Explanation: The given undirected graph will be like this: 5 - 1 - 2 | | 4 - 3 */ public class redundant_connection { // dfs public int[] findRedundantConnection(int[][] edges) { int[] sets = new int[edges.length + 1]; for (int[] edge : edges) { int u = find(sets, edge[0]); int v = find(sets, edge[1]); if (u == v) { return edge; } sets[u] = v; } return new int[0]; } private int find(int[] sets, int v) { return sets[v] == 0 ? v : find(sets, sets[v]); } }
92349ff145a13fa1abeda25b6c01b3e5370d5731
1,406
java
Java
src/info/ata4/util/io/BitInputStream.java
dletozeun/disunity
f22f4a55f3de655d90dcf0d5dfe751d199ec9577
[ "Unlicense" ]
1
2015-01-20T11:45:07.000Z
2015-01-20T11:45:07.000Z
src/info/ata4/util/io/BitInputStream.java
dletozeun/disunity
f22f4a55f3de655d90dcf0d5dfe751d199ec9577
[ "Unlicense" ]
null
null
null
src/info/ata4/util/io/BitInputStream.java
dletozeun/disunity
f22f4a55f3de655d90dcf0d5dfe751d199ec9577
[ "Unlicense" ]
null
null
null
21.96875
68
0.541963
996,993
/* ** 2014 May 20 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. */ package info.ata4.util.io; import java.io.IOException; import java.io.InputStream; /** * * @author Nico Bergemann <barracuda415 at yahoo.de> */ public class BitInputStream extends InputStream { private final InputStream is; private int bitBuffer; private int bitCount; private int bits = 8; public BitInputStream(InputStream is) { this.is = is; } public int getBitLength() { return bits; } public void setBitLength(int bits) { if (bits < 1 || bits > 32) { throw new IllegalArgumentException(); } this.bits = bits; } @Override public int read() throws IOException { while (bitCount < bits) { int b = is.read(); if (b == -1) { return b; } bitBuffer |= b << bitCount; bitCount += 8; } int code = bitBuffer; if (bitCount != 32) { code &= (1 << bits) - 1; } bitBuffer >>= bits; bitCount -= bits; return code; } }
9234a07c11acab71ee2bfd3191218a8f4218130b
1,840
java
Java
common/src/main/java/org/devel/jerseyfx/common/model/Person.java
stefanil/LazyTablesFX
037f103f49e72839ea12a914052118d95e8f822f
[ "Apache-2.0" ]
null
null
null
common/src/main/java/org/devel/jerseyfx/common/model/Person.java
stefanil/LazyTablesFX
037f103f49e72839ea12a914052118d95e8f822f
[ "Apache-2.0" ]
1
2015-01-06T15:11:14.000Z
2015-01-06T15:11:14.000Z
common/src/main/java/org/devel/jerseyfx/common/model/Person.java
stefanil/LazyTablesFX
037f103f49e72839ea12a914052118d95e8f822f
[ "Apache-2.0" ]
null
null
null
23.589744
121
0.692391
996,994
package org.devel.jerseyfx.common.model; import java.util.List; public class Person { private String email; private String firstName; private String lastName; private List<Person> parents; public Person() { } public Person( final String email ) { if(email == null) throw new IllegalArgumentException("Email of Person must not be null."); this.email = email; } public Person(final String email, final String firstName, final String lastName) { this(email); if(firstName == null) throw new IllegalArgumentException("First name of Person must not be null."); if(lastName == null) throw new IllegalArgumentException("Last name of Person must not be null."); this.firstName = firstName; this.lastName = lastName; } public Person(final String email, final String firstName, final String lastName, final List<Person> parents) { this(email, firstName, lastName); if(parents == null) { throw new IllegalArgumentException("Mother of Person must not be null."); } this.parents = parents; } @Override public String toString() { return "Person = {\n\teMail: " + this.email + "\n\tFirst name: " + this.firstName + "\n\tLast name: " + this.lastName + "\n\tSize of parents: " + (this.parents != null ? this.parents.size() : "0") + "\n}"; } public String getEmail() { return email; } public void setEmail( final String email ) { this.email = email; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public void setFirstName( final String firstName ) { this.firstName = firstName; } public void setLastName( final String lastName ) { this.lastName = lastName; } public List<Person> getParents() { return parents; } public void setParents(List<Person> parents) { this.parents = parents; } }
9234a3d4135c55a725e9224fd6583ef454bc705c
5,674
java
Java
DuelistMod/src/main/java/duelistmod/cards/OjamaEmperor.java
Dream5366/StS-DuelistMod
f2902db0e14cfa175053188b9f37b4c9611955ac
[ "Unlicense" ]
null
null
null
DuelistMod/src/main/java/duelistmod/cards/OjamaEmperor.java
Dream5366/StS-DuelistMod
f2902db0e14cfa175053188b9f37b4c9611955ac
[ "Unlicense" ]
null
null
null
DuelistMod/src/main/java/duelistmod/cards/OjamaEmperor.java
Dream5366/StS-DuelistMod
f2902db0e14cfa175053188b9f37b4c9611955ac
[ "Unlicense" ]
null
null
null
30.836957
153
0.701093
996,995
package duelistmod.cards; 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 duelistmod.DuelistMod; import duelistmod.abstracts.DuelistCard; import duelistmod.actions.common.RandomizedHandAction; import duelistmod.helpers.DebuffHelper; import duelistmod.patches.AbstractCardEnum; import duelistmod.powers.*; import duelistmod.variables.Tags; public class OjamaEmperor extends DuelistCard { // TEXT DECLARATION public static final String ID = DuelistMod.makeID("OjamaEmperor"); private static final CardStrings cardStrings = CardCrawlGame.languagePack.getCardStrings(ID); public static final String IMG = DuelistMod.makeCardPath("OjamaEmperor.png"); public static final String NAME = cardStrings.NAME; public static final String DESCRIPTION = cardStrings.DESCRIPTION; public static final String UPGRADE_DESCRIPTION = cardStrings.UPGRADE_DESCRIPTION; // /TEXT DECLARATION/ // STAT DECLARATION private static final CardRarity RARITY = CardRarity.RARE; private static final CardTarget TARGET = CardTarget.ENEMY; private static final CardType TYPE = CardType.SKILL; public static final CardColor COLOR = AbstractCardEnum.DUELIST_MONSTERS; private static final int COST = 3; private static int MIN_BUFF_TURNS_ROLL = 1; private static int MAX_BUFF_TURNS_ROLL = 3; private static int MIN_DEBUFF_TURNS_ROLL = 1; private static int MAX_DEBUFF_TURNS_ROLL = 6; private static int RAND_CARDS = 2; private static int RAND_BUFFS = 1; private static int RAND_DEBUFFS = 2; // /STAT DECLARATION/ public OjamaEmperor() { super(ID, NAME, IMG, COST, DESCRIPTION, TYPE, COLOR, RARITY, TARGET); this.tags.add(Tags.MONSTER); this.tags.add(Tags.OJAMA); this.tags.add(Tags.NEVER_GENERATE); this.misc = 0; this.originalName = this.name; this.tributes = this.baseTributes = 5; this.baseMagicNumber = this.magicNumber = 10; this.showEvokeValue = true; this.showEvokeOrbCount = 1; this.exhaust = true; } // Actions the card should do. @Override public void use(AbstractPlayer p, AbstractMonster m) { // Tribute tribute(p, this.tributes, false, this); // Add 5 random cards to hand, set cost to 0 for (int i = 0; i < RAND_CARDS; i++) { AbstractCard card = AbstractDungeon.returnTrulyRandomCardInCombat().makeStatEquivalentCopy(); AbstractDungeon.actionManager.addToTop(new RandomizedHandAction(card, false, true, true, false, false, false, true, true, 1, 3, 0, 1, 1, 2)); if (DuelistMod.debug) { DuelistMod.logger.info("Calling RandomizedAction from: " + this.originalName); } } // Give self 3 random buffs for (int i = 0; i < RAND_BUFFS; i++) { int randomTurnNum = AbstractDungeon.cardRandomRng.random(MIN_BUFF_TURNS_ROLL, MAX_BUFF_TURNS_ROLL); applyRandomBuffPlayer(p, randomTurnNum, false); } // Give 3 random debuffs to enemy for (int i = 0; i < RAND_DEBUFFS; i++) { int randomTurnNum = AbstractDungeon.cardRandomRng.random(MIN_DEBUFF_TURNS_ROLL, MAX_DEBUFF_TURNS_ROLL); applyPower(DebuffHelper.getRandomDebuff(p, m, randomTurnNum), m); } channelRandom(); heal(p, this.magicNumber); } // Which card to return when making a copy of this card. @Override public AbstractCard makeCopy() { return new OjamaEmperor(); } // Upgraded stats. @Override public void upgrade() { if (!this.upgraded) { this.upgradeName(); this.upgradeMagicNumber(5); this.upgradeTributes(-1); this.rawDescription = UPGRADE_DESCRIPTION; this.initializeDescription(); } } // If player doesn't have enough summons, can't play card @Override public boolean canUse(AbstractPlayer p, AbstractMonster m) { // Check super canUse() boolean canUse = super.canUse(p, m); if (!canUse) { return false; } // Pumpking & Princess else if (this.misc == 52) { return true; } // Mausoleum check else if (p.hasPower(EmperorPower.POWER_ID)) { EmperorPower empInstance = (EmperorPower)p.getPower(EmperorPower.POWER_ID); if (!empInstance.flag) { return true; } else { if (p.hasPower(SummonPower.POWER_ID)) { int temp = (p.getPower(SummonPower.POWER_ID).amount); if (temp >= this.tributes) { return true; } } } } // Check for # of summons >= tributes else { if (p.hasPower(SummonPower.POWER_ID)) { int temp = (p.getPower(SummonPower.POWER_ID).amount); if (temp >= this.tributes) { return true; } } } // Player doesn't have something required at this point this.cantUseMessage = this.tribString; return false; } @Override public void onTribute(DuelistCard tributingCard) { // TODO Auto-generated method stub } @Override public void onResummon(int summons) { // TODO Auto-generated method stub } @Override public void summonThis(int summons, DuelistCard c, int var) { // TODO Auto-generated method stub } @Override public void summonThis(int summons, DuelistCard c, int var, AbstractMonster m) { // TODO Auto-generated method stub } @Override public String getID() { return ID; } @Override public void optionSelected(AbstractPlayer arg0, AbstractMonster arg1, int arg2) { // TODO Auto-generated method stub } }
9234a4a6ebbc781cd39c6f7f1d1d37b0f75f2346
4,732
java
Java
app/src/test/java/eu/vmpay/overtimetracker/CalendarsViewModelTest.java
vmpay/OvertimeTracker
716a34427f1e68bf4130b22110df73e842c9b1e6
[ "Apache-2.0" ]
null
null
null
app/src/test/java/eu/vmpay/overtimetracker/CalendarsViewModelTest.java
vmpay/OvertimeTracker
716a34427f1e68bf4130b22110df73e842c9b1e6
[ "Apache-2.0" ]
1
2018-07-17T10:37:09.000Z
2018-07-17T10:37:09.000Z
app/src/test/java/eu/vmpay/overtimetracker/CalendarsViewModelTest.java
vmpay/OvertimeTracker
716a34427f1e68bf4130b22110df73e842c9b1e6
[ "Apache-2.0" ]
null
null
null
28.678788
109
0.783601
996,996
package eu.vmpay.overtimetracker; import android.Manifest; import android.app.Application; import android.arch.core.executor.testing.InstantTaskExecutorRule; import com.tbruyelle.rxpermissions2.RxPermissions; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.util.ArrayList; import java.util.List; import eu.vmpay.overtimetracker.calendars.CalendarsViewModel; import eu.vmpay.overtimetracker.repository.CalendarModel; import eu.vmpay.overtimetracker.repository.CalendarRepository; import io.reactivex.Observable; import io.reactivex.Single; import io.reactivex.schedulers.TestScheduler; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertTrue; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * Unit tests for the implementation of {@link CalendarsViewModel} */ public class CalendarsViewModelTest { // Executes each task synchronously using Architecture Components. @Rule public InstantTaskExecutorRule instantExecutorRule = new InstantTaskExecutorRule(); @Mock private CalendarRepository calendarRepository; @Mock private Application application; @Mock private RxPermissions rxPermissions; private CalendarsViewModel calendarsViewModel; private TestScheduler testScheduler; private static List<CalendarModel> calendarModelList; @Before public void setUp() { // Mockito has a very convenient way to inject mocks by using the @Mock annotation. To // inject the mocks in the test the initMocks method needs to be called. MockitoAnnotations.initMocks(this); // Mock scheduler using RxJava TestScheduler. testScheduler = new TestScheduler(); // Get a reference to the class under test calendarsViewModel = new CalendarsViewModel(calendarRepository, application, testScheduler, testScheduler); // We initialise the calendars to 3 calendarModelList = new ArrayList<>(); calendarModelList.add(new CalendarModel(1, "Title1", "Account1", "Owner1")); calendarModelList.add(new CalendarModel(2, "Title2", "Account2", "Owner2")); calendarModelList.add(new CalendarModel(3, "Title3", "Account3", "Owner3")); setUpRules(); } private void setUpRules() { when(application.getApplicationContext()).thenReturn(application); when(rxPermissions.isGranted(Manifest.permission.READ_CALENDAR)).thenReturn(true); doReturn(Observable.just(true)).when(rxPermissions).request(Manifest.permission.READ_CALENDAR); // Make repository return mocked list doReturn(Single.just(calendarModelList)).when(calendarRepository).getCalendarList(); } @Test public void permissionGrantedHappyTest() { // Check permission calendarsViewModel.checkPermissionGranted(rxPermissions); // Trigger loading calendar action testScheduler.triggerActions(); // Verify results assertTrue(calendarsViewModel.isPermissionGranted.get()); verify(calendarRepository).getCalendarList(); for(int i = 0; i < calendarModelList.size(); i++) { assertEquals(calendarModelList.get(i), calendarsViewModel.items.get(i)); } } @Test public void permissionDeniedHappyTest() { // Mock rxPermission object RxPermissions rxPermissions = mock(RxPermissions.class); when(rxPermissions.isGranted(Manifest.permission.READ_CALENDAR)).thenReturn(false); // Check permission calendarsViewModel.checkPermissionGranted(rxPermissions); // Verify result assertFalse(calendarsViewModel.isPermissionGranted.get()); } @Test public void permissionCheckFailTest() { // Pass null argument calendarsViewModel.checkPermissionGranted(null); // Verify method never called verify(calendarRepository, never()).getCalendarList(); } @Test public void viewModelStartHappyTest() { // Starts viewModel calendarsViewModel.start(rxPermissions); // Trigger loading calendar action testScheduler.triggerActions(); // Verify results verify(calendarRepository).getCalendarList(); for(int i = 0; i < calendarModelList.size(); i++) { assertEquals(calendarModelList.get(i), calendarsViewModel.items.get(i)); } assertTrue(calendarsViewModel.isPermissionGranted.get()); } @Test public void viewModelStartFailTest() { // Starts viewModel with null argument calendarsViewModel.start(null); // Verify result assertFalse(calendarsViewModel.isPermissionGranted.get()); } @After public void tearDown() { calendarModelList = null; calendarsViewModel = null; testScheduler = null; } }
9234a5407f5fd89e0c32b5bbfd73f02ad218a8f3
1,631
java
Java
jmx/src/main/javax/management/MBeanServerDelegateMBean.java
cquoss/jboss-4.2.3.GA-jdk8
f3acab9a69c764365bb3f38c0e9a01708dd22b4b
[ "Apache-2.0" ]
null
null
null
jmx/src/main/javax/management/MBeanServerDelegateMBean.java
cquoss/jboss-4.2.3.GA-jdk8
f3acab9a69c764365bb3f38c0e9a01708dd22b4b
[ "Apache-2.0" ]
null
null
null
jmx/src/main/javax/management/MBeanServerDelegateMBean.java
cquoss/jboss-4.2.3.GA-jdk8
f3acab9a69c764365bb3f38c0e9a01708dd22b4b
[ "Apache-2.0" ]
null
null
null
31.921569
70
0.746929
996,997
/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package javax.management; /** * Management interface of the MBean server delegate MBean. * * @see javax.management.MBeanServerDelegate * * @author <a href="mailto:kenaa@example.com">Juha Lindfors</a>. * @version $Revision: 57200 $ * */ public interface MBeanServerDelegateMBean { public String getMBeanServerId(); public String getSpecificationName(); public String getSpecificationVersion(); public String getSpecificationVendor(); public String getImplementationName(); public String getImplementationVersion(); public String getImplementationVendor(); }
9234a5ecf35d6f88c9187f19b618ae98ef0b09a5
10,549
java
Java
src/test/java/com/aminebag/larjson/resource/SafeResourceCloserTest.java
aminebag/LarJson
eab5c835befabc891e182b04c4ec110eb13572f5
[ "MIT" ]
2
2020-12-08T19:15:02.000Z
2021-02-09T09:19:43.000Z
src/test/java/com/aminebag/larjson/resource/SafeResourceCloserTest.java
aminebag/LarJson
eab5c835befabc891e182b04c4ec110eb13572f5
[ "MIT" ]
null
null
null
src/test/java/com/aminebag/larjson/resource/SafeResourceCloserTest.java
aminebag/LarJson
eab5c835befabc891e182b04c4ec110eb13572f5
[ "MIT" ]
null
null
null
40.110266
115
0.49891
996,998
package com.aminebag.larjson.resource; import org.junit.jupiter.api.Test; import java.io.IOException; import java.util.Arrays; import java.util.concurrent.atomic.AtomicInteger; import static org.junit.jupiter.api.Assertions.*; /** * @author Amine Bagdouri */ public class SafeResourceCloserTest { @Test void testCloseWithoutException() throws IOException { AtomicInteger counter = new AtomicInteger(); new SafeResourceCloser() .add(() -> counter.getAndIncrement()) .add(() -> counter.getAndAdd(2)) .add(Arrays.asList( () -> counter.getAndAdd(3), () -> counter.getAndAdd(4) )).close(); assertEquals(10, counter.get()); } @Test void testCloseOneIOException() { AtomicInteger counter = new AtomicInteger(); IOException ioException = new IOException(); try { new SafeResourceCloser() .add(() -> counter.getAndIncrement()) .add(() -> { throw ioException; }) .add(() -> counter.getAndAdd(2)) .add(Arrays.asList( () -> counter.getAndAdd(3), () -> counter.getAndAdd(4) )).close(); fail(); } catch (IOException e) { assertTrue(ioException == e); } assertEquals(10, counter.get()); } @Test void testCloseMultipleIOExceptions() throws IOException { AtomicInteger counter = new AtomicInteger(); IOException ioException0 = new IOException(); IOException ioException1 = new IOException(); try { new SafeResourceCloser() .add(() -> counter.getAndIncrement()) .add(() -> { throw ioException0; }) .add(() -> counter.getAndAdd(2)) .add(Arrays.asList( () -> counter.getAndAdd(3), () -> { throw ioException1; }, () -> counter.getAndAdd(4) )).close(); fail(); } catch (MultipleResourcesIOException e) { assertEquals(Arrays.asList(ioException0, ioException1), e.getIOExceptions()); assertEquals(Arrays.asList(), e.getRuntimeExceptions()); } assertEquals(10, counter.get()); } @Test void testCloseOneRuntimeException() throws IOException { AtomicInteger counter = new AtomicInteger(); NumberFormatException numberFormatException = new NumberFormatException(); try { new SafeResourceCloser() .add(() -> counter.getAndIncrement()) .add(() -> { throw numberFormatException; }) .add(() -> counter.getAndAdd(2)) .add(Arrays.asList( () -> counter.getAndAdd(3), () -> counter.getAndAdd(4) )).close(); fail(); } catch (NumberFormatException e) { assertTrue(numberFormatException == e); } assertEquals(10, counter.get()); } @Test void testCloseMultipleRuntimeExceptions() throws IOException { AtomicInteger counter = new AtomicInteger(); NumberFormatException numberFormatException = new NumberFormatException(); IllegalArgumentException illegalArgumentException = new IllegalArgumentException(); try { new SafeResourceCloser() .add(() -> counter.getAndIncrement()) .add(() -> { throw numberFormatException; }) .add(() -> counter.getAndAdd(2)) .add(Arrays.asList( () -> counter.getAndAdd(3), () -> { throw illegalArgumentException; }, () -> counter.getAndAdd(4) )).close(); fail(); } catch (MultipleResourcesRuntimeException e) { assertEquals(Arrays.asList(numberFormatException, illegalArgumentException), e.getRuntimeExceptions()); } assertEquals(10, counter.get()); } @Test void testCloseMultipleIOExceptionsOneRuntimeException() throws IOException { AtomicInteger counter = new AtomicInteger(); IOException ioException0 = new IOException(); IOException ioException1 = new IOException(); NumberFormatException numberFormatException = new NumberFormatException(); try { new SafeResourceCloser() .add(() -> counter.getAndIncrement()) .add(() -> { throw ioException0; }) .add(() -> counter.getAndAdd(2)) .add(Arrays.asList( () -> { throw numberFormatException; }, () -> counter.getAndAdd(3), () -> { throw ioException1; }, () -> counter.getAndAdd(4) )).close(); fail(); } catch (MultipleResourcesIOException e) { assertEquals(Arrays.asList(ioException0, ioException1), e.getIOExceptions()); assertEquals(Arrays.asList(numberFormatException), e.getRuntimeExceptions()); } assertEquals(10, counter.get()); } @Test void testCloseOneIOExceptionOneRuntimeException() throws IOException { AtomicInteger counter = new AtomicInteger(); IOException ioException = new IOException(); NumberFormatException numberFormatException = new NumberFormatException(); try { new SafeResourceCloser() .add(() -> counter.getAndIncrement()) .add(() -> { throw ioException; }) .add(() -> counter.getAndAdd(2)) .add(Arrays.asList( () -> { throw numberFormatException; }, () -> counter.getAndAdd(3), () -> counter.getAndAdd(4) )).close(); fail(); } catch (MultipleResourcesIOException e) { assertEquals(Arrays.asList(ioException), e.getIOExceptions()); assertEquals(Arrays.asList(numberFormatException), e.getRuntimeExceptions()); } assertEquals(10, counter.get()); } @Test void testCloseMultipleIOExceptionsMultipleRuntimeExceptions() throws IOException { closeMultipleIOExceptionsMultipleRuntimeExceptions(); } @Test void testCloseOneIOExceptionMultipleRuntimeExceptions() throws IOException { AtomicInteger counter = new AtomicInteger(); IOException ioException = new IOException(); NumberFormatException numberFormatException = new NumberFormatException(); IllegalArgumentException illegalArgumentException = new IllegalArgumentException(); try { new SafeResourceCloser() .add(() -> counter.getAndIncrement()) .add(() -> { throw ioException; }) .add(() -> counter.getAndAdd(2)) .add(Arrays.asList( () -> { throw numberFormatException; }, () -> counter.getAndAdd(3), () -> { throw illegalArgumentException; }, () -> counter.getAndAdd(4) )).close(); fail(); } catch (MultipleResourcesIOException e) { assertEquals(Arrays.asList(ioException), e.getIOExceptions()); assertEquals(Arrays.asList(numberFormatException, illegalArgumentException), e.getRuntimeExceptions()); } assertEquals(10, counter.get()); } @Test void testCloseTwice() throws IOException { SafeResourceCloser safeResourceCloser = closeMultipleIOExceptionsMultipleRuntimeExceptions(); safeResourceCloser.close(); } private SafeResourceCloser closeMultipleIOExceptionsMultipleRuntimeExceptions() throws IOException { AtomicInteger counter = new AtomicInteger(); IOException ioException0 = new IOException(); IOException ioException1 = new IOException(); NumberFormatException numberFormatException = new NumberFormatException(); IllegalArgumentException illegalArgumentException = new IllegalArgumentException(); SafeResourceCloser safeResourceCloser = null; try { safeResourceCloser = new SafeResourceCloser() .add(() -> { throw numberFormatException; }) .add(() -> counter.getAndIncrement()) .add(() -> { throw ioException0; }) .add(() -> counter.getAndAdd(2)) .add(Arrays.asList( () -> { throw ioException1; }, () -> counter.getAndAdd(3), () -> { throw illegalArgumentException; }, () -> counter.getAndAdd(4) )); safeResourceCloser.close(); fail(); } catch (MultipleResourcesIOException e) { assertEquals(Arrays.asList(ioException0, ioException1), e.getIOExceptions()); assertEquals(Arrays.asList(numberFormatException, illegalArgumentException), e.getRuntimeExceptions()); } assertEquals(10, counter.get()); return safeResourceCloser; } }
9234a622dc6d2a3e2b2ace75d7f170afbc2ab3a2
5,813
java
Java
java/basic/topic6/src/com/company/Main.java
PCianes/OpenBootcamp
0568ee025155b3e26b2248c2046bbae1d8e50acc
[ "MIT" ]
null
null
null
java/basic/topic6/src/com/company/Main.java
PCianes/OpenBootcamp
0568ee025155b3e26b2248c2046bbae1d8e50acc
[ "MIT" ]
null
null
null
java/basic/topic6/src/com/company/Main.java
PCianes/OpenBootcamp
0568ee025155b3e26b2248c2046bbae1d8e50acc
[ "MIT" ]
null
null
null
26.912037
96
0.543781
996,999
package com.company; import java.io.*; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; public class Main { public static void main(String[] args) { String word = "hello world"; String reverseWord = reverse(word); System.out.println("Reversed word: " + reverseWord); String reverseWordBuilder = reverse( new StringBuilder(word) ); System.out.println("Reversed word with Builder: " + reverseWordBuilder); // launching all methods as different exercises method1(); method2(); method3(); method4(); method5(); method6(); try { int number = 555; int result = method7(number); } catch (ArithmeticException exception) { System.out.println("This can't be done (divide by zero)"); } finally { System.out.println("Code demo"); } Path path = Paths.get("src/resources"); String resourcesPath = path.toAbsolutePath().toString(); method8(resourcesPath + "/input-data.txt", resourcesPath + "/output-data.txt"); method9(resourcesPath + "/final-data.txt"); } private static String reverse(String text){ String reverseText = ""; for(int i = text.length() - 1; i >= 0; i--){ String letter = String.valueOf( text.charAt(i) ); reverseText = reverseText.concat( letter ); } return reverseText; } private static String reverse( StringBuilder text){ return text.reverse().toString(); } private static void method1() { String[] data = { "apple", "tomato", "car", "house", "cloudy"}; for (String word : data ){ System.out.println(word); } } private static void method2(){ int[][] data = { {1, 2, 3, 4, 5}, {11, 22, 33, 44, 55} }; for (int row =0; row < data.length; row++){ for ( int column=0; column < data[row].length; column++){ System.out.println("Position ["+ row + "]["+ column +"]: " + data[row][column]); } } /* for ( int[] x: data){ for ( int y : x) { System.out.println(y); } } */ } private static void method3() { Vector<Integer> dataVector = new Vector<>(); dataVector.add(111); dataVector.add(222); dataVector.add(333); dataVector.add(444); dataVector.add(555); System.out.println(dataVector); dataVector.remove(1); System.out.println(dataVector); dataVector.remove(2); System.out.println(dataVector); } private static void method4() { Vector<Integer> dataVector = new Vector<>(); System.out.println("Initial Capacity: " + dataVector.capacity()); for(int i=1; i <=1000; i++){ dataVector.add(i); } System.out.println(dataVector); System.out.println("Final Capacity: " + dataVector.capacity()); } private static void method5(){ ArrayList<String> arrayData = new ArrayList<>(); arrayData.add("one"); arrayData.add("two"); arrayData.add("three"); arrayData.add("four"); for( String word: arrayData){ System.out.println(word); } LinkedList<String> linkedData = new LinkedList<>(arrayData); for( String word: linkedData) { System.out.println(word); } } private static void method6(){ ArrayList<Integer> arrayData = new ArrayList<>(); for( int i = 1; i<=10; i++){ arrayData.add(i); } for( int i = arrayData.size()-1; i>=0 ;i--){ int number = arrayData.get(i); if( number % 2 == 0){ arrayData.remove(i); } } for(int number: arrayData){ System.out.println(number); } } private static int method7(int number) throws ArithmeticException { int zero = 0; return number / zero; } private static void method8(String fileIn, String fileOut){ try { InputStream inputFile = new FileInputStream(fileIn); PrintStream outputFile = new PrintStream(fileOut); byte[] bytes = inputFile.readAllBytes(); String content = new String(bytes, StandardCharsets.UTF_8); outputFile.println(content); inputFile.close(); outputFile.close(); } catch (FileNotFoundException exception){ System.out.println(exception.toString()); } catch (IOException exception) { exception.printStackTrace(); } } private static void method9(String fileOut){ HashMap<Integer, String> content = new HashMap<>(); try { PrintStream outputFile = new PrintStream(fileOut); while (content.size() < 5){ System.out.println("Type a character"); InputStreamReader input = new InputStreamReader(System.in); int code = input.read(); char character = (char) code; outputFile.println("code: " + code + " => character: " + character); content.put(code, String.valueOf(character)); } outputFile.close(); } catch (IOException e) { e.printStackTrace(); } LinkedList<Integer> keys = new LinkedList<>(content.keySet()); LinkedList<String> values = new LinkedList<>(content.values()); System.out.println(keys); System.out.println(values); } }
9234a78cbb638abe5031450ebb3fb770d7d81b2b
508
java
Java
laravel_mix/src/main/java/me/ixk/laravel_mix/LaravelMixApplication.java
syfxlin/spring-learn
61f84f8a5b9eea136521891a90c650ba33803f8f
[ "MIT" ]
null
null
null
laravel_mix/src/main/java/me/ixk/laravel_mix/LaravelMixApplication.java
syfxlin/spring-learn
61f84f8a5b9eea136521891a90c650ba33803f8f
[ "MIT" ]
null
null
null
laravel_mix/src/main/java/me/ixk/laravel_mix/LaravelMixApplication.java
syfxlin/spring-learn
61f84f8a5b9eea136521891a90c650ba33803f8f
[ "MIT" ]
null
null
null
24.190476
68
0.799213
997,000
package me.ixk.laravel_mix; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; @SpringBootApplication @Controller public class LaravelMixApplication { public static void main(String[] args) { SpringApplication.run(LaravelMixApplication.class, args); } @GetMapping public String index() { return "index"; } }
9234a7b7f54b12debcf262c3c27b3c4f63a77eb6
6,426
java
Java
hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/term/LoadedFileDescriptors.java
ArborMetrix/hapi-fhir
a25aa37e6afd6b9ff5bc48063e389a3541a200cb
[ "Apache-2.0" ]
1
2020-11-19T07:08:06.000Z
2020-11-19T07:08:06.000Z
hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/term/LoadedFileDescriptors.java
ArborMetrix/hapi-fhir
a25aa37e6afd6b9ff5bc48063e389a3541a200cb
[ "Apache-2.0" ]
31
2020-10-27T07:17:10.000Z
2022-03-14T10:22:02.000Z
hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/term/LoadedFileDescriptors.java
ArborMetrix/hapi-fhir
a25aa37e6afd6b9ff5bc48063e389a3541a200cb
[ "Apache-2.0" ]
1
2022-02-17T17:17:32.000Z
2022-02-17T17:17:32.000Z
36.72
216
0.721133
997,001
package ca.uhn.fhir.jpa.term; /*- * #%L * HAPI FHIR JPA Server * %% * Copyright (C) 2014 - 2020 University Health Network * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import ca.uhn.fhir.jpa.term.api.ITermLoaderSvc; import ca.uhn.fhir.jpa.util.LogicUtil; import ca.uhn.fhir.rest.server.exceptions.InternalErrorException; import ca.uhn.fhir.rest.server.exceptions.UnprocessableEntityException; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.io.input.BOMInputStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; public class LoadedFileDescriptors implements Closeable { private static final Logger ourLog = LoggerFactory.getLogger(LoadedFileDescriptors.class); private List<File> myTemporaryFiles = new ArrayList<>(); private List<ITermLoaderSvc.FileDescriptor> myUncompressedFileDescriptors = new ArrayList<>(); LoadedFileDescriptors(List<ITermLoaderSvc.FileDescriptor> theFileDescriptors) { try { for (ITermLoaderSvc.FileDescriptor next : theFileDescriptors) { if (next.getFilename().toLowerCase().endsWith(".zip")) { ourLog.info("Uncompressing {} into temporary files", next.getFilename()); try (InputStream inputStream = next.getInputStream()) { try (BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream)) { try (ZipInputStream zis = new ZipInputStream(bufferedInputStream)) { for (ZipEntry nextEntry; (nextEntry = zis.getNextEntry()) != null; ) { try (BOMInputStream fis = new NonClosableBOMInputStream(zis)) { File nextTemporaryFile = File.createTempFile("hapifhir", ".tmp"); ourLog.info("Creating temporary file: {}", nextTemporaryFile.getAbsolutePath()); nextTemporaryFile.deleteOnExit(); try (FileOutputStream fos = new FileOutputStream(nextTemporaryFile, false)) { IOUtils.copy(fis, fos); String nextEntryFileName = nextEntry.getName(); myUncompressedFileDescriptors.add(new ITermLoaderSvc.FileDescriptor() { @Override public String getFilename() { return nextEntryFileName; } @Override public InputStream getInputStream() { try { return new FileInputStream(nextTemporaryFile); } catch (FileNotFoundException e) { throw new InternalErrorException(e); } } }); myTemporaryFiles.add(nextTemporaryFile); } } } } } } } else { myUncompressedFileDescriptors.add(next); } } } catch (IOException e) { throw new InternalErrorException(e); } } public boolean hasFile(String theFilename) { return myUncompressedFileDescriptors .stream() .map(t -> t.getFilename().replaceAll(".*[\\\\/]", "")) // Strip the path from the filename .anyMatch(t -> t.equals(theFilename)); } @Override public void close() { for (File next : myTemporaryFiles) { ourLog.info("Deleting temporary file: {}", next.getAbsolutePath()); FileUtils.deleteQuietly(next); } } List<ITermLoaderSvc.FileDescriptor> getUncompressedFileDescriptors() { return myUncompressedFileDescriptors; } private List<String> notFound(List<String> theExpectedFilenameFragments) { Set<String> foundFragments = new HashSet<>(); for (String nextExpected : theExpectedFilenameFragments) { for (ITermLoaderSvc.FileDescriptor next : myUncompressedFileDescriptors) { if (next.getFilename().contains(nextExpected)) { foundFragments.add(nextExpected); break; } } } ArrayList<String> notFoundFileNameFragments = new ArrayList<>(theExpectedFilenameFragments); notFoundFileNameFragments.removeAll(foundFragments); return notFoundFileNameFragments; } void verifyMandatoryFilesExist(List<String> theExpectedFilenameFragments) { List<String> notFound = notFound(theExpectedFilenameFragments); if (!notFound.isEmpty()) { throw new UnprocessableEntityException("Could not find the following mandatory files in input: " + notFound); } } void verifyOptionalFilesExist(List<String> theExpectedFilenameFragments) { List<String> notFound = notFound(theExpectedFilenameFragments); if (!notFound.isEmpty()) { ourLog.warn("Could not find the following optional files: " + notFound); } } void verifyPartLinkFilesExist(List<String> theMultiPartLinkFiles, String theSinglePartLinkFile) { List<String> notFoundMulti = notFound(theMultiPartLinkFiles); List<String> notFoundSingle = notFound(Arrays.asList(theSinglePartLinkFile)); // Expect all of the files in theMultiPartLinkFiles to be found and theSinglePartLinkFile to not be found, // or none of the files in theMultiPartLinkFiles to be found and the SinglePartLinkFile to be found. boolean multiPartFilesFound = notFoundMulti.isEmpty(); boolean singlePartFilesFound = notFoundSingle.isEmpty(); if (!LogicUtil.multiXor(multiPartFilesFound, singlePartFilesFound)) { String msg; if (!multiPartFilesFound && !singlePartFilesFound) { msg = "Could not find any of the PartLink files: " + notFoundMulti + " nor " + notFoundSingle; } else { msg = "Only either the single PartLink file or the split PartLink files can be present. Found both the single PartLink file, " + theSinglePartLinkFile + ", and the split PartLink files: " + theMultiPartLinkFiles; } throw new UnprocessableEntityException(msg); } } private static class NonClosableBOMInputStream extends BOMInputStream { NonClosableBOMInputStream(InputStream theWrap) { super(theWrap); } @Override public void close() { // nothing } } }
9234a815a85a09ba7cbe359767335f462f41fa9b
2,450
java
Java
src/edu/lewisu/cs/kylevbye/mazegame/MazeGame.java
kylebye4mav/MazeGame
e1812d7fbcfe4fed73d01af1aebcec63ffbaca3d
[ "MIT" ]
null
null
null
src/edu/lewisu/cs/kylevbye/mazegame/MazeGame.java
kylebye4mav/MazeGame
e1812d7fbcfe4fed73d01af1aebcec63ffbaca3d
[ "MIT" ]
null
null
null
src/edu/lewisu/cs/kylevbye/mazegame/MazeGame.java
kylebye4mav/MazeGame
e1812d7fbcfe4fed73d01af1aebcec63ffbaca3d
[ "MIT" ]
null
null
null
21.875
82
0.662857
997,002
/** * */ package edu.lewisu.cs.kylevbye.mazegame; import java.util.ArrayList; import edu.lewisu.cs.kylevbye.util.*; /** * This class launches a game where you find hidden * treasure. Random rooms may heal, damage, or do nothing. * * @author Kyle V Bye * @see Building * @see RoomReader * @see Room * @see MazeGameManager * @see edu.lewisu.cs.kylevbye.util.ConsoleUtil */ public class MazeGame { /** * Program begins here. * @param args program arguments */ public static void main(String[] args) { // Starting sequence System.out.println("\nStart\n"); // Take mapFileName from user. String mapFileName; while ((mapFileName = ConsoleUtil.readLine("Input Map File: ")).equals("")) { System.out.println("\nPlease actually type something.\n"); } System.out.println(); // Process File if (!RoomReader.readFile(mapFileName)) { System.err.println("File Process Failed... Terminating"); terminate(); return; } // Link Rooms into a Building Building building = new Building(mapFileName.replace(".txt", "")); building.setRoomList(RoomReader.getRoomList()); building.linkRooms(RoomReader.getMapStringList(), RoomReader.getBuildingSize()); // Set up Player and Game Manager Player player = new Player(askPlayerName(),100); MazeGameManager gameManager = new MazeGameManager(building, player); // Play boolean playAgain = true; while(playAgain) { gameManager.play(); playAgain = askPlayAgain(); } // End of program terminate(); } /** * Returns a non empty player name. * @return String representing a player's name. */ private static String askPlayerName() { String playerName = new String(); while (playerName.equals(new String())) { playerName = ConsoleUtil.readLine("Please Enter Your Name: "); } return playerName; } /** * Returns true if and only if the user types in "Y" in the input * stream. Otherwise, false is returned. * * @return true/false */ private static boolean askPlayAgain() { String userInput = ""; while (!(userInput.equals("Y") || userInput.equals("N"))) { userInput = ConsoleUtil.readLine("Play Again? [Y/N]-->").toUpperCase(); } return userInput.equals("Y"); } /** * Prints "Terminating..." to the output stream * with line feeds before and after. */ private static void terminate() { System.out.println("\nTerminating...\n"); } }
9234a82ce6db1b0fb526d0d072a75114ddfb7acc
11,560
java
Java
workspaces/voyage/hpic4vc_storage_provider/src/main/java/com/hp/asi/hpic4vc/storage/provider/adapter/storagesystem/StorageSystemOverviewDataAdapter.java
raychorn/svn_hp-projects
d5547906354e2759a93b8030632128e8c4bf3880
[ "CC0-1.0" ]
null
null
null
workspaces/voyage/hpic4vc_storage_provider/src/main/java/com/hp/asi/hpic4vc/storage/provider/adapter/storagesystem/StorageSystemOverviewDataAdapter.java
raychorn/svn_hp-projects
d5547906354e2759a93b8030632128e8c4bf3880
[ "CC0-1.0" ]
null
null
null
workspaces/voyage/hpic4vc_storage_provider/src/main/java/com/hp/asi/hpic4vc/storage/provider/adapter/storagesystem/StorageSystemOverviewDataAdapter.java
raychorn/svn_hp-projects
d5547906354e2759a93b8030632128e8c4bf3880
[ "CC0-1.0" ]
null
null
null
50.480349
100
0.659602
997,003
package com.hp.asi.hpic4vc.storage.provider.adapter.storagesystem; import com.hp.asi.hpic4vc.provider.locale.I18NProvider; import com.hp.asi.hpic4vc.provider.model.LabelValueListModel; import com.hp.asi.hpic4vc.provider.model.PieChartModel; import com.hp.asi.hpic4vc.provider.model.SummaryPortletModel; import com.hp.asi.hpic4vc.storage.provider.dam.model.StorageSystemOverviewModel; import com.hp.asi.hpic4vc.storage.provider.locale.I18NStorageProvider; import com.hp.asi.ui.hpicsm.ws.data.StorageSystemOverviewResult; import com.hp.asi.ui.hpicsm.ws.data.StorageSystemOverviewWSImpl; public class StorageSystemOverviewDataAdapter extends BaseStorageSystemDataAdapter<StorageSystemOverviewResult, StorageSystemOverviewModel> { /** This is the address of the service. **/ private static final String SERVICE_NAME = "services/swd/storagesystemoverview"; public StorageSystemOverviewDataAdapter (String storageSystemUid) { super(StorageSystemOverviewResult.class, storageSystemUid); } @Override public StorageSystemOverviewModel formatData (StorageSystemOverviewResult rawData) { StorageSystemOverviewModel summaryModel = new StorageSystemOverviewModel(); if (null != rawData.getErrorMessage() && !rawData.getErrorMessage().equals("")) { log.info("StorageSystemOverviewResult had an error message. " + "Returning a StorageSystemOverviewModel with an error message"); summaryModel.errorMessage = rawData.getErrorMessage(); } else if (null == rawData.getResult()) { log.info("StorageSystemOverviewResult has a null result. " + "Returning a StorageSystemOverviewModel with an information message"); summaryModel.informationMessage = this.i18nProvider.getInternationalString (locale, I18NProvider.Info_NotAvailable); } else { populateSummaryModel(summaryModel, rawData.getResult()); } return summaryModel; } @Override public StorageSystemOverviewModel getEmptyModel () { return new StorageSystemOverviewModel(); } @Override public String getServiceName () { return SERVICE_NAME; } private void populateSummaryModel (StorageSystemOverviewModel summaryModel, final StorageSystemOverviewWSImpl result) { if (mostDataFieldsAreNull(result)) { summaryModel.errorMessage = this.i18nProvider.getInternationalString (locale, I18NProvider.Info_NotAvailable); } else { StorageTypeEnum typeEnum = StorageTypeEnum.getStorageTypeEnum(result.getStorageSystemType()); summaryModel.storageType = result.getStorageSystemType(); summaryModel.summaryDetails = createListData(typeEnum, result); summaryModel.storageSystemOverview = createOverview(typeEnum, result); summaryModel.volumesOverProvisioned = result.getOverProvisionedVolumes(); summaryModel.volumesProvisioned = result.getTotalVolumes(); summaryModel.volumesThinProvisioned = result.getThinProvisionedVolumes(); } } private boolean mostDataFieldsAreNull (StorageSystemOverviewWSImpl result) { int score = 0; boolean mostLikelyArrayError = false; if (!isValidData(result.getDisplayName())) { score++; } if (!isValidData(result.getFirmwareVersion())) { score++; } if (result.getTotalCapacity() <= 0) { score++; } if (score >= 2 ) { mostLikelyArrayError = true; } return mostLikelyArrayError; } private LabelValueListModel createListData(final StorageTypeEnum type, final StorageSystemOverviewWSImpl result) { switch (type) { case HP_STOREONCE: return createStoreOnceListData(result); case HP_3PAR: return create3ParListData(result); case HP_LEFTHAND: return createLefthandListData(result); default: return createGenericListData(result); } } private LabelValueListModel createStoreOnceListData(final StorageSystemOverviewWSImpl result) { String model = I18NStorageProvider.getInstance().getInternationalString (locale, I18NStorageProvider.DAM_SSO_MODEL); String systemId = I18NStorageProvider.getInstance().getInternationalString (locale, I18NStorageProvider.DAM_SSO_SYSTEM_ID); String mgmtGroup = I18NStorageProvider.getInstance().getInternationalString (locale, I18NStorageProvider.DAM_SSO_MANAGEMENT_GROUP); String firmware = I18NStorageProvider.getInstance().getInternationalString (locale, I18NStorageProvider.DAM_SSO_FIRMWARE); LabelValueListModel list = new LabelValueListModel(); list.addLabelValuePair(model, result.getStorageSystemModel()); list.addLabelValuePair(systemId, result.getStorageSystemUID()); list.addLabelValuePair(mgmtGroup, printList(result.getManagementGroup())); list.addLabelValuePair(firmware, result.getFirmwareVersion()); return list; } private LabelValueListModel create3ParListData (StorageSystemOverviewWSImpl result) { String model = I18NStorageProvider.getInstance().getInternationalString (locale, I18NStorageProvider.DAM_SSO_MODEL); String serialNumber = I18NStorageProvider.getInstance().getInternationalString (locale, I18NStorageProvider.DAM_SSO_SERIAL_NUMBER); String systemId = I18NStorageProvider.getInstance().getInternationalString (locale, I18NStorageProvider.DAM_SSO_SYSTEM_ID); String systemWwn = I18NStorageProvider.getInstance().getInternationalString (locale, I18NStorageProvider.DAM_SSO_SYSTEM_WWN); String firmware = I18NStorageProvider.getInstance().getInternationalString (locale, I18NStorageProvider.DAM_SSO_FIRMWARE); LabelValueListModel list = new LabelValueListModel(); list.addLabelValuePair(model, result.getStorageSystemModel()); list.addLabelValuePair(serialNumber, result.getSerialNumber()); list.addLabelValuePair(systemId, result.getSystemId()); list.addLabelValuePair(systemWwn, result.getStorageSystemUID()); list.addLabelValuePair(firmware, result.getFirmwareVersion()); return list; } private LabelValueListModel createLefthandListData (StorageSystemOverviewWSImpl result) { String model = I18NStorageProvider.getInstance().getInternationalString (locale, I18NStorageProvider.DAM_SSO_MODEL); String systemId = I18NStorageProvider.getInstance().getInternationalString (locale, I18NStorageProvider.DAM_SSO_SYSTEM_ID); String firmware = I18NStorageProvider.getInstance().getInternationalString (locale, I18NStorageProvider.DAM_SSO_FIRMWARE); LabelValueListModel list = new LabelValueListModel(); list.addLabelValuePair(model, result.getStorageSystemModel()); list.addLabelValuePair(systemId, result.getStorageSystemUID()); list.addLabelValuePair(firmware, result.getFirmwareVersion()); return list; } private LabelValueListModel createGenericListData (StorageSystemOverviewWSImpl result) { String model = I18NStorageProvider.getInstance().getInternationalString (locale, I18NStorageProvider.DAM_SSO_MODEL); String systemId = I18NStorageProvider.getInstance().getInternationalString (locale, I18NStorageProvider.DAM_SSO_SYSTEM_ID); String mgmtGroup = I18NStorageProvider.getInstance().getInternationalString (locale, I18NStorageProvider.DAM_SSO_MANAGEMENT_GROUP); String firmware = I18NStorageProvider.getInstance().getInternationalString (locale, I18NStorageProvider.DAM_SSO_FIRMWARE); LabelValueListModel list = new LabelValueListModel(); list.addLabelValuePair(model, result.getStorageSystemModel()); list.addLabelValuePair(systemId, result.getStorageSystemUID()); list.addLabelValuePair(mgmtGroup, printList(result.getManagementGroup())); list.addLabelValuePair(firmware, result.getFirmwareVersion()); return list; } private SummaryPortletModel createOverview (final StorageTypeEnum type, final StorageSystemOverviewWSImpl result) { if (type == StorageTypeEnum.HP_STOREONCE) { return null; } SummaryPortletModel portletModel = new SummaryPortletModel(); String provisioned = I18NStorageProvider.getInstance().getInternationalString (locale, I18NStorageProvider.DAM_SSO_PROVISIONED); String used = I18NStorageProvider.getInstance().getInternationalString (locale, I18NStorageProvider.DAM_SSO_USED); String thinProvisioned = I18NStorageProvider.getInstance().getInternationalString (locale, I18NStorageProvider.DAM_SSO_THIN_PROVISIONED); String usedThinProvisioned = I18NStorageProvider.getInstance().getInternationalString (locale, I18NStorageProvider.DAM_SSO_USED_THIN_PROVISIONED); String savings = I18NStorageProvider.getInstance().getInternationalString (locale, I18NStorageProvider.DAM_SSO_SAVINGS); portletModel.pieChartData = createPieChartModel(result.getUsedCapacity(), result.getTotalCapacity()); LabelValueListModel overviewList = new LabelValueListModel(); overviewList.addLabelValuePair(provisioned, result.getFormattedTotalCapacity()); overviewList.addLabelValuePair(used, result.getFormattedUsedCapacity()); overviewList.addLabelValuePair(thinProvisioned, result.getFormattedTotalThinCapacity()); overviewList.addLabelValuePair(usedThinProvisioned, result.getFormattedUsedThinCapacity()); overviewList.addLabelValuePair(savings, result.getFormattedThinProvisioningSavings()); portletModel.fieldData = overviewList; return portletModel; } private PieChartModel createPieChartModel(final long amtUsed, final long amtTotal) { PieChartModel pieChartData = new PieChartModel(); if (amtUsed < amtTotal) { pieChartData.percentUsed = ((int) ( ((double) amtUsed / (double) amtTotal) * 100.0)); pieChartData.percentFree = 100 - pieChartData.percentUsed; } else { pieChartData.percentUsed = 100; } return pieChartData; } }
9234a8cd1eeffb50d0fbb3ada909ef1a77a9cf50
19,569
java
Java
kernel/com.onboard.service.activity.impl/src/main/java/com/onboard/service/activity/impl/ActivityServiceImpl.java
sercxtyf/onboard
98706fd02a9f181c79ab195f8f2e00571402a6d7
[ "Apache-2.0" ]
136
2015-09-18T15:18:42.000Z
2022-03-27T11:09:34.000Z
kernel/com.onboard.service.activity.impl/src/main/java/com/onboard/service/activity/impl/ActivityServiceImpl.java
sercxtyf/onboard
98706fd02a9f181c79ab195f8f2e00571402a6d7
[ "Apache-2.0" ]
2
2016-07-01T09:57:28.000Z
2018-10-16T06:01:24.000Z
kernel/com.onboard.service.activity.impl/src/main/java/com/onboard/service/activity/impl/ActivityServiceImpl.java
sercxtyf/onboard
98706fd02a9f181c79ab195f8f2e00571402a6d7
[ "Apache-2.0" ]
93
2015-09-18T15:50:25.000Z
2021-12-25T06:46:18.000Z
36.105166
129
0.674332
997,004
/******************************************************************************* * Copyright [2015] [Onboard team of SERC, Peking University] * * 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.onboard.service.activity.impl; import java.util.ArrayList; import java.util.Comparator; import java.util.Date; import java.util.List; import java.util.Map; import java.util.TreeMap; import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.onboard.domain.mapper.ActivityMapper; import com.onboard.domain.mapper.NotificationMapper; import com.onboard.domain.mapper.ProjectMapper; import com.onboard.domain.mapper.UserProjectMapper; import com.onboard.domain.mapper.model.ActivityExample; import com.onboard.domain.mapper.model.NotificationExample; import com.onboard.domain.mapper.model.UserProjectExample; import com.onboard.domain.model.Activity; import com.onboard.domain.model.Notification; import com.onboard.domain.model.Project; import com.onboard.domain.model.Todo; import com.onboard.domain.model.User; import com.onboard.domain.model.UserProject; import com.onboard.service.account.UserService; import com.onboard.service.activity.ActivityActionType; import com.onboard.service.activity.ActivityService; import com.onboard.service.web.SessionService; /** * {@link ActivityService}接口实现 * * @author yewei * */ @Transactional @Service("activityServiceBean") public class ActivityServiceImpl implements ActivityService { @Autowired private ActivityMapper activityMapper; @Autowired private ProjectMapper projectMapper; @Autowired private UserProjectMapper userProjectMapper; @Autowired private NotificationMapper notificationMapper; @Autowired private SessionService session; @Autowired private UserService userService; private void addProjectConstraint(ActivityExample example, List<Integer> projectList) { if (projectList != null) { example.getOredCriteria().get(0).andProjectIdIn(projectList); } } /** * 获取截止到某个时间的活动,该活动属于用户参与的一组项目 * * @param activity * 与activity具有相同属性的活动才会被选取 * @param endTime * 截止时间 * @param limit * 分页参数,最终取出来的活动数可能大于limit,取的原则是一旦某天的一些活动被取出来,则会将改天所有活动取出 * @param projectList * 项目集合 * @return */ private List<Activity> getActivitiesTillDay(Activity activity, Date endTime, int limit, List<Integer> projectList) { if (projectList != null && projectList.isEmpty()) { return new ArrayList<Activity>(); } ActivityExample example = new ActivityExample(activity); example.setLimit(0, limit); example.setOrderByClause("id desc"); example.getOredCriteria().get(0).andCreatedLessThan(endTime); addProjectConstraint(example, projectList); List<Activity> activities = activityMapper.selectByExample(example); if (activities.size() == limit) { Activity end = activities.get(limit - 1); Date startTime = new DateTime(end.getCreated()).withTimeAtStartOfDay().toDate(); example = new ActivityExample(activity); example.setOrderByClause("id desc"); example.getOredCriteria().get(0).andCreatedGreaterThanOrEqualTo(startTime).andIdLessThan(end.getId()); addProjectConstraint(example, projectList); activities.addAll(activityMapper.selectByExample(example)); } return activities; } /** * 创建一个按id降序排列,设置好分页的example * * @param activity * @param start * @param limit * @return */ private ActivityExample buildBasicExample(Activity activity, int start, int limit) { ActivityExample activityExample = new ActivityExample(activity); activityExample.setLimit(start, limit); activityExample.setOrderByClause("id desc"); return activityExample; } private TreeMap<Date, List<Activity>> groupActivitiesByDate(List<Activity> activities) { TreeMap<Date, List<Activity>> map = new TreeMap<Date, List<Activity>>(new Comparator<Date>() { @Override public int compare(Date o1, Date o2) { return o2.compareTo(o1); } }); for (Activity ac : activities) { Date d = new DateTime(ac.getCreated()).withTimeAtStartOfDay().toDate(); if (!map.containsKey(d)) { List<Activity> list = new ArrayList<Activity>(); list.add(ac); map.put(d, list); } else { map.get(d).add(ac); } } return map; } private List<Integer> getProjectIdListByUserByCompany(int userId, int companyId, int start, int limit) { List<Integer> projects = new ArrayList<Integer>(); UserProject userProject = new UserProject(); userProject.setUserId(userId); userProject.setCompanyId(companyId); UserProjectExample example = new UserProjectExample(userProject); example.setLimit(start, limit); List<UserProject> userProjectList = userProjectMapper.selectByExample(example); for (UserProject up : userProjectList) { Project project = new Project(projectMapper.selectByPrimaryKey(up.getProjectId())); if (project.getDeleted() == false) { projects.add(project.getId()); } } return projects; } @Override public Activity create(Activity activity) { activityMapper.insertSelective(activity); return activity; } @Override public Activity update(Activity activity) { activityMapper.updateByPrimaryKey(activity); return activity; } @Override public void delete(int id) { Notification sample = new Notification(); sample.setActivityId(id); notificationMapper.deleteByExample(new NotificationExample(sample)); activityMapper.deleteByPrimaryKey(id); } @Override public Activity getById(int id) { return activityMapper.selectByPrimaryKey(id); } @Override public List<Activity> getByProject(int projectId, int start, int limit) { Activity activity = new Activity(); activity.setProjectId(projectId); ActivityExample activityExample = buildBasicExample(activity, start, limit); return activityMapper.selectByExample(activityExample); } @Override public List<Activity> getByProjectTillDay(int projectId, Date endTime, int limit) { Activity activity = new Activity(); activity.setProjectId(projectId); return getActivitiesTillDay(activity, endTime, limit, null); } @Override public List<Activity> getByCompany(int companyId, int start, int limit) { Activity activity = new Activity(); activity.setCompanyId(companyId); ActivityExample activityExample = buildBasicExample(activity, start, limit); return activityMapper.selectByExample(activityExample); } @Override public List<Activity> getByCompanyTillDay(int companyId, Date endTime, int limit) { Activity activity = new Activity(); activity.setCompanyId(companyId); return getActivitiesTillDay(activity, endTime, limit, null); } @Override public List<Activity> getLatestByUser(int companyId, int userId, int limit, List<Integer> projectList) { Activity activity = new Activity(); activity.setCreatorId(userId); return getLatestByBySampleCompanyByPage(activity, companyId, 0, limit, projectList); } @Override public List<Activity> getLatestByUserByPage(int companyId, int userId, int start, int limit, List<Integer> projectList) { if (projectList != null && projectList.isEmpty()) { return new ArrayList<Activity>(); } Activity sample = new Activity(); sample.setCreatorId(userId); sample.setCompanyId(companyId); ActivityExample example = buildBasicExample(sample, start, limit); addProjectConstraint(example, projectList); return activityMapper.selectByExample(example); } private List<Activity> appendActivitiesOfLastDay(List<Activity> activities, ActivityExample example) { if (activities != null && !activities.isEmpty()) { Activity lastActivity = activities.get(activities.size() - 1); Date since = new DateTime(lastActivity.getCreated()).withTimeAtStartOfDay().toDate(); example.getOredCriteria().get(0).andCreatedGreaterThanOrEqualTo(since).andCreatedLessThan(lastActivity.getCreated()); activities.addAll(activityMapper.selectByExample(example)); } return activities; } @Override public List<Activity> getByUserGroupByDateReturnList(int companyId, int userId, int limit, List<Integer> projectList, Date until) { if (projectList != null && projectList.isEmpty()) { return new ArrayList<Activity>(); } Activity sample = new Activity(); sample.setCreatorId(userId); sample.setCompanyId(companyId); ActivityExample example = new ActivityExample(sample); addProjectConstraint(example, projectList); example.getOredCriteria().get(0).andCreatedLessThanOrEqualTo(until); example.setLimit(limit); example.setOrderByClause("id desc"); List<Activity> originActivities = activityMapper.selectByExample(example); if (originActivities == null || originActivities.isEmpty()) { return new ArrayList<Activity>(); } // 将最后一天剩余的所有activity都取出来,最终activity的数目可能大于limit List<Activity> activities = appendActivitiesOfLastDay(originActivities, example); return activities; } @Override public TreeMap<Date, List<Activity>> getByUserGroupByDate(int companyId, int userId, int limit, List<Integer> projectList, Date until) { List<Activity> activities = this.getByUserGroupByDateReturnList(companyId, userId, limit, projectList, until); return groupActivitiesByDate(activities); } @Override public List<Activity> getUserVisibleTillDay(int companyId, Integer filterUserId, Integer filterProjectId, Date endTime, String filterType, int limit) { Activity sample = new Activity(); if (filterProjectId != null) { sample.setProjectId(filterProjectId); } if (filterUserId != null) { sample.setCreatorId(filterUserId); } if (filterType != null) { sample.setAttachType(filterType); } return this.getUserVisibleBySampleTillDay(companyId, sample, endTime, limit); } @Override public List<Activity> getUserVisibleBySampleTillDay(int companyId, Activity sample, Date endTime, int limit) { if (sample == null) { return new ArrayList<Activity>(); } sample.setCompanyId(companyId); List<Integer> projectList = getProjectIdListByUserByCompany(session.getCurrentUser().getId(), companyId, 0, -1); return getActivitiesTillDay(sample, endTime, limit, projectList); } @Override public List<Activity> getByTodo(int todoId, int start, int limit) { Activity activity = new Activity(); activity.setAttachId(todoId); activity.setAttachType(new Todo().getType()); ActivityExample activityExample = buildBasicExample(activity, start, limit); // TODO hard-coding of subject, subject should be moved to config files activityExample.getOredCriteria().get(0).andActionNotEqualTo(ActivityActionType.REPLY); return activityMapper.selectByExample(activityExample); } @Override public List<Activity> getByProjectByDate(int projectId, Date date) { Activity sample = new Activity(); sample.setProjectId(projectId); ActivityExample example = new ActivityExample(sample); DateTime dt = new DateTime(date); Date start = dt.withTimeAtStartOfDay().toDate(); Date end = dt.plusDays(1).toDate(); example.getOredCriteria().get(0).andCreatedGreaterThanOrEqualTo(start).andCreatedLessThan(end); return activityMapper.selectByExample(example); } @Override public List<Activity> getByAttachTypeAndId(String type, int id) { Activity activity = new Activity(); activity.setAttachId(id); activity.setAttachType(type); ActivityExample example = new ActivityExample(activity); example.setOrderByClause("id desc"); return activityMapper.selectByExample(example); } @Override public List<Activity> getLatestByBySampleCompanyByPage(Activity sample, int companyId, int start, int limit, List<Integer> projectList) { if (projectList != null && projectList.isEmpty()) { return new ArrayList<Activity>(); } sample.setCompanyId(companyId); ActivityExample example = buildBasicExample(sample, start, limit); addProjectConstraint(example, projectList); return activityMapper.selectByExample(example); } @Override public List<Activity> getByActivityExample(ActivityExample example) { return activityMapper.selectByExample(example); } @Override public void deleteByAttachTypeAndId(String type, int id) { Activity deletingActivity = new Activity(); deletingActivity.setAttachType(type); deletingActivity.setAttachId(id); List<Activity> activities = activityMapper.selectByExample(new ActivityExample(deletingActivity)); for (Activity activity : activities) { this.delete(activity.getId()); } } @Override public List<Activity> getLatestByUserSince(int companyId, int userId, List<Integer> projectList, Date since) { Activity sample = new Activity(); sample.setCreatorId(userId); sample.setCompanyId(companyId); ActivityExample example = new ActivityExample(sample); addProjectConstraint(example, projectList); example.getOredCriteria().get(0).andCreatedGreaterThanOrEqualTo(since); example.setOrderByClause("created desc"); List<Activity> originActivities = activityMapper.selectByExample(example); return originActivities; } @Override public List<Activity> getByProjectBetweenDates(int projectId, Date start, Date end) { Activity sample = new Activity(); sample.setProjectId(projectId); ActivityExample example = new ActivityExample(sample); DateTime dt = new DateTime(start); start = dt.withTimeAtStartOfDay().toDate(); dt = new DateTime(end); end = dt.withTimeAtStartOfDay().plusDays(1).toDate(); example.getOredCriteria().get(0).andCreatedGreaterThanOrEqualTo(start).andCreatedLessThan(end); example.setOrderByClause("id desc"); return activityMapper.selectByExample(example); } @Override public List<Activity> getByProjectUserBetweenDates(int projectId, int userId, Date start, Date end) { Activity sample = new Activity(); sample.setProjectId(projectId); sample.setCreatorId(userId); ActivityExample example = new ActivityExample(sample); DateTime dt = new DateTime(start); start = dt.withTimeAtStartOfDay().toDate(); dt = new DateTime(end); end = dt.withTimeAtStartOfDay().plusDays(1).toDate(); example.getOredCriteria().get(0).andCreatedGreaterThanOrEqualTo(start).andCreatedLessThan(end); example.setOrderByClause("id desc"); return activityMapper.selectByExample(example); } private Integer getCountByCompanyUserBetweenDates(int companyId, int userId, Date start, Date end) { Activity sample = new Activity(); sample.setCompanyId(companyId); sample.setCreatorId(userId); ActivityExample example = new ActivityExample(sample); DateTime dt = new DateTime(start); start = dt.withTimeAtStartOfDay().toDate(); dt = new DateTime(end); end = dt.withTimeAtStartOfDay().plusDays(1).toDate(); example.getOredCriteria().get(0).andCreatedGreaterThanOrEqualTo(start).andCreatedLessThan(end); example.setOrderByClause("id desc"); return activityMapper.countByExample(example); } @Override public Map<Integer, Integer> getActivityCountForUsers(Integer companyId, Date since, Date until) { List<User> companyUsers = userService.getUserByCompanyId(companyId); Map<Integer, Integer> activityCountMap = Maps.newHashMap(); for (User user : companyUsers) { activityCountMap.put(user.getId(), getCountByCompanyUserBetweenDates(companyId, user.getId(), since, until)); } return activityCountMap; } @Override public List<Map<String, ?>> getActivityCountForUsersGroupByDate(Integer companyId, Date since, Date until) { List<User> companyUsers = userService.getUserByCompanyId(companyId); List<Map<String, ?>> result = Lists.newArrayList(); Map<Integer, Integer> activityCountMap; DateTime dt = new DateTime(since); dt = dt.withTimeAtStartOfDay(); DateTime end = new DateTime(until); end = end.withTimeAtStartOfDay().plusDays(1).minusMinutes(1); while (dt.toDate().before(end.toDate())) { activityCountMap = Maps.newHashMap(); for (User user : companyUsers) { activityCountMap.put(user.getId(), getCountByCompanyUserBetweenDates(companyId, user.getId(), dt.toDate(), dt.toDate())); } result.add(ImmutableMap.of("time", dt.toDate().getTime(), "counts", activityCountMap)); dt = dt.plusDays(1); } return result; } @Override public List<Activity> getActivitiesByCompanyAndDates(Integer companyId, Date since, Date until) { Activity activity = new Activity(); activity.setCompanyId(companyId); ActivityExample example = new ActivityExample(activity); DateTime dt = new DateTime(since); since = dt.withTimeAtStartOfDay().toDate(); dt = new DateTime(until); until = dt.withTimeAtStartOfDay().plusDays(1).toDate(); example.getOredCriteria().get(0).andCreatedGreaterThanOrEqualTo(since).andCreatedLessThan(until); example.setOrderByClause("id desc"); return activityMapper.selectByExample(example); } }
9234a8d4592049d6294d51c5621bbf2e907db096
1,391
java
Java
src/de/cpgaertner/edu/inf/games/datacenter/command/talk/data/Insults.java
ChristianGaertner/TextAdventure
2d4f47e112452a18e29b81390d322aca895137a9
[ "MIT" ]
null
null
null
src/de/cpgaertner/edu/inf/games/datacenter/command/talk/data/Insults.java
ChristianGaertner/TextAdventure
2d4f47e112452a18e29b81390d322aca895137a9
[ "MIT" ]
null
null
null
src/de/cpgaertner/edu/inf/games/datacenter/command/talk/data/Insults.java
ChristianGaertner/TextAdventure
2d4f47e112452a18e29b81390d322aca895137a9
[ "MIT" ]
null
null
null
23.183333
65
0.519051
997,005
package de.cpgaertner.edu.inf.games.datacenter.command.talk.data; import lombok.Getter; import java.util.ArrayList; import java.util.List; public class Insults extends RandomString { @Getter protected static List<String> sData; @Getter protected List<String> data; static { sData = new ArrayList<>(); sData.add("stupid"); sData.add("ass"); sData.add("idiot"); sData.add("dumb"); sData.add("silly"); sData.add("bimbo"); sData.add("bugger"); sData.add("dag"); sData.add("dago"); sData.add("dickhead"); sData.add("donkey"); sData.add("dope"); sData.add("dork"); sData.add("flake"); sData.add("freak"); sData.add("gasbag"); sData.add("git"); sData.add("jerk"); sData.add("lardass"); sData.add("louse"); sData.add("nerd"); sData.add("nut"); sData.add("nutter"); sData.add("pig"); sData.add("prat"); sData.add("rat"); sData.add("redneck"); sData.add("scum"); sData.add("scumbag"); sData.add("arse"); sData.add("toff"); sData.add("tool"); sData.add("twit"); sData.add("wanker"); sData.add("wimp"); sData.add("zero"); } public Insults() { this.data = sData; } }
9234a8efae50a6dd2699b279ad1b7b425580d92f
6,758
java
Java
src/main/java/de/kosit/validationtool/impl/ScenarioRepository.java
rkottmann/validator
1e33b2b1126ac4f714e138f7e9f8421a28e2f7a0
[ "Apache-2.0" ]
null
null
null
src/main/java/de/kosit/validationtool/impl/ScenarioRepository.java
rkottmann/validator
1e33b2b1126ac4f714e138f7e9f8421a28e2f7a0
[ "Apache-2.0" ]
null
null
null
src/main/java/de/kosit/validationtool/impl/ScenarioRepository.java
rkottmann/validator
1e33b2b1126ac4f714e138f7e9f8421a28e2f7a0
[ "Apache-2.0" ]
null
null
null
38.83908
137
0.692661
997,006
/* * Licensed to the Koordinierungsstelle für IT-Standards (KoSIT) under * one or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. KoSIT 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 de.kosit.validationtool.impl; import java.net.MalformedURLException; import java.net.URI; import java.util.List; import java.util.stream.Collectors; import javax.xml.transform.dom.DOMSource; import org.w3c.dom.Document; import org.w3c.dom.Element; import lombok.AccessLevel; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import de.kosit.validationtool.api.CheckConfiguration; import de.kosit.validationtool.api.InputFactory; import de.kosit.validationtool.impl.model.Result; import de.kosit.validationtool.impl.tasks.DocumentParseAction; import de.kosit.validationtool.model.reportInput.XMLSyntaxError; import de.kosit.validationtool.model.scenarios.ScenarioType; import de.kosit.validationtool.model.scenarios.Scenarios; import net.sf.saxon.s9api.*; /** * Repository for die aktiven Szenario einer Prüfinstanz. * * @author Andreas Penski */ @Slf4j @RequiredArgsConstructor public class ScenarioRepository { private static final String SUPPORTED_MAJOR_VERSION = "1"; private static final String SUPPORTED_MAJOR_VERSION_SCHEMA = "http://www.xoev.de/de/validator/framework/1/scenarios"; @Getter(value = AccessLevel.PRIVATE) private final Processor processor; @Getter(value = AccessLevel.PRIVATE) private final ContentRepository repository; private XsltExecutable noScenarioReport; @Getter(value = AccessLevel.PACKAGE) private Scenarios scenarios; private static boolean isSupportedDocument(Document doc) { final Element root = doc.getDocumentElement(); return root.hasAttribute("frameworkVersion") && root.getAttribute("frameworkVersion").startsWith(SUPPORTED_MAJOR_VERSION) && doc.getDocumentElement().getNamespaceURI().equals(SUPPORTED_MAJOR_VERSION_SCHEMA); } private static void checkVersion(URI scenarioDefinition) { DocumentParseAction p = new DocumentParseAction(); try { final Result<Document, XMLSyntaxError> result = p.parseDocument(InputFactory.read(scenarioDefinition.toURL())); if (result.isValid() && !isSupportedDocument(result.getObject())) { throw new IllegalStateException(String.format( "Specified scenario configuration %s is not supported.%nThis version only supports definitions of '%s'", scenarioDefinition, SUPPORTED_MAJOR_VERSION_SCHEMA)); } } catch (MalformedURLException e) { throw new IllegalStateException("Error reading definition file"); } } public XsltExecutable getNoScenarioReport() { if (noScenarioReport == null) { noScenarioReport = repository.loadXsltScript(URI.create(scenarios.getNoScenarioReport().getResource().getLocation())); } return noScenarioReport; } /** * Initialisiert das Repository mit der angegebenen Konfiguration. * * @param config die Konfiguration */ public void initialize(CheckConfiguration config) { ConversionService conversionService = new ConversionService(); checkVersion(config.getScenarioDefinition()); log.info("Loading scenarios from {}", config.getScenarioDefinition()); CollectingErrorEventHandler handler = new CollectingErrorEventHandler(); this.scenarios = conversionService.readXml(config.getScenarioDefinition(), Scenarios.class, repository.getScenarioSchema(), handler); if (!handler.hasErrors()) { log.info("Loaded scenarios for {} by {} from {}. The following scenarios are available:\n\n{}", scenarios.getName(), scenarios.getAuthor(), scenarios.getDate(), summarizeScenarios()); log.info("Loading scenario content from {}", config.getScenarioRepository()); getScenarios().getScenario().forEach(s -> s.initialize(repository, false)); } else { throw new IllegalStateException(String.format("Can not load scenarios from %s due to %s", config.getScenarioDefinition(), handler.getErrorDescription())); } // initialize fallback report eager getNoScenarioReport(); } private String summarizeScenarios() { StringBuilder b = new StringBuilder(); scenarios.getScenario().forEach(s -> { b.append(s.getName()); b.append("\n"); }); return b.toString(); } /** * Ermittelt für das angegebene Dokument das passende Szenario. * * @param document das Eingabedokument * @return ein Ergebnis-Objekt zur weiteren Verarbeitung */ public Result<ScenarioType, String> selectScenario(Document document) { Result<ScenarioType, String> result = new Result<>(); final List<ScenarioType> collect = scenarios.getScenario().stream().filter(s -> match(document, s)).collect(Collectors.toList()); if (collect.size() == 1) { result = new Result<>(collect.get(0)); } else if (collect.isEmpty()) { result.getErrors().add("None of the loaded scenarios matches the specified document"); } else { result.getErrors().add("More than on scenario matches the specified document"); } return result; } private boolean match(Document document, ScenarioType scenario) { try { final XPathSelector selector = scenario.getSelector(); DocumentBuilder documentBuilder = getProcessor().newDocumentBuilder(); final XdmNode xdmSource = documentBuilder.build(new DOMSource(document)); selector.setContextItem(xdmSource); return selector.effectiveBooleanValue(); } catch (SaxonApiException e) { log.error("Error evaluating xpath expression", e); } return false; } void initialize(Scenarios def) { this.scenarios = def; } }
9234a9b5358116613587f9b08708258ad1fdcbe7
1,090
java
Java
modules/base/analysis-api/src/main/java/com/intellij/codeInspection/InspectionToolsFactory.java
MC-JY/consulo
ebd31008fcfd03e144b46a9408d2842d0b06ffc8
[ "Apache-2.0" ]
634
2015-01-01T19:14:25.000Z
2022-03-22T11:42:50.000Z
modules/base/analysis-api/src/main/java/com/intellij/codeInspection/InspectionToolsFactory.java
MC-JY/consulo
ebd31008fcfd03e144b46a9408d2842d0b06ffc8
[ "Apache-2.0" ]
410
2015-01-19T09:57:51.000Z
2022-03-22T16:24:59.000Z
modules/base/analysis-api/src/main/java/com/intellij/codeInspection/InspectionToolsFactory.java
MC-JY/consulo
ebd31008fcfd03e144b46a9408d2842d0b06ffc8
[ "Apache-2.0" ]
50
2015-03-10T04:14:49.000Z
2022-03-22T07:08:45.000Z
31.142857
133
0.761468
997,007
/* * Copyright 2000-2009 JetBrains s.r.o. * * 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. */ /* * User: anna * Date: 28-May-2009 */ package com.intellij.codeInspection; import com.intellij.openapi.extensions.ExtensionPointName; /** * This will be removed in future versions. * Please use {@link InspectionEP} for inspection registration */ @Deprecated public interface InspectionToolsFactory { ExtensionPointName<InspectionToolsFactory> EXTENSION_POINT_NAME = ExtensionPointName.create("com.intellij.inspectionToolsFactory"); InspectionProfileEntry[] createTools(); }
9234abc59446b82ed94218008fc0b2e889f0a79b
5,663
java
Java
wava-core/src/main/java/org/brutusin/wava/main/peer/GroupMain.java
brutusin/linux-scheduler
73103ecf5846a40ccfd2905fa2437aab81b5b718
[ "Apache-2.0" ]
11
2016-11-02T17:34:20.000Z
2020-05-13T13:45:44.000Z
wava-core/src/main/java/org/brutusin/wava/main/peer/GroupMain.java
brutusin/linux-scheduler
73103ecf5846a40ccfd2905fa2437aab81b5b718
[ "Apache-2.0" ]
17
2016-10-17T00:00:09.000Z
2019-04-04T10:47:13.000Z
wava-core/src/main/java/org/brutusin/wava/main/peer/GroupMain.java
brutusin/linux-scheduler
73103ecf5846a40ccfd2905fa2437aab81b5b718
[ "Apache-2.0" ]
3
2017-06-20T19:47:10.000Z
2019-04-11T07:35:06.000Z
39.657343
192
0.535003
997,008
/* * Copyright 2016 Ignacio del Valle Alles nnheo@example.com. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.brutusin.wava.main.peer; import java.io.File; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.DefaultParser; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.brutusin.wava.core.io.CommandLineRequestExecutor; import org.brutusin.wava.utils.CoreUtils; import org.brutusin.wava.io.OpName; import org.brutusin.wava.input.GroupInput; import org.brutusin.wava.io.RetCode; /** * * @author Ignacio del Valle Alles nnheo@example.com */ public class GroupMain { public static final String DESCRIPTION = "group management commands"; private static void showHelp(Options options) { CoreUtils.showHelp(options, "wava -g [options]\n" + DESCRIPTION); } private static GroupInput getRequest(String[] args) { Options options = new Options(); Option nOpt = Option.builder("n") .longOpt("name") .argName("group name") .desc("name of the group to be created or updated.") .hasArg() .build(); Option dOpt = Option.builder("d") .longOpt("delete") .desc("deletes an existing empty group") .build(); Option lOpt = Option.builder("l") .longOpt("list") .desc("list existing groups") .build(); Option hOpt = Option.builder("h") .longOpt("no-headers") .desc("do not output headers") .build(); Option pOpt = Option.builder("p") .longOpt("priority") .argName("integer") .desc("priority") .hasArg() .build(); Option tOpt = Option.builder("t") .longOpt("idle") .argName("integer") .desc("time to idle. Elapsed time since the last executing job of the group finishes and the group is deleted. Default is -1, meaning that the group to be created is eternal") .hasArg() .build(); Option sOpt = Option.builder("s") .longOpt("stats-folder") .argName("file") .hasArg() .desc("folder to save group stats logs. If null, no logging is performed") .build(); options.addOption(dOpt); options.addOption(nOpt); options.addOption(pOpt); options.addOption(tOpt); options.addOption(lOpt); options.addOption(hOpt); options.addOption(sOpt); try { CommandLineParser parser = new DefaultParser(); CommandLine cl = parser.parse(options, args); GroupInput gi = new GroupInput(); if (cl.hasOption(nOpt.getOpt())) { gi.setGroupName(cl.getOptionValue(nOpt.getOpt())); if (cl.hasOption(dOpt.getOpt())) { gi.setDelete(true); } else { if (cl.hasOption(pOpt.getOpt())) { try { gi.setPriority(Integer.valueOf(cl.getOptionValue(pOpt.getOpt()))); } catch (NumberFormatException ex) { throw new ParseException("Invalid " + pOpt.getOpt() + " value"); } } if (cl.hasOption(tOpt.getOpt())) { try { gi.setTimetoIdleSeconds(Integer.valueOf(cl.getOptionValue(tOpt.getOpt()))); } catch (NumberFormatException ex) { throw new ParseException("Invalid " + tOpt.getOpt() + " value"); } } if (cl.hasOption(sOpt.getOpt())) { gi.setStatsDirectory(new File(cl.getOptionValue(sOpt.getOpt()))); } } } else if (cl.hasOption(lOpt.getOpt())) { gi.setList(true); if (cl.hasOption(hOpt.getOpt())) { gi.setNoHeaders(true); } } else { showHelp(options); return null; } return gi; } catch (ParseException exp) { System.err.println("Parsing failed. Reason: " + exp.getMessage() + "\n"); showHelp(options); return null; } } public static void main(String[] args) throws Exception { CoreUtils.validateCoreRunning(); GroupInput gi = getRequest(args); if (gi == null) { System.exit(RetCode.ERROR.getCode()); } System.exit(new CommandLineRequestExecutor().executeRequest(OpName.group, gi)); } }
9234abffcc8e44d48ef52f673240d3ab83bd592f
7,557
java
Java
Project3/QHT.java
alken2/COP3530
e836eef3f195641504b574341183fa3e9153b03e
[ "MIT" ]
null
null
null
Project3/QHT.java
alken2/COP3530
e836eef3f195641504b574341183fa3e9153b03e
[ "MIT" ]
null
null
null
Project3/QHT.java
alken2/COP3530
e836eef3f195641504b574341183fa3e9153b03e
[ "MIT" ]
null
null
null
27.48
106
0.416567
997,009
public class QHT<K, V> { public static class KVPair<K, V> { /* Generic key-value pair class */ K k; V v; KVPair(K key, V val) { k = key; v = val; } public K key() { return k; } public V value() { return v; } } /* instance variables. DO NOT CHANGE, ADD OR REMOVE INSTANCE VARIABLES */ KVPair[] htable; //The Hash table which is an array of KVPairs int size; //Number of elements in the hash table int initCap; //Initial capacity of the hash table static final int DEFAULT_EXP = 2; //Default exponent if it's not specified final KVPair TOMBSTONE = new KVPair(null, null); //The Tombstone to be used when deleting an element QHT() { /* ***TO-DO*** Default constructor should initialize the hash table with default capacity */ initCap = 2; for (int i = 1; i < DEFAULT_EXP; i++) { initCap *= 2; } htable = new KVPair[initCap]; } QHT(int exp) { /* ***TO-DO*** Single-parameter constructor. The capacity of the hash table should be 2^exp. if exp < 2, use default exponent. initialize size and initCap accordingly */ if (exp < 2) { exp = DEFAULT_EXP; } initCap = 2; for (int i = 1; i < exp; i++) { initCap *= 2; } htable = new KVPair[initCap]; } public int size() { /* ***TO-DO*** return the number of elements currently stored in the hash table. Shouldn't include TOMBSTONES Should run in O(1) */ return size; } public int capacity() { /* ***TO-DO*** return the capacity of the hash table Should run in O(1) */ return htable.length; } public boolean isEmpty() { /* ***TO-DO*** return true if hash table is empty, false otherwise Should run in O(1) */ return size == 0; } public double loadFactor() { /* ***TO-DO*** return the load factor of this hash table. load factor is the ratio of size to capacity Should run in O(1). Note that the return type is double. */ return (double)size / (double)htable.length; } private int h(K k) { /* The hash function. returns an integer for an arbitrary key Should run in O(1) */ return (k.hashCode() + capacity()) % capacity(); } private int p(K k, int i) { /* The probe function. returns an integer. i is the number of collisions seen so far for the key Should run in O(1) */ return i/2 + (i*i)/2 + (i%2); } public void insert(K k, V v) { /* ***TO-DO*** should insert the given key and value as a KVPair in the hash table. if load factor > 0.5, increase capacity by a factor of 2 */ //The main thing int i = h(k); int z = i; int j = 0; if (htable[i] != null) { if (find(k) != null) { return; } } while (htable[i] != null && htable[i] != TOMBSTONE) { i = (z + p(k, ++j)) % htable.length; if (j == htable.length) { throw new IllegalStateException(); } } htable[i] = new KVPair(k, v); size++; //resize table if (loadFactor() > 0.5) { KVPair[] temp = new KVPair[htable.length * 2]; for (int y = 0; y < htable.length; y++) { if (htable[y] == null || htable[y] == TOMBSTONE) { continue; } i = (htable[y].key().hashCode() + temp.length) % temp.length; z = i; j = 0; while (temp[i] != null && temp[i] != TOMBSTONE) { i = (z + p(k, ++j)) % temp.length; if (j == temp.length) { throw new IllegalStateException(); } } temp[i] = htable[y]; } htable = temp.clone(); } } public V remove(K k) { /* ***TO-DO*** if k is found in the hash table, remove KVPair and return the value. Otherwise, return null. if load factor < 0.25 then reduce capacity in half. */ //the main thing int i = h(k); int z = i; int j = 0; while ((K)htable[i].key() != k) { i = (z + p(k, ++j)) % htable.length; if (j == htable.length) { return null; } while (htable[i] == null) { i = (z + p(k, ++j)) % htable.length; if (j == htable.length) { return null; } } } KVPair remove = htable[i]; htable[i] = TOMBSTONE; size--; //resize table if (loadFactor() < 0.25 && (htable.length / 2) >= initCap) { KVPair[] temp = new KVPair[htable.length / 2]; for (int y = 0; y < htable.length; y++) { if (htable[y] == null || htable[y] == TOMBSTONE) { continue; } i = (htable[y].key().hashCode() + temp.length) % temp.length; z = i; j = 0; while (temp[i] != null && temp[i] != TOMBSTONE) { i = (z + p(k, ++j)) % temp.length; if (j == temp.length) { throw new IllegalStateException(); } } temp[i] = htable[y]; } htable = temp.clone(); } return (V)remove.value(); } public V find(K k) { /* ***TO-DO*** if k is found in the hash table, return the value. Otherwise, return null. */ int i = h(k); int z = i; int j = 0; while ((K)htable[i].key() != k) { i = (z + p(k, ++j)) % htable.length; if (j == htable.length) { return null; } while (htable[i] == null) { i = (z + p(k, ++j)) % htable.length; if (j == htable.length) { return null; } } } return (V)htable[i].value(); } public KVPair get(int i) { /* return the KVPair at index i of the hash table */ if (i >= capacity()) return null; return htable[i]; } public String toString() { /* return a string representation of the hash table. */ String ret = "\n\n"; for (int i = 0; i < capacity(); i++) { if (get(i) != null) { if (get(i).key() != null) ret += i + "\t" + get(i).key() + "\t->\t" + get(i).value() + "\n"; else ret += i + "\tTOMBSTONE\n"; } else { ret += i + "\tnull\n"; } } return ret; } }
9234acb7af769ca780f3584937ac789df6dd48fe
25,498
java
Java
app/src/main/java/com/example/android/products/EditorActivity.java
SaraAlMuzaini/Product_App
4b83ffe1c5140138e66ff1c38f394b44d0da2e61
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/android/products/EditorActivity.java
SaraAlMuzaini/Product_App
4b83ffe1c5140138e66ff1c38f394b44d0da2e61
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/example/android/products/EditorActivity.java
SaraAlMuzaini/Product_App
4b83ffe1c5140138e66ff1c38f394b44d0da2e61
[ "Apache-2.0" ]
null
null
null
44.421603
128
0.637266
997,010
/* * Copyright (C) 2016 The Android Open Source 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.example.android.products; import android.app.Activity; import android.app.AlertDialog; import android.app.LoaderManager; import android.content.ContentValues; import android.content.CursorLoader; import android.content.DialogInterface; import android.content.Intent; import android.content.Loader; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.NavUtils; import android.support.v7.app.AppCompatActivity; import android.text.TextUtils; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.example.android.products.data.ProductContract.ProductEntry; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileNotFoundException; import java.io.InputStream; /** * Allows user to create a new product or edit an existing one. */ public class EditorActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor> { /** * Identifier for the product data loader */ private static final int EXISTING_PRODUCT_LOADER = 0; /** * Content URI for the existing product (null if it's a new product) */ private Uri mCurrentProductUri; /** * EditText field to enter the product's name */ private EditText mNameEditText; /** * EditText field to enter the product's quantity */ private EditText mQuantityEditText; /** * EditText field to enter the product's price */ private EditText mPriceEditText; /** * EditText field to enter the product's supplier name */ private EditText mSupplierNameEditText; /** * EditText field to enter the product's supplier email */ private EditText mSupplierEmailEditText; /** * ImageButton field to pick the product's picture */ private ImageButton mInsertPictureImageButton; public static final int IMAGE_PICKER_CODE = 3; private ImageView mImageEditShow; private byte[] imageArray; /** * If any field Empty this TextView show Error massage */ private TextView mEmptyFieldError; /** * Boolean flag that keeps track of whether the product has been edited (true) or not (false) */ private boolean mProductHasChanged = false; /** * OnTouchListener that listens for any user touches on a View, implying that they are modifying * the view, and we change the mProductHasChanged boolean to true. */ private View.OnTouchListener mTouchListener = new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { mProductHasChanged = true; return false; } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_editor); // Examine the intent that was used to launch this activity, // in order to figure out if we're creating a new product or editing an existing one. Intent intent = getIntent(); mCurrentProductUri = intent.getData(); // If the intent DOES NOT contain a product content URI, then we know that we are // creating a new product. if (mCurrentProductUri == null) { // This is a new product, so change the app bar to say "Add a Product" setTitle(getString(R.string.editor_activity_title_new_product)); // Invalidate the options menu, so the "Delete" menu option can be hidden. // (It doesn't make sense to delete a product that hasn't been created yet.) invalidateOptionsMenu(); } else { // Otherwise this is an existing product, so change app bar to say "Edit product" setTitle(getString(R.string.editor_activity_title_edit_product)); // Initialize a loader to read the product data from the database // and display the current values in the editor getLoaderManager().initLoader(EXISTING_PRODUCT_LOADER, null, this); } // Find all relevant views that we will need to read user input from mNameEditText = (EditText) findViewById(R.id.name_edit); mQuantityEditText = (EditText) findViewById(R.id.quantity_edit); mPriceEditText = (EditText) findViewById(R.id.price_edit); mSupplierNameEditText = (EditText) findViewById(R.id.supplier_name_edit); mSupplierEmailEditText = (EditText) findViewById(R.id.supplier_email_edit); mInsertPictureImageButton = (ImageButton) findViewById(R.id.insert_picture); mImageEditShow = (ImageView) findViewById(R.id.image_edit); mEmptyFieldError = (TextView) findViewById(R.id.empty_field_error); // Setup OnTouchListeners on all the input fields, so we can determine if the user // has touched or modified them. This will let us know if there are unsaved changes // or not, if the user tries to leave the editor without saving. mNameEditText.setOnTouchListener(mTouchListener); mQuantityEditText.setOnTouchListener(mTouchListener); mPriceEditText.setOnTouchListener(mTouchListener); mSupplierNameEditText.setOnTouchListener(mTouchListener); mSupplierEmailEditText.setOnTouchListener(mTouchListener); mInsertPictureImageButton.setOnTouchListener(mTouchListener); //Setup on click for insert image to make user pick picture mInsertPictureImageButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { // Create image picker intent Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); Intent chooserIntent = Intent.createChooser(intent, "Select an Image"); startActivityForResult(chooserIntent, IMAGE_PICKER_CODE); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == IMAGE_PICKER_CODE && resultCode == Activity.RESULT_OK) { if (data == null) { return; } // Otherwise get image out of data try { final Uri imageUri = data.getData(); final InputStream imageStream = getContentResolver().openInputStream(imageUri); final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream); // Temp code to store image mImageEditShow.setImageBitmap(selectedImage); imageArray = imageToArray(selectedImage); } catch (FileNotFoundException e) { e.printStackTrace(); Toast.makeText(EditorActivity.this, "Something went wrong", Toast.LENGTH_LONG).show(); } } else if (requestCode == IMAGE_PICKER_CODE) { Toast.makeText(EditorActivity.this, "You haven't picked an image", Toast.LENGTH_LONG).show(); } } public static byte[] imageToArray(Bitmap bitmap) { if (bitmap != null) { ByteArrayOutputStream stream = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream); return stream.toByteArray(); } return null; } /** * Get user input from editor and save product into database. */ private void saveProduct() { // Read from input fields // Use trim to eliminate leading or trailing white space String nameString = mNameEditText.getText().toString().trim(); String supplierNameString = mSupplierNameEditText.getText().toString().trim(); String supplierEmailString = mSupplierEmailEditText.getText().toString().trim(); String quantityString = mQuantityEditText.getText().toString().trim(); String priceString = mPriceEditText.getText().toString().trim(); // Check if this is supposed to be a new product // and check if all the fields in the editor are blank if (mCurrentProductUri == null && TextUtils.isEmpty(nameString) && TextUtils.isEmpty(supplierNameString) && TextUtils.isEmpty(supplierEmailString) && TextUtils.isEmpty(quantityString) && TextUtils.isEmpty(priceString) && imageArray == null) { // Since no fields were modified, we can return early without creating a new product. // No need to create ContentValues and no need to do any ContentProvider operations. return; } // Create a ContentValues object where column names are the keys, // and product attributes from the editor are the values. ContentValues values = new ContentValues(); values.put(ProductEntry.COLUMN_NAME, nameString); values.put(ProductEntry.COLUMN_SUPPLIER_NAME, supplierNameString); values.put(ProductEntry.COLUMN_SUPPLIER_EMAIL, supplierEmailString); if (imageArray != null) { values.put(ProductEntry.COLUMN_PICTURE, imageArray); } int quantity = 0; if (!TextUtils.isEmpty(quantityString)) { quantity = Integer.parseInt(quantityString); } values.put(ProductEntry.COLUMN_QUANTITY, quantity); // If the price is not provided by the user, don't try to parse the string into an // integer value. Use 0 by default. int price = 0; if (!TextUtils.isEmpty(priceString)) { price = Integer.parseInt(priceString); } values.put(ProductEntry.COLUMN_PRICE, price); // Determine if this is a new or existing product by checking if mCurrentProductUri is null or not if (mCurrentProductUri == null) { // This is a NEW product, so insert a new product into the provider, // returning the content URI for the new product. Uri newUri = getContentResolver().insert(ProductEntry.CONTENT_URI, values); // Show a toast message depending on whether or not the insertion was successful. if (newUri == null) { // If the new content URI is null, then there was an error with insertion. Toast.makeText(this, getString(R.string.editor_insert_product_failed), Toast.LENGTH_SHORT).show(); } else { // Otherwise, the insertion was successful and we can display a toast. Toast.makeText(this, getString(R.string.editor_insert_product_successful), Toast.LENGTH_SHORT).show(); } } else { // Otherwise this is an EXISTING product, so update the product with content URI: mCurrentProductUri // and pass in the new ContentValues. Pass in null for the selection and selection args // because mCurrentProductUri will already identify the correct row in the database that // we want to modify. int rowsAffected = getContentResolver().update(mCurrentProductUri, values, null, null); // Show a toast message depending on whether or not the update was successful. if (rowsAffected == 0) { // If no rows were affected, then there was an error with the update. Toast.makeText(this, getString(R.string.editor_update_product_failed), Toast.LENGTH_SHORT).show(); } else { // Otherwise, the update was successful and we can display a toast. Toast.makeText(this, getString(R.string.editor_update_product_successful), Toast.LENGTH_SHORT).show(); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu options from the res/menu/menu_editor.xml file. // This adds menu items to the app bar. getMenuInflater().inflate(R.menu.menu_editor, menu); return true; } /** * This method is called after invalidateOptionsMenu(), so that the * menu can be updated (some menu items can be hidden or made visible). */ @Override public boolean onPrepareOptionsMenu(Menu menu) { super.onPrepareOptionsMenu(menu); // If this is a new pet, hide the "Delete" menu item. if (mCurrentProductUri == null) { MenuItem menuItem = menu.findItem(R.id.action_delete); menuItem.setVisible(false); } return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // User clicked on a menu option in the app bar overflow menu switch (item.getItemId()) { // Respond to a click on the "Save" menu option case R.id.action_save: // Save product to database if (!isFieldNull()) { saveProduct(); // Exit activity finish(); } else { /** * show Error and stay in the Editor don't exist activity */ mEmptyFieldError.setVisibility(View.VISIBLE); } return true; // Respond to a click on the "Delete" menu option case R.id.action_delete: // Pop up confirmation dialog for deletion showDeleteConfirmationDialog(); return true; // Respond to a click on the "Up" arrow button in the app bar case android.R.id.home: // If the product hasn't changed, continue with navigating up to parent activity // which is the {@link CatalogActivity}. if (!mProductHasChanged) { NavUtils.navigateUpFromSameTask(EditorActivity.this); return true; } // Otherwise if there are unsaved changes, setup a dialog to warn the user. // Create a click listener to handle the user confirming that // changes should be discarded. DialogInterface.OnClickListener discardButtonClickListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { // User clicked "Discard" button, navigate to parent activity. NavUtils.navigateUpFromSameTask(EditorActivity.this); } }; // Show a dialog that notifies the user they have unsaved changes showUnsavedChangesDialog(discardButtonClickListener); return true; } return super.onOptionsItemSelected(item); } private boolean isFieldNull() { // Read from input fields // Use trim to eliminate leading or trailing white space String nameString = mNameEditText.getText().toString().trim(); String supplierNameString = mSupplierNameEditText.getText().toString().trim(); String supplierEmailString = mSupplierEmailEditText.getText().toString().trim(); String quantityString = mQuantityEditText.getText().toString().trim(); String priceString = mPriceEditText.getText().toString().trim(); // Check if this is supposed to be a new product // and check if all the fields in the editor are blank if (TextUtils.isEmpty(nameString) || TextUtils.isEmpty(supplierNameString) || TextUtils.isEmpty(supplierEmailString) || TextUtils.isEmpty(quantityString) || TextUtils.isEmpty(priceString) || imageArray == null) { // if any of this fields weren't modified return null return true; } else { return false; } } /** * This method is called when the back button is pressed. */ @Override public void onBackPressed() { // If the product hasn't changed, continue with handling back button press if (!mProductHasChanged) { super.onBackPressed(); return; } // Otherwise if there are unsaved changes, setup a dialog to warn the user. // Create a click listener to handle the user confirming that changes should be discarded. DialogInterface.OnClickListener discardButtonClickListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { // User clicked "Discard" button, close the current activity. finish(); } }; // Show dialog that there are unsaved changes showUnsavedChangesDialog(discardButtonClickListener); } @Override public Loader<Cursor> onCreateLoader(int i, Bundle bundle) { // Since the editor shows all product attributes, define a projection that contains // all columns from the product table String[] projection = { ProductEntry._ID, ProductEntry.COLUMN_NAME, ProductEntry.COLUMN_SUPPLIER_NAME, ProductEntry.COLUMN_SUPPLIER_EMAIL, ProductEntry.COLUMN_QUANTITY, ProductEntry.COLUMN_PRICE, ProductEntry.COLUMN_PICTURE}; // This loader will execute the ContentProvider's query method on a background thread return new CursorLoader(this, // Parent activity context mCurrentProductUri, // Query the content URI for the current product projection, // Columns to include in the resulting Cursor null, // No selection clause null, // No selection arguments null); // Default sort order } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { // Bail early if the cursor is null or there is less than 1 row in the cursor if (cursor == null || cursor.getCount() < 1) { return; } // Proceed with moving to the first row of the cursor and reading data from it // (This should be the only row in the cursor) if (cursor.moveToFirst()) { // Find the columns of product attributes that we're interested in int nameColumnIndex = cursor.getColumnIndex(ProductEntry.COLUMN_NAME); int supplierNameColumnIndex = cursor.getColumnIndex(ProductEntry.COLUMN_SUPPLIER_NAME); int supplierEmailColumnIndex = cursor.getColumnIndex(ProductEntry.COLUMN_SUPPLIER_EMAIL); int quantityColumnIndex = cursor.getColumnIndex(ProductEntry.COLUMN_QUANTITY); int priceColumnIndex = cursor.getColumnIndex(ProductEntry.COLUMN_PRICE); int pictureColumnIndex = cursor.getColumnIndex(ProductEntry.COLUMN_PICTURE); // Extract out the value from the Cursor for the given column index String name = cursor.getString(nameColumnIndex); String supplierName = cursor.getString(supplierNameColumnIndex); String supplierEmail = cursor.getString(supplierEmailColumnIndex); int quantity = cursor.getInt(quantityColumnIndex); int price = cursor.getInt(priceColumnIndex); byte[] picture = cursor.getBlob(pictureColumnIndex); // Update the views on the screen with the values from the database mNameEditText.setText(name); mSupplierNameEditText.setText(supplierName); mSupplierEmailEditText.setText(supplierEmail); mQuantityEditText.setText(Integer.toString(quantity)); mPriceEditText.setText(Integer.toString(price)); mImageEditShow.setImageBitmap(byteToBitmap(picture)); } } public Bitmap byteToBitmap(byte[] imageByte) { ByteArrayInputStream imageStream = new ByteArrayInputStream(imageByte); Bitmap imageBitmap = BitmapFactory.decodeStream(imageStream); return imageBitmap; } @Override public void onLoaderReset(Loader<Cursor> loader) { // If the loader is invalidated, clear out all the data from the input fields. mNameEditText.setText(""); mQuantityEditText.setText(""); mSupplierNameEditText.setText(""); mSupplierEmailEditText.setText(""); } /** * Show a dialog that warns the user there are unsaved changes that will be lost * if they continue leaving the editor. * * @param discardButtonClickListener is the click listener for what to do when * the user confirms they want to discard their changes */ private void showUnsavedChangesDialog( DialogInterface.OnClickListener discardButtonClickListener) { // Create an AlertDialog.Builder and set the message, and click listeners // for the positive and negative buttons on the dialog. AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.unsaved_changes_dialog_msg); builder.setPositiveButton(R.string.discard, discardButtonClickListener); builder.setNegativeButton(R.string.keep_editing, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User clicked the "Keep editing" button, so dismiss the dialog // and continue editing the pet. if (dialog != null) { dialog.dismiss(); } } }); // Create and show the AlertDialog AlertDialog alertDialog = builder.create(); alertDialog.show(); } /** * Prompt the user to confirm that they want to delete this product. */ private void showDeleteConfirmationDialog() { // Create an AlertDialog.Builder and set the message, and click listeners // for the positive and negative buttons on the dialog. AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.delete_dialog_msg); builder.setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User clicked the "Delete" button, so delete the product. deleteProduct(); } }); builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // User clicked the "Cancel" button, so dismiss the dialog // and continue editing the pet. if (dialog != null) { dialog.dismiss(); } } }); // Create and show the AlertDialog AlertDialog alertDialog = builder.create(); alertDialog.show(); } /** * Perform the deletion of the product in the database. */ private void deleteProduct() { // Only perform the delete if this is an existing product. if (mCurrentProductUri != null) { // Call the ContentResolver to delete the product at the given content URI. // Pass in null for the selection and selection args because the mCurrentProductUri // content URI already identifies the product that we want. int rowsDeleted = getContentResolver().delete(mCurrentProductUri, null, null); // Show a toast message depending on whether or not the delete was successful. if (rowsDeleted == 0) { // If no rows were deleted, then there was an error with the delete. Toast.makeText(this, getString(R.string.editor_delete_product_failed), Toast.LENGTH_SHORT).show(); } else { // Otherwise, the delete was successful and we can display a toast. Toast.makeText(this, getString(R.string.editor_delete_product_successful), Toast.LENGTH_SHORT).show(); } } // Close the activity finish(); } }
9234ae7cafc5bea0f38edd9badf1e6cf855dd20b
1,077
java
Java
sharding-jdbc-core/src/test/java/com/dangdang/ddframe/rdb/common/jaxb/SQLParameters.java
dyzzwj/sharding-jdbc1.5
c061ba86a00c3aea0be79c763fe33ac44d66dd26
[ "Apache-2.0" ]
114
2017-09-25T03:04:52.000Z
2022-03-16T15:38:44.000Z
sharding-jdbc-core/src/test/java/com/dangdang/ddframe/rdb/common/jaxb/SQLParameters.java
dyzzwj/sharding-jdbc1.5
c061ba86a00c3aea0be79c763fe33ac44d66dd26
[ "Apache-2.0" ]
null
null
null
sharding-jdbc-core/src/test/java/com/dangdang/ddframe/rdb/common/jaxb/SQLParameters.java
dyzzwj/sharding-jdbc1.5
c061ba86a00c3aea0be79c763fe33ac44d66dd26
[ "Apache-2.0" ]
110
2017-07-31T00:17:14.000Z
2022-03-16T15:38:34.000Z
29.108108
75
0.753946
997,011
/* * Copyright 1999-2015 dangdang.com. * <p> * 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. * </p> */ package com.dangdang.ddframe.rdb.common.jaxb; import lombok.Getter; import lombok.Setter; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import java.util.ArrayList; import java.util.List; @XmlAccessorType(XmlAccessType.FIELD) @Getter @Setter public final class SQLParameters { @XmlElement private List<SQLAssertData> parameter = new ArrayList<>(); }
9234b03ab99c4e37bd639fd4d50d5402f103cf4a
8,776
java
Java
Aveon Server Programs/src/Mad/Competition/Server/SqlUserDatabaseInterface.java
JakeB1998/aveon-social-data-sharing-app
d9dcd9dab3a8aec13132609553e1b080a3f14aa8
[ "Apache-2.0" ]
3
2020-06-12T17:50:03.000Z
2020-07-30T02:52:39.000Z
Aveon Server Programs/src/Mad/Competition/Server/SqlUserDatabaseInterface.java
JakeB1998/Aveon-Social-Data-Sharing-App
d9dcd9dab3a8aec13132609553e1b080a3f14aa8
[ "Apache-2.0" ]
null
null
null
Aveon Server Programs/src/Mad/Competition/Server/SqlUserDatabaseInterface.java
JakeB1998/Aveon-Social-Data-Sharing-App
d9dcd9dab3a8aec13132609553e1b080a3f14aa8
[ "Apache-2.0" ]
2
2020-06-16T10:34:28.000Z
2020-06-26T09:16:58.000Z
23.155673
121
0.587397
997,012
/* * File name: SqlDatabaseInterface.java * * Programmer : Jake Botka * ULID: JMBOTKA * * Date: Mar 31, 2020 * * Out Of Class Personal Program */ package Mad.Competition.Server; import java.sql.Blob; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import com.example.madcompetition.backend.utils.SerializationOperations; /** * <insert class description here> * * @author Jake Botka * */ public class SqlUserDatabaseInterface { private final String DATABASE_FILE_NAME = "Users.db"; private final String TABLE_NAME = "Users"; private final static SqlUserDatabaseInterface instance = new SqlUserDatabaseInterface(); /** * */ private SqlUserDatabaseInterface() { } public static SqlUserDatabaseInterface getInstance() { return instance; } public Connection connectToDatabaseTable() { Connection conn = null; try { // db parameters String url = "jdbc:sqlite:" + DATABASE_FILE_NAME; // create a connection to the database conn = DriverManager.getConnection(url); Server.safePrintln("Connection to SQLite has been established."); return conn; } catch (SQLException e) { System.out.println(e.getMessage()); return null; } } public void createNewDatabase() { if (this.doesDatabseTableExist() == false) { String url = "jdbc:sqlite:" + DATABASE_FILE_NAME; try (Connection connection = DriverManager.getConnection(url)) { if (connection != null) { DatabaseMetaData meta = connection.getMetaData(); System.out.println("The driver name is " + meta.getDriverName()); System.out.println("A new database has been created."); connection.close(); } } catch (SQLException e) { System.out.println(e.getMessage()); } } else { Server.safePrintln(("Database Already Exists")); } } public void createDatabaseTable() { Connection connection = this.connectToDatabaseTable(); Statement statement; try { statement = connection.createStatement(); statement.setQueryTimeout(30); // set timeout to 30 sec. statement.executeUpdate("DROP TABLE IF EXISTS" + " " + TABLE_NAME); statement.executeUpdate("CREATE TABLE " + TABLE_NAME + " (id INTEGER PRIMARY KEY, " + DatabaseContract.COLUMN_NAME_USER_ID + " STRING, " + DatabaseContract.COLUMN_NAME_USER_OBJ + " BlOB)"); Server.safePrintln("Database table created"); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if (connection != null) { connection.close(); } } catch (SQLException ex) { System.out.println(ex.getMessage()); } } } public ArrayList<SqlUserRowResults> queryDatabaseTable() { ArrayList<SqlUserRowResults> results = new ArrayList(0); Statement statement; String sql; sql = "SELECT id," + DatabaseContract.COLUMN_NAME_USER_ID + "," + DatabaseContract.COLUMN_NAME_USER_OBJ + " FROM " + TABLE_NAME; try (Connection conn = this.connectToDatabaseTable(); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(sql)) { while (rs.next()) { int id = rs.getRow(); int userId = Integer.parseInt(rs.getString(DatabaseContract.COLUMN_NAME_USER_ID)); if (rs.getBytes(DatabaseContract.COLUMN_NAME_USER_OBJ) != null) { User user = (User) SerializationOperations.deserializeToObject(rs.getBytes(DatabaseContract.COLUMN_NAME_USER_OBJ)); results.add(new SqlUserRowResults(id, userId, user)); } } return results; } catch (SQLException e) { System.out.println(e.getMessage()); } return null; } public void getResults(String WhereClause, String selectionArgs) { } public boolean doesDatabseTableExist() { return false; } public void insertObject(User object) { if ( this.isUserInDatabase(object) == false) { String sql = "INSERT INTO " + TABLE_NAME + "(" + DatabaseContract.COLUMN_NAME_USER_ID +"," + DatabaseContract.COLUMN_NAME_USER_OBJ + ") VALUES(?,?)"; sql = String.format(sql , "s"); try (Connection conn = this.connectToDatabaseTable(); PreparedStatement pstmt = conn.prepareStatement(sql)) { pstmt.setString(1, Integer.toString(object.getRestrictedAccount().getAccountId())); pstmt.setBytes(2, SerializationOperations.serializeObjectToBtyeArray(object) ); pstmt.executeUpdate(); Server.safePrintln("Data inserted to database"); } catch (SQLException e) { e.printStackTrace(); } Server.safePrintln("Data Attemted to insert completed"); } else { Server.safePrintln("User already in database"); } } public void deleteDatabase() { } public void deleteTable() { Connection conn = this.connectToDatabaseTable(); try { Statement statement = conn.createStatement(); statement.execute("DROP TABLE " + TABLE_NAME); Server.safePrintln("Database table deleted"); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void deleteRow(int rowId) { String sql = "DELETE FROM " + TABLE_NAME + " " + "WHERE id = " + Integer.toString(rowId); try (Connection conn = this.connectToDatabaseTable(); PreparedStatement pstmt = conn.prepareStatement(sql)) { // execute the delete statement pstmt.executeUpdate(); conn.close(); } catch (SQLException e) { System.out.println(e.getMessage()); } } public void updateRow(int rowId, String collumn,Object data) { String sql = "UPDATE Users SET UserObject = ? " + "WHERE UserID = ?"; final String ID = "?"; if (rowId >= 0) { try (Connection conn = this.connectToDatabaseTable(); PreparedStatement pstmt = conn.prepareStatement(sql)) { pstmt.setBytes(1, SerializationOperations.serializeObjectToBtyeArray(data)); pstmt.setInt(2,rowId); pstmt.executeUpdate(); conn.close(); } catch (SQLException e) { System.out.println(e.getMessage()); } } else { Server.safePrintln("Invlid row id"); } } /** * * @param user * @return */ public boolean saveUser(User user) { ArrayList<SqlUserRowResults> results = this.queryDatabaseTable(); for (SqlUserRowResults res : results) { System.out.println(res.getUser().getUserName()); if (res.getUser().equals(user)) { int rowId = res.getUserId(); this.updateRow(rowId, DatabaseContract.COLUMN_NAME_USER_OBJ, user); System.out.println("Found user in database to save : " + res.getUserId()); return true; } } return false; } /** * * @param user * @return */ public boolean isUserInDatabase(User user) { ArrayList<SqlUserRowResults> results = this.queryDatabaseTable(); if (results != null) { if (this.isDatabaseEmpty() == false) { for (SqlUserRowResults res : results) { if (res.getUser().equals(user)) { Server.safePrintln("User already in database"); return true; } } } } return false; } public boolean isDatabaseEmpty() { ArrayList<SqlUserRowResults> results = this.queryDatabaseTable(); if (results != null) { if (results.size() <= 0) { Server.safePrintln("The database table is empty"); return true; } } return false; } public class DatabaseContract { public static final String COLUMN_NAME_USER_OBJ = "UserObject"; public static final String COLUMN_NAME_USER_ID = "UserID"; } }
9234b0a7856e162fedc992ed965732d6a5f30daa
236
java
Java
features/src/main/java/features/domain/builders/ManyToManyBBarBuilder.java
apidae-tourisme/joist
17f320f38ba739e3c90ade0877b0bc14ecb14304
[ "Apache-2.0" ]
16
2015-04-13T15:24:03.000Z
2020-11-02T09:06:43.000Z
features/src/main/java/features/domain/builders/ManyToManyBBarBuilder.java
mdietz198/joist
dcca7586204667adbd3dbf47d1217feb1d3e2df0
[ "Apache-2.0" ]
4
2016-06-20T11:21:15.000Z
2019-09-02T18:46:12.000Z
features/src/main/java/features/domain/builders/ManyToManyBBarBuilder.java
mdietz198/joist
dcca7586204667adbd3dbf47d1217feb1d3e2df0
[ "Apache-2.0" ]
12
2015-10-09T16:50:11.000Z
2021-09-08T14:42:10.000Z
19.666667
73
0.813559
997,013
package features.domain.builders; import features.domain.ManyToManyBBar; public class ManyToManyBBarBuilder extends ManyToManyBBarBuilderCodegen { public ManyToManyBBarBuilder(ManyToManyBBar instance) { super(instance); } }
9234b0a88801841b02770b9408c1f754b8d2ebd7
7,864
java
Java
archaius-etcd/src/test/java/com/netflix/config/source/EtcdConfigurationSourceTest.java
bTest2018/archaius
891d471151f657ea5acd0efa4e6410ef1d1d2120
[ "Apache-2.0" ]
2,084
2015-01-02T11:21:17.000Z
2022-03-30T09:38:44.000Z
archaius-etcd/src/test/java/com/netflix/config/source/EtcdConfigurationSourceTest.java
bTest2018/archaius
891d471151f657ea5acd0efa4e6410ef1d1d2120
[ "Apache-2.0" ]
347
2015-01-07T17:51:03.000Z
2021-12-27T21:46:22.000Z
archaius-etcd/src/test/java/com/netflix/config/source/EtcdConfigurationSourceTest.java
bTest2018/archaius
891d471151f657ea5acd0efa4e6410ef1d1d2120
[ "Apache-2.0" ]
474
2015-01-22T17:34:19.000Z
2022-03-02T05:50:43.000Z
46.532544
130
0.721261
997,014
package com.netflix.config.source; import com.google.common.collect.Lists; import com.netflix.config.*; import org.boon.core.Handler; import org.boon.etcd.ClientBuilder; import org.boon.etcd.Etcd; import org.boon.etcd.Node; import org.boon.etcd.Response; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.URI; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.*; /** * Tests the implementation of {@link EtcdConfigurationSource}. * * @author spoon16 */ public class EtcdConfigurationSourceTest { private static final Logger logger = LoggerFactory.getLogger(EtcdConfigurationSourceTest.class); private static final Etcd ETCD = mock(Etcd.class); // uncomment to use local/vagrant CoreOS VM running Etcd // private static final Etcd ETCD = ClientBuilder.builder().hosts(URI.create("http://172.17.8.101:4001")).createClient(); private static final String CONFIG_PATH = "config"; private static final Response ETCD_LIST_RESPONSE = new Response("get", 200, new Node("/config", null, 1378, 1378, 0, true, Lists.newArrayList( new Node("/config/test.key1", "test.value1-etcd", 19311, 19311, 0, false, null), new Node("/config/test.key4", "test.value4-etcd", 1388, 1388, 0, false, null), new Node("/config/test.key6", "test.value6-etcd", 1232, 1232, 0, false, null), new Node("/config/test.key7", "test.value7-etcd", 1234, 1234, 0, false, null) ))); private static Handler<Response> ETCD_UPDATE_HANDLER; private static final Answer WITH_ETCD_UPDATE_HANDLER = new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { ETCD_UPDATE_HANDLER = (Handler<Response>) invocation.getArguments()[0]; return null; } }; private static EtcdConfigurationSource ETCD_CONFIGURATION_SOURCE; private static DynamicWatchedConfiguration ETCD_CONFIGURATION; private static final ConcurrentMapConfiguration MAP_CONFIGURATION = new ConcurrentMapConfiguration(); private static final ConcurrentMapConfiguration SYSTEM_CONFIGURATION = new ConcurrentMapConfiguration(); @BeforeClass public static void before() throws Exception { final ConcurrentCompositeConfiguration compositeConfig = new ConcurrentCompositeConfiguration(); doReturn(ETCD_LIST_RESPONSE).when(ETCD).list(anyString()); doAnswer(WITH_ETCD_UPDATE_HANDLER).when(ETCD).waitRecursive(any(Handler.class), anyString()); ETCD_CONFIGURATION_SOURCE = new EtcdConfigurationSource(ETCD, CONFIG_PATH); ETCD_CONFIGURATION = new DynamicWatchedConfiguration(ETCD_CONFIGURATION_SOURCE); compositeConfig.addConfiguration(ETCD_CONFIGURATION, "etcd dynamic override configuration"); MAP_CONFIGURATION.addProperty("test.key1", "test.value1-map"); MAP_CONFIGURATION.addProperty("test.key2", "test.value2-map"); MAP_CONFIGURATION.addProperty("test.key3", "test.value3-map"); MAP_CONFIGURATION.addProperty("test.key4", "test.value4-map"); MAP_CONFIGURATION.addProperty("test.key7", "test.value7-map"); compositeConfig.addConfiguration(MAP_CONFIGURATION, "map configuration"); System.setProperty("test.key4", "test.value4-system"); System.setProperty("test.key5", "test.value5-system"); SYSTEM_CONFIGURATION.loadProperties(System.getProperties()); compositeConfig.addConfiguration(SYSTEM_CONFIGURATION, "system configuration"); ConfigurationManager.install(compositeConfig); } /** * should return value from EtcdConfigurationSource when EtcdConfigurationSource provides key */ @Test public void testEtcdPropertyOverride() throws Exception { // there is a etcd value for this key assertEquals("test.value1-etcd", DynamicPropertyFactory.getInstance().getStringProperty("test.key1", "default").get()); } /** * should return map configuration source value when EtcdConfigurationSource does not provide key */ @Test public void testNoEtcdPropertyOverride() throws Exception { // there is not etcd value for this key but there is a configuration source that provides this key assertEquals("test.value2-map", DynamicPropertyFactory.getInstance().getStringProperty("test.key2", "default").get()); } /** * should return default value when no configuration source provides key */ @Test public void testDefault() throws Exception { // no configuration source for key assertEquals("default", DynamicPropertyFactory.getInstance().getStringProperty("test.key99", "default").get()); } /** * should select lower priority configuration sources selected when EtcdConfigurationSource does not provide key */ @Test public void testSystemPropertyOverride() throws Exception { // system configuration provides key, etcd configuration provides key, source = etcd configuration assertEquals("test.value4-etcd", DynamicPropertyFactory.getInstance().getStringProperty("test.key4", "default").get()); // system configuration provides key, etcd configuration does not provide key, source = system configuration assertEquals("test.value5-system", DynamicPropertyFactory.getInstance().getStringProperty("test.key5", "default").get()); } /** * should not override EtcdConfigurationSource when lower priority configuration source is updated */ @Test public void testUpdateOverriddenProperty() throws Exception { final String updateProperty = "test.key1"; // update the map config's property and assert that the value is still the overridden value MAP_CONFIGURATION.setProperty(updateProperty, "prop1"); assertEquals("test.value1-etcd", DynamicPropertyFactory.getInstance().getStringProperty(updateProperty, "default").get()); } /** * should update EtcdConfigurationSource when Etcd client handles writes */ @Test public void testUpdateEtcdProperty() throws Exception { final String updateProperty = "test.key6"; final String updateKey = CONFIG_PATH + "/" + updateProperty; final String updateValue = "test.value6-etcd-override"; final String initialValue = "test.value6-etcd"; assertEquals(initialValue, DynamicPropertyFactory.getInstance().getStringProperty(updateProperty, "default").get()); ETCD_UPDATE_HANDLER.handle(new Response("set", 200, new Node(updateKey, updateValue, 19444, 19444, 0, false, null))); assertEquals(updateValue, DynamicPropertyFactory.getInstance().getStringProperty(updateProperty, "default").get()); } /** * should delete from EtcdConfigurationSource when Etcd client handles a delete event */ @Test public void testDeleteEtcdProperty() throws Exception { final String deleteProperty = "test.key7"; final String deleteKey = CONFIG_PATH + "/" + deleteProperty; final String initialValue = "test.value7-etcd"; assertEquals(initialValue, DynamicPropertyFactory.getInstance().getStringProperty(deleteProperty, "default").get()); ETCD_UPDATE_HANDLER.handle(new Response("delete", 200, new Node(deleteKey, null, 12345, 12345, 0, false, null))); assertEquals("test.value7-map", DynamicPropertyFactory.getInstance().getStringProperty(deleteProperty, "default").get()); } }
9234b0ba166a37e825f62dfa2a0351089486c464
549
java
Java
src/main/java/nerdhub/simplestoragesystems/api/item/ICustomStorageStack.java
NerdHubMC/Simple-Storage-Systems
9b042938213a2df7dc816418563173846b28a7a3
[ "MIT" ]
null
null
null
src/main/java/nerdhub/simplestoragesystems/api/item/ICustomStorageStack.java
NerdHubMC/Simple-Storage-Systems
9b042938213a2df7dc816418563173846b28a7a3
[ "MIT" ]
2
2019-02-16T14:33:44.000Z
2019-02-23T01:03:36.000Z
src/main/java/nerdhub/simplestoragesystems/api/item/ICustomStorageStack.java
NerdHubMC/Simple-Storage-Systems
9b042938213a2df7dc816418563173846b28a7a3
[ "MIT" ]
null
null
null
18.3
68
0.728597
997,015
package nerdhub.simplestoragesystems.api.item; import nerdhub.simplestoragesystems.client.gui.gui.ContainerGuiBase; import net.minecraft.item.ItemStack; public interface ICustomStorageStack { ItemStack getStack(); String getName(); String getModid(); String getModName(); String getFormattedAmount(); void draw(ContainerGuiBase gui, int x, int y); boolean isCraftingObject(); void setIsCrafingObject(boolean object); void addAmount(int amount); void setAmount(int amount); int getAmount(); }
9234b1462d63bfb0b270b99c69c77d9edcf07430
58
java
Java
HPWS/src/main/java/com/san/section/SectionRequest.java
searleser97/HeartPreventSpring
1e17b1a635e1ba08c962ae0ae333af7cc72f3dad
[ "MIT" ]
null
null
null
HPWS/src/main/java/com/san/section/SectionRequest.java
searleser97/HeartPreventSpring
1e17b1a635e1ba08c962ae0ae333af7cc72f3dad
[ "MIT" ]
null
null
null
HPWS/src/main/java/com/san/section/SectionRequest.java
searleser97/HeartPreventSpring
1e17b1a635e1ba08c962ae0ae333af7cc72f3dad
[ "MIT" ]
null
null
null
11.6
29
0.775862
997,016
package com.san.section; public class SectionRequest { }
9234b27be830f1daee3c8ead6158cb99493b42dd
731
java
Java
app/src/main/java/com/gworks/richtext/tags/StyleMarkup.java
TheAndroidMonk/RichText
7e556072bea4fd591e013e3160c393319fd6d5fb
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/gworks/richtext/tags/StyleMarkup.java
TheAndroidMonk/RichText
7e556072bea4fd591e013e3160c393319fd6d5fb
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/gworks/richtext/tags/StyleMarkup.java
TheAndroidMonk/RichText
7e556072bea4fd591e013e3160c393319fd6d5fb
[ "Apache-2.0" ]
null
null
null
19.756757
70
0.648427
997,017
package com.gworks.richtext.tags; import android.text.Spannable; /** * Created by durgadass on 6/1/18. */ public abstract class StyleMarkup extends Markup { private Object styleSpan; public StyleMarkup(Object styleSpan) { this.styleSpan = styleSpan; } @Override public boolean canExistWith(Class<? extends Markup> anotherType) { return anotherType != getClass(); } @Override public void apply(Spannable text, int from, int to, int flags) { text.setSpan(styleSpan, from, to, flags); } @Override public void remove(Spannable text) { text.removeSpan(styleSpan); } @Override public boolean isSplittable() { return true; } }
9234b33532d90acc2977b132f63db1c140ff1410
1,492
java
Java
platforms/android/uwx/src/main/java/com/ucar/weex/init/manager/ContentInfo.java
weexext/weex-demo
733ae90e22e849516fde35184326936db171c1de
[ "Apache-2.0" ]
null
null
null
platforms/android/uwx/src/main/java/com/ucar/weex/init/manager/ContentInfo.java
weexext/weex-demo
733ae90e22e849516fde35184326936db171c1de
[ "Apache-2.0" ]
null
null
null
platforms/android/uwx/src/main/java/com/ucar/weex/init/manager/ContentInfo.java
weexext/weex-demo
733ae90e22e849516fde35184326936db171c1de
[ "Apache-2.0" ]
null
null
null
26.175439
121
0.66622
997,018
package com.ucar.weex.init.manager; import android.app.Activity; import android.text.TextUtils; import com.ucar.weex.init.utils.Assertions; /** * Created by chenxi.cui on 2017/9/6. */ public class ContentInfo { public Class mClass; public String mActivityStr; public ContentInfo(Class activityClass) { this(activityClass, activityClass != null ? activityClass.getName() : null); } public ContentInfo(Class activityClass, String activityString) { Assertions.assumeCondition(Activity.class.isAssignableFrom(activityClass), "This class is not a Activity class"); this.mClass = activityClass; if (activityString != null) { this.mActivityStr = activityString; } } public void setActivityStr(String activityStr) { Assertions.assertCondition(!TextUtils.isEmpty(activityStr)); this.mActivityStr = activityStr; } public Class getActivityClass() { return this.mClass; } public String getActivityStr() { return this.mActivityStr; } public boolean equals(Class activityClass) { return activityClass == this.mClass; } public boolean equals(String activityStr) { return this.mActivityStr == activityStr; } @Override public boolean equals(Object o) { if (o instanceof ContentInfo) { return ((ContentInfo) o).getActivityStr().equals(getActivityStr()); } return super.equals(o); } }
9234b395529a2aa3ee8addfed71647b114bc4557
4,490
java
Java
src/main/java/net/openid/conformance/info/TestInfoApi.java
openid-certification/conformance-suite
86f25bd22837391e6639edfa55190588b9612422
[ "MIT" ]
2
2021-09-12T11:45:13.000Z
2022-01-24T14:56:44.000Z
src/main/java/net/openid/conformance/info/TestInfoApi.java
openid-certification/conformance-suite
86f25bd22837391e6639edfa55190588b9612422
[ "MIT" ]
6
2019-10-29T18:16:34.000Z
2021-08-14T09:48:39.000Z
src/main/java/net/openid/conformance/info/TestInfoApi.java
openid-certification/conformance-suite
86f25bd22837391e6639edfa55190588b9612422
[ "MIT" ]
null
null
null
37.107438
207
0.756347
997,019
package net.openid.conformance.info; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import net.openid.conformance.security.AuthenticationFacade; import net.openid.conformance.testmodule.OIDFJSON; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import com.google.common.base.Strings; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.gson.JsonObject; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; @Controller @RequestMapping(value = "/api") public class TestInfoApi { @Autowired private TestInfoRepository testInfos; @Autowired private AuthenticationFacade authenticationFacade; @Autowired private TestInfoService testInfoService; @GetMapping(value = "/info", produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "Get information of all test module instances", notes = "Will return all run test modules if user is admin role, otherwise only the logged in user's tests will be returned") @ApiResponses({ @ApiResponse(code = 200, message = "Retrieved successfully") }) public ResponseEntity<List<TestInfo>> getAllTests() { List<TestInfo> testInfo = null; if (authenticationFacade.isAdmin()) { testInfo = Lists.newArrayList(testInfos.findAll()); } else { ImmutableMap<String, String> owner = authenticationFacade.getPrincipal(); if (owner != null) { testInfo = Lists.newArrayList(testInfos.findAllByOwner(owner)); } } return new ResponseEntity<>(testInfo, HttpStatus.OK); } @GetMapping(value = "/info/{id}", produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "Get test information by test id") @ApiResponses(value = { @ApiResponse(code = 200, message = "Retrieved successfully"), @ApiResponse(code = 404, message = "Couldn't find test information for provided testId") }) public ResponseEntity<Object> getTestInfo( @ApiParam(value = "Id of test") @PathVariable("id") String id, @ApiParam(value = "Published data only") @RequestParam(name = "public", defaultValue = "false") boolean publicOnly) { Optional<?> testInfo = Optional.empty(); if (publicOnly) { testInfo = testInfos.findByIdPublic(id); } else if (authenticationFacade.isAdmin()) { testInfo = testInfos.findById(id); } else { ImmutableMap<String, String> owner = authenticationFacade.getPrincipal(); if (owner != null) { testInfo = testInfos.findByIdAndOwner(id, owner); } } if (!testInfo.isPresent()) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } else { return new ResponseEntity<>(testInfo.get(), HttpStatus.OK); } } @PostMapping(value = "/info/{id}/publish", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE) @ApiOperation(value = "Publish a test information") @ApiResponses(value = { @ApiResponse(code = 200, message = "Published successfully"), @ApiResponse(code = 400, message = "'publish' field is missing or its value is not JsonPrimitive"), @ApiResponse(code = 403, message = "'publish' value is not valid") }) public ResponseEntity<Object> publishTestInfo(@ApiParam(value = "Id of test that you want to publish")@PathVariable("id") String id, @ApiParam(value = "Configuration Json") @RequestBody JsonObject config) { String publish = null; if (config.has("publish") && config.get("publish").isJsonPrimitive()) { publish = Strings.emptyToNull(OIDFJSON.getString(config.get("publish"))); } else { return new ResponseEntity<>(HttpStatus.BAD_REQUEST); } if (!testInfoService.publishTest(id, publish)) { return new ResponseEntity<>(HttpStatus.FORBIDDEN); } Map<String, Object> map = new HashMap<>(); map.put("id", id); map.put("publish", publish); return new ResponseEntity<>(map, HttpStatus.OK); } }
9234b3b093e1e5a2c4e21cec24cf195f28c4811d
1,909
java
Java
src/main/java/team/baymax/model/util/datetime/Duration.java
theyellowfellow/tp
d20df37e28cbebba78e066a1f2bcb5875ba39e7f
[ "MIT" ]
1
2021-02-07T11:51:22.000Z
2021-02-07T11:51:22.000Z
src/main/java/team/baymax/model/util/datetime/Duration.java
theyellowfellow/tp
d20df37e28cbebba78e066a1f2bcb5875ba39e7f
[ "MIT" ]
244
2020-09-05T05:53:21.000Z
2020-11-13T11:39:57.000Z
src/main/java/team/baymax/model/util/datetime/Duration.java
theyellowfellow/tp
d20df37e28cbebba78e066a1f2bcb5875ba39e7f
[ "MIT" ]
5
2020-09-11T15:19:31.000Z
2020-09-11T15:29:28.000Z
28.492537
109
0.628601
997,020
package team.baymax.model.util.datetime; import static java.util.Objects.requireNonNull; import static team.baymax.commons.util.AppUtil.checkArgument; import java.util.function.Predicate; public class Duration { public static final String MESSAGE_CONSTRAINTS = "Duration (in minutes) must be a valid integer spanning" + " not more than one day"; private static final int MIN_VALUE = 1; private static final int MAX_VALUE = 24 * 60; public static final Predicate<Integer> VALIDATION_PREDICATE = i -> i >= MIN_VALUE && i <= MAX_VALUE; public final Integer value; /** * Constructs a {@Duration} from an integer. * */ public Duration(Integer duration) { requireNonNull(duration); checkArgument(isValidDuration(duration), MESSAGE_CONSTRAINTS); this.value = duration; } public int numberOfHours() { return value / 60; } public int numberOfMinutes() { return value % 60; } /** * Returns true if a given Integer is a valid duration. */ public static boolean isValidDuration(Integer dur) { return VALIDATION_PREDICATE.test(dur); } @Override public String toString() { if (numberOfHours() == 0) { return String.format("%d Minute(s)", numberOfMinutes()); } else if (numberOfMinutes() == 0) { return String.format("%d Hour(s)", numberOfHours()); } return String.format("%1$d Hour(s) %2$d Minute(s)", numberOfHours(), numberOfMinutes()); } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof Duration // instanceof handles nulls && value.equals(((Duration) other).value)); // state check } @Override public int hashCode() { return value.hashCode(); } }
9234b441b63bad3da9bcbf861ccbee49b57bdbbe
378
java
Java
src/main/java/com/streetferret/opus/location/LocationMatchSorter.java
ZeLonewolf/openstreetmap-pad-us-inspector
d71557618e32463d31567bbc49af92de45729507
[ "CC0-1.0" ]
2
2020-11-28T05:12:25.000Z
2021-12-26T04:07:00.000Z
src/main/java/com/streetferret/opus/location/LocationMatchSorter.java
ZeLonewolf/openstreetmap-pad-us-inspector
d71557618e32463d31567bbc49af92de45729507
[ "CC0-1.0" ]
null
null
null
src/main/java/com/streetferret/opus/location/LocationMatchSorter.java
ZeLonewolf/openstreetmap-pad-us-inspector
d71557618e32463d31567bbc49af92de45729507
[ "CC0-1.0" ]
null
null
null
27
88
0.767196
997,021
package com.streetferret.opus.location; import java.util.Comparator; public class LocationMatchSorter implements Comparator<LocationMatch> { @Override public int compare(LocationMatch m1, LocationMatch m2) { return Double.compare(m1.getMatchExact() + m1.getMatchOverlap() + m1.getMatchInside(), m2.getMatchExact() + m2.getMatchOverlap() + m2.getMatchInside()); } }
9234b51e1623f56a9034a83ab886cb0c11d4d78e
1,221
java
Java
core/src/main/java/com/orientechnologies/orient/core/storage/index/sbtree/local/v2/OSBTreeException.java
bernhardriegler/orientdb
9d1e4ff1bb5ebb52092856baad40c35cf27295f8
[ "Apache-2.0" ]
3,651
2015-01-02T23:58:10.000Z
2022-03-31T21:12:12.000Z
core/src/main/java/com/orientechnologies/orient/core/storage/index/sbtree/local/v2/OSBTreeException.java
bernhardriegler/orientdb
9d1e4ff1bb5ebb52092856baad40c35cf27295f8
[ "Apache-2.0" ]
6,890
2015-01-01T09:41:48.000Z
2022-03-29T08:39:49.000Z
core/src/main/java/com/orientechnologies/orient/core/storage/index/sbtree/local/v2/OSBTreeException.java
bernhardriegler/orientdb
9d1e4ff1bb5ebb52092856baad40c35cf27295f8
[ "Apache-2.0" ]
923
2015-01-01T20:40:08.000Z
2022-03-21T07:26:56.000Z
31.307692
79
0.712531
997,022
/* * * * Copyright 2010-2016 OrientDB LTD (http://orientdb.com) * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * * * For more information: http://orientdb.com * */ package com.orientechnologies.orient.core.storage.index.sbtree.local.v2; import com.orientechnologies.orient.core.exception.ODurableComponentException; /** * @author Andrey Lomakin (a.lomakin-at-orientdb.com) * @since 8/30/13 */ public class OSBTreeException extends ODurableComponentException { public OSBTreeException(OSBTreeException exception) { super(exception); } public OSBTreeException(String message, OSBTreeV2 component) { super(message, component); } }
9234b550ea953fafe28c978fe6549cc6eb090a91
1,064
java
Java
MMIT/src/main/java/com/mmit/integracion/usuarios/UsuariosDAO.java
Dielam/MMIT
146ed5bf721b4dd75fdc8298ca4eaefbed32527c
[ "MIT" ]
null
null
null
MMIT/src/main/java/com/mmit/integracion/usuarios/UsuariosDAO.java
Dielam/MMIT
146ed5bf721b4dd75fdc8298ca4eaefbed32527c
[ "MIT" ]
null
null
null
MMIT/src/main/java/com/mmit/integracion/usuarios/UsuariosDAO.java
Dielam/MMIT
146ed5bf721b4dd75fdc8298ca4eaefbed32527c
[ "MIT" ]
null
null
null
31.294118
72
0.724624
997,023
/* * Copyright (C) 2018 Your Organisation * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.mmit.integracion.usuarios; import com.mmit.negocio.usuarios.UsuarioTrans; /** * * @author carlos */ public interface UsuariosDAO { /** *Devuelve los datos de un usuario dado su nombre * @param nombre nombre del usuario * @return datos del usuario */ public UsuarioTrans readByNombre(String nombre) throws Exception; }
9234b570803fef290a0a882e083f51f84e373fc1
1,930
java
Java
src/main/java/com/whalecloud/service/ReportResService.java
tmf-201911-blockchain/tmf
16e08a99545a757c74d5b1ad74a0527a8210f99d
[ "Apache-2.0" ]
6
2019-11-05T10:21:21.000Z
2020-04-21T07:41:21.000Z
src/main/java/com/whalecloud/service/ReportResService.java
tmf-201911-blockchain/tmf
16e08a99545a757c74d5b1ad74a0527a8210f99d
[ "Apache-2.0" ]
2
2019-12-12T07:05:23.000Z
2022-03-31T20:29:26.000Z
src/main/java/com/whalecloud/service/ReportResService.java
tmf-201911-blockchain/tmf
16e08a99545a757c74d5b1ad74a0527a8210f99d
[ "Apache-2.0" ]
2
2019-12-12T06:20:19.000Z
2020-03-18T13:47:24.000Z
16.782609
84
0.59171
997,024
package com.whalecloud.service; import com.whalecloud.domain.OpsInfo; import com.whalecloud.domain.ReportInfoResponse; import com.whalecloud.domain.ReportResDto; import com.whalecloud.domain.ReportResWithSpeed; import com.whalecloud.domain.re.ReportRes; import java.util.List; /** * * 评论和打分 * * @author zhaoyanac * @date 2019/10/31 */ public interface ReportResService { void cochain(String taskId) throws Exception; /** * 报障 * * @param dto * @return */ ReportInfoResponse report(ReportRes dto) throws Exception; /** * 打分 * * @param phone * @param mark */ ReportRes mark(String phone, Integer mark, String resourceId) throws Exception; /** * * 根据手机号和基站ID获取信息 * * @param phone * @return */ ReportRes getOneByPhone(String phone, String resourceId); /** * * 把流程转换成1 * * @param taskId * @throws Exception */ void updateYn(String taskId) throws Exception; /** * * 同意 * * @param taskId * @param isSolved 是否同意 1:同意 0: 不同意 * */ void process(String taskId, Integer isSolved) throws Exception; /** * * 查询出所有信息 * * @param dto * @return * @throws Exception */ List<OpsInfo> fetchList(OpsInfo dto) throws Exception; /** * * 是否已经申请过,并且处理过 * * @param phone * @return */ int haveReported(String phone); /** * 通过taskId获取 * * @param taskId * @return * @throws Exception */ ReportResDto getOneByTaskId(String taskId) throws Exception; /** * 通过基站ID获取所有信息 * * @param resourceId * @return * @throws Exception */ List<ReportRes> getOneByResourceId(String resourceId) throws Exception; List<ReportResWithSpeed> showStationReport(String resourceId) throws Exception; }
9234b594dfce7c1cf06de8880c8b37daa6f61657
31,191
java
Java
content/public/android/java/src/org/chromium/content/browser/ChildProcessLauncher.java
rzr/chromium-crosswalk
d391344809adf7b4f39764ac0e15c378169b805f
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2019-11-28T10:46:52.000Z
2019-11-28T10:46:52.000Z
content/public/android/java/src/org/chromium/content/browser/ChildProcessLauncher.java
eth-sri/ChromeER
002512fd4168c50bd7613c38a322e2862c9ffd89
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
content/public/android/java/src/org/chromium/content/browser/ChildProcessLauncher.java
eth-sri/ChromeER
002512fd4168c50bd7613c38a322e2862c9ffd89
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2015-03-27T11:15:39.000Z
2016-08-17T14:19:56.000Z
41.422311
100
0.626687
997,025
// Copyright 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.content.browser; import android.content.Context; import android.content.pm.ApplicationInfo; import android.content.pm.PackageManager; import android.graphics.SurfaceTexture; import android.os.RemoteException; import android.util.Log; import android.util.Pair; import android.view.Surface; import org.chromium.base.CalledByNative; import org.chromium.base.JNINamespace; import org.chromium.base.ThreadUtils; import org.chromium.base.TraceEvent; import org.chromium.base.VisibleForTesting; import org.chromium.base.library_loader.Linker; import org.chromium.content.app.ChildProcessService; import org.chromium.content.app.ChromiumLinkerParams; import org.chromium.content.app.PrivilegedProcessService; import org.chromium.content.app.SandboxedProcessService; import org.chromium.content.common.IChildProcessCallback; import org.chromium.content.common.SurfaceWrapper; import java.util.ArrayList; import java.util.LinkedList; import java.util.Map; import java.util.Queue; import java.util.concurrent.ConcurrentHashMap; /** * This class provides the method to start/stop ChildProcess called by native. */ @JNINamespace("content") public class ChildProcessLauncher { private static final String TAG = "ChildProcessLauncher"; static final int CALLBACK_FOR_UNKNOWN_PROCESS = 0; static final int CALLBACK_FOR_GPU_PROCESS = 1; static final int CALLBACK_FOR_RENDERER_PROCESS = 2; static final int CALLBACK_FOR_UTILITY_PROCESS = 3; private static final String SWITCH_PROCESS_TYPE = "type"; private static final String SWITCH_RENDERER_PROCESS = "renderer"; private static final String SWITCH_UTILITY_PROCESS = "utility"; private static final String SWITCH_GPU_PROCESS = "gpu-process"; private static class ChildConnectionAllocator { // Connections to services. Indices of the array correspond to the service numbers. private final ChildProcessConnection[] mChildProcessConnections; // The list of free (not bound) service indices. // SHOULD BE ACCESSED WITH mConnectionLock. private final ArrayList<Integer> mFreeConnectionIndices; private final Object mConnectionLock = new Object(); private Class<? extends ChildProcessService> mChildClass; private final boolean mInSandbox; public ChildConnectionAllocator(boolean inSandbox, int numChildServices) { mChildProcessConnections = new ChildProcessConnectionImpl[numChildServices]; mFreeConnectionIndices = new ArrayList<Integer>(numChildServices); for (int i = 0; i < numChildServices; i++) { mFreeConnectionIndices.add(i); } mChildClass = inSandbox ? SandboxedProcessService.class : PrivilegedProcessService.class; mInSandbox = inSandbox; } public ChildProcessConnection allocate( Context context, ChildProcessConnection.DeathCallback deathCallback, ChromiumLinkerParams chromiumLinkerParams) { synchronized (mConnectionLock) { if (mFreeConnectionIndices.isEmpty()) { Log.d(TAG, "Ran out of services to allocate."); return null; } int slot = mFreeConnectionIndices.remove(0); assert mChildProcessConnections[slot] == null; mChildProcessConnections[slot] = new ChildProcessConnectionImpl(context, slot, mInSandbox, deathCallback, mChildClass, chromiumLinkerParams); Log.d(TAG, "Allocator allocated a connection, sandbox: " + mInSandbox + ", slot: " + slot); return mChildProcessConnections[slot]; } } public void free(ChildProcessConnection connection) { synchronized (mConnectionLock) { int slot = connection.getServiceNumber(); if (mChildProcessConnections[slot] != connection) { int occupier = mChildProcessConnections[slot] == null ? -1 : mChildProcessConnections[slot].getServiceNumber(); Log.e(TAG, "Unable to find connection to free in slot: " + slot + " already occupied by service: " + occupier); assert false; } else { mChildProcessConnections[slot] = null; assert !mFreeConnectionIndices.contains(slot); mFreeConnectionIndices.add(slot); Log.d(TAG, "Allocator freed a connection, sandbox: " + mInSandbox + ", slot: " + slot); } } } /** @return the count of connections managed by the allocator */ @VisibleForTesting int allocatedConnectionsCountForTesting() { return mChildProcessConnections.length - mFreeConnectionIndices.size(); } } private static class PendingSpawnData { private final Context mContext; private final String[] mCommandLine; private final int mChildProcessId; private final FileDescriptorInfo[] mFilesToBeMapped; private final long mClientContext; private final int mCallbackType; private final boolean mInSandbox; private PendingSpawnData( Context context, String[] commandLine, int childProcessId, FileDescriptorInfo[] filesToBeMapped, long clientContext, int callbackType, boolean inSandbox) { mContext = context; mCommandLine = commandLine; mChildProcessId = childProcessId; mFilesToBeMapped = filesToBeMapped; mClientContext = clientContext; mCallbackType = callbackType; mInSandbox = inSandbox; } private Context context() { return mContext; } private String[] commandLine() { return mCommandLine; } private int childProcessId() { return mChildProcessId; } private FileDescriptorInfo[] filesToBeMapped() { return mFilesToBeMapped; } private long clientContext() { return mClientContext; } private int callbackType() { return mCallbackType; } private boolean inSandbox() { return mInSandbox; } } private static class PendingSpawnQueue { // The list of pending process spawn requests and its lock. private static Queue<PendingSpawnData> sPendingSpawns = new LinkedList<PendingSpawnData>(); static final Object sPendingSpawnsLock = new Object(); /** * Queue up a spawn requests to be processed once a free service is available. * Called when a spawn is requested while we are at the capacity. */ public void enqueue(final PendingSpawnData pendingSpawn) { synchronized (sPendingSpawnsLock) { sPendingSpawns.add(pendingSpawn); } } /** * Pop the next request from the queue. Called when a free service is available. * @return the next spawn request waiting in the queue. */ public PendingSpawnData dequeue() { synchronized (sPendingSpawnsLock) { return sPendingSpawns.poll(); } } /** @return the count of pending spawns in the queue */ public int size() { synchronized (sPendingSpawnsLock) { return sPendingSpawns.size(); } } } private static final PendingSpawnQueue sPendingSpawnQueue = new PendingSpawnQueue(); // Service class for child process. As the default value it uses SandboxedProcessService0 and // PrivilegedProcessService0. private static ChildConnectionAllocator sSandboxedChildConnectionAllocator; private static ChildConnectionAllocator sPrivilegedChildConnectionAllocator; private static final String NUM_SANDBOXED_SERVICES_KEY = "org.chromium.content.browser.NUM_SANDBOXED_SERVICES"; private static final String NUM_PRIVILEGED_SERVICES_KEY = "org.chromium.content.browser.NUM_PRIVILEGED_SERVICES"; private static int getNumberOfServices(Context context, boolean inSandbox) { try { PackageManager packageManager = context.getPackageManager(); ApplicationInfo appInfo = packageManager.getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA); int numServices = appInfo.metaData.getInt(inSandbox ? NUM_SANDBOXED_SERVICES_KEY : NUM_PRIVILEGED_SERVICES_KEY); if (numServices <= 0) { throw new RuntimeException("Illegal meta data value for number of child services"); } return numServices; } catch (PackageManager.NameNotFoundException e) { throw new RuntimeException("Could not get application info"); } } private static void initConnectionAllocatorsIfNecessary(Context context) { synchronized (ChildProcessLauncher.class) { if (sSandboxedChildConnectionAllocator == null) { sSandboxedChildConnectionAllocator = new ChildConnectionAllocator(true, getNumberOfServices(context, true)); } if (sPrivilegedChildConnectionAllocator == null) { sPrivilegedChildConnectionAllocator = new ChildConnectionAllocator(false, getNumberOfServices(context, false)); } } } private static ChildConnectionAllocator getConnectionAllocator(boolean inSandbox) { return inSandbox ? sSandboxedChildConnectionAllocator : sPrivilegedChildConnectionAllocator; } private static ChildProcessConnection allocateConnection(Context context, boolean inSandbox, ChromiumLinkerParams chromiumLinkerParams) { ChildProcessConnection.DeathCallback deathCallback = new ChildProcessConnection.DeathCallback() { @Override public void onChildProcessDied(ChildProcessConnection connection) { if (connection.getPid() != 0) { stop(connection.getPid()); } else { freeConnection(connection); } } }; initConnectionAllocatorsIfNecessary(context); return getConnectionAllocator(inSandbox).allocate(context, deathCallback, chromiumLinkerParams); } private static boolean sLinkerInitialized = false; private static long sLinkerLoadAddress = 0; private static ChromiumLinkerParams getLinkerParamsForNewConnection() { if (!sLinkerInitialized) { if (Linker.isUsed()) { sLinkerLoadAddress = Linker.getBaseLoadAddress(); if (sLinkerLoadAddress == 0) { Log.i(TAG, "Shared RELRO support disabled!"); } } sLinkerInitialized = true; } if (sLinkerLoadAddress == 0) return null; // Always wait for the shared RELROs in service processes. final boolean waitForSharedRelros = true; return new ChromiumLinkerParams(sLinkerLoadAddress, waitForSharedRelros, Linker.getTestRunnerClassName()); } private static ChildProcessConnection allocateBoundConnection(Context context, String[] commandLine, boolean inSandbox) { ChromiumLinkerParams chromiumLinkerParams = getLinkerParamsForNewConnection(); ChildProcessConnection connection = allocateConnection(context, inSandbox, chromiumLinkerParams); if (connection != null) { connection.start(commandLine); } return connection; } private static final long FREE_CONNECTION_DELAY_MILLIS = 1; private static void freeConnection(ChildProcessConnection connection) { // Freeing a service should be delayed. This is so that we avoid immediately reusing the // freed service (see http://crbug.com/164069): the framework might keep a service process // alive when it's been unbound for a short time. If a new connection to the same service // is bound at that point, the process is reused and bad things happen (mostly static // variables are set when we don't expect them to). final ChildProcessConnection conn = connection; ThreadUtils.postOnUiThreadDelayed(new Runnable() { @Override public void run() { getConnectionAllocator(conn.isInSandbox()).free(conn); final PendingSpawnData pendingSpawn = sPendingSpawnQueue.dequeue(); if (pendingSpawn != null) { new Thread(new Runnable() { @Override public void run() { startInternal(pendingSpawn.context(), pendingSpawn.commandLine(), pendingSpawn.childProcessId(), pendingSpawn.filesToBeMapped(), pendingSpawn.clientContext(), pendingSpawn.callbackType(), pendingSpawn.inSandbox()); } }).start(); } } }, FREE_CONNECTION_DELAY_MILLIS); } // Represents an invalid process handle; same as base/process/process.h kNullProcessHandle. private static final int NULL_PROCESS_HANDLE = 0; // Map from pid to ChildService connection. private static Map<Integer, ChildProcessConnection> sServiceMap = new ConcurrentHashMap<Integer, ChildProcessConnection>(); // A pre-allocated and pre-bound connection ready for connection setup, or null. private static ChildProcessConnection sSpareSandboxedConnection = null; // Manages oom bindings used to bind chind services. private static BindingManager sBindingManager = BindingManagerImpl.createBindingManager(); // Map from surface id to Surface. private static Map<Integer, Surface> sViewSurfaceMap = new ConcurrentHashMap<Integer, Surface>(); // Map from surface texture id to Surface. private static Map<Pair<Integer, Integer>, Surface> sSurfaceTextureSurfaceMap = new ConcurrentHashMap<Pair<Integer, Integer>, Surface>(); @VisibleForTesting public static void setBindingManagerForTesting(BindingManager manager) { sBindingManager = manager; } /** @return true iff the child process is protected from out-of-memory killing */ @CalledByNative private static boolean isOomProtected(int pid) { return sBindingManager.isOomProtected(pid); } @CalledByNative private static void registerViewSurface(int surfaceId, Surface surface) { sViewSurfaceMap.put(surfaceId, surface); } @CalledByNative private static void unregisterViewSurface(int surfaceId) { sViewSurfaceMap.remove(surfaceId); } private static void registerSurfaceTextureSurface( int surfaceTextureId, int clientId, Surface surface) { Pair<Integer, Integer> key = new Pair<Integer, Integer>(surfaceTextureId, clientId); sSurfaceTextureSurfaceMap.put(key, surface); } private static void unregisterSurfaceTextureSurface(int surfaceTextureId, int clientId) { Pair<Integer, Integer> key = new Pair<Integer, Integer>(surfaceTextureId, clientId); Surface surface = sSurfaceTextureSurfaceMap.remove(key); if (surface == null) return; assert surface.isValid(); surface.release(); } @CalledByNative private static void createSurfaceTextureSurface( int surfaceTextureId, int clientId, SurfaceTexture surfaceTexture) { registerSurfaceTextureSurface(surfaceTextureId, clientId, new Surface(surfaceTexture)); } @CalledByNative private static void destroySurfaceTextureSurface(int surfaceTextureId, int clientId) { unregisterSurfaceTextureSurface(surfaceTextureId, clientId); } @CalledByNative private static SurfaceWrapper getSurfaceTextureSurface( int surfaceTextureId, int clientId) { Pair<Integer, Integer> key = new Pair<Integer, Integer>(surfaceTextureId, clientId); Surface surface = sSurfaceTextureSurfaceMap.get(key); if (surface == null) { Log.e(TAG, "Invalid Id for surface texture."); return null; } assert surface.isValid(); return new SurfaceWrapper(surface); } /** * Sets the visibility of the child process when it changes or when it is determined for the * first time. */ @CalledByNative public static void setInForeground(int pid, boolean inForeground) { sBindingManager.setInForeground(pid, inForeground); } /** * Called when the renderer commits a navigation. This signals a time at which it is safe to * rely on renderer visibility signalled through setInForeground. See http://crbug.com/421041. */ public static void determinedVisibility(int pid) { sBindingManager.determinedVisibility(pid); } /** * Called when the embedding application is sent to background. */ public static void onSentToBackground() { sBindingManager.onSentToBackground(); } /** * Called when the embedding application is brought to foreground. */ public static void onBroughtToForeground() { sBindingManager.onBroughtToForeground(); } /** * Should be called early in startup so the work needed to spawn the child process can be done * in parallel to other startup work. Must not be called on the UI thread. Spare connection is * created in sandboxed child process. * @param context the application context used for the connection. */ public static void warmUp(Context context) { synchronized (ChildProcessLauncher.class) { assert !ThreadUtils.runningOnUiThread(); if (sSpareSandboxedConnection == null) { sSpareSandboxedConnection = allocateBoundConnection(context, null, true); } } } private static String getSwitchValue(final String[] commandLine, String switchKey) { if (commandLine == null || switchKey == null) { return null; } // This format should be matched with the one defined in command_line.h. final String switchKeyPrefix = "--" + switchKey + "="; for (String command : commandLine) { if (command != null && command.startsWith(switchKeyPrefix)) { return command.substring(switchKeyPrefix.length()); } } return null; } /** * Spawns and connects to a child process. May be called on any thread. It will not block, but * will instead callback to {@link #nativeOnChildProcessStarted} when the connection is * established. Note this callback will not necessarily be from the same thread (currently it * always comes from the main thread). * * @param context Context used to obtain the application context. * @param commandLine The child process command line argv. * @param fileIds The ID that should be used when mapping files in the created process. * @param fileFds The file descriptors that should be mapped in the created process. * @param fileAutoClose Whether the file descriptors should be closed once they were passed to * the created process. * @param clientContext Arbitrary parameter used by the client to distinguish this connection. */ @CalledByNative static void start( Context context, final String[] commandLine, int childProcessId, int[] fileIds, int[] fileFds, boolean[] fileAutoClose, long clientContext) { assert fileIds.length == fileFds.length && fileFds.length == fileAutoClose.length; FileDescriptorInfo[] filesToBeMapped = new FileDescriptorInfo[fileFds.length]; for (int i = 0; i < fileFds.length; i++) { filesToBeMapped[i] = new FileDescriptorInfo(fileIds[i], fileFds[i], fileAutoClose[i]); } assert clientContext != 0; int callbackType = CALLBACK_FOR_UNKNOWN_PROCESS; boolean inSandbox = true; String processType = getSwitchValue(commandLine, SWITCH_PROCESS_TYPE); if (SWITCH_RENDERER_PROCESS.equals(processType)) { callbackType = CALLBACK_FOR_RENDERER_PROCESS; } else if (SWITCH_GPU_PROCESS.equals(processType)) { callbackType = CALLBACK_FOR_GPU_PROCESS; inSandbox = false; } else if (SWITCH_UTILITY_PROCESS.equals(processType)) { // We only support sandboxed right now. callbackType = CALLBACK_FOR_UTILITY_PROCESS; } else { assert false; } startInternal(context, commandLine, childProcessId, filesToBeMapped, clientContext, callbackType, inSandbox); } private static void startInternal( Context context, final String[] commandLine, int childProcessId, FileDescriptorInfo[] filesToBeMapped, long clientContext, int callbackType, boolean inSandbox) { try { TraceEvent.begin("ChildProcessLauncher.startInternal"); ChildProcessConnection allocatedConnection = null; synchronized (ChildProcessLauncher.class) { if (inSandbox) { allocatedConnection = sSpareSandboxedConnection; sSpareSandboxedConnection = null; } } if (allocatedConnection == null) { allocatedConnection = allocateBoundConnection(context, commandLine, inSandbox); if (allocatedConnection == null) { Log.d(TAG, "Allocation of new service failed. Queuing up pending spawn."); sPendingSpawnQueue.enqueue(new PendingSpawnData(context, commandLine, childProcessId, filesToBeMapped, clientContext, callbackType, inSandbox)); return; } } Log.d(TAG, "Setting up connection to process: slot=" + allocatedConnection.getServiceNumber()); triggerConnectionSetup(allocatedConnection, commandLine, childProcessId, filesToBeMapped, callbackType, clientContext); } finally { TraceEvent.end("ChildProcessLauncher.startInternal"); } } @VisibleForTesting static void triggerConnectionSetup( final ChildProcessConnection connection, String[] commandLine, int childProcessId, FileDescriptorInfo[] filesToBeMapped, int callbackType, final long clientContext) { ChildProcessConnection.ConnectionCallback connectionCallback = new ChildProcessConnection.ConnectionCallback() { @Override public void onConnected(int pid) { Log.d(TAG, "on connect callback, pid=" + pid + " context=" + clientContext); if (pid != NULL_PROCESS_HANDLE) { sBindingManager.addNewConnection(pid, connection); sServiceMap.put(pid, connection); } // If the connection fails and pid == 0, the Java-side cleanup was already // handled by DeathCallback. We still have to call back to native for // cleanup there. if (clientContext != 0) { // Will be 0 in Java instrumentation tests. nativeOnChildProcessStarted(clientContext, pid); } } }; assert callbackType != CALLBACK_FOR_UNKNOWN_PROCESS; connection.setupConnection(commandLine, filesToBeMapped, createCallback(childProcessId, callbackType), connectionCallback, Linker.getSharedRelros()); } /** * Terminates a child process. This may be called from any thread. * * @param pid The pid (process handle) of the service connection obtained from {@link #start}. */ @CalledByNative static void stop(int pid) { Log.d(TAG, "stopping child connection: pid=" + pid); ChildProcessConnection connection = sServiceMap.remove(pid); if (connection == null) { logPidWarning(pid, "Tried to stop non-existent connection"); return; } sBindingManager.clearConnection(pid); connection.stop(); freeConnection(connection); } /** * This implementation is used to receive callbacks from the remote service. */ private static IChildProcessCallback createCallback( final int childProcessId, final int callbackType) { return new IChildProcessCallback.Stub() { /** * This is called by the remote service regularly to tell us about new values. Note that * IPC calls are dispatched through a thread pool running in each process, so the code * executing here will NOT be running in our main thread -- so, to update the UI, we * need to use a Handler. */ @Override public void establishSurfacePeer( int pid, Surface surface, int primaryID, int secondaryID) { // Do not allow a malicious renderer to connect to a producer. This is only used // from stream textures managed by the GPU process. if (callbackType != CALLBACK_FOR_GPU_PROCESS) { Log.e(TAG, "Illegal callback for non-GPU process."); return; } nativeEstablishSurfacePeer(pid, surface, primaryID, secondaryID); } @Override public SurfaceWrapper getViewSurface(int surfaceId) { // Do not allow a malicious renderer to get to our view surface. if (callbackType != CALLBACK_FOR_GPU_PROCESS) { Log.e(TAG, "Illegal callback for non-GPU process."); return null; } Surface surface = sViewSurfaceMap.get(surfaceId); if (surface == null) { Log.e(TAG, "Invalid surfaceId."); return null; } assert surface.isValid(); return new SurfaceWrapper(surface); } @Override public void registerSurfaceTextureSurface( int surfaceTextureId, int clientId, Surface surface) { if (callbackType != CALLBACK_FOR_GPU_PROCESS) { Log.e(TAG, "Illegal callback for non-GPU process."); return; } ChildProcessLauncher.registerSurfaceTextureSurface(surfaceTextureId, clientId, surface); } @Override public void unregisterSurfaceTextureSurface( int surfaceTextureId, int clientId) { if (callbackType != CALLBACK_FOR_GPU_PROCESS) { Log.e(TAG, "Illegal callback for non-GPU process."); return; } ChildProcessLauncher.unregisterSurfaceTextureSurface(surfaceTextureId, clientId); } @Override public SurfaceWrapper getSurfaceTextureSurface(int surfaceTextureId) { if (callbackType != CALLBACK_FOR_RENDERER_PROCESS) { Log.e(TAG, "Illegal callback for non-renderer process."); return null; } return ChildProcessLauncher.getSurfaceTextureSurface(surfaceTextureId, childProcessId); } }; } static void logPidWarning(int pid, String message) { // This class is effectively a no-op in single process mode, so don't log warnings there. if (pid > 0 && !nativeIsSingleProcess()) { Log.w(TAG, message + ", pid=" + pid); } } @VisibleForTesting static ChildProcessConnection allocateBoundConnectionForTesting(Context context) { return allocateBoundConnection(context, null, true); } /** * Queue up a spawn requests for testing. */ @VisibleForTesting static void enqueuePendingSpawnForTesting(Context context) { sPendingSpawnQueue.enqueue(new PendingSpawnData(context, new String[0], 1, new FileDescriptorInfo[0], 0, CALLBACK_FOR_RENDERER_PROCESS, true)); } /** @return the count of sandboxed connections managed by the allocator */ @VisibleForTesting static int allocatedConnectionsCountForTesting(Context context) { initConnectionAllocatorsIfNecessary(context); return sSandboxedChildConnectionAllocator.allocatedConnectionsCountForTesting(); } /** @return the count of services set up and working */ @VisibleForTesting static int connectedServicesCountForTesting() { return sServiceMap.size(); } /** @return the count of pending spawns in the queue */ @VisibleForTesting static int pendingSpawnsCountForTesting() { return sPendingSpawnQueue.size(); } /** * Kills the child process for testing. * @return true iff the process was killed as expected */ @VisibleForTesting public static boolean crashProcessForTesting(int pid) { if (sServiceMap.get(pid) == null) return false; try { ((ChildProcessConnectionImpl) sServiceMap.get(pid)).crashServiceForTesting(); } catch (RemoteException ex) { return false; } return true; } private static native void nativeOnChildProcessStarted(long clientContext, int pid); private static native void nativeEstablishSurfacePeer( int pid, Surface surface, int primaryID, int secondaryID); private static native boolean nativeIsSingleProcess(); }
9234b72135a7bda55f85469aa999cffbafdf8f86
73
java
Java
src/main/java/com/mx/skeleton/web/controller/config/Acciones.java
iammiguelmx/skeleton-api-spring
4e7b4e958ae447e31d9a938a372d2ea795f403c8
[ "MIT" ]
null
null
null
src/main/java/com/mx/skeleton/web/controller/config/Acciones.java
iammiguelmx/skeleton-api-spring
4e7b4e958ae447e31d9a938a372d2ea795f403c8
[ "MIT" ]
1
2021-07-26T01:29:32.000Z
2021-07-26T01:29:32.000Z
src/main/java/com/mx/skeleton/web/controller/config/Acciones.java
iammiguelmx/skeleton-api-spring
4e7b4e958ae447e31d9a938a372d2ea795f403c8
[ "MIT" ]
null
null
null
14.6
46
0.780822
997,026
package com.mx.skeleton.web.controller.config; public enum Acciones { }
9234b776316ec0dbe394732be8bf2f45e9521c44
2,221
java
Java
backend/src/main/java/com/bakdata/conquery/models/auth/develop/DefaultInitialUserRealm.java
manuel-hegner/conquery
94d7915e56e10187dd1c8298df962875d3f7a897
[ "MIT" ]
29
2018-01-18T10:46:11.000Z
2022-02-15T00:27:29.000Z
backend/src/main/java/com/bakdata/conquery/models/auth/develop/DefaultInitialUserRealm.java
bakdata/conquery
94f44e9e42508d8b27884621f27395603a755f79
[ "MIT" ]
818
2018-01-18T12:00:05.000Z
2022-03-29T09:14:22.000Z
backend/src/main/java/com/bakdata/conquery/models/auth/develop/DefaultInitialUserRealm.java
manuel-hegner/conquery
94d7915e56e10187dd1c8298df962875d3f7a897
[ "MIT" ]
11
2018-10-22T22:20:42.000Z
2021-08-11T14:46:42.000Z
38.293103
129
0.680774
997,027
package com.bakdata.conquery.models.auth.develop; import com.bakdata.conquery.models.config.auth.AuthorizationConfig; import com.bakdata.conquery.models.auth.ConqueryAuthenticationInfo; import com.bakdata.conquery.models.auth.ConqueryAuthenticationRealm; import com.bakdata.conquery.models.auth.util.SkippingCredentialsMatcher; import com.bakdata.conquery.models.identifiable.ids.specific.UserId; import lombok.extern.slf4j.Slf4j; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationToken; /** * This realm authenticates requests as if they are effected by the first * initial user, that is found in the {@link AuthorizationConfig}, when no * identifying information was found in the request. If the realm was able to * parse a {@link UserId} from a request, it submits this id in an * {@link AuthenticationToken}. * */ @Slf4j public class DefaultInitialUserRealm extends ConqueryAuthenticationRealm { /** * The warning that is displayed, when the realm is instantiated. */ private static final String WARNING = "\n" + " §§\n" + " § §\n" + " § §\n" + " § §\n" + " § §§§§ § You instantiated and are probably using a Shiro realm\n" + " § §§§§ § that does not do any permission checks or authentication.\n" + " § §§ § Access to all resources is granted to everyone.\n" + " § §§ § DO NOT USE THIS REALM IN PRODUCTION\n" + " $ §\n" + " § §§ §\n" + " § §\n" + " §§§§§§§§§§§§§§§§§§§§§§"; /** * Standard constructor. */ public DefaultInitialUserRealm() { log.warn(WARNING); this.setAuthenticationTokenClass(DevelopmentToken.class); this.setCredentialsMatcher(SkippingCredentialsMatcher.INSTANCE); } @Override protected ConqueryAuthenticationInfo doGetConqueryAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { if (!(token instanceof DevelopmentToken)) { return null; } DevelopmentToken devToken = (DevelopmentToken) token; return new ConqueryAuthenticationInfo(devToken.getPrincipal(), devToken.getCredentials(), this, true); } }
9234b79ec7e8c93cf1f5a96bbca3874ca9e6c4d7
2,488
java
Java
taier-data-develop/src/main/java/com/dtstack/taier/develop/service/template/sqlserver/SqlServerCdcReaderParam.java
vainhope/Taier
58938f6c5844be43a0919adbd130139aed3c0491
[ "ECL-2.0", "Apache-2.0" ]
227
2022-02-18T14:47:24.000Z
2022-03-31T11:00:47.000Z
taier-data-develop/src/main/java/com/dtstack/taier/develop/service/template/sqlserver/SqlServerCdcReaderParam.java
vainhope/Taier
58938f6c5844be43a0919adbd130139aed3c0491
[ "ECL-2.0", "Apache-2.0" ]
89
2022-02-18T10:05:01.000Z
2022-03-31T06:16:28.000Z
taier-data-develop/src/main/java/com/dtstack/taier/develop/service/template/sqlserver/SqlServerCdcReaderParam.java
vainhope/Taier
58938f6c5844be43a0919adbd130139aed3c0491
[ "ECL-2.0", "Apache-2.0" ]
67
2022-02-20T06:17:28.000Z
2022-03-29T10:09:35.000Z
18.294118
73
0.614148
997,028
package com.dtstack.taier.develop.service.template.sqlserver; import com.dtstack.taier.develop.service.template.DaPluginParam; import java.util.List; import java.util.Map; /** * Date: 2020/2/20 * Company: www.dtstack.com * * @author xiaochen */ public class SqlServerCdcReaderParam extends DaPluginParam { /** * 0从任务运行时开始 * 1按时间选择 * 2按文件选择 * 3用户手动输入 */ private Integer collectType; /** * 分组分表 */ private Map<String, Object> distributeTable; /** * 监听操作类型 * DAoperators数组 */ private List<Integer> cat; /** * 嵌套JSON平铺 */ private Boolean pavingData; /** * 手动输入的lsn */ private String lsn; private String schema; private Boolean allTable; private List<String> table; private Integer rdbmsDaType; private Long pollInterval; public Integer getCollectType() { return collectType; } public void setCollectType(Integer collectType) { this.collectType = collectType; } public Map<String, Object> getDistributeTable() { return distributeTable; } public void setDistributeTable(Map<String, Object> distributeTable) { this.distributeTable = distributeTable; } public List<Integer> getCat() { return cat; } public void setCat(List<Integer> cat) { this.cat = cat; } public Boolean getPavingData() { return pavingData; } public void setPavingData(Boolean pavingData) { this.pavingData = pavingData; } public String getLsn() { return lsn; } public void setLsn(String lsn) { this.lsn = lsn; } public String getSchema() { return schema; } public void setSchema(String schema) { this.schema = schema; } public Boolean getAllTable() { return allTable; } public void setAllTable(Boolean allTable) { this.allTable = allTable; } public List<String> getTable() { return table; } public void setTable(List<String> table) { this.table = table; } public Integer getRdbmsDaType() { return rdbmsDaType; } public void setRdbmsDaType(Integer rdbmsDaType) { this.rdbmsDaType = rdbmsDaType; } public Long getPollInterval() { return pollInterval; } public void setPollInterval(Long pollInterval) { this.pollInterval = pollInterval; } }
9234b7d451e5f28ddb9e9920e9e50e9efba3e9bf
4,947
java
Java
llap-common/src/java/org/apache/hadoop/hive/llap/impl/LlapProtocolClientImpl.java
TencentEMapReduce/EMR131-Hive
70d741709a3af706b5ca764268c37ab8ca9da5d5
[ "Apache-2.0" ]
30
2016-05-14T06:44:39.000Z
2021-02-25T06:40:12.000Z
llap-common/src/java/org/apache/hadoop/hive/llap/impl/LlapProtocolClientImpl.java
TencentEMapReduce/EMR131-Hive
70d741709a3af706b5ca764268c37ab8ca9da5d5
[ "Apache-2.0" ]
2
2015-07-30T12:21:06.000Z
2015-08-17T06:13:36.000Z
llap-common/src/java/org/apache/hadoop/hive/llap/impl/LlapProtocolClientImpl.java
TencentEMapReduce/EMR131-Hive
70d741709a3af706b5ca764268c37ab8ca9da5d5
[ "Apache-2.0" ]
49
2016-09-05T03:09:53.000Z
2022-03-18T08:10:38.000Z
39.261905
171
0.739438
997,029
/* * 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.apache.hadoop.hive.llap.impl; import javax.annotation.Nullable; import javax.net.SocketFactory; import java.io.IOException; import java.net.InetSocketAddress; import com.google.protobuf.RpcController; import com.google.protobuf.ServiceException; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hive.llap.daemon.rpc.LlapDaemonProtocolProtos.QueryCompleteRequestProto; import org.apache.hadoop.hive.llap.daemon.rpc.LlapDaemonProtocolProtos.QueryCompleteResponseProto; import org.apache.hadoop.hive.llap.daemon.rpc.LlapDaemonProtocolProtos.SourceStateUpdatedRequestProto; import org.apache.hadoop.hive.llap.daemon.rpc.LlapDaemonProtocolProtos.SourceStateUpdatedResponseProto; import org.apache.hadoop.hive.llap.daemon.rpc.LlapDaemonProtocolProtos.SubmitWorkRequestProto; import org.apache.hadoop.hive.llap.daemon.rpc.LlapDaemonProtocolProtos.SubmitWorkResponseProto; import org.apache.hadoop.hive.llap.daemon.rpc.LlapDaemonProtocolProtos.TerminateFragmentRequestProto; import org.apache.hadoop.hive.llap.daemon.rpc.LlapDaemonProtocolProtos.TerminateFragmentResponseProto; import org.apache.hadoop.io.retry.RetryPolicy; import org.apache.hadoop.ipc.ProtobufRpcEngine; import org.apache.hadoop.ipc.ProtocolProxy; import org.apache.hadoop.ipc.RPC; import org.apache.hadoop.net.NetUtils; import org.apache.hadoop.hive.llap.protocol.LlapProtocolBlockingPB; import org.apache.hadoop.security.UserGroupInformation; // TODO Change all this to be based on a regular interface instead of relying on the Proto service - Exception signatures cannot be controlled without this for the moment. public class LlapProtocolClientImpl implements LlapProtocolBlockingPB { private final Configuration conf; private final InetSocketAddress serverAddr; private final RetryPolicy retryPolicy; private final SocketFactory socketFactory; LlapProtocolBlockingPB proxy; public LlapProtocolClientImpl(Configuration conf, String hostname, int port, @Nullable RetryPolicy retryPolicy, @Nullable SocketFactory socketFactory) { this.conf = conf; this.serverAddr = NetUtils.createSocketAddr(hostname, port); this.retryPolicy = retryPolicy; if (socketFactory == null) { this.socketFactory = NetUtils.getDefaultSocketFactory(conf); } else { this.socketFactory = socketFactory; } } @Override public SubmitWorkResponseProto submitWork(RpcController controller, SubmitWorkRequestProto request) throws ServiceException { try { return getProxy().submitWork(null, request); } catch (IOException e) { throw new ServiceException(e); } } @Override public SourceStateUpdatedResponseProto sourceStateUpdated(RpcController controller, SourceStateUpdatedRequestProto request) throws ServiceException { try { return getProxy().sourceStateUpdated(null, request); } catch (IOException e) { throw new ServiceException(e); } } @Override public QueryCompleteResponseProto queryComplete(RpcController controller, QueryCompleteRequestProto request) throws ServiceException { try { return getProxy().queryComplete(null, request); } catch (IOException e) { throw new ServiceException(e); } } @Override public TerminateFragmentResponseProto terminateFragment( RpcController controller, TerminateFragmentRequestProto request) throws ServiceException { try { return getProxy().terminateFragment(null, request); } catch (IOException e) { throw new ServiceException(e); } } public LlapProtocolBlockingPB getProxy() throws IOException { if (proxy == null) { proxy = createProxy(); } return proxy; } public LlapProtocolBlockingPB createProxy() throws IOException { RPC.setProtocolEngine(conf, LlapProtocolBlockingPB.class, ProtobufRpcEngine.class); ProtocolProxy<LlapProtocolBlockingPB> proxy = RPC.getProtocolProxy(LlapProtocolBlockingPB.class, 0, serverAddr, UserGroupInformation.getCurrentUser(), conf, NetUtils.getDefaultSocketFactory(conf), 0, retryPolicy); return proxy.getProxy(); } }
9234b98d94d4f1a222aa9bf3d97490b36c35597e
5,777
java
Java
KthSmallestWithOnly3_5_7AsFactors.java
byegates/Algos
bc5a448821dc900a91f48e15df8fe1aaa071fc38
[ "MIT" ]
3
2022-03-17T22:18:34.000Z
2022-03-20T06:38:17.000Z
KthSmallestWithOnly3_5_7AsFactors.java
byegates/Algorithms
f5e6360c7401627e23f2d25a86c9fe1eea74c3bd
[ "MIT" ]
null
null
null
KthSmallestWithOnly3_5_7AsFactors.java
byegates/Algorithms
f5e6360c7401627e23f2d25a86c9fe1eea74c3bd
[ "MIT" ]
null
null
null
32.273743
131
0.499394
997,030
/* Find the Kth the smallest number s such that s = 3 ^ x * 5 ^ y * 7 ^ z, x > 0 and y > 0 and z > 0, x, y, z are all integers. Assumptions K >= 1 Examples the smallest is 3 * 5 * 7 = 105 the 2nd smallest is 3 ^ 2 * 5 * 7 = 315 the 3rd smallest is 3 * 5 ^ 2 * 7 = 525 the 5th smallest is 3 ^ 3 * 5 * 7 = 945 */ import org.jetbrains.annotations.NotNull; import java.util.*; public class KthSmallestWithOnly3_5_7AsFactors { static class Helper implements Comparable<Helper>{ public Long val; int i, j, k; public Helper(Long val, int i, int j, int k) { this.val = val; this.i = i; this.j = j; this.k = k; } public Helper next(int e) { Helper next = cloneHelper(); switch (e) { case 3: next.i++;break; case 5: next.j++;break; case 7: next.k++;break; default: ; } next.val *= e; return next; } public Helper cloneHelper() { return new Helper(val, i, j, k); } @Override public int compareTo(@NotNull KthSmallestWithOnly3_5_7AsFactors.Helper o) { return Long.compare(this.val, o.val); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Helper helper = (Helper) o; return val.equals(helper.val); } @Override public int hashCode() { return Objects.hash(val); } public String toString() { return String.format("%5d(%d, %d, %d)", val, i, j, k); } } public void kthHelper(int k) { PriorityQueue<Helper> pq = new PriorityQueue<>(k); Set<Helper> set = new HashSet<>(); Helper cur = new Helper(3 * 5 * 7L, 1, 1, 1); pq.offer(cur); set.add(cur); for (;k > 1 && !pq.isEmpty(); k--) { // each round we poll 1 and add max 3 cur = pq.poll(); System.out.println(cur); for (int val : new int[]{3, 5, 7}) enQHelper(pq, set, cur, val); } //return pq.isEmpty() ? cur : pq.peek(); } private void enQHelper(PriorityQueue<Helper> pq, Set<Helper> set, Helper cur, int val) { Helper next = cur.next(val); if (set.add(next)) pq.offer(next); } public long kth(int k) { PriorityQueue<Long> pq = new PriorityQueue<>(k); Set<Long> set = new HashSet<>(); long cur = 3 * 5 * 7; pq.offer(cur); set.add(cur); for (;k > 1 && !pq.isEmpty(); k--) { // each round we poll 1 and add max 3 cur = pq.poll(); for (int val : new int[]{3, 5, 7}) enQ(pq, set, val * cur); } return pq.isEmpty() ? cur : pq.peek(); } private void enQ(PriorityQueue<Long> pq, Set<Long> set, long val) { if (set.add(val)) pq.offer(val); } public long kth2(int k) { // SC: O(k), SC: O(k) long res = 3 * 5 * 7; Deque<Long> dq3 = new ArrayDeque<>(); Deque<Long> dq5 = new ArrayDeque<>(); Deque<Long> dq7 = new ArrayDeque<>(); offer(res, dq3, dq5, dq7); while (k-- > 1 && !dq3.isEmpty() && !dq5.isEmpty() && !dq7.isEmpty()) { // add non-empty check only to mitigate IDE warning if (dq3.peekFirst() < dq5.peekFirst() && dq3.peekFirst() < dq7.peekFirst()) { res = dq3.pollFirst(); offer(res, dq3, dq5, dq7); } else if (dq5.peekFirst() < dq3.peekFirst() && dq5.peekFirst() < dq7.peekFirst()) { res = dq5.pollFirst(); offer(res, null, dq5, dq7); } else { res = dq7.pollFirst(); dq7.offerLast(res * 7); } } return res; } private void offer(long res, Deque<Long> dq3, Deque<Long> dq5, Deque<Long> dq7) { if (dq3 != null) dq3.offerLast(res * 3); if (dq5 != null) dq5.offerLast(res * 5); dq7.offerLast(res * 7); } public void kth2b(int k) { // SC: O(k), SC: O(k) Helper cur = new Helper(3 * 5 * 7L, 1, 1, 1); Deque<Helper> dq3 = new ArrayDeque<>(); Deque<Helper> dq5 = new ArrayDeque<>(); Deque<Helper> dq7 = new ArrayDeque<>(); offerHelper(cur, dq3, dq5, dq7); while (k-- > 1 && !dq3.isEmpty() && !dq5.isEmpty() && !dq7.isEmpty()) { // add non-empty check only to mitigate IDE warning if (dq3.peekFirst().val < dq5.peekFirst().val && dq3.peekFirst().val < dq7.peekFirst().val) { cur = dq3.pollFirst(); offerHelper(cur, dq3, dq5, dq7); } else if (dq5.peekFirst().val < dq3.peekFirst().val && dq5.peekFirst().val < dq7.peekFirst().val) { cur = dq5.pollFirst(); offerHelper(cur, null, dq5, dq7); } else { cur = dq7.pollFirst(); dq7.offerLast(cur.next(7)); } } } private void offerHelper(Helper cur, Deque<Helper> dq3, Deque<Helper> dq5, Deque<Helper> dq7) { if (dq3 != null) dq3.offerLast(cur.next(3)); if (dq5 != null) dq5.offerLast(cur.next(5)); dq7.offerLast(cur.next(7)); } public static void main(String[] args) { KthSmallestWithOnly3_5_7AsFactors k357 = new KthSmallestWithOnly3_5_7AsFactors(); int k = 20; System.out.println(k357.kth(k) + " vs " + k357.kth2(k)); k357.kthHelper(k); System.out.println(); k357.kth2b(k); } }
9234ba9d91bdf30375bd843f4ec225d4811dbc10
28,886
java
Java
app/src/main/java/com/yuenov/open/widget/DetailOperationView.java
yuenov/reader-android
ad18e934dafd4fb249092d72ab0f18f1681c242f
[ "MIT" ]
133
2020-05-28T03:25:32.000Z
2022-03-24T16:49:03.000Z
app/src/main/java/com/yuenov/open/widget/DetailOperationView.java
mohsinalimat/reader-android
ad18e934dafd4fb249092d72ab0f18f1681c242f
[ "MIT" ]
5
2020-06-04T07:54:01.000Z
2021-02-22T06:51:54.000Z
app/src/main/java/com/yuenov/open/widget/DetailOperationView.java
mohsinalimat/reader-android
ad18e934dafd4fb249092d72ab0f18f1681c242f
[ "MIT" ]
66
2020-06-04T06:55:30.000Z
2022-03-31T10:20:00.000Z
35.573892
183
0.644049
997,031
package com.yuenov.open.widget; import android.content.Context; import android.os.Handler; import android.os.Message; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.SeekBar; import android.widget.TextView; import androidx.annotation.Nullable; import com.yuenov.open.R; import com.yuenov.open.activitys.baseInfo.BaseActivity; import com.yuenov.open.adapters.BookDetailBottomMenuListAdapter; import com.yuenov.open.constant.ConstantSetting; import com.yuenov.open.database.AppDatabase; import com.yuenov.open.database.tb.TbBookChapter; import com.yuenov.open.database.tb.TbReadHistory; import com.yuenov.open.model.standard.ReadSettingInfo; import com.yuenov.open.utils.EditSharedPreferences; import com.yuenov.open.utils.Utility; import com.yuenov.open.utils.UtilityBrightness; import com.yuenov.open.utils.UtilityException; import com.yuenov.open.utils.UtilityMeasure; import com.yuenov.open.utils.UtilityReadInfo; import com.yuenov.open.widget.page.PageMode; import com.renrui.libraries.util.LibUtility; import com.renrui.libraries.util.Logger; import com.renrui.libraries.util.UtilitySecurity; import com.renrui.libraries.util.UtilitySecurityListener; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; public class DetailOperationView extends LinearLayout implements View.OnClickListener, LightView.ILightViewListener, SeekBar.OnSeekBarChangeListener, AdapterView.OnItemClickListener { public interface IDetailOperationView { void onDetailOperationViewChange(ReadSettingInfo newData); /** * 选中某章 */ void onSelectChapter(TbBookChapter chapter); } private BaseActivity activity; @BindView(R.id.rlWgDpMenuList) protected RelativeLayout rlWgDpMenuList; @BindView(R.id.viewWgDpMenuListClose) protected View viewWgDpMenuListClose; @BindView(R.id.llWgDpMenuListData) protected LinearLayout llWgDpMenuListData; @BindView(R.id.tvWgDpMenuListTitle) protected TextView tvWgDpMenuListTitle; @BindView(R.id.rlWgDpMenuListOrder) protected RelativeLayout rlWgDpMenuListOrder; @BindView(R.id.ivWgDpMenuListOrder) protected ImageView ivWgDpMenuListOrder; @BindView(R.id.lvWgDpMenuList) protected MyListView lvWgDpMenuList; @BindView(R.id.llWgDpMenu) protected LinearLayout llWgDpMenu; @BindView(R.id.ivWgDpMenu) protected ImageView ivWgDpMenu; @BindView(R.id.llWgDpProcessContent) protected LinearLayout llWgDpProcessContent; @BindView(R.id.tvWgDpProcessTitle) protected TextView tvWgDpProcessTitle; @BindView(R.id.skWgDpProcess) protected SeekBar skWgDpProcess; @BindView(R.id.llWgDpProcess) protected LinearLayout llWgDpProcess; @BindView(R.id.ivWgDpProcess) protected ImageView ivWgDpProcess; @BindView(R.id.llWgDpLightContent) protected LinearLayout llWgDpLightContent; @BindView(R.id.skWgDpLight) protected SeekBar skWgDpLight; @BindView(R.id.lvWgDpLight1) protected LightView lvWgDpLight1; @BindView(R.id.lvWgDpLight2) protected LightView lvWgDpLight2; @BindView(R.id.lvWgDpLight3) protected LightView lvWgDpLight3; @BindView(R.id.lvWgDpLight4) protected LightView lvWgDpLight4; @BindView(R.id.lvWgDpLight5) protected LightView lvWgDpLight5; @BindView(R.id.llWgDpLight) protected LinearLayout llWgDpLight; @BindView(R.id.ivWgDpLight) protected ImageView ivWgDpLight; @BindView(R.id.llWgDpFrontContent) protected LinearLayout llWgDpFrontContent; @BindView(R.id.skWgDpFront) protected SeekBar skWgDpFront; @BindView(R.id.tvWgDpAnim1) protected TextView tvWgDpAnim1; @BindView(R.id.tvWgDpAnim2) protected TextView tvWgDpAnim2; @BindView(R.id.tvWgDpAnim3) protected TextView tvWgDpAnim3; @BindView(R.id.tvWgDpAnim4) protected TextView tvWgDpAnim4; @BindView(R.id.llWgDpFront) protected LinearLayout llWgDpFront; @BindView(R.id.ivWgDpFront) protected ImageView ivWgDpFront; private String title; private int bookId; private boolean menuListOrderAsc = true; private Thread thread; private IDetailOperationView listener; private List<TbBookChapter> lisMenuList; private BookDetailBottomMenuListAdapter menuListAdapter; private int hmWhat_loadMenuList = 1; private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == hmWhat_loadMenuList) { loadMenuList(); } } }; public void setActivity(BaseActivity activity) { this.activity = activity; } public DetailOperationView(Context context) { super(context); init(); } public DetailOperationView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); init(); } public DetailOperationView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); } public void setData(String title, int bookId) { this.title = title; this.bookId = bookId; // 最后目录 UtilitySecurity.setText(tvWgDpMenuListTitle, title); // 初始化目录列表 initMenuList(); resetReadInfo(); initListener(); } public void setListener(IDetailOperationView listener) { this.listener = listener; } private void init() { initLayout(); // initListener(); } private void initLayout() { LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); LayoutParams layoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); View viewContent = inflater.inflate(R.layout.view_widget_detailoperation, null); ButterKnife.bind(this, viewContent); this.addView(viewContent, layoutParams); } private void initListener() { UtilitySecurityListener.setOnClickListener(this, viewWgDpMenuListClose, rlWgDpMenuListOrder); UtilitySecurityListener.setOnItemClickListener(lvWgDpMenuList, this); UtilitySecurityListener.setOnClickListener(this, llWgDpMenu, llWgDpProcess, llWgDpLight, llWgDpFront); skWgDpProcess.setOnSeekBarChangeListener(this); lvWgDpLight1.setListener(this); lvWgDpLight2.setListener(this); lvWgDpLight3.setListener(this); lvWgDpLight4.setListener(this); lvWgDpLight5.setListener(this); UtilitySecurityListener.setOnClickListener(this, tvWgDpAnim1, tvWgDpAnim2, tvWgDpAnim3, tvWgDpAnim4); // 加大进度条可点击区域 Utility.addSeekBarTouchPoint(skWgDpLight); Utility.addSeekBarTouchPoint(skWgDpFront); } /** * 目录列表 */ public void initMenuList() { try { lvWgDpMenuList.setMaxHeight(LibUtility.getScreenHeight() - Utility.dip2px(165)); if (thread != null && thread.getState() == Thread.State.RUNNABLE) { return; } if (lisMenuList != null) lisMenuList.clear(); thread = new Thread() { @Override public void run() { lisMenuList = AppDatabase.getInstance().ChapterDao().getChapterListByBookIdOrderByAsc(bookId); mHandler.sendEmptyMessage(hmWhat_loadMenuList); } }; thread.start(); } catch (Exception ex) { UtilityException.catchException(ex); } } private void loadMenuList() { if (UtilitySecurity.isEmpty(lisMenuList)) return; try { menuListAdapter = new BookDetailBottomMenuListAdapter(lisMenuList); lvWgDpMenuList.setAdapter(menuListAdapter); } catch (Exception ex) { UtilityException.catchException(ex); } } /** * 排序目录列表 */ private void sortMenuList(boolean orderAsc) { UtilitySecurity.setImageResource(ivWgDpMenuListOrder, orderAsc ? R.mipmap.ic_book_down : R.mipmap.ic_book_up); menuListAdapter.setOrderByAes(orderAsc); UtilitySecurityListener.setOnClickListener(rlWgDpMenuListOrder, null); menuListAdapter.notifyDataSetChanged(); lvWgDpMenuList.post(new Runnable() { @Override public void run() { UtilitySecurityListener.setOnClickListener(rlWgDpMenuListOrder, DetailOperationView.this); if (!UtilitySecurity.isEmpty(lisMenuList)) lvWgDpMenuList.setSelection(0); } }); } private void resetReadInfo() { try { skWgDpProcess.setOnSeekBarChangeListener(null); skWgDpLight.setOnSeekBarChangeListener(null); skWgDpFront.setOnSeekBarChangeListener(null); // 由于本地章节列表可能会变更,所以阅读章节 放在点击目录的时候初始化 // 亮度 if (UtilityReadInfo.getReadSettingInfo().lightValue < 1) { int value = UtilityBrightness.getScreenBrightness(getContext()); skWgDpLight.setProgress(value); } else { skWgDpLight.setProgress(UtilityReadInfo.getReadSettingInfo().lightValue); } switch (UtilityReadInfo.getReadSettingInfo().lightType) { case 1: lvWgDpLight1.setSelect(true); break; case 2: lvWgDpLight2.setSelect(true); break; case 3: lvWgDpLight3.setSelect(true); break; case 4: lvWgDpLight4.setSelect(true); break; case 5: lvWgDpLight5.setSelect(true); break; } // 字体 skWgDpFront.setMax(ConstantSetting.MAX_FRONT); int defaultFrontSize = (int) (UtilityReadInfo.getReadSettingInfo().frontSize - ConstantSetting.frontSize) / 2; skWgDpFront.setProgress(defaultFrontSize); // 动画 if (UtilityReadInfo.getReadSettingInfo().pageAnimType == PageMode.SIMULATION) { selectAnim1(); } else if (UtilityReadInfo.getReadSettingInfo().pageAnimType == PageMode.COVER) { selectAnim2(); } else if (UtilityReadInfo.getReadSettingInfo().pageAnimType == PageMode.SCROLL) { selectAnim3(); } else if (UtilityReadInfo.getReadSettingInfo().pageAnimType == PageMode.NONE) { selectAnim4(); } skWgDpProcess.setOnSeekBarChangeListener(this); skWgDpLight.setOnSeekBarChangeListener(this); skWgDpFront.setOnSeekBarChangeListener(this); } catch (Exception ex) { UtilityException.catchException(ex); } } private int getPositionByChapterId(long chapterId) { int position = 0; try { for (int i = 0; i < lisMenuList.size(); i++) { if (lisMenuList.get(i).chapterId == chapterId) { position = i; break; } } } catch (Exception ex) { UtilityException.catchException(ex); } return position; } private void showMenu() { if (UtilitySecurity.isEmpty(lisMenuList)) return; // 如果有阅读记录,定位到最后阅读记录 TbReadHistory readHistory = AppDatabase.getInstance().ReadHistoryDao().getEntity(bookId); if (readHistory != null) { int lastReadChapterIdPosition = getPositionByChapterId(readHistory.chapterId); lastReadChapterIdPosition = getMenuListPosition(lastReadChapterIdPosition); lvWgDpMenuList.setSelection(lastReadChapterIdPosition); } UtilitySecurity.resetVisibility(llWgDpProcessContent, false); UtilitySecurity.setImageResource(ivWgDpProcess, R.mipmap.ic_book_progress_unselect); UtilitySecurity.resetVisibility(llWgDpLightContent, false); UtilitySecurity.setImageResource(ivWgDpLight, R.mipmap.ic_book_light_unselect); UtilitySecurity.resetVisibility(llWgDpFrontContent, false); UtilitySecurity.setImageResource(ivWgDpFront, R.mipmap.ic_book_set_unselect); UtilitySecurity.setImageResource(ivWgDpMenu, R.mipmap.ic_book_menu_select); showAnimation(R.anim.anim_fade_in, rlWgDpMenuList); showAnimation(R.anim.anim_widget_bookdetail_bottomshow, llWgDpMenuListData); } private void hideMenu() { UtilitySecurity.setImageResource(ivWgDpMenu, R.mipmap.ic_book_menu_unselect); hideAnimation(R.anim.anim_fade_out, rlWgDpMenuList); hideAnimation(R.anim.anim_widget_bookdetail_bottomhide, llWgDpMenuListData, new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { UtilitySecurity.resetVisibility(llWgDpMenuListData, false); if (!menuListOrderAsc) { menuListOrderAsc = true; menuListAdapter.setOrderByAes(menuListOrderAsc); menuListAdapter.notifyDataSetChanged(); UtilitySecurity.setImageResource(ivWgDpMenuListOrder, R.mipmap.ic_book_down); } } @Override public void onAnimationRepeat(Animation animation) { } }); // hideAnimation(R.anim.anim_fade_out, llWgDpMenuList); } private void showProcess() { if (UtilitySecurity.isEmpty(lisMenuList)) return; try { skWgDpProcess.setMax(lisMenuList.size() - 1); // 定位到最后阅读章节 TbReadHistory readHistory = AppDatabase.getInstance().ReadHistoryDao().getEntity(bookId); if (readHistory != null) { int lastReadChapterIdPosition = getPositionByChapterId(readHistory.chapterId); skWgDpProcess.setProgress(lastReadChapterIdPosition); UtilitySecurity.setText(tvWgDpProcessTitle, lisMenuList.get(lastReadChapterIdPosition).chapterName); } } catch (Exception ex) { UtilityException.catchException(ex); } UtilitySecurity.resetVisibility(rlWgDpMenuList, false); UtilitySecurity.setImageResource(ivWgDpMenu, R.mipmap.ic_book_menu_unselect); UtilitySecurity.resetVisibility(llWgDpProcessContent, false); UtilitySecurity.setImageResource(ivWgDpMenu, R.mipmap.ic_book_menu_unselect); UtilitySecurity.resetVisibility(llWgDpLightContent, false); UtilitySecurity.setImageResource(ivWgDpLight, R.mipmap.ic_book_light_unselect); UtilitySecurity.resetVisibility(llWgDpFrontContent, false); UtilitySecurity.setImageResource(ivWgDpFront, R.mipmap.ic_book_set_unselect); UtilitySecurity.setImageResource(ivWgDpProcess, R.mipmap.ic_book_progress_select); showAnimation(R.anim.anim_widget_bookdetail_bottomshow, llWgDpProcessContent); // showAnimation(R.anim.anim_fade_in, llWgDpProcessContent); } private void hideProcess() { UtilitySecurity.setImageResource(ivWgDpProcess, R.mipmap.ic_book_progress_unselect); hideAnimation(R.anim.anim_widget_bookdetail_bottomhide, llWgDpProcessContent); // hideAnimation(R.anim.anim_fade_out, llWgDpProcessContent); } private void showLight() { UtilitySecurity.resetVisibility(rlWgDpMenuList, false); UtilitySecurity.setImageResource(ivWgDpMenu, R.mipmap.ic_book_menu_unselect); UtilitySecurity.resetVisibility(llWgDpProcessContent, false); UtilitySecurity.setImageResource(ivWgDpProcess, R.mipmap.ic_book_progress_unselect); UtilitySecurity.resetVisibility(llWgDpFrontContent, false); UtilitySecurity.setImageResource(ivWgDpFront, R.mipmap.ic_book_set_unselect); UtilitySecurity.setImageResource(ivWgDpLight, R.mipmap.ic_book_light_select); showAnimation(R.anim.anim_widget_bookdetail_bottomshow, llWgDpLightContent); // showAnimation(R.anim.anim_fade_in, llWgDpLightContent); } private void hideLight() { UtilitySecurity.setImageResource(ivWgDpLight, R.mipmap.ic_book_light_unselect); hideAnimation(R.anim.anim_widget_bookdetail_bottomhide, llWgDpLightContent); // hideAnimation(R.anim.anim_fade_out, llWgDpLightContent); } private void showFront() { UtilitySecurity.resetVisibility(rlWgDpMenuList, false); UtilitySecurity.setImageResource(ivWgDpMenu, R.mipmap.ic_book_menu_unselect); UtilitySecurity.resetVisibility(llWgDpProcessContent, false); UtilitySecurity.setImageResource(ivWgDpProcess, R.mipmap.ic_book_progress_unselect); UtilitySecurity.resetVisibility(llWgDpLightContent, false); UtilitySecurity.setImageResource(ivWgDpLight, R.mipmap.ic_book_light_unselect); UtilitySecurity.setImageResource(ivWgDpFront, R.mipmap.ic_book_set_select); showAnimation(R.anim.anim_widget_bookdetail_bottomshow, llWgDpFrontContent); // showAnimation(R.anim.anim_fade_in, llWgDpFrontContent); } private void hideFront() { UtilitySecurity.setImageResource(ivWgDpFront, R.mipmap.ic_book_set_unselect); hideAnimation(R.anim.anim_widget_bookdetail_bottomhide, llWgDpFrontContent); // hideAnimation(R.anim.anim_fade_out, llWgDpFrontContent); } private void showAnimation(int animResourceId, View view) { UtilitySecurity.resetVisibility(view, true); Animation showAnimation = AnimationUtils.loadAnimation(getContext(), animResourceId); view.startAnimation(showAnimation); } private void hideAnimation(int animResourceId, View view, Animation.AnimationListener listener) { if (view.getVisibility() == View.GONE) return; Animation hideAnimation = AnimationUtils.loadAnimation(getContext(), animResourceId); if (listener != null) hideAnimation.setAnimationListener(listener); else hideAnimation.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { UtilitySecurity.resetVisibility(view, false); } @Override public void onAnimationRepeat(Animation animation) { } }); view.startAnimation(hideAnimation); } private void hideAnimation(int animResourceId, View view) { hideAnimation(animResourceId, view, null); } private void selectAnim1() { resetAnimButton(); UtilitySecurity.setTextColor(tvWgDpAnim1, R.color.white); UtilitySecurity.setBackgroundResource(tvWgDpAnim1, R.drawable.bg_widget_bd_op_select); } private void selectAnim2() { resetAnimButton(); UtilitySecurity.setTextColor(tvWgDpAnim2, R.color.white); UtilitySecurity.setBackgroundResource(tvWgDpAnim2, R.drawable.bg_widget_bd_op_select); } private void selectAnim3() { resetAnimButton(); UtilitySecurity.setTextColor(tvWgDpAnim3, R.color.white); UtilitySecurity.setBackgroundResource(tvWgDpAnim3, R.drawable.bg_widget_bd_op_select); } private void selectAnim4() { resetAnimButton(); UtilitySecurity.setTextColor(tvWgDpAnim4, R.color.white); UtilitySecurity.setBackgroundResource(tvWgDpAnim4, R.drawable.bg_widget_bd_op_select); } private void resetAnimButton() { try { UtilitySecurity.setTextColor(tvWgDpAnim1, R.color._5e60); UtilitySecurity.setBackgroundResource(tvWgDpAnim1, R.drawable.bg_widget_bd_op_unselect); UtilitySecurity.setTextColor(tvWgDpAnim2, R.color._5e60); UtilitySecurity.setBackgroundResource(tvWgDpAnim2, R.drawable.bg_widget_bd_op_unselect); UtilitySecurity.setTextColor(tvWgDpAnim3, R.color._5e60); UtilitySecurity.setBackgroundResource(tvWgDpAnim3, R.drawable.bg_widget_bd_op_unselect); UtilitySecurity.setTextColor(tvWgDpAnim4, R.color._5e60); UtilitySecurity.setBackgroundResource(tvWgDpAnim4, R.drawable.bg_widget_bd_op_unselect); } catch (Exception ex) { UtilityException.catchException(ex); } } /** * 100毫秒内只执行最后一次(防止快还未绘制完就速改变字体重新绘制) */ private void onChange() { if (listener != null) listener.onDetailOperationViewChange(UtilityReadInfo.getReadSettingInfo()); EditSharedPreferences.setReadSettingInfo(UtilityReadInfo.getReadSettingInfo()); } private void resetLightStat() { lvWgDpLight1.setSelect(false); lvWgDpLight2.setSelect(false); lvWgDpLight3.setSelect(false); lvWgDpLight4.setSelect(false); lvWgDpLight5.setSelect(false); } /** * 是否有展示的menu content */ public boolean isShowMenuContent() { return (rlWgDpMenuList.getVisibility() == View.VISIBLE) || (llWgDpProcessContent.getVisibility() == View.VISIBLE) || (llWgDpLightContent.getVisibility() == View.VISIBLE) || (llWgDpFrontContent.getVisibility() == View.VISIBLE); } /** * 隐藏所有menu content */ public void hideAllMenuContent() { close(); hideMenu(); hideProcess(); hideLight(); hideFront(); } public void close() { try { if (thread != null) thread.interrupt(); } catch (Exception ex) { UtilityException.catchException(ex); } } /** * 亮度单选 */ @Override public void onStatChange(View view, boolean select) { if (select) { resetLightStat(); switch (view.getId()) { case R.id.lvWgDpLight1: UtilityReadInfo.getReadSettingInfo().lightType = ConstantSetting.LIGHTTYPE_1; UtilityReadInfo.getReadSettingInfo().frontColor = R.color.black; lvWgDpLight1.setSelect(true); break; case R.id.lvWgDpLight2: UtilityReadInfo.getReadSettingInfo().lightType = ConstantSetting.LIGHTTYPE_2; UtilityReadInfo.getReadSettingInfo().frontColor = R.color.gray_2d2d; lvWgDpLight2.setSelect(true); break; case R.id.lvWgDpLight3: UtilityReadInfo.getReadSettingInfo().lightType = ConstantSetting.LIGHTTYPE_3; UtilityReadInfo.getReadSettingInfo().frontColor = R.color.gray_3f4c; lvWgDpLight3.setSelect(true); break; case R.id.lvWgDpLight4: UtilityReadInfo.getReadSettingInfo().lightType = ConstantSetting.LIGHTTYPE_4; UtilityReadInfo.getReadSettingInfo().frontColor = R.color.gray_442e; lvWgDpLight4.setSelect(true); break; case R.id.lvWgDpLight5: UtilityReadInfo.getReadSettingInfo().lightType = ConstantSetting.LIGHTTYPE_5; UtilityReadInfo.getReadSettingInfo().frontColor = R.color.gray_3333; lvWgDpLight5.setSelect(true); break; } } else { UtilityReadInfo.getReadSettingInfo().lightType = ConstantSetting.LIGHTTYPE_1; } onChange(); } private int getMenuListPosition(int position) { if (UtilitySecurity.isEmpty(lisMenuList)) return 0; else return menuListOrderAsc ? position : UtilitySecurity.size(lisMenuList) - 1 - position; } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { try { if (listener != null) listener.onSelectChapter(lisMenuList.get(getMenuListPosition(position))); hideAllMenuContent(); } catch (Exception ex) { UtilityException.catchException(ex); } } @Override public void onProgressChanged(SeekBar seekBar, int processValue, boolean b) { try { UtilitySecurity.setText(tvWgDpProcessTitle, lisMenuList.get(processValue).chapterName); } catch (Exception ex) { UtilityException.catchException(ex); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { int processValue = seekBar.getProgress(); Logger.firstE("onStopTrackingTouch:" + processValue); switch (seekBar.getId()) { // 进度 case R.id.skWgDpProcess: TbBookChapter bookChapter = lisMenuList.get(processValue); UtilitySecurity.setText(tvWgDpProcessTitle, bookChapter.chapterName); hideAllMenuContent(); if (listener != null) listener.onSelectChapter(bookChapter); break; // 亮度 case R.id.skWgDpLight: UtilityReadInfo.getReadSettingInfo().lightValue = (processValue); onChange(); break; // 字体 case R.id.skWgDpFront: float newFrontSize = ConstantSetting.frontSize + (processValue * 2); UtilityReadInfo.getReadSettingInfo().frontSize = newFrontSize; UtilityReadInfo.getReadSettingInfo().lineSpacingExtra = UtilityMeasure.getLineSpacingExtra(newFrontSize); onChange(); break; } } @Override public void onClick(View view) { if (LibUtility.isFastDoubleClick()) return; if (activity.getStatusTip().isShowing()) return; switch (view.getId()) { // 目录空白区域:关闭目录 case R.id.viewWgDpMenuListClose: hideMenu(); break; // 目录列表 case R.id.llWgDpMenu: if (rlWgDpMenuList.getVisibility() == View.VISIBLE) { hideMenu(); } else { showMenu(); } break; // 正序或倒序 目录列表 case R.id.rlWgDpMenuListOrder: menuListOrderAsc = !menuListOrderAsc; sortMenuList(menuListOrderAsc); break; // 进度 case R.id.llWgDpProcess: if (llWgDpProcessContent.getVisibility() == View.VISIBLE) hideProcess(); else showProcess(); break; // 亮度 case R.id.llWgDpLight: if (llWgDpLightContent.getVisibility() == View.VISIBLE) hideLight(); else showLight(); break; // 字体和翻页 case R.id.llWgDpFront: if (llWgDpFrontContent.getVisibility() == View.VISIBLE) hideFront(); else showFront(); break; // 翻页动画 case R.id.tvWgDpAnim1: selectAnim1(); UtilityReadInfo.getReadSettingInfo().pageAnimType = PageMode.SIMULATION; hideAllMenuContent(); onChange(); break; case R.id.tvWgDpAnim2: selectAnim2(); UtilityReadInfo.getReadSettingInfo().pageAnimType = PageMode.COVER; hideAllMenuContent(); onChange(); break; case R.id.tvWgDpAnim3: selectAnim3(); UtilityReadInfo.getReadSettingInfo().pageAnimType = PageMode.SCROLL; hideAllMenuContent(); onChange(); break; case R.id.tvWgDpAnim4: selectAnim4(); UtilityReadInfo.getReadSettingInfo().pageAnimType = PageMode.NONE; hideAllMenuContent(); onChange(); break; } } }
9234bb445487617dec38df4fb021fd95067eaa35
1,759
java
Java
java/vernacular/persistence/dev/d02/src/main/java/org/ppwcode/vernacular/exception_N/InternalException.java
jandockx/ppwcode
7878d1c1c9efff2982d73e4b10fd141f78e7c200
[ "Apache-2.0" ]
null
null
null
java/vernacular/persistence/dev/d02/src/main/java/org/ppwcode/vernacular/exception_N/InternalException.java
jandockx/ppwcode
7878d1c1c9efff2982d73e4b10fd141f78e7c200
[ "Apache-2.0" ]
null
null
null
java/vernacular/persistence/dev/d02/src/main/java/org/ppwcode/vernacular/exception_N/InternalException.java
jandockx/ppwcode
7878d1c1c9efff2982d73e4b10fd141f78e7c200
[ "Apache-2.0" ]
null
null
null
27.484375
77
0.731097
997,032
/*<license> Copyright 2004 - $Date$ by PeopleWare n.v.. 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>*/ package org.ppwcode.vernacular.exception_N; import static org.ppwcode.metainfo_I.License.Type.APACHE_V2; import org.ppwcode.metainfo_I.Copyright; import org.ppwcode.metainfo_I.License; import org.ppwcode.metainfo_I.vcs.SvnInfo; import org.toryt.annotations_I.Expression; import org.toryt.annotations_I.MethodContract; /** * Superclass that gathers all internal exceptions that can be thrown. * Internal exceptions carry as much information about the exceptional * occurence as possible, which can be used higher up to display a meaningful * message to the end user. */ @Copyright("2004 - $Date$, PeopleWare n.v.") @License(APACHE_V2) @SvnInfo(revision = "$Revision$", date = "$Date$") public class InternalException extends Error { @MethodContract( post = { @Expression("message == _message"), @Expression("cause == _cause") } ) public InternalException(String message, Throwable cause) { super(message, cause); } @MethodContract( post = { @Expression("message == _message"), @Expression("cause == null") } ) public InternalException(String message) { super(message); } }
9234bbbdad8abd0bcbe139a62bf467c4401f7c42
364
java
Java
app/src/com/rainbowcard/client/model/SearchResultModel.java
muchen1/caihongka
df9f828feeddab785fae7ea1c9d1cebcada6512c
[ "Apache-2.0" ]
null
null
null
app/src/com/rainbowcard/client/model/SearchResultModel.java
muchen1/caihongka
df9f828feeddab785fae7ea1c9d1cebcada6512c
[ "Apache-2.0" ]
null
null
null
app/src/com/rainbowcard/client/model/SearchResultModel.java
muchen1/caihongka
df9f828feeddab785fae7ea1c9d1cebcada6512c
[ "Apache-2.0" ]
null
null
null
21.411765
51
0.692308
997,033
package com.rainbowcard.client.model; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; /** * Created by gc on 2017-1-6. */ public class SearchResultModel { @Expose @SerializedName("status") public int status; @Expose @SerializedName("data") public SearchResultEntity data; }
9234bbdfca42cd7c6820a40b7bc4328f8d54b84b
11,386
java
Java
src/test/java/ezvcard/io/scribe/DateOrTimePropertyScribeTest.java
mangstadt/ez-vcard
96e455b1e798b71c01973fde08d519a9659ed97d
[ "BSD-2-Clause-FreeBSD" ]
368
2015-03-27T12:37:51.000Z
2022-02-28T11:20:00.000Z
src/test/java/ezvcard/io/scribe/DateOrTimePropertyScribeTest.java
mangstadt/ez-vcard
96e455b1e798b71c01973fde08d519a9659ed97d
[ "BSD-2-Clause-FreeBSD" ]
98
2015-05-06T20:44:18.000Z
2022-03-11T16:36:53.000Z
src/test/java/ezvcard/io/scribe/DateOrTimePropertyScribeTest.java
mangstadt/ez-vcard
96e455b1e798b71c01973fde08d519a9659ed97d
[ "BSD-2-Clause-FreeBSD" ]
103
2015-03-25T23:53:00.000Z
2021-12-12T20:15:12.000Z
44.476563
123
0.776304
997,034
package ezvcard.io.scribe; import static ezvcard.VCardDataType.DATE; import static ezvcard.VCardDataType.DATE_TIME; import static ezvcard.VCardDataType.TEXT; import static ezvcard.VCardVersion.V2_1; import static ezvcard.VCardVersion.V3_0; import static ezvcard.VCardVersion.V4_0; import static ezvcard.util.TestUtils.date; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import java.util.Calendar; import java.util.Date; import org.junit.ClassRule; import org.junit.Test; import ezvcard.io.scribe.Sensei.Check; import ezvcard.property.DateOrTimeProperty; import ezvcard.util.DefaultTimezoneRule; import ezvcard.util.PartialDate; /* Copyright (c) 2012-2021, Michael Angstadt All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ /** * @author Michael Angstadt */ public class DateOrTimePropertyScribeTest { @ClassRule public static final DefaultTimezoneRule tzRule = new DefaultTimezoneRule(1, 0); private final DateOrTimeScribeImpl scribe = new DateOrTimeScribeImpl(); private final Sensei<DateOrTimePropertyImpl> sensei = new Sensei<DateOrTimePropertyImpl>(scribe); private final Date date = date("1980-06-05"); private final String dateStr = "19800605"; private final String dateExtendedStr = "1980-06-05"; private final Calendar dateTime = date(1980, Calendar.JUNE, 5, 13, 10, 20, 1); private final String dateTimeStr = dateStr + "T131020+0100"; private final String dateTimeExtendedStr = dateExtendedStr + "T13:10:20+01:00"; private final PartialDate partialDate = PartialDate.builder().month(6).date(5).build(); private final PartialDate partialTime = PartialDate.builder().hour(12).build(); private final PartialDate partialDateTime = PartialDate.builder().month(6).date(5).hour(13).minute(10).second(20).build(); private final String text = "Sometime in, ;1980;"; private final String textEscaped = "Sometime in\\, \\;1980\\;"; private final DateOrTimePropertyImpl withDate = new DateOrTimePropertyImpl(); { withDate.setDate(date, false); } private final DateOrTimePropertyImpl withDateTime = new DateOrTimePropertyImpl(); { withDateTime.setDate(dateTime, true); } private final DateOrTimePropertyImpl withPartialDate = new DateOrTimePropertyImpl(); { withPartialDate.setPartialDate(partialDate); } private final DateOrTimePropertyImpl withPartialTime = new DateOrTimePropertyImpl(); { withPartialTime.setPartialDate(partialTime); } private final DateOrTimePropertyImpl withPartialDateTime = new DateOrTimePropertyImpl(); { withPartialDateTime.setPartialDate(partialDateTime); } private final DateOrTimePropertyImpl withText = new DateOrTimePropertyImpl(); { withText.setText(text); } private final DateOrTimePropertyImpl empty = new DateOrTimePropertyImpl(); @Test public void dataType() { sensei.assertDataType(withDate).versions(V2_1, V3_0).run(null); sensei.assertDataType(withDate).versions(V4_0).run(DATE); sensei.assertDataType(withDateTime).versions(V2_1, V3_0).run(null); sensei.assertDataType(withDateTime).versions(V4_0).run(DATE_TIME); sensei.assertDataType(withPartialDate).versions(V2_1, V3_0).run(null); sensei.assertDataType(withPartialDate).versions(V4_0).run(DATE); sensei.assertDataType(withPartialTime).versions(V2_1, V3_0).run(null); sensei.assertDataType(withPartialTime).versions(V4_0).run(DATE_TIME); sensei.assertDataType(withPartialDateTime).versions(V2_1, V3_0).run(null); sensei.assertDataType(withPartialDateTime).versions(V4_0).run(DATE_TIME); sensei.assertDataType(withText).versions(V2_1, V3_0).run(null); sensei.assertDataType(withText).versions(V4_0).run(TEXT); } @Test public void writeText() { sensei.assertWriteText(withDate).versions(V2_1, V4_0).run(dateStr); sensei.assertWriteText(withDate).versions(V3_0).run(dateExtendedStr); sensei.assertWriteText(withDateTime).versions(V2_1, V4_0).run(dateTimeStr); sensei.assertWriteText(withDateTime).versions(V3_0).run(dateTimeExtendedStr); sensei.assertWriteText(withPartialDate).versions(V2_1, V3_0).run(""); sensei.assertWriteText(withPartialDate).versions(V4_0).run(partialDate.toISO8601(false)); sensei.assertWriteText(withPartialTime).versions(V2_1, V3_0).run(""); sensei.assertWriteText(withPartialTime).versions(V4_0).run(partialTime.toISO8601(false)); sensei.assertWriteText(withPartialDateTime).versions(V2_1, V3_0).run(""); sensei.assertWriteText(withPartialDateTime).versions(V4_0).run(partialDateTime.toISO8601(false)); sensei.assertWriteText(withText).versions(V2_1, V3_0).run(""); sensei.assertWriteText(withText).versions(V4_0).run(textEscaped); sensei.assertWriteText(empty).run(""); } @Test public void writeXml() { sensei.assertWriteXml(withDate).run("<date>" + dateStr + "</date>"); sensei.assertWriteXml(withDateTime).run("<date-time>" + dateTimeStr + "</date-time>"); sensei.assertWriteXml(withPartialDate).run("<date>" + partialDate.toISO8601(false) + "</date>"); sensei.assertWriteXml(withPartialTime).run("<time>" + partialTime.toISO8601(false) + "</time>"); sensei.assertWriteXml(withPartialDateTime).run("<date-time>" + partialDateTime.toISO8601(false) + "</date-time>"); sensei.assertWriteXml(withText).run("<text>" + text + "</text>"); sensei.assertWriteXml(empty).run("<date-and-or-time/>"); } @Test public void writeJson() { sensei.assertWriteJson(withDate).run(dateExtendedStr); sensei.assertWriteJson(withDateTime).run(dateTimeExtendedStr); sensei.assertWriteJson(withPartialDate).run(partialDate.toISO8601(true)); sensei.assertWriteJson(withPartialTime).run(partialTime.toISO8601(true)); sensei.assertWriteJson(withPartialDateTime).run(partialDateTime.toISO8601(true)); sensei.assertWriteJson(withText).run(text); sensei.assertWriteJson(empty).run(""); } @Test public void parseText() { sensei.assertParseText(dateExtendedStr).run(withDate); sensei.assertParseText(dateTimeExtendedStr).run(withDateTime); sensei.assertParseText(partialDate.toISO8601(false)).versions(V2_1, V3_0).cannotParse(5); sensei.assertParseText(partialDate.toISO8601(false)).versions(V4_0).run(withPartialDate); sensei.assertParseText(partialTime.toISO8601(false)).versions(V2_1, V3_0).cannotParse(5); sensei.assertParseText(partialTime.toISO8601(false)).versions(V4_0).run(withPartialTime); sensei.assertParseText(partialDateTime.toISO8601(false)).versions(V2_1, V3_0).cannotParse(5); sensei.assertParseText(partialDateTime.toISO8601(false)).versions(V4_0).run(withPartialDateTime); sensei.assertParseText(text).versions(V2_1, V3_0).cannotParse(5); sensei.assertParseText(text).versions(V4_0).warnings(6).run(hasText(text)); sensei.assertParseText(text).versions(V2_1, V3_0).dataType(TEXT).cannotParse(5); sensei.assertParseText(text).versions(V4_0).dataType(TEXT).run(withText); } @Test public void parseXml() { String tags[] = { "date", "date-time", "date-and-or-time" }; for (String tag : tags) { String format = "<" + tag + ">%s</" + tag + ">"; sensei.assertParseXml(String.format(format, dateStr)).run(withDate); sensei.assertParseXml(String.format(format, dateTimeStr)).run(withDateTime); sensei.assertParseXml(String.format(format, partialDate.toISO8601(false))).run(withPartialDate); sensei.assertParseXml(String.format(format, partialTime.toISO8601(false))).run(withPartialTime); sensei.assertParseXml(String.format(format, partialDateTime.toISO8601(false))).run(withPartialDateTime); sensei.assertParseXml(String.format(format, "invalid")).warnings(6).run(hasText("invalid")); } sensei.assertParseXml("<text>" + text + "</text>").run(withText); sensei.assertParseXml("<date>" + dateStr + "</date><date>invalid</date>").run(withDate); //only considers the first sensei.assertParseXml("").cannotParse(0); } @Test public void parseJson() { sensei.assertParseJson(dateExtendedStr).run(withDate); sensei.assertParseJson(dateTimeExtendedStr).run(withDateTime); sensei.assertParseJson(partialDate.toISO8601(true)).run(withPartialDate); sensei.assertParseJson(partialTime.toISO8601(true)).run(withPartialTime); sensei.assertParseJson(partialDateTime.toISO8601(true)).run(withPartialDateTime); sensei.assertParseJson(text).warnings(6).run(withText); sensei.assertParseJson(text).dataType(TEXT).run(withText); } @Test public void parseHtml() { sensei.assertParseHtml("<time datetime=\"" + dateExtendedStr + "\">June 5, 1980</time>").run(withDate); sensei.assertParseHtml("<time>" + dateExtendedStr + "</time>").run(withDate); sensei.assertParseHtml("<div>" + dateExtendedStr + "</div>").run(withDate); sensei.assertParseHtml("<time>June 5, 1980</time>").cannotParse(5); } private static class DateOrTimeScribeImpl extends DateOrTimePropertyScribe<DateOrTimePropertyImpl> { public DateOrTimeScribeImpl() { super(DateOrTimePropertyImpl.class, "DATETIME"); } @Override protected DateOrTimePropertyImpl newInstance(String text) { DateOrTimePropertyImpl property = new DateOrTimePropertyImpl(); property.setText(text); return property; } @Override protected DateOrTimePropertyImpl newInstance(Calendar date, boolean hasTime) { DateOrTimePropertyImpl property = new DateOrTimePropertyImpl(); property.setDate(date, hasTime); return property; } @Override protected DateOrTimePropertyImpl newInstance(PartialDate partialDate) { DateOrTimePropertyImpl property = new DateOrTimePropertyImpl(); property.setPartialDate(partialDate); return property; } } private static class DateOrTimePropertyImpl extends DateOrTimeProperty { public DateOrTimePropertyImpl() { super((Date) null); } } private Check<DateOrTimePropertyImpl> hasText(final String text) { return new Check<DateOrTimePropertyImpl>() { public void check(DateOrTimePropertyImpl property) { assertNull(property.getDate()); assertNull(property.getPartialDate()); assertEquals(text, property.getText()); } }; } }
9234bc3a08530991687a4f3081c3b1709506d46a
3,465
java
Java
src/main/java/org/opensaml/saml2/metadata/impl/IDPSSODescriptorUnmarshaller.java
danpal/OpenSAML
8297262c7ef649249f84750a6c197f4359669f97
[ "Apache-2.0" ]
3
2016-04-19T09:11:40.000Z
2020-01-21T14:47:34.000Z
src/main/java/org/opensaml/saml2/metadata/impl/IDPSSODescriptorUnmarshaller.java
danpal/OpenSAML
8297262c7ef649249f84750a6c197f4359669f97
[ "Apache-2.0" ]
2
2015-05-05T13:30:56.000Z
2017-07-27T07:33:07.000Z
src/main/java/org/opensaml/saml2/metadata/impl/IDPSSODescriptorUnmarshaller.java
danpal/OpenSAML
8297262c7ef649249f84750a6c197f4359669f97
[ "Apache-2.0" ]
10
2016-01-07T12:23:40.000Z
2022-02-23T03:24:07.000Z
40.290698
118
0.718903
997,035
/* * Copyright [2005] [University Corporation for Advanced Internet Development, Inc.] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * */ package org.opensaml.saml2.metadata.impl; import org.opensaml.common.xml.SAMLConstants; import org.opensaml.saml2.core.Attribute; import org.opensaml.saml2.metadata.AssertionIDRequestService; import org.opensaml.saml2.metadata.AttributeProfile; import org.opensaml.saml2.metadata.IDPSSODescriptor; import org.opensaml.saml2.metadata.NameIDMappingService; import org.opensaml.saml2.metadata.SingleSignOnService; import org.opensaml.xml.XMLObject; import org.opensaml.xml.io.UnmarshallingException; import org.opensaml.xml.schema.XSBooleanValue; import org.w3c.dom.Attr; /** * A thread safe Unmarshaller for {@link org.opensaml.saml2.metadata.SSODescriptor} objects. */ public class IDPSSODescriptorUnmarshaller extends SSODescriptorUnmarshaller { /** * Constructor */ public IDPSSODescriptorUnmarshaller() { super(SAMLConstants.SAML20MD_NS, IDPSSODescriptor.DEFAULT_ELEMENT_LOCAL_NAME); } /** * Constructor * * @param namespaceURI * @param elementLocalName */ protected IDPSSODescriptorUnmarshaller(String namespaceURI, String elementLocalName) { super(namespaceURI, elementLocalName); } /** {@inheritDoc} */ protected void processChildElement(XMLObject parentObject, XMLObject childObject) throws UnmarshallingException { IDPSSODescriptor descriptor = (IDPSSODescriptor) parentObject; if (childObject instanceof SingleSignOnService) { descriptor.getSingleSignOnServices().add((SingleSignOnService) childObject); } else if (childObject instanceof NameIDMappingService) { descriptor.getNameIDMappingServices().add((NameIDMappingService) childObject); } else if (childObject instanceof AssertionIDRequestService) { descriptor.getAssertionIDRequestServices().add((AssertionIDRequestService) childObject); } else if (childObject instanceof AttributeProfile) { descriptor.getAttributeProfiles().add((AttributeProfile) childObject); } else if (childObject instanceof Attribute) { descriptor.getAttributes().add((Attribute) childObject); } else { super.processChildElement(parentObject, childObject); } } /** {@inheritDoc} */ protected void processAttribute(XMLObject samlObject, Attr attribute) throws UnmarshallingException { IDPSSODescriptor descriptor = (IDPSSODescriptor) samlObject; if (attribute.getLocalName().equals(IDPSSODescriptor.WANT_AUTHN_REQ_SIGNED_ATTRIB_NAME)) { descriptor.setWantAuthnRequestsSigned(XSBooleanValue.valueOf(attribute.getValue())); } else { super.processAttribute(samlObject, attribute); } } }
9234bcbdf1740e8b0900f4c668dc840f86a64826
7,107
java
Java
openmpis-domain/src/main/java/org/vincenzolabs/openmpis/representation/TipJson.java
rvbabilonia/openmpis
63eb1057aefd0c84a65af631de30c2e052562485
[ "MIT" ]
1
2017-06-17T04:15:08.000Z
2017-06-17T04:15:08.000Z
openmpis-domain/src/main/java/org/vincenzolabs/openmpis/representation/TipJson.java
rvbabilonia/openmpis
63eb1057aefd0c84a65af631de30c2e052562485
[ "MIT" ]
121
2019-10-28T23:02:29.000Z
2021-07-23T05:36:54.000Z
openmpis-domain/src/main/java/org/vincenzolabs/openmpis/representation/TipJson.java
rvbabilonia/openmpis
63eb1057aefd0c84a65af631de30c2e052562485
[ "MIT" ]
2
2019-02-18T09:48:52.000Z
2019-10-28T22:11:18.000Z
25.843636
83
0.613339
997,036
/* * This file is part of OpenMPIS. * * Copyright (c) 2019 VincenzoLabs * * 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.vincenzolabs.openmpis.representation; import java.time.OffsetDateTime; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.apache.commons.lang3.builder.ToStringBuilder; import org.vincenzolabs.openmpis.enumeration.MessageStatus; /** * The data transfer object for tip (formerly message). * * @author Rey Vincent Babilonia */ public class TipJson { private String uuid; private OffsetDateTime creationDate; private String firstName; private String lastName; private String emailAddress; private String contactNumber; private String message; private MessageStatus status; private String ipAddress; /** * Returns the UUID. * * @return the UUID */ public String getUuid() { return uuid; } /** * Sets the UUID. * * @param uuid the UUID */ public void setUuid(String uuid) { this.uuid = uuid; } /** * Returns the {@link OffsetDateTime} the tip was filed. * * @return the {@link OffsetDateTime} the {@link TipJson} was filed */ public OffsetDateTime getCreationDate() { return creationDate; } /** * Sets the {@link OffsetDateTime} the {@link TipJson} was filed. * * @param creationDate the {@link OffsetDateTime} the {@link TipJson} was filed */ public void setCreationDate(OffsetDateTime creationDate) { this.creationDate = creationDate; } /** * Returns the optional first name of the person filing a tip. * * @return the first name */ public String getFirstName() { return firstName; } /** * Sets the optional first name of the person filing a tip. * * @param firstName the first name */ public void setFirstName(String firstName) { this.firstName = firstName; } /** * Returns the optional last name of the person filing a tip. * * @return the last name */ public String getLastName() { return lastName; } /** * Sets the optional last name of the person filing a tip. * * @param lastName the last name */ public void setLastName(String lastName) { this.lastName = lastName; } /** * Returns the email address of the person filing a tip. * * @return the email address */ public String getEmailAddress() { return emailAddress; } /** * Sets the email address of the person filing a tip. * * @param emailAddress the email address */ public void setEmailAddress(String emailAddress) { this.emailAddress = emailAddress; } /** * Returns the contact number of the person filing a tip. * * @return the contact number */ public String getContactNumber() { return contactNumber; } /** * Sets the contact number of the person filing a tip. * * @param contactNumber the contact number */ public void setContactNumber(String contactNumber) { this.contactNumber = contactNumber; } /** * Returns the message. * * @return the message */ public String getMessage() { return message; } /** * Sets the message. * * @param message the message */ public void setMessage(String message) { this.message = message; } /** * Returns the {@link MessageStatus}. * * @return the {@link MessageStatus} */ public MessageStatus getStatus() { return status; } /** * Sets the {@link MessageStatus}. * * @param status the {@link MessageStatus} */ public void setStatus(MessageStatus status) { this.status = status; } /** * Returns the client IP address of the person filing a tip. * * @return the client IP address */ public String getIpAddress() { return ipAddress; } /** * Sets the client IP address of the person filing a tip. * * @param ipAddress the client IP address */ public void setIpAddress(String ipAddress) { this.ipAddress = ipAddress; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } TipJson tipJson = (TipJson) o; return new EqualsBuilder() .append(uuid, tipJson.uuid) .append(creationDate, tipJson.creationDate) .append(firstName, tipJson.firstName) .append(lastName, tipJson.lastName) .append(emailAddress, tipJson.emailAddress) .append(contactNumber, tipJson.contactNumber) .append(message, tipJson.message) .append(status, tipJson.status) .append(ipAddress, tipJson.ipAddress) .isEquals(); } @Override public int hashCode() { return new HashCodeBuilder(17, 37) .append(uuid) .append(creationDate) .append(firstName) .append(lastName) .append(emailAddress) .append(contactNumber) .append(message) .append(status) .append(ipAddress) .toHashCode(); } @Override public String toString() { return new ToStringBuilder(this) .append("uuid", uuid) .append("creationDate", creationDate) .append("firstName", firstName) .append("lastName", lastName) .append("emailAddress", emailAddress) .append("contactNumber", contactNumber) .append("message", message) .append("status", status) .append("ipAddress", ipAddress) .toString(); } }
9234bcf5ba0cb45ceafc6b26fbc04edfaefcffab
2,264
java
Java
src/test/java/seedu/whatnow/model/freetime/PeriodTest.java
Verbena/WhatNow
0f072199951b4de077af2fa53204ec8fd9640a67
[ "MIT" ]
null
null
null
src/test/java/seedu/whatnow/model/freetime/PeriodTest.java
Verbena/WhatNow
0f072199951b4de077af2fa53204ec8fd9640a67
[ "MIT" ]
null
null
null
src/test/java/seedu/whatnow/model/freetime/PeriodTest.java
Verbena/WhatNow
0f072199951b4de077af2fa53204ec8fd9640a67
[ "MIT" ]
null
null
null
33.791045
67
0.626767
997,037
//@@author A0139772U package seedu.whatnow.model.freetime; import org.junit.Test; import static org.junit.Assert.assertEquals; import java.util.ArrayList; public class PeriodTest { @Test public void compareTo_periodEqual_periodAreEqual() { Period period1 = new Period("12:00am", "02:00am"); Period period2 = new Period("12:00am", "02:00am"); ArrayList<Period> periods = new ArrayList<Period>(); periods.add(period1); periods.add(period2); periods.sort(new Period()); assertEquals(periods.get(0), period1); assertEquals(periods.get(1), period2); } @Test public void compareTo_firstSmallerThanSecond_periodAreEqual() { Period period1 = new Period("12:00am", "02:00am"); Period period2 = new Period("02:00am", "04:00am"); ArrayList<Period> periods = new ArrayList<Period>(); periods.add(period1); periods.add(period2); periods.sort(new Period()); assertEquals(periods.get(0), period1); assertEquals(periods.get(1), period2); } @Test public void compareTo_firstBiggerThanSecond_periodAreEqual() { Period period1 = new Period("02:00am", "04:00am"); Period period2 = new Period("12:00am", "02:00am"); ArrayList<Period> periods = new ArrayList<Period>(); periods.add(period1); periods.add(period2); periods.sort(new Period()); assertEquals(periods.get(1), period1); assertEquals(periods.get(0), period2); } @Test public void compareTo_invalidFormat_periodAreEqual() { Period period1 = new Period("02-00am", "04-00am"); Period period2 = new Period("12-00am", "02-00am"); ArrayList<Period> periods = new ArrayList<Period>(); periods.add(period1); periods.add(period2); periods.sort(new Period()); assertEquals(periods.get(0), period1); assertEquals(periods.get(1), period2); } @Test public void setter_ObjectInstantiated_validSet() { Period period1 = new Period("02-00am", "04-00am"); period1.setStart("02:00am"); period1.setEnd("04:00am"); assertEquals(period1.toString(), "[02:00am, 04:00am]"); } }
9234bd0a6dcf80eac9daa919ecce949d36ce9e7c
3,085
java
Java
src/main/java/com/microsoft/teamfoundation/bamboo/action/TfsBaseAction.java
madhureddykolama/vsts-bamboo-build-integration-sample
a7afc90e21a41d46bd4e1ef1b609e2c7509042cf
[ "MIT" ]
3
2016-06-18T23:20:39.000Z
2018-07-30T22:25:46.000Z
src/main/java/com/microsoft/teamfoundation/bamboo/action/TfsBaseAction.java
madhureddykolama/vsts-bamboo-build-integration-sample
a7afc90e21a41d46bd4e1ef1b609e2c7509042cf
[ "MIT" ]
3
2018-03-12T20:41:09.000Z
2018-11-13T18:01:17.000Z
src/main/java/com/microsoft/teamfoundation/bamboo/action/TfsBaseAction.java
madhureddykolama/vsts-bamboo-build-integration-sample
a7afc90e21a41d46bd4e1ef1b609e2c7509042cf
[ "MIT" ]
6
2019-11-03T16:41:28.000Z
2021-11-10T10:09:36.000Z
35.872093
114
0.758185
997,038
package com.microsoft.teamfoundation.bamboo.action; import com.atlassian.bamboo.build.BuildLoggerManager; import com.atlassian.bamboo.security.EncryptionService; import com.microsoft.teamfoundation.bamboo.BambooSecret; import com.microsoft.teamfoundation.bamboo.Constants; import com.microsoft.teamfoundation.plugin.TfsBuildFacadeFactory; import com.microsoft.teamfoundation.plugin.TfsClientFactory; import com.microsoft.teamfoundation.plugin.TfsSecret; import com.microsoft.teamfoundation.plugin.impl.TfsBuildFacadeFactoryImpl; import com.microsoft.teamfoundation.plugin.impl.TfsClient; import com.microsoft.teamfoundation.plugin.impl.TfsClientFactoryImpl; import java.net.URISyntaxException; import java.util.Map; /** * Created by yacao on 4/30/2015. */ public abstract class TfsBaseAction { private EncryptionService encryptionService; private TfsBuildFacadeFactory tfsBuildFacadeFactory; private TfsClientFactory tfsClientFactory; private BuildLoggerManager buildLoggerManager; protected TfsClient getTfsClient(Map<String, String> configurations) throws URISyntaxException{ String serverUrl = configurations.get(Constants.TFS_SERVER_URL); String username = configurations.get(Constants.TFS_USERNAME); TfsSecret password = new BambooSecret(getEncryptionService(), configurations.get(Constants.TFS_PASSWORD)); TfsClient tfsClient = getTfsClientFactory().getValidatedClient(serverUrl, username, password); if (tfsClient == null) { throw new RuntimeException("Could not connect to the specified URL with provided credentials."); } return tfsClient; } // this will be spring DI'ed public EncryptionService getEncryptionService() { return encryptionService; } public BuildLoggerManager getBuildLoggerManager() { return buildLoggerManager; } // for some reason spring was not able to inject those two classes on a remote agent // default to standard singleton getter public synchronized TfsBuildFacadeFactory getTfsBuildFacadeFactory() { if (this.tfsBuildFacadeFactory == null) { this.tfsBuildFacadeFactory = new TfsBuildFacadeFactoryImpl(); } return tfsBuildFacadeFactory; } public synchronized TfsClientFactory getTfsClientFactory() { if(this.tfsClientFactory == null) { this.tfsClientFactory = new TfsClientFactoryImpl(); } return tfsClientFactory; } /* spring setters */ public void setEncryptionService(EncryptionService encryptionService) { this.encryptionService = encryptionService; } public void setTfsBuildFacadeFactory(TfsBuildFacadeFactory tfsBuildFacadeFactory) { this.tfsBuildFacadeFactory = tfsBuildFacadeFactory; } public void setTfsClientFactory(TfsClientFactory tfsClientFactory) { this.tfsClientFactory = tfsClientFactory; } public void setBuildLoggerManager(final BuildLoggerManager buildLoggerManager) { this.buildLoggerManager = buildLoggerManager; } }
9234bda789cc55556c25304fe1411e87f3c0aace
388
java
Java
src/test/java/util/Repeat.java
VennMaker/vennmaker-source
5bb5a446ab00555800da211a2f6c29ab50a5aa59
[ "Apache-2.0" ]
2
2019-07-05T14:18:31.000Z
2020-09-01T08:06:04.000Z
src/test/java/util/Repeat.java
VennMaker/vennmaker-source
5bb5a446ab00555800da211a2f6c29ab50a5aa59
[ "Apache-2.0" ]
16
2017-04-17T16:42:29.000Z
2021-08-25T15:11:17.000Z
src/test/java/util/Repeat.java
VennMaker/vennmaker-source
5bb5a446ab00555800da211a2f6c29ab50a5aa59
[ "Apache-2.0" ]
4
2017-01-14T20:03:32.000Z
2019-05-27T14:02:27.000Z
19.4
68
0.734536
997,039
package util; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Setzt fuer einen Test-Case eine bestimmte Anzahl an durchlaufen. * * */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Repeat { int value(); }
9234bdeea4ec0b701a2af4ad977eac8db56d4d0e
480
java
Java
word8/src/main/java/eu/doppel_helix/jna/tlb/word8/WdEditionType.java
matthiasblaesing/COMTypelibraries
c17acfca689305c0e23d4ff9d8ee437e0ee3d437
[ "MIT" ]
15
2016-11-30T17:25:43.000Z
2021-07-10T22:32:06.000Z
word8/src/main/java/eu/doppel_helix/jna/tlb/word8/WdEditionType.java
matthiasblaesing/COMTypelibraries
c17acfca689305c0e23d4ff9d8ee437e0ee3d437
[ "MIT" ]
null
null
null
word8/src/main/java/eu/doppel_helix/jna/tlb/word8/WdEditionType.java
matthiasblaesing/COMTypelibraries
c17acfca689305c0e23d4ff9d8ee437e0ee3d437
[ "MIT" ]
1
2019-09-10T02:40:33.000Z
2019-09-10T02:40:33.000Z
16
54
0.56875
997,040
package eu.doppel_helix.jna.tlb.word8; import com.sun.jna.platform.win32.COM.util.IComEnum; /** * <p>uuid({8D0DC233-B993-3557-8702-0B855D6ECB56})</p> */ public enum WdEditionType implements IComEnum { /** * (0) */ wdPublisher(0), /** * (1) */ wdSubscriber(1), ; private WdEditionType(long value) { this.value = value; } private long value; public long getValue() { return this.value; } }
9234be0fe946c74717b340513c144bd12935be00
748
java
Java
sbd_rabbitmq/src/test/java/com/minipa/sbd/rabbitmq/rabbitmq/DirectTest.java
weijunzhang/spring_boot_demos
66666fce33799371874bfbc01525f59b79850561
[ "RSA-MD" ]
7
2017-12-20T00:49:28.000Z
2021-05-07T08:42:06.000Z
sbd_rabbitmq/src/test/java/com/minipa/sbd/rabbitmq/rabbitmq/DirectTest.java
weijunzhang/spring_boot_demos
66666fce33799371874bfbc01525f59b79850561
[ "RSA-MD" ]
null
null
null
sbd_rabbitmq/src/test/java/com/minipa/sbd/rabbitmq/rabbitmq/DirectTest.java
weijunzhang/spring_boot_demos
66666fce33799371874bfbc01525f59b79850561
[ "RSA-MD" ]
4
2018-04-24T07:13:24.000Z
2019-12-21T11:25:37.000Z
25.965517
65
0.755644
997,041
package com.minipa.sbd.rabbitmq.rabbitmq; import com.minipa.sbd.rabbitmq.rabbit.direct.DirectSender; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; /** * DirectTest: * * @author: <a href="mailto:hzdkv@example.com">chengjs</a> <a href="https://github.com/MiniPa">minipa_github</a> * @version: 1.0.0, 2017-12-01 shared by all free coders **/ @RunWith(SpringRunner.class) @SpringBootTest public class DirectTest { @Autowired private DirectSender helloSender; @Test public void send() throws Exception { helloSender.send(); } }
9234be7b201f31a4a92fe16a6fe92bd6b73bb882
2,240
java
Java
main/feature/src/boofcv/abst/feature/detdesc/WrapDetectDescribeSift.java
dewmal/BoofCV
19a970ab712b5a062f59f751145c77c36c2daa3f
[ "Apache-2.0" ]
1
2022-02-26T06:27:29.000Z
2022-02-26T06:27:29.000Z
main/feature/src/boofcv/abst/feature/detdesc/WrapDetectDescribeSift.java
dewmal/BoofCV
19a970ab712b5a062f59f751145c77c36c2daa3f
[ "Apache-2.0" ]
null
null
null
main/feature/src/boofcv/abst/feature/detdesc/WrapDetectDescribeSift.java
dewmal/BoofCV
19a970ab712b5a062f59f751145c77c36c2daa3f
[ "Apache-2.0" ]
null
null
null
23.829787
94
0.751339
997,042
/* * Copyright (c) 2011-2013, Peter Abeles. All Rights Reserved. * * This file is part of BoofCV (http://boofcv.org). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package boofcv.abst.feature.detdesc; import boofcv.alg.feature.detdesc.DetectDescribeSift; import boofcv.struct.feature.SurfFeature; import boofcv.struct.image.ImageFloat32; import georegression.struct.point.Point2D_F64; /** * Wrapper around {@link DetectDescribeSift} for {@link DetectDescribePoint}. * * @author Peter Abeles */ public class WrapDetectDescribeSift implements DetectDescribePoint<ImageFloat32,SurfFeature> { DetectDescribeSift alg; public WrapDetectDescribeSift(DetectDescribeSift alg) { this.alg = alg; } @Override public SurfFeature createDescription() { return new SurfFeature(alg.getDescriptorLength()); } @Override public SurfFeature getDescription(int index) { return alg.getFeatures().data[index]; } @Override public Class<SurfFeature> getDescriptionType() { return SurfFeature.class; } @Override public int getDescriptionLength() { return alg.getDescriptorLength(); } @Override public void detect(ImageFloat32 input) { alg.process(input); } @Override public int getNumberOfFeatures() { return alg.getFeatures().size; } @Override public Point2D_F64 getLocation(int featureIndex) { return alg.getLocation().get(featureIndex); } @Override public double getScale(int featureIndex) { return alg.getFeatureScales().get(featureIndex); } @Override public double getOrientation(int featureIndex) { return alg.getFeatureAngles().get(featureIndex); } @Override public boolean hasScale() { return true; } @Override public boolean hasOrientation() { return true; } }
9234bf52f3602c71a5a6d6695c5cb3f8a3a34ca4
2,756
java
Java
activemq-amqp/src/main/java/org/apache/activemq/transport/amqp/AmqpProtocolConverter.java
gemmellr/activemq
5bd2abf85dbda14bf41f54d09af4866e814f931f
[ "Apache-2.0" ]
2,073
2015-01-01T15:27:57.000Z
2022-03-31T09:08:51.000Z
activemq-amqp/src/main/java/org/apache/activemq/transport/amqp/AmqpProtocolConverter.java
gemmellr/activemq
5bd2abf85dbda14bf41f54d09af4866e814f931f
[ "Apache-2.0" ]
338
2015-01-05T17:50:20.000Z
2022-03-31T17:46:12.000Z
activemq-amqp/src/main/java/org/apache/activemq/transport/amqp/AmqpProtocolConverter.java
gemmellr/activemq
5bd2abf85dbda14bf41f54d09af4866e814f931f
[ "Apache-2.0" ]
1,498
2015-01-03T10:58:42.000Z
2022-03-28T05:11:21.000Z
34.45
83
0.697025
997,043
/** * 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.transport.amqp; import java.io.IOException; import org.apache.activemq.command.Command; /** * Interface that defines the API for any AMQP protocol converter ised to * map AMQP mechanics to ActiveMQ and back. */ public interface AmqpProtocolConverter { /** * A new incoming data packet from the remote peer is handed off to the * protocol converter for processing. The type can vary and be either an * AmqpHeader at the handshake phase or a byte buffer containing the next * incoming frame data from the remote. * * @param data * the next incoming data object from the remote peer. * * @throws Exception if an error occurs processing the incoming data packet. */ void onAMQPData(Object data) throws Exception; /** * Called when the transport detects an exception that the converter * needs to respond to. * * @param error * the error that triggered this call. */ void onAMQPException(IOException error); /** * Incoming Command object from ActiveMQ. * * @param command * the next incoming command from the broker. * * @throws Exception if an error occurs processing the command. */ void onActiveMQCommand(Command command) throws Exception; /** * On changes to the transport tracing options the Protocol Converter * should update its internal state so that the proper AMQP data is * logged. */ void updateTracer(); /** * Perform any keep alive processing for the connection such as sending * empty frames or closing connections due to remote end being inactive * for to long. * * @returns the amount of milliseconds to wait before performing another check. * * @throws IOException if an error occurs on writing heart-beats to the wire. */ long keepAlive() throws IOException; }
9234c0667d0b97faefa91f1270131463bc5381c5
702
java
Java
demo_ssm 2/src/main/java/com/system/mapper/RechargeRecordMapper.java
ITvisions/graduate-project
57a1f2544fdf027b04084bf9cc9251dc91ed6404
[ "Apache-2.0" ]
5
2020-06-19T07:04:29.000Z
2022-01-09T14:10:55.000Z
demo_ssm 2/src/main/java/com/system/mapper/RechargeRecordMapper.java
ITvisions/graduate-project
57a1f2544fdf027b04084bf9cc9251dc91ed6404
[ "Apache-2.0" ]
10
2020-10-29T09:19:37.000Z
2022-02-27T05:04:57.000Z
demo_ssm 2/src/main/java/com/system/mapper/RechargeRecordMapper.java
ITvisions/graduate-project
57a1f2544fdf027b04084bf9cc9251dc91ed6404
[ "Apache-2.0" ]
1
2020-10-29T09:15:48.000Z
2020-10-29T09:15:48.000Z
25.071429
66
0.796296
997,044
package com.system.mapper; import com.system.domain.RechargeRecord; import com.system.domain.vo.UserRechargeVo; import java.util.List; public interface RechargeRecordMapper { int deleteByPrimaryKey(Integer rechargeId); int insert(RechargeRecord record); int insertSelective(RechargeRecord record); RechargeRecord selectByPrimaryKey(Integer rechargeId); float selectWallentByPassengerId(Integer passengerId); int updateByPrimaryKeySelective(RechargeRecord record); int updateByPrimaryKey(RechargeRecord record); List<RechargeRecord> selectBypassengerId(Integer passengerId); UserRechargeVo getsumaccount(); List<RechargeRecord> selectByoptionName(); }
9234c2697879fbd843fc94118c338db1e002e420
6,936
java
Java
app/src/main/java/com/b2gsoft/mrb/Fragment/Expense/ExpenseOilFragment.java
imsajib02/BrickField
88237a76c626e9555c1f922e3d5f6fcb5a66eba2
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/b2gsoft/mrb/Fragment/Expense/ExpenseOilFragment.java
imsajib02/BrickField
88237a76c626e9555c1f922e3d5f6fcb5a66eba2
[ "Apache-2.0" ]
null
null
null
app/src/main/java/com/b2gsoft/mrb/Fragment/Expense/ExpenseOilFragment.java
imsajib02/BrickField
88237a76c626e9555c1f922e3d5f6fcb5a66eba2
[ "Apache-2.0" ]
null
null
null
41.04142
264
0.601499
997,045
package com.b2gsoft.mrb.Fragment.Expense; import android.annotation.SuppressLint; import android.app.ProgressDialog; import android.os.Bundle; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.toolbox.JsonObjectRequest; import com.b2gsoft.mrb.Adapter.ExpenseAdapterTab; import com.b2gsoft.mrb.Model.Expense; import com.b2gsoft.mrb.R; import com.b2gsoft.mrb.Utils.ApplicationController; import com.b2gsoft.mrb.Utils.ConnectionDetector; import com.b2gsoft.mrb.Utils.GenericVollyError; import com.b2gsoft.mrb.Utils.RoundFormat; import com.b2gsoft.mrb.Utils.SharedPreferences; import com.b2gsoft.mrb.Utils.StaticValue; import com.b2gsoft.mrb.Utils.Url; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; /** * A simple {@link Fragment} subclass. */ @SuppressLint("ValidFragment") public class ExpenseOilFragment extends Fragment { private ConnectionDetector connectionDetector; /* access modifiers changed from: private */ public ArrayList<Expense> expenseArrayList; /* access modifiers changed from: private */ public ListView listViewExpense; private ProgressDialog pDialog; private SharedPreferences sharedPreferences; int pos = 0; private LinearLayout linearLayoutTotal; private TextView tvTotal, tvPaid; private int sub_id = 1; public ExpenseOilFragment(int i) { sub_id =i; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view = inflater.inflate(R.layout.fragment_expense_mill_one, container, false); pDialog = new ProgressDialog(getActivity()); connectionDetector = new ConnectionDetector(getContext()); sharedPreferences = new SharedPreferences(getContext()); listViewExpense = (ListView)view. findViewById(R.id.lv_expense); linearLayoutTotal = (LinearLayout)view.findViewById(R.id.ll_total); tvTotal = (TextView)view.findViewById(R.id.tv_total_balance); tvPaid = (TextView)view.findViewById(R.id.tv_total_paid); if (connectionDetector.isConnectingToInternet()) { getExpense(); } return view; } private void getExpense() { showDialog(); JSONObject jsonObject = new JSONObject(); JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, Url.ExpenseWiseHistory+"9&expense_sub_sector_id="+sub_id+"&token=" + sharedPreferences.getSessionToken(), jsonObject, response(), GenericVollyError.errorListener(getContext(), pDialog)); Log.e("exw", Url.ExpenseWiseHistory+ pos+"&token=" + sharedPreferences.getSessionToken()); ApplicationController.getInstance().addToRequestQueue(request); } private Response.Listener<JSONObject> response() { return new Response.Listener<JSONObject>() { public void onResponse(JSONObject response) { dismissProgressDialog(); try { Log.e("res", response.toString()); try { if (response.getBoolean(StaticValue.Success)) { JSONArray data = response.getJSONArray(StaticValue.Data); if (data.length() > 0) { double total =0, paid =0; expenseArrayList = new ArrayList(); for (int i = 0; i < data.length(); i++) { JSONObject value = data.getJSONObject(i); JSONObject expenseSector = value.getJSONObject("expense_sector"); Expense expense = new Expense(); expense.expense_way_name = expenseSector.getString(StaticValue.Name); expense.name = value.getString(StaticValue.ExpenseSub); expense.unit = value.getString(StaticValue.Unit); expense.per_unit_price = value.getString(StaticValue.PerUnitPrice); expense.total_price = value.getString(StaticValue.TotalPrice); expense.payment_type_id = value.getString(StaticValue.PaymentTypeId); expense.date = value.getString(StaticValue.ExpenseDate); expense.cash = value.getString(StaticValue.Cash); expense.due = value.getString(StaticValue.Due); total += Double.parseDouble(expense.total_price); paid += Double.parseDouble(expense.cash); expenseArrayList.add(expense); } ExpenseAdapterTab expenseAdapter = new ExpenseAdapterTab(getContext(), expenseArrayList); expenseAdapter.notifyDataSetChanged(); listViewExpense.setAdapter(expenseAdapter); linearLayoutTotal.setVisibility(View.VISIBLE); tvTotal.setText(""+ RoundFormat.roundTwoDecimals(total)); tvPaid.setText(""+ RoundFormat.roundTwoDecimals(paid)+""); } return; } } catch (JSONException e) { e.printStackTrace(); } Toast.makeText(getContext(), response.getString(StaticValue.Message), Toast.LENGTH_LONG).show(); } catch (JSONException e) { Log.e("expense", e.getMessage()); } } }; } private void showDialog() { try { this.pDialog.setMessage(getString(R.string.please_wait)); this.pDialog.setIndeterminate(false); this.pDialog.setCancelable(false); this.pDialog.setCanceledOnTouchOutside(false); this.pDialog.show(); } catch (Exception e) { } } public void onDestroy() { dismissProgressDialog(); super.onDestroy(); } /* access modifiers changed from: private */ public void dismissProgressDialog() { if (this.pDialog != null && this.pDialog.isShowing()) { this.pDialog.dismiss(); } } }
9234c2ed6610764d997f9941f9a9549d65b9ed62
3,187
java
Java
Java/M02JavaFundamentals/Exam/PreparationForFinalExam/FE05/E03Pirates.java
todorkrastev/softuni-software-engineering
cfc0b5eaeb82951ff4d4668332ec3a31c59a5f84
[ "MIT" ]
3
2021-04-06T21:35:50.000Z
2021-08-07T09:51:58.000Z
Java/M02JavaFundamentals/Exam/PreparationForFinalExam/FE05/E03Pirates.java
todorkrastev/softuni-software-engineering
cfc0b5eaeb82951ff4d4668332ec3a31c59a5f84
[ "MIT" ]
null
null
null
Java/M02JavaFundamentals/Exam/PreparationForFinalExam/FE05/E03Pirates.java
todorkrastev/softuni-software-engineering
cfc0b5eaeb82951ff4d4668332ec3a31c59a5f84
[ "MIT" ]
1
2021-12-02T13:58:21.000Z
2021-12-02T13:58:21.000Z
39.345679
147
0.492626
997,046
package E05ProgrammingFundamentalsFinalExam; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; import java.util.Map; import java.util.TreeMap; public class E03Pirates { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader( new InputStreamReader(System.in, StandardCharsets.UTF_8)); Map<String, int[]> map = new TreeMap<>(); String input; while (!"Sail".equals(input = reader.readLine())) { String[] split = input.trim().split("\\|\\|"); String city = split[0]; int population = Integer.parseInt(split[1]); int gold = Integer.parseInt(split[2]); map.putIfAbsent(city, new int[2]); map.get(city)[0] += population; map.get(city)[1] += gold; } String secondInput; while (!"End".equals(secondInput = reader.readLine())) { String[] commandParts = secondInput.trim().split("=>"); String command = commandParts[0]; String town = commandParts[1]; switch (command) { case "Plunder": int people = Integer.parseInt(commandParts[2]); int gold = Integer.parseInt(commandParts[3]); System.out.printf("%s plundered! %d gold stolen, %d citizens killed.%n", town, gold, people); if (map.containsKey(town)) { map.get(town)[0] -= people; map.get(town)[1] -= gold; if (map.get(town)[0] <= 0 || map.get(town)[1] <= 0) { map.remove(town); System.out.printf("%s has been wiped off the map!%n", town); } } break; case "Prosper": int goldProsper = Integer.parseInt(commandParts[2]); if (goldProsper < 0) { System.out.println("Gold added cannot be a negative number!"); } else { if (map.containsKey(town)) { map.get(town)[1] += goldProsper; System.out.printf("%d gold added to the city treasury. %s now has %d gold.%n", goldProsper, town, map.get(town)[1]); } } break; default: break; } } if (map.isEmpty()) { System.out.println("Ahoy, Captain! All targets have been plundered and destroyed!"); } else { System.out.printf("Ahoy, Captain! There are %d wealthy settlements to go to:%n", map.size()); map .entrySet() .stream() .sorted((a, b) -> Integer.compare(b.getValue()[1], a.getValue()[1])) .forEach(e -> System.out.printf("%s -> Population: %d citizens, Gold: %d kg%n", e.getKey(), e.getValue()[0], e.getValue()[1])); } } }
9234c362aa95c35b2d11b50042d1d49f7efaa2b0
475
java
Java
core/modules/cloud/src/main/java/org/onetwo/cloud/core/CloudWebMvcRegistrations.java
wayshall/onetwo
221ddfc0cbf3eafbef8ec090c21b9972c7d8ea23
[ "Apache-2.0" ]
19
2015-05-27T02:18:43.000Z
2021-11-16T11:02:17.000Z
core/modules/cloud/src/main/java/org/onetwo/cloud/core/CloudWebMvcRegistrations.java
wayshall/onetwo
221ddfc0cbf3eafbef8ec090c21b9972c7d8ea23
[ "Apache-2.0" ]
58
2017-03-07T03:06:32.000Z
2022-02-01T00:57:27.000Z
core/modules/cloud/src/main/java/org/onetwo/cloud/core/CloudWebMvcRegistrations.java
wayshall/onetwo
221ddfc0cbf3eafbef8ec090c21b9972c7d8ea23
[ "Apache-2.0" ]
12
2016-08-11T03:26:34.000Z
2019-01-09T10:56:29.000Z
25
75
0.814737
997,047
package org.onetwo.cloud.core; import org.onetwo.boot.core.web.mvc.BootWebMvcRegistrations; import org.onetwo.boot.core.web.mvc.ExtRequestMappingHandlerMapping; import org.onetwo.cloud.bugfix.FixFeignClientsHandlerMapping; /** * @author wayshall * <br/> */ public class CloudWebMvcRegistrations extends BootWebMvcRegistrations { @Override public ExtRequestMappingHandlerMapping getRequestMappingHandlerMapping() { return new FixFeignClientsHandlerMapping(); } }
9234c532ba53b10231f9090463d8640afecbf92f
42,548
java
Java
proto-google-cloud-compute-v1/src/main/java/com/google/cloud/compute/v1/ScalingScheduleStatus.java
googleapis/java-compute
28bd65d278b162538195e71b7dbb3d83d909514c
[ "Apache-2.0" ]
19
2020-01-28T12:32:27.000Z
2022-02-12T07:48:33.000Z
proto-google-cloud-compute-v1/src/main/java/com/google/cloud/compute/v1/ScalingScheduleStatus.java
googleapis/java-compute
28bd65d278b162538195e71b7dbb3d83d909514c
[ "Apache-2.0" ]
458
2019-11-04T22:32:18.000Z
2022-03-30T00:03:12.000Z
proto-google-cloud-compute-v1/src/main/java/com/google/cloud/compute/v1/ScalingScheduleStatus.java
googleapis/java-compute
28bd65d278b162538195e71b7dbb3d83d909514c
[ "Apache-2.0" ]
23
2019-10-31T21:05:28.000Z
2021-08-24T16:35:45.000Z
32.087481
227
0.654414
997,048
/* * Copyright 2020 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. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/compute/v1/compute.proto package com.google.cloud.compute.v1; /** * * * <pre> * </pre> * * Protobuf type {@code google.cloud.compute.v1.ScalingScheduleStatus} */ public final class ScalingScheduleStatus extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.cloud.compute.v1.ScalingScheduleStatus) ScalingScheduleStatusOrBuilder { private static final long serialVersionUID = 0L; // Use ScalingScheduleStatus.newBuilder() to construct. private ScalingScheduleStatus(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private ScalingScheduleStatus() { lastStartTime_ = ""; nextStartTime_ = ""; state_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance(UnusedPrivateParameter unused) { return new ScalingScheduleStatus(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private ScalingScheduleStatus( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 276360858: { java.lang.String s = input.readStringRequireUtf8(); bitField0_ |= 0x00000001; lastStartTime_ = s; break; } case 778160818: { java.lang.String s = input.readStringRequireUtf8(); bitField0_ |= 0x00000002; nextStartTime_ = s; break; } case 878060682: { java.lang.String s = input.readStringRequireUtf8(); bitField0_ |= 0x00000004; state_ = s; break; } default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_ScalingScheduleStatus_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_ScalingScheduleStatus_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.compute.v1.ScalingScheduleStatus.class, com.google.cloud.compute.v1.ScalingScheduleStatus.Builder.class); } /** * * * <pre> * [Output Only] The current state of a scaling schedule. * </pre> * * Protobuf enum {@code google.cloud.compute.v1.ScalingScheduleStatus.State} */ public enum State implements com.google.protobuf.ProtocolMessageEnum { /** * * * <pre> * A value indicating that the enum field is not set. * </pre> * * <code>UNDEFINED_STATE = 0;</code> */ UNDEFINED_STATE(0), /** * * * <pre> * The current autoscaling recommendation is influenced by this scaling schedule. * </pre> * * <code>ACTIVE = 314733318;</code> */ ACTIVE(314733318), /** * * * <pre> * This scaling schedule has been disabled by the user. * </pre> * * <code>DISABLED = 516696700;</code> */ DISABLED(516696700), /** * * * <pre> * This scaling schedule will never become active again. * </pre> * * <code>OBSOLETE = 66532761;</code> */ OBSOLETE(66532761), /** * * * <pre> * The current autoscaling recommendation is not influenced by this scaling schedule. * </pre> * * <code>READY = 77848963;</code> */ READY(77848963), UNRECOGNIZED(-1), ; /** * * * <pre> * A value indicating that the enum field is not set. * </pre> * * <code>UNDEFINED_STATE = 0;</code> */ public static final int UNDEFINED_STATE_VALUE = 0; /** * * * <pre> * The current autoscaling recommendation is influenced by this scaling schedule. * </pre> * * <code>ACTIVE = 314733318;</code> */ public static final int ACTIVE_VALUE = 314733318; /** * * * <pre> * This scaling schedule has been disabled by the user. * </pre> * * <code>DISABLED = 516696700;</code> */ public static final int DISABLED_VALUE = 516696700; /** * * * <pre> * This scaling schedule will never become active again. * </pre> * * <code>OBSOLETE = 66532761;</code> */ public static final int OBSOLETE_VALUE = 66532761; /** * * * <pre> * The current autoscaling recommendation is not influenced by this scaling schedule. * </pre> * * <code>READY = 77848963;</code> */ public static final int READY_VALUE = 77848963; public final int getNumber() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalArgumentException( "Can't get the number of an unknown enum value."); } return value; } /** * @param value The numeric wire value of the corresponding enum entry. * @return The enum associated with the given numeric wire value. * @deprecated Use {@link #forNumber(int)} instead. */ @java.lang.Deprecated public static State valueOf(int value) { return forNumber(value); } /** * @param value The numeric wire value of the corresponding enum entry. * @return The enum associated with the given numeric wire value. */ public static State forNumber(int value) { switch (value) { case 0: return UNDEFINED_STATE; case 314733318: return ACTIVE; case 516696700: return DISABLED; case 66532761: return OBSOLETE; case 77848963: return READY; default: return null; } } public static com.google.protobuf.Internal.EnumLiteMap<State> internalGetValueMap() { return internalValueMap; } private static final com.google.protobuf.Internal.EnumLiteMap<State> internalValueMap = new com.google.protobuf.Internal.EnumLiteMap<State>() { public State findValueByNumber(int number) { return State.forNumber(number); } }; public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { if (this == UNRECOGNIZED) { throw new java.lang.IllegalStateException( "Can't get the descriptor of an unrecognized enum value."); } return getDescriptor().getValues().get(ordinal()); } public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { return getDescriptor(); } public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { return com.google.cloud.compute.v1.ScalingScheduleStatus.getDescriptor() .getEnumTypes() .get(0); } private static final State[] VALUES = values(); public static State valueOf(com.google.protobuf.Descriptors.EnumValueDescriptor desc) { if (desc.getType() != getDescriptor()) { throw new java.lang.IllegalArgumentException("EnumValueDescriptor is not for this type."); } if (desc.getIndex() == -1) { return UNRECOGNIZED; } return VALUES[desc.getIndex()]; } private final int value; private State(int value) { this.value = value; } // @@protoc_insertion_point(enum_scope:google.cloud.compute.v1.ScalingScheduleStatus.State) } private int bitField0_; public static final int LAST_START_TIME_FIELD_NUMBER = 34545107; private volatile java.lang.Object lastStartTime_; /** * * * <pre> * [Output Only] The last time the scaling schedule became active. Note: this is a timestamp when a schedule actually became active, not when it was planned to do so. The timestamp is in RFC3339 text format. * </pre> * * <code>optional string last_start_time = 34545107;</code> * * @return Whether the lastStartTime field is set. */ @java.lang.Override public boolean hasLastStartTime() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * [Output Only] The last time the scaling schedule became active. Note: this is a timestamp when a schedule actually became active, not when it was planned to do so. The timestamp is in RFC3339 text format. * </pre> * * <code>optional string last_start_time = 34545107;</code> * * @return The lastStartTime. */ @java.lang.Override public java.lang.String getLastStartTime() { java.lang.Object ref = lastStartTime_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); lastStartTime_ = s; return s; } } /** * * * <pre> * [Output Only] The last time the scaling schedule became active. Note: this is a timestamp when a schedule actually became active, not when it was planned to do so. The timestamp is in RFC3339 text format. * </pre> * * <code>optional string last_start_time = 34545107;</code> * * @return The bytes for lastStartTime. */ @java.lang.Override public com.google.protobuf.ByteString getLastStartTimeBytes() { java.lang.Object ref = lastStartTime_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); lastStartTime_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int NEXT_START_TIME_FIELD_NUMBER = 97270102; private volatile java.lang.Object nextStartTime_; /** * * * <pre> * [Output Only] The next time the scaling schedule is to become active. Note: this is a timestamp when a schedule is planned to run, but the actual time might be slightly different. The timestamp is in RFC3339 text format. * </pre> * * <code>optional string next_start_time = 97270102;</code> * * @return Whether the nextStartTime field is set. */ @java.lang.Override public boolean hasNextStartTime() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * [Output Only] The next time the scaling schedule is to become active. Note: this is a timestamp when a schedule is planned to run, but the actual time might be slightly different. The timestamp is in RFC3339 text format. * </pre> * * <code>optional string next_start_time = 97270102;</code> * * @return The nextStartTime. */ @java.lang.Override public java.lang.String getNextStartTime() { java.lang.Object ref = nextStartTime_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextStartTime_ = s; return s; } } /** * * * <pre> * [Output Only] The next time the scaling schedule is to become active. Note: this is a timestamp when a schedule is planned to run, but the actual time might be slightly different. The timestamp is in RFC3339 text format. * </pre> * * <code>optional string next_start_time = 97270102;</code> * * @return The bytes for nextStartTime. */ @java.lang.Override public com.google.protobuf.ByteString getNextStartTimeBytes() { java.lang.Object ref = nextStartTime_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextStartTime_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int STATE_FIELD_NUMBER = 109757585; private volatile java.lang.Object state_; /** * * * <pre> * [Output Only] The current state of a scaling schedule. * Check the State enum for the list of possible values. * </pre> * * <code>optional string state = 109757585;</code> * * @return Whether the state field is set. */ @java.lang.Override public boolean hasState() { return ((bitField0_ & 0x00000004) != 0); } /** * * * <pre> * [Output Only] The current state of a scaling schedule. * Check the State enum for the list of possible values. * </pre> * * <code>optional string state = 109757585;</code> * * @return The state. */ @java.lang.Override public java.lang.String getState() { java.lang.Object ref = state_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); state_ = s; return s; } } /** * * * <pre> * [Output Only] The current state of a scaling schedule. * Check the State enum for the list of possible values. * </pre> * * <code>optional string state = 109757585;</code> * * @return The bytes for state. */ @java.lang.Override public com.google.protobuf.ByteString getStateBytes() { java.lang.Object ref = state_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); state_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (((bitField0_ & 0x00000001) != 0)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 34545107, lastStartTime_); } if (((bitField0_ & 0x00000002) != 0)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 97270102, nextStartTime_); } if (((bitField0_ & 0x00000004) != 0)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 109757585, state_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) != 0)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(34545107, lastStartTime_); } if (((bitField0_ & 0x00000002) != 0)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(97270102, nextStartTime_); } if (((bitField0_ & 0x00000004) != 0)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(109757585, state_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.cloud.compute.v1.ScalingScheduleStatus)) { return super.equals(obj); } com.google.cloud.compute.v1.ScalingScheduleStatus other = (com.google.cloud.compute.v1.ScalingScheduleStatus) obj; if (hasLastStartTime() != other.hasLastStartTime()) return false; if (hasLastStartTime()) { if (!getLastStartTime().equals(other.getLastStartTime())) return false; } if (hasNextStartTime() != other.hasNextStartTime()) return false; if (hasNextStartTime()) { if (!getNextStartTime().equals(other.getNextStartTime())) return false; } if (hasState() != other.hasState()) return false; if (hasState()) { if (!getState().equals(other.getState())) return false; } if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); if (hasLastStartTime()) { hash = (37 * hash) + LAST_START_TIME_FIELD_NUMBER; hash = (53 * hash) + getLastStartTime().hashCode(); } if (hasNextStartTime()) { hash = (37 * hash) + NEXT_START_TIME_FIELD_NUMBER; hash = (53 * hash) + getNextStartTime().hashCode(); } if (hasState()) { hash = (37 * hash) + STATE_FIELD_NUMBER; hash = (53 * hash) + getState().hashCode(); } hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.cloud.compute.v1.ScalingScheduleStatus parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.ScalingScheduleStatus parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.compute.v1.ScalingScheduleStatus parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.ScalingScheduleStatus parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.compute.v1.ScalingScheduleStatus parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.cloud.compute.v1.ScalingScheduleStatus parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.cloud.compute.v1.ScalingScheduleStatus parseFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.compute.v1.ScalingScheduleStatus parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.compute.v1.ScalingScheduleStatus parseDelimitedFrom( java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input); } public static com.google.cloud.compute.v1.ScalingScheduleStatus parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException( PARSER, input, extensionRegistry); } public static com.google.cloud.compute.v1.ScalingScheduleStatus parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input); } public static com.google.cloud.compute.v1.ScalingScheduleStatus parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3.parseWithIOException( PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.cloud.compute.v1.ScalingScheduleStatus prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * * * <pre> * </pre> * * Protobuf type {@code google.cloud.compute.v1.ScalingScheduleStatus} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.cloud.compute.v1.ScalingScheduleStatus) com.google.cloud.compute.v1.ScalingScheduleStatusOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_ScalingScheduleStatus_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_ScalingScheduleStatus_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.cloud.compute.v1.ScalingScheduleStatus.class, com.google.cloud.compute.v1.ScalingScheduleStatus.Builder.class); } // Construct using com.google.cloud.compute.v1.ScalingScheduleStatus.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {} } @java.lang.Override public Builder clear() { super.clear(); lastStartTime_ = ""; bitField0_ = (bitField0_ & ~0x00000001); nextStartTime_ = ""; bitField0_ = (bitField0_ & ~0x00000002); state_ = ""; bitField0_ = (bitField0_ & ~0x00000004); return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.cloud.compute.v1.Compute .internal_static_google_cloud_compute_v1_ScalingScheduleStatus_descriptor; } @java.lang.Override public com.google.cloud.compute.v1.ScalingScheduleStatus getDefaultInstanceForType() { return com.google.cloud.compute.v1.ScalingScheduleStatus.getDefaultInstance(); } @java.lang.Override public com.google.cloud.compute.v1.ScalingScheduleStatus build() { com.google.cloud.compute.v1.ScalingScheduleStatus result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.cloud.compute.v1.ScalingScheduleStatus buildPartial() { com.google.cloud.compute.v1.ScalingScheduleStatus result = new com.google.cloud.compute.v1.ScalingScheduleStatus(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) != 0)) { to_bitField0_ |= 0x00000001; } result.lastStartTime_ = lastStartTime_; if (((from_bitField0_ & 0x00000002) != 0)) { to_bitField0_ |= 0x00000002; } result.nextStartTime_ = nextStartTime_; if (((from_bitField0_ & 0x00000004) != 0)) { to_bitField0_ |= 0x00000004; } result.state_ = state_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.cloud.compute.v1.ScalingScheduleStatus) { return mergeFrom((com.google.cloud.compute.v1.ScalingScheduleStatus) other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.cloud.compute.v1.ScalingScheduleStatus other) { if (other == com.google.cloud.compute.v1.ScalingScheduleStatus.getDefaultInstance()) return this; if (other.hasLastStartTime()) { bitField0_ |= 0x00000001; lastStartTime_ = other.lastStartTime_; onChanged(); } if (other.hasNextStartTime()) { bitField0_ |= 0x00000002; nextStartTime_ = other.nextStartTime_; onChanged(); } if (other.hasState()) { bitField0_ |= 0x00000004; state_ = other.state_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.cloud.compute.v1.ScalingScheduleStatus parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.cloud.compute.v1.ScalingScheduleStatus) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private java.lang.Object lastStartTime_ = ""; /** * * * <pre> * [Output Only] The last time the scaling schedule became active. Note: this is a timestamp when a schedule actually became active, not when it was planned to do so. The timestamp is in RFC3339 text format. * </pre> * * <code>optional string last_start_time = 34545107;</code> * * @return Whether the lastStartTime field is set. */ public boolean hasLastStartTime() { return ((bitField0_ & 0x00000001) != 0); } /** * * * <pre> * [Output Only] The last time the scaling schedule became active. Note: this is a timestamp when a schedule actually became active, not when it was planned to do so. The timestamp is in RFC3339 text format. * </pre> * * <code>optional string last_start_time = 34545107;</code> * * @return The lastStartTime. */ public java.lang.String getLastStartTime() { java.lang.Object ref = lastStartTime_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); lastStartTime_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * [Output Only] The last time the scaling schedule became active. Note: this is a timestamp when a schedule actually became active, not when it was planned to do so. The timestamp is in RFC3339 text format. * </pre> * * <code>optional string last_start_time = 34545107;</code> * * @return The bytes for lastStartTime. */ public com.google.protobuf.ByteString getLastStartTimeBytes() { java.lang.Object ref = lastStartTime_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); lastStartTime_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * [Output Only] The last time the scaling schedule became active. Note: this is a timestamp when a schedule actually became active, not when it was planned to do so. The timestamp is in RFC3339 text format. * </pre> * * <code>optional string last_start_time = 34545107;</code> * * @param value The lastStartTime to set. * @return This builder for chaining. */ public Builder setLastStartTime(java.lang.String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000001; lastStartTime_ = value; onChanged(); return this; } /** * * * <pre> * [Output Only] The last time the scaling schedule became active. Note: this is a timestamp when a schedule actually became active, not when it was planned to do so. The timestamp is in RFC3339 text format. * </pre> * * <code>optional string last_start_time = 34545107;</code> * * @return This builder for chaining. */ public Builder clearLastStartTime() { bitField0_ = (bitField0_ & ~0x00000001); lastStartTime_ = getDefaultInstance().getLastStartTime(); onChanged(); return this; } /** * * * <pre> * [Output Only] The last time the scaling schedule became active. Note: this is a timestamp when a schedule actually became active, not when it was planned to do so. The timestamp is in RFC3339 text format. * </pre> * * <code>optional string last_start_time = 34545107;</code> * * @param value The bytes for lastStartTime to set. * @return This builder for chaining. */ public Builder setLastStartTimeBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); bitField0_ |= 0x00000001; lastStartTime_ = value; onChanged(); return this; } private java.lang.Object nextStartTime_ = ""; /** * * * <pre> * [Output Only] The next time the scaling schedule is to become active. Note: this is a timestamp when a schedule is planned to run, but the actual time might be slightly different. The timestamp is in RFC3339 text format. * </pre> * * <code>optional string next_start_time = 97270102;</code> * * @return Whether the nextStartTime field is set. */ public boolean hasNextStartTime() { return ((bitField0_ & 0x00000002) != 0); } /** * * * <pre> * [Output Only] The next time the scaling schedule is to become active. Note: this is a timestamp when a schedule is planned to run, but the actual time might be slightly different. The timestamp is in RFC3339 text format. * </pre> * * <code>optional string next_start_time = 97270102;</code> * * @return The nextStartTime. */ public java.lang.String getNextStartTime() { java.lang.Object ref = nextStartTime_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); nextStartTime_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * [Output Only] The next time the scaling schedule is to become active. Note: this is a timestamp when a schedule is planned to run, but the actual time might be slightly different. The timestamp is in RFC3339 text format. * </pre> * * <code>optional string next_start_time = 97270102;</code> * * @return The bytes for nextStartTime. */ public com.google.protobuf.ByteString getNextStartTimeBytes() { java.lang.Object ref = nextStartTime_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); nextStartTime_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * [Output Only] The next time the scaling schedule is to become active. Note: this is a timestamp when a schedule is planned to run, but the actual time might be slightly different. The timestamp is in RFC3339 text format. * </pre> * * <code>optional string next_start_time = 97270102;</code> * * @param value The nextStartTime to set. * @return This builder for chaining. */ public Builder setNextStartTime(java.lang.String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000002; nextStartTime_ = value; onChanged(); return this; } /** * * * <pre> * [Output Only] The next time the scaling schedule is to become active. Note: this is a timestamp when a schedule is planned to run, but the actual time might be slightly different. The timestamp is in RFC3339 text format. * </pre> * * <code>optional string next_start_time = 97270102;</code> * * @return This builder for chaining. */ public Builder clearNextStartTime() { bitField0_ = (bitField0_ & ~0x00000002); nextStartTime_ = getDefaultInstance().getNextStartTime(); onChanged(); return this; } /** * * * <pre> * [Output Only] The next time the scaling schedule is to become active. Note: this is a timestamp when a schedule is planned to run, but the actual time might be slightly different. The timestamp is in RFC3339 text format. * </pre> * * <code>optional string next_start_time = 97270102;</code> * * @param value The bytes for nextStartTime to set. * @return This builder for chaining. */ public Builder setNextStartTimeBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); bitField0_ |= 0x00000002; nextStartTime_ = value; onChanged(); return this; } private java.lang.Object state_ = ""; /** * * * <pre> * [Output Only] The current state of a scaling schedule. * Check the State enum for the list of possible values. * </pre> * * <code>optional string state = 109757585;</code> * * @return Whether the state field is set. */ public boolean hasState() { return ((bitField0_ & 0x00000004) != 0); } /** * * * <pre> * [Output Only] The current state of a scaling schedule. * Check the State enum for the list of possible values. * </pre> * * <code>optional string state = 109757585;</code> * * @return The state. */ public java.lang.String getState() { java.lang.Object ref = state_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); state_ = s; return s; } else { return (java.lang.String) ref; } } /** * * * <pre> * [Output Only] The current state of a scaling schedule. * Check the State enum for the list of possible values. * </pre> * * <code>optional string state = 109757585;</code> * * @return The bytes for state. */ public com.google.protobuf.ByteString getStateBytes() { java.lang.Object ref = state_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref); state_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * * * <pre> * [Output Only] The current state of a scaling schedule. * Check the State enum for the list of possible values. * </pre> * * <code>optional string state = 109757585;</code> * * @param value The state to set. * @return This builder for chaining. */ public Builder setState(java.lang.String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000004; state_ = value; onChanged(); return this; } /** * * * <pre> * [Output Only] The current state of a scaling schedule. * Check the State enum for the list of possible values. * </pre> * * <code>optional string state = 109757585;</code> * * @return This builder for chaining. */ public Builder clearState() { bitField0_ = (bitField0_ & ~0x00000004); state_ = getDefaultInstance().getState(); onChanged(); return this; } /** * * * <pre> * [Output Only] The current state of a scaling schedule. * Check the State enum for the list of possible values. * </pre> * * <code>optional string state = 109757585;</code> * * @param value The bytes for state to set. * @return This builder for chaining. */ public Builder setStateBytes(com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); bitField0_ |= 0x00000004; state_ = value; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.cloud.compute.v1.ScalingScheduleStatus) } // @@protoc_insertion_point(class_scope:google.cloud.compute.v1.ScalingScheduleStatus) private static final com.google.cloud.compute.v1.ScalingScheduleStatus DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.cloud.compute.v1.ScalingScheduleStatus(); } public static com.google.cloud.compute.v1.ScalingScheduleStatus getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<ScalingScheduleStatus> PARSER = new com.google.protobuf.AbstractParser<ScalingScheduleStatus>() { @java.lang.Override public ScalingScheduleStatus parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new ScalingScheduleStatus(input, extensionRegistry); } }; public static com.google.protobuf.Parser<ScalingScheduleStatus> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<ScalingScheduleStatus> getParserForType() { return PARSER; } @java.lang.Override public com.google.cloud.compute.v1.ScalingScheduleStatus getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
9234c5ee0f7bf5903d10e59496e73c753e59417b
1,739
java
Java
integration/edge_ripple/src/main/java/com/d/lib/pulllayout/edge/ripple/state/Discon.java
Dsiner/Xrv
ad887eae5585d004cbd53607380f3c60610a5691
[ "Apache-2.0" ]
23
2017-08-31T14:06:37.000Z
2020-06-07T10:29:14.000Z
integration/edge_ripple/src/main/java/com/d/lib/pulllayout/edge/ripple/state/Discon.java
Dsiner/xRecyclerViewF
ad887eae5585d004cbd53607380f3c60610a5691
[ "Apache-2.0" ]
3
2020-04-06T22:25:07.000Z
2021-07-06T02:43:18.000Z
integration/edge_ripple/src/main/java/com/d/lib/pulllayout/edge/ripple/state/Discon.java
Dsiner/xRecyclerViewF
ad887eae5585d004cbd53607380f3c60610a5691
[ "Apache-2.0" ]
7
2018-01-15T08:33:46.000Z
2019-12-11T08:52:07.000Z
26.348485
124
0.621047
997,049
package com.d.lib.pulllayout.edge.ripple.state; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.RectF; import android.view.View; import com.d.lib.pulllayout.util.Utils; /** * Discon * Created by D on 2018/3/30. */ public class Discon extends State { private Paint mPaint; private Paint mPaintCircle; private Rect mRect; private RectF mRectF; private float mStrokeWidth; public Discon(View view) { super(view); init(mContext); } private void init(Context context) { mStrokeWidth = Utils.dp2px(context, 2.5f); mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); mPaint.setColor(mColorWhite); mPaint.setStrokeCap(Paint.Cap.ROUND); mPaintCircle = new Paint(Paint.ANTI_ALIAS_FLAG); mPaintCircle.setColor(mColorError); mRect = new Rect(); mRectF = new RectF(); } @Override public void onDraw(Canvas canvas) { super.onDraw(canvas); float h = mHeight * 0.35f; float w = h; float startX = (mWidth - w) / 2; float startY = (mHeight - h) / 2; canvas.drawCircle(mWidth / 2f, mHeight / 2f, h / 2f, mPaintCircle); canvas.translate(mWidth / 2, mHeight / 2); canvas.rotate(45); float factor = 0.51f; mRect.set((int) (-w / 2f * factor), (int) (-mStrokeWidth / 2f), (int) (w / 2f * factor), (int) (mStrokeWidth / 2f)); mRectF.set(mRect); canvas.drawRect(mRectF, mPaint); canvas.rotate(90); canvas.drawRect(mRectF, mPaint); canvas.rotate(-135); canvas.translate(-mWidth / 2, -mHeight / 2); } }
9234c61c04e1628b38eea8c2f6f4c85e5cdaca83
3,836
java
Java
src/main/java/com/microsoft/graph/requests/extensions/GroupPolicyDefinitionValueRequestBuilder.java
isabella232/msgraph-beta-sdk-java
7d2b929d5c99c01ec1af1a251f4bf5876ca95ed8
[ "MIT" ]
null
null
null
src/main/java/com/microsoft/graph/requests/extensions/GroupPolicyDefinitionValueRequestBuilder.java
isabella232/msgraph-beta-sdk-java
7d2b929d5c99c01ec1af1a251f4bf5876ca95ed8
[ "MIT" ]
1
2021-02-23T20:48:12.000Z
2021-02-23T20:48:12.000Z
src/main/java/com/microsoft/graph/requests/extensions/GroupPolicyDefinitionValueRequestBuilder.java
isabella232/msgraph-beta-sdk-java
7d2b929d5c99c01ec1af1a251f4bf5876ca95ed8
[ "MIT" ]
null
null
null
49.179487
187
0.759906
997,050
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ package com.microsoft.graph.requests.extensions; import com.microsoft.graph.http.IRequestBuilder; import com.microsoft.graph.core.ClientException; import com.microsoft.graph.concurrency.ICallback; import com.microsoft.graph.models.extensions.GroupPolicyDefinitionValue; import com.microsoft.graph.requests.extensions.IGroupPolicyPresentationValueCollectionRequestBuilder; import com.microsoft.graph.requests.extensions.IGroupPolicyPresentationValueRequestBuilder; import com.microsoft.graph.requests.extensions.GroupPolicyPresentationValueCollectionRequestBuilder; import com.microsoft.graph.requests.extensions.GroupPolicyPresentationValueRequestBuilder; import com.microsoft.graph.requests.extensions.IGroupPolicyDefinitionRequestBuilder; import com.microsoft.graph.requests.extensions.GroupPolicyDefinitionRequestBuilder; import java.util.Arrays; import java.util.EnumSet; import com.microsoft.graph.core.IBaseClient; import com.microsoft.graph.http.BaseRequestBuilder; // **NOTE** This file was generated by a tool and any changes will be overwritten. /** * The class for the Group Policy Definition Value Request Builder. */ public class GroupPolicyDefinitionValueRequestBuilder extends BaseRequestBuilder implements IGroupPolicyDefinitionValueRequestBuilder { /** * The request builder for the GroupPolicyDefinitionValue * * @param requestUrl the request URL * @param client the service client * @param requestOptions the options for this request */ public GroupPolicyDefinitionValueRequestBuilder(final String requestUrl, final IBaseClient client, final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) { super(requestUrl, client, requestOptions); } /** * Creates the request * * @param requestOptions the options for this request * @return the IGroupPolicyDefinitionValueRequest instance */ public IGroupPolicyDefinitionValueRequest buildRequest(final com.microsoft.graph.options.Option... requestOptions) { return buildRequest(getOptions(requestOptions)); } /** * Creates the request with specific requestOptions instead of the existing requestOptions * * @param requestOptions the options for this request * @return the IGroupPolicyDefinitionValueRequest instance */ public IGroupPolicyDefinitionValueRequest buildRequest(final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) { return new com.microsoft.graph.requests.extensions.GroupPolicyDefinitionValueRequest(getRequestUrl(), getClient(), requestOptions); } /** * Gets the request builder for GroupPolicyDefinition * * @return the IGroupPolicyDefinitionWithReferenceRequestBuilder instance */ public IGroupPolicyDefinitionWithReferenceRequestBuilder definition() { return new GroupPolicyDefinitionWithReferenceRequestBuilder(getRequestUrlWithAdditionalSegment("definition"), getClient(), null); } public IGroupPolicyPresentationValueCollectionRequestBuilder presentationValues() { return new GroupPolicyPresentationValueCollectionRequestBuilder(getRequestUrlWithAdditionalSegment("presentationValues"), getClient(), null); } public IGroupPolicyPresentationValueRequestBuilder presentationValues(final String id) { return new GroupPolicyPresentationValueRequestBuilder(getRequestUrlWithAdditionalSegment("presentationValues") + "/" + id, getClient(), null); } }
9234c63833f3ca829cce610cfac806b2cc7d7f4f
4,011
java
Java
src/main/java/seedu/address/model/exercise/Exercise.java
AY1920S2-CS2103T-F11-2/main
6db899de8f54c2d0656e9df9ed3515435576bc84
[ "MIT" ]
1
2020-02-21T00:33:04.000Z
2020-02-21T00:33:04.000Z
src/main/java/seedu/address/model/exercise/Exercise.java
AY1920S2-CS2103T-F11-2/main
6db899de8f54c2d0656e9df9ed3515435576bc84
[ "MIT" ]
135
2020-02-20T16:35:45.000Z
2020-04-16T16:14:18.000Z
src/main/java/seedu/address/model/exercise/Exercise.java
AY1920S2-CS2103T-F11-2/main
6db899de8f54c2d0656e9df9ed3515435576bc84
[ "MIT" ]
5
2020-02-14T07:19:57.000Z
2020-02-29T09:28:16.000Z
34.282051
100
0.658689
997,051
package seedu.address.model.exercise; import static seedu.address.commons.util.CollectionUtil.requireAllNonNull; import java.util.Objects; /** * Represents an exercise done by a client. Guarantees: details are present and * not null, field values are validated, immutable. */ public class Exercise { public final ExerciseName exerciseName; public final ExerciseReps exerciseReps; public final ExerciseSets exerciseSets; public final ExerciseWeight exerciseWeight; public final ExerciseDate exerciseDate; public Exercise(ExerciseName exerciseName, ExerciseReps exerciseReps, ExerciseSets exerciseSets, ExerciseWeight exerciseWeight, ExerciseDate exerciseDate) { requireAllNonNull(exerciseName, exerciseDate, exerciseReps, exerciseSets, exerciseWeight); this.exerciseName = exerciseName; this.exerciseReps = exerciseReps; this.exerciseSets = exerciseSets; this.exerciseWeight = exerciseWeight; this.exerciseDate = exerciseDate; } public ExerciseName getExerciseName() { return exerciseName; } public ExerciseReps getExerciseReps() { return exerciseReps; } public ExerciseSets getExerciseSets() { return exerciseSets; } public ExerciseWeight getExerciseWeight() { return exerciseWeight; } public ExerciseDate getExerciseDate() { return exerciseDate; } /** * Returns a string of describing {@code Exercise} to be shown in {@code ResultDisplay} */ public String getForOutput() { final StringBuilder builder = new StringBuilder(); builder.append("Exercise name: ").append(getExerciseName()) .append("\nDate: ").append(getExerciseDate()) .append("\nReps: ").append(getExerciseReps()) .append("\nWeight: ").append(getExerciseWeight()) .append("\nSets: ").append(getExerciseSets()); return builder.toString(); } /** * Returns true if both exercises of the same name, date, reps and weight. * This defines a weaker notion of equality between two exercises. */ public boolean isSameExercise(Exercise otherExercise) { if (otherExercise == this) { return true; } return otherExercise != null && otherExercise.getExerciseName().equals(getExerciseName()) && otherExercise.getExerciseReps().equals(getExerciseReps()) && otherExercise.getExerciseWeight().equals(getExerciseWeight()) && otherExercise.getExerciseDate().equals(getExerciseDate()); } /** * Returns true if both exercise have the attribute values. */ @Override public boolean equals(Object other) { if (other == this) { return true; } if (!(other instanceof Exercise)) { return false; } Exercise otherExercise = (Exercise) other; return otherExercise.getExerciseName().equals(getExerciseName()) && otherExercise.getExerciseReps().equals(getExerciseReps()) && otherExercise.getExerciseSets().equals(getExerciseSets()) && otherExercise.getExerciseWeight().equals(getExerciseWeight()) && otherExercise.getExerciseDate().equals(getExerciseDate()); } @Override public int hashCode() { // use this method for custom fields hashing instead of implementing your own return Objects.hash(exerciseName, exerciseReps, exerciseSets, exerciseWeight, exerciseDate); } @Override public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("Exercise name: ").append(getExerciseName()) .append(" Date: ").append(getExerciseDate()) .append(" Sets: ").append(getExerciseSets()) .append(" Reps: ").append(getExerciseReps()) .append(" Weight: ").append(getExerciseWeight()); return builder.toString(); } }
9234c798d1e223cc23dd50c48d11f11346b6b32a
903
java
Java
shared/src/com/vaadin/shared/Position.java
allanim/vaadin
b7f9b2316bff98bc7d37c959fa6913294d9608e4
[ "Apache-2.0" ]
2
2016-12-06T09:05:58.000Z
2016-12-07T08:57:55.000Z
shared/src/com/vaadin/shared/Position.java
allanim/vaadin
b7f9b2316bff98bc7d37c959fa6913294d9608e4
[ "Apache-2.0" ]
null
null
null
shared/src/com/vaadin/shared/Position.java
allanim/vaadin
b7f9b2316bff98bc7d37c959fa6913294d9608e4
[ "Apache-2.0" ]
null
null
null
34.730769
120
0.730897
997,052
/* * Copyright 2000-2014 Vaadin Ltd. * * 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.vaadin.shared; public enum Position { TOP_LEFT, TOP_CENTER, TOP_RIGHT, MIDDLE_LEFT, MIDDLE_CENTER, MIDDLE_RIGHT, BOTTOM_LEFT, BOTTOM_CENTER, BOTTOM_RIGHT, /** * Position that is only accessible for assistive devices, invisible for * visual users. **/ ASSISTIVE; }
9234c88633baa0f172d7a5576f62527ffcb8ab09
1,576
java
Java
src/main/java/com/spotinst/sdkjava/model/ApiElastigroupActiveInstanceConverter.java
MethodLevelAnalyzer/spotinst-sdk-java
897f2bb7c7ad6802f90ee8354cd04e09de83aa2a
[ "Apache-2.0" ]
2
2017-10-20T04:53:19.000Z
2020-09-14T11:04:21.000Z
src/main/java/com/spotinst/sdkjava/model/ApiElastigroupActiveInstanceConverter.java
MethodLevelAnalyzer/spotinst-sdk-java
897f2bb7c7ad6802f90ee8354cd04e09de83aa2a
[ "Apache-2.0" ]
31
2018-10-09T18:32:48.000Z
2022-03-09T06:06:39.000Z
src/main/java/com/spotinst/sdkjava/model/ApiElastigroupActiveInstanceConverter.java
MethodLevelAnalyzer/spotinst-sdk-java
897f2bb7c7ad6802f90ee8354cd04e09de83aa2a
[ "Apache-2.0" ]
5
2017-08-20T14:34:37.000Z
2021-06-04T09:42:25.000Z
46.352941
109
0.774746
997,053
package com.spotinst.sdkjava.model; import com.spotinst.sdkjava.enums.AwsInstanceLifecycleEnum; import com.spotinst.sdkjava.enums.AwsInstanceTypeEnum; /** * Created by talzur on 12/12/2016. */ class ApiElastigroupActiveInstanceConverter { static ElastigroupActiveInstance dalToBl(ApiElastigroupActiveInstance apiElastigroupActiveInstance) { ElastigroupActiveInstance retVal = new ElastigroupActiveInstance(); retVal.setInstanceId(apiElastigroupActiveInstance.getInstanceId()); retVal.setAvailabilityZone(apiElastigroupActiveInstance.getAvailabilityZone()); retVal.setInstanceType(AwsInstanceTypeEnum.fromName(apiElastigroupActiveInstance.getInstanceType())); if (apiElastigroupActiveInstance.getSpotInstanceRequestId() != null) { retVal.setLifeCycle(AwsInstanceLifecycleEnum.SPOT); } else { retVal.setLifeCycle(AwsInstanceLifecycleEnum.ON_DEMAND); } retVal.setCreatedAt(apiElastigroupActiveInstance.getCreatedAt()); retVal.setStatus(apiElastigroupActiveInstance.getStatus()); retVal.setProduct(apiElastigroupActiveInstance.getProduct()); retVal.setSpotInstanceRequestId(apiElastigroupActiveInstance.getSpotInstanceRequestId()); retVal.setGroupId(apiElastigroupActiveInstance.getGroupId()); retVal.setPublicIp(apiElastigroupActiveInstance.getPublicIp()); retVal.setPrivateIp(apiElastigroupActiveInstance.getPrivateIp()); retVal.setIpv6Address(apiElastigroupActiveInstance.getIpv6Address()); return retVal; } }